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
108
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
67k
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
ccc0093f23ef2a08aee93406c0284dec8b6fc9b4
2,725
cpp
C++
AdventOfCode/2020/c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
AdventOfCode/2020/c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
AdventOfCode/2020/c.cpp
onexmaster/cp
b78b0f1e586d6977d86c97b32f48fed33f1469af
[ "Apache-2.0", "MIT" ]
null
null
null
// Created by Tanuj Jain #include<bits/stdc++.h> #include<ext/pb_ds/assoc_container.hpp> #include<ext/pb_ds/tree_policy.hpp> using namespace std; using namespace __gnu_pbds; #define pb push_back #define mp make_pair # define M_PI 3.14159265358979323846 /* pi */ #define FIO ios_base::sync_with_stdio(false);cin.tie(NULL);cout.tie(NULL); typedef long long ll; typedef pair<int,int> pii; typedef pair<ll,ll>pll; template<class T> using oset=tree<T, null_type, less<T>, rb_tree_tag, tree_order_statistics_node_update>; const int INF = 0x3f3f3f3f; int knight_moves[8][2]={{-2,-1},{-1,-2},{1,-2},{2,-1},{-2,1},{-1,2},{1,2},{2,1}}; int moves[4][2]={{0,1},{0,-1},{1,0},{-1,0}}; struct custom_hash { static uint64_t splitmix64(uint64_t x) { // http://xorshift.di.unimi.it/splitmix64.c x += 0x9e3779b97f4a7c15; x = (x ^ (x >> 30)) * 0xbf58476d1ce4e5b9; x = (x ^ (x >> 27)) * 0x94d049bb133111eb; return x ^ (x >> 31); } size_t operator()(uint64_t x) const { static const uint64_t FIXED_RANDOM = chrono::steady_clock::now().time_since_epoch().count(); return splitmix64(x + FIXED_RANDOM); } }; char grid[324][5000]; int main() { FIO; #ifndef ONLINE_JUDGE freopen("input.txt","r",stdin); freopen("output.txt","w",stdout); #endif string temp; int i=0; int m; while(getline(cin,temp)) { m=temp.size(); for(int j=0;j<m;j++) grid[i][j]=temp[j]; for(int j=m;j<5000;j++) grid[i][j]=grid[i][j%m]; i++; } ll trees1=0; int sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees1++; sy+=3; sx+=1; } ll trees2=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees2++; sy+=1; sx+=1; } ll trees3=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees3++; sy+=5; sx+=1; } ll trees4=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees4++; sy+=7; sx+=1; } ll trees5=0; sx=0,sy=0; while(sx<323) { //cout<<sx<<" "<<sy<<endl; if(grid[sx][sy]=='#') trees5++; sy+=1; sx+=2; } cout<<trees1*trees2*trees3*trees4*trees5; return 0; }
25
106
0.473394
onexmaster
ccc07390dc2cf8c2f8c7df0bf3d0c1a2dcb29cde
2,923
cpp
C++
src/eventloop/EventLoop.cpp
ag88/stm32duino-eventloop
463a9b73e3234ccbab26130a5a9c795cf15ce25e
[ "MIT" ]
7
2018-11-08T10:08:20.000Z
2021-12-15T04:59:58.000Z
src/eventloop/EventLoop.cpp
ag88/stm32duino-eventloop
463a9b73e3234ccbab26130a5a9c795cf15ce25e
[ "MIT" ]
null
null
null
src/eventloop/EventLoop.cpp
ag88/stm32duino-eventloop
463a9b73e3234ccbab26130a5a9c795cf15ce25e
[ "MIT" ]
3
2020-12-25T08:01:35.000Z
2021-09-23T09:33:30.000Z
/* A stm32duino eventloop * Copyright (c) 2018 Andrew Goh * Provided as-is, No warranties of any kind, Use at your own risk * License: MIT */ #include "EventLoop.h" #include "Event.h" CEventLoop::CEventLoop() { m_eventbuffer = RingBuffer<TEvent,EVENT_BUFFER_SIZE>::getInstance(); m_numhandler = 0; for(int i=0; i<MAX_EVENT_HANDLERS; i++) { m_event_handlers[i].handle_id = EHandleID::NoTask; m_event_handlers[i].handler = NULL; } } uint8_t CEventLoop::registerhandler(EHandleID handle_id, CEventHandler& eventhandler) { if(m_numhandler+1 > MAX_EVENT_HANDLERS) { Serial.print(F("MAX_EVEN_HANDLERS exceeded:")); Serial.println(MAX_EVENT_HANDLERS); return 0; } m_event_handlers[m_numhandler].handle_id = handle_id; m_event_handlers[m_numhandler].handler = &eventhandler; m_numhandler++; return static_cast<uint8_t>(handle_id); } void CEventLoop::removehandler(EHandleID handler_id) { if(m_numhandler > MAX_EVENT_HANDLERS) return; bool found = false; uint8_t hindex = 0; for(int i=0; i<m_numhandler; i++) { if(m_event_handlers[m_numhandler].handle_id == handler_id) { hindex = i; found = true; break; } } if(found) { for(int i=hindex; i<m_numhandler-1; i++) { m_event_handlers[i].handle_id = m_event_handlers[i+1].handle_id; m_event_handlers[i].handler = m_event_handlers[i+1].handler; } m_event_handlers[m_numhandler-1].handle_id = EHandleID::NoTask; m_event_handlers[m_numhandler-1].handler = NULL; m_numhandler--; } } void CEventLoop::setup() { } int8_t CEventLoop::post(Event& event) { /* if you have no interrupts ISR that post events using this method * you could comment the * noInterrupts(); * interrupts(); * statements which may improve performance */ if(m_eventbuffer->is_full()) return -1; noInterrupts(); m_eventbuffer->push(event); interrupts(); // Serial.print("post:"); // uint16_t ev = static_cast<uint16_t>(event.event); // Serial.println(ev); return 0; } bool CEventLoop::proceventimm(Event& event) { // Serial.print("pop:"); // uint16_t ev = static_cast<uint16_t>(event.event); // Serial.println(ev); bool ret = false; if (event.handle_id == EHandleID::BroadCast) { //broadcast for (int i = 0; i < m_numhandler; i++) { m_event_handlers[i].handler->handleEvent(event); } } else { for (int i = 0; i < m_numhandler; i++) { if (m_event_handlers[i].handle_id == event.handle_id) { ret = m_event_handlers[i].handler->handleEvent(event); break; } } } return ret; } void CEventLoop::processevent() { while(!m_eventbuffer->is_empty()) { /* if you have no interrupts ISR that post events using this method * you could comment the * noInterrupts(); * interrupts(); * statements which may improve performance */ noInterrupts(); TEvent *pevent = m_eventbuffer->pop(); interrupts(); if(pevent == NULL) continue; proceventimm(*pevent); } } CEventLoop EventLoop;
23.015748
87
0.700308
ag88
ccc27e2f3eb0a50fb1390a42327c25e9cc291628
2,791
cpp
C++
samples/ListApp/ListApp.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
samples/ListApp/ListApp.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
samples/ListApp/ListApp.cpp
r3dl3g/guipp
3d3179be3022935b46b59f1b988a029abeabfcbf
[ "MIT" ]
null
null
null
#include <gui/layout/layout_container.h> #include <gui/layout/adaption_layout.h> #include <gui/ctrl/virtual_view.h> #include <gui/ctrl/file_tree.h> #include <gui/ctrl/std_dialogs.h> // -------------------------------------------------------------------------- int gui_main(const std::vector<std::string>& /*args*/) { using namespace gui; using namespace gui::win; using namespace gui::layout; using namespace gui::ctrl; using namespace gui::core; layout_main_window<gui::layout::horizontal_adaption<>> main; virtual_view<file_list<path_tree::sorted_path_info, default_file_item_drawer, core::selector::multi>> multi_client; virtual_view<file_list<path_tree::sorted_path_info, default_file_item_drawer, core::selector::single>> single_client; virtual_view<file_list<path_tree::sorted_path_info, default_file_item_drawer, core::selector::none>> none_client; multi_client->on_selection_commit([&] () { auto path = multi_client->get_selected_path(); if (sys_fs::is_directory(path)) { multi_client->set_path(path); multi_client.layout(); } }); multi_client->on_key_down<core::keys::up, core::state::alt>([&] () { auto path = multi_client->get_current_path(); multi_client->set_path(path.parent_path()); multi_client.layout(); }); single_client->on_key_down<core::keys::enter>([&] () { auto path = single_client->get_selected_path(); if (sys_fs::is_directory(path)) { single_client->set_path(path); single_client.layout(); } }); single_client->on_key_down<core::keys::up, core::state::alt>([&] () { auto path = single_client->get_current_path(); single_client->set_path(path.parent_path()); single_client.layout(); }); single_client->on_left_btn_dblclk([&] (gui::os::key_state ks, const core::native_point& pt) { const int idx = single_client->get_index_at_point(single_client->surface_to_client(pt)); auto path = single_client->get_selected_path(); message_dialog::show(main, "Info", str_fmt() << "Double click at index: " << idx << "\nfor path; '" << path << "'", "Ok"); }); none_client->on_selection_commit([&] () { auto path = none_client->get_selected_path(); if (sys_fs::is_directory(path)) { none_client->set_path(path); none_client.layout(); } }); main.add({multi_client, single_client, none_client}); main.on_create([&] () { multi_client->set_path("/"); single_client->set_path("/"); none_client->set_path("/"); }); main.create({50, 50, 800, 600}); main.on_destroy(&quit_main_loop); main.set_title("filelist"); main.set_visible(); return run_main_loop(); }
33.626506
95
0.636689
r3dl3g
ccc38e9ee25e0fc1d201b389f548a591f9ab70c3
8,123
cpp
C++
src/plugins/bittorrent/torrenttabfileswidget.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
120
2015-01-22T14:10:39.000Z
2021-11-25T12:57:16.000Z
src/plugins/bittorrent/torrenttabfileswidget.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
8
2015-02-07T19:38:19.000Z
2017-11-30T20:18:28.000Z
src/plugins/bittorrent/torrenttabfileswidget.cpp
Maledictus/leechcraft
79ec64824de11780b8e8bdfd5d8a2f3514158b12
[ "BSL-1.0" ]
33
2015-02-07T16:59:55.000Z
2021-10-12T00:36:40.000Z
/********************************************************************** * LeechCraft - modular cross-platform feature rich internet client. * Copyright (C) 2006-2014 Georg Rudoy * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE or copy at https://www.boost.org/LICENSE_1_0.txt) **********************************************************************/ #include "torrenttabfileswidget.h" #include <QMenu> #include <QTimer> #include <QSortFilterProxyModel> #include <util/gui/clearlineeditaddon.h> #include <util/sll/prelude.h> #include <util/util.h> #include "filesviewdelegate.h" #include "ltutils.h" #include "torrentfilesmodel.h" namespace LC::BitTorrent { namespace { class FilesProxyModel final : public QSortFilterProxyModel { public: FilesProxyModel (QObject *parent) : QSortFilterProxyModel { parent } { setDynamicSortFilter (true); } protected: bool filterAcceptsRow (int row, const QModelIndex& parent) const override { const auto& idx = sourceModel ()->index (row, TorrentFilesModel::ColumnPath, parent); if (idx.data ().toString ().contains (filterRegExp ().pattern (), Qt::CaseInsensitive)) return true; const auto rc = sourceModel ()->rowCount (idx); for (int i = 0; i < rc; ++i) if (filterAcceptsRow (i, idx)) return true; return false; } }; } TorrentTabFilesWidget::TorrentTabFilesWidget (QWidget *parent) : QWidget { parent } , ProxyModel_ { new FilesProxyModel { this } } { Ui_.setupUi (this); new Util::ClearLineEditAddon { GetProxyHolder (), Ui_.SearchLine_ }; ProxyModel_->setSortRole (TorrentFilesModel::RoleSort); Ui_.FilesView_->setItemDelegate (new FilesViewDelegate (Ui_.FilesView_)); Ui_.FilesView_->setModel (ProxyModel_); connect (Ui_.FilesView_->selectionModel (), &QItemSelectionModel::currentChanged, this, &TorrentTabFilesWidget::HandleFileSelected); HandleFileSelected ({}); connect (Ui_.SearchLine_, &QLineEdit::textChanged, [this] (const QString& text) { ProxyModel_->setFilterFixedString (text); Ui_.FilesView_->expandAll (); }); connect (Ui_.FilePriorityRegulator_, qOverload<int> (&QSpinBox::valueChanged), [this] (int prio) { for (auto idx : GetSelectedIndexes ()) { idx = idx.siblingAtColumn (TorrentFilesModel::ColumnPriority); Ui_.FilesView_->model ()->setData (idx, prio); } }); connect (Ui_.FilesView_, &QTreeView::customContextMenuRequested, this, &TorrentTabFilesWidget::ShowContextMenu); } void TorrentTabFilesWidget::SetAlertDispatcher (AlertDispatcher& dispatcher) { AlertDispatcher_ = &dispatcher; } void TorrentTabFilesWidget::SetCurrentIndex (const QModelIndex& index) { ProxyModel_->setSourceModel (nullptr); delete CurrentFilesModel_; Ui_.SearchLine_->clear (); const auto& handle = GetTorrentHandle (index); CurrentFilesModel_ = new TorrentFilesModel { handle, *AlertDispatcher_ }; ProxyModel_->setSourceModel (CurrentFilesModel_); QTimer::singleShot (0, Ui_.FilesView_, &QTreeView::expandAll); const auto filesCount = GetFilesCount (handle); Ui_.SearchLine_->setVisible (filesCount > 1); const auto& fm = Ui_.FilesView_->fontMetrics (); Ui_.FilesView_->header ()->resizeSection (0, fm.horizontalAdvance (QStringLiteral ("some very long file name or a directory name in a torrent file"))); } QList<QModelIndex> TorrentTabFilesWidget::GetSelectedIndexes () const { const auto selModel = Ui_.FilesView_->selectionModel (); const auto& current = selModel->currentIndex (); auto selected = selModel->selectedRows (); if (!selected.contains (current)) selected.append (current); return selected; } void TorrentTabFilesWidget::HandleFileSelected (const QModelIndex& index) { Ui_.FilePriorityRegulator_->setEnabled (index.isValid ()); if (!index.isValid ()) { Ui_.FilePath_->setText ({}); Ui_.FileProgress_->setText ({}); Ui_.FilePriorityRegulator_->blockSignals (true); Ui_.FilePriorityRegulator_->setValue (0); Ui_.FilePriorityRegulator_->blockSignals (false); } else { auto path = index.data (TorrentFilesModel::RoleFullPath).toString (); path = fontMetrics ().elidedText (path, Qt::ElideLeft, Ui_.FilePath_->width ()); Ui_.FilePath_->setText (path); auto sindex = index.siblingAtColumn (TorrentFilesModel::ColumnProgress); double progress = sindex.data (TorrentFilesModel::RoleProgress).toDouble (); qint64 size = sindex.data (TorrentFilesModel::RoleSize).toLongLong (); qint64 done = progress * size; Ui_.FileProgress_->setText (tr ("%1% (%2 of %3)") .arg (progress * 100, 0, 'f', 1) .arg (Util::MakePrettySize (done), Util::MakePrettySize (size))); Ui_.FilePriorityRegulator_->blockSignals (true); if (index.model ()->rowCount (index)) Ui_.FilePriorityRegulator_->setValue (1); else { auto prindex = index.siblingAtColumn (TorrentFilesModel::ColumnPriority); int priority = prindex.data ().toInt (); Ui_.FilePriorityRegulator_->setValue (priority); } Ui_.FilePriorityRegulator_->blockSignals (false); } } void TorrentTabFilesWidget::ShowContextMenu (const QPoint& pos) { const auto itm = GetProxyHolder ()->GetIconThemeManager (); QMenu menu; const auto& selected = GetSelectedIndexes (); const auto& openable = Util::Filter (selected, [] (const QModelIndex& idx) { const auto progress = idx.data (TorrentFilesModel::RoleProgress).toDouble (); return idx.model ()->rowCount (idx) || std::abs (progress - 1) < std::numeric_limits<double>::epsilon (); }); if (!openable.isEmpty ()) { const auto& openActName = openable.size () == 1 ? tr ("Open file") : tr ("Open %n file(s)", 0, openable.size ()); const auto openAct = menu.addAction (openActName, this, [openable, this] { for (const auto& idx : openable) CurrentFilesModel_->HandleFileActivated (ProxyModel_->mapToSource (idx)); }); openAct->setIcon (itm->GetIcon (QStringLiteral ("document-open"))); menu.addSeparator (); } const auto& cachedRoots = Util::Map (selected, [] (const QModelIndex& idx) { return qMakePair (idx, idx.data (TorrentFilesModel::RoleFullPath).toString ()); }); const auto& priorityRoots = Util::Map (Util::Filter (cachedRoots, [&cachedRoots] (const QPair<QModelIndex, QString>& idxPair) { return std::none_of (cachedRoots.begin (), cachedRoots.end (), [&idxPair] (const QPair<QModelIndex, QString>& existing) { return idxPair.first != existing.first && idxPair.second.startsWith (existing.second); }); }), [] (const QPair<QModelIndex, QString>& idxPair) { return idxPair.first.siblingAtColumn (TorrentFilesModel::ColumnPriority); }); if (!priorityRoots.isEmpty ()) { const auto subMenu = menu.addMenu (tr ("Change priority")); const QList<QPair<int, QString>> descrs { { 0, tr ("File is not downloaded.") }, { 1, tr ("Normal priority, download order depends on availability.") }, { 2, tr ("Pieces are preferred over the pieces with same availability.") }, { 3, tr ("Empty pieces are preferred just as much as partial pieces.") }, { 4, tr ("Empty pieces are preferred over partial pieces with the same availability.") }, { 5, tr ("Same as previous.") }, { 6, tr ("Pieces are considered to have highest availability.") }, { 7, tr ("Maximum file priority.") } }; for (const auto& descr : descrs) { const auto prio = descr.first; subMenu->addAction (QString::number (prio) + " " + descr.second, this, [this, prio, priorityRoots] { for (const auto& idx : priorityRoots) ProxyModel_->setData (idx, prio); }); } } menu.addAction (tr ("Expand all"), Ui_.FilesView_, &QTreeView::expandAll); menu.addAction (tr ("Collapse all"), Ui_.FilesView_, &QTreeView::collapseAll); menu.exec (Ui_.FilesView_->viewport ()->mapToGlobal (pos)); } }
31.242308
110
0.666256
Maledictus
ccc437b9b6c4dfcc1e5ae048e15d00a691019e2c
1,530
hpp
C++
src/sounds/Mp3Decoder.hpp
vgmoose/space
8f72c1d155b16b9705aa248ae8e84989f28fb498
[ "MIT" ]
25
2016-02-02T14:13:29.000Z
2018-04-27T18:57:43.000Z
src/sounds/Mp3Decoder.hpp
vgmoose/wiiu-space
8f72c1d155b16b9705aa248ae8e84989f28fb498
[ "MIT" ]
14
2016-03-18T17:41:59.000Z
2017-01-04T11:00:25.000Z
src/sounds/Mp3Decoder.hpp
vgmoose/space
8f72c1d155b16b9705aa248ae8e84989f28fb498
[ "MIT" ]
8
2016-03-18T07:05:24.000Z
2018-04-24T14:38:11.000Z
/*************************************************************************** * Copyright (C) 2010 * by Dimok * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any * damages arising from the use of this software. * * Permission is granted to anyone to use this software for any * purpose, including commercial applications, and to alter it and * redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you * must not claim that you wrote the original software. If you use * this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * * 2. Altered source versions must be plainly marked as such, and * must not be misrepresented as being the original software. * * 3. This notice may not be removed or altered from any source * distribution. * * for WiiXplorer 2010 ***************************************************************************/ #include <mad.h> #include "SoundDecoder.hpp" class Mp3Decoder : public SoundDecoder { public: Mp3Decoder(const char * filepath); Mp3Decoder(const u8 * sound, int len); virtual ~Mp3Decoder(); int Rewind(); int Read(u8 * buffer, int buffer_size, int pos); protected: void OpenFile(); struct mad_stream Stream; struct mad_frame Frame; struct mad_synth Synth; mad_timer_t Timer; u8 * GuardPtr; u8 * ReadBuffer; u32 SynthPos; };
31.875
77
0.660131
vgmoose
ccc55ae9d8e24241afd8176f50ccf373a55130ec
2,893
hpp
C++
inc/Helpers/Parameter.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
inc/Helpers/Parameter.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
inc/Helpers/Parameter.hpp
ACubeSAT/ecss-services
92d81c1ff455d9baef9417e656388c98ec552751
[ "MIT" ]
null
null
null
#ifndef ECSS_SERVICES_PARAMETER_HPP #define ECSS_SERVICES_PARAMETER_HPP #include "etl/String.hpp" #include "Message.hpp" #include "ECSS_Definitions.hpp" /** * Implementation of a Parameter field, as specified in ECSS-E-ST-70-41C. * * @author Grigoris Pavlakis <grigpavl@ece.auth.gr> * @author Athanasios Theocharis <athatheoc@gmail.com> * * @section Introduction * The Parameter class implements a way of storing and updating system parameters * of arbitrary size and type, while avoiding std::any and dynamic memory allocation. * It is split in two distinct parts: * 1) an abstract \ref ParameterBase class which provides a * common data type used to create any pointers to \ref Parameter objects, as well as * virtual functions for accessing the parameter's data part, and * 2) a templated \ref Parameter used to store any type-specific parameter information, * such as the actual data field where the parameter's value will be stored. * * @section Architecture Rationale * The ST[20] Parameter service is implemented with the need of arbitrary type storage * in mind, while avoiding any use of dynamic memory allocation, a requirement for use * in embedded systems. Since lack of Dynamic Memory Access precludes usage of stl::any * and the need for truly arbitrary (even for template-based objects like etl::string) type storage * would exclude from consideration constructs like etl::variant due to limitations on * the number of supported distinct types, a custom solution was needed. * Furthermore, the \ref ParameterService should provide ID-based access to parameters. */ class ParameterBase { public: virtual void appendValueToMessage(Message& message) = 0; virtual void setValueFromMessage(Message& message) = 0; virtual double getValueAsDouble() = 0; }; /** * Implementation of a parameter containing its value. See \ref ParameterBase for more information. * @tparam DataType The type of the Parameter value. This is the type used for transmission and reception * as per the PUS. */ template <typename DataType> class Parameter : public ParameterBase { private: DataType currentValue; public: explicit Parameter(DataType initialValue) : currentValue(initialValue) {} inline void setValue(DataType value) { currentValue = value; } inline DataType getValue() { return currentValue; } inline double getValueAsDouble() override { return static_cast<double>(currentValue); } /** * Given an ECSS message that contains this parameter as its first input, this loads the value from that paremeter */ inline void setValueFromMessage(Message& message) override { currentValue = message.read<DataType>(); }; /** * Appends the parameter as an ECSS value to an ECSS Message */ inline void appendValueToMessage(Message& message) override { message.append<DataType>(currentValue); }; }; #endif // ECSS_SERVICES_PARAMETER_HPP
35.716049
115
0.766678
ACubeSAT
ccd75449587615b2d6b8be5cbf43c63ca7aea6b1
120,789
cpp
C++
olp-cpp-sdk-dataservice-read/test/unit/src/CatalogClientTest.cpp
ystefinko/here-olp-edge-sdk-cpp
59f814cf98acd8f6c62572104a21ebdff4027171
[ "Apache-2.0" ]
1
2021-01-27T13:10:32.000Z
2021-01-27T13:10:32.000Z
olp-cpp-sdk-dataservice-read/test/unit/src/CatalogClientTest.cpp
ystefinko/here-olp-edge-sdk-cpp
59f814cf98acd8f6c62572104a21ebdff4027171
[ "Apache-2.0" ]
null
null
null
olp-cpp-sdk-dataservice-read/test/unit/src/CatalogClientTest.cpp
ystefinko/here-olp-edge-sdk-cpp
59f814cf98acd8f6c62572104a21ebdff4027171
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2019 HERE Europe B.V. * * 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. * * SPDX-License-Identifier: Apache-2.0 * License-Filename: LICENSE */ #include <chrono> #include <iostream> #include <regex> #include <string> #include <gmock/gmock.h> #include <gtest/gtest.h> #include <olp/authentication/AuthenticationCredentials.h> #include <olp/authentication/Settings.h> #include <olp/authentication/TokenEndpoint.h> #include <olp/authentication/TokenProvider.h> #include <olp/authentication/TokenResult.h> #include <olp/core/cache/DefaultCache.h> #include <olp/core/client/CancellationToken.h> #include <olp/core/client/HRN.h> #include <olp/core/client/OlpClient.h> #include <olp/core/client/OlpClientFactory.h> #include <olp/core/logging/Log.h> #include <olp/core/network/HttpResponse.h> #include <olp/core/network/Network.h> #include <olp/core/network/NetworkConfig.h> #include <olp/core/network/NetworkRequest.h> #include <olp/core/porting/make_unique.h> #include <olp/core/utils/Dir.h> #include <olp/dataservice/read/PrefetchTilesRequest.h> #include "HttpResponses.h" #include "olp/dataservice/read/CatalogClient.h" #include "olp/dataservice/read/CatalogRequest.h" #include "olp/dataservice/read/CatalogVersionRequest.h" #include "olp/dataservice/read/DataRequest.h" #include "olp/dataservice/read/PartitionsRequest.h" #include "olp/dataservice/read/model/Catalog.h" #include "testutils/CustomParameters.hpp" using namespace olp::dataservice::read; using namespace testing; #ifdef _WIN32 const std::string k_client_test_dir("\\catalog_client_test"); const std::string k_client_test_cache_dir("\\catalog_client_test\\cache"); #else const std::string k_client_test_dir("/catalog_client_test"); const std::string k_client_test_cache_dir("/catalog_client_test/cache"); #endif class MockHandler { public: MOCK_METHOD3(op, olp::client::CancellationToken( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& config, const olp::client::NetworkAsyncCallback& callback)); olp::client::CancellationToken operator()( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& config, const olp::client::NetworkAsyncCallback& callback) { return op(request, config, callback); } }; enum CacheType { InMemory = 0, Disk, Both }; using ClientTestParameter = std::pair<bool, CacheType>; class CatalogClientTestBase : public ::testing::TestWithParam<ClientTestParameter> { protected: virtual bool isOnlineTest() { return std::get<0>(GetParam()); } std::string GetTestCatalog() { static std::string mockCatalog{"hrn:here:data:::hereos-internal-test-v2"}; return isOnlineTest() ? CustomParameters::getArgument("catalog") : mockCatalog; } std::string PrintError(const olp::client::ApiError& error) { std::ostringstream resultStream; resultStream << "ERROR: code: " << static_cast<int>(error.GetErrorCode()) << ", status: " << error.GetHttpStatusCode() << ", message: " << error.GetMessage(); return resultStream.str(); } template <typename T> T GetExecutionTime(std::function<T()> func) { auto startTime = std::chrono::high_resolution_clock::now(); auto result = func(); auto end = std::chrono::high_resolution_clock::now(); std::chrono::duration<double> time = end - startTime; std::cout << "duration: " << time.count() * 1000000 << " us" << std::endl; return result; } protected: std::shared_ptr<olp::client::OlpClientSettings> settings_; std::shared_ptr<olp::client::OlpClient> client_; std::shared_ptr<MockHandler> handler_; }; class CatalogClientOnlineTest : public CatalogClientTestBase { void SetUp() { // olp::logging::Log::setLevel(olp::logging::Level::Trace); handler_ = std::make_shared<MockHandler>(); olp::authentication::TokenProviderDefault provider( CustomParameters::getArgument("appid"), CustomParameters::getArgument("secret")); olp::client::AuthenticationSettings authSettings; authSettings.provider = provider; settings_ = std::make_shared<olp::client::OlpClientSettings>(); settings_->authentication_settings = authSettings; client_ = olp::client::OlpClientFactory::Create(*settings_); } }; INSTANTIATE_TEST_SUITE_P(TestOnline, CatalogClientOnlineTest, ::testing::Values(std::make_pair(true, Both))); TEST_P(CatalogClientOnlineTest, GetCatalog) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::CatalogRequest(); auto catalogResponse = GetExecutionTime<olp::dataservice::read::CatalogResponse>([&] { auto future = catalogClient->GetCatalog(request); return future.GetFuture().get(); }); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientOnlineTest, GetPartitionsWithInvalidHrn) { olp::client::HRN hrn("hrn:here:data:::nope-test-v2"); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(403, partitionsResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetPartitions) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientOnlineTest, GetPartitionsForInvalidLayer) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("invalidLayer"); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithInvalidHrn) { olp::client::HRN hrn("hrn:here:data:::nope-test-v2"); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithDataHandle("d5d73b64-7365-41c3-8faf-aa6ad5bab135"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(403, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithHandle) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithDataHandle("d5d73b64-7365-41c3-8faf-aa6ad5bab135"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientOnlineTest, GetDataWithInvalidDataHandle) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithDataHandle("invalidDataHandle"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(404, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetDataHandleWithInvalidLayer) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("invalidLayer").WithDataHandle("invalidDataHandle"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithPartitionId) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientOnlineTest, GetDataWithPartitionIdVersion2) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientOnlineTest, GetDataWithPartitionIdInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(10); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetPartitionsVersion2) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(2); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_LT(0, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientOnlineTest, GetPartitionsInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(10); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithNonExistentPartitionId) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("noPartition"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_FALSE(dataResponse.GetResult()); } TEST_P(CatalogClientOnlineTest, GetDataWithInvalidLayerId) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("invalidLayer").WithPartitionId("269"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientOnlineTest, GetDataWithInlineField) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("3"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ(0u, dataStr.find("data:")); } TEST_P(CatalogClientOnlineTest, GetDataWithEmptyField) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("1"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_FALSE(dataResponse.GetResult()); } TEST_P(CatalogClientOnlineTest, GetDataCompressed) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("here_van_wc2018_pool"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0u, dataResponse.GetResult()->size()); auto requestCompressed = olp::dataservice::read::DataRequest(); requestCompressed.WithLayerId("testlayer_gzip") .WithPartitionId("here_van_wc2018_pool"); auto dataResponseCompressed = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(requestCompressed); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponseCompressed.IsSuccessful()) << PrintError(dataResponseCompressed.GetError()); ASSERT_LT(0u, dataResponseCompressed.GetResult()->size()); ASSERT_EQ(dataResponse.GetResult()->size(), dataResponseCompressed.GetResult()->size()); } void dumpTileKey(const olp::geo::TileKey& tileKey) { std::cout << "Tile: " << tileKey.ToHereTile() << ", level: " << tileKey.Level() << ", parent: " << tileKey.Parent().ToHereTile() << std::endl; } TEST_P(CatalogClientOnlineTest, Prefetch) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); std::vector<olp::geo::TileKey> tileKeys; tileKeys.emplace_back(olp::geo::TileKey::FromHereTile("5904591")); auto request = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys) .WithMinLevel(10) .WithMaxLevel(12); auto future = catalogClient->PrefetchTiles(request); auto response = future.GetFuture().get(); ASSERT_TRUE(response.IsSuccessful()); auto& result = response.GetResult(); for (auto tileResult : result) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(6u, result.size()); // Second part, use the cache, fetch a partition that's the child of 5904591 { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("23618365") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } // The parent of 5904591 should be fetched too { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("1476147") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } } //** ** ** ** MOCK TESTS ** ** ** ** **// MATCHER_P(IsGetRequest, url, "") { // uri, verb, null body return olp::network::NetworkRequest::HttpVerb::GET == arg.Verb() && url == arg.Url() && (!arg.Content() || arg.Content()->empty()); } olp::client::NetworkAsyncHandler setsPromiseWaitsAndReturns( std::shared_ptr<std::promise<void>> preSignal, std::shared_ptr<std::promise<void>> waitForSignal, olp::network::HttpResponse response, std::shared_ptr<std::promise<void>> postSignal = std::make_shared<std::promise<void>>()) { return [preSignal, waitForSignal, response, postSignal]( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& /*config*/, const olp::client::NetworkAsyncCallback& callback) -> olp::client::CancellationToken { auto completed = std::make_shared<std::atomic_bool>(false); std::thread([request, preSignal, waitForSignal, completed, callback, response, postSignal]() { // emulate a small response delay std::this_thread::sleep_for(std::chrono::milliseconds(50)); preSignal->set_value(); waitForSignal->get_future().get(); if (!completed->exchange(true)) { callback(response); } postSignal->set_value(); }) .detach(); return olp::client::CancellationToken([request, completed, callback, postSignal]() { if (!completed->exchange(true)) { callback({olp::network::Network::ErrorCode::Cancelled, "Cancelled"}); } }); }; } olp::client::NetworkAsyncHandler returnsResponse( olp::network::HttpResponse response) { return [=](const olp::network::NetworkRequest& /*request*/, const olp::network::NetworkConfig& /*config*/, const olp::client::NetworkAsyncCallback& callback) -> olp::client::CancellationToken { std::thread([callback, response]() { callback(response); }).detach(); return olp::client::CancellationToken(); }; } class CatalogClientMockTest : public CatalogClientTestBase { protected: void SetUp() { handler_ = std::make_shared<MockHandler>(); auto weakHandler = std::weak_ptr<MockHandler>(handler_); auto handle = [weakHandler]( const olp::network::NetworkRequest& request, const olp::network::NetworkConfig& config, const olp::client::NetworkAsyncCallback& callback) -> olp::client::CancellationToken { auto sharedHandler = weakHandler.lock(); if (sharedHandler) { return (*sharedHandler)(request, config, callback); } return olp::client::CancellationToken(); }; settings_ = std::make_shared<olp::client::OlpClientSettings>(); settings_->network_async_handler = handle; client_ = olp::client::OlpClientFactory::Create(*settings_); SetUpCommonNetworkMockCalls(); } void SetUpCommonNetworkMockCalls() { ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_CONFIG}))); ON_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_CONFIG}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_METADATA}))); ON_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LATEST_CATALOG_VERSION}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LAYER_VERSIONS}))); ON_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITIONS}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_QUERY}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITION_269}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_LOOKUP_BLOB}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_269}))); ON_CALL(*handler_, op(IsGetRequest(URL_PARTITION_3), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITION_3}))); ON_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_VOLATILE_BLOB), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LOOKUP_VOLATILE_BLOB}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_LAYER_VERSIONS_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITION_269_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269_V2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_269_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_V10), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_V10}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_VN1), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_VN1}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V10), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_V10}))); ON_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_VN1), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({400, HTTP_RESPONSE_INVALID_VERSION_VN1}))); ON_CALL(*handler_, op(IsGetRequest(URL_CONFIG_V2), testing::_, testing::_)) .WillByDefault( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_CONFIG_V2}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_23618364), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_23618364}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_1476147), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_1476147}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_5904591), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_5904591}))); ON_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_369036), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_QUADKEYS_369036}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_1), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_1}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_2), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_2}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_3), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_3}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_4), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_4}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_5), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_5}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_6), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_6}))); ON_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_PREFETCH_7), testing::_, testing::_)) .WillByDefault(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_BLOB_DATA_PREFETCH_7}))); // Catch any non-interesting network calls that don't need to be verified EXPECT_CALL(*handler_, op(testing::_, testing::_, testing::_)) .Times(testing::AtLeast(0)); } }; INSTANTIATE_TEST_SUITE_P(TestMock, CatalogClientMockTest, ::testing::Values(std::make_pair(false, Both))); TEST_P(CatalogClientMockTest, GetCatalog) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); catalogClient = nullptr; // Release crash. Do delete this line if you found it. auto request = CatalogRequest(); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogCallback) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; catalogClient->GetCatalog(request, callback); CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalog403) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(403, catalogResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetPartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionId) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientMockTest, GetDataWithInlineField) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITION_3), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("3"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ(0u, dataStr.find("data:")); } TEST_P(CatalogClientMockTest, GetEmptyPartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_EMPTY_PARTITIONS}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(0u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetVolatileDataHandle) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest( "https://volatile-blob-ireland.data.api.platform.here.com/" "blobstore/v1/catalogs/hereos-internal-test-v2/layers/" "testlayer_volatile/data/volatileHandle"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke(returnsResponse({200, "someData"}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer_volatile").WithDataHandle("volatileHandle"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("someData", dataStr); } TEST_P(CatalogClientMockTest, GetVolatilePartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL( *handler_, op(IsGetRequest( "https://metadata.data.api.platform.here.com/metadata/v1/catalogs/" "hereos-internal-test-v2/layers/testlayer_volatile/partitions"), testing::_, testing::_)) .Times(1) .WillRepeatedly( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer_volatile"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); request.WithVersion(18); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetVolatileDataByPartitionId) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL(*handler_, op(IsGetRequest("https://query.data.api.platform.here.com/query/" "v1/catalogs/hereos-internal-test-v2/layers/" "testlayer_volatile/partitions?partition=269"), testing::_, testing::_)) .Times(1) .WillRepeatedly( testing::Invoke(returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); EXPECT_CALL( *handler_, op(IsGetRequest( "https://volatile-blob-ireland.data.api.platform.here.com/" "blobstore/v1/catalogs/hereos-internal-test-v2/layers/" "testlayer_volatile/data/4eed6ed1-0d32-43b9-ae79-043cb4256410"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke(returnsResponse({200, "someData"}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer_volatile").WithPartitionId("269"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("someData", dataStr); } TEST_P(CatalogClientMockTest, GetStreamDataHandle) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer_stream").WithDataHandle("streamHandle"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::ServiceUnavailable, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetData429Error) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); } olp::client::RetrySettings retrySettings; retrySettings.retry_condition = [](const olp::network::HttpResponse& response) { return 429 == response.status; }; settings_->retry_settings = retrySettings; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithDataHandle("4eed6ed1-0d32-43b9-ae79-043cb4256432"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } TEST_P(CatalogClientMockTest, GetPartitions429Error) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); } olp::client::RetrySettings retrySettings; retrySettings.retry_condition = [](const olp::network::HttpResponse& response) { return 429 == response.status; }; settings_->retry_settings = retrySettings; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, ApiLookup429) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(2) .WillRepeatedly(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); } olp::client::RetrySettings retrySettings; retrySettings.retry_condition = [](const olp::network::HttpResponse& response) { return 429 == response.status; }; settings_->retry_settings = retrySettings; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetPartitionsForInvalidLayer) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("invalidLayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::InvalidArgument, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetData404Error) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest("https://blob-ireland.data.api.platform.here.com/" "blobstore/v1/catalogs/hereos-internal-test-v2/" "layers/testlayer/data/invalidDataHandle"), testing::_, testing::_)) .Times(1) .WillRepeatedly( testing::Invoke(returnsResponse({404, "Resource not found."}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithDataHandle("invalidDataHandle"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(404, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetPartitionsGarbageResponse) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({200, R"jsonString(kd3sdf\)jsonString"}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::ServiceUnavailable, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetCatalogCancelApiLookup) { olp::client::HRN hrn(GetTestCatalog()); auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); // Setup the expected calls : EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(0); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalog(request, callback); waitForCancel->get_future().get(); cancelToken.cancel(); pauseForCancel->set_value(); CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(catalogResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, catalogResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetCatalogCancelConfig) { olp::client::HRN hrn(GetTestCatalog()); auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); // Setup the expected calls : EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_CONFIG}))); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalog(request, callback); waitForCancel->get_future().get(); std::cout << "Cancelling" << std::endl; cancelToken.cancel(); // crashing? std::cout << "Cancelled, unblocking response" << std::endl; pauseForCancel->set_value(); std::cout << "Post Cancel, get response" << std::endl; CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(catalogResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, catalogResponse.GetError().GetErrorCode()); std::cout << "Post Test" << std::endl; } TEST_P(CatalogClientMockTest, GetCatalogCancelAfterCompletion) { olp::client::HRN hrn(GetTestCatalog()); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); std::promise<CatalogResponse> promise; CatalogResponseCallback callback = [&promise](CatalogResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalog(request, callback); CatalogResponse catalogResponse = promise.get_future().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); cancelToken.cancel(); } TEST_P(CatalogClientMockTest, GetPartitionsCancelLookupMetadata) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest().WithLayerId("testlayer"); std::promise<PartitionsResponse> promise; PartitionsResponseCallback callback = [&promise](PartitionsResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetPartitions(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler PartitionsResponse partitionsResponse = promise.get_future().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ( olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetPartitionsCancelLatestCatalogVersion) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LATEST_CATALOG_VERSION}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest().WithLayerId("testlayer"); std::promise<PartitionsResponse> promise; PartitionsResponseCallback callback = [&promise](PartitionsResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetPartitions(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler PartitionsResponse partitionsResponse = promise.get_future().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsCancelLayerVersions) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LAYER_VERSIONS}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest().WithLayerId("testlayer"); std::promise<PartitionsResponse> promise; PartitionsResponseCallback callback = [&promise](PartitionsResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetPartitions(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler PartitionsResponse partitionsResponse = promise.get_future().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupConfig) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelConfig) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupMetadata) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLatestCatalogVersion) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LATEST_CATALOG_VERSION}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelInnerConfig) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_CONFIG}))); } EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); olp::cache::CacheSettings cacheSettings; cacheSettings.max_memory_cache_size = 0; auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, olp::dataservice::read::CreateDefaultCache(cacheSettings)); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupQuery) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_QUERY}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelQuery) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_PARTITION_269}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelLookupBlob) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_BLOB}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdCancelBlob) { olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_BLOB_DATA_269}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); std::promise<DataResponse> promise; DataResponseCallback callback = [&promise](DataResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetData(request, callback); waitForCancel->get_future().get(); // wait for handler to get the request cancelToken.cancel(); pauseForCancel->set_value(); // unblock the handler DataResponse dataResponse = promise.get_future().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogVersion) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogVersionRequest().WithStartVersion(-1); auto future = catalogClient->GetCatalogMetadataVersion(request); auto catalogVersionResponse = future.GetFuture().get(); ASSERT_TRUE(catalogVersionResponse.IsSuccessful()) << PrintError(catalogVersionResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdVersion2) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V2), testing::_, testing::_)) .Times(0); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031_V2", dataStr); } TEST_P(CatalogClientMockTest, GetDataWithPartitionIdInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269").WithVersion(10); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, dataResponse.GetError().GetErrorCode()); ASSERT_EQ(400, dataResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetPartitionsVersion2) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS_V2), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(2); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientMockTest, GetPartitionsInvalidVersion) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithVersion(10); auto partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); request.WithVersion(-1); partitionsResponse = GetExecutionTime<olp::dataservice::read::PartitionsResponse>([&] { auto future = catalogClient->GetPartitions(request); return future.GetFuture().get(); }); ASSERT_FALSE(partitionsResponse.IsSuccessful()); ASSERT_EQ(olp::client::ErrorCode::BadRequest, partitionsResponse.GetError().GetErrorCode()); ASSERT_EQ(400, partitionsResponse.GetError().GetHttpStatusCode()); } TEST_P(CatalogClientMockTest, GetCatalogVersionCancel) { olp::client::HRN hrn(GetTestCatalog()); auto waitForCancel = std::make_shared<std::promise<void>>(); auto pauseForCancel = std::make_shared<std::promise<void>>(); // Setup the expected calls : EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel, pauseForCancel, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(0); // Run it! auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogVersionRequest().WithStartVersion(-1); std::promise<CatalogVersionResponse> promise; CatalogVersionCallback callback = [&promise](CatalogVersionResponse response) { promise.set_value(response); }; olp::client::CancellationToken cancelToken = catalogClient->GetCatalogMetadataVersion(request, callback); waitForCancel->get_future().get(); cancelToken.cancel(); pauseForCancel->set_value(); CatalogVersionResponse versionResponse = promise.get_future().get(); ASSERT_FALSE(versionResponse.IsSuccessful()) << PrintError(versionResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(versionResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, versionResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, GetCatalogCacheOnly) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); request.WithFetchOption(CacheOnly); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogOnlineOnly) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); } auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); request.WithFetchOption(OnlineOnly); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); future = catalogClient->GetCatalog(request); // Should fail despite valid cache entry. catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalogCacheWithUpdate) { olp::logging::Log::setLevel(olp::logging::Level::Trace); olp::client::HRN hrn(GetTestCatalog()); auto waitToStartSignal = std::make_shared<std::promise<void>>(); auto preCallbackWait = std::make_shared<std::promise<void>>(); preCallbackWait->set_value(); auto waitForEnd = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitToStartSignal, preCallbackWait, {200, HTTP_RESPONSE_CONFIG}, waitForEnd))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); request.WithFetchOption(CacheWithUpdate); // Request 1 EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "Request Catalog, CacheWithUpdate"); auto future = catalogClient->GetCatalog(request); EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "get CatalogResponse1"); CatalogResponse catalogResponse = future.GetFuture().get(); // Request 1 return. Cached value (nothing) ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); // Wait for background cache update to finish EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "wait some time for update to conclude"); waitForEnd->get_future().get(); // Request 2 to check there is a cached value. EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "Request Catalog, CacheOnly"); request.WithFetchOption(CacheOnly); future = catalogClient->GetCatalog(request); EDGE_SDK_LOG_TRACE_F("CatalogClientMockTest", "get CatalogResponse2"); catalogResponse = future.GetFuture().get(); // Cache should be available here. ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataCacheOnly) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetDataOnlineOnly) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); } auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(OnlineOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); // Should fail despite cached response future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); } TEST_P(CatalogClientMockTest, GetDataCacheWithUpdate) { olp::logging::Log::setLevel(olp::logging::Level::Trace); olp::client::HRN hrn(GetTestCatalog()); // Setup the expected calls : auto waitToStartSignal = std::make_shared<std::promise<void>>(); auto preCallbackWait = std::make_shared<std::promise<void>>(); preCallbackWait->set_value(); auto waitForEndSignal = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitToStartSignal, preCallbackWait, {200, HTTP_RESPONSE_BLOB_DATA_269}, waitForEndSignal))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = DataRequest(); request.WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(CacheWithUpdate); // Request 1 auto future = catalogClient->GetData(request); DataResponse dataResponse = future.GetFuture().get(); // Request 1 return. Cached value (nothing) ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); // Request 2 to check there is a cached value. // waiting for cache to fill-in waitForEndSignal->get_future().get(); request.WithFetchOption(CacheOnly); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); // Cache should be available here. ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsCacheOnly) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(0); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithFetchOption(CacheOnly); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsOnlineOnly) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( returnsResponse({429, "Server busy at the moment."}))); } auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer").WithFetchOption(OnlineOnly); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); // Should fail despite valid cache entry ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetPartitionsCacheWithUpdate) { olp::logging::Log::setLevel(olp::logging::Level::Trace); olp::client::HRN hrn(GetTestCatalog()); auto waitToStartSignal = std::make_shared<std::promise<void>>(); auto preCallbackWait = std::make_shared<std::promise<void>>(); preCallbackWait->set_value(); auto waitForEndSignal = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitToStartSignal, preCallbackWait, {200, HTTP_RESPONSE_PARTITIONS}, waitForEndSignal))); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = PartitionsRequest(); request.WithLayerId("testlayer").WithFetchOption(CacheWithUpdate); // Request 1 auto future = catalogClient->GetPartitions(request); PartitionsResponse partitionsResponse = future.GetFuture().get(); // Request 1 return. Cached value (nothing) ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); // Request 2 to check there is a cached value. waitForEndSignal->get_future().get(); request.WithFetchOption(CacheOnly); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); // Cache should be available here. ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); } TEST_P(CatalogClientMockTest, GetCatalog403CacheClear) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); } auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = CatalogRequest(); // Populate cache auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()); auto datarequest = DataRequest(); datarequest.WithLayerId("testlayer").WithPartitionId("269"); auto datafuture = catalogClient->GetData(datarequest); auto dataresponse = datafuture.GetFuture().get(); // Receive 403 request.WithFetchOption(OnlineOnly); future = catalogClient->GetCatalog(request); catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()); ASSERT_EQ(403, catalogResponse.GetError().GetHttpStatusCode()); // Check for cached response request.WithFetchOption(CacheOnly); future = catalogClient->GetCatalog(request); catalogResponse = future.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()); // Check the associated data has also been cleared datarequest.WithFetchOption(CacheOnly); datafuture = catalogClient->GetData(datarequest); dataresponse = datafuture.GetFuture().get(); ASSERT_FALSE(dataresponse.IsSuccessful()); } TEST_P(CatalogClientMockTest, GetData403CacheClear) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); } auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto request = DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); // Populate cache auto future = catalogClient->GetData(request); DataResponse dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()); // Receive 403 request.WithFetchOption(OnlineOnly); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); ASSERT_EQ(403, dataResponse.GetError().GetHttpStatusCode()); // Check for cached response request.WithFetchOption(CacheOnly); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()); } TEST_P(CatalogClientMockTest, GetPartitions403CacheClear) { olp::client::HRN hrn(GetTestCatalog()); auto catalog_client = std::make_unique<CatalogClient>(hrn, settings_); { InSequence s; EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), _, _)).Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), _, _)) .WillOnce(Invoke(returnsResponse({403, HTTP_RESPONSE_403}))); } // Populate cache auto request = PartitionsRequest().WithLayerId("testlayer"); auto future = catalog_client->GetPartitions(request); auto partitions_response = future.GetFuture().get(); ASSERT_TRUE(partitions_response.IsSuccessful()); // Receive 403 request.WithFetchOption(OnlineOnly); future = catalog_client->GetPartitions(request); partitions_response = future.GetFuture().get(); ASSERT_FALSE(partitions_response.IsSuccessful()); ASSERT_EQ(403, partitions_response.GetError().GetHttpStatusCode()); // Check for cached response request.WithFetchOption(CacheOnly); future = catalog_client->GetPartitions(request); partitions_response = future.GetFuture().get(); ASSERT_FALSE(partitions_response.IsSuccessful()); } TEST_P(CatalogClientMockTest, CancelPendingRequestsCatalog) { olp::client::HRN hrn(GetTestCatalog()); testing::InSequence s; std::vector<std::shared_ptr<std::promise<void>>> waits; std::vector<std::shared_ptr<std::promise<void>>> pauses; auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto catalogRequest = CatalogRequest().WithFetchOption(OnlineOnly); auto versionRequest = CatalogVersionRequest().WithFetchOption(OnlineOnly); // Make a few requests auto waitForCancel1 = std::make_shared<std::promise<void>>(); auto pauseForCancel1 = std::make_shared<std::promise<void>>(); auto waitForCancel2 = std::make_shared<std::promise<void>>(); auto pauseForCancel2 = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel1, pauseForCancel1, {200, HTTP_RESPONSE_LOOKUP_CONFIG}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel2, pauseForCancel2, {200, HTTP_RESPONSE_LOOKUP_METADATA}))); waits.push_back(waitForCancel1); pauses.push_back(pauseForCancel1); auto catalogFuture = catalogClient->GetCatalog(catalogRequest); waits.push_back(waitForCancel2); pauses.push_back(pauseForCancel2); auto versionFuture = catalogClient->GetCatalogMetadataVersion(versionRequest); for (auto wait : waits) { wait->get_future().get(); } // Cancel them all catalogClient->cancelPendingRequests(); for (auto pause : pauses) { pause->set_value(); } // Verify they are all cancelled CatalogResponse catalogResponse = catalogFuture.GetFuture().get(); ASSERT_FALSE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(catalogResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, catalogResponse.GetError().GetErrorCode()); CatalogVersionResponse versionResponse = versionFuture.GetFuture().get(); ASSERT_FALSE(versionResponse.IsSuccessful()) << PrintError(versionResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(versionResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, versionResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, CancelPendingRequestsPartitions) { olp::client::HRN hrn(GetTestCatalog()); testing::InSequence s; std::vector<std::shared_ptr<std::promise<void>>> waits; std::vector<std::shared_ptr<std::promise<void>>> pauses; auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_); auto partitionsRequest = PartitionsRequest().WithLayerId("testlayer").WithFetchOption(OnlineOnly); auto dataRequest = DataRequest() .WithLayerId("testlayer") .WithPartitionId("269") .WithFetchOption(OnlineOnly); // Make a few requests auto waitForCancel1 = std::make_shared<std::promise<void>>(); auto pauseForCancel1 = std::make_shared<std::promise<void>>(); auto waitForCancel2 = std::make_shared<std::promise<void>>(); auto pauseForCancel2 = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel1, pauseForCancel1, {200, HTTP_RESPONSE_LAYER_VERSIONS}))); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke( setsPromiseWaitsAndReturns(waitForCancel2, pauseForCancel2, {200, HTTP_RESPONSE_BLOB_DATA_269}))); waits.push_back(waitForCancel1); pauses.push_back(pauseForCancel1); auto partitionsFuture = catalogClient->GetPartitions(partitionsRequest); waits.push_back(waitForCancel2); pauses.push_back(pauseForCancel2); auto dataFuture = catalogClient->GetData(dataRequest); std::cout << "waiting" << std::endl; for (auto wait : waits) { wait->get_future().get(); } std::cout << "done waitingg" << std::endl; // Cancel them all catalogClient->cancelPendingRequests(); std::cout << "done cancelling" << std::endl; for (auto pause : pauses) { pause->set_value(); } // Verify they are all cancelled PartitionsResponse partitionsResponse = partitionsFuture.GetFuture().get(); ASSERT_FALSE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ( olp::network::Network::ErrorCode::Cancelled, static_cast<int>(partitionsResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, partitionsResponse.GetError().GetErrorCode()); DataResponse dataResponse = dataFuture.GetFuture().get(); ASSERT_FALSE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_EQ(olp::network::Network::ErrorCode::Cancelled, static_cast<int>(dataResponse.GetError().GetHttpStatusCode())); ASSERT_EQ(olp::client::ErrorCode::Cancelled, dataResponse.GetError().GetErrorCode()); } TEST_P(CatalogClientMockTest, Prefetch) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); std::vector<olp::geo::TileKey> tileKeys; tileKeys.emplace_back(olp::geo::TileKey::FromHereTile("5904591")); auto request = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys) .WithMinLevel(10) .WithMaxLevel(12); auto future = catalogClient->PrefetchTiles(request); auto response = future.GetFuture().get(); ASSERT_TRUE(response.IsSuccessful()); auto& result = response.GetResult(); for (auto tileResult : result) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(6u, result.size()); // Second part, use the cache, fetch a partition that's the child of 5904591 { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("23618365") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } // The parent of 5904591 should be fetched too { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("1476147") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); } } TEST_P(CatalogClientMockTest, PrefetchEmbedded) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); std::vector<olp::geo::TileKey> tileKeys; tileKeys.emplace_back(olp::geo::TileKey::FromHereTile("369036")); auto request = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys) .WithMinLevel(9) .WithMaxLevel(9); auto future = catalogClient->PrefetchTiles(request); auto response = future.GetFuture().get(); ASSERT_TRUE(response.IsSuccessful()); auto& result = response.GetResult(); for (auto tileResult : result) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(1u, result.size()); // Second part, use the cache to fetch the partition { auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("hype-test-prefetch") .WithPartitionId("369036") .WithFetchOption(FetchOptions::CacheOnly); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); // expected data = "data:Embedded Data for 369036" std::string dataStrDup(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("data:Embedded Data for 369036", dataStrDup); } } TEST_P(CatalogClientMockTest, PrefetchBusy) { olp::client::HRN hrn(GetTestCatalog()); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); // Prepare the first request std::vector<olp::geo::TileKey> tileKeys1; tileKeys1.emplace_back(olp::geo::TileKey::FromHereTile("5904591")); auto request1 = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys1) .WithMinLevel(10) .WithMaxLevel(12); // Prepare to delay the response of URL_QUADKEYS_5904591 until we've issued // the second request auto waitForQuadKeyRequest = std::make_shared<std::promise<void>>(); auto pauseForSecondRequest = std::make_shared<std::promise<void>>(); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUADKEYS_5904591), testing::_, testing::_)) .Times(1) .WillOnce(testing::Invoke(setsPromiseWaitsAndReturns( waitForQuadKeyRequest, pauseForSecondRequest, {200, HTTP_RESPONSE_QUADKEYS_5904591}))); // Issue the first request auto future1 = catalogClient->PrefetchTiles(request1); // Wait for QuadKey request waitForQuadKeyRequest->get_future().get(); // Prepare the second request std::vector<olp::geo::TileKey> tileKeys2; tileKeys2.emplace_back(olp::geo::TileKey::FromHereTile("369036")); auto request2 = olp::dataservice::read::PrefetchTilesRequest() .WithLayerId("hype-test-prefetch") .WithTileKeys(tileKeys2) .WithMinLevel(9) .WithMaxLevel(9); // Issue the second request auto future2 = catalogClient->PrefetchTiles(request2); // Unblock the QuadKey request pauseForSecondRequest->set_value(); // Validate that the second request failed auto response2 = future2.GetFuture().get(); ASSERT_FALSE(response2.IsSuccessful()); auto& error = response2.GetError(); ASSERT_EQ(olp::client::ErrorCode::SlowDown, error.GetErrorCode()); // Get and validate the first request auto response1 = future1.GetFuture().get(); ASSERT_TRUE(response1.IsSuccessful()); auto& result1 = response1.GetResult(); for (auto tileResult : result1) { ASSERT_TRUE(tileResult->IsSuccessful()); ASSERT_TRUE(tileResult->tile_key_.IsValid()); dumpTileKey(tileResult->tile_key_); } ASSERT_EQ(6u, result1.size()); } class CatalogClientCacheTest : public CatalogClientMockTest { void SetUp() { CatalogClientMockTest::SetUp(); olp::cache::CacheSettings settings; switch (std::get<1>(GetParam())) { case InMemory: { // use the default value break; } case Disk: { settings.max_memory_cache_size = 0; settings.disk_path = olp::utils::Dir::TempDirectory() + k_client_test_cache_dir; ClearCache(settings.disk_path.get()); break; } case Both: { settings.disk_path = olp::utils::Dir::TempDirectory() + k_client_test_cache_dir; ClearCache(settings.disk_path.get()); break; } default: // shouldn't get here break; } cache_ = std::make_shared<olp::cache::DefaultCache>(settings); ASSERT_EQ(olp::cache::DefaultCache::StorageOpenResult::Success, cache_->Open()); } void ClearCache(const std::string& path) { olp::utils::Dir::remove(path); } void TearDown() { if (cache_) { cache_->Close(); } ClearCache(olp::utils::Dir::TempDirectory() + k_client_test_dir); handler_.reset(); } protected: std::shared_ptr<olp::cache::DefaultCache> cache_; }; INSTANTIATE_TEST_SUITE_P(TestInMemoryCache, CatalogClientCacheTest, ::testing::Values(std::make_pair(false, InMemory))); INSTANTIATE_TEST_SUITE_P(TestDiskCache, CatalogClientCacheTest, ::testing::Values(std::make_pair(false, Disk))); INSTANTIATE_TEST_SUITE_P(TestBothCache, CatalogClientCacheTest, ::testing::Values(std::make_pair(false, Both))); TEST_P(CatalogClientCacheTest, GetApi) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_, cache_); auto request = CatalogVersionRequest().WithStartVersion(-1); auto future = catalogClient->GetCatalogMetadataVersion(request); auto catalogVersionResponse = future.GetFuture().get(); ASSERT_TRUE(catalogVersionResponse.IsSuccessful()) << PrintError(catalogVersionResponse.GetError()); auto partitionsRequest = olp::dataservice::read::PartitionsRequest(); partitionsRequest.WithLayerId("testlayer"); auto partitionsFuture = catalogClient->GetPartitions(partitionsRequest); auto partitionsResponse = partitionsFuture.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientCacheTest, GetCatalog) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<CatalogClient>(hrn, settings_, cache_); auto request = CatalogRequest(); auto future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse = future.GetFuture().get(); ASSERT_TRUE(catalogResponse.IsSuccessful()) << PrintError(catalogResponse.GetError()); future = catalogClient->GetCatalog(request); CatalogResponse catalogResponse2 = future.GetFuture().get(); ASSERT_TRUE(catalogResponse2.IsSuccessful()) << PrintError(catalogResponse2.GetError()); ASSERT_EQ(catalogResponse2.GetResult().GetName(), catalogResponse.GetResult().GetName()); } TEST_P(CatalogClientCacheTest, GetDataWithPartitionId) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::DataRequest(); request.WithLayerId("testlayer").WithPartitionId("269"); auto future = catalogClient->GetData(request); auto dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); future = catalogClient->GetData(request); dataResponse = future.GetFuture().get(); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStrDup(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStrDup); } TEST_P(CatalogClientCacheTest, GetPartitionsLayerVersions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); std::string url_testlayer_res = std::regex_replace( URL_PARTITIONS, std::regex("testlayer"), "testlayer_res"); std::string http_response_testlayer_res = std::regex_replace( HTTP_RESPONSE_PARTITIONS, std::regex("testlayer"), "testlayer_res"); EXPECT_CALL(*handler_, op(IsGetRequest(url_testlayer_res), testing::_, testing::_)) .Times(1) .WillOnce( testing::Invoke(returnsResponse({200, http_response_testlayer_res}))); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); request.WithLayerId("testlayer_res"); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientCacheTest, GetPartitions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LAYER_VERSIONS), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_PARTITIONS), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(4u, partitionsResponse.GetResult().GetPartitions().size()); } TEST_P(CatalogClientCacheTest, GetDataWithPartitionIdDifferentVersions) { olp::client::HRN hrn(GetTestCatalog()); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_METADATA), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LATEST_CATALOG_VERSION), testing::_, testing::_)) .Times(2); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_CONFIG), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_BLOB), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_LOOKUP_QUERY), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_QUERY_PARTITION_269_V2), testing::_, testing::_)) .Times(1); EXPECT_CALL(*handler_, op(IsGetRequest(URL_BLOB_DATA_269_V2), testing::_, testing::_)) .Times(1); auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>(hrn, settings_); auto request = olp::dataservice::read::DataRequest(); { request.WithLayerId("testlayer").WithPartitionId("269"); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } { request.WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031_V2", dataStr); } { request.WithVersion(boost::none); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031", dataStr); } { request.WithVersion(2); auto dataResponse = GetExecutionTime<olp::dataservice::read::DataResponse>([&] { auto future = catalogClient->GetData(request); return future.GetFuture().get(); }); ASSERT_TRUE(dataResponse.IsSuccessful()) << PrintError(dataResponse.GetError()); ASSERT_LT(0, dataResponse.GetResult()->size()); std::string dataStr(dataResponse.GetResult()->begin(), dataResponse.GetResult()->end()); ASSERT_EQ("DT_2_0031_V2", dataStr); } } TEST_P(CatalogClientCacheTest, GetVolatilePartitionsExpiry) { olp::client::HRN hrn(GetTestCatalog()); { testing::InSequence s; EXPECT_CALL( *handler_, op(IsGetRequest( "https://metadata.data.api.platform.here.com/metadata/v1/" "catalogs/" "hereos-internal-test-v2/layers/testlayer_volatile/partitions"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_PARTITIONS_V2}))); EXPECT_CALL( *handler_, op(IsGetRequest( "https://metadata.data.api.platform.here.com/metadata/v1/" "catalogs/" "hereos-internal-test-v2/layers/testlayer_volatile/partitions"), testing::_, testing::_)) .Times(1) .WillRepeatedly(testing::Invoke( returnsResponse({200, HTTP_RESPONSE_EMPTY_PARTITIONS}))); } auto catalogClient = std::make_unique<olp::dataservice::read::CatalogClient>( hrn, settings_, cache_); auto request = olp::dataservice::read::PartitionsRequest(); request.WithLayerId("testlayer_volatile"); auto future = catalogClient->GetPartitions(request); auto partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); // hit the cache only, should be still be there request.WithFetchOption(olp::dataservice::read::CacheOnly); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(1u, partitionsResponse.GetResult().GetPartitions().size()); // wait for the layer to expire in cache std::this_thread::sleep_for(std::chrono::seconds(2)); request.WithFetchOption(olp::dataservice::read::OnlineIfNotFound); future = catalogClient->GetPartitions(request); partitionsResponse = future.GetFuture().get(); ASSERT_TRUE(partitionsResponse.IsSuccessful()) << PrintError(partitionsResponse.GetError()); ASSERT_EQ(0u, partitionsResponse.GetResult().GetPartitions().size()); }
36.74749
81
0.695146
ystefinko
ccd7f0ecb1012bc3172bb0343849506f7eba3e34
18,220
cxx
C++
3rd/fltk/OpenGL/Fl_Gl_Window.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
11
2017-09-30T12:21:55.000Z
2021-04-29T21:31:57.000Z
3rd/fltk/OpenGL/Fl_Gl_Window.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
2
2017-07-11T11:20:08.000Z
2018-03-27T12:09:02.000Z
3rd/fltk/OpenGL/Fl_Gl_Window.cxx
MarioHenze/cgv
bacb2d270b1eecbea1e933b8caad8d7e11d807c2
[ "BSD-3-Clause" ]
24
2018-03-27T11:46:16.000Z
2021-05-01T20:28:34.000Z
// "$Id: Fl_Gl_Window.cxx 5936 2007-07-24 11:25:53Z spitzak $" // // Copyright 1998-2006 by Bill Spitzak and others. // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Library General Public License for more details. // // You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 // USA. // // Please report all bugs and problems to "fltk-bugs@fltk.org". #include <config.h> #if HAVE_GL #include "GlChoice.h" #include <fltk/GlWindow.h> #include <fltk/damage.h> #include <fltk/error.h> #include <fltk/visual.h> #include <fltk/layout.h> #include <fltk/run.h> #include <fltk/events.h> #include <stdlib.h> #include <string.h> using namespace fltk; /** \class fltk::GlWindow Provides an area in which the draw() method can use OpenGL to draw. This widget sets things up so OpenGL works, and also keeps an OpenGL "context" for that window, so that changes to the lighting and projection may be reused between redraws. GlWindow also flushes the OpenGL streams and swaps buffers after draw() returns. draw() is a pure virtual method. You must subclass GlWindow and provide an implementation for draw(). You can avoid reinitializing the viewport and lights and other things by checking valid() at the start of draw() and only doing the initialization if it is false. draw() can \e only use OpenGL calls. Do not attempt to call any of the functions in &lt;fltk/draw.h&gt;, or X or GDI32 or any other drawing api. Do not call glstart() or glfinish(). <h2>Double Buffering</h2> Normally double-buffering is enabled. You can disable it by chaning the mode() to turn off the DOUBLE_BUFFER bit. If double-buffering is enabled, the back buffer is made current before draw() is called, and the back and front buffers are \e automatically swapped after draw() is completed. Some tricks using the front buffer require you to control the swapping. You can call swap_buffers() to swap them (OpenGL does not provide a portable function for this, so we provide it). But you will need to turn off the auto-swap, you do this by adding the NO_AUTO_SWAP bit to the mode(). <h2>Overlays</h2> The method draw_overlay() is a second drawing operation that is put atop the main image. You can implement this, and call redraw_overlay() to indicate that the image in this overlay has changed and that draw_overlay() must be called. Originally this was written to support hardware overlays, but FLTK emulated it if the hardware was missing so programs were portable. FLTK 2.0 is not normally compiled to support hardware overlays, but the emulation still remains, so you can use these functions. (Modern hardware typically has no overlays, and besides it is fast enough that the original purpose of them is moot) By default the emulation is to call draw_overlay() after draw() and before swapping the buffers, so the overlay is just part of the normal image and does not blink. You can get some of the advantages of overlay hardware by setting the GL_SWAP_TYPE environment variable, which will cause the front buffer to be used for the draw_overlay() method, and not call draw() each time the overlay changes. This will be faster if draw() is very complex, but the overlay will blink. GL_SWAP_TYPE can be set to: - "USE_COPY" use glCopyPixels to copy the back buffer to the front. This should always work. - "COPY" indicates that the swap_buffers() function actually copies the back to the front buffer, rather than swapping them. If your card does this (most do) then this is best. - "NODAMAGE" indicates that behavior is like "COPY" but \e nothing changes the back buffer, including overlapping it with another OpenGL window. This is true of software OpenGL emulation, and may be true of some modern cards with lots of memory. */ //////////////////////////////////////////////////////////////// // The symbol SWAP_TYPE defines what is in the back buffer after doing // a glXSwapBuffers(). // The OpenGl documentation says that the contents of the backbuffer // are "undefined" after glXSwapBuffers(). However, if we know what // is in the backbuffers then we can save a good deal of time. For // this reason you can define some symbols to describe what is left in // the back buffer. // Having not found any way to determine this from glx (or wgl) I have // resorted to letting the user specify it with an environment variable, // GL_SWAP_TYPE, it should be equal to one of these symbols: // contents of back buffer after glXSwapBuffers(): #define SWAP 1 // assumme garbage is in back buffer (default) #define USE_COPY 2 // use glCopyPixels to imitate COPY behavior #define COPY 3 // unchanged #define NODAMAGE 4 // unchanged even by X expose() events static char SWAP_TYPE = 0; // 0 = determine it from environment variable //////////////////////////////////////////////////////////////// /** \fn bool GlWindow::can_do() const Returns true if the hardware supports the current value of mode(). If false, attempts to show or draw this window will cause an fltk::error(). */ /** Returns true if the hardware supports \a mode, see mode() for the meaning of the bits. */ bool GlWindow::can_do(int mode) { return GlChoice::find(mode) != 0; } void GlWindow::create() { if (!gl_choice) { gl_choice = GlChoice::find(mode_); if (!gl_choice) {error("Insufficient GL support"); return;} } #ifdef WIN32 Window::create(); #elif USE_QUARTZ Window::create(); #else CreatedWindow::create(this, gl_choice->vis, gl_choice->colormap, -1); //if (overlay && overlay != this) ((GlWindow*)overlay)->show(); //fltk::flush(); glXWaitGL(); glXWaitX(); #endif } /** \fn char GlWindow::valid() const; This flag is turned off on a new window or if the window is ever resized or the context is changed. It is turned on after draw() is called. draw() can use this to skip initializing the viewport, lights, or other pieces of the context. \code void My_GlWindow_Subclass::draw() { if (!valid()) { glViewport(0,0,w(),h()); glFrustum(...); glLight(...); glEnable(...); ...other initialization... } ... draw your geometry here ... } \endcode */ /** Turn off valid(). */ void GlWindow::invalidate() { valid(0); #if USE_X11 if (overlay) ((GlWindow*)overlay)->valid(0); #endif } /** Set or change the OpenGL capabilites of the window. The value can be any of the symbols from \link visual.h <fltk/visual.h> \endlink OR'd together: - fltk::INDEXED_COLOR indicates that a colormapped visual is ok. This call will normally fail if a TrueColor visual cannot be found. - fltk::RGB_COLOR this value is zero and may be passed to indicate that fltk::INDEXED_COLOR is \e not wanted. - fltk::RGB24_COLOR indicates that the visual must have at least 8 bits of red, green, and blue (Windows calls this "millions of colors"). - fltk::DOUBLE_BUFFER indicates that double buffering is wanted. - fltk::SINGLE_BUFFER is zero and can be used to indicate that double buffering is \a not wanted. - fltk::ACCUM_BUFFER makes the accumulation buffer work - fltk::ALPHA_BUFFER makes an alpha buffer - fltk::DEPTH_BUFFER makes a depth/Z buffer - fltk::STENCIL_BUFFER makes a stencil buffer - fltk::MULTISAMPLE makes it multi-sample antialias if possible (X only) - fltk::STEREO stereo if possible - NO_AUTO_SWAP disables the automatic call to swap_buffers() after draw(). - NO_ERASE_OVERLAY if overlay hardware is used, don't call glClear before calling draw_overlay(). If the desired combination cannot be done, FLTK will try turning off MULTISAMPLE and STERERO. If this also fails then attempts to create the context will cause fltk::error() to be called, aborting the program. Use can_do() to check for this and try other combinations. You can change the mode while the window is displayed. This is most useful for turning double-buffering on and off. Under X this will cause the old X window to be destroyed and a new one to be created. If this is a top-level window this will unfortunately also cause the window to blink, raise to the top, and be de-iconized, and the ID will change, possibly breaking other code. It is best to make the GL window a child of another window if you wish to do this! */ bool GlWindow::mode(int m) { if (m == mode_) return false; mode_ = m; // destroy context and g: if (shown()) { bool reshow = visible_r(); destroy(); gl_choice = 0; if (reshow) {create(); show();} } return true; } #define NON_LOCAL_CONTEXT 0x80000000 /** Selects the OpenGL context for the widget, creating it if necessary. It is called automatically prior to the draw() method being called. You can call it in handle() to set things up to do OpenGL hit detection, or call it other times to do incremental update of the window. */ void GlWindow::make_current() { Window::make_current(); // so gc is correct for non-OpenGL calls #if USE_QUARTZ if (!gl_choice) { gl_choice = GlChoice::find(mode_); if (!gl_choice) {error("Insufficient GL support"); return;} } #endif if (!context_) { mode_ &= ~NON_LOCAL_CONTEXT; context_ = create_gl_context(this, gl_choice); set_gl_context(this, context_); valid(0); } else { set_gl_context(this, context_); } } /** Set the projection so 0,0 is in the lower left of the window and each pixel is 1 unit wide/tall. If you are drawing 2D images, your draw() method may want to call this when valid() is false. */ void GlWindow::ortho() { #if 1 // simple version glLoadIdentity(); glViewport(0, 0, w(), h()); glOrtho(0, w(), 0, h(), -1, 1); #else // this makes glRasterPos off the edge much less likely to clip, // but a lot of OpenGL drivers do not like it. GLint v[2]; glGetIntegerv(GL_MAX_VIEWPORT_DIMS, v); glLoadIdentity(); glViewport(w()-v[0], h()-v[1], v[0], v[1]); glOrtho(w()-v[0], w(), h()-v[1], h(), -1, 1); #endif } /** Swap the front and back buffers of this window (or copy the back buffer to the front, possibly clearing or garbaging the back one, depending on your OpenGL implementation. This is called automatically after draw() unless the NO_AUTO_SWAP flag is set in the mode(). */ void GlWindow::swap_buffers() { #ifdef _WIN32 #if USE_GL_OVERLAY // Do not swap the overlay, to match GLX: wglSwapLayerBuffers(CreatedWindow::find(this)->dc, WGL_SWAP_MAIN_PLANE); #else SwapBuffers(CreatedWindow::find(this)->dc); #endif #elif USE_QUARTZ aglSwapBuffers((AGLContext)context_); #else glXSwapBuffers(xdisplay, xid(this)); #endif } #if USE_GL_OVERLAY && defined(_WIN32) int fl_overlay_depth = 0; bool fl_overlay; #endif void GlWindow::flush() { uchar save_valid = valid_; uchar save_damage = damage(); CreatedWindow* i = CreatedWindow::find(this); #if USE_GL_OVERLAY && defined(_WIN32) if (save_damage == DAMAGE_OVERLAY && overlay && overlay != this && !i->region) goto OVERLAY_ONLY; #endif make_current(); if (mode_ & DOUBLE_BUFFER) { glDrawBuffer(GL_BACK); if (!SWAP_TYPE) { SWAP_TYPE = SWAP; const char* c = getenv("GL_SWAP_TYPE"); if (c) switch (c[0]) { case 'U' : SWAP_TYPE = USE_COPY; break; case 'C' : SWAP_TYPE = COPY; break; case 'N' : SWAP_TYPE = NODAMAGE; break; default : SWAP_TYPE = SWAP; break; } } if (SWAP_TYPE == NODAMAGE) { // don't draw if only overlay damage or expose events: if (save_damage != DAMAGE_OVERLAY || !save_valid) { draw(); if (!(mode_ & NO_AUTO_SWAP)) swap_buffers(); } else { swap_buffers(); } } else if (SWAP_TYPE == COPY) { // don't draw if only the overlay is damaged: if (save_damage != DAMAGE_OVERLAY || i->region || !save_valid) { draw(); if (!(mode_ & NO_AUTO_SWAP)) swap_buffers(); } else { swap_buffers(); } } else if (SWAP_TYPE == USE_COPY && overlay == this) { // If we are faking the overlay, use CopyPixels to act like // SWAP_TYPE == COPY. Otherwise overlay redraw is way too slow. // don't draw if only the overlay is damaged: if (damage1_ || save_damage != DAMAGE_OVERLAY || i->region || !save_valid) draw(); // we use a seperate context for the copy because rasterpos must be 0 // and depth test needs to be off: static GLContext ortho_context = 0; static GlWindow* ortho_window = 0; if (!ortho_context) { ortho_context = create_gl_context(this, gl_choice); save_valid = 0; } set_gl_context(this, ortho_context); if (!save_valid || ortho_window != this) { ortho_window = this; glDisable(GL_DEPTH_TEST); glReadBuffer(GL_BACK); glDrawBuffer(GL_FRONT); glLoadIdentity(); glViewport(0, 0, w(), h()); glOrtho(0, w(), 0, h(), -1, 1); glRasterPos2i(0,0); } glCopyPixels(0,0,w(),h(),GL_COLOR); make_current(); // set current context back to draw overlay damage1_ = 0; } else { damage1_ = save_damage; set_damage(DAMAGE_ALL); draw(); if (overlay == this) draw_overlay(); if (!(mode_ & NO_AUTO_SWAP)) swap_buffers(); goto NO_OVERLAY; } if (overlay==this) { // fake overlay in front buffer glDrawBuffer(GL_FRONT); draw_overlay(); glDrawBuffer(GL_BACK); glFlush(); } NO_OVERLAY:; } else { // single-buffered context is simpler: draw(); if (overlay == this) draw_overlay(); glFlush(); } #if USE_GL_OVERLAY && defined(_WIN32) OVERLAY_ONLY: // Draw into hardware overlay planes if they are damaged: if (overlay && overlay != this && (i->region || save_damage&DAMAGE_OVERLAY || !save_valid)) { #if SGI320_BUG // SGI 320 messes up overlay with user-defined cursors: bool fixcursor = false; if (i->cursor && i->cursor != fl_default_cursor) { fixcursor = true; // make it restore cursor later SetCursor(0); } #endif set_gl_context(this, (GLContext)overlay); if (fl_overlay_depth) wglRealizeLayerPalette(i->dc, 1, TRUE); glDisable(GL_SCISSOR_TEST); if (!(mode_&NO_ERASE_OVERLAY)) glClear(GL_COLOR_BUFFER_BIT); fl_overlay = true; valid(save_valid); draw_overlay(); fl_overlay = false; wglSwapLayerBuffers(i->dc, WGL_SWAP_OVERLAY1); #if SGI320_BUG if (fixcursor) SetCursor(i->cursor); #endif } #endif valid(1); } void GlWindow::layout() { if (layout_damage() & LAYOUT_WH) { valid(0); #if USE_QUARTZ no_gl_context(); // because the BUFFER_RECT may change #endif #if USE_X11 if (!resizable() && overlay && overlay != this) ((GlWindow*)overlay)->resize(0,0,w(),h()); #endif } Window::layout(); #if USE_X11 glXWaitX(); #endif } /** \fn GLContext GlWindow::context() const; Return the current OpenGL context object being used by this window, or 0 if there is none. */ /** \fn void GlWindow::context(GLContext v, bool destroy_flag); Set the OpenGL context object to use to draw this window. This is a system-dependent structure (HGLRC on Windows,GLXContext on X, and AGLContext (may change) on OS/X), but it is portable to copy the context from one window to another. You can also set it to NULL, which will force FLTK to recreate the context the next time make_current() is called, this is useful for getting around bugs in OpenGL implementations. \a destroy_flag indicates that the context belongs to this window and should be destroyed by it when no longer needed. It will be destroyed when the window is destroyed, or when the mode() is changed, or if the context is changed to a new value with this call. */ void GlWindow::_context(void* v, bool destroy_flag) { if (context_ && context_ != v && !(mode_&NON_LOCAL_CONTEXT)) delete_gl_context(context_); context_ = (GLContext)v; if (destroy_flag) mode_ &= ~NON_LOCAL_CONTEXT; else mode_ |= NON_LOCAL_CONTEXT; } /** Besides getting rid of the window, this will destroy the context if it belongs to the window. */ void GlWindow::destroy() { context(0); #if USE_GL_OVERLAY if (overlay && overlay != this) { #ifdef _WIN32 delete_gl_context((GLContext)overlay); #endif overlay = 0; } #endif Window::destroy(); } /** The destructor will destroy the context() if it belongs to the window. */ GlWindow::~GlWindow() { destroy(); } /** \fn GlWindow::GlWindow(int x, int y, int w, int h, const char *label=0); The constructor sets the mode() to RGB_COLOR|DEPTH_BUFFER|DOUBLE_BUFFER which is probably all that is needed for most 3D OpenGL graphics. */ void GlWindow::init() { mode_ = DEPTH_BUFFER | DOUBLE_BUFFER; context_ = 0; gl_choice = 0; overlay = 0; damage1_ = 0; } /** You must implement this virtual function if you want to draw into the overlay. The overlay is cleared before this is called (unless the NO_ERASE_OVERLAY bit is set in the mode \e and hardware overlay is supported). You should draw anything that is not clear using OpenGL. If the hardware overlay is being used it will probably be color indexed. You must use glsetcolor() to choose colors (it allocates them from the colormap using system-specific calls), and remember that you are in an indexed OpenGL mode and drawing anything other than flat-shaded will probably not work. Depending on the OS and whether or not the overlay is being simulated, the context may be shared with the main window. This means if you check valid() in draw() to avoid initialization, you must do so here and initialize to exactly the same setting. */ void GlWindow::draw_overlay() {} int GlWindow::handle( int event ) { #if USE_QUARTZ switch ( event ) { case HIDE: aglSetDrawable( context(), NULL ); break; } #endif return Window::handle( event ); } #endif // // End of "$Id: Fl_Gl_Window.cxx 5936 2007-07-24 11:25:53Z spitzak $". //
32.710952
99
0.704007
MarioHenze
ccd8312594e55bf962aa855e1fefc1e514fe86db
20,619
cpp
C++
frameworks/render/libs/isect/dmzRenderIsect.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
2
2015-11-05T03:03:43.000Z
2017-05-15T12:55:39.000Z
frameworks/render/libs/isect/dmzRenderIsect.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
frameworks/render/libs/isect/dmzRenderIsect.cpp
dmzgroup/dmz
fc2d9ddcb04ed71f4106b8d33539529807b3dea6
[ "MIT" ]
null
null
null
#include <dmzRenderIsect.h> #include <dmzTypesHandleContainer.h> #include <dmzTypesHashTableUInt32Template.h> #include <dmzTypesVector.h> //! \cond const dmz::UInt32 dmz::IsectPolygonBackCulledMask (0x01); const dmz::UInt32 dmz::IsectPolygonFrontCulledMask (0x02); const dmz::UInt32 dmz::IsectPolygonInvisibleMask (0x04); //! \endcond namespace { struct testStruct { dmz::UInt32 testID; dmz::IsectTestTypeEnum type; dmz::Vector pt1; dmz::Vector pt2; testStruct &operator= (const testStruct &Value) { testID = Value.testID; type = Value.type; pt1 = Value.pt1; pt2 = Value.pt2; return *this; } testStruct () : testID (0), type (dmz::IsectUnknownTest) {;} testStruct ( const dmz::UInt32 TestID, const dmz::IsectTestTypeEnum TheType, const dmz::Vector &ThePt1, const dmz::Vector &ThePt2) : testID (TestID), type (TheType), pt1 (ThePt1), pt2 (ThePt2) {;} testStruct (const testStruct &Value) : testID (0), type (dmz::IsectUnknownTest) { *this = Value; } }; }; /*! \class dmz::IsectTestContainer \ingroup Render \brief Intersection test container. \details The intersection test container stores multiple intersection tests so that the tests may be batch processed if the underlying implementation supports it. Intersection test may use either rays or segments. */ struct dmz::IsectTestContainer::State { UInt32 count; HashTableUInt32Iterator it; HashTableUInt32Template<testStruct> table; State () : count (0) {;} ~State () { table.empty (); } void clear () { it.reset (); count = 0; table.empty (); } }; //! Constructor. dmz::IsectTestContainer::IsectTestContainer () : _state (*(new State)) {;} //! Copy constructor. dmz::IsectTestContainer::IsectTestContainer (const IsectTestContainer &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectTestContainer::~IsectTestContainer () { delete &_state; } //! Assignment operator. dmz::IsectTestContainer & dmz::IsectTestContainer::operator= (const IsectTestContainer &Value) { _state.count = Value._state.count; _state.table.empty (); _state.table.copy (Value._state.table); return *this; } //! Clear container. void dmz::IsectTestContainer::clear () { _state.clear (); } /*! \brief Adds or updates an intersection test in the container. \param[in] TestID Intersection test identification value. ID values do not need to be sequential. \param[in] TestType Type intersection test to perform. Defines how \a Value1 and \a Value2 are interpreted. \param[in] Value1 The start point. \param[in] Value2 Either the ray's direction or the end of the segment. \return Returns dmz::True if the test was successfully stored in the container. \sa dmz::IsectTestTypeEnum */ dmz::Boolean dmz::IsectTestContainer::set_test ( const UInt32 TestID, const IsectTestTypeEnum TestType, const Vector &Value1, const Vector &Value2) { Boolean result (False); testStruct *ts = _state.table.lookup (TestID); if (!ts) { ts = new testStruct (TestID, TestType, Value1, Value2); if (_state.table.store (TestID, ts)) { result = True; } else { delete ts; ts = 0; } } else { ts->type = TestType; ts->pt1 = Value1; ts->pt2 = Value2; result = True; } return result; } /*! \brief Adds or updates a ray intersection test in the container. \param[in] TestID Intersection test identification value. ID values do not need to be sequential. \param[in] Position Starting point of the ray. \param[in] Direction Unit vector containing the direction of the ray. \return Returns dmz::True if the ray test was successfully stored in the container. */ dmz::Boolean dmz::IsectTestContainer::set_ray_test ( const UInt32 TestID, const Vector &Position, const Vector &Direction) { return set_test (TestID, IsectRayTest, Position, Direction); } /*! \brief Adds or updates a segment intersection test in the container. \param[in] TestID Intersection test identification value. ID values do not need to be sequential. \param[in] StartPoint Starting point of the segment. \param[in] EndPoint End point of the segment. \return Returns dmz::True if the segment test was successfully stored in the container. */ dmz::Boolean dmz::IsectTestContainer::set_segment_test ( const UInt32 TestID, const Vector &StartPoint, const Vector &EndPoint) { return set_test (TestID, IsectSegmentTest, StartPoint, EndPoint); } /*! \brief Adds an intersection test in the container. \param[in] TestType Type intersection test to perform. Defines how \a Value1 and \a Value2 are interpreted. \param[in] Value1 The start point. \param[in] Value2 Either the ray's direction or the end of the segment. \return Returns the test ID. Returns zero if the test was not added. \sa dmz::IsectTestTypeEnum */ dmz::UInt32 dmz::IsectTestContainer::add_test ( const IsectTestTypeEnum TestType, const Vector &Value1, const Vector &Value2) { UInt32 result (0); testStruct *ts (new testStruct (0, TestType, Value1, Value2)); if (ts) { _state.count++; if (!_state.count) { _state.count++; } if (_state.table.store (_state.count, ts)) { result = ts->testID = _state.count; } else { const UInt32 Start (_state.count); _state.count++; if (!_state.count) { _state.count++; } while ((_state.count != Start) && _state.table.lookup (_state.count)) { _state.count++; if (!_state.count) { _state.count++; } } if (_state.count != Start) { if (_state.table.store (_state.count, ts)) { result = ts->testID = _state.count; } else { delete ts; ts = 0; } } } } return result; } /*! \brief Adds a ray intersection test in the container. \param[in] Position Starting point of the ray. \param[in] Direction Unit vector containing the direction of the ray. \return Returns the test ID. Returns zero if the test was not added. */ dmz::UInt32 dmz::IsectTestContainer::add_ray_test (const Vector &Position, const Vector &Direction) { return add_test (IsectRayTest, Position, Direction); } /*! \brief Adds a segment intersection test in the container. \param[in] StartPoint Starting point of the segment. \param[in] EndPoint End point of the segment. \return Returns the test ID. Returns zero if the test was not added. */ dmz::UInt32 dmz::IsectTestContainer::add_segment_test ( const Vector &StartPoint, const Vector &EndPoint) { return add_test (IsectSegmentTest, StartPoint, EndPoint); } /*! \brief Removes intersection test. \param[in] TestID Intersection test ID value. \return Returns dmz::True if the test was successfully removed from the container. */ dmz::Boolean dmz::IsectTestContainer::remove_test (const UInt32 TestID) { Boolean result (False); testStruct *ts = _state.table.remove (TestID); if (ts) { result = True; delete ts; ts = 0; } return result; } /*! \brief Looks up intersection test. \param[in] TestID Intersection test ID value. \param[out] testType The type of the test. \param[out] value1 First Vector value of the intersection test. \param[out] value2 Second Vector value of the intersection test. \return Returns dmz::True if the intersection test specified by \a TestID is found. */ dmz::Boolean dmz::IsectTestContainer::lookup_test ( const UInt32 TestID, IsectTestTypeEnum &testType, Vector &value1, Vector &value2) const { Boolean result (False); testStruct *ts = _state.table.lookup (TestID); if (ts) { testType = ts->type; value1 = ts->pt1; value2 = ts->pt2; result = True; } return result; } /*! \brief Gets first intersection test. \param[out] testID Intersection test ID value. \param[out] testType The type of the test. \param[out] value1 First Vector value of the intersection test. \param[out] value2 Second Vector value of the intersection test. \return Returns dmz::True if the first intersection test is returned. Returns dmz::False if the container is empty. */ dmz::Boolean dmz::IsectTestContainer::get_first_test ( UInt32 &testID, IsectTestTypeEnum &testType, Vector &value1, Vector &value2) const { Boolean result (False); testStruct *ts = _state.table.get_first (_state.it); if (ts) { testID = ts->testID; testType = ts->type; value1 = ts->pt1; value2 = ts->pt2; result = True; } return result; } /*! \brief Gets next intersection test. \param[out] testID Intersection test ID value. \param[out] testType The type of the test. \param[out] value1 First Vector value of the intersection test. \param[out] value2 Second Vector value of the intersection test. \return Returns dmz::True if the next intersection test is returned. Returns dmz::False if the container has returned all intersection tests. */ dmz::Boolean dmz::IsectTestContainer::get_next_test ( UInt32 &testID, IsectTestTypeEnum &testType, Vector &value1, Vector &value2) const { Boolean result (False); testStruct *ts = _state.table.get_next (_state.it); if (ts) { testID = ts->testID; testType = ts->type; value1 = ts->pt1; value2 = ts->pt2; result = True; } return result; } /*! \class dmz::IsectParameters \ingroup Render \brief Intersection test parameters. \details The dmz::IsectParameters specifies what results should be collect from the intersection test. Bu default, all parameters are set to dmz::True. */ struct dmz::IsectParameters::State { IsectTestResultTypeEnum type; Boolean findNormal; Boolean findHandle; Boolean findDistance; Boolean findCullMode; Boolean attrSet; HandleContainer attr; State () : type (IsectAllPoints), findNormal (True), findHandle (True), findDistance (True), findCullMode (True), attrSet (False) {;} }; //! Constructor. dmz::IsectParameters::IsectParameters () : _state (*(new State)) {;} //! Copy constructor. dmz::IsectParameters::IsectParameters (const IsectParameters &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectParameters::~IsectParameters () { delete &_state; } //! Assignment operator. dmz::IsectParameters & dmz::IsectParameters::operator= (const IsectParameters &Value) { _state.type = Value._state.type; _state.findNormal = Value._state.findNormal; _state.findHandle = Value._state.findHandle; _state.findDistance = Value._state.findDistance; _state.findCullMode = Value._state.findCullMode; return *this; } //! Specifies how test points should be processed and returned. void dmz::IsectParameters::set_test_result_type (const IsectTestResultTypeEnum Type) { _state.type = Type; } //! Gets how test points should be processed and returned. dmz::IsectTestResultTypeEnum dmz::IsectParameters::get_test_result_type () const { return _state.type; } //! Specifies if intersection normal should be calculated for each result. void dmz::IsectParameters::set_calculate_normal (const Boolean AttrState) { _state.findNormal = AttrState; } //! Returns if intersection normal should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_normal () const { return _state.findNormal; } //! Specifies if the objects Handle should be calculated for each result. void dmz::IsectParameters::set_calculate_object_handle (const Boolean AttrState) { _state.findHandle = AttrState; } //! Returns if the objects Handle should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_object_handle () const { return _state.findHandle; } //! Specifies if the intersection distance should be calculated for each result. void dmz::IsectParameters::set_calculate_distance (const Boolean AttrState) { _state.findDistance = AttrState; } //! Returns if the intersection distance should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_distance () const { return _state.findDistance; } //! Specifies if the polygon cull mode should be calculated for each result. void dmz::IsectParameters::set_calculate_cull_mode (const Boolean Value) { _state.findCullMode = Value; } //! Returns if the polygon cull mode should be calculated for each result. dmz::Boolean dmz::IsectParameters::get_calculate_cull_mode () const { return _state.findCullMode; } /*! \brief Sets the isect attributes to use in the intersection tests. \details By default, all intersections are tested against dmz::RenderIsectStaticName and dmz::RenderIsectEntityName. \param[in] Attr HandleContainer containing the isect attribute handles. */ void dmz::IsectParameters::set_isect_attributes (const HandleContainer &Attr) { if (Attr.get_count () > 0) { _state.attrSet = True; _state.attr = Attr; } } /*! \brief Gets the isect attributes to use in the intersection tests. \param[out] attr HandleContainer containing the isect attribute handles. \return Return dmz::True if any handles were returned in the HandleContainer. */ dmz::Boolean dmz::IsectParameters::get_isect_attributes (HandleContainer &attr) const { Boolean result (_state.attrSet); if (result) { attr = _state.attr; } return result; } /*! \class dmz::IsectResult \ingroup Render \brief Intersection test result. */ struct dmz::IsectResult::State { UInt32 testID; Boolean pointSet; Vector point; Boolean normalSet; Vector normal; Boolean objHandleSet; Handle objHandle; Boolean distanceSet; Float64 distance; Boolean cullModeSet; UInt32 cullMode; State () : testID (0), pointSet (False), normalSet (False), objHandleSet (False), objHandle (0), distanceSet (False), distance (0.0), cullModeSet (False), cullMode (0) {;} }; //! Base constructor. dmz::IsectResult::IsectResult () : _state (*(new State)) {;} /*! \brief Test ID Constructor. \param[in] TestID Intersection test identification value. */ dmz::IsectResult::IsectResult (const UInt32 TestID) : _state (*(new State)) { _state.testID = TestID; } //! Copy constructor. dmz::IsectResult::IsectResult (const IsectResult &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectResult::~IsectResult () { delete &_state; } //! Assignment operator. dmz::IsectResult & dmz::IsectResult::operator= (const IsectResult &Value) { _state.testID = Value._state.testID; _state.pointSet = Value._state.pointSet; _state.point = Value._state.point; _state.normalSet = Value._state.normalSet; _state.normal = Value._state.normal; _state.objHandleSet = Value._state.objHandleSet; _state.objHandle = Value._state.objHandle; _state.distanceSet = Value._state.distanceSet; _state.distance = Value._state.distance; _state.cullModeSet = Value._state.cullModeSet; _state.cullMode = Value._state.cullMode; return *this; } //! Sets intersection test identification value. void dmz::IsectResult::set_isect_test_id (const UInt32 TestID) { _state.testID = TestID; } //! Gets intersection test identification value. dmz::UInt32 dmz::IsectResult::get_isect_test_id () const { return _state.testID; } //! Sets intersection point. void dmz::IsectResult::set_point (const Vector &Value) { _state.pointSet = True; _state.point = Value; } /*! \brief Gets intersection point. \param[out] value Vector containing intersection point. \return Returns dmz::True if the intersection point was set. */ dmz::Boolean dmz::IsectResult::get_point (Vector &value) const { value = _state.point; return _state.pointSet; } //! Sets intersection point normal. void dmz::IsectResult::set_normal (const Vector &Value) { _state.normalSet = True; _state.normal = Value; } /*! \brief Gets intersection point normal. \param[out] value Vector containing intersection point normal. \return Returns dmz::True if the intersection point normal was set. */ dmz::Boolean dmz::IsectResult::get_normal (Vector &value) const { value = _state.normal; return _state.normalSet; } //! Sets intersected object's Handle. void dmz::IsectResult::set_object_handle (const Handle Value) { _state.objHandleSet = True; _state.objHandle = Value; } /*! \brief Gets intersection point object Handle. \param[out] value Handle containing intersection point object Handle. \return Returns dmz::True if the intersection point object Handle was set. */ dmz::Boolean dmz::IsectResult::get_object_handle (Handle &value) const { value = _state.objHandle; return _state.objHandleSet; } //! Sets intersection distance from start point. void dmz::IsectResult::set_distance (const Float64 Value) { _state.distanceSet = True; _state.distance = Value; } /*! \brief Gets intersection distance from the intersection start point. \param[out] value Distance from the intersection start point. \return Returns dmz::True if the intersection distance was set. */ dmz::Boolean dmz::IsectResult::get_distance (Float64 &value) const { value = _state.distance; return _state.distanceSet; } //! Sets cull mode of intersected polygon. void dmz::IsectResult::set_cull_mode (const UInt32 Value) { _state.cullModeSet = True; _state.cullMode = Value; } /*! \brief Gets intersection point cull mode. \param[out] value Mask containing the polygons cull mode. \return Returns dmz::True if the cull mode was set. */ dmz::Boolean dmz::IsectResult::get_cull_mode (UInt32 &value) const { value = _state.cullMode; return _state.cullModeSet; } /*! \class dmz::IsectResultContainer \ingroup Render \brief Intersection test result container. \details The intersection result container will have an IsectResult for each intersection point that is returned. Multiple IsectResult objects may result from a single test. */ struct dmz::IsectResultContainer::State { UInt32 count; HashTableUInt32Iterator it; HashTableUInt32Template<IsectResult> table; State () : count (0) {;} ~State () { table.empty (); } }; //! Base constructor. dmz::IsectResultContainer::IsectResultContainer () : _state (*(new State)) {;} //! Copy constructor. dmz::IsectResultContainer::IsectResultContainer (const IsectResultContainer &Value) : _state (*(new State)) { *this = Value; } //! Destructor. dmz::IsectResultContainer::~IsectResultContainer () { delete &_state; } //! Assignment operator. dmz::IsectResultContainer & dmz::IsectResultContainer::operator= (const IsectResultContainer &Value) { _state.count = Value._state.count; _state.table.empty (); _state.table.copy (Value._state.table); return *this; } //! Returns number of intersection results are stored in the container. dmz::Int32 dmz::IsectResultContainer::get_result_count () const { return _state.table.get_count (); } //! Resets the iterator. void dmz::IsectResultContainer::reset () { _state.it.reset (); } //! Clears the container. void dmz::IsectResultContainer::clear () { _state.it.reset (); _state.table.empty (); _state.count = 0; } //! Adds a result to the container. void dmz::IsectResultContainer::add_result (const IsectResult &Value) { IsectResult *ir (new IsectResult (Value)); if (ir) { if (_state.table.store (_state.count, ir)) { _state.count++; } else { delete ir; ir = 0; } } } /*! \brief Gets first result stored in the container. \param[out] value First result stored in the container. \return Returns dmz::True if the first result is returned in \a value. Returns dmz::False if the container is empty. */ dmz::Boolean dmz::IsectResultContainer::get_first (IsectResult &value) const { Boolean result (False); IsectResult *ir (_state.table.get_first (_state.it)); if (ir) { value = *ir; result = True; } return result; } /*! \brief Gets next result stored in the container. \param[out] value next result stored in the container. \return Returns dmz::True if the next result is returned in \a value. Returns dmz::False if the container has returned all results. */ dmz::Boolean dmz::IsectResultContainer::get_next (IsectResult &value) const { Boolean result (False); IsectResult *ir (_state.table.get_next (_state.it)); if (ir) { value = *ir; result = True; } return result; }
23.193476
90
0.701392
dmzgroup
ccda31c2812b512e71f448266234ec53ea6dc35b
1,498
hpp
C++
include/cppgit2/tag.hpp
koordinates/cppgit2
49c36843f828f2f628aacdd04daf9d0812a220a4
[ "MIT" ]
null
null
null
include/cppgit2/tag.hpp
koordinates/cppgit2
49c36843f828f2f628aacdd04daf9d0812a220a4
[ "MIT" ]
null
null
null
include/cppgit2/tag.hpp
koordinates/cppgit2
49c36843f828f2f628aacdd04daf9d0812a220a4
[ "MIT" ]
1
2022-01-26T20:23:12.000Z
2022-01-26T20:23:12.000Z
#pragma once #include <cppgit2/libgit2_api.hpp> #include <cppgit2/object.hpp> #include <cppgit2/oid.hpp> #include <cppgit2/ownership.hpp> #include <cppgit2/signature.hpp> #include <git2.h> namespace cppgit2 { class tag : public libgit2_api { public: // Default construct a tag tag(); // Construct from libgit2 C ptr // If owned by user, this will be free'd in destructor tag(git_tag *c_ptr, ownership owner = ownership::libgit2); // Cleanup tag ptr ~tag(); // Move constructor (appropriate other's c_ptr_) tag(tag&& other); // Move assignment constructor (appropriate other's c_ptr_) tag& operator= (tag&& other); // Create an in-memory copy of a tag tag copy() const; // Copy constructor tag(tag const& other); // Id of the tag oid id() const; // Tag mesage std::string message() const; // Tag name std::string name() const; // Recursively peel until a non-tag git_object is found object peel() const; // Get tagger (author) of this tag signature tagger() const; // Get the tagged object of this tag object target() const; // Get the OID of the tagged object oid target_id() const; // Get the type of a tag's tagged object object::object_type target_type() const; // Owner repository for this tag class repository owner() const; // Access to libgit2 C ptr git_tag *c_ptr(); const git_tag *c_ptr() const; private: friend class repository; git_tag *c_ptr_; ownership owner_; }; } // namespace cppgit2
20.520548
61
0.685581
koordinates
ef9ddb8bf2a42a685700817d638d505ef1a0f0a5
397
cpp
C++
higan/fc/cpu/serialization.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
higan/fc/cpu/serialization.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
higan/fc/cpu/serialization.cpp
13824125580/higan
fbdd3f980b65412c362096579869ae76730e4118
[ "Intel", "ISC" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
auto CPU::serialize(serializer& s) -> void { MOS6502::serialize(s); Thread::serialize(s); s.array(ram); s.integer(io.interruptPending); s.integer(io.nmiPending); s.integer(io.nmiLine); s.integer(io.irqLine); s.integer(io.apuLine); s.integer(io.rdyLine); s.integer(io.rdyAddrValid); s.integer(io.rdyAddrValue); s.integer(io.oamdmaPending); s.integer(io.oamdmaPage); }
19.85
44
0.690176
13824125580
efa042dc4136bec3323bfe0cefe543bcbd5721e4
2,356
cc
C++
gcj2019/Round_1b/Problem1.cc
maciej-marek-mielczarek/gcj
b3ccdd48f24c2e89f4135f6d8f53d12c404f327b
[ "MIT" ]
null
null
null
gcj2019/Round_1b/Problem1.cc
maciej-marek-mielczarek/gcj
b3ccdd48f24c2e89f4135f6d8f53d12c404f327b
[ "MIT" ]
null
null
null
gcj2019/Round_1b/Problem1.cc
maciej-marek-mielczarek/gcj
b3ccdd48f24c2e89f4135f6d8f53d12c404f327b
[ "MIT" ]
null
null
null
#include<iostream> #include<string> #include<vector> using std::cin; using std::cout; using std::endl; using std::vector; int main() { int test_case = 1, n_test_cases; cin >> n_test_cases; for(;test_case <= n_test_cases; ++test_case) { int p, q; cin >> p >> q; if(q>100) break; vector<int> tmp(11, 0); vector< vector<int> > interest(11, tmp); for(int n=0;n<p;++n) { int xx, yy; cin >> xx >> yy; char d; cin >> d; if(d=='N') { for(int x=0;x<=q;++x) { for(int y=yy+1;y<=q;++y) { ++(interest[x][y]); } } } if(d=='S') { for(int x=0;x<=q;++x) { for(int y=0;y<=yy-1;++y) { ++(interest[x][y]); } } } if(d=='E') { for(int x=xx+1;x<=q;++x) { for(int y=0;y<=q;++y) { ++(interest[x][y]); } } } if(d=='W') { for(int x=0;x<=xx-1;++x) { for(int y=0;y<=q;++y) { ++(interest[x][y]); } } } } int x=0, y=0, score=interest[0][0]; for(int xi=0;xi<=q;++xi) { for(int yi=0;yi<=q;++yi) { if(interest[xi][yi]>score) { score = interest[xi][yi]; x=xi; y=yi; } } } cout << "Case #" << test_case << ": " << x << " " << y<<"\n"; } /* int test_case = 1, n_test_cases = 0; string tmp{}; std::getline(cin, tmp); for(char digit : tmp) { if(digit >= '0' && digit <= '9') { n_test_cases *= 10; n_test_cases += (digit - '0'); } } for(;test_case <= n_test_cases; ++test_case) { } */ return 0; }
23.098039
69
0.290323
maciej-marek-mielczarek
efa08206632b844ab7d8ab2a76e49588af975efd
1,056
hh
C++
include/neutrino/utils/io/stream_copier.hh
devbrain/neutrino
5e7cd7c93b5c264a5f1da6ae88312e14253de10d
[ "Apache-2.0" ]
null
null
null
include/neutrino/utils/io/stream_copier.hh
devbrain/neutrino
5e7cd7c93b5c264a5f1da6ae88312e14253de10d
[ "Apache-2.0" ]
null
null
null
include/neutrino/utils/io/stream_copier.hh
devbrain/neutrino
5e7cd7c93b5c264a5f1da6ae88312e14253de10d
[ "Apache-2.0" ]
null
null
null
// // Created by igor on 08/07/2021. // #ifndef NEUTRINO_UTILS_IO_STREAM_COPIER_HH #define NEUTRINO_UTILS_IO_STREAM_COPIER_HH #include <istream> #include <ostream> #include <cstddef> namespace neutrino::utils::io { /// This class provides static methods to copy the contents from one stream /// into another. struct stream_copier { /// Writes all bytes readable from istr to ostr, using an internal buffer. /// /// Returns the number of bytes copied. static std::streamsize copy_stream (std::istream& istr, std::ostream& ostr, std::size_t bufferSize = 8192); /// Writes all bytes readable from istr to ostr. /// /// Returns the number of bytes copied. static std::streamsize copy_stream_unbuffered (std::istream& istr, std::ostream& ostr); /// Appends all bytes readable from istr to the given string, using an internal buffer. /// /// Returns the number of bytes copied. static std::streamsize copy_to_string (std::istream& istr, std::string& str, std::size_t bufferSize = 8192); }; } #endif
30.171429
112
0.704545
devbrain
efa1c3d012db6b8ff25ed550db2088ff438ff81a
33,110
cpp
C++
shared/src/wdg/ds_slider_painter_bevelled.cpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
shared/src/wdg/ds_slider_painter_bevelled.cpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
shared/src/wdg/ds_slider_painter_bevelled.cpp
amazingidiot/qastools
6e3b0532ebc353c79d6df0628ed375e3d3c09d12
[ "MIT" ]
null
null
null
/// QasTools: Desktop toolset for the Linux sound system ALSA. /// \copyright See COPYING file. #include "ds_slider_painter_bevelled.hpp" #include "dpe/image_set.hpp" #include "dpe/image_set_meta.hpp" #include "dpe/paint_job.hpp" #include "wdg/color_methods.hpp" #include "wdg/ds_slider_meta_bg.hpp" #include "wdg/ds_widget_style_db.hpp" #include "wdg/ds_widget_types.hpp" #include "wdg/uint_mapper.hpp" #include <QImage> #include <QLinearGradient> #include <QPainter> #include <QPainterPath> #include <QRadialGradient> #include <QScopedPointer> #include <cmath> #include <iostream> namespace Wdg { namespace Painter { struct DS_Slider_Painter_Bevelled::PData { inline QSize & size () { return meta->size; } inline int width () { return meta->size.width (); } inline int height () { return meta->size.height (); } ::dpe::Image_Set_Meta * meta; QPalette pal; QPainter qpnt; int ew; // Edge width int bw; // Border width x,y int bevel; int tick_width[ 3 ]; int tick_min_dist; QRectF rectf; bool has_focus; bool has_weak_focus; bool mouse_over; bool is_down; ::dpe::Image * img; ::Wdg::DS_Slider_Meta_Bg * meta_bg; }; DS_Slider_Painter_Bevelled::DS_Slider_Painter_Bevelled () : ::Wdg::Painter::DS_Widget_Painter ( ::Wdg::DS_SLIDER ) { } int DS_Slider_Painter_Bevelled::paint_image ( ::dpe::Paint_Job * pjob_n ) { int res ( 0 ); // Init paint data PData pd; pd.meta = pjob_n->meta; pd.img = &pjob_n->img_set->image ( pjob_n->img_idx ); res = create_image_data ( pd.img, pd.meta ); if ( res == 0 ) { // Init general painting setup if ( wdg_style_db () != 0 ) { pd.pal = wdg_style_db ()->palettes[ pd.meta->style_id ]; pd.pal.setCurrentColorGroup ( wdg_style_db ()->color_group ( pd.meta->style_sub_id ) ); } pd.bw = pd.meta->size.width () / 24; if ( pd.bw < 2 ) { pd.bw = 2; } pd.ew = ( pd.bw / 4 ); if ( pd.ew < 1 ) { pd.ew = 1; } pd.bevel = pd.bw; pd.rectf = QRectF ( 0.0, 0.0, pd.width (), pd.height () ); // Init painter pd.qpnt.begin ( &pd.img->qimage () ); pd.qpnt.setRenderHints ( QPainter::Antialiasing | QPainter::SmoothPixmapTransform ); // Paint type switch ( pd.meta->type_id ) { case 0: res = paint_bg ( pjob_n, pd ); break; case 1: res = paint_marker ( pjob_n, pd ); break; case 2: res = paint_frame ( pjob_n, pd ); break; case 3: res = paint_handle ( pjob_n, pd ); break; } } return res; } // Background painting int DS_Slider_Painter_Bevelled::paint_bg ( ::dpe::Paint_Job * pjob_n, PData & pd ) { //::std::cout << "DS_Slider_Painter_Bevelled::paint_bg " << "\n"; pd.meta_bg = dynamic_cast<::Wdg::DS_Slider_Meta_Bg * > ( pjob_n->meta ); if ( pd.meta_bg == 0 ) { return -1; } // Calculate tick sizes { int in_width ( pd.meta->size.width () - 2 * pd.bw ); pd.tick_width[ 0 ] = in_width * 1 / 2; pd.tick_width[ 1 ] = in_width * 1 / 4; pd.tick_width[ 2 ] = in_width * 1 / 16; pd.tick_width[ 0 ] = ::std::max ( pd.tick_width[ 0 ], 6 ); pd.tick_width[ 1 ] = ::std::max ( pd.tick_width[ 1 ], 4 ); pd.tick_width[ 2 ] = ::std::max ( pd.tick_width[ 2 ], 2 ); if ( ( pd.meta->size.width () % 2 ) == 0 ) { for ( int ii = 0; ii < 3; ++ii ) { if ( ( pd.tick_width[ ii ] % 2 ) != 0 ) { ++( pd.tick_width[ ii ] ); } } } else { for ( int ii = 0; ii < 3; ++ii ) { if ( ( pd.tick_width[ ii ] % 2 ) == 0 ) { ++( pd.tick_width[ ii ] ); } } } pd.tick_min_dist = 8; } // State flags { pd.is_down = ( pjob_n->img_idx == 1 ); } // Painting { paint_bg_area ( pd ); paint_bg_frame ( pd ); paint_bg_area_deco ( pd ); paint_bg_ticks ( pd ); } return 0; } void DS_Slider_Painter_Bevelled::paint_bg_area ( PData & pd ) { QColor col_li ( pd.pal.color ( QPalette::Button ) ); QColor col_mid ( pd.pal.color ( QPalette::Button ) ); QColor col_dk ( pd.pal.color ( QPalette::Mid ) ); col_li.setAlpha ( 55 ); col_dk.setAlpha ( 190 ); const double inner_width ( pd.width () - 2 * pd.bw ); const double x_start = pd.bw; const double x_end = pd.width () - pd.bw; const double x_mid = x_start + inner_width / 3.0; QPainterPath area_path; papp_bevel_area ( area_path, pd.rectf, pd.bevel, pd.bw / 2.0 ); // Base color { pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_mid ); } pd.qpnt.drawPath ( area_path ); // Fake 3D gradient { QLinearGradient lgrad ( QPointF ( x_start, 0.0 ), QPointF ( x_end, 0.0 ) ); lgrad.setColorAt ( 0.0, col_li ); lgrad.setColorAt ( x_mid / ( x_end - x_start ), col_mid ); lgrad.setColorAt ( 1.0, col_dk ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( lgrad ); } pd.qpnt.drawPath ( area_path ); // Sound color overlay { QColor c0 ( pd.pal.color ( QPalette::Window ) ); QColor c1 ( c0 ); c0.setAlpha ( 30 ); c1.setAlpha ( 0 ); QLinearGradient lgrad ( QPointF ( x_start, 0.0 ), QPointF ( x_start + inner_width / 7.0, 0.0 ) ); lgrad.setColorAt ( 0.0, c0 ); lgrad.setColorAt ( 1.0, c1 ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( lgrad ); } pd.qpnt.drawPath ( area_path ); } void DS_Slider_Painter_Bevelled::paint_bg_frame ( PData & pd ) { QColor fcol; { QColor col_btn ( pd.pal.color ( QPalette::Button ) ); QColor col_mid ( pd.pal.color ( QPalette::Mid ) ); if ( col_mid == col_btn ) { col_mid = pd.pal.color ( QPalette::WindowText ); fcol = col_mix ( col_btn, col_mid, 1, 1 ); } else { fcol = col_mix ( col_btn, col_mid, 1, 2 ); } // fcol = col_mid; } paint_bevel_raised_frame ( pd, pd.rectf, pd.bevel, pd.bw, pd.ew, fcol ); } void DS_Slider_Painter_Bevelled::paint_bg_area_deco ( PData & pd ) { QPainterPath ppath; const int range_max_idx ( pd.meta_bg->ticks_range_max_idx ); int y_min; int y_bottom; int y_top; bool has_minimum ( pd.meta_bg->bg_show_image ); bool has_zero_split ( false ); y_bottom = pd.height () - 1; y_bottom -= pd.meta_bg->ticks_range_start; y_top = y_bottom - range_max_idx; y_min = y_bottom; if ( has_minimum ) { Wdg::UInt_Mapper_Auto mapper ( range_max_idx, pd.meta_bg->ticks_max_idx ); y_min -= mapper.v2_to_v1 ( pd.meta_bg->bg_tick_min_idx ); } has_zero_split = ( ( y_min > y_top ) && ( y_min < y_bottom ) ); const double w_tick ( ( pd.tick_width[ 0 ] + pd.tick_width[ 1 ] ) / 2.0 ); const double w_out ( w_tick * 2.0 / 3.0 ); const double w_neck ( 1 ); double x_out_l ( ( pd.width () - w_tick ) / 2.0 ); double x_neck_l ( x_out_l ); double x_out_r; double x_neck_r; x_neck_l = std::floor ( x_neck_l ); x_neck_r = x_neck_l + w_neck; x_out_l = std::floor ( x_out_l ); x_out_r = x_out_l + w_out; if ( has_minimum ) { if ( has_zero_split ) { double x_out_rt ( x_out_r ); double x_out_rb ( x_out_r ); const int dt ( y_min - y_top ); const int db ( y_bottom - y_min ); if ( dt > db ) { int ww = ( db * w_out ) / dt; x_out_rb = x_out_l + ww; } else { int ww = ( dt * w_out ) / db; x_out_rt = x_out_l + ww; } ppath.moveTo ( x_out_l, y_top + 0.5 ); ppath.lineTo ( x_out_rt, y_top + 0.5 ); ppath.lineTo ( x_neck_r, y_min + 0.5 ); ppath.lineTo ( x_out_rb, y_bottom + 0.5 ); ppath.lineTo ( x_out_l, y_bottom + 0.5 ); ppath.lineTo ( x_neck_l, y_min + 0.5 ); ppath.closeSubpath (); } else { double x_rt; double x_rb; if ( y_min < y_bottom ) { x_rt = x_neck_r; x_rb = x_out_r; } else { x_rt = x_out_r; x_rb = x_neck_r; } ppath.moveTo ( x_neck_l, y_top + 0.5 ); ppath.lineTo ( x_rt, y_top + 0.5 ); ppath.lineTo ( x_rb, y_bottom + 0.5 ); ppath.lineTo ( x_out_l, y_bottom + 0.5 ); ppath.closeSubpath (); } } else { x_out_r = x_out_l + w_out / 2.0; ppath.moveTo ( x_out_l, y_top + 0.5 ); ppath.lineTo ( x_out_r, y_top + 0.5 ); ppath.lineTo ( x_out_r, y_bottom + 0.5 ); ppath.lineTo ( x_out_l, y_bottom + 0.5 ); ppath.closeSubpath (); } { QColor col_fill ( pd.pal.color ( QPalette::Window ) ); QColor col_pen ( pd.pal.color ( QPalette::WindowText ) ); if ( pd.is_down ) { col_fill.setAlpha ( 40 ); col_pen.setAlpha ( 40 ); } else { col_fill.setAlpha ( 16 ); col_pen.setAlpha ( 18 ); } { QPen pen; pen.setColor ( col_pen ); pen.setWidth ( 1.0 ); pd.qpnt.setPen ( pen ); } pd.qpnt.setBrush ( col_fill ); } pd.qpnt.drawPath ( ppath ); } void DS_Slider_Painter_Bevelled::paint_bg_ticks ( PData & pd ) { const int range_max_idx ( pd.meta_bg->ticks_range_max_idx ); unsigned int ticks_max_idx; int idx_delta ( 1 ); int y_off; y_off = pd.height () - 1; y_off -= pd.meta_bg->ticks_range_start; const int y_bottom = y_off; const int y_top = y_off - range_max_idx; // Setup main tick position mapper ticks_max_idx = pd.meta_bg->ticks_max_idx; if ( ticks_max_idx > 0 ) { if ( ( range_max_idx / ticks_max_idx ) < 2 ) { ticks_max_idx = range_max_idx / pd.tick_min_dist; } } ::Wdg::UInt_Mapper_Up mapper ( ticks_max_idx, range_max_idx ); if ( ticks_max_idx > 0 ) { const int tmd ( mapper.min_dist () ); while ( ( idx_delta * tmd ) < pd.tick_min_dist ) { ++idx_delta; } } // Paint { QColor tick_col ( pd.pal.color ( QPalette::WindowText ) ); tick_col = col_mix ( tick_col, pd.pal.color ( QPalette::Button ), 3, 1 ); const int idx_start = idx_delta; for ( unsigned int ii = idx_start; ii < ticks_max_idx; ii += idx_delta ) { int yy = y_bottom - mapper.map ( ii ); if ( ( yy - y_top ) < pd.tick_min_dist ) { break; } paint_bg_tick ( pd, yy, pd.tick_width[ 1 ], tick_col ); } } { QColor tick_col ( pd.pal.color ( QPalette::WindowText ) ); tick_col = col_mix ( tick_col, pd.pal.color ( QPalette::Button ), 4, 1 ); // Bottom and top ticks if ( ticks_max_idx > 0 ) { paint_bg_tick ( pd, y_top, pd.tick_width[ 0 ], tick_col ); } paint_bg_tick ( pd, y_bottom, pd.tick_width[ 0 ], tick_col ); } } void DS_Slider_Painter_Bevelled::paint_bg_tick ( PData & pd, double tick_pos_n, double tick_width_n, const QColor & col_n ) { const double tick_start ( ( pd.width () - tick_width_n ) / 2.0 ); QColor col ( col_n ); // Glow below solid line { col.setAlpha ( 32 ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col ); const unsigned int num_pts ( 9 ); double xl ( tick_start - 0.5 ); double xr ( tick_start + tick_width_n + 0.5 ); const QPointF points[ num_pts ] = {QPointF ( xl, tick_pos_n - 1 ), QPointF ( xr, tick_pos_n - 1 ), QPointF ( xr + 1, tick_pos_n ), QPointF ( xr + 1, tick_pos_n + 1 ), QPointF ( xr, tick_pos_n + 2 ), QPointF ( xl, tick_pos_n + 2 ), QPointF ( xl - 1, tick_pos_n + 1 ), QPointF ( xl - 1, tick_pos_n ), QPointF ( xl, tick_pos_n - 1 )}; pd.qpnt.drawPolygon ( points, num_pts ); } // Solid line { col.setAlpha ( 200 ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col ); pd.qpnt.drawRect ( tick_start, tick_pos_n, tick_width_n, 1.0 ); } } // Marker painting int DS_Slider_Painter_Bevelled::paint_marker ( ::dpe::Paint_Job * pjob_n, PData & pd ) { int res ( 0 ); //::std::cout << "DS_Slider_Painter_Bevelled::paint_marker\n"; switch ( pjob_n->img_idx ) { case 0: paint_marker_current ( pd ); break; case 1: paint_marker_hint ( pd ); break; default: res = -1; break; } return res; } void DS_Slider_Painter_Bevelled::paint_marker_current ( PData & pd ) { int bevel ( pd.width () / 3 ); bevel = qMax ( bevel, 2 ); { // Background const unsigned int num_pts ( 9 ); const double x0 ( 0.0 ); const double x1 ( bevel ); const double x2 ( pd.width () - bevel ); const double x3 ( pd.width () ); const double y0 ( 0.0 ); const double y1 ( bevel ); const double y2 ( pd.height () - bevel ); const double y3 ( pd.height () ); const QPointF points[ num_pts ] = {QPointF ( x0, y1 ), QPointF ( x1, y0 ), QPointF ( x2, y0 ), QPointF ( x3, y1 ), QPointF ( x3, y2 ), QPointF ( x2, y3 ), QPointF ( x1, y3 ), QPointF ( x0, y2 ), QPointF ( x0, y1 )}; { QColor col ( pd.pal.color ( QPalette::WindowText ) ); col.setAlpha ( 64 ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col ); } pd.qpnt.drawPolygon ( points, num_pts ); } { // Foreground const unsigned int num_pts ( 9 ); double delta ( pd.width () / 6.0 ); if ( delta < 1.0 ) { delta = 1.0; } double delta_sq ( delta * ( ::std::sqrt ( 2.0 ) - 1.0 ) ); const double x0 ( delta ); const double x1 ( bevel + delta_sq ); const double x2 ( pd.width () - x1 ); const double x3 ( pd.width () - x0 ); const double y0 ( delta ); const double y1 ( bevel + delta_sq ); const double y2 ( pd.height () - y1 ); const double y3 ( pd.height () - y0 ); const QPointF points[ num_pts ] = {QPointF ( x0, y1 ), QPointF ( x1, y0 ), QPointF ( x2, y0 ), QPointF ( x3, y1 ), QPointF ( x3, y2 ), QPointF ( x2, y3 ), QPointF ( x1, y3 ), QPointF ( x0, y2 ), QPointF ( x0, y1 )}; { const QColor & col ( pd.pal.color ( QPalette::WindowText ) ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col ); } pd.qpnt.drawPolygon ( points, num_pts ); } } void DS_Slider_Painter_Bevelled::paint_marker_hint ( PData & pd ) { int bevel ( pd.width () / 3 ); bevel = qMax ( bevel, 2 ); { const unsigned int num_pts ( 9 ); const double x0 ( 0.0 ); const double x1 ( bevel ); const double x2 ( pd.width () - bevel ); const double x3 ( pd.width () ); const double y0 ( 0.0 ); const double y1 ( bevel ); const double y2 ( pd.height () - bevel ); const double y3 ( pd.height () ); const QPointF points[ num_pts ] = { QPointF ( x0, y1 ), QPointF ( x1, y0 ), QPointF ( x2, y0 ), QPointF ( x3, y1 ), QPointF ( x3, y2 ), QPointF ( x2, y3 ), QPointF ( x1, y3 ), QPointF ( x0, y2 ), QPointF ( x0, y1 ), }; { QColor col ( pd.pal.color ( QPalette::WindowText ) ); col.setAlpha ( 100 ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col ); } pd.qpnt.drawPolygon ( points, num_pts ); } } // Frame painting int DS_Slider_Painter_Bevelled::paint_frame ( ::dpe::Paint_Job * pjob_n, PData & pd ) { //::std::cout << "DS_Slider_Painter_Bevelled::paint_frame " << pjob_n->img_idx //<< "\n"; // Calculate state flags { pd.has_focus = ( pjob_n->img_idx == 0 ); pd.has_weak_focus = ( pjob_n->img_idx == 1 ); } // Paint paint_frame_deco ( pd ); return 0; } void DS_Slider_Painter_Bevelled::paint_frame_deco ( PData & pd ) { const QColor col_norm ( pd.pal.color ( QPalette::Button ) ); const QColor col_text ( pd.pal.color ( QPalette::ButtonText ) ); const QColor col_text2 ( pd.pal.color ( QPalette::WindowText ) ); const QColor col_high ( pd.pal.color ( QPalette::Highlight ) ); { QColor col; if ( pd.has_weak_focus ) { col = col_high; } else { col = ::Wdg::col_mix ( col_text, col_text2, 2, 1 ); col = ::Wdg::col_mix ( col, col_norm, 3, 1 ); } int frw ( qMax ( 1, pd.bw - 2 * pd.ew ) ); double shrink ( pd.ew ); if ( frw < 2 ) { if ( !pd.has_weak_focus ) { if ( pd.bw > 2 ) { frw = qMin ( 2, pd.bw ); } else { // shrink = false; } } } // Fill pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col ); pd.qpnt.drawPath ( path_bevel_frame ( pd.rectf, pd.bevel, frw, shrink ) ); } } // Handle painting int DS_Slider_Painter_Bevelled::paint_handle ( ::dpe::Paint_Job * pjob_n, PData & pd ) { pd.bw = pd.width () / 24; pd.bw = qMax ( 2, pd.bw ); pd.ew = qMax ( 1, ( pd.bw / 4 ) ); { pd.has_focus = ( ( pjob_n->img_idx == 1 ) || ( pjob_n->img_idx == 3 ) ); pd.mouse_over = ( pjob_n->img_idx >= 2 ); pd.is_down = ( pjob_n->img_idx == 4 ); } // Painting { paint_handle_area ( pd ); paint_handle_frame ( pd ); paint_handle_items ( pd ); } return 0; } void DS_Slider_Painter_Bevelled::paint_handle_area ( PData & pd ) { const int iw ( pd.width () - 2 * pd.bw ); const int ih ( pd.height () - 2 * pd.bw ); QPainterPath area_path; papp_bevel_area ( area_path, pd.rectf, pd.bevel, pd.bw / 2.0 ); // Background { const double grw ( iw / 3.0 ); const double grwn ( grw / double ( iw ) ); QColor col_base ( pd.pal.color ( QPalette::Window ) ); if ( pd.pal.currentColorGroup () == QPalette::Disabled ) { QColor col_btn ( pd.pal.color ( QPalette::Button ) ); col_base = col_mix ( col_base, col_btn, 2, 1 ); } QColor col_edge ( col_base ); QColor col_center ( col_base ); col_edge.setAlpha ( 170 ); col_center.setAlpha ( 145 ); QLinearGradient lgrad ( QPointF ( pd.bw, 0.0 ), QPointF ( pd.width () - pd.bw, 0.0 ) ); lgrad.setColorAt ( 0.0, col_edge ); lgrad.setColorAt ( grwn, col_center ); lgrad.setColorAt ( 1.0 - grwn, col_center ); lgrad.setColorAt ( 1.0, col_edge ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( lgrad ); } pd.qpnt.drawPath ( area_path ); // Highlight { QColor col_edge ( pd.pal.color ( QPalette::Light ) ); QColor col_trans ( pd.pal.color ( QPalette::Light ) ); col_edge.setAlpha ( 128 ); col_trans.setAlpha ( 30 ); const double hl_dy ( ih / 8.0 ); const double y_top ( pd.bw ); const double y_bottom ( pd.height () - pd.bw ); QLinearGradient lgrad; if ( pd.is_down ) { lgrad.setStart ( 0.0, y_bottom - hl_dy ); lgrad.setFinalStop ( 0.0, y_top ); } else { lgrad.setStart ( 0.0, y_top + hl_dy ); lgrad.setFinalStop ( 0.0, y_bottom ); if ( pd.mouse_over ) { col_edge.setAlpha ( 150 ); } } // Adjust gradient pattern lgrad.setColorAt ( 0.0, col_edge ); lgrad.setColorAt ( 1.0, col_trans ); lgrad.setSpread ( QGradient::ReflectSpread ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( lgrad ); } pd.qpnt.drawPath ( area_path ); } void DS_Slider_Painter_Bevelled::paint_handle_frame ( PData & pd ) { QColor col; { // const QColor col_btn ( pd.pal.color ( QPalette::Button ) ); const QColor col_bg ( pd.pal.color ( QPalette::Window ) ); const QColor col_fg ( pd.pal.color ( QPalette::WindowText ) ); col = ::Wdg::col_mix ( col_bg, col_fg, 1, 1 ); } paint_bevel_raised_frame ( pd, pd.rectf, pd.bevel, pd.bw, pd.ew, col ); } void DS_Slider_Painter_Bevelled::paint_handle_items ( PData & pd ) { // Colors QColor col_bg ( pd.pal.color ( QPalette::Window ) ); QColor col_light ( pd.pal.color ( QPalette::Light ) ); col_light = ::Wdg::col_mix ( col_light, col_bg, 3, 2 ); QColor col_dark ( pd.pal.color ( QPalette::WindowText ) ); col_dark = ::Wdg::col_mix ( col_dark, col_bg, 5, 1 ); // Transforms const QTransform trans_hmirror ( -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, pd.width (), 0.0, 1.0 ); // Variables const double center_v ( pd.height () / 2.0 ); const double height_sub ( pd.bevel + pd.bw * ( sqrt ( 2.0 ) - 1.0 ) ); const double line_width_long ( 1.3333 ); // Width of the bright border const double line_width_small ( 1.25 ); // Width of the bright border const double line_width_fine ( 1.0 ); // Width of the bright border double tri_height_base; double tri_width; { const double in_w ( pd.width () - 2 * pd.bw ); const double in_h ( pd.height () - 2 * pd.bw ); const double tri_len_h ( in_w / 6.0f ); const double tri_len_v ( in_h / 6.0f ); const double tri_len ( qMin ( tri_len_v, tri_len_h ) ); tri_height_base = tri_len; tri_width = tri_len; tri_width += 1; } if ( pd.is_down ) { const double down_scale ( 3.0 / 4.0 ); tri_width *= down_scale; } // Round tri_width = ::std::floor ( tri_width + 0.5 ); // Install clipping region { QPainterPath area_path; papp_bevel_area ( area_path, pd.rectf, pd.bevel, pd.bw ); pd.qpnt.setClipPath ( area_path ); } { // Paint long piece QPainterPath ppath; { const double bb_w_loc ( line_width_long / 2.0 ); const double xoff ( pd.bw ); double pp_w ( tri_width - bb_w_loc ); double pp_h ( pd.height () / 2.0 - height_sub - bb_w_loc ); const QPointF ptop ( xoff, center_v - pp_h ); const QPointF pbot ( xoff, center_v + pp_h ); const QPointF pmid_top ( xoff + pp_w, center_v - 0.5 ); const QPointF pmid_bot ( xoff + pp_w, center_v + 0.5 ); const double sl_dk_x1 ( pp_w / 2.25 ); const double sl_dk_y1 ( pp_w / 2.5 ); const double sl_dk_y2 ( pp_h / 4.0 ); // Create path ppath.moveTo ( 0.0, ptop.y () ); ppath.lineTo ( ptop.x (), ptop.y () ); ppath.cubicTo ( QPointF ( ptop.x () + sl_dk_x1, ptop.y () + sl_dk_y1 ), QPointF ( pmid_top.x (), pmid_top.y () - sl_dk_y2 ), QPointF ( pmid_top.x (), pmid_top.y () ) ); ppath.lineTo ( pmid_bot.x (), pmid_bot.y () ); ppath.cubicTo ( QPointF ( pmid_bot.x (), pmid_bot.y () + sl_dk_y2 ), QPointF ( pbot.x () + sl_dk_x1, pbot.y () - sl_dk_y1 ), QPointF ( pbot.x (), pbot.y () ) ); ppath.lineTo ( 0.0, pbot.y () ); ppath.closeSubpath (); } { QPen pen; pen.setWidthF ( line_width_long ); pen.setColor ( col_light ); pd.qpnt.setPen ( pen ); } pd.qpnt.setBrush ( col_dark ); pd.qpnt.drawPath ( ppath ); ppath = trans_hmirror.map ( ppath ); pd.qpnt.drawPath ( ppath ); } { // Paint small triangle QPainterPath ppath; { double tri_height ( tri_height_base ); tri_height = std::floor ( tri_height ) + 0.5; const double xoff ( pd.bw ); const double pp_w ( tri_width ); const double pp_h ( tri_height ); // Create path ppath.moveTo ( 0, center_v - pp_h ); ppath.lineTo ( xoff, center_v - pp_h ); ppath.lineTo ( xoff, center_v - pp_h ); ppath.lineTo ( xoff + pp_w, center_v ); ppath.lineTo ( xoff, center_v + pp_h ); ppath.lineTo ( 0, center_v + pp_h ); ppath.closeSubpath (); } { QPen pen; pen.setWidthF ( line_width_small ); pen.setColor ( col_light ); pd.qpnt.setPen ( pen ); } pd.qpnt.setBrush ( col_dark ); pd.qpnt.drawPath ( ppath ); ppath = trans_hmirror.map ( ppath ); pd.qpnt.drawPath ( ppath ); } { // Center line const double xoff ( pd.bw + tri_width ); // Bright background pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_light ); pd.qpnt.drawRect ( xoff, center_v - 0.5 - line_width_fine, pd.width () - 2 * xoff, 1.0 + line_width_fine * 2 ); // Dark foreground pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_dark ); pd.qpnt.drawRect ( pd.bw, center_v - 0.5f, pd.width () - 2 * pd.bw, 1.0 ); } // Remove clipping region pd.qpnt.setClipping ( false ); } void DS_Slider_Painter_Bevelled::papp_bevel_area ( QPainterPath & ppath_n, const QRectF & area_n, double bevel_n, double indent_n ) { const double angle_tan ( ::std::tan ( 22.5 / 180.0 * M_PI ) ); double ds ( indent_n ); double db ( bevel_n + angle_tan * indent_n ); double xl[ 2 ] = {area_n.left (), area_n.left () + area_n.width ()}; double yl[ 2 ] = {area_n.top (), area_n.top () + area_n.height ()}; ppath_n.moveTo ( xl[ 0 ] + ds, yl[ 0 ] + db ), ppath_n.lineTo ( xl[ 0 ] + db, yl[ 0 ] + ds ), ppath_n.lineTo ( xl[ 1 ] - db, yl[ 0 ] + ds ), ppath_n.lineTo ( xl[ 1 ] - ds, yl[ 0 ] + db ), ppath_n.lineTo ( xl[ 1 ] - ds, yl[ 1 ] - db ), ppath_n.lineTo ( xl[ 1 ] - db, yl[ 1 ] - ds ), ppath_n.lineTo ( xl[ 0 ] + db, yl[ 1 ] - ds ), ppath_n.lineTo ( xl[ 0 ] + ds, yl[ 1 ] - db ), ppath_n.closeSubpath (); } void DS_Slider_Painter_Bevelled::paint_bevel_raised_frame ( PData & pd, const QRectF & area_n, double bevel_n, double frame_width_n, double edge_width_n, const QColor & col_n ) { QColor col_light ( pd.pal.color ( QPalette::Light ) ); QColor col_shadow ( pd.pal.color ( QPalette::Shadow ) ); QColor col_mid ( col_n ); QColor col_br ( ::Wdg::col_mix ( col_n, col_light, 5, 4 ) ); QColor col_dk ( ::Wdg::col_mix ( col_n, col_shadow, 5, 4 ) ); const double shrink_out ( 0.0 ); const double shrink_in ( frame_width_n - edge_width_n ); // Bright area { QPainterPath pp; papp_bevel_frame_edge ( pp, area_n, 3, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_corner ( pp, area_n, 0, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_edge ( pp, area_n, 0, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_edge ( pp, area_n, 1, bevel_n, edge_width_n, shrink_in ); papp_bevel_frame_corner ( pp, area_n, 2, bevel_n, edge_width_n, shrink_in ); papp_bevel_frame_edge ( pp, area_n, 2, bevel_n, edge_width_n, shrink_in ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_br ); pd.qpnt.drawPath ( pp ); } // Mid area { QPainterPath pp; papp_bevel_frame_corner ( pp, area_n, 1, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_corner ( pp, area_n, 1, bevel_n, edge_width_n, shrink_in ); papp_bevel_frame_corner ( pp, area_n, 3, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_corner ( pp, area_n, 3, bevel_n, edge_width_n, shrink_in ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_mid ); pd.qpnt.drawPath ( pp ); } // Dark area { QPainterPath pp; papp_bevel_frame_edge ( pp, area_n, 3, bevel_n, edge_width_n, shrink_in ); papp_bevel_frame_corner ( pp, area_n, 0, bevel_n, edge_width_n, shrink_in ); papp_bevel_frame_edge ( pp, area_n, 0, bevel_n, edge_width_n, shrink_in ); papp_bevel_frame_edge ( pp, area_n, 1, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_corner ( pp, area_n, 2, bevel_n, edge_width_n, shrink_out ); papp_bevel_frame_edge ( pp, area_n, 2, bevel_n, edge_width_n, shrink_out ); pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_dk ); pd.qpnt.drawPath ( pp ); } // Frame center line area const double mid_width ( frame_width_n - 2.0 * edge_width_n ); if ( mid_width > 0.0 ) { pd.qpnt.setPen ( Qt::NoPen ); pd.qpnt.setBrush ( col_mid ); pd.qpnt.drawPath ( path_bevel_frame ( area_n, bevel_n, mid_width, edge_width_n ) ); } } QPainterPath DS_Slider_Painter_Bevelled::path_bevel_frame ( const QRectF & area_n, double bevel_n, double frame_width_n, double indent_n ) { QPainterPath ppath; papp_bevel_area ( ppath, area_n, bevel_n, indent_n ); papp_bevel_area ( ppath, area_n, bevel_n, indent_n + frame_width_n ); return ppath; } void DS_Slider_Painter_Bevelled::papp_bevel_frame_corner ( QPainterPath & ppath_n, const QRectF & area_n, unsigned int edge_n, double bevel_n, double width_n, double indent_n ) { double xx[ 4 ]; double yy[ 4 ]; { const double angle_tan ( ::std::tan ( 22.5 / 180.0 * M_PI ) ); double ds1 ( indent_n ); double db1 ( bevel_n + angle_tan * ds1 ); double ds2 ( indent_n + width_n ); double db2 ( bevel_n + angle_tan * ds2 ); xx[ 0 ] = ds1; xx[ 1 ] = db1; xx[ 2 ] = db2; xx[ 3 ] = ds2; yy[ 0 ] = db1; yy[ 1 ] = ds1; yy[ 2 ] = ds2; yy[ 3 ] = db2; } { double x_off ( area_n.left () ); double y_off ( area_n.top () ); double x_scale ( 1.0 ); double y_scale ( 1.0 ); if ( edge_n == 0 ) { // pass } else if ( edge_n == 1 ) { x_off += area_n.width (); x_scale = -1; } else if ( edge_n == 2 ) { x_off += area_n.width (); y_off += area_n.height (); x_scale = -1; y_scale = -1; } else { y_off += area_n.height (); y_scale = -1; } for ( unsigned int ii = 0; ii < 4; ++ii ) { xx[ ii ] *= x_scale; } for ( unsigned int ii = 0; ii < 4; ++ii ) { yy[ ii ] *= y_scale; } for ( unsigned int ii = 0; ii < 4; ++ii ) { xx[ ii ] += x_off; } for ( unsigned int ii = 0; ii < 4; ++ii ) { yy[ ii ] += y_off; } } ppath_n.moveTo ( xx[ 0 ], yy[ 0 ] ); ppath_n.lineTo ( xx[ 1 ], yy[ 1 ] ); ppath_n.lineTo ( xx[ 2 ], yy[ 2 ] ); ppath_n.lineTo ( xx[ 3 ], yy[ 3 ] ); ppath_n.closeSubpath (); } void DS_Slider_Painter_Bevelled::papp_bevel_frame_edge ( QPainterPath & ppath_n, const QRectF & area_n, unsigned int edge_n, double bevel_n, double width_n, double indent_n ) { double xx[ 4 ]; double yy[ 4 ]; { const double angle_tan ( ::std::tan ( 22.5 / 180.0 * M_PI ) ); double ds1 ( indent_n ); double db1 ( bevel_n + angle_tan * ds1 ); double ds2 ( indent_n + width_n ); double db2 ( bevel_n + angle_tan * ds2 ); if ( ( edge_n % 2 ) == 0 ) { // top / bottom xx[ 0 ] = area_n.left () + db1; xx[ 1 ] = area_n.left () + area_n.width () - db1; xx[ 2 ] = area_n.left () + area_n.width () - db2; xx[ 3 ] = area_n.left () + db2; yy[ 0 ] = ds1; yy[ 1 ] = ds1; yy[ 2 ] = ds2; yy[ 3 ] = ds2; } else { // left / right xx[ 0 ] = ds1; xx[ 1 ] = ds1; xx[ 2 ] = ds2; xx[ 3 ] = ds2; yy[ 0 ] = area_n.top () + area_n.height () - db1; yy[ 1 ] = area_n.top () + db1; yy[ 2 ] = area_n.top () + db2; yy[ 3 ] = area_n.top () + area_n.height () - db2; } } // Flip sides if ( edge_n == 1 ) { // flip left to right for ( unsigned int ii = 0; ii < 4; ++ii ) { xx[ ii ] *= -1; } const double x_off ( area_n.left () + area_n.width () ); for ( unsigned int ii = 0; ii < 4; ++ii ) { xx[ ii ] += x_off; } } else if ( edge_n == 2 ) { // flip top to bottom for ( unsigned int ii = 0; ii < 4; ++ii ) { yy[ ii ] *= -1; } const double y_off ( area_n.top () + area_n.height () ); for ( unsigned int ii = 0; ii < 4; ++ii ) { yy[ ii ] += y_off; } } ppath_n.moveTo ( xx[ 0 ], yy[ 0 ] ); ppath_n.lineTo ( xx[ 1 ], yy[ 1 ] ); ppath_n.lineTo ( xx[ 2 ], yy[ 2 ] ); ppath_n.lineTo ( xx[ 3 ], yy[ 3 ] ); ppath_n.closeSubpath (); } } // namespace Painter } // namespace Wdg
27.753562
80
0.539807
amazingidiot
efa2b3b8f5cff514aa7914aef5da94f8f26c10e4
887
cpp
C++
17A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
17A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
17A.cpp
felikjunvianto/kfile-codeforces-submissions
1b53da27a294a12063b0912e12ad32efe24af678
[ "MIT" ]
null
null
null
#include <cstdio> #include <cmath> #include <iostream> #include <string> #include <cstring> #include <algorithm> #include <vector> #include <utility> #include <stack> #include <queue> #include <map> #define fi first #define se second #define pb push_back #define mp make_pair #define pi 2*acos(0.0) #define eps 1e-9 #define PII pair<int,int> #define PDD pair<double,double> #define LL long long #define INF 1000000000 using namespace std; bool prime[2000]; vector<int> bil; int N,K,x,y,z; int main() { memset(prime,true,sizeof(prime)); for(x=2;x*x<=2000;x++) if(prime[x]) { z=2; while(x*z<=2000) { prime[x*z]=false; z++; } } for(x=2;x<=2000;x++) if(prime[x]) bil.pb(x); scanf("%d %d",&N,&K); for(x=1;bil[x]+bil[x-1]+1<=N;x++) if(prime[bil[x]+bil[x-1]+1]) K--; printf("%s\n",K>0?"NO":"YES"); return 0; }
17.392157
69
0.598647
felikjunvianto
efa35a29214e795495f41465f977d9c2a4a96f50
753
cpp
C++
tests/AllegroFlare/ProfilerTest.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
25
2015-03-30T02:02:43.000Z
2019-03-04T22:29:12.000Z
tests/AllegroFlare/ProfilerTest.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
122
2015-04-01T08:15:26.000Z
2019-10-16T20:31:22.000Z
tests/AllegroFlare/ProfilerTest.cpp
MarkOates/allegro_flare
b454cb85eb5e43d19c23c0c6fd2dc11b96666ce7
[ "MIT" ]
4
2016-09-02T12:14:09.000Z
2018-11-23T20:38:49.000Z
#include <gtest/gtest.h> #include <AllegroFlare/Profiler.hpp> // for usleep on Windows #include <unistd.h> TEST(AllegroFlare_ProfilerTest, can_be_created_without_blowing_up) { AllegroFlare::Profiler profiler; } TEST(AllegroFlare_ProfilerTest, DISABLED__emit__will_add_an_event_time_to_that_event_bucket) // TODO this test crashes on Windows { std::string EVENT_IDENTIFIER = "my_custom_event"; AllegroFlare::Profiler profiler; for (unsigned i=0; i<10; i++) { profiler.emit(EVENT_IDENTIFIER); usleep(10000); } ASSERT_EQ(1, profiler.get_event_buckets().size()); ASSERT_EQ(10, profiler.get_event_samples(EVENT_IDENTIFIER, 10).size()); ASSERT_EQ(6, profiler.get_event_samples(EVENT_IDENTIFIER, 6).size()); }
24.290323
92
0.747676
MarkOates
efa40c24df2b0e4cf499973838a4d0f28f180fc5
61,356
cpp
C++
third_party/omr/compiler/runtime/OMRCodeCache.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/compiler/runtime/OMRCodeCache.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
third_party/omr/compiler/runtime/OMRCodeCache.cpp
xiacijie/omr-wala-linkage
a1aff7aef9ed131a45555451abde4615a04412c1
[ "Apache-2.0" ]
null
null
null
/******************************************************************************* * Copyright (c) 2000, 2019 IBM Corp. and others * * This program and the accompanying materials are made available under * the terms of the Eclipse Public License 2.0 which accompanies this * distribution and is available at http://eclipse.org/legal/epl-2.0 * or the Apache License, Version 2.0 which accompanies this distribution * and is available at https://www.apache.org/licenses/LICENSE-2.0. * * This Source Code may also be made available under the following Secondary * Licenses when the conditions for such availability set forth in the * Eclipse Public License, v. 2.0 are satisfied: GNU General Public License, * version 2 with the GNU Classpath Exception [1] and GNU General Public * License, version 2 with the OpenJDK Assembly Exception [2]. * * [1] https://www.gnu.org/software/classpath/license.html * [2] http://openjdk.java.net/legal/assembly-exception.html * * SPDX-License-Identifier: EPL-2.0 OR Apache-2.0 OR GPL-2.0 WITH Classpath-exception-2.0 OR LicenseRef-GPL-2.0 WITH Assembly-exception *******************************************************************************/ #include "runtime/OMRCodeCache.hpp" #include <algorithm> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <string.h> #include "codegen/FrontEnd.hpp" #include "control/Options.hpp" #include "control/Options_inlines.hpp" #include "env/CompilerEnv.hpp" #include "env/IO.hpp" #include "env/defines.h" #include "env/jittypes.h" #include "il/DataTypes.hpp" #include "infra/Assert.hpp" #include "infra/CriticalSection.hpp" #include "infra/Monitor.hpp" #include "omrformatconsts.h" #include "runtime/CodeCache.hpp" #include "runtime/CodeCacheManager.hpp" #include "runtime/CodeCacheMemorySegment.hpp" #include "runtime/CodeCacheConfig.hpp" #include "runtime/Runtime.hpp" #ifdef LINUX #include <elf.h> #include <unistd.h> #endif namespace TR { class CodeGenerator; } /***************************************************************************** * Multi Code Cache page management */ /** * \page CodeCache Code Cache Layout: * * Basic layout of the code cache memory (capitalized names are fixed, others * move) * * * TRAMPOLINEBASE TEMPTRAMPOLINETOP * | TEMPTRAMPOLINEBASE | * | | | * warmCodeAlloc coldCodeAlloc | | HELPERBASE HELPERTOP * |--> <--| | | | | * |_____v_________________v______v_______________v___________v_________v * warm cold * \ / * ----> Method Bodies<--- ^ Trampolines ^ TempTramps^ Helpers * * (Low memory) ---------------------------------------> (High memory) * * * * There are a fixed number of helper trampolines. Each helper has an index into * these trampolines. * * There are a fixed number of temporary trampoline slots. `_tempTrampolineNext` * goes from `_tempTrampolineBase`, allocating to `tempTrampolineMax.` * * There are a fixed number of permanent trampoline slots. * ** `_trampolineReservationMark` goes from `_tempTrampolineBase` to `_trampolineBase` * backwards, reserving trampoline slots. * ** `_trampolineAllocationMark` goes from `_tempTrampolineBase` to * `_trampolineReservationMark` filling in the trampoline slots. * * When there is no more room for trampolines the code cache is full. * * 5% of the code cache is allocated to the above trampolines. The rest is used * for method bodies. Regular parts of method bodies are allocated from the * heapBase forwards, and cold parts of method bodies are allocated from * `_trampolineBase` backwards. When the two meet, the code cache is full. * */ OMR::CodeCache::CacheCriticalSection::CacheCriticalSection(TR::CodeCache *codeCache) : CriticalSection(codeCache->_mutex) { } TR::CodeCache * OMR::CodeCache::self() { return static_cast<TR::CodeCache *>(this); } void OMR::CodeCache::destroy(TR::CodeCacheManager *manager) { while (_hashEntrySlab) { CodeCacheHashEntrySlab *slab = _hashEntrySlab; _hashEntrySlab = slab->_next; slab->free(manager); } #if defined(TR_HOST_POWER) if (_trampolineSyncList) { if (_trampolineSyncList->_hashEntryArray) manager->freeMemory(_trampolineSyncList->_hashEntryArray); manager->freeMemory(_trampolineSyncList); } #endif if (manager->codeCacheConfig().needsMethodTrampolines()) { if (_resolvedMethodHT) { if (_resolvedMethodHT->_buckets) manager->freeMemory(_resolvedMethodHT->_buckets); manager->freeMemory(_resolvedMethodHT); } if (_unresolvedMethodHT) { if (_unresolvedMethodHT->_buckets) manager->freeMemory(_unresolvedMethodHT->_buckets); manager->freeMemory(_unresolvedMethodHT); } } } uint8_t * OMR::CodeCache::getCodeAlloc() { return _segment->segmentAlloc(); } uint8_t * OMR::CodeCache::getCodeBase() { return _segment->segmentBase(); } uint8_t * OMR::CodeCache::getCodeTop() { return _segment->segmentTop(); } void OMR::CodeCache::reserve(int32_t reservingCompThreadID) { _reserved = true; _reservingCompThreadID = reservingCompThreadID; } void OMR::CodeCache::unreserve() { _reserved = false; _reservingCompThreadID = -2; } void OMR::CodeCache::writeMethodHeader(void *freeBlock, size_t size, bool isCold) { CodeCacheMethodHeader * block = (CodeCacheMethodHeader *)freeBlock; block->_size = size; TR::CodeCacheConfig & config = _manager->codeCacheConfig(); if (!isCold) memcpy(block->_eyeCatcher, config.warmEyeCatcher(), sizeof(block->_eyeCatcher)); else memcpy(block->_eyeCatcher, config.coldEyeCatcher(), sizeof(block->_eyeCatcher)); block->_metaData = NULL; } bool OMR::CodeCache::trimCodeMemoryAllocation(void *codeMemoryStart, size_t actualSizeInBytes) { if (actualSizeInBytes == 0) return false; // nothing to resize, just return TR::CodeCacheConfig & config = _manager->codeCacheConfig(); size_t round = config.codeCacheAlignment() - 1; codeMemoryStart = (uint8_t *) codeMemoryStart - sizeof(CodeCacheMethodHeader); // Do we always have a header? actualSizeInBytes = (actualSizeInBytes + sizeof(CodeCacheMethodHeader) + round) & ~round; CodeCacheMethodHeader *cacheHeader = (CodeCacheMethodHeader *) codeMemoryStart; // sanity check, the eyecatcher must be there TR_ASSERT(cacheHeader->_eyeCatcher[0] == config.warmEyeCatcher()[0], "Missing eyecatcher during trimCodeMemoryAllocation"); size_t oldSize = cacheHeader->_size; if (actualSizeInBytes >= oldSize) return false; size_t shrinkage = oldSize - actualSizeInBytes; uint8_t *expectedHeapAlloc = (uint8_t *) codeMemoryStart + oldSize; if (config.verboseReclamation()) { TR_VerboseLog::writeLineLocked(TR_Vlog_CODECACHE,"--trimCodeMemoryAllocation-- CC=%p cacheHeader=%p oldSize=%u actualSizeInBytes=%d shrinkage=%u", this, cacheHeader, oldSize, actualSizeInBytes, shrinkage); } if (expectedHeapAlloc == _warmCodeAlloc) { _manager->increaseFreeSpaceInCodeCacheRepository(shrinkage); _warmCodeAlloc -= shrinkage; cacheHeader->_size = actualSizeInBytes; return true; } else // the allocation could have been from a free block or from the cold portion { if (shrinkage >= MIN_SIZE_BLOCK) { // addFreeBlock needs to be done with VM access because the GC may also // change the list of free blocks if (self()->addFreeBlock2((uint8_t *) codeMemoryStart+actualSizeInBytes, (uint8_t *)expectedHeapAlloc)) { //fprintf(stderr, "---ccr--- addFreeBlock due to shrinkage\n"); } cacheHeader->_size = actualSizeInBytes; return true; } } //fprintf(stderr, "--ccr-- shrink code by %d\n", shrinkage); return false; } // Initialize a code cache // bool OMR::CodeCache::initialize(TR::CodeCacheManager *manager, TR::CodeCacheMemorySegment *codeCacheSegment, size_t allocatedCodeCacheSizeInBytes) { _manager = manager; // heapSize can be calculated as (codeCache->helperTop - codeCacheSegment->heapBase), which is equal to segmentSize // If codeCachePadKB is set, this will make the system believe that we allocated segmentSize bytes, // instead of _jitConfig->codeCachePadKB * 1024 bytes // If codeCachePadKB is not set, heapSize is segmentSize anyway _segment = codeCacheSegment; // helperTop is heapTop, usually // When codeCachePadKB > segmentSize, the helperTop is not at the very end of the segemnt _helperTop = _segment->segmentBase() + allocatedCodeCacheSizeInBytes; TR::CodeCacheConfig &config = manager->codeCacheConfig(); // Allocate the CodeCacheHashEntrySlab object and the initial slab // _hashEntrySlab = CodeCacheHashEntrySlab::allocate(manager, config.codeCacheHashEntryAllocatorSlabSize()); if (!_hashEntrySlab) { return false; } // FIXME: try to provide different names to the mutex based on the codecache if (!(_mutex = TR::Monitor::create("JIT-CodeCacheMonitor-??"))) { _hashEntrySlab->free(manager); return false; } _hashEntryFreeList = NULL; _freeBlockList = NULL; _flags = 0; _CCPreLoadedCodeInitialized = false; self()->unreserve(); _almostFull = TR_no; _sizeOfLargestFreeColdBlock = 0; _sizeOfLargestFreeWarmBlock = 0; _lastAllocatedBlock = NULL; // MP *((TR::CodeCache **)(_segment->segmentBase())) = self(); // Write a pointer to this cache at the beginning of the segment _warmCodeAlloc = _segment->segmentBase() + sizeof(this); _warmCodeAlloc = align(_warmCodeAlloc, config.codeCacheAlignment() - 1); if (!config.trampolineCodeSize()) { // _helperTop is heapTop _trampolineBase = _helperTop; _helperBase = _helperTop; _trampolineReservationMark = _trampolineAllocationMark = _trampolineBase; // set the pre loaded per Cache Helper slab _CCPreLoadedCodeTop = (uint8_t *)(((size_t)_trampolineBase) & (~config.codeCacheHelperAlignmentMask())); _CCPreLoadedCodeBase = _CCPreLoadedCodeTop - config.ccPreLoadedCodeSize(); TR_ASSERT( (((size_t)_CCPreLoadedCodeBase) & config.codeCacheHelperAlignmentMask()) == 0, "Per-code cache helper sizes do not account for alignment requirements." ); _coldCodeAlloc = _CCPreLoadedCodeBase; _trampolineSyncList = NULL; return true; } // Helpers are located at the top of the code cache (offset N), growing down towards the base (offset 0) size_t trampolineSpaceSize = config.trampolineCodeSize() * config.numRuntimeHelpers(); // _helperTop is heapTop _helperBase = _helperTop - trampolineSpaceSize; _helperBase = (uint8_t *)(((size_t)_helperBase) & (~config.codeCacheTrampolineAlignmentBytes())); if (!config.needsMethodTrampolines()) { // There is no need in method trampolines when there is going to be // only one code cache segment // _trampolineBase = _helperBase; _tempTrampolinesMax = 0; } else { // _helperTop is heapTop // (_helperTop - segment->heapBase) is heapSize _trampolineBase = _helperBase - ((_helperBase - _segment->segmentBase())*config.trampolineSpacePercentage()/100); // Grab the configuration details from the JIT platform code // // (_helperTop - segment->heapBase) is heapSize config.mccCallbacks().codeCacheConfig((_helperTop - _segment->segmentBase()), &_tempTrampolinesMax); } mcc_printf("mcc_initialize: trampoline base %p\n", _trampolineBase); // set the temporary trampoline slab right under the helper trampolines, should be already aligned _tempTrampolineTop = _helperBase; _tempTrampolineBase = _tempTrampolineTop - (config.trampolineCodeSize() * _tempTrampolinesMax); _tempTrampolineNext = _tempTrampolineBase; // Check if we have enough space in the code cache to contain the trampolines if (_trampolineBase >= _tempTrampolineNext && config.needsMethodTrampolines()) { _hashEntrySlab->free(manager); return false; } // set the allocation pointer to right after the temporary trampolines _trampolineAllocationMark = _tempTrampolineBase; _trampolineReservationMark = _trampolineAllocationMark; // set the pre loaded per Cache Helper slab _CCPreLoadedCodeTop = (uint8_t *)(((size_t)_trampolineBase) & (~config.codeCacheHelperAlignmentMask())); _CCPreLoadedCodeBase = _CCPreLoadedCodeTop - config.ccPreLoadedCodeSize(); TR_ASSERT( (((size_t)_CCPreLoadedCodeBase) & config.codeCacheHelperAlignmentMask()) == 0, "Per-code cache helper sizes do not account for alignment requirements." ); _coldCodeAlloc = _CCPreLoadedCodeBase; // Set helper trampoline table available // config.mccCallbacks().createHelperTrampolines((uint8_t *)_helperBase, config.numRuntimeHelpers()); _trampolineSyncList = NULL; if (_tempTrampolinesMax) { // Initialize temporary trampoline synchronization list if (!self()->allocateTempTrampolineSyncBlock()) { _hashEntrySlab->free(manager); return false; } } if (config.needsMethodTrampolines()) { // Initialize hashtables to hold trampolines for resolved and unresolved methods _resolvedMethodHT = CodeCacheHashTable::allocate(manager); _unresolvedMethodHT = CodeCacheHashTable::allocate(manager); if (_resolvedMethodHT==NULL || _unresolvedMethodHT==NULL) { _hashEntrySlab->free(manager); return false; } } // Before returning, let's adjust the free space seen by VM. // Usable space is between _warmCodeAlloc and _trampolineBase. Everything else is overhead // Only relevant if code cache repository is used size_t spaceLost = (_warmCodeAlloc - _segment->segmentBase()) + (_segment->segmentTop() - _trampolineBase); _manager->decreaseFreeSpaceInCodeCacheRepository(spaceLost); return true; } /***************************************************************************** * Trampoline Reservation */ // Allocate a trampoline in given code cache // // An allocation MUST be preceeded by at least one reservation. If we get a case // where we dont have reserved space, abort // OMR::CodeCacheTrampolineCode * OMR::CodeCache::allocateTrampoline() { CodeCacheTrampolineCode *trampoline = NULL; if (_trampolineAllocationMark > _trampolineReservationMark) { TR::CodeCacheConfig &config = _manager->codeCacheConfig(); _trampolineAllocationMark -= config.trampolineCodeSize(); trampoline = (CodeCacheTrampolineCode *) _trampolineAllocationMark; } else { //TR_ASSERT(0); } return trampoline; } // Allocate a temporary trampoline // OMR::CodeCacheTrampolineCode * OMR::CodeCache::allocateTempTrampoline() { CodeCacheTrampolineCode *freeTrampolineSlot; if (_tempTrampolineNext >= _tempTrampolineTop) return NULL; freeTrampolineSlot = _tempTrampolineNext; TR::CodeCacheConfig &config = _manager->codeCacheConfig(); _tempTrampolineNext += config.trampolineCodeSize(); return freeTrampolineSlot; } OMR::CodeCacheErrorCode::ErrorCode OMR::CodeCache::reserveSpaceForTrampoline_bridge(int32_t numTrampolines) { return self()->reserveSpaceForTrampoline(numTrampolines); } OMR::CodeCacheErrorCode::ErrorCode OMR::CodeCache::reserveSpaceForTrampoline(int32_t numTrampolines) { CacheCriticalSection ReserveSpaceForTrampoline(self()); CodeCacheErrorCode::ErrorCode status = CodeCacheErrorCode::ERRORCODE_SUCCESS; TR::CodeCacheConfig &config = _manager->codeCacheConfig(); size_t size = numTrampolines * config.trampolineCodeSize(); if (size) { // See if we are hitting against the method body allocation pointer // indicating that there is no more free space left in this code cache // if (_trampolineReservationMark >= _trampolineBase + size) { _trampolineReservationMark -= size; } else { status = CodeCacheErrorCode::ERRORCODE_INSUFFICIENTSPACE; _almostFull = TR_yes; if (config.verboseCodeCache()) { TR_VerboseLog::writeLineLocked(TR_Vlog_CODECACHE, "CodeCache %p marked as full in reserveSpaceForTrampoline", self()); } } } return status; } void OMR::CodeCache::unreserveSpaceForTrampoline() { // sanity check, should never have the reservation mark dip past the // allocation mark //TR_ASSERT(_trampolineReservationMark < _trampolineAllocationMark); TR::CodeCacheConfig &config = _manager->codeCacheConfig(); _trampolineReservationMark += config.trampolineCodeSize(); } //------------------------------ reserveResolvedTrampoline ------------------ // Find or create a reservation for an resolved method trampoline. // Method must be called with VM access in hand to prevent unloading // Returns 0 on success or a negative error code on failure //--------------------------------------------------------------------------- int32_t OMR::CodeCache::reserveResolvedTrampoline(TR_OpaqueMethodBlock *method, bool inBinaryEncoding) { int32_t retValue = CodeCacheErrorCode::ERRORCODE_SUCCESS; // assume success TR_ASSERT(_reserved, "CodeCache %p is not reserved when calling reservedResolvedTrampoline\n", this); // does the platform need trampolines at all? TR::CodeCacheConfig &config = _manager->codeCacheConfig(); if (!config.needsMethodTrampolines()) return retValue; // scope for cache critical section { CacheCriticalSection reserveTrampoline(self()); // see if a reservation for this method already exists, return corresponding // code cache if thats the case CodeCacheHashEntry *entry = _resolvedMethodHT->findResolvedMethod(method); if (!entry) { // Reserve a new trampoline since there is not an active reservation for given method // retValue = self()->reserveSpaceForTrampoline(); if (retValue == OMR::CodeCacheErrorCode::ERRORCODE_SUCCESS) { // add hashtable entry if (!self()->addResolvedMethod(method)) retValue = CodeCacheErrorCode::ERRORCODE_FATALERROR; // couldn't allocate memory from VM } } } return retValue; } // Trampoline lookup for resolved methods // OMR::CodeCacheTrampolineCode * OMR::CodeCache::findTrampoline(TR_OpaqueMethodBlock * method) { CodeCacheTrampolineCode *trampoline; // scope for critical section { CacheCriticalSection resolveAndCreateTrampoline(self()); CodeCacheHashEntry *entry = _resolvedMethodHT->findResolvedMethod(method); trampoline = entry->_info._resolved._currentTrampoline; if (!trampoline) { void *newPC = (void *) TR::Compiler->mtd.startPC(method); trampoline = self()->allocateTrampoline(); self()->createTrampoline(trampoline, newPC, method); entry->_info._resolved._currentTrampoline = trampoline; entry->_info._resolved._currentStartPC = newPC; } } return trampoline; } // Trampoline lookup for helper methods // OMR::CodeCacheTrampolineCode * OMR::CodeCache::findTrampoline(int32_t helperIndex) { CodeCacheTrampolineCode *trampoline; TR::CodeCacheConfig &config = _manager->codeCacheConfig(); trampoline = (CodeCacheTrampolineCode *) (_helperBase + (config.trampolineCodeSize() * helperIndex)); //TR_ASSERT(trampoline < _helperTop); return trampoline; } // Replace a trampoline // OMR::CodeCacheTrampolineCode * OMR::CodeCache::replaceTrampoline(TR_OpaqueMethodBlock *method, void *oldTrampoline, void *oldTargetPC, void *newTargetPC, bool needSync) { CodeCacheTrampolineCode *trampoline = oldTrampoline; CodeCacheHashEntry *entry; entry = _resolvedMethodHT->findResolvedMethod(method); //suspicious that this assertion is commented out... //TR_ASSERT(entry); if (oldTrampoline == NULL) { // A trampoline has not been created. Simply allocate a new one. // trampoline = self()->allocateTrampoline(); entry->_info._resolved._currentTrampoline = trampoline; } else { if (needSync) { // Trampoline CANNOT be safely modified in place // We have to allocate a new temporary trampoline // and rely on the sync later on to update the old one using the // temporary data // // A permanent trampoline already exists, create a temporary one, // This might fail due to lack of free slots // trampoline = self()->allocateTempTrampoline(); // Save the temporary trampoline entry for future temp->parm synchronization self()->saveTempTrampoline(entry); if (!trampoline) { // Unable to fulfill the replacement request, no temp space left return NULL; } } } // update the hash entry for this method entry->_info._resolved._currentStartPC = newTargetPC; return trampoline; } // Synchronize all temporary trampolines in given code cache // void OMR::CodeCache::syncTempTrampolines() { if (_flags & CODECACHE_FULL_SYNC_REQUIRED) { for (uint32_t entryIdx = 0; entryIdx < _resolvedMethodHT->_size; entryIdx++) { for (CodeCacheHashEntry *entry = _resolvedMethodHT->_buckets[entryIdx]; entry; entry = entry->_next) { void *newPC = (void *) TR::Compiler->mtd.startPC(entry->_info._resolved._method); void *trampoline = entry->_info._resolved._currentTrampoline; if (trampoline && entry->_info._resolved._currentStartPC != newPC) { self()->createTrampoline(trampoline, newPC, entry->_info._resolved._method); entry->_info._resolved._currentStartPC = newPC; } } } for (CodeCacheTempTrampolineSyncBlock *syncBlock = _trampolineSyncList; syncBlock; syncBlock = syncBlock->_next) syncBlock->_entryCount = 0; _flags &= ~CODECACHE_FULL_SYNC_REQUIRED; } else { CodeCacheTempTrampolineSyncBlock *syncBlock = NULL; // Traverse the list of trampoline synchronization blocks for (syncBlock = _trampolineSyncList; syncBlock; syncBlock = syncBlock->_next) { //TR_ASSERT(syncBlock->_entryCount <= syncBlock->_entryListSize); // Synchronize all stored sync requests for (uint32_t entryIdx = 0; entryIdx < syncBlock->_entryCount; entryIdx++) { CodeCacheHashEntry *entry = syncBlock->_hashEntryArray[entryIdx]; void *newPC = (void *) TR::Compiler->mtd.startPC(entry->_info._resolved._method); // call the codegen to perform the trampoline code modification self()->createTrampoline(entry->_info._resolved._currentTrampoline, newPC, entry->_info._resolved._method); entry->_info._resolved._currentStartPC = newPC; } syncBlock->_entryCount = 0; } } _tempTrampolineNext = _tempTrampolineBase; } // Patch the address of a method in this code cache's trampolines // void OMR::CodeCache::patchCallPoint(TR_OpaqueMethodBlock *method, void *callSite, void *newStartPC, void *extraArg) { TR::CodeCacheConfig &config = _manager->codeCacheConfig(); // the name is still the same. The logic of callPointPatching is as follow: // look up the right codeCache, // search for the hashEntry for the method, // grab its current trampoline plus its current pointed-at address (if no trampoline, both are NULL). // Then, call code_patching with these things as argument. // scope to patch trampoline { CacheCriticalSection patching(self()); CodeCacheTrampolineCode *resolvedTramp = NULL; void *methodRunAddress = NULL; if (config.needsMethodTrampolines()) { CodeCacheHashEntry *entry = _resolvedMethodHT->findResolvedMethod(method); if (entry) { resolvedTramp = entry->_info._resolved._currentTrampoline; if (resolvedTramp) methodRunAddress = entry->_info._resolved._currentStartPC; } } else if (TR::Options::getCmdLineOptions()->getOption(TR_UseGlueIfMethodTrampolinesAreNotNeeded)) { // Safety measure, return to the old behaviour of always going through the glue return; } if (TR::Options::getCmdLineOptions()->getVerboseOption(TR_VerbosePatching)) { TR_VerboseLog::writeLineLocked(TR_Vlog_PATCH, "Patching callsite=0x%p using j9method=0x%p,resolvedTramp=0x%p,methodRunAddress=0x%p,newStartPC=0x%p,extraArg=0x%p", callSite, method, resolvedTramp, methodRunAddress, newStartPC, extraArg); } // Patch the code for a method trampoline int32_t rc = _manager->codeCacheConfig().mccCallbacks().patchTrampoline(method, callSite, methodRunAddress, resolvedTramp, newStartPC, extraArg); } } // Create code for a method trampoline at indicated address // // Calls platform dependent code to create a trampoline code snippet at the // specified address and initialize it to jump to targetStartPC. // void OMR::CodeCache::createTrampoline(CodeCacheTrampolineCode *trampoline, void *targetStartPC, TR_OpaqueMethodBlock *method) { TR::CodeCacheConfig &config = _manager->codeCacheConfig(); config.mccCallbacks().createMethodTrampoline(trampoline, targetStartPC, method); } bool OMR::CodeCache::saveTempTrampoline(CodeCacheHashEntry *entry) { CodeCacheTempTrampolineSyncBlock *freeSyncBlock = NULL; CodeCacheTempTrampolineSyncBlock *syncBlock; for (syncBlock = _trampolineSyncList; syncBlock; syncBlock = syncBlock->_next) { // See if the entry already exists in the block. // If so, don't add another copy. // for (int32_t i = 0; i < syncBlock->_entryCount; i++) { if (syncBlock->_hashEntryArray[i] == entry) return true; } // Remember the first sync block that has some free slots // if (syncBlock->_entryCount < syncBlock->_entryListSize && !freeSyncBlock) freeSyncBlock = syncBlock; } if (!freeSyncBlock) { // Allocate a new temp trampoline sync block // if (!self()->allocateTempTrampolineSyncBlock()) { // Can't allocate another block, mark the code cache as needing a // full/slow sync during a safe point // _flags |= CODECACHE_FULL_SYNC_REQUIRED; return false; } // New block is now at the at head of list // freeSyncBlock = _trampolineSyncList; } freeSyncBlock->_hashEntryArray[freeSyncBlock->_entryCount] = entry; freeSyncBlock->_entryCount++; return true; } // Allocate a new temp trampoline sync block and add it to the head of the list // of such blocks. // bool OMR::CodeCache::allocateTempTrampolineSyncBlock() { CodeCacheTempTrampolineSyncBlock *block = static_cast<CodeCacheTempTrampolineSyncBlock*>(_manager->getMemory(sizeof(CodeCacheTempTrampolineSyncBlock))); if (!block) return false; TR::CodeCacheConfig &config = _manager->codeCacheConfig(); block->_hashEntryArray = static_cast<CodeCacheHashEntry**>(_manager->getMemory(sizeof(CodeCacheHashEntry *) * config.codeCacheTempTrampolineSyncArraySize())); if (!block->_hashEntryArray) { _manager->freeMemory(block); return false; } mcc_printf("mcc_temptrampolinesyncblock: trampolineSyncList = %p\n", _trampolineSyncList); mcc_printf("mcc_temptrampolinesyncblock: block = %p\n", block); block->_entryCount = 0; block->_entryListSize = config.codeCacheTempTrampolineSyncArraySize(); block->_next = _trampolineSyncList; _trampolineSyncList = block; return true; } // Allocate a trampoline hash entry // OMR::CodeCacheHashEntry * OMR::CodeCache::allocateHashEntry() { CodeCacheHashEntry *entry; CodeCacheHashEntrySlab *slab = _hashEntrySlab; // Do we have any free entries that were previously allocated from (perhaps) // a slab or this list and were released onto it? if (_hashEntryFreeList) { entry = _hashEntryFreeList; _hashEntryFreeList = entry->_next; return entry; } // Look for a slab with free hash entries if ((slab->_heapAlloc + sizeof(CodeCacheHashEntry)) > slab->_heapTop) { TR::CodeCacheConfig & config = _manager->codeCacheConfig(); slab = CodeCacheHashEntrySlab::allocate(_manager, config.codeCacheHashEntryAllocatorSlabSize()); if (slab == NULL) return NULL; slab->_next = _hashEntrySlab; _hashEntrySlab = slab; } entry = (CodeCacheHashEntry *) slab->_heapAlloc; slab->_heapAlloc += sizeof(CodeCacheHashEntry); return entry; } // Release an unused trampoline hash entry back onto the free list // void OMR::CodeCache::freeHashEntry(CodeCacheHashEntry *entry) { // put it back onto the first slabs free list, see comment above entry->_next = _hashEntryFreeList; _hashEntryFreeList = entry; } // Add a resolved method to the trampoline hash table // bool OMR::CodeCache::addResolvedMethod(TR_OpaqueMethodBlock *method) { CodeCacheHashEntry *entry = self()->allocateHashEntry(); if (!entry) return false; entry->_key = _resolvedMethodHT->hashResolvedMethod(method); entry->_info._resolved._method = method; entry->_info._resolved._currentStartPC = NULL; entry->_info._resolved._currentTrampoline = NULL; _resolvedMethodHT->add(entry); return true; } // empty by default OMR::CodeCacheMethodHeader * OMR::CodeCache::addFreeBlock(void * metaData) { return NULL; } // May add the block between start and end to freeBlockList. // returns false if block is not added // No lock is needed because this operation is performed at GC points // when GC has exclusive access; This is why the allocation (by the compilation // thread needs to be done with VM access // It can also be done by a compilation thread that performs a resize, but we // also take VM access around resize. bool OMR::CodeCache::addFreeBlock2WithCallSite(uint8_t *start, uint8_t *end, char *file, uint32_t lineNumber) { TR::CodeCacheConfig &config = _manager->codeCacheConfig(); // align start on a code cache alignment boundary uint8_t *start_o = start; uint32_t round = config.codeCacheAlignment() - 1; start = align(start, round); // make sure aligning start didn't push it past end if (end <= (start+sizeof(CodeCacheFreeCacheBlock))) { if (config.verboseReclamation()) { TR_VerboseLog::writeLineLocked(TR_Vlog_FAILURE,"addFreeBlock2[%s.%d]: failed to add free block. start = 0x%016x end = 0x%016x alignment = 0x%04x sizeof(CodeCacheFreeCacheBlock) = 0x%08x", file, lineNumber, start_o, end, config.codeCacheAlignment(), sizeof(CodeCacheFreeCacheBlock)); } return false; } uint64_t size = end - start; // Size of space to be freed // Destroy the eyeCatcher; note that there might not be an eyecatcher at all // if (size >= sizeof(CodeCacheMethodHeader)) ((CodeCacheMethodHeader*)start)->_eyeCatcher[0] = 0; //fprintf(stderr, "--ccr-- newFreeBlock size %d at %p\n", size, start); CodeCacheFreeCacheBlock *mergedBlock = NULL; CodeCacheFreeCacheBlock *link = NULL; if (_freeBlockList) { CodeCacheFreeCacheBlock *curr; // find the insertion point for (curr = _freeBlockList; curr->_next && (uint8_t *)(curr->_next) < start; curr = curr->_next) {} if (start < (uint8_t *)curr && (uint8_t *)curr - end < sizeof(CodeCacheFreeCacheBlock)) { // merge with the curr block ahead, which is also the first block TR_ASSERT(end <= (uint8_t *)curr, "assertion failure"); // check for no overlap of blocks // we should not merge warm block with cold blocks if (!(start < _warmCodeAlloc && (uint8_t *)curr >= _coldCodeAlloc)) { // which is also the first block link = (CodeCacheFreeCacheBlock *) start; mergedBlock = curr; //fprintf(stderr, "--ccr-- merging new free block of the size %d with a block of the size %d at %p\n", size, curr->size, link); link->_size = (uint8_t *)curr + curr->_size - start; link->_next = curr->_next; _freeBlockList = link; //fprintf(stderr, "--ccr-- new merged free block's size is %d\n", link->size); } } else if (curr->_next && ((uint8_t *)curr->_next - end < sizeof(CodeCacheFreeCacheBlock)) && !(start < _warmCodeAlloc && (uint8_t *)curr->_next >= _coldCodeAlloc)) { // merge with the next block, but don't merge warm blocks with cold blocks if ((start - ((uint8_t *)curr + curr->_size) < sizeof(CodeCacheFreeCacheBlock)) && !((uint8_t *)curr < _warmCodeAlloc && start >= _coldCodeAlloc)) { // merge with the previous and the next blocks mergedBlock = curr; //fprintf(stderr, "--ccr-- merging new free block of the size %d with blocks of the size %d and %d at %p\n", size, curr->_size, curr->_next->_size, curr); curr->_size = (uint8_t *)curr->_next + curr->_next->_size - (uint8_t *)curr; curr->_next = curr->_next->_next; //fprintf(stderr, "--ccr-- new merged free block's size is %d\n", curr->_size); link = curr; #ifdef DEBUG start = (uint8_t *)curr; #endif } else { mergedBlock = curr->_next; link = (CodeCacheFreeCacheBlock *) start; //fprintf(stderr, "--ccr-- merging new free block of the size %d with a block of the size %d at %p\n", size, curr->next->size, link); link->_size = (uint8_t *)curr->_next + curr->_next->_size - start; link->_next = curr->_next->_next; curr->_next = link; //fprintf(stderr, "--ccr-- new merged free block's size is %d\n", link->_size); } } else if ((uint8_t *)curr < start && start - ((uint8_t *)curr + curr->_size) < sizeof(CodeCacheFreeCacheBlock)) { // merge with the previous block if (!((uint8_t *)curr < _warmCodeAlloc && start >= _coldCodeAlloc)) { mergedBlock = curr; curr->_size = start + size - (uint8_t *)curr; //fprintf(stderr, "--ccr-- new merged free block's size is %d\n", curr->_size); link = curr; #ifdef DEBUG start = (uint8_t *)curr; #endif } } if (!link) // no merging happened { link = (CodeCacheFreeCacheBlock *) start; link->_size = size; if (start < (uint8_t *)curr) { link->_next = _freeBlockList; _freeBlockList = link; } else { link->_next = curr->_next; curr->_next = link; } } } else // This is the first block in the list { _freeBlockList = (CodeCacheFreeCacheBlock *) start; _freeBlockList->_size = size; _freeBlockList->_next = NULL; //updateMaxSizeOfFreeBlocks(_freeBlockList, _freeBlockList->_size); link = _freeBlockList; } self()->updateMaxSizeOfFreeBlocks(link, link->_size); if (config.verboseReclamation()) { TR_VerboseLog::writeLineLocked(TR_Vlog_CODECACHE,"--ccr-- addFreeBlock2WithCallSite CC=%p start=%p end=%p mergedBlock=%p link=%p link->_size=%u, _sizeOfLargestFreeWarmBlock=%d _sizeOfLargestFreeColdBlock=%d warmCodeAlloc=%p coldBlockAlloc=%p", this, (void*)start, (void*)end, mergedBlock, link, (uint32_t)link->_size, _sizeOfLargestFreeWarmBlock, _sizeOfLargestFreeColdBlock, _warmCodeAlloc, _coldCodeAlloc); } #ifdef DEBUG uint8_t *paintStart = start + sizeof(CodeCacheFreeCacheBlock); memset((void*)paintStart, 0xcc, ((CodeCacheFreeCacheBlock*)start)->_size - sizeof(CodeCacheFreeCacheBlock)); #endif if (config.doSanityChecks()) self()->checkForErrors(); return true; } void OMR::CodeCache::updateMaxSizeOfFreeBlocks(CodeCacheFreeCacheBlock *blockPtr, size_t blockSize) { TR::CodeCacheConfig &config = _manager->codeCacheConfig(); if (config.codeCacheFreeBlockRecylingEnabled()) { if ((uint8_t *)blockPtr < _warmCodeAlloc) { if (blockSize > _sizeOfLargestFreeWarmBlock) { //fprintf(stderr, "_sizeOfLargestFreeBlock for cache %p increased to %d\n", this, blockSize); _sizeOfLargestFreeWarmBlock = blockSize; } } else // block belongs to cold code { if (blockSize > _sizeOfLargestFreeColdBlock) _sizeOfLargestFreeColdBlock = blockSize; } } } // Find the smallest free block that will satisfy the request. // // isCold indicates whether a warm or cold block of memory is required. // uint8_t * OMR::CodeCache::findFreeBlock(size_t size, bool isCold, bool isMethodHeaderNeeded) { CodeCacheFreeCacheBlock *currLink; CodeCacheFreeCacheBlock *prevLink; CodeCacheFreeCacheBlock *bestFitLink = NULL, *bestFitLinkPrev = NULL; CodeCacheFreeCacheBlock *biggestLink = NULL; CodeCacheFreeCacheBlock *secondBiggestLink = NULL; TR_ASSERT(_freeBlockList, "Because we first checked that a freeBlockExists, freeBlockList cannot be null"); // Find the smallest free link to fit the requested blockSize for (currLink = _freeBlockList, prevLink = NULL; currLink; prevLink = currLink, currLink = currLink->_next) { if (isCold) { if ((void*)currLink < (void*)_coldCodeAlloc) continue; } else { if ((void*)currLink >= (void*)_warmCodeAlloc) continue; // curLink is warm code } //fprintf(stderr, "cache %p findFreeBlock bs=%u\n", this, currLink->size); if (!biggestLink) { biggestLink = currLink; } else { if (currLink->_size >= biggestLink->_size) // >= is important; do not use > only as secondBiggestLink may be wrong { secondBiggestLink = biggestLink; biggestLink = currLink; } else { if (secondBiggestLink) { if (currLink->_size >= secondBiggestLink->_size) secondBiggestLink = currLink; } else { secondBiggestLink = currLink; } } } if (currLink->_size >= size) { if (!bestFitLink) { bestFitLink = currLink; bestFitLinkPrev = prevLink; } else if (bestFitLink->_size > currLink->_size) { bestFitLink = currLink; bestFitLinkPrev = prevLink; } } } // end for // safety net TR_ASSERT(biggestLink, "There must be a biggestLink"); TR_ASSERT(bestFitLink, "There must be a bestFitLink"); TR::CodeCacheConfig & config = _manager->codeCacheConfig(); if (!isCold) { TR_ASSERT(!config.codeCacheFreeBlockRecylingEnabled() || _sizeOfLargestFreeWarmBlock == biggestLink->_size, "_sizeOfLargestFreeWarmBlock=%d biggestLink->_size=%d", _sizeOfLargestFreeWarmBlock, (int32_t)biggestLink->_size); } else { TR_ASSERT(!config.codeCacheFreeBlockRecylingEnabled() || _sizeOfLargestFreeColdBlock == biggestLink->_size, "assertion failure"); } if (bestFitLink) { // Fix the linked list by removing the allocated block AND if there is any unused // space left in the currLink chunk, reclaim it and put back on the freeList CodeCacheFreeCacheBlock *leftBlock = self()->removeFreeBlock(size, bestFitLinkPrev, bestFitLink); if (bestFitLink == biggestLink) // Size of biggest might have changed { uint64_t leftBlockSize = leftBlock ? leftBlock->_size : 0; uint64_t secondBiggestSize = secondBiggestLink ? secondBiggestLink->_size : 0; uint64_t biggestSize = leftBlockSize > secondBiggestSize ? leftBlockSize : secondBiggestSize; if (!isCold) { _sizeOfLargestFreeWarmBlock = (size_t)biggestSize; } else _sizeOfLargestFreeColdBlock = (size_t)biggestSize; } //fprintf(stderr, "--ccr-- reallocate free'd block of size %d\n", size); if (config.verboseReclamation()) { TR_VerboseLog::writeLineLocked(TR_Vlog_CODECACHE,"--ccr- findFreeBlock: CodeCache=%p size=%u isCold=%d bestFitLink=%p bestFitLink->size=%u leftBlock=%p", this, size, isCold, bestFitLink, bestFitLink->_size, leftBlock); } } // Because we call this method only after we made sure a free block exists // this function can never return NULL TR_ASSERT(bestFitLink, "FindFreeBlock return NULL"); if (isMethodHeaderNeeded) self()->writeMethodHeader(bestFitLink, bestFitLink->_size, isCold); if (config.doSanityChecks()) self()->checkForErrors(); return (uint8_t *) bestFitLink; } // Remove a free block from the list of free blocks for this code cache to make // it available for re-use. // // blockSize is the amount of memory needed from this free block. // // The function returns the remaining part of the block that was split OMR::CodeCacheFreeCacheBlock * OMR::CodeCache::removeFreeBlock(size_t blockSize, CodeCacheFreeCacheBlock *prev, CodeCacheFreeCacheBlock *curr) { CodeCacheFreeCacheBlock *next = curr->_next; // Is there any left over space in the current link? Save it as a // separate link and adjust the sizes of the two split resulting blocks if (curr->_size - blockSize >= MIN_SIZE_BLOCK) { size_t splitSize = curr->_size - blockSize; // remaining portion curr->_size = blockSize; curr = (CodeCacheFreeCacheBlock *) ((uint8_t *) curr + blockSize); curr->_size = splitSize; curr->_next = next; if (prev) prev->_next = curr; else _freeBlockList = curr; return curr; } else // Use the entire block { if (prev) prev->_next = next; else _freeBlockList = next; return NULL; } } void OMR::CodeCache::dumpCodeCache() { printf("Code Cache @%p\n", this); printf(" |-- warmCodeAlloc = 0x%08" OMR_PRIxPTR "\n", (uintptr_t)_warmCodeAlloc ); printf(" |-- coldCodeAlloc = 0x%08" OMR_PRIxPTR "\n", (uintptr_t)_coldCodeAlloc ); printf(" |-- tempTrampsMax = %d\n", _tempTrampolinesMax ); printf(" |-- flags = %d\n", _flags ); printf(" |-- next = 0x%p\n", _next ); } void OMR::CodeCache::printOccupancyStats() { fprintf(stderr, "Code Cache @%p flags=0x%x almostFull=%d\n", this, _flags, _almostFull); fprintf(stderr, " cold-warm hole size = %8" OMR_PRIuSIZE " bytes\n", self()->getFreeContiguousSpace()); fprintf(stderr, " warmCodeAlloc=%p coldCodeAlloc=%p\n", (void*)_warmCodeAlloc, (void*)_coldCodeAlloc); if (_freeBlockList) { fprintf(stderr, " sizeOfLargestFreeColdBlock = %8" OMR_PRIuSIZE " bytes\n", _sizeOfLargestFreeColdBlock); fprintf(stderr, " sizeOfLargestFreeWarmBlock = %8" OMR_PRIuSIZE " bytes\n", _sizeOfLargestFreeWarmBlock); fprintf(stderr, " reclaimed sizes:"); // scope for critical section { CacheCriticalSection resolveAndCreateTrampoline(self()); for (CodeCacheFreeCacheBlock *currLink = _freeBlockList; currLink; currLink = currLink->_next) fprintf(stderr, " %" OMR_PRIuSIZE, currLink->_size); } fprintf(stderr, "\n"); } TR::CodeCacheConfig &config = _manager->codeCacheConfig(); if (config.trampolineCodeSize()) { fprintf(stderr, " trampoline free space = %d (temp=%d)\n", (int32_t)(_trampolineReservationMark - _trampolineBase), (int32_t)(_tempTrampolineNext - _tempTrampolineBase)); } } void OMR::CodeCache::printFreeBlocks() { fprintf(stderr, "List of free blocks:\n"); // scope for cache walk { CacheCriticalSection walkList(self()); for (CodeCacheFreeCacheBlock *currLink = _freeBlockList; currLink; currLink = currLink->_next) fprintf(stderr, "%p - %p\n", currLink, ((char*)currLink) + currLink->_size); } } //-------------------- checkForErrors --------------------------------- // Scan the entire list of free blocks and make sure numbers make sense // Blocks should be in ascending order of their addresses // StartBlock+size should lead to an allocated portion (otherwise a merge // would have happened) // StartBlock and StartBlock+size should be within the cache //--------------------------------------------------------------------- void OMR::CodeCache::checkForErrors() { if (_freeBlockList) { bool doCrash = false; size_t maxFreeWarmSize = 0, maxFreeColdSize = 0; // scope for cache walk { CacheCriticalSection walkFreeList(self()); for (CodeCacheFreeCacheBlock *currLink = _freeBlockList; currLink; currLink = currLink->_next) { // Does the size look right? uint64_t cacheSize = _segment->segmentTop() - _segment->segmentBase(); if (currLink->_size > cacheSize) { fprintf(stderr, "checkForErrors cache %p: Error: Size of the free block %u is bigger than the size of the cache %u\n", this, (uint32_t)currLink->_size, (uint32_t)cacheSize); doCrash = true; } // Is the block fully contained in this code cache? if ((uint8_t*)currLink < _segment->segmentBase()+sizeof(void*) || (uint8_t*)currLink > _segment->segmentTop()) { fprintf(stderr, "checkForErrors cache %p: Error: curLink %p is outside cache boundaries\n", this, currLink); doCrash = true; } uint8_t *endBlock = (uint8_t *)currLink + currLink->_size; if (endBlock < _segment->segmentBase()+sizeof(void*) || endBlock > _segment->segmentTop()) { fprintf(stderr, "checkForErrors cache %p: Error: End of block %p residing at %p is outside cache boundaries\n", this, currLink, endBlock); doCrash = true; } // Next free block (if any) should be after the end of this free block if (currLink->_next) { if ((uint8_t*)currLink->_next == endBlock) { // Two freed blocks can be adjacent if one belongs to the warm region // and the other one belongs to the cold region if (!((uint8_t*)currLink < _warmCodeAlloc && endBlock >= _coldCodeAlloc)) { fprintf(stderr, "checkForErrors cache %p: Error: missed freed block coalescing opportunity. Next block (%p) is adjacent to current one %p-%p\n", this, currLink->_next, currLink, endBlock); doCrash = true; } } else { if ((uint8_t*)currLink->_next <= endBlock) { fprintf(stderr, "checkForErrors cache %p: Error: next block (%p) should come after end of current one %p-%p\n", this, currLink->_next, currLink, endBlock); doCrash = true;; } // A free block is always followed by a used block except when this is the last free block in the warm region if (endBlock != _warmCodeAlloc) { // There should be valid code between this block and the next uint8_t* eyeCatcherPosition = endBlock+offsetof(CodeCacheMethodHeader, _eyeCatcher); if (*eyeCatcherPosition != *(_manager->codeCacheConfig().warmEyeCatcher())) { fprintf(stderr, "checkForErrors cache %p: Error: block coming after this free one (%p-%p) does not have the eye catcher but %u\n", this, currLink, endBlock, *eyeCatcherPosition); doCrash = true; } } } } if ((uint8_t*)currLink < _warmCodeAlloc) // warm block { if (currLink->_size > maxFreeWarmSize) maxFreeWarmSize = currLink->_size; } else // cold block { if (currLink->_size > maxFreeColdSize) maxFreeColdSize = currLink->_size; } } // end for if (_sizeOfLargestFreeWarmBlock != maxFreeWarmSize) { fprintf(stderr, "checkForErrors cache %p: Error: _sizeOfLargestFreeWarmBlock(%" OMR_PRIuSIZE ") != maxFreeWarmSize(%" OMR_PRIuSIZE ")\n", this, _sizeOfLargestFreeWarmBlock, maxFreeWarmSize); doCrash = true; } if (_sizeOfLargestFreeColdBlock != maxFreeColdSize) { fprintf(stderr, "checkForErrors cache %p: Error: _sizeOfLargestFreeColdBlock(%" OMR_PRIuSIZE ") != maxFreeColdSize(%" OMR_PRIuSIZE ")\n", this, _sizeOfLargestFreeColdBlock, maxFreeColdSize); doCrash = true; } // Blocks must come one after another; // 1. A free block must be followed by a used block; // The only exception is when we make transition from warm to cold section // 2. A used block must be followed by another used block or by a free block // 3. All used blocks must have a CodeCacheMethodHeader with size as first parameter, folowed by eyeCatcher and metaData TR::CodeCacheConfig &config = _manager->codeCacheConfig(); uint8_t *start = align(((uint8_t*)_segment->segmentTop()) + sizeof(char*), config.codeCacheAlignment() - 1); uint8_t *prevBlock = NULL; while (start < this->_trampolineBase) { // Is it a free segment? bool freeSeg = false; CodeCacheFreeCacheBlock *currLink = _freeBlockList; for (; currLink; currLink = currLink->_next) if (start == (uint8_t *)currLink) { freeSeg = true; break; } if (freeSeg) { prevBlock = start; start = (uint8_t *)currLink + currLink->_size; continue; } else // used seg { // There should be valid code between this block and the next uint8_t * eyeCatcherPosition = start+offsetof(CodeCacheMethodHeader, _eyeCatcher); if (*eyeCatcherPosition != *(_manager->codeCacheConfig().warmEyeCatcher())) { prevBlock = start; start = start + ((CodeCacheMethodHeader*)start)->_size; if (start >= _warmCodeAlloc) start = _coldCodeAlloc; continue; } else { fprintf(stderr, "checkForErrors cache %p: block %p is not in the free list and does not have eye-catcher; prevBlock=%p\n", this, start, prevBlock); doCrash = true; break; } } } // end while } if (doCrash) { self()->dumpCodeCache(); self()->printOccupancyStats(); self()->printFreeBlocks(); *((int32_t*)1) = 0xffffffff; // cause a crash } } } OMR::CodeCacheHashEntry * OMR::CodeCache::findResolvedMethod(TR_OpaqueMethodBlock *method) { return _resolvedMethodHT->findResolvedMethod(method); } void OMR::CodeCache::findOrAddResolvedMethod(TR_OpaqueMethodBlock *method) { CacheCriticalSection codeCacheLock(self()); CodeCacheHashEntry *entry = self()->findResolvedMethod(method); if (!entry) self()->addResolvedMethod(method); } // Allocate code memory within a code cache. Some of the allocation may come from the free list // uint8_t * OMR::CodeCache::allocateCodeMemory(size_t warmCodeSize, size_t coldCodeSize, uint8_t **coldCode, bool needsToBeContiguous, bool isMethodHeaderNeeded) { TR::CodeCacheConfig & config = _manager->codeCacheConfig(); uint8_t * warmCodeAddress = NULL; uint8_t * coldCodeAddress = NULL; uint8_t * cacheHeapAlloc; bool warmIsFreeBlock = false; bool coldIsFreeBlock = false; size_t warmSize = warmCodeSize; size_t coldSize = coldCodeSize; _manager->performSizeAdjustments(warmSize, coldSize, needsToBeContiguous, isMethodHeaderNeeded); // side effect on warmSize and coldSize // Acquire mutex because we are walking the list of free blocks CacheCriticalSection walkingFreeList(self()); // See if we can get a warm and/or cold block from the reclaimed method list if (!needsToBeContiguous) { if (warmSize) warmIsFreeBlock = _sizeOfLargestFreeWarmBlock >= warmSize; if (coldSize) coldIsFreeBlock = _sizeOfLargestFreeColdBlock >= coldSize; } // We want to avoid the case where we allocate the warm portion and then // discover that we cannot allocate the cold portion and switch to // another code cache. Therefore, lets make sure that we can allocate // cold before proceding with the allocation if (coldSize != 0 && !coldIsFreeBlock && coldSize + (warmIsFreeBlock ? 0 : warmSize) > self()->getFreeContiguousSpace()) { return NULL; } size_t round = config.codeCacheAlignment() - 1; if (!warmIsFreeBlock) { if (warmSize) { // Try to allocate a block from the code cache heap cacheHeapAlloc = _warmCodeAlloc; cacheHeapAlloc = (uint8_t*)(((size_t)cacheHeapAlloc + round) & ~round); warmCodeAddress = cacheHeapAlloc; cacheHeapAlloc += warmSize; // Do we have enough space in codeCache to allocate the warm code? if (cacheHeapAlloc > _coldCodeAlloc) { // No - just return failure // return NULL; } // _warmCodeAlloc will change to its new value 'cacheHeapAlloc' // Thus the free code cache space decreases by (cacheHeapAlloc-_warmCodeAlloc) _manager->decreaseFreeSpaceInCodeCacheRepository(cacheHeapAlloc-_warmCodeAlloc); _warmCodeAlloc = cacheHeapAlloc; if (isMethodHeaderNeeded) self()->writeMethodHeader(warmCodeAddress, warmSize, false); } else warmCodeAddress = _warmCodeAlloc; } else { warmCodeAddress = self()->findFreeBlock(warmSize, false, isMethodHeaderNeeded); // side effect: free block is unlinked // If isMeathodHeaderNeeded is true, warmCodeAddress will look like a pointer to CodeCacheMethodHeader // Otherwise, it look like a pointer to CodeCacheFreeCacheBlock // Note that findFreeBlock may return a block which is slightly bigger than what we wanted // Change the warmSize to the higher size so that the size of the block is correctly maintained //if (((CodeCacheFreeCacheBlock*)warmCodeAddress)->size > warmSize) // warmSize = ((CodeCacheFreeCacheBlock*)warmCodeAddress)->size; } if (!coldIsFreeBlock) { if (coldSize) { cacheHeapAlloc = _coldCodeAlloc - coldSize; cacheHeapAlloc = (uint8_t *)(((size_t)cacheHeapAlloc) & ~round); // Do we have enough space in codeCache to allocate the warm code? if (cacheHeapAlloc < _warmCodeAlloc) { // This case should never happen now because we checked above that both warm and cold can be allocated TR_ASSERT(false, "Must be able to find space for cold code"); // No - just return failure // if (!warmIsFreeBlock) { _warmCodeAlloc = warmCodeAddress; } return NULL; } _manager->decreaseFreeSpaceInCodeCacheRepository(_coldCodeAlloc - cacheHeapAlloc); _coldCodeAlloc = cacheHeapAlloc; coldCodeAddress = cacheHeapAlloc; if (isMethodHeaderNeeded) self()->writeMethodHeader(coldCodeAddress, coldSize, true); } else coldCodeAddress = _coldCodeAlloc; } else { coldCodeAddress = self()->findFreeBlock(coldSize, true, isMethodHeaderNeeded); // side effect: free block is unlinked // Note that findFreeBlock may return a block which is slightly bigger than what we wanted // Change the warmSize to the higher size so that the size of the block is correctly maintained //if (((CodeCacheFreeCacheBlock*)coldCodeAddress)->size > coldSize) // coldSize = ((CodeCacheFreeCacheBlock*)coldCodeAddress)->size; } /////diagnostic("allocated method @0x%p [cc=0x%p] (reclaimed block)\n", methodBlockAddress, this); _lastAllocatedBlock = (CodeCacheMethodHeader*)warmCodeAddress; // MP if (isMethodHeaderNeeded) { if (warmSize) { warmCodeAddress += sizeof(CodeCacheMethodHeader); } if (coldSize) { coldCodeAddress += sizeof(CodeCacheMethodHeader); } } if (!needsToBeContiguous) *coldCode = coldCodeAddress; else *coldCode = warmCodeAddress; return warmCodeAddress; } void * OMR::CodeCache::getCCPreLoadedCodeAddress(TR_CCPreLoadedCode h, TR::CodeGenerator *codeGenerator) { if (!_CCPreLoadedCodeInitialized) { if (TR_numCCPreLoadedCode) { TR::CodeCacheConfig &config = _manager->codeCacheConfig(); config.mccCallbacks().createCCPreLoadedCode(_CCPreLoadedCodeBase, _CCPreLoadedCodeTop, _CCPreLoadedCode, codeGenerator); _CCPreLoadedCodeInitialized = true; } } return (h >= 0 && h < TR_numCCPreLoadedCode) ? _CCPreLoadedCode[h] : (void *) (uintptr_t) 0xDEADBEEF; } // Allocate and initialize a new code cache // If reservingCompThreadID >= -1, then the new code codecache will be reserved // A value of -1 for this parameter means that an application thread is requesting the reservation // A positive value means that a compilation thread is requesting the reservation // A value of -2 (or less) means that no reservation is requested // TR::CodeCache * OMR::CodeCache::allocate(TR::CodeCacheManager *manager, size_t segmentSize, int32_t reservingCompThreadID) { return manager->allocateCodeCacheFromNewSegment(segmentSize, reservingCompThreadID); }
36.65233
249
0.627665
xiacijie
efa68845f579d193ab3e5f439ffdc6bb52b04b56
5,161
cpp
C++
src/workers/src/postgres_workers_repository.cpp
maxerMU/db-course
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
[ "Apache-2.0" ]
null
null
null
src/workers/src/postgres_workers_repository.cpp
maxerMU/db-course
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
[ "Apache-2.0" ]
null
null
null
src/workers/src/postgres_workers_repository.cpp
maxerMU/db-course
3927f1cf0ccb2a937d571626dcc42d725a89d3f6
[ "Apache-2.0" ]
null
null
null
#include "postgres_workers_repository.h" #include <time.h> #include "base_sections.h" #include "database_exceptions.h" #include "iostream" PostgresWorkersRepository::PostgresWorkersRepository( const std::shared_ptr<BaseConfig>& conf, const std::string& connection_section) { read_config(conf, connection_section); connect(); add_prepare_statements(); } void PostgresWorkersRepository::read_config( const std::shared_ptr<BaseConfig>& conf, const std::string& connection_section) { name_ = conf->get_string_field({connection_section, DbNameSection}); user_ = conf->get_string_field({connection_section, DbUserSection}); user_password_ = conf->get_string_field({connection_section, DbUserPasswordSection}); host_ = conf->get_string_field({connection_section, DbHostSection}); port_ = conf->get_uint_field({connection_section, DbPortSection}); } void PostgresWorkersRepository::connect() { std::string connection_string = "dbname = " + name_ + " user = " + user_ + " password = " + user_password_ + " hostaddr = " + host_ + " port = " + std::to_string(port_); try { connection_ = std::shared_ptr<pqxx::connection>( new pqxx::connection(connection_string.c_str())); if (!connection_->is_open()) { throw DatabaseConnectException("can't connect to " + name_); } else std::cout << "Connected to db " << name_ << std::endl; } catch (std::exception& ex) { throw DatabaseConnectException("can't connect to " + name_ + " " + ex.what()); } } void PostgresWorkersRepository::add_prepare_statements() { connection_->prepare(requests_names[CREATE], "SELECT FN_ADD_WORKER($1, $2, $3, $4, $5, $6)"); connection_->prepare(requests_names[READ_COUNT], "SELECT FN_WORKERS_COUNT()"); connection_->prepare(requests_names[READ_PASSWORD], "SELECT * FROM FN_GET_PASSWORD($1)"); connection_->prepare(requests_names[READ_BASE_INF], "SELECT * FROM FN_GET_WORKER_BY_ID($1)"); connection_->prepare( requests_names[UPDATE], "SELECT * FROM FN_UPDATE_WORKER($1, $2, $3, $4, $5, $6)"); connection_->prepare(requests_names[UPDATE_PRIVILEGE], "CALL PR_UPDATE_WORKER_PRIVILEGE($1, $2)"); } int PostgresWorkersRepository::create(const WorkerPost& worker) { pqxx::work w(*connection_); std::string birthdate = std::to_string(worker.birthdate().tm_year + 1900) + "-" + std::to_string(worker.birthdate().tm_mon + 1) + "-" + std::to_string(worker.birthdate().tm_mday); pqxx::result res = w.exec_prepared( requests_names[CREATE], worker.name(), worker.surname(), birthdate, (int)worker.getPrivilege(), worker.username(), worker.password()); w.commit(); return res[0][0].as<size_t>(); } size_t PostgresWorkersRepository::workers_count() { pqxx::work w(*connection_); pqxx::result res = w.exec_prepared(requests_names[READ_COUNT]); w.commit(); return res[0][0].as<size_t>(); } WorkerBaseInf PostgresWorkersRepository::read(size_t worker_id) { pqxx::work w(*connection_); pqxx::result res = w.exec_prepared(requests_names[READ_BASE_INF], worker_id); w.commit(); if (res.size() == 0) throw DatabaseNotFoundException("can't find user"); WorkerBaseInf worker; worker.setName(res[0][0].as<std::string>()); worker.setSurname(res[0][1].as<std::string>()); auto birthdate_str = res[0][2].as<std::string>(); tm birthdate; if (!strptime(birthdate_str.c_str(), "%Y-%m-%d", &birthdate)) throw DatabaseIncorrectAnswerException("can't parse datetime"); worker.setBirthdate(birthdate); worker.setPrivilege(static_cast<PrivilegeLevel>(res[0][3].as<int>())); return worker; } int PostgresWorkersRepository::update(const WorkerUpdate& worker) { pqxx::work w(*connection_); std::string birthdate = std::to_string(worker.birthdate().tm_year + 1900) + "-" + std::to_string(worker.birthdate().tm_mon + 1) + "-" + std::to_string(worker.birthdate().tm_mday); pqxx::result res = w.exec_prepared( requests_names[UPDATE], worker.getWorker_id(), worker.name(), worker.surname(), birthdate, worker.username(), worker.password()); w.commit(); return res[0][0].as<size_t>(); } bool PostgresWorkersRepository::get_password(std::string& password, size_t& worker_id, const std::string& username) { pqxx::work w(*connection_); pqxx::result res = w.exec_prepared(requests_names[READ_PASSWORD], username); w.commit(); if (!res[0][0].as<bool>()) return false; worker_id = res[0][1].as<size_t>(); password = res[0][2].as<std::string>(); return true; } void PostgresWorkersRepository::update_privilege( size_t worker_id, const PrivilegeLevel& privilege) { pqxx::work w(*connection_); w.exec_prepared(requests_names[UPDATE_PRIVILEGE], worker_id, (int)privilege); w.commit(); }
36.090909
80
0.649293
maxerMU
efaad9a18ffbf7767f4649de0397a17239b95512
10,840
cc
C++
avida/avida-core/source/cpu/cInstSet.cc
FergusonAJ/plastic-evolvability-avida
441a91f1cafa2a0883f8f3ce09c8894efa963e7c
[ "MIT" ]
2
2021-09-16T14:47:43.000Z
2021-10-31T04:55:16.000Z
avida/avida-core/source/cpu/cInstSet.cc
FergusonAJ/plastic-evolvability-avida
441a91f1cafa2a0883f8f3ce09c8894efa963e7c
[ "MIT" ]
null
null
null
avida/avida-core/source/cpu/cInstSet.cc
FergusonAJ/plastic-evolvability-avida
441a91f1cafa2a0883f8f3ce09c8894efa963e7c
[ "MIT" ]
2
2020-08-19T20:01:14.000Z
2020-12-21T21:24:12.000Z
/* * cInstSet.cc * Avida * * Called "inst_set.cc" prior to 12/5/05. * Copyright 1999-2011 Michigan State University. All rights reserved. * Copyright 1993-2001 California Institute of Technology. * * * This file is part of Avida. * * Avida is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. * * Avida is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License along with Avida. * If not, see <http://www.gnu.org/licenses/>. * */ #include "cInstSet.h" #include "avida/core/WorldDriver.h" #include "cArgContainer.h" #include "cArgSchema.h" #include "cAvidaContext.h" #include "cStringUtil.h" #include "cUserFeedback.h" #include "cWorld.h" #include <iostream> using namespace std; using namespace Avida; cInstSet::cInstSet(const cInstSet& _in) : m_world(_in.m_world) , m_name(_in.m_name) , m_hw_type(_in.m_hw_type) , m_inst_lib(_in.m_inst_lib) , m_lib_name_map(_in.m_lib_name_map) , m_mutation_index(NULL) , m_has_costs(_in.m_has_costs) , m_has_ft_costs(_in.m_has_ft_costs) , m_has_energy_costs(_in.m_has_energy_costs) , m_has_res_costs(_in.m_has_res_costs) , m_has_fem_res_costs(_in.m_has_fem_res_costs) , m_has_female_costs(_in.m_has_female_costs) , m_has_choosy_female_costs(_in.m_has_choosy_female_costs) , m_has_post_costs(_in.m_has_post_costs) , m_has_bonus_costs(_in.m_has_bonus_costs) { m_mutation_index = new cOrderedWeightedIndex(*_in.m_mutation_index); } cInstSet& cInstSet::operator=(const cInstSet& _in) { m_world = _in.m_world; m_name = _in.m_name; m_hw_type = _in.m_hw_type; m_inst_lib = _in.m_inst_lib; m_lib_name_map = _in.m_lib_name_map; m_mutation_index = NULL; m_has_costs = _in.m_has_costs; m_has_ft_costs = _in.m_has_ft_costs; m_has_energy_costs = _in.m_has_energy_costs; m_has_res_costs = _in.m_has_res_costs; m_has_fem_res_costs = _in.m_has_fem_res_costs; m_has_female_costs = _in.m_has_female_costs; m_has_choosy_female_costs = _in.m_has_choosy_female_costs; m_has_post_costs = _in.m_has_post_costs; m_has_bonus_costs = _in.m_has_bonus_costs; m_mutation_index = new cOrderedWeightedIndex(*_in.m_mutation_index); return *this; } Instruction cInstSet::GetRandomInst(cAvidaContext& ctx) const { double weight = ctx.GetRandom().GetDouble(m_mutation_index->GetTotalWeight()); unsigned inst_ndx = m_mutation_index->FindPosition(weight); return Instruction(inst_ndx); } Instruction cInstSet::ActivateNullInst() { const int inst_id = m_lib_name_map.GetSize(); const int null_fun_id = m_inst_lib->GetInstNull(); assert(inst_id < MAX_INSTSET_SIZE); // Make sure not to activate again if NULL is already active for (int i = 0; i < inst_id; i++) if (m_lib_name_map[i].lib_fun_id == null_fun_id) return Instruction(i); // Increase the size of the array... m_lib_name_map.Resize(inst_id + 1); // Setup the new function... m_lib_name_map[inst_id].lib_fun_id = null_fun_id; m_lib_name_map[inst_id].redundancy = 0; m_lib_name_map[inst_id].cost = 0; m_lib_name_map[inst_id].ft_cost = 0; m_lib_name_map[inst_id].energy_cost = 0; m_lib_name_map[inst_id].prob_fail = 0.0; m_lib_name_map[inst_id].addl_time_cost = 0; m_lib_name_map[inst_id].res_cost = 0.0; m_lib_name_map[inst_id].fem_res_cost = 0.0; m_lib_name_map[inst_id].post_cost = 0; m_lib_name_map[inst_id].bonus_cost = 0.0; return Instruction(inst_id); } cString cInstSet::FindBestMatch(const cString& in_name) const { int best_dist = 1024; cString best_name(""); for (int i = 0; i < m_lib_name_map.GetSize(); i++) { const cString & cur_name = m_inst_lib->GetName(m_lib_name_map[i].lib_fun_id); const int cur_dist = cStringUtil::EditDistance(cur_name, in_name); if (cur_dist < best_dist) { best_dist = cur_dist; best_name = cur_name; } if (cur_dist == 0) break; } return best_name; } bool cInstSet::InstInSet(const cString& in_name) const { cString best_name(""); for (int i = 0; i < m_lib_name_map.GetSize(); i++) { const cString& cur_name = m_inst_lib->GetName(m_lib_name_map[i].lib_fun_id); if (cur_name == in_name) return true; } return false; } bool cInstSet::LoadWithStringList(const cStringList& sl, cUserFeedback* feedback) { cArgSchema schema(':'); // Integer schema.AddEntry("cost", 0, 0); schema.AddEntry("initial_cost", 1, 0); schema.AddEntry("energy_cost", 2, 0); schema.AddEntry("addl_time_cost", 3, 0); schema.AddEntry("female_cost", 4, 0); //@CHC schema.AddEntry("choosy_female_cost", 5, 0); //@CHC schema.AddEntry("post_cost", 6, 0); // Double schema.AddEntry("prob_fail", 0, 0.0); schema.AddEntry("res_cost", 1, 0.0); schema.AddEntry("redundancy", 2, 1.0); schema.AddEntry("fem_res_cost", 3, 0.0); schema.AddEntry("bonus_cost", 4, 0.0); // String schema.AddEntry("inst_code", 0, ""); // Ensure that the instruction code length is in the range of bits supported by the int type int inst_code_len = m_world->GetConfig().INST_CODE_LENGTH.Get(); if ((unsigned)inst_code_len > (sizeof(int) * 8)) inst_code_len = sizeof(int) * 8; else if (inst_code_len <= 0) inst_code_len = 1; bool success = true; for (int line_id = 0; line_id < sl.GetSize(); line_id++) { cString cur_line = sl.GetLine(line_id); // Look for the INST keyword at the beginning of each line, and ignore if not found. cString inst_name = cur_line.PopWord(); if (inst_name != "INST") continue; // Lookup the instruction name in the library inst_name = cur_line.Pop(':'); int fun_id = m_inst_lib->GetIndex(inst_name); if (fun_id == -1) { // Oh oh! Didn't find an instruction! Apto::String a_inst_name((const char*)inst_name); if (feedback) feedback->Error("unknown instruction '%s' (Best match = '%s')", (const char*)inst_name, (const char*)m_inst_lib->GetNearMatch(a_inst_name)); success = false; continue; } // Load the arguments for this instruction cArgContainer* args = cArgContainer::Load(cur_line, schema, *feedback); if (!args) { success = false; continue; } // Check to make sure we are not inserting the special NULL instruction if (fun_id == m_inst_lib->GetInstNull()) { if (feedback) feedback->Error("invalid use of NULL instruction"); success = false; continue; } double redundancy = args->GetDouble(2); if (redundancy < 0.0) { if (feedback) feedback->Warning("instruction '%s' has negative redundancy, ignoring...", (const char*)inst_name); continue; } // Get the ID of the new Instruction const int inst_id = m_lib_name_map.GetSize(); assert(inst_id < MAX_INSTSET_SIZE); // Increase the size of the array... m_lib_name_map.Resize(inst_id + 1); // Setup the new function... m_lib_name_map[inst_id].lib_fun_id = fun_id; m_lib_name_map[inst_id].redundancy = redundancy; m_lib_name_map[inst_id].cost = args->GetInt(0); m_lib_name_map[inst_id].ft_cost = args->GetInt(1); m_lib_name_map[inst_id].energy_cost = args->GetInt(2); m_lib_name_map[inst_id].prob_fail = args->GetDouble(0); m_lib_name_map[inst_id].addl_time_cost = args->GetInt(3); m_lib_name_map[inst_id].res_cost = args->GetDouble(1); m_lib_name_map[inst_id].fem_res_cost = args->GetDouble(3); m_lib_name_map[inst_id].female_cost = args->GetInt(4); m_lib_name_map[inst_id].choosy_female_cost = args->GetInt(5); m_lib_name_map[inst_id].post_cost = args->GetInt(6); m_lib_name_map[inst_id].bonus_cost = args->GetDouble(4); if (m_lib_name_map[inst_id].cost > 1) m_has_costs = true; if (m_lib_name_map[inst_id].ft_cost) m_has_ft_costs = true; if (m_lib_name_map[inst_id].energy_cost) m_has_energy_costs = true; if (m_lib_name_map[inst_id].res_cost) m_has_res_costs = true; if (m_lib_name_map[inst_id].fem_res_cost) m_has_fem_res_costs = true; if (m_lib_name_map[inst_id].female_cost) m_has_female_costs = true; if (m_lib_name_map[inst_id].choosy_female_cost) m_has_choosy_female_costs = true; if (m_lib_name_map[inst_id].post_cost > 1) m_has_post_costs = true; if (m_lib_name_map[inst_id].bonus_cost) m_has_bonus_costs = true; // Parse the instruction code cString inst_code = args->GetString(0); if (inst_code == "") { switch (m_world->GetConfig().INST_CODE_DEFAULT_TYPE.Get()) { case INST_CODE_ZEROS: m_lib_name_map[inst_id].inst_code = 0; break; case INST_CODE_INSTNUM: m_lib_name_map[inst_id].inst_code = ((~0) >> ((sizeof(int) * 8) - inst_code_len)) & inst_id; break; default: if (feedback) feedback->Error("invalid default instruction code type"); success = false; break; } } else { int inst_code_val = 0; for (int i = 0; i < inst_code_len && i < inst_code.GetSize(); i++) { inst_code_val <<= 1; if (inst_code[i] == '1') inst_code_val |= 1; else if (inst_code[i] != '0') { if (feedback) feedback->Error("invalid character in instruction code, must be 0 or 1"); success = false; break; } } m_lib_name_map[inst_id].inst_code = inst_code_val; } // If this is a nop, add it to the proper mappings if ((*m_inst_lib)[fun_id].IsNop()) { // Assert nops are at the _beginning_ of an inst_set. if (m_lib_name_map.GetSize() != (m_lib_nopmod_map.GetSize() + 1)) { if (feedback) feedback->Error("invalid NOP placement, all NOPs must be listed first"); success = false; } m_lib_nopmod_map.Resize(inst_id + 1); m_lib_nopmod_map[inst_id] = fun_id; } // Clean up the argument container for this instruction delete args; } //Setup mutation indexing based on redundancies m_mutation_index = new cOrderedWeightedIndex(); for (int id=0; id < m_lib_name_map.GetSize(); id++) { double red = m_lib_name_map[id].redundancy; if (red == 0.0) { continue; } m_mutation_index->SetWeight(id, m_lib_name_map[id].redundancy); } return success; } void cInstSet::SaveInstructionSequence(ofstream& of, const InstructionSequence& seq) const { for (int i = 0; i < seq.GetSize(); i++) of << GetName(seq[i]) << endl; }
33.875
125
0.6869
FergusonAJ
efaaeb5c1d98d01e80e9d8f73e66cad874694928
722
hpp
C++
core/src/modules/include/IFreezingPoint.hpp
athelaf/nextsimdg
557e45db6af2cc07d00b3228c2d46f87567fe755
[ "Apache-2.0" ]
null
null
null
core/src/modules/include/IFreezingPoint.hpp
athelaf/nextsimdg
557e45db6af2cc07d00b3228c2d46f87567fe755
[ "Apache-2.0" ]
null
null
null
core/src/modules/include/IFreezingPoint.hpp
athelaf/nextsimdg
557e45db6af2cc07d00b3228c2d46f87567fe755
[ "Apache-2.0" ]
null
null
null
/*! * @file IFreezingPoint.hpp * * @date Nov 9, 2021 * @author Tim Spain <timothy.spain@nersc.no> */ #ifndef SRC_INCLUDE_IFREEZINGPOINT_HPP_ #define SRC_INCLUDE_IFREEZINGPOINT_HPP_ namespace Nextsim { //! The interface class for calculation of the freezing point of seawater. class IFreezingPoint { public: virtual ~IFreezingPoint() = default; /*! * @brief A virtual function that calculates the freezing point of * seawater. * * @details Freezing point in ˚C of water with the given salinity at * standard pressure. * * @param sss Sea surface salinity [PSU] */ virtual double operator()(double sss) const = 0; }; } #endif /* SRC_INCLUDE_IFREEZINGPOINT_HPP_ */
23.290323
74
0.689751
athelaf
efafec67d13a37f21e8be68ec3e153811f614343
2,981
cpp
C++
grasp_generation/graspitmodified_lm/graspit/src/worldElementFactory.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/graspit/src/worldElementFactory.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
grasp_generation/graspitmodified_lm/graspit/src/worldElementFactory.cpp
KraftOreo/EBM_Hand
9ab1722c196b7eb99b4c3ecc85cef6e8b1887053
[ "MIT" ]
null
null
null
//###################################################################### // // GraspIt! // Copyright (C) 2002-2009 Columbia University in the City of New York. // All rights reserved. // // GraspIt! is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // GraspIt! is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with GraspIt!. If not, see <http://www.gnu.org/licenses/>. // // Author(s): Andrew T. Miller and Matei T. Ciocarlie // // $Id: worldElement.h,v 1.17 2009/06/18 20:41:02 saint Exp $ // //###################################################################### #include "graspit/worldElementFactory.h" /* Since we are using a class down here to register all the built in types at runtime, we have to include all relevant headers here. Maybe we can find a better solution at some point. */ #include "graspit/robot.h" #include "graspit/body.h" #include "graspit/robot.h" #include "graspit/robots/humanHand.h" #include "graspit/robots/robonaut.h" #include "graspit/robots/pr2Gripper.h" #include "graspit/robots/m7.h" #include "graspit/robots/m7tool.h" #include "graspit/robots/barrett.h" #include "graspit/robots/shadow.h" #include "graspit/robots/puma560.h" #include "graspit/robots/mcGrip.h" #include "graspit/robots/robotiq.h" WorldElementFactory::~WorldElementFactory() { for (std::map<std::string, WorldElementCreator *>::iterator it = mCreators.begin(); it != mCreators.end(); it++) { delete it->second; } } WorldElement * WorldElementFactory::createElement(std::string elementType, World *parent, const char *name) { std::map<std::string, WorldElementCreator *>::iterator it = mCreators.find(elementType); if (it == mCreators.end()) { return NULL; } return (*(it->second))(parent, name); } void WorldElementFactory::registerCreator(std::string elementType, WorldElementCreator *creator) { mCreators[elementType] = creator; } void WorldElementFactory::registerBuiltinCreators() { REGISTER_CREATOR("Body", Body); REGISTER_CREATOR("GraspableBody", GraspableBody); REGISTER_CREATOR("Robot", Robot); REGISTER_CREATOR("Hand", Hand); REGISTER_CREATOR("Puma560", Puma560); REGISTER_CREATOR("Barrett", Barrett); REGISTER_CREATOR("Robonaut", Robonaut); REGISTER_CREATOR("Pr2Gripper", Pr2Gripper); REGISTER_CREATOR("Pr2Gripper2010", Pr2Gripper2010); REGISTER_CREATOR("M7", M7); REGISTER_CREATOR("M7Tool", M7Tool); REGISTER_CREATOR("HumanHand", HumanHand); REGISTER_CREATOR("Shadow", Shadow); REGISTER_CREATOR("McGrip", McGrip); REGISTER_CREATOR("RobotIQ", RobotIQ); }
34.264368
114
0.702113
KraftOreo
efb0162355995140ed09d23da8d405bfd8ef2e39
2,449
cpp
C++
src/shaders/basic_shaders.cpp
Wei-Parker-Guo/RayTracer
3312c5fc73d7d175818f94dcca66b87a0222aad4
[ "MIT" ]
1
2021-06-19T07:53:22.000Z
2021-06-19T07:53:22.000Z
src/shaders/basic_shaders.cpp
Wei-Parker-Guo/RayTracer
3312c5fc73d7d175818f94dcca66b87a0222aad4
[ "MIT" ]
null
null
null
src/shaders/basic_shaders.cpp
Wei-Parker-Guo/RayTracer
3312c5fc73d7d175818f94dcca66b87a0222aad4
[ "MIT" ]
null
null
null
#include "basic_shaders.h" /* generate lambertian shade with another light source * equation: c = cr(ca + clmax(0, n.l)) */ void gen_lambert_shade(const vec3 ca, const vec3 cr, const vec3 cl, const vec3 n, const vec3 l, vec3 c){ //reflectance float r = std::max(0.0f, vec3_mul_inner(n,l)); vec3_scale(c, cl, r); vec3_add(c, c, ca); //apply reflect fraction vec3_fraction(c, cr, c); } /* generate phong shade based on a precalculated lambertian shade equation: c = clambert + clcpmax(e.r)^p */ void gen_phong_shade(const vec3 cl, const vec3 cp, const vec3 l, const vec3 e, const vec3 n, const int p, vec3 clambert){ //calculate r vec3 r; vec3_scale( r, n, 2.0f*vec3_mul_inner(l,n) ); vec3_sub(r, r, l); vec3_norm(r,r); //calculate shade vec3 cphong; vec3_scale(cphong, cp, fast_pow(std::max(0.0f,vec3_mul_inner(e,r)),p)); vec3_fraction(cphong, cl, cphong); vec3_add(clambert, clambert, cphong); vec3_cull(clambert); } /* generate anisotropic phong shade by dividing the normal into uv directions and calculating specular based on the Ward Anisotropic Distribution Model (a BRDF), finally adding the lambertian base shade. Notice this can't use our fast_pow since the exponential is float. The formula is referenced from this url: https://en.wikibooks.org/wiki/GLSL_Programming/Unity/Brushed_Metal */ void gen_WARD_anisotropic_phong_shade(const vec3 cl, const vec3 cp, const vec3 l, const vec3 e, const vec3 n, const float pu, const float pv, const float y, vec3 clambert){ //calculate h vec3 h; vec3_add(h, e, l); vec3_norm(h,h); //calculate u and v unit vector vec3 v; vec3 y_v = {0.0f, y, 0.0f}; vec3_scale(v, n, vec3_mul_inner(n,y_v)); vec3_sub(v, y_v, v); vec3_norm(v,v); vec3 u; vec3_mul_cross(u, v, n); vec3_norm(u,u); //calculate kspecular vec3 kspec; vec3_scale(kspec, cp, sqrt( std::max(0.0f, vec3_mul_inner(n,l) / vec3_mul_inner(n,l)*vec3_mul_inner(n,e)) )); //first term of the multiplication vec3_scale(kspec, kspec, 1.0f / (4.0f*PI*pu*pv) ); //second term vec3_scale(kspec, kspec, exp( -2.0f * (sqr(vec3_mul_inner(h,u)/pu) + sqr(vec3_mul_inner(h,v)/pv)) / (1.0f+vec3_mul_inner(h,n)) ) ); //thrid term vec3_fraction(kspec, kspec, cl); //control one more time by light color //add specular to lambertian shade vec3_add(clambert, clambert, kspec); vec3_cull(clambert); }
38.265625
172
0.684361
Wei-Parker-Guo
efb1e3b88c3e0fc5e6fb5df3c558b4c61feb32d7
918
cpp
C++
CommandLine/IO_L.cpp
AnuragNtl/QwikProjSearch
6eb34a87a22f8cd8dfa07aa0691b86c53f0cf54a
[ "Apache-2.0" ]
null
null
null
CommandLine/IO_L.cpp
AnuragNtl/QwikProjSearch
6eb34a87a22f8cd8dfa07aa0691b86c53f0cf54a
[ "Apache-2.0" ]
7
2020-09-06T23:09:44.000Z
2022-03-02T05:15:08.000Z
CommandLine/IO_L.cpp
AnuragNtl/QwikProjSearch
6eb34a87a22f8cd8dfa07aa0691b86c53f0cf54a
[ "Apache-2.0" ]
null
null
null
#include "IO_L.h" #include <boost/filesystem/path.hpp> using namespace ProjSearch; IoL :: IoL() {} bool IoL :: fileExists(string filePath) const { return boost :: filesystem :: exists(filePath); } bool IoL :: isFile(string filePath) const { return boost :: filesystem :: is_regular(filePath) || boost :: filesystem :: is_symlink(filePath) || boost :: filesystem :: is_other(filePath); } bool IoL :: isDirectory(string filePath) const { return boost :: filesystem :: is_directory(filePath); } vector<string> IoL :: listDirectory(string filePath) const { if(!isDirectory(filePath)) { throw ProjReadException(); } vector<string> fileList; boost :: filesystem :: path directoryPath(filePath); for(boost :: filesystem :: directory_iterator it(directoryPath); it != boost :: filesystem :: directory_iterator(); it++) { fileList.push_back(it->path().filename().string()); } return fileList; }
26.228571
66
0.701525
AnuragNtl
efb24ca4a71a7cc0a1f7a0bd5c90f459bb8b2996
3,164
hpp
C++
include/memory/hadesmem/detail/winapi.hpp
phlip9/hadesmem
59e13a92c05918b8c842141fd5cac1ed390cd79e
[ "MIT" ]
19
2017-10-19T23:13:11.000Z
2022-03-29T11:37:26.000Z
include/memory/hadesmem/detail/winapi.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
null
null
null
include/memory/hadesmem/detail/winapi.hpp
Bia10/hadesmem
b91bce37611d0e939a55d9490c49780f9f0f3bff
[ "MIT" ]
10
2018-04-04T07:55:16.000Z
2021-11-23T20:22:43.000Z
// Copyright (C) 2010-2015 Joshua Boyce // See the file COPYING for copying permission. #pragma once #include <windows.h> #include <hadesmem/detail/assert.hpp> #include <hadesmem/detail/smart_handle.hpp> #include <hadesmem/error.hpp> namespace hadesmem { namespace detail { inline SYSTEM_INFO GetSystemInfo() { SYSTEM_INFO sys_info{}; ::GetSystemInfo(&sys_info); return sys_info; } inline bool IsWoW64Process(HANDLE handle) { BOOL is_wow64 = FALSE; if (!::IsWow64Process(handle, &is_wow64)) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"IsWoW64Process failed."} << ErrorCodeWinLast{last_error}); } return is_wow64 != FALSE; } inline detail::SmartHandle OpenProcess(DWORD id, DWORD access) { HANDLE const handle = ::OpenProcess(access, FALSE, id); if (!handle) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"OpenProcess failed."} << ErrorCodeWinLast{last_error}); } return detail::SmartHandle(handle); } inline detail::SmartHandle OpenProcessAllAccess(DWORD id) { return OpenProcess(id, PROCESS_ALL_ACCESS); } inline detail::SmartHandle OpenThread(DWORD id, DWORD access) { HANDLE const handle = ::OpenThread(access, FALSE, id); if (!handle) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"OpenThread failed."} << ErrorCodeWinLast{last_error}); } return detail::SmartHandle(handle); } inline detail::SmartHandle OpenThreadAllAccess(DWORD id) { return OpenThread(id, THREAD_ALL_ACCESS); } inline detail::SmartHandle DuplicateHandle(HANDLE handle) { HADESMEM_DETAIL_ASSERT(handle != nullptr); HANDLE new_handle = nullptr; if (!::DuplicateHandle(::GetCurrentProcess(), handle, ::GetCurrentProcess(), &new_handle, 0, FALSE, DUPLICATE_SAME_ACCESS)) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION(Error{} << ErrorString{"DuplicateHandle failed."} << ErrorCodeWinLast{last_error}); } return detail::SmartHandle(new_handle); } inline std::wstring QueryFullProcessImageName(HANDLE handle) { HADESMEM_DETAIL_ASSERT(handle != nullptr); std::vector<wchar_t> path(HADESMEM_DETAIL_MAX_PATH_UNICODE); DWORD path_len = static_cast<DWORD>(path.size()); if (!::QueryFullProcessImageNameW(handle, 0, path.data(), &path_len)) { DWORD const last_error = ::GetLastError(); HADESMEM_DETAIL_THROW_EXCEPTION( Error{} << ErrorString{"QueryFullProcessImageName failed."} << ErrorCodeWinLast{last_error}); } return path.data(); } } }
27.754386
81
0.611252
phlip9
efb6f422e008221c2f7d98e066c8aa6ae7bbf426
8,039
cc
C++
tensorflow/compiler/xla/shape_tree_test.cc
xincao79/tensorflow
7fa0cf39f854d5fdaaa19ad6425dfed02f5fea64
[ "Apache-2.0" ]
13
2017-02-22T02:20:06.000Z
2018-06-06T04:18:03.000Z
tensorflow/compiler/xla/shape_tree_test.cc
xincao79/tensorflow
7fa0cf39f854d5fdaaa19ad6425dfed02f5fea64
[ "Apache-2.0" ]
3
2020-03-24T18:15:52.000Z
2021-02-02T22:28:38.000Z
tensorflow/compiler/xla/shape_tree_test.cc
xincao79/tensorflow
7fa0cf39f854d5fdaaa19ad6425dfed02f5fea64
[ "Apache-2.0" ]
38
2017-04-28T04:15:48.000Z
2019-09-28T05:11:46.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow/compiler/xla/shape_tree.h" #include "tensorflow/compiler/xla/shape_util.h" #include "tensorflow/compiler/xla/test.h" #include "tensorflow/compiler/xla/xla_data.pb.h" namespace xla { namespace { class ShapeTreeTest : public ::testing::Test { protected: ShapeTreeTest() { array_shape_ = ShapeUtil::MakeShape(F32, {42, 42, 123}); tuple_shape_ = ShapeUtil::MakeTupleShape({array_shape_, array_shape_, array_shape_}); nested_tuple_shape_ = ShapeUtil::MakeTupleShape( {array_shape_, ShapeUtil::MakeTupleShape({array_shape_, array_shape_}), ShapeUtil::MakeTupleShape( {ShapeUtil::MakeTupleShape({array_shape_, array_shape_}), array_shape_})}); } void TestShapeConstructor(const Shape& shape, int expected_num_nodes); void TestInitValueConstructor(const Shape& shape, int expected_num_nodes); // An array shape (non-tuple). Shape array_shape_; // A three element tuple shape. Shape tuple_shape_; // A nested tuple shape of the following form: (a, (c, d), ((e, f), g)) Shape nested_tuple_shape_; }; TEST_F(ShapeTreeTest, DefaultConstructor) { ShapeTree<int> int_tree; EXPECT_TRUE(ShapeUtil::IsNil(int_tree.shape())); ShapeTree<bool> bool_tree; EXPECT_TRUE(ShapeUtil::IsNil(bool_tree.shape())); } void ShapeTreeTest::TestShapeConstructor(const Shape& shape, int expected_num_nodes) { ShapeTree<int> int_tree(shape); int num_nodes = 0; TF_CHECK_OK(int_tree.ForEachElement( [&num_nodes](const ShapeIndex& /*index*/, bool /*is_leaf*/, int data) { EXPECT_EQ(0, data); ++num_nodes; return Status::OK(); })); EXPECT_EQ(expected_num_nodes, num_nodes); ShapeTree<bool> bool_tree(shape); num_nodes = 0; TF_CHECK_OK(bool_tree.ForEachElement( [&num_nodes](const ShapeIndex& /*index*/, bool /*is_leaf*/, bool data) { EXPECT_EQ(false, data); ++num_nodes; return Status::OK(); })); EXPECT_EQ(expected_num_nodes, num_nodes); } TEST_F(ShapeTreeTest, ShapeConstructor) { TestShapeConstructor(array_shape_, 1); TestShapeConstructor(tuple_shape_, 4); TestShapeConstructor(nested_tuple_shape_, 10); } void ShapeTreeTest::TestInitValueConstructor(const Shape& shape, int expected_num_nodes) { ShapeTree<int> tree(shape, 42); int num_nodes = 0; TF_CHECK_OK(tree.ForEachElement( [&num_nodes](const ShapeIndex& /*index*/, bool /*is_leaf*/, int data) { EXPECT_EQ(42, data); ++num_nodes; return Status::OK(); })); EXPECT_EQ(expected_num_nodes, num_nodes); num_nodes = 0; TF_CHECK_OK(tree.ForEachMutableElement( [&num_nodes](const ShapeIndex& /*index*/, bool /*is_leaf*/, int* data) { EXPECT_EQ(42, *data); *data = num_nodes; ++num_nodes; return Status::OK(); })); EXPECT_EQ(expected_num_nodes, num_nodes); num_nodes = 0; TF_CHECK_OK(tree.ForEachElement( [&num_nodes](const ShapeIndex& /*index*/, bool /*is_leaf*/, int data) { EXPECT_EQ(num_nodes, data); ++num_nodes; return Status::OK(); })); EXPECT_EQ(expected_num_nodes, num_nodes); } TEST_F(ShapeTreeTest, InitValueConstructor) { TestInitValueConstructor(array_shape_, 1); TestInitValueConstructor(tuple_shape_, 4); TestInitValueConstructor(nested_tuple_shape_, 10); } TEST_F(ShapeTreeTest, ArrayShape) { ShapeTree<int> shape_tree{array_shape_}; *shape_tree.mutable_element({}) = 42; EXPECT_EQ(42, shape_tree.element({})); *shape_tree.mutable_element({}) = 123; EXPECT_EQ(123, shape_tree.element({})); EXPECT_TRUE(ShapeUtil::Compatible(array_shape_, shape_tree.shape())); // Test the copy constructor. ShapeTree<int> copy{shape_tree}; EXPECT_EQ(123, copy.element({})); // Mutate the copy, and ensure the original doesn't change. *copy.mutable_element({}) = 99; EXPECT_EQ(99, copy.element({})); EXPECT_EQ(123, shape_tree.element({})); // Test the assignment operator. copy = shape_tree; EXPECT_EQ(123, copy.element({})); } TEST_F(ShapeTreeTest, TupleShape) { ShapeTree<int> shape_tree{tuple_shape_}; *shape_tree.mutable_element({}) = 1; *shape_tree.mutable_element({0}) = 42; *shape_tree.mutable_element({1}) = 123; *shape_tree.mutable_element({2}) = -100; EXPECT_EQ(1, shape_tree.element({})); EXPECT_EQ(42, shape_tree.element({0})); EXPECT_EQ(123, shape_tree.element({1})); EXPECT_EQ(-100, shape_tree.element({2})); EXPECT_TRUE(ShapeUtil::Compatible(tuple_shape_, shape_tree.shape())); // Sum all elements in the shape. int sum = 0; TF_CHECK_OK(shape_tree.ForEachElement( [&sum](const ShapeIndex& /*index*/, bool /*is_leaf*/, int data) { sum += data; return Status::OK(); })); EXPECT_EQ(66, sum); // Test the copy constructor. ShapeTree<int> copy{shape_tree}; EXPECT_EQ(1, copy.element({})); EXPECT_EQ(42, copy.element({0})); EXPECT_EQ(123, copy.element({1})); EXPECT_EQ(-100, copy.element({2})); // Write zero to all data elements. TF_CHECK_OK(shape_tree.ForEachMutableElement( [&sum](const ShapeIndex& /*index*/, bool /*is_leaf*/, int* data) { *data = 0; return Status::OK(); })); EXPECT_EQ(0, shape_tree.element({})); EXPECT_EQ(0, shape_tree.element({0})); EXPECT_EQ(0, shape_tree.element({1})); EXPECT_EQ(0, shape_tree.element({2})); EXPECT_EQ(1, copy.element({})); EXPECT_EQ(42, copy.element({0})); EXPECT_EQ(123, copy.element({1})); EXPECT_EQ(-100, copy.element({2})); // Test the assignment operator. copy = shape_tree; EXPECT_EQ(0, copy.element({})); EXPECT_EQ(0, copy.element({0})); EXPECT_EQ(0, copy.element({1})); EXPECT_EQ(0, copy.element({2})); } TEST_F(ShapeTreeTest, NestedTupleShape) { ShapeTree<int> shape_tree{nested_tuple_shape_}; *shape_tree.mutable_element({0}) = 42; *shape_tree.mutable_element({1, 1}) = 123; *shape_tree.mutable_element({2, 0, 1}) = -100; EXPECT_EQ(42, shape_tree.element({0})); EXPECT_EQ(123, shape_tree.element({1, 1})); EXPECT_EQ(-100, shape_tree.element({2, 0, 1})); EXPECT_TRUE(ShapeUtil::Compatible(nested_tuple_shape_, shape_tree.shape())); // Test the copy constructor. ShapeTree<int> copy{shape_tree}; EXPECT_EQ(42, copy.element({0})); EXPECT_EQ(123, copy.element({1, 1})); EXPECT_EQ(-100, copy.element({2, 0, 1})); // Mutate the copy, and ensure the original doesn't change. *copy.mutable_element({0}) = 1; *copy.mutable_element({1, 1}) = 2; *copy.mutable_element({2, 0, 1}) = 3; EXPECT_EQ(1, copy.element({0})); EXPECT_EQ(2, copy.element({1, 1})); EXPECT_EQ(3, copy.element({2, 0, 1})); EXPECT_EQ(42, shape_tree.element({0})); EXPECT_EQ(123, shape_tree.element({1, 1})); EXPECT_EQ(-100, shape_tree.element({2, 0, 1})); // Test the assignment operator. copy = shape_tree; EXPECT_EQ(42, copy.element({0})); EXPECT_EQ(123, copy.element({1, 1})); EXPECT_EQ(-100, copy.element({2, 0, 1})); } TEST_F(ShapeTreeTest, InvalidIndexingTuple) { ShapeTree<int> shape_tree{tuple_shape_}; EXPECT_DEATH(shape_tree.element({4}), ""); } TEST_F(ShapeTreeTest, InvalidIndexingNestedTuple) { ShapeTree<int> shape_tree{nested_tuple_shape_}; EXPECT_DEATH(shape_tree.element({0, 0}), ""); } } // namespace } // namespace xla
32.156
80
0.673964
xincao79
efba47f84fc744499023300ed0881c6224ce2206
365
hxx
C++
include/usagi/environment_special_support.hxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
2
2016-11-20T04:59:17.000Z
2017-02-13T01:44:37.000Z
include/usagi/environment_special_support.hxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
3
2015-09-28T12:00:02.000Z
2015-09-28T12:03:21.000Z
include/usagi/environment_special_support.hxx
usagi/usagi
2d57d21eeb92eadfdf4154a3e470aebfc3e388e5
[ "MIT" ]
3
2017-07-02T06:09:47.000Z
2018-07-09T01:00:57.000Z
/// @file /// @brief 処理系依存の特別な対応 /// @attention 必要に応じて最も優先的にこのヘッダーファイルをインクルードして用いる #pragma once #include "environment_special_support/winsock.hxx" #include "environment_special_support/windows.hxx" #include "environment_special_support/ciso646.hxx" #include "environment_special_support/use_math_defines.hxx" #include "environment_special_support/emscripten.hxx"
30.416667
59
0.835616
usagi
efbc7aaac6633655864e11f11088b8a45cff837f
787
cpp
C++
engine/src/concurrency/semaphore.cpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
44
2017-01-25T05:57:21.000Z
2021-09-21T13:36:49.000Z
engine/src/concurrency/semaphore.cpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
1
2017-04-05T01:50:18.000Z
2017-04-05T01:50:18.000Z
engine/src/concurrency/semaphore.cpp
ValtoForks/Terminus-Engine
0c7381af84736ec7b029977843590453cde64b1d
[ "MIT" ]
3
2017-09-28T08:11:00.000Z
2019-03-27T03:38:47.000Z
#include <concurrency/semaphore.hpp> TE_BEGIN_TERMINUS_NAMESPACE #if defined(_WIN32) Semaphore::Semaphore() { m_semaphore = CreateSemaphore(NULL, 0, 256000, NULL); } Semaphore::~Semaphore() { CloseHandle(m_semaphore); } void Semaphore::signal() { ReleaseSemaphore(m_semaphore, 1, NULL); } void Semaphore::wait() { WaitForSingleObject(m_semaphore, INFINITE); } #else Semaphore::Semaphore() { assert(pthread_mutex_init(&m_lock, NULL) == 0); assert(pthread_cond_init(&m_cond, NULL) == 0); } Semaphore::~Semaphore() { pthread_cond_destroy(&m_cond); pthread_mutex_destroy(&m_lock); } void Semaphore::signal() { pthread_cond_signal(&m_cond); } void Semaphore::wait() { pthread_cond_wait(&m_cond, &m_lock); } #endif TE_END_TERMINUS_NAMESPACE
14.849057
57
0.710292
ValtoForks
efbe30af83bbe916246b4c5d45f11e020efe8ef4
2,393
cpp
C++
Engine/Source/Runtime/Core/FileSystem/FileUtils.cpp
1992please/NullEngine
8f5f124e9718b8d6627992bb309cf0f0d106d07a
[ "Apache-2.0" ]
null
null
null
Engine/Source/Runtime/Core/FileSystem/FileUtils.cpp
1992please/NullEngine
8f5f124e9718b8d6627992bb309cf0f0d106d07a
[ "Apache-2.0" ]
null
null
null
Engine/Source/Runtime/Core/FileSystem/FileUtils.cpp
1992please/NullEngine
8f5f124e9718b8d6627992bb309cf0f0d106d07a
[ "Apache-2.0" ]
null
null
null
#include "NullPCH.h" #include "FileUtils.h" #include "Core/Application/Application.h" #include "Core/Application/ApplicationWindow.h" bool FFileUtils::OpenFileDialog(const FString& Starting, const char* InFilter, FString& OutFilePath) { char OutFileName[256] = { 0 }; OPENFILENAMEA OFN; FMemory::Memzero(&OFN, sizeof(OFN)); OFN.lStructSize = sizeof(OPENFILENAME); OFN.hwndOwner = (HWND)FApplication::GetApplication()->GetWindow()->GetOSWindow(); //OFN.hInstance; OFN.lpstrFilter = InFilter; //OFN.lpstrCustomFilter; //OFN.nMaxCustFilter; OFN.nFilterIndex = 1; OFN.lpstrFile = OutFileName; OFN.nMaxFile = sizeof(OutFileName); OFN.lpstrFileTitle; //OFN.nMaxFileTitle; OFN.lpstrInitialDir = Starting.GetCharArray().GetData(); //OFN.lpstrTitle; OFN.Flags = OFN_DONTADDTORECENT | OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST | OFN_HIDEREADONLY; //OFN.nFileOffset; //OFN.nFileExtension; //OFN.lpstrDefExt; //OFN.lCustData; //OFN.lpfnHook; //OFN.lpTemplateName; //OFN.lpEditInfo; //OFN.lpstrPrompt; //OFN.pvReserved; //OFN.dwReserved; //OFN.FlagsEx; if (GetOpenFileNameA(&OFN) != 0) { OutFilePath = OFN.lpstrFile; return true; } return false; } bool FFileUtils::SaveFileDialog(const FString& Starting, const char* InFilter, FString& OutFilePath) { char OutFileName[256] = { 0 }; OPENFILENAMEA OFN; FMemory::Memzero(&OFN, sizeof(OFN)); OFN.lStructSize = sizeof(OPENFILENAME); OFN.hwndOwner = (HWND)FApplication::GetApplication()->GetWindow()->GetOSWindow(); //OFN.hInstance; OFN.lpstrFilter = InFilter; //OFN.lpstrCustomFilter; //OFN.nMaxCustFilter; OFN.nFilterIndex = 1; OFN.lpstrFile = OutFileName; OFN.nMaxFile = sizeof(OutFileName); OFN.lpstrFileTitle; //OFN.nMaxFileTitle; OFN.lpstrInitialDir = Starting.GetCharArray().GetData(); //OFN.lpstrTitle; OFN.Flags = OFN_DONTADDTORECENT | OFN_PATHMUSTEXIST | OFN_NOCHANGEDIR | OFN_HIDEREADONLY; //OFN.nFileOffset; //OFN.nFileExtension; OFN.lpstrDefExt = FCString::StrChar(InFilter, '\0') + 1; //OFN.lCustData; //OFN.lpfnHook; //OFN.lpTemplateName; //OFN.lpEditInfo; //OFN.lpstrPrompt; //OFN.pvReserved; //OFN.dwReserved; //OFN.FlagsEx; if (GetSaveFileNameA(&OFN) != 0) { OutFilePath = OFN.lpstrFile; return true; } return false; } FString FFileUtils::GetCurrentDirectory() { char currentDir[256] = { 0 }; GetCurrentDirectoryA(sizeof(currentDir), currentDir); return currentDir; }
26.588889
100
0.735896
1992please
efbe3381f36230772b5ed4d20dca744b281ce35b
857
hpp
C++
Merlin/Merlin/Core/layer_stack.hpp
kshatos/MerlinEngine
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
[ "MIT" ]
null
null
null
Merlin/Merlin/Core/layer_stack.hpp
kshatos/MerlinEngine
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
[ "MIT" ]
null
null
null
Merlin/Merlin/Core/layer_stack.hpp
kshatos/MerlinEngine
a7eb9b39b6cb8a02bef0f739db25268a7a06e215
[ "MIT" ]
null
null
null
#ifndef LAYER_STACK_HPP #define LAYER_STACK_HPP #include <vector> #include <deque> #include"Merlin/Core/layer.hpp" namespace Merlin { class LayerStack { std::deque<std::shared_ptr<Layer>> m_layers; public: void PushFront(std::shared_ptr<Layer> layer); void PushBack(std::shared_ptr<Layer> layer); void PopFront(); void PopBack(); void PopLayer(std::shared_ptr<Layer> layer); inline std::deque<std::shared_ptr<Layer>>::iterator begin() { return m_layers.begin(); } inline std::deque<std::shared_ptr<Layer>>::iterator end() { return m_layers.end(); } inline std::deque<std::shared_ptr<Layer>>::const_iterator begin() const { return m_layers.begin(); } inline std::deque<std::shared_ptr<Layer>>::const_iterator end() const { return m_layers.end(); } }; } #endif
32.961538
108
0.660443
kshatos
efc1efa71b2b66dfe9a16ce0a2cc76f5cf1d5b4a
727
cc
C++
algorithms/image/fill_holes/boost_python/fill_holes_ext.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
58
2015-10-15T09:28:20.000Z
2022-03-28T20:09:38.000Z
algorithms/image/fill_holes/boost_python/fill_holes_ext.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
1,741
2015-11-24T08:17:02.000Z
2022-03-31T15:46:42.000Z
algorithms/image/fill_holes/boost_python/fill_holes_ext.cc
TiankunZhou/dials
bd5c95b73c442cceb1c61b1690fd4562acf4e337
[ "BSD-3-Clause" ]
45
2015-10-14T13:44:16.000Z
2022-03-22T14:45:56.000Z
/* * filter_ext.cc * * Copyright (C) 2013 Diamond Light Source * * Author: James Parkhurst * * This code is distributed under the BSD license, a copy of which is * included in the root directory of this package. */ #include <boost/python.hpp> #include <boost/python/def.hpp> #include <dials/algorithms/image/fill_holes/simple.h> namespace dials { namespace algorithms { namespace boost_python { using namespace boost::python; BOOST_PYTHON_MODULE(dials_algorithms_image_fill_holes_ext) { def("simple_fill", &simple_fill, (arg("data"), arg("mask"))); def( "diffusion_fill", &diffusion_fill, (arg("data"), arg("mask"), arg("niter") = 10)); } }}} // namespace dials::algorithms::boost_python
26.925926
88
0.701513
TiankunZhou
efc4437cbd04243327b3fe9b9f313d0a0b1178d3
8,694
hpp
C++
SDK/ARKSurvivalEvolved_WeapCrossbow_Zipline_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
10
2020-02-17T19:08:46.000Z
2021-07-31T11:07:19.000Z
SDK/ARKSurvivalEvolved_WeapCrossbow_Zipline_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
9
2020-02-17T18:15:41.000Z
2021-06-06T19:17:34.000Z
SDK/ARKSurvivalEvolved_WeapCrossbow_Zipline_classes.hpp
2bite/ARK-SDK
c38ca9925309516b2093ad8c3a70ed9489e1d573
[ "MIT" ]
3
2020-07-22T17:42:07.000Z
2021-06-19T17:16:13.000Z
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_WeapCrossbow_Zipline_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass WeapCrossbow_Zipline.WeapCrossbow_Zipline_C // 0x0118 (0x0F70 - 0x0E58) class AWeapCrossbow_Zipline_C : public AWeapCrossbow_C { public: class USceneComponent* PreviewCableAttach; // 0x0E58(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class USceneComponent* PreviewTargetPoint; // 0x0E60(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class UStaticMeshComponent* ProjectileMesh1P; // 0x0E68(0x0008) (BlueprintVisible, ZeroConstructor, IsPlainOldData) class AProjZiplineAnchor_C* PendingAnchor; // 0x0E70(0x0008) (Edit, BlueprintVisible, Net, ZeroConstructor, DisableEditOnTemplate, DisableEditOnInstance, IsPlainOldData) float MaxAnchorDistance; // 0x0E78(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData00[0x4]; // 0x0E7C(0x0004) MISSED OFFSET class UPrimalCableComponent* PreviewCable; // 0x0E80(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) int Steps; // 0x0E88(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float StepTime; // 0x0E8C(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float TracesPerCentimeter; // 0x0E90(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData01[0x4]; // 0x0E94(0x0004) MISSED OFFSET class UParticleSystemComponent* PreviewEmitter; // 0x0E98(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) class UParticleSystem* PreviewEmitterParticle; // 0x0EA0(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FVector PreviewHitLocation; // 0x0EA8(0x000C) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) float PreviewInterpSpeed; // 0x0EB4(0x0004) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) class UStaticMeshComponent* PreviewMeshComp; // 0x0EB8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) struct FRotator NewVar; // 0x0EC0(0x000C) (Edit, BlueprintVisible, ZeroConstructor, IsPlainOldData) float MinAnchorDistance; // 0x0ECC(0x0004) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool PreviewHitValid; // 0x0ED0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData02[0x7]; // 0x0ED1(0x0007) MISSED OFFSET class UMaterialInstanceDynamic* PreviewCableMID; // 0x0ED8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool UsePreviewColorChange; // 0x0EE0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) unsigned char UnknownData03[0x7]; // 0x0EE1(0x0007) MISSED OFFSET class UMaterialInstanceDynamic* PreviewMeshMID; // 0x0EE8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool Temp_bool_IsClosed_Variable; // 0x0EF0(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool Temp_bool_IsClosed_Variable2; // 0x0EF1(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool Temp_bool_Has_Been_Initd_Variable; // 0x0EF2(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool Temp_bool_Has_Been_Initd_Variable2; // 0x0EF3(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool Temp_bool_Whether_the_gate_is_currently_open_or_close_Variable;// 0x0EF4(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool Temp_bool_Has_Been_Initd_Variable3; // 0x0EF5(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData04[0x2]; // 0x0EF6(0x0002) MISSED OFFSET class APlayerController* CallFunc_GetOwnerController_ReturnValue; // 0x0EF8(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) class AShooterPlayerController* K2Node_DynamicCast_AsShooterPlayerController; // 0x0F00(0x0008) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool K2Node_DynamicCast_CastSuccess; // 0x0F08(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool CallFunc_IsLocallyOwned_ReturnValue; // 0x0F09(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) bool Temp_bool_IsClosed_Variable3; // 0x0F0A(0x0001) (ZeroConstructor, Transient, DuplicateTransient, IsPlainOldData) unsigned char UnknownData05[0x5]; // 0x0F0B(0x0005) MISSED OFFSET struct UObject_FTransform CallFunc_AddComponent_RelativeTransform_AddComponentDefaultTransform;// 0x0F10(0x0030) (Transient, DuplicateTransient, IsPlainOldData) struct UObject_FTransform CallFunc_AddComponent_RelativeTransform2_AddComponentDefaultTransform;// 0x0F40(0x0030) (Transient, DuplicateTransient, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass WeapCrossbow_Zipline.WeapCrossbow_Zipline_C"); return ptr; } void STATIC_ZiplineObstructionTrace(const struct FVector& Start, bool* Hit); void BPHandleMeleeAttack(); void IsValidHitLocationForAttachment(struct FHitResult* Hit, bool* IsValidHit); bool BPWeaponCanFire(); void Get_ZipProjectile_Default_Object(class AProjZiplineAnchor_C** AsProjArrow_Zipline_Bolt_C); void Update_Preview_Cable(); void ReceiveTick(float* DeltaSeconds); void ReceiveDestroyed(); void UserConstructionScript(); void ReloadNow(); void ResetReload(); void NoPlacementNoti(); void BPFiredWeapon(); void ExecuteUbergraph_WeapCrossbow_Zipline(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
95.538462
236
0.560271
2bite
efc54fffed30f34b1306377ae37acada8fc33496
1,638
hpp
C++
Source/Console/ConsoleDefinition.hpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
6
2017-12-31T17:28:40.000Z
2021-12-04T06:11:34.000Z
Source/Console/ConsoleDefinition.hpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
Source/Console/ConsoleDefinition.hpp
gunstarpl/Game-Engine-12-2013
bfc53f5c998311c17e97c1b4d65792d615c51d36
[ "MIT", "Unlicense" ]
null
null
null
#pragma once #include "Precompiled.hpp" // // Console Definition // Base class used by console variable/command classes. // class ConsoleDefinition : public NonCopyable { protected: ConsoleDefinition(std::string name, std::string description); public: virtual ~ConsoleDefinition(); // Called when a definition has been executed in the console. virtual void Execute(std::string arguments) = 0; // Accessor methods. std::string GetName() const { return m_name; } std::string GetDescription() const { return m_description; } bool HasExecuted() const { return m_executed; } bool HasChanged() const { return m_changed; } protected: // Sets intermediate states. void Executed(); void Changed(); // Resets intermediate states. void ResetIntermediateState(); private: std::string m_name; std::string m_description; bool m_executed; bool m_changed; public: // Use this string as a name to mark definition as internal. static const char* Internal; // Call at the very beginning of main() to finalize // static instances of this class, so static and normal // instanced can be distinguished. static void FinalizeStatic(); private: // Allow console system to register static definitions. friend class ConsoleSystem; // List of static definitions that were created // before the console system has been initialized. ConsoleDefinition* m_staticNext; static ConsoleDefinition* m_staticHead; static bool m_staticDone; };
21.552632
65
0.666667
gunstarpl
efcd134f4ff70b0892b244d57fab43f0fd97c732
882
cpp
C++
src/engine/keen/vorticon/ai/CDoor.cpp
rikimbo/Commander-Genius
0b56993f4c36be8369cfd48f15aa2b9ee74a734d
[ "X11" ]
137
2015-01-01T21:04:51.000Z
2022-03-30T01:41:10.000Z
src/engine/keen/vorticon/ai/CDoor.cpp
rikimbo/Commander-Genius
0b56993f4c36be8369cfd48f15aa2b9ee74a734d
[ "X11" ]
154
2015-01-01T16:34:39.000Z
2022-01-28T14:14:45.000Z
src/engine/keen/vorticon/ai/CDoor.cpp
rikimbo/Commander-Genius
0b56993f4c36be8369cfd48f15aa2b9ee74a734d
[ "X11" ]
35
2015-03-24T02:20:54.000Z
2021-05-13T11:44:22.000Z
#include "CDoor.h" #include "graphics/GsGraphics.h" CDoor::CDoor(CMap *pmap, Uint32 x, Uint32 y, Uint32 doorspriteID): CVorticonSpriteObject(pmap, x, y, OBJ_DOOR, 0) { mSpriteIdx=doorspriteID; GsSprite &Doorsprite = gGraphics.getSprite(mSprVar,mSpriteIdx); timer = 0; Doorsprite.setHeight(32); inhibitfall = true; x = getXPosition()>>CSF; y = getYPosition()>>CSF; mpMap->redrawAt(x, y); mpMap->redrawAt(x, y+1); } void CDoor::process() { GsSprite &Doorsprite = gGraphics.getSprite(mSprVar,mSpriteIdx); if (timer > DOOR_OPEN_SPEED) { // TODO: Create a flag for mods in which the door can be opened in another direction //if (DoorOpenDir==DOWN) moveDown(1<<STC); Doorsprite.setHeight(Doorsprite.getHeight()-1); timer = 0; if (Doorsprite.getHeight() == 0) { exists = false; return; } } else timer++; }
23.210526
87
0.660998
rikimbo
efce684ab6546a13268fe406728c7f1d9dac2484
2,471
cpp
C++
sc-memory/unit_tests/sc-memory/units/test_python.cpp
kroschenko/sc-machine
10a9535b3b9151ed683d351f2d222a95fc078e2b
[ "MIT" ]
null
null
null
sc-memory/unit_tests/sc-memory/units/test_python.cpp
kroschenko/sc-machine
10a9535b3b9151ed683d351f2d222a95fc078e2b
[ "MIT" ]
null
null
null
sc-memory/unit_tests/sc-memory/units/test_python.cpp
kroschenko/sc-machine
10a9535b3b9151ed683d351f2d222a95fc078e2b
[ "MIT" ]
1
2021-12-03T13:20:18.000Z
2021-12-03T13:20:18.000Z
/* * This source file is part of an OSTIS project. For the latest info, see http://ostis.net * Distributed under the MIT License * (See accompanying file COPYING.MIT or copy at http://opensource.org/licenses/MIT) */ #include <thread> #include "test_defines.hpp" #include "catch2/catch.hpp" #include "sc-test-framework/sc_test_unit.hpp" #include "sc-memory/python/sc_python_interp.hpp" #include "sc-memory/python/sc_python_service.hpp" TEST_CASE("Python_interp", "[test python]") { test::ScTestUnit::InitMemory("sc-memory.ini", ""); SECTION("common") { SUBTEST_START("common") { try { py::ScPythonInterpreter::AddModulesPath(SC_TEST_KPM_PYTHON_PATH); py::DummyService testService("sc_tests/test_main.py"); testService.Run(); while (testService.IsRun()) std::this_thread::sleep_for(std::chrono::milliseconds(10)); testService.Stop(); } catch (...) { SC_LOG_ERROR("Test \"common\" failed") } } SUBTEST_END() } test::ScTestUnit::ShutdownMemory(false); } TEST_CASE("Python_clean", "[test python]") { test::ScTestUnit::InitMemory("sc-memory.ini", ""); try { py::ScPythonInterpreter::AddModulesPath(SC_TEST_KPM_PYTHON_PATH); volatile bool passed = true; std::vector<std::unique_ptr<std::thread>> threads; size_t const numTests = 50; threads.resize(numTests); for (size_t i = 0; i < numTests; ++i) { threads[i].reset( new std::thread([&passed]() { py::DummyService testService("sc_tests/test_dummy.py"); try { testService.Run(); } catch (utils::ScException const & ex) { SC_LOG_ERROR(ex.Message()); passed = false; } catch (...) { SC_LOG_ERROR("Unknown error"); passed = false; } })); } for (auto const & t : threads) t->join(); REQUIRE(passed); } catch (...) { SC_LOG_ERROR("Test \"Python_clean\" failed") } test::ScTestUnit::ShutdownMemory(false); }
26.858696
89
0.511938
kroschenko
efd23bca15c3960369a78a0940a30f1313a5aac6
1,009
cpp
C++
jsUnits/jsVelocityResponseSpectrum.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
jsUnits/jsVelocityResponseSpectrum.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
jsUnits/jsVelocityResponseSpectrum.cpp
dnv-opensource/Reflection
27effb850e9f0cc6acc2d48630ee6aa5d75fa000
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2021 DNV AS // // 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 <jsUnits/jsVelocityResponseSpectrum.h> #include <jsUnits/jsUnitClass.h> #include <Units/VelocityResponseSpectrum.h> #include "jsKinematicViscosity.h" using namespace DNVS::MoFa::Units; Runtime::DynamicPhenomenon jsVelocityResponseSpectrum::GetPhenomenon() { return VelocityResponseSpectrumPhenomenon(); } void jsVelocityResponseSpectrum::init(jsTypeLibrary& typeLibrary) { jsUnitClass<jsVelocityResponseSpectrum,DNVS::MoFa::Units::VelocityResponseSpectrum> cls(typeLibrary); if(cls.reinit()) return; cls.ImplicitConstructorConversion(&jsUnitClass<jsVelocityResponseSpectrum,DNVS::MoFa::Units::VelocityResponseSpectrum>::ConstructEquivalentQuantity<jsKinematicViscosity>); cls.ImplicitConstructorConversion([](const jsVelocityResponseSpectrum& val) {return KinematicViscosity(val); }); }
37.37037
174
0.800793
dnv-opensource
efd6998e3ce22d79dddd9d58a4a7fdf8e7051153
5,842
cpp
C++
MfgToolLib/HidDevice.cpp
Koltak/mfgtools
02d9e639ceeda38be0184f3b697a126c5d3f03e7
[ "BSD-3-Clause" ]
null
null
null
MfgToolLib/HidDevice.cpp
Koltak/mfgtools
02d9e639ceeda38be0184f3b697a126c5d3f03e7
[ "BSD-3-Clause" ]
null
null
null
MfgToolLib/HidDevice.cpp
Koltak/mfgtools
02d9e639ceeda38be0184f3b697a126c5d3f03e7
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright 2009-2014, 2016 Freescale Semiconductor, Inc. * * 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 Freescale Semiconductor nor the names of its * contributors may be used to endorse or promote products derived from this * software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * */ #include "stdafx.h" #include "HidDevice.h" //#include "logmgr.h" //#include <Assert.h> HidDevice::HidDevice(DeviceClass * deviceClass, DEVINST devInst, CString path, INSTANCE_HANDLE handle) : Device(deviceClass, devInst, path, handle) , _status(CSW_CMD_PASSED) , _pReadReport(NULL) , _pWriteReport(NULL) , _chipFamily(ChipUnknown) , _habType(HabUnknown) { memset(&_Capabilities, 0, sizeof(_Capabilities)); INT32 err = AllocateIoBuffers(); if (err != ERROR_SUCCESS) { TRACE(_T("HidDevice::InitHidDevie() AllocateIoBuffers fail!\r\n")); } } HidDevice::~HidDevice(void) { FreeIoBuffers(); } void HidDevice::FreeIoBuffers() { if(_pReadReport) { free(_pReadReport); _pReadReport = NULL; } if(_pWriteReport) { free(_pWriteReport); _pWriteReport = NULL; } } typedef UINT (CALLBACK* LPFNDLLFUNC1)(HANDLE, PVOID); typedef UINT (CALLBACK* LPFNDLLFUNC2)(PVOID); // Modiifes _Capabilities member variable // Modiifes _pReadReport member variable // Modiifes _pWriteReport member variable INT32 HidDevice::AllocateIoBuffers() { INT32 error = ERROR_SUCCESS; return ERROR_SUCCESS; } void CALLBACK HidDevice::IoCompletion(DWORD dwErrorCode, // completion code DWORD dwNumberOfBytesTransfered, // number of bytes transferred LPOVERLAPPED lpOverlapped) // pointer to structure with I/O information { HidDevice* pDevice = dynamic_cast<HidDevice*>((HidDevice*)lpOverlapped->hEvent); switch (dwErrorCode) { case 0: break; default: TRACE(_T(" HidDevice::IoCompletion() 0x%x - Undefined Error(%x).\r\n"), pDevice, dwErrorCode); break; } } UINT32 HidDevice::SendCommand(StApi& api, UINT8* additionalInfo) { return ERROR_SUCCESS; } bool HidDevice::ProcessWriteCommand(const HANDLE hDevice, const StApi& api, NotifyStruct& nsInfo) { return true; } bool HidDevice::ProcessReadStatus(const HANDLE hDevice, const StApi& api, NotifyStruct& nsInfo) { return true; } // Changes data in pApi parameter, therefore must use 'StAp&*' instead of 'const StApi&' bool HidDevice::ProcessReadData(const HANDLE hDevice, StApi* pApi, NotifyStruct& nsInfo) { return true; } bool HidDevice::ProcessWriteData(const HANDLE hDevice, const StApi& api, NotifyStruct& nsInfo) { return true; } INT32 HidDevice::ProcessTimeOut(const INT32 timeout) { return ERROR_SUCCESS; } CString HidDevice::GetSendCommandErrorStr() { CString msg; switch ( _status ) { case CSW_CMD_PASSED: msg.Format(_T("HID Status: PASSED(0x%02X)\r\n"), _status); break; case CSW_CMD_FAILED: msg.Format(_T("HID Status: FAILED(0x%02X)\r\n"), _status); break; case CSW_CMD_PHASE_ERROR: msg.Format(_T("HID Status: PHASE_ERROR(0x%02X)\r\n"), _status); break; default: msg.Format(_T("HID Status: UNKNOWN(0x%02X)\r\n"), _status); } return msg; } UINT32 HidDevice::ResetChip() { api::HidDeviceReset api; return SendCommand(api); } HidDevice::ChipFamily_t HidDevice::GetChipFamily() { if ( _chipFamily == Unknown ) { CString devPath = UsbDevice()->_path.get(); devPath.MakeUpper(); if ( devPath.Find(_T("VID_066F&PID_3780")) != -1 ) { _chipFamily = MX23; } else if ( devPath.Find(_T("VID_15A2&PID_004F")) != -1 ) { _chipFamily = MX28; } } return _chipFamily; } //------------------------------------------------------------------------------------- // Function to get HAB_TYPE value // // @return // HabEnabled: if is prodction // HabDisabled: if is development/disable //------------------------------------------------------------------------------------- HidDevice::HAB_t HidDevice::GetHABType(ChipFamily_t chipType) { HAB_t habType = HabUnknown; return habType; } DWORD HidDevice::GetHabType() { _chipFamily = GetChipFamily(); if(_chipFamily == MX28) { if(_habType == HabUnknown) _habType = GetHABType(_chipFamily); } return _habType; }
27.952153
116
0.657994
Koltak
efdd89d2b326ec62a9e713a463a107becdd9625c
1,559
cpp
C++
cpp-htp/standard/ch21solutions/Ex21_21/ex21_21.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
75
2020-03-23T11:00:31.000Z
2022-02-20T05:22:53.000Z
cpp-htp/standard/ch21solutions/Ex21_21/ex21_21.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
null
null
null
cpp-htp/standard/ch21solutions/Ex21_21/ex21_21.cpp
yanshengjia/cplusplus-practice-range
6767a0ac50de8b532255511cd450dc84c66d1517
[ "Apache-2.0" ]
39
2020-04-03T23:47:24.000Z
2022-01-19T05:06:39.000Z
// Exercise 21.21 Solution: ex21_21.cpp #include <iostream> #include <cstdlib> using namespace std; const int SIZE = 6; int main() { char stringValue[ SIZE ]; int sum = 0; for ( int i = 1; i <= 4; ++i ) { cout << "Enter an integer string: "; cin >> stringValue; sum += atoi( stringValue ); // add converted stringValue to sum } // end for cout << "The total of the values is " << sum << endl; } // end main /************************************************************************** * (C) Copyright 1992-2010 by Deitel & Associates, Inc. and * * Pearson Education, Inc. All Rights Reserved. * * * * DISCLAIMER: The authors and publisher of this book have used their * * best efforts in preparing the book. These efforts include the * * development, research, and testing of the theories and programs * * to determine their effectiveness. The authors and publisher make * * no warranty of any kind, expressed or implied, with regard to these * * programs or to the documentation contained in these books. The authors * * and publisher shall not be liable in any event for incidental or * * consequential damages in connection with, or arising out of, the * * furnishing, performance, or use of these programs. * *************************************************************************/
39.974359
76
0.52213
yanshengjia
efe1ffe86c38e44a2b6a41ac546f963c1b6da326
456
cpp
C++
Selection Sort.cpp
Gayane05/Algorithms-Design_Patterns
9cba4b1b2018ae27a24f52b1e09ef037b9742f48
[ "MIT" ]
null
null
null
Selection Sort.cpp
Gayane05/Algorithms-Design_Patterns
9cba4b1b2018ae27a24f52b1e09ef037b9742f48
[ "MIT" ]
null
null
null
Selection Sort.cpp
Gayane05/Algorithms-Design_Patterns
9cba4b1b2018ae27a24f52b1e09ef037b9742f48
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <algorithm> template<typename T> void SelectionSort(std::vector<T>& vec) { for (int i = 1; i < vec.size() - 1; ++i) { int min = i; for (int j = i + 1; j < vec.size(); ++j) { if (vec[j] < vec[min]) { min = j; } std::swap(vec[j], vec[min]); } } } int main() { std::vector<char> nums { 'c', 't', 'f', 'g', 'j' }; SelectionSort(nums); return 0; }
14.709677
53
0.482456
Gayane05
efe246a0189f73fa17a75289694b57c4f589b186
111
cpp
C++
zadaci_prvi_ciklus_laboratorjiskih_vjezbi/zadatak1/main.cpp
Miillky/objektno_orijentirano_programiranje
b41fe690c25a73acd09aff5606524b9e43f0b38a
[ "MIT" ]
null
null
null
zadaci_prvi_ciklus_laboratorjiskih_vjezbi/zadatak1/main.cpp
Miillky/objektno_orijentirano_programiranje
b41fe690c25a73acd09aff5606524b9e43f0b38a
[ "MIT" ]
null
null
null
zadaci_prvi_ciklus_laboratorjiskih_vjezbi/zadatak1/main.cpp
Miillky/objektno_orijentirano_programiranje
b41fe690c25a73acd09aff5606524b9e43f0b38a
[ "MIT" ]
null
null
null
#include <iostream> #include "Automobil.hpp" int main(){ Automobil automobil; automobil.prikazi(); }
12.333333
24
0.675676
Miillky
efe47232b045b326e4802e9f1ae56254de9769e4
804
cpp
C++
851-loud-and-rich/851-loud-and-rich.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
2
2022-01-02T19:15:00.000Z
2022-01-05T21:12:24.000Z
851-loud-and-rich/851-loud-and-rich.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
null
null
null
851-loud-and-rich/851-loud-and-rich.cpp
Ananyaas/LeetCodeDaily
e134e20ac02f26dc40881c376656d3294be0df2c
[ "MIT" ]
1
2022-03-11T17:11:07.000Z
2022-03-11T17:11:07.000Z
class Solution { public: vector<int> loudAndRich(vector<vector<int>>& richer, vector<int>& quiet) { int n = quiet.size(); vector<vector<int>> graph(n); for(auto i : richer) graph[i[1]].push_back(i[0]); vector<bool> visited(n, false); vector<int> ans(n); for(int i = 0; i < n; i++) if(!visited[i]) dfs(i, visited, ans, quiet, graph); return ans; } int dfs(int i, vector<bool> &visited, vector<int> &ans, vector<int> &quiet, vector<vector<int>> &graph) { if(visited[i]) return ans[i]; int tmp = i; for(auto j : graph[i]) { int tmp2 = dfs(j, visited, ans, quiet, graph); if(quiet[tmp] > quiet[tmp2]) tmp = tmp2; } visited[i] = true; return ans[i] = tmp; } };
22.971429
103
0.529851
Ananyaas
efe5cac533b77730bea13363d24a1c4e9ff18347
2,851
cpp
C++
libraries/picosystem.cpp
Gadgetoid/picosystem
52890ea5c8e15a605889c7f5103e1ee97202d61c
[ "MIT" ]
null
null
null
libraries/picosystem.cpp
Gadgetoid/picosystem
52890ea5c8e15a605889c7f5103e1ee97202d61c
[ "MIT" ]
null
null
null
libraries/picosystem.cpp
Gadgetoid/picosystem
52890ea5c8e15a605889c7f5103e1ee97202d61c
[ "MIT" ]
null
null
null
#include <stdio.h> #include <cstdlib> #include <math.h> #include "picosystem.hpp" namespace picosystem { color_t _pen; int32_t _tx = 0, _ty = 0; int32_t _camx = 0, _camy = 0; uint32_t _io = 0, _lio = 0; blend_func_t _bf = BLEND; #ifdef PIXEL_DOUBLE color_t _fb[120 * 120]; buffer_t SCREEN{.w = 120, .h = 120, .data = _fb}; int32_t _cx = 0, _cy = 0, _cw = 120, _ch = 120; #else color_t _fb[240 * 240]; buffer_t SCREEN{.w = 240, .h = 240, .data = _fb}; int32_t _cx = 0, _cy = 0, _cw = 240, _ch = 240; #endif buffer_t &_dt = SCREEN; #ifdef NO_SPRITESHEET buffer_t *_ss = nullptr; #else buffer_t SPRITESHEET{.w = 128, .h = 128, .data = _default_sprite_sheet}; buffer_t *_ss = &SPRITESHEET; #endif #ifdef NO_FONT uint8_t *_font = nullptr; #else uint8_t *_font = &_default_font[0][0]; #endif } using namespace picosystem; // main entry point - the users' code will be automatically // called when they implement the init(), update(), and render() // functions in their project int main() { _init_hardware(); // setup lut for fast sin/cos functions for(uint32_t i = 0; i < 256; i++) { _fsin_lut[i] = sin((_PI * 2.0f) * (float(i) / 256.0f)); } #ifndef NO_STARTUP_LOGO // fade in logo by ramping up backlight pen(0, 0, 0); clear(); pen(15, 15, 15); _logo(); for(int i = 0; i < 75; i++) { backlight(i); _wait_vsync(); _flip(); } sleep(300); // ...and breathe out... // fade out logo in 16 colour steps for(int i = 15; i >= 0; i--) { pen(0, 0, 0); clear(); pen(i, i, i); _logo(); _wait_vsync(); _flip(); sleep(20); } #else backlight(75); #endif sleep(300); pen(0, 0, 0); clear(); // call users init() function so they can perform any needed // setup for world state etc init(); uint32_t update_rate_ms = 10; uint32_t pending_update_ms = 0; uint32_t last_ms = time(); uint32_t tick = 0; _io = _gpio_get(); while(true) { uint32_t ms = time(); // work out how many milliseconds of updates we're waiting // to process and then call the users update() function as // many times as needed to catch up pending_update_ms += (ms - last_ms); while(pending_update_ms >= update_rate_ms) { _lio = _io; _io = _gpio_get(); update(tick++); pending_update_ms -= update_rate_ms; } // if current flipping the framebuffer in the background // then wait until that is complete before allow the user // to render while(_is_flipping()) {} // call user render function to draw world draw(); // wait for the screen to vsync before triggering flip // to ensure no tearing _wait_vsync(); // flip the framebuffer to the screen _flip(); last_ms = ms; } }
21.598485
76
0.603297
Gadgetoid
efe9558965689a612351a7590523cf9f7e51ca72
2,420
hpp
C++
src/Kommunikationsstelle.hpp
Raspi64/imgui_setup
3d2a53211d26805c4851e3e28a9b2d6f02df1db8
[ "MIT" ]
1
2021-05-04T07:30:41.000Z
2021-05-04T07:30:41.000Z
src/Kommunikationsstelle.hpp
Raspi64/raspi64
3d2a53211d26805c4851e3e28a9b2d6f02df1db8
[ "MIT" ]
3
2020-11-21T17:49:13.000Z
2020-12-18T14:21:17.000Z
src/Kommunikationsstelle.hpp
Raspi64/raspi64
3d2a53211d26805c4851e3e28a9b2d6f02df1db8
[ "MIT" ]
3
2020-10-27T14:13:28.000Z
2020-12-18T14:16:07.000Z
// // Created by simon on 12/1/20. // #ifndef IMGUI_SETUP_KOMMUNIKATIONSSTELLE_HPP #define IMGUI_SETUP_KOMMUNIKATIONSSTELLE_HPP #include <string> #include <Gui.hpp> #include <Plugin.hpp> class Kommunikationsstelle { public: static void init(Gui *, LANG); enum Status { NOT_STARTED, // No program has been executed so far LOADING, // The user-program is currently loading/parsing LOAD_ERROR, // The user-program could not be loaded RUNNING, // The user-program is currently running RUN_ERROR, // There was an error when running the user-program KILLED, // The program was stopped in mid-execution COMPLETED_OK, // Program has exited successfully }; static void set_language(LANG lang); static bool start_script(const std::string &script); static void kill_current_task(); static void save(const std::string &name, const std::string &text); static std::string load(const std::string &name); static bool handle_command(std::string command); static void on_key_press(SDL_Keysym keysym); static void on_key_release(SDL_Keysym keysym); static Entry *get_common_help_root(); static Entry *get_language_help_root(); static std::vector<Entry *> search_entries(const std::string &searchword); static void gui_draw_rect(TGraphicRect rect); static void gui_draw_circle(TGraphicCircle circle); static void gui_draw_line(TGraphicLine line); static void gui_draw_text(TGraphicText text); static void gui_draw_pixel(TGraphicPixel pixel); static void gui_clear(); static void gui_print(const std::string &message); static void on_error(int line, const std::string &message); static std::string get_input_line(); static Kommunikationsstelle::Status status; private: static std::string base_path; static Gui *gui; static Plugin *interpreter; static pthread_t exec_thread; static bool waiting_for_input; static std::string input; static bool input_ready; static void *exec_script(void *params_void); static Plugin *get_interpreter(LANG language); static Entry help_root_entry; static void sort_subtrees(std::vector<Entry> *entries); static std::string get_key_name(const SDL_Keysym &keysym); static void delete_file(const std::string &basicString); }; #endif //IMGUI_SETUP_KOMMUNIKATIONSSTELLE_HPP
25.208333
78
0.721074
Raspi64
efef5493997fd4276533446b75110b7c76c62411
1,487
cpp
C++
Graph/networkdelaytime.cpp
thisisnitish/cp-dsa
6a00f1d60712115f70c346cee238ad1730e6c39e
[ "MIT" ]
4
2020-12-29T09:27:10.000Z
2022-02-12T14:20:23.000Z
Graph/networkdelaytime.cpp
thisisnitish/cp-dsa
6a00f1d60712115f70c346cee238ad1730e6c39e
[ "MIT" ]
1
2021-11-27T06:15:28.000Z
2021-11-27T06:15:28.000Z
Graph/networkdelaytime.cpp
thisisnitish/cp-dsa
6a00f1d60712115f70c346cee238ad1730e6c39e
[ "MIT" ]
1
2021-11-17T21:42:57.000Z
2021-11-17T21:42:57.000Z
/* Leetcode Question 743. Network Delay Time https://leetcode.com/problems/network-delay-time/ */ class Solution { public: /*the basic idea is that indirectly the question itself is asking single source shortest path, so we can apply dijsktra's algorithm. Time: O(ElogV)*/ int networkDelayTime(vector<vector<int> > &times, int n, int k) { vector<vector<pair<int, int> > > adj(n + 1); for (auto edge : times) { adj[edge[0]].push_back(make_pair(edge[1], edge[2])); } priority_queue<pair<int, int>, vector<pair<int, int> >, greater<pair<int, int> > > pq; vector<int> distance(n + 1, INT_MAX); distance[k] = 0; pq.push(make_pair(0, k)); while (!pq.empty()) { int u = pq.top().second; pq.pop(); for (auto neighbour : adj[u]) { int v = neighbour.first; int weight = neighbour.second; if (distance[v] > distance[u] + weight) { distance[v] = distance[u] + weight; pq.push(make_pair(distance[v], v)); } } } //since we want the maximum from the distance int result = 0; for (int i = 1; i <= n; i++) { if (distance[i] == INT_MAX) return -1; result = max(result, distance[i]); } return result; } };
26.553571
94
0.494956
thisisnitish
eff5d5ffbf67b5ff6da2cfa3e4b6b7e9e7aa478d
933
cpp
C++
aws-cpp-sdk-eks/source/model/DeleteAddonRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-eks/source/model/DeleteAddonRequest.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-eks/source/model/DeleteAddonRequest.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/eks/model/DeleteAddonRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/http/URI.h> #include <aws/core/utils/memory/stl/AWSStringStream.h> #include <utility> using namespace Aws::EKS::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws::Http; DeleteAddonRequest::DeleteAddonRequest() : m_clusterNameHasBeenSet(false), m_addonNameHasBeenSet(false), m_preserve(false), m_preserveHasBeenSet(false) { } Aws::String DeleteAddonRequest::SerializePayload() const { return {}; } void DeleteAddonRequest::AddQueryStringParameters(URI& uri) const { Aws::StringStream ss; if(m_preserveHasBeenSet) { ss << m_preserve; uri.AddQueryStringParameter("preserve", ss.str()); ss.str(""); } }
20.733333
69
0.714898
perfectrecall
eff649fba127a39df62f8e4763b5d469c27ab2cf
5,898
cc
C++
tensorflow_serving/servables/feature/feature_transformer.cc
ydp/serving
a3102b03a3435a645e64d28de67b45e9162a8a8c
[ "Apache-2.0" ]
6
2018-03-20T19:58:10.000Z
2020-11-23T09:29:04.000Z
tensorflow_serving/servables/feature/feature_transformer.cc
ydp/serving
a3102b03a3435a645e64d28de67b45e9162a8a8c
[ "Apache-2.0" ]
null
null
null
tensorflow_serving/servables/feature/feature_transformer.cc
ydp/serving
a3102b03a3435a645e64d28de67b45e9162a8a8c
[ "Apache-2.0" ]
null
null
null
#include "tensorflow_serving/servables/feature/feature_transformer.h" #include "tensorflow/core/lib/core/errors.h" #include "tensorflow/core/lib/io/path.h" #include "tensorflow/core/lib/io/inputbuffer.h" #include "tensorflow/core/lib/strings/str_util.h" #include "tensorflow/core/platform/env.h" #include "tensorflow/core/platform/types.h" #include "rapidjson/error/en.h" #include "tensorflow/core/example/example.pb.h" #include "tensorflow/core/example/feature.pb.h" namespace tensorflow { namespace serving { FeatureTransformer::~FeatureTransformer() {} Status FeatureTransformer::LoadTfExampleConf(string path) { const string file = io::JoinPath(path, "features.conf"); std::unique_ptr<RandomAccessFile> f; TF_RETURN_IF_ERROR(Env::Default()->NewRandomAccessFile(file, &f)); const size_t kBufferSizeBytes = 262144; io::InputBuffer in(f.get(), kBufferSizeBytes); string line; while (in.ReadLine(&line).ok()) { if (line.size() > 2 && line[0] == '#' && line[1] != '#') { std::vector<string> cols = str_util::Split(line, '\t'); if (cols.size() != 4) { return errors::InvalidArgument("features.conf not have 4 cols."); } const string& name = cols[0].substr(1); const string& opType = cols[1]; const string& oper = cols[2]; const string& args = cols[3]; rapidjson::MemoryStream ms(args.data(), args.size()); rapidjson::EncodedInputStream<rapidjson::UTF8<>, rapidjson::MemoryStream> jsonstream(ms); rapidjson::Document doc; if (doc.ParseStream<rapidjson::kParseNanAndInfFlag>(jsonstream) .HasParseError()) { return errors::InvalidArgument( "JSON Parse error: ", rapidjson::GetParseError_En(doc.GetParseError()), " at offset: ", doc.GetErrorOffset()); } if (!doc.IsObject()) { return errors::InvalidArgument("expected json to an object."); } FeatureNode node; node.name = name; node.opType = opType; if (oper == "tffeaturecolumn") { ParseFeatureColumn(doc, node); } else if (oper == "pickcats") { ParsePickcats(doc, node); } feature_nodes_.emplace_back(node); } } return Status::OK(); } Status FeatureTransformer::ParseFeatureColumn(const rapidjson::Document& doc, FeatureNode& node) { rapidjson::Value::ConstMemberIterator itor; itor = doc.FindMember("type"); if (itor != doc.MemberEnd()) { node.dataType = itor->value.GetString(); } itor = doc.FindMember("defaultin"); if (itor != doc.MemberEnd()) { const string& v = itor->value.GetString(); if (node.dataType == "float") { node.defaultVal.fval = atof(v.c_str()); } else if (node.dataType == "int") { node.defaultVal.ival = atoi(v.c_str()); } else if (node.dataType == "string") { node.defaultVal.sval = v; } else { return errors::InvalidArgument("unsupported data type."); } } return Status::OK(); } Status FeatureTransformer::ParsePickcats(const rapidjson::Document& doc, FeatureNode& node) { rapidjson::Value::ConstMemberIterator itor; itor = doc.FindMember("rowdelimiter"); if (itor != doc.MemberEnd()) { node.rowdelimiter = itor->value.GetString(); } itor = doc.FindMember("coldelimiter"); if (itor != doc.MemberEnd()) { node.coldelimiter = itor->value.GetString(); } itor = doc.FindMember("valuetype"); if (itor != doc.MemberEnd()) { node.valuetype = itor->value.GetString(); } itor = doc.FindMember("defaultin"); if (itor != doc.MemberEnd()) { node.defaultVal.sval = itor->value.GetString(); } return Status::OK(); } Status FeatureTransformer::Transform(const rapidjson::Document& doc, Tensor& example_tensor) { rapidjson::Value::ConstMemberIterator it = doc.FindMember("input"); if (it == doc.MemberEnd()) { return errors::InvalidArgument("did not find input field."); } if (!it->value.IsArray()) { return errors::InvalidArgument("input field is not an array."); } rapidjson::Value::ConstMemberIterator itor; for (rapidjson::SizeType i = 0; i < it->value.Size(); ++i) { const rapidjson::Value& sample = it->value[i]; Example example; string str_example; auto features = example.mutable_features(); for (auto& feature_def : feature_nodes_) { auto& fea = (*features->mutable_feature())[feature_def.name]; itor = sample.FindMember(feature_def.name.c_str()); if (itor != sample.MemberEnd()) { const string& v = itor->value.GetString(); if (feature_def.opType == "tffeaturecolumn") { if (feature_def.dataType == "int") { fea.mutable_int64_list()->add_value(atoi(v.c_str())); } else if (feature_def.dataType == "float") { fea.mutable_float_list()->add_value(atof(v.c_str())); } else if (feature_def.dataType == "string") { fea.mutable_bytes_list()->add_value(v); } } else if (feature_def.opType == "pickcats") { // TODO } } else { if (feature_def.dataType == "int") { fea.mutable_int64_list()->add_value(feature_def.defaultVal.ival); } else if (feature_def.dataType == "float") { fea.mutable_float_list()->add_value(feature_def.defaultVal.fval); } else if (feature_def.dataType == "string") { fea.mutable_bytes_list()->add_value(feature_def.defaultVal.sval); } } } // for feature_nodes_ // LOG(INFO) << example.DebugString().c_str(); example.SerializeToString(&str_example); example_tensor.flat<string>()(i) = str_example; example.Clear(); str_example.clear(); } // for it->value return Status::OK(); } } // namespace serving } // namespace tensorflow
35.963415
81
0.626823
ydp
eff65efeeb1bde6d66b9f8c1c12a1c51aece6dfd
557
cc
C++
sample/src/utils/FileOperationUtils.cc
aliyun/aliyun-pds-cpp-sdk
d1f5091efe7a3ac971285ccb82bbf9cc77a41ccc
[ "Apache-2.0" ]
2
2021-09-18T12:51:39.000Z
2021-09-19T13:38:31.000Z
sample/src/utils/FileOperationUtils.cc
aliyun/aliyun-pds-cpp-sdk
d1f5091efe7a3ac971285ccb82bbf9cc77a41ccc
[ "Apache-2.0" ]
null
null
null
sample/src/utils/FileOperationUtils.cc
aliyun/aliyun-pds-cpp-sdk
d1f5091efe7a3ac971285ccb82bbf9cc77a41ccc
[ "Apache-2.0" ]
null
null
null
#include "FileOperationUtils.h" #include <sys/stat.h> bool GetPathInfo(const std::string& path, time_t& t, std::streamsize& size) { struct stat buf; auto filename = path.c_str(); #if defined(_WIN32) && _MSC_VER < 1900 std::string tmp; if (!path.empty() && (path.rbegin()[0] == PATH_DELIMITER)) { tmp = path.substr(0, path.size() - 1); filename = tmp.c_str(); } #endif if (stat(filename, &buf) != 0) return false; t = buf.st_mtime; size = static_cast<std::streamsize>(buf.st_size); return true; }
26.52381
75
0.610413
aliyun
eff977b4191397ec7902a88c7b8c346e4efb6f7d
2,567
cpp
C++
TC647 - 1000.cpp
therainmak3r/dirty-laundry
39e295e9390b62830bef53282cdcb63716efac45
[ "MIT" ]
20
2015-12-22T14:14:59.000Z
2019-10-25T12:14:23.000Z
TC647 - 1000.cpp
therainmak3r/dirty-laundry
39e295e9390b62830bef53282cdcb63716efac45
[ "MIT" ]
null
null
null
TC647 - 1000.cpp
therainmak3r/dirty-laundry
39e295e9390b62830bef53282cdcb63716efac45
[ "MIT" ]
2
2016-06-27T13:34:08.000Z
2018-10-02T20:36:54.000Z
#include <iostream> #include <algorithm> #include <vector> using namespace std; class BuildingTowers { public: long long between(int xi, long long a, int xj, long long b, long long k) { if (a > b) return between(xj,b,xi,a,k); int available = abs(xj - xi) - 1; while (a < b) { available--; a += k; if (available <= 0) return max(a,b); } bool flipper = 1; while (available > 0) { if (flipper) { b +=k; flipper = 0; } else { a += k; flipper = 1; } available--; } return max(a,b); } long long maxHeight (int N, int K, vector<int> x, vector<int> t) { if (x.size() == 0) return ((long long)(N-1))*(long long)K; vector<pair<int,int> > join; for (int i = 0; i < x.size(); i++) join.push_back(make_pair(x[i],t[i])); sort(join.begin(), join.end()); for (int i = 0; i < x.size(); i++) { x[i] = join[i].first; t[i] = join[i].second; // cout << "i is " << i << " and x[i] is " << x[i] << " and t[i] is " << t[i] << endl; } long long ans = between(1,0,x[0],t[0],K); // cout << "max height with first building is " << ans << endl; t[0] = min((long long)t[0],(long long)(x[0]-1)*(long long)K); for (int i = 0; i < x.size() - 1; i++) { t[i+1] = min((long long)t[i+1],t[i]+ (long long)(x[i+1]-x[i])*(long long)K); long long temp = between(x[i],t[i],x[i+1],t[i+1],K); // cout << " i is " << i << " and max height is " << temp << endl; ans = max(ans, temp); } long long temp = (long long)t[x.size()-1] + (long long)(N-x[x.size()-1])*(long long)K; // cout << "height with last building is " << temp << endl; ans = max(ans, temp); return ans; } }; int main() { vector<int> x; x.push_back(2); /* x.push_back(7); x.push_back(13); x.push_back(15); x.push_back(18); */ vector<int> t; t.push_back(3); /* t.push_back(22); t.push_back(1); t.push_back(55); t.push_back(42); */ BuildingTowers obj; long long ans = obj.maxHeight(5,4,x,t); cout << "Final ans is " << ans << endl; return 0; }
28.522222
98
0.423062
therainmak3r
effad5b5bb5119a9fac318036c0eb5cbba76ab41
8,826
cpp
C++
legacy/libgcrypt/mpi/mpi-bit.cpp
mehrdad-shokri/neopg
05b370c04ffc019e55d75ab262d17abe6e69cafc
[ "BSD-2-Clause" ]
224
2017-10-29T09:48:00.000Z
2021-07-21T10:27:14.000Z
legacy/libgcrypt/mpi/mpi-bit.cpp
mehrdad-shokri/neopg
05b370c04ffc019e55d75ab262d17abe6e69cafc
[ "BSD-2-Clause" ]
66
2017-10-29T16:17:55.000Z
2020-11-30T18:53:40.000Z
legacy/libgcrypt/mpi/mpi-bit.cpp
mehrdad-shokri/neopg
05b370c04ffc019e55d75ab262d17abe6e69cafc
[ "BSD-2-Clause" ]
22
2017-10-29T19:55:45.000Z
2020-01-04T13:25:50.000Z
/* mpi-bit.c - MPI bit level functions * Copyright (C) 1998, 1999, 2001, 2002, 2006 Free Software Foundation, Inc. * Copyright (C) 2013 g10 Code GmbH * * This file is part of Libgcrypt. * * Libgcrypt is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * Libgcrypt is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA */ #include <config.h> #include <stdio.h> #include <stdlib.h> #include "longlong.h" #include "mpi-internal.h" #ifdef MPI_INTERNAL_NEED_CLZ_TAB #ifdef __STDC__ const #endif unsigned char _gcry_clz_tab[] = { 0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, }; #endif #define A_LIMB_1 ((mpi_limb_t)1) /**************** * Sometimes we have MSL (most significant limbs) which are 0; * this is for some reasons not good, so this function removes them. */ void _gcry_mpi_normalize(gcry_mpi_t a) { if (mpi_is_opaque(a)) return; for (; a->nlimbs && !a->d[a->nlimbs - 1]; a->nlimbs--) ; } /**************** * Return the number of bits in A. */ unsigned int _gcry_mpi_get_nbits(gcry_mpi_t a) { unsigned n; if (mpi_is_opaque(a)) { return a->sign; /* which holds the number of bits */ } _gcry_mpi_normalize(a); if (a->nlimbs) { mpi_limb_t alimb = a->d[a->nlimbs - 1]; if (alimb) count_leading_zeros(n, alimb); else n = BITS_PER_MPI_LIMB; n = BITS_PER_MPI_LIMB - n + (a->nlimbs - 1) * BITS_PER_MPI_LIMB; } else n = 0; return n; } /**************** * Test whether bit N is set. */ int _gcry_mpi_test_bit(gcry_mpi_t a, unsigned int n) { unsigned int limbno, bitno; mpi_limb_t limb; limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) return 0; /* too far left: this is a 0 */ limb = a->d[limbno]; return (limb & (A_LIMB_1 << bitno)) ? 1 : 0; } /**************** * Set bit N of A. */ void _gcry_mpi_set_bit(gcry_mpi_t a, unsigned int n) { unsigned int i, limbno, bitno; if (mpi_is_immutable(a)) { mpi_immutable_failed(); return; } limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) { for (i = a->nlimbs; i < a->alloced; i++) a->d[i] = 0; mpi_resize(a, limbno + 1); a->nlimbs = limbno + 1; } a->d[limbno] |= (A_LIMB_1 << bitno); } /**************** * Set bit N of A. and clear all bits above */ void _gcry_mpi_set_highbit(gcry_mpi_t a, unsigned int n) { unsigned int i, limbno, bitno; if (mpi_is_immutable(a)) { mpi_immutable_failed(); return; } limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) { for (i = a->nlimbs; i < a->alloced; i++) a->d[i] = 0; mpi_resize(a, limbno + 1); a->nlimbs = limbno + 1; } a->d[limbno] |= (A_LIMB_1 << bitno); for (bitno++; bitno < BITS_PER_MPI_LIMB; bitno++) a->d[limbno] &= ~(A_LIMB_1 << bitno); a->nlimbs = limbno + 1; } /**************** * clear bit N of A and all bits above */ void _gcry_mpi_clear_highbit(gcry_mpi_t a, unsigned int n) { unsigned int limbno, bitno; if (mpi_is_immutable(a)) { mpi_immutable_failed(); return; } limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) return; /* not allocated, therefore no need to clear bits :-) */ for (; bitno < BITS_PER_MPI_LIMB; bitno++) a->d[limbno] &= ~(A_LIMB_1 << bitno); a->nlimbs = limbno + 1; } /**************** * Clear bit N of A. */ void _gcry_mpi_clear_bit(gcry_mpi_t a, unsigned int n) { unsigned int limbno, bitno; if (mpi_is_immutable(a)) { mpi_immutable_failed(); return; } limbno = n / BITS_PER_MPI_LIMB; bitno = n % BITS_PER_MPI_LIMB; if (limbno >= a->nlimbs) return; /* Don't need to clear this bit, it's far too left. */ a->d[limbno] &= ~(A_LIMB_1 << bitno); } /**************** * Shift A by COUNT limbs to the right * This is used only within the MPI library */ void _gcry_mpi_rshift_limbs(gcry_mpi_t a, unsigned int count) { mpi_ptr_t ap = a->d; mpi_size_t n = a->nlimbs; unsigned int i; if (mpi_is_immutable(a)) { mpi_immutable_failed(); return; } if (count >= n) { a->nlimbs = 0; return; } for (i = 0; i < n - count; i++) ap[i] = ap[i + count]; ap[i] = 0; a->nlimbs -= count; } /* * Shift A by N bits to the right. */ void _gcry_mpi_rshift(gcry_mpi_t x, gcry_mpi_t a, unsigned int n) { mpi_size_t xsize; unsigned int i; unsigned int nlimbs = (n / BITS_PER_MPI_LIMB); unsigned int nbits = (n % BITS_PER_MPI_LIMB); if (mpi_is_immutable(x)) { mpi_immutable_failed(); return; } if (x == a) { /* In-place operation. */ if (nlimbs >= x->nlimbs) { x->nlimbs = 0; return; } if (nlimbs) { for (i = 0; i < x->nlimbs - nlimbs; i++) x->d[i] = x->d[i + nlimbs]; x->d[i] = 0; x->nlimbs -= nlimbs; } if (x->nlimbs && nbits) _gcry_mpih_rshift(x->d, x->d, x->nlimbs, nbits); } else if (nlimbs) { /* Copy and shift by more or equal bits than in a limb. */ xsize = a->nlimbs; x->sign = a->sign; RESIZE_IF_NEEDED(x, xsize); x->nlimbs = xsize; for (i = 0; i < a->nlimbs; i++) x->d[i] = a->d[i]; x->nlimbs = i; if (nlimbs >= x->nlimbs) { x->nlimbs = 0; return; } if (nlimbs) { for (i = 0; i < x->nlimbs - nlimbs; i++) x->d[i] = x->d[i + nlimbs]; x->d[i] = 0; x->nlimbs -= nlimbs; } if (x->nlimbs && nbits) _gcry_mpih_rshift(x->d, x->d, x->nlimbs, nbits); } else { /* Copy and shift by less than bits in a limb. */ xsize = a->nlimbs; x->sign = a->sign; RESIZE_IF_NEEDED(x, xsize); x->nlimbs = xsize; if (xsize) { if (nbits) _gcry_mpih_rshift(x->d, a->d, x->nlimbs, nbits); else { /* The rshift helper function is not specified for NBITS==0, thus we do a plain copy here. */ for (i = 0; i < x->nlimbs; i++) x->d[i] = a->d[i]; } } } MPN_NORMALIZE(x->d, x->nlimbs); } /**************** * Shift A by COUNT limbs to the left * This is used only within the MPI library */ void _gcry_mpi_lshift_limbs(gcry_mpi_t a, unsigned int count) { mpi_ptr_t ap; int n = a->nlimbs; int i; if (!count || !n) return; RESIZE_IF_NEEDED(a, n + count); ap = a->d; for (i = n - 1; i >= 0; i--) ap[i + count] = ap[i]; for (i = 0; i < count; i++) ap[i] = 0; a->nlimbs += count; } /* * Shift A by N bits to the left. */ void _gcry_mpi_lshift(gcry_mpi_t x, gcry_mpi_t a, unsigned int n) { unsigned int nlimbs = (n / BITS_PER_MPI_LIMB); unsigned int nbits = (n % BITS_PER_MPI_LIMB); if (mpi_is_immutable(x)) { mpi_immutable_failed(); return; } if (x == a && !n) return; /* In-place shift with an amount of zero. */ if (x != a) { /* Copy A to X. */ unsigned int alimbs = a->nlimbs; int asign = a->sign; mpi_ptr_t xp, ap; RESIZE_IF_NEEDED(x, alimbs + nlimbs + 1); xp = x->d; ap = a->d; MPN_COPY(xp, ap, alimbs); x->nlimbs = alimbs; x->flags = a->flags; x->sign = asign; } if (nlimbs && !nbits) { /* Shift a full number of limbs. */ _gcry_mpi_lshift_limbs(x, nlimbs); } else if (n) { /* We use a very dump approach: Shift left by the number of limbs plus one and than fix it up by an rshift. */ _gcry_mpi_lshift_limbs(x, nlimbs + 1); mpi_rshift(x, x, BITS_PER_MPI_LIMB - nbits); } MPN_NORMALIZE(x->d, x->nlimbs); }
26.112426
79
0.567868
mehrdad-shokri
effb6ad015942570849c6bfb3b062b91674ca864
1,872
cpp
C++
deps/emp-tool/uint.cpp
fakecoinbase/boltlabs-incslashlibzkchannels
c0b43790c637f4ffd2956193b16f9ddcea94a3a4
[ "MIT" ]
68
2020-01-18T22:07:57.000Z
2022-02-03T02:30:55.000Z
deps/emp-tool/uint.cpp
fakecoinbase/boltlabs-incslashlibzkchannels
c0b43790c637f4ffd2956193b16f9ddcea94a3a4
[ "MIT" ]
2
2020-04-29T02:02:49.000Z
2021-04-08T11:23:48.000Z
deps/emp-tool/uint.cpp
fakecoinbase/boltlabs-incslashlibzkchannels
c0b43790c637f4ffd2956193b16f9ddcea94a3a4
[ "MIT" ]
3
2021-04-04T05:04:16.000Z
2022-01-26T10:14:46.000Z
#include <typeinfo> #include "emp-tool/emp-tool.h" #include <iostream> using namespace std; using namespace emp; template<typename Op, typename Op2> void test_int(int party, int range1 = 1<<25, int range2 = 1<<25, int runs = 1000) { PRG prg; for(int i = 0; i < runs; ++i) { unsigned long long ia, ib; prg.random_data(&ia, 8); prg.random_data(&ib, 8); ia %= range1; ib %= range2; while( Op()(int(ia), int(ib)) != Op()(ia, ib) ) { prg.random_data(&ia, 8); prg.random_data(&ib, 8); ia %= range1; ib %= range2; } UInteger a(32, ia, ALICE); UInteger b(32, ib, BOB); UInteger res = Op2()(a,b); if (res.reveal<uint>(PUBLIC) != Op()(ia,ib)) { cout << ia <<"\t"<<ib<<"\t"<<Op()(ia,ib)<<"\t"<<res.reveal<int>(PUBLIC)<<endl<<flush; } assert(res.reveal<uint>(PUBLIC) == Op()(ia,ib)); } cout << typeid(Op2).name()<<"\t\t\tDONE"<<endl; } void scratch_pad() { UInteger a(32, 9, ALICE); cout << "HW "<<a.hamming_weight().reveal<string>(PUBLIC)<<endl; cout << "LZ "<<a.leading_zeros().reveal<string>(PUBLIC)<<endl; } int main(int argc, char** argv) { int party = PUBLIC; setup_plain_prot(false, ""); // scratch_pad();return 0; test_int<std::plus<uint>, std::plus<UInteger>>(party); /* test_int<std::minus<int>, std::minus<Integer>>(party); test_int<std::multiplies<int>, std::multiplies<Integer>>(party); test_int<std::divides<int>, std::divides<Integer>>(party); test_int<std::modulus<int>, std::modulus<Integer>>(party); */ test_int<std::bit_and<uint>, std::bit_and<UInteger>>(party); test_int<std::bit_or<uint>, std::bit_or<UInteger>>(party); test_int<std::bit_xor<uint>, std::bit_xor<UInteger>>(party); finalize_plain_prot(); }
31.2
97
0.571581
fakecoinbase
effcc4905f3eab31d3927931f9dafab1702a61d4
225
cpp
C++
Baekjoon/10103.cpp
r4k0nb4k0n/Programming-Challenges
3d734902a7503f9dc49c97fe6e69e7541cd73e56
[ "MIT" ]
2
2019-05-24T08:58:26.000Z
2022-01-09T00:46:42.000Z
Baekjoon/10103.cpp
r4k0nb4k0n/Programming-Challenges
3d734902a7503f9dc49c97fe6e69e7541cd73e56
[ "MIT" ]
null
null
null
Baekjoon/10103.cpp
r4k0nb4k0n/Programming-Challenges
3d734902a7503f9dc49c97fe6e69e7541cd73e56
[ "MIT" ]
null
null
null
#include <cstdio> using namespace std; int main(){ int n; int a=100,b=100; scanf("%d",&n); while(n--){ int i, j; scanf("%d %d",&i,&j); if(i<j) a-=j; else if(i>j) b-=i; } printf("%d\n%d",a,b); return 0; }
12.5
23
0.502222
r4k0nb4k0n
effd4d35c462f68745db4533748530419ec94797
618
cpp
C++
CPlusPlusThings/struct/struct_things.cpp
lijianran/Leetcode
d94f9ed0caeee5318041e9f1d70f3db4518aed49
[ "Apache-2.0" ]
1
2021-05-15T14:38:15.000Z
2021-05-15T14:38:15.000Z
CPlusPlusThings/struct/struct_things.cpp
lijianran/Leetcode
d94f9ed0caeee5318041e9f1d70f3db4518aed49
[ "Apache-2.0" ]
null
null
null
CPlusPlusThings/struct/struct_things.cpp
lijianran/Leetcode
d94f9ed0caeee5318041e9f1d70f3db4518aed49
[ "Apache-2.0" ]
null
null
null
/** * @file struct_things.cpp * @author lijianran (lijianran@outlook.com) * @brief struct 那些事 https://light-city.club/sc/basic_content/struct/ * @version 0.1 * @date 2021-12-17 */ #include <iostream> #include <stdio.h> struct Base { // 默认 public int v1; // private: int v3; public: //显示声明 public int v2; void print() { printf("%s\n", "hello world"); }; }; int main() { struct Base base1; //ok Base base2; //ok Base base; base.v1 = 1; base.v3 = 2; base.print(); printf("%d\n", base.v1); printf("%d\n", base.v3); return 0; }
15.073171
69
0.550162
lijianran
560a79738fc9fd930f5108100445c7a498b78e80
1,622
cpp
C++
brainfuck/test.cpp
DenisOstashov/cpp-advanced-hse
6e4317763c0a9c510d639ae1e5793a8e9549d953
[ "MIT" ]
null
null
null
brainfuck/test.cpp
DenisOstashov/cpp-advanced-hse
6e4317763c0a9c510d639ae1e5793a8e9549d953
[ "MIT" ]
null
null
null
brainfuck/test.cpp
DenisOstashov/cpp-advanced-hse
6e4317763c0a9c510d639ae1e5793a8e9549d953
[ "MIT" ]
null
null
null
#include <catch.hpp> #include <limits> #include "brainfuck.h" TEST_CASE("Consume") { REQUIRE(std::is_same_v<Consume<Tape<0, 0, 'a'>>, decltype(std::pair<Char<0>, Tape<0, 'a'>>{})>); REQUIRE(std::is_same_v<Consume<Tape<0, 'a'>>, decltype(std::pair<Char<'a'>, Tape<0>>{})>); REQUIRE(std::is_same_v<Consume<Tape<0>>, Error>); } TEST_CASE("Produce") { REQUIRE(std::is_same_v<Produce<'a', Tape<0>>, Tape<0, 'a'>>); REQUIRE(std::is_same_v<Produce<'a', Tape<0, 'b'>>, Tape<0, 'b', 'a'>>); } TEST_CASE("IncrementPos") { REQUIRE(std::is_same_v<IncrementPos<Tape<0, '0', '0'>>, Tape<1, '0', '0'>>); REQUIRE(std::is_same_v<IncrementPos<Tape<1, '0', '0'>>, Error>); REQUIRE(std::is_same_v<IncrementPos<Tape<0, '0'>>, Error>); REQUIRE(std::is_same_v<IncrementPos<Tape<0>>, Error>); } TEST_CASE("DecrementPos") { REQUIRE(std::is_same_v<DecrementPos<Tape<1, '0', '0'>>, Tape<0, '0', '0'>>); REQUIRE(std::is_same_v<DecrementPos<Tape<0, 'a', 'b'>>, Error>); REQUIRE(std::is_same_v<DecrementPos<Tape<0>>, Error>); } TEST_CASE("IncrementCell") { REQUIRE(std::is_same_v<IncrementCell<Tape<1, '0', '0'>>, Tape<1, '0', '1'>>); REQUIRE(std::is_same_v<IncrementCell<Tape<0, 'a', '0'>>, Tape<0, 'b', '0'>>); REQUIRE(std::is_same_v<IncrementCell<Tape<0, std::numeric_limits<char>::max()>>, Error>); } TEST_CASE("DecrementCell") { REQUIRE(std::is_same_v<DecrementCell<Tape<1, '0', '9'>>, Tape<1, '0', '8'>>); REQUIRE(std::is_same_v<DecrementCell<Tape<0, '\1'>>, Tape<0, '\0'>>); REQUIRE(std::is_same_v<DecrementCell<Tape<0, std::numeric_limits<char>::min()>>, Error>); }
40.55
100
0.620838
DenisOstashov
560caad7b2f7cb4c36f408bb8d529de237d92edb
5,434
cpp
C++
src/KernelArg.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
5
2019-12-16T15:32:05.000Z
2021-05-21T18:36:37.000Z
src/KernelArg.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
98
2019-12-07T15:28:18.000Z
2021-03-02T14:20:48.000Z
src/KernelArg.cpp
rise-lang/yacx
da81fe8f814151b1c2024617f0bc9891f210cd84
[ "MIT" ]
6
2019-12-08T13:20:57.000Z
2021-05-16T11:21:14.000Z
#include "yacx/Exception.hpp" #include "yacx/KernelArgs.hpp" #include "yacx/Logger.hpp" #include <builtin_types.h> #include <stdexcept> using yacx::KernelArg, yacx::KernelArgMatrixPadding, yacx::loglevel, yacx::detail::DataCopy, yacx::detail::DataCopyKernelArg, yacx::detail::DataCopyKernelArgMatrixPadding; std::shared_ptr<DataCopyKernelArg> KernelArg::dataCopyKernelArg = std::make_shared<DataCopyKernelArg>(); KernelArg::KernelArg(void *const data, size_t size, bool download, bool copy, bool upload) : m_hdata{data}, m_dataCopy(KernelArg::dataCopyKernelArg), m_size{size}, m_download{download}, m_copy{copy}, m_upload{upload} { Logger(loglevel::DEBUG) << "created KernelArg with size: " << size << ", which should " << (m_upload ? "be" : "not be") << " uploaded and should " << (m_download ? "be" : "not be") << " downloaded"; } KernelArgMatrixPadding::KernelArgMatrixPadding(void *data, size_t size, bool download, int elementSize, unsigned int paddingValue, int src_rows, int src_columns, int dst_rows, int dst_columns) : KernelArg(data, size, download, true, true) { m_dataCopy = std::make_shared<DataCopyKernelArgMatrixPadding>( elementSize, paddingValue, src_rows, src_columns, dst_rows, dst_columns); Logger(loglevel::DEBUG) << "created KernelArgMatrixPadding with src_rows: " << src_rows << ", src_columns: " << src_columns << ", dst_rows: " << dst_rows << ", dst_columns: " << dst_columns << ", paddingValue: " << paddingValue; } void KernelArg::malloc() { if (m_upload) { Logger(loglevel::DEBUG1) << "uploading argument"; CUDA_SAFE_CALL(cuMemAlloc(&m_ddata, m_size)); } else { Logger(loglevel::DEBUG1) << "NOT uploading argument"; } } void KernelArg::uploadAsync(CUstream stream) { if (m_upload && m_copy) { Logger(loglevel::DEBUG1) << "copying data to device"; m_dataCopy.get()->copyDataHtoD(const_cast<void *>(m_hdata), m_ddata, m_size, stream); } } void KernelArg::downloadAsync(void *hdata, CUstream stream) { if (m_download) { Logger(loglevel::DEBUG1) << "downloading argument"; m_dataCopy.get()->copyDataDtoH(m_ddata, hdata, m_size, stream); } else { Logger(loglevel::DEBUG1) << "NOT downloading argument"; } } void KernelArg::free() { if (m_upload) { Logger(loglevel::DEBUG1) << "freeing argument from device"; CUDA_SAFE_CALL(cuMemFree(m_ddata)); } else { Logger(loglevel::DEBUG1) << "NOT freeing argument from device"; } } const void *KernelArg::content() const { if (m_upload) { Logger(loglevel::DEBUG1) << "returning device pointer"; return &m_ddata; } Logger(loglevel::DEBUG1) << "returning host pointer"; return m_hdata; } void DataCopyKernelArg::copyDataHtoD(void *hdata, CUdeviceptr ddata, size_t size, CUstream stream) { CUDA_SAFE_CALL(cuMemcpyHtoDAsync(ddata, hdata, size, stream)); } void DataCopyKernelArg::copyDataDtoH(CUdeviceptr ddata, void *hdata, size_t size, CUstream stream) { CUDA_SAFE_CALL(cuMemcpyDtoHAsync(hdata, ddata, size, stream)); } void DataCopyKernelArgMatrixPadding::copyDataHtoD(void *hdata, CUdeviceptr ddata, size_t, CUstream stream) { char *src = static_cast<char *>(hdata); const unsigned char paddingValueChar = m_paddingValue >> (sizeof(int) - sizeof(char)); const unsigned short paddingValueShort = m_paddingValue >> (sizeof(int) - sizeof(short)); switch (m_elementSize) { case 1: CUDA_SAFE_CALL(cuMemsetD8Async(ddata, paddingValueChar, m_dst_rows * m_dst_columns, stream)); break; case 2: CUDA_SAFE_CALL(cuMemsetD16Async(ddata, paddingValueShort, m_dst_rows * m_dst_columns, stream)); break; case 4: CUDA_SAFE_CALL(cuMemsetD32Async(ddata, m_paddingValue, m_dst_rows * m_dst_columns, stream)); break; default: throw std::invalid_argument("invalid elementsize of paddingArg. Only 1,2 " "or 4 bytes elementsize are supported."); } const size_t sizeSrcColumn = m_src_columns * m_elementSize; const size_t sizeDstColumn = m_dst_columns * m_elementSize; for (int i = 0; i < m_src_rows; i++) { CUDA_SAFE_CALL(cuMemcpyHtoDAsync(ddata, src, sizeSrcColumn, stream)); ddata += sizeDstColumn; src += sizeSrcColumn; } } void DataCopyKernelArgMatrixPadding::copyDataDtoH(CUdeviceptr ddata, void *hdata, size_t, CUstream stream) { char *src = static_cast<char *>(hdata); const size_t sizeSrcColumn = m_src_columns * m_elementSize; for (int i = 0; i < m_src_rows; i++) { CUDA_SAFE_CALL(cuMemcpyDtoHAsync(src, ddata, sizeSrcColumn, stream)); ddata += m_dst_columns * m_elementSize; src += sizeSrcColumn; } }
36.716216
80
0.605631
rise-lang
560df63a041345e0e002b3745ecce37c9cfe24d7
3,503
cpp
C++
FreeRTOS/cpp11_gcc/thread.cpp
klepsydra-technologies/FreeRTOS_cpp11
0676bd7d9667d999c9ba8e377f51771f197359aa
[ "MIT" ]
66
2019-07-23T10:25:36.000Z
2022-03-24T12:45:03.000Z
FreeRTOS/cpp11_gcc/thread.cpp
klepsydra-technologies/FreeRTOS_cpp11
0676bd7d9667d999c9ba8e377f51771f197359aa
[ "MIT" ]
10
2019-10-14T21:25:54.000Z
2021-03-28T17:39:18.000Z
FreeRTOS/cpp11_gcc/thread.cpp
klepsydra-technologies/FreeRTOS_cpp11
0676bd7d9667d999c9ba8e377f51771f197359aa
[ "MIT" ]
17
2019-06-13T03:24:07.000Z
2022-01-18T00:28:34.000Z
/// Copyright 2021 Piotr Grygorczuk <grygorek@gmail.com> /// /// Permission is hereby granted, free of charge, to any person obtaining a copy /// of this software and associated documentation files (the "Software"), to deal /// in the Software without restriction, including without limitation the rights /// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell /// copies of the Software, and to permit persons to whom the Software is /// furnished to do so, subject to the following conditions: /// /// The above copyright notice and this permission notice shall be included in all /// copies or substantial portions of the Software. /// /// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR /// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, /// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE /// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER /// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, /// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN /// THE SOFTWARE. #include <thread> #include <system_error> #include <cerrno> #include "FreeRTOS.h" #include "gthr_key_type.h" namespace free_rtos_std { extern Key *s_key; } // namespace free_rtos_std namespace std { static void __execute_native_thread_routine(void *__p) { __gthread_t local{*static_cast<__gthread_t *>(__p)}; //copy { // we own the arg now; it must be deleted after run() returns thread::_State_ptr __t{static_cast<thread::_State *>(local.arg())}; local.notify_started(); // copy has been made; tell we are running __t->_M_run(); } if (free_rtos_std::s_key) free_rtos_std::s_key->CallDestructor(__gthread_t::self().native_task_handle()); local.notify_joined(); // finished; release joined threads } thread::_State::~_State() = default; void thread::_M_start_thread(_State_ptr state, void (*)()) { const int err = __gthread_create( &_M_id._M_thread, __execute_native_thread_routine, state.get()); if (err) __throw_system_error(err); state.release(); } void thread::join() { id invalid; if (_M_id._M_thread != invalid._M_thread) __gthread_join(_M_id._M_thread, nullptr); else __throw_system_error(EINVAL); // destroy the handle explicitly - next call to join/detach will throw _M_id = std::move(invalid); } void thread::detach() { id invalid; if (_M_id._M_thread != invalid._M_thread) __gthread_detach(_M_id._M_thread); else __throw_system_error(EINVAL); // destroy the handle explicitly - next call to join/detach will throw _M_id = std::move(invalid); } // Returns the number of concurrent threads supported by the implementation. // The value should be considered only a hint. // // Return value // Number of concurrent threads supported. If the value is not well defined // or not computable, returns ​0​. unsigned int thread::hardware_concurrency() noexcept { return 0; // not computable } void this_thread::__sleep_for(chrono::seconds sec, chrono::nanoseconds nsec) { long ms = nsec.count() / 1'000'000; if (sec.count() == 0 && ms == 0 && nsec.count() > 0) ms = 1; // round up to 1 ms => if sleep time != 0, sleep at least 1ms vTaskDelay(pdMS_TO_TICKS(chrono::milliseconds(sec).count() + ms)); } } // namespace std
31.845455
85
0.697688
klepsydra-technologies
560f33837d3c3bcaf97b6dc85c652c32a9b3aa39
13,402
cc
C++
src/libxtp/jobcalculators/iexcitoncl.cc
choudarykvsp/xtp
9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a
[ "Apache-2.0" ]
1
2018-03-05T17:36:53.000Z
2018-03-05T17:36:53.000Z
src/libxtp/jobcalculators/iexcitoncl.cc
choudarykvsp/xtp
9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a
[ "Apache-2.0" ]
null
null
null
src/libxtp/jobcalculators/iexcitoncl.cc
choudarykvsp/xtp
9a249fd34615abcf790d5f0ecd3ddf1ed0ac0e7a
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2009-2017 The VOTCA Development Team * (http://www.votca.org) * * 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 "iexcitoncl.h" #include <boost/format.hpp> #include <boost/filesystem.hpp> #include <votca/tools/constants.h> #include <boost/numeric/ublas/matrix_proxy.hpp> #include <boost/numeric/ublas/vector_proxy.hpp> #include <votca/tools/propertyiomanipulator.h> #include <votca/ctp/logger.h> #include <votca/ctp/xinteractor.h> using namespace boost::filesystem; using namespace votca::tools; namespace ub = boost::numeric::ublas; namespace votca { namespace xtp { // +++++++++++++++++++++++++++++ // // IEXCITON MEMBER FUNCTIONS // // +++++++++++++++++++++++++++++ // void IEXCITON::Initialize(tools::Property* options ) { cout << endl << "... ... Initialized with " << _nThreads << " threads. " << flush; _maverick = (_nThreads == 1) ? true : false; _induce= false; _statenumber=1; _epsilon=1; _cutoff=-1; string key = "options."+Identify(); if ( options->exists(key+".job_file")) { _jobfile = options->get(key+".job_file").as<string>(); } else { throw std::runtime_error("Job-file not set. Abort."); } key = "options." + Identify(); if ( options->exists(key+".mapping")) { _xml_file = options->get(key+".mapping").as<string>(); } else { throw std::runtime_error("Mapping-file not set. Abort."); } if ( options->exists(key+".emp_file")) { _emp_file = options->get(key+".emp_file").as<string>(); } else { throw std::runtime_error("Emp-file not set. Abort."); } if ( options->exists(key+".statenumber")) { _statenumber=options->get(key+".statenumber").as<int>(); } else { cout << endl << "Statenumber not specified, assume singlet s1 " << flush; _statenumber=1; } if ( options->exists(key+".epsilon")) { _epsilon=options->get(key+".epsilon").as<double>(); } else{ _epsilon=1; } if ( options->exists(key+".cutoff")) { _cutoff=options->get(key+".cutoff").as<double>(); } else{ _cutoff=-1; } if ( options->exists(key+".induce")) { _induce = options->get(key+".induce").as<bool>(); } cout << "done"<< endl; } void IEXCITON::PreProcess(ctp::Topology *top) { // INITIALIZE MPS-MAPPER (=> POLAR TOP PREP) cout << endl << "... ... Initialize MPS-mapper: " << flush; _mps_mapper.GenerateMap(_xml_file, _emp_file, top); } void IEXCITON::CustomizeLogger(ctp::QMThread *thread) { // CONFIGURE LOGGER ctp::Logger* log = thread->getLogger(); log->setReportLevel(ctp::logDEBUG); log->setMultithreading(_maverick); log->setPreface(ctp::logINFO, (boost::format("\nT%1$02d INF ...") % thread->getId()).str()); log->setPreface(ctp::logERROR, (boost::format("\nT%1$02d ERR ...") % thread->getId()).str()); log->setPreface(ctp::logWARNING, (boost::format("\nT%1$02d WAR ...") % thread->getId()).str()); log->setPreface(ctp::logDEBUG, (boost::format("\nT%1$02d DBG ...") % thread->getId()).str()); } ctp::Job::JobResult IEXCITON::EvalJob(ctp::Topology *top, ctp::Job *job, ctp::QMThread *opThread) { // report back to the progress observer ctp::Job::JobResult jres = ctp::Job::JobResult(); // get the logger from the thread ctp::Logger* pLog = opThread->getLogger(); // get the information about the job executed by the thread int _job_ID = job->getId(); Property _job_input = job->getInput(); list<Property*> segment_list = _job_input.Select( "segment" ); int ID_A = segment_list.front()->getAttribute<int>( "id" ); string type_A = segment_list.front()->getAttribute<string>( "type" ); string mps_fileA = segment_list.front()->getAttribute<string>( "mps_file" ); int ID_B = segment_list.back()->getAttribute<int>( "id" ); string type_B = segment_list.back()->getAttribute<string>( "type" ); string mps_fileB = segment_list.back()->getAttribute<string>( "mps_file" ); ctp::Segment *seg_A = top->getSegment( ID_A ); assert( seg_A->getName() == type_A ); ctp::Segment *seg_B = top->getSegment( ID_B ); assert( seg_B->getName() == type_B ); CTP_LOG(ctp::logINFO,*pLog) << ctp::TimeStamp() << " Evaluating pair " << _job_ID << " [" << ID_A << ":" << ID_B << "]" << flush; vector<ctp::APolarSite*> seg_A_raw=ctp::APS_FROM_MPS(mps_fileA,0,opThread); vector<ctp::APolarSite*> seg_B_raw=ctp::APS_FROM_MPS(mps_fileB,0,opThread); ctp::PolarSeg* seg_A_polar=_mps_mapper.MapPolSitesToSeg(seg_A_raw,seg_A); ctp::PolarSeg* seg_B_polar=_mps_mapper.MapPolSitesToSeg(seg_B_raw,seg_B); double JAB=EvaluatePair(top,seg_A_polar,seg_B_polar, pLog); std::vector< ctp::APolarSite* >::iterator it; for (it = seg_A_raw.begin() ; it !=seg_A_raw.end(); ++it){ delete *it; } seg_A_raw.clear(); for (it = seg_B_raw.begin() ; it !=seg_B_raw.end(); ++it){ delete *it; } seg_B_raw.clear(); delete seg_A_polar; delete seg_B_polar; Property _job_summary; Property *_job_output = &_job_summary.add("output",""); Property *_pair_summary = &_job_output->add("pair",""); string nameA = seg_A->getName(); string nameB = seg_B->getName(); _pair_summary->setAttribute("idA", ID_A); _pair_summary->setAttribute("idB", ID_B); _pair_summary->setAttribute("typeA", nameA); _pair_summary->setAttribute("typeB", nameB); Property *_coupling_summary = &_pair_summary->add("Coupling",""); _coupling_summary->setAttribute("jABstatic", JAB); jres.setOutput( _job_summary ); jres.setStatus(ctp::Job::COMPLETE); return jres; } double IEXCITON::EvaluatePair(ctp::Topology *top,ctp::PolarSeg* Seg1,ctp::PolarSeg* Seg2, ctp::Logger* pLog ){ ctp::XInteractor actor; actor.ResetEnergy(); Seg1->CalcPos(); Seg2->CalcPos(); vec s=top->PbShortestConnect(Seg1->getPos(),Seg2->getPos())+Seg1->getPos()-Seg2->getPos(); //CTP_LOG(logINFO, *pLog) << "Evaluate pair for debugging " << Seg1->getId() << ":" <<Seg2->getId() << " Distance "<< abs(s) << flush; ctp::PolarSeg::iterator pit1; ctp::PolarSeg::iterator pit2; double E=0.0; for (pit1=Seg1->begin();pit1<Seg1->end();++pit1){ for (pit2=Seg2->begin();pit2<Seg2->end();++pit2){ actor.BiasIndu(*(*pit1), *(*pit2),s); (*pit1)->Depolarize(); (*pit2)->Depolarize(); E += actor.E_f(*(*pit1), *(*pit2)); } } if(_cutoff>=0){ if(abs(s)>_cutoff){ E=E/_epsilon; } } return E*conv::int2eV; } void IEXCITON::WriteJobFile(ctp::Topology *top) { cout << endl << "... ... Writing job file " << flush; std::ofstream ofs; ofs.open(_jobfile.c_str(), std::ofstream::out); if (!ofs.is_open()) throw runtime_error("\nERROR: bad file handle: " + _jobfile); ctp::QMNBList::iterator pit; ctp::QMNBList &nblist = top->NBList(); int jobCount = 0; if (nblist.size() == 0) { cout << endl << "... ... No pairs in neighbor list, skip." << flush; return; } ofs << "<jobs>" << endl; string tag = ""; for (pit = nblist.begin(); pit != nblist.end(); ++pit) { if ((*pit)->getType()==3){ int id1 = (*pit)->Seg1()->getId(); string name1 = (*pit)->Seg1()->getName(); int id2 = (*pit)->Seg2()->getId(); string name2 = (*pit)->Seg2()->getName(); int id = ++jobCount; string mps_file1=(boost::format("MP_FILES/%s_n2s%d.mps") % name1 % _statenumber).str(); string mps_file2=(boost::format("MP_FILES/%s_n2s%d.mps") % name1 % _statenumber).str(); Property Input; Property *pInput = &Input.add("input",""); Property *pSegment = &pInput->add("segment" , boost::lexical_cast<string>(id1) ); pSegment->setAttribute<string>("type", name1 ); pSegment->setAttribute<int>("id", id1 ); pSegment->setAttribute<string>("mps_file",mps_file1); pSegment = &pInput->add("segment" , boost::lexical_cast<string>(id2) ); pSegment->setAttribute<string>("type", name2 ); pSegment->setAttribute<int>("id", id2 ); pSegment->setAttribute<string>("mps_file",mps_file2); ctp::Job job(id, tag, Input, ctp::Job::AVAILABLE ); job.ToStream(ofs,"xml"); } } // CLOSE STREAM ofs << "</jobs>" << endl; ofs.close(); cout << endl << "... ... In total " << jobCount << " jobs" << flush; } void IEXCITON::ReadJobFile(ctp::Topology *top) { Property xml; vector<Property*> records; // gets the neighborlist from the topology ctp::QMNBList &nblist = top->NBList(); int _number_of_pairs = nblist.size(); int _current_pairs=0; // output using logger ctp::Logger _log; _log.setReportLevel(ctp::logINFO); // load the QC results in a vector indexed by the pair ID load_property_from_xml(xml, _jobfile); list<Property*> jobProps = xml.Select("jobs.job"); records.resize( _number_of_pairs + 1 ); //to skip pairs which are not in the jobfile for (unsigned i=0;i<records.size();i++){ records[i]=NULL; } // loop over all jobs = pair records in the job file for (list<Property*> ::iterator it = jobProps.begin(); it != jobProps.end(); ++it) { // if job produced an output, then continue with analysis if ( (*it)->exists("output") && (*it)->exists("output.pair") ) { _current_pairs++; // get the output records Property& poutput = (*it)->get("output.pair"); // id's of two segments of a pair int idA = poutput.getAttribute<int>("idA"); int idB = poutput.getAttribute<int>("idB"); // segments which correspond to these ids ctp::Segment *segA = top->getSegment(idA); ctp::Segment *segB = top->getSegment(idB); // pair that corresponds to the two segments ctp::QMPair *qmp = nblist.FindPair(segA,segB); if (qmp == NULL) { // there is no pair in the neighbor list with this name CTP_LOG_SAVE(ctp::logINFO, _log) << "No pair " << idA << ":" << idB << " found in the neighbor list. Ignoring" << flush; } else { //CTP_LOG(logINFO, _log) << "Store in record: " << idA << ":" << idB << flush; records[qmp->getId()] = & ((*it)->get("output.pair")); } } else { Property thebadone = (*it)->get("id"); throw runtime_error("\nERROR: Job file incomplete.\n Job with id "+thebadone.as<string>()+" is not finished. Check your job file for FAIL, AVAILABLE, or ASSIGNED. Exiting\n"); } } // finished loading from the file // loop over all pairs in the neighbor list CTP_LOG_SAVE(ctp::logINFO, _log) << "Neighborlist size " << top->NBList().size() << flush; for (ctp::QMNBList::iterator ipair = top->NBList().begin(); ipair != top->NBList().end(); ++ipair) { ctp::QMPair *pair = *ipair; if (records[ pair->getId() ]==NULL) continue; //skip pairs which are not in the jobfile //Segment* segmentA = pair->Seg1(); //Segment* segmentB = pair->Seg2(); double Jeff2 = 0.0; double jAB=0.0; //cout << "\nProcessing pair " << segmentA->getId() << ":" << segmentB->getId() << flush; if ( pair->getType() == ctp::QMPair::Excitoncl){ Property* pair_property = records[ pair->getId() ]; list<Property*> pCoupling = pair_property->Select("Coupling"); for (list<Property*> ::iterator itCoupling = pCoupling.begin(); itCoupling != pCoupling.end(); ++itCoupling) { jAB = (*itCoupling)->getAttribute<double>("jABstatic"); } Jeff2 = jAB*jAB; pair->setJeff2(Jeff2, 2); pair->setIsPathCarrier(true, 2); } } CTP_LOG_SAVE(ctp::logINFO, _log) << "Pairs [total:updated] " << _number_of_pairs << ":" << _current_pairs << flush; cout << _log; } }};
32.687805
187
0.565065
choudarykvsp
5610b425a0cc434a6c9d241aecaf7bc4bae58eca
1,198
cpp
C++
5Graph_accesses_using_BGL.cpp
mohsenuss91/BGL_workshop
03d2bea291d4c6d67e7ddcd562694a0b7ecc5130
[ "MIT" ]
1
2015-02-12T18:40:32.000Z
2015-02-12T18:40:32.000Z
5Graph_accesses_using_BGL.cpp
mohsenuss91/IBM_BGL
03d2bea291d4c6d67e7ddcd562694a0b7ecc5130
[ "MIT" ]
null
null
null
5Graph_accesses_using_BGL.cpp
mohsenuss91/IBM_BGL
03d2bea291d4c6d67e7ddcd562694a0b7ecc5130
[ "MIT" ]
null
null
null
#include <iostream> #include <boost/graph/adjacency_list.hpp> using namespace boost; using namespace std; typedef property<edge_weight_t, int> EdgeWeightProperty; typedef property<edge_weight_t, int> EdgeWeightProperty; typedef boost::adjacency_list < listS, vecS, undirectedS, no_property, EdgeWeightProperty> mygraph; int main() { mygraph g; add_edge (0, 1, 8, g); add_edge (0, 3, 18, g); add_edge (1, 2, 20, g); add_edge (2, 3, 2, g); add_edge (3, 1, 1, g); add_edge (1, 3, 7, g); cout << "Number of edges: " << num_edges(g) << "\n"; cout << "Number of vertices: " << num_vertices(g) << "\n"; mygraph::vertex_iterator vertexIt, vertexEnd; tie(vertexIt, vertexEnd) = vertices(g); for (; vertexIt != vertexEnd; ++vertexIt) { std::cout << "in-degree for " << *vertexIt << ": "<< in_degree(*vertexIt, g) << "\n"; std::cout << "out-degree for " << *vertexIt << ": "<< out_degree(*vertexIt, g) << "\n"; } mygraph::edge_iterator edgeIt, edgeEnd; tie(edgeIt, edgeEnd) = edges(g); for (; edgeIt!= edgeEnd; ++edgeIt) { std::cout << "edge " << source(*edgeIt, g) << "-->"<< target(*edgeIt, g) << "\n"; } }
36.30303
99
0.600167
mohsenuss91
561102d0305d5e59c254b50186f862a1506e482d
25,650
cpp
C++
pikoc/src/PikoSummary.cpp
piko-dev/piko-public
8d7ab461de155992ca75e839f406670279fb6bad
[ "BSD-3-Clause" ]
15
2015-05-19T08:23:26.000Z
2021-11-26T02:59:36.000Z
pikoc/src/PikoSummary.cpp
piko-dev/piko-public
8d7ab461de155992ca75e839f406670279fb6bad
[ "BSD-3-Clause" ]
null
null
null
pikoc/src/PikoSummary.cpp
piko-dev/piko-public
8d7ab461de155992ca75e839f406670279fb6bad
[ "BSD-3-Clause" ]
4
2015-10-06T15:14:43.000Z
2020-02-20T13:17:11.000Z
#include "PikoSummary.hpp" #include <algorithm> #include <sstream> using namespace std; bool compBranchesFurthest(vector<stageSummary*> a, vector<stageSummary*> b) { return (a[0]->distFromDrain > b[0]->distFromDrain); } bool compBranchesClosest(vector<stageSummary*> a, vector<stageSummary*> b) { return (a[0]->distFromDrain < b[0]->distFromDrain); } bool isInCycleRecur(stageSummary *target, stageSummary *path, vector<stageSummary*> visited) { // if a stage looped around to itself if(target == path) return true; else { // if we haven't been to this stage already if(std::find(visited.begin(), visited.end(), path) == visited.end()) { visited.push_back(path); bool ret = false; for(unsigned i=0; i<path->prevStages.size(); i++) { ret |= isInCycleRecur(target, path->prevStages[i], visited); } return ret; } else return false; } } bool isInCycle(stageSummary *target, stageSummary *path) { vector<stageSummary*> visited; return isInCycleRecur(target, path, visited); } bool branchReady(vector<stageSummary*> branch, vector<stageSummary*> doneStages, int whichSchedule) { vector<stageSummary*> ds = doneStages; for(unsigned i=0; i<branch.size(); i++) { if(branch[i]->prevStages.size() == 0) { ds.push_back(branch[i]); } else { // check endStage dependencies if(branch[i]->schedules[whichSchedule].endStagePtr!=NULL && std::find(ds.begin(), ds.end(), branch[i]->schedules[whichSchedule].endStagePtr) == ds.end()) return false; // check previous stage dependencies for(unsigned j=0; j<branch[i]->prevStages.size(); j++) { stageSummary *curPrevStage = branch[i]->prevStages[j]; // if a previous stage is not the current stage (for self-cyclic stages) and // the previous stage is not done yet if(/*curPrevStage != branch[i] && */std::find(ds.begin(), ds.end(), curPrevStage) == ds.end() && !isInCycle(branch[i], curPrevStage)) return false; else ds.push_back(branch[i]); } } } return true; } // generate kernel plan void PipeSummary::generateKernelPlan(ostream& outfile){ // step 1: discover drain nodes //printf("-----------\n"); printf("%s (%s)\n",this->name.c_str(),this->filename.c_str()); for(unsigned printi=0; printi<(this->name.length() + this->filename.length() + 3); printi++) printf("="); printf("\n"); printf("* Drain stages: "); for(unsigned i=0; i<stages.size(); i++){ if(stages[i].nextStages.size() == 0){ printf("[%s] ",stages[i].name.c_str()); drainStages.push_back(&stages[i]); stages[i].distFromDrain=0; updateDrainDistance(&stages[i]); } } printf("\n"); //printf("Drain distances:\n"); //for(unsigned i=0; i<stages.size(); i++){ // printf("\t[%d] %s\n",stages[i].distFromDrain, stages[i].name.c_str()); //} // step 2. sort by drain distances //sort(stages.begin(), stages.end(), stageSummary::higherDrainDist); // step 3. discover preschedule candidates for(unsigned i=0; i<stages.size(); i++){ if(stages[i].schedules[0].schedPolicy == schedDirectMap || stages[i].schedules[0].schedPolicy == schedSerialize){ stages[i].schedules[0].isPreScheduleCandidate = true; } } // divide pipeline into branches vector< vector<stageSummary*> > branches; { vector<stageSummary*> inBranch; // create branches and add first stage to each // new branch created if the stage: // 1) my only parent is myself // 2) has no previous stage OR // 3) has multiple previous stages OR // 4) is the child of a stage with mulitple next stages for(unsigned i=0; i<stages.size(); i++) { bool isInBranch = std::find(inBranch.begin(), inBranch.end(), &stages[i]) != inBranch.end(); // If my only parent is myself, make new branch if(!isInBranch && stages[i].prevStages.size() == 1 && stages[i].prevStages[0] == &stages[i]) { vector<stageSummary*> tmp; tmp.push_back(&stages[i]); inBranch.push_back(&stages[i]); branches.push_back(tmp); } // Does 2 and 3 else if(!isInBranch && (stages[i].prevStages.size() == 0 || stages[i].prevStages.size() > 1) ) { vector<stageSummary*> tmp; tmp.push_back(&stages[i]); inBranch.push_back(&stages[i]); branches.push_back(tmp); } // Does 4 if(stages[i].nextStages.size() > 1) { if(stages[i].nextStages.size() == 2 && (stages[i].nextStages[0] == &stages[i] || stages[i].nextStages[1] == &stages[i]) ) { } else { for(unsigned j=0; j<stages[i].nextStages.size(); j++) { stageSummary *candidate = stages[i].nextStages[j]; if(std::find(inBranch.begin(), inBranch.end(), candidate) == inBranch.end()) { vector<stageSummary*> tmp; tmp.push_back(candidate); inBranch.push_back(candidate); branches.push_back(tmp); } } } } } // find other stages in each branch for(unsigned i=0; i<branches.size(); i++) { int stgNum = 0; bool done = false; while(!done) { if(branches[i][stgNum]->nextStages.size() == 0) done = true; else { stageSummary *candidate = branches[i][stgNum]->nextStages[0]; if(candidate == branches[i][stgNum] && branches[i][stgNum]->nextStages.size() > 1) candidate = branches[i][stgNum]->nextStages[1]; // if stage not already in a branch if(std::find(inBranch.begin(), inBranch.end(), candidate) == inBranch.end()) { // if stage has a Custom dependency, push to new branch if(candidate->schedules[0].waitPolicy == waitCustom) { vector<stageSummary*> tmp; tmp.push_back(candidate); inBranch.push_back(candidate); branches.push_back(tmp); done = true; } // else if stage has EndStage dependency else if(candidate->schedules[0].waitPolicy == waitEndStage) { // if the EndStagePtr is not in the current branch if(std::find(branches[i].begin(), branches[i].end(), candidate->schedules[0].endStagePtr) == branches[i].end()) { // push to new branch vector<stageSummary*> tmp; tmp.push_back(candidate); inBranch.push_back(candidate); branches.push_back(tmp); done = true; } else { // add to current branch branches[i].push_back(candidate); inBranch.push_back(candidate); stgNum += 1; } } else { branches[i].push_back(candidate); inBranch.push_back(candidate); stgNum += 1; } } else done = true; } } } /* for(unsigned i=0; i<branches.size(); i++) { for(unsigned j=0; j<branches[i].size(); j++) { printf("Branch %d Stage %d - %s\n",i,j,branches[i][j]->name.c_str()); } } */ // sort branches by distFromDrain - furthest comes first or closest comes first sort(branches.begin(), branches.end(), compBranchesFurthest); // furthest from drain are scheduled first //sort(branches.begin(), branches.end(), compBranchesClosest); // closest drain are scheduled first } // schedule branches in this order: // furthest from drain stages come first // if dependent on another branch, skip to next branch and come back afterwards int curKernelID = 0; int curBranchNum = 0; int curBucketLoopLevel = 0; int lastBucketLoopLevel = 0; int curBucketLoopID = -1; vector<stageSummary*> doneStages; while(branches.size() > 0) { if(curBranchNum == branches.size()) break; vector<stageSummary*> curBranch = branches[curBranchNum]; //printf("attempting %d\n", curBranchNum); if( branchReady(curBranch, doneStages, 0) ) { //printf("scheduling %d\n", curBranchNum); // schedule branch vector<stageSummary*> almostDoneStages; vec2i lastBinsize = curBranch[0]->binsize; for(unsigned i=0; i<curBranch.size(); i++) { stagesInOrder.push_back(curBranch[i]); assignBinSummary& ass = curBranch[i]->assignBin; scheduleSummary& sch = curBranch[i]->schedules[0]; processSummary& pro = curBranch[i]->process; int nextKernelID = curKernelID+1; int lastBucketLoopLevel = curBucketLoopLevel; int lastBucketLoopID = curBucketLoopID; if(preferDepthFirst && sch.schedPolicy != schedAll) { if(i>0) { if(curBranch[i-1]->process.bucketLoopLevel == 0 || sch.waitPolicy == waitEndStage) curBucketLoopLevel = 0; else { //bool sameBinSize = (curBranch[i]->binsize == (curBranch[i-1]->binsize)); //bool secondLarger = (curBranch[i]->binsize[0] > (curBranch[i-1]->binsize[0]) // || curBranch[i]->binsize[1] > (curBranch[i-1]->binsize[1])); //bool secondLarger = (curBranch[i]->binsize[0] > lastBinsize[0] // || curBranch[i]->binsize[1] > lastBinsize[1]); int lastBinX = (lastBinsize[0] == 0) ? INT_MAX : lastBinsize[0]; int lastBinY = (lastBinsize[1] == 0) ? INT_MAX : lastBinsize[1]; int curBinX = (curBranch[i]->binsize[0] == 0) ? INT_MAX : curBranch[i]->binsize[0]; int curBinY = (curBranch[i]->binsize[1] == 0) ? INT_MAX : curBranch[i]->binsize[1]; bool secondLarger = (curBinX > lastBinX || curBinY > lastBinY); if(secondLarger) curBucketLoopLevel = 0; else { curBucketLoopLevel = lastBucketLoopLevel; curBucketLoopID = lastBucketLoopID; } } } else { curBucketLoopLevel = 0; } } else { if(sch.schedPolicy != schedAll) curBucketLoopLevel = 0; else if(sch.waitPolicy == waitEndStage) { curBucketLoopLevel = 1; curBucketLoopID = lastBucketLoopID+1; lastBinsize = curBranch[i]->binsize; } else { if(i>0){ //&& !(sch.binsize==(curBranch[i-1]->schedules[0].binsize))) if(curBranch[i-1]->process.bucketLoopLevel == 0) { curBucketLoopLevel = 1; curBucketLoopID = lastBucketLoopID+1; } else { //bool secondLarger = (curBranch[i]->binsize[0] > lastBinsize[0] // || curBranch[i]->binsize[1] > lastBinsize[1]); bool sameBinSize = (curBranch[i]->binsize == lastBinsize); int lastBinX = (lastBinsize[0] == 0) ? INT_MAX : lastBinsize[0]; int lastBinY = (lastBinsize[1] == 0) ? INT_MAX : lastBinsize[1]; int curBinX = (curBranch[i]->binsize[0] == 0) ? INT_MAX : curBranch[i]->binsize[0]; int curBinY = (curBranch[i]->binsize[1] == 0) ? INT_MAX : curBranch[i]->binsize[1]; bool secondLarger = (curBinX > lastBinX || curBinY > lastBinY); if(sameBinSize) { curBucketLoopLevel = lastBucketLoopLevel; curBucketLoopID = lastBucketLoopID; } else if(secondLarger) { curBucketLoopLevel = 1; curBucketLoopID = lastBucketLoopID+1; } else { curBucketLoopLevel = lastBucketLoopLevel+1; curBucketLoopID = lastBucketLoopID+1; } } } else{ curBucketLoopLevel = 1; curBucketLoopID = lastBucketLoopID+1; } lastBinsize = curBranch[i]->binsize; } } ass.kernelID = curKernelID; ass.bucketLoopLevel = curBucketLoopLevel; ass.bucketLoopID = (curBucketLoopLevel == 0) ? -1 : curBucketLoopID; if(i==0 && ass.policy != assignEmpty) curKernelID = nextKernelID; if(i>0 && !canFuse(*curBranch[i-1],*curBranch[i],0,doneStages)) { curKernelID = nextKernelID; for(unsigned j=0; j<almostDoneStages.size(); j++) doneStages.push_back(almostDoneStages[j]); almostDoneStages.clear(); //doneStages.push_back(curBranch[i-1]); } almostDoneStages.push_back(curBranch[i]); // if last iteration, add all almostDoneStages to doneStages if(i == curBranch.size()-1) { for(unsigned j=0; j<almostDoneStages.size(); j++) doneStages.push_back(almostDoneStages[j]); almostDoneStages.clear(); } sch.kernelID = curKernelID; sch.bucketLoopLevel = curBucketLoopLevel; sch.bucketLoopID = (curBucketLoopLevel == 0) ? -1 : curBucketLoopID; // TODO: Think about what PreScheduleCandiate means, and whether schedAll should be a preschedule candidate if(sch.isPreScheduleCandidate) sch.kernelID = ass.kernelID; else if((sch.schedPolicy != schedLoadBalance && sch.schedPolicy != schedAll) || !sch.trivial) curKernelID += 1; pro.kernelID = curKernelID; pro.bucketLoopLevel = curBucketLoopLevel; pro.bucketLoopID = (curBucketLoopLevel == 0) ? -1 : curBucketLoopID; for(unsigned k=0; k<curBranch[i]->nextStages.size(); k++) { stageSummary *tmp = curBranch[i]->nextStages[k]; if(std::find(doneStages.begin(), doneStages.end(), tmp) != doneStages.end() || std::find(almostDoneStages.begin(), almostDoneStages.end(), tmp) != almostDoneStages.end()) { tmp->loopStart = true; curBranch[i]->loopEnd = true; printf("\nRepeat kernels %d through %d as necessary\n\n",tmp->assignBin.kernelID,curKernelID); } } // special case for self-cyclic cycles if(curBranch[i]->nextStages.size() == 2 && (curBranch[i]->nextStages[0] == curBranch[i] || curBranch[i]->nextStages[1] == curBranch[i]) ) { curKernelID += 1; } } // remove branch from list branches.erase(branches.begin() + curBranchNum); curBranchNum = 0; curKernelID += 1; } else curBranchNum += 1; } assertPrint(branches.size() == 0, "Assert failed: There are unscheduled branches remaining.\n"); // // {{{ old planner // vector<stageSummary*> doneStages; // // int curKernelID = 0; // for(unsigned i=0; i<stages.size(); i++){ // // assignBinSummary& ass = stages[i].assignBin; // scheduleSummary& sch = stages[i].schedules[0]; // processSummary& pro = stages[i].process; // // int nextKernelID = curKernelID+1; // // ass.kernelID = curKernelID; // // if(i>0 && !canFuse(stages[i-1],stages[i],0,doneStages)){ // curKernelID = nextKernelID; // // doneStages.push_back(&stages[i-1]); // } // // sch.kernelID = curKernelID; // // // TODO: Think about what PreScheduleCandiate means, and whether schedAll should be a preschedule candidate // if(sch.isPreScheduleCandidate) sch.kernelID = ass.kernelID; // else if(sch.schedPolicy != schedLoadBalance // && sch.schedPolicy != schedAll) curKernelID += 1; // // pro.kernelID = curKernelID; // // } // // }}} printf("* Number of Kernels: %d\n", curKernelID); printf("|Level ID|\n"); curKernelID = -1; curBucketLoopLevel = -1; curBucketLoopID = -1; for(unsigned i=0; i<stagesInOrder.size(); i++){ const stageSummary& stg = *stagesInOrder[i]; const assignBinSummary& ass = stg.assignBin; const scheduleSummary& sch = stg.schedules[0]; const processSummary& pro = stg.process; if(ass.policy != assignEmpty){ curBucketLoopID = ass.bucketLoopID; curBucketLoopLevel = ass.bucketLoopLevel; if(ass.kernelID != curKernelID) { printf("|%d %d| * Kernel %d:\n",curBucketLoopLevel,curBucketLoopID,ass.kernelID); } curKernelID = ass.kernelID; //printf("|%d-%d| - [%d] %s.AssignBin\n",curBucketLoopLevel,curBucketLoopID,stg.distFromDrain, stg.name.c_str()); printf(" - [%d] %s.AssignBin\n",stg.distFromDrain, stg.name.c_str()); } curBucketLoopID = sch.bucketLoopID; curBucketLoopLevel = sch.bucketLoopLevel; if(sch.kernelID != curKernelID) { printf("|%d %d| * Kernel %d:\n",curBucketLoopLevel,curBucketLoopID,sch.kernelID); } curKernelID = sch.kernelID; //printf("|%d-%d| - %s.Schedule%s",curBucketLoopLevel,curBucketLoopID, stg.name.c_str(), printf(" - %s.Schedule%s", stg.name.c_str(), sch.isPreScheduleCandidate? "\t<--- 1 core per block\n": sch.schedPolicy==schedLoadBalance? "\t<--- 1 bin per block\n":"\n"); // \t<--- trivialized to cuda scheduler if(pro.policy != procEmpty){ curBucketLoopID = sch.bucketLoopID; curBucketLoopLevel = pro.bucketLoopLevel; if(pro.kernelID != curKernelID) { printf("|%d %d| * Kernel %d:\n",curBucketLoopLevel,curBucketLoopID,pro.kernelID); } curKernelID = pro.kernelID; //printf("|%d-%d| - %s.Process\n",curBucketLoopLevel,curBucketLoopID, stg.name.c_str()); printf(" - %s.Process\n", stg.name.c_str()); } } printf("\n"); // commenting out kernel order code because it doesn't work yet /* printf("\tKernel order:\n"); vector< pair<int,string> > *kernOrder = new vector< pair<int,string> >(); stages[0].findKernelOrder(-1, 0, kernOrder); int curBatch = 0; printf("\tBatch %d\n", curBatch); for(unsigned int i=0; i<kernOrder->size(); ++i) { if((*kernOrder)[i].first == curBatch) printf("\t%s", (*kernOrder)[i].second.c_str()); else { curBatch = (*kernOrder)[i].first; printf("\tBatch %d\n", curBatch); printf("\t%s", (*kernOrder)[i].second.c_str()); } } */ } void stageSummary::findKernelOrder(int kernelID, int batch, vector< pair<int,string> > *order) { stringstream ss; ss.str(""); ss.clear(); int curKernelID = kernelID; int curBatch = batch; assignBinSummary& ass = assignBin; scheduleSummary& sch = schedules[0]; processSummary& pro = process; if(ass.kernelID != curKernelID) { if(ass.policy != assignEmpty) { curKernelID = ass.kernelID; ss << "\tKernel " << curKernelID << endl; } } if(sch.kernelID != curKernelID) { curKernelID = sch.kernelID; ss << "\tKernel " << curKernelID << endl; } if(pro.kernelID != curKernelID) { if(pro.policy != procEmpty) { curKernelID = pro.kernelID; ss << "\tKernel " << curKernelID << endl; } } //printf("!!! HERE 1 !!!\n"); pair<int,string> ret(curBatch, ss.str()); //printf("SIZE: %d\n", ret.second.length()); //printf("!!! HERE 2 !!!\n"); if(ret.second != "") { //printf("!!! HERE 3 !!!\n"); order->push_back(ret); //printf("!!! HERE 4 !!!\n"); ss.str(""); ss.clear(); //printf("!!! HERE 5 !!!\n"); } if(nextStages.size() > 1) curBatch += 1; for(unsigned int i=0; i<nextStages.size(); ++i) { //printf("iter = %d\n",i); //printf("!!! HERE 1 !!!\n"); if(isCurOrPrevStage(nextStages[i])) { //printf("!!! HERE 2 !!!\n"); ss << "repeat kernel " << nextStages[i]->assignBin.kernelID << " to kernel " << curKernelID << " sequence\n"; ret.first = (curBatch == batch) ? curBatch+1 : curBatch; ret.second = ss.str(); order->push_back(ret); ss.str(""); ss.clear(); } else { //printf("!!! HERE 3 !!!\n"); if(nextStages[i]->prevStages.size() > 1) nextStages[i]->findKernelOrder(curKernelID, curBatch+1, order); else if(nextStages[i]->schedules[0].waitPolicy == waitEndStage) nextStages[i]->findKernelOrder(curKernelID, curBatch+1, order); else nextStages[i]->findKernelOrder(curKernelID, curBatch, order); } } } bool stageSummary::isCurOrPrevStage(stageSummary *stg) { //printf("stg = %s\n", stg->name.c_str()); //printf("this = %s\n", this->name.c_str()); //printf("!!! HERE 1 !!!\n"); if(stg == this) return true; //printf("!!! HERE 2 !!!\n"); for(unsigned int i=0; i<prevStages.size(); ++i) { //printf("this = %s\n", this->name.c_str()); //printf("prev = %s\n", this->prevStages[i]->name.c_str()); //printf("!!! HERE 3 !!!\n"); if(prevStages[i]->isCurOrPrevStage(stg)) return true; } //printf("!!! HERE 4 !!!\n"); return false; } // update distances from drain stage (recursively) void PipeSummary::updateDrainDistance(stageSummary* stage){ if(stage != NULL){ for(unsigned i=0; i<stage->prevStages.size(); i++){ stageSummary* ps = stage->prevStages[i]; int oldDist = ps->distFromDrain; ps->distFromDrain = min(stage->distFromDrain+1, oldDist); int newDist = ps->distFromDrain; if(oldDist != newDist) updateDrainDistance(ps); } } } // update all links void PipeSummary::processLinks(){ for(unsigned i=0; i<stages.size(); i++){ // update nextStages for(unsigned j=0; j<stages[i].nextStageNames.size(); j++){ stageSummary* nextStage = findStageByName(stages[i].nextStageNames[j]); if(nextStage!=NULL){ stages[i].nextStages.push_back(nextStage); nextStage->prevStages.push_back(&stages[i]); } } // update endStagePtr if waitPolicy is set to endStage if(stages[i].schedules[0].waitPolicy == waitEndStage){ stages[i].schedules[0].endStagePtr = findStageByName(stages[i].schedules[0].endStageName); } } } // given stage name, fetch pointer stageSummary* PipeSummary::findStageByName(const string& stageName){ for(unsigned i=0; i<stages.size(); i++){ if(stageName == stages[i].name) return &stages[i]; } printf("Cannot find Stage named \"%s\"\n",stageName.c_str()); return NULL; } // given stage type, fetch pointer and return vector vector<stageSummary*> PipeSummary::findStageByType(const string& stageType){ vector<stageSummary*> ret; for(unsigned i=0; i<stages.size(); i++){ if(stageType == stages[i].type) ret.push_back(&stages[i]); } if(ret.size() > 0) return ret; else { printf("Cannot find Stage type \"%s\"\n",stageType.c_str()); exit(3); return ret; } } // display pipe summary void PipeSummary::displaySummary(){ printf("Pipe %s\n",name.c_str()); for(unsigned i=0; i<stages.size(); i++){ stageSummary& curStage = stages[i]; printf("\tStage %s\n",curStage.name.c_str()); printf("\t\tType: %s\n", curStage.type.c_str()); printf("\t\tBinsize: %d x %d\n", curStage.binsize.x(), curStage.binsize.y()); printf("\t\tNextStages: "); for(unsigned j=0; j<curStage.nextStageNames.size(); j++) printf("%s ",curStage.nextStageNames[j].c_str()); printf("\n"); printf("\t\tCode: %s\n",curStage.codeFile.c_str()); printf("\t\tAssignBin\n"); printf("\t\t\tCode: %s\n",curStage.assignBin.codeFile.c_str()); printf("\t\t\tPolicy: %s\n",toString(curStage.assignBin.policy).c_str()); printf("\t\t\ttrivial: %s\n", (curStage.assignBin.trivial) ? "true" : "false"); //printf("\t\t\tCode: %s\n",curStage.assignBin.codeFile.c_str()); for(unsigned j=0; j<curStage.schedules.size(); j++){ printf("\t\tSchedule\n"); printf("\t\t\tCode: %s\n",curStage.schedules[j].codeFile.c_str()); printf("\t\t\tArch: %s\n", toString(curStage.schedules[j].arch).c_str()); printf("\t\t\tschedPolicy: %s\n", toString(curStage.schedules[j].schedPolicy).c_str()); printf("\t\t\ttileSplitSize: %d\n", curStage.schedules[j].tileSplitSize); printf("\t\t\twaitPolicy: %s\n", toString(curStage.schedules[j].waitPolicy).c_str()); printf("\t\t\twaitBatchSize: %d\n", curStage.schedules[j].waitBatchSize); printf("\t\t\ttrivial: %s\n", (curStage.schedules[j].trivial) ? "true" : "false"); //printf("\t\t\tCode: %s\n",curStage.schedules[j].codeFile.c_str()); } printf("\t\tProcess\n"); printf("\t\t\tCode: %s\n",curStage.process.codeFile.c_str()); printf("\t\t\tMaxOutPrims: %d\n",curStage.process.maxOutPrims); printf("\t\t\ttrivial: %s\n", (curStage.process.trivial) ? "true" : "false"); //printf("\t\t\tCode: %s\n",curStage.process.codeFile.c_str()); } printf("---\n"); } bool PipeSummary::canFuse(stageSummary& s1, stageSummary& s2, int whichSchedule, vector<stageSummary*>& doneStages){ // Cannot fuse two stages if they are the same type if(s1.type == s2.type) return false; scheduleSummary& sch1 = s1.schedules[whichSchedule]; scheduleSummary& sch2 = s2.schedules[whichSchedule]; // make sure architectures match (for your sanity) if(sch1.arch != sch2.arch) return false; // we will not fuse with a stage that has multiple input paths if(s2.prevStages.size() > 1) return false; if(s1.nextStages.size() > 1) return false; // max_fan_out_per_\process ... removing for now //if(s1.process.maxOutPrims > 64 && sch2.waitPolicy!=waitNone) return false; // if dependencies are not resolved, we cannot fuse if(sch2.endStagePtr!=NULL && std::find(doneStages.begin(), doneStages.end(), sch2.endStagePtr) == doneStages.end()) return false; // the following flag will check s1 and s2 run in the same core bool sameCore = false; sameCore = sameCore; // fusing DirectMap scheduler sameCore = sameCore || ((sch2.schedPolicy == sch1.schedPolicy) && (s2.assignBin.policy == assignInBin) && (sch1.schedPolicy == schedDirectMap)); // fusing Serialize Scheduler sameCore = sameCore || ((sch2.schedPolicy == sch1.schedPolicy) && (sch1.schedPolicy == schedSerialize)); // fusing LoadBalance Scheduler sameCore = sameCore || ((sch2.schedPolicy == sch1.schedPolicy) && (s2.assignBin.policy == assignInBin) && (sch1.schedPolicy == schedLoadBalance)); bool preferLoadBalance = false; preferLoadBalance = preferLoadBalance || (sch2.schedPolicy==schedLoadBalance); if( 0//(sch2.waitPolicy == waitNone && s2.process.maxOutPrims<=8 && s2.assignBin.policy != assignCustom) || ((s2.binsize == s1.binsize) && sameCore && sch1.tileSplitSize == sch2.tileSplitSize) || 0 ) { return true; } // fusing schedAll else if(sch1.schedPolicy == schedAll && sch2.schedPolicy == schedAll && s2.assignBin.policy == assignInBin && s1.binsize == s2.binsize && sch2.waitPolicy == waitNone && sch1.tileSplitSize == sch2.tileSplitSize) { return true; } else { return false; } }
33.928571
121
0.625497
piko-dev
561158798e45c93c237c70d997d7e7d12b1867b0
804
cpp
C++
demos/tutorial/interval.cpp
tbellotti/samurai
b10fa2115d69eb184609103579ba433ff09891df
[ "BSD-3-Clause" ]
13
2021-01-07T19:23:42.000Z
2022-01-26T13:07:41.000Z
demos/tutorial/interval.cpp
gouarin/samurai
7ae877997e8b9bdb85b84acaabb3c0483ff78689
[ "BSD-3-Clause" ]
1
2021-07-04T17:30:47.000Z
2021-07-04T17:30:47.000Z
demos/tutorial/interval.cpp
gouarin/samurai
7ae877997e8b9bdb85b84acaabb3c0483ff78689
[ "BSD-3-Clause" ]
2
2021-01-07T15:54:49.000Z
2021-02-24T13:11:42.000Z
// Copyright 2021 SAMURAI TEAM. All rights reserved. // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file. #include <iostream> #include <samurai/cell_array.hpp> #include <samurai/cell_list.hpp> int main() { constexpr std::size_t dim = 2; samurai::CellList<dim> cl; cl[0][{}].add_interval({0, 2}); cl[0][{}].add_interval({5, 6}); cl[1][{}].add_interval({4, 7}); cl[1][{}].add_interval({8, 10}); cl[2][{}].add_interval({15, 17}); samurai::CellArray<dim> ca{cl}; std::cout << ca << std::endl; constexpr std::size_t start_level = 3; samurai::Box<double, dim> box({-1, -1}, {1, 1}); samurai::CellArray<dim> ca_box; ca_box[start_level] = {start_level, box}; std::cout << ca_box << std::endl; }
23.647059
53
0.614428
tbellotti
5613753614e4123daac05025841cc8649e667ba4
569
cc
C++
test/access_restriction.cc
Georepublic/valhalla
079c11978093608e730b22a52c2363d39eefdc15
[ "MIT" ]
1,947
2016-02-25T20:54:40.000Z
2022-03-30T11:13:21.000Z
test/access_restriction.cc
Bolaxax/valhalla
f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb
[ "MIT" ]
2,635
2016-02-23T15:36:46.000Z
2022-03-30T09:51:41.000Z
test/access_restriction.cc
Bolaxax/valhalla
f5e464a1f7f2d75d08ea6db6bb8418c0f500eccb
[ "MIT" ]
472
2016-03-11T09:38:02.000Z
2022-03-29T14:01:48.000Z
#include <vector> #include "baldr/accessrestriction.h" #include "test.h" using namespace std; using namespace valhalla::baldr; // Expected size is 16 bytes. We want to alert if somehow any change grows // this structure size as that indicates incompatible tiles. constexpr size_t kAccessRestrictionExpectedSize = 16; namespace { TEST(AccessRestrictions, SizeofCheck) { EXPECT_EQ(sizeof(AccessRestriction), kAccessRestrictionExpectedSize); } } // namespace int main(int argc, char* argv[]) { testing::InitGoogleTest(&argc, argv); return RUN_ALL_TESTS(); }
21.884615
74
0.764499
Georepublic
56141c4d5b7b4ebb21e15f3a26ee35acb9d1987b
11,595
cpp
C++
s4_casa/main.cpp
code-mds/grafica
604a802bf32ce5245abf249a13cadb7eb32e1fd8
[ "MIT" ]
1
2020-02-23T09:48:25.000Z
2020-02-23T09:48:25.000Z
s4_casa/main.cpp
code-mds/grafica
604a802bf32ce5245abf249a13cadb7eb32e1fd8
[ "MIT" ]
null
null
null
s4_casa/main.cpp
code-mds/grafica
604a802bf32ce5245abf249a13cadb7eb32e1fd8
[ "MIT" ]
null
null
null
//glut_test.cpp #pragma clang diagnostic ignored "-Wdeprecated-declarations" #ifdef __APPLE__ // Headers richiesti da OSX #include <GL/glew.h> #include <GLUT/glut.h> #else // headers richiesti da Windows e linux #include <GL\glew.h> #include <GL\freeglut.h> #endif #include "draw_utils.h" #define COLOR_ROOF_EXTERNAL 230, 0, 0 #define COLOR_ROOF_INTERNAL 160, 0, 0 #define COLOR_WALL_EXTERNAL 200, 200, 200 #define COLOR_WALL_INTERNAL 80, 80, 80 #define COLOR_FLOOR 160, 160, 160 const int WINDOW_WIDTH = 600; const int WINDOW_HEIGHT = 600; const float SW = 10.0f; //SCENE WIDTH const float HALF_DOOR_WIDTH = 2.0f; const float HALF_BASE_WIDTH = 5.0f; const float BASE_HEIGHT = 8.0f; const float WALL_THICK = 1.0f; const float WALL_HEIGHT = 6.0f; const float ROOF_HEIGHT = 11.0f; void draw_prism_walls(); void draw_lateral_walls(); void draw_roof(); void draw_floor(); void drawCB() { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); draw_axis(); draw_floor(); draw_lateral_walls(); draw_prism_walls(); draw_roof(); glutSwapBuffers(); } void draw_floor() { rectangle_t rect = { // floor {HALF_BASE_WIDTH / SW, 0, 0}, {HALF_BASE_WIDTH / SW, 0, -BASE_HEIGHT / SW}, {-HALF_BASE_WIDTH / SW, 0, -BASE_HEIGHT / SW}, {-HALF_BASE_WIDTH / SW, 0, 0}, COLOR_FLOOR }; draw_rectangle3D(&rect); } void draw_roof() { rectangle_t rectangles[] = { // right roof wall { { WALL_HEIGHT/SW, WALL_HEIGHT/SW, WALL_THICK / SW }, { WALL_HEIGHT/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT + WALL_THICK) / SW}, { 0, (ROOF_HEIGHT + WALL_THICK) / SW, -(BASE_HEIGHT + WALL_THICK) / SW }, { 0, (ROOF_HEIGHT + WALL_THICK) / SW, WALL_THICK / SW }, COLOR_ROOF_EXTERNAL },{ { WALL_HEIGHT/SW, HALF_BASE_WIDTH/SW, -(BASE_HEIGHT + WALL_THICK) / SW}, { WALL_HEIGHT/SW, HALF_BASE_WIDTH/SW, WALL_THICK / SW }, { 0, ROOF_HEIGHT/SW, WALL_THICK / SW }, { 0, ROOF_HEIGHT/SW, -(BASE_HEIGHT + WALL_THICK) / SW }, COLOR_ROOF_INTERNAL }, // left roof wall { { -WALL_HEIGHT/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT + WALL_THICK) / SW}, { -WALL_HEIGHT/SW, WALL_HEIGHT/SW, WALL_THICK / SW }, { 0, (ROOF_HEIGHT + WALL_THICK) / SW, WALL_THICK / SW }, { 0, (ROOF_HEIGHT + WALL_THICK) / SW, -(BASE_HEIGHT + WALL_THICK) / SW }, COLOR_ROOF_EXTERNAL },{ { -WALL_HEIGHT/SW, HALF_BASE_WIDTH/SW, WALL_THICK / SW }, { -WALL_HEIGHT/SW, HALF_BASE_WIDTH/SW, -(BASE_HEIGHT + WALL_THICK) / SW}, { 0, ROOF_HEIGHT/SW, -(BASE_HEIGHT + WALL_THICK) / SW }, { 0, ROOF_HEIGHT/SW, WALL_THICK / SW }, COLOR_ROOF_INTERNAL } }; draw_parallelepiped(&rectangles[0], &rectangles[1]); draw_parallelepiped(&rectangles[2], &rectangles[3]); } void draw_prism_walls() { rectangle_t rect[] = { { {HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0}, {-HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0}, {-HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -WALL_THICK / SW}, {HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -WALL_THICK / SW}, COLOR_FLOOR }, { {HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT - WALL_THICK) / SW}, {-HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT - WALL_THICK) / SW}, {-HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT) / SW}, {HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT) / SW}, COLOR_FLOOR }, }; draw_rectangle3D(&rect[0]); draw_rectangle3D(&rect[1]); vertex_t vertices[][3] = { { { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0 }, { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0 }, { 0, ROOF_HEIGHT/SW, 0 } }, { { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -WALL_THICK / SW }, { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -WALL_THICK / SW}, { 0, ROOF_HEIGHT/SW, -WALL_THICK / SW } }, { { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT)/SW }, { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT)/SW}, { 0, ROOF_HEIGHT/SW, -BASE_HEIGHT/SW } }, { { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT - WALL_THICK) / SW}, { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -(BASE_HEIGHT - WALL_THICK) / SW }, { 0, ROOF_HEIGHT/SW, -(BASE_HEIGHT - WALL_THICK) / SW } }, }; color_t frontColor = { COLOR_WALL_EXTERNAL }; color_t backColor = { COLOR_WALL_INTERNAL }; int nrOfWalls = sizeof(vertices) / sizeof(vertices[0]); for (int i = 0; i < nrOfWalls; ++i) { draw_triangle3D(&vertices[i][0], &vertices[i][1], &vertices[i][2], i%2==0 ? &frontColor : &backColor); } } void draw_lateral_walls() { rectangle_t rectangles[10] = { // front walls { { HALF_DOOR_WIDTH/SW, 0, 0 }, { HALF_BASE_WIDTH/SW, 0, 0 }, { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0 }, { HALF_DOOR_WIDTH/SW, WALL_HEIGHT/SW, 0 }, COLOR_WALL_EXTERNAL }, { { (HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -WALL_THICK / SW }, { HALF_DOOR_WIDTH/SW, 0, -WALL_THICK / SW }, { HALF_DOOR_WIDTH/SW, WALL_HEIGHT/SW, -WALL_THICK / SW }, { (HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -WALL_THICK / SW }, COLOR_WALL_INTERNAL }, { { -HALF_BASE_WIDTH/SW, 0, 0}, { -HALF_DOOR_WIDTH/SW, 0, 0 }, { -HALF_DOOR_WIDTH/SW, WALL_HEIGHT/SW, 0 }, { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0 }, COLOR_WALL_EXTERNAL }, { { -HALF_DOOR_WIDTH/SW, 0, -WALL_THICK / SW }, { -(HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -WALL_THICK / SW}, { -(HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -WALL_THICK / SW }, { -HALF_DOOR_WIDTH/SW, WALL_HEIGHT/SW, -WALL_THICK / SW }, COLOR_WALL_INTERNAL }, //right wall { { HALF_BASE_WIDTH/SW, 0, 0}, { HALF_BASE_WIDTH/SW, 0, -BASE_HEIGHT/SW }, { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -BASE_HEIGHT/SW }, { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0 }, COLOR_WALL_EXTERNAL }, { { (HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -(BASE_HEIGHT - WALL_THICK) / SW }, { (HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -WALL_THICK / SW}, { (HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -WALL_THICK / SW }, { (HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -(BASE_HEIGHT - WALL_THICK) / SW }, COLOR_WALL_INTERNAL }, // back wall { { HALF_BASE_WIDTH/SW, 0, -BASE_HEIGHT/SW }, { -HALF_BASE_WIDTH/SW, 0, -BASE_HEIGHT/SW}, { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -BASE_HEIGHT/SW }, { HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -BASE_HEIGHT/SW }, COLOR_WALL_EXTERNAL }, { { -(HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -(BASE_HEIGHT - WALL_THICK) / SW}, { (HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -(BASE_HEIGHT - WALL_THICK) / SW }, { (HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -(BASE_HEIGHT - WALL_THICK) / SW }, { -(HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -(BASE_HEIGHT - WALL_THICK) / SW }, COLOR_WALL_INTERNAL }, //left wall { { -HALF_BASE_WIDTH/SW, 0, -BASE_HEIGHT/SW}, { -HALF_BASE_WIDTH/SW, 0, 0 }, { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, 0 }, { -HALF_BASE_WIDTH/SW, WALL_HEIGHT/SW, -BASE_HEIGHT/SW }, COLOR_WALL_EXTERNAL }, { { -(HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -WALL_THICK / SW }, { -(HALF_BASE_WIDTH - WALL_THICK) / SW, 0, -(BASE_HEIGHT - WALL_THICK) / SW}, { -(HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -(BASE_HEIGHT - WALL_THICK) / SW }, { -(HALF_BASE_WIDTH - WALL_THICK) / SW, WALL_HEIGHT / SW, -WALL_THICK / SW }, COLOR_WALL_INTERNAL }, }; int nrOfWalls = sizeof(rectangles) / sizeof(rectangles[0]); for (int i = 0; i < nrOfWalls; i=i+2) { draw_parallelepiped(&rectangles[i], &rectangles[i + 1]); } } void mainMenuCB(int value) { switch (value) { case 1: toggleAxesVisibility(); break; case 2: toggleWireframeVisibility(); break; } } void init(void) { glEnable(GL_CULL_FACE); glEnable(GL_DEPTH_TEST); glClearColor(1.0, 1.0, 1.0, 0.0); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(-1.0, 1.0, -.5, 1.5, -1.0, 100.0); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Position camera at (x1, y1, z1) looking at (x2, y2, y2) with the vector <0, 1, 0> pointing upward. gluLookAt(-.6, 0.4, 1, 0, 0, 0, 0, 1, 0); glutCreateMenu(mainMenuCB); glutAddMenuEntry("Show/Hide Axes", 1); glutAddMenuEntry("Show/Hide Wireframe", 2); glutAttachMenu(GLUT_RIGHT_BUTTON); } void keyboardS(int key, int x, int y) { switch (key) { case GLUT_KEY_F1: toggleAxesVisibility(); break; case GLUT_KEY_F2: toggleWireframeVisibility(); break; case GLUT_KEY_UP: glRotatef(1.0,1.0,0.0,0.0); glutPostRedisplay(); break; case GLUT_KEY_DOWN: glRotatef(1.0,-1.0,0.0,0.0); glutPostRedisplay(); break; case GLUT_KEY_RIGHT: glRotatef(1.0,0.0,1.0,0.0); glutPostRedisplay(); break; case GLUT_KEY_LEFT: glRotatef(-1.0,0.0,1.0,0.0); glutPostRedisplay(); break; } } int main(int argc, char* argv[]) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH); glutInitWindowSize(WINDOW_WIDTH, WINDOW_HEIGHT); glutCreateWindow("S4 house"); init(); glutDisplayFunc(drawCB); glutSpecialFunc(keyboardS); glutMainLoop(); }
38.521595
113
0.508754
code-mds
561c1abb21a95704ddd42ede79cbef5a8d6bb6c3
8,368
cpp
C++
examples/depthnet/depthnet.cpp
jwkim386/Jetson_Inference
5aaba1c362b6cfca8475a41c15336dbfe03252fa
[ "MIT" ]
5,788
2016-08-22T09:09:46.000Z
2022-03-31T17:05:54.000Z
examples/depthnet/depthnet.cpp
jwkim386/Jetson_Inference
5aaba1c362b6cfca8475a41c15336dbfe03252fa
[ "MIT" ]
1,339
2016-08-15T08:51:10.000Z
2022-03-31T18:44:20.000Z
examples/depthnet/depthnet.cpp
jwkim386/Jetson_Inference
5aaba1c362b6cfca8475a41c15336dbfe03252fa
[ "MIT" ]
2,730
2016-08-23T11:04:26.000Z
2022-03-30T14:06:08.000Z
/* * Copyright (c) 2021, NVIDIA CORPORATION. All rights reserved. * * 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 "videoSource.h" #include "videoOutput.h" #include "cudaOverlay.h" #include "cudaMappedMemory.h" #include "depthNet.h" #include <signal.h> bool signal_recieved = false; void sig_handler(int signo) { if( signo == SIGINT ) { printf("received SIGINT\n"); signal_recieved = true; } } int usage() { printf("usage: depthnet [--help] [--network NETWORK]\n"); printf(" [--colormap COLORMAP] [--filter-mode MODE]\n"); printf(" [--visualize VISUAL] [--depth-size SIZE]\n"); printf(" input_URI [output_URI]\n\n"); printf("Mono depth estimation on a video/image stream using depthNet DNN.\n\n"); printf("See below for additional arguments that may not be shown above.\n\n"); printf("optional arguments:\n"); printf(" --help show this help message and exit\n"); printf(" --network=NETWORK pre-trained model to load (see below for options)\n"); printf(" --visualize=VISUAL controls what is displayed (e.g. --visualize=input,depth)\n"); printf(" valid combinations are: 'input', 'depth' (comma-separated)\n"); printf(" --depth-size=SIZE scales the size of the depth map visualization, as a\n"); printf(" percentage of the input size (default is 1.0)\n"); printf(" --filter-mode=MODE filtering mode used during visualization,\n"); printf(" options are: 'point' or 'linear' (default: 'linear')\n"); printf(" --colormap=COLORMAP depth colormap (default is 'viridis-inverted')\n"); printf(" options are: 'inferno', 'inferno-inverted',\n"); printf(" 'magma', 'magma-inverted',\n"); printf(" 'parula', 'parula-inverted',\n"); printf(" 'plasma', 'plasma-inverted',\n"); printf(" 'turbo', 'turbo-inverted',\n"); printf(" 'viridis', 'viridis-inverted'\n\n"); printf("positional arguments:\n"); printf(" input_URI resource URI of input stream (see videoSource below)\n"); printf(" output_URI resource URI of output stream (see videoOutput below)\n\n"); printf("%s", depthNet::Usage()); printf("%s", videoSource::Usage()); printf("%s", videoOutput::Usage()); printf("%s", Log::Usage()); return 0; } // // depth map buffers // typedef uchar3 pixelType; // this can be uchar3, uchar4, float3, float4 pixelType* imgDepth = NULL; // colorized depth map image pixelType* imgComposite = NULL; // original image with depth map next to it int2 inputSize; int2 depthSize; int2 compositeSize; // allocate depth map & output buffers bool allocBuffers( int width, int height, uint32_t flags, float depthScale ) { // check if the buffers were already allocated for this size if( imgDepth != NULL && width == inputSize.x && height == inputSize.y ) return true; // free previous buffers if they exit CUDA_FREE_HOST(imgDepth); CUDA_FREE_HOST(imgComposite); // allocate depth map inputSize = make_int2(width, height); depthSize = make_int2(width * depthScale, height * depthScale); if( !cudaAllocMapped(&imgDepth, depthSize) ) { LogError("depthnet: failed to allocate CUDA memory for depth map (%ix%i)\n", depthSize.x, depthSize.y); return false; } // allocate composite image compositeSize = make_int2(0,0); if( flags & depthNet::VISUALIZE_DEPTH ) { compositeSize.x += depthSize.x; compositeSize.y = depthSize.y; } if( flags & depthNet::VISUALIZE_INPUT ) { compositeSize.x += inputSize.x; compositeSize.y = inputSize.y; } if( !cudaAllocMapped(&imgComposite, compositeSize) ) { LogError("depthnet: failed to allocate CUDA memory for composite image (%ix%i)\n", compositeSize.x, compositeSize.y); return false; } return true; } int main( int argc, char** argv ) { /* * parse command line */ commandLine cmdLine(argc, argv); if( cmdLine.GetFlag("help") ) return usage(); /* * attach signal handler */ if( signal(SIGINT, sig_handler) == SIG_ERR ) LogError("can't catch SIGINT\n"); /* * create input stream */ videoSource* input = videoSource::Create(cmdLine, ARG_POSITION(0)); if( !input ) { LogError("depthnet: failed to create input stream\n"); return 0; } /* * create output stream */ videoOutput* output = videoOutput::Create(cmdLine, ARG_POSITION(1)); if( !output ) LogError("depthnet: failed to create output stream\n"); /* * create mono-depth network */ depthNet* net = depthNet::Create(cmdLine); if( !net ) { LogError("depthnet: failed to initialize depthNet\n"); return 0; } // parse the desired colormap const cudaColormapType colormap = cudaColormapFromStr(cmdLine.GetString("colormap", "viridis-inverted")); // parse the desired filter mode const cudaFilterMode filterMode = cudaFilterModeFromStr(cmdLine.GetString("filter-mode")); // parse the visualization flags const uint32_t visualizationFlags = depthNet::VisualizationFlagsFromStr(cmdLine.GetString("visualize")); // get the depth map size scaling factor const float depthScale = cmdLine.GetFloat("depth-size", 1.0); /* * processing loop */ while( !signal_recieved ) { // capture next image image pixelType* imgInput = NULL; if( !input->Capture(&imgInput, 1000) ) { // check for EOS if( !input->IsStreaming() ) break; LogError("depthnet: failed to capture next frame\n"); continue; } // allocate buffers for this size frame if( !allocBuffers(input->GetWidth(), input->GetHeight(), visualizationFlags, depthScale) ) { LogError("depthnet: failed to allocate output buffers\n"); continue; } // infer the depth and visualize the depth map if( !net->Process(imgInput, inputSize.x, inputSize.y, imgDepth, depthSize.x, depthSize.y, colormap, filterMode) ) { LogError("depthnet-camera: failed to process depth map\n"); continue; } // overlay the images into composite output image if( visualizationFlags & depthNet::VISUALIZE_INPUT ) CUDA(cudaOverlay(imgInput, inputSize, imgComposite, compositeSize, 0, 0)); if( visualizationFlags & depthNet::VISUALIZE_DEPTH ) CUDA(cudaOverlay(imgDepth, depthSize, imgComposite, compositeSize, (visualizationFlags & depthNet::VISUALIZE_INPUT) ? inputSize.x : 0, 0)); // render outputs if( output != NULL ) { output->Render(imgComposite, compositeSize.x, compositeSize.y); // update the status bar char str[256]; sprintf(str, "TensorRT %i.%i.%i | %s | Network %.0f FPS", NV_TENSORRT_MAJOR, NV_TENSORRT_MINOR, NV_TENSORRT_PATCH, net->GetNetworkName(), net->GetNetworkFPS()); output->SetStatus(str); // check if the user quit if( !output->IsStreaming() ) signal_recieved = true; } // wait for the GPU to finish CUDA(cudaDeviceSynchronize()); // print out timing info net->PrintProfilerTimes(); } /* * destroy resources */ LogVerbose("depthnet: shutting down...\n"); SAFE_DELETE(input); SAFE_DELETE(output); SAFE_DELETE(net); CUDA_FREE_HOST(imgDepth); CUDA_FREE_HOST(imgComposite); LogVerbose("depthnet: shutdown complete.\n"); return 0; }
29.568905
163
0.672204
jwkim386
561f922c3d574e6bcb611672f1e80b775df59000
310
cpp
C++
leetcode/168.cpp
Moonshile/MyAlgorithmCandy
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
[ "Apache-2.0" ]
2
2016-11-26T02:56:35.000Z
2019-06-17T04:09:02.000Z
leetcode/168.cpp
Moonshile/MyAlgorithmCandy
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
[ "Apache-2.0" ]
null
null
null
leetcode/168.cpp
Moonshile/MyAlgorithmCandy
e1ab006a5abe7d2749ae564ad2bffc4a628ed31b
[ "Apache-2.0" ]
3
2016-07-18T14:13:20.000Z
2019-06-17T04:08:32.000Z
class Solution { public: string convertToTitle(int n) { stringstream ss; do { n -= 1; ss << static_cast<char>(n%26 + 'A'); n /= 26; } while (n); string res = ss.str(); reverse(res.begin(), res.end()); return res; } };
20.666667
48
0.435484
Moonshile
561fd816353ace7a5952d7f6e20f9d364c0df184
2,363
hpp
C++
include/security_headers_middleware.hpp
hyche/bmcweb
ebc692c9d14b59ffea43f6a83d3fc1467fe09aff
[ "Apache-2.0" ]
null
null
null
include/security_headers_middleware.hpp
hyche/bmcweb
ebc692c9d14b59ffea43f6a83d3fc1467fe09aff
[ "Apache-2.0" ]
null
null
null
include/security_headers_middleware.hpp
hyche/bmcweb
ebc692c9d14b59ffea43f6a83d3fc1467fe09aff
[ "Apache-2.0" ]
null
null
null
#pragma once #include <crow/http_request.h> #include <crow/http_response.h> namespace crow { static const char* strictTransportSecurityKey = "Strict-Transport-Security"; static const char* strictTransportSecurityValue = "max-age=31536000; includeSubdomains; preload"; static const char* uaCompatabilityKey = "X-UA-Compatible"; static const char* uaCompatabilityValue = "IE=11"; static const char* xframeKey = "X-Frame-Options"; static const char* xframeValue = "DENY"; static const char* xssKey = "X-XSS-Protection"; static const char* xssValue = "1; mode=block"; static const char* contentSecurityKey = "X-Content-Security-Policy"; static const char* contentSecurityValue = "default-src 'self'"; static const char* pragmaKey = "Pragma"; static const char* pragmaValue = "no-cache"; static const char* cacheControlKey = "Cache-Control"; static const char* cacheControlValue = "no-Store,no-Cache"; struct SecurityHeadersMiddleware { struct Context { }; void beforeHandle(crow::Request& req, Response& res, Context& ctx) { #ifdef BMCWEB_INSECURE_DISABLE_XSS_PREVENTION if ("OPTIONS"_method == req.method()) { res.end(); } #endif } void afterHandle(Request& req, Response& res, Context& ctx) { /* TODO(ed) these should really check content types. for example, X-UA-Compatible header doesn't make sense when retrieving a JSON or javascript file. It doesn't hurt anything, it's just ugly. */ res.addHeader(strictTransportSecurityKey, strictTransportSecurityValue); res.addHeader(uaCompatabilityKey, uaCompatabilityValue); res.addHeader(xframeKey, xframeValue); res.addHeader(xssKey, xssValue); res.addHeader(contentSecurityKey, contentSecurityValue); res.addHeader(pragmaKey, pragmaValue); res.addHeader(cacheControlKey, cacheControlValue); #ifdef BMCWEB_INSECURE_DISABLE_XSS_PREVENTION res.addHeader("Access-Control-Allow-Origin", "http://localhost:8080"); res.addHeader("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH"); res.addHeader("Access-Control-Allow-Credentials", "true"); res.addHeader("Access-Control-Allow-Headers", "Origin, Content-Type, Accept, Cookie, X-XSRF-TOKEN"); #endif } }; } // namespace crow
32.369863
80
0.697842
hyche
562082d638a08a7b526766b534c24e7f8c3bd751
2,736
cpp
C++
philibs/img/imgfactory.cpp
prwhite/philibs
3cb65bd0dae105026839a3e88d9cebafb72c2616
[ "Zlib" ]
5
2015-05-12T14:48:03.000Z
2021-07-14T13:18:16.000Z
philibs/img/imgfactory.cpp
prwhite/philibs
3cb65bd0dae105026839a3e88d9cebafb72c2616
[ "Zlib" ]
null
null
null
philibs/img/imgfactory.cpp
prwhite/philibs
3cb65bd0dae105026839a3e88d9cebafb72c2616
[ "Zlib" ]
1
2021-04-18T07:32:43.000Z
2021-04-18T07:32:43.000Z
///////////////////////////////////////////////////////////////////// // // class: factory // ///////////////////////////////////////////////////////////////////// ///////////////////////////////////////////////////////////////////// #include "imgfactory.h" #include "pnisearchpath.h" #include "imgdds.h" #include "imgtarga.h" #include "imgcoreimage.h" #include "imgpvr.h" #include "pnidbg.h" #include <string> #include <algorithm> ///////////////////////////////////////////////////////////////////// namespace { std::string toLower ( std::string const& src ) { std::string ret = src; std::transform(ret.begin(), ret.end(), ret.begin(), ::tolower); return ret; } } namespace img { factory::factory () { addLoader("dds", [] ( std::string const& fname ) { return dds::loadHelper ( fname ); } ); // addLoader("tga", [] ( std::string const& fname ) { return targa::loadHelper ( fname ); } ); #if defined __IPHONE_7_0 || defined __MAC_10_9 auto coreImageFunc = [] ( std::string const& fname ) { return coreImage::loadHelper(fname); }; addLoader("jpg", coreImageFunc); addLoader("jpeg", coreImageFunc); addLoader("png", coreImageFunc); addLoader("tif", coreImageFunc); addLoader("tiff", coreImageFunc); addLoader("gif", coreImageFunc); auto pvrImageFunc = [] ( std::string const& fname ) { return pvr::loadHelper(fname); }; addLoader("pvr",pvrImageFunc); addLoader("pvrtc",pvrImageFunc); #endif } factory& factory::getInstance () { static factory* pFactory = 0; if ( ! pFactory ) pFactory = new factory; return *pFactory; } factory::LoadFuture factory::loadAsync ( std::string const& fname ) { return mThreadPool.enqueue( [=]() { return this->loadSync( fname ); } ); } base* factory::loadSync ( std::string const& cfname ) { std::string fname; if ( mSearchPath.resolve(cfname, fname)) { std::string extension = toLower ( pni::pstd::searchPath::ext(fname) ); auto found = mLoadFunctions.find ( extension ); if ( found != mLoadFunctions.end () ) { base* pImg = found->second ( fname ); if ( pImg ) pImg->setName(fname); return pImg; } else PNIDBGSTR("could not find loader for " << cfname); } else PNIDBGSTR("could not resolve file for " << cfname); return nullptr; } void factory::cancel ( LoadFuture const& loadFuture ) { } void factory::addLoader ( std::string const& extension, LoadFunction func ) { mLoadFunctions[ toLower ( extension ) ] = func; } void factory::remLoader ( std::string const& extension ) { auto found = mLoadFunctions.find ( toLower ( extension ) ); if ( found != mLoadFunctions.end () ) mLoadFunctions.erase ( found ); } } // end namespace img
23.586207
96
0.580775
prwhite
5620b2073705b566ef3007c03797a8b9eeeec987
631
cpp
C++
aoj/Volume23/2312/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
aoj/Volume23/2312/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
aoj/Volume23/2312/solve.cpp
tobyapi/online-judge-solutions
4088adb97ea592e8e6582ae7d2ecde2f85e2ed9c
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<algorithm> typedef long long ll; using namespace std; ll N,M,L,K[2001],sum[100001],dp[2001][2001]; ll func(ll l,ll r){ if(dp[l][r]>0)return dp[l][r]; ll n=max(l,r)+1; if(n==N)return (sum[K[n]]-sum[K[l]-1])/L+(sum[K[n]]-sum[K[r]-1])/L; ll lf=func(n,r)+(sum[K[n]]-sum[K[l]-1])/L; ll rt=func(l,n)+(sum[K[n]]-sum[K[r]-1])/L; return dp[l][r]=min(lf,rt); } int main(void){ cin >> N >> M >> L; for(int i=1;i<=N;i++)cin >> K[i]; sort(K+1,K+N+1); for(int i=1;i<=M;i++){ cin >> sum[i]; sum[i]+=sum[i-1]; } cout << func(1,1) << endl; return 0; }
15.390244
69
0.522979
tobyapi
56235951bd98c0b75c39babf30362b550366915f
88
cpp
C++
display_water_vehicle.cpp
citz73/battleship_game
1ed086c3a2bafe297725f07c32a2ba5945779977
[ "MIT" ]
null
null
null
display_water_vehicle.cpp
citz73/battleship_game
1ed086c3a2bafe297725f07c32a2ba5945779977
[ "MIT" ]
null
null
null
display_water_vehicle.cpp
citz73/battleship_game
1ed086c3a2bafe297725f07c32a2ba5945779977
[ "MIT" ]
null
null
null
#include "display_water_vehicle.h" display_water_vehicle::display_water_vehicle() { }
12.571429
46
0.806818
citz73
5625bdd8fe41ae25036baf2914048ca6aa9d75d7
1,457
cpp
C++
pus/Service9TimeManagement.cpp
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
pus/Service9TimeManagement.cpp
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
pus/Service9TimeManagement.cpp
bl4ckic3/fsfw
c76fc8c703e19d917c45a25710b4642e5923c68a
[ "Apache-2.0" ]
null
null
null
#include "Service9TimeManagement.h" #include "servicepackets/Service9Packets.h" #include "../timemanager/CCSDSTime.h" #include "../events/EventManagerIF.h" #include "../serviceinterface/ServiceInterfaceStream.h" Service9TimeManagement::Service9TimeManagement(object_id_t objectId, uint16_t apid, uint8_t serviceId) : PusServiceBase(objectId, apid , serviceId) { } Service9TimeManagement::~Service9TimeManagement() {} ReturnValue_t Service9TimeManagement::performService() { return RETURN_OK; } ReturnValue_t Service9TimeManagement::handleRequest(uint8_t subservice) { switch(subservice){ case SUBSERVICE::SET_TIME:{ return setTime(); } default: return AcceptsTelecommandsIF::INVALID_SUBSERVICE; } } ReturnValue_t Service9TimeManagement::setTime() { Clock::TimeOfDay_t timeToSet; TimePacket timePacket(currentPacket.getApplicationData(), currentPacket.getApplicationDataSize()); ReturnValue_t result = CCSDSTime::convertFromCcsds(&timeToSet, timePacket.getTime(), timePacket.getTimeSize()); if(result != RETURN_OK) { triggerEvent(CLOCK_SET_FAILURE, result, 0); return result; } uint32_t formerUptime; Clock::getUptime(&formerUptime); result = Clock::setClock(&timeToSet); if(result == RETURN_OK) { uint32_t newUptime; Clock::getUptime(&newUptime); triggerEvent(CLOCK_SET,newUptime,formerUptime); return RETURN_OK; } else { triggerEvent(CLOCK_SET_FAILURE, result, 0); return RETURN_FAILED; } }
24.694915
73
0.773507
bl4ckic3
56296f30b6ea852d654ad58454ab112417e7e3f9
11,736
hpp
C++
include/uzlmath_headers/fn_dwt.hpp
dmlux/UZLMathLib
7055c798dca6e6dc1ce0233b9ca539994feb4ade
[ "BSD-3-Clause" ]
null
null
null
include/uzlmath_headers/fn_dwt.hpp
dmlux/UZLMathLib
7055c798dca6e6dc1ce0233b9ca539994feb4ade
[ "BSD-3-Clause" ]
null
null
null
include/uzlmath_headers/fn_dwt.hpp
dmlux/UZLMathLib
7055c798dca6e6dc1ce0233b9ca539994feb4ade
[ "BSD-3-Clause" ]
null
null
null
// // fn_dwt.hpp // UZLMathLib // // Created by Denis-Michael Lux on 03.05.15. // // This software may be modified and distributed under the terms // of the BSD license. See the LICENSE file for details. // #ifndef UZLMathLib_fn_dwt_hpp #define UZLMathLib_fn_dwt_hpp UZLMATH_NAMESPACE(DWT) /*- For more information/implementation details see fn_dwt.cpp file! -*/ /*! * @brief Computes the **quadrature weights** as a vector that is used for the DWT * which is necessary for a bandwidth \f$B\f$ transform. * @details The weights vector is a vector that contains the needed weights for the * data vector. The elements can be expressed by * \f{eqnarray*}{ * w_B(j) = \frac{2}{B}\sin\left(\frac{\pi(2j+1)}{4B}\right) * \sum\limits_{k = 0}^{B-1}\frac{1}{2k + 1} * \sin\left((2j+1)(2k+1)\frac{\pi}{4B}\right) * \f} * where \f$B\f$ is the bandlimit that is given and \f$0\leq j\leq 2B-1\f$. * The dimension of this matrix is \f$2B\times 2B\f$ * * @param[in] bandwidth The given bandwidth * @return A vector containing the quadrature weights that can be used to compute the DWT * \f{eqnarray*}{ * \begingroup * \renewcommand*{\arraystretch}{1.5} * W = \left(\begin{array}{c} * w_B(0)\\ * w_B(1)\\ * \vdots\\ * w_B(2B-1) * \end{array}\right) * \endgroup * \f} * * @since 0.0.1 * * @author Denis-Michael Lux <denis.lux@icloud.com> * @date 03.05.15 */ template< typename T > inline void_number_type< T > quadrature_weights(vector< T >& vec) { if (vec.size & 1) { uzlmath_warning("%s", "uneven vector length in DWT::quadrature_weights. "); return; } int i, k, bandwidth = vec.size / 2; for (i = 0; i < bandwidth; ++i) { T wi = 2.0 / bandwidth * sin(constants< T >::pi * (2.0 * i + 1.0)/(4.0 * bandwidth)); T sum = 0; for (k = 0; k < bandwidth; ++k) { sum += 1.0 / (2.0 * k + 1.0) * sin((2.0 * i + 1.0) * (2.0 * k + 1.0) * constants< T >::pi / (4.0 * bandwidth)); } wi *= sum; vec[i] = wi; vec[2 * bandwidth - 1 - i] = wi; } } /*! * @brief The Wigner d-matrix where the weights are calculated onto the matrix values. * @details Calculates \f$d\cdot w\f$ where \f$d\f$ is matrix containing wigner * d-Function values on each entry and \f$w\f$ is diagonal matrix containing * the quadrature weights on the diagonal. * * @param[in] bandwidth The given bandwidth. * @param[in] M The order \f$M\f$ of \f$d^J_{MM'}\f$. * @param[in] Mp The order \f$M'\f$ of \f$d^J_{MM'}\f$. * @param[in] weights A vector containing the quadrature weights. * @return A matix containing weighted values of Wigner d-function. * * @sa wigner::wiger_d_matrix * @sa wigner::weight_matrix * * @since 0.0.1 * * @author Denis-Michael Lux <denis.lux@icloud.com> * @date 03.05.15 */ template< typename T > inline void_number_type< T > weighted_wigner_d_matrix(matrix< T >& wig, const int& bandwidth, const int& M, const int& Mp, const vector< T >& weights) { // Definition of used indices and the matrix that will be returned int i, j, minJ = std::max(abs(M), abs(Mp)); if ( wig.rows != bandwidth - minJ || wig.cols != 2 * bandwidth ) { uzlmath_warning("%s", "dimension mismatch between input matrix and function arguments in DWT::weighted_wigner_d_matrix."); return; } // Compute root coefficient for the base case T normFactor = sqrt((2.0 * minJ + 1.0)/2.0); for (i = 0 ; i < minJ - std::min(abs(M), abs(Mp)) ; ++i) { normFactor *= sqrt((2.0 * minJ - i) / (i + 1.0)); } // Sin sign for the recurrence base case T sinSign = (minJ == abs(M) && M >= 0 && (minJ - Mp) & 1 ? 1 : -1); sinSign = (minJ != abs(M) && Mp < 0 && (minJ - Mp) & 1 ? sinSign : -1); // Powers T cosPower, sinPower; if (minJ == abs(M) && M >= 0) { cosPower = minJ + Mp; sinPower = minJ - Mp; } else if (minJ == abs(M)) { cosPower = minJ - Mp; sinPower = minJ + Mp; } else if (Mp >= 0) { cosPower = minJ + M; sinPower = minJ - M; } else { cosPower = minJ - M; sinPower = minJ + M; } // Base cases and filling matrix with values T cosBeta[2 * bandwidth]; for (i = 0 ; i < 2 * bandwidth; ++i) { // Getting sin and cos values for the power operator T sinHalfBeta = sin(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth)); T cosHalfBeta = cos(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth)); // Store cosine values for reuse in recurrence loop cosBeta[i] = cos(((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth)); // Computing base wigners. filling the first row in matrix with those values wig(0, i) = normFactor * sinSign * pow(sinHalfBeta, sinPower) * pow(cosHalfBeta, cosPower) * weights[i]; } // Filling wigner matrix with values. Starting with second row and // iterate to last row with index B - 1 for(i = 0 ; i < bandwidth - minJ - 1; ++i) { // Recurrence coefficients T c1 = 0; // Index for wigner function T idx = minJ + i; // Terms in recurrence T norm = sqrt((2.0 * idx + 3.0) / (2.0 * idx + 1.0)); T nom = (idx + 1.0) * (2. * idx + 1.0); T den = 1.0 / sqrt(((idx + 1) * (idx + 1) - M*M) * ((idx + 1) * (idx + 1) - Mp*Mp)); // Fractions T f1 = norm * nom * den; T f2 = 0; // Correcting undefined values from division by zero if (minJ + i != 0) { T t1 = sqrt((2.0 * idx + 3.0)/(2.0 * idx - 1.0) ) * (idx + 1.0)/idx ; T t2 = sqrt((idx*idx - M*M) * (idx*idx - Mp*Mp)); c1 = -t1 * t2 * den; f2 = -M*Mp / (idx * (idx + 1.)); } // Filling matrix with next recurrence step value for (j = 0; j < 2*bandwidth; ++j) { wig(i + 1, j) = c1 * (i == 0 ? 0 : wig(i - 1, j)) + wig(i, j) * f1 * (f2 + cosBeta[j]); } } } /*! * @brief Generates the Wigner d-matrix which is a matrix that * contains the results of the \f$L^2\f$-normalized Wigner * d-function on each entry. * @details The dimension of this matrix is \f$(B-J+1)\times 2B\f$ where * \f$B\f$ denotes a given bandwidth. * * @param[in] bandwidth The given bandwidth * @param[in] M The order \f$M\f$ for the \f$L^2\f$-normalized Wigner d-function * @param[in] Mp The order \f$M'\f$ for the \f$L^2\f$-normalized Wigner d-function * @return The resulting matrix looks as follows * \f{eqnarray*}{ * \begingroup * \renewcommand*{\arraystretch}{1.5} * D = \left(\begin{array}{c c c c} * \tilde{d}^J_{M,M'}(\beta_0) & \tilde{d}^J_{M,M'}(\beta_1) * & \cdots & \tilde{d}^J_{M,M'}(\beta_{2B-1})\\ * \tilde{d}^{J+1}_{M,M'}(\beta_0) & \tilde{d}^{J+1}_{M,M'}(\beta_1) * & \cdots & \tilde{d}^{J+1}_{M,M'}(\beta_{2B-1})\\ * \vdots & \vdots & \ddots & \vdots\\ * \tilde{d}^{B-1}_{M,M'}(\beta_0) & \tilde{d}^{B-1}_{M,M'}(\beta_1) * & \cdots & \tilde{d}^{B-1}_{M,M'}(\beta_{2B-1}) * \end{array}\right) * \endgroup * \f} * with \f$\beta_k = \frac{\pi(2k + 1)}{4B}\f$ * * @since 0.0.1 * * @author Denis-Michael Lux <denis.lux@icloud.com> * @date 03.05.15 * * @see wigner::wigner_d * @see wigner::wigner_d_l2normalized */ template< typename T > inline void_number_type< T > wigner_d_matrix(matrix< T >& wig, const int& bandwidth, const int& M, const int& Mp) { // Definition of used indices and the matrix that will be returned int i, j, minJ = std::max(abs(M), abs(Mp)); if ( wig.rows != bandwidth - minJ || wig.cols != 2 * bandwidth ) { uzlmath_warning("%s", "dimension mismatch between input matrix and function arguments in DWT::weighted_wigner_d_matrix."); return; } // Compute root coefficient for the base case T normFactor = sqrt((2.0 * minJ + 1.0)/2.0); for (i = 0 ; i < minJ - std::min(abs(M), abs(Mp)) ; ++i) { normFactor *= sqrt((2.0 * minJ - i) / (i + 1.0)); } // Sin sign for the recurrence base case T sinSign = (minJ == abs(M) && M >= 0 && (minJ - Mp) & 1 ? 1 : -1 ); sinSign = (minJ != abs(M) && Mp < 0 && (minJ - Mp) & 1 ? sinSign : -1); // Powers T cosPower, sinPower; if (minJ == abs(M) && M >= 0) { cosPower = minJ + Mp; sinPower = minJ - Mp; } else if (minJ == abs(M)) { cosPower = minJ - Mp; sinPower = minJ + Mp; } else if (Mp >= 0) { cosPower = minJ + M; sinPower = minJ - M; } else { cosPower = minJ - M; sinPower = minJ + M; } // Base cases and filling matrix with values T cosBeta[2 * bandwidth]; for (i = 0 ; i < 2 * bandwidth; ++i) { // Getting sin and cos values for the power operator T sinHalfBeta = sin(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth)); T cosHalfBeta = cos(0.5 * ((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth)); // Store cosine values for reuse in recurrence loop cosBeta[i] = cos(((2.0 * i + 1.0) * constants< T >::pi) / (4.0 * bandwidth)); // Computing base wigners wig(0, i) = normFactor * sinSign * pow(sinHalfBeta, sinPower) * pow(cosHalfBeta, cosPower); } // Filling wigner matrix with values. Starting with second row and // iterate to last row with index B - 1 for(i = 0 ; i < bandwidth - minJ - 1; ++i) { // Recurrence coefficients T c1 = 0; // Index for wigner function T idx = minJ + i; // Terms in recurrence T norm = sqrt((2.0 * idx + 3.0) / (2.0 * idx + 1.0)); T nom = (idx + 1.0) * (2.0 * idx + 1.0); T den = 1.0 / sqrt(((idx + 1) * (idx + 1) - M*M) * ((idx + 1) * (idx + 1) - Mp*Mp)); // Fractions T f1 = norm * nom * den; T f2 = 0; // Correcting undefined values from division by zero if (minJ + i != 0) { T t1 = sqrt((2.0 * idx + 3.0)/(2.0 * idx - 1.0) ) * (idx + 1.0)/idx ; T t2 = sqrt((idx*idx - M*M) * (idx*idx - Mp*Mp)); c1 = -t1 * t2 * den; f2 = -M*Mp / (idx * (idx + 1.0)); } // Filling matrix with next recurrence step value for (j = 0; j < 2 * bandwidth; ++j) { wig(i + 1, j) = c1 * (i == 0 ? 0 : wig(i - 1, j)) + wig(i, j) * f1 * (f2 + cosBeta[j]); } } } UZLMATH_NAMESPACE_END #endif /* fn_dwt.hpp */
35.349398
143
0.488156
dmlux
562e5c423a39646e8abd87e6da118261201b90e5
1,311
cpp
C++
CodeSignal/Arcade/Intro/58-messageFromBinaryCode.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
6
2018-11-26T02:38:07.000Z
2021-07-28T00:16:41.000Z
CodeSignal/Arcade/Intro/58-messageFromBinaryCode.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
1
2021-05-30T09:25:53.000Z
2021-06-05T08:33:56.000Z
CodeSignal/Arcade/Intro/58-messageFromBinaryCode.cpp
ravirathee/Competitive-Programming
20a0bfda9f04ed186e2f475644e44f14f934b533
[ "Unlicense" ]
4
2020-04-16T07:15:01.000Z
2020-12-04T06:26:07.000Z
/*You are taking part in an Escape Room challenge designed specifically for programmers. In your efforts to find a clue, you've found a binary code written on the wall behind a vase, and realized that it must be an encrypted message. After some thought, your first guess is that each consecutive 8 bits of the code stand for the character with the corresponding extended ASCII code. Assuming that your hunch is correct, decode the message. Example For code = "010010000110010101101100011011000110111100100001", the output should be messageFromBinaryCode(code) = "Hello!". The first 8 characters of the code are 01001000, which is 72 in the binary numeral system. 72 stands for H in the ASCII-table, so the first letter is H. Other letters can be obtained in the same manner. Input/Output [execution time limit] 0.5 seconds (cpp) [input] string code A string, the encrypted message consisting of characters '0' and '1'. Guaranteed constraints: 0 < code.length < 800. [output] string The decrypted message. */ std::string messageFromBinaryCode(std::string code) { std::string result; for (std::size_t i = 0; i<code.size(); i+=8) { char c = static_cast<char>(std::stoi(code.substr(i, 8), nullptr, 2)); result.push_back(c); } return result; }
35.432432
382
0.727689
ravirathee
562eed95c503484ba4ceb04bff339f3592889390
18,094
cc
C++
third_party/5pt-6pt-Li-Hartley/polydet.cc
youruncleda/relative_pose
cb613f210a812e03754fbfc9c2e93d1f6fe4a265
[ "BSD-3-Clause" ]
21
2020-07-08T17:58:17.000Z
2022-02-28T03:58:37.000Z
matlab/basic_geometry/polydet.cc
leehsiu/SFRM
2d22a92ea737f0a03b949c7a7801bd56232b5717
[ "MIT" ]
null
null
null
matlab/basic_geometry/polydet.cc
leehsiu/SFRM
2d22a92ea737f0a03b949c7a7801bd56232b5717
[ "MIT" ]
5
2020-07-24T01:26:28.000Z
2020-10-13T13:32:48.000Z
// Copyright Richard Hartley, 2010 static const char *copyright = "Copyright Richard Hartley, 2010"; //-------------------------------------------------------------------------- // LICENSE INFORMATION // // 1. For academic/research users: // // This program is free for academic/research purpose: you can redistribute // it and/or modify it under the terms of the GNU General Public License as // published by the Free Software Foundation, either version 3 of the License, // or (at your option) any later version. // // Under this academic/research condition, this program is distributed in // the hope that it will be useful, but WITHOUT ANY WARRANTY; without even // the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR // PURPOSE. See the GNU General Public License for more details. // // You should have received a copy of the GNU General Public License along // with this program. If not, see <http://www.gnu.org/licenses/>. // // 2. For commercial OEMs, ISVs and VARs: // // For OEMs, ISVs, and VARs who distribute/modify/use this software // (binaries or source code) with their products, and do not license and // distribute their source code under the GPL, please contact NICTA // (www.nicta.com.au), and NICTA will provide a flexible OEM Commercial // License. // //--------------------------------------------------------------------------- #include <stdio.h> #include <stdlib.h> #include <string.h> #include <math.h> #include "hidden6.h" // #define RH_DEBUG // For generating synthetic polynomials const int ColumnDegree[] = {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2}; const int NRepetitions = 10000; int stuffit () { return 1; } static double urandom() { // Returns a real random between -1 and 1 const int MAXRAND = 65000; return 4.0*((rand()%MAXRAND)/((double) MAXRAND) - 0.5); // return rand() % 20 - 10.0; } void eval_poly (PolyMatrix &Q, PolyDegree &deg, double x) { // Evaluates the polynomial at a given value, overwriting it for (int i=0; i<Nrows; i++) for (int j=0; j<Ncols; j++) { // Evaluate the poly for (int k=deg[i][j]-1; k>=0; k--) Q[i][j][k] += x*Q[i][j][k+1]; // Set degree to zero deg[i][j] = 0; } } void cross_prod ( double a11[], int deg11, double a12[], int deg12, double a21[], int deg21, double a22[], int deg22, double a00[], double toep[], int deg00, double res[], int &dres, BMatrix B, int &current_size ) { // Does a single 2x2 cross multiplication // Do the multiplcation in temporary storage double temp[2*Maxdegree + 1]; // Work out the actual degree int deg1 = deg11 + deg22; int deg2 = deg12 + deg21; int deg = (deg1 > deg2) ? deg1 : deg2; // Clear out the temporary memset (temp, 0, sizeof(temp)); // Now, start multiplying for (int i=0; i<=deg11; i++) for (int j=0; j<=deg22; j++) temp[i+j] += a11[i]*a22[j]; for (int i=0; i<=deg12; i++) for (int j=0; j<=deg21; j++) temp[i+j] -= a12[i]*a21[j]; // Clear out the result -- not really necessary memset (res, 0, (Maxdegree+1)*sizeof(double)); //----------------------------------------------------- // This is the most tricky part of the code, to divide // one polynomial into the other. By theory, the division // should be exact, but it is not, because of roundoff error. // we need to find a way to do this efficiently and accurately. //----------------------------------------------------- #define USE_TOEPLITZ #ifdef USE_TOEPLITZ // Now, divide by a00 - there should be no remainder int sres; polyquotient (temp, deg+1, a00, toep, deg00+1, res, sres, B, current_size); dres = sres-1; #else // Now, divide by a00 - there should be no remainder double *pres = &(res[deg-deg00]); for (int d=deg; d>=deg00; d--) { // Work out the divisor int td = d - deg00; // Degree of current term double val = temp[d] / a00[deg00]; *(pres--) = val; // Do the subtraction involved in the division for (int j=0; j<deg00; j++) temp[j+td] -= val * a00[j]; } #endif #ifdef RH_DEBUG // Print the remainder printf ("Remainder\n"); for (int i=0; i<deg00; i++) printf ("\t%.5e\n", temp[i]); #endif // Set the degree of the term dres = deg - deg00; } void det_preprocess_6pt ( PolyMatrix &Q, PolyDegree degree, int n_zero_roots // Number of roots known to be zero ) { // We do row-echelon form decomposition on the matrix to eliminate the // trivial known roots. // What is assumed here is the following. // - the first row of the matrix consists of constants // - the nullity of the matrix of constant terms is n_zero_roots, // so when it is put in row-echelon form, the last n_zero_roots are zero. // Initialize the list of and columns. We will do complete pivoting const int nrows = Nrows - 1; const int ncols = Nrows; int rows[Nrows], cols[Nrows]; for (int i=0; i<nrows; i++) rows[i] = i+1; // Miss the first row for (int i=0; i<ncols; i++) cols[i] = i; // Eliminate one row at a time for (int nr=nrows-1, nc=ncols-1; nr>=n_zero_roots; nr--,nc--) { // We must take the first row first to pivot around double bestval = 0.0; int bestrow = 0, bestcol = 0; // Find the highest value to pivot around for (int i=0; i<=nr; i++) for (int j=0; j<=nc; j++) { double val=Q[rows[i]][cols[j]][0]; if (fabs(val) > bestval) { bestval = fabs(val); bestrow = i; // Actually rows[i] bestcol = j; } } // #define RH_DEBUG #ifdef RH_DEBUG #undef RH_DEBUG // Print out the best value printf ("Pivot %d = %e at position %d %d\n",nr, bestval, rows[bestrow], cols[bestcol]); #endif // Now, select this row as a pivot. Also keep track of rows pivoted int prow = rows[bestrow]; rows[bestrow] = rows[nr]; // Replace pivot row by last row rows[nr] = prow; int pcol = cols[bestcol]; cols[bestcol] = cols[nc]; cols[nc] = pcol; // Clear out all the values above and to the right for (int i=0; i<nr; i++) { int iii = rows[i]; double fac = Q[iii][pcol][0] / Q[prow][pcol][0]; // Must do this to all the columns for (int j=0; j<ncols; j++) { int jjj = cols[j]; int deg = degree[prow][jjj]; int dij = degree[iii][jjj]; if (deg>dij) degree[iii][jjj] = deg; for (int d=0; d<=deg; d++) { if (d <= dij) Q[iii][jjj][d] -= Q[prow][jjj][d] * fac; else Q[iii][jjj][d] = -Q[prow][jjj][d] * fac; } } } } // Decrease the degree of the remaining rows for (int i=0; i<n_zero_roots; i++) { int ii = rows[i]; for (int jj=0; jj<ncols; jj++) { // Decrease the degree of this element by one for (int d=1; d<=degree[ii][jj]; d++) Q[ii][jj][d-1] = Q[ii][jj][d]; degree[ii][jj] -= 1; } } // #define RH_DEBUG #ifdef RH_DEBUG #undef RH_DEBUG printf ("Degrees\n"); for (int i=0; i<Nrows; i++) { for (int j=0; j<Nrows; j++) printf ("%1d ", degree[i][j]); printf ("\n"); } printf("\n"); printf ("Equation matrix\n"); for (int i=0; i<nrows; i++) { for (int j=0; j<ncols; j++) printf ("%7.4f ", Q[rows[i]][cols[j]][0]); printf ("\n"); } printf ("\n"); #endif } double quick_compute_determinant (double A[Nrows][Nrows], int dim) { // Do row reduction on A to find the determinant (up to sign) // Initialize the list of rows int rows[Nrows]; for (int i=0; i<dim; i++) rows[i] = i; // To accumulate the determinant double sign = 1.0; // Sweep out one row at a time for (int p = dim-1; p>=0; p--) { // Find the highest value to pivot around, in column p double bestval = 0.0; int bestrow = 0; for (int i=0; i<=p; i++) { double val=A[rows[i]][p]; if (fabs(val) > bestval) { bestval = fabs(val); bestrow = i; // Actually rows[i] } } // Return early if the determinant is zero if (bestval == 0.0) return 0.0; // Now, select this row as a pivot. Swap this row with row p if (bestrow != p) { int prow = rows[bestrow]; rows[bestrow] = rows[p]; // Replace pivot row by last row rows[p] = prow; sign = -sign; // Keep track of sign } // Clear out all the values above and to the right for (int i=0; i<p; i++) { int ii = rows[i]; double fac = A[ii][p] / A[rows[p]][p]; // Must do this to all the columns for (int j=0; j<dim; j++) A[ii][j] -= A[rows[p]][j] * fac; } } // Now compute the determinant double det = sign; for (int i=0; i<dim; i++) det *= A[rows[i]][i]; return det; } void do_scale ( PolyMatrix &Q, PolyDegree degree, double &scale_factor, // Value that x is multiplied by bool degree_by_row, // Estimate degree from row degrees int dim // Actual dimension of the matrix ) { // Scale the variable so that coefficients of low and high order are equal // There is an assumption made here that the high order term of the // determinant can be computed from the high-order values of each term, // which is not in general true, but is so in the cases that we consider. // First step is to compute these values double low_order, high_order; int total_degree; // Find the coefficient of minimum degree term double A[Nrows][Nrows]; for (int i=0; i<dim; i++) for (int j=0; j<dim; j++) A[i][j] = Q[i][j][0]; low_order = quick_compute_determinant (A, dim); // printf ("Low order = %.7e\n", low_order); // Find the coefficient of maximum degree term total_degree = 0; for (int i=0; i<dim; i++) { // Find what the degree of this row is int rowdegree = -1; if (degree_by_row) { for (int j=0; j<dim; j++) if (degree[i][j] > rowdegree) rowdegree = degree[i][j]; for (int j=0; j<dim; j++) if (degree[i][j] < rowdegree) A[i][j] = 0.0; else A[i][j] = Q[i][j][rowdegree]; } else { for (int j=0; j<dim; j++) if (degree[j][i] > rowdegree) rowdegree = degree[j][i]; for (int j=0; j<dim; j++) if (degree[j][i] < rowdegree) A[j][i] = 0.0; else A[j][i] = Q[j][i][rowdegree]; } // Accumulate the row degree total_degree += rowdegree; } high_order = quick_compute_determinant (A, dim); // printf ("High order = %.7e\n", high_order); // Now, work out what the scale factor should be, and scale scale_factor = pow(fabs(low_order/high_order), 1.0 / total_degree); // printf ("Scale factor = %e\n", scale_factor); for (int i=0; i<dim; i++) for (int j=0; j<dim; j++) { double fac = scale_factor; for (int d=1; d<=degree[i][j]; d++) { Q[i][j][d] *= fac; fac *= scale_factor; } } } void find_polynomial_determinant ( PolyMatrix &Q, PolyDegree deg, int rows[Nrows], // This keeps the order of rows pivoted on. int dim // Actual dimension of the matrix ) { // Compute the polynomial determinant - we work backwards from // the end of the matrix. Do not bother with pivoting // Polynomial to start with double aa = 1.0; double *a00 = &aa; int deg00 = 0; // Initialize the list of rows for (int i=0; i<dim; i++) rows[i] = dim-1-i; // The row to pivot around. At end of the loop, this will be // the row containing the result. int piv; for (int p = dim-1; p>=1; p--) { // We want to find the element with the biggest high order term to // pivot around #define DO_PARTIAL_PIVOT #ifdef DO_PARTIAL_PIVOT double bestval = 0.0; int bestrow = 0; for (int i=0; i<=p; i++) { double val=Q[rows[i]][p][deg[rows[i]][p]]; if (fabs(val) > bestval) { bestval = fabs(val); bestrow = i; // Actually rows[i] } } // Now, select this row as a pivot. Also keep track of rows pivoted piv = rows[bestrow]; rows[bestrow] = rows[p]; // Replace pivot row by last row rows[p] = piv; #else piv = rows[p]; #endif // #define RH_DEBUG #ifdef RH_DEBUG #undef RH_DEBUG // Print out the pivot printf ("Pivot %d = \n", p); for (int i=0; i<=deg[piv][p]; i++) printf ("\t%16.5e\n", Q[piv][p][i]); #endif // Set up a matrix for Toeplitz BMatrix B; int current_size = 0; // Also the Toeplitz vector double toep[Maxdegree+1]; for (int i=0; i<=deg00; i++) { toep[i] = 0.0; for (int j=0; j+i<=deg00; j++) toep[i] += a00[j] * a00[j+i]; } // Clear out all the values above and to the right for (int i=0; i<p; i++) { int iii = rows[i]; for (int j=0; j<p; j++) cross_prod ( Q[piv][p], deg[piv][p], Q[piv][j], deg[piv][j], Q[iii][p], deg[iii][p], Q[iii][j], deg[iii][j], a00, toep, deg00, Q[iii][j], deg[iii][j], // Replace original value B, current_size ); } // Now, update to the next a00 = &(Q[piv][p][0]); deg00 = deg[piv][p]; } // Now, the polynomial in the position Q(0,0) is the solution } //========================================================================= // The rest of this code is for stand-alone testing //========================================================================= #ifndef BUILD_MEX #ifdef POLYDET_HAS_MAIN void copy_poly ( PolyMatrix pin, PolyDegree din, PolyMatrix pout, PolyDegree dout) { memcpy (pout, pin, sizeof(PolyMatrix)); memcpy (dout, din, sizeof(PolyDegree)); } int accuracy_test_main (int argc, char *argv[]) { // Try this out // To hold the matrix and its degrees PolyMatrix p; PolyDegree degrees; int pivotrows[Nrows]; //-------------------------------------------------------- // Generate some data for (int i=0; i<Nrows; i++) for (int j=0; j<Ncols; j++) degrees[i][j] = ColumnDegree[j]; // Now, fill out the polynomials for (int i=0; i<Nrows; i++) for (int j=0; j<Ncols; j++) { for (int k=0; k<=ColumnDegree[j]; k++) p[i][j][k] = urandom(); for (int k=ColumnDegree[j]+1; k<=Maxdegree; k++) p[i][j][k] = 0.0; } //-------------------------------------------------------- // Back up the matrix PolyMatrix pbak; PolyDegree degbak; copy_poly (p, degrees, pbak, degbak); //--------------------- // Find determinant, then evaluate //--------------------- // Now, compute the determinant copy_poly (pbak, degbak, p, degrees); // Preprocess double scale_factor = 1.0; det_preprocess_6pt (p, degrees, 3); do_scale (p, degrees, scale_factor, true); // Find the determinant find_polynomial_determinant (p, degrees, pivotrows); // Print out the solution const double print_solution = 0; if (print_solution) { printf ("Solution is\n"); for (int i=0; i<=degrees[pivotrows[0]][0]; i++) printf ("\t%16.5e\n", p[pivotrows[0]][0][i]); } // Now, evaluate and print out double x = 1.0; eval_poly (p, degrees, x); double val1 = p[pivotrows[0]][0][0]; //--------------------- // Now, evaluate first //--------------------- copy_poly (pbak, degbak, p, degrees); // Now, evaluate and print out eval_poly (p, degrees, x); find_polynomial_determinant (p, degrees, pivotrows); double val2 = p[pivotrows[0]][0][0]; double diff = fabs((fabs(val1) - fabs(val2))) / fabs(val1); printf ("%18.9e\t%18.9e\t%10.3e\n", val1, val2, diff); return 0; } int timing_test_main (int argc, char *argv[]) { // Try this out // To hold the matrix and its degrees PolyMatrix p; PolyDegree degrees; int pivotrows[Nrows]; //-------------------------------------------------------- // Generate some data for (int i=0; i<Nrows; i++) for (int j=0; j<Ncols; j++) degrees[i][j] = ColumnDegree[j]; // Now, fill out the polynomials for (int i=0; i<Nrows; i++) for (int j=0; j<Ncols; j++) { for (int k=0; k<=ColumnDegree[j]; k++) p[i][j][k] = urandom(); for (int k=ColumnDegree[j]+1; k<=Maxdegree; k++) p[i][j][k] = 0.0; } //-------------------------------------------------------- // Back up the matrix PolyMatrix pbak; PolyDegree degbak; copy_poly (p, degrees, pbak, degbak); // Now, compute the determinant for (int rep=0; rep<NRepetitions; rep++) { copy_poly (pbak, degbak, p, degrees); find_polynomial_determinant (p, degrees, pivotrows); } return 0; } //=========================================================================== int main (int argc, char *argv[]) { // Now, compute the determinant // for (int rep=0; rep<NRepetitions; rep++) // accuracy_test_main (argc, argv); timing_test_main (argc, argv); return 0; } #endif #endif // BUILD_MEX
27.751534
80
0.525036
youruncleda
563227327b4aa00b9493a105a2cd7965dee1c65a
5,115
cpp
C++
example/clientlike/main.cpp
clodfront/jingke
ac6da9e73d7c69c7575267d2da52cdf6357e6dc9
[ "Apache-2.0" ]
6
2019-11-18T01:37:52.000Z
2021-07-31T14:19:10.000Z
example/clientlike/main.cpp
clodfront/jingke
ac6da9e73d7c69c7575267d2da52cdf6357e6dc9
[ "Apache-2.0" ]
null
null
null
example/clientlike/main.cpp
clodfront/jingke
ac6da9e73d7c69c7575267d2da52cdf6357e6dc9
[ "Apache-2.0" ]
1
2019-11-18T01:27:44.000Z
2019-11-18T01:27:44.000Z
// Project: jingke // File: main.cpp // Created: 11/2019 // Author: Goof // // Copyright 2019-2020 Goof // // 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 <stddef.h> #include <stdlib.h> #include <iostream> #include <string> #include "server.h" #include "log_writer.h" #include "test_protoc.h" #include "test_cs.pb.h" using namespace std; using namespace jingke; class CSProtocolParser : public CProtocolParser { public: virtual size_t GetPackSize(const void* data_, size_t length_) { static SPackHead head; if(!data_ || !length_) return INVALID_PACK_SIZE; constexpr size_t needsize = offsetof(SPackHead, len) + sizeof(head.len); if(length_ < needsize) return UNDETERMINED_PACK_SIZE; uint32_t pack_len = ntohl(*((uint32_t*)((char*)data_ + offsetof(SPackHead, len)))); return pack_len; } virtual uint64_t GetAsyncKey(const void* data_, size_t length_) { return 0; } }; CSProtocolParser g_parser; class CClinetLike : public IServer { public: virtual CProtocolParser* GetClientParser(uint16_t listener_id_) { //no cfg listener_id return NULL; } virtual CProtocolParser* GetServiceParser(uint16_t service_id_) { //no peer service cfg if(1 == service_id_) return &g_parser; return NULL; } virtual void OnRecvClient(const void* data_, size_t data_len_, uint32_t session_id_, uint16_t listener_id_) { } virtual void OnRecvService(const void* data_, size_t data_len_, uint16_t service_id_) { if(!data_ || data_len_ < sizeof(SPackHead)) return; if(service_id_ != 1) return; SPackHead pack_head; if(!ExampleMessageCoder::decode_head(data_, data_len_, pack_head)) return; switch (pack_head.cmd) { case CSP::cs_cmd_fight_rsp: { CSP::CsFightRsp rsp; if(!ExampleMessageCoder::decode_body(data_, data_len_, rsp)) return; if(rsp.errcode()) { LOG_ERROR("fight failed ec:%d", rsp.errcode()); } else { LOG_INFO("fight done winner:%u", rsp.winnerid()); } } break; case CSP::cs_cmd_query_rank_top3_rsp: { CSP::CsRankTop3Rsp rsp; if(!ExampleMessageCoder::decode_body(data_, data_len_, rsp)) return; if(rsp.errcode()) { LOG_ERROR("query top3 failed ec:%d", rsp.errcode()); } else { LOG_INFO("top3 info : valid num:%u", rsp.validnum()); for(int i=0; i<rsp.ids_size(); ++i) { LOG_INFO("top3 %dth:%u", i+1, rsp.ids(i)); } } } break; default: LOG_ERROR("recv unknow cmd:%u failed. service_id=%u", pack_head.cmd, service_id_); } } protected: virtual int OnInit() { srand(time(0)); uint32_t id = SetMonoTimer(std::bind(&CClinetLike::ReqFight, this, std::placeholders::_1 ,std::placeholders::_2) ,3000 ,2000); if(!id) { LOG_ERROR("SetMonoTimer failed"); return -1; } id = SetMonoTimer(std::bind(&CClinetLike::GetTop3, this, std::placeholders::_1 ,std::placeholders::_2) ,10000 ,60000); if(!id) { LOG_ERROR("SetMonoTimer failed"); return -1; } LOG_INFO("CClinetLike::OnInit OK"); return 0; } virtual void OnFini() { LOG_INFO("CClinetLike::OnFini finish"); } private: void ReqFight(mstime_t mono_time_, uint16_t step_) { static char req_pack_buff[1024]; CSP::CsFightReq req; uint32_t fighterid_a = 0; uint32_t fighterid_b = 0; fighterid_a = rand()%100 + 1; do { fighterid_b = rand()%100 + 1; } while (fighterid_b == fighterid_a); req.set_fighterid_a(fighterid_a); req.set_fighterid_b(fighterid_b); SPackHead req_head; req_head.cmd = CSP::cs_cmd_fight_req; req_head.asyncid = 0; size_t encode_size = 0; if(!ExampleMessageCoder::encode(req_pack_buff, sizeof(req_pack_buff), req_head, &req, &encode_size)) return; int ret = SendToService(1, req_pack_buff, encode_size); if(ret != 0) { LOG_ERROR("SendToService failed, ret:%d", ret); } } void GetTop3(mstime_t mono_time_, uint16_t step_) { static char req_pack_buff[1024]; CSP::CsRankTop3Req req; req.set_order(0); SPackHead req_head; req_head.cmd = CSP::cs_cmd_query_rank_top3_req; req_head.asyncid = 0; size_t encode_size = 0; if(!ExampleMessageCoder::encode(req_pack_buff, sizeof(req_pack_buff), req_head, &req, &encode_size)) return; int ret = SendToService(1, req_pack_buff, encode_size); if(ret != 0) { LOG_ERROR("SendToService failed, ret:%d", ret); } } }; int main(int argc, char** argv) { if(argc < 2) { cout << "argc < 2" << endl; return -1; } CClinetLike svr; int ret = svr.Init(argv[1]); if(ret != 0) { cout << "svr.Init fail. ret:" << ret << endl; return -2; } svr.Run(); return 0; }
23.571429
114
0.681134
clodfront
56331442fa99035ab7439b67bc60cb66a33b96c1
19,731
cpp
C++
src/scripting/backend/dynarrays.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
2
2018-01-18T21:30:20.000Z
2018-01-19T02:24:46.000Z
src/scripting/backend/dynarrays.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
src/scripting/backend/dynarrays.cpp
raa-eruanna/ProjectPanther
7d703c162b4ede25faa3e99cacacb4fc79fb77da
[ "RSA-MD" ]
null
null
null
/* ** dynarray.cpp ** ** internal data types for dynamic arrays ** **--------------------------------------------------------------------------- ** Copyright 2016-2017 Christoph Oelckers ** All rights reserved. ** ** Redistribution and use in source and binary forms, with or without ** modification, are permitted provided that the following conditions ** are met: ** ** 1. Redistributions of source code must retain the above copyright ** notice, this list of conditions and the following disclaimer. ** 2. Redistributions in binary form must reproduce the above copyright ** notice, this list of conditions and the following disclaimer in the ** documentation and/or other materials provided with the distribution. ** 3. The name of the author may not be used to endorse or promote products ** derived from this software without specific prior written permission. ** 4. When not used as part of ZDoom or a ZDoom derivative, this code will be ** covered by the terms of the GNU General Public License as published by ** the Free Software Foundation; either version 2 of the License, or (at ** your option) any later version. ** ** THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR ** IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES ** OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. ** IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, ** INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT ** NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF ** THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **--------------------------------------------------------------------------- ** */ #include "tarray.h" #include "dobject.h" #include "vm.h" #include "types.h" // We need one specific type for each of the 7 integral VM types and instantiate the needed functions for each of them. // Dynamic arrays cannot hold structs because for every type there'd need to be an internal implementation which is impossible. typedef TArray<uint8_t> FDynArray_I8; typedef TArray<uint16_t> FDynArray_I16; typedef TArray<uint32_t> FDynArray_I32; typedef TArray<float> FDynArray_F32; typedef TArray<double> FDynArray_F64; typedef TArray<void*> FDynArray_Ptr; typedef TArray<DObject*> FDynArray_Obj; typedef TArray<FString> FDynArray_String; //----------------------------------------------------- // // Int8 array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_I8, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_POINTER(other, FDynArray_I8); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_POINTER(other, FDynArray_I8); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(val); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_I8, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(val); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_I8, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_I8, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(index); PARAM_INT(val); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I8, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_I8, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_I8, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I8); self->Clear(); return 0; } //----------------------------------------------------- // // Int16 array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_I16, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_POINTER(other, FDynArray_I16); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_POINTER(other, FDynArray_I16); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(val); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_I16, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(val); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_I16, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_I16, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(index); PARAM_INT(val); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I16, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_I16, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_I16, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I16); self->Clear(); return 0; } //----------------------------------------------------- // // Int32 array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_I32, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_POINTER(other, FDynArray_I32); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_POINTER(other, FDynArray_I32); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(val); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_I32, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(val); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_I32, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_I32, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(index); PARAM_INT(val); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_I32, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_I32, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_I32, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_I32); self->Clear(); return 0; } //----------------------------------------------------- // // Float32 array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_F32, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_POINTER(other, FDynArray_F32); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_POINTER(other, FDynArray_F32); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_FLOAT(val); ACTION_RETURN_INT(self->Find((float)val)); } DEFINE_ACTION_FUNCTION(FDynArray_F32, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_FLOAT(val); ACTION_RETURN_INT(self->Push((float)val)); } DEFINE_ACTION_FUNCTION(FDynArray_F32, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_F32, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_INT(index); PARAM_FLOAT(val); self->Insert(index, (float)val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F32, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_F32, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_F32, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F32); self->Clear(); return 0; } //----------------------------------------------------- // // Float64 array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_F64, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_POINTER(other, FDynArray_F64); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_POINTER(other, FDynArray_F64); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_FLOAT(val); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_F64, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_FLOAT(val); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_F64, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_F64, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_INT(index); PARAM_FLOAT(val); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_F64, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_F64, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_F64, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_F64); self->Clear(); return 0; } //----------------------------------------------------- // // Pointer array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_POINTER(other, FDynArray_Ptr); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_POINTER(other, FDynArray_Ptr); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_POINTER(val, void); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_POINTER(val, void); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_INT(index); PARAM_POINTER(val, void); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_Ptr, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Ptr); self->Clear(); return 0; } //----------------------------------------------------- // // Object array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_Obj, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_POINTER(other, FDynArray_Obj); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_POINTER(other, FDynArray_Obj); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_OBJECT(val, DObject); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_OBJECT(val, DObject); GC::WriteBarrier(val); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_INT(index); PARAM_OBJECT(val, DObject); GC::WriteBarrier(val); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_Obj, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_Obj); self->Clear(); return 0; } //----------------------------------------------------- // // String array // //----------------------------------------------------- DEFINE_ACTION_FUNCTION(FDynArray_String, Copy) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_POINTER(other, FDynArray_String); *self = *other; return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, Move) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_POINTER(other, FDynArray_String); *self = std::move(*other); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, Find) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_STRING(val); ACTION_RETURN_INT(self->Find(val)); } DEFINE_ACTION_FUNCTION(FDynArray_String, Push) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_STRING(val); ACTION_RETURN_INT(self->Push(val)); } DEFINE_ACTION_FUNCTION(FDynArray_String, Pop) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); ACTION_RETURN_BOOL(self->Pop()); } DEFINE_ACTION_FUNCTION(FDynArray_String, Delete) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_INT(index); PARAM_INT_DEF(count); self->Delete(index, count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, Insert) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_INT(index); PARAM_STRING(val); self->Insert(index, val); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, ShrinkToFit) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); self->ShrinkToFit(); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, Grow) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_INT(count); self->Grow(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, Resize) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_INT(count); self->Resize(count); return 0; } DEFINE_ACTION_FUNCTION(FDynArray_String, Reserve) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); PARAM_INT(count); ACTION_RETURN_INT(self->Reserve(count)); } DEFINE_ACTION_FUNCTION(FDynArray_String, Max) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); ACTION_RETURN_INT(self->Max()); } DEFINE_ACTION_FUNCTION(FDynArray_String, Clear) { PARAM_SELF_STRUCT_PROLOGUE(FDynArray_String); self->Clear(); return 0; } DEFINE_FIELD_NAMED_X(DynArray_I8, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_I16, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_I32, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_F32, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_F64, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_Ptr, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_Obj, FArray, Count, Size) DEFINE_FIELD_NAMED_X(DynArray_String, FArray, Count, Size)
22.095185
127
0.746034
raa-eruanna
563395172803aab27f0e23d2dc544610981636a0
2,137
cpp
C++
modules/sdk/unit/simd/category_of.cpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
1
2022-03-24T03:35:10.000Z
2022-03-24T03:35:10.000Z
modules/sdk/unit/simd/category_of.cpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
null
null
null
modules/sdk/unit/simd/category_of.cpp
brycelelbach/nt2
73d7e8dd390fa4c8d251c6451acdae65def70e0b
[ "BSL-1.0" ]
null
null
null
/******************************************************************************* * Copyright 2003 & onward LASMEA UMR 6602 CNRS/Univ. Clermont II * Copyright 2009 & onward LRI UMR 8623 CNRS/Univ Paris Sud XI * * Distributed under the Boost Software License, Version 1.0. * See accompanying file LICENSE.txt or copy at * http://www.boost.org/LICENSE_1_0.txt ******************************************************************************/ #define NT2_UNIT_MODULE "nt2::meta::category_of simd" #include <nt2/sdk/simd/native.hpp> #include <nt2/sdk/meta/hierarchy_of.hpp> #include <boost/type_traits/is_same.hpp> #include <nt2/sdk/unit/tests/basic.hpp> #include <nt2/sdk/unit/module.hpp> //////////////////////////////////////////////////////////////////////////////// // Test category of SIMD types //////////////////////////////////////////////////////////////////////////////// NT2_TEST_CASE(simd_category) { using nt2::simd::native; using nt2::meta::hierarchy_of; using boost::is_same; using namespace nt2; /* typedef NT2_SIMD_DEFAULT_EXTENSION ext_t; typedef functors::simd_<tag::arithmetic_,ext_t,1> cat_t; #if defined(NT2_SIMD_SSE_FAMILY) NT2_TEST((is_same<category_of<native<double ,ext_t> >::type, cat_t>::value)); NT2_TEST((is_same<category_of<native<nt2::uint64_t,ext_t> >::type, cat_t>::value)); NT2_TEST((is_same<category_of<native<nt2::int64_t,ext_t > >::type, cat_t>::value)); #endif NT2_TEST((is_same<category_of<native<float ,ext_t> >::type , cat_t >::value)); NT2_TEST((is_same<category_of<native<nt2::uint32_t ,ext_t> >::type , cat_t >::value)); NT2_TEST((is_same<category_of<native<nt2::uint16_t ,ext_t> >::type , cat_t >::value)); NT2_TEST((is_same<category_of<native<nt2::uint8_t ,ext_t> >::type , cat_t >::value)); NT2_TEST((is_same<category_of<native<nt2::int32_t ,ext_t> >::type , cat_t >::value)); NT2_TEST((is_same<category_of<native<nt2::int16_t ,ext_t> >::type , cat_t >::value)); NT2_TEST((is_same<category_of<native<nt2::int8_t ,ext_t> >::type , cat_t >::value)); */ }
45.468085
88
0.582592
brycelelbach
56340e785d1e0dcecb183c96fc3029c33d72f47b
753
cpp
C++
engine/poker-lib/test-game-generator.cpp
torives/poker-updater-demo
0a7be9e53ab3bd973296ced0561bbbd1a9dd1493
[ "Apache-2.0" ]
12
2021-06-30T17:04:00.000Z
2022-03-11T18:34:51.000Z
engine/poker-lib/test-game-generator.cpp
torives/poker-updater-demo
0a7be9e53ab3bd973296ced0561bbbd1a9dd1493
[ "Apache-2.0" ]
9
2021-06-29T06:45:44.000Z
2022-02-11T23:26:13.000Z
engine/poker-lib/test-game-generator.cpp
torives/poker-updater-demo
0a7be9e53ab3bd973296ced0561bbbd1a9dd1493
[ "Apache-2.0" ]
1
2022-01-07T12:03:19.000Z
2022-01-07T12:03:19.000Z
#include <iostream> #include <sstream> #include <memory.h> #include <inttypes.h> #include "test-util.h" #include "poker-lib.h" #include "game-generator.h" #define TEST_SUITE_NAME "Test game generator" using namespace poker; void the_happy_path() { std::cout << "---- " TEST_SUITE_NAME << " - the_happy_path" << std::endl; game_generator gen; assert_eql(SUCCESS, gen.generate()); assert_neq(0, gen.raw_player_info.size()); assert_neq(0, gen.raw_turn_metadata.size()); assert_neq(0, gen.raw_verification_info.size()); assert_neq(0, gen.raw_turn_data.size()); } int main(int argc, char** argv) { init_poker_lib(); the_happy_path(); std::cout << "---- SUCCESS - " TEST_SUITE_NAME << std::endl; return 0; }
25.1
78
0.671979
torives
5638143f1b535d49bc43a8a008499f6dafbb1a29
6,861
cpp
C++
PolyEngine/CzolgInvaders/Src/InvadersGame.cpp
MuniuDev/PolyEngine
9389537e4f551fa5dd621ebd3704e55b04c98792
[ "MIT" ]
1
2017-04-30T13:55:54.000Z
2017-04-30T13:55:54.000Z
PolyEngine/CzolgInvaders/Src/InvadersGame.cpp
MuniuDev/PolyEngine
9389537e4f551fa5dd621ebd3704e55b04c98792
[ "MIT" ]
null
null
null
PolyEngine/CzolgInvaders/Src/InvadersGame.cpp
MuniuDev/PolyEngine
9389537e4f551fa5dd621ebd3704e55b04c98792
[ "MIT" ]
3
2017-11-22T16:37:26.000Z
2019-04-24T17:47:58.000Z
#include "InvadersGame.hpp" #include <DeferredTaskSystem.hpp> #include <CameraComponent.hpp> #include <TransformComponent.hpp> #include <MeshRenderingComponent.hpp> #include <FreeFloatMovementComponent.hpp> #include <ScreenSpaceTextComponent.hpp> #include <Core.hpp> #include <DeferredTaskSystem.hpp> #include <ViewportWorldComponent.hpp> #include <ResourceManager.hpp> #include <SoundEmitterComponent.hpp> #include <SoundSystem.hpp> #include "GameManagerSystem.hpp" #include "MovementComponent.hpp" #include "MovementSystem.hpp" #include "CollisionComponent.hpp" #include "CollisionSystem.hpp" #include "TankComponent.hpp" using namespace Poly; DEFINE_GAME(InvadersGame) void InvadersGame::Init() { Engine->RegisterComponent<PlayerControllerComponent>((int)eGameComponents::PLAYERCONTROLLER); Engine->RegisterComponent<BulletComponent>((int)eGameComponents::BULLET); Engine->RegisterComponent<GameManagerComponent>((int)eGameComponents::GAMEMANAGER); Engine->RegisterComponent<EnemyMovementComponent>((int)eGameComponents::ENEMYMOVEMENT); Engine->RegisterComponent<Invaders::MovementSystem::MovementComponent>((int)eGameComponents::MOVEMENT); Engine->RegisterComponent<Invaders::CollisionSystem::CollisionComponent>((int)eGameComponents::COLLISION); Engine->RegisterComponent<Invaders::TankComponent>((int)eGameComponents::TANK); Camera = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), Camera); DeferredTaskSystem::AddComponentImmediate<Poly::CameraComponent>(Engine->GetWorld(), Camera, 60_deg, 1.0f, 1000.f); DeferredTaskSystem::AddComponentImmediate<Poly::FreeFloatMovementComponent>(Engine->GetWorld(), Camera, 10.0f, 0.003f); float y_pos = (float)Engine->GetRenderingDevice()->GetScreenSize().Height; auto textDispaly = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<Poly::ScreenSpaceTextComponent>(Engine->GetWorld(), textDispaly, Vector{ 0.0f, y_pos ,0.0f }, "Fonts/Raleway/Raleway-Heavy.ttf", 32, "Kill count: 0"); GameManager = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<GameManagerComponent>(Engine->GetWorld(), GameManager, textDispaly); GameManagerComponent* gameManagerComponent = Engine->GetWorld()->GetComponent<GameManagerComponent>(GameManager); // Set some camera position Poly::TransformComponent* cameraTrans = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(Camera); cameraTrans->SetLocalTranslation(Vector(0.0f, 20.0f, 60.0f)); cameraTrans->SetLocalRotation(Quaternion({ 1, 0, 0 }, -30_deg)); for (int i = -10; i < 0; ++i) { for (int j = -2; j < 1; ++j) { auto ent = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), ent); DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), ent, "model-tank/turret.fbx"); Poly::TransformComponent* entTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(ent); auto base = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), base); DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), base, "model-tank/base.fbx"); DeferredTaskSystem::AddComponentImmediate<Invaders::MovementSystem::MovementComponent>(Engine->GetWorld(), base, Vector(5, 0, 0), Vector(0, 0, 0), Quaternion(Vector(0, 0, 0), 0_deg), Quaternion(Vector(0, 0, 0), 0_deg)); DeferredTaskSystem::AddComponentImmediate<Invaders::CollisionSystem::CollisionComponent>(Engine->GetWorld(), base, Vector(0, 0, 0), Vector(5.0f, 5.0f, 5.0f)); DeferredTaskSystem::AddComponentImmediate<Invaders::TankComponent>(Engine->GetWorld(), base, ent, 12.0_deg, (i * j)%5 ); Poly::TransformComponent* baseTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(base); entTransform->SetParent(baseTransform); baseTransform->SetLocalTranslation(Vector(i * 12.f, 0.f, j * 8.f)); baseTransform->SetLocalRotation(Quaternion(Vector::UNIT_Y, -90.0_deg)); entTransform->SetLocalRotation(Quaternion(Vector::UNIT_Y, -60.0_deg)); } } auto player = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), player); DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), player, "Models/tank2/bradle.3ds"); DeferredTaskSystem::AddComponentImmediate<PlayerControllerComponent>(Engine->GetWorld(), player, 10.0f); DeferredTaskSystem::AddComponentImmediate<Poly::SoundEmitterComponent>(Engine->GetWorld(), player, "COJ2_Battle_Hard_Attack.ogg"); Poly::TransformComponent* entTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(player); entTransform->SetLocalTranslation(Vector(0, 0, 50)); entTransform->SetLocalScale(10); entTransform->SetLocalRotation(Quaternion(Vector::UNIT_Y, -90_deg) * Quaternion(Vector::UNIT_X, -90_deg)); Engine->GetWorld()->GetWorldComponent<ViewportWorldComponent>()->SetCamera(0, Engine->GetWorld()->GetComponent<Poly::CameraComponent>(Camera)); Engine->RegisterGameUpdatePhase(Invaders::MovementSystem::MovementUpdatePhase); Engine->RegisterGameUpdatePhase(Invaders::CollisionSystem::CollisionUpdatePhase); Engine->RegisterGameUpdatePhase(GameMainSystem::GameUpdate); Engine->RegisterGameUpdatePhase(ControlSystem::ControlSystemPhase); Engine->RegisterGameUpdatePhase(GameManagerSystem::GameManagerSystemPhase); for(int x = -1; x <= 1; ++x) for (int z = -1; z <= 1; ++z) { const float SCALE = 4.0f; const float SIZE = 40.0f; auto ground = DeferredTaskSystem::SpawnEntityImmediate(Engine->GetWorld()); DeferredTaskSystem::AddComponentImmediate<Poly::TransformComponent>(Engine->GetWorld(), ground); DeferredTaskSystem::AddComponentImmediate<Poly::MeshRenderingComponent>(Engine->GetWorld(), ground, "Models/ground/ground.fbx"); Poly::TransformComponent* groundTransform = Engine->GetWorld()->GetComponent<Poly::TransformComponent>(ground); groundTransform->SetLocalTranslation(Vector(x * SCALE * SIZE, 0, z * SCALE * SIZE)); groundTransform->SetLocalScale(SCALE); } // Precache bullet mesh BulletMesh = Poly::ResourceManager<MeshResource>::Load("Models/bullet/lowpolybullet.obj"); }; void InvadersGame::Deinit() { DeferredTaskSystem::DestroyEntityImmediate(Engine->GetWorld(), Camera); for(auto ent : GameEntities) DeferredTaskSystem::DestroyEntityImmediate(Engine->GetWorld(), ent); Poly::ResourceManager<MeshResource>::Release(BulletMesh); }; void GameMainSystem::GameUpdate(Poly::World* /*world*/) { }
54.452381
222
0.78181
MuniuDev
56397e3bac7cb82ef1f1643229888efe6f106eb5
2,161
cpp
C++
src/Main.cpp
muhopensores/dmc3-inputs-thing
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
[ "MIT" ]
5
2021-06-09T23:53:28.000Z
2022-02-21T06:09:41.000Z
src/Main.cpp
muhopensores/dmc3-inputs-thing
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
[ "MIT" ]
9
2021-06-09T23:52:43.000Z
2021-09-17T14:05:47.000Z
src/Main.cpp
muhopensores/dmc3-inputs-thing
2cb97f30c39bbe8d6bbe724f61d932a1fdaa1719
[ "MIT" ]
null
null
null
#include <thread> #include <chrono> #include <windows.h> #include "ModFramework.hpp" static HMODULE g_dinput; static HMODULE g_styleswitcher; #if 1 extern "C" { // DirectInput8Create wrapper for dinput8.dll __declspec(dllexport) HRESULT WINAPI direct_input8_create(HINSTANCE hinst, DWORD dw_version, const IID& riidltf, LPVOID* ppv_out, LPUNKNOWN punk_outer) { // This needs to be done because when we include dinput.h in DInputHook, // It is a redefinition, so we assign an export by not using the original name #pragma comment(linker, "/EXPORT:DirectInput8Create=_direct_input8_create@20") return ((decltype(direct_input8_create)*)GetProcAddress(g_dinput, "DirectInput8Create"))(hinst, dw_version, riidltf, ppv_out, punk_outer); } } #endif void failed() { MessageBox(0, "DMC3 ModFramework: Unable to load the original version.dll. Please report this to the developer.", "ModFramework", 0); ExitProcess(0); } void startup_thread() { #ifndef NDEBUG AllocConsole(); HANDLE handleOut = GetStdHandle(STD_OUTPUT_HANDLE); DWORD consoleMode; GetConsoleMode( handleOut , &consoleMode); consoleMode |= ENABLE_VIRTUAL_TERMINAL_PROCESSING; consoleMode |= DISABLE_NEWLINE_AUTO_RETURN; SetConsoleMode( handleOut , consoleMode ); freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); #endif #if 1 wchar_t buffer[MAX_PATH]{ 0 }; if (GetSystemDirectoryW(buffer, MAX_PATH) != 0) { // Load the original dinput8.dll if ((g_dinput = LoadLibraryW((std::wstring{ buffer } + L"\\dinput8.dll").c_str())) == NULL) { failed(); } g_framework = std::make_unique<ModFramework>(); } else { failed(); } #else g_framework = std::make_unique<ModFramework>(); #endif } BOOL APIENTRY DllMain(HMODULE handle, DWORD reason, LPVOID reserved) { if (reason == DLL_PROCESS_ATTACH) { LoadLibrary("StyleSwitcher.dll"); #ifndef NDEBUG MessageBox(NULL, "Debug attach opportunity", "DMC3", MB_ICONINFORMATION); #endif CreateThread(nullptr, 0, (LPTHREAD_START_ROUTINE)startup_thread, nullptr, 0, nullptr); } if (reason == DLL_PROCESS_DETACH) { FreeLibrary(g_styleswitcher); } return TRUE; }
30.871429
154
0.73577
muhopensores
5639c61e5f2394e34ff497af6f77389582a24b91
7,331
hpp
C++
include/r2p/Topic.hpp
r2p/Middleware
6438bdef16671482ecc1330679fa56439f916c61
[ "BSD-2-Clause" ]
1
2020-11-26T04:21:41.000Z
2020-11-26T04:21:41.000Z
include/r2p/Topic.hpp
r2p/Middleware
6438bdef16671482ecc1330679fa56439f916c61
[ "BSD-2-Clause" ]
null
null
null
include/r2p/Topic.hpp
r2p/Middleware
6438bdef16671482ecc1330679fa56439f916c61
[ "BSD-2-Clause" ]
1
2020-11-26T04:21:47.000Z
2020-11-26T04:21:47.000Z
#pragma once #include <r2p/common.hpp> #include <r2p/NamingTraits.hpp> #include <r2p/impl/MemoryPool_.hpp> #include <r2p/StaticList.hpp> #include <r2p/Time.hpp> namespace r2p { #if !defined(R2P_DEFAULT_FORWARDING) || defined(__DOXYGEN__) #define R2P_DEFAULT_FORWARDING_RULE R2P_USE_BRIDGE_MODE #endif class Message; class LocalPublisher; class LocalSubscriber; class RemotePublisher; class RemoteSubscriber; class Topic : private Uncopyable { friend class Middleware; private: const char *const namep; Time publish_timeout; MemoryPool_ msg_pool; size_t num_local_publishers; size_t num_remote_publishers; StaticList<LocalSubscriber> local_subscribers; StaticList<RemoteSubscriber> remote_subscribers; size_t max_queue_length; #if R2P_USE_BRIDGE_MODE bool forwarding; #endif StaticList<Topic>::Link by_middleware; public: const char *get_name() const; const Time &get_publish_timeout() const; size_t get_type_size() const; size_t get_payload_size() const; size_t get_max_queue_length() const; bool is_forwarding() const; bool has_local_publishers() const; bool has_remote_publishers() const; bool has_publishers() const; bool has_local_subscribers() const; bool has_remote_subscribers() const; bool has_subscribers() const; bool is_awaiting_advertisements() const; bool is_awaiting_subscriptions() const; const Time compute_deadline_unsafe(const Time &timestamp) const; const Time compute_deadline_unsafe() const; Message *alloc_unsafe(); template<typename MessageType> bool alloc_unsafe(MessageType *&msgp); bool release_unsafe(Message &msg); void free_unsafe(Message &msg); bool notify_locals_unsafe(Message &msg, const Time &timestamp); bool notify_remotes_unsafe(Message &msg, const Time &timestamp); bool forward_copy_unsafe(const Message &msg, const Time &timestamp); const Time compute_deadline(const Time &timestamp) const; const Time compute_deadline() const; Message *alloc(); template<typename MessageType> bool alloc(MessageType *&msgp); bool release(Message &msg); void free(Message &msg); bool notify_locals(Message &msg, const Time &timestamp); bool notify_remotes(Message &msg, const Time &timestamp); bool forward_copy(const Message &msg, const Time &timestamp); void extend_pool(Message array[], size_t arraylen); void advertise(LocalPublisher &pub, const Time &publish_timeout); void advertise(RemotePublisher &pub, const Time &publish_timeout); void subscribe(LocalSubscriber &sub, size_t queue_length); void subscribe(RemoteSubscriber &sub, size_t queue_length); private: void patch_pubsub_msg(Message &msg, Transport &transport) const; public: Topic(const char *namep, size_t type_size, bool forwarding = R2P_DEFAULT_FORWARDING_RULE); public: static bool has_name(const Topic &topic, const char *namep); }; class MessageGuard : private Uncopyable { private: Message &msg; Topic &topic; public: MessageGuard(Message &msg, Topic &topic); ~MessageGuard(); }; class MessageGuardUnsafe : private Uncopyable { private: Message &msg; Topic &topic; public: MessageGuardUnsafe(Message &msg, Topic &topic); ~MessageGuardUnsafe(); }; } // namespace r2p #include <r2p/Message.hpp> #include <r2p/LocalPublisher.hpp> #include <r2p/LocalSubscriber.hpp> #include <r2p/RemotePublisher.hpp> #include <r2p/RemoteSubscriber.hpp> namespace r2p { inline const char *Topic::get_name() const { return namep; } inline const Time &Topic::get_publish_timeout() const { return publish_timeout; } inline size_t Topic::get_type_size() const { return msg_pool.get_item_size(); } inline size_t Topic::get_payload_size() const { return Message::get_payload_size(msg_pool.get_item_size()); } inline size_t Topic::get_max_queue_length() const { return max_queue_length; } inline bool Topic::is_forwarding() const { #if R2P_USE_BRIDGE_MODE return forwarding; #else return R2P_DEFAULT_FORWARDING_RULE; #endif } inline bool Topic::has_local_publishers() const { return num_local_publishers > 0; } inline bool Topic::has_remote_publishers() const { return num_remote_publishers > 0; } inline bool Topic::has_publishers() const { return num_local_publishers > 0 || num_remote_publishers > 0; } inline bool Topic::has_local_subscribers() const { return !local_subscribers.is_empty_unsafe(); } inline bool Topic::has_remote_subscribers() const { return !remote_subscribers.is_empty_unsafe(); } inline bool Topic::has_subscribers() const { return !local_subscribers.is_empty_unsafe() || !remote_subscribers.is_empty_unsafe(); } inline bool Topic::is_awaiting_advertisements() const { return !has_local_publishers() && !has_remote_publishers() && has_local_subscribers(); } inline bool Topic::is_awaiting_subscriptions() const { return !has_local_subscribers() && !has_remote_subscribers() && has_local_publishers(); } inline const Time Topic::compute_deadline_unsafe(const Time &timestamp) const { return timestamp + publish_timeout; } inline const Time Topic::compute_deadline_unsafe() const { return compute_deadline_unsafe(Time::now()); } inline Message *Topic::alloc_unsafe() { register Message *msgp = reinterpret_cast<Message *>(msg_pool.alloc_unsafe()); if (msgp != NULL) { msgp->reset_unsafe(); return msgp; } return NULL; } template<typename MessageType> inline bool Topic::alloc_unsafe(MessageType *&msgp) { static_cast_check<MessageType, Message>(); return (msgp = reinterpret_cast<MessageType *>(alloc_unsafe())) != NULL; } inline bool Topic::release_unsafe(Message &msg) { if (!msg.release_unsafe()) { free_unsafe(msg); return true; } return false; } inline void Topic::free_unsafe(Message &msg) { msg_pool.free_unsafe(reinterpret_cast<void *>(&msg)); } inline const Time Topic::compute_deadline(const Time &timestamp) const { SysLock::acquire(); const Time &deadline = compute_deadline_unsafe(timestamp); SysLock::release(); return deadline; } inline const Time Topic::compute_deadline() const { return compute_deadline(Time::now()); } template<typename MessageType> inline bool Topic::alloc(MessageType *&msgp) { static_cast_check<MessageType, Message>(); return (msgp = reinterpret_cast<MessageType *>(alloc())) != NULL; } inline bool Topic::release(Message &msg) { SysLock::acquire(); bool freed = release_unsafe(msg); SysLock::release(); return freed; } inline void Topic::free(Message &msg) { msg_pool.free(reinterpret_cast<void *>(&msg)); } inline void Topic::extend_pool(Message array[], size_t arraylen) { msg_pool.extend(array, arraylen); } inline bool Topic::has_name(const Topic &topic, const char *namep) { return namep != NULL && 0 == strncmp(topic.get_name(), namep, NamingTraits<Topic>::MAX_LENGTH); } inline MessageGuard::MessageGuard(Message &msg, Topic &topic) : msg(msg), topic(topic) { msg.acquire(); } inline MessageGuard::~MessageGuard() { topic.release(msg); } inline MessageGuardUnsafe::MessageGuardUnsafe(Message &msg, Topic &topic) : msg(msg), topic(topic) { msg.acquire_unsafe(); } inline MessageGuardUnsafe::~MessageGuardUnsafe() { topic.release_unsafe(msg); } } // namespace r2p
19.343008
80
0.740554
r2p
563b9ce01f55c133a5e2a6ec6e24aa31d8bb83ce
6,932
cpp
C++
Source/DirectConnectionLibLink.cpp
NewBlueFX/DirectConnect
49482c8555695eee77eff0317d2d5689cea33ba7
[ "MIT" ]
null
null
null
Source/DirectConnectionLibLink.cpp
NewBlueFX/DirectConnect
49482c8555695eee77eff0317d2d5689cea33ba7
[ "MIT" ]
null
null
null
Source/DirectConnectionLibLink.cpp
NewBlueFX/DirectConnect
49482c8555695eee77eff0317d2d5689cea33ba7
[ "MIT" ]
null
null
null
// DirectConnectionLibLink.cpp /* MIT License Copyright (c) 2016,2018 NewBlue, Inc. <https://github.com/NewBlueFX> 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 "DirectConnectionLibLink.h" #include "DirectConnectionInstanceCreator.h" #include "DirectConnectionIPCClient.h" #include "DirectConnectionGeneric.h" #include <string> #include <sstream> #include <algorithm> #include <locale> #include <codecvt> #ifdef _WIN32 # include <shellapi.h> # define LIBLINKBASE_NEW_BLUE_REG_PATH_PREFIX L"Software\\NewBlue\\" # ifdef _WIN64 # define LIBLINKBASE_INSTALL_PATH_KEY_NAME L"Install Path 64" # else # define LIBLINKBASE_INSTALL_PATH_KEY_NAME L"Install Path" # endif #elif __APPLE__ // While nothing #else # error Unsupported platform #endif namespace DCTL { namespace { bool CheckServerConnection(Port port) { // The most reliable way to check connection, it is to create the client for given port and call any function. bool bConnected = false; DirectConnectionIPCClient* pRpcClient = new DirectConnectionIPCClient(port, false, &bConnected); if (bConnected) { // Send any metadata, we do not need if server will process it. // We need to know if server is alive. bConnected = (pRpcClient->SendGlobalMetadataFrame(-1, "") != DCERR_ServerShutdown); } pRpcClient->Release(); return bConnected; } } DirectConnectionLibLink::DirectConnectionLibLink(const wchar_t* pwszHostName, const wchar_t* pwszSkuName, bool bLaunchAppOnDemand, bool bEnableMultipleAppInstances) : m_hostName(pwszHostName) , m_wideSkuName(pwszSkuName) , m_skuName(std::wstring_convert<std::codecvt_utf8_utf16<wchar_t> >().to_bytes(pwszSkuName)) , m_bLaunchAppOnDemand(bLaunchAppOnDemand) , m_bEnableMultipleAppInstances(bEnableMultipleAppInstances) { // PID used for generating unique shared_memory name const long long llPID = m_bEnableMultipleAppInstances ? DCTL::Utility::GetCurrentProcessId() : -1; m_sHostPID = DCTL::Utility::ProcessIdToString(llPID); } DirectConnectionLibLink::~DirectConnectionLibLink() { } void DirectConnectionLibLink::Clear() { std::lock_guard<std::recursive_mutex> lock(m_instanceCreatorsLock); m_instanceCreators.clear(); } std::list<PortAndChannels> DirectConnectionLibLink::GetAvailableSources() { // We will check and will launch only one time Standalone per this application. static bool standaloneLaunched = false; if (!standaloneLaunched) { static std::recursive_mutex globalCritSec; std::lock_guard<std::recursive_mutex> lock(globalCritSec); if (!standaloneLaunched) { if (m_bLaunchAppOnDemand) { if (!StandaloneApplication::IsLaunched(m_skuName.c_str(), m_sHostPID.data())) { StandaloneApplication::LaunchStandaloneApplication(m_skuName.c_str(), m_sHostPID.data()); } standaloneLaunched = true; } } } auto portAndChannels = ServerPortAndChannels::GetAvailableSources(m_skuName.c_str(), m_sHostPID.data()); for (auto it = portAndChannels.begin(); it != portAndChannels.end();) { // Try to connect to each port to be sure that such port is alive. // For example, two Standalone-s will be launched and one is crashed, // the info for crashed app will be presented in portAndChannels. if (CheckServerConnection(it->first)) { // Working port ++it; } else { // Unworking port it = portAndChannels.erase(it); } } return portAndChannels; } IDirectConnection* DirectConnectionLibLink::CreateInstance(Port port, Channel channel) { std::lock_guard<std::recursive_mutex> lock(m_instanceCreatorsLock); for (auto it = m_instanceCreators.begin(); it != m_instanceCreators.end();) { // Just in case, check that process is running. // If it is not so, remove such DirectConnectionInstanceCreator. if (!(*it)->IsProcessRunning()) { // Remove this instance it = m_instanceCreators.erase(it); } else { ++it; } } auto it = std::find_if(m_instanceCreators.begin(), m_instanceCreators.end(), [&port](const InstanceCreatorPtr& ptr) { return ptr->GetStandaloneClientPort() == port; }); DirectConnectionInstanceCreator* instanceCreator = nullptr; if (it == m_instanceCreators.end()) { bool bInitialized = false; // DirectConnectionInstanceCreator was not created for this port, create now. auto creator = std::make_shared<DirectConnectionInstanceCreator>(port, &bInitialized); NBAssert(bInitialized); // if result is false, seems DirectConnection output was destroyed between calls - // GetAvailableSources() and CreateInstance(). It is normal, // but need to check this case anyway, to be sure. if (bInitialized) { m_instanceCreators.push_back(creator); instanceCreator = creator.get(); } } else { instanceCreator = (*it).get(); } IDirectConnection* pInstance = nullptr; if (instanceCreator) { DirectConnectionInstance* pDCInstance = instanceCreator->CreateInstance(channel); NBAssert(pDCInstance); // Client is down? if (pDCInstance) { pDCInstance->QueryInterface(IID_DirectConnection, reinterpret_cast<void**>(&pInstance)); NBAssert(pInstance); // dev, self-check pDCInstance->Release(); } } return pInstance; } DCResult DirectConnectionLibLink::CloseNTXProcesses() { std::lock_guard<std::recursive_mutex> lock(m_instanceCreatorsLock); DCResult res = DCResult::DCERR_Failed; const char* pszData = "<newblue_ext command=\"exitApp\" />"; for (auto it = m_instanceCreators.begin(); it != m_instanceCreators.end(); ++it) { // Just in case, check that process is running. // If it is, we end the ntx process if ((*it)->IsProcessRunning()) { // Kill ntx process res = (*it)->SendGlobalMetadataFrame(-1, pszData); } } return res; } } // end namespace DCTL
29.12605
112
0.723168
NewBlueFX
56414bebcab6e456a5fc0e6049e856756ce9648d
1,566
hpp
C++
src/Engine/Physics/Obb.hpp
DaftMat/Draft-Engine
395b22c454a4c198824b158dbe8778babb4e11c6
[ "MIT" ]
null
null
null
src/Engine/Physics/Obb.hpp
DaftMat/Draft-Engine
395b22c454a4c198824b158dbe8778babb4e11c6
[ "MIT" ]
null
null
null
src/Engine/Physics/Obb.hpp
DaftMat/Draft-Engine
395b22c454a4c198824b158dbe8778babb4e11c6
[ "MIT" ]
null
null
null
// // Created by mathis on 28/02/2020. // #ifndef DAFT_ENGINE_OBB_HPP #define DAFT_ENGINE_OBB_HPP #include <Eigen/Core> #include <Eigen/Geometry> #include <opengl_stuff.h> #include <Utils/types.hpp> #include <src/Utils/adapters.hpp> /** * Oriented Bounding Box. * A Bounding Box that rotate with the affiliated object */ class Obb { public: /** type of axis for obb planes */ enum AxisType { X = 0, Y, Z }; /** Default constructor. * creates an untransformed obb. */ Obb() : m_aabb(), m_transform{Utils::Transform::Identity()} {} /** Constructor. * * @param aabb - AABB of the affiliated object. * @param transform - transformation of the object. */ Obb( const Utils::Aabb& aabb, const Utils::Transform& transform ) : m_aabb{aabb}, m_transform{transform} {} /** untransformed aabb min getter. * * @return aabb min. */ glm::vec3 min() const { return toGlm( m_aabb.min() ); } /** untransformed aabb max getter. * * @return aabb max. */ glm::vec3 max() const { return toGlm( m_aabb.max() ); } /** obb's position getter. * * @return position of OBB. */ glm::vec3 position() const; /** util function for the axis of obb's planes. * * @param i - index of the axis (0, 1, 2) * @return */ glm::vec3 axis( int i ) const; glm::vec3 axis( AxisType i ) const { return axis( int( i ) ); } private: Utils::Aabb m_aabb; Utils::Transform m_transform; }; #endif // DAFT_ENGINE_OBB_HPP
22.056338
71
0.599617
DaftMat
56417ce9c512e29badff2616b97c9e0dfcc42a62
41,912
hh
C++
schemelib/scheme/objective/hash/XformHash.hh
YaoYinYing/rifdock
cbde6bbeefd29a066273bdf2937cf36b0d2e6335
[ "Apache-2.0" ]
25
2019-07-23T01:03:48.000Z
2022-03-31T04:16:08.000Z
schemelib/scheme/objective/hash/XformHash.hh
YaoYinYing/rifdock
cbde6bbeefd29a066273bdf2937cf36b0d2e6335
[ "Apache-2.0" ]
13
2018-01-30T17:45:57.000Z
2022-03-28T11:02:44.000Z
schemelib/scheme/objective/hash/XformHash.hh
YaoYinYing/rifdock
cbde6bbeefd29a066273bdf2937cf36b0d2e6335
[ "Apache-2.0" ]
14
2018-02-08T01:42:28.000Z
2022-03-31T12:56:17.000Z
#ifndef INCLUDED_objective_hash_XformHash_HH #define INCLUDED_objective_hash_XformHash_HH #include "scheme/util/SimpleArray.hh" #include "scheme/util/dilated_int.hh" #include "scheme/nest/pmap/TetracontoctachoronMap.hh" #include "scheme/numeric/util.hh" #include "scheme/numeric/bcc_lattice.hh" #include <boost/utility/binary.hpp> namespace scheme { namespace objective { namespace hash { template<class Float> void get_transform_rotation( Eigen::Transform<Float,3,Eigen::AffineCompact> const & x, Eigen::Matrix<Float,3,3> & rotation ){ for(int i = 0; i < 9; ++i) rotation.data()[i] = x.data()[i]; } template< class _Xform > struct XformHash_Quat_BCC7_Zorder { typedef uint64_t Key; typedef _Xform Xform; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::BCC< 7, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<7,Float> F7; typedef scheme::util::SimpleArray<7,uint64_t> I7; static Key const ORI_MASK = ~ BOOST_BINARY( 11111111 11111111 11111000 01110000 11100001 11000011 10000111 00001110 ); static Key const ORI_MASK_NO0 = ~ BOOST_BINARY( 11111111 11111111 11111000 01110000 11100001 11000011 10000111 00001111 ); static Key const CART_MASK_NO0 = BOOST_BINARY( 11111111 11111111 11111000 01110000 11100001 11000011 10000111 00001110 ); Grid grid_; int ori_nside_; bool operator==( XformHash_Quat_BCC7_Zorder<Xform> const & o) const { return grid_ == o.grid_; } bool operator!=( XformHash_Quat_BCC7_Zorder<Xform> const & o) const { return grid_ != o.grid_; } static std::string name(){ return "XformHash_Quat_BCC7_Zorder"; } Float cart_spacing() const { return grid_.width_[0]; } XformHash_Quat_BCC7_Zorder() {} XformHash_Quat_BCC7_Zorder( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) { init( cart_resl, cart_resl, cart_bound ); } XformHash_Quat_BCC7_Zorder( Float cart_resl, int ori_nside, Float cart_bound=512.0 ){ init_nside( ori_nside, cart_resl, cart_bound ); } void init( Float cart_resl, Float ang_resl, Float cart_bound ) { // bcc orientation grid covering radii static float const covrad[61] = { 84.09702,54.20621,43.98427,31.58683,27.58101,22.72314,20.42103,17.58167,16.12208,14.44320,13.40178,12.15213,11.49567, 10.53203,10.11448, 9.32353, 8.89083, 8.38516, 7.95147, 7.54148, 7.23572, 6.85615, 6.63594, 6.35606, 6.13243, 5.90677, 5.72515, 5.45705, 5.28864, 5.06335, 4.97668, 4.78774, 4.68602, 4.51794, 4.46654, 4.28316, 4.20425, 4.08935, 3.93284, 3.84954, 3.74505, 3.70789, 3.58776, 3.51407, 3.45023, 3.41919, 3.28658, 3.24700, 3.16814, 3.08456, 3.02271, 2.96266, 2.91052, 2.86858, 2.85592, 2.78403, 2.71234, 2.69544, 2.63151, 2.57503, 2.59064 }; uint64_t ori_nside = 1; while( covrad[ori_nside-1]*1.35 > ang_resl && ori_nside < 61 ) ++ori_nside; // TODO: fix this number! init_nside( (int)ori_nside, cart_resl, cart_bound ); ori_nside_ = ori_nside; } void init_nside( int ori_nside, Float cart_resl, Float cart_bound ){ cart_resl /= sqrt(3)/2.0; if( 2.0*cart_bound/cart_resl > 8192.0 ) throw std::out_of_range("too many cart cells, > 8192"); if( ori_nside > 62 ) throw std::out_of_range("too many ori cells"); // cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) ); // ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) ); I7 nside; nside[0] = nside[1] = nside[2] = 2 * (int)(cart_bound/cart_resl)+1; if( ori_nside % 2 == 0 ) nside[0] = nside[1] = nside[2] = nside[0]+1; // allows repr of 0,0,0... sometimes nside[3] = nside[4] = nside[5] = nside[6] = ori_nside+1; F7 lb,ub; lb[0] = lb[1] = lb[2] = -cart_bound; ub[0] = ub[1] = ub[2] = cart_bound; lb[3] = lb[4] = lb[5] = lb[6] = -1.0-2.0/ori_nside; ub[3] = ub[4] = ub[5] = ub[6] = 1.0; grid_.init( nside, lb, ub ); // std::cout << "NSIDE " << nside << std::endl; } Key get_key( Xform const & x ) const { Eigen::Matrix<Float,3,3> rotation; get_transform_rotation( x, rotation ); Eigen::Quaternion<Float> q( rotation ); q = numeric::to_half_cell(q); F7 f7; f7[0] = x.translation()[0]; f7[1] = x.translation()[1]; f7[2] = x.translation()[2]; f7[3] = q.w(); f7[4] = q.x(); f7[5] = q.y(); f7[6] = q.z(); // std::cout << f7 << std::endl; bool odd; I7 i7 = grid_.get_indices( f7, odd ); // std::cout << std::endl << (i7[0]>>6) << " " << (i7[1]>>6) << " " << (i7[2]>>6) << " " << i7[3] << " " << i7[4] << " " // << i7[5] << " " << i7[6] << " " << std::endl; // std::cout << std::endl << i7 << std::endl; Key key = odd; key = key | (i7[0]>>6)<<57; key = key | (i7[1]>>6)<<50; key = key | (i7[2]>>6)<<43; key = key | util::dilate<7>( i7[0] & 63 ) << 1; key = key | util::dilate<7>( i7[1] & 63 ) << 2; key = key | util::dilate<7>( i7[2] & 63 ) << 3; key = key | util::dilate<7>( i7[3] ) << 4; key = key | util::dilate<7>( i7[4] ) << 5; key = key | util::dilate<7>( i7[5] ) << 6; key = key | util::dilate<7>( i7[6] ) << 7; return key; } I7 get_indices(Key key, bool & odd) const { odd = key & (Key)1; I7 i7; i7[0] = (util::undilate<7>( key>>1 ) & 63) | ((key>>57)&127)<<6; i7[1] = (util::undilate<7>( key>>2 ) & 63) | ((key>>50)&127)<<6; i7[2] = (util::undilate<7>( key>>3 ) & 63) | ((key>>43)&127)<<6; i7[3] = util::undilate<7>( key>>4 ) & 63; i7[4] = util::undilate<7>( key>>5 ) & 63; i7[5] = util::undilate<7>( key>>6 ) & 63; i7[6] = util::undilate<7>( key>>7 ) & 63; return i7; } Xform get_center(Key key) const { bool odd; I7 i7 = get_indices(key,odd); // std::cout << i7 << std::endl << std::endl; F7 f7 = grid_.get_center(i7,odd); // std::cout << f7 << std::endl; Eigen::Quaternion<Float> q( f7[3], f7[4], f7[5], f7[6] ); q.normalize(); // q = numeric::to_half_cell(q); // should be un-necessary Xform center( q.matrix() ); center.translation()[0] = f7[0]; center.translation()[1] = f7[1]; center.translation()[2] = f7[2]; return center; } Key cart_shift_key(Key key, int dx, int dy, int dz, Key d_o=0) const { Key o = key%2; Key x = (util::undilate<7>( key>>1 ) & 63) | ((key>>57)&127)<<6; Key y = (util::undilate<7>( key>>2 ) & 63) | ((key>>50)&127)<<6; Key z = (util::undilate<7>( key>>3 ) & 63) | ((key>>43)&127)<<6; x += dx; y += dy; z += dz; o ^= d_o; key &= ORI_MASK; // zero cart parts of key key &= ~(Key)1; // zero even/odd key |= o; key |= (x>>6)<<57 | util::dilate<7>( x & 63 ) << 1; key |= (y>>6)<<50 | util::dilate<7>( y & 63 ) << 2; key |= (z>>6)<<43 | util::dilate<7>( z & 63 ) << 3; return key; } Key approx_size() const { return grid_.size(); } Key approx_nori() const { static int const nori[63] = { 0, 53, 53, 181, 321, 665, 874, 1642, 1997, 2424, 3337, 4504, 5269, 6592, 8230, 10193, 11420, 14068, 16117, 19001, 21362, 25401, 29191, 33227, 37210, 41454, 45779, 51303, 57248, 62639, 69417, 76572, 83178, 92177, 99551,108790,117666,127850,138032,149535,159922,171989,183625,196557,209596,226672,239034,253897, 271773,288344,306917,324284,342088,364686,381262,405730,427540,450284,472265,498028,521872,547463}; return nori[ grid_.nside_[3]-2 ]; // -1 for 0-index, -1 for ori_side+1 } Float cart_width() const { return grid_.width_[0]; } Float ang_width() const { return grid_.width_[3]; } Key asym_key(Key key, Key & isym) const { // get o,w,x,y,z for orig key Key o = key & (Key)1; Key w = util::undilate<7>( key>>4 ) & 63; Key x = util::undilate<7>( key>>5 ) & 63; Key y = util::undilate<7>( key>>6 ) & 63; Key z = util::undilate<7>( key>>7 ) & 63; // std::cout << grid_.nside_[3]-o <<" " << o << " " << w << "\t" << x << "\t" << y << "\t" << z << std::endl; // move to primaary assert(o==0||o==1); Key nside1 = grid_.nside_[3] - o; isym = /*(w>nside1/2)<<3 |*/ (x<=nside1/2&&nside1!=2*x)<<2 | (y<=nside1/2&&nside1!=2*y)<<1 | (z<=nside1/2&&nside1!=2*z)<<0; assert( w >= nside1/2 ); // w = w > nside1/2 ? w : nside1-w; // std::cout << "FX " << (x <= nside1/2) << " " << (2*x==nside1) << std::endl; // std::cout << "FY " << (y <= nside1/2) << " " << (2*y==nside1) << std::endl; // std::cout << "FZ " << (z <= nside1/2) << " " << (2*z==nside1) << std::endl; x = x > nside1/2 ? x : nside1-x; y = y > nside1/2 ? y : nside1-y; z = z > nside1/2 ? z : nside1-z; // make new key Key k = key & ~ORI_MASK; k = k | o; k = k | util::dilate<7>( w ) << 4; k = k | util::dilate<7>( x ) << 5; k = k | util::dilate<7>( y ) << 6; k = k | util::dilate<7>( z ) << 7; return k; } Key sym_key(Key key, Key isym) const { // get o,w,x,y,z for orig key Key o = key & (Key)1; Key w = util::undilate<7>( key>>4 ) & 63; Key x = util::undilate<7>( key>>5 ) & 63; Key y = util::undilate<7>( key>>6 ) & 63; Key z = util::undilate<7>( key>>7 ) & 63; // std::cout << grid_.nside_[3]-o <<" " << o << " " << w << "\t" << x << "\t" << y << "\t" << z << std::endl; // move to isym Key nside1 = grid_.nside_[3] - o; assert( w >= nside1/2 ); // w = (isym>>3)&1 ? w : nside1-w; x = (isym>>2)&1 ? nside1-x : x; y = (isym>>1)&1 ? nside1-y : y; z = (isym>>0)&1 ? nside1-z : z; // make new key Key k = key & ~ORI_MASK; k = k | o; k = k | util::dilate<7>( w ) << 4; k = k | util::dilate<7>( x ) << 5; k = k | util::dilate<7>( y ) << 6; k = k | util::dilate<7>( z ) << 7; return k; } Key num_key_symmetries() const { return 16; } void print_key(Key key) const { bool odd; I7 i7 = get_indices(key,odd); std::cout << i7 << " " << odd << std::endl; } F7 lever_coord( Key key, Float lever_dist, F7 const & ref ) const { bool odd; I7 i7 = get_indices(key,odd); F7 f7 = grid_.get_center(i7,odd); Eigen::Quaternion<Float> q( f7[3], f7[4], f7[5], f7[6] ); q.normalize(); Eigen::Quaternion<Float> qref( ref[3], ref[4], ref[5], ref[6] ); bool const neg = q.dot( qref ) < 0.0; f7[3] = ( neg? -q.w() : q.w() ) * lever_dist * 2.0; f7[4] = ( neg? -q.x() : q.x() ) * lever_dist * 2.0; f7[5] = ( neg? -q.y() : q.y() ) * lever_dist * 2.0; f7[6] = ( neg? -q.z() : q.z() ) * lever_dist * 2.0; return f7; } }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // EVERYTHING BELOW THIS POINT MAY BE INCOMPLETE IN SOME WAY /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template< class _Xform > struct XformHash_Quat_BCC7 { typedef uint64_t Key; typedef _Xform Xform; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::BCC< 7, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<7,Float> F7; typedef scheme::util::SimpleArray<7,uint64_t> I7; Float grid_size_; Float grid_spacing_; OriMap ori_map_; Grid grid_; int ori_nside_; static std::string name(){ return "XformHash_Quat_BCC7"; } XformHash_Quat_BCC7( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) { cart_resl /= sqrt(3)/2.0; // TODO: fix this number! // bcc orientation grid covering radii static float const covrad[99] = { 84.09702,54.20621,43.98427,31.58683,27.58101,22.72314,20.42103,17.58167,16.12208,14.44320,13.40178,12.15213,11.49567, 10.53203,10.11448, 9.32353, 8.89083, 8.38516, 7.95147, 7.54148, 7.23572, 6.85615, 6.63594, 6.35606, 6.13243, 5.90677, 5.72515, 5.45705, 5.28864, 5.06335, 4.97668, 4.78774, 4.68602, 4.51794, 4.46654, 4.28316, 4.20425, 4.08935, 3.93284, 3.84954, 3.74505, 3.70789, 3.58776, 3.51407, 3.45023, 3.41919, 3.28658, 3.24700, 3.16814, 3.08456, 3.02271, 2.96266, 2.91052, 2.86858, 2.85592, 2.78403, 2.71234, 2.69544, 2.63151, 2.57503, 2.59064, 2.55367, 2.48010, 2.41046, 2.40289, 2.36125, 2.33856, 2.29815, 2.26979, 2.21838, 2.19458, 2.17881, 2.12842, 2.14030, 2.06959, 2.05272, 2.04950, 2.00790, 1.96385, 1.96788, 1.91474, 1.90942, 1.90965, 1.85602, 1.83792, 1.81660, 1.80228, 1.77532, 1.76455, 1.72948, 1.72179, 1.68324, 1.67009, 1.67239, 1.64719, 1.63832, 1.60963, 1.60093, 1.58911}; uint64_t ori_nside = 1; while( covrad[ori_nside-1]*1.35 > ang_resl && ori_nside < 100 ) ++ori_nside; ori_nside_ = ori_nside; if( 2.0*cart_bound/cart_resl > 8192.0 ) throw std::out_of_range("too many cart cells, > 8192"); // cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) ); // ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) ); I7 nside; nside[0] = nside[1] = nside[2] = 2.0*cart_bound/cart_resl; nside[3] = nside[4] = nside[5] = nside[6] = ori_nside+2; F7 ub; ub[0] = ub[1] = ub[2] = cart_bound; ub[3] = ub[4] = ub[5] = ub[6] = 1.0+2.0/ori_nside; grid_.init( nside, -ub, ub ); } Key get_key( Xform const & x ) const { Eigen::Matrix<Float,3,3> rotation; get_transform_rotation( x, rotation ); Eigen::Quaternion<Float> q( rotation ); q = numeric::to_half_cell(q); F7 f7; f7[0] = x.translation()[0]; f7[1] = x.translation()[1]; f7[2] = x.translation()[2]; f7[3] = q.w(); f7[4] = q.x(); f7[5] = q.y(); f7[6] = q.z(); // std::cout << f7 << std::endl; Key key = grid_[f7]; return key; } Xform get_center(Key key) const { F7 f7 = grid_[key]; // std::cout << f7 << std::endl; Eigen::Quaternion<Float> q( f7[3], f7[4], f7[5], f7[6] ); q.normalize(); Xform center( q.matrix() ); center.translation()[0] = f7[0]; center.translation()[1] = f7[1]; center.translation()[2] = f7[2]; return center; } Key approx_size() const { return grid_.size(); } Key approx_nori() const { static int const nori[63] = { 0, 53, 53, 181, 321, 665, 874, 1642, 1997, 2424, 3337, 4504, 5269, 6592, 8230, 10193, 11420, 14068, 16117, 19001, 21362, 25401, 29191, 33227, 37210, 41454, 45779, 51303, 57248, 62639, 69417, 76572, 83178, 92177, 99551,108790,117666,127850,138032,149535,159922,171989,183625,196557,209596,226672,239034,253897, 271773,288344,306917,324284,342088,364686,381262,405730,427540,450284,472265,498028,521872,547463}; return nori[ grid_.nside_[3]-2 ]; // -1 for 0-index, -1 for ori_side+1 } Float ang_width() const { return grid_.with_[3]; } }; template< class Xform > struct XformHash_bt24_BCC3_Zorder { typedef uint64_t Key; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::BCC< 3, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<3,Float> F3; typedef scheme::util::SimpleArray<3,uint64_t> I3; Float grid_size_; Float grid_spacing_; OriMap ori_map_; Grid cart_grid_, ori_grid_; int ori_nside_; static std::string name(){ return "XformHash_bt24_BCC3_Zorder"; } XformHash_bt24_BCC3_Zorder( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) { // bcc orientation grid covering radii static float const covrad[64] = { 49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932, 4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235, 2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216, 1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436, 1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480, 0.86141, 0.84846, 0.83677, 0.82164 }; uint64_t ori_nside = 1; while( covrad[ori_nside-1]*1.01 > ang_resl && ori_nside < 62 ) ++ori_nside; ori_nside_ = ori_nside; init( cart_resl, ori_nside, cart_bound ); } XformHash_bt24_BCC3_Zorder( Float cart_resl, int ori_nside, Float cart_bound ){ init(cart_resl,ori_nside,cart_bound); } void init( Float cart_resl, int ori_nside, Float cart_bound ){ cart_resl /= 0.56; // TODO: fix this number! // std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl; if( 2*(int)(cart_bound/cart_resl) > 8192 ){ throw std::out_of_range("can have at most 8192 cart cells!"); } cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) ); ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) ); // std::cout << "cart_bcc " << cart_grid_ << std::endl; // std::cout << " ori_bcc " << ori_grid_ << std::endl; // std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl; } // Key structure // 5 bits bt24 cell index // 7 bits high order cart X bits // 7 bits high order cart Y bits // 7 bits high order cart Z bits // 36 bits 6*6 zorder cart/ori // 2 bits cart/ori even/odd Key get_key( Xform const & x ) const { Eigen::Matrix3d rotation; get_transform_rotation( x, rotation ); uint64_t cell_index; F3 params; ori_map_.value_to_params( rotation, 0, params, cell_index ); assert( cell_index < 24 ); assert( 0.0 <= params[0] && params[0] <= 1.0 ); assert( 0.0 <= params[1] && params[1] <= 1.0 ); assert( 0.0 <= params[2] && params[2] <= 1.0 ); bool ori_odd, cart_odd; I3 ori_indices, cart_indices; ori_indices = ori_grid_.get_indices( params, ori_odd ); F3 trans(x.translation()); cart_indices = cart_grid_.get_indices( trans, cart_odd ); // std::cout << "get_index " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl; Key key; key = cell_index << 59; key = key | (cart_indices[0]>>6) << 52; key = key | (cart_indices[1]>>6) << 45; key = key | (cart_indices[2]>>6) << 38; // 6*6 zorder key = key>>2; key = key | ( util::dilate<6>( ori_indices[0] ) << 0 ); key = key | ( util::dilate<6>( ori_indices[1] ) << 1 ); key = key | ( util::dilate<6>( ori_indices[2] ) << 2 ); key = key | ( util::dilate<6>( (cart_indices[0] & 63) ) << 3 ); key = key | ( util::dilate<6>( (cart_indices[1] & 63) ) << 4 ); key = key | ( util::dilate<6>( (cart_indices[2] & 63) ) << 5 ); key = key<<2; // lowest two bits, even/odd key = key | ori_odd | cart_odd<<1; return key; } Xform get_center(Key key) const { I3 cart_indices, ori_indices; uint64_t cell_index = key >> 59; cart_indices[0] = (((key>>52)&127) << 6) | (util::undilate<6>( (key>>5) ) & 63); cart_indices[1] = (((key>>45)&127) << 6) | (util::undilate<6>( (key>>6) ) & 63); cart_indices[2] = (((key>>38)&127) << 6) | (util::undilate<6>( (key>>7) ) & 63); ori_indices[0] = util::undilate<6>( (key>>2)&(((uint64_t)1<<36)-1) ) & 63; ori_indices[1] = util::undilate<6>( (key>>3)&(((uint64_t)1<<36)-1) ) & 63; ori_indices[2] = util::undilate<6>( (key>>4)&(((uint64_t)1<<36)-1) ) & 63; bool ori_odd = key & (Key)1; bool cart_odd = key & (Key)2; F3 trans = cart_grid_.get_center(cart_indices,cart_odd); F3 params = ori_grid_.get_center(ori_indices,ori_odd); Eigen::Matrix3d m; ori_map_.params_to_value( params, cell_index, 0, m ); // std::cout << "get_center " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl; Xform center( m ); center.translation()[0] = trans[0]; center.translation()[1] = trans[1]; center.translation()[2] = trans[2]; return center; } Key approx_size() const { return (ori_grid_.sizes_[0]-1)*(ori_grid_.sizes_[1]-1)*(ori_grid_.sizes_[2]-1)*2 * cart_grid_.size() * 24; } Key approx_nori() const { throw std::logic_error("not implemented"); } }; template< class Xform > struct XformHash_bt24_BCC3 { typedef uint64_t Key; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::BCC< 3, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<3,Float> F3; typedef scheme::util::SimpleArray<3,uint64_t> I3; Float grid_size_; Float grid_spacing_; OriMap ori_map_; Grid cart_grid_, ori_grid_; int ori_nside_; static std::string name(){ return "XformHash_bt24_BCC3"; } XformHash_bt24_BCC3( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) { cart_resl /= 0.56; // TODO: fix this number! // bcc orientation grid covering radii static float const covrad[64] = { 49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932, 4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235, 2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216, 1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436, 1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480, 0.86141, 0.84846, 0.83677, 0.82164 }; uint64_t ori_nside = 1; while( covrad[ori_nside-1]*1.01 > ang_resl && ori_nside < 62 ) ++ori_nside; // std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl; ori_nside_ = ori_nside; if( 2*(int)(cart_bound/cart_resl) > 8192 ){ throw std::out_of_range("can have at most 8192 cart cells!"); } cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) ); ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) ); // std::cout << "cart_bcc " << cart_grid_ << std::endl; // std::cout << " ori_bcc " << ori_grid_ << std::endl; // std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl; } Key get_key( Xform const & x ) const { Eigen::Matrix3d rotation; get_transform_rotation( x, rotation ); uint64_t cell_index; F3 params; ori_map_.value_to_params( rotation, 0, params, cell_index ); assert( cell_index < 24 ); assert( 0.0 <= params[0] && params[0] <= 1.0 ); assert( 0.0 <= params[1] && params[1] <= 1.0 ); assert( 0.0 <= params[2] && params[2] <= 1.0 ); F3 trans(x.translation()); Key ori_index, cart_index; ori_index = ori_grid_[ params ]; cart_index = cart_grid_[ trans ]; // std::cout << cart_index << " " << ori_isndex << " " << cell_index << std::endl; Key key; key = cell_index << 59; key = key | cart_index << 18; key = key | ori_index; return key; } Xform get_center(Key key) const { I3 cart_indices, ori_indices; Key cell_index = key >> 59; Key cart_index = (key<<5)>>23; Key ori_index = key & (((Key)1<<18)-1); // std::cout << cart_index << " " << ori_index << " " << cell_index << std::endl; F3 trans = cart_grid_[cart_index]; F3 params = ori_grid_[ori_index]; Eigen::Matrix3d m; ori_map_.params_to_value( params, cell_index, 0, m ); Xform center( m ); center.translation()[0] = trans[0]; center.translation()[1] = trans[1]; center.translation()[2] = trans[2]; return center; } Key approx_size() const { return (ori_grid_.sizes_[0]-1)*(ori_grid_.sizes_[1]-1)*(ori_grid_.sizes_[2]-1)*2 * cart_grid_.size() * 24; } Key approx_nori() const { throw std::logic_error("not implemented"); } }; // TODO: make _Zorder version of XformHash_bt24_BCC6 template< class Xform > struct XformHash_bt24_BCC6 { typedef uint64_t Key; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::BCC< 6, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<3,Float> F3; typedef scheme::util::SimpleArray<3,uint64_t> I3; typedef scheme::util::SimpleArray<6,Float> F6; typedef scheme::util::SimpleArray<6,uint64_t> I6; Float grid_size_; Float grid_spacing_; OriMap ori_map_; Grid grid_; int ori_nside_; static std::string name(){ return "XformHash_bt24_BCC6"; } XformHash_bt24_BCC6(){} XformHash_bt24_BCC6( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ){ init( cart_resl, ang_resl, cart_bound ); } void init( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ){ // bcc orientation grid covering radii static float const covrad[64] = { 49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932, 4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235, 2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216, 1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436, 1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480, 0.86141, 0.84846, 0.83677, 0.82164 }; uint64_t ori_nside = 1; while( covrad[ori_nside-1]*1.45 > ang_resl && ori_nside < 62 ) ++ori_nside; // TODO: HACK multiplier! ori_nside_ = ori_nside; // std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; // std::cout << "ori_nside: " << ori_nside << std::endl; // std::cout << "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" << std::endl; init( cart_resl, (int)ori_nside, cart_bound ); } XformHash_bt24_BCC6( Float cart_resl, int ori_nside, Float cart_bound ){ // std::cout << "ori_nside c'tor" << std::endl; init( cart_resl, ori_nside, cart_bound ); } void init( Float cart_resl, int ori_nside, Float cart_bound ){ cart_resl /= sqrt(3.0)/2.0; // TODO: HACK multiplier! // std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl; if( 2*(int)(cart_bound/cart_resl) > 8192 ){ throw std::out_of_range("can have at most 8192 cart cells!"); } I6 nside; nside[0] = nside[1] = nside[2] = 2.0*cart_bound/cart_resl; nside[3] = nside[4] = nside[5] = ori_nside+1; // std::cout << "SIDES: " << nside[0] << " " << nside[3] << std::endl; F6 lb,ub; lb[0] = lb[1] = lb[2] = -cart_bound; ub[0] = ub[1] = ub[2] = cart_bound; lb[3] = lb[4] = lb[5] = -1.0/ori_nside; ub[3] = ub[4] = ub[5] = 1.0; grid_.init( nside, lb, ub ); } scheme::util::SimpleArray<7,Float> get_f7( Xform const & x ) const { Eigen::Matrix<Float,3,3> rotation; get_transform_rotation( x, rotation ); F3 params; uint64_t cell_index; // ori_map_.value_to_params( rotation, 0, params, cell_index ); { // from TetracontoctachoronMap.hh Eigen::Quaternion<Float> q(rotation); numeric::get_cell_48cell_half( q.coeffs(), cell_index ); q = nest::pmap::hbt24_cellcen<Float>( cell_index ).inverse() * q; q = numeric::to_half_cell(q); params[0] = q.x()/q.w()/nest::pmap::cell_width<Float>() + 0.5; params[1] = q.y()/q.w()/nest::pmap::cell_width<Float>() + 0.5; params[2] = q.z()/q.w()/nest::pmap::cell_width<Float>() + 0.5; // assert( -0.0001 <= params[0] && params[0] <= 1.0001 ); // assert( -0.0001 <= params[1] && params[1] <= 1.0001 ); // assert( -0.0001 <= params[2] && params[2] <= 1.0001 ); } assert( cell_index < 24 ); params[0] = fmax(0.0,params[0]); params[1] = fmax(0.0,params[1]); params[2] = fmax(0.0,params[2]); params[0] = fmin(1.0,params[0]); params[1] = fmin(1.0,params[1]); params[2] = fmin(1.0,params[2]); scheme::util::SimpleArray<7,Float> params6; params6[0] = x.translation()[0]; params6[1] = x.translation()[1]; params6[2] = x.translation()[2]; params6[3] = params[0]; params6[4] = params[1]; params6[5] = params[2]; params6[6] = cell_index; return params6; } Key get_key( Xform const & x ) const { Eigen::Matrix<Float,3,3> rotation; get_transform_rotation( x, rotation ); uint64_t cell_index; F3 params; // ori_map_.value_to_params( rotation, 0, params, cell_index ); { // from TetracontoctachoronMap.hh Eigen::Quaternion<Float> q(rotation); numeric::get_cell_48cell_half( q.coeffs(), cell_index ); q = nest::pmap::hbt24_cellcen<Float>( cell_index ).inverse() * q; q = numeric::to_half_cell(q); params[0] = q.x()/q.w()/nest::pmap::cell_width<Float>() + 0.5; params[1] = q.y()/q.w()/nest::pmap::cell_width<Float>() + 0.5; params[2] = q.z()/q.w()/nest::pmap::cell_width<Float>() + 0.5; // assert( -0.0001 <= params[0] && params[0] <= 1.0001 ); // assert( -0.0001 <= params[1] && params[1] <= 1.0001 ); // assert( -0.0001 <= params[2] && params[2] <= 1.0001 ); } assert( cell_index < 24 ); params[0] = fmax(0.0,params[0]); params[1] = fmax(0.0,params[1]); params[2] = fmax(0.0,params[2]); params[0] = fmin(1.0,params[0]); params[1] = fmin(1.0,params[1]); params[2] = fmin(1.0,params[2]); F6 params6; params6[0] = x.translation()[0]; params6[1] = x.translation()[1]; params6[2] = x.translation()[2]; params6[3] = params[0]; params6[4] = params[1]; params6[5] = params[2]; return cell_index<<59 | grid_[params6]; } std::vector<Key> get_key_and_nbrs( Xform const & x ) const { Eigen::Matrix<Float,3,3> rotation; get_transform_rotation( x, rotation ); uint64_t cell_index; F3 params; // ori_map_.value_to_params( rotation, 0, params, cell_index ); { // from TetracontoctachoronMap.hh Eigen::Quaternion<Float> q(rotation); numeric::get_cell_48cell_half( q.coeffs(), cell_index ); q = nest::pmap::hbt24_cellcen<Float>( cell_index ).inverse() * q; q = numeric::to_half_cell(q); params[0] = q.x()/q.w()/nest::pmap::cell_width<Float>() + 0.5; params[1] = q.y()/q.w()/nest::pmap::cell_width<Float>() + 0.5; params[2] = q.z()/q.w()/nest::pmap::cell_width<Float>() + 0.5; // assert( -0.0001 <= params[0] && params[0] <= 1.0001 ); // assert( -0.0001 <= params[1] && params[1] <= 1.0001 ); // assert( -0.0001 <= params[2] && params[2] <= 1.0001 ); } assert( cell_index < 24 ); params[0] = fmax(0.0,params[0]); params[1] = fmax(0.0,params[1]); params[2] = fmax(0.0,params[2]); params[0] = fmin(1.0,params[0]); params[1] = fmin(1.0,params[1]); params[2] = fmin(1.0,params[2]); F6 params6; params6[0] = x.translation()[0]; params6[1] = x.translation()[1]; params6[2] = x.translation()[2]; params6[3] = params[0]; params6[4] = params[1]; params6[5] = params[2]; uint64_t index = grid_[params6]; std::vector<Key> to_ret { index }; grid_.neighbors( index, std::back_inserter(to_ret), true ); for ( int i = 0; i < to_ret.size(); i++ ) { to_ret[i] = cell_index<<59 | to_ret[i]; } return to_ret; } Xform get_center(Key key) const { Key cell_index = key >> 59; F6 params6 = grid_[ key & (((Key)1<<59)-(Key)1) ]; F3 params; params[0] = params6[3]; params[1] = params6[4]; params[2] = params6[5]; Eigen::Matrix<Float,3,3> m; // ori_map_.params_to_value( params, cell_index, 0, m ); { Float const & w(nest::pmap::cell_width<Float>()); // assert( params[0] >= -0.0001 && params[0] <= 1.0001 ); // assert( params[1] >= -0.0001 && params[1] <= 1.0001 ); // assert( params[2] >= -0.0001 && params[2] <= 1.0001 ); params[0] = fmax(0.0,params[0]); params[1] = fmax(0.0,params[1]); params[2] = fmax(0.0,params[2]); params[0] = fmin(1.0,params[0]); params[1] = fmin(1.0,params[1]); params[2] = fmin(1.0,params[2]); // std::cout << cell_index << " " << p << " " << p << std::endl; // static int count = 0; if( ++count > 30 ) std::exit(-1); params = w*(params-0.5); // now |params| < sqrt(2)-1 // Eigen::Quaternion<Float> q( sqrt(1.0-p.squaredNorm()), p[0], p[1], p[2] ); // assert( fabs(q.squaredNorm()-1.0) < 0.000001 ); Eigen::Quaternion<Float> q( 1.0, params[0], params[1], params[2] ); q.normalize(); q = nest::pmap::hbt24_cellcen<Float>( cell_index ) * q; m = q.matrix(); } Xform center( m ); center.translation()[0] = params6[0]; center.translation()[1] = params6[1]; center.translation()[2] = params6[2]; return center; } Key approx_size() const { return grid_.size() * 24; } Key approx_nori() const { static int const nori[18] = { 192, 648, 1521, 2855, 4990, 7917, 11682, 16693, 23011, 30471, 39504, 50464, 62849, 77169, 93903,112604,133352,157103 }; return nori[ grid_.nside_[3]-2 ]; // -1 for 0-index, -1 for ori_side+1 } }; template< class Xform > struct XformHash_bt24_Cubic_Zorder { typedef uint64_t Key; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::Cubic< 3, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<3,Float> F3; typedef scheme::util::SimpleArray<3,uint64_t> I3; Float grid_size_; Float grid_spacing_; OriMap ori_map_; Grid cart_grid_, ori_grid_; int ori_nside_; static std::string name(){ return "XformHash_bt24_Cubic_Zorder"; } XformHash_bt24_Cubic_Zorder( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) { cart_resl /= 0.867; // TODO: fix this number! // bcc orientation grid covering radii static float const covrad[64] = { 62.71876,39.26276,26.61019,20.06358,16.20437,13.45733,11.58808,10.10294, 9.00817, 8.12656, 7.37295, 6.74856, 6.23527, 5.77090, 5.38323, 5.07305, 4.76208, 4.50967, 4.25113, 4.04065, 3.88241, 3.68300, 3.53376, 3.36904, 3.22018, 3.13437, 2.99565, 2.89568, 2.78295, 2.70731, 2.61762, 2.52821, 2.45660, 2.37996, 2.31057, 2.25207, 2.18726, 2.13725, 2.08080, 2.02489, 1.97903, 1.92123, 1.88348, 1.83759, 1.79917, 1.76493, 1.72408, 1.68516, 1.64581, 1.62274, 1.57909, 1.55846, 1.52323, 1.50846, 1.47719, 1.44242, 1.42865, 1.39023, 1.37749, 1.34783, 1.32588, 1.31959, 1.29872, 1.26796 }; uint64_t ori_nside = 1; while( covrad[ori_nside-1]*1.01 > ang_resl && ori_nside < 62 ) ++ori_nside; // std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl; ori_nside_ = ori_nside; if( 2*(int)(cart_bound/cart_resl) > 8192 ){ throw std::out_of_range("can have at most 8192 cart cells!"); } cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) ); ori_grid_.init( I3(ori_nside), F3(0.0), F3(1.0) ); // std::cout << "cart_bcc " << cart_grid_ << std::endl; // std::cout << " ori_bcc " << ori_grid_ << std::endl; // std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl; } Key get_key( Xform const & x ) const { Eigen::Matrix3d rotation; get_transform_rotation( x, rotation ); uint64_t cell_index; F3 params; ori_map_.value_to_params( rotation, 0, params, cell_index ); assert( cell_index < 24 ); assert( 0.0 <= params[0] && params[0] <= 1.0 ); assert( 0.0 <= params[1] && params[1] <= 1.0 ); assert( 0.0 <= params[2] && params[2] <= 1.0 ); I3 ori_indices, cart_indices; ori_indices = ori_grid_.get_indices( params ); F3 trans(x.translation()); cart_indices = cart_grid_.get_indices( trans ); // std::cout << "get_index " << cell_index << " " << cart_indices << " " << ori_indices << std::endl; Key key; key = cell_index << 59; key = key | (cart_indices[0]>>6) << 52; key = key | (cart_indices[1]>>6) << 45; key = key | (cart_indices[2]>>6) << 38; // 6*6 zorder key = key >> 2; key = key | ( util::dilate<6>( ori_indices[0] ) << 0 ); key = key | ( util::dilate<6>( ori_indices[1] ) << 1 ); key = key | ( util::dilate<6>( ori_indices[2] ) << 2 ); key = key | ( util::dilate<6>( (cart_indices[0] & 63) ) << 3 ); key = key | ( util::dilate<6>( (cart_indices[1] & 63) ) << 4 ); key = key | ( util::dilate<6>( (cart_indices[2] & 63) ) << 5 ); key = key << 2; return key; } Xform get_center(Key key) const { I3 cart_indices, ori_indices; uint64_t cell_index = key >> 59; cart_indices[0] = (((key>>52)&127) << 6) | (util::undilate<6>( (key>>5) ) & 63); cart_indices[1] = (((key>>45)&127) << 6) | (util::undilate<6>( (key>>6) ) & 63); cart_indices[2] = (((key>>38)&127) << 6) | (util::undilate<6>( (key>>7) ) & 63); ori_indices[0] = util::undilate<6>( (key>>2)&(((Key)1<<36)-1) ) & 63; ori_indices[1] = util::undilate<6>( (key>>3)&(((Key)1<<36)-1) ) & 63; ori_indices[2] = util::undilate<6>( (key>>4)&(((Key)1<<36)-1) ) & 63; F3 trans = cart_grid_.get_center(cart_indices); F3 params = ori_grid_.get_center(ori_indices); // std::cout << "get_center " << cell_index << " " << cart_indices << " " << ori_indices << std::endl; Eigen::Matrix3d m; ori_map_.params_to_value( params, cell_index, 0, m ); Xform center( m ); center.translation()[0] = trans[0]; center.translation()[1] = trans[1]; center.translation()[2] = trans[2]; return center; } Key approx_size() const { return (ori_grid_.sizes_[0])*(ori_grid_.sizes_[1])*(ori_grid_.sizes_[2]) * cart_grid_.size() * 24; } Key approx_nori() const { throw std::logic_error("not implemented"); } }; template< class Xform > struct XformHash_Quatgrid_Cubic { typedef uint64_t Key; typedef typename Xform::Scalar Float; typedef scheme::nest::pmap::TetracontoctachoronMap<> OriMap; typedef scheme::numeric::Cubic< 3, Float, uint64_t > Grid; typedef scheme::util::SimpleArray<3,Float> F3; typedef scheme::util::SimpleArray<3,uint64_t> I3; Float grid_size_; Float grid_spacing_; OriMap ori_map_; Grid cart_grid_, ori_grid_; static std::string name(){ return "XformHash_Quatgrid_Cubic"; } XformHash_Quatgrid_Cubic( Float cart_resl, Float ang_resl, Float cart_bound=512.0 ) { cart_resl /= 0.56; // TODO: fix this number! // bcc orientation grid covering radii static float const covrad[64] = { 49.66580,25.99805,17.48845,13.15078,10.48384, 8.76800, 7.48210, 6.56491, 5.84498, 5.27430, 4.78793, 4.35932, 4.04326, 3.76735, 3.51456, 3.29493, 3.09656, 2.92407, 2.75865, 2.62890, 2.51173, 2.39665, 2.28840, 2.19235, 2.09949, 2.01564, 1.94154, 1.87351, 1.80926, 1.75516, 1.69866, 1.64672, 1.59025, 1.54589, 1.50077, 1.46216, 1.41758, 1.38146, 1.35363, 1.31630, 1.28212, 1.24864, 1.21919, 1.20169, 1.17003, 1.14951, 1.11853, 1.09436, 1.07381, 1.05223, 1.02896, 1.00747, 0.99457, 0.97719, 0.95703, 0.93588, 0.92061, 0.90475, 0.89253, 0.87480, 0.86141, 0.84846, 0.83677, 0.82164 }; uint64_t ori_nside = 1; while( covrad[ori_nside-1] > ang_resl && ori_nside < 62 ) ++ori_nside; // std::cout << "requested ang_resl: " << ang_resl << " got " << covrad[ori_nside-1] << std::endl; if( 2*(int)(cart_bound/cart_resl) > 8192 ){ throw std::out_of_range("can have at most 8192 cart cells!"); } cart_grid_.init( I3(2.0*cart_bound/cart_resl), F3(-cart_bound), F3(cart_bound) ); ori_grid_.init( I3(ori_nside+2), F3(-1.0/ori_nside), F3(1.0+1.0/ori_nside) ); // std::cout << "cart_bcc " << cart_grid_ << std::endl; // std::cout << " ori_bcc " << ori_grid_ << std::endl; // std::cout << log2( (double)cart_grid_.size() / ori_grid_.size() ) << std::endl; } Key get_key( Xform const & x ) const { Eigen::Matrix3d rotation; get_transform_rotation( x, rotation ); uint64_t cell_index; F3 params; ori_map_.value_to_params( rotation, 0, params, cell_index ); assert( cell_index < 24 ); assert( 0.0 <= params[0] && params[0] <= 1.0 ); assert( 0.0 <= params[1] && params[1] <= 1.0 ); assert( 0.0 <= params[2] && params[2] <= 1.0 ); bool ori_odd, cart_odd; I3 ori_indices, cart_indices; ori_indices = ori_grid_.get_indices( params, ori_odd ); F3 trans(x.translation()); cart_indices = cart_grid_.get_indices( trans, cart_odd ); // std::cout << "get_index " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl; Key key; key = cell_index << 59; key = key | (cart_indices[0]>>6) << 52; key = key | (cart_indices[1]>>6) << 45; key = key | (cart_indices[2]>>6) << 38; // 6*6 zorder key = key>>2; key = key | ( util::dilate<6>( ori_indices[0] ) << 0 ); key = key | ( util::dilate<6>( ori_indices[1] ) << 1 ); key = key | ( util::dilate<6>( ori_indices[2] ) << 2 ); key = key | ( util::dilate<6>( (cart_indices[0] & 63) ) << 3 ); key = key | ( util::dilate<6>( (cart_indices[1] & 63) ) << 4 ); key = key | ( util::dilate<6>( (cart_indices[2] & 63) ) << 5 ); key = key<<2; // lowest two bits, even/odd key = key | ori_odd | cart_odd<<1; return key; } Xform get_center(Key key) const { I3 cart_indices, ori_indices; uint64_t cell_index = key >> 59; cart_indices[0] = (((key>>52)&127) << 6) | (util::undilate<6>( (key>>5) ) & 63); cart_indices[1] = (((key>>45)&127) << 6) | (util::undilate<6>( (key>>6) ) & 63); cart_indices[2] = (((key>>38)&127) << 6) | (util::undilate<6>( (key>>7) ) & 63); ori_indices[0] = util::undilate<6>( (key>>2)&(((Key)1<<36)-1) ) & 63; ori_indices[1] = util::undilate<6>( (key>>3)&(((Key)1<<36)-1) ) & 63; ori_indices[2] = util::undilate<6>( (key>>4)&(((Key)1<<36)-1) ) & 63; bool ori_odd = key & (Key)1; bool cart_odd = key & (Key)2; F3 trans = cart_grid_.get_center(cart_indices,cart_odd); F3 params = ori_grid_.get_center(ori_indices,ori_odd); Eigen::Matrix3d m; ori_map_.params_to_value( params, cell_index, 0, m ); // std::cout << "get_center " << cell_index << " " << cart_indices << " " << cart_odd << " " << ori_indices << " " << ori_odd << std::endl; Xform center( m ); center.translation()[0] = trans[0]; center.translation()[1] = trans[1]; center.translation()[2] = trans[2]; return center; } Key approx_size() const { return ori_grid_.size() * cart_grid_.size() * 24; } Key approx_nori() const { throw std::logic_error("not implemented"); } }; }}} #endif
37.45487
144
0.605292
YaoYinYing
5645417f6bc160fb11a7e02a0bfee4454aa1d402
19,920
cc
C++
src/rocksdb2/table/plain_table_reader.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
5
2019-01-23T04:36:03.000Z
2020-02-04T07:10:39.000Z
src/rocksdb2/table/plain_table_reader.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
null
null
null
src/rocksdb2/table/plain_table_reader.cc
yinchengtsinghua/RippleCPPChinese
a32a38a374547bdc5eb0fddcd657f45048aaad6a
[ "BSL-1.0" ]
2
2019-05-14T07:26:59.000Z
2020-06-15T07:25:01.000Z
//此源码被清华学神尹成大魔王专业翻译分析并修改 //尹成QQ77025077 //尹成微信18510341407 //尹成所在QQ群721929980 //尹成邮箱 yinc13@mails.tsinghua.edu.cn //尹成毕业于清华大学,微软区块链领域全球最有价值专家 //https://mvp.microsoft.com/zh-cn/PublicProfile/4033620 //版权所有(c)2011 LevelDB作者。版权所有。 //此源代码的使用受可以 //在许可证文件中找到。有关参与者的名称,请参阅作者文件。 #ifndef ROCKSDB_LITE #include "table/plain_table_reader.h" #include <string> #include <vector> #include "db/dbformat.h" #include "rocksdb/cache.h" #include "rocksdb/comparator.h" #include "rocksdb/env.h" #include "rocksdb/filter_policy.h" #include "rocksdb/options.h" #include "rocksdb/statistics.h" #include "table/block.h" #include "table/bloom_block.h" #include "table/filter_block.h" #include "table/format.h" #include "table/internal_iterator.h" #include "table/meta_blocks.h" #include "table/two_level_iterator.h" #include "table/plain_table_factory.h" #include "table/plain_table_key_coding.h" #include "table/get_context.h" #include "monitoring/histogram.h" #include "monitoring/perf_context_imp.h" #include "util/arena.h" #include "util/coding.h" #include "util/dynamic_bloom.h" #include "util/hash.h" #include "util/murmurhash.h" #include "util/stop_watch.h" #include "util/string_util.h" namespace rocksdb { namespace { //从char数组安全地获取uint32_t元素,其中,从 //‘base`,每4个字节被视为一个固定的32位整数。 inline uint32_t GetFixed32Element(const char* base, size_t offset) { return DecodeFixed32(base + offset * sizeof(uint32_t)); } } //命名空间 //迭代索引表的迭代器 class PlainTableIterator : public InternalIterator { public: explicit PlainTableIterator(PlainTableReader* table, bool use_prefix_seek); ~PlainTableIterator(); bool Valid() const override; void SeekToFirst() override; void SeekToLast() override; void Seek(const Slice& target) override; void SeekForPrev(const Slice& target) override; void Next() override; void Prev() override; Slice key() const override; Slice value() const override; Status status() const override; private: PlainTableReader* table_; PlainTableKeyDecoder decoder_; bool use_prefix_seek_; uint32_t offset_; uint32_t next_offset_; Slice key_; Slice value_; Status status_; //不允许复制 PlainTableIterator(const PlainTableIterator&) = delete; void operator=(const Iterator&) = delete; }; extern const uint64_t kPlainTableMagicNumber; PlainTableReader::PlainTableReader(const ImmutableCFOptions& ioptions, unique_ptr<RandomAccessFileReader>&& file, const EnvOptions& storage_options, const InternalKeyComparator& icomparator, EncodingType encoding_type, uint64_t file_size, const TableProperties* table_properties) : internal_comparator_(icomparator), encoding_type_(encoding_type), full_scan_mode_(false), user_key_len_(static_cast<uint32_t>(table_properties->fixed_key_len)), prefix_extractor_(ioptions.prefix_extractor), enable_bloom_(false), bloom_(6, nullptr), file_info_(std::move(file), storage_options, static_cast<uint32_t>(table_properties->data_size)), ioptions_(ioptions), file_size_(file_size), table_properties_(nullptr) {} PlainTableReader::~PlainTableReader() { } Status PlainTableReader::Open(const ImmutableCFOptions& ioptions, const EnvOptions& env_options, const InternalKeyComparator& internal_comparator, unique_ptr<RandomAccessFileReader>&& file, uint64_t file_size, unique_ptr<TableReader>* table_reader, const int bloom_bits_per_key, double hash_table_ratio, size_t index_sparseness, size_t huge_page_tlb_size, bool full_scan_mode) { if (file_size > PlainTableIndex::kMaxFileSize) { return Status::NotSupported("File is too large for PlainTableReader!"); } TableProperties* props = nullptr; auto s = ReadTableProperties(file.get(), file_size, kPlainTableMagicNumber, ioptions, &props); if (!s.ok()) { return s; } assert(hash_table_ratio >= 0.0); auto& user_props = props->user_collected_properties; auto prefix_extractor_in_file = props->prefix_extractor_name; if (!full_scan_mode && /*efix_提取器_in_file.empty()/*旧版sst文件*/ &prefix提取程序在文件中!=“null pTr”){ 如果(!)ioptions.prefix_提取器) 返回状态::invalidArgument( “打开生成的普通表时缺少前缀提取程序” “使用前缀提取程序”); else if(前缀_extractor_in_file.compare( ioptions.prefix_extractor->name())!= 0){ 返回状态::invalidArgument( “给定的前缀提取程序与用于生成的前缀提取程序不匹配” “明码表”; } } 编码类型编码类型=kplain; 自动编码\类型\属性= 用户属性查找(plainTablePropertyNames::kencodingType); 如果(编码\类型\属性!=user_props.end()) encoding_type=static_cast<encoding type> decodeFixed32(encoding_type_prop->second.c_str()); } std::unique_ptr<plaintablereader>new_reader(new plaintablereader( ioptions,std::move(file),env_选项,internal_comparator, 编码类型、文件大小、属性); s=new_reader->mmapdationFeeded(); 如果(!)S.O.()){ 返回S; } 如果(!)全扫描模式) s=new_reader->populateindex(props,bloom_bits_per_key,hash_table_ratio, 索引稀疏度,巨大的页面大小); 如果(!)S.O.()){ 返回S; } }否则{ //指示它是完全扫描模式的标志,以便没有任何索引 /可以使用。 新的读卡器->全扫描模式uu=true; } *表读卡器=标准::移动(新读卡器); 返回S; } void plainTableReader::SetupForCompaction() } InternalIterator*PlainTableReader::NewIterator(const readoptions&options, 竞技场*竞技场, bool skip_filters)_ bool use_prefix_seek=!istotalOrderMode()&&!选项。总订单搜索; 如果(竞技场==nullptr) 返回新的PlainTableIterator(这将使用前缀\u seek); }否则{ auto mem=arena->allocateAligned(sizeof(plainTableIterator)); 返回new(mem)plainTableIterator(这个,使用前缀\u seek); } } 状态PlainTableReader::PopulateIndexRecordList( plainTableIndexBuilder*索引生成器,vector<uint32_t>*前缀_hashes) 切片前一个键前缀切片; std::字符串prev_key_prefix_buf; uint32_t pos=数据\开始\偏移量\; bool isou firstou record=true; 切片键\前缀\切片; PlainTableKeyDecoder解码器(&file_info_uuu,encoding_type_u,user_key_len_uuuu,&file_info_uu,encoding_type_u,user_key_u len_uuu,&file ioptions前缀提取程序); 同时(pos<file_info_u.data_end_offset) uint32_t key_offset=pos; ParsedinInternalkey键; 切片值_slice; bool seecable=false; 状态S=下一个(&decoder,&pos,&key,nullptr,&value_slice,&seecable); 如果(!)S.O.()){ 返回S; } key_prefix_slice=getPrefix(key); 如果(启用ou bloom_ Bloom_u.AddHash(GetSliceHash(key.user_key)); }否则{ 如果(是“第一个记录”上一个键_前缀_切片!=key_prefix_slice) 如果(!)是第一个记录吗? 前缀_hashes->push_back(getsliehash(prev_key_prefix_slice)); } 如果(文件信息为“命令”模式) prev_key_prefix_slice=key_prefix_slice; }否则{ prev_key_prefix_buf=key_prefix_slice.toString(); prev_key_prefix_slice=prev_key_prefix_buf; } } } index_builder->addkeyprefix(getprefix(key),key_offset); 如果(!)可查找&&是第一条记录) 返回状态::损坏(“前缀的键不可查找”); } 第一条记录为假; } 前缀_hashes->push_back(getslicehash(key_prefix_slice)); auto s=index_.initfromrawdata(index_builder->finish()); 返回S; } void plainTableReader::allocateAndFillBloom(int bloom_bits_per_key, int num_前缀, 大小\u t超大\u页\u tlb \u大小, vector<uint32_t>*前缀_hashes) 如果(!)istotalOrderMode()) uint32_t bloom_total_bits=num_prefixes*bloom_bits_per_key; 如果(bloom_total_bits>0) 启用“Bloom”=true; 布卢姆·塞托阿尔比斯(&arena_uuu,布卢姆o total_u bits,ioptions uu.bloom u地区, 巨大的页面大小,ioptions,信息日志; FillBloom(前缀_hashes); } } } void plainTableReader::fillBloom(vector<uint32_t>>*prefix_hashes) 断言(bloom_uu.isInitialized()); for(自动前缀_hash:*前缀_hashes) bloom_u.addhash(前缀_hash); } } status plainTableReader::mmapdationFeeded() 如果(文件信息为“命令”模式) //获取mmap内存。 返回文件“信息文件”->“读取”(0,文件“大小”,文件“信息文件”,“数据,空指针”); } 返回状态::OK(); } 状态PlainTableReader::PopulateIndex(TableProperties*Props, Int Bloom_Bits_per_键, 双哈希表比率, 尺寸指数稀疏度, 尺寸特大页面TLB尺寸 断言(道具)!= null pTr); 表“属性”重置(props); 块内容索引块内容; status s=readmetablock(file_info_.file.get(),nullptr/*预取缓冲区*/, file_size_, kPlainTableMagicNumber, ioptions_, PlainTableIndexBuilder::kPlainTableIndexBlock, &index_block_contents); bool index_in_file = s.ok(); BlockContents bloom_block_contents; bool bloom_in_file = false; //如果索引块在文件中,我们只需要读取bloom块。 if (index_in_file) { /*readmetablock(file_info_.file.get(),nullptr/*预取缓冲区*/, 文件大小,kPlainTableMagicNumber,ioptions, BloomBlockBuilder::KbloomBlock,&BloomBlock_内容); bloom_in_file=s.ok()&&bloom_block_contents.data.size()>0; } 切片*花块; 如果(bloom_in_file) //如果bloom块的contents.allocation不是空的(这种情况下 //对于非mmap模式),它保存bloom块的分配内存。 //它需要保持活动才能使'bloom_block'保持有效。 bloom_block_alloc_u=std::move(bloom_block_contents.allocation); bloom_block=&bloom_block_contents.data; }否则{ bloom_block=nullptr; } 切片*索引块; if(index_in_file) //如果index_block_contents.allocation不为空(即 //对于非mmap模式),它保存索引块的分配内存。 //需要保持活动状态才能使'index_block'保持有效。 index_block_alloc_u=std::move(index_block_contents.allocation); index_block=&index_block_contents.data; }否则{ 索引块=nullptr; } if((ioptions前缀提取程序=nullptr)&& (哈希表比率!= 0){ //对于基于哈希的查找,需要ioptons.prefix_提取器。 返回状态::不支持( “PlainTable需要前缀提取程序启用前缀哈希模式。”); } //首先,读取整个文件,每个kindexintervalforameprefixkeys行 //对于前缀(从第一个开始),生成(hash, //offset)并将其附加到indexrecordlist,这是一个创建的数据结构 //存储它们。 如果(!)_文件中的索引_ //在此处为总订单模式分配Bloom筛选器。 if(istotalOrderMode()) uint32_t num_bloom_位= static_cast<uint32_t>(table_properties_u->num_entries)* 布卢姆每把钥匙都有一点; 如果(num_bloom_位>0) 启用“Bloom”=true; 布卢姆·塞托阿尔比斯(&arena_uuu,num_o Bloom_Bits,IOptions_u.Bloom_地区, 巨大的页面大小,ioptions,信息日志; } } 否则,如果(bloom_在_文件中) 启用“Bloom”=true; auto num_blocks_property=props->user_collected_properties.find( 普通表属性名称::knumbloomblocks); uint32_t num_块=0; 如果(num_块_属性!=props->user_collected_properties.end()) 切片温度切片(num_blocks_property->second); 如果(!)getvarint32(&temp_slice,&num_blocks)) NUMIX块=0; } } //取消常量限定符,因为不会更改bloom_u 布卢姆·塞特拉瓦达( const_cast<unsigned char*>() reinterpret_cast<const unsigned char*>(bloom_block->data()), static_cast<uint32_t>(bloom_block->size())*8,num_blocks); }否则{ //文件中有索引,但文件中没有bloom。在这种情况下禁用Bloom过滤器。 启用“Bloom”=false; Bloom_Bits_per_键=0; } plaintableindexbuilder index_builder(&arena_uuu,ioptions_u,index_稀疏度, hash_table_比率,巨大的_page_tlb_大小); std::vector<uint32_t>前缀_hashes; 如果(!)_文件中的索引_ s=popultiendexrecordlist(&index_builder,&prefix_hashes); 如果(!)S.O.()){ 返回S; } }否则{ s=index_.initfromrawdata(*index_block); 如果(!)S.O.()){ 返回S; } } 如果(!)_文件中的索引_ //计算的Bloom筛选器大小并为分配内存 //根据前缀数进行bloom过滤,然后填充。 allocateAndFillBloom(bloom_bits_per_key,index_.getNumPrefixes(), 巨大的_page_tlb_大小,&prefix_hashes); } //填充两个表属性。 如果(!)_文件中的索引_ props->user_collected_properties[“plain_table_hash_table_size”]= ToString(index_.getIndexSize()*PlainTableIndex::KoffsetLen); props->user_collected_properties[“plain_table_sub_index_size”]= toString(index_.getSubIndexSize()); }否则{ props->user_collected_properties[“plain_table_hash_table_size”]= ToStand(0); props->user_collected_properties[“plain_table_sub_index_size”]= ToStand(0); } 返回状态::OK(); } 状态PlainTableReader::GetOffset(PlainTableKeyDecoder*解码器, 常量切片和目标,常量切片和前缀, uint32_t prefix_hash,bool&prefix_matched, uint32_t*偏移)常量 前缀匹配=假; uint32_t前缀_index_offset; auto res=index_.getoffset(前缀_hash,&prefix_index_offset); if(res==plainTableIndex::knoprefixForBucket) *offset=文件\信息\数据\结束\偏移; 返回状态::OK(); else if(res==plaintableindex::kdirecttofile) *offset=前缀_index_offset; 返回状态::OK(); } //指向子索引,需要进行二进制搜索 uint32_t上限; 常量字符*基指针= index_u.getSubindexBaseptrandUpperbound(前缀_index_offset,&upper_bound); uint32_t低=0; uint32_t high=上限; ParsedinInternalkey Mid_键; parsedinteralkey parsed_目标; 如果(!)parseInternalKey(target,&parsed_target)) 返回状态::损坏(slice()); } //键在[低,高]之间。在两者之间进行二进制搜索。 同时(高-低>1) uint32_t mid=(高+低)/2; uint32_t file_offset=getFixed32元素(base_ptr,mid); UIT32 32 TMP; 状态S=decoder->nextkenovalue(文件偏移、&mid-key、nullptr和tmp); 如果(!)S.O.()){ 返回S; } int cmp_result=internal_comparator_u.compare(mid_key,parsed_target); if(cmp_result<0) 低=中; }否则{ 如果(cmp_result==0) //碰巧发现精确的键或目标小于 //基极偏移后的第一个键。 前缀匹配=真; *offset=文件偏移量; 返回状态::OK(); }否则{ 高=中; } } } //低位或低位的两个键+1可以相同 //前缀作为目标。我们得排除其中一个以免走 //到错误的前缀。 ParsedinInternalkey低_键; UIT32 32 TMP; uint32_t low_key_offset=getFixed32element(base_ptr,low); 状态S=解码器->NextKeyNovalue(低\u键偏移量,&low \u键,空指针,&tmp); 如果(!)S.O.()){ 返回S; } if(getPrefix(low_key)==前缀) 前缀匹配=真; *偏移量=低\键\偏移量; 否则,如果(低+1<上限) //可能有下一个前缀,返回它 前缀匹配=假; *offset=getFixed32element(基极指针,低+1); }否则{ //目标大于此bucket中最后一个前缀的键 //但前缀不同。密钥不存在。 *offset=文件\信息\数据\结束\偏移; } 返回状态::OK(); } bool plainTableReader::matchBloom(uint32_t hash)const_ 如果(!)启用“Bloom” 回归真实; } 如果(布卢姆可能含有烟灰(哈希)) 性能计数器添加(bloom-sst-hit-count,1); 回归真实; }否则{ 性能计数器添加(Bloom_sst_Miss_Count,1); 返回错误; } } 状态:PlainTableReader::Next(PlainTableKeyDecoder*解码器,uint32_t*偏移量, parsedinteralkey*已分析的_键, slice*内部\键,slice*值, bool*seecable)const_ if(*offset==file_info_u.data_end_offset) *offset=文件\信息\数据\结束\偏移; 返回状态::OK(); } 如果(*offset>file_info_u.data_end_offset) 返回状态::损坏(“偏移量超出文件大小”); } uint32字节读取; 状态S=解码器->下一个键(*偏移量,已解析的键,内部键,值, &bytes_read,可查找); 如果(!)S.O.()){ 返回S; } *offset=*offset+bytes_read; 返回状态::OK(); } void plainTableReader::准备(const slice&target) 如果(启用ou bloom_ uint32_t prefix_hash=getsliehash(getprefix(target)); 布卢姆预取(前缀_hash); } } status plaintablereader::get(const readoptions&ro,const slice&target, getContext*获取_context,bool skip_filters) //首先检查Bloom过滤器。 切片前缀\切片; uint32_t前缀_hash; if(istotalOrderMode()) 如果(全扫描模式) StutsUs= status::invalidArgument(“get()在完全扫描模式下不允许使用”); } //匹配Bloom筛选器检查的整个用户密钥。 如果(!)matchbloom(getsliehash(getuserkey(target))) 返回状态::OK(); } //在total order模式下,只有一个bucket 0,我们总是使用空的 / /前缀。 前缀_slice=slice(); 前缀_hash=0; }否则{ prefix_slice=getprefix(目标); 前缀_hash=getslicehash(前缀_slice); 如果(!)matchbloom(前缀_hash)) 返回状态::OK(); } } uint32_t偏移; bool前缀匹配; PlainTableKeyDecoder解码器(&file_info_uuu,encoding_type_u,user_key_len_uuuu,&file_info_uu,encoding_type_u,user_key_u len_uuu,&file ioptions前缀提取程序); 状态s=getoffset(&decoder,target,prefix_slice,prefix_hash, 前缀“匹配与偏移”); 如果(!)S.O.()){ 返回S; } ParsedinInternalkey找到了\u键; parsedinteralkey parsed_目标; 如果(!)parseInternalKey(target,&parsed_target)) 返回状态::损坏(slice()); } 切片找到值; while(offset<file_info_u.data_end_offset) s=下一个(&decoder,&offset,&found_key,nullptr,&found_value); 如果(!)S.O.()){ 返回S; } 如果(!)前缀匹配({) //如果尚未找到第一个键,则需要验证其前缀 /检查。 如果(getprefix(found_key)!=前缀_slice) 返回状态::OK(); } 前缀_match=true; } //todo(ljin):因为我们知道这里的关键比较结果, //我们能启用快速路径吗? if(内部_comparator_u.compare(found_key,parsed_target)>=0) 如果(!)get_context->savevalue(found_key,found_value)) 断裂; } } } 返回状态::OK(); } uint64_t plainTableReader::approceoffsetof(const slice&key) 返回0; } PlainTableIterator::PlainTableIterator(PlainTableReader*表, bool使用前缀查找) :表u(表), 解码器uux(&table)->文件u信息u,表->编码u类型uu, table_u->user_key_len_u,table_->prefix_extractor_u, 使用_前缀_seek_u(使用_前缀_seek) 下一个偏移量 } PlainTableIterator::~PlainTableIterator() } bool plainTableIterator::valid()常量 返回偏移量表->文件信息数据结束偏移量和 offset_>=table_->data_start_offset_; } void PlainTableIterator::seektofFirst() 下一个_offset_u=table_u->data_start_offset_u; if(next_offset_>=table_->file_info_u.data_end_offset) 下一个偏移量 }否则{ (下); } } void PlainTableIterator::seektolast() 断言(假); status_u=status::not supported(“seektolast()在plaintable中不受支持”); } void plainTableIterator::seek(const slice&target) 如果(使用前缀搜索)=!表_->istotalOrderMode()) //在此处执行此检查而不是newIterator(),以允许创建 //total_order_seek=true的迭代器,即使我们无法seek()。 //它。压缩时需要这样做:它使用 //totalou orderou seek=true,但通常不会对其执行seek(), //仅SeekToFirst()。 StutsUs= 状态::无效参数( “未为PlainTable实现总订单寻道。”); offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; 返回; } //如果用户没有设置前缀查找选项,并且我们无法执行 //total seek()。断言失败。 if(table_->istotalOrderMode()) if(表_->full_scan_mode_123; StutsUs= status::invalidArgument(“seek()在完全扫描模式下不允许使用”); offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; 返回; else if(table_->getIndexSize()>1) 断言(假); 状态=状态::不支持( “PlainTable不能发出非前缀查找,除非按总顺序” “模式”; offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; 返回; } } slice prefix_slice=table_uu->getprefix(目标); uint32_t prefix_hash=0; //在TOTAL ORDER模式下,Bloom过滤器被忽略。 如果(!)表_->istotalOrderMode()) 前缀_hash=getslicehash(前缀_slice); 如果(!)表_->matchbloom(前缀_hash)) offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; 返回; } } bool前缀匹配; 状态_u=table_u->getoffset(&decoder_uux,target,prefix_slice,prefix_hash, 前缀“匹配”,下一个“偏移”; 如果(!)StasuS.O.()){ offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; 返回; } if(下一个_o偏移量_<table_u->file_信息_u.data_结束_偏移量) for(next();status_.ok()&&valid();next()) 如果(!)前缀匹配({) //需要验证第一个键的前缀 如果(table_->getPrefix(key())!=前缀_slice) offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; 断裂; } 前缀_match=true; } if(table_->internal_comparator_.compare(key(),target)>=0) 断裂; } } }否则{ offset_=table_u->file_info_u.data_end_offset; } } void PlainTableIterator::seekForRev(const slice&target) 断言(假); StutsUs= 状态::NotSupported(“SeekForRev()在PlainTable中不受支持”); } void PlainTableIterator::Next() offset_u=下一个_offset_uu; if(offset<table_u->file_info_u.data_end_offset) 切片TMP_切片; parsedinteralkey parsed_键; StutsUs= 表->next(&decoder_uu,&next_offset_uu,&parsed_key,&key_uu,&value_u); 如果(!)StasuS.O.()){ offset_u=下一个_u offset_u=表u->文件u信息u.data _结束_offset; } } } void PlainTableIterator::prev() 断言(假); } Slice PlainTableIterator::key()常量 断言(valid()); 返回键; } Slice PlainTableIterator::Value()常量 断言(valid()); 返回值; } status plainTableIterator::status()常量 返回状态; } //命名空间rocksdb endif//rocksdb_lite
26.314399
129
0.642771
yinchengtsinghua
5646e0f01432b486fe168c43c2d60c41ed629dc8
178
cpp
C++
4.11.cpp
tompotter0/-
9e1ff2b035eb8769637762d3007e09bbd3fb7250
[ "MIT" ]
null
null
null
4.11.cpp
tompotter0/-
9e1ff2b035eb8769637762d3007e09bbd3fb7250
[ "MIT" ]
null
null
null
4.11.cpp
tompotter0/-
9e1ff2b035eb8769637762d3007e09bbd3fb7250
[ "MIT" ]
null
null
null
#include<iostream> int f(int x){ if (x == 1)return 1; return x*x + f(x - 1); } int main(){ int a; std::cin >> a; std::cout << f(a) << std::endl; return 0; }
12.714286
33
0.483146
tompotter0
564791367909c9a668d1623fb4a078e6d96d4f3f
64,079
cxx
C++
osprey/common/targ_info/generate/si_gen.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/common/targ_info/generate/si_gen.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/common/targ_info/generate/si_gen.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright (C) 2010 Advanced Micro Devices, Inc. All Rights Reserved. */ /* * Copyright (C) 2007 PathScale, LLC. All Rights Reserved. */ /* * Copyright 2003, 2004, 2005, 2006 PathScale, Inc. All Rights Reserved. */ /* Copyright (C) 2000, 2001 Silicon Graphics, Inc. All Rights Reserved. This program is free software; you can redistribute it and/or modify it under the terms of version 2 of the GNU General Public License as published by the Free Software Foundation. This program is distributed in the hope that it would be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. Further, this software is distributed without any warranty that it is free of the rightful claim of any third person regarding infringement or the like. Any license provided herein, whether implied or otherwise, applies only to this software file. Patent licenses, if any, provided herein do not apply to combinations of this program with other software, or any other product whatsoever. You should have received a copy of the GNU General Public License along with this program; if not, write the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston MA 02111-1307, USA. Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pky, Mountain View, CA 94043, or: http://www.sgi.com For further information regarding this notice, see: http://oss.sgi.com/projects/GenInfo/NoticeExplan */ // si_gen ///////////////////////////////////// // // Description: // // Digest the description of a particular hardware implementation's // scheduling information and generate a c file that describes the // features. The interface is extensively described in si_gen.h. // ///////////////////////////////////// // $Revision: 1.6 $ // $Date: 04/12/21 14:57:26-08:00 $ // $Author: bos@eng-25.internal.keyresearch.com $ // $Source: /home/bos/bk/kpro64-pending/common/targ_info/generate/SCCS/s.si_gen.cxx $ #include <assert.h> #include <stdio.h> #include <unistd.h> #include <limits.h> #include <stdarg.h> #include <stdlib.h> #include <string.h> #include <list> #include <map> #include <set> #include <string> #include <vector> #include "topcode.h" #include "targ_isa_properties.h" #include "targ_isa_subset.h" #include "targ_isa_operands.h" #include "gen_util.h" #include "si_gen.h" // Parameters: const int bits_per_long = 32; const int bits_per_long_long = 64; const bool use_long_longs = true; // For now always const int max_operands = ISA_OPERAND_max_operands; const int max_results = ISA_OPERAND_max_results; const int max_machine_slots = 16; static int current_machine_slot; static ISA_SUBSET machine_isa[max_machine_slots]; static std::string machine_name[max_machine_slots]; static const char * const interface[] = { "/* ====================================================================", " * ====================================================================", " *", " * Description:", " *", " * Raw processor-specific scheduling information.", " *", " * Clients should access this information through the public interface", " * defined in \"ti_si.h\". See that interface for more detailed", " * documentation.", " *", " * The following variables are exported:", " *", " * const SI_RRW SI_RRW_initializer", " * Initial value (no resources reserved) for resource reservation", " * entry.", " *", " * const SI_RRW SI_RRW_overuse_mask", " * Mask used to determine if a resource reservation entry has an", " * overuse.", " *", " * const INT SI_resource_count", " * Count of elements in SI_resources array.", " *", " * const SI_RESOURCE* const SI_resources[n]", " * Fixed-size array of SI_RESOURCE records.", " *", " * const SI SI_all[m]", " * Fixed-size array of all SI records.", " *", " * const SI_MACHINE si_machines[p]", " * Fixed-size array of SI_MACHINE records.", " *", " * int si_current_machine", " * Global index into the si_machines array, defined here for", " * convenience.", " *", " * ====================================================================", " * ====================================================================", " */", NULL }; ///////////////////////////////////// int Mod( int i, int j ) ///////////////////////////////////// // Mathematically correct integer modulus function. Unlike C's // builtin remainder function, this correctly handles the case where // one of the two arguments is negative. ///////////////////////////////////// { int rem; if ( j == 0 ) return i; rem = i % j; if ( rem == 0 ) return 0; if ( (i < 0) != (j < 0) ) return j + rem; else return rem; } ///////////////////////////////////// static void Maybe_Print_Comma(FILE* fd, bool& is_first) ///////////////////////////////////// // Print a "," to <fd> if <is_first> is false. Update <is_first> to false. // Great for printing C initializers. ///////////////////////////////////// { if ( is_first ) is_first = false; else fprintf(fd,","); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class GNAME { ///////////////////////////////////// // A generated name for a variable in the generated file. This supports a // unified method for naming and getting the names of the objects we generate. ///////////////////////////////////// public: GNAME(); // Generate a unique name. Don't care about prefix. GNAME(const char* prefix); // Generate a unique name. Force a particular prefix. GNAME(const GNAME& other); // Generate a name that is a copy of <other>. The name will not be unique. // Really only useful when <other> is about to be destructed, but we still // need to refer to it. const char* Gname() const; // Return the name. This is the name under which the object is defined. const char* Addr_Of_Gname() const; // Return a pointer to the named object. void Stub_Out(); // We've decided not to define the object after all but we may still want a // pointer to it. After this call, Addr_Of_Gname will return 0. static GNAME Stub_Gname(); // Return pre-built stub name. private: char gname[16]; // Where to keep the name. (This could be more // hi-tech, but why? bool stubbed; // Stubbed-out? static int count; // For generating the unique names. }; int GNAME::count = 0; GNAME::GNAME() : stubbed(false) { sprintf(gname,"&gname%d",count++); } GNAME::GNAME(const char* prefix) : stubbed(false) { assert(strlen(prefix) <= 8); sprintf(gname,"&%s%d",prefix,count++); } GNAME::GNAME(const GNAME& other) : stubbed(other.stubbed) { sprintf(gname,"%s",other.gname); } const char* GNAME::Gname() const { if (stubbed) return "0"; else return gname + 1; } const char* GNAME::Addr_Of_Gname() const { if (stubbed) return "0"; else return gname; } void GNAME::Stub_Out() { stubbed = true; } GNAME GNAME::Stub_Gname() { static GNAME stub_gname; stub_gname.Stub_Out(); return stub_gname; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class RES_WORD { ///////////////////////////////////// // A machine word in the resource reservation table. We use an encoding of // resources that allows very effecient checking for resources with more than // a single instance. Shifted arithmetic is used to check for resource // availability and to reserve resources. Each resource has a reserved field // in the RES_WORD. The field for a given resource r is log2(count(r)) + 1 // bits wide. This field is wide enough to hold the count of members of r and // one extra bit to the left of the count. This bit is called the "overuse // bit". The field is initialized to be 2**field_width - (count + 1). This // means that we can add count elements to the field without effecting the // overuse bit, but adding more elements to the field will set the overuse // bit. So we can can check for resource availability of all the resources // reqpresented in a word with an an add (of the counts required) and a mask // of the overuse bits. If the result is non-zero, there is a resource // overuse (conflict). // // In theory this could be any natural sized integer supported on the host // architecture, but for now we will always use long longs so we don't have to // worry about generating/checking more than one word/cycle. This could be // extended, but it would mean moving the actual resource checking to the // generated side of the compile time interface (since it would need to know // the format of the resource reservation table which could change... public: static void Find_Word_Allocate_Field(int width, int count, int &word, int &bit); // Allocate the first available resource field with <widtn> bits to hold // <count> resources. A new resource word is allocated if required. On // return, <word> and <bit> hold the word index and bit index of the // allocated word. static void Output_All(FILE* fd); // Write resource word descriptions to output. private: int bit_inx; // Index of first next free bit const int word_inx; // My index in table long long initializer; // Value when no resources used long long overuse_mask; // Bits to check // for overuse after adding new // resources static std::list<RES_WORD*> res_words; // List of all res_words in order. static int count; // Count of all resource words. static bool has_long_long_word; // Will we need to use long longs for resource words? RES_WORD() : bit_inx(0), word_inx(count++), initializer(0), overuse_mask(0) { res_words.push_back(this); } bool Allocate_Field(int width, int count, int &word, int &bit); }; std::list<RES_WORD*> RES_WORD::res_words; int RES_WORD::count = 0; bool RES_WORD::has_long_long_word = false; ///////////////////////////////////// bool RES_WORD::Allocate_Field(int width, int count, int &word, int &bit) ///////////////////////////////////// // Allocate a field <width> bits wide to hold <count> elements. Return true // to indicate success with <word> set to my word_inx and <bit> set to the // the bit index of the start of the field. ///////////////////////////////////// { int new_inx = bit_inx + width; if ( (use_long_longs && new_inx >= bits_per_long_long) || (!use_long_longs && new_inx >= bits_per_long) ) { return false; } if ( new_inx >= bits_per_long ) has_long_long_word = true; word = word_inx; bit = bit_inx; initializer |= ((1ll << (width - 1)) - (count + 1)) << bit_inx; overuse_mask |= (1ll << (width - 1)) << bit_inx; bit_inx += width; return true; } void RES_WORD::Find_Word_Allocate_Field(int width, int count, int &word, int &bit) { std::list<RES_WORD*>::iterator rwi; for ( rwi = res_words.begin(); rwi != res_words.end(); ++rwi ) { if ( (*rwi)->Allocate_Field(width,count,word,bit) ) return; } RES_WORD* new_res_word = new RES_WORD(); if ( ! new_res_word->Allocate_Field(width,count,word,bit) ) { fprintf(stderr,"### Cannot allocate field for %d resources\n",count); exit(EXIT_FAILURE); } } void RES_WORD::Output_All(FILE* fd) { if ( count == 0 ) fprintf(stderr,"ERROR: no resource words allocated.\n"); else if ( count > 1 ) { fprintf(stderr,"ERROR: cannot handle %d > 1 long long worth of " "resource info.\n", count); } else { // Important special case. We don't need a vector of resource words at all // and can just use a scalar. fprintf(fd,"const SI_RRW SI_RRW_initializer = 0x%" LL_FORMAT "x;\n", res_words.front()->initializer); fprintf(fd,"const SI_RRW SI_RRW_overuse_mask = 0x%" LL_FORMAT "x;\n", res_words.front()->overuse_mask); } } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class RES { ///////////////////////////////////// // A machine level resource. ///////////////////////////////////// public: static RES* Create(const char *name, int count); // <name> is used for documentation and debugging. <count> is the number of // elements in the class. static RES* Get(int id); // Find and return the resource with the given <id>. const char* Name() const { return name; } // Return debugging name. const char* Addr_Of_Gname() { return gname.Addr_Of_Gname(); } // Return name of pointer to this resource object (in generated code). unsigned int Count() const { return count; } // How may members? int Word() const { return word; } // Index of word in resource reservation table. (We have sort of allowed // there to be more than one, but this is probably not fully working.) int Id() const { return id; } // Unique ID of resource. Index into table of pointers to resources in the // generated file. unsigned int Shift_Count() const { return shift_count; } // Bit index of the field in the resource reservation word. static void Output_All( FILE* fd ); // Write out all the resource info to <fd>. static int Total() { return total; } // Total number of different RESs. private: const int count; // Available per cycle const char* name; // For documentation and debugging const int id; // Unique numerical identifier GNAME gname; // Generated symbolic name int word; // Which word in the table? int field_width; // How wide the field? int shift_count; // How much to shift (starting pos of the low // order bit static int total; // Total number of different RESs (not the the // total of their counts, 1 for each RES) static std::map<int,RES*> resources; // Map of all resources, ordered by their Id's RES(const char *name, int count); void Calculate_Field_Width(); void Calculate_Field_Pos(); static void Calculate_Fields(); // Calculate fields for all resources. This can only be done at the very // end becaue we may not know for sure that there are no multiple resources // until then. void Output( FILE* fd ); }; int RES::total = 0; std::map<int,RES*> RES::resources; RES::RES(const char *name, int count) // constructor maintains list of all resources. : count(count), name(name), id(total++), gname("resource") { resources[id] = this; } RES* RES::Create(const char *name, int count) { int i; for ( i = 0; i < total; ++i ) if (resources[i]->count == count && strcmp(resources[i]->name, name) == 0) return resources[i]; return new RES(name,count); } RES* RES::Get(int i) { assert(total > 0 && i >= 0 && i < total); return resources[i]; } void RES::Output_All( FILE* fd ) { int i; Calculate_Fields(); for ( i = 0; i < total; ++i ) resources[i]->Output(fd); fprintf(fd,"const int SI_resource_count = %d;\n",total); fprintf(fd,"const SI_RESOURCE * const SI_resources[%d] = {",total); bool is_first = true; for ( i = 0; i < total; ++i ) { Maybe_Print_Comma(fd,is_first); fprintf(fd,"\n %s",resources[i]->gname.Addr_Of_Gname()); } fprintf(fd,"\n};\n"); } ///////////////////////////////////// void RES::Calculate_Field_Width() ///////////////////////////////////// // Calculate the number of bits for my field and set <field_width> // accordingly. ///////////////////////////////////// { int i; assert(count > 0); for ( i = 31 ; i >= 0 ; --i ) { if ((( (int) 1) << i) & count) { field_width = i + 2; break; } } } void RES::Calculate_Field_Pos() { Calculate_Field_Width(); RES_WORD::Find_Word_Allocate_Field(field_width,count,word,shift_count); } ///////////////////////////////////// void RES::Calculate_Fields() ///////////////////////////////////// // See interface description. // Description ///////////////////////////////////// { for ( int i = 0; i < total; ++i ) resources[i]->Calculate_Field_Pos(); } ///////////////////////////////////// void RES::Output( FILE* fd ) ///////////////////////////////////// // Allocate my field in the resource reservation table. ///////////////////////////////////// { fprintf(fd,"static const SI_RESOURCE %s = {\"%s\",%d,%d,%d,%d};\n", gname.Gname(), name, id, count, word, shift_count); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class RES_REQ { ///////////////////////////////////// // A resource requirement. Represents all the resources needed to perform an // instruction. ///////////////////////////////////// public: RES_REQ(); RES_REQ(const RES_REQ& rhs); // Copy constructor. bool Add_Resource(const RES* res, int cycle); // Require an additional resource <res> at the given <cycle> relative to // my start. Return indication of success. If adding the resource would // create an overuse, don't add it and return false. void Output(FILE* fd); // Output my definition and initialization. const char* Addr_Of_Gname() const; // Return name of pointer to me (in generated code). const char* Gname() const; // Return my name (in generated code). // The RES_REQ must be Output first. bool Compute_Maybe_Output_II_RES_REQ(int ii, FILE* fd, GNAME*& res_req_gname, GNAME*& resource_id_set_gname); // When software pipelining, we want to check all the resources for a given // cycle of the schedule at once. Because the resource requirement may be // longer than the II into which we are trying to schedule it, we statically // combine the resource requirements for each II shorter than the number of // cycles in the request. This function does the combining and returns a // bool to indicate whether the resource requirement can be scheduled in the // given <ii>. If it can, the combined a definition and initialization of // resource requirement is output to <fd> under the GNAME <res_req_gname>. // A cycle indexed set of resource id's used is also output under the GNAME // <resource_id_set_gname>. int Max_Res_Cycle() const { return max_res_cycle; } // Return the cycle (relative to my start) of the latest resource I // require. (Used to know how many II relative resource requirements need // to be computed/output.) void Compute_Output_Resource_Count_Vec(FILE* fd); // Count up all the resources of each kind that I require (in all my cycles) // and output a definition and initialization. const char* Res_Count_Vec_Gname() const; // Return name of pointer to start of my resource count vector. int Res_Count_Vec_Size() const { return res_count_vec_size; } // Return length of my resource count vector. const char* Res_Id_Set_Gname() const; // Return name of pointer to start of vector of resource id sets, one per // cycle. friend bool operator < (const RES_REQ& lhs, const RES_REQ& rhs); // Comparison operator for std::map. private: ///////////////////////////////////// class CYCLE_RES { ///////////////////////////////////// // A cycle and resource (id) combined into a single object. Used as a key // into a map so we can find out how may of the given resources are required // in the given cycle. ///////////////////////////////////// public: CYCLE_RES(int cycle, const RES* res) : cycle(cycle), res_id(res->Id()) {} // Construct the <cycle,res> combination. CYCLE_RES(const CYCLE_RES& rhs) : cycle(rhs.cycle), res_id(rhs.res_id) {} // Copy constructor for use by STL map. int Cycle() const { return cycle; } // Return cycle component. RES* Res() const { return RES::Get(res_id); } // Return resource component. friend bool operator < (const CYCLE_RES& a, const CYCLE_RES& b) // Ordering for map. { return (a.cycle < b.cycle) || (a.cycle == b.cycle && a.res_id < b.res_id); } private: const short cycle; const short res_id; }; typedef std::map<CYCLE_RES,int> CYCLE_RES_COUNT_MAP; // For keeping track of the number of resources of a given type in a given // cycle. <cycle,res> => count int max_res_cycle; // Latest cycle with a resource requirement CYCLE_RES_COUNT_MAP cycle_res_count; // <cycle,res> -> count required GNAME res_count_vec_gname; // Symbolic name of my resource count vector. int res_count_vec_size; // How big it is. bool Compute_II_RES_REQ(int ii, RES_REQ& ii_res_req); static std::map<RES_REQ,GNAME> res_req_name_map; // Map of already-printed RES_REQ instances to names. typedef std::vector<unsigned long long> RES_ID_SET; struct res_id_set_cmp { bool operator () (const RES_ID_SET* lhs, const RES_ID_SET* rhs) const { if (lhs == 0 && rhs != 0) return true; else if (rhs == 0) return false; return *lhs < *rhs; // std::lexicographical_compare } }; typedef std::map<RES_ID_SET*,GNAME,res_id_set_cmp> RES_ID_SET_NAME_MAP; // Map of RES_ID_SET pointers to names. static std::vector<RES_ID_SET*> all_res_id_sets; // List of all allocated resource id sets. static RES_ID_SET_NAME_MAP res_id_set_name_map; // Map of weak RES_ID_SET references to names. RES_ID_SET* res_used_set_ptr; // Weak reference to res_used_set for this RES_REQ. typedef std::map<int,int> RES_COUNT_VEC; // Actually a map of resource ids to counts. struct res_count_vec_cmp { bool operator () (const RES_COUNT_VEC* lhs, const RES_COUNT_VEC* rhs) const { if (lhs == 0 && rhs != 0) return true; else if (rhs == 0) return false; return *lhs < *rhs; // std::map lexicographical_compare } }; typedef std::map<RES_COUNT_VEC*,GNAME,res_count_vec_cmp> RES_COUNT_NAME_MAP; static std::vector<RES_COUNT_VEC*> all_res_count_vecs; // List of all allocated resource count vectors. static RES_COUNT_NAME_MAP res_count_name_map; // Map of RES_COUNT_VEC weak references to names. RES_COUNT_VEC* res_count_vec_ptr; // Weak reference to res_count_vec for this RES_REQ. }; std::map<RES_REQ,GNAME> RES_REQ::res_req_name_map; std::vector<RES_REQ::RES_ID_SET*> RES_REQ::all_res_id_sets; RES_REQ::RES_ID_SET_NAME_MAP RES_REQ::res_id_set_name_map; std::vector<RES_REQ::RES_COUNT_VEC*> RES_REQ::all_res_count_vecs; RES_REQ::RES_COUNT_NAME_MAP RES_REQ::res_count_name_map; RES_REQ::RES_REQ() : max_res_cycle(-1) {} RES_REQ::RES_REQ(const RES_REQ& rhs) : max_res_cycle(rhs.max_res_cycle), cycle_res_count(rhs.cycle_res_count), res_count_vec_gname(rhs.res_count_vec_gname), res_count_vec_size(rhs.res_count_vec_size) {} bool RES_REQ::Add_Resource(const RES* res, int cycle) { assert(cycle >= 0); if ( cycle > max_res_cycle ) max_res_cycle = cycle; CYCLE_RES cr = CYCLE_RES(cycle,res); int count = cycle_res_count[cr]; if ( count >= res->Count() ) return false; cycle_res_count[cr] = ++count; return true; } const char* RES_REQ::Addr_Of_Gname() const { return res_req_name_map[*this].Addr_Of_Gname(); } const char* RES_REQ::Gname() const { return res_req_name_map[*this].Gname(); } const char* RES_REQ::Res_Count_Vec_Gname() const { if ( res_count_vec_size == 0 ) return "0"; return res_count_name_map[res_count_vec_ptr].Gname(); } const char* RES_REQ::Res_Id_Set_Gname() const { if ( max_res_cycle < 0 ) return "0"; return res_id_set_name_map[res_used_set_ptr].Gname(); } ///////////////////////////////////// bool RES_REQ::Compute_II_RES_REQ(int ii, RES_REQ& ii_res_req) ///////////////////////////////////// // Compute my <ii> relative resourse requirement info <ii_res_req> and return // a bool to indicate whether it is possible to issue me in a loop with <ii> // cycles. ///////////////////////////////////// { CYCLE_RES_COUNT_MAP::iterator mi; for (mi = cycle_res_count.begin(); mi != cycle_res_count.end(); ++mi) { int cycle = (*mi).first.Cycle(); RES* res = (*mi).first.Res(); int count = (*mi).second; for (int i = 0; i < count; ++i) { if ( ! ii_res_req.Add_Resource(res,Mod(cycle,ii)) ) return false; } } return true; } bool RES_REQ::Compute_Maybe_Output_II_RES_REQ(int ii, FILE* fd, GNAME*& res_req_gname, GNAME*& res_id_set_gname_ref) { RES_REQ ii_res_req; if ( ! Compute_II_RES_REQ(ii,ii_res_req) ) return false; ii_res_req.Output(fd); res_req_gname = new GNAME(res_req_name_map[ii_res_req]); if ( max_res_cycle < 0 ) res_id_set_gname_ref = new GNAME(GNAME::Stub_Gname()); else res_id_set_gname_ref = new GNAME(res_id_set_name_map[res_used_set_ptr]); return true; } void RES_REQ::Compute_Output_Resource_Count_Vec(FILE* fd) { CYCLE_RES_COUNT_MAP::iterator mi; std::map<int,int,std::less<int> > res_inx_count; // res_id => count // Sum up the number of each required for (mi = cycle_res_count.begin(); mi != cycle_res_count.end(); ++mi) { RES* res = (*mi).first.Res(); int count = (*mi).second; res_inx_count[res->Id()] += count; } res_count_vec_size = res_inx_count.size(); if ( res_count_vec_size == 0 ) return; // Avoid printing duplicate RES_REQ definitions. RES_COUNT_NAME_MAP::iterator rcmi = res_count_name_map.find(&res_inx_count); if ( rcmi == res_count_name_map.end() ) { // Allocate and save a copy of the local res_inx_count variable. RES_COUNT_VEC* res_inx_copy = new RES_COUNT_VEC(res_inx_count); all_res_count_vecs.push_back(res_inx_copy); res_count_vec_ptr = res_inx_copy; // Generate a name and add it to the map. GNAME gname; res_count_name_map[res_inx_copy] = gname; fprintf(fd,"static const SI_RESOURCE_TOTAL %s[] = {", gname.Gname()); bool is_first = true; RES_COUNT_VEC::iterator mj; for (mj = res_inx_count.begin(); mj != res_inx_count.end(); ++mj) { RES* res = RES::Get((*mj).first); // You'd think STL would allow int count = (*mj).second; // something less ugly! But no. Maybe_Print_Comma(fd,is_first); fprintf(fd,"\n {%s,%d} /* %s */", RES::Get(res->Id())->Addr_Of_Gname(),count,res->Name()); } fprintf(fd,"\n};\n"); } else res_count_vec_ptr = rcmi->first; } void RES_REQ::Output(FILE* fd) { int i; CYCLE_RES_COUNT_MAP::iterator mi; RES_ID_SET res_vec((size_t) max_res_cycle + 1,0); RES_ID_SET res_used_set((size_t) max_res_cycle + 1,0); for (mi = cycle_res_count.begin(); mi != cycle_res_count.end(); ++mi) { int cycle = (*mi).first.Cycle(); // You'd think this could be abstracted, RES* res = (*mi).first.Res(); // but I couldn't even explain the long long count = (*mi).second; // the concept to Alex S. res_vec[cycle] += count << res->Shift_Count(); res_used_set[cycle] |= 1ll << res->Id(); } // Avoid printing duplicate RES_REQ definitions. std::map<RES_REQ,GNAME>::iterator rrmi = res_req_name_map.find(*this); if ( rrmi == res_req_name_map.end() ) { // Generate a name and add it to the map. GNAME gname("res_req"); res_req_name_map[*this] = gname; fprintf(fd,"static const SI_RRW %s[%d] = {\n %d", gname.Gname(), max_res_cycle + 2, max_res_cycle + 1); for ( i = 0; i <= max_res_cycle; ++i ) fprintf(fd,",\n 0x%" LL_FORMAT "x",res_vec[i]); fprintf(fd,"\n};\n"); } if ( max_res_cycle < 0 ) return; // Avoid printing duplicate resource id sets. RES_ID_SET_NAME_MAP::iterator rsmi = res_id_set_name_map.find(&res_used_set); if ( rsmi == res_id_set_name_map.end() ) { // Allocate and save a copy of the local res_used_set variable. RES_ID_SET* res_set_copy = new RES_ID_SET(res_used_set); all_res_id_sets.push_back(res_set_copy); res_used_set_ptr = res_set_copy; // Generate a name and add it to the map. GNAME gname; res_id_set_name_map[res_set_copy] = gname; fprintf(fd,"static const SI_RESOURCE_ID_SET %s[%d] = {", gname.Gname(), max_res_cycle + 1); bool is_first = true; for ( i = 0; i <= max_res_cycle; ++i ) { Maybe_Print_Comma(fd,is_first); fprintf(fd,"\n 0x%" LL_FORMAT "x",res_used_set[i]); } fprintf(fd,"\n};\n"); } else res_used_set_ptr = rsmi->first; } bool operator < (const RES_REQ& lhs, const RES_REQ& rhs) { // Check for differing max_res_cycle values. if (lhs.max_res_cycle != rhs.max_res_cycle) return lhs.max_res_cycle < rhs.max_res_cycle; // Compute the res_vec vector as in RES_REQ::Output. std::vector<unsigned long long> res_vec_lhs((size_t) lhs.max_res_cycle + 1,0); RES_REQ::CYCLE_RES_COUNT_MAP::const_iterator mi; for (mi = lhs.cycle_res_count.begin(); mi != lhs.cycle_res_count.end(); ++mi) { int cycle = (*mi).first.Cycle(); RES* res = (*mi).first.Res(); long long count = (*mi).second; res_vec_lhs[cycle] += count << res->Shift_Count(); } std::vector<unsigned long long> res_vec_rhs((size_t) rhs.max_res_cycle + 1,0); for (mi = rhs.cycle_res_count.begin(); mi != rhs.cycle_res_count.end(); ++mi) { int cycle = (*mi).first.Cycle(); RES* res = (*mi).first.Res(); long long count = (*mi).second; res_vec_rhs[cycle] += count << res->Shift_Count(); } // Compare values in res_vec vectors. int i; for ( i = 0; i <= lhs.max_res_cycle; ++i ) if (res_vec_lhs[i] != res_vec_rhs[i]) return res_vec_lhs[i] < res_vec_rhs[i]; // The two RES_REQ instances will be identical in output. return false; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class ISLOT { ///////////////////////////////////// // An issue slot. This is for modeling the horrible beast skewed pipe and we // hope that it will be useful enough to support experimentation with related // ideas. ///////////////////////////////////// public: ISLOT(const char* name, int skew, int avail_count); // <name> is for documentation and debugging. <skew> gives a latency skew // instructions issued in me. const char* Addr_Of_Gname() { return gname.Addr_Of_Gname(); } // Return pointer to my name in generated. static void Output_Data(FILE* fd, int machine_slot); // Output all the issue slots and a vector of pointers to them all. static void Output_Members(FILE* fd, int machine_slot); // Output the count of issue slots and a pointer to the vector. private: const char* name; // User supplied for documentation & debugging const int skew; // Latency skew const int avail_count; // How many instructions can happen in it GNAME gname; // Symbolic name in generated static std::list<ISLOT*> islots[max_machine_slots]; // All the created islot lists. static int count[max_machine_slots]; // How many issue slots in each list? }; std::list<ISLOT*> ISLOT::islots[max_machine_slots]; int ISLOT::count[max_machine_slots] = { 0 }; ISLOT::ISLOT(const char* name, int skew, int avail_count) : name(name), skew(skew), avail_count(avail_count) { islots[current_machine_slot].push_back(this); ++count[current_machine_slot]; } void ISLOT::Output_Data(FILE* fd, int machine_slot) { std::list<ISLOT*>::iterator isi; for ( isi = islots[machine_slot].begin(); isi != islots[machine_slot].end(); ++isi ) { ISLOT* islot = *isi; fprintf(fd,"static const SI_ISSUE_SLOT %s = { \"%s\",%d,%d};\n", islot->gname.Gname(), islot->name, islot->skew, islot->avail_count); } if ( count[machine_slot] == 0 ) fprintf(fd, "\n" "static const SI_ISSUE_SLOT * const SI_issue_slots_%d[1] = {0};\n", machine_slot); else { fprintf(fd,"\nstatic const SI_ISSUE_SLOT * const SI_issue_slots_%d[%d] = {", machine_slot, count[machine_slot]); bool is_first = true; for ( isi = islots[machine_slot].begin(); isi != islots[machine_slot].end(); ++isi ) { ISLOT* islot = *isi; Maybe_Print_Comma(fd,is_first); fprintf(fd,"\n %s",islot->Addr_Of_Gname()); } fprintf(fd,"\n};\n"); } } void ISLOT::Output_Members(FILE* fd, int machine_slot) { fprintf(fd," %-20d /* SI_issue_slot_count */,\n",count[machine_slot]); fprintf(fd," SI_issue_slots_%-5d /* si_issue_slots */,\n",machine_slot); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class LATENCY_INFO { ///////////////////////////////////// // Describes latency information for an instruction group's operands or // results. ///////////////////////////////////// public: LATENCY_INFO(int max_elements); // <max_elements> is the maximum number either of operands or results. LATENCY_INFO(const LATENCY_INFO& rhs); // Copy constructor void Set_Any_Time(int time); // Any (all) of the operands or results have <time> as access or available // time. void Set_Time(int index, int time); // <index>'th operand or result has <time> as access or available time. void Output(FILE* fd); // Output latency vector to <fd>. const char* Gname() const; // Return name of pointer to me in generated file. // The latency vector must be output first. friend bool operator < (const LATENCY_INFO& a, const LATENCY_INFO& b); // Comparison operator for std::map. private: const int max_elements; // Maximum number of operands or results bool any_time_defined; // Overriding time defined int any_time; // And here it is std::vector<bool> times_defined; // Times for each operands defined? std::vector<int> times; // And here they are static std::map<LATENCY_INFO,GNAME> output_latencies; }; std::map<LATENCY_INFO,GNAME> LATENCY_INFO::output_latencies; LATENCY_INFO::LATENCY_INFO(int max_elements) : max_elements(max_elements), any_time_defined(false), times_defined(max_elements,false), times(max_elements) {} LATENCY_INFO::LATENCY_INFO(const LATENCY_INFO& rhs) : max_elements(rhs.max_elements), any_time_defined(rhs.any_time_defined), any_time(rhs.any_time), times_defined(rhs.times_defined), times(rhs.times) {} void LATENCY_INFO::Set_Any_Time(int time) { if ( any_time_defined ) { fprintf(stderr,"### Warning any_time redefined for latency. " "Was %d. Is %d\n", any_time, time); } any_time_defined = true; any_time = time; } void LATENCY_INFO::Set_Time(int index, int time) { if ( any_time_defined ) { fprintf(stderr,"### WARNING: latency setting specific time after any time. " "Any %d. Specific %d\n", any_time, time); } assert(index < max_elements); if ( times_defined[index] ) { fprintf(stderr,"### WARNING: Resetting latency time. " "Was %d. Now is %d\n", time, times[index]); } times_defined[index] = true; times[index] = time; } void LATENCY_INFO::Output(FILE* fd) { // Avoid output of duplicate latencies. std::map<LATENCY_INFO,GNAME>::iterator lmi = output_latencies.find(*this); if ( lmi != output_latencies.end() ) return; // Generate a name and add it to the map. GNAME gname("latency"); output_latencies[*this] = gname; fprintf(fd,"static const mUINT8 %s[%lu] = {",gname.Gname(),times.size()); bool is_first = true; std::vector<int>::iterator i; for ( i = times.begin(); i < times.end(); ++i ) { Maybe_Print_Comma(fd,is_first); fprintf(fd,"%d",any_time_defined ? any_time : *i); } fprintf(fd,"};\n"); } const char* LATENCY_INFO::Gname() const { return output_latencies[*this].Gname(); } bool operator < (const LATENCY_INFO& a, const LATENCY_INFO& b) { if ( a.times.size() != b.times.size() ) return a.times.size() < b.times.size(); for (int i = 0; i < a.times.size(); ++i) { int t_a = a.any_time_defined ? a.any_time : a.times[i]; int t_b = b.any_time_defined ? b.any_time : b.times[i]; if ( t_a != t_b ) return t_a < t_b; } // The two latencies will be identical in output. return false; } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class INSTRUCTION_GROUP { ///////////////////////////////////// // Represents one of the instruction groups, a common piece of scheduling // information for a set of instructions. ///////////////////////////////////// public: // These functions correspond exactly with the defined C client interface. INSTRUCTION_GROUP(const char* name); void Set_Any_Operand_Access_Time(int time); void Set_Operand_Access_Time(int operand_index, int time); void Set_Any_Result_Available_Time(int time); void Set_Result_Available_Time(int result_index, int time); void Set_Load_Access_Time( int time ); void Set_Last_Issue_Cycle( int time ); void Set_Store_Available_Time( int time ); void Add_Resource_Requirement(const RES* res, int cycle); void Add_Alternative_Resource_Requirement(const RES* res, int cycle); void Add_Valid_ISLOT(ISLOT* islot); void Set_Write_Write_Interlock(); static void Output_All(FILE* fd); // Write them all out static void Output_Data(FILE* fd, int machine_slot); // Write out per-machine list of pointers. static void Output_Members(FILE* fd, int machine_slot); // Write out count and pointer to data. unsigned int Id(); // Unique id (available only after call to Output_All). static unsigned int Count(); // Number of unique SI records (available only after call to Output_All). private: int id; // Index in vector of same const char* name; // User supplied name for documentation RES_REQ res_requirement; // Required to issue RES_REQ alternative_res_requirement; // Alternative resource if // res_requirement cannot be satisified std::list<ISLOT*> valid_islots; // If there are any issue slots at all GNAME islot_vec_gname; // Variable name of above in generated LATENCY_INFO operand_latency_info; // When operands latch LATENCY_INFO result_latency_info; // When results available int load_access_time; // When loads access memory int last_issue_cycle; // Last issue cycle in simulated insts int store_available_time; // When stores make value available in // memory bool write_write_interlock; // For simulator GNAME ii_res_req_gname; // Generated name of vector of resource requirements for each II less than // the total number of cycles in res_requirement (one based). GNAME ii_res_id_set_gname; // Generate name of vector of resource id sets for each II less than // the total number of cycles in res_requirement (one based). unsigned long long bad_iis[2]; // Tells whether it is possible to schedule at all at a given II. This // could be a more flexible data structure. As it is, it is limited to 128 // bad IIs, but I think this will be enough. static std::list<INSTRUCTION_GROUP*> instruction_groups; // All the defined instruction groups (may have duplicates). static std::list<INSTRUCTION_GROUP*> by_machine_instruction_groups[max_machine_slots]; // List of instruction groups for each machine. static int by_machine_count[max_machine_slots]; // Count of instruction groups for each machine. int II_Info_Size() const { return res_requirement.Max_Res_Cycle(); } // Latest cycle in which I need a resource void Output_II_Info(FILE* fd); void Output_Latency_Info(FILE* fd); void Output_Issue_Slot_Info(FILE* fd); void Output_Members(FILE* fd); void Output(FILE* fd) const; struct instruction_group_cmp { bool operator () (const INSTRUCTION_GROUP* lhs, const INSTRUCTION_GROUP* rhs) const { if (lhs == NULL && rhs != NULL) return true; else if (rhs == NULL) return false; // Compare fields as in Output member function. #ifdef Is_True_On // name if (lhs->name == NULL && rhs->name != NULL) return true; else if (rhs->name == NULL) return false; if (strcmp(lhs->name, rhs->name) != 0) return strcmp(lhs->name, rhs->name) < 0; #endif // operand_latency_info if (strcmp(lhs->operand_latency_info.Gname(), rhs->operand_latency_info.Gname()) != 0) return strcmp(lhs->operand_latency_info.Gname(), rhs->operand_latency_info.Gname()) < 0; // result_latency_info if (strcmp(lhs->result_latency_info.Gname(), rhs->result_latency_info.Gname()) != 0) return strcmp(lhs->result_latency_info.Gname(), rhs->result_latency_info.Gname()) < 0; // load_access_time if (lhs->load_access_time != rhs->load_access_time) return lhs->load_access_time < rhs->load_access_time; // last_issue_cycle if (lhs->last_issue_cycle != rhs->last_issue_cycle) return lhs->last_issue_cycle < rhs->last_issue_cycle; // store_available_time if (lhs->store_available_time != rhs->store_available_time) return lhs->store_available_time < rhs->store_available_time; // res_requirement if (strcmp(lhs->res_requirement.Gname(), rhs->res_requirement.Gname()) != 0) return strcmp(lhs->res_requirement.Gname(), rhs->res_requirement.Gname()) < 0; // alternative_res_requirement if (strcmp(lhs->alternative_res_requirement.Gname(), rhs->alternative_res_requirement.Gname()) != 0) return strcmp(lhs->alternative_res_requirement.Gname(), rhs->alternative_res_requirement.Gname()) < 0; // Res_Id_Set_Gname, II_Info_Size: redundant (res_requirement) // ii_res_req_gname if (strcmp(lhs->ii_res_req_gname.Gname(), rhs->ii_res_req_gname.Gname()) != 0) return strcmp(lhs->ii_res_req_gname.Gname(), rhs->ii_res_req_gname.Gname()) < 0; // ii_res_id_set_gname if (strcmp(lhs->ii_res_id_set_gname.Gname(), rhs->ii_res_id_set_gname.Gname()) != 0) return strcmp(lhs->ii_res_id_set_gname.Gname(), rhs->ii_res_id_set_gname.Gname()) < 0; // bad_iis int i; for (i = 0; i < sizeof(lhs->bad_iis) / sizeof(lhs->bad_iis[0]); ++i) if (lhs->bad_iis[i] != rhs->bad_iis[i]) return lhs->bad_iis[i] < rhs->bad_iis[i]; // valid_islots if (lhs->valid_islots.size() != rhs->valid_islots.size()) return lhs->valid_islots.size() < rhs->valid_islots.size(); // islot_vec_gname if (strcmp(lhs->islot_vec_gname.Gname(), rhs->islot_vec_gname.Gname()) != 0) return strcmp(lhs->islot_vec_gname.Gname(), rhs->islot_vec_gname.Gname()) < 0; // Res_Count_Vec_Size, Res_Count_Vec_Gname: redundant (res_requirment) // write_write_interlock if (lhs->write_write_interlock != rhs->write_write_interlock) return lhs->write_write_interlock < rhs->write_write_interlock; return false; } }; typedef std::set<INSTRUCTION_GROUP*,instruction_group_cmp> INSTRUCTION_GROUP_SET; static INSTRUCTION_GROUP_SET instruction_group_set; // Set of all unique instruction group objects. }; std::list<INSTRUCTION_GROUP*> INSTRUCTION_GROUP::instruction_groups; std::list<INSTRUCTION_GROUP*> INSTRUCTION_GROUP::by_machine_instruction_groups[max_machine_slots]; INSTRUCTION_GROUP::INSTRUCTION_GROUP_SET INSTRUCTION_GROUP::instruction_group_set; INSTRUCTION_GROUP::INSTRUCTION_GROUP(const char* name) : name(name), operand_latency_info(max_operands), result_latency_info(max_results), load_access_time(0), last_issue_cycle(0), store_available_time(0), write_write_interlock(false), ii_res_req_gname("ii_rr") { bad_iis[0] = 0; bad_iis[1] = 0; instruction_groups.push_back(this); by_machine_instruction_groups[current_machine_slot].push_back(this); } void INSTRUCTION_GROUP::Set_Any_Operand_Access_Time(int time) { operand_latency_info.Set_Any_Time(time); } void INSTRUCTION_GROUP::Set_Operand_Access_Time(int operand_index, int time) { operand_latency_info.Set_Time(operand_index,time); } void INSTRUCTION_GROUP::Set_Any_Result_Available_Time(int time) { result_latency_info.Set_Any_Time(time); } void INSTRUCTION_GROUP::Set_Result_Available_Time(int result_index, int time) { result_latency_info.Set_Time(result_index,time); } void INSTRUCTION_GROUP::Set_Load_Access_Time( int time ) { load_access_time = time; } void INSTRUCTION_GROUP::Set_Last_Issue_Cycle( int time ) { last_issue_cycle = time; } void INSTRUCTION_GROUP::Set_Store_Available_Time( int time ) { store_available_time = time; } void INSTRUCTION_GROUP::Add_Resource_Requirement(const RES* res, int cycle) { if (! res_requirement.Add_Resource(res,cycle)) { fprintf(stderr,"### ERROR: Impossible resource request for " "instruction group %s.\n", name); fprintf(stderr,"### %s at cycle %d.\n",res->Name(),cycle); } } void INSTRUCTION_GROUP::Add_Alternative_Resource_Requirement(const RES* res, int cycle) { if (! alternative_res_requirement.Add_Resource(res,cycle)) { fprintf(stderr,"### ERROR: Impossible resource request for " "instruction group %s.\n", name); fprintf(stderr,"### %s at cycle %d.\n",res->Name(),cycle); } } void INSTRUCTION_GROUP::Add_Valid_ISLOT(ISLOT* islot) { valid_islots.push_back(islot); } void INSTRUCTION_GROUP::Set_Write_Write_Interlock() { write_write_interlock = true; } void INSTRUCTION_GROUP::Output_II_Info(FILE* fd) { int i; bool is_first; const int ii_vec_size = II_Info_Size(); const int max_num_bad_iis = sizeof(bad_iis) * 8; // We need ii relative information for ii's in the range // 1..cycle_with_final_res_requirement. An ii of 0 makes no sense and an II // enough cycles that the request doesn't need to wrap are the outside bounds. if ( ii_vec_size <= 0 ) { ii_res_req_gname.Stub_Out(); ii_res_id_set_gname.Stub_Out(); return; } std::vector<GNAME*> ii_res_req_gname_vector(ii_vec_size); std::vector<GNAME*> ii_resources_used_gname_vector(ii_vec_size); std::vector<bool> ii_can_do_vector(ii_vec_size); int greatest_bad_ii = 0; for ( i = 0; i < res_requirement.Max_Res_Cycle(); ++i ) { if ( res_requirement.Compute_Maybe_Output_II_RES_REQ( i+1,fd, ii_res_req_gname_vector[i], ii_resources_used_gname_vector[i]) ) { ii_can_do_vector[i] = true; } else { ii_can_do_vector[i] = false; greatest_bad_ii = i; if ( i > max_num_bad_iis ) { fprintf(stderr,"### Error: bad II %d > %d. " "Need a more flexible representation.\n", i, max_num_bad_iis); } } } unsigned int j; for ( j = 0; j < sizeof(bad_iis) / sizeof(bad_iis[0]); ++j ) { bad_iis[j] = 0ULL; } for ( i = 0; i <= greatest_bad_ii; ++i ) { if ( ! ii_can_do_vector[i] ) { bad_iis[i / bits_per_long_long] |= (1ULL << (i % bits_per_long_long)); } } // Print vector of pointers to the II relative resource requirements fprintf(fd,"static const SI_RR %s[] = {", ii_res_req_gname.Gname()); is_first = true; for ( i = 0; i < ii_vec_size; ++i ) { Maybe_Print_Comma(fd,is_first); if ( ii_can_do_vector[i] ) fprintf(fd,"\n %s",ii_res_req_gname_vector[i]->Gname()); else fprintf(fd,"\n 0"); } fprintf(fd,"\n};\n"); // Print vector of pointers to the II relative resoruce id sets fprintf(fd,"static const SI_RESOURCE_ID_SET * const %s[] = {", ii_res_id_set_gname.Gname()); is_first = true; for ( i = 0; i < ii_vec_size; ++i ) { Maybe_Print_Comma(fd,is_first); if ( ii_can_do_vector[i] ) { fprintf(fd,"\n %s", ii_resources_used_gname_vector[i]->Gname()); } else fprintf(fd,"\n 0"); } fprintf(fd,"\n};\n"); } void INSTRUCTION_GROUP::Output_Latency_Info(FILE* fd) { operand_latency_info.Output(fd); result_latency_info.Output(fd); } void INSTRUCTION_GROUP::Output_Issue_Slot_Info(FILE* fd) { if ( valid_islots.size() == 0 ) { /* Comment out the warning until the beast skewed support is implemented; * it's currently a post 7.2 affair. * * if ( ISLOT::Count() > 0 ) * fprintf(stderr,"### Issue slots defined but none defined for %s\n",name); */ islot_vec_gname.Stub_Out(); return; } fprintf(fd,"static SI_ISSUE_SLOT * const %s[] = {",islot_vec_gname.Gname()); bool is_first = true; std::list<ISLOT*>::iterator i; for (i = valid_islots.begin(); i != valid_islots.end(); ++i) { ISLOT* islot = *i; Maybe_Print_Comma(fd,is_first); fprintf(fd,"\n %s",islot->Addr_Of_Gname()); } fprintf(fd,"\n};\n"); } void INSTRUCTION_GROUP::Output_Members(FILE* fd) { unsigned int i; res_requirement.Output(fd); res_requirement.Compute_Output_Resource_Count_Vec(fd); alternative_res_requirement.Output(fd); alternative_res_requirement.Compute_Output_Resource_Count_Vec(fd); Output_II_Info(fd); Output_Latency_Info(fd); Output_Issue_Slot_Info(fd); // Keep track of duplicate instruction group data. INSTRUCTION_GROUP_SET::iterator mi = instruction_group_set.find(this); if (mi == instruction_group_set.end()) { instruction_group_set.insert(this); } } void INSTRUCTION_GROUP::Output(FILE* fd) const { unsigned int i; assert(id != 0); fprintf(fd," { /* SI id %u */\n",id); #ifdef Is_True_On fprintf(fd," \"%s\",\n",name); #endif fprintf(fd," %-15s, /* operand latency */\n", operand_latency_info.Gname()); fprintf(fd," %-15s, /* result latency */\n", result_latency_info.Gname()); fprintf(fd," %-15d, /* load access time */\n", load_access_time); fprintf(fd," %-15d, /* last issue cycle */\n", last_issue_cycle); fprintf(fd," %-15d, /* store available time */\n", store_available_time); fprintf(fd," %-15s, /* resource requirement */\n", res_requirement.Gname()); fprintf(fd," %-15s, /* alternative resource requirement */\n", alternative_res_requirement.Gname()); fprintf(fd," %-15s, /* res id used set vec */\n", res_requirement.Res_Id_Set_Gname()); fprintf(fd," %-15d, /* II info size */\n", II_Info_Size() >= 0 ? II_Info_Size() : 0); fprintf(fd," %-15s, /* II resource requirement vec */\n", ii_res_req_gname.Gname()); fprintf(fd," %-15s, /* II res id used set vec */\n", ii_res_id_set_gname.Gname()); fprintf(fd," {{"); for ( i = 0; i < sizeof(bad_iis) / sizeof(bad_iis[0]); ++i ) { fprintf(fd, "0x%" LL_FORMAT "x", bad_iis[i]); if ( i < sizeof(bad_iis) / sizeof(bad_iis[0]) - 1 ) fprintf(fd, ","); } fprintf(fd, "}} , /* bad IIs */\n"); fprintf(fd," %-15d, /* valid issue slots vec size */\n", (unsigned int) valid_islots.size()); fprintf(fd," %-15s, /* valid issue slots vec */\n", islot_vec_gname.Gname()); fprintf(fd," %-15d, /* resource count vec size */\n", res_requirement.Res_Count_Vec_Size()); fprintf(fd," %-15s, /* resource count vec */\n", res_requirement.Res_Count_Vec_Gname()); fprintf(fd," %-15s /* write-write interlock */\n", write_write_interlock ? "1" : "0"); fprintf(fd," }"); } void INSTRUCTION_GROUP::Output_All(FILE* fd) { std::list<INSTRUCTION_GROUP*>::iterator iig; INSTRUCTION_GROUP_SET::iterator mi; unsigned int i; for (iig = instruction_groups.begin(); iig != instruction_groups.end(); ++iig ) { (*iig)->Output_Members(fd); } i = 1; fprintf(fd,"\nconst SI SI_all[%lu] = {\n", instruction_group_set.size()); for (mi = instruction_group_set.begin(); mi != instruction_group_set.end(); ++mi ) { if (i > 1) fprintf(fd,",\n"); (*mi)->id = i; (*mi)->Output(fd); i++; } fprintf(fd,"\n};\n"); } void INSTRUCTION_GROUP::Output_Data(FILE* fd, int machine_slot) { std::list<INSTRUCTION_GROUP*>::iterator iig; fprintf(fd,"\nstatic const int SI_ID_si_%d[%lu] = {",machine_slot, by_machine_instruction_groups[machine_slot].size()); bool is_first = true; for (iig = by_machine_instruction_groups[machine_slot].begin(); iig != by_machine_instruction_groups[machine_slot].end(); ++iig ) { Maybe_Print_Comma(fd,is_first); fprintf(fd,"\n %u",(*iig)->Id()); } fprintf(fd,"\n};\n"); fprintf(fd,"\n"); // One extra new line to separate from what follows. } void INSTRUCTION_GROUP::Output_Members(FILE* fd, int machine_slot) { fprintf(fd," %-20lu /* SI_ID_count */,\n", by_machine_instruction_groups[machine_slot].size()); fprintf(fd," SI_ID_si_%-11d /* SI_ID_si */,\n",machine_slot); } unsigned int INSTRUCTION_GROUP::Id() { // Use the id from the representative instruction group object. INSTRUCTION_GROUP_SET::iterator mi = instruction_group_set.find(this); assert(mi != instruction_group_set.end()); return (*mi)->id; } unsigned int INSTRUCTION_GROUP::Count() { return instruction_group_set.size(); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// ///////////////////////////////////// class TOP_SCHED_INFO_MAP { ///////////////////////////////////// // Keeps track of which TOPs need are in which INSTRUCTION_GROUPs (and thus // map to which TOP_SCHED_INFOs. ///////////////////////////////////// public: static void Add_Entry( TOP top, INSTRUCTION_GROUP* ig ); // Add entry to the map. <top> uses <ig>'s scheduling information. static void Output_Data( FILE* fd , int machine_slot ); // Write out the map. static void Output_Members( FILE* fd, int machine_slot ); // Write out a pointer to the map. static void Create_Dummies( void ); // Create scheduling info for the "dummy" instructions. private: static std::vector<INSTRUCTION_GROUP*> top_sched_info_ptr_map[max_machine_slots]; // Map to instruction group instances. static std::vector<bool> top_sched_info_defined[max_machine_slots]; // Which elements defined static INSTRUCTION_GROUP* machine_dummies[max_machine_slots]; // Pointer to dummy instruction used to fill unused slots }; std::vector<INSTRUCTION_GROUP*> TOP_SCHED_INFO_MAP::top_sched_info_ptr_map[max_machine_slots]; std::vector<bool> TOP_SCHED_INFO_MAP::top_sched_info_defined[max_machine_slots]; INSTRUCTION_GROUP* TOP_SCHED_INFO_MAP::machine_dummies[max_machine_slots]; void TOP_SCHED_INFO_MAP::Create_Dummies( void ) { INSTRUCTION_GROUP *dummies = NULL; top_sched_info_ptr_map[current_machine_slot].resize(TOP_count,NULL); top_sched_info_defined[current_machine_slot].resize(TOP_count,false); for ( int i = 0; i < TOP_count; ++i ) { if ( TOP_is_dummy((TOP)i) ) { if ( !dummies ) { dummies = new INSTRUCTION_GROUP("Dummy instructions"); dummies->Set_Any_Operand_Access_Time(0); dummies->Set_Any_Result_Available_Time(0); } top_sched_info_ptr_map[current_machine_slot][i] = dummies; } } machine_dummies[current_machine_slot] = dummies; } void TOP_SCHED_INFO_MAP::Add_Entry( TOP top, INSTRUCTION_GROUP* ig ) { if ( top_sched_info_defined[current_machine_slot][(int) top] ) { fprintf(stderr,"### Warning: scheduling information for %s redefined.\n", TOP_Name(top)); } top_sched_info_ptr_map[current_machine_slot][(int) top] = ig; top_sched_info_defined[current_machine_slot][(int) top] = true; } void TOP_SCHED_INFO_MAP::Output_Data( FILE* fd, int machine_slot ) { int i; fprintf(fd,"static const int SI_top_si_%d[%d] = {",machine_slot,TOP_count); bool err = false; bool is_first = true; for ( i = 0; i < TOP_count; ++i ) { bool isa_member = ISA_SUBSET_Member(machine_isa[machine_slot], (TOP)i); bool is_dummy = TOP_is_dummy((TOP)i); if ( top_sched_info_defined[machine_slot][i] ) { if ( ! isa_member ) { fprintf(stderr, "### Warning: scheduling info for non-%s ISA opcode %s (%s)\n", ISA_SUBSET_Name(machine_isa[machine_slot]), TOP_Name((TOP)i), machine_name[machine_slot].c_str()); } else if ( is_dummy ) { fprintf(stderr, "### Warning: scheduling info for dummy opcode %s (%s)\n", TOP_Name((TOP)i), machine_name[machine_slot].c_str()); } } else { if ( isa_member && ! is_dummy ) { fprintf(stderr, "### Error: no scheduling info for opcode %s for machine %s\n", TOP_Name((TOP)i), machine_name[machine_slot].c_str()); err = true; } } // If we have seen a fatal error, skip printing the entry to avoid a crash. if ( ! err ) { Maybe_Print_Comma(fd,is_first); if ( ! isa_member ) fprintf(fd,"\n %-4u /* %s (dummy, not in ISA subset %s) */", machine_dummies[machine_slot]->Id(),TOP_Name((TOP)i), ISA_SUBSET_Name(machine_isa[machine_slot])); else fprintf(fd,"\n %-4u /* %s */", top_sched_info_ptr_map[machine_slot][i]->Id(),TOP_Name((TOP)i)); } } fprintf(fd,"\n};\n"); if (err) exit(EXIT_FAILURE); } void TOP_SCHED_INFO_MAP::Output_Members( FILE* fd, int machine_slot ) { fprintf(fd," SI_top_si_%-10d /* SI_top_si */\n",machine_slot); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// // The client interface functions static INSTRUCTION_GROUP* current_instruction_group; void Targ_SI( void ) { current_machine_slot = 0; } void Machine( const char* name, ISA_SUBSET isa ) { machine_name[current_machine_slot] = name; machine_isa[current_machine_slot] = isa; TOP_SCHED_INFO_MAP::Create_Dummies(); } RESOURCE RESOURCE_Create(const char* name, int count) { return RES::Create(name,count); } ISSUE_SLOT ISSUE_SLOT_Create(const char* name, int skew, int count) { return new ISLOT(name,skew,count); } void Instruction_Group(const char* name,...) { va_list ap; TOP opcode; current_instruction_group = new INSTRUCTION_GROUP(name); va_start(ap,name); while ( (opcode = static_cast<TOP>(va_arg(ap,int))) != TOP_UNDEFINED ) TOP_SCHED_INFO_MAP::Add_Entry(opcode,current_instruction_group); va_end(ap); } void Any_Operand_Access_Time( int time ) { current_instruction_group->Set_Any_Operand_Access_Time(time); } void Operand_Access_Time( int operand_index, int time ) { current_instruction_group->Set_Operand_Access_Time(operand_index,time); } void Any_Result_Available_Time( int time ) { current_instruction_group->Set_Any_Result_Available_Time(time); } void Result_Available_Time( int result_index, int time ) { current_instruction_group->Set_Result_Available_Time(result_index,time); } void Load_Access_Time( int time ) { current_instruction_group->Set_Load_Access_Time(time); } void Last_Issue_Cycle( int time ) { current_instruction_group->Set_Last_Issue_Cycle(time); } void Store_Available_Time( int time ) { current_instruction_group->Set_Store_Available_Time(time); } void Resource_Requirement( RESOURCE resource, int time ) { current_instruction_group->Add_Resource_Requirement(resource,time); } void Alternative_Resource_Requirement( RESOURCE resource, int time ) { current_instruction_group->Add_Alternative_Resource_Requirement(resource,time); } void Valid_Issue_Slot( ISSUE_SLOT slot ) { current_instruction_group->Add_Valid_ISLOT(slot); } void Write_Write_Interlock( void ) { current_instruction_group->Set_Write_Write_Interlock(); } void Machine_Done( void ) { current_machine_slot++; if (current_machine_slot == max_machine_slots) { fprintf(stderr,"### Error: max_machine_slots is %d\n",max_machine_slots); exit(EXIT_FAILURE); } } void Targ_SI_Done( const char* basename ) { std::string h_filename(basename); std::string c_filename(basename); h_filename.append(".h"); c_filename.append(".c"); FILE* hfile = fopen(h_filename.c_str(),"w"); FILE* cfile = fopen(c_filename.c_str(),"w"); if ( hfile == NULL ) { fprintf(stderr,"### Error: couldn't write %s\n",h_filename.c_str()); return; } if ( cfile == NULL ) { fprintf(stderr,"### Error: couldn't write %s\n",c_filename.c_str()); return; } Emit_Header(hfile, basename, interface); fprintf(hfile,"#include \"ti_si_types.h\"\n"); fprintf(cfile,"#include \"%s\"\n", h_filename.c_str()); bool is_first = true; int i; // output global data RES::Output_All(cfile); RES_WORD::Output_All(cfile); INSTRUCTION_GROUP::Output_All(cfile); // output per-machine data for (i = 0; i < current_machine_slot; ++i) { ISLOT::Output_Data(cfile, i); INSTRUCTION_GROUP::Output_Data(cfile, i); TOP_SCHED_INFO_MAP::Output_Data(cfile, i); } fprintf(hfile,"\nextern const SI_RRW SI_RRW_initializer;\n"); fprintf(hfile,"extern const SI_RRW SI_RRW_overuse_mask;\n"); fprintf(hfile,"\nextern const INT SI_resource_count;\n"); fprintf(hfile,"extern const SI_RESOURCE* const SI_resources[%d];\n", RES::Total()); fprintf(hfile,"\nextern const SI SI_all[%u];\n",INSTRUCTION_GROUP::Count()); fprintf(hfile,"\nextern const SI_MACHINE si_machines[%d];\n", current_machine_slot); fprintf(cfile,"\nconst SI_MACHINE si_machines[%d] = {",current_machine_slot); // output SI_MACHINE members for (i = 0; i < current_machine_slot; ++i) { std::string quoted_name("\""); quoted_name.append(machine_name[i]); quoted_name.append("\""); Maybe_Print_Comma(cfile, is_first); fprintf(cfile,"\n {\n"); fprintf(cfile," %-20s /* name */,\n", quoted_name.c_str()); ISLOT::Output_Members(cfile, i); INSTRUCTION_GROUP::Output_Members(cfile, i); TOP_SCHED_INFO_MAP::Output_Members(cfile, i); fprintf(cfile," }"); } fprintf(cfile,"\n};\n"); fprintf(hfile,"\nextern int si_current_machine;\n"); fprintf(cfile,"\nint si_current_machine; /* index into si_machines */\n"); Emit_Footer(hfile); fclose(hfile); fclose(cfile); }
30.881446
87
0.624932
sharugupta
564943190f12d12653b4f3dc33482834e54ace2e
24,450
cpp
C++
6502/tests.cpp
mavroskardia/6502
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
[ "MIT" ]
1
2016-02-27T19:23:13.000Z
2016-02-27T19:23:13.000Z
6502/tests.cpp
mavroskardia/6502
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
[ "MIT" ]
null
null
null
6502/tests.cpp
mavroskardia/6502
bc7a278ecc8b9f18e845240b014c6513df5e9e9e
[ "MIT" ]
null
null
null
#include "includes.h" string make_string(vector<unsigned char>&); // there are 150 opcode variations to implement, // some opcodes have implied, absolute, indirect, // immediate, and relative modes that I put into // different namespaces // 25 total implied opcodes - DONE namespace impl { void test_brk(Instruction&, CPU&, Memory&); void test_rti(Instruction&, CPU&, Memory&); void test_rts(Instruction&, CPU&, Memory&); void test_php(Instruction&, CPU&, Memory&); void test_clc(Instruction&, CPU&, Memory&); void test_plp(Instruction&, CPU&, Memory&); void test_sec(Instruction&, CPU&, Memory&); void test_pha(Instruction&, CPU&, Memory&); void test_cli(Instruction&, CPU&, Memory&); void test_pla(Instruction&, CPU&, Memory&); void test_sei(Instruction&, CPU&, Memory&); void test_dey(Instruction&, CPU&, Memory&); void test_tya(Instruction&, CPU&, Memory&); void test_tay(Instruction&, CPU&, Memory&); void test_clv(Instruction&, CPU&, Memory&); void test_iny(Instruction&, CPU&, Memory&); void test_cld(Instruction&, CPU&, Memory&); void test_inx(Instruction&, CPU&, Memory&); void test_sed(Instruction&, CPU&, Memory&); void test_txa(Instruction&, CPU&, Memory&); void test_txs(Instruction&, CPU&, Memory&); void test_tax(Instruction&, CPU&, Memory&); void test_tsx(Instruction&, CPU&, Memory&); void test_dex(Instruction&, CPU&, Memory&); void test_nop(Instruction&, CPU&, Memory&); } // 8 total relative opcodes - DONE namespace rel { void test_bpl(Instruction&, CPU&, Memory&); void test_bmi(Instruction&, CPU&, Memory&); void test_bvc(Instruction&, CPU&, Memory&); void test_bvs(Instruction&, CPU&, Memory&); void test_bcc(Instruction&, CPU&, Memory&); void test_bcs(Instruction&, CPU&, Memory&); void test_bne(Instruction&, CPU&, Memory&); void test_beq(Instruction&, CPU&, Memory&); } // 23 total absolute opcodes - WIP namespace abso { // 00 LO (1) void test_jsr(Instruction&, CPU&, Memory&); // 0C LO (6) void test_bit(Instruction&, CPU&, Memory&); void test_jmp(Instruction&, CPU&, Memory&); void test_sty(Instruction&, CPU&, Memory&); void test_ldy(Instruction&, CPU&, Memory&); void test_cpy(Instruction&, CPU&, Memory&); void test_cpx(Instruction&, CPU&, Memory&); // 0D LO (8) void test_ora(Instruction&, CPU&, Memory&); void test_and(Instruction&, CPU&, Memory&); void test_eor(Instruction&, CPU&, Memory&); void test_adc(Instruction&, CPU&, Memory&); void test_sta(Instruction&, CPU&, Memory&); void test_lda(Instruction&, CPU&, Memory&); void test_cmp(Instruction&, CPU&, Memory&); void test_sbc(Instruction&, CPU&, Memory&); // OE LO (8) void test_asl(Instruction&, CPU&, Memory&); void test_rol(Instruction&, CPU&, Memory&); void test_lsr(Instruction&, CPU&, Memory&); void test_ror(Instruction&, CPU&, Memory&); void test_stx(Instruction&, CPU&, Memory&); void test_ldx(Instruction&, CPU&, Memory&); void test_dec(Instruction&, CPU&, Memory&); void test_inc(Instruction&, CPU&, Memory&); } namespace abso_x { /* // 0C: void test_ldy(Instruction&, CPU&, Memory&); // 0D: void test_ora(Instruction&, CPU&, Memory&); void test_and(Instruction&, CPU&, Memory&); void test_eor(Instruction&, CPU&, Memory&); void test_adc(Instruction&, CPU&, Memory&); void test_sta(Instruction&, CPU&, Memory&); void test_lda(Instruction&, CPU&, Memory&); void test_cmp(Instruction&, CPU&, Memory&); void test_sbc(Instruction&, CPU&, Memory&); // 0E: void test_asl(Instruction&, CPU&, Memory&); void test_rol(Instruction&, CPU&, Memory&); void test_lsr(Instruction&, CPU&, Memory&); void test_ror(Instruction&, CPU&, Memory&); void test_dec(Instruction&, CPU&, Memory&); void test_inc(Instruction&, CPU&, Memory&); */ } void test_stack(); void do_memory_tests(); void do_implied_tests(); void do_relative_tests(); void do_absolute_tests(); //void do_absolute_x_tests(); //void do_absolute_y_tests(); // //void do_immediate_tests(); //void do_indirect_tests(); //void do_x_indirect_tests(); //void do_y_indirect_tests(); // //void do_zero_page_tests(); //void do_zero_page_x_tests(); //void do_zero_page_y_tests(); void do_full_program_tests(); int do_tests() { do_memory_tests(); do_implied_tests(); do_relative_tests(); // TODO: do_absolute_tests(); /*do_absolute_x_tests(); do_absolute_y_tests(); do_immediate_tests(); do_indirect_tests(); do_x_indirect_tests(); do_y_indirect_tests(); do_zero_page_tests(); do_zero_page_x_tests(); do_zero_page_y_tests();*/ //do_full_program_tests(); return 0; } void do_memory_tests() { test_stack(); } void test_stack() { Memory m; uint8_t sp = 0xa0, ret = 0x0; m.push_stack(sp, 0xb1); m.push_stack(sp, 0xb2); assert(sp == 0xa2); assert(m[0x1ff - 0xa0] == 0xb1); assert(m[0x1ff - 0xa1] == 0xb2); ret = m.pop_stack(sp); assert(ret == 0xb2); assert(sp == 0xa1); assert(m[0x1ff - 0xa0] == 0xb1); } // DONE void do_implied_tests() { Executor e; CPU cpu; Memory mem; impl::test_brk(*e.instruction(0x00), cpu, mem); impl::test_rti(*e.instruction(0x40), cpu, mem); impl::test_rts(*e.instruction(0x60), cpu, mem); impl::test_txa(*e.instruction(0x8a), cpu, mem); impl::test_txs(*e.instruction(0x9a), cpu, mem); impl::test_tax(*e.instruction(0xaa), cpu, mem); impl::test_tsx(*e.instruction(0xba), cpu, mem); impl::test_dex(*e.instruction(0xca), cpu, mem); impl::test_nop(*e.instruction(0xea), cpu, mem); impl::test_php(*e.instruction(0x08), cpu, mem); impl::test_clc(*e.instruction(0x18), cpu, mem); impl::test_plp(*e.instruction(0x28), cpu, mem); impl::test_sec(*e.instruction(0x38), cpu, mem); impl::test_pha(*e.instruction(0x48), cpu, mem); impl::test_cli(*e.instruction(0x58), cpu, mem); impl::test_pla(*e.instruction(0x68), cpu, mem); impl::test_sei(*e.instruction(0x78), cpu, mem); impl::test_dey(*e.instruction(0x88), cpu, mem); impl::test_tya(*e.instruction(0x98), cpu, mem); impl::test_tay(*e.instruction(0xa8), cpu, mem); impl::test_clv(*e.instruction(0xb8), cpu, mem); impl::test_iny(*e.instruction(0xc8), cpu, mem); impl::test_cld(*e.instruction(0xd8), cpu, mem); impl::test_inx(*e.instruction(0xe8), cpu, mem); impl::test_sed(*e.instruction(0xf8), cpu, mem); } // DONE void do_relative_tests() { Executor e; CPU cpu; Memory mem; rel::test_bpl(*e.instruction(0x10), cpu, mem); rel::test_bmi(*e.instruction(0x30), cpu, mem); rel::test_bvc(*e.instruction(0x50), cpu, mem); rel::test_bvs(*e.instruction(0x70), cpu, mem); rel::test_bcc(*e.instruction(0x90), cpu, mem); rel::test_bcs(*e.instruction(0xb0), cpu, mem); rel::test_bne(*e.instruction(0xd0), cpu, mem); rel::test_beq(*e.instruction(0xf0), cpu, mem); } void do_absolute_tests() { Executor e; CPU cpu; Memory mem; // 00 abso::test_jsr(*e.instruction(0x20), cpu, mem); // 0C abso::test_bit(*e.instruction(0x2c), cpu, mem); abso::test_jmp(*e.instruction(0x4c), cpu, mem); abso::test_sty(*e.instruction(0x8c), cpu, mem); abso::test_ldy(*e.instruction(0xac), cpu, mem); abso::test_cpy(*e.instruction(0xcc), cpu, mem); abso::test_cpx(*e.instruction(0xec), cpu, mem); // 0D abso::test_ora(*e.instruction(0x0d), cpu, mem); abso::test_and(*e.instruction(0x2d), cpu, mem); abso::test_eor(*e.instruction(0x4d), cpu, mem); // PICK UP HERE abso::test_adc(*e.instruction(0x6d), cpu, mem); /*abso::test_sta(*e.instruction(0x8d), cpu, mem); abso::test_lda(*e.instruction(0xad), cpu, mem); abso::test_cmp(*e.instruction(0xcd), cpu, mem); abso::test_sbc(*e.instruction(0xed), cpu, mem); // 0E abso::test_asl(*e.instruction(0x0e), cpu, mem); abso::test_rol(*e.instruction(0x2e), cpu, mem); abso::test_lsr(*e.instruction(0x4e), cpu, mem); abso::test_ror(*e.instruction(0x6e), cpu, mem); abso::test_stx(*e.instruction(0x8e), cpu, mem); abso::test_ldx(*e.instruction(0xae), cpu, mem); abso::test_dec(*e.instruction(0xce), cpu, mem); abso::test_inc(*e.instruction(0xee), cpu, mem);*/ } void do_absolute_x_tests() { Executor e; CPU cpu; Memory mem; /* // 0C abso_x::test_ldy(*e.instruction(0xbc), cpu, mem); // 0D: abso_x::test_ora(*e.instruction(0xbc), cpu, mem); abso_x::test_and(*e.instruction(0xbc), cpu, mem); abso_x::test_eor(*e.instruction(0xbc), cpu, mem); abso_x::test_adc(*e.instruction(0xbc), cpu, mem); abso_x::test_sta(*e.instruction(0xbc), cpu, mem); abso_x::test_lda(*e.instruction(0xbc), cpu, mem); abso_x::test_cmp(*e.instruction(0xbc), cpu, mem); abso_x::test_sbc(*e.instruction(0xbc), cpu, mem); // 0E: abso_x::test_asl(*e.instruction(0xbc), cpu, mem); abso_x::test_rol(*e.instruction(0xbc), cpu, mem); abso_x::test_lsr(*e.instruction(0xbc), cpu, mem); abso_x::test_ror(*e.instruction(0xbc), cpu, mem); abso_x::test_dec(*e.instruction(0xbc), cpu, mem); abso_x::test_inc(*e.instruction(0xbc), cpu, mem);*/ } namespace abso_x { } namespace abso { void test_adc(Instruction& adc, CPU& cpu, Memory& mem) { // add with carry (A = A + M) } void test_eor(Instruction& eor, CPU& cpu, Memory& mem) { // exclusive or with accumulator (A = A ^ M) // non-zero, non-negative cpu.pc = 0x33; cpu.acc = 0xb5; // 10110101 mem[cpu.pc + 1] = 0x22; mem[cpu.pc + 2] = 0x44; mem[0x4422] = 0x88; // 10001000 eor(cpu, mem); assert(cpu.acc == 0x3d);// 00111101 assert(!cpu.p_n()); assert(!cpu.p_z()); // non-zero, negative cpu.pc = 0x33; cpu.acc = 0xb5; // 10110101 mem[cpu.pc + 1] = 0x22; mem[cpu.pc + 2] = 0x44; mem[0x4422] = 0x68; // 01101000 eor(cpu, mem); assert(cpu.acc == 0xdd);// 11011101 assert(cpu.p_n()); assert(!cpu.p_z()); // zero, non-negative cpu.pc = 0x33; cpu.acc = 0xb5; // 10110101 mem[cpu.pc + 1] = 0x22; mem[cpu.pc + 2] = 0x44; mem[0x4422] = 0x68; // 01101000 eor(cpu, mem); assert(cpu.acc == 0xdd);// 11011101 assert(cpu.p_n()); assert(!cpu.p_z()); } void test_and(Instruction& _and, CPU& cpu, Memory& mem) { // AND value pointed to in memory with the accumulator cpu.pc = 0x33; cpu.acc = 0xcc; // 11001100 mem[cpu.pc + 1] = 0x22; mem[cpu.pc + 2] = 0x44; mem[0x4422] = 0xaa; // 10101010 _and(cpu, mem); // result should be 10001000 (0x88) assert(cpu.acc == 0x88); assert(cpu.p_n()); assert(!cpu.p_z()); } void test_cpx(Instruction& cpx, CPU& cpu, Memory& mem) { // set flags depending on the comparison of Y and the value pointed to in memory // X < M cpu.pc = 0x21; cpu.x = 0x33; mem[cpu.pc + 1] = 0x22; // lo mem[cpu.pc + 2] = 0x33; // hi mem[0x3322] = 0x55; cpx(cpu, mem); assert(cpu.pc == 0x24); assert(cpu.p_n()); assert(!cpu.p_z()); assert(!cpu.p_c()); // X >= M cpu.pc = 0x21; cpu.x = 0x66; mem[cpu.pc + 1] = 0x22; // lo mem[cpu.pc + 2] = 0x33; // hi mem[0x3322] = 0x33; cpx(cpu, mem); assert(cpu.pc == 0x24); assert(!cpu.p_n()); assert(!cpu.p_z()); assert(cpu.p_c()); // X == M cpu.pc = 0x21; cpu.x = 0x55; mem[cpu.pc + 1] = 0x22; // lo mem[cpu.pc + 2] = 0x33; // hi mem[0x3322] = 0x55; cpx(cpu, mem); assert(cpu.pc == 0x24); assert(!cpu.p_n()); assert(cpu.p_z()); assert(cpu.p_c()); } void test_cpy(Instruction& cpy, CPU& cpu, Memory& mem) { // set flags depending on the comparison of Y and the value pointed to in memory // Y < M cpu.pc = 0x21; cpu.y = 0x33; mem[cpu.pc + 1] = 0x22; // lo mem[cpu.pc + 2] = 0x33; // hi mem[0x3322] = 0x55; cpy(cpu, mem); assert(cpu.pc == 0x24); assert(cpu.p_n()); assert(!cpu.p_z()); assert(!cpu.p_c()); // Y >= M cpu.pc = 0x21; cpu.y = 0x66; mem[cpu.pc + 1] = 0x22; // lo mem[cpu.pc + 2] = 0x33; // hi mem[0x3322] = 0x33; cpy(cpu, mem); assert(cpu.pc == 0x24); assert(!cpu.p_n()); assert(!cpu.p_z()); assert(cpu.p_c()); // Y == M cpu.pc = 0x21; cpu.y = 0x55; mem[cpu.pc + 1] = 0x22; // lo mem[cpu.pc + 2] = 0x33; // hi mem[0x3322] = 0x55; cpy(cpu, mem); assert(cpu.pc == 0x24); assert(!cpu.p_n()); assert(cpu.p_z()); assert(cpu.p_c()); } void test_ldy(Instruction& ldy, CPU& cpu, Memory& mem) { cpu.pc = 0x20; cpu.y = 0x34; mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x20; // hi mem[0x2010] = 0x54; ldy(cpu, mem); assert(cpu.y == mem[0x2010]); assert(cpu.pc == 0x23); } void test_sty(Instruction& sty, CPU& cpu, Memory& mem) { cpu.pc = 0x20; cpu.y = 0x34; mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x20; // hi sty(cpu, mem); assert(mem[0x2010] == cpu.y); assert(cpu.pc == 0x23); } void test_jmp(Instruction& jmp, CPU& cpu, Memory& mem) { cpu.pc = 0x55; mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x20; // hi jmp(cpu, mem); assert(cpu.pc == 0x2010); } void test_bit(Instruction& bit, CPU& cpu, Memory& mem) { // BIT does an AND with the accumulator and the value pointed to at mem and sets status flags according to the result // (but does not change the accumulator or any other register) // negative flag set cpu.acc = 0xff; cpu.pc = 0x20; mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x20; // hi mem[0x2010] = 0x80; // 10000000 bit(cpu, mem); // results with 10000000 (0x80), which sets the negative flag only assert(cpu.acc == 0xff); // make sure the accumulator didn't change assert(cpu.p_n()); assert(!cpu.p_v()); assert(!cpu.p_z()); // overflow flag set mem[0x2010] = 0x20; // 00100000 mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x20; // hi bit(cpu, mem); assert(!cpu.p_n()); assert(cpu.p_v()); assert(!cpu.p_z()); // zero flag set mem[0x2010] = 0x00; mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x20; // hi bit(cpu, mem); assert(!cpu.p_n()); assert(!cpu.p_v()); assert(cpu.p_z()); } void test_jsr(Instruction& jsr, CPU& cpu, Memory& mem) { cpu.pc = 0x0a; // this will increment to 0x0d cpu.sp = 0; mem[cpu.pc + 1] = 0x10; // lo mem[cpu.pc + 2] = 0x30; // hi jsr(cpu, mem); assert(mem[0x1ff] == 0x0c); assert(cpu.pc == 0x3010); } void test_ora(Instruction& ora, CPU& cpu, Memory& mem) { // test that when the accumulator is 10101010 ($AA) // and the value pointed to by the operand is 01010101 ($55) // that the result is 11111111 ($FF) // note: this is negative, so the negative bit will be set cpu.pc = 0x00; cpu.acc = 0xaa; // 1010 1010 mem[cpu.pc + 1] = 0x20; // lo mem[cpu.pc + 2] = 0x30; // hi mem[0x3020] = 0x55; // 0101 0101 ora(cpu, mem); assert(cpu.acc == 0xff); assert(cpu.pc == 0x03); assert(!cpu.p_z()); assert(cpu.p_n()); // special case with result as 0 cpu.acc = 0; cpu.pc = 0x00; mem[0x3020] = 0; ora(cpu, mem); assert(cpu.acc == 0x00); assert(cpu.pc == 0x03); assert(cpu.p_z()); assert(!cpu.p_n()); // non-negative, non-zero cpu.acc = 1; cpu.pc = 0x00; mem[0x3020] = 2; ora(cpu, mem); assert(cpu.acc == 3); assert(cpu.pc == 0x03); assert(!cpu.p_z()); assert(!cpu.p_n()); } } namespace rel { void test_branching(Instruction& i, function<void(CPU&)> positive, function<void(CPU&)> negative) { CPU cpu; Memory mem; positive(cpu); cpu.pc = 0; // do the jump mem[cpu.pc + 1] = 0x45; // this is how far forward the PC should be set on positive evaluation i(cpu, mem); assert(cpu.pc == 0x47); // again? mem[cpu.pc + 1] = 0x45; i(cpu, mem); assert(cpu.pc == 0x8e); // what about negative jump? mem[cpu.pc + 1] = 0x80; i(cpu, mem); assert(cpu.pc == 0x10); // what about no jump? negative(cpu); i(cpu, mem); assert(cpu.pc == 0x12); // ensure relatives are pushing the right pc increment} } void test_beq(Instruction& beq, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_z(true); }; auto negative = [](CPU& cpu) { cpu.p_z(false); }; test_branching(beq, positive, negative); } void test_bne(Instruction& bne, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_z(false); }; auto negative = [](CPU& cpu) { cpu.p_z(true); }; test_branching(bne, positive, negative); } void test_bcs(Instruction& bcs, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_c(false); }; auto negative = [](CPU& cpu) { cpu.p_c(true); }; test_branching(bcs, positive, negative); } void test_bcc(Instruction& bcc, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_c(true); }; auto negative = [](CPU& cpu) { cpu.p_c(false); }; test_branching(bcc, positive, negative); } void test_bvs(Instruction& bvs, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_v(true); }; auto negative = [](CPU& cpu) { cpu.p_v(false); }; test_branching(bvs, positive, negative); } void test_bvc(Instruction& bvc, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_v(false); }; auto negative = [](CPU& cpu) { cpu.p_v(true); }; test_branching(bvc, positive, negative); } void test_bmi(Instruction& bmi, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_n(true); }; auto negative = [](CPU& cpu) { cpu.p_n(false); }; test_branching(bmi, positive, negative); } void test_bpl(Instruction& bpl, CPU& cpu, Memory& mem) { auto positive = [](CPU& cpu) { cpu.p_n(false); }; auto negative = [](CPU& cpu) { cpu.p_n(true); }; test_branching(bpl, positive, negative); } } namespace impl { void test_brk(Instruction& brk, CPU& cpu, Memory& mem) { // TODO } void test_rti(Instruction& rti, CPU& cpu, Memory& mem) { // TODO } void test_rts(Instruction& rts, CPU& cpu, Memory& mem) { // RTS returns from subroutine // Grabs the two bytes off the stack as the return address // then sets the PC to that address + 1 cpu.sp = 0; cpu.pc = 0x0000; mem.push_stack(cpu.sp, 0x30); mem.push_stack(cpu.sp, 0x40); dbgout("about to call RTS" << std::endl); rts(cpu, mem); dbgout("finished calling RTS. PC: " << cpu.pc); assert(cpu.pc == 0x4031); assert(cpu.sp == 0); } void test_txa(Instruction& txa, CPU& cpu, Memory& mem) { cpu.x = 0x10; cpu.acc = 0x20; txa(cpu, mem); assert(cpu.acc == cpu.x); assert(!cpu.p_z()); assert(!cpu.p_n()); cpu.x = 0x00; cpu.acc = 0x20; txa(cpu, mem); assert(cpu.acc == cpu.x); assert(cpu.p_z()); assert(!cpu.p_n()); cpu.x = 0x80; cpu.acc = 0x20; txa(cpu, mem); assert(cpu.acc == cpu.x); assert(cpu.p_n()); assert(!cpu.p_z()); } void test_txs(Instruction& txs, CPU& cpu, Memory& mem) { cpu.x = 0x77; cpu.sp = 0x88; txs(cpu, mem); assert(cpu.sp == cpu.x); } void test_tax(Instruction& tax, CPU& cpu, Memory& mem) { cpu.acc = 0x17; cpu.x = 0x18; tax(cpu, mem); assert(cpu.x == cpu.acc); assert(!cpu.p_n()); assert(!cpu.p_z()); cpu.acc = 0x87; cpu.x = 0x18; tax(cpu, mem); assert(cpu.x == cpu.acc); assert(cpu.p_n()); assert(!cpu.p_z()); cpu.acc = 0x00; cpu.x = 0x18; tax(cpu, mem); assert(cpu.x == cpu.acc); assert(!cpu.p_n()); assert(cpu.p_z()); } void test_tsx(Instruction& tsx, CPU& cpu, Memory& mem) { cpu.sp = 0x22; cpu.x = 0x11; tsx(cpu, mem); assert(cpu.x == cpu.sp); } void test_dex(Instruction& dex, CPU& cpu, Memory& mem) { cpu.x = 0x11; dex(cpu, mem); assert(cpu.x == 0x10); assert(!cpu.p_n()); assert(!cpu.p_z()); cpu.x = 0x81; dex(cpu, mem); assert(cpu.x == 0x80); assert(cpu.p_n()); assert(!cpu.p_z()); cpu.x = 0x01; dex(cpu, mem); assert(cpu.x == 0x00); assert(!cpu.p_n()); assert(cpu.p_z()); } void test_nop(Instruction& nop, CPU& cpu, Memory& mem) { CPU tempCPU = CPU(cpu); nop(cpu, mem); assert(cpu.acc == tempCPU.acc); assert(cpu.pc == tempCPU.pc + 1); assert(cpu.sp == tempCPU.sp); assert(cpu.x == tempCPU.x); assert(cpu.y == tempCPU.y); assert(cpu.p == tempCPU.p); } void test_sed(Instruction& sed, CPU& cpu, Memory& mem) { cpu.p_d(false); sed(cpu, mem); assert(cpu.p_d()); } void test_inx(Instruction& inx, CPU& cpu, Memory& mem) { cpu.x = 0x77; inx(cpu, mem); assert(cpu.x == 0x78); assert(!cpu.p_n()); assert(!cpu.p_z()); cpu.x = 0xff; inx(cpu, mem); assert(cpu.x == 0x00); assert(!cpu.p_n()); assert(cpu.p_z()); cpu.x = 0x7f; inx(cpu, mem); assert(cpu.x == 0x80); assert(cpu.p_n()); assert(!cpu.p_z()); } void test_cld(Instruction& cld, CPU& cpu, Memory& mem) { cpu.p_d(true); cld(cpu, mem); assert(!cpu.p_d()); } void test_iny(Instruction& iny, CPU& cpu, Memory& mem) { cpu.y = 0x77; iny(cpu, mem); assert(cpu.y == 0x78); assert(!cpu.p_n()); assert(!cpu.p_z()); cpu.y = 0xff; iny(cpu, mem); assert(cpu.y == 0x00); assert(!cpu.p_n()); assert(cpu.p_z()); cpu.y = 0x7f; iny(cpu, mem); assert(cpu.y == 0x80); assert(cpu.p_n()); assert(!cpu.p_z()); } void test_clv(Instruction& clv, CPU& cpu, Memory& mem) { cpu.p_v(true); clv(cpu, mem); assert(!cpu.p_v()); } void test_tay(Instruction& tay, CPU& cpu, Memory& mem) { cpu.acc = 0x10; cpu.y = 0x20; tay(cpu, mem); assert(cpu.y == cpu.acc); assert(!cpu.p_z()); assert(!cpu.p_n()); cpu.acc = 0x00; cpu.y = 0x20; tay(cpu, mem); assert(cpu.acc == cpu.y); assert(cpu.p_z()); assert(!cpu.p_n()); cpu.acc = 0x80; cpu.y = 0x20; tay(cpu, mem); assert(cpu.acc == cpu.y); assert(cpu.p_n()); assert(!cpu.p_z()); } void test_tya(Instruction& tya, CPU& cpu, Memory& mem) { cpu.y = 0x10; cpu.acc = 0x20; tya(cpu, mem); assert(cpu.acc == cpu.y); assert(!cpu.p_z()); assert(!cpu.p_n()); cpu.y = 0x00; cpu.acc = 0x20; tya(cpu, mem); assert(cpu.acc == cpu.y); assert(cpu.p_z()); assert(!cpu.p_n()); cpu.y = 0x80; cpu.acc = 0x20; tya(cpu, mem); assert(cpu.acc == cpu.y); assert(cpu.p_n()); assert(!cpu.p_z()); } void test_dey(Instruction& dey, CPU& cpu, Memory& mem) { cpu.y = 0x10; dey(cpu, mem); assert(cpu.y == 0x0f); assert(!cpu.p_z()); assert(!cpu.p_n()); cpu.y = 0x01; dey(cpu, mem); assert(cpu.y == 0); assert(cpu.p_z()); assert(!cpu.p_n()); // test when the value is negative (I think it still straight decrements?) // 10000001 => 10000000 (0x81 -> DEY -> 0x80) cpu.y = 0x81; dey(cpu, mem); assert(cpu.y == 0x80); assert(!cpu.p_z()); assert(cpu.p_n()); } void test_sei(Instruction& sei, CPU& cpu, Memory& mem) { cpu.p_i(false); sei(cpu, mem); assert(cpu.p_i()); } void test_pla(Instruction& pla, CPU& cpu, Memory& mem) { cpu.acc = 0x77; cpu.sp = 0x02; mem[0x1fe] = 0x66; pla(cpu, mem); assert(cpu.acc == 0x66); assert(cpu.sp == 0x01); } void test_cli(Instruction& cli, CPU& cpu, Memory& mem) { cpu.p_i(true); cli(cpu, mem); assert(!cpu.p_i()); } void test_pha(Instruction& pha, CPU& cpu, Memory& mem) { cpu.acc = 0x66; cpu.sp = 0; mem[0x1ff] = 0x00; pha(cpu, mem); assert(mem[0x1ff] == cpu.acc); } void test_sec(Instruction& sec, CPU& cpu, Memory& mem) { cpu.p_c(false); sec(cpu, mem); assert(cpu.p_c()); } void test_plp(Instruction& plp, CPU& cpu, Memory& mem) { cpu.p = 0x70; cpu.sp = 0x44; mem.push_stack(cpu.sp, 0x10); plp(cpu, mem); assert(cpu.p == 0x10); assert(cpu.sp == 0x44); } void test_php(Instruction& php, CPU& cpu, Memory& mem) { // PHP: push the status register onto the stack cpu.sp = 0; cpu.p = 0x70; assert(mem[0x1ff] != cpu.p); php(cpu, mem); assert(cpu.sp == 1); assert(mem[0x1ff] == cpu.p); php(cpu, mem); php(cpu, mem); assert(cpu.sp == 3); assert(mem[0x1fe] == cpu.p); assert(mem[0x1fd] == cpu.p); } void test_clc(Instruction& clc, CPU& cpu, Memory& mem) { // CLC: clear the carry flag on the status register cpu.p_c(true); clc(cpu, mem); assert(!cpu.p_c()); cpu.p_c(false); clc(cpu, mem); assert(!cpu.p_c()); } } int do_asm_tests() { cout << "Running tests" << endl; Assembler assembler; vector<unsigned char> result; string resultstr; result = assembler.decodeline(string("BRK")); resultstr = make_string(result); assert(resultstr == string("00")); result = assembler.decodeline(string("BPL $00")); resultstr = make_string(result); assert(resultstr == string("10FD")); result = assembler.decodeline(string("BPL $10")); resultstr = make_string(result); assert(resultstr == string("100B")); return 0; } string make_string(vector<unsigned char>& in) { ostringstream ss; for (auto c : in) { if (c < 10) ss << '0'; ss << hex << (int) c; } return ss.str(); } void do_full_program_tests() { /* 38 B0 00 20 07 80 18 C8 60 ==> $8000: SEC $8001: BCS $01 $8003: INX $8004: JSR $08 $80 $8007: CLC $8008: INY $8009: RTS # will fail on the second loop since the return address no longer exists on the stack */ Executor e; e.load("test.s"); e.run(); }
24.572864
119
0.629039
mavroskardia
5649774c3b69eb849339ef5da9eb2b98e9f8a049
499
hh
C++
game/flame.hh
Faerbit/Saxum
3b255142337e08988f2b4f1f56d6e061e8754336
[ "CC-BY-3.0", "CC-BY-4.0" ]
2
2015-03-12T16:19:10.000Z
2015-11-24T20:23:26.000Z
game/flame.hh
Faerbit/Saxum
3b255142337e08988f2b4f1f56d6e061e8754336
[ "CC-BY-3.0", "CC-BY-4.0" ]
15
2015-03-14T14:13:12.000Z
2015-06-02T18:39:55.000Z
game/flame.hh
Faerbit/Saxum
3b255142337e08988f2b4f1f56d6e061e8754336
[ "CC-BY-3.0", "CC-BY-4.0" ]
null
null
null
#pragma once #include "entity.hh" #include <ACGL/OpenGL/Objects.hh> using namespace ACGL::OpenGL; class Flame : public Entity { public: Flame(glm::vec3 position, glm::vec3 color, glm::vec3 size); Flame(); void render(SharedShaderProgram shader, glm::mat4 viewProjectionMatrix, float time, bool withColor, glm::vec2 skewing); private: glm::vec3 color; glm::vec3 size; SharedVertexArrayObject vao; SharedArrayBuffer ab; };
26.263158
79
0.649299
Faerbit
871c7e8e0f783429dd763ce113fb82da83c7ff50
1,462
hxx
C++
src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Include/base64.hxx
legistek/AspNetCore
f8368097a909ba2618efbec5efa5e7e036d3a2e8
[ "Apache-2.0" ]
13,846
2020-01-07T21:33:57.000Z
2022-03-31T20:28:11.000Z
src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Include/base64.hxx
legistek/AspNetCore
f8368097a909ba2618efbec5efa5e7e036d3a2e8
[ "Apache-2.0" ]
20,858
2020-01-07T21:28:23.000Z
2022-03-31T23:51:40.000Z
src/Installers/Windows/AspNetCoreModule-Setup/IIS-Setup/IIS-Common/Include/base64.hxx
legistek/AspNetCore
f8368097a909ba2618efbec5efa5e7e036d3a2e8
[ "Apache-2.0" ]
4,871
2020-01-07T21:27:37.000Z
2022-03-31T21:22:44.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. #ifndef _BASE64_HXX_ #define _BASE64_HXX_ DWORD Base64Encode( __in_bcount( cbDecodedBufferSize ) VOID * pDecodedBuffer, IN DWORD cbDecodedBufferSize, __out_ecount_opt( cchEncodedStringSize ) PWSTR pszEncodedString, IN DWORD cchEncodedStringSize, __out_opt DWORD * pcchEncoded ); DWORD Base64Decode( __in PCWSTR pszEncodedString, __out_opt VOID * pDecodeBuffer, __in DWORD cbDecodeBufferSize, __out_opt DWORD * pcbDecoded ); DWORD Base64Encode( __in_bcount( cbDecodedBufferSize ) VOID * pDecodedBuffer, IN DWORD cbDecodedBufferSize, __out_ecount_opt( cchEncodedStringSize ) PSTR pszEncodedString, IN DWORD cchEncodedStringSize, __out_opt DWORD * pcchEncoded ); DWORD Base64Decode( __in PCSTR pszEncodedString, __out_opt VOID * pDecodeBuffer, __in DWORD cbDecodeBufferSize, __out_opt DWORD * pcbDecoded ); #endif // _BASE64_HXX_
34
69
0.522572
legistek
871cda5ce2cc19e20b167f28215c3f7c9c6b4a99
1,528
cpp
C++
Past Papers/2020 Assignment 01/THUSHARA/Train/Sol-2-Train - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
19
2021-04-28T13:32:15.000Z
2022-03-08T11:52:59.000Z
Past Papers/2020 Assignment 01/THUSHARA/Train/Sol-2-Train - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
5
2021-03-03T08:06:15.000Z
2021-12-26T18:14:45.000Z
Past Papers/2020 Assignment 01/THUSHARA/Train/Sol-2-Train - Thushara.cpp
GIHAA/Cpp-programming
0b094868652fd83f8dc4eb02c5abe3c3501bcdf1
[ "MIT" ]
27
2021-01-18T22:35:01.000Z
2022-02-22T19:52:19.000Z
// Using Char Arrays #include<iostream> #include<cstring> using namespace std; // You can put this code segment in Train.h file ----- class Train { private: int trainID; int capacity; char startTime[15]; char destination[10]; public: void setTrainDetails(int tID, int c, char sT[10], char d[15]); void displayTrainDetails(); void setStartTime(); }; // ---------------------------------------------------- int main() { Train t1, t2, t3; t1.setTrainDetails(1, 200, (char *)"6:00AM", (char *)"Kandy"); t2.setTrainDetails(2, 150, (char *)"7:30AM", (char *)"Galle"); t3.setTrainDetails(3, 300, (char *)"4:00AM", (char *)"Jaffna"); t1.setStartTime(); t2.setStartTime(); t3.setStartTime(); t1.displayTrainDetails(); t2.displayTrainDetails(); t3.displayTrainDetails(); return 0; } // You can put this code segment in Train.cpp file ----- void Train::setTrainDetails(int tID, int c, char sT[10], char d[15]) { trainID = tID; capacity = c; strcpy(startTime, sT); strcpy(destination, d); } void Train::displayTrainDetails() { cout << endl << "TrainID = " << trainID << endl; cout << "Capacity = " << capacity << endl; cout << "StartTime = " << startTime << endl; cout << "Destination = " << destination << endl; } void Train::setStartTime() { cout << "Input new start time of train " << trainID << ": "; cin >> startTime; } // ----------------------------------------------------
25.466667
70
0.554319
GIHAA
871eb51ace4e94c3b6a2fa16d62c3e0e2464b1b0
2,105
cc
C++
src/network/connection_manager.cc
fon/flexran-rtc
27a955a0494597c6fd175f6b4d31b9eaac2b8dfd
[ "MIT" ]
1
2019-11-05T16:22:11.000Z
2019-11-05T16:22:11.000Z
src/network/connection_manager.cc
fon/flexran-rtc
27a955a0494597c6fd175f6b4d31b9eaac2b8dfd
[ "MIT" ]
null
null
null
src/network/connection_manager.cc
fon/flexran-rtc
27a955a0494597c6fd175f6b4d31b9eaac2b8dfd
[ "MIT" ]
3
2019-05-02T05:14:36.000Z
2021-06-15T12:40:52.000Z
/* The MIT License (MIT) Copyright (c) 2016 Xenofon Foukas 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 "connection_manager.h" flexran::network::connection_manager::connection_manager(boost::asio::io_service& io_service, const boost::asio::ip::tcp::endpoint& endpoint, async_xface& xface) : acceptor_(io_service, endpoint), socket_(io_service), next_id_(0), xface_(xface) { do_accept(); } void flexran::network::connection_manager::send_msg_to_agent(std::shared_ptr<tagged_message> msg) { sessions_[msg->getTag()]->deliver(msg); } void flexran::network::connection_manager::do_accept() { acceptor_.async_accept(socket_, [this](boost::system::error_code ec) { if (!ec) { sessions_[next_id_] = std::make_shared<agent_session>(std::move(socket_), *this, xface_, next_id_); sessions_[next_id_]->start(); xface_.initialize_connection(next_id_); next_id_++; } do_accept(); }); } void flexran::network::connection_manager::close_connection(int session_id) { sessions_.erase(session_id); }
36.929825
100
0.737292
fon
87227fe73c6eefada6b3f33ace19caa52b1edbdb
3,478
cpp
C++
scripts/urdf_scenes.cpp
psh117/motion_bench_maker
11ec8378a50595b27151da878517ada6642f10b5
[ "BSD-3-Clause" ]
19
2021-12-13T14:48:29.000Z
2022-03-11T03:24:17.000Z
scripts/urdf_scenes.cpp
psh117/motion_bench_maker
11ec8378a50595b27151da878517ada6642f10b5
[ "BSD-3-Clause" ]
1
2022-02-15T20:05:04.000Z
2022-02-15T20:05:04.000Z
scripts/urdf_scenes.cpp
psh117/motion_bench_maker
11ec8378a50595b27151da878517ada6642f10b5
[ "BSD-3-Clause" ]
1
2021-12-29T10:54:49.000Z
2021-12-29T10:54:49.000Z
/*Constantinos Chamzas */ #include <motion_bench_maker/parser.h> // Robowflex library #include <robowflex_library/util.h> #include <robowflex_library/yaml.h> #include <robowflex_library/io/visualization.h> #include <robowflex_library/io.h> #include <robowflex_library/scene.h> #include <robowflex_library/trajectory.h> #include <robowflex_library/detail/fetch.h> #include <robowflex_library/builder.h> // Robowflex ompl #include <robowflex_ompl/ompl_interface.h> static const std::string GROUP = "arm_with_torso"; using namespace robowflex; int main(int argc, char **argv) { ROS ros(argc, argv, "urdf_scenes"); ros::NodeHandle node("~"); // Create scene auto scene_robot = std::make_shared<Robot>("robot"); // scene_robot->initialize("package://fetch_description/robots/fetch.urdf"); scene_robot->initialize("package://motion_bench_maker/configs/scenes/kitchen/kitchen.urdf"); scene_robot->getScratchState()->setToRandomPositions(); scene_robot->dumpToScene(IO::resolvePackage("package://motion_bench_maker/" "configs/scenes/kitchen/" "kitchen_urdf.yaml")); auto robot = std::make_shared<robowflex::FetchRobot>(); robot->initialize(); auto scene = std::make_shared<robowflex::Scene>(robot); // Create RVIZ helper. auto rviz = std::make_shared<IO::RVIZHelper>(robot); // Create the default planner for the Fetch. auto planner = std::make_shared<OMPL::FetchOMPLPipelinePlanner>(robot, "default"); planner->initialize(); // Create a motion planning request with a pose goal. auto request = std::make_shared<MotionRequestBuilder>(planner, GROUP); robot->setGroupState(GROUP, {0.05, 1.32, 1.40, -0.2, 1.72, 0.0, 1.66, 0.0}); // Stow request->setStartConfiguration(robot->getScratchState()); robot->setGroupState(GROUP, {0.15, 0, 0, 0, 0, 0, 0, 0}); request->setGoalConfiguration(robot->getScratchState()); request->setConfig("RRTConnect"); int attempts = 0; while (1) { scene_robot->getScratchState()->setToRandomPositions(); scene_robot->dumpToScene(IO::resolvePackage("package://motion_bench_maker/" "configs/scenes/kitchen/" "kitchen_urdf.yaml")); ROS_INFO("Visualizing scene %d ....", attempts); attempts += 1; scene->fromYAMLFile(IO::resolvePackage("package://motion_bench_maker/" "configs/scenes/kitchen/" "kitchen_urdf.yaml")); rviz->updateScene(scene); rviz->updateScene(scene); // Visualize start state. rviz->visualizeState(request->getStartConfiguration()); parser::waitForUser("Displaying initial state!"); // Visualize goal state. rviz->visualizeState(request->getGoalConfiguration()); parser::waitForUser("Displaying goal state!"); auto res = planner->plan(scene, request->getRequestConst()); auto trajectory = std::make_shared<Trajectory>(*res.trajectory_); if (res.error_code_.val == moveit_msgs::MoveItErrorCodes::SUCCESS) { // Visualize the trajectory. rviz->updateTrajectory(trajectory->getTrajectory()); parser::waitForUser("Displaying The trajectory!"); } } }
37.804348
96
0.63226
psh117
87279e7bf5477f522845051e0f8fbcdda45ab3d4
6,804
cpp
C++
Algo/03/D.cpp
abel1502/mipt_3s
10efc85371e53a0780302763c409cde2158f81fc
[ "MIT" ]
2
2021-10-16T10:58:26.000Z
2021-12-22T22:18:37.000Z
Algo/03/D.cpp
abel1502/mipt_3s
10efc85371e53a0780302763c409cde2158f81fc
[ "MIT" ]
null
null
null
Algo/03/D.cpp
abel1502/mipt_3s
10efc85371e53a0780302763c409cde2158f81fc
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <cassert> #include <cstring> #include <vector> #include <string_view> #include <string> #include <iostream> #include <algorithm> #include <map> #include <new> #include <type_traits> #include <utility> #if 0 #define DBG(FMT, ...) \ printf("[%s#%d: " FMT "]\n", __FUNCTION__, __LINE__, ##__VA_ARGS__) #else #define DBG(FMT, ...) #endif class SuffixAutomata { public: using idx_t = unsigned; static constexpr idx_t BAD_IDX = -1u; struct Node; struct Node { char chr; // Hold the END position in both cases! unsigned long long firstOcc = 0, lastOcc = 0; unsigned long long longestLen = 0; idx_t link = BAD_IDX; bool terminal = false; unsigned long long score = -1ull; std::map<char, idx_t> children{}; Node(char chr_) noexcept : chr{chr_} {} inline bool hasChild(char chr_) const noexcept { return children.find(chr_) != children.end(); } inline idx_t getChild(char chr_) const noexcept { auto it = children.find(chr_); return it != children.end() ? it->second : BAD_IDX; } inline void addChild(char chr_, idx_t child) noexcept { children[chr_] = child; } inline bool isRoot() const noexcept { return chr == '\0'; } inline bool isTerm() const noexcept { return terminal; } void dfsCalcScores(SuffixAutomata &automata) { if (score != -1ull) return; unsigned long long maxContainingLen = lastOcc + longestLen - firstOcc; score = maxContainingLen; if (lastOcc != firstOcc) { score += longestLen * longestLen; } // Otherwise we're only found once in the string, so we // aren't a proper suprefix and shouldn't be accounted for for (auto child : children) { automata[child.second].dfsCalcScores(automata); } } void dump(const SuffixAutomata &automata, unsigned indentation = 0) const { indent(indentation); printf("'%c' <%u> (link = %d, len = %llu)\n", chr, automata.refToIdx(*this), (int)link, longestLen); for (auto child : children) { indent(indentation); printf(" |-> '%c' %u\n", child.first, child.second); } printf("\n"); } private: static void indent(unsigned indentation) { static constexpr const char INDENT[] = " "; for (unsigned i = 0; i < indentation; ++i) { printf("%s", INDENT); } } }; friend struct Node; SuffixAutomata(const char *str_ = "") : str{str_}, nodes{Node('\0')} { build(); } SuffixAutomata &operator=(const char *str_) { str = str_; nodes.clear(); nodes.push_back(Node('\0')); build(); return *this; } void dump() const { printf("SuffAutomata(\"%s\") {\n", str.data()); for (const Node &node : nodes) { node.dump(*this, 1); } printf("}\n"); } const std::string_view &getStr() const noexcept { return str; } const Node &operator[](idx_t idx) const { assert(idx < nodes.size()); return nodes[idx]; } unsigned long long findBestScore() { assert(nodes.size() > 0); nodes[0].dfsCalcScores(*this); unsigned long long bestScore = 0; for (const Node &node : nodes) { if (bestScore < node.score) { bestScore = node.score; } } return bestScore; } protected: std::string_view str; std::vector<Node> nodes; idx_t last = 0; Node &operator[](idx_t idx) { assert(idx < nodes.size()); return nodes[idx]; } inline idx_t refToIdx(const Node &node) const { assert((size_t)(&node - nodes.data()) < nodes.size()); return &node - nodes.data(); } inline idx_t lastIdx() const noexcept { assert(nodes.size()); return nodes.size() - 1; } idx_t addNode(idx_t prev, char chr) { // assert(!nodes[prev].hasChild(chr)); nodes.emplace_back(chr); Node & newNode = (*this)[lastIdx()]; Node &prevNode = (*this)[prev ]; // Shouldn't be done here, in fact // prevNode.addChild(chr, lastIdx()); newNode.longestLen = prevNode.longestLen + 1; newNode.firstOcc = prevNode.firstOcc + 1; newNode. lastOcc = prevNode. lastOcc + 1; return lastIdx(); } idx_t cloneNode(idx_t original) { nodes.emplace_back((*this)[original]); return lastIdx(); } void build() { for (unsigned idx = 0; idx < str.size(); ++idx) { step(str[idx]); } markTerminals(); } void step(char chr) { idx_t curIdx = addNode(last, chr); idx_t prevIdx = last; for (; prevIdx != BAD_IDX && !(*this)[prevIdx].hasChild(chr); prevIdx = (*this)[prevIdx].link) { (*this)[prevIdx].addChild(chr, curIdx); } if (prevIdx == BAD_IDX) { (*this)[curIdx].link = 0; last = curIdx; return; } idx_t candidateIdx = (*this)[prevIdx].getChild(chr); assert(candidateIdx != BAD_IDX); if ((*this)[candidateIdx].longestLen == (*this)[prevIdx].longestLen + 1) { (*this)[curIdx].link = candidateIdx; (*this)[candidateIdx].lastOcc = (*this)[curIdx].lastOcc; last = curIdx; return; } idx_t cloneIdx = cloneNode(candidateIdx); (*this)[cloneIdx].lastOcc = (*this)[curIdx].lastOcc; (*this)[cloneIdx].longestLen = (*this)[prevIdx].longestLen + 1; for (; prevIdx != BAD_IDX && (*this)[prevIdx].getChild(chr) == candidateIdx; prevIdx = (*this)[prevIdx].link) { (*this)[prevIdx].addChild(chr, cloneIdx); } (*this)[curIdx] .link = cloneIdx; (*this)[candidateIdx].link = cloneIdx; last = curIdx; return; } void markTerminals() { idx_t cur = last; for (; cur != BAD_IDX; cur = (*this)[cur].link) { (*this)[cur].terminal = true; } } }; int main() { std::string str{}; std::cin >> str; // str = "ababaab"; SuffixAutomata sa(str.data()); // sa.dump(); std::cout << sa.findBestScore() << "\n"; return 0; }
24.12766
84
0.518519
abel1502
8728743f14f04e0c27b27cb967b9ffc0038bb4b8
7,824
cpp
C++
src/mayaToBase/src/mt@_common/mt@_mayaRenderer.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
42
2015-01-03T15:07:25.000Z
2021-12-09T03:56:59.000Z
src/mayaToBase/src/mt@_common/mt@_mayaRenderer.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
66
2015-01-02T13:28:44.000Z
2022-03-16T14:00:57.000Z
src/mayaToBase/src/mt@_common/mt@_mayaRenderer.cpp
haggi/OpenMaya
746e0740f480d9ef8d2173f31b3c99b9b0ea0d24
[ "MIT" ]
12
2015-02-07T05:02:17.000Z
2020-07-10T17:21:44.000Z
#include "mt@_mayaRenderer.h" #include "utilities/logging.h" #include "utilities/tools.h" #include "utilities/attrTools.h" #include "world.h" #if MAYA_API_VERSION >= 201600 #include <vector> #include <maya/MPxRenderer.h> #include <maya/MGlobal.h> #define kNumChannels 4 float FLT_RAND() { return float(rand()) / RAND_MAX; } mt@_MayaRenderer::mt@_MayaRenderer() { width = height = initialSize; renderBuffer = (float*)malloc(width*height*kNumChannels*sizeof(float)); good = true; } mt@_MayaRenderer::~mt@_MayaRenderer() { if (!good)return; } bool mt@_MayaRenderer::isRunningAsync() { Logging::debug("isRunningAsync"); return true; } void* mt@_MayaRenderer::creator() { return new mt@_MayaRenderer(); } void mt@_MayaRenderer::render() { Logging::debug("Rendering..."); ProgressParams progressParams; progressParams.progress = 0.0f; progress(progressParams); isRendering = true; --renderFrame(); isRendering = false; progressParams.progress = 1.0f; progress(progressParams); } static void startRenderThread(mt@_MayaRenderer* renderPtr) { renderPtr->render(); } static void startFbThread(mt@_MayaRenderer* renderPtr) { if (!renderPtr->good)return; while (renderPtr->isRendering) { Logging::debug("FbThread sleeping..."); std::this_thread::sleep_for(std::chrono::milliseconds(renderPtr->refreshInteraval * 1000)); renderPtr->framebufferCallback(); } } void mt@_MayaRenderer::finishRendering() { if (good) cancelRender(); if (this->renderThread.joinable()) this->renderThread.join(); if (this->fbThread.joinable()) this->fbThread.join(); } MStatus mt@_MayaRenderer::startAsync(const JobParams& params) { //mt@_MayaRenderer::running = true; //render(); return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::stopAsync() { Logging::debug("stopAsync"); finishRendering(); return MS::kSuccess; } MStatus mt@_MayaRenderer::beginSceneUpdate() { Logging::debug("beginSceneUpdate"); finishRendering(); return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::endSceneUpdate() { Logging::debug("endSceneUpdate"); completlyInitialized = true; this->renderThread = std::thread(startRenderThread, this); this->fbThread = std::thread(startFbThread, this); return MStatus::kSuccess; }; static float demoRot = 0.0f; MStatus mt@_MayaRenderer::translateMesh(const MUuid& id, const MObject& node) { Logging::debug("translateMesh"); IdNameStruct idn; idn.id = id; idn.mobject = node; idn.name = "mesh"; objectArray.push_back(idn); lastShape = node; return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::translateLightSource(const MUuid& id, const MObject& node) { Logging::debug("translateLightSource"); IdNameStruct idn; idn.id = id; idn.mobject = node; idn.name = "light"; objectArray.push_back(idn); lastShape = node; return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::translateCamera(const MUuid& id, const MObject& node) { Logging::debug("translateCamera"); IdNameStruct idn; idn.id = id; idn.mobject = node; idn.name = "camera"; objectArray.push_back(idn); lastShape = node; return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::translateEnvironment(const MUuid& id, EnvironmentType type) { Logging::debug("translateEnvironment"); IdNameStruct idn; idn.id = id; idn.name = "environment"; objectArray.push_back(idn); lastShape = MObject::kNullObj; return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::translateTransform(const MUuid& id, const MUuid& childId, const MMatrix& matrix) { Logging::debug("translateTransform"); IdNameStruct ids; ids.id = id; ids.name = "transform"; objectArray.push_back(ids); ids.id = childId; ids.name = "transformChild"; objectArray.push_back(ids); return MStatus::kSuccess; return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::translateShader(const MUuid& id, const MObject& node) { Logging::debug(MString("translateShader: ")); bool alreadyExists = false; for (auto idn : objectArray) { if ( idn.mobject == node) { Logging::debug(MString("found existing shader node.")); if (idn.instance != nullptr) { alreadyExists = true; break; } } } if (!alreadyExists) { IdNameStruct idn; idn.id = id; idn.name = "material"; idn.mobject = node; objectArray.push_back(idn); } lastShape = node; return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::setProperty(const MUuid& id, const MString& name, bool value) { Logging::debug(MString("setProperty bool: ") + name + " " + value); return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::setProperty(const MUuid& id, const MString& name, int value) { Logging::debug(MString("setProperty int: ") + name + " " + value); return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::setProperty(const MUuid& id, const MString& name, float value) { Logging::debug(MString("setProperty float: ") + name + " " + value); return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::setProperty(const MUuid& id, const MString& name, const MString& value) { mt@_FileLoader fl; Logging::debug(MString("setProperty string: ") + name + " " + value); MString mayaRoot = getenv("MAYA_LOCATION"); MString blackImage = mayaRoot + "/presets/Assets/IBL/black.exr"; IdNameStruct idNameObj; for (auto idobj : objectArray) { if (idobj.id == id) { Logging::debug(MString("Found id object for string property: ") + idobj.name); if (idobj.name == "environment") { if (name == "imageFile") { Logging::debug(MString("Setting environment image file to: ") + value); if (value.length() == 0) // else // } } } } return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::setShader(const MUuid& id, const MUuid& shaderId) { Logging::debug("setShader"); IdNameStruct *idnShader; MObject meshObject; // first find the shader node for (uint i = 0; i < objectArray.size(); i++) { if (objectArray[i].id == shaderId) { idnShader = &objectArray[i]; break; } } IdNameStruct idnGeo; for (uint i = 0; i < objectArray.size(); i++) { if (objectArray[i].id == id) { idnGeo = objectArray[i]; break; } } if ((idnShader->mobject == MObject::kNullObj) || (idnGeo.mobject == MObject::kNullObj)) { Logging::debug(MString("Object not fund for shader update.")); return MS::kFailure; } // first find the shader node bool alreadyExists = false; for (uint i = 0; i < objectArray.size(); i++) { if (objectArray[i].id == id) { if (objectArray[i].name == "coronaMaterial") { objectArray[i].material = mat; alreadyExists = true; break; } } } if (!alreadyExists) { IdNameStruct idn; idn.id = id; idn.name = "coronaMaterial"; idn.mobject = idnGeo.mobject; idn.material = mat; objectArray.push_back(idn); } return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::setResolution(unsigned int w, unsigned int h) { Logging::debug(MString("setResolution ") + w + " " + h); this->width = w; this->height = h; this->renderBuffer = (float*)realloc(this->renderBuffer, w*h*kNumChannels*sizeof(float)); if (good) { } return MStatus::kSuccess; }; MStatus mt@_MayaRenderer::destroyScene() { Logging::debug("destroyScene"); finishRendering(); ProgressParams progressParams; progressParams.progress = -1.0f; progress(progressParams); objectArray.clear(); return MStatus::kSuccess; }; bool mt@_MayaRenderer::isSafeToUnload() { Logging::debug("isSafeToUnload"); return true; }; void mt@_MayaRenderer::framebufferCallback() { Logging::debug("framebufferCallback"); refreshParams.bottom = 0; refreshParams.top = height - 1; refreshParams.bytesPerChannel = sizeof(float); refreshParams.channels = kNumChannels; refreshParams.left = 0; refreshParams.right = width - 1; refreshParams.width = width; refreshParams.height = height; refreshParams.data = renderBuffer; refresh(refreshParams); } #endif
22.039437
106
0.702326
haggi
872aff7ad6c842e2f405062451ddabe647aef012
1,227
hpp
C++
Cores/Mednafen/mednafen-1.21/src/snes/src/lib/nall/stdint.hpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
3,459
2015-01-07T14:07:09.000Z
2022-03-25T03:51:10.000Z
Cores/Mednafen/mednafen-1.21/src/snes/src/lib/nall/stdint.hpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
1,046
2018-03-24T17:56:16.000Z
2022-03-23T08:13:09.000Z
Cores/Mednafen/mednafen-1.21/src/snes/src/lib/nall/stdint.hpp
werminghoff/Provenance
de61b4a64a3eb8e2774e0a8ed53488c6c7aa6cb2
[ "BSD-3-Clause" ]
549
2015-01-07T14:07:15.000Z
2022-01-07T16:13:05.000Z
#ifndef NALL_STDINT_HPP #define NALL_STDINT_HPP #include <nall/static.hpp> #if defined(_MSC_VER) typedef signed char int8_t; typedef signed short int16_t; typedef signed int int32_t; typedef signed long long int64_t; typedef int64_t intmax_t; #if defined(_WIN64) typedef int64_t intptr_t; #else typedef int32_t intptr_t; #endif typedef unsigned char uint8_t; typedef unsigned short uint16_t; typedef unsigned int uint32_t; typedef unsigned long long uint64_t; typedef uint64_t uintmax_t; #if defined(_WIN64) typedef uint64_t uintptr_t; #else typedef uint32_t uintptr_t; #endif #else #include <stdint.h> #endif namespace nall_v059 { static nall_static_assert<sizeof(int8_t) == 1> int8_t_assert; static nall_static_assert<sizeof(int16_t) == 2> int16_t_assert; static nall_static_assert<sizeof(int32_t) == 4> int32_t_assert; static nall_static_assert<sizeof(int64_t) == 8> int64_t_assert; static nall_static_assert<sizeof(uint8_t) == 1> uint8_t_assert; static nall_static_assert<sizeof(uint16_t) == 2> uint16_t_assert; static nall_static_assert<sizeof(uint32_t) == 4> uint32_t_assert; static nall_static_assert<sizeof(uint64_t) == 8> uint64_t_assert; } #endif
27.266667
67
0.766911
werminghoff
8730f9e62be3c0b02dccd24f2b8c770f1db502d1
2,818
cpp
C++
pkg/pillar/vendor/github.com/anatol/smart.go/nvme_darwin.cpp
wahello/eve
fffc58c0a504ea26e1ad8b57832e205b8a390231
[ "Apache-2.0" ]
86
2022-02-09T17:30:43.000Z
2022-03-30T12:43:21.000Z
pkg/pillar/vendor/github.com/anatol/smart.go/nvme_darwin.cpp
wahello/eve
fffc58c0a504ea26e1ad8b57832e205b8a390231
[ "Apache-2.0" ]
3
2022-02-10T00:01:31.000Z
2022-02-19T01:18:13.000Z
pkg/pillar/vendor/github.com/anatol/smart.go/nvme_darwin.cpp
wahello/eve
fffc58c0a504ea26e1ad8b57832e205b8a390231
[ "Apache-2.0" ]
5
2022-02-09T23:44:27.000Z
2022-03-30T12:43:39.000Z
// SPDX-License-Identifier: MIT #include "nvme_darwin.h" #include <CoreFoundation/CoreFoundation.h> #include <IOKit/IOCFPlugIn.h> #include <IOKit/IOKitLib.h> #include <IOKit/storage/nvme/NVMeSMARTLibExternal.h> #include <stdlib.h> struct smart_nvme_darwin { IONVMeSMARTInterface **smartIfNVMe; IOCFPlugInInterface **plugin; io_object_t disk; }; static bool is_smart_capable(io_object_t dev) { CFTypeRef smartCapableKey = IORegistryEntryCreateCFProperty(dev, CFSTR(kIOPropertyNVMeSMARTCapableKey), kCFAllocatorDefault, 0); if (smartCapableKey) { CFRelease(smartCapableKey); return true; } return false; } // *path is a string that has a format like "disk0". unsigned int smart_nvme_open_darwin(const char *path, void **ptr) { // see also https://gist.github.com/AlanQuatermain/250538 SInt32 score = 0; int res = EINVAL; IONVMeSMARTInterface **smartIfNVMe; IOCFPlugInInterface **plugin; struct smart_nvme_darwin *nvme; CFMutableDictionaryRef matcher = IOBSDNameMatching(kIOMasterPortDefault, 0, path); io_object_t disk = IOServiceGetMatchingService(kIOMasterPortDefault, matcher); while (!is_smart_capable(disk)) { io_object_t prevdisk = disk; // Find this device's parent and try again. IOReturn err = IORegistryEntryGetParentEntry(disk, kIOServicePlane, &disk); if (err != kIOReturnSuccess || !disk) { IOObjectRelease(prevdisk); break; } } if (!disk) { printf("no disk found"); goto exit1; } res = IOCreatePlugInInterfaceForService(disk, kIONVMeSMARTUserClientTypeID, kIOCFPlugInInterfaceID, &plugin, &score); if (res != kIOReturnSuccess) goto exit2; res = (*plugin)->QueryInterface(plugin, CFUUIDGetUUIDBytes(kIONVMeSMARTInterfaceID), (void **)&smartIfNVMe); if (res != S_OK) goto exit3; *ptr = malloc(sizeof(struct smart_nvme_darwin)); nvme = (struct smart_nvme_darwin *)*ptr; nvme->disk = disk; nvme->plugin = plugin; nvme->smartIfNVMe = smartIfNVMe; return 0; exit3: IODestroyPlugInInterface(plugin); exit2: IOObjectRelease(disk); exit1: return res; } unsigned int smart_nvme_identify_darwin(void *ptr, void *buffer, unsigned int nsid) { struct smart_nvme_darwin *nvme = (struct smart_nvme_darwin *)ptr; return (*nvme->smartIfNVMe)->GetIdentifyData(nvme->smartIfNVMe, buffer, nsid); } unsigned int smart_nvme_readsmart_darwin(void *ptr, void *buffer) { struct smart_nvme_darwin *nvme = (struct smart_nvme_darwin *)ptr; return (*nvme->smartIfNVMe)->SMARTReadData(nvme->smartIfNVMe, (struct NVMeSMARTData *)buffer); } void smart_nvme_close_darwin(void *ptr) { struct smart_nvme_darwin *nvme = (struct smart_nvme_darwin *)ptr; (*nvme->smartIfNVMe)->Release(nvme->smartIfNVMe); IODestroyPlugInInterface(nvme->plugin); IOObjectRelease(nvme->disk); free(nvme); }
29.051546
130
0.741306
wahello
873646b8790f0941bf1ce610a1e5870593d719ac
602
cpp
C++
ModelViewer/UniformColorMap_Abaqus.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
null
null
null
ModelViewer/UniformColorMap_Abaqus.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
2
2020-10-19T02:03:11.000Z
2021-03-19T16:34:39.000Z
ModelViewer/UniformColorMap_Abaqus.cpp
COFS-UWA/MPM3D
1a0c5dc4e92dff3855367846002336ca5a18d124
[ "MIT" ]
1
2020-04-28T00:33:14.000Z
2020-04-28T00:33:14.000Z
#include "ModelViewer_pcp.h" #include "UniformColorMap_Abaqus.h" UniformColorMap_Abaqus::UniformColorMap_Abaqus() { unsigned char abaqus_color_map[][3] = { { 0, 0, 255 }, { 0, 93, 255 }, { 0, 185, 255 }, { 0, 255, 232 }, { 0, 255, 139 }, { 0, 255, 46 }, { 46, 255, 0 }, { 139, 255, 0 }, { 232, 255, 0 }, { 255, 185, 0 }, { 255, 93, 0 }, { 255, 0, 0 } }; size_t abaqus_color_num = sizeof(abaqus_color_map) / sizeof(abaqus_color_map[0]); set_color(abaqus_color_map, abaqus_color_num); } UniformColorMap_Abaqus::~UniformColorMap_Abaqus() {}
22.296296
82
0.58804
COFS-UWA
873ff515bbef697598acb4f7c9defed11472eb93
273
cpp
C++
Some_cpp_sols/A1467.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
Some_cpp_sols/A1467.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
Some_cpp_sols/A1467.cpp
Darknez07/Codeforces-sol
afd926c197f43784c12220430bb3c06011bb185e
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(){ int t,n,counter;cin>>t;while(t--){cin>>n;counter=0;for(int i=0;i<n;i++){if(i == 2 || i == 0){cout<<9;}if(i == 1){cout<<8;}if(i > 2){cout<<counter;counter = counter == 9 ? 0: counter + 1;}}cout<<"\n";} return 0; }
45.5
204
0.567766
Darknez07
8740058b7482430fa785a8635f2de62be14297d1
360
cc
C++
example/main.cc
baotiao/picdb
ca3d92f721796abb0620fdc7045465dd54ac6037
[ "MIT" ]
1
2016-09-13T09:18:06.000Z
2016-09-13T09:18:06.000Z
example/main.cc
baotiao/picdb
ca3d92f721796abb0620fdc7045465dd54ac6037
[ "MIT" ]
null
null
null
example/main.cc
baotiao/picdb
ca3d92f721796abb0620fdc7045465dd54ac6037
[ "MIT" ]
null
null
null
#include <stdio.h> #include <unistd.h> #include <linux/falloc.h> #include <fcntl.h> #include "xdebug.h" #include "include/db.h" #include "output/include/options.h" int main() { bitcask::Options op; bitcask::DB *db; db = NULL; bitcask::DB::Open(op, "./db", &db); // bitcask::WriteOptions wop; // db->Put(wop, "zz", "czzzz"); return 0; }
13.846154
37
0.613889
baotiao
87403295a119177bfdc6a356c9e15263d14c8b57
919
cpp
C++
image.ContourDetector/src/contour_detector.cpp
LALMAN2000/bnosa
d37e869c724736133b0ac1513a366817bb2dc5c1
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
243
2017-02-28T08:52:35.000Z
2022-03-10T16:54:48.000Z
image.ContourDetector/src/contour_detector.cpp
LALMAN2000/bnosa
d37e869c724736133b0ac1513a366817bb2dc5c1
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
25
2017-07-07T20:39:47.000Z
2022-03-15T11:38:14.000Z
image.ContourDetector/src/contour_detector.cpp
LALMAN2000/bnosa
d37e869c724736133b0ac1513a366817bb2dc5c1
[ "BSD-3-Clause", "BSD-2-Clause", "MIT" ]
59
2017-04-05T15:39:19.000Z
2021-11-08T13:49:08.000Z
#include <Rcpp.h> using namespace Rcpp; extern "C" { #include "smooth_contours.h" } // [[Rcpp::export]] List detect_contours(NumericVector image, int X, int Y, double Q = 2.0) { double * x; /* x[n] y[n] coordinates of result contour point n */ double * y; int * curve_limits; /* limits of the curves in the x[] and y[] */ int N,M; /* result: N contour points, forming M curves */ //double Q = 2.0; /* default Q=2 */ //double W = 1.3; /* PDF line width 1.3 */ smooth_contours(&x, &y, &N, &curve_limits, &M, image.begin(), X, Y, Q); NumericVector contour_x(N); for(int i = 0; i < N; i++) contour_x[i] = x[i]; NumericVector contour_y(N); for(int i = 0; i < N; i++) contour_y[i] = y[i]; NumericVector curvelimits(M); for(int i = 0; i < M; i++) curvelimits[i] = curve_limits[i]; List z = List::create(contour_x, contour_y, curvelimits, M, N); return z; }
27.848485
76
0.594124
LALMAN2000
8740dcda21663621496f7e9b256f762abe5015d3
3,211
cc
C++
DataFormats/MuonDetId/test/testRPCCompDetId.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
852
2015-01-11T21:03:51.000Z
2022-03-25T21:14:00.000Z
DataFormats/MuonDetId/test/testRPCCompDetId.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
30,371
2015-01-02T00:14:40.000Z
2022-03-31T23:26:05.000Z
DataFormats/MuonDetId/test/testRPCCompDetId.cc
ckamtsikis/cmssw
ea19fe642bb7537cbf58451dcf73aa5fd1b66250
[ "Apache-2.0" ]
3,240
2015-01-02T05:53:18.000Z
2022-03-31T17:24:21.000Z
/** \file test file for RPCCompDetId \author Stefano ARGIRO \date 27 Jul 2005 */ #include <cppunit/extensions/HelperMacros.h> #include <DataFormats/MuonDetId/interface/RPCCompDetId.h> #include <FWCore/Utilities/interface/Exception.h> #include <iostream> using namespace std; class testRPCCompDetId : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(testRPCCompDetId); CPPUNIT_TEST(testOne); CPPUNIT_TEST(testFail); CPPUNIT_TEST(testMemberOperators); CPPUNIT_TEST_SUITE_END(); public: void setUp() {} void tearDown() {} void testOne(); void testFail(); void testMemberOperators(); }; ///registration of the test so that the runner can find it CPPUNIT_TEST_SUITE_REGISTRATION(testRPCCompDetId); void testRPCCompDetId::testOne() { for (int region = RPCCompDetId::minRegionId; region <= RPCCompDetId::maxRegionId; ++region) { const int minRing(0 != region ? RPCCompDetId::minRingForwardId : RPCCompDetId::minRingBarrelId); const int maxRing(0 != region ? RPCCompDetId::maxRingForwardId : RPCCompDetId::maxRingBarrelId); const int minSector(0 != region ? RPCCompDetId::minSectorForwardId : RPCCompDetId::minSectorBarrelId); const int maxSector(0 != region ? RPCCompDetId::maxSectorForwardId : RPCCompDetId::maxSectorBarrelId); for (int ring = minRing; ring <= maxRing; ++ring) for (int station = RPCCompDetId::minStationId; station <= RPCCompDetId::maxStationId; ++station) for (int sector = minSector; sector <= maxSector; ++sector) for (int layer = RPCCompDetId::minLayerId; layer <= RPCCompDetId::maxLayerId; ++layer) for (int subSector = RPCCompDetId::minSubSectorId; subSector <= RPCCompDetId::maxSubSectorId; ++subSector) { RPCCompDetId detid(region, ring, station, sector, layer, subSector, 0); CPPUNIT_ASSERT(detid.region() == region); CPPUNIT_ASSERT(detid.ring() == ring); CPPUNIT_ASSERT(detid.station() == station); CPPUNIT_ASSERT(detid.sector() == sector); CPPUNIT_ASSERT(detid.layer() == layer); CPPUNIT_ASSERT(detid.subsector() == subSector); // test constructor from id int myId = detid.rawId(); RPCCompDetId anotherId(myId); CPPUNIT_ASSERT(detid == anotherId); } } } void testRPCCompDetId::testFail() { // contruct using an invalid input index try { // Station number too high RPCCompDetId detid(0, 1, 7, 2, 2, 1, 1); CPPUNIT_ASSERT("Failed to throw required exception" == 0); detid.rawId(); // avoid compiler warning } catch (cms::Exception& e) { // OK } catch (...) { CPPUNIT_ASSERT("Threw wrong kind of exception" == 0); } // contruct using an invalid input id try { RPCCompDetId detid(100); CPPUNIT_ASSERT("Failed to throw required exception" == 0); detid.rawId(); // avoid compiler warning } catch (cms::Exception& e) { // OK } catch (...) { CPPUNIT_ASSERT("Threw wrong kind of exception" == 0); } } void testRPCCompDetId::testMemberOperators() { RPCCompDetId unit1(0, -2, 1, 2, 2, 1, 1); RPCCompDetId unit2 = unit1; CPPUNIT_ASSERT(unit2 == unit1); }
34.159574
120
0.670196
ckamtsikis
874325ee04d2502492e247783c225fcbc6a4403e
3,369
hpp
C++
gears/meta/core.hpp
Rapptz/Gears
ce65bf135057939c19710286f772a874504efeb4
[ "MIT" ]
16
2015-01-18T13:40:22.000Z
2021-11-08T11:52:35.000Z
gears/meta/core.hpp
Rapptz/Gears
ce65bf135057939c19710286f772a874504efeb4
[ "MIT" ]
3
2015-01-17T01:23:26.000Z
2015-03-30T22:30:01.000Z
gears/meta/core.hpp
Rapptz/Gears
ce65bf135057939c19710286f772a874504efeb4
[ "MIT" ]
3
2017-10-21T05:42:58.000Z
2021-06-07T18:04:40.000Z
// The MIT License (MIT) // Copyright (c) 2012-2014 Danny Y., Rapptz // 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. #ifndef GEARS_META_CORE_HPP #define GEARS_META_CORE_HPP #include <type_traits> // macros for C++14 detection #ifndef GEARS_META_HAS_CPP14 #define GEARS_META_CLANG defined(__clang__) && ((__clang_major__ > 3) || (__clang_major__ == 3) && (__clang_minor__ >= 4)) #define GEARS_META_HAS_CPP14 GEARS_META_CLANG #endif namespace gears { namespace meta { /** * @ingroup meta * @brief Template alias for getting the type */ template<typename T> using eval = typename T::type; /** * @ingroup meta * @brief Template alias for `std::integral_constant`. */ template<typename T, T t> using constant = std::integral_constant<T, t>; /** * @ingroup meta * @brief Template alias for integer `std::integral_constant`. */ template<int i> using integer = constant<int, i>; /** * @ingroup meta * @brief Tag used to check if a type is deduced. */ struct deduced {}; /** * @ingroup meta * @brief Metafunction used to check if a type is the same as deduced. */ template<typename T> using is_deduced = std::is_same<T, deduced>; /** * @ingroup meta * @brief Identity meta function * @details The identity meta function. Typically * used for lazy evaluation or forced template parameter * evaluation. * */ template<typename T> struct identity { using type = T; }; /** * @ingroup meta * @brief Void meta function. * @details Void meta function. Used to swallow * arguments and evaluate to void. * */ template<typename...> struct void_ { using type = void; }; /** * @ingroup meta * @brief Template alias for void meta function. */ template<typename... T> using void_t = eval<void_<T...>>; /** * @ingroup meta * @brief Template alias for `std::integral_constant<bool, B>`. */ template<bool B> using boolean = constant<bool, B>; /** * @ingroup meta * @brief Removes all cv and ref qualifiers from a type. */ template<typename T> struct unqualified { using type = typename std::remove_cv<typename std::remove_reference<T>::type>::type; }; /** * @ingroup meta * @brief Template alias for `std::aligned_storage` with proper alignment. */ template<typename T> using storage_for = eval<std::aligned_storage<sizeof(T), std::alignment_of<T>::value>>; } // meta } // gears #endif // GEARS_META_CORE_HPP
26.320313
122
0.721282
Rapptz
8747ea64e5078cadc82e49c525d94acc7a012438
12,264
hpp
C++
include/VROSC/GarbageManager.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/GarbageManager.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
include/VROSC/GarbageManager.hpp
RedBrumbler/virtuoso-codegen
e83f6f0f9b47bec4b6dd976b21edc1d46bf3cfe3
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "beatsaber-hook/shared/utils/typedefs.h" #include "beatsaber-hook/shared/utils/byref.hpp" // Including type: UnityEngine.MonoBehaviour #include "UnityEngine/MonoBehaviour.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "beatsaber-hook/shared/utils/utils.h" #include "beatsaber-hook/shared/utils/typedefs-string.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: VROSC namespace VROSC { // Forward declaring type: Error struct Error; } // Completed forward declares // Type namespace: VROSC namespace VROSC { // Forward declaring type: GarbageManager class GarbageManager; } #include "beatsaber-hook/shared/utils/il2cpp-type-check.hpp" NEED_NO_BOX(::VROSC::GarbageManager); DEFINE_IL2CPP_ARG_TYPE(::VROSC::GarbageManager*, "VROSC", "GarbageManager"); // Type namespace: VROSC namespace VROSC { // Size: 0x19 #pragma pack(push, 1) // Autogenerated type: VROSC.GarbageManager // [TokenAttribute] Offset: FFFFFFFF class GarbageManager : public ::UnityEngine::MonoBehaviour { public: // Nested type: ::VROSC::GarbageManager::$DisableCollectionForSessionHandling$d__7 struct $DisableCollectionForSessionHandling$d__7; #ifdef USE_CODEGEN_FIELDS public: #else #ifdef CODEGEN_FIELD_ACCESSIBILITY CODEGEN_FIELD_ACCESSIBILITY: #else protected: #endif #endif // private System.Boolean _automaticCollectionEnabled // Size: 0x1 // Offset: 0x18 bool automaticCollectionEnabled; // Field size check static_assert(sizeof(bool) == 0x1); public: // Deleting conversion operator: operator ::System::IntPtr constexpr operator ::System::IntPtr() const noexcept = delete; // Get instance field reference: private System.Boolean _automaticCollectionEnabled bool& dyn__automaticCollectionEnabled(); // protected System.Void Awake() // Offset: 0x88FABC void Awake(); // protected System.Void OnDestroy() // Offset: 0x890008 void OnDestroy(); // protected System.Void Start() // Offset: 0x890554 void Start(); // private System.Void EnableAutomaticCollection(System.Boolean enable) // Offset: 0x890620 void EnableAutomaticCollection(bool enable); // public System.Void Collect() // Offset: 0x890584 void Collect(); // private System.Void EnableCollectionForSessionHandling() // Offset: 0x890668 void EnableCollectionForSessionHandling(); // private System.Void DisableCollectionForSessionHandling() // Offset: 0x89069C void DisableCollectionForSessionHandling(); // private System.Void RecorderSaveSucceeded() // Offset: 0x890760 void RecorderSaveSucceeded(); // private System.Void RecorderSaveFailed(VROSC.Error error) // Offset: 0x890764 void RecorderSaveFailed(::VROSC::Error error); // private System.Void SaveSucceeded(System.String sessionId) // Offset: 0x890768 void SaveSucceeded(::StringW sessionId); // private System.Void SaveFailed(System.String sessionId, VROSC.Error error) // Offset: 0x89076C void SaveFailed(::StringW sessionId, ::VROSC::Error error); // private System.Void LoadSucceeded(System.String sessionId, System.Boolean isDefaultSession) // Offset: 0x890770 void LoadSucceeded(::StringW sessionId, bool isDefaultSession); // private System.Void LoadFailed(System.String sessionId, System.Boolean isDefaultSession, VROSC.Error error) // Offset: 0x890774 void LoadFailed(::StringW sessionId, bool isDefaultSession, ::VROSC::Error error); // public System.Void .ctor() // Offset: 0x890778 // Implemented from: UnityEngine.MonoBehaviour // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> static GarbageManager* New_ctor() { static auto ___internal__logger = ::Logger::get().WithContext("::VROSC::GarbageManager::.ctor"); return THROW_UNLESS((::il2cpp_utils::New<GarbageManager*, creationType>())); } }; // VROSC.GarbageManager #pragma pack(pop) static check_size<sizeof(GarbageManager), 24 + sizeof(bool)> __VROSC_GarbageManagerSizeCheck; static_assert(sizeof(GarbageManager) == 0x19); } #include "beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: VROSC::GarbageManager::Awake // Il2CppName: Awake template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::Awake)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "Awake", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::OnDestroy // Il2CppName: OnDestroy template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::OnDestroy)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "OnDestroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::Start // Il2CppName: Start template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::Start)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "Start", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::EnableAutomaticCollection // Il2CppName: EnableAutomaticCollection template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(bool)>(&VROSC::GarbageManager::EnableAutomaticCollection)> { static const MethodInfo* get() { static auto* enable = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "EnableAutomaticCollection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{enable}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::Collect // Il2CppName: Collect template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::Collect)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "Collect", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::EnableCollectionForSessionHandling // Il2CppName: EnableCollectionForSessionHandling template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::EnableCollectionForSessionHandling)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "EnableCollectionForSessionHandling", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::DisableCollectionForSessionHandling // Il2CppName: DisableCollectionForSessionHandling template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::DisableCollectionForSessionHandling)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "DisableCollectionForSessionHandling", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::RecorderSaveSucceeded // Il2CppName: RecorderSaveSucceeded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)()>(&VROSC::GarbageManager::RecorderSaveSucceeded)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "RecorderSaveSucceeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::RecorderSaveFailed // Il2CppName: RecorderSaveFailed template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::VROSC::Error)>(&VROSC::GarbageManager::RecorderSaveFailed)> { static const MethodInfo* get() { static auto* error = &::il2cpp_utils::GetClassFromName("VROSC", "Error")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "RecorderSaveFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{error}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::SaveSucceeded // Il2CppName: SaveSucceeded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW)>(&VROSC::GarbageManager::SaveSucceeded)> { static const MethodInfo* get() { static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "SaveSucceeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::SaveFailed // Il2CppName: SaveFailed template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW, ::VROSC::Error)>(&VROSC::GarbageManager::SaveFailed)> { static const MethodInfo* get() { static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* error = &::il2cpp_utils::GetClassFromName("VROSC", "Error")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "SaveFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, error}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::LoadSucceeded // Il2CppName: LoadSucceeded template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW, bool)>(&VROSC::GarbageManager::LoadSucceeded)> { static const MethodInfo* get() { static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* isDefaultSession = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "LoadSucceeded", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, isDefaultSession}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::LoadFailed // Il2CppName: LoadFailed template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (VROSC::GarbageManager::*)(::StringW, bool, ::VROSC::Error)>(&VROSC::GarbageManager::LoadFailed)> { static const MethodInfo* get() { static auto* sessionId = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg; static auto* isDefaultSession = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg; static auto* error = &::il2cpp_utils::GetClassFromName("VROSC", "Error")->byval_arg; return ::il2cpp_utils::FindMethod(classof(VROSC::GarbageManager*), "LoadFailed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{sessionId, isDefaultSession, error}); } }; // Writing MetadataGetter for method: VROSC::GarbageManager::New_ctor // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
51.746835
184
0.740868
RedBrumbler