hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3b9027e84e808aa0513dd18b0f066437ed41c0c9 | 4,364 | cpp | C++ | src/kernel/os.cpp | justinc1/IncludeOS | 2ce07b04e7a35c8d96e773f041db32a4593ca3d0 | [
"Apache-2.0"
] | null | null | null | src/kernel/os.cpp | justinc1/IncludeOS | 2ce07b04e7a35c8d96e773f041db32a4593ca3d0 | [
"Apache-2.0"
] | null | null | null | src/kernel/os.cpp | justinc1/IncludeOS | 2ce07b04e7a35c8d96e773f041db32a4593ca3d0 | [
"Apache-2.0"
] | null | null | null | // This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//#define DEBUG
#define MYINFO(X,...) INFO("Kernel", X, ##__VA_ARGS__)
#include <kernel/os.hpp>
#include <kernel/rng.hpp>
#include <service>
#include <cstdio>
#include <cinttypes>
#include <util/fixed_vector.hpp>
//#define ENABLE_PROFILERS
#ifdef ENABLE_PROFILERS
#include <profile>
#define PROFILE(name) ScopedProfiler __CONCAT(sp, __COUNTER__){name};
#else
#define PROFILE(name) /* name */
#endif
extern "C" void* get_cpu_esp();
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
extern uintptr_t _start;
extern uintptr_t _end;
extern uintptr_t _ELF_START_;
extern uintptr_t _TEXT_START_;
extern uintptr_t _LOAD_START_;
extern uintptr_t _ELF_END_;
// Initialize static OS data members
bool OS::power_ = true;
bool OS::boot_sequence_passed_ = false;
bool OS::m_is_live_updated = false;
bool OS::m_block_drivers_ready = false;
KHz OS::cpu_khz_ {-1};
uintptr_t OS::liveupdate_loc_ = 0;
uintptr_t OS::memory_end_ = 0;
uintptr_t OS::heap_max_ = (uintptr_t) -1;
const uintptr_t OS::elf_binary_size_ {(uintptr_t)&_ELF_END_ - (uintptr_t)&_ELF_START_};
// stdout redirection
using Print_vec = Fixed_vector<OS::print_func, 8>;
static Print_vec os_print_handlers(Fixedvector_Init::UNINIT);
// Plugins
struct Plugin_desc {
Plugin_desc(OS::Plugin f, const char* n) : func{f}, name{n} {}
OS::Plugin func;
const char* name;
};
static Fixed_vector<Plugin_desc, 16> plugins(Fixedvector_Init::UNINIT);
// OS version
std::string OS::version_str_ = OS_VERSION;
std::string OS::arch_str_ = ARCH;
void* OS::liveupdate_storage_area() noexcept
{
return (void*) OS::liveupdate_loc_;
}
const char* OS::cmdline = nullptr;
const char* OS::cmdline_args() noexcept {
return cmdline;
}
void OS::register_plugin(Plugin delg, const char* name){
MYINFO("Registering plugin %s", name);
plugins.emplace_back(delg, name);
}
void OS::reboot()
{
extern void __arch_reboot();
__arch_reboot();
}
void OS::shutdown()
{
MYINFO("Soft shutdown signalled");
power_ = false;
}
void OS::post_start()
{
// if the LiveUpdate storage area is not yet determined,
// we can assume its a fresh boot, so calculate new one based on ...
if (OS::liveupdate_loc_ == 0)
{
// default size is 1/4 of heap from the end of memory
auto size = OS::heap_max() / 4;
OS::liveupdate_loc_ = (OS::heap_max() - size) & 0xFFFFFFF0;
}
MYINFO("Initializing RNG");
PROFILE("RNG init");
RNG::init();
// Seed rand with 32 bits from RNG
srand(rng_extract_uint32());
// Custom initialization functions
MYINFO("Initializing plugins");
// the boot sequence is over when we get to plugins/Service::start
OS::boot_sequence_passed_ = true;
PROFILE("Plugins init");
for (auto plugin : plugins) {
INFO2("* Initializing %s", plugin.name);
try {
plugin.func();
} catch(std::exception& e){
MYINFO("Exception thrown when initializing plugin: %s", e.what());
} catch(...){
MYINFO("Unknown exception when initializing plugin");
}
}
PROFILE("Service::start");
// begin service start
FILLINE('=');
printf(" IncludeOS %s (%s / %i-bit)\n",
version().c_str(), arch().c_str(),
static_cast<int>(sizeof(uintptr_t)) * 8);
printf(" +--> Running [ %s ]\n", Service::name());
FILLINE('~');
Service::start();
}
void OS::add_stdout(OS::print_func func)
{
os_print_handlers.push_back(func);
}
__attribute__((weak))
bool os_enable_boot_logging = false;
void OS::print(const char* str, const size_t len)
{
for (auto& callback : os_print_handlers) {
if (os_enable_boot_logging || OS::is_booted() || OS::is_panicking())
callback(str, len);
}
}
| 27.275 | 87 | 0.702796 | justinc1 |
3b97ac6c3bf82e29620f29be6892e404d66a2a79 | 656 | cpp | C++ | Pbinfo/Cifre4.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | 7 | 2019-01-06T19:10:14.000Z | 2021-10-16T06:41:23.000Z | Pbinfo/Cifre4.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | null | null | null | Pbinfo/Cifre4.cpp | Al3x76/cpp | 08a0977d777e63e0d36d87fcdea777de154697b7 | [
"MIT"
] | 6 | 2019-01-06T19:17:30.000Z | 2020-02-12T22:29:17.000Z | #include <iostream>
using namespace std;
void sortare(int n, int a[], int b[]){
for(int i=0; i<n; i++)
for(int j=i; j<=n; j++){
if(b[i]>b[j]){
swap(a[i], a[j]);
swap(b[i], b[j]);
}
else if(b[i]==b[j] && a[i]>a[j]) swap(a[i], a[j]);
}
}
int fr[10];
int main(){
int nr[10], n, x;
cin>>n;
for(int i=1; i<=n; i++){
cin>>x;
while(x){
fr[x%10]++;
x/=10;
}
}
for(int i=0; i<=9; i++) nr[i]=i;
sortare(9, nr, fr);
for(int i=0; i<=9; i++)
if(fr[i]) cout<<nr[i]<<" ";
return 0;
} | 16 | 62 | 0.356707 | Al3x76 |
3b998dcf30bdf1043fcee76236d2c2bc85631cb9 | 693 | cc | C++ | src/ui.cc | rfdickerson/Hodhr | 261ee0fc96c203487a428b8cf82550615eef7c43 | [
"MIT"
] | null | null | null | src/ui.cc | rfdickerson/Hodhr | 261ee0fc96c203487a428b8cf82550615eef7c43 | [
"MIT"
] | null | null | null | src/ui.cc | rfdickerson/Hodhr | 261ee0fc96c203487a428b8cf82550615eef7c43 | [
"MIT"
] | null | null | null | // Copyright Robert Dickerson 2014
# <memory>
# <utility>
# <vector>
# "include/common.h"
# "include/ui.h"
# "include/uiwidget.h"
namespace Hodhr {
UI::UI() {}
UI::UI(unsigned int width, unsigned int height) {
this->width_ = width;
this->height_ = height;
}
UI::~UI() {
}
void UI::addWidget(std::unique_ptr<UIWidget> widget) {
widgets_.push_back(std::move(widget));
fprintf(stderr, "Adding widget to UI, total widgets is %ld\n",
widgets_.size());
}
void UI::draw() {
for (unsigned int index = 0; index < widgets_.size(); ++index) {
widgets_[index]->draw();
widgets_[index]->update();
}
}
} // namespace Hodhr
| 18.72973 | 68 | 0.591631 | rfdickerson |
3b9fef178cd33e0eccc8c75a1dfc803a0dd6efd4 | 1,974 | cpp | C++ | topcoder/srm/src/SRM622/FibonacciDiv2.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | topcoder/srm/src/SRM622/FibonacciDiv2.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | 19 | 2016-05-04T02:46:31.000Z | 2021-11-27T06:18:33.000Z | topcoder/srm/src/SRM622/FibonacciDiv2.cpp | Johniel/contests | b692eff913c20e2c1eb4ff0ce3cd4c57900594e0 | [
"Unlicense"
] | null | null | null | #include <bits/stdc++.h>
#define each(i, c) for (auto& i : c)
#define unless(cond) if (!(cond))
using namespace std;
typedef long long int lli;
typedef unsigned long long ull;
typedef complex<double> point;
class FibonacciDiv2 {
public:
int find(int N)
{
const int M = 10000;
lli f[M];
f[0] = 0;
f[1] = 1;
for (int i = 2; i < M; ++i) {
f[i] = f[i - 1] + f[i - 2];
}
int mn = 1 << 28;
for (int i = 0; i < M; ++i) {
mn = min<lli>(mn, abs(f[i] - N));
if (N <= f[i]) break;
}
return mn;
}
// BEGIN CUT HERE
public:
void run_test(int Case) { if ((Case == -1) || (Case == 0)) test_case_0(); if ((Case == -1) || (Case == 1)) test_case_1(); if ((Case == -1) || (Case == 2)) test_case_2(); if ((Case == -1) || (Case == 3)) test_case_3(); if ((Case == -1) || (Case == 4)) test_case_4(); }
private:
template <typename T> string print_array(const vector<T> &V) { ostringstream os; os << "{ "; for (typename vector<T>::const_iterator iter = V.begin(); iter != V.end(); ++iter) os << '\"' << *iter << "\","; os << " }"; return os.str(); }
void verify_case(int Case, const int &Expected, const int &Received) { cerr << "Test Case #" << Case << "..."; if (Expected == Received) cerr << "PASSED" << endl; else { cerr << "FAILED" << endl; cerr << "\tExpected: \"" << Expected << '\"' << endl; cerr << "\tReceived: \"" << Received << '\"' << endl; } }
void test_case_0() { int Arg0 = 1; int Arg1 = 0; verify_case(0, Arg1, find(Arg0)); }
void test_case_1() { int Arg0 = 13; int Arg1 = 0; verify_case(1, Arg1, find(Arg0)); }
void test_case_2() { int Arg0 = 15; int Arg1 = 2; verify_case(2, Arg1, find(Arg0)); }
void test_case_3() { int Arg0 = 19; int Arg1 = 2; verify_case(3, Arg1, find(Arg0)); }
void test_case_4() { int Arg0 = 1000000; int Arg1 = 167960; verify_case(4, Arg1, find(Arg0)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main() {
FibonacciDiv2 ___test;
___test.run_test(-1);
}
// END CUT HERE
| 35.25 | 308 | 0.56231 | Johniel |
3ba2c813ebaf581f07e6f8c104775d26d78dce86 | 536 | cpp | C++ | URI/Ad-Hoc/1574.cpp | danielcunhaa/Competitive-Programming | 6868a8dfb8000fd10650a692c548a86272f19735 | [
"MIT"
] | 1 | 2021-04-03T11:17:33.000Z | 2021-04-03T11:17:33.000Z | URI/Ad-Hoc/1574.cpp | danielcunhaa/Competitive-Programming | 6868a8dfb8000fd10650a692c548a86272f19735 | [
"MIT"
] | null | null | null | URI/Ad-Hoc/1574.cpp | danielcunhaa/Competitive-Programming | 6868a8dfb8000fd10650a692c548a86272f19735 | [
"MIT"
] | 1 | 2020-07-24T15:27:46.000Z | 2020-07-24T15:27:46.000Z | #include <iostream>
#include <cstdio>
#include <vector>
using std::cin;
using std::cout;
using std::string;
int main()
{
int T, N, p, i;
string tmp;
scanf("%d", &T);
while(T--)
{
std::vector<int> v;
p = 0;
scanf("%d", &N);
cin.ignore();
while(N--)
{
cin >> tmp;
if(tmp == "LEFT")
{
--p;
v.push_back(-1);
}
else if(tmp == "RIGHT")
{
++p;
v.push_back(1);
}
else
{
cin >> tmp >> i;
p += v[i-1];
v.push_back(v[i-1]);
}
}
printf("%d\n", p);
}
return 0;
} | 11.404255 | 26 | 0.462687 | danielcunhaa |
3bac9edd3e207204994f707fa60dac9cc7eec706 | 3,757 | cpp | C++ | Homework3/BehaviorSimFramework/src/MainFrm.cpp | Zenologos/IDS6938-SimulationTechniques | b3630852b2edb3ec4e176b26f0de56b77b460a2a | [
"Apache-2.0"
] | null | null | null | Homework3/BehaviorSimFramework/src/MainFrm.cpp | Zenologos/IDS6938-SimulationTechniques | b3630852b2edb3ec4e176b26f0de56b77b460a2a | [
"Apache-2.0"
] | null | null | null | Homework3/BehaviorSimFramework/src/MainFrm.cpp | Zenologos/IDS6938-SimulationTechniques | b3630852b2edb3ec4e176b26f0de56b77b460a2a | [
"Apache-2.0"
] | null | null | null | // MainFrm.cpp : implementation of the CMainFrame class
//
#include "stdafx.h"
#include "Behavior.h"
#include "MainFrm.h"
#include "BehaviorView.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
#define PanelWidth 255
/////////////////////////////////////////////////////////////////////////////
// CMainFrame
IMPLEMENT_DYNCREATE(CMainFrame, CFrameWnd)
BEGIN_MESSAGE_MAP(CMainFrame, CFrameWnd)
//{{AFX_MSG_MAP(CMainFrame)
ON_WM_CREATE()
ON_WM_SIZE()
ON_WM_TIMER()
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
static UINT indicators[] =
{
ID_SEPARATOR, // status line indicator
ID_INDICATOR_CAPS,
ID_INDICATOR_NUM,
ID_INDICATOR_SCRL,
};
/////////////////////////////////////////////////////////////////////////////
// CMainFrame construction/destruction
CMainFrame::CMainFrame()
{
// TODO: add member initialization code here
SplitterReady = false;
}
CMainFrame::~CMainFrame()
{
}
int CMainFrame::OnCreate(LPCREATESTRUCT lpCreateStruct)
{
if (CFrameWnd::OnCreate(lpCreateStruct) == -1)
return -1;
/*
if (!m_wndToolBar.CreateEx(this, TBSTYLE_FLAT, WS_CHILD | WS_VISIBLE | CBRS_TOP
| CBRS_GRIPPER | CBRS_TOOLTIPS | CBRS_FLYBY | CBRS_SIZE_DYNAMIC) ||
!m_wndToolBar.LoadToolBar(IDR_MAINFRAME))
{
TRACE0("Failed to create toolbar\n");
return -1; // fail to create
}*/
if (!m_wndStatusBar.Create(this) ||
!m_wndStatusBar.SetIndicators(indicators,
sizeof(indicators)/sizeof(UINT)))
{
TRACE0("Failed to create status bar\n");
return -1; // fail to create
}
// TODO: Delete these three lines if you don't want the toolbar to
// be dockable
/*
m_wndToolBar.EnableDocking(CBRS_ALIGN_ANY);
EnableDocking(CBRS_ALIGN_ANY);
DockControlBar(&m_wndToolBar);*/
return 0;
}
BOOL CMainFrame::PreCreateWindow(CREATESTRUCT& cs)
{
if( !CFrameWnd::PreCreateWindow(cs) )
return FALSE;
// TODO: Modify the Window class or styles here by modifying
// the CREATESTRUCT cs
return TRUE;
}
/////////////////////////////////////////////////////////////////////////////
// CMainFrame diagnostics
#ifdef _DEBUG
void CMainFrame::AssertValid() const
{
CFrameWnd::AssertValid();
}
void CMainFrame::Dump(CDumpContext& dc) const
{
CFrameWnd::Dump(dc);
}
#endif //_DEBUG
/////////////////////////////////////////////////////////////////////////////
// CMainFrame message handlers
BOOL CMainFrame::OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext)
{
// TODO: Add your specialized code here and/or call the base class
CRect cr;
GetClientRect(&cr);
if(!m_Splitter.CreateStatic(this, 1, 2)){
MessageBox( "Error setting up splitter frames!",
"Init Error!", MB_OK | MB_ICONERROR );
return false;
}
if (!m_Splitter.CreateView(0,0, RUNTIME_CLASS(CBehaviorView),CSize(cr.Width() - PanelWidth, cr.Height()), pContext)){
MessageBox( "Error setting up splitter frames!",
"Init Error!", MB_OK | MB_ICONERROR );
return false;
}
if (!m_Splitter.CreateView(0,1, RUNTIME_CLASS(CPanel),CSize(PanelWidth, cr.Height()), pContext)){
MessageBox( "Error setting up splitter frames!",
"Init Error!", MB_OK | MB_ICONERROR );
return false;
}
pView = (CBehaviorView*)m_Splitter.GetPane(0,0);
pPanel = (CPanel*)m_Splitter.GetPane(0,1);
pPanel->GetSimulation(&(pView->sim));
SplitterReady = true;
return true;
//return CFrameWnd::OnCreateClient(lpcs, pContext);
}
void CMainFrame::OnSize(UINT nType, int cx, int cy)
{
CFrameWnd::OnSize(nType, cx, cy);
// TODO: Add your message handler code here
if ( SplitterReady && nType != SIZE_MINIMIZED )
{
if(cx - PanelWidth > 0){
m_Splitter.SetColumnInfo( 0, cx - PanelWidth, 0);
m_Splitter.SetColumnInfo( 1, PanelWidth, 0);
m_Splitter.RecalcLayout();
}
}
}
| 23.778481 | 118 | 0.656375 | Zenologos |
3bacf72cec810dac1550092f9731888c45627ba4 | 1,322 | cpp | C++ | IME Starters Try-outs 2018/G-Greatest IME.cpp | Sohieeb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | 1 | 2020-01-30T20:08:24.000Z | 2020-01-30T20:08:24.000Z | IME Starters Try-outs 2018/G-Greatest IME.cpp | Sohieb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | null | null | null | IME Starters Try-outs 2018/G-Greatest IME.cpp | Sohieb/competitive-programming | fe3fca0d4d2a242053d097c7ae71667a135cfc45 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
using namespace __gnu_cxx;
typedef double db;
typedef long long ll;
typedef pair<db, db> pdd;
typedef pair<ll, ll> pll;
typedef pair<int, int> pii;
typedef unsigned long long ull;
#define F first
#define S second
#define pnl printf("\n")
#define sz(x) (int)x.size()
#define sf(x) scanf("%d",&x)
#define pf(x) printf("%d\n",x)
#define all(x) x.begin(),x.end()
#define rall(x) x.rbegin(),x.rend()
#define rep(i, n) for(int i = 0; i < n; ++i)
const db eps = 1e-9;
const db pi = acos(-1);
const int INF = 0x3f3f3f3f;
const ll LL_INF = 0x3f3f3f3f3f3f3f3f;
const int mod = 1000 * 1000 * 1000 + 7;
int n, c;
int fac[300005];
int pwr(int base ,int pw) {
int ans = 1;
while (pw) {
if (pw % 2) ans = ans * 1LL * base % mod;
base = base * 1LL * base % mod;
pw /= 2;
}
return ans;
}
int nCr(int N, int R) {
return (fac[N] * 1LL * pwr((fac[R] * 1LL * fac[N - R]) % mod, mod - 2) % mod);
}
int main() {
fac[0] = 1;
for (int i = 1; i < 300005; ++i)
fac[i] = (fac[i - 1] * 1LL * i) % mod;
cin >> n >> c;
int N = n + c - 3 * n;
int res = nCr(N, n);
res = res * 1LL * fac[n] % mod;
res = res * 1LL * pwr(6, n) % mod;
cout << res << endl;
return 0;
}
| 22.793103 | 82 | 0.530257 | Sohieeb |
3bb0d9bf02ab1c70f8dbf03eba031bab2438ab04 | 1,429 | cpp | C++ | src/Events/Mouse.cpp | apodrugin/Sourcehold | c18c134eda7a9cf8efe55d8f780439e1b2a4c9aa | [
"MIT"
] | null | null | null | src/Events/Mouse.cpp | apodrugin/Sourcehold | c18c134eda7a9cf8efe55d8f780439e1b2a4c9aa | [
"MIT"
] | null | null | null | src/Events/Mouse.cpp | apodrugin/Sourcehold | c18c134eda7a9cf8efe55d8f780439e1b2a4c9aa | [
"MIT"
] | null | null | null | #include "Events/Mouse.h"
using namespace Sourcehold::Events;
Mouse::Mouse()
{
}
Mouse::~Mouse()
{
}
bool Mouse::LmbDown()
{
if(event.button.state == SDL_PRESSED && event.button.button == SDL_BUTTON_LEFT) return true;
return false;
}
bool Mouse::MmbDown()
{
if(event.button.state == SDL_PRESSED && event.button.button == SDL_BUTTON_MIDDLE) return true;
return false;
}
bool Mouse::RmbDown()
{
if(event.button.state == SDL_PRESSED && event.button.button == SDL_BUTTON_RIGHT) return true;
return false;
}
bool Mouse::LmbUp()
{
if(event.button.state == SDL_RELEASED && event.button.button == SDL_BUTTON_LEFT) return true;
return false;
}
bool Mouse::MmbUp()
{
if(event.button.state == SDL_RELEASED && event.button.button == SDL_BUTTON_MIDDLE) return true;
return false;
}
bool Mouse::RmbUp()
{
if(event.button.state == SDL_RELEASED && event.button.button == SDL_BUTTON_RIGHT) return true;
return false;
}
uint32_t Mouse::GetPosX()
{
return event.motion.x;
}
uint32_t Mouse::GetPosY()
{
return event.motion.y;
}
EventType Mouse::GetType()
{
return type;
}
void Mouse::eventCallback(SDL_Event &event)
{
this->event = event;
Event::SetHandled(true);
type = ConvertTypes(event.type);
if(
type == MOTION ||
type == BUTTONDOWN ||
type == BUTTONUP ||
type == WHEEL
) {
Event::SetHandled(false);
}
}
| 17.641975 | 99 | 0.649405 | apodrugin |
3bb82e8ccfcf489a410625500805f375e6d2ce52 | 2,428 | cpp | C++ | src/shader.cpp | Sirflankalot/Bomberman | 7f2fa5cf657672e070e8850233c9a36a0b480b2f | [
"Apache-2.0"
] | null | null | null | src/shader.cpp | Sirflankalot/Bomberman | 7f2fa5cf657672e070e8850233c9a36a0b480b2f | [
"Apache-2.0"
] | null | null | null | src/shader.cpp | Sirflankalot/Bomberman | 7f2fa5cf657672e070e8850233c9a36a0b480b2f | [
"Apache-2.0"
] | null | null | null | #include <GL/glew.h>
#include "shader.hpp"
#include "util.hpp"
#include <exception>
#include <iostream>
#include <sstream>
Shader_Program::Shader_Program() {
this->program = glCreateProgram();
}
void Shader_Program::add(const char* filename, Shader::shadertype_t type) {
GLenum new_type = 0;
switch (type) {
case Shader::VERTEX:
new_type = GL_VERTEX_SHADER;
break;
case Shader::GEOMETRY:
new_type = GL_GEOMETRY_SHADER;
break;
case Shader::TESS_C:
new_type = GL_TESS_CONTROL_SHADER;
break;
case Shader::TESS_E:
new_type = GL_TESS_EVALUATION_SHADER;
break;
case Shader::FRAGMENT:
new_type = GL_FRAGMENT_SHADER;
break;
case Shader::COMPUTE:
new_type = GL_COMPUTE_SHADER;
break;
default:
break;
}
this->add(filename, new_type);
}
void Shader_Program::add(const char* filename, GLenum type) {
std::string code = file_contents(filename);
const char* code_ptr = code.c_str();
GLuint ident;
ident = glCreateShader(type);
glShaderSource(ident, 1, &code_ptr, NULL);
shaders.push_back(ident);
}
void Shader_Program::compile() {
for (GLuint s : shaders) {
glCompileShader(s);
GLint success;
glGetShaderiv(s, GL_COMPILE_STATUS, &success);
if (!success) {
GLchar infoLog[1024];
glGetShaderInfoLog(s, sizeof(infoLog), NULL, infoLog);
std::cerr << "Shader compilation failed:\n" << infoLog << '\n';
throw std::runtime_error("Shader compilation failed.");
}
}
}
void Shader_Program::link() {
for (GLuint s : shaders) {
glAttachShader(this->program, s);
}
glLinkProgram(this->program);
GLint success;
glGetProgramiv(this->program, GL_LINK_STATUS, &success);
if (!success) {
GLchar infoLog[1024];
glGetProgramInfoLog(this->program, sizeof(infoLog), NULL, infoLog);
std::cerr << "Shader program linking failed:\n" << infoLog << '\n';
throw std::runtime_error("Shader program linking failed.");
}
for (GLuint s : shaders) {
glDeleteShader(s);
}
shaders.clear();
}
void Shader_Program::use() {
glUseProgram(this->program);
}
GLuint Shader_Program::getUniform(const char* uniform_name, Shader::throwonfail_t should_throw) {
GLint name = glGetUniformLocation(program, uniform_name);
if (name == -1 && should_throw) {
std::ostringstream err_str;
err_str << "Can't find uniform named " << uniform_name << ".\n";
std::cerr << err_str.str() << '\n';
throw std::runtime_error(err_str.str().c_str());
}
return name;
}
| 23.12381 | 97 | 0.697282 | Sirflankalot |
3bb8eddd3363495b44f89ed84c03525240d0634e | 6,416 | cpp | C++ | communication/decoder.cpp | tysonite/libicsneo | 2a47b6f179699f67dc8c39634ea245c49b02ec0f | [
"BSD-3-Clause"
] | null | null | null | communication/decoder.cpp | tysonite/libicsneo | 2a47b6f179699f67dc8c39634ea245c49b02ec0f | [
"BSD-3-Clause"
] | null | null | null | communication/decoder.cpp | tysonite/libicsneo | 2a47b6f179699f67dc8c39634ea245c49b02ec0f | [
"BSD-3-Clause"
] | null | null | null | #include "icsneo/communication/decoder.h"
#include "icsneo/communication/communication.h"
#include "icsneo/communication/message/serialnumbermessage.h"
#include "icsneo/communication/message/resetstatusmessage.h"
#include "icsneo/communication/message/readsettingsmessage.h"
#include "icsneo/communication/command.h"
#include "icsneo/device/device.h"
#include "icsneo/communication/packet/canpacket.h"
#include "icsneo/communication/packet/ethernetpacket.h"
#include <iostream>
using namespace icsneo;
uint64_t Decoder::GetUInt64FromLEBytes(uint8_t* bytes) {
uint64_t ret = 0;
for(int i = 0; i < 8; i++)
ret |= (bytes[i] << (i * 8));
return ret;
}
bool Decoder::decode(std::shared_ptr<Message>& result, const std::shared_ptr<Packet>& packet) {
switch(packet->network.getType()) {
case Network::Type::Ethernet:
result = HardwareEthernetPacket::DecodeToMessage(packet->data);
if(!result)
return false; // A nullptr was returned, the packet was not long enough to decode
// Timestamps are in (resolution) ns increments since 1/1/2007 GMT 00:00:00.0000
// The resolution depends on the device
result->timestamp *= timestampResolution;
result->network = packet->network;
return true;
case Network::Type::CAN:
case Network::Type::SWCAN:
case Network::Type::LSFTCAN: {
if(packet->data.size() < 24)
return false;
result = HardwareCANPacket::DecodeToMessage(packet->data);
if(!result)
return false; // A nullptr was returned, the packet was malformed
// Timestamps are in (resolution) ns increments since 1/1/2007 GMT 00:00:00.0000
// The resolution depends on the device
result->timestamp *= timestampResolution;
result->network = packet->network;
return true;
}
case Network::Type::Internal: {
switch(packet->network.getNetID()) {
case Network::NetID::Reset_Status: {
if(packet->data.size() < sizeof(HardwareResetStatusPacket))
return false;
HardwareResetStatusPacket* data = (HardwareResetStatusPacket*)packet->data.data();
auto msg = std::make_shared<ResetStatusMessage>();
msg->network = packet->network;
msg->mainLoopTime = data->main_loop_time_25ns * 25;
msg->maxMainLoopTime = data->max_main_loop_time_25ns * 25;
msg->busVoltage = data->busVoltage;
msg->deviceTemperature = data->deviceTemperature;
msg->justReset = data->status.just_reset;
msg->comEnabled = data->status.com_enabled;
msg->cmRunning = data->status.cm_is_running;
msg->cmChecksumFailed = data->status.cm_checksum_failed;
msg->cmLicenseFailed = data->status.cm_license_failed;
msg->cmVersionMismatch = data->status.cm_version_mismatch;
msg->cmBootOff = data->status.cm_boot_off;
msg->hardwareFailure = data->status.hardware_failure;
msg->usbComEnabled = data->status.usbComEnabled;
msg->linuxComEnabled = data->status.linuxComEnabled;
msg->cmTooBig = data->status.cm_too_big;
msg->hidUsbState = data->status.hidUsbState;
msg->fpgaUsbState = data->status.fpgaUsbState;
result = msg;
return true;
}
default:
break;//return false;
}
}
default:
switch(packet->network.getNetID()) {
case Network::NetID::Main51: {
switch((Command)packet->data[0]) {
case Command::RequestSerialNumber: {
auto msg = std::make_shared<SerialNumberMessage>();
msg->network = packet->network;
uint64_t serial = GetUInt64FromLEBytes(packet->data.data() + 1);
// The device sends 64-bits of serial number, but we never use more than 32-bits.
msg->deviceSerial = Device::SerialNumToString((uint32_t)serial);
msg->hasMacAddress = packet->data.size() >= 15;
if(msg->hasMacAddress)
memcpy(msg->macAddress, packet->data.data() + 9, sizeof(msg->macAddress));
msg->hasPCBSerial = packet->data.size() >= 31;
if(msg->hasPCBSerial)
memcpy(msg->pcbSerial, packet->data.data() + 15, sizeof(msg->pcbSerial));
result = msg;
return true;
}
default:
auto msg = std::make_shared<Main51Message>();
msg->network = packet->network;
msg->command = Command(packet->data[0]);
msg->data.insert(msg->data.begin(), packet->data.begin() + 1, packet->data.end());
result = msg;
return true;
}
}
case Network::NetID::RED_OLDFORMAT: {
/* So-called "old format" messages are a "new style, long format" wrapper around the old short messages.
* They consist of a 16-bit LE length first, then the 8-bit length and netid combo byte, then the payload
* with no checksum. The upper-nibble length of the combo byte should be ignored completely, using the
* length from the first two bytes in it's place. Ideally, we never actually send the oldformat messages
* out to the rest of the application as they can recursively get decoded to another message type here.
* Feed the result back into the decoder in case we do something special with the resultant netid.
*/
uint16_t length = packet->data[0] | (packet->data[1] << 8);
packet->network = Network(packet->data[2] & 0xF);
packet->data.erase(packet->data.begin(), packet->data.begin() + 3);
if(packet->data.size() != length)
packet->data.resize(length);
return decode(result, packet);
}
case Network::NetID::ReadSettings: {
auto msg = std::make_shared<ReadSettingsMessage>();
msg->network = packet->network;
msg->response = ReadSettingsMessage::Response(packet->data[0]);
if(msg->response == ReadSettingsMessage::Response::OK) {
// The global settings structure is the payload of the message in this case
msg->data.insert(msg->data.begin(), packet->data.begin() + 10, packet->data.end());
uint16_t resp_len = msg->data[8] | (msg->data[9] << 8);
if(msg->data.size() - 1 == resp_len) // There is a padding byte at the end
msg->data.pop_back();
result = msg;
return true;
}
// We did not get a successful response, so the payload is all of the data
msg->data.insert(msg->data.begin(), packet->data.begin(), packet->data.end());
result = msg;
return true;
}
}
}
// For the moment other types of messages will automatically be decoded as raw messages
auto msg = std::make_shared<Message>();
msg->network = packet->network;
msg->data = packet->data;
result = msg;
return true;
} | 41.662338 | 110 | 0.678928 | tysonite |
3bb99a80ece30631ca12d9c95f5a61d40e457070 | 583 | hpp | C++ | Include/SockServer.hpp | kwiato88/sock | fff7ab7d2a0183bfbb7db45ac7d298f2980825f2 | [
"MIT"
] | null | null | null | Include/SockServer.hpp | kwiato88/sock | fff7ab7d2a0183bfbb7db45ac7d298f2980825f2 | [
"MIT"
] | null | null | null | Include/SockServer.hpp | kwiato88/sock | fff7ab7d2a0183bfbb7db45ac7d298f2980825f2 | [
"MIT"
] | null | null | null | //This code is under MIT licence, you can find the complete file here: https://github.com/kwiato88/sock/blob/master/LICENSE
#pragma once
#include <string>
#include <memory>
#include "SockListeningSocket.hpp"
#include "SockConnection.hpp"
namespace sock
{
class Server
{
public:
/**
* throws Error
*/
Server(const std::string& p_host, const std::string& p_port);
Server(const Server&) = delete;
Server& operator=(const Server&) = delete;
/**
* throws Error
*/
std::unique_ptr<Connection> accept();
private:
ListeningSocket socket;
};
}
| 18.21875 | 124 | 0.67753 | kwiato88 |
3bbae5d44f5b85c4e47398acdb93bf11b4935b23 | 921 | cc | C++ | 2_Programmieraufgabe/main2.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | 2_Programmieraufgabe/main2.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | 2_Programmieraufgabe/main2.cc | j3l4ck0ut/UdemyCpp | ed3b75cedbf9cad211a205195605cfd3c9280efc | [
"MIT"
] | null | null | null | #include <iostream>
#include "exercise2.h"
// int main()
int main()
{
int *my_data = nullptr;
unsigned int size = 3;
my_data = new int[size];
my_data[0] = 0;
my_data[1] = 1;
my_data[2] = 2; // int main()
std::cout << "Start-values of the array: " << std::endl;
for (unsigned int i = 0; i < size; i++)
{
std::cout << my_data[i] << std::endl;
}
// Aufgabe 1
// 0 1 2 12
push_back(my_data, size, 12);
size++;
std::cout << "Append value 12 at the end: " << std::endl;
for (unsigned int i = 0; i < size; i++)
{
std::cout << my_data[i] << std::endl;
}
// Aufgabe 2
pop_back(my_data, size);
size--;
std::cout << "Remove the last value: " << std::endl;
for (unsigned int i = 0; i < size; i++)
{
std::cout << my_data[i] << std::endl;
}
delete[] my_data;
my_data = nullptr;
return 0;
} | 19.595745 | 61 | 0.508143 | j3l4ck0ut |
3bc2701501bd1cf63d2e04504dd315c3acd18f2d | 1,550 | cpp | C++ | LeetCode/103 - Binary Tree Zigzag Level Order Traversal.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | LeetCode/103 - Binary Tree Zigzag Level Order Traversal.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | LeetCode/103 - Binary Tree Zigzag Level Order Traversal.cpp | GokulVSD/ScratchPad | 53dee2293a2039186b00c7a465c7ef28e2b8e291 | [
"Unlicense"
] | null | null | null | // https://leetcode.com/problems/binary-tree-zigzag-level-order-traversal/
// Can also be done via 102 Level Order Traversal method, and reverse alternating vectors.
class Solution {
public:
vector<vector<int>> zigzagLevelOrder(TreeNode* root) {
vector<vector<int>> zzlo;
if (!root)
return zzlo;
int cur = 0;
zzlo.push_back(vector<int>());
stack<TreeNode*> currentlevel;
stack<TreeNode*> nextlevel;
currentlevel.push(root);
bool lefttoright = true;
while (!currentlevel.empty()) {
TreeNode* temp = currentlevel.top();
currentlevel.pop();
if (temp) {
zzlo[cur].push_back(temp->val);
if (lefttoright) {
if (temp->left)
nextlevel.push(temp->left);
if (temp->right)
nextlevel.push(temp->right);
}
else {
if (temp->right)
nextlevel.push(temp->right);
if (temp->left)
nextlevel.push(temp->left);
}
}
if (currentlevel.empty()) {
lefttoright = !lefttoright;
zzlo.push_back(vector<int>());
++cur;
swap(currentlevel, nextlevel);
}
}
zzlo.pop_back();
return zzlo;
}
}; | 27.678571 | 90 | 0.447742 | GokulVSD |
3bc38704cb1d4c2d9e9698e85ba7d7668c5400f9 | 13,701 | hpp | C++ | ThirdParty/oglplus-develop/include/oglplus/uniform_subroutines.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/include/oglplus/uniform_subroutines.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | ThirdParty/oglplus-develop/include/oglplus/uniform_subroutines.hpp | vif/3D-STG | 721402e76a9b9b99b88ba3eb06beb6abb17a9254 | [
"MIT"
] | null | null | null | /**
* @file oglplus/uniform_subroutines.hpp
* @brief Wrapper for uniform subroutine operations
*
* @author Matus Chochlik
*
* Copyright 2010-2013 Matus Chochlik. 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)
*/
#pragma once
#ifndef OGLPLUS_UNIFORM_SUBROUTINE_1107121519_HPP
#define OGLPLUS_UNIFORM_SUBROUTINE_1107121519_HPP
#include <oglplus/config.hpp>
#include <oglplus/glfunc.hpp>
#include <oglplus/error.hpp>
#include <oglplus/friend_of.hpp>
#include <oglplus/shader.hpp>
#include <oglplus/program.hpp>
#include <oglplus/string.hpp>
#include <oglplus/auxiliary/uniform_init.hpp>
#include <cassert>
namespace oglplus {
#if OGLPLUS_DOCUMENTATION_ONLY || GL_VERSION_4_0 || GL_ARB_shader_subroutine
class UniformSubroutines;
namespace aux {
class SubroutineUniformInitOps
{
private:
ShaderType _stage;
protected:
typedef ShaderType ParamType;
SubroutineUniformInitOps(ShaderType stage)
: _stage(stage)
{ }
GLint _do_init_location(GLuint program, const GLchar* identifier) const
{
GLint result = OGLPLUS_GLFUNC(GetSubroutineUniformLocation)(
program,
GLenum(_stage),
identifier
);
OGLPLUS_VERIFY(OGLPLUS_ERROR_INFO(GetSubroutineUniformLocation));
return result;
}
void _handle_error(
GLuint program,
const GLchar* identifier,
GLint location
) const;
GLint _init_location(GLuint program, const GLchar* identifier) const
{
GLint location = _do_init_location(program, identifier);
if(OGLPLUS_IS_ERROR(location == GLint(-1)))
{
_handle_error(program, identifier, location);
}
return location;
}
public:
/// Returns this subroutine uniform's program stage
ShaderType Stage(void) const
{
return _stage;
}
};
typedef EagerUniformInitTpl<SubroutineUniformInitOps>
EagerSubroutineUniformInit;
typedef LazyUniformInitTpl<SubroutineUniformInitOps, NoUniformTypecheck>
LazySubroutineUniformInit;
} //namespace aux
/// Template for SubroutineUniform and LazySubroutineUniform
/** @note Do not use directly, use SubroutineUniform or
* LazySubroutineUniform instead.
*
* @ingroup shader_variables
*
* @glvoereq{4,0,ARB,shader_subroutine}
*/
template <class Initializer>
class SubroutineUniformTpl
: public Initializer
{
private:
friend class UniformSubroutines;
public:
template <typename String_>
SubroutineUniformTpl(
const Program& program,
const ShaderType stage,
String_&& identifier
): Initializer(
program,
stage,
std::forward<String_>(identifier),
NoTypecheck()
)
{ }
/// Tests if this SubroutineUniform is active and can be used
/**
* For SubroutineUniform this function always
* returns true as it cannot be in uninitialized state.
* For LazySubroutineUniform this function
* returns true if the uniform is active and can be referenced
* and used for subsequent operations.
* If this function returns false then trying to use the
* uniform throws an exception.
*/
bool IsActive(void)
{
return this->_try_init_location();
}
/// Equivalent to IsActive()
/**
* @see IsActive
*/
operator bool (void)
{
return IsActive();
}
/// Equivalent to !IsActive()
/**
* @see IsActive
*/
bool operator ! (void)
{
return !IsActive();
}
};
#if OGLPLUS_DOCUMENTATION_ONLY
/// Subroutine uniform variable
/**
* The difference between SubroutineUniform and LazySubroutineUniform is,
* that SubroutineUniform tries to get the location of the GLSL
* subroutine uniform variable in a Program during construction
* and LazySubroutineUniform postpones this initialization until
* the value is actually needed at the cost of having to internally
* store the identifer in a String.
*
* @see LazySubroutineUniform
* @see Subroutine
* @see LazySubroutine
*
* @ingroup shader_variables
*
* @glvoereq{4,0,ARB,shader_subroutine}
*/
struct SubroutineUniform
: public SubroutineUniformTpl<Unspecified>
{
/// Constructionf from a program, stage and identifier
SubroutineUniform(
const Program& program,
const ShaderType stage,
String identifier
);
};
#else
typedef SubroutineUniformTpl<aux::EagerSubroutineUniformInit>
SubroutineUniform;
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Lazy subroutine uniform variable
/**
* The difference between SubroutineUniform and LazySubroutineUniform is,
* that SubroutineUniform tries to get the location of the GLSL
* subroutine uniform variable in a Program during construction
* and LazySubroutineUniform postpones this initialization until
* the value is actually needed at the cost of having to internally
* store the identifer in a String.
*
* @see SubroutineUniform
* @see Subroutine
* @see LazySubroutine
*
* @ingroup shader_variables
*
* @glvoereq{4,0,ARB,shader_subroutine}
*/
struct LazySubroutineUniform
: public SubroutineUniformTpl<Unspecified>
{
/// Constructionf from a program, stage and identifier
LazySubroutineUniform(
const Program& program,
const ShaderType stage,
String identifier
);
};
#else
typedef SubroutineUniformTpl<aux::LazySubroutineUniformInit>
LazySubroutineUniform;
#endif
namespace aux {
class SubroutineInitOps
{
private:
ShaderType _stage;
protected:
typedef ShaderType ParamType;
SubroutineInitOps(ShaderType stage)
: _stage(stage)
{ }
GLint _do_init_location(GLuint program, const GLchar* identifier) const
{
GLint result = OGLPLUS_GLFUNC(GetSubroutineIndex)(
program,
GLenum(_stage),
identifier
);
OGLPLUS_VERIFY(OGLPLUS_ERROR_INFO(GetSubroutineIndex));
return result;
}
void _handle_error(
GLuint program,
const GLchar* identifier,
GLint location
) const;
GLint _init_location(GLuint program, const GLchar* identifier) const
{
GLint location = _do_init_location(program, identifier);
if(OGLPLUS_IS_ERROR(location == GLint(-1)))
{
_handle_error(program, identifier, location);
}
return location;
}
public:
/// Returns this subroutine's program stage
ShaderType Stage(void) const
{
return _stage;
}
};
typedef EagerUniformInitTpl<SubroutineInitOps>
EagerSubroutineInit;
typedef LazyUniformInitTpl<SubroutineInitOps, NoUniformTypecheck>
LazySubroutineInit;
} // namespace aux
/// Template for Subroutine and LazySubroutine
/** @note Do not use directly, use Subroutine or LazySubroutine instead.
*
* @ingroup shader_variables
*/
template <class Initializer>
class SubroutineTpl
: public Initializer
{
private:
friend class UniformSubroutines;
public:
template <class String>
SubroutineTpl(
const Program& program,
const ShaderType stage,
String&& identifier
): Initializer(
program,
stage,
std::forward<String>(identifier),
NoTypecheck()
)
{ }
/// Tests if this Subroutine is active and can be used
/**
* For Subroutine this function always
* returns true as it cannot be in uninitialized state.
* For LazySubroutine this function
* returns true if the subroutine is active and can be referenced
* and used for subsequent assignment operations.
* If this function returns false then trying to use the
* subroutine throws an exception.
*/
bool IsActive(void)
{
return this->_try_init_location();
}
/// Equivalent to IsActive()
/**
* @see IsActive
*/
operator bool (void)
{
return IsActive();
}
/// Equivalent to !IsActive()
/**
* @see IsActive
*/
bool operator ! (void)
{
return !IsActive();
}
};
#if OGLPLUS_DOCUMENTATION_ONLY
/// Subroutine variable
/**
* The difference between Subroutine and LazySubroutine is,
* that Subroutine tries to get the location of the GLSL
* function declared as subroutine in a Program during construction
* and LazySubroutine postpones this initialization until
* the value is actually needed at the cost of having to internally
* store the identifer in a String.
*
* @see SubroutineUniform
* @see LazySubroutineUniform
* @see LazySubroutine
*
* @ingroup shader_variables
*
* @glvoereq{4,0,ARB,shader_subroutine}
*/
struct Subroutine
: public SubroutineTpl<Unspecified>
{
/// Constructionf from a program, stage and identifier
Subroutine(
const Program& program,
const ShaderType stage,
String identifier
);
};
#else
typedef SubroutineTpl<aux::EagerSubroutineInit> Subroutine;
#endif
#if OGLPLUS_DOCUMENTATION_ONLY
/// Lazy subroutine variable
/**
* The difference between Subroutine and LazySubroutine is,
* that Subroutine tries to get the location of the GLSL
* function declared as subroutine in a Program during construction
* and LazySubroutine postpones this initialization until
* the value is actually needed at the cost of having to internally
* store the identifer in a String.
*
* @see SubroutineUniform
* @see LazySubroutineUniform
* @see Subroutine
*
* @ingroup shader_variables
*
* @glvoereq{4,0,ARB,shader_subroutine}
*/
struct LazySubroutine
: public SubroutineTpl<Unspecified>
{
/// Constructionf from a program, stage and identifier
LazySubroutine(
const Program& program,
const ShaderType stage,
String identifier
);
};
#else
typedef SubroutineTpl<aux::LazySubroutineInit> LazySubroutine;
#endif
/// Encapsulates the uniform subroutine setting operations
/**
* @ingroup shader_variables
*
* @glvoereq{4,0,ARB,shader_subroutine}
*/
class UniformSubroutines
: public FriendOf<Program>
{
private:
GLuint _program;
GLenum _stage;
std::vector<GLuint> _indices;
static GLsizei _get_location_count(
GLuint program,
GLenum stage
)
{
GLint result;
OGLPLUS_GLFUNC(GetProgramStageiv)(
program,
stage,
GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS,
&result
);
OGLPLUS_VERIFY(OGLPLUS_OBJECT_ERROR_INFO(
GetProgramStageiv,
Program,
nullptr,
program
));
return result;
}
std::vector<GLuint>& _get_indices(void)
{
if(_indices.empty())
_indices.resize(_get_location_count(_program, _stage), 0);
return _indices;
}
public:
/// Constructs a uniform subroutine setter for a @p stage of a @p program
UniformSubroutines(
const Program& program,
const ShaderType stage
): _program(FriendOf<Program>::GetName(program))
, _stage(GLenum(stage))
{ }
#if OGLPLUS_DOCUMENTATION_ONLY
/// Assigns the @p subroutine to the subroutine @p uniform
/**
* @note This function does not apply the changes to the actual
* uniform variables in the stage of the program. Use Apply
* function to do this after the subroutines are assigned.
*
* @see Apply
*/
UniformSubroutines& Assign(
SubroutineUniform& uniform,
Subroutine& subroutine
);
#endif
template <typename SUInit, typename SInit>
UniformSubroutines& Assign(
SubroutineUniformTpl<SUInit>& uniform,
SubroutineTpl<SInit>& subroutine
)
{
assert(uniform._get_program() == _program);
assert(subroutine._get_program() == _program);
assert(uniform.Stage() == ShaderType(_stage));
assert(subroutine.Stage() == ShaderType(_stage));
assert(uniform._get_location() <= GLint(_get_indices().size()));
_get_indices()[uniform._get_location()] = subroutine._get_location();
return *this;
}
/// This type stores a setting of the whole set of subroutine uniforms
/** Preset stores a whole setting of a set of subroutine uniforms
* which can be later applied or loaded.
*
* Applications should treat this type as opaque and use it
* only with the Save, Load and Apply functions.
*
* @see Save
* @see Load
* @see Apply
*/
class Preset
{
private:
friend class UniformSubroutines;
const std::vector<GLuint> _indices;
#ifndef NDEBUG
GLuint _program;
GLenum _stage;
#endif
Preset(
#ifndef NDEBUG
GLuint program,
GLenum stage,
#endif
const std::vector<GLuint>& indices
): _indices(indices)
#ifndef NDEBUG
, _program(program)
, _stage(stage)
#endif
{ }
public:
Preset(Preset&& tmp)
: _indices(std::move(tmp._indices))
#ifndef NDEBUG
, _program(tmp._program)
, _stage(tmp._stage)
#endif
{ }
};
/// Saves the current setting of subroutine uniforms into a preset
/**
* @see Preset
* @see Apply
* @see Load
*/
Preset Save(void)
{
return Preset(
#ifndef NDEBUG
_program,
_stage,
#endif
_get_indices()
);
}
/// Loads the setting of subroutine uniforms from a @p preset
/** @note Only presets from the same instance of UniformSubroutines
* that saved them can be loaded or applied.
*
* @see Preset
* @see Apply
* @see Save
*/
void Load(const Preset& preset)
{
assert(_program == preset._program);
assert(_stage == preset._stage);
assert(_get_indices().size() == preset._indices.size());
_get_indices() = preset._indices;
}
/// Applies the setting from a preset without changing the current setting
/** @note Only presets from the same instance of UniformSubroutines
* that saved them can be loaded or applied.
*
* @see Preset
* @see Save
* @see Load
*/
void Apply(const Preset& preset)
{
assert(_program == preset._program);
assert(_stage == preset._stage);
assert(_get_indices().size() == preset._indices.size());
OGLPLUS_GLFUNC(UniformSubroutinesuiv)(
_stage,
GLsizei(preset._indices.size()),
preset._indices.data()
);
OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(UniformSubroutinesuiv));
}
/// Applies all changes made by Assign
/**
* @see Assign
*/
void Apply(void)
{
OGLPLUS_GLFUNC(UniformSubroutinesuiv)(
_stage,
GLsizei(_get_indices().size()),
_get_indices().data()
);
OGLPLUS_CHECK(OGLPLUS_ERROR_INFO(UniformSubroutinesuiv));
}
};
#endif
} // namespace oglplus
#if !OGLPLUS_LINK_LIBRARY || defined(OGLPLUS_IMPLEMENTING_LIBRARY)
#include <oglplus/uniform_subroutines.ipp>
#endif // OGLPLUS_LINK_LIBRARY
#endif // include guard
| 22.911371 | 76 | 0.735786 | vif |
3bc8e22408de0785bc50e9c5fd6d2d3ac2c52a63 | 4,515 | cpp | C++ | thrift/compiler/test/fixtures/basic/gen-cpp2/MyServicePrioParent.cpp | malmerey/fbthrift | 2984cccced9aa5f430598974b6256fcca73e500a | [
"Apache-2.0"
] | null | null | null | thrift/compiler/test/fixtures/basic/gen-cpp2/MyServicePrioParent.cpp | malmerey/fbthrift | 2984cccced9aa5f430598974b6256fcca73e500a | [
"Apache-2.0"
] | null | null | null | thrift/compiler/test/fixtures/basic/gen-cpp2/MyServicePrioParent.cpp | malmerey/fbthrift | 2984cccced9aa5f430598974b6256fcca73e500a | [
"Apache-2.0"
] | null | null | null | /**
* Autogenerated by Thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated
*/
#include "thrift/compiler/test/fixtures/basic/gen-cpp2/MyServicePrioParent.h"
#include "thrift/compiler/test/fixtures/basic/gen-cpp2/MyServicePrioParent.tcc"
#include <thrift/lib/cpp2/gen/service_cpp.h>
#include <thrift/lib/cpp2/protocol/BinaryProtocol.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
#include <thrift/lib/cpp2/protocol/Protocol.h>
namespace cpp2 {
std::unique_ptr<apache::thrift::AsyncProcessor> MyServicePrioParentSvIf::getProcessor() {
return std::make_unique<MyServicePrioParentAsyncProcessor>(this);
}
void MyServicePrioParentSvIf::ping() {
apache::thrift::detail::si::throw_app_exn_unimplemented("ping");
}
folly::SemiFuture<folly::Unit> MyServicePrioParentSvIf::semifuture_ping() {
return apache::thrift::detail::si::semifuture([&] { return ping(); });
}
folly::Future<folly::Unit> MyServicePrioParentSvIf::future_ping() {
return apache::thrift::detail::si::future(semifuture_ping(), getThreadManager());
}
void MyServicePrioParentSvIf::async_tm_ping(std::unique_ptr<apache::thrift::HandlerCallback<void>> callback) {
apache::thrift::detail::si::async_tm(this, std::move(callback), [&] { return future_ping(); });
}
void MyServicePrioParentSvIf::pong() {
apache::thrift::detail::si::throw_app_exn_unimplemented("pong");
}
folly::SemiFuture<folly::Unit> MyServicePrioParentSvIf::semifuture_pong() {
return apache::thrift::detail::si::semifuture([&] { return pong(); });
}
folly::Future<folly::Unit> MyServicePrioParentSvIf::future_pong() {
return apache::thrift::detail::si::future(semifuture_pong(), getThreadManager());
}
void MyServicePrioParentSvIf::async_tm_pong(std::unique_ptr<apache::thrift::HandlerCallback<void>> callback) {
apache::thrift::detail::si::async_tm(this, std::move(callback), [&] { return future_pong(); });
}
void MyServicePrioParentSvNull::ping() {
return;
}
void MyServicePrioParentSvNull::pong() {
return;
}
const char* MyServicePrioParentAsyncProcessor::getServiceName() {
return "MyServicePrioParent";
}
folly::Optional<std::string> MyServicePrioParentAsyncProcessor::getCacheKey(folly::IOBuf* buf, apache::thrift::protocol::PROTOCOL_TYPES protType) {
return apache::thrift::detail::ap::get_cache_key(buf, protType, cacheKeyMap_);
}
void MyServicePrioParentAsyncProcessor::process(std::unique_ptr<apache::thrift::ResponseChannelRequest> req, std::unique_ptr<folly::IOBuf> buf, apache::thrift::protocol::PROTOCOL_TYPES protType, apache::thrift::Cpp2RequestContext* context, folly::EventBase* eb, apache::thrift::concurrency::ThreadManager* tm) {
apache::thrift::detail::ap::process(this, std::move(req), std::move(buf), protType, context, eb, tm);
}
bool MyServicePrioParentAsyncProcessor::isOnewayMethod(const folly::IOBuf* buf, const apache::thrift::transport::THeader* header) {
return apache::thrift::detail::ap::is_oneway_method(buf, header, onewayMethods_);
}
std::shared_ptr<folly::RequestContext> MyServicePrioParentAsyncProcessor::getBaseContextForRequest() {
return iface_->getBaseContextForRequest();
}
std::unordered_set<std::string> MyServicePrioParentAsyncProcessor::onewayMethods_ {};
std::unordered_map<std::string, int16_t> MyServicePrioParentAsyncProcessor::cacheKeyMap_ {};
const MyServicePrioParentAsyncProcessor::ProcessMap& MyServicePrioParentAsyncProcessor::getBinaryProtocolProcessMap() {
return binaryProcessMap_;
}
const MyServicePrioParentAsyncProcessor::ProcessMap MyServicePrioParentAsyncProcessor::binaryProcessMap_ {
{"ping", &MyServicePrioParentAsyncProcessor::_processInThread_ping<apache::thrift::BinaryProtocolReader, apache::thrift::BinaryProtocolWriter>},
{"pong", &MyServicePrioParentAsyncProcessor::_processInThread_pong<apache::thrift::BinaryProtocolReader, apache::thrift::BinaryProtocolWriter>},
};
const MyServicePrioParentAsyncProcessor::ProcessMap& MyServicePrioParentAsyncProcessor::getCompactProtocolProcessMap() {
return compactProcessMap_;
}
const MyServicePrioParentAsyncProcessor::ProcessMap MyServicePrioParentAsyncProcessor::compactProcessMap_ {
{"ping", &MyServicePrioParentAsyncProcessor::_processInThread_ping<apache::thrift::CompactProtocolReader, apache::thrift::CompactProtocolWriter>},
{"pong", &MyServicePrioParentAsyncProcessor::_processInThread_pong<apache::thrift::CompactProtocolReader, apache::thrift::CompactProtocolWriter>},
};
} // cpp2
namespace apache { namespace thrift {
}} // apache::thrift
| 42.196262 | 311 | 0.786932 | malmerey |
3bcb4804632671983b95c5a24b7b502affc8182a | 484 | cpp | C++ | ads-2021.2/estrutura-dados-l/listas/lista-01/q14-sexo.cpp | rsmwall/ifpi-ads-course | ce741086743c6cf9069d8b84e9e6cdd467a19e3f | [
"MIT"
] | 1 | 2021-09-07T00:06:43.000Z | 2021-09-07T00:06:43.000Z | ads-2021.2/estrutura-dados-l/listas/lista-01/q14-sexo.cpp | rsmwall/ifpi-ads-course | ce741086743c6cf9069d8b84e9e6cdd467a19e3f | [
"MIT"
] | null | null | null | ads-2021.2/estrutura-dados-l/listas/lista-01/q14-sexo.cpp | rsmwall/ifpi-ads-course | ce741086743c6cf9069d8b84e9e6cdd467a19e3f | [
"MIT"
] | null | null | null | /* Leia uma letra e verifique se letra é "F" e escreva “F – Feminino” ou “M” e escreva “M – Masculino”,
se não for nem F ou M, escreva “Sexo Inválido” */
#include <stdio.h>
int main(){
char sexo;
printf("Digite a letra referente ao sexo: ");
scanf("%s", &sexo);
if(sexo =='f' || sexo == 'F'){
printf("F - Feminino\n\n");
}else if(sexo == 'm' || sexo == 'M'){
printf("M - Masculino\n\n");
}else{
printf("Sexo inválido\n\n");
}
}
| 24.2 | 103 | 0.539256 | rsmwall |
3bcb5d5e03703ef0e08ba991e8649916e8ca8b64 | 11,670 | cpp | C++ | lugre/baselib/ois/src/win32/extras/WiiMote/OISWiiMote.cpp | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | 1 | 2020-10-18T14:33:05.000Z | 2020-10-18T14:33:05.000Z | lugre/baselib/ois/src/win32/extras/WiiMote/OISWiiMote.cpp | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | null | null | null | lugre/baselib/ois/src/win32/extras/WiiMote/OISWiiMote.cpp | ghoulsblade/vegaogre | 2ece3b799f9bd667f081d47c1a0f3ef5e78d3e0f | [
"MIT"
] | null | null | null | #include "OISConfig.h"
#ifdef OIS_WIN32_WIIMOTE_SUPPORT
/*
The zlib/libpng License
Copyright (c) 2005-2007 Phillip Castaneda (pjcast -- www.wreckedgames.com)
This software is provided 'as-is', without any express or implied warranty. In no event will
the authors be held liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose, including commercial
applications, and to alter it and redistribute it freely, subject to the following
restrictions:
1. The origin of this software must not be misrepresented; you must not claim that
you wrote the original software. If you use this software in a product,
an acknowledgment in the product documentation would be appreciated but is
not required.
2. Altered source versions must be plainly marked as such, and must not be
misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
*/
#include "OISWiiMote.h"
#include "OISWiiMoteFactoryCreator.h"
#include "OISException.h"
#include "OISWiiMoteForceFeedback.h"
#define _USE_MATH_DEFINES
#include <math.h>
#include <limits.h>
using namespace OIS;
//-----------------------------------------------------------------------------------//
WiiMote::WiiMote(InputManager* creator, int id, bool buffered, WiiMoteFactoryCreator* local_creator) :
JoyStick("cWiiMote", buffered, id, creator),
mWiiCreator(local_creator),
mtInitialized(false),
mRingBuffer(OIS_WII_EVENT_BUFFER),
mtLastButtonStates(0),
mtLastPOVState(0),
mtLastX(0.0f),
mtLastY(1.0f),
mtLastZ(0.0f),
mtLastNunChuckX(0.0f),
mtLastNunChuckY(1.0f),
mtLastNunChuckZ(0.0f),
mLastNunChuckXAxis(0),
mLastNunChuckYAxis(0),
_mWiiMoteMotionDelay(5),
mRumble(0)
{
mRumble = new WiiMoteForceFeedback(mWiiMote);
}
//-----------------------------------------------------------------------------------//
WiiMote::~WiiMote()
{
delete mRumble;
if( mWiiMote.IsConnected() )
{
mWiiMote.StopDataStream();
mWiiMote.Disconnect();
}
mWiiCreator->_returnWiiMote(mDevID);
}
//-----------------------------------------------------------------------------------//
void WiiMote::_initialize()
{
if( mWiiMote.ConnectToDevice(mDevID) == false )
OIS_EXCEPT(E_InputDisconnected, "Error connecting to WiiMote!");
if( mWiiMote.StartDataStream() == false )
OIS_EXCEPT(E_InputDisconnected, "Error starting WiiMote data stream!");
//Fill in joystick information
mState.mVectors.clear();
mState.mButtons.clear();
mState.mAxes.clear();
if( mWiiMote.IsNunChuckAttached() )
{ //Setup for WiiMote + nunChuck
mState.mVectors.resize(2);
mState.mButtons.resize(9);
mState.mAxes.resize(2);
mState.mAxes[0].absOnly = true;
mState.mAxes[1].absOnly = true;
}
else
{ //Setup for WiiMote
mState.mVectors.resize(1);
mState.mButtons.resize(7);
}
mPOVs = 1;
mState.clear();
mtInitialized = true;
}
//-----------------------------------------------------------------------------------//
void WiiMote::_threadUpdate()
{
//Leave early if nothing is setup yet
if( mtInitialized == false )
return;
//Oops, no room left in ring buffer.. have to wait for client app to call Capture()
if( mRingBuffer.GetWriteAvailable() == 0 )
return;
WiiMoteEvent newEvent;
newEvent.clear();
//Update read
mWiiMote.HeartBeat();
//Get & check current button states
const cWiiMote::tButtonStatus &bState = mWiiMote.GetLastButtonStatus();
_doButtonCheck(bState.m1, 0, newEvent.pushedButtons, newEvent.releasedButtons); //1
_doButtonCheck(bState.m2, 1, newEvent.pushedButtons, newEvent.releasedButtons); //2
_doButtonCheck(bState.mA, 2, newEvent.pushedButtons, newEvent.releasedButtons); //A
_doButtonCheck(bState.mB, 3, newEvent.pushedButtons, newEvent.releasedButtons); //B
_doButtonCheck(bState.mPlus, 4, newEvent.pushedButtons, newEvent.releasedButtons);//+
_doButtonCheck(bState.mMinus, 5, newEvent.pushedButtons, newEvent.releasedButtons);//-
_doButtonCheck(bState.mHome, 6, newEvent.pushedButtons, newEvent.releasedButtons);//Home
//Check POV
newEvent.povChanged = _doPOVCheck(bState, newEvent.povDirection);
//Do motion check on main orientation - accounting for sensitivity factor
mWiiMote.GetCalibratedAcceleration(newEvent.x, newEvent.y, newEvent.z);
//Normalize new vector (old vector is already normalized)
float len = sqrt((newEvent.x*newEvent.x) + (newEvent.y*newEvent.y) + (newEvent.z*newEvent.z));
newEvent.x /= len;
newEvent.y /= len;
newEvent.z /= len;
//Get new angle
float angle = acos((newEvent.x * mtLastX) + (newEvent.y * mtLastY) + (newEvent.z * mtLastZ));
if( angle > (mVector3Sensitivity * (M_PI / 180.0)) )
{ //Store for next check
mtLastX = newEvent.x;
mtLastY = newEvent.y;
mtLastZ = newEvent.z;
if( _mWiiMoteMotionDelay <= 0 )
newEvent.movement = true; //Set flag as moved
else
--_mWiiMoteMotionDelay;
}
//Act on NunChuck Data
if( mWiiMote.IsNunChuckAttached() )
{
const cWiiMote::tChuckReport &bState = mWiiMote.GetLastChuckReport();
_doButtonCheck(bState.mButtonC, 7, newEvent.pushedButtons, newEvent.releasedButtons); //C
_doButtonCheck(bState.mButtonZ, 8, newEvent.pushedButtons, newEvent.releasedButtons); //Z
mWiiMote.GetCalibratedChuckAcceleration(newEvent.nunChuckx, newEvent.nunChucky, newEvent.nunChuckz);
//Normalize new vector (old vector is already normalized)
float len = sqrt((newEvent.nunChuckx*newEvent.nunChuckx) +
(newEvent.nunChucky*newEvent.nunChucky) +
(newEvent.nunChuckz*newEvent.nunChuckz));
newEvent.nunChuckx /= len;
newEvent.nunChucky /= len;
newEvent.nunChuckz /= len;
float angle = acos((newEvent.nunChuckx * mtLastNunChuckX) +
(newEvent.nunChucky * mtLastNunChuckY) +
(newEvent.nunChuckz * mtLastNunChuckZ));
if( angle > (mVector3Sensitivity * (M_PI / 180.0)) )
{ //Store for next check
mtLastNunChuckX = newEvent.nunChuckx;
mtLastNunChuckY = newEvent.nunChucky;
mtLastNunChuckZ = newEvent.nunChuckz;
if( _mWiiMoteMotionDelay <= 0 )
newEvent.movementChuck = true;
}
//Ok, Now check both NunChuck Joystick axes for movement
float tempX = 0.0f, tempY = 0.0f;
mWiiMote.GetCalibratedChuckStick(tempX, tempY);
//Convert to int and clip
newEvent.nunChuckXAxis = (int)(tempX * JoyStick::MAX_AXIS);
if( newEvent.nunChuckXAxis > JoyStick::MAX_AXIS )
newEvent.nunChuckXAxis = JoyStick::MAX_AXIS;
else if( newEvent.nunChuckXAxis < JoyStick::MIN_AXIS )
newEvent.nunChuckXAxis = JoyStick::MIN_AXIS;
newEvent.nunChuckYAxis = (int)(tempY * JoyStick::MAX_AXIS);
if( newEvent.nunChuckYAxis > JoyStick::MAX_AXIS )
newEvent.nunChuckYAxis = JoyStick::MAX_AXIS;
else if( newEvent.nunChuckYAxis < JoyStick::MIN_AXIS )
newEvent.nunChuckYAxis = JoyStick::MIN_AXIS;
//Apply a little dead-zone dampner
int xDiff = newEvent.nunChuckXAxis - mLastNunChuckXAxis;
if( xDiff > 1500 || xDiff < -1500 )
{
mLastNunChuckXAxis = newEvent.nunChuckXAxis;
newEvent.nunChuckXAxisMoved = true;
}
int yDiff = newEvent.nunChuckYAxis - mLastNunChuckYAxis;
if( yDiff > 1500 || yDiff < -1500 )
{
mLastNunChuckYAxis = newEvent.nunChuckYAxis;
newEvent.nunChuckYAxisMoved = true;
}
}
//Ok, put entry in ringbuffer if something changed
if(newEvent.pushedButtons || newEvent.releasedButtons || newEvent.povChanged || newEvent.movement ||
newEvent.movementChuck || newEvent.nunChuckXAxisMoved || newEvent.nunChuckYAxisMoved)
{
mRingBuffer.Write(&newEvent, 1);
}
//mWiiMote.PrintStatus();
}
//-----------------------------------------------------------------------------------//
void WiiMote::_doButtonCheck(bool new_state, int ois_button, unsigned int &pushed, unsigned int &released)
{
const bool old_state = ((mtLastButtonStates & ( 1L << ois_button )) == 0) ? false : true;
//Check to see if new state and old state are the same, and hence, need no change
if( new_state == old_state )
return;
//Ok, so it changed... but how?
if( new_state )
{ //Ok, new state is pushed, old state was not pushed.. so send button press
mtLastButtonStates |= 1 << ois_button; //turn the bit flag on
pushed |= 1 << ois_button;
}
else
{ //Ok, so new state is not pushed, and old state was pushed.. So, send release
mtLastButtonStates &= ~(1 << ois_button); //turn the bit flag off
released |= 1 << ois_button;
}
}
//-----------------------------------------------------------------------------------//
bool WiiMote::_doPOVCheck(const cWiiMote::tButtonStatus &bState, unsigned int &newPosition)
{
newPosition = Pov::Centered;
if( bState.mUp )
newPosition |= Pov::North;
else if( bState.mDown )
newPosition |= Pov::South;
if( bState.mLeft )
newPosition |= Pov::West;
else if( bState.mRight )
newPosition |= Pov::East;
//Was there a change?
if( mtLastPOVState != newPosition )
{
mtLastPOVState = newPosition;
return true;
}
return false;
}
//-----------------------------------------------------------------------------------//
void WiiMote::setBuffered(bool buffered)
{
mBuffered = buffered;
}
//-----------------------------------------------------------------------------------//
void WiiMote::capture()
{
//Anything to read?
int entries = mRingBuffer.GetReadAvailable();
if( entries <= 0 )
return;
WiiMoteEvent events[OIS_WII_EVENT_BUFFER];
if( entries > OIS_WII_EVENT_BUFFER )
entries = OIS_WII_EVENT_BUFFER;
mRingBuffer.Read(events, entries);
//Loop through each event
for( int i = 0; i < entries; ++i )
{
//Any movement changes in the main accellerometers?
if( events[i].movement )
{
mState.mVectors[0].x = events[i].x;
mState.mVectors[0].y = events[i].y;
mState.mVectors[0].z = events[i].z;
if( mBuffered && mListener )
if( !mListener->vector3Moved( JoyStickEvent( this, mState ), 0 ) ) return;
}
//Check NunChuck movements
if( events[i].movementChuck )
{
mState.mVectors[1].x = events[i].nunChuckx;
mState.mVectors[1].y = events[i].nunChucky;
mState.mVectors[1].z = events[i].nunChuckz;
if( mBuffered && mListener )
if( !mListener->vector3Moved( JoyStickEvent( this, mState ), 1 ) ) return;
}
if( events[i].nunChuckXAxisMoved )
{
mState.mAxes[0].abs = events[i].nunChuckXAxis;
if( mBuffered && mListener )
if( !mListener->axisMoved( JoyStickEvent( this, mState ), 0 ) ) return;
}
if( events[i].nunChuckYAxisMoved )
{
mState.mAxes[1].abs = events[i].nunChuckYAxis;
if( mBuffered && mListener )
if( !mListener->axisMoved( JoyStickEvent( this, mState ), 1 ) ) return;
}
//Has the hat swtich changed?
if( events[i].povChanged )
{
mState.mPOV[0].direction = events[i].povDirection;
if( mBuffered && mListener )
if( !mListener->povMoved( JoyStickEvent( this, mState ), 0 ) ) return;
}
//Check for any pushed/released events for each button bit
int buttons = (int)mState.mButtons.size();
for( int b = 0; b < buttons; ++b )
{
unsigned bit_flag = 1 << b;
if( (events[i].pushedButtons & bit_flag) != 0 )
{ //send event
mState.mButtons[i] = true;
if( mBuffered && mListener )
if( !mListener->buttonPressed( JoyStickEvent( this, mState ), b ) ) return;
}
if( (events[i].releasedButtons & bit_flag) != 0 )
{ //send event
mState.mButtons[i] = false;
if( mBuffered && mListener )
if( !mListener->buttonReleased( JoyStickEvent( this, mState ), b ) ) return;
}
}
}
}
//-----------------------------------------------------------------------------------//
Interface* WiiMote::queryInterface(Interface::IType type)
{
if( type == Interface::ForceFeedback && mtInitialized )
return mRumble;
return 0;
}
#endif
| 31.203209 | 106 | 0.666153 | ghoulsblade |
3bcd84eba9673176c345a9a40fa09fd9367ecb2a | 1,455 | hpp | C++ | components/rgbd-sources/src/sources/screencapture/screencapture.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | 4 | 2020-12-28T15:29:15.000Z | 2021-06-27T12:37:15.000Z | components/rgbd-sources/src/sources/screencapture/screencapture.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | null | null | null | components/rgbd-sources/src/sources/screencapture/screencapture.hpp | knicos/voltu | 70b39da7069f8ffd7e33aeb5bdacc84fe4a78f01 | [
"MIT"
] | 2 | 2021-01-13T05:28:39.000Z | 2021-05-04T03:37:11.000Z | #ifndef _FTL_RGBD_SCREENCAPTURE_HPP_
#define _FTL_RGBD_SCREENCAPTURE_HPP_
#include "../../basesource.hpp"
#include <ftl/config.h>
#include <ftl/codecs/touch.hpp>
namespace ftl {
namespace rgbd {
namespace detail {
#ifdef HAVE_X11
struct X11State;
typedef X11State ImplState;
#else
typedef int ImplState;
#endif
class ScreenCapture : public ftl::rgbd::BaseSourceImpl {
public:
explicit ScreenCapture(ftl::rgbd::Source *host);
~ScreenCapture();
bool capture(int64_t ts) override { return true; };
bool retrieve(ftl::rgbd::Frame &frame) override;
bool isReady() override;
size_t getOffsetX() const { return (offset_x_ > full_width_-params_.width) ? full_width_-params_.width : offset_x_; }
size_t getOffsetY() const { return (offset_y_ > full_height_-params_.height) ? full_height_-params_.height : offset_y_; }
private:
bool ready_;
int64_t cap_ts_;
int64_t cur_ts_;
//ftl::rgbd::Frame sframe_;
size_t full_width_;
size_t full_height_;
size_t offset_x_;
size_t offset_y_;
Eigen::Matrix4d pose_;
bool do_update_params_ = false;
bool pressed_ = false;
ftl::codecs::Touch primary_touch_;
ImplState *impl_state_;
ftl::rgbd::Camera params_;
//void _mouseClick(int button, int x, int y);
void _singleTouch(const ftl::codecs::Touch &t);
void _press();
void _release();
void _move(int x, int y);
void _noTouch();
void _multiTouch(const std::vector<ftl::codecs::Touch> &);
};
}
}
}
#endif // _FTL_RGBD_SCREENCAPTURE_HPP_
| 22.384615 | 122 | 0.74433 | knicos |
3bd66fa82497c9025472bbb04d455e4e6ad9150d | 2,001 | cpp | C++ | src/runtime_src/core/edge/user/device_linux.cpp | cellery/XRT | a5c908d18dd8cd99d922ec8c847f869477d21079 | [
"Apache-2.0"
] | null | null | null | src/runtime_src/core/edge/user/device_linux.cpp | cellery/XRT | a5c908d18dd8cd99d922ec8c847f869477d21079 | [
"Apache-2.0"
] | 1 | 2019-08-14T05:47:34.000Z | 2019-08-14T16:21:49.000Z | src/runtime_src/core/edge/user/device_linux.cpp | larry9523/XRT | d046a37b323e16cdbda57d65d0b8fc0469a96123 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright (C) 2020 Xilinx, Inc
*
* Licensed under the Apache License, Version 2.0 (the "License"). You may
* not use this file except in compliance with the License. A copy of the
* License is located 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 "device_linux.h"
#include "xrt.h"
#include <string>
#include <iostream>
#include <map>
#include "boost/format.hpp"
namespace xrt_core {
const device_linux::SysDevEntry&
device_linux::get_sysdev_entry(QueryRequest qr) const
{
static const std::map<QueryRequest, SysDevEntry> QueryRequestToSysDevTable = {};
// Find the translation entry
auto it = QueryRequestToSysDevTable.find(qr);
if (it == QueryRequestToSysDevTable.end()) {
std::string errMsg = boost::str( boost::format("The given query request ID (%d) is not supported.") % qr);
throw no_such_query(qr, errMsg);
}
return it->second;
}
void
device_linux::
query(QueryRequest qr, const std::type_info& tinfo, boost::any& value) const
{
boost::any anyEmpty;
value.swap(anyEmpty);
std::string errmsg;
errmsg = boost::str( boost::format("Error: Unsupported query_device return type: '%s'") % tinfo.name());
if (!errmsg.empty()) {
throw std::runtime_error(errmsg);
}
}
device_linux::
device_linux(id_type device_id, bool user)
: device_edge(device_id, user)
{
}
void
device_linux::
read_dma_stats(boost::property_tree::ptree& pt) const
{
}
void
device_linux::
read(uint64_t offset, void* buf, uint64_t len) const
{
throw error(-ENODEV, "read failed");
}
void
device_linux::
write(uint64_t offset, const void* buf, uint64_t len) const
{
throw error(-ENODEV, "write failed");
}
} // xrt_core
| 23.541176 | 110 | 0.718141 | cellery |
3bd72206f92aad7c20c4be271bba52d2c3f48943 | 10,128 | hpp | C++ | include/natalie/object.hpp | natalie-lang/natalie | 5597f401a41128631c92378b99bf3e8b5393717b | [
"MIT"
] | 7 | 2022-03-08T08:47:54.000Z | 2022-03-29T15:08:36.000Z | include/natalie/object.hpp | natalie-lang/natalie | 5597f401a41128631c92378b99bf3e8b5393717b | [
"MIT"
] | 12 | 2022-03-10T13:04:42.000Z | 2022-03-24T01:40:23.000Z | include/natalie/object.hpp | natalie-lang/natalie | 5597f401a41128631c92378b99bf3e8b5393717b | [
"MIT"
] | 5 | 2022-03-13T17:46:16.000Z | 2022-03-31T07:28:26.000Z | #pragma once
#include <assert.h>
#include "natalie/env.hpp"
#include "natalie/forward.hpp"
#include "natalie/gc.hpp"
#include "natalie/global_env.hpp"
#include "natalie/macros.hpp"
#include "natalie/method_visibility.hpp"
#include "natalie/object_type.hpp"
#include "natalie/value.hpp"
#include "tm/hashmap.hpp"
namespace Natalie {
extern "C" {
#include "onigmo.h"
}
class Object : public Cell {
public:
using Type = ObjectType;
enum Flag {
MainObject = 1,
Frozen = 2,
Break = 4,
Redo = 8,
Inspecting = 16,
};
enum class Conversion {
Strict,
NullAllowed,
};
enum class ConstLookupSearchMode {
NotStrict,
Strict,
};
enum class ConstLookupFailureMode {
Null,
Raise,
};
Object()
: m_klass { GlobalEnv::the()->Object() } { }
Object(ClassObject *klass)
: m_klass { klass } {
assert(klass);
}
Object(Type type, ClassObject *klass)
: m_klass { klass }
, m_type { type } {
assert(klass);
}
Object(const Object &);
Object &operator=(const Object &) = delete;
Object &operator=(Object &&other) {
m_type = other.m_type;
m_singleton_class = other.m_singleton_class;
m_owner = other.m_owner;
m_flags = other.m_flags;
m_ivars = std::move(other.m_ivars);
return *this;
}
virtual ~Object() override {
m_type = ObjectType::Nil;
}
static Value create(Env *, ClassObject *);
static Value _new(Env *, Value, size_t, Value *, Block *);
static Value allocate(Env *, Value, size_t, Value *, Block *);
Type type() { return m_type; }
ClassObject *klass() const { return m_klass; }
ModuleObject *owner() { return m_owner; }
void set_owner(ModuleObject *owner) { m_owner = owner; }
int flags() const { return m_flags; }
Value initialize(Env *);
bool is_nil() const { return m_type == Type::Nil; }
bool is_true() const { return m_type == Type::True; }
bool is_false() const { return m_type == Type::False; }
bool is_fiber() const { return m_type == Type::Fiber; }
bool is_array() const { return m_type == Type::Array; }
bool is_method() const { return m_type == Type::Method; }
bool is_module() const { return m_type == Type::Module || m_type == Type::Class; }
bool is_class() const { return m_type == Type::Class; }
bool is_encoding() const { return m_type == Type::Encoding; }
bool is_exception() const { return m_type == Type::Exception; }
bool is_float() const { return m_type == Type::Float; }
bool is_hash() const { return m_type == Type::Hash; }
bool is_integer() const { return m_type == Type::Integer; }
bool is_io() const { return m_type == Type::Io; }
bool is_match_data() const { return m_type == Type::MatchData; }
bool is_proc() const { return m_type == Type::Proc; }
bool is_random() const { return m_type == Type::Random; }
bool is_range() const { return m_type == Type::Range; }
bool is_rational() const { return m_type == Type::Rational; }
bool is_regexp() const { return m_type == Type::Regexp; }
bool is_symbol() const { return m_type == Type::Symbol; }
bool is_string() const { return m_type == Type::String; }
bool is_unbound_method() const { return m_type == Type::UnboundMethod; }
bool is_void_p() const { return m_type == Type::VoidP; }
bool is_truthy() const { return !is_false() && !is_nil(); }
bool is_falsey() const { return !is_truthy(); }
bool is_numeric() const { return is_integer() || is_float(); }
bool is_boolean() const { return is_true() || is_false(); }
ArrayObject *as_array();
ClassObject *as_class();
EncodingObject *as_encoding();
ExceptionObject *as_exception();
FalseObject *as_false();
FiberObject *as_fiber();
FileObject *as_file();
FloatObject *as_float();
HashObject *as_hash();
IntegerObject *as_integer();
IoObject *as_io();
MatchDataObject *as_match_data();
MethodObject *as_method();
ModuleObject *as_module();
NilObject *as_nil();
ProcObject *as_proc();
RandomObject *as_random();
RangeObject *as_range();
RationalObject *as_rational();
RegexpObject *as_regexp();
StringObject *as_string();
const StringObject *as_string() const;
SymbolObject *as_symbol();
TrueObject *as_true();
UnboundMethodObject *as_unbound_method();
VoidPObject *as_void_p();
KernelModule *as_kernel_module_for_method_binding();
EnvObject *as_env_object_for_method_binding();
ParserObject *as_parser_object_for_method_binding();
SexpObject *as_sexp_object_for_method_binding();
SymbolObject *to_symbol(Env *, Conversion);
SymbolObject *to_instance_variable_name(Env *);
ClassObject *singleton_class() const { return m_singleton_class; }
ClassObject *singleton_class(Env *);
ClassObject *subclass(Env *env, const char *name);
void set_singleton_class(ClassObject *);
Value extend(Env *, size_t, Value *);
void extend_once(Env *, ModuleObject *);
virtual Value const_find(Env *, SymbolObject *, ConstLookupSearchMode = ConstLookupSearchMode::Strict, ConstLookupFailureMode = ConstLookupFailureMode::Raise);
virtual Value const_get(SymbolObject *);
virtual Value const_fetch(SymbolObject *);
virtual Value const_set(SymbolObject *, Value);
bool ivar_defined(Env *, SymbolObject *);
Value ivar_get(Env *, SymbolObject *);
Value ivar_remove(Env *, SymbolObject *);
Value ivar_set(Env *, SymbolObject *, Value);
Value instance_variables(Env *);
Value cvar_get(Env *, SymbolObject *);
virtual Value cvar_get_or_null(Env *, SymbolObject *);
virtual Value cvar_set(Env *, SymbolObject *, Value);
virtual SymbolObject *define_method(Env *, SymbolObject *, MethodFnPtr, int arity);
virtual SymbolObject *define_method(Env *, SymbolObject *, Block *);
virtual SymbolObject *undefine_method(Env *, SymbolObject *);
SymbolObject *define_singleton_method(Env *, SymbolObject *, MethodFnPtr, int);
SymbolObject *define_singleton_method(Env *, SymbolObject *, Block *);
SymbolObject *undefine_singleton_method(Env *, SymbolObject *);
Value main_obj_define_method(Env *, Value, Value, Block *);
virtual Value private_method(Env *, size_t, Value *);
virtual Value protected_method(Env *, size_t, Value *);
virtual Value module_function(Env *, size_t, Value *);
void private_method(Env *, SymbolObject *);
void protected_method(Env *, SymbolObject *);
void module_function(Env *, SymbolObject *);
void alias(Env *env, Value new_name, Value old_name);
virtual void alias(Env *, SymbolObject *, SymbolObject *);
nat_int_t object_id() const { return reinterpret_cast<nat_int_t>(this); }
Value itself() { return this; }
const ManagedString *pointer_id() {
char buf[100]; // ought to be enough for anybody ;-)
snprintf(buf, 100, "%p", this);
return new ManagedString(buf);
}
Value public_send(Env *, SymbolObject *, size_t = 0, Value * = nullptr, Block * = nullptr);
Value public_send(Env *, size_t, Value *, Block *);
Value send(Env *, SymbolObject *, size_t = 0, Value * = nullptr, Block * = nullptr);
Value send(Env *, size_t, Value *, Block *);
Value send(Env *env, SymbolObject *name, std::initializer_list<Value> args, Block *block = nullptr) {
return send(env, name, args.size(), const_cast<Value *>(data(args)), block);
}
Value send(Env *, SymbolObject *, size_t, Value *, Block *, MethodVisibility);
Value method_missing(Env *, size_t, Value *, Block *);
Method *find_method(Env *, SymbolObject *, MethodVisibility);
Value dup(Env *);
Value clone(Env *env);
bool is_a(Env *, Value) const;
bool respond_to(Env *, Value, bool = true);
bool respond_to_method(Env *, Value, Value) const;
bool respond_to_method(Env *, Value, bool) const;
const char *defined(Env *, SymbolObject *, bool);
Value defined_obj(Env *, SymbolObject *, bool = false);
virtual ProcObject *to_proc(Env *);
bool is_main_object() const { return (m_flags & Flag::MainObject) == Flag::MainObject; }
void add_main_object_flag() { m_flags = m_flags | Flag::MainObject; }
bool is_frozen() const { return is_integer() || is_float() || (m_flags & Flag::Frozen) == Flag::Frozen; }
void freeze() { m_flags = m_flags | Flag::Frozen; }
void add_break_flag() { m_flags = m_flags | Flag::Break; }
void remove_break_flag() { m_flags = m_flags & ~Flag::Break; }
bool has_break_flag() const { return (m_flags & Flag::Break) == Flag::Break; }
void add_redo_flag() { m_flags = m_flags | Flag::Redo; }
void remove_redo_flag() { m_flags = m_flags & ~Flag::Redo; }
bool has_redo_flag() const { return (m_flags & Flag::Redo) == Flag::Redo; }
void add_inspecting_flag() { m_flags = m_flags | Flag::Inspecting; }
void remove_inspecting_flag() { m_flags = m_flags & ~Flag::Inspecting; }
bool has_inspecting_flag() const { return (m_flags & Flag::Inspecting) == Flag::Inspecting; }
bool eq(Env *, Value other) {
return other == this;
}
bool equal(Value);
bool neq(Env *env, Value other);
Value instance_eval(Env *, Value, Block *);
void assert_type(Env *, Object::Type, const char *);
void assert_not_frozen(Env *);
const ManagedString *inspect_str(Env *);
Value enum_for(Env *env, const char *method, size_t argc = 0, Value *args = nullptr);
virtual void visit_children(Visitor &visitor) override;
virtual void gc_inspect(char *buf, size_t len) const override;
ArrayObject *to_ary(Env *env);
IntegerObject *to_int(Env *env);
StringObject *to_str(Env *env);
protected:
ClassObject *m_klass { nullptr };
private:
Type m_type { Type::Object };
ClassObject *m_singleton_class { nullptr };
ModuleObject *m_owner { nullptr };
int m_flags { 0 };
TM::Hashmap<SymbolObject *, Value> m_ivars {};
};
}
| 33.76 | 163 | 0.655608 | natalie-lang |
3bd90cf5b0d3fb9f817a2f94c935e86335bc02d4 | 6,935 | cpp | C++ | src/image_management/lib/mesh/mesh_parametric.cpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | src/image_management/lib/mesh/mesh_parametric.cpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | src/image_management/lib/mesh/mesh_parametric.cpp | Neckrome/vectorFieldSurface | 91afebadf9815e6a2dc658cdce82691fddd603ee | [
"MIT"
] | null | null | null | /*
** TP CPE Lyon
** Copyright (C) 2015 Damien Rohmer
**
** This program is free software: you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mesh_parametric.hpp"
#include "../common/error_handling.hpp"
namespace cpe
{
mesh_parametric::mesh_parametric()
:mesh_basic(),size_u_data(0),size_v_data(0)
{}
void mesh_parametric::set_plane_xy_unit(int const size_u_param,int const size_v_param)
{
ASSERT_CPE(size_u_param>0 && size_v_param>0 , "Problem of mesh size");
size_u_data = size_u_param;
size_v_data = size_v_param;
//set data
for(int kv=0 ; kv<size_v_param ; ++kv)
{
float const v = static_cast<float>(kv)/(size_v_param-1);
for(int ku=0 ; ku<size_u_param ; ++ku)
{
float const u = static_cast<float>(ku)/(size_u_param-1);
add_vertex( {u,v,0.0f} );
add_texture_coord( {u,v} );
add_normal( {0.0f,0.0f,1.0f} );
}
}
//set connectivity
for(int kv=0 ; kv<size_v_param-1 ; ++kv)
{
for(int ku=0 ; ku<size_u_param-1 ; ++ku)
{
int const offset = ku+size_u_param*kv;
triangle_index tri0 = {offset,offset+1,offset+size_u_param+1};
triangle_index tri1 = {offset,offset+size_u_param+1,offset+size_u_param};
add_triangle_index(tri0);
add_triangle_index(tri1);
}
}
fill_empty_field_by_default();
ASSERT_CPE(valid_mesh(),"Mesh is not valid");
}
int mesh_parametric::size_u() const {return size_u_data;}
int mesh_parametric::size_v() const {return size_v_data;}
vec3 mesh_parametric::vertex(int const ku,int const kv) const
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::vertex(offset);
}
vec3& mesh_parametric::vertex(int const ku,int const kv)
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::vertex(offset);
}
vec3 mesh_parametric::normal(int const ku,int const kv) const
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::normal(offset);
}
vec3& mesh_parametric::normal(int const ku,int const kv)
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::normal(offset);
}
vec3 mesh_parametric::color(int const ku,int const kv) const
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::color(offset);
}
vec3& mesh_parametric::color(int const ku,int const kv)
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::color(offset);
}
vec2 mesh_parametric::texture_coord(int const ku,int const kv) const
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::texture_coord(offset);
}
vec2& mesh_parametric::texture_coord(int const ku,int const kv)
{
ASSERT_CPE(ku >= 0 , "Value ku ("+std::to_string(ku)+") should be >=0 ");
ASSERT_CPE(ku < size_u() , "Value ku ("+std::to_string(ku)+") should be < size_u ("+std::to_string(size_u())+")");
ASSERT_CPE(ku >= 0 , "Value kv ("+std::to_string(kv)+") should be >=0 ");
ASSERT_CPE(ku < size_v() , "Value kv ("+std::to_string(kv)+") should be < size_v ("+std::to_string(size_v())+")");
int const offset = ku+size_u_data*kv;
return mesh_basic::texture_coord(offset);
}
bool mesh_parametric::valid_mesh() const
{
int const total_size=size_u()*size_v();
if(size_vertex()!=total_size ||
size_color()!=total_size ||
size_texture_coord()!=total_size ||
size_normal()!=total_size )
{
std::cout<<"mesh parametric has incorrect data size"<<std::endl;
return false;
}
return mesh_basic::valid_mesh();
}
}
| 39.856322 | 118 | 0.627397 | Neckrome |
3bdaaa126f48ef28a0f539ba46397f3bc53d6277 | 995 | cpp | C++ | hdu-winter-2020/contests/PTA天梯/2/11.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | 1 | 2020-08-10T21:40:21.000Z | 2020-08-10T21:40:21.000Z | hdu-winter-2020/contests/PTA天梯/2/11.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | hdu-winter-2020/contests/PTA天梯/2/11.cpp | songhn233/Algorithm-Packages | 56d6f3c2467c175ab8a19b82bdfb25fc881e2206 | [
"CC0-1.0"
] | null | null | null | #include<cstdio>
#include<algorithm>
#include<cstring>
#include<iostream>
#include<vector>
#include<queue>
#include<cmath>
#include<map>
#include<set>
#define ll long long
#define F(i,a,b) for(int i=(a);i<=(b);i++)
#define mst(a,b) memset((a),(b),sizeof(a))
#define PII pair<int,int>
using namespace std;
template<class T>inline void read(T &x) {
x=0; int ch=getchar(),f=0;
while(ch<'0'||ch>'9'){if (ch=='-') f=1;ch=getchar();}
while (ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+(ch^48);ch=getchar();}
if(f)x=-x;
}
const int inf=0x3f3f3f3f;
const int maxn=10050;
int n,k,m;
double ans[maxn];
int main()
{
cin>>n>>k>>m;
for(int i=1;i<=n;i++)
{
int maxx=-inf,minx=inf;
int x;
double temp=0;
for(int j=1;j<=k;j++)
{
read(x);
maxx=max(maxx,x);
minx=min(minx,x);
temp+=x;
}
temp-=(maxx+minx);
temp/=(k-2);
ans[i]=temp;
}
sort(ans+1,ans+n+1);
for(int i=n-m+1;i<=n;i++)
{
if(i!=n) printf("%.3lf ",ans[i]);
else printf("%.3lf\n",ans[i]);
}
return 0;
}
| 18.773585 | 67 | 0.574874 | songhn233 |
3be54d8117eee3a2945d79380715c028264d6324 | 2,669 | cpp | C++ | submitted_models/bosdyn_spot/src/joint_trajectory_bridge.cpp | jfkeller/subt_explorer_canary1_sensor_config_1 | 1f0419130b79f48c66e83c084e704e521782a95a | [
"ECL-2.0",
"Apache-2.0"
] | 173 | 2020-04-09T18:39:39.000Z | 2022-03-15T06:15:07.000Z | submitted_models/bosdyn_spot/src/joint_trajectory_bridge.cpp | jfkeller/subt_explorer_canary1_sensor_config_1 | 1f0419130b79f48c66e83c084e704e521782a95a | [
"ECL-2.0",
"Apache-2.0"
] | 538 | 2020-04-09T18:34:04.000Z | 2022-02-20T09:53:17.000Z | submitted_models/bosdyn_spot/src/joint_trajectory_bridge.cpp | jfkeller/subt_explorer_canary1_sensor_config_1 | 1f0419130b79f48c66e83c084e704e521782a95a | [
"ECL-2.0",
"Apache-2.0"
] | 89 | 2020-04-14T20:46:48.000Z | 2022-03-14T16:45:30.000Z | #include <memory>
#include <ignition/msgs/joint_trajectory.pb.h>
#include <ignition/transport/Node.hh>
#include <ros/ros.h>
#include <trajectory_msgs/JointTrajectory.h>
#include <nodelet/nodelet.h>
#include <ros_ign_bridge/convert.hpp>
#include <pluginlib/class_list_macros.h>
using namespace ros_ign_bridge;
namespace subt
{
/// \brief ROS-Ign bridge for JointTrajectory messages.
class JointTrajectoryBridge : public nodelet::Nodelet
{
protected: void onInit() override
{
if (!this->getPrivateNodeHandle().getParam("ign_topic", this->ignTopic))
{
ROS_ERROR("Please, provide parameter ~ign_topic");
exit(1);
}
this->sub = this->getPrivateNodeHandle().subscribe("trajectory", 100, &JointTrajectoryBridge::OnTrajectory, this);
ROS_INFO("Publishing to Ignition topic %s", this->ignTopic.c_str());
this->pub = this->node.Advertise<ignition::msgs::JointTrajectory>(this->ignTopic);
}
protected: void OnTrajectory(const trajectory_msgs::JointTrajectory& msg)
{
ROS_INFO_ONCE("Publishing first message to topic %s", this->ignTopic.c_str());
ignition::msgs::JointTrajectory ignMsg;
convert_ros_to_ign(msg.header, (*ignMsg.mutable_header()));
ignMsg.mutable_points()->Reserve(msg.points.size());
for (const auto & name : msg.joint_names)
ignMsg.add_joint_names(name);
ignMsg.mutable_points()->Reserve(msg.points.size());
for (const auto& point : msg.points)
{
auto* ignPoint = ignMsg.add_points();
ignPoint->mutable_positions()->Reserve(point.positions.size());
for (const auto & ros_position : point.positions)
ignPoint->add_positions(ros_position);
ignPoint->mutable_velocities()->Reserve(point.velocities.size());
for (const auto & ros_velocity : point.velocities)
ignPoint->add_velocities(ros_velocity);
ignPoint->mutable_accelerations()->Reserve(point.accelerations.size());
for (const auto & ros_acceleration : point.accelerations)
ignPoint->add_accelerations(ros_acceleration);
ignPoint->mutable_effort()->Reserve(point.effort.size());
for (const auto & ros_effort : point.effort)
ignPoint->add_effort(ros_effort);
auto* ign_duration = ignPoint->mutable_time_from_start();
ign_duration->set_sec(point.time_from_start.sec);
ign_duration->set_nsec(point.time_from_start.nsec);
}
this->pub.Publish(ignMsg);
}
protected: ignition::transport::Node::Publisher pub;
protected: ignition::transport::Node node;
protected: ros::Subscriber sub;
protected: std::string ignTopic;
};
}
PLUGINLIB_EXPORT_CLASS(subt::JointTrajectoryBridge, nodelet::Nodelet) | 31.4 | 118 | 0.715624 | jfkeller |
3beb3f81bf5ec69428d08f176bc4edde3ddc0edc | 518 | hpp | C++ | chaine/src/mesh/mesh/vertices.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/mesh/mesh/vertices.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/mesh/mesh/vertices.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | #pragma once
#include "mesh.hpp"
#include "mesh/vertex/is_valid.hpp"
#include "mesh/vertex/proxy.hpp"
#include <range/v3/view/filter.hpp>
#include <range/v3/view/iota.hpp>
#include <range/v3/view/transform.hpp>
namespace face_vertex {
inline
auto vertices(Mesh& m) {
return ranges::views::ints(uint32_t(0), vertex_count(m))
| ranges::views::transform([&m] (auto i) {
return proxy(m, VertexIndex{i}); })
| ranges::views::filter([](const VertexProxy& vp) {
return is_valid(vp); });
}
}
| 21.583333 | 60 | 0.667954 | the-last-willy |
3bed17f1ca772fbb99cd489f79a67eb67330052b | 31,137 | cpp | C++ | aws-cpp-sdk-awstransfer/source/TransferClient.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-awstransfer/source/TransferClient.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-awstransfer/source/TransferClient.cpp | crazecdwn/aws-sdk-cpp | e74b9181a56e82ee04cf36a4cb31686047f4be42 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/core/utils/Outcome.h>
#include <aws/core/auth/AWSAuthSigner.h>
#include <aws/core/client/CoreErrors.h>
#include <aws/core/client/RetryStrategy.h>
#include <aws/core/http/HttpClient.h>
#include <aws/core/http/HttpResponse.h>
#include <aws/core/http/HttpClientFactory.h>
#include <aws/core/auth/AWSCredentialsProviderChain.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>
#include <aws/core/utils/threading/Executor.h>
#include <aws/core/utils/DNS.h>
#include <aws/core/utils/logging/LogMacros.h>
#include <aws/awstransfer/TransferClient.h>
#include <aws/awstransfer/TransferEndpoint.h>
#include <aws/awstransfer/TransferErrorMarshaller.h>
#include <aws/awstransfer/model/CreateServerRequest.h>
#include <aws/awstransfer/model/CreateUserRequest.h>
#include <aws/awstransfer/model/DeleteServerRequest.h>
#include <aws/awstransfer/model/DeleteSshPublicKeyRequest.h>
#include <aws/awstransfer/model/DeleteUserRequest.h>
#include <aws/awstransfer/model/DescribeServerRequest.h>
#include <aws/awstransfer/model/DescribeUserRequest.h>
#include <aws/awstransfer/model/ImportSshPublicKeyRequest.h>
#include <aws/awstransfer/model/ListServersRequest.h>
#include <aws/awstransfer/model/ListTagsForResourceRequest.h>
#include <aws/awstransfer/model/ListUsersRequest.h>
#include <aws/awstransfer/model/StartServerRequest.h>
#include <aws/awstransfer/model/StopServerRequest.h>
#include <aws/awstransfer/model/TagResourceRequest.h>
#include <aws/awstransfer/model/TestIdentityProviderRequest.h>
#include <aws/awstransfer/model/UntagResourceRequest.h>
#include <aws/awstransfer/model/UpdateServerRequest.h>
#include <aws/awstransfer/model/UpdateUserRequest.h>
using namespace Aws;
using namespace Aws::Auth;
using namespace Aws::Client;
using namespace Aws::Transfer;
using namespace Aws::Transfer::Model;
using namespace Aws::Http;
using namespace Aws::Utils::Json;
static const char* SERVICE_NAME = "transfer";
static const char* ALLOCATION_TAG = "TransferClient";
TransferClient::TransferClient(const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<DefaultAWSCredentialsProviderChain>(ALLOCATION_TAG),
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<TransferErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
TransferClient::TransferClient(const AWSCredentials& credentials, const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, Aws::MakeShared<SimpleAWSCredentialsProvider>(ALLOCATION_TAG, credentials),
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<TransferErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
TransferClient::TransferClient(const std::shared_ptr<AWSCredentialsProvider>& credentialsProvider,
const Client::ClientConfiguration& clientConfiguration) :
BASECLASS(clientConfiguration,
Aws::MakeShared<AWSAuthV4Signer>(ALLOCATION_TAG, credentialsProvider,
SERVICE_NAME, clientConfiguration.region),
Aws::MakeShared<TransferErrorMarshaller>(ALLOCATION_TAG)),
m_executor(clientConfiguration.executor)
{
init(clientConfiguration);
}
TransferClient::~TransferClient()
{
}
void TransferClient::init(const ClientConfiguration& config)
{
m_configScheme = SchemeMapper::ToString(config.scheme);
if (config.endpointOverride.empty())
{
m_uri = m_configScheme + "://" + TransferEndpoint::ForRegion(config.region, config.useDualStack);
}
else
{
OverrideEndpoint(config.endpointOverride);
}
}
void TransferClient::OverrideEndpoint(const Aws::String& endpoint)
{
if (endpoint.compare(0, 7, "http://") == 0 || endpoint.compare(0, 8, "https://") == 0)
{
m_uri = endpoint;
}
else
{
m_uri = m_configScheme + "://" + endpoint;
}
}
CreateServerOutcome TransferClient::CreateServer(const CreateServerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateServerOutcome(CreateServerResult(outcome.GetResult()));
}
else
{
return CreateServerOutcome(outcome.GetError());
}
}
CreateServerOutcomeCallable TransferClient::CreateServerCallable(const CreateServerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateServerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateServer(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::CreateServerAsync(const CreateServerRequest& request, const CreateServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateServerAsyncHelper( request, handler, context ); } );
}
void TransferClient::CreateServerAsyncHelper(const CreateServerRequest& request, const CreateServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateServer(request), context);
}
CreateUserOutcome TransferClient::CreateUser(const CreateUserRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return CreateUserOutcome(CreateUserResult(outcome.GetResult()));
}
else
{
return CreateUserOutcome(outcome.GetError());
}
}
CreateUserOutcomeCallable TransferClient::CreateUserCallable(const CreateUserRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< CreateUserOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->CreateUser(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::CreateUserAsync(const CreateUserRequest& request, const CreateUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->CreateUserAsyncHelper( request, handler, context ); } );
}
void TransferClient::CreateUserAsyncHelper(const CreateUserRequest& request, const CreateUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, CreateUser(request), context);
}
DeleteServerOutcome TransferClient::DeleteServer(const DeleteServerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteServerOutcome(NoResult());
}
else
{
return DeleteServerOutcome(outcome.GetError());
}
}
DeleteServerOutcomeCallable TransferClient::DeleteServerCallable(const DeleteServerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteServerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteServer(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::DeleteServerAsync(const DeleteServerRequest& request, const DeleteServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteServerAsyncHelper( request, handler, context ); } );
}
void TransferClient::DeleteServerAsyncHelper(const DeleteServerRequest& request, const DeleteServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteServer(request), context);
}
DeleteSshPublicKeyOutcome TransferClient::DeleteSshPublicKey(const DeleteSshPublicKeyRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteSshPublicKeyOutcome(NoResult());
}
else
{
return DeleteSshPublicKeyOutcome(outcome.GetError());
}
}
DeleteSshPublicKeyOutcomeCallable TransferClient::DeleteSshPublicKeyCallable(const DeleteSshPublicKeyRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteSshPublicKeyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteSshPublicKey(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::DeleteSshPublicKeyAsync(const DeleteSshPublicKeyRequest& request, const DeleteSshPublicKeyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteSshPublicKeyAsyncHelper( request, handler, context ); } );
}
void TransferClient::DeleteSshPublicKeyAsyncHelper(const DeleteSshPublicKeyRequest& request, const DeleteSshPublicKeyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteSshPublicKey(request), context);
}
DeleteUserOutcome TransferClient::DeleteUser(const DeleteUserRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DeleteUserOutcome(NoResult());
}
else
{
return DeleteUserOutcome(outcome.GetError());
}
}
DeleteUserOutcomeCallable TransferClient::DeleteUserCallable(const DeleteUserRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DeleteUserOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DeleteUser(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::DeleteUserAsync(const DeleteUserRequest& request, const DeleteUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DeleteUserAsyncHelper( request, handler, context ); } );
}
void TransferClient::DeleteUserAsyncHelper(const DeleteUserRequest& request, const DeleteUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DeleteUser(request), context);
}
DescribeServerOutcome TransferClient::DescribeServer(const DescribeServerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DescribeServerOutcome(DescribeServerResult(outcome.GetResult()));
}
else
{
return DescribeServerOutcome(outcome.GetError());
}
}
DescribeServerOutcomeCallable TransferClient::DescribeServerCallable(const DescribeServerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeServerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeServer(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::DescribeServerAsync(const DescribeServerRequest& request, const DescribeServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeServerAsyncHelper( request, handler, context ); } );
}
void TransferClient::DescribeServerAsyncHelper(const DescribeServerRequest& request, const DescribeServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeServer(request), context);
}
DescribeUserOutcome TransferClient::DescribeUser(const DescribeUserRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return DescribeUserOutcome(DescribeUserResult(outcome.GetResult()));
}
else
{
return DescribeUserOutcome(outcome.GetError());
}
}
DescribeUserOutcomeCallable TransferClient::DescribeUserCallable(const DescribeUserRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< DescribeUserOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->DescribeUser(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::DescribeUserAsync(const DescribeUserRequest& request, const DescribeUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->DescribeUserAsyncHelper( request, handler, context ); } );
}
void TransferClient::DescribeUserAsyncHelper(const DescribeUserRequest& request, const DescribeUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, DescribeUser(request), context);
}
ImportSshPublicKeyOutcome TransferClient::ImportSshPublicKey(const ImportSshPublicKeyRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ImportSshPublicKeyOutcome(ImportSshPublicKeyResult(outcome.GetResult()));
}
else
{
return ImportSshPublicKeyOutcome(outcome.GetError());
}
}
ImportSshPublicKeyOutcomeCallable TransferClient::ImportSshPublicKeyCallable(const ImportSshPublicKeyRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ImportSshPublicKeyOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ImportSshPublicKey(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::ImportSshPublicKeyAsync(const ImportSshPublicKeyRequest& request, const ImportSshPublicKeyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ImportSshPublicKeyAsyncHelper( request, handler, context ); } );
}
void TransferClient::ImportSshPublicKeyAsyncHelper(const ImportSshPublicKeyRequest& request, const ImportSshPublicKeyResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ImportSshPublicKey(request), context);
}
ListServersOutcome TransferClient::ListServers(const ListServersRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListServersOutcome(ListServersResult(outcome.GetResult()));
}
else
{
return ListServersOutcome(outcome.GetError());
}
}
ListServersOutcomeCallable TransferClient::ListServersCallable(const ListServersRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListServersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListServers(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::ListServersAsync(const ListServersRequest& request, const ListServersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListServersAsyncHelper( request, handler, context ); } );
}
void TransferClient::ListServersAsyncHelper(const ListServersRequest& request, const ListServersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListServers(request), context);
}
ListTagsForResourceOutcome TransferClient::ListTagsForResource(const ListTagsForResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListTagsForResourceOutcome(ListTagsForResourceResult(outcome.GetResult()));
}
else
{
return ListTagsForResourceOutcome(outcome.GetError());
}
}
ListTagsForResourceOutcomeCallable TransferClient::ListTagsForResourceCallable(const ListTagsForResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListTagsForResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListTagsForResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::ListTagsForResourceAsync(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListTagsForResourceAsyncHelper( request, handler, context ); } );
}
void TransferClient::ListTagsForResourceAsyncHelper(const ListTagsForResourceRequest& request, const ListTagsForResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListTagsForResource(request), context);
}
ListUsersOutcome TransferClient::ListUsers(const ListUsersRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return ListUsersOutcome(ListUsersResult(outcome.GetResult()));
}
else
{
return ListUsersOutcome(outcome.GetError());
}
}
ListUsersOutcomeCallable TransferClient::ListUsersCallable(const ListUsersRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< ListUsersOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->ListUsers(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::ListUsersAsync(const ListUsersRequest& request, const ListUsersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->ListUsersAsyncHelper( request, handler, context ); } );
}
void TransferClient::ListUsersAsyncHelper(const ListUsersRequest& request, const ListUsersResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, ListUsers(request), context);
}
StartServerOutcome TransferClient::StartServer(const StartServerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return StartServerOutcome(NoResult());
}
else
{
return StartServerOutcome(outcome.GetError());
}
}
StartServerOutcomeCallable TransferClient::StartServerCallable(const StartServerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< StartServerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StartServer(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::StartServerAsync(const StartServerRequest& request, const StartServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->StartServerAsyncHelper( request, handler, context ); } );
}
void TransferClient::StartServerAsyncHelper(const StartServerRequest& request, const StartServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, StartServer(request), context);
}
StopServerOutcome TransferClient::StopServer(const StopServerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return StopServerOutcome(NoResult());
}
else
{
return StopServerOutcome(outcome.GetError());
}
}
StopServerOutcomeCallable TransferClient::StopServerCallable(const StopServerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< StopServerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->StopServer(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::StopServerAsync(const StopServerRequest& request, const StopServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->StopServerAsyncHelper( request, handler, context ); } );
}
void TransferClient::StopServerAsyncHelper(const StopServerRequest& request, const StopServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, StopServer(request), context);
}
TagResourceOutcome TransferClient::TagResource(const TagResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return TagResourceOutcome(NoResult());
}
else
{
return TagResourceOutcome(outcome.GetError());
}
}
TagResourceOutcomeCallable TransferClient::TagResourceCallable(const TagResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< TagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TagResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::TagResourceAsync(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->TagResourceAsyncHelper( request, handler, context ); } );
}
void TransferClient::TagResourceAsyncHelper(const TagResourceRequest& request, const TagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, TagResource(request), context);
}
TestIdentityProviderOutcome TransferClient::TestIdentityProvider(const TestIdentityProviderRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return TestIdentityProviderOutcome(TestIdentityProviderResult(outcome.GetResult()));
}
else
{
return TestIdentityProviderOutcome(outcome.GetError());
}
}
TestIdentityProviderOutcomeCallable TransferClient::TestIdentityProviderCallable(const TestIdentityProviderRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< TestIdentityProviderOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->TestIdentityProvider(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::TestIdentityProviderAsync(const TestIdentityProviderRequest& request, const TestIdentityProviderResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->TestIdentityProviderAsyncHelper( request, handler, context ); } );
}
void TransferClient::TestIdentityProviderAsyncHelper(const TestIdentityProviderRequest& request, const TestIdentityProviderResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, TestIdentityProvider(request), context);
}
UntagResourceOutcome TransferClient::UntagResource(const UntagResourceRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UntagResourceOutcome(NoResult());
}
else
{
return UntagResourceOutcome(outcome.GetError());
}
}
UntagResourceOutcomeCallable TransferClient::UntagResourceCallable(const UntagResourceRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UntagResourceOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UntagResource(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::UntagResourceAsync(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UntagResourceAsyncHelper( request, handler, context ); } );
}
void TransferClient::UntagResourceAsyncHelper(const UntagResourceRequest& request, const UntagResourceResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UntagResource(request), context);
}
UpdateServerOutcome TransferClient::UpdateServer(const UpdateServerRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateServerOutcome(UpdateServerResult(outcome.GetResult()));
}
else
{
return UpdateServerOutcome(outcome.GetError());
}
}
UpdateServerOutcomeCallable TransferClient::UpdateServerCallable(const UpdateServerRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateServerOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateServer(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::UpdateServerAsync(const UpdateServerRequest& request, const UpdateServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateServerAsyncHelper( request, handler, context ); } );
}
void TransferClient::UpdateServerAsyncHelper(const UpdateServerRequest& request, const UpdateServerResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateServer(request), context);
}
UpdateUserOutcome TransferClient::UpdateUser(const UpdateUserRequest& request) const
{
Aws::Http::URI uri = m_uri;
Aws::StringStream ss;
ss << "/";
uri.SetPath(uri.GetPath() + ss.str());
JsonOutcome outcome = MakeRequest(uri, request, HttpMethod::HTTP_POST, Aws::Auth::SIGV4_SIGNER);
if(outcome.IsSuccess())
{
return UpdateUserOutcome(UpdateUserResult(outcome.GetResult()));
}
else
{
return UpdateUserOutcome(outcome.GetError());
}
}
UpdateUserOutcomeCallable TransferClient::UpdateUserCallable(const UpdateUserRequest& request) const
{
auto task = Aws::MakeShared< std::packaged_task< UpdateUserOutcome() > >(ALLOCATION_TAG, [this, request](){ return this->UpdateUser(request); } );
auto packagedFunction = [task]() { (*task)(); };
m_executor->Submit(packagedFunction);
return task->get_future();
}
void TransferClient::UpdateUserAsync(const UpdateUserRequest& request, const UpdateUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
m_executor->Submit( [this, request, handler, context](){ this->UpdateUserAsyncHelper( request, handler, context ); } );
}
void TransferClient::UpdateUserAsyncHelper(const UpdateUserRequest& request, const UpdateUserResponseReceivedHandler& handler, const std::shared_ptr<const Aws::Client::AsyncCallerContext>& context) const
{
handler(this, request, UpdateUser(request), context);
}
| 41.295756 | 233 | 0.765616 | crazecdwn |
3bf46a0fed869fb16189bcd0d03036eb87c1b47f | 268 | cpp | C++ | testing/check_cpu_time/main.cpp | NewYaroslav/xtime_cpp | d2f7acf223659fb77fbafb1feb536cad636d14d9 | [
"MIT"
] | 1 | 2021-09-15T21:11:57.000Z | 2021-09-15T21:11:57.000Z | testing/check_cpu_time/main.cpp | NewYaroslav/xtime_cpp | d2f7acf223659fb77fbafb1feb536cad636d14d9 | [
"MIT"
] | null | null | null | testing/check_cpu_time/main.cpp | NewYaroslav/xtime_cpp | d2f7acf223659fb77fbafb1feb536cad636d14d9 | [
"MIT"
] | 4 | 2019-12-02T15:17:46.000Z | 2021-10-09T17:32:34.000Z | #include <iostream>
#include <xtime_cpu_time.hpp>
#include <xtime.hpp>
using namespace std;
int main() {
cout << "get_cpu_time " << xtime::get_cpu_time() << endl;
xtime::delay(1);
cout << "get_cpu_time " << xtime::get_cpu_time() << endl;
return 0;
}
| 20.615385 | 61 | 0.634328 | NewYaroslav |
3bf512f486a98f2559dc956fa2be08138c3b36be | 4,571 | cpp | C++ | src/device_intrf.cpp | tmaltesen/IOsonata | 3ada9216305653670fccfca8fd53c6597ace8f12 | [
"MIT"
] | null | null | null | src/device_intrf.cpp | tmaltesen/IOsonata | 3ada9216305653670fccfca8fd53c6597ace8f12 | [
"MIT"
] | null | null | null | src/device_intrf.cpp | tmaltesen/IOsonata | 3ada9216305653670fccfca8fd53c6597ace8f12 | [
"MIT"
] | null | null | null | /**-------------------------------------------------------------------------
@file device_intrf.h
@brief Generic data transfer interface class
This class is used to implement device communication interfaces such as I2C, UART, etc...
Not limited to wired or physical interface. It could be soft interface as well such
as SLIP protocol or any mean of transferring data between 2 entities.
@author Hoang Nguyen Hoan
@date Nov. 25, 2011
@license
Copyright (c) 2011, I-SYST inc., all rights reserved
Permission to use, copy, modify, and distribute this software for any purpose
with or without fee is hereby granted, provided that the above copyright
notice and this permission notice appear in all copies, and none of the
names : I-SYST or its contributors may be used to endorse or
promote products derived from this software without specific prior written
permission.
For info or contributing contact : hnhoan at i-syst dot com
THIS SOFTWARE IS PROVIDED BY THE REGENTS 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 REGENTS 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 <string.h>
#include "device_intrf.h"
// NOTE : For thread safe use
//
// DeviceIntrfStartRx
// DeviceIntrfStopRx
// DeviceIntrfStartTx
// DeviceIntrfStopTx
//
int DeviceIntrfRx(DEVINTRF * const pDev, int DevAddr, uint8_t *pBuff, int BuffLen)
{
if (pBuff == NULL || BuffLen <= 0)
return 0;
int count = 0;
int nrtry = pDev->MaxRetry;
do {
if (DeviceIntrfStartRx(pDev, DevAddr)) {
count = pDev->RxData(pDev, pBuff, BuffLen);
DeviceIntrfStopRx(pDev);
}
} while(count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfTx(DEVINTRF * const pDev, int DevAddr, uint8_t *pBuff, int BuffLen)
{
if (pBuff == NULL || BuffLen <= 0)
return 0;
int count = 0;
int nrtry = pDev->MaxRetry;
do {
if (DeviceIntrfStartTx(pDev, DevAddr)) {
count = pDev->TxData(pDev, pBuff, BuffLen);
DeviceIntrfStopTx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfRead(DEVINTRF * const pDev, int DevAddr, uint8_t *pAdCmd, int AdCmdLen,
uint8_t *pRxBuff, int RxLen)
{
int count = 0;
int nrtry = pDev->MaxRetry;
if (pRxBuff == NULL || RxLen <= 0)
return 0;
do {
if (DeviceIntrfStartTx(pDev, DevAddr))
{
if (pAdCmd)
{
count = pDev->TxData(pDev, pAdCmd, AdCmdLen);
}
// Note : this is restart condition in read mode,
// must not generate any stop condition here
pDev->StartRx(pDev, DevAddr);
count = pDev->RxData(pDev, pRxBuff, RxLen);
DeviceIntrfStopRx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
return count;
}
int DeviceIntrfWrite(DEVINTRF * const pDev, int DevAddr, uint8_t *pAdCmd, int AdCmdLen,
uint8_t *pData, int DataLen)
{
int count = 0, txlen = AdCmdLen;
int nrtry = pDev->MaxRetry;
if (pAdCmd == NULL || (AdCmdLen + DataLen) <= 0)
return 0;
#if defined(WIN32) || defined(__ICCARM__)
uint8_t d[100];
#else
uint8_t d[AdCmdLen + DataLen];
#endif
// NOTE : Some I2C devices that uses DMA transfer may require that the tx to be combined
// into single tx. Because it may generate a end condition at the end of the DMA
memcpy(d, pAdCmd, AdCmdLen);
if (pData != NULL && DataLen > 0)
{
memcpy(&d[AdCmdLen], pData, DataLen);
txlen += DataLen;
}
do {
if (DeviceIntrfStartTx(pDev, DevAddr))
{
count = pDev->TxData(pDev, d, txlen);
DeviceIntrfStopTx(pDev);
}
} while (count <= 0 && nrtry-- > 0);
if (count >= AdCmdLen)
count -= AdCmdLen;
else
count = 0;
return count;
}
| 29.490323 | 90 | 0.625027 | tmaltesen |
0eca31a0efd30ecc59040446adea1a6eb5710747 | 2,925 | cpp | C++ | project-euler/src/matterport_3.cpp | ammarhusain/challenges | efdb907833d04e9e37fc800d1b2b32507cfcd2e4 | [
"MIT"
] | null | null | null | project-euler/src/matterport_3.cpp | ammarhusain/challenges | efdb907833d04e9e37fc800d1b2b32507cfcd2e4 | [
"MIT"
] | null | null | null | project-euler/src/matterport_3.cpp | ammarhusain/challenges | efdb907833d04e9e37fc800d1b2b32507cfcd2e4 | [
"MIT"
] | null | null | null | /** ----------------------------------------------------------------------
* Copyright 2014 < Ammar Husain (Carnegie Mellon University) >
*
* @file pe1.cpp
* @author Ammar Husain <ahusain@nrec.ri.cmu.edu>
* @date Thu Jul 31 17:18:28 2014
*
* @brief Boiler Plate
*
*
---------------------------------------------------------------------- */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <vector>
#include <stdint.h>
#include <iostream>
#include <ctime>
#include <queue>
using namespace std;
struct coordinate {
int x;
int y;
};
int numberOfPaths(int a[][100],int M, int N) {
/// instantiate a matrix the size of a
/// using vector of vector because its just convenient
vector< vector<int> > matrix(M);
/// initialize all elements to 0
for (int i = 0; i < M; i++)
matrix[i].resize(N, 0);
/// set the first element to 0
/// matrix[0][0] = 0;
/// use a queue to queue up possible grids to enter
queue<coordinate> togo;
/// put your position in togo
/// just do that you are not adding stuff outside the loop
coordinate current;
current.x = 0;
current.y = 0;
togo.push(current);
/// initial value for starting position
matrix[0][0] = -1;
/// keep going till we have nowhere to go
while(togo.size() > 0) {
/// get the first position on the queue
coordinate next = togo.front();
togo.pop();
/// increment the counter of getting here by
matrix[next.x][next.y] += 1;
coordinate newGrid;
/// where else can we go
/// right?
if (next.x+1 < M) {
if (a[next.x+1][next.y]){
newGrid.x = next.x+1;
newGrid.y = next.y;
togo.push(newGrid);
}
}
/// down?
if (next.y+1 < N) {
if (a[next.x][next.y+1]){
newGrid.x = next.x;
newGrid.y = next.y+1;
togo.push(newGrid);
}
}
}
/// number of ways is the last element of the matrix
return matrix[M-1][N-1];
}
/** ----------------------------------------------------------------
* Main Routine
*
* @param argc
* @param argv
*
* @return
---------------------------------------------------------------- */
int main(int argc, char *argv[]) {
std::cout << "Boiler-Plate code!" << std::endl;
uint numTests;
std::cin >> numTests;
uint64_t input;
/// keep a timer
std::clock_t start;
double duration;
for (uint i = 0; i < numTests; i++) {
std::cin >> input;
start = std::clock_t();
/// do work here
duration = (std::clock() - start)/static_cast<double>(CLOCKS_PER_SEC);
std::cout<< "it took: "<< duration << "s" << std::endl;
}
return 0;
}
| 22.674419 | 78 | 0.472479 | ammarhusain |
0ecc00b0f90f69711c95911041ca882e83883e44 | 386 | hpp | C++ | include/termox/widget/detail/graph_tree.hpp | a-n-t-h-o-n-y/MCurses | c9184a0fefbdc4eb9a044f815ee2270e6b8f202c | [
"MIT"
] | 284 | 2017-11-07T10:06:48.000Z | 2021-01-12T15:32:51.000Z | include/termox/widget/detail/graph_tree.hpp | a-n-t-h-o-n-y/MCurses | c9184a0fefbdc4eb9a044f815ee2270e6b8f202c | [
"MIT"
] | 38 | 2018-01-14T12:34:54.000Z | 2020-09-26T15:32:43.000Z | include/termox/widget/detail/graph_tree.hpp | a-n-t-h-o-n-y/MCurses | c9184a0fefbdc4eb9a044f815ee2270e6b8f202c | [
"MIT"
] | 31 | 2017-11-30T11:22:21.000Z | 2020-11-03T05:27:47.000Z | #ifndef TERMOX_WIDGET_DETAIL_GRAPH_TREE_HPP
#define TERMOX_WIDGET_DETAIL_GRAPH_TREE_HPP
#include <string>
namespace ox {
class Widget;
} // namespace ox
namespace ox::detail {
/// Outputs filename.gz graph description of widget tree hierarchy.
void graph_tree(Widget const& w, std::string const& filename);
} // namespace ox::detail
#endif // TERMOX_WIDGET_DETAIL_GRAPH_TREE_HPP
| 24.125 | 67 | 0.787565 | a-n-t-h-o-n-y |
0ecd6a9209dfdca0807b129c53b07b9bd52a2b18 | 8,676 | cpp | C++ | tools/clang/test/OpenMP/target_parallel_debug_codegen.cpp | GoSSIP-SJTU/TripleDoggy | 03648d6b19c812504b14e8b98c8c7b3f443f4e54 | [
"Apache-2.0"
] | 171 | 2018-09-17T13:15:12.000Z | 2022-03-18T03:47:04.000Z | tools/clang/test/OpenMP/target_parallel_debug_codegen.cpp | Ewenwan/TripleDoggy | 01db804b6570b1e25e29a387aa2addb68b48335f | [
"Apache-2.0"
] | 7 | 2018-10-05T04:54:18.000Z | 2020-10-02T07:58:13.000Z | tools/clang/test/OpenMP/target_parallel_debug_codegen.cpp | Ewenwan/TripleDoggy | 01db804b6570b1e25e29a387aa2addb68b48335f | [
"Apache-2.0"
] | 35 | 2018-09-18T07:46:53.000Z | 2022-03-27T07:59:48.000Z | // RUN: %clang_cc1 -DCK1 -verify -fopenmp -x c++ -triple powerpc64le-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -fopenmp-cuda-mode -emit-llvm-bc %s -o %t-ppc-host.bc
// RUN: %clang_cc1 -DCK1 -verify -fopenmp -x c++ -triple nvptx64-unknown-unknown -fopenmp-targets=nvptx64-nvidia-cuda -fopenmp-cuda-mode -emit-llvm %s -fopenmp-is-device -fopenmp-host-ir-file-path %t-ppc-host.bc -o - -debug-info-kind=limited | FileCheck %s
// expected-no-diagnostics
int main() {
/* int(*b)[a]; */
/* int *(**c)[a]; */
bool bb;
int a;
int b[10][10];
int c[10][10][10];
#pragma omp target parallel firstprivate(a, b) map(tofrom \
: c) map(tofrom \
: bb) if (a)
{
int &f = c[1][1][1];
int &g = a;
int &h = b[1][1];
int d = 15;
a = 5;
b[0][a] = 10;
c[0][0][a] = 11;
b[0][a] = c[0][0][a];
bb |= b[0][a];
}
#pragma omp target parallel firstprivate(a) map(tofrom \
: c, b) map(to \
: bb)
{
int &f = c[1][1][1];
int &g = a;
int &h = b[1][1];
int d = 15;
a = 5;
b[0][a] = 10;
c[0][0][a] = 11;
b[0][a] = c[0][0][a];
d = bb;
}
#pragma omp target parallel map(tofrom \
: a, c, b) map(from \
: bb)
{
int &f = c[1][1][1];
int &g = a;
int &h = b[1][1];
int d = 15;
a = 5;
b[0][a] = 10;
c[0][0][a] = 11;
b[0][a] = c[0][0][a];
bb = b[0][a];
}
return 0;
}
// CHECK: define internal void @__omp_offloading{{[^(]+}}([10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]]* {{[^,]+}}, i8 addrspace(1)* noalias{{[^,]+}}, i1 {{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]] addrspace(1)* %{{.+}} to [10 x [10 x [10 x i32]]]*
// CHECK: call void [[NONDEBUG_WRAPPER:.+]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]]* {{[^,]+}}, i64 {{[^,]+}}, [10 x [10 x i32]]* {{[^,]+}}, i8* {{[^)]+}})
// CHECK: define internal void [[DEBUG_PARALLEL:@.+]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]] addrspace(1)* noalias{{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]]* noalias{{[^,]+}}, i8 addrspace(1)* noalias{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]] addrspace(1)* %{{.+}} to [10 x [10 x [10 x i32]]]*
// CHECK: define internal void [[NONDEBUG_WRAPPER]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]]* dereferenceable{{[^,]+}}, i64 {{[^,]+}}, [10 x [10 x i32]]* dereferenceable{{[^,]+}}, i8* dereferenceable{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]]* %{{.+}} to [10 x [10 x [10 x i32]]] addrspace(1)*
// CHECK: call void [[DEBUG_PARALLEL]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]]* {{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: define void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]]* dereferenceable{{[^,]+}}, i64 {{[^,]+}}, [10 x [10 x i32]]* dereferenceable{{[^,]+}}, i8* dereferenceable{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]]* %{{.+}} to [10 x [10 x [10 x i32]]] addrspace(1)*
// CHECK: call void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]]* {{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: define internal void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]] addrspace(1)* noalias{{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]] addrspace(1)* noalias{{[^,]+}}, i8 addrspace(1)* noalias{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]] addrspace(1)* %{{.+}} to [10 x [10 x [10 x i32]]]*
// CHECK: addrspacecast [10 x [10 x i32]] addrspace(1)* %{{.+}} to [10 x [10 x i32]]*
// CHECK: call void [[NONDEBUG_WRAPPER:.+]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]]* {{[^,]+}}, i64 {{[^,]+}}, [10 x [10 x i32]]* {{[^,]+}}, i8* {{[^)]+}})
// CHECK: define internal void [[DEBUG_PARALLEL:@.+]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]] addrspace(1)* noalias{{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]] addrspace(1)* noalias{{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]] addrspace(1)* %{{.+}} to [10 x [10 x [10 x i32]]]*
// CHECK: addrspacecast [10 x [10 x i32]] addrspace(1)* %{{.+}} to [10 x [10 x i32]]*
// CHECK: define internal void [[NONDEBUG_WRAPPER]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]]* dereferenceable{{[^,]+}}, i64 {{[^,]+}}, [10 x [10 x i32]]* dereferenceable{{[^,]+}}, i8* dereferenceable{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]]* %{{.+}} to [10 x [10 x [10 x i32]]] addrspace(1)*
// CHECK: addrspacecast [10 x [10 x i32]]* %{{.+}} to [10 x [10 x i32]] addrspace(1)*
// CHECK: call void [[DEBUG_PARALLEL]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]] addrspace(1)* {{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: define void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]]* dereferenceable{{[^,]+}}, i64 {{[^,]+}}, [10 x [10 x i32]]* dereferenceable{{[^,]+}}, i8* dereferenceable{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]]* %{{.+}} to [10 x [10 x [10 x i32]]] addrspace(1)*
// CHECK: addrspacecast [10 x [10 x i32]]* %{{.+}} to [10 x [10 x i32]] addrspace(1)*
// CHECK: call void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 {{[^,]+}}, [10 x [10 x i32]] addrspace(1)* {{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: define internal void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]] addrspace(1)* noalias{{[^,]+}}, i32 addrspace(1)* noalias{{[^,]+}}, [10 x [10 x i32]] addrspace(1)* noalias{{[^,]+}}, i8 addrspace(1)* noalias{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]] addrspace(1)* %{{.+}} to [10 x [10 x [10 x i32]]]*
// CHECK: addrspacecast i32 addrspace(1)* %{{.+}} to i32*
// CHECK: addrspacecast [10 x [10 x i32]] addrspace(1)* %{{.+}} to [10 x [10 x i32]]*
// CHECK: call void @[[NONDEBUG_WRAPPER:.+]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]]* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x i32]]* {{[^,]+}}, i8* {{[^)]+}})
// CHECK: define internal void @[[DEBUG_PARALLEL:.+]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]] addrspace(1)* noalias{{[^,]+}}, i32 addrspace(1)* noalias{{[^,]+}}, [10 x [10 x i32]] addrspace(1)* noalias{{[^,]+}}, i8 addrspace(1)* noalias{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]] addrspace(1)* %{{.+}} to [10 x [10 x [10 x i32]]]*
// CHECK: addrspacecast i32 addrspace(1)* %{{.+}} to i32*
// CHECK: addrspacecast [10 x [10 x i32]] addrspace(1)* %{{.+}} to [10 x [10 x i32]]*
// CHECK: define internal void @[[NONDEBUG_WRAPPER]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]]* dereferenceable{{[^,]+}}, i32* dereferenceable{{[^,]+}}, [10 x [10 x i32]]* dereferenceable{{[^,]+}}, i8* dereferenceable{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]]* %{{.+}} to [10 x [10 x [10 x i32]]] addrspace(1)*
// CHECK: addrspacecast i32* %{{.+}} to i32 addrspace(1)*
// CHECK: addrspacecast [10 x [10 x i32]]* %{{.+}} to [10 x [10 x i32]] addrspace(1)*
// CHECK: call void @[[DEBUG_PARALLEL]](i32* {{[^,]+}}, i32* {{[^,]+}}, [10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 addrspace(1)* {{[^,]+}}, [10 x [10 x i32]] addrspace(1)* {{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: define void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]]* dereferenceable{{[^,]+}}, i32* dereferenceable{{[^,]+}}, [10 x [10 x i32]]* dereferenceable{{[^,]+}}, i8* dereferenceable{{[^)]+}})
// CHECK: addrspacecast [10 x [10 x [10 x i32]]]* %{{.+}} to [10 x [10 x [10 x i32]]] addrspace(1)*
// CHECK: addrspacecast i32* %{{.+}} to i32 addrspace(1)*
// CHECK: addrspacecast [10 x [10 x i32]]* %{{.+}} to [10 x [10 x i32]] addrspace(1)*
// CHECK: call void @__omp_offloading_{{[^(]+}}([10 x [10 x [10 x i32]]] addrspace(1)* {{[^,]+}}, i32 addrspace(1)* {{[^,]+}}, [10 x [10 x i32]] addrspace(1)* {{[^,]+}}, i8 addrspace(1)* {{[^)]+}})
// CHECK: !DILocalVariable(name: ".global_tid.",
// CHECK-SAME: DIFlagArtificial
// CHECK: !DILocalVariable(name: ".bound_tid.",
// CHECK-SAME: DIFlagArtificial
// CHECK: !DILocalVariable(name: "c",
// CHECK-SAME: line: 11
// CHECK: !DILocalVariable(name: "a",
// CHECK-SAME: line: 9
// CHECK: !DILocalVariable(name: "b",
// CHECK-SAME: line: 10
// CHECK-DAG: distinct !DISubprogram(name: "[[NONDEBUG_WRAPPER]]",
// CHECK-DAG: distinct !DISubprogram(name: "[[DEBUG_PARALLEL]]",
| 68.314961 | 263 | 0.496657 | GoSSIP-SJTU |
0ed5374b36fe6cfc5418b1179c1430a452a9f234 | 996 | cpp | C++ | aba12d.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 264 | 2015-01-08T10:07:01.000Z | 2022-03-26T04:11:51.000Z | aba12d.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 17 | 2016-04-15T03:38:07.000Z | 2020-10-30T00:33:57.000Z | aba12d.cpp | ohmyjons/SPOJ-1 | 870ae3b072a3fbc89149b35fe5649a74512a8f60 | [
"Unlicense"
] | 127 | 2015-01-08T04:56:44.000Z | 2022-02-25T18:40:37.000Z | // 2014-09-22
#include <vector>
#include <algorithm>
#include <cstdio>
using namespace std;
bool is_knumber[1000001];
int knumber_count[1000001];
bool is_prime(int x) {
if (x < 2) return false;
for (int i = 2; i*i <= x; i++) {
if (x%i == 0) return false;
}
return true;
}
int main() {
is_knumber[2] = true;
for (int i = 2; i <= 1000; i++) {
if (is_prime(i)) {
int pwr = i*i;
int sod = 1 + i + i*i;
while (pwr <= 1000000) {
if (is_prime(sod)) {
is_knumber[pwr] = true;
}
pwr *= i;
sod += pwr;
}
}
}
knumber_count[0] = 0;
for (int i = 1; i <= 1000000; i++) {
knumber_count[i] = knumber_count[i-1] + int(is_knumber[i]);
}
int T; scanf("%d", &T);
while (T--) {
int A, B; scanf("%d %d", &A, &B);
printf("%d\n", knumber_count[B] - knumber_count[A-1]);
}
return 0;
}
| 24.292683 | 67 | 0.451807 | ohmyjons |
0eda560b7d2a090781ddb30fa8826d263deb8ece | 7,425 | cc | C++ | src/Testing/Utils/SCIRunFieldSamples.cc | benjaminlarson/SCIRunGUIPrototype | ed34ee11cda114e3761bd222a71a9f397517914d | [
"Unlicense"
] | null | null | null | src/Testing/Utils/SCIRunFieldSamples.cc | benjaminlarson/SCIRunGUIPrototype | ed34ee11cda114e3761bd222a71a9f397517914d | [
"Unlicense"
] | null | null | null | src/Testing/Utils/SCIRunFieldSamples.cc | benjaminlarson/SCIRunGUIPrototype | ed34ee11cda114e3761bd222a71a9f397517914d | [
"Unlicense"
] | null | null | null | /*
For more information, please see: http://software.sci.utah.edu
The MIT License
Copyright (c) 2014 Scientific Computing and Imaging Institute,
University of Utah.
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 <Testing/Utils/SCIRunFieldSamples.h>
#include <Core/GeometryPrimitives/Point.h>
#include <Core/Datatypes/Legacy/Field/Field.h>
#include <Core/Datatypes/Legacy/Field/VMesh.h>
#include <boost/assign.hpp>
namespace SCIRun
{
namespace TestUtils
{
using namespace SCIRun::Core::Geometry;
using namespace boost::assign;
void tetCubeGeometry(FieldHandle field)
{
auto vmesh = field->vmesh();
VMesh::Node::array_type vdata;
vdata.resize(4);
vmesh->node_reserve(8);
vmesh->elem_reserve(1);
vmesh->add_point( Point(0.0, 0.0, 0.0) );
vmesh->add_point( Point(1.0, 0.0, 0.0) );
vmesh->add_point( Point(1.0, 1.0, 0.0) );
vmesh->add_point( Point(0.0, 1.0, 0.0) );
vmesh->add_point( Point(0.0, 0.0, 1.0) );
vmesh->add_point( Point(1.0, 0.0, 1.0) );
vmesh->add_point( Point(1.0, 1.0, 1.0) );
vmesh->add_point( Point(0.0, 1.0, 1.0) );
vdata[0]=5; vdata[1]=6; vdata[2]=0; vdata[3]=4;
vmesh->add_elem(vdata);
vdata[0]=0; vdata[1]=7; vdata[2]=2; vdata[3]=3;
vmesh->add_elem(vdata);
vdata[0]=2; vdata[1]=6; vdata[2]=0; vdata[3]=1;
vmesh->add_elem(vdata);
vdata[0]=0; vdata[1]=6; vdata[2]=5; vdata[3]=1;
vmesh->add_elem(vdata);
vdata[0]=0; vdata[1]=6; vdata[2]=2; vdata[3]=7;
vmesh->add_elem(vdata);
vdata[0]=6; vdata[1]=7; vdata[2]=0; vdata[3]=4;
vmesh->add_elem(vdata);
}
void tetTetrahedronGeometry(FieldHandle field)
{
auto vmesh = field->vmesh();
VMesh::Node::array_type vdata;
vdata.resize(4);
vmesh->node_reserve(4);
vmesh->elem_reserve(1);
vmesh->add_point( Point(0, 0, 0) );
vmesh->add_point( Point(0.5, 1.0, 0) );
vmesh->add_point( Point(1.0, 0, 0) );
vmesh->add_point( Point(0.5, 0.5, 1.0) );
for (size_type i = 0; i < 4; ++i)
{
vdata[i] = i;
}
vmesh->add_elem(vdata);
}
void triTriangleGeometry(FieldHandle field)
{
auto vmesh = field->vmesh();
vmesh->add_point(Point(0.0, 0.0, 0.0));
vmesh->add_point(Point(1.0, 0.0, 0.0));
vmesh->add_point(Point(0.5, 1.0, 0.0));
VMesh::Node::array_type vdata;
vdata += 0, 1, 2;
vmesh->add_elem(vdata);
}
void triTetrahedronGeometry(FieldHandle field)
{
auto vmesh = field->vmesh();
vmesh->add_point(Point(1.0, 0.0, -0.707));
vmesh->add_point(Point(-1.0, 0.0, -0.707));
vmesh->add_point(Point(0.0, 1.0, 0.707));
vmesh->add_point(Point(0.0, -1.0, 0.707));
VMesh::Node::array_type vdata1;
vdata1 += 0, 1, 2;
vmesh->add_elem(vdata1);
VMesh::Node::array_type vdata2;
vdata2 += 0, 1, 3;
vmesh->add_elem(vdata2);
VMesh::Node::array_type vdata3;
vdata3 += 1, 2, 3;
vmesh->add_elem(vdata2);
VMesh::Node::array_type vdata4;
vdata4 += 0, 2, 3;
vmesh->add_elem(vdata4);
}
void triCubeGeometry(FieldHandle field)
{
auto vmesh = field->vmesh();
vmesh->add_point(Point(0.0, 1.0, 0.0));
vmesh->add_point(Point(0.0, 0.0, 0.0));
vmesh->add_point(Point(1.0, 1.0, 0.0));
vmesh->add_point(Point(1.0, 0.0, 0.0));
vmesh->add_point(Point(1.0, 0.0, -1.0));
vmesh->add_point(Point(1.0, 1.0, -1.0));
vmesh->add_point(Point(0.0, 1.0, -1.0));
vmesh->add_point(Point(0.0, 0.0, -1.0));
VMesh::Node::array_type vdata1;
vdata1 += 0, 1, 7;
vmesh->add_elem(vdata1);
VMesh::Node::array_type vdata2;
vdata2 += 0, 7, 6;
vmesh->add_elem(vdata2);
VMesh::Node::array_type vdata3;
vdata3 += 1, 0, 2;
vmesh->add_elem(vdata2);
VMesh::Node::array_type vdata4;
vdata4 += 1, 3, 2;
vmesh->add_elem(vdata4);
VMesh::Node::array_type vdata5;
vdata5 += 2, 3, 4;
vmesh->add_elem(vdata5);
VMesh::Node::array_type vdata6;
vdata6 += 2, 4, 5;
vmesh->add_elem(vdata6);
VMesh::Node::array_type vdata7;
vdata7 += 4, 7, 1;
vmesh->add_elem(vdata7);
VMesh::Node::array_type vdata8;
vdata8 += 4, 3, 1;
vmesh->add_elem(vdata8);
VMesh::Node::array_type vdata9;
vdata9 += 5, 6, 0;
vmesh->add_elem(vdata9);
VMesh::Node::array_type vdata10;
vdata10 += 5, 2, 0;
vmesh->add_elem(vdata10);
VMesh::Node::array_type vdata11;
vdata11 += 7, 6, 5;
vmesh->add_elem(vdata11);
VMesh::Node::array_type vdata12;
vdata12 += 7, 4, 5;
vmesh->add_elem(vdata12);
}
FieldHandle CubeTetVolConstantBasis(data_info_type type)
{
FieldInformation fi(TETVOLMESH_E, CONSTANTDATA_E, type);
FieldHandle field = CreateField(fi);
tetCubeGeometry(field);
return field;
}
FieldHandle CubeTetVolLinearBasis(data_info_type type)
{
FieldInformation fi(TETVOLMESH_E, LINEARDATA_E, type);
FieldHandle field = CreateField(fi);
tetCubeGeometry(field);
return field;
}
FieldHandle TetrahedronTetVolConstantBasis(data_info_type type)
{
FieldInformation fi(TETVOLMESH_E, CONSTANTDATA_E, type);
FieldHandle field = CreateField(fi);
tetTetrahedronGeometry(field);
return field;
}
FieldHandle TetrahedronTetVolLinearBasis(data_info_type type)
{
FieldInformation fi(TETVOLMESH_E, LINEARDATA_E, type);
FieldHandle field = CreateField(fi);
tetTetrahedronGeometry(field);
return field;
}
FieldHandle TriangleTriSurfConstantBasis(data_info_type type)
{
FieldInformation fi(TRISURFMESH_E, CONSTANTDATA_E, type);
FieldHandle field = CreateField(fi);
triTriangleGeometry(field);
return field;
}
FieldHandle TriangleTriSurfLinearBasis(data_info_type type)
{
FieldInformation fi(TRISURFMESH_E, LINEARDATA_E, type);
FieldHandle field = CreateField(fi);
triTriangleGeometry(field);
return field;
}
FieldHandle TetrahedronTriSurfConstantBasis(data_info_type type)
{
FieldInformation fi(TRISURFMESH_E, CONSTANTDATA_E, type);
FieldHandle field = CreateField(fi);
triTetrahedronGeometry(field);
return field;
}
FieldHandle TetrahedronTriSurfLinearBasis(data_info_type type)
{
FieldInformation fi(TRISURFMESH_E, LINEARDATA_E, type);
FieldHandle field = CreateField(fi);
triTetrahedronGeometry(field);
return field;
}
FieldHandle CubeTriSurfConstantBasis(data_info_type type)
{
FieldInformation fi(TRISURFMESH_E, CONSTANTDATA_E, type);
FieldHandle field = CreateField(fi);
triCubeGeometry(field);
return field;
}
FieldHandle CubeTriSurfLinearBasis(data_info_type type)
{
FieldInformation fi(TRISURFMESH_E, LINEARDATA_E, type);
FieldHandle field = CreateField(fi);
triCubeGeometry(field);
return field;
}
}}
| 26.423488 | 76 | 0.701953 | benjaminlarson |
0edc0724375eb70b19edbe2a8bba0e6a6dc3afbb | 5,684 | cpp | C++ | src/behaviortree/nodes/actions/waitframes.cpp | 675492062/behaviac | f7c3df58e704b1e8248b3f931c6f582915da654b | [
"BSD-3-Clause"
] | null | null | null | src/behaviortree/nodes/actions/waitframes.cpp | 675492062/behaviac | f7c3df58e704b1e8248b3f931c6f582915da654b | [
"BSD-3-Clause"
] | null | null | null | src/behaviortree/nodes/actions/waitframes.cpp | 675492062/behaviac | f7c3df58e704b1e8248b3f931c6f582915da654b | [
"BSD-3-Clause"
] | 2 | 2016-03-17T11:19:16.000Z | 2020-03-16T16:17:56.000Z | /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Tencent is pleased to support the open source community by making behaviac available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company. All rights reserved.
//
// Licensed under the BSD 3-Clause License (the "License"); you may not use this file except in compliance with
// the License. You may obtain a copy of the License at http://opensource.org/licenses/BSD-3-Clause
//
// 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 "behaviac/base/base.h"
#include "behaviac/behaviortree/nodes/actions/waitframes.h"
#include "behaviac/agent/agent.h"
#include "behaviac/behaviortree/nodes/actions/action.h"
#include "behaviac/behaviortree/nodes/conditions/condition.h"
namespace behaviac
{
WaitFrames::WaitFrames() : m_frames_var(0), m_frames_method(0)
{
}
WaitFrames::~WaitFrames()
{
BEHAVIAC_DELETE(this->m_frames_method);
}
//Property* LoadRight(const char* value, const behaviac::string& propertyName, behaviac::string& typeName);
//CMethodBase* LoadMethod(const char* value);
void WaitFrames::load(int version, const char* agentType, const properties_t& properties)
{
super::load(version, agentType, properties);
for (propertie_const_iterator_t it = properties.begin(); it != properties.end(); ++it)
{
const property_t& p = (*it);
if (!strcmp(p.name, "Frames"))
{
const char* pParenthesis = strchr(p.value, '(');
if (pParenthesis == 0)
{
behaviac::string typeName;
behaviac::string propertyName;
this->m_frames_var = Condition::LoadRight(p.value, typeName);
}
else
{
//method
this->m_frames_method = Action::LoadMethod(p.value);
}
}
}
}
int WaitFrames::GetFrames(Agent* pAgent) const
{
if (this->m_frames_var)
{
BEHAVIAC_ASSERT(this->m_frames_var);
TProperty<int>* pP = (TProperty<int>*)this->m_frames_var;
uint64_t frames = pP->GetValue(pAgent);
return (frames == ((uint64_t) - 1) ? -1 : (int)frames);
}
else if (this->m_frames_method)
{
Agent* pParent = Agent::GetInstance(pAgent, this->m_frames_method->GetInstanceNameString());
BEHAVIAC_ASSERT(pParent);
this->m_frames_method->run(pParent, pAgent);
int frames = this->m_frames_method->GetReturnValue<int>(pParent);
return frames;
}
return 0;
}
BehaviorTask* WaitFrames::createTask() const
{
WaitFramesTask* pTask = BEHAVIAC_NEW WaitFramesTask();
return pTask;
}
WaitFramesTask::WaitFramesTask() : LeafTask(), m_start(0), m_frames(0)
{
}
void WaitFramesTask::copyto(BehaviorTask* target) const
{
super::copyto(target);
BEHAVIAC_ASSERT(WaitFramesTask::DynamicCast(target));
WaitFramesTask* ttask = (WaitFramesTask*)target;
ttask->m_start = this->m_start;
ttask->m_frames = this->m_frames;
}
void WaitFramesTask::save(ISerializableNode* node) const
{
super::save(node);
if (this->m_status != BT_INVALID)
{
CSerializationID startId("start");
node->setAttr(startId, this->m_start);
CSerializationID framesId("frames");
node->setAttr(framesId, this->m_frames);
}
}
void WaitFramesTask::load(ISerializableNode* node)
{
super::load(node);
if (this->m_status != BT_INVALID)
{
CSerializationID startId("start");
behaviac::string attrStr;
node->getAttr(startId, attrStr);
StringUtils::FromString(attrStr.c_str(), this->m_start);
CSerializationID framesId("frames");
node->getAttr(framesId, attrStr);
StringUtils::FromString(attrStr.c_str(), this->m_frames);
}
}
WaitFramesTask::~WaitFramesTask()
{
}
int WaitFramesTask::GetFrames(Agent* pAgent) const
{
BEHAVIAC_ASSERT(WaitFrames::DynamicCast(this->GetNode()));
const WaitFrames* pWaitNode = (const WaitFrames*)(this->GetNode());
return pWaitNode ? pWaitNode->GetFrames(pAgent) : 0;
}
bool WaitFramesTask::onenter(Agent* pAgent)
{
BEHAVIAC_UNUSED_VAR(pAgent);
this->m_start = Workspace::GetInstance()->GetFrameSinceStartup();
this->m_frames = this->GetFrames(pAgent);
if (this->m_frames <= 0)
{
return false;
}
return true;
}
void WaitFramesTask::onexit(Agent* pAgent, EBTStatus s)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(s);
}
EBTStatus WaitFramesTask::update(Agent* pAgent, EBTStatus childStatus)
{
BEHAVIAC_UNUSED_VAR(pAgent);
BEHAVIAC_UNUSED_VAR(childStatus);
if (Workspace::GetInstance()->GetFrameSinceStartup() - this->m_start + 1 >= this->m_frames)
{
return BT_SUCCESS;
}
return BT_RUNNING;
}
}
| 30.55914 | 113 | 0.586735 | 675492062 |
0ee668cd7e9d9c4fb2248aa67d6343d78edc9c8f | 2,879 | cpp | C++ | src/tunit/src/tunit/base_assert.cpp | gammasoft71/tunit | 9bbe236db66593495fa4549cd0abf7c4239407fd | [
"MIT"
] | 3 | 2021-03-06T17:24:02.000Z | 2021-12-16T09:28:02.000Z | src/tunit/src/tunit/base_assert.cpp | gammasoft71/xtd_tunit | 9bbe236db66593495fa4549cd0abf7c4239407fd | [
"MIT"
] | null | null | null | src/tunit/src/tunit/base_assert.cpp | gammasoft71/xtd_tunit | 9bbe236db66593495fa4549cd0abf7c4239407fd | [
"MIT"
] | null | null | null | #include "../../include/tunit/base_assert.h"
#include "../../include/tunit/settings.h"
#include "../../include/tunit/unit_test.h"
#include "../../include/tunit/test.h"
#include <string>
using namespace tunit;
using namespace std;
using namespace std::string_literals;
void base_assert::abort(const std::string& message, const tunit::line_info& line_info) {
if (line_info != tunit::line_info::empty())
tunit::test::current_test().info_ = line_info;
if (tunit::test::current_test().message_.empty())
tunit::test::current_test().message_ = !message.empty() ? message : "Test aborted"s;
tunit::test::current_test().status_ = test::test_status::aborted;
throw abort_error(tunit::test::current_test().message_);
}
void base_assert::error() {
tunit::settings::default_settings().exit_status(EXIT_FAILURE);
tunit::test::current_unit_test().event_listener_->on_test_failed(tunit::test_event_args(tunit::test::current_test(), tunit::test::current_test_class(), tunit::test::current_unit_test()));
}
void base_assert::error(const std::string& expected, const std::string& actual, const std::string& message, const tunit::line_info& line_info) {
if (line_info != tunit::line_info::empty())
tunit::test::current_test().info_ = line_info;
tunit::test::current_test().message_ = message == "" && expected == "" && actual == "" ? "Test failed"s : message;
tunit::test::current_test().actual_ = actual;
tunit::test::current_test().expect_ = expected;
base_assert::error();
}
void base_assert::fail(const std::string& expected, const std::string& actual, const std::string& message, const tunit::line_info& line_info) {
if (line_info != tunit::line_info::empty())
tunit::test::current_test().info_ = line_info;
tunit::test::current_test().message_ = message == "" && expected == "" && actual == "" ? "Test failed"s : message;
tunit::test::current_test().actual_ = actual;
tunit::test::current_test().expect_ = expected;
tunit::test::current_test().status_ = test::test_status::failed;
throw assert_error(message != ""s ? message : "assertion failed!"s);
}
void base_assert::ignore(const std::string& message, const tunit::line_info& line_info) {
if (line_info != tunit::line_info::empty())
tunit::test::current_test().info_ = line_info;
tunit::test::current_test().message_ = message != ""s ? message : "Test ignored"s;
tunit::test::current_test().status_ = test::test_status::ignored;
throw ignore_error(tunit::test::current_test().message_);
}
void base_assert::succeed(const std::string& message, const tunit::line_info& line_info) {
if (line_info != tunit::line_info::empty())
tunit::test::current_test().info_ = line_info;
tunit::test::current_test().message_ = message;
if (tunit::test::current_test().status_ != test::test_status::failed)
tunit::test::current_test().status_ = test::test_status::succeed;
}
| 48.79661 | 189 | 0.708232 | gammasoft71 |
0eec0041e39485e247332af6c9bf97a50b2ffe9b | 914 | cpp | C++ | test/snippet/alphabet/all.cpp | giesselmann/seqan3 | 3a26b42b7066ac424b6e604115fe516607c308c0 | [
"BSD-3-Clause"
] | null | null | null | test/snippet/alphabet/all.cpp | giesselmann/seqan3 | 3a26b42b7066ac424b6e604115fe516607c308c0 | [
"BSD-3-Clause"
] | null | null | null | test/snippet/alphabet/all.cpp | giesselmann/seqan3 | 3a26b42b7066ac424b6e604115fe516607c308c0 | [
"BSD-3-Clause"
] | null | null | null | #include <seqan3/alphabet/all.hpp>
#include <seqan3/alphabet/nucleotide/dna4.hpp>
using namespace seqan3;
int main()
{
{
//! [ambiguity]
// does not work:
// dna4 my_letter{0}; // we want to set the default, an A
// dna4 my_letter{'A'}; // we also want to set an A, but we are setting value 65
// std::cout << my_letter; // you expect 'A', but how would you access the number?
//! [ambiguity]
}
{
//! [nonambiguous]
dna4 my_letter;
assign_rank(my_letter, 0); // assign an A via rank interface
assign_char(my_letter, 'A'); // assign an A via char interface
my_letter = dna4::A; // some alphabets (BUT NOT ALL!) also provide an enum-like interface
std::cout << to_char(my_letter); // prints 'A'
std::cout << (unsigned)to_rank(my_letter); // prints 0
// we have to add the cast here, because uint8_t is also treated as a char type by default :(
//! [nonambiguous]
}
}
| 27.69697 | 101 | 0.656455 | giesselmann |
0ef273bb0bba5bb5a016e5381507d4a862ce6aba | 2,331 | cpp | C++ | 03_DataStructrue/06_Tree/03_VT.cpp | WUST-mengqinyu/Template | 99b129284567896c37f9ac271e77099d300e7565 | [
"MIT"
] | 2 | 2021-07-14T03:21:06.000Z | 2021-11-11T08:00:47.000Z | 03_DataStructrue/06_Tree/03_VT.cpp | WUST-mengqinyu/Template | 99b129284567896c37f9ac271e77099d300e7565 | [
"MIT"
] | 1 | 2021-06-09T14:57:15.000Z | 2021-06-09T14:57:15.000Z | 03_DataStructrue/06_Tree/03_VT.cpp | WUST-mengqinyu/Template | 99b129284567896c37f9ac271e77099d300e7565 | [
"MIT"
] | null | null | null | // Virtual Tree
//
// Comprime uma arvore dado um conjunto S de vertices, de forma que
// o conjunto de vertices da arvore comprimida contenha S e seja
// minimal e fechado sobre a operacao de LCA
// Se |S| = k, a arvore comprimida tem O(k) vertices
//
// O(k log(k))
template<typename T> struct rmq {
vector<T> v;
int n; static const int b = 30;
vector<int> mask, t;
int op(int x, int y) { return v[x] < v[y] ? x : y; }
int msb(int x) { return __builtin_clz(1)-__builtin_clz(x); }
rmq() {}
rmq(const vector<T>& v_) : v(v_), n(v.size()), mask(n), t(n) {
for (int i = 0, at = 0; i < n; mask[i++] = at |= 1) {
at = (at<<1)&((1<<b)-1);
while (at and op(i, i-msb(at&-at)) == i) at ^= at&-at;
}
for (int i = 0; i < n/b; i++) t[i] = b*i+b-1-msb(mask[b*i+b-1]);
for (int j = 1; (1<<j) <= n/b; j++) for (int i = 0; i+(1<<j) <= n/b; i++)
t[n/b*j+i] = op(t[n/b*(j-1)+i], t[n/b*(j-1)+i+(1<<(j-1))]);
}
int small(int r, int sz = b) { return r-msb(mask[r]&((1<<sz)-1)); }
T query(int l, int r) {
if (r-l+1 <= b) return small(r, r-l+1);
int ans = op(small(l+b-1), small(r));
int x = l/b+1, y = r/b-1;
if (x <= y) {
int j = msb(y-x+1);
ans = op(ans, op(t[n/b*j+x], t[n/b*j+y-(1<<j)+1]));
}
return ans;
}
};
namespace lca {
vector<int> g[MAX];
int v[2*MAX], pos[MAX], dep[2*MAX];
int t;
rmq<int> RMQ;
void dfs(int i, int d = 0, int p = -1) {
v[t] = i, pos[i] = t, dep[t++] = d;
for (int j : g[i]) if (j != p) {
dfs(j, d+1, i);
v[t] = i, dep[t++] = d;
}
}
void build(int n, int root) {
t = 0;
dfs(root);
RMQ = rmq<int>(vector<int>(dep, dep+2*n-1));
}
int lca(int a, int b) {
a = pos[a], b = pos[b];
return v[RMQ.query(min(a, b), max(a, b))];
}
int dist(int a, int b) {
return dep[pos[a]] + dep[pos[b]] - 2*dep[pos[lca(a, b)]];
}
}
vector<int> virt[MAX];
#warning lembrar de buildar o LCA antes
int build_virt(vector<int> v) {
auto cmp = [&](int i, int j) { return lca::pos[i] < lca::pos[j]; };
sort(v.begin(), v.end(), cmp);
for (int i = v.size()-1; i; i--) v.push_back(lca::lca(v[i], v[i-1]));
sort(v.begin(), v.end(), cmp);
v.erase(unique(v.begin(), v.end()), v.end());
for (int i : v) virt[i].clear();
for (int i = 1; i < v.size(); i++) {
#warning soh to colocando aresta descendo
virt[lca::lca(v[i-1], v[i])].push_back(v[i]);
}
return v[0];
} | 28.426829 | 75 | 0.525526 | WUST-mengqinyu |
0ef318d8a0262f4ac60ff7ccad926430b6ba0d92 | 1,472 | cpp | C++ | src/learn_dx11/main.cpp | ref2401/cg | 4654377f94fe54945c33156911ca25e807c96236 | [
"MIT"
] | 2 | 2019-04-02T14:19:01.000Z | 2021-05-27T13:42:20.000Z | src/learn_dx11/main.cpp | ref2401/cg | 4654377f94fe54945c33156911ca25e807c96236 | [
"MIT"
] | 4 | 2016-11-05T14:17:14.000Z | 2017-03-30T15:03:37.000Z | src/learn_dx11/main.cpp | ref2401/cg | 4654377f94fe54945c33156911ca25e807c96236 | [
"MIT"
] | null | null | null | #include <iostream>
#include "cg/base/base.h"
#include "learn_dx11/base/app.h"
#include "learn_dx11/mesh_rnd/displacement_mapping_example.h"
#include "learn_dx11/mesh_rnd/vertex_skinning_example.h"
#include "learn_dx11/mesh_rnd/static_mesh_example.h"
#include "learn_dx11/tess/terrain_tessellation_example.h"
#include "learn_dx11/tess/compute_complanarity_example.h"
#include "learn_dx11/image_processing/gaussian_filter_example.h"
#include "learn_dx11/image_processing/bilateral_filter_example.h"
#include "cg/data/model.h"
int main(int argc, char* argv[])
{
uint2 window_position(90, 50);
uint2 window_size(960, 540);
try {
OutputDebugString("----------------\n");
learn_dx11::Application app(window_position, window_size);
// Uncomment a line to execute the appropriate example.
//app.run<learn_dx11::mesh_rnd::Static_mesh_example>();
//app.run<learn_dx11::mesh_rnd::Vertex_skinning_example>();
//app.run<learn_dx11::mesh_rnd::Displacement_mapping_example>();
//app.run<learn_dx11::tess::Terrain_tessellation_example>();
//app.run<learn_dx11::tess::Compute_complanarity_example>();
//app.run<learn_dx11::image_processing::Gaussian_filter_example>();
app.run<learn_dx11::image_processing::Bilateral_filter_example>();
}
catch(std::exception& exc) {
OutputDebugString("\nException:\n");
OutputDebugString(cg::exception_message(exc).c_str());
OutputDebugString("----------\n");
}
return 1;
} | 36.8 | 70 | 0.73981 | ref2401 |
0ef4dffeb637cea383fa8a726c05f9d1530ee4c5 | 1,092 | cpp | C++ | 517-9B.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | 517-9B.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | 517-9B.cpp | AndrewWayne/OI_Learning | 0fe8580066704c8d120a131f6186fd7985924dd4 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
const int maxn = 1e5 + 10;
const int MOD = 1e9 + 7;
const int prime[5] = {2, 3, 5, 7};
int n;
pair<int, int> a[maxn];
long long f[maxn][1 << 5];
inline long long Mod(long long x){
x %= MOD;
while(x < 0) x += MOD;
return x;
}
int main(){
cin >> n;
for(int i = 1; i <= n; i++)
cin >> a[i].first;
for(int i = 1; i <= n; i++){
for(int j = 0; j < 4; j++){
int k = 0;
while(a[i].first % prime[j] == 0)
k ^= 1, a[i].first /= prime[j];
a[i].second |= (k << j);
}
}
sort(a+1, a+1+n);
f[0][0] = 1;
for(int i = 1; i <= n; i++){
int l = i, r = i;
while(r <= n && a[r].first == a[l].first) r++;
r--;
bool flag = (a[i].first > 1);
for(int j = 0; j <= (1 << 5) - 1; j++)
if((j >> 4) & 1) f[i-1][j] = 0;
for(int j = l; j <= r; j++){
for(int k = 0; k <= (1 << 5) - 1; k++){
if(!f[j-1][k]) continue;
f[j][k] = (f[j-1][k] + f[j][k]) % MOD;
int stat = (a[j].second | (flag << 4));
f[j][k ^ stat] = (f[j][k ^ stat] + f[j-1][k]) % MOD;
}
}
i = r;
}
printf("%d\n", Mod(f[n][0] - 1));
return 0;
}
| 22.75 | 56 | 0.436813 | AndrewWayne |
0ef562c6206a1f153152841347903e2e8807e985 | 1,894 | cpp | C++ | coreneuron/io/mech_report.cpp | alexsavulescu/CoreNeuron | af7e95d98819c052b07656961d20de6a71b70740 | [
"BSD-3-Clause"
] | null | null | null | coreneuron/io/mech_report.cpp | alexsavulescu/CoreNeuron | af7e95d98819c052b07656961d20de6a71b70740 | [
"BSD-3-Clause"
] | null | null | null | coreneuron/io/mech_report.cpp | alexsavulescu/CoreNeuron | af7e95d98819c052b07656961d20de6a71b70740 | [
"BSD-3-Clause"
] | null | null | null | /*
# =============================================================================
# Copyright (c) 2016 - 2021 Blue Brain Project/EPFL
#
# See top-level LICENSE file for details.
# =============================================================================
*/
#include <iostream>
#include <vector>
#include "coreneuron/coreneuron.hpp"
#include "coreneuron/mpi/nrnmpi.h"
#include "coreneuron/mpi/nrnmpi_impl.h"
namespace coreneuron {
/** display global mechanism count */
void write_mech_report() {
/// mechanim count across all gids, local to rank
const auto n_memb_func = corenrn.get_memb_funcs().size();
std::vector<long> local_mech_count(n_memb_func, 0);
/// each gid record goes on separate row, only check non-empty threads
for (size_t i = 0; i < nrn_nthread; i++) {
const auto& nt = nrn_threads[i];
for (auto* tml = nt.tml; tml; tml = tml->next) {
const int type = tml->index;
const auto& ml = tml->ml;
local_mech_count[type] += ml->nodecount;
}
}
std::vector<long> total_mech_count(n_memb_func);
#if NRNMPI
/// get global sum of all mechanism instances
nrnmpi_long_allreduce_vec(&local_mech_count[0],
&total_mech_count[0],
local_mech_count.size(),
1);
#else
total_mech_count = local_mech_count;
#endif
/// print global stats to stdout
if (nrnmpi_myid == 0) {
printf("\n================ MECHANISMS COUNT BY TYPE ==================\n");
printf("%4s %20s %10s\n", "Id", "Name", "Count");
for (size_t i = 0; i < total_mech_count.size(); i++) {
printf("%4lu %20s %10ld\n", i, nrn_get_mechname(i), total_mech_count[i]);
}
printf("=============================================================\n");
}
}
} // namespace coreneuron
| 32.655172 | 85 | 0.517951 | alexsavulescu |
0ef6894d4557dab17c758afa406847753ecefed5 | 8,368 | cpp | C++ | src/modules/muorb/adsp/px4muorb.cpp | Qsome43/Firmware | 430c32fa4087f988e7bd8b3daf3326cfac186221 | [
"BSD-3-Clause"
] | 10 | 2020-11-25T14:04:15.000Z | 2022-03-02T23:46:57.000Z | src/modules/muorb/adsp/px4muorb.cpp | choudhary0parivesh/Firmware | 02f4ad61ec8eb4f7906dd06b4eb1fd6abb994244 | [
"BSD-3-Clause"
] | 20 | 2017-11-30T09:49:45.000Z | 2018-02-12T07:56:29.000Z | src/modules/muorb/adsp/px4muorb.cpp | choudhary0parivesh/Firmware | 02f4ad61ec8eb4f7906dd06b4eb1fd6abb994244 | [
"BSD-3-Clause"
] | 10 | 2019-04-02T09:06:30.000Z | 2021-06-23T15:52:33.000Z | /****************************************************************************
*
* Copyright (C) 2015 Mark Charlebois. 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. Neither the name PX4 nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include "px4muorb.hpp"
#include "uORBFastRpcChannel.hpp"
#include "uORBManager.hpp"
#include <px4_platform_common/tasks.h>
#include <px4_platform_common/posix.h>
#include <dspal_platform.h>
#include "uORB/topics/sensor_combined.h"
#include "uORB.h"
#include <parameters/param.h>
#include <px4_platform_common/shmem.h>
#include <px4_platform_common/log.h>
__BEGIN_DECLS
extern int dspal_main(int argc, char *argv[]);
__END_DECLS
int px4muorb_orb_initialize()
{
HAP_power_request(100, 100, 1000);
shmem_info_p = NULL;
// The uORB Manager needs to be initialized first up, otherwise the instance is nullptr.
uORB::Manager::initialize();
// Register the fastrpc muorb with uORBManager.
uORB::Manager::get_instance()->set_uorb_communicator(
uORB::FastRpcChannel::GetInstance());
// Now continue with the usual dspal startup.
const char *argv[] = { "dspal", "start" };
int argc = 2;
int rc;
rc = dspal_main(argc, (char **) argv);
return rc;
}
int px4muorb_set_absolute_time_offset(int32_t time_diff_us)
{
return hrt_set_absolute_time_offset(time_diff_us);
}
int px4muorb_get_absolute_time(uint64_t *time_us)
{
*time_us = hrt_absolute_time();
return 0;
}
/*update value and param's change bit in shared memory*/
int px4muorb_param_update_to_shmem(uint32_t param, const uint8_t *value,
int data_len_in_bytes)
{
unsigned int byte_changed, bit_changed;
union param_value_u *param_value = (union param_value_u *) value;
if (!shmem_info_p) {
init_shared_memory();
}
if (get_shmem_lock(__FILE__, __LINE__) != 0) {
PX4_INFO("Could not get shmem lock\n");
return -1;
}
shmem_info_p->params_val[param] = *param_value;
byte_changed = param / 8;
bit_changed = 1 << param % 8;
shmem_info_p->krait_changed_index[byte_changed] |= bit_changed;
release_shmem_lock(__FILE__, __LINE__);
return 0;
}
int px4muorb_param_update_index_from_shmem(unsigned char *data, int data_len_in_bytes)
{
if (!shmem_info_p) {
return -1;
}
if (get_shmem_lock(__FILE__, __LINE__) != 0) {
PX4_INFO("Could not get shmem lock\n");
return -1;
}
for (int i = 0; i < data_len_in_bytes; i++) {
data[i] = shmem_info_p->adsp_changed_index[i];
}
release_shmem_lock(__FILE__, __LINE__);
return 0;
}
int px4muorb_param_update_value_from_shmem(uint32_t param, const uint8_t *value,
int data_len_in_bytes)
{
unsigned int byte_changed, bit_changed;
union param_value_u *param_value = (union param_value_u *) value;
if (!shmem_info_p) {
return -1;
}
if (get_shmem_lock(__FILE__, __LINE__) != 0) {
PX4_INFO("Could not get shmem lock\n");
return -1;
}
*param_value = shmem_info_p->params_val[param];
/*also clear the index since we are holding the lock*/
byte_changed = param / 8;
bit_changed = 1 << param % 8;
shmem_info_p->adsp_changed_index[byte_changed] &= ~bit_changed;
release_shmem_lock(__FILE__, __LINE__);
return 0;
}
int px4muorb_topic_advertised(const char *topic_name)
{
int rc = 0;
PX4_INFO("TEST px4muorb_topic_advertised of [%s] on remote side...", topic_name);
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
uORBCommunicator::IChannelRxHandler *rxHandler = channel->GetRxHandler();
if (rxHandler != nullptr) {
rc = rxHandler->process_remote_topic(topic_name, 1);
} else {
rc = -1;
}
return rc;
}
int px4muorb_topic_unadvertised(const char *topic_name)
{
int rc = 0;
PX4_INFO("TEST px4muorb_topic_unadvertised of [%s] on remote side...", topic_name);
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
uORBCommunicator::IChannelRxHandler *rxHandler = channel->GetRxHandler();
if (rxHandler != nullptr) {
rc = rxHandler->process_remote_topic(topic_name, 0);
} else {
rc = -1;
}
return rc;
}
int px4muorb_add_subscriber(const char *name)
{
int rc = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
channel->AddRemoteSubscriber(name);
uORBCommunicator::IChannelRxHandler *rxHandler = channel->GetRxHandler();
if (rxHandler != nullptr) {
rc = rxHandler->process_add_subscription(name, 0);
if (rc != OK) {
channel->RemoveRemoteSubscriber(name);
}
} else {
rc = -1;
}
return rc;
}
int px4muorb_remove_subscriber(const char *name)
{
int rc = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
channel->RemoveRemoteSubscriber(name);
uORBCommunicator::IChannelRxHandler *rxHandler = channel->GetRxHandler();
if (rxHandler != nullptr) {
rc = rxHandler->process_remove_subscription(name);
} else {
rc = -1;
}
return rc;
}
int px4muorb_send_topic_data(const char *name, const uint8_t *data,
int data_len_in_bytes)
{
int rc = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
uORBCommunicator::IChannelRxHandler *rxHandler = channel->GetRxHandler();
if (rxHandler != nullptr) {
rc = rxHandler->process_received_message(name, data_len_in_bytes,
(uint8_t *) data);
} else {
rc = -1;
}
return rc;
}
int px4muorb_is_subscriber_present(const char *topic_name, int *status)
{
int rc = 0;
int32_t local_status = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
rc = channel->is_subscriber_present(topic_name, &local_status);
if (rc == 0) {
*status = (int) local_status;
}
return rc;
}
int px4muorb_receive_msg(int *msg_type, char *topic_name, int topic_name_len,
uint8_t *data, int data_len_in_bytes, int *bytes_returned)
{
int rc = 0;
int32_t local_msg_type = 0;
int32_t local_bytes_returned = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
//PX4_DEBUG( "topic_namePtr: [0x%p] dataPtr: [0x%p]", topic_name, data );
rc = channel->get_data(&local_msg_type, topic_name, topic_name_len, data,
data_len_in_bytes, &local_bytes_returned);
*msg_type = (int) local_msg_type;
*bytes_returned = (int) local_bytes_returned;
return rc;
}
int px4muorb_receive_bulk_data(uint8_t *bulk_transfer_buffer,
int max_size_in_bytes, int *returned_length_in_bytes, int *topic_count)
{
int rc = 0;
int32_t local_bytes_returned = 0;
int32_t local_topic_count = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
//PX4_DEBUG( "topic_namePtr: [0x%p] dataPtr: [0x%p]", topic_name, data );
rc = channel->get_bulk_data(bulk_transfer_buffer, max_size_in_bytes,
&local_bytes_returned, &local_topic_count);
*returned_length_in_bytes = (int) local_bytes_returned;
*topic_count = (int) local_topic_count;
return rc;
}
int px4muorb_unblock_recieve_msg(void)
{
int rc = 0;
uORB::FastRpcChannel *channel = uORB::FastRpcChannel::GetInstance();
rc = channel->unblock_get_data_method();
return rc;
}
| 28.175084 | 89 | 0.724426 | Qsome43 |
0ef78fa196c8777e3aaf95426c8713f14e088661 | 353 | cpp | C++ | C++/prime.cpp | rainoverme002/Software-Developer-Interview-Preparation | e4d9d704d619c11c0eb6458dcb57761b5946cd82 | [
"MIT"
] | null | null | null | C++/prime.cpp | rainoverme002/Software-Developer-Interview-Preparation | e4d9d704d619c11c0eb6458dcb57761b5946cd82 | [
"MIT"
] | 2 | 2021-09-02T20:33:10.000Z | 2022-03-29T10:04:07.000Z | C++/prime.cpp | rainoverme002/Software-Developer-Interview-Preparation | e4d9d704d619c11c0eb6458dcb57761b5946cd82 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdlib>
#include<cmath>
using namespace std;
int main(){
int N;
cout<<"Masukan Banyaknya Bilangan Prima yang ingin ditampilkan"<<endl;
cin >> N;
int counter = 0, x = 1;
while(counter!=N){
if(x%2!=0){
cout<<x<<endl;
counter+=1;
}
x+=1;
}
} | 14.708333 | 74 | 0.509915 | rainoverme002 |
0ef9314af14bf74923771005982042c09bd08fae | 4,898 | hpp | C++ | src/ngraph/runtime/cpu/pass/cpu_dnnl_primitive_build.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/pass/cpu_dnnl_primitive_build.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | src/ngraph/runtime/cpu/pass/cpu_dnnl_primitive_build.hpp | pqLee/ngraph | ddfa95b26a052215baf9bf5aa1ca5d1f92aa00f7 | [
"Apache-2.0"
] | null | null | null | //*****************************************************************************
// Copyright 2017-2020 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//*****************************************************************************
#pragma once
#include "ngraph/pass/pass.hpp"
#include <fstream>
#include <functional>
#include <typeindex>
#include <unordered_map>
#define CONSTRUCT_PRIMITIVE_BUILD_STRING_DECL(op_name) \
construct_primitive_build_string<op_name>(ngraph::runtime::cpu::DNNLEmitter & dnnl_emitter, \
ngraph::Node * node, \
std::string & construct_string, \
std::vector<size_t> & deps, \
size_t & index, \
size_t & scratchpad_size, \
std::ofstream & desc_file)
namespace dnnl
{
struct primitive;
}
namespace ngraph
{
class Node;
namespace runtime
{
namespace cpu
{
class DNNLEmitter;
namespace pass
{
using PrimitiveBuildStringConstructFunction =
std::function<void(ngraph::runtime::cpu::DNNLEmitter&,
ngraph::Node*,
std::string&,
std::vector<size_t>&,
size_t&,
size_t&,
std::ofstream&)>;
using PrimitiveBuildStringConstructOpMap =
std::unordered_map<std::type_index, PrimitiveBuildStringConstructFunction>;
/// This pass traverses the call graph and creates DNNL primitives for those ops
/// that have been assigned to DNNL.
class DNNLPrimitiveBuildPass : public ngraph::pass::CallGraphPass
{
private:
std::string m_desc_filename;
ngraph::runtime::cpu::DNNLEmitter& m_dnnl_emitter;
/// External map to store each node with dnnl implementation and its dnnl
/// creation string, deps, dnnl primitive index, and dnnl primitive
/// scratchpad size.
std::map<const Node*,
std::tuple<std::string, std::vector<size_t>, size_t, size_t>>&
m_node_primitive_string_deps_index_size_map;
public:
DNNLPrimitiveBuildPass(
std::string filename,
ngraph::runtime::cpu::DNNLEmitter& dnnl_emitter,
std::map<const Node*,
std::tuple<std::string, std::vector<size_t>, size_t, size_t>>&
node_primitive_string_deps_index_size_map)
: m_desc_filename(filename)
, m_dnnl_emitter(dnnl_emitter)
, m_node_primitive_string_deps_index_size_map(
node_primitive_string_deps_index_size_map)
{
}
bool run_on_call_graph(const std::list<std::shared_ptr<Node>>& nodes) override;
template <typename OP>
static void construct_primitive_build_string(
ngraph::runtime::cpu::DNNLEmitter& /* dnnl_emitter */,
ngraph::Node* node,
std::string& /* construct_string */,
std::vector<size_t>& /* deps */,
size_t& /* index */,
size_t& /* scratchpad size */,
std::ofstream& /* desc_file */)
{
throw std::runtime_error("Unimplemented op '" + node->description() +
"' in DNNLPrimitiveBuildPass");
}
};
}
}
}
}
| 43.345133 | 100 | 0.459371 | pqLee |
0ef9679a8de0384af7cd0aacea5daf32d2d6feb7 | 8,811 | cpp | C++ | DLE/DataTypes/RenderModel.cpp | overload-development-community/DLE.NET | fe422895a91a28fdee7f980f7613bb4c8c047bb0 | [
"MIT"
] | 2 | 2020-07-08T22:07:55.000Z | 2020-08-21T05:42:34.000Z | DLE/DataTypes/RenderModel.cpp | overload-development-community/DLE.NET | fe422895a91a28fdee7f980f7613bb4c8c047bb0 | [
"MIT"
] | 2 | 2020-09-11T01:01:00.000Z | 2020-12-07T23:09:35.000Z | DLE/DataTypes/RenderModel.cpp | overload-development-community/DLE.NET | fe422895a91a28fdee7f980f7613bb4c8c047bb0 | [
"MIT"
] | 1 | 2021-09-28T16:39:30.000Z | 2021-09-28T16:39:30.000Z | #include "stdafx.h"
#include "ModelTextures.h"
#include "PolyModel.h"
#include "ASEModel.h"
#include "OOFModel.h"
#include "rendermodel.h"
using namespace RenderModel;
//------------------------------------------------------------------------------
void CModel::Init(void)
{
memset(m_teamTextures, 0, sizeof(m_teamTextures));
memset(m_nGunSubModels, 0xFF, sizeof(m_nGunSubModels));
m_nModel = -1;
m_fScale = 0;
m_nType = 0; //-1: custom mode, 0: default model, 1: alternative model, 2: hires model
m_nFaces = 0;
m_iFace = 0;
m_nVerts = 0;
m_nFaceVerts = 0;
m_iFaceVert = 0;
m_nSubModels = 0;
m_nTextures = 0;
m_iSubModel = 0;
m_bHasTransparency = 0;
m_bValid = 0;
m_bRendered = 0;
m_bBullets = 0;
m_vBullets.Clear();
m_vboDataHandle = 0;
m_vboIndexHandle = 0;
}
//------------------------------------------------------------------------------
bool CModel::Create(void)
{
m_vertices.Create(m_nVerts);
m_color.Create(m_nVerts);
m_vertBuf[0].Create(m_nFaceVerts);
m_faceVerts.Create(m_nFaceVerts);
m_vertNorms.Create(m_nFaceVerts);
m_subModels.Create(m_nSubModels);
m_faces.Create(m_nFaces);
m_index[0].Create(m_nFaceVerts);
m_sortedVerts.Create(m_nFaceVerts);
m_vertices.Clear(0);
m_color.Clear(0xff);
m_vertBuf[0].Clear(0);
m_faceVerts.Clear(0);
m_vertNorms.Clear(0);
m_subModels.Clear(0);
m_faces.Clear(0);
m_index[0].Clear(0);
m_sortedVerts.Clear(0);
for (ushort i = 0; i < m_nSubModels; i++)
m_subModels[i].m_nSubModel = i;
return true;
}
//------------------------------------------------------------------------------
void CModel::Destroy(void)
{
m_textures = null;
m_sortedVerts.Destroy();
m_index[0].Destroy();
m_faces.Destroy();
m_subModels.Destroy();
m_vertNorms.Destroy();
m_faceVerts.Destroy();
m_vertBuf[0].Destroy();
m_vertBuf[1].SetBuffer(0); //avoid trying to delete memory allocated by the graphics driver
m_color.Destroy();
m_vertices.Destroy();
Init();
}
//------------------------------------------------------------------------------
void CModel::Setup(int bHires, int bSort)
{
CSubModel* psm;
CFace* pfi, * pfj;
CVertex* pmv;
CFloatVector* pv, * pn;
tTexCoord2d* pt;
rgbaColorf* pc;
CTexture* textureP = bHires ? m_textures->Buffer() : null;
int i, j;
ushort nId;
m_fScale = 1;
for (i = 0, j = m_nFaceVerts; i < j; i++)
m_index[0][i] = i;
//sort each submodel's faces
for (i = 0; i < m_nSubModels; i++) {
psm = &m_subModels[i];
if (psm->m_nFaces) {
if (bSort) {
psm->SortFaces(textureP);
psm->GatherVertices(m_faceVerts, m_sortedVerts);
}
pfi = psm->m_faces;
pfi->SetTexture(textureP);
for (nId = 0, j = psm->m_nFaces - 1; j; j--) {
pfi->m_nId = nId;
pfj = pfi++;
pfi->SetTexture(textureP);
if (*pfi != *pfj)
nId++;
if (textureP && (textureP[pfi->m_nTexture].Transparent()))
m_bHasTransparency = 1;
}
pfi->m_nId = nId;
}
}
m_vbVerts.SetBuffer(reinterpret_cast<CFloatVector*> (m_vertBuf[0].Buffer()), 1, m_vertBuf[0].Length());
m_vbNormals.SetBuffer(m_vbVerts.Buffer() + m_nFaceVerts, true, m_vertBuf[0].Length());
m_vbColor.SetBuffer(reinterpret_cast<rgbaColorf*> (m_vbNormals.Buffer() + m_nFaceVerts), 1, m_vertBuf[0].Length());
m_vbTexCoord.SetBuffer(reinterpret_cast<tTexCoord2d*> (m_vbColor.Buffer() + m_nFaceVerts), 1, m_vertBuf[0].Length());
pv = m_vbVerts.Buffer();
pn = m_vbNormals.Buffer();
pt = m_vbTexCoord.Buffer();
pc = m_vbColor.Buffer();
pmv = bSort ? m_sortedVerts.Buffer() : m_faceVerts.Buffer();
for (i = 0, j = m_nFaceVerts; i < j; i++, pmv++) {
pv[i] = pmv->m_vertex;
pn[i] = pmv->m_normal;
pc[i] = pmv->m_baseColor;
pt[i] = pmv->m_texCoord;
}
if (bSort)
memcpy(m_faceVerts.Buffer(), m_sortedVerts.Buffer(), m_faceVerts.Size());
else
memcpy(m_sortedVerts.Buffer(), m_faceVerts.Buffer(), m_sortedVerts.Size());
m_bValid = 1;
m_sortedVerts.Destroy();
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
int CFace::Compare(const CFace* pf, const CFace* pm)
{
if (pf == pm)
return 0;
if (pf->m_bBillboard < pm->m_bBillboard)
return -1;
if (pf->m_bBillboard > pm->m_bBillboard)
return 1;
if (pf->m_nTexture < pm->m_nTexture)
return -1;
if (pf->m_nTexture > pm->m_nTexture)
return 1;
if (pf->m_nVerts < pm->m_nVerts)
return -1;
if (pf->m_nVerts > pm->m_nVerts)
return 1;
return 0;
}
//------------------------------------------------------------------------------
const bool CFace::operator!= (CFace& other)
{
if (m_nTexture < other.m_nTexture)
return true;
if (m_nTexture > other.m_nTexture)
return true;
if (m_nVerts < other.m_nVerts)
return true;
if (m_nVerts > other.m_nVerts)
return true;
return false;
}
//------------------------------------------------------------------------------
void CFace::SetTexture(CTexture* textureP)
{
m_textureP = (textureP && (m_nTexture >= 0)) ? textureP + m_nTexture : null;
}
//------------------------------------------------------------------------------
int CFace::GatherVertices(CDynamicArray<RenderModel::CVertex>& source, CDynamicArray<RenderModel::CVertex>& dest, int nIndex)
{
#if DBG
if (uint(m_nIndex + m_nVerts) > source.Length())
return 0;
if (uint(nIndex + m_nVerts) > dest.Length())
return 0;
#endif
memcpy(dest + nIndex, source + m_nIndex, m_nVerts * sizeof(CVertex));
m_nIndex = nIndex; //set this face's index of its first vertex in the model's vertex buffer
return m_nVerts;
}
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
void CSubModel::InitMinMax(void)
{
m_vMin.Set(1e30f, 1e30f, 1e30f);
m_vMax.Set(-1e30f, -1e30f, -1e30f);
}
//------------------------------------------------------------------------------
void CSubModel::SetMinMax(CFloatVector* pVertex)
{
CFloatVector v = *pVertex;
if (m_vMin.v.x > v.v.x)
m_vMin.v.x = v.v.x;
if (m_vMin.v.y > v.v.y)
m_vMin.v.y = v.v.y;
if (m_vMin.v.z > v.v.z)
m_vMin.v.z = v.v.z;
if (m_vMax.v.x < v.v.x)
m_vMax.v.x = v.v.x;
if (m_vMax.v.y < v.v.y)
m_vMax.v.y = v.v.y;
if (m_vMax.v.z < v.v.z)
m_vMax.v.z = v.v.z;
}
//------------------------------------------------------------------------------
void CSubModel::SortFaces(CTexture* textureP)
{
CQuickSort<CFace> qs;
for (int i = 0; i < m_nFaces; i++)
m_faces[i].SetTexture(textureP);
if (m_nFaces > 1)
qs.SortAscending(m_faces, 0, static_cast<uint> (m_nFaces - 1), &RenderModel::CFace::Compare);
}
//------------------------------------------------------------------------------
void CSubModel::GatherVertices(CDynamicArray<RenderModel::CVertex>& source, CDynamicArray<RenderModel::CVertex>& dest)
{
int nIndex = m_nIndex; //this submodels vertices start at m_nIndex in the models vertex buffer
// copy vertices face by face
for (int i = 0; i < m_nFaces; i++)
nIndex += m_faces[i].GatherVertices(source, dest, nIndex);
}
//------------------------------------------------------------------------------
static int bCenterGuns [] = {0, 1, 1, 0, 0, 0, 1, 1, 0, 1};
int CSubModel::Filter (int nGunId, int nBombId, int nMissileId, int nMissiles)
{
if (!m_bRender)
return 0;
if (m_bFlare)
return 1;
if (m_nGunPoint >= 0)
return 1;
if (m_bBullets)
return 1;
if (m_bThruster && ((m_bThruster & (REAR_THRUSTER | FRONTAL_THRUSTER)) != (REAR_THRUSTER | FRONTAL_THRUSTER)))
return 1;
if (m_bHeadlight)
return 0;
if (m_bBombMount)
return (nBombId == 0);
if (m_bWeapon) {
int bLasers = 1;
int bSuperLasers = 1;
int bQuadLasers = 1;
int bCenterGun = bCenterGuns [nGunId];
int nWingtip = bQuadLasers ? bSuperLasers : 2; //gameOpts->render.ship.nWingtip;
if (nWingtip == 0)
nWingtip = bLasers && bSuperLasers && bQuadLasers;
else if (nWingtip == 1)
nWingtip = !bLasers || bSuperLasers;
if (m_nGun == nGunId + 1) {
if (bLasers) {
if ((m_nWeaponPos > 2) && !bQuadLasers && (nWingtip != bSuperLasers))
return 1;
}
}
else if (m_nGun == LASER_INDEX + 1) {
if (nWingtip)
return 1;
return !bCenterGun && (m_nWeaponPos < 3);
}
else if (m_nGun == SUPER_LASER_INDEX + 1) {
if (nWingtip != 1)
return 1;
return !bCenterGun && (m_nWeaponPos < 3);
}
else if (!m_nGun) {
if (bLasers && bQuadLasers)
return 1;
if (m_nType != nWingtip)
return 1;
return 0;
}
else
return 1;
}
return 0;
}
//------------------------------------------------------------------------------
static inline int PlayerColor (int nObject)
{
return 1;
}
//------------------------------------------------------------------------------
//eof
| 26.459459 | 125 | 0.555442 | overload-development-community |
0eff3206742a98bcc95c1c129d5b80ac03da4a86 | 15,066 | cpp | C++ | src/syntactic.cpp | Donluigimx/MiniC | b692a1115d889897de185d3bc28db48447d2de9d | [
"MIT"
] | 2 | 2016-04-19T18:26:37.000Z | 2016-04-20T21:56:01.000Z | src/syntactic.cpp | Donluigimx/MiniC | b692a1115d889897de185d3bc28db48447d2de9d | [
"MIT"
] | null | null | null | src/syntactic.cpp | Donluigimx/MiniC | b692a1115d889897de185d3bc28db48447d2de9d | [
"MIT"
] | null | null | null | #include "syntactic.hpp"
#include "node.hpp"
Syntactic::Syntactic(Lexic* lex) {
lexic = lex;
Analize();
}
void Syntactic::Analize() {
tree = Translation_Unit();
}
Node* Syntactic::Translation_Unit() {
Program* nodent = new Program();
Node* aux = nullptr;
while( lexic->Token != Token::END_OF_FILE) {
aux = External_Declaration();
if (aux != nullptr)
nodent->nodes.push_back(aux);
}
return nodent;
}
Node* Syntactic::External_Declaration() {
int type;
std::string symbol;
Node* nodent = nullptr;
DefVar* defv = nullptr;
DefFunc* deff = nullptr;
type = lexic->Token;
Specifier();
symbol = lexic->Symbol;
Check(Token::IDENTIFIER);
nodent = _External_Declaration();
defv = dynamic_cast<DefVar*>(nodent);
deff = dynamic_cast<DefFunc*>(nodent);
if(defv != nullptr) {
defv->type = type;
if(defv->values[0].first == "1")
defv->values[0].first = symbol;
} else if(deff != nullptr) {
deff->type = type;
deff->symbol = symbol;
}
return nodent;
}
Node* Syntactic::Specifier() {
if (lexic->Token == Token::INT || lexic->Token == Token::VOID) {
lexic->Next();
} else
Error();
return nullptr;
}
Node* Syntactic::_External_Declaration() {
DefVar* defv = nullptr;
DefVar* auxv = nullptr;
DefFunc* deff = nullptr;
Compound* comp = nullptr;
Expression* expp = nullptr;
Node* nodent = nullptr;
if (lexic->Token == Token::PARENTHESES_O) {
lexic->Next();
if (lexic->Token != Token::PARENTHESES_C)
deff = Parameter_List();
else
deff = new DefFunc("",0);
Check(")");
comp = Compound_S();
deff->compound = comp;
nodent = deff;
} else{
defv = new DefVar(0);
expp = _Initializer();
auxv = Initializer();
defv->values.push_back(std::pair<std::string, Expression* >("1", expp));
if (auxv != nullptr)
for(auto it: auxv->values)
defv->values.push_back(it);
nodent = defv;
Check(";");
}
return nodent;
}
DefFunc* Syntactic::Parameter_List() {
DefFunc* deff = new DefFunc("",0);
DefFunc* auxf = nullptr;
int type;
type = lexic->Token;
Specifier();
deff->parameters.push_back(new Parameter(lexic->Symbol, type));
Check(Token::IDENTIFIER);
auxf = _Parameter_List();
if( auxf != nullptr)
for(auto it: auxf->parameters)
deff->parameters.push_back(it);
return deff;
}
DefFunc* Syntactic::_Parameter_List() {
DefFunc* deff = nullptr;
DefFunc* auxf = nullptr;
int type;
if (lexic->Token == Token::COMMA) {
deff = new DefFunc("",0);
lexic->Next();
type = lexic->Token;
Specifier();
deff->parameters.push_back(new Parameter(lexic->Symbol, type));
Check(Token::IDENTIFIER);
auxf = _Parameter_List();
if( auxf != nullptr)
for(auto it: auxf->parameters)
deff->parameters.push_back(it);
}
return deff;
}
DefVar* Syntactic::Initializer() {
DefVar* defv = nullptr;
DefVar* auxv = nullptr;
Expression* expr = nullptr;
std::string symbol;
if (lexic->Token == Token::COMMA) {
defv = new DefVar(0);
lexic->Next();
symbol = lexic->Symbol;
Check(Token::IDENTIFIER);
expr = _Initializer();
auxv = Initializer();
defv->values.push_back(std::pair<std::string, Expression* >(symbol,expr));
if (auxv != nullptr)
for(auto it: auxv->values)
defv->values.push_back(it);
}
return defv;
}
Expression* Syntactic::_Initializer() {
Expression* expr = nullptr;
if (lexic->Token == Token::EQUAL) {
lexic->Next();
expr = expression();
}
return expr;
}
Compound* Syntactic::Compound_S() {
Compound* comp = nullptr;
if (lexic->Token == Token::BRACE_O) {
lexic->Next();
comp = _Compound_S();
Check("}");
} else {
Check(";");
}
return comp;
}
Compound* Syntactic::_Compound_S() {
Compound* comp = new Compound();
Compound* aux = nullptr;
if (lexic->Token == Token::INT || lexic->Token == Token::VOID) {
comp->stmt.push_back(Declaration_List());
aux = _Compound_S();
} else {
switch (lexic->Token) {
case Token::BRACE_O:
case Token::SEMICOLON:
case Token::IF:
case Token::WHILE:
case Token::DO:
case Token::FOR:
case Token::CONTINUE:
case Token::BREAK:
case Token::RETURN:
case Token::NUMBER:
case Token::IDENTIFIER:
case Token::PARENTHESES_O:
comp->stmt.push_back(Statement_List());
aux = _Compound_S();
break;
}
}
if(comp->stmt.empty()) {
delete comp;
comp = nullptr;
}
if(aux != nullptr) {
for(auto it: aux->stmt)
comp->stmt.push_back(it);
delete aux;
}
return comp;
}
Node* Syntactic::Statement_List() {
Node* nodent = nullptr;
switch (lexic->Token) {
case Token::BRACE_O:
case Token::SEMICOLON:
nodent = Compound_S();
break;
case Token::IF:
nodent = Selection_S();
break;
case Token::WHILE:
case Token::DO:
case Token::FOR:
nodent = Iteration_S();
break;
case Token::CONTINUE:
case Token::BREAK:
case Token::RETURN:
nodent = Jump_S();
break;
case Token::NUMBER:
case Token::IDENTIFIER:
case Token::PARENTHESES_O:
nodent = expression();
break;
default:
Error();
break;
}
return nodent;
}
If* Syntactic::Selection_S() {
If* nodeif = new If();
Else* nodels = nullptr;
Check(Token::IF);
Check("(");
nodeif->exp = expression();
Check(")");
nodeif->statement = Statement_List();
nodels = _Selection_S();
if (nodels != nullptr) {
for(auto it: nodels->els)
nodeif->els.push_back(it);
nodels->els.clear();
}
return nodeif;
}
Else* Syntactic::_Selection_S() {
Else* els = nullptr;
If* nodeif = nullptr;
if ( lexic->Token == Token::ELSE ) {
lexic->Next();
els->statement = Statement_List();
nodeif = dynamic_cast<If*>(els->statement);
if (nodeif != nullptr) {
for(auto it: nodeif->els)
els->els.push_back(it);
nodeif->els.clear();
}
}
return els;
}
Iterator* Syntactic::Iteration_S() {
Iterator* iter = new Iterator(lexic->Symbol, lexic->Token);
if ( lexic->Token == Token::WHILE ) {
lexic->Next();
Check("(");
iter->lexpr.push_back(expression());
Check(")");
iter->statement = Statement_List();
} else if ( lexic->Token == Token::FOR ) {
lexic->Next();
Check("(");
iter->lexpr.push_back(For_S());
iter->lexpr.push_back(For_S());
iter->lexpr.push_back(_For_S());
Check(")");
iter->statement = Statement_List();
} else if ( lexic->Token == Token::DO ) {
lexic->Next();
iter->statement = Statement_List();
Check(Token::WHILE);
Check("(");
iter->lexpr.push_back(expression());
Check(")");
Check(";");
} else
Error();
return iter;
}
Expression* Syntactic::For_S() {
Expression* nodent = nullptr;
if (lexic->Token == Token::IDENTIFIER ||
lexic->Token == Token::NUMBER) {
nodent = Expression_S();
}
else
Check(";");
return nodent;
}
Expression* Syntactic::_For_S() {
Expression* nodent = nullptr;
if (lexic->Token == Token::IDENTIFIER ||
lexic->Token == Token::NUMBER) {
nodent = expression();
}
return nodent;
}
Expression* Syntactic::Expression_S() {
Expression* expr = nullptr;
expr = expression();
Check(";");
return expr;
}
Expression* Syntactic::expression() {
Expression* ope = nullptr;
Expression* oper = nullptr;
ope = OP();
oper = EQ();
if (oper != nullptr)
oper->l = ope;
else
oper = ope;
return oper;
}
Expression* Syntactic::EQ() {
Expression* ope = nullptr;
Expression* aux = nullptr;
Expression* aux2 = nullptr;
std::string auxs;
int auxt;
if (lexic->Token == Token::EQUAL) {
auxs = lexic->Symbol;
auxt = lexic->Token;
lexic->Next();
aux = OP();
aux2 = EQ();
if (aux2 != nullptr)
aux2->l = aux;
else
aux2 = aux;
ope = new Assign(aux2, auxs, auxt);
}
return ope;
}
Expression* Syntactic::OP() {
Expression* ope = nullptr;
Expression* oper = nullptr;
ope = ROP();
oper = _OP();
if (oper != nullptr)
oper->l = ope;
else
oper = ope;
return oper;
}
Expression* Syntactic::_OP() {
Expression* ope = nullptr;
Expression* aux = nullptr;
Expression* aux2 = nullptr;
std::string auxs;
int auxt;
if (lexic->Token == Token::DOUBLE_EQUAL ||
lexic->Token == Token::NOT_EQUAL) {
auxs = lexic->Symbol;
auxt = lexic->Token;
lexic->Next();
aux = _OP();
aux2 = ROP();
if (aux2 != nullptr)
aux2->l = aux;
else
aux2 = aux;
ope = new Comp(aux2, auxs, auxt);
}
return ope;
}
Expression* Syntactic::ROP() {
Expression* ope = nullptr;
Expression* oper = nullptr;
ope = E();
oper = _ROP();
if (oper != nullptr)
oper->l = ope;
else
oper = ope;
return oper;
}
Expression* Syntactic::_ROP() {
Expression* ope = nullptr;
Expression* aux = nullptr;
Expression* aux2 = nullptr;
std::string auxs;
int auxt;
if (lexic->Token == Token::GREATER ||
lexic->Token == Token::LESS ||
lexic->Token == Token::GREATER_OR_EQUAL ||
lexic->Token == Token::LESS_OR_EQUAL) {
auxs = lexic->Symbol;
auxt = lexic->Token;
lexic->Next();
aux = E();
aux2 = _ROP();
if (aux2 != nullptr)
aux2->l = aux;
else
aux2 = aux;
ope = new Comp(aux2, auxs, auxt);
}
return ope;
}
Expression* Syntactic::E() {
Expression* ope = nullptr;
Expression* oper = nullptr;
ope = T();
oper = _E();
if (oper != nullptr)
oper->l = ope;
else
oper = ope;
return oper;
}
Expression* Syntactic::_E() {
Expression* ope = nullptr;
Expression* aux = nullptr;
Expression* aux2 = nullptr;
std::string auxs;
int auxt;
if (lexic->Token == Token::PLUS ||
lexic->Token == Token::MINUS) {
auxs = lexic->Symbol;
auxt = lexic->Token;
lexic->Next();
aux = T();
aux2 = _E();
if (aux2 != nullptr)
aux2->l = aux;
else
aux2 = aux;
ope = new Add(aux2, auxs, auxt);
}
return ope;
}
Expression* Syntactic::T() {
Expression* ope = nullptr;
Expression* oper = nullptr;
ope = F();
oper = _T();
if (oper != nullptr)
oper->l = ope;
else
oper = ope;
return oper;
}
Expression* Syntactic::_T() {
Expression* ope = nullptr;
Expression* aux = nullptr;
Expression* aux2 = nullptr;
std::string auxs;
int auxt;
if (lexic->Token == Token::MULTIPLICATION ||
lexic->Token == Token::DIVISION ||
lexic->Token == Token::MODULE) {
auxs = lexic->Symbol;
auxt = lexic->Token;
lexic->Next();
aux = F();
aux2 = _T();
if (aux2 != nullptr)
aux2->l = aux;
else
aux2 = aux;
ope = new Mul(aux2, auxs, auxt);
}
return ope;
}
Expression* Syntactic::F() {
Expression* nodent = nullptr;
FuncCall* aux = nullptr;
std::string auxs = lexic->Symbol;
int auxt = lexic->Token;
if (lexic->Token == Token::IDENTIFIER) {
lexic->Next();
aux = FD();
if (aux != nullptr) {
aux->symbol = auxs;
aux->type = auxt;
nodent = aux;
} else {
nodent = new Id(auxs, auxt);
}
} else if (lexic->Token == Token::NUMBER) {
nodent = new Value(lexic->Symbol, lexic->Token);
lexic->Next();
} else if (lexic->Token == Token::PARENTHESES_O) {
lexic->Next();
nodent = expression();
Check(")");
} else
Error();
return nodent;
}
FuncCall* Syntactic::FD() {
FuncCall* funcc = nullptr;
FuncCall* auxc = nullptr;
if (lexic->Token == Token::PARENTHESES_O) {
funcc = new FuncCall();
lexic->Next();
auxc = F_List();
Check(")");
if (auxc != nullptr) {
for (auto it: auxc->values)
funcc->values.push_back(it);
delete auxc;
}
}
return funcc;
}
FuncCall* Syntactic::F_List() {
FuncCall* funcc = nullptr;
FuncCall* auxc = nullptr;
if (lexic->Token == Token::NUMBER ||
lexic->Token == Token::IDENTIFIER ||
lexic->Token == Token::PARENTHESES_O) {
funcc = new FuncCall();
funcc->values.push_back(expression());
auxc = _F_List();
if (auxc != nullptr) {
for (auto it: auxc->values)
funcc->values.push_back(it);
delete auxc;
}
}
return funcc;
}
FuncCall* Syntactic::_F_List() {
FuncCall* funcc = nullptr;
FuncCall* auxc = nullptr;
if (lexic->Token == Token::COMMA) {
funcc = new FuncCall();
lexic->Next();
funcc->values.push_back(expression());
auxc = _F_List();
if (auxc != nullptr) {
for (auto it: auxc->values)
funcc->values.push_back(it);
delete auxc;
}
}
return funcc;
}
Jump* Syntactic::Jump_S() {
Jump* jump = new Jump(lexic->Symbol, lexic->Token);
if (lexic->Token == Token::CONTINUE ||
lexic->Token == Token::BREAK) {
lexic->Next();
Check(";");
} else if (lexic->Token == Token::RETURN) {
lexic->Next();
jump->exp = _RR();
Check(";");
} else
Error();
return jump;
}
Expression* Syntactic::_RR() {
Expression* nodent = nullptr;
if (lexic->Token == Token::NUMBER ||
lexic->Token == Token::IDENTIFIER ||
lexic->Token == Token::PARENTHESES_O)
nodent = expression();
return nodent;
}
DefVar* Syntactic::Declaration_List() {
DefVar* defv = nullptr;
defv = Declarator();
Check(";");
return defv;
}
DefVar* Syntactic::Declarator() {
DefVar* defv = nullptr;
DefVar* auxv = nullptr;
Expression* expr = nullptr;
int type = lexic->Token;
std::string symbol;
Specifier();
symbol = lexic->Symbol;
Check(Token::IDENTIFIER);
expr = _Initializer();
auxv = Initializer();
defv = new DefVar(type);
defv->values.push_back( std::pair<std::string, Expression*>(symbol,expr));
if (auxv != nullptr)
for (auto it: auxv->values)
defv->values.push_back(it);
return defv;
}
void Syntactic::Check(int value) {
if (value == lexic->Token) {
lexic->Next();
} else {
Error();
}
}
void Syntactic::Check(std::string value) {
if (value == lexic->Symbol) {
lexic->Next();
} else
Error();
}
void Syntactic::Error() {
std::cout << "ERROR IN SYNTACTIC PHASE" << std::endl;
std::cout << "Error near \"" << lexic->Symbol << "\".\n";
exit(0);
}
| 22.32 | 76 | 0.557812 | Donluigimx |
160223bd99ab97b75926acbb952eafbf66a5bc08 | 1,114 | inl | C++ | 4_Timeline-examples/4_3_Sequentity/src/sequentity/Components.inl | Daandelange/ofxSurfingImGui | 122241ebcb900d30a5fa6b548de41b2910a27401 | [
"MIT"
] | 11 | 2021-06-27T09:02:07.000Z | 2022-03-13T07:40:36.000Z | 4_Timeline-examples/4_3_Sequentity/src/sequentity/Components.inl | Daandelange/ofxSurfingImGui | 122241ebcb900d30a5fa6b548de41b2910a27401 | [
"MIT"
] | null | null | null | 4_Timeline-examples/4_3_Sequentity/src/sequentity/Components.inl | Daandelange/ofxSurfingImGui | 122241ebcb900d30a5fa6b548de41b2910a27401 | [
"MIT"
] | 6 | 2021-06-09T08:01:36.000Z | 2021-12-06T07:28:52.000Z | // Components
using TimeType = int;
using Position = Vector2i;
using Orientation = float;
struct InitialPosition : Position { using Position::Position; };
struct StartPosition : Position { using Position::Position; };
struct Size : Position { using Position::Position; };
struct InitialSize : Size { using Size::Size; };
using Index = unsigned int;
struct Preselected {};
struct Selected {};
struct Hovered {};
using Color = ImVec4;
struct Name {
const char* text;
};
// Input
// From e.g. Wacom tablet
struct InputPressure { float strength; };
struct InputPitch { float angle; };
struct InputYaw { float angle; };
// From e.g. Mouse or WASD keys
struct InputPosition2D {
Vector2i absolute;
Vector2i relative;
Vector2i delta;
Vector2i normalised;
unsigned int width;
unsigned int height;
};
struct InputPosition3D : Vector3i {
using Vector3i::Vector3i;
};
// From e.g. WASD keys or D-PAD on XBox controller
enum class Direction2D : std::uint8_t { Left = 0, Up, Right, Down };
enum class Direction3D : std::uint8_t { Left = 0, Up, Right, Down, Forward, Backward };
| 21.423077 | 87 | 0.698384 | Daandelange |
1605232a7fe88177bff7ee2fc6b5c326e32c634e | 612 | cpp | C++ | AIC/AIC'20 - Level 2 Training/Week #3.1/Z.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 3 | 2020-11-01T06:31:30.000Z | 2022-02-21T20:37:51.000Z | AIC/AIC'20 - Level 2 Training/Week #3.1/Z.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | null | null | null | AIC/AIC'20 - Level 2 Training/Week #3.1/Z.cpp | MaGnsio/CP-Problems | a7f518a20ba470f554b6d54a414b84043bf209c5 | [
"Unlicense"
] | 1 | 2021-05-05T18:56:31.000Z | 2021-05-05T18:56:31.000Z | //https://vjudge.net/contest/419722#problem/Z
#include <bits/stdc++.h>
using namespace std;
#define F first
#define S second
typedef long long ll;
typedef long double ld;
ll mod = 1e9 + 7;
int main ()
{
ios_base::sync_with_stdio (0); cin.tie (0); cout.tie (0);
ll n, cnt = 1;
cin >> n;
vector<pair<bool, ll>> a(n + 1, {true, 0});
for (ll i = 2; i <= n; ++i)
{
if (a[i].F)
{
a[i].S = cnt;
for (ll j = 2 * i; j <= n; j += i) a[j].F = false, a[j].S = cnt;
cnt++;
}
}
for (ll i = 2; i <= n; ++i) cout << a[i].S << " ";
}
| 21.857143 | 76 | 0.46732 | MaGnsio |
16064c8d3937a988233e43709e7ba84375c7714f | 17,259 | cpp | C++ | getic/texref.cpp | circinusX1/qgetic | 112e20af4e940eae44af9cbf51362f362a743329 | [
"BSD-4-Clause"
] | null | null | null | getic/texref.cpp | circinusX1/qgetic | 112e20af4e940eae44af9cbf51362f362a743329 | [
"BSD-4-Clause"
] | null | null | null | getic/texref.cpp | circinusX1/qgetic | 112e20af4e940eae44af9cbf51362f362a743329 | [
"BSD-4-Clause"
] | null | null | null |
#include "stdafx.h"
#include "winwrap.h"
#include "GL/gl.h"
#include "texref.h"
#include "geticapp.h"
#include "glwindow.h"
#include "view3d.h"
#include "geticmainwnd.h"
#ifdef WINDOWS
# pragma warning (disable: 4786)
#endif
#ifdef _DEBUG
#undef THIS_FILE
static char THIS_FILE[]=__FILE__;
#define new DEBUG_NEW
#endif
#ifndef __HTEX
typedef int32_t HTEX;
#define __HTEX
#endif //
u_bool32 TexRef::_MakeCurrent=1;
Htex TexRef::_defTex;
int32_t SmartTex::_TexCopy = 1;
extern Htex _dumptex;
static struct Bppform
{
int32_t bpp;
int32_t gl1;
int32_t gl2;
} GBpp[5] =
{
{0, -1 , -1 },
{1, GL_LUMINANCE, GL_LUMINANCE},
{2, -1 , -1 },
{3, GL_RGB, GL_UNSIGNED_BYTE },
{4, GL_RGBA, GL_UNSIGNED_BYTE }
};
void MakeCurrent(char c)
{
assert(0);
}
void MakeCurrent(HDC hdc, HGLRC hrc)
{
assert(0);
}
void TexRef::RemoveTex(Htex* it, int32_t i)
{
assert(ThrID == GetCurrentThreadId());
if(ThrID != GetCurrentThreadId())
{
//AfxGetMainWnd()->SendMessage(WM_REMOVETEX, it);
return;
}
GCur gc(PT3);
if(*it > 0 && glIsTexture(*it))
{
glDeleteTextures(1,(u_int32_t*)&it->hTex);
}
}
Htex TexRef::GlGenTex(int32_t x, int32_t y, int32_t bpp, u_int8_t* pBuff, u_int32_t flags)
{
#ifdef WINDOWS
assert(ThrID == GetCurrentThreadId());
if(ThrID != GetCurrentThreadId())
return TexRef::_defTex;
if(_MakeCurrent)
::wglMakeCurrent(PT3->_hdc, PT3->m_hRC);
Htex itex = _GlGenTex(x, y, bpp, pBuff, flags);
itex.glTarget = flags;
if(itex > 32000)
{
Beep(1000,200);
SBT(0,"Too many textures!");
}
#else
if(ThrID != GetCurrentThreadId())
return TexRef::_defTex;
GCur gc(PT3);
Htex itex = _GlGenTex(x, y, bpp, pBuff, flags);
itex.glTarget = flags;
if(itex > 32000)
{
Beep(1000,200);
SBT(0,"Too many textures!");
glDeleteTextures(1, &itex.hTex);
return _dumptex;
}
return itex;
#endif
}
void TexRef::_RemoveTex(Htex& it)
{
/*
assert(ThrID == GetCurrentThreadId());
if(ThrID != GetCurrentThreadId())
return;
*/
if(it > 0 && glIsTexture(it))
{
glDeleteTextures(1,(u_int32_t*)&it);
}
}
//--------------------------------------------------------------------------------------------
void Local_LoadBytes(u_int8_t* pD, u_int8_t* pS, int32_t sx, int32_t sy, int32_t x, int32_t y, int32_t lS)
{
u_int8_t* pDest = pD;
for(int32_t j=0;j<y;j++)
{
for(int32_t i=0; i < x; i++)
{
*pDest = pS[sx+i + (sy +j)*lS];
++pDest;
}
}
}
Htex TexRef::_GlGenTex(int32_t x, int32_t y, int32_t bpp, u_int8_t* pBuff, u_int32_t flags)
{
Htex hTex;
u_int32_t texTarget;
u_bool32 ok=1;
try{
::glGenTextures(1,(u_int32_t*)&hTex.hTex);
if(0==hTex.hTex)
{
int32_t le = GetLastError();
return hTex;
}
hTex.glTarget = flags;
switch(TGET_TARGET(flags))
{
case GEN_TEX_2D_MAP:
glBindTexture(GL_TEXTURE_2D, hTex.hTex);
texTarget = GL_TEXTURE_2D;
break;
case GEN_TEX_CUBE_MAP:
glBindTexture(GL_TEXTURE_CUBE_MAP, hTex.hTex); // pause for now
texTarget = GL_TEXTURE_CUBE_MAP;
break;
case GEN_TEX_3D_MAP: // disabled
glBindTexture(GL_TEXTURE_2D, hTex.hTex);
texTarget = GL_TEXTURE_2D;
break;
}
// decompose the on bitmap (see if 6 bitmaps are there)
if(TGET_WRAP(flags) == GEN_TEX_HAS_CUBE_T)
{
u_int8_t* lb = new u_int8_t[(x*y*bpp)/12];
Local_LoadBytes(lb, pBuff, x/4, 0, x/4, y/3, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/4, y/3, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, 0, y/3, x/4, y/3, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/4, y/3, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, x/4, y/3, x/4, y/3, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/4, y/3, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, 2*x/4, y/3, x/4, y/3, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/4, y/3, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, 3*x/4, y/3, x/4, y/3, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/4, y/3, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, x/4, 2*y/3, x/4, y/3, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/4, y/3, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
delete[] lb;
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
ok=1;
}
if(TGET_WRAP(flags) == GEN_TEX_HAS_CUBE_M)
{
u_int8_t* lb = new u_int8_t[(x*y*bpp)/6];
Local_LoadBytes(lb, pBuff, 0, 0, x/3, y/2, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/3, y/2, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, x/3, 0, x/3, y/2, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/3, y/2, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, 2*x/3, 0, x/3, y/2, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/3, y/2, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, 0, y/2, x/3, y/2, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/3, y/2, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, x/3, y/2, x/3, y/2, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/3, y/2, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
Local_LoadBytes(lb, pBuff, 2*x/3, y/2, x/3, y/2, x);
glTexImage2D( GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB,
0, GL_RGB, x/3, y/2, 0, GL_RGB, GL_UNSIGNED_BYTE, lb);
delete[] lb;
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_CUBE_MAP_ARB, GL_TEXTURE_WRAP_R, GL_CLAMP_TO_EDGE);
ok=1;
}
if(TGET_WRAP(flags) == GEN_CLAMP)
{
glTexParameteri(texTarget, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE );
glTexParameteri(texTarget, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE );
}
else
{
glTexParameteri(texTarget,GL_TEXTURE_WRAP_S,GL_REPEAT);
glTexParameteri(texTarget,GL_TEXTURE_WRAP_T,GL_REPEAT);
}
switch(TGET_FILTER(flags))
{
case GEN_TEX_MM_NONE:
glTexParameteri(texTarget, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(texTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
case GEN_TEX_MM_LINEAR: //lin
glTexParameteri(texTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(texTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
break;
default:
case GEN_TEX_MM_BILINEAR: // 2 lin
glTexParameteri(texTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(texTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_NEAREST);
break;
case GEN_TEX_MM_TRILINEAR: // 3 lin
glTexParameteri(texTarget, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(texTarget, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
break;
}
if(ok && pBuff)
{
// assert(0);
glTexImage2D(texTarget,0,bpp,x,y,0,GBpp[bpp].gl1, GBpp[bpp].gl2,pBuff);
gluBuild2DMipmaps(texTarget,bpp,x,y,GBpp[bpp].gl1, GBpp[bpp].gl2,pBuff);
}
}catch(...){}
return hTex;
}
u_int8_t* TexRef::LoadRCTextureBuffer(const char* szId,int32_t sx, int32_t sy)
{
#ifdef WINDOWS
HRSRC hrsrc = FindResource(AfxGetResourceHandle(),szId, "SCE_ITEM");
if(hrsrc)
{
HGLOBAL hResLoad = LoadResource(AfxGetResourceHandle(), hrsrc);
if(hResLoad)
{
// read the dim here
u_int32_t dwSize = SizeofResource( AfxGetResourceHandle(), hrsrc);
if(sx==sy)
{
sx = sqrt(float(dwSize/3.0));
sy = sqrt(float(dwSize/3.0));
assert(sx==sy);
//fix . make it square if escapes
sx = tmin(sx,sy);
sy =sx;
}
void* pData = LockResource(hResLoad);
if(pData)
{
u_int8_t* retBuff = new u_int8_t[sx * sy * 3];
// make it upside down
::memcpy(retBuff, (u_int8_t*)pData, sx * sy * 3);
return retBuff;
}
}
}
#else
assert(0);
#endif
return 0;
}
static void $Invert(u_int8_t* by, int32_t x, int32_t y, int32_t bpp)
{
u_int8_t* line = new u_int8_t[x*y*3];
for(int32_t i=0; i < y/2; i++ )
{
//flip vertical
memcpy(&line[0], &by[i], bpp * x);
memcpy(&by[i], &by[y-i-1], bpp * x);
memcpy(&by[y-i-1], line, bpp * x);
}
delete[] line;
}
//load a resource id bitmap and get rgb's and make a texture out of it
Htex TexRef::LoadRCTexture(const char* szId, int32_t sx, int32_t sy, u_int8_t* pwantbuff)
{
#ifdef WINDOWNS
HRSRC hrsrc = FindResource(AfxGetResourceHandle(),szId, "SCE_ITEM");
if(hrsrc)
{
HGLOBAL hResLoad = LoadResource(AfxGetResourceHandle(), hrsrc);
if(hResLoad)
{
// read the dim here
u_int32_t dwSize = SizeofResource( AfxGetResourceHandle(), hrsrc);
if(sx==sy)
{
sx = sqrt(float(dwSize/3.0));
sy = sqrt(float(dwSize/3.0));
assert(sx==sy);
//fix . make it square if escapes
sx = tmin(sx,sy);
sy =sx;
}
void* pData = LockResource(hResLoad);
if(pData)
{
if(_MakeCurrent)
MakeCurrent('3');
//$Invert((u_int8_t*)pData,sx,sy, 3);
if(pwantbuff){
memcpy(pwantbuff, pData, sx * sy* 3);
}
return _GlGenTex(sx, sy, 3, (u_int8_t*)pData, TEX_NORMAL);
}
}
}
#else
assert(0);
#endif
return _defTex;
}
Htex TexRef::LoadThisFile(const char* pszFileName, u_int32_t flags)
{
TexHandler th;
if(th.LoadThisFile(pszFileName, flags))
return _GlGenTex(th.n_x, th.n_y, th.n_bpp, th.Buffer(), flags);
return _defTex;
}
Htex TexRef::LoadFile(char* pszFileName, u_int32_t flags)
{
TexHandler th;
if(th.LoadFile(pszFileName, flags))
return _GlGenTex(th.n_x, th.n_y, th.n_bpp, th.Buffer(), flags);
return _defTex;
}
void TexRef::Clear(u_bool32 b)
{
theApp->_TexSys.Clean();
::memset(theApp->_TexSys._texmap,0,sizeof(u_int32_t)*TEX_CAPACITY);
}
void TexRef::GlLmapMode(u_bool32 start)
{
if(start)
{
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
glDepthFunc(GL_EQUAL);
glBlendFunc(GL_ZERO,GL_SRC_COLOR);
//glBlendFunc(GL_SRC_ALPHA, GL_ONE);
}
else
{
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
}
}
void TexRef::GlDecalMode(u_bool32 start)
{
if(start)
{
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
glDepthFunc(GL_EQUAL);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); //transparency
}
else
{
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
}
}
void TexRef::GlHalloMode(u_bool32 start)
{
if(start)
{
/*
u_int32_t modes[]={ GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_SRC_ALPHA_SATURATE,
-1,
};
*/
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
glDepthFunc(GL_EQUAL);
glBlendFunc(GL_ONE, GL_ONE);
// glBlendFunc(modes[(int32_t)SCENE()._si.fogNear],modes[(int32_t)SCENE()._si.fogFar]);
}
else
{
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
}
}
void TexRef::GlDetailMode(u_bool32 start)
{
if(start)
{
u_int32_t modes[]={ GL_ZERO,
GL_ONE,
GL_SRC_COLOR,
GL_ONE_MINUS_SRC_COLOR,
GL_DST_COLOR,
GL_ONE_MINUS_DST_COLOR,
GL_SRC_ALPHA,
GL_ONE_MINUS_SRC_ALPHA,
GL_DST_ALPHA,
GL_ONE_MINUS_DST_ALPHA,
GL_SRC_ALPHA_SATURATE,
-1,
};
glEnable(GL_BLEND);
glDepthMask(GL_FALSE);
glDepthFunc(GL_EQUAL);
glBlendFunc(774,772);
}
else
{
glDepthMask(GL_TRUE);
glDepthFunc(GL_LESS);
glDisable(GL_BLEND);
}
}
SmartTex::SmartTex():_pRefs(0){}
SmartTex::SmartTex (const SmartTex& r)
{
if(_TexCopy==0) return;
if(r._hTex.hTex == TexRef::_defTex.hTex || r._hTex.hTex == 0)
{
_hTex = r._hTex;
return;
}
Clear();
++theApp->_TexSys._texmap[r._hTex.hTex];
_hTex = r._hTex;
_pRefs = &theApp->_TexSys._texmap[_hTex.hTex];
}
SmartTex::~SmartTex(){
if(_TexCopy==0)return;
Clear();
}
SmartTex& SmartTex::operator=(const SmartTex& r)
{
if(_TexCopy==0) return *this;
if(r._hTex.hTex == TexRef::_defTex.hTex || r._hTex.hTex == 0)
{
_hTex = r._hTex;
return *this;
}
if(this!=&r){
Clear();
++theApp->_TexSys._texmap[r._hTex.hTex];
_hTex = r._hTex;
_pRefs = &theApp->_TexSys._texmap[_hTex.hTex];
}
return *this;
}
SmartTex& SmartTex::operator=(const Htex& ht){
if(_TexCopy==0)return *this;
++theApp->_TexSys._texmap[ht.hTex];
_hTex = ht;
_pRefs = &theApp->_TexSys._texmap[ht.hTex];
return *this;
}
void SmartTex::operator--(){
if(_TexCopy==0)return;
Clear();
}
const char* SmartTex::GetTexName(){
return theApp->_TexSys.GetTexName(_hTex);
}
void SmartTex::AddRef(){
_pRefs = &theApp->_TexSys._texmap[_hTex.hTex];
++(*_pRefs);
}
SmartTex& SmartTex::Assign(const char* p, u_int32_t flags){
if(_TexCopy==0)
return *this;
Clear();
Htex ht = theApp->_TexSys.Assign(p, flags);
if(ht.hTex)
{
assert(ht.hTex < TEX_CAPACITY);
if(ht.hTex < TEX_CAPACITY)
{
++theApp->_TexSys._texmap[ht.hTex];
_hTex = ht;
_pRefs = &theApp->_TexSys._texmap[_hTex.hTex];
}
else
{
_hTex = _dumptex; // default dummy
_hTex.glTarget = 0;
}
}else
{
_hTex = ht; // default dummy
_hTex.glTarget = 0;
}
return *this;
}
void SmartTex::Reset(){
_hTex.hTex = 0;
}
void SmartTex::Clear(){
if(_hTex.hTex == TexRef::_defTex.hTex || _hTex.hTex == 0) return;
if(theApp->_TexSys._texmap[_hTex.hTex]==0) return;
--theApp->_TexSys._texmap[_hTex.hTex];
if(theApp->_TexSys._texmap[_hTex.hTex]==0)
{
theApp->_TexSys.RemoveTexture(_hTex);
_hTex.hTex = 0;
_hTex.glTarget = 0;
}
}
| 27.265403 | 106 | 0.547598 | circinusX1 |
160851bb5c5591be914c9f011ac26f1690b40c9a | 7,036 | cpp | C++ | src/materialsystem/stdshaders/detail_grass.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 6 | 2022-01-23T09:40:33.000Z | 2022-03-20T20:53:25.000Z | src/materialsystem/stdshaders/detail_grass.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | null | null | null | src/materialsystem/stdshaders/detail_grass.cpp | cstom4994/SourceEngineRebuild | edfd7f8ce8af13e9d23586318350319a2e193c08 | [
"MIT"
] | 1 | 2022-02-06T21:05:23.000Z | 2022-02-06T21:05:23.000Z |
#include "BaseVSShader.h"
#include "mathlib/vmatrix.h"
#include "convar.h"
#include "cpp_shader_constant_register_map.h"
#include "detail_prop_shader_ps30.inc"
#include "detail_prop_shader_vs30.inc"
static const float kDefaultSpecColor[] = { 0.905750f, 1.0f, 0.675000f };
BEGIN_VS_SHADER(detail_grass, "")
BEGIN_SHADER_PARAMS
SHADER_PARAM(MUTABLE_01, SHADER_PARAM_TYPE_VEC3, "[0 0 0]", "Wind Dir")
SHADER_PARAM(MUTABLE_02, SHADER_PARAM_TYPE_FLOAT, "0.0f", "Wind Angle (Radians)")
SHADER_PARAM(GRASS_SPEC_COLOR, SHADER_PARAM_TYPE_COLOR, "[0.905750 1 0.675000]", "")
SHADER_PARAM(TIME, SHADER_PARAM_TYPE_FLOAT, "0.0", "Needs CurrentTime Proxy")
END_SHADER_PARAMS
SHADER_INIT_PARAMS()
{
SET_PARAM_VEC_IF_NOT_DEFINED(GRASS_SPEC_COLOR, kDefaultSpecColor, 3);
}
SHADER_FALLBACK
{
return 0;
}
SHADER_INIT
{
LoadTexture(BASETEXTURE);
LoadTexture(FLASHLIGHTTEXTURE, TEXTUREFLAGS_SRGB);
}
SHADER_DRAW
{
int nShadowFilterMode = 0;
bool bHasFlashlight = UsingFlashlight(params);
if (bHasFlashlight)
{
nShadowFilterMode = g_pHardwareConfig->GetShadowFilterMode(); // Based upon vendor and device dependent formats
}
SHADOW_STATE
{
// Reset shadow state manually since we're drawing from two materials
SetInitialShadowState();
pShaderShadow->EnableTexture(SHADER_SAMPLER0, true);
pShaderShadow->EnableSRGBRead(SHADER_SAMPLER0, false);
pShaderShadow->EnableTexture(SHADER_SAMPLER1, true);
pShaderShadow->EnableSRGBRead(SHADER_SAMPLER1, true);
pShaderShadow->EnableTexture(SHADER_SAMPLER2, true); // Depth texture
pShaderShadow->SetShadowDepthFiltering(SHADER_SAMPLER2);
pShaderShadow->EnableTexture(SHADER_SAMPLER3, true);
pShaderShadow->EnableSRGBRead(SHADER_SAMPLER3, false);
pShaderShadow->EnableSRGBWrite(false);
pShaderShadow->EnableDepthWrites(true);
pShaderShadow->EnableCulling(false);
pShaderShadow->EnableAlphaTest(true);
pShaderShadow->EnableBlending(false);
pShaderShadow->EnableDepthTest(true);
pShaderShadow->AlphaFunc(SHADER_ALPHAFUNC_GEQUAL, 0.5f);
unsigned int flags = VERTEX_POSITION|VERTEX_NORMAL|VERTEX_COLOR| VERTEX_FORMAT_VERTEX_SHADER;
int nTexCoordCount = 3;
int userDataSize = 0;
int nTexCoordDims[] = { 2, 3, 3 };
pShaderShadow->VertexShaderVertexFormat(flags, nTexCoordCount, nTexCoordDims, userDataSize);
// Vertex Shader
DECLARE_STATIC_VERTEX_SHADER(detail_prop_shader_vs30);
SET_STATIC_VERTEX_SHADER_COMBO(FLASHLIGHT, bHasFlashlight);
SET_STATIC_VERTEX_SHADER(detail_prop_shader_vs30);
DECLARE_STATIC_PIXEL_SHADER(detail_prop_shader_ps30);
SET_STATIC_PIXEL_SHADER_COMBO(FLASHLIGHT, bHasFlashlight);
SET_STATIC_PIXEL_SHADER_COMBO(FLASHLIGHTDEPTHFILTERMODE, nShadowFilterMode);
SET_STATIC_PIXEL_SHADER(detail_prop_shader_ps30);
}
DYNAMIC_STATE
{
// Reset render state manually since we're drawing from two materials
pShaderAPI->SetDefaultState();
bool bFlashlightShadows = false;
if (bHasFlashlight)
{
VMatrix worldToTexture;
ITexture *pFlashlightDepthTexture;
FlashlightState_t state = pShaderAPI->GetFlashlightStateEx(worldToTexture, &pFlashlightDepthTexture);
bFlashlightShadows = state.m_bEnableShadows && (pFlashlightDepthTexture != NULL);
BindTexture(SHADER_SAMPLER1, state.m_pSpotlightTexture, state.m_nSpotlightTextureFrame);
SetFlashLightColorFromState(state, pShaderAPI, PSREG_FLASHLIGHT_COLOR);
if (pFlashlightDepthTexture && g_pConfig->ShadowDepthTexture() && state.m_bEnableShadows)
{
BindTexture(SHADER_SAMPLER2, pFlashlightDepthTexture, 0);
pShaderAPI->BindStandardTexture(SHADER_SAMPLER3, TEXTURE_SHADOW_NOISE_2D);
}
}
// Set Vertex Shader Combos
DECLARE_DYNAMIC_VERTEX_SHADER(detail_prop_shader_vs30);
SET_DYNAMIC_VERTEX_SHADER(detail_prop_shader_vs30);
DECLARE_DYNAMIC_PIXEL_SHADER(detail_prop_shader_ps30);
SET_DYNAMIC_PIXEL_SHADER_COMBO(WRITEWATERFOGTODESTALPHA, false);
SET_DYNAMIC_PIXEL_SHADER_COMBO(PIXELFOGTYPE, pShaderAPI->GetPixelFogCombo());
SET_DYNAMIC_PIXEL_SHADER_COMBO(FLASHLIGHTSHADOWS, bFlashlightShadows);
SET_DYNAMIC_PIXEL_SHADER(detail_prop_shader_ps30);
if (params[BASETEXTURE]->IsTexture())
{
BindTexture(SHADER_SAMPLER0, BASETEXTURE, FRAME);
}
else
{
pShaderAPI->BindStandardTexture(SHADER_SAMPLER0, TEXTURE_WHITE);
}
pShaderAPI->SetPixelShaderFogParams(PSREG_FOG_PARAMS);
float vPsConst0[4] = { 0.0f, 0.0f, 0.0f, 0.0f };
if (IS_PARAM_DEFINED(MUTABLE_01))
{
params[MUTABLE_01]->GetVecValue(vPsConst0, 3);
}
if (IS_PARAM_DEFINED(MUTABLE_02))
{
vPsConst0[3] = params[MUTABLE_02]->GetFloatValue();
}
pShaderAPI->SetVertexShaderConstant(VERTEX_SHADER_SHADER_SPECIFIC_CONST_0, vPsConst0);
float flTime = IS_PARAM_DEFINED(TIME) && params[TIME]->GetFloatValue() > 0.0f ? params[TIME]->GetFloatValue() : pShaderAPI->CurrentTime();
float vPsConst1[4] = { flTime, 0.0f, 0.0f, 0.0f };
pShaderAPI->SetVertexShaderConstant(VERTEX_SHADER_SHADER_SPECIFIC_CONST_1, vPsConst1);
if (bHasFlashlight)
{
VMatrix worldToTexture;
float atten[4], pos[4], tweaks[4];
const FlashlightState_t &flashlightState = pShaderAPI->GetFlashlightState(worldToTexture);
SetFlashLightColorFromState(flashlightState, pShaderAPI, PSREG_FLASHLIGHT_COLOR);
BindTexture(SHADER_SAMPLER1, flashlightState.m_pSpotlightTexture, flashlightState.m_nSpotlightTextureFrame);
atten[0] = flashlightState.m_fConstantAtten; // Set the flashlight attenuation factors
atten[1] = flashlightState.m_fLinearAtten;
atten[2] = flashlightState.m_fQuadraticAtten;
atten[3] = flashlightState.m_FarZ;
pShaderAPI->SetPixelShaderConstant(PSREG_FLASHLIGHT_ATTENUATION, atten, 1);
pos[0] = flashlightState.m_vecLightOrigin[0]; // Set the flashlight origin
pos[1] = flashlightState.m_vecLightOrigin[1];
pos[2] = flashlightState.m_vecLightOrigin[2];
pShaderAPI->SetPixelShaderConstant(PSREG_FLASHLIGHT_POSITION_RIM_BOOST, pos, 1);
pShaderAPI->SetVertexShaderConstant(VERTEX_SHADER_SHADER_SPECIFIC_CONST_2, worldToTexture.Base(), 4);
// Tweaks associated with a given flashlight
tweaks[0] = ShadowFilterFromState(flashlightState);
tweaks[1] = ShadowAttenFromState(flashlightState);
HashShadow2DJitter(flashlightState.m_flShadowJitterSeed, &tweaks[2], &tweaks[3]);
pShaderAPI->SetPixelShaderConstant(PSREG_ENVMAP_TINT__SHADOW_TWEAKS, tweaks, 1);
// Dimensions of screen, used for screen-space noise map sampling
float vScreenScale[4] = { 1280.0f / 32.0f, 720.0f / 32.0f, 0, 0 };
int nWidth, nHeight;
pShaderAPI->GetBackBufferDimensions(nWidth, nHeight);
vScreenScale[0] = (float)nWidth / 32.0f;
vScreenScale[1] = (float)nHeight / 32.0f;
pShaderAPI->SetPixelShaderConstant(PSREG_FLASHLIGHT_SCREEN_SCALE, vScreenScale, 1);
}
float eyePos[4];
pShaderAPI->GetWorldSpaceCameraPosition(eyePos);
pShaderAPI->SetPixelShaderConstant(PSREG_EYEPOS_SPEC_EXPONENT, eyePos);
SetPixelShaderConstant(17, GRASS_SPEC_COLOR);
}
Draw();
}
END_SHADER
| 34.15534 | 140 | 0.777146 | cstom4994 |
160939911fffefe5565b85cc0728557ffca85107 | 721 | cpp | C++ | libs/storage/storage.cpp | digitalpiloten/pxt-ev3 | b9b21328b16cc69963b45efcb9999f511224f2d0 | [
"MIT"
] | 40 | 2019-05-11T06:19:58.000Z | 2022-02-19T19:44:19.000Z | libs/storage/storage.cpp | digitalpiloten/pxt-ev3 | b9b21328b16cc69963b45efcb9999f511224f2d0 | [
"MIT"
] | 113 | 2019-05-27T17:55:18.000Z | 2022-02-20T11:57:21.000Z | libs/storage/storage.cpp | digitalpiloten/pxt-ev3 | b9b21328b16cc69963b45efcb9999f511224f2d0 | [
"MIT"
] | 33 | 2019-05-18T08:11:25.000Z | 2022-02-15T02:15:05.000Z | #include "pxt.h"
#include <sys/types.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
namespace storage {
/** Will be moved. */
//%
Buffer __stringToBuffer(String s) {
return mkBuffer((uint8_t *)s->data, s->length);
}
/** Will be moved. */
//%
String __bufferToString(Buffer s) {
return mkString((char*)s->data, s->length);
}
//%
void __init() {
// do nothing
}
//%
void __unlink(String filename) {
::unlink(filename->data);
}
//%
void __truncate(String filename) {
int fd = open(filename->data, O_CREAT | O_TRUNC | O_WRONLY, 0777);
close(fd);
}
/** Create named directory. */
//%
void __mkdir(String filename) {
::mkdir(filename->data, 0777);
}
} // namespace storage
| 16.022222 | 70 | 0.631068 | digitalpiloten |
160ad4687ce21f5680448aa95550f036121f2bd6 | 2,561 | hpp | C++ | src/mlpack/methods/emst/union_find.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 675 | 2019-02-07T01:23:19.000Z | 2022-03-28T05:45:10.000Z | src/mlpack/methods/emst/union_find.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 843 | 2019-01-25T01:06:46.000Z | 2022-03-16T11:15:53.000Z | src/mlpack/methods/emst/union_find.hpp | RMaron/mlpack | a179a2708d9555ab7ee4b1e90e0c290092edad2e | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 83 | 2019-02-20T06:18:46.000Z | 2022-03-20T09:36:09.000Z | /**
* @file union_find.hpp
* @author Bill March (march@gatech.edu)
*
* Implements a union-find data structure. This structure tracks the components
* of a graph. Each point in the graph is initially in its own component.
* Calling unionfind.Union(x, y) unites the components indexed by x and y.
* unionfind.Find(x) returns the index of the component containing point x.
*
* mlpack is free software; you may redistribute it and/or modify it under the
* terms of the 3-clause BSD license. You should have received a copy of the
* 3-clause BSD license along with mlpack. If not, see
* http://www.opensource.org/licenses/BSD-3-Clause for more information.
*/
#ifndef MLPACK_METHODS_EMST_UNION_FIND_HPP
#define MLPACK_METHODS_EMST_UNION_FIND_HPP
#include <mlpack/prereqs.hpp>
namespace mlpack {
namespace emst {
/**
* A Union-Find data structure. See Cormen, Rivest, & Stein for details. The
* structure tracks the components of a graph. Each point in the graph is
* initially in its own component. Calling Union(x, y) unites the components
* indexed by x and y. Find(x) returns the index of the component containing
* point x.
*/
class UnionFind
{
private:
arma::Col<size_t> parent;
arma::ivec rank;
public:
//! Construct the object with the given size.
UnionFind(const size_t size) : parent(size), rank(size)
{
for (size_t i = 0; i < size; ++i)
{
parent[i] = i;
rank[i] = 0;
}
}
//! Destroy the object (nothing to do).
~UnionFind() { }
/**
* Returns the component containing an element.
*
* @param x the component to be found
* @return The index of the component containing x
*/
size_t Find(const size_t x)
{
if (parent[x] == x)
{
return x;
}
else
{
// This ensures that the tree has a small depth.
parent[x] = Find(parent[x]);
return parent[x];
}
}
/**
* Union the components containing x and y.
*
* @param x one component
* @param y the other component
*/
void Union(const size_t x, const size_t y)
{
const size_t xRoot = Find(x);
const size_t yRoot = Find(y);
if (xRoot == yRoot)
{
return;
}
else if (rank[xRoot] == rank[yRoot])
{
parent[yRoot] = parent[xRoot];
rank[xRoot] = rank[xRoot] + 1;
}
else if (rank[xRoot] > rank[yRoot])
{
parent[yRoot] = xRoot;
}
else
{
parent[xRoot] = yRoot;
}
}
}; // class UnionFind
} // namespace emst
} // namespace mlpack
#endif // MLPACK_METHODS_EMST_UNION_FIND_HPP
| 24.390476 | 80 | 0.64467 | RMaron |
160fa8e9240bf2cf611313c54ab694d7ce45fb96 | 761 | cpp | C++ | SDKs/CryCode/3.6.15/CryEngine/CryAction/TweakMenu/TweakMetadataCallback.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 4 | 2017-12-18T20:10:16.000Z | 2021-02-07T21:21:24.000Z | SDKs/CryCode/3.6.15/CryEngine/CryAction/TweakMenu/TweakMetadataCallback.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | null | null | null | SDKs/CryCode/3.6.15/CryEngine/CryAction/TweakMenu/TweakMetadataCallback.cpp | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 3 | 2019-03-11T21:36:15.000Z | 2021-02-07T21:21:26.000Z | /*************************************************************************
Crytek Source File.
Copyright (C), Crytek Studios, 2011.
-------------------------------------------------------------------------
Description:
Header for tweak item that calls a user-supplied function
*************************************************************************/
#include "StdAfx.h"
#include "TweakMetadataCallback.h"
CTweakMetadataCallback::CTweakMetadataCallback(CTweakMenuController* pMenuController, const string& command)
: CTweakMetadata(pMenuController, command)
{
m_type = eTT_Callback;
m_pFunction = NULL;
m_pUserData = NULL;
}
bool CTweakMetadataCallback::ChangeValue(bool bIncrement)
{
if(m_pFunction)
(m_pFunction)(m_pUserData);
return true;
}
| 26.241379 | 108 | 0.554534 | amrhead |
161165f52353d152ea0877dccf35228cd35ef63e | 5,330 | cc | C++ | IntegrationWithMacSim/src/noc.cc | uwuser/MCsim | df0033e73aa7669fd89bc669ff25a659dbb253f6 | [
"MIT"
] | 1 | 2021-11-25T20:09:08.000Z | 2021-11-25T20:09:08.000Z | IntegrationWithMacSim/src/noc.cc | uwuser/MCsim | df0033e73aa7669fd89bc669ff25a659dbb253f6 | [
"MIT"
] | 1 | 2021-11-03T21:15:53.000Z | 2021-11-04T15:53:20.000Z | IntegrationWithMacSim/src/noc.cc | uwuser/MCsim | df0033e73aa7669fd89bc669ff25a659dbb253f6 | [
"MIT"
] | 1 | 2020-11-25T14:09:30.000Z | 2020-11-25T14:09:30.000Z | /*
Copyright (c) <2012>, <Georgia Institute of Technology> All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted
provided that the following conditions are met:
Redistributions of source code must retain the above copyright notice, this list of conditions
and the following disclaimer.
Redistributions in binary form must reproduce the above copyright notice, this list of
conditions and the following disclaimer in the documentation and/or other materials provided
with the distribution.
Neither the name of the <Georgia Institue of Technology> 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.
*/
/**********************************************************************************************
* File : noc.h
* Author : Jaekyu Lee
* Date : 3/4/2011
* SVN : $Id: dram.h 867 2009-11-05 02:28:12Z kacear $:
* Description : Interface to interconnection network
*********************************************************************************************/
#include "debug_macros.h"
#include "memory.h"
#include "noc.h"
#include "all_knobs.h"
#define DEBUG(args...) _DEBUG(*m_simBase->m_knobs->KNOB_DEBUG_MEM, ## args)
// noc_c constructor
noc_c::noc_c(macsim_c* simBase)
{
m_simBase = simBase;
m_pool = new pool_c<noc_entry_s>(1000, "nocpool");
m_cpu_entry_up = new list<noc_entry_s*>;
m_cpu_entry_down = new list<noc_entry_s*>;
if (*m_simBase->m_knobs->KNOB_HETERO_NOC_USE_SAME_QUEUE) {
m_gpu_entry_up = m_cpu_entry_up;
m_gpu_entry_down = m_cpu_entry_down;
}
else {
m_gpu_entry_up = new list<noc_entry_s*>;
m_gpu_entry_down = new list<noc_entry_s*>;
}
}
// noc_c destructor
noc_c::~noc_c()
{
}
// insert a new request to NoC
bool noc_c::insert(int src, int dst, int msg, mem_req_s* req)
{
noc_entry_s* new_entry = m_pool->acquire_entry();
if (src > dst) {
if (req->m_ptx == true)
m_cpu_entry_up->push_back(new_entry);
else
m_gpu_entry_up->push_back(new_entry);
}
else {
if (req->m_ptx == true)
m_cpu_entry_down->push_back(new_entry);
else
m_gpu_entry_down->push_back(new_entry);
}
new_entry->m_src = src;
new_entry->m_dst = dst;
new_entry->m_msg = msg;
new_entry->m_req = req;
new_entry->m_rdy = CYCLE + 10;
return true;
}
// tick a cycle
void noc_c::run_a_cycle()
{
list<noc_entry_s*> done_list;
memory_c* memory = m_simBase->m_memory;
for (auto itr = m_cpu_entry_up->begin(); itr != m_cpu_entry_up->end(); ++itr) {
if ((*itr)->m_rdy <= CYCLE) {
done_list.push_back((*itr));
}
else
break;
}
for (auto itr = done_list.begin(); itr != done_list.end(); ++itr) {
if (memory->receive((*itr)->m_src, (*itr)->m_dst, (*itr)->m_msg, (*itr)->m_req)) {
m_cpu_entry_up->remove((*itr));
m_pool->release_entry((*itr));
}
}
done_list.clear();
if (!*m_simBase->m_knobs->KNOB_HETERO_NOC_USE_SAME_QUEUE) {
for (auto itr = m_gpu_entry_up->begin(); itr != m_gpu_entry_up->end(); ++itr) {
if ((*itr)->m_rdy <= CYCLE) {
done_list.push_back((*itr));
}
else
break;
}
for (auto itr = done_list.begin(); itr != done_list.end(); ++itr) {
if (memory->receive((*itr)->m_src, (*itr)->m_dst, (*itr)->m_msg, (*itr)->m_req)) {
m_gpu_entry_up->remove((*itr));
m_pool->release_entry((*itr));
}
}
done_list.clear();
}
for (auto itr = m_cpu_entry_down->begin(); itr != m_cpu_entry_down->end(); ++itr) {
if ((*itr)->m_rdy <= CYCLE) {
done_list.push_back((*itr));
}
else
break;
}
for (auto itr = done_list.begin(); itr != done_list.end(); ++itr) {
if (memory->receive((*itr)->m_src, (*itr)->m_dst, (*itr)->m_msg, (*itr)->m_req)) {
m_cpu_entry_down->remove((*itr));
m_pool->release_entry((*itr));
}
}
done_list.clear();
if (!*m_simBase->m_knobs->KNOB_HETERO_NOC_USE_SAME_QUEUE) {
for (auto itr = m_gpu_entry_down->begin(); itr != m_gpu_entry_down->end(); ++itr) {
if ((*itr)->m_rdy <= CYCLE) {
done_list.push_back((*itr));
}
else
break;
}
for (auto itr = done_list.begin(); itr != done_list.end(); ++itr) {
if (memory->receive((*itr)->m_src, (*itr)->m_dst, (*itr)->m_msg, (*itr)->m_req)) {
m_gpu_entry_down->remove((*itr));
m_pool->release_entry((*itr));
}
}
done_list.clear();
}
}
| 29.447514 | 95 | 0.63546 | uwuser |
16119af1d41acfc6f2b844d8848278e5436a4773 | 2,797 | hpp | C++ | lib/RdfQueryDB.hpp | ericprud/SWObjects | c2ceae74a9e20649dac84f1da1a4b0d2bd9ddce6 | [
"MIT"
] | 8 | 2015-06-29T17:17:37.000Z | 2021-05-21T12:05:40.000Z | lib/RdfQueryDB.hpp | ericprud/SWObjects | c2ceae74a9e20649dac84f1da1a4b0d2bd9ddce6 | [
"MIT"
] | 2 | 2016-01-17T20:12:24.000Z | 2016-12-20T20:32:52.000Z | lib/RdfQueryDB.hpp | ericprud/SWObjects | c2ceae74a9e20649dac84f1da1a4b0d2bd9ddce6 | [
"MIT"
] | 2 | 2015-04-08T19:12:02.000Z | 2020-01-28T08:52:16.000Z | /* RdfQueryDB - sets of variable bindings and their proofs.
* $Id: RdfQueryDB.hpp,v 1.4 2008-10-24 10:57:31 eric Exp $
*/
#ifndef RDF_QUERY_DB_H
#define RDF_QUERY_DB_H
#include "RdfDB.hpp"
namespace w3c_sw {
class DBExpressor;
class RdfQueryDB : public RdfDB {
friend class DBExpressor;
Operation* op;
const TableOperation* top;
public:
RdfQueryDB (const TableOperation* p_op, AtomFactory* atomFactory);
};
class DBExpressor : public RecursiveExpressor {
protected:
RdfQueryDB* db;
AtomFactory* atomFactory;
bool optState;
public:
DBExpressor (RdfQueryDB* p_db, AtomFactory* atomFactory) : db(p_db), atomFactory(atomFactory), optState(false) { }
virtual void base (const Base* const, std::string productionName) { throw(std::runtime_error(productionName)); };
virtual void filter (const Filter* const, const TableOperation* p_op, const ProductionVector<const Expression*>* p_Constraints) {
p_op->express(this);
p_Constraints->express(this);
}
void _absorbGraphPattern (BasicGraphPattern* g, const ProductionVector<const TriplePattern*>* p_TriplePatterns) {
for (std::vector<const TriplePattern*>::const_iterator it = p_TriplePatterns->begin();
it != p_TriplePatterns->end(); it++)
g->addTriplePattern(atomFactory->getTriple(*it, optState));
}
virtual void namedGraphPattern (const NamedGraphPattern* const, const TTerm* p_IRIref, bool /*p_allOpts*/, const ProductionVector<const TriplePattern*>* p_TriplePatterns) {
_absorbGraphPattern(db->ensureGraph(p_IRIref), p_TriplePatterns);
}
virtual void defaultGraphPattern (const DefaultGraphPattern* const, bool /*p_allOpts*/, const ProductionVector<const TriplePattern*>* p_TriplePatterns) {
_absorbGraphPattern(db->ensureGraph(DefaultGraph), p_TriplePatterns);
}
virtual void tableDisjunction (TableDisjunction*, const ProductionVector<const TableOperation*>*, const ProductionVector<const Filter*>*) { // p_TableOperations p_Filters
throw(std::runtime_error(FUNCTION_STRING)); // query should already be DNF'd, ergo no disjunctions.
}
virtual void tableConjunction (const TableConjunction* const, const ProductionVector<const TableOperation*>* p_TableOperations) {
p_TableOperations->express(this);
}
virtual void optionalGraphPattern (const OptionalGraphPattern* const, const TableOperation* p_GroupGraphPattern, const ProductionVector<const Expression*>* p_Expressions) {
bool oldOptState = optState;
optState = true;
p_GroupGraphPattern->express(this);
p_Expressions->express(this);
optState = oldOptState;
}
virtual void minusGraphPattern (const MinusGraphPattern* const, const TableOperation* p_GroupGraphPattern) {
p_GroupGraphPattern->express(this);
}
};
} // namespace w3c_sw
#endif // !RDF_QUERY_DB_H
| 41.746269 | 173 | 0.757955 | ericprud |
1618b550128137b262fa34e786a344b04e1d2a2c | 4,842 | cc | C++ | simulation/src/EventAction.cc | ThorbenQuast/HGCal_TB_Geant4 | 5da74358e5c4495e14a7de1b92d60ee5015decb3 | [
"MIT"
] | 1 | 2021-02-18T05:40:51.000Z | 2021-02-18T05:40:51.000Z | simulation/src/EventAction.cc | innonano/HGCal_TB_Geant4 | 9accdd0587b51f8bf34bd2e087c70c3e028c256e | [
"MIT"
] | null | null | null | simulation/src/EventAction.cc | innonano/HGCal_TB_Geant4 | 9accdd0587b51f8bf34bd2e087c70c3e028c256e | [
"MIT"
] | 3 | 2018-11-05T20:12:04.000Z | 2021-02-18T05:40:31.000Z |
#include "EventAction.hh"
#include "RunAction.hh"
#include "G4Event.hh"
#include "G4SDManager.hh"
#include "G4RunManager.hh"
#include "SiliconPixelHit.hh"
#include "SiPMHit.hh"
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
EventAction::EventAction()
: G4UserEventAction()
{
hitTimeCut = -1;
toaThreshold = 0;
firstHadInteractionDepth = -999 * CLHEP::m;
firstHadInteractionTime = 1000 * CLHEP::s;
DefineCommands();
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
EventAction::~EventAction()
{}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void EventAction::BeginOfEventAction(const G4Event* EventAction)
{
hits_ID.clear();
hits_x.clear();
hits_y.clear();
hits_z.clear();
hits_Edep.clear();
hits_EdepNonIonising.clear();
hits_TOA.clear();
hits_TOA_last.clear();
hits_type.clear();
firstHadInteractionDepth = -999 * CLHEP::m;
firstHadInteractionTime = 1000 * CLHEP::s;
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
void EventAction::EndOfEventAction(const G4Event* event)
{
auto analysisManager = G4AnalysisManager::Instance();
std::cout << "Simulated event " << event->GetEventID() << std::endl;
analysisManager->FillNtupleIColumn(0, event->GetEventID());
analysisManager->FillNtupleDColumn(1, event->GetPrimaryVertex()->GetX0() / CLHEP::cm);
analysisManager->FillNtupleDColumn(2, event->GetPrimaryVertex()->GetY0() / CLHEP::cm);
analysisManager->FillNtupleDColumn(3, event->GetPrimaryVertex()->GetZ0() / CLHEP::cm);
auto hce = event->GetHCofThisEvent();
auto sdManager = G4SDManager::GetSDMpointer();
G4int collId;
//HGCAL EE + FH
collId = sdManager->GetCollectionID("SiliconPixelHitCollection");
auto hc = hce->GetHC(collId);
if ( ! hc ) return;
double esum_HGCAL = 0; double cogz_HGCAL = 0; int Nhits_HGCAL = 0;
for (unsigned int i = 0; i < hc->GetSize(); ++i) {
auto hit = static_cast<SiliconPixelHit*>(hc->GetHit(i));
hit->Digitise(hitTimeCut / CLHEP::ns, toaThreshold / CLHEP::keV );
if (hit->isValidHit()) {
hits_ID.push_back(hit->ID());
hits_x.push_back(hit->GetX());
hits_y.push_back(hit->GetY());
hits_z.push_back(hit->GetZ());
hits_Edep.push_back(hit->GetEdep());
hits_EdepNonIonising.push_back(hit->GetEdepNonIonizing());
hits_TOA.push_back(hit->GetTOA());
hits_TOA_last.push_back(hit->GetLastTOA());
hits_type.push_back(0);
Nhits_HGCAL++;
esum_HGCAL += hit->GetEdep() * CLHEP::keV / CLHEP::MeV;
cogz_HGCAL += hit->GetZ() * hit->GetEdep();
}
}
if (esum_HGCAL > 0) cogz_HGCAL /= esum_HGCAL;
analysisManager->FillNtupleDColumn(13, esum_HGCAL);
analysisManager->FillNtupleDColumn(14, cogz_HGCAL);
analysisManager->FillNtupleIColumn(15, Nhits_HGCAL);
//AHCAL
collId = sdManager->GetCollectionID("SiPMHitCollection");
hc = hce->GetHC(collId);
if ( ! hc ) return;
double esum_AHCAL = 0; double cogz_AHCAL = 0; int Nhits_AHCAL = 0;
for (unsigned int i = 0; i < hc->GetSize(); ++i) {
auto hit = static_cast<SiPMHit*>(hc->GetHit(i));
hit->Digitise(-1, 0 );
if (hit->isValidHit()) {
hits_ID.push_back(hit->ID());
hits_x.push_back(hit->GetX());
hits_y.push_back(hit->GetY());
hits_z.push_back(hit->GetZ());
hits_Edep.push_back(hit->GetEdep());
hits_EdepNonIonising.push_back(hit->GetEdepNonIonizing());
hits_TOA.push_back(hit->GetTOA());
hits_type.push_back(1);
Nhits_AHCAL++;
esum_AHCAL += hit->GetEdep() * CLHEP::keV / CLHEP::MeV;
cogz_AHCAL += hit->GetZ() * hit->GetEdep();
}
}
if (esum_AHCAL > 0) cogz_AHCAL /= esum_AHCAL;
analysisManager->FillNtupleDColumn(16, esum_AHCAL);
analysisManager->FillNtupleDColumn(17, cogz_AHCAL);
analysisManager->FillNtupleIColumn(18, Nhits_AHCAL);
//add the first hadronic interaction depth
analysisManager->FillNtupleIColumn(19, firstHadInteractionDepth / CLHEP::cm);
analysisManager->AddNtupleRow();
}
void EventAction::DefineCommands() {
fMessenger
= new G4GenericMessenger(this,
"/Simulation/hits/",
"Primary generator control");
// time cut command
auto& timeCutCmd
= fMessenger->DeclarePropertyWithUnit("timeCut", "ns", hitTimeCut,
"Size of time window for hit digitalisation");
timeCutCmd.SetParameterName("timeCut", true);
timeCutCmd.SetRange("timeCut>=-1");
timeCutCmd.SetDefaultValue("-1");
// toa threshold command
auto& toaThresholdCmd
= fMessenger->DeclarePropertyWithUnit("toaThreshold", "keV", toaThreshold,
"Threshold for TOA activation");
toaThresholdCmd.SetParameterName("toaThreshold", true);
toaThresholdCmd.SetRange("toaThreshold>=0");
toaThresholdCmd.SetDefaultValue("0");
}
//....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
| 30.074534 | 87 | 0.686493 | ThorbenQuast |
161918df61a566882b454429ffa1fdb6d358aa49 | 110,081 | hh | C++ | pes.timed/proof.hh | jkeiren/TimeSolver | 246d54d43a529c05eccdef4567700eef3b3b1a57 | [
"MIT"
] | 4 | 2018-12-19T14:30:27.000Z | 2022-03-20T20:19:20.000Z | pes.timed/proof.hh | jkeiren/TimeSolver | 246d54d43a529c05eccdef4567700eef3b3b1a57 | [
"MIT"
] | null | null | null | pes.timed/proof.hh | jkeiren/TimeSolver | 246d54d43a529c05eccdef4567700eef3b3b1a57 | [
"MIT"
] | 2 | 2019-04-24T03:18:20.000Z | 2019-09-13T07:49:00.000Z | /** \file proof.hh
* Proof-search implementation for timed-automata model checking, based on PESs.
* @author Peter Fontana
* @author Dezhuang Zhang
* @author Rance Cleaveland
* @author Jeroen Keiren
* @copyright MIT Licence, see the accompanying LICENCE.txt
*/
#ifndef PROOF_HH
#define PROOF_HH
#include "cpplogging/logger.h"
#include "prover_options.hh"
#include "pes.hh"
#include "DBM.hh"
#include "ExprNode.hh"
#include "transition.hh"
#include "comp_ph.hh"
#include "sequent_cache.hh"
class prover {
protected:
const pes& input_pes;
const prover_options& options;
/** The current step in the proof; initially 0 */
size_t step;
size_t numLocations;
/** This DBM is a copy of a DBM initially
* that represents the unconstrained DBM in
* canonical form. */
DBM INFTYDBM;
/** Global variable that keeps track of the parent sequent
* of the current sequent in the proof tree. Used for sequents
* without placeholder parents, and used to help generate backpointers
* in the proof tree. */
Sequent* parentRef;
/** Global variable that keeps track of the parent placeholder sequent
* of the current sequent in the proof tree. Used for sequents
* with placeholder parents, and used to help generate backpointers
* in the proof tree. */
SequentPlace* parentPlaceRef;
/** Cache for storing sequents. This incorporates true and false sequents, as
* well as sequents for predicate variables in order to detect cycles.
*/
sequent_cache cache;
public:
prover(const pes& input_pes, const prover_options& options)
: input_pes(input_pes),
options(options),
step(0),
numLocations(1),
INFTYDBM(input_pes.clocks()),
parentRef(nullptr),
parentPlaceRef(nullptr),
cache(input_pes, options.nHash) {
/* This is initialized to be the largest (loosest)
* possible DBM
* @see DBM Constructor (Default Constructor). */
INFTYDBM.cf();
}
~prover() {}
size_t getNumLocations() const { return numLocations; }
/** Prove a given property for the provided PES.
* @param p the PES to prove.
* @param placeholder the placeholder to use (default nullptr).
* if the nullptr is provided as placholder, internally do_proof (without placeholders)
* is used. If a non-empty placeholder is provided, that placeholder is used in the
* proof using do_proof_place. In this case, the method returns true iff the initial clock zone
* is included in the resulting placeholder. */
bool do_proof_init(pes& p, DBMList* placeholder = nullptr)
{
const ExprNode* start_pred = p.lookup_predicate(p.start_predicate());
if (placeholder == nullptr)
{
return do_proof(p.initial_state(), *p.initial_clock_zone(), *start_pred);
} else {
do_proof_place(p.initial_state(), *p.initial_clock_zone(), placeholder, *start_pred);
return *placeholder >= *p.initial_clock_zone();
}
}
void printTabledSequents(std::ostream& os) const {
cache.printTabledSequents(os);
}
protected:
/** The prover function to prove whether a sequent is true or false.
* @param step The "tree level" of the sequent in the proof tree.
* A lower number is closer to the root, and a higher level is close
* to "leaf" sequents. The main() method
* that calls this feeds in 0.
* @param zone (*) The initial DBM of clock constraints (Sequent Premise)
* @param formula (*) The Expression/Consequent (root of the Expression Tree)
* that the prover
* needs to determine if it is true or false.
* @param discrete_state (*) The current substitution list of variables and their
* substituted values, used to represent the current
* atomic "state" of the Sequent.
* @return True if the expression evaluates to True given the other parameters
* and False otherwise (if the expression evaluates to False).*/
__attribute__((flatten))
bool do_proof(const SubstList& discrete_state,
const DBM& zone,
const ExprNode& formula) {
assert(zone.isInCf());
bool result = false;
if (cpplogEnabled(cpplogging::debug)) {
print_sequent(std::cerr, step, result, zone, formula, discrete_state,
formula.getOpType());
}
++step;
switch (formula.getOpType()) {
case PREDICATE: {
result = do_proof_predicate(discrete_state, zone, formula);
break;
}
case AND: {
result = do_proof_and(discrete_state, zone, formula);
break;
}
case OR: {
result = do_proof_or(discrete_state, zone, formula);
break;
}
case OR_SIMPLE: {
result = do_proof_or_simple(discrete_state, zone, formula);
break;
}
case FORALL: {
result = do_proof_forall(discrete_state, zone, formula);
break;
}
case FORALL_REL: {
result = do_proof_forall_rel(discrete_state, zone, formula);
break;
}
case EXISTS: {
result = do_proof_exists(discrete_state, zone, formula);
break;
}
case EXISTS_REL: {
result = do_proof_exists_rel(discrete_state, zone, formula);
break;
}
case ALLACT: {
result = do_proof_allact(discrete_state, zone, formula);
break;
}
case EXISTACT: {
result = do_proof_existact(discrete_state, zone, formula);
break;
}
case IMPLY: {
result = do_proof_imply(discrete_state, zone, formula);
break;
}
case CONSTRAINT: {
result = do_proof_constraint(zone, formula);
break;
}
case BOOL: {
result = do_proof_place_bool(nullptr, formula);
break;
}
case ATOMIC: {
result = do_proof_place_atomic(discrete_state, nullptr, formula);
break;
}
case ATOMIC_NOT: {
result = do_proof_place_atomic_not(discrete_state, nullptr, formula);
break;
}
case ATOMIC_LT: {
result = do_proof_place_atomic_lt(discrete_state, nullptr, formula);
break;
}
case ATOMIC_GT: {
result = do_proof_place_atomic_gt(discrete_state, nullptr, formula);
break;
}
case ATOMIC_LE: {
result = do_proof_place_atomic_le(discrete_state, nullptr, formula);
break;
}
case ATOMIC_GE: {
result = do_proof_place_atomic_ge(discrete_state, nullptr, formula);
break;
}
case SUBLIST: {
result = do_proof_sublist(discrete_state, zone, formula);
break;
}
case RESET: {
result = do_proof_reset(discrete_state, zone, formula);
break;
}
case ASSIGN: {
result = do_proof_assign(discrete_state, zone, formula);
break;
}
case REPLACE: {
result = do_proof_replace(discrete_state, zone, formula);
break;
}
case ABLEWAITINF: {
result = do_proof_place_ablewaitinf(discrete_state, zone, nullptr);
break;
}
case UNABLEWAITINF: {
result = do_proof_place_unablewaitinf(discrete_state, zone, nullptr);
break;
}
}
--step;
return result;
}
/** The prover function that handles placeholders.
* @param step The "tree level" of the sequent in the proof tree.
* A lower number is closer to the root, and a higher level is close
* to "leaf" sequents. The main() method
* that calls this feeds in 0.
* @param zone (*) The initial DBM of clock constraints (Sequent Premise)
* @param place (*) The current zone union of the Placeholder DBM.
* @param formula (*) The Expression/Consequent (root of the Expression Tree)
* that the prover
* needs to determine if it is true or false.
* @param discrete_state (*) The current substitution list of variables and their
* substituted values, used to represent the current
* atomic "state" of the Sequent.
* @return The DBM Value of the placeholder constraint or an empty DBM if
* no valid value for the placeholder exists (thus proof is Invalid).
* The sequent is valid for the clock valuations in the intersection of zone
* and the return value. */
__attribute__((flatten)) void do_proof_place(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula) {
/* do_proof_place() written by Peter Fontana, needed for support
* of EXISTS Quantifiers. */
assert(zone.isInCf());
assert(place->isInCf());
if (cpplogEnabled(cpplogging::debug)) {
print_sequent_place(std::cerr, step, false, zone, *place, formula,
discrete_state, formula.getOpType());
}
++step;
switch (formula.getOpType()) {
case PREDICATE: {
do_proof_place_predicate(discrete_state, zone, place, formula);
break;
}
case AND: {
do_proof_place_and(discrete_state, zone, place, formula);
break;
}
case OR: {
do_proof_place_or(discrete_state, zone, place, formula);
break;
}
case OR_SIMPLE: {
do_proof_place_or_simple(discrete_state, zone, place, formula);
break;
}
case FORALL: {
do_proof_place_forall(discrete_state, zone, place, formula);
break;
}
case FORALL_REL: {
do_proof_place_forall_rel(discrete_state, zone, place, formula);
break;
}
case EXISTS: {
do_proof_place_exists(discrete_state, zone, place, formula);
break;
}
case EXISTS_REL: {
do_proof_place_exists_rel(discrete_state, zone, place, formula);
break;
}
case ALLACT: {
do_proof_place_allact(discrete_state, zone, place, formula);
break;
}
case EXISTACT: {
do_proof_place_existact(discrete_state, zone, place, formula);
break;
}
case IMPLY: {
do_proof_place_imply(discrete_state, zone, place, formula);
break;
}
case CONSTRAINT: {
do_proof_place_constraint(zone, place, formula);
break;
}
case BOOL: {
do_proof_place_bool(place, formula);
break;
}
case ATOMIC: {
do_proof_place_atomic(discrete_state, place, formula);
break;
}
case ATOMIC_NOT: {
do_proof_place_atomic_not(discrete_state, place, formula);
break;
}
case ATOMIC_LT: {
do_proof_place_atomic_lt(discrete_state, place, formula);
break;
}
case ATOMIC_GT: {
do_proof_place_atomic_gt(discrete_state, place, formula);
break;
}
case ATOMIC_LE: {
do_proof_place_atomic_le(discrete_state, place, formula);
break;
}
case ATOMIC_GE: {
do_proof_place_atomic_ge(discrete_state, place, formula);
break;
}
case SUBLIST: {
do_proof_place_sublist(discrete_state, zone, place, formula);
break;
}
case RESET: {
do_proof_place_reset(discrete_state, zone, place, formula);
break;
}
case ASSIGN: {
do_proof_place_assign(discrete_state, zone, place, formula);
break;
}
case REPLACE: {
do_proof_place_replace(discrete_state, zone, place, formula);
break;
}
case ABLEWAITINF: {
do_proof_place_ablewaitinf(discrete_state, zone, place);
break;
}
case UNABLEWAITINF: {
do_proof_place_unablewaitinf(discrete_state, zone, place);
break;
}
}
--step;
}
bool do_proof_predicate(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_and(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_or(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_or_simple(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_forall(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_forall_rel(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_exists(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_exists_rel(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_allact(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_existact(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_imply(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_constraint(const DBM& zone, const ExprNode& formula) const;
bool do_proof_sublist(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_reset(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_assign(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
bool do_proof_replace(const SubstList& discrete_state, const DBM& zone,
const ExprNode& formula);
void do_proof_place_predicate(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_and(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_or(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_or_simple(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_forall(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_forall_rel(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_exists(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_exists_rel(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_allact(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_existact(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_imply(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_constraint(const DBM& zone, DBMList* place,
const ExprNode& formula) const;
bool do_proof_place_bool(DBMList* place, const ExprNode& formula) const;
bool do_proof_place_atomic(const SubstList& discrete_state,
DBMList* place, const ExprNode& formula) const;
bool do_proof_place_atomic_not(const SubstList& discrete_state,
DBMList* place, const ExprNode& formula) const;
bool do_proof_place_atomic_lt(const SubstList& discrete_state,
DBMList* place, const ExprNode& formula) const;
bool do_proof_place_atomic_gt(const SubstList& discrete_state,
DBMList* place, const ExprNode& formula) const;
bool do_proof_place_atomic_le(const SubstList& discrete_state,
DBMList* place, const ExprNode& formula) const;
bool do_proof_place_atomic_ge(const SubstList& discrete_state,
DBMList* place, const ExprNode& formula) const;
void do_proof_place_sublist(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_reset(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_assign(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
void do_proof_place_replace(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula);
bool do_proof_place_ablewaitinf(const SubstList& discrete_state,
const DBM& zone, DBMList* place) const;
bool do_proof_place_unablewaitinf(const SubstList& discrete_state,
const DBM& zone, DBMList* place) const;
inline void establish_exists_rel_sidecondition(
DBMList* result,
const DBM& zone,
const DBMList& placeholder1,
const DBMList& placeholder2) const {
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << "Computing side condition for relativized exists with zone " << zone << std::endl
<< " placeholder1: " << placeholder1 << std::endl
<< " placeholder2: " << placeholder2 << std::endl;
DBM succ_zone(zone);
succ_zone.suc();
succ_zone.cf();
// First check if placeholder2 works without restricting.
DBMList pred_placeholder2_strict(placeholder2);
pred_placeholder2_strict.pre();
pred_placeholder2_strict.predClosureRev();
pred_placeholder2_strict.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " pre_<(placeholder2) = " << pred_placeholder2_strict << std::endl;
// left hand side of containment check
DBMList succ_zone_and_pred_placeholder2_strict(succ_zone);
succ_zone_and_pred_placeholder2_strict.intersect(pred_placeholder2_strict);
succ_zone_and_pred_placeholder2_strict.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " succ((l,cc)) && pre_<(placeholder2) = " << succ_zone_and_pred_placeholder2_strict << std::endl;
// right hand side of containment check
DBMList succ_zone_and_placeholder1(succ_zone);
succ_zone_and_placeholder1.intersect(placeholder1);
succ_zone_and_placeholder1.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " succ((l,cc)) && placeholder1 = " << succ_zone_and_placeholder1 << std::endl;
if(succ_zone_and_pred_placeholder2_strict <= succ_zone_and_placeholder1) {
*result = placeholder2;
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " placeholder2 works!" << std::endl;
} else {
result->makeEmpty();
DBMList placeholder1_complement(placeholder1);
!placeholder1_complement;
placeholder1_complement.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " !placeholder1 = " << placeholder1_complement << std::endl;
// Process on a per-DBM basis
for (const DBM& placeholder2_zone: placeholder2)
{
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " placeholder2-part = " << placeholder2_zone << std::endl;
DBM pred_placeholder2_zone_strict(placeholder2_zone);
pred_placeholder2_zone_strict.pre();
pred_placeholder2_zone_strict.predClosureRev();
pred_placeholder2_zone_strict.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " pre_<(placeholder2-part) = " << pred_placeholder2_zone_strict << std::endl;
// left hand side of containment check
DBMList succ_zone_and_pred_placeholder2_zone_strict(succ_zone);
succ_zone_and_pred_placeholder2_zone_strict.intersect(pred_placeholder2_zone_strict);
succ_zone_and_pred_placeholder2_zone_strict.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " succ((l,cc)) && pre_<(placeholder2-part) = " << succ_zone_and_pred_placeholder2_zone_strict << std::endl;
DBMList bad(succ_zone_and_pred_placeholder2_zone_strict);
bad.intersect(placeholder1_complement);
bad.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " bad = " << bad << std::endl;
DBMList bad_successors_strict(bad);
bad_successors_strict.suc();
bad_successors_strict.closureRev();
bad_successors_strict.cf();
DBMList bad_successors_strict_complement(bad_successors_strict);
!bad_successors_strict_complement;
bad_successors_strict_complement.cf();
DBMList placeholder(placeholder2_zone);
placeholder.intersect(bad_successors_strict_complement);
placeholder.cf();
cpplog(cpplogging::debug1, "exists_rel_sidecondition") << " adding placeholder " << placeholder << std::endl;
result->addDBMList(placeholder);
}
}
}
inline void establish_forall_place_sidecondition(DBMList* result,
const SubstList& discrete_state,
const DBM& zone,
const DBMList& placeholder2) const
{
assert(placeholder2.isInCf());
// First, we establish whether placeholder2 is a good candidate for the result.
// i.e. assume placeholder = !inv(l) || placeholder2
DBM succ_zone(zone);
succ_zone.suc();
succ_zone.cf();
// establish placeholder = !inv(l) || placeholder2
// this ensures satisfaction of first sidecondition.
DBMList placeholder(std::move(placeholder2));
DBMList invariant_region(INFTYDBM);
bool nonempty_invariant = restrict_to_invariant(
input_pes.invariants(), invariant_region, discrete_state);
if (nonempty_invariant) {
invariant_region.cf();
!invariant_region;
invariant_region.cf();
placeholder.addDBMList(invariant_region);
placeholder.cf();
}
// Guess placeholder_forall == placeholder is enough to satisfy second sidecondition.
DBMList placeholder_forall(placeholder);
// succ((l,cc)) && placeholder
DBMList succ_zone_and_placeholder(placeholder);
succ_zone_and_placeholder.intersect(succ_zone);
succ_zone_and_placeholder.cf();
// succ((l,cc) && placeholder_forall)
DBMList succ_zone_restricted_to_placeholder_forall(zone);
succ_zone_restricted_to_placeholder_forall.intersect(placeholder_forall);
succ_zone_restricted_to_placeholder_forall.cf();
succ_zone_restricted_to_placeholder_forall.suc();
succ_zone_restricted_to_placeholder_forall.cf();
if(succ_zone_restricted_to_placeholder_forall <= succ_zone_and_placeholder) {
// success
*result = placeholder_forall;
} else {
// restrict placeholder_forall.
// oberve that forall(placeholder) = !exists(!placeholderl).
// compute the subset of !placeholder that can be reached from (l,cc) && placeholder_forall
DBMList not_placeholder(placeholder);
!not_placeholder;
not_placeholder.intersect(succ_zone_restricted_to_placeholder_forall);
not_placeholder.cf();
// Note for exists(!placeholder), we determine all predecessors that
// lead to this set.
not_placeholder.pre();
not_placeholder.cf();
// we now have an approximation of exists(!placeholder_forall)
!not_placeholder;
// and this leads to an approximation of !exists(!placeholder_forall);
// We do ensure all these states are reachable from (l,cc).
not_placeholder.intersect(succ_zone);
not_placeholder.cf();
// Restrict placeholder!
placeholder_forall.intersect(not_placeholder);
placeholder_forall.cf();
// Check that this is indeed correct.
// succ((l,cc) && placeholder_forall)
succ_zone_restricted_to_placeholder_forall = zone;
succ_zone_restricted_to_placeholder_forall.intersect(placeholder_forall);
succ_zone_restricted_to_placeholder_forall.cf();
succ_zone_restricted_to_placeholder_forall.suc();
succ_zone_restricted_to_placeholder_forall.cf();
if(succ_zone_restricted_to_placeholder_forall.emptiness() || succ_zone_restricted_to_placeholder_forall <= succ_zone_and_placeholder) {
*result = placeholder_forall;
} else {
cpplog(cpplogging::debug1, "forall_place_sidecondition")
<< "placeholder_forall: " << placeholder_forall << std::endl
<< "succ((l,cc) && placeholder_forall): " << succ_zone_restricted_to_placeholder_forall << std::endl
<< "succ((l,cc)) && old placeholder_forall: " << succ_zone_and_placeholder << std::endl;
assert(succ_zone_restricted_to_placeholder_forall <= succ_zone_and_placeholder);
// The old implementation simply returns the empty placeholder here.
// JK is wondering whether this is really reachable.
result->makeEmpty();
}
}
}
};
/* IMPLEMENTATION PROOF WITHOUT PLACEHOLDERS */
inline bool prover::do_proof_predicate(const SubstList& discrete_state,
const DBM& zone,
const ExprNode& formula) {
bool retVal = false;
/* Look in Known True and Known False Sequent Caches */
if (options.useCaching) {
cpplog(cpplogging::debug1) << "Looking for sequent in known-false and known-true cache" << std::endl;
if (cache.is_known_false_sequent(discrete_state, zone, formula, parentRef)) {
cpplog(cpplogging::debug)
<< "---(Invalid) Located a Known False Sequent ----" << std::endl
<< std::endl;
return false;
} else if (cache.is_known_true_sequent(discrete_state, zone, formula, parentRef)) {
cpplog(cpplogging::debug)
<< "---(Valid) Located a Known True Sequent ----" << std::endl
<< std::endl;
return true;
}
cpplog(cpplogging::debug1) << "... not found in caches" << std::endl;
}
/* Now deal with greatest fixpoint circularity and least
* fixpoint circularity */
Sequent* cached_fp_sequent = nullptr;
{ // Restricted scope for detecting circularities
if (formula.is_gfp()) { // Thus a Greatest Fixpoint
std::pair<Sequent*, bool> gfp_cycle = cache.completes_gfp_cycle(discrete_state, zone, formula, parentRef);
if (gfp_cycle.second) {
cpplog(cpplogging::debug)
<< "---(Valid) Located a True Sequent or gfp Circularity ----"
<< std::endl
<< std::endl;
// Add sequent to known true cache
if (options.useCaching) {
cache.cache_true_sequent(discrete_state, zone, formula);
}
return true;
} else {
cached_fp_sequent = gfp_cycle.first;
}
} else { // Thus, a least fixpoint
std::pair<Sequent*, bool> lfp_cycle = cache.completes_lfp_cycle(discrete_state, zone, formula, parentRef);
if (lfp_cycle.second) {
cpplog(cpplogging::debug)
<< "---(Invalid) Located a lfp Circularity ----" << std::endl
<< std::endl;
// Now Put Sequent in False Cache
if (options.useCaching) {
cache.cache_false_sequent(discrete_state, zone, formula);
}
return false; // least fixed point circularity found
} else {
cached_fp_sequent = lfp_cycle.first;
}
}
} // End scope for circularity
assert(cached_fp_sequent != nullptr);
// no least/greatest fixed point circularity was found;
// add current zone to the cache.
cached_fp_sequent->push_sequent(new DBM(zone));
// Note: cached_fp_sequent is used as parent in the recursive call; essentially, we mimick a call stack here,
// but perform caller-saving of parentRef.
Sequent* parentRef_saved = parentRef;
parentRef = cached_fp_sequent; // parentRef to use for recursive call
// Recursively solve the right and side of the equation
const ExprNode* rhs = input_pes.lookup_equation(formula.getPredicate());
retVal = do_proof(discrete_state, zone, *rhs);
// Restore caller-saved value of parentRef.
parentRef = parentRef_saved;
cached_fp_sequent->pop_sequent();
// We have now recursively established the value of the rhs.
// This possibly changes the value of some cached items, since we now know whether we can prove
// (discrete_state, zone) |- X under the current assumptions.
// This means we have to purge the caches.
if (options.useCaching) {
if (retVal) {
cache.purge_false_sequent(discrete_state, zone, formula);
cache.cache_true_sequent(discrete_state, zone, formula);
} else { // !retVal
cache.purge_true_sequent(discrete_state, zone, formula);
cache.cache_false_sequent(discrete_state, zone, formula);
}
}
return retVal;
}
// [FC14] Proof rule \land
inline bool prover::do_proof_and(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
/* Because zone is only changed after it is copied, it can
* be passed to both branches. */
bool retVal = do_proof(discrete_state, zone, *formula.getLeft());
if (retVal) {
retVal = do_proof(discrete_state, zone, *formula.getRight());
}
return retVal;
}
/* For an expression l || r we consider three cases, using a placeholder:
* - the proof for l returns an empty placeholder
* - the proof for l covers the entire DBM zone
* - the proof for l covers a strict, non-empty subset of zone
*/
// [FC14] Proof rule based on \lor_{s_2}
inline bool prover::do_proof_or(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
bool retVal = false;
/* Use two placeholders to provide split here */
DBMList placeholder1(INFTYDBM);
do_proof_place(discrete_state, zone, &placeholder1, *formula.getLeft());
placeholder1.cf();
// We optimise on proving the right hand side, depending on the placeholder.
// If empty, the right hand side needs to hold for the entire DBM
// If the placeholder already covers the entire DBM, we are done,
// otherwise we need to prove the right hand side for a fresh placeholder.
// Reset place parent to nullptr
parentPlaceRef = nullptr;
if (placeholder1.emptiness()) {
retVal = do_proof(discrete_state, zone, *formula.getRight());
} else if (placeholder1 >= zone) {
retVal = true;
} else {
/* Here we get the corner case where we have to use the
* OR Split rule, so we try to establish whether part of zone is covered by
* l, and the other part is covered by formula. */
DBMList placeholder2(INFTYDBM);
do_proof_place(discrete_state, zone, &placeholder2, *formula.getRight());
placeholder2.cf();
// Reset place parent to nullptr
parentPlaceRef = nullptr;
placeholder2.union_(placeholder1);
placeholder2.cf();
retVal = placeholder2 >= zone; // if the union of both placeholders covers
// the set of states, we are still happy
}
return retVal;
}
// [FC14], rules \lor_{l} and \lor_{r}
inline bool prover::do_proof_or_simple(const SubstList& discrete_state,
const DBM& zone,
const ExprNode& formula) {
/* Simplified OR does not need to split on placeholders */
bool retVal = do_proof(discrete_state, zone, *formula.getLeft());
if (!retVal) {
retVal = do_proof(discrete_state, zone, *formula.getRight());
}
return retVal;
}
// [FC14] Rule \forall_{t1}
inline bool prover::do_proof_forall(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
/* Here the model checker looks at the zone of
* all time sucessors and then substitutes in
* the substitued constraints and sees if the
* zone satifies the constraints */
/* DBM zone is copied because it is changed by suc() and invs_chk().
* The copying here assures that zone is unchanged when it is returned,
* allowing multiple branches of AND and OR to have the same zone. */
DBM succ_lhs(zone);
succ_lhs.suc();
succ_lhs.cf();
restrict_to_invariant(input_pes.invariants(), succ_lhs, discrete_state);
succ_lhs.cf();
return do_proof(discrete_state, succ_lhs, *formula.getQuant());
}
// [FC14] Proof rules \forall_{ro1}, \forall_{ro2}, \forall_{ro3}
inline bool prover::do_proof_forall_rel(const SubstList& discrete_state,
const DBM& zone,
const ExprNode& formula) {
/* Proof methodology:
* first, see if \phi_1 is satisfied during the time advance.
* If it is, check that phi_2 is true both at and before those
* times (time predecessor).
* If this is not satisfactory, then do a regular FORALL proof
* without a placeholder. */
bool retVal;
/* First, see if \exists(phi_1) is true. The common case is that it
* will not be. */
DBM lhs_succ(zone);
lhs_succ.suc();
// Make sure lhs_succ is not modified; we reuse it for the sake of efficiency.
DBMList placeholder1(INFTYDBM); // phi_{s1}
restrict_to_invariant(input_pes.invariants(), placeholder1, discrete_state);
placeholder1.cf();
do_proof_place(discrete_state, lhs_succ, &placeholder1, *formula.getLeft());
placeholder1.cf();
// Reset place parent to nullptr
parentPlaceRef = nullptr;
if (placeholder1.emptiness()) { // Here, \forall phi_2 needs to hold.
// [FC14] derived rule? of \forall_{ro1} TODO
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(std::cerr, step - 1, false, zone, placeholder1,
discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() Empty Relativization Placeholder: phi1 is never true -----"
<< std::endl
<< std::endl;
}
/* Since here, \forall phi_2 must be true; we use \forall_{ro1}.
* Note that we do not call do_proof_forall on a new sequent, instead we
* unfold the definition of \forall_{t1}. */
/* DBM zone is copied because it is changed by suc() and invs_chk().
* The copying here assures that zone is unchanged when it is returned,
* allowing multiple branches of AND and OR to have the same zone. */
DBM lhs_succ_invariant(lhs_succ); // that part of lhs_succ that satisfies
// the location invariant
restrict_to_invariant(input_pes.invariants(), lhs_succ_invariant, discrete_state);
lhs_succ_invariant.cf();
retVal = do_proof(discrete_state, lhs_succ_invariant, *formula.getRight());
} else if (placeholder1 >= zone) {
// placeholder1 nonempty
/* First check for the simplest case: no time elapse is needed */
/* For improved performance, first ask if the formula
* is true with no time elapse. */
// [FC14] proof rule \forall_{ro2};
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, true, zone,
placeholder1, discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----(Valid) Placeholder indicates no time "
"elapse is needed (Check Only)-----"
<< std::endl
<< "----With Placeholder := {" << placeholder1
<< "} ----" << std::endl
<< std::endl;
}
// If here, we neither need a placeholder nor to elapse time
retVal = do_proof(discrete_state, zone, *formula.getRight());
} else {
// This is the more complicated case that requires a placeholder
// for the FORALL
/* Now check that we can elapse to the placeholder. */
// Store the set of times that satisfy phi1
cpplog(cpplogging::debug)
<< "----() Relativization \\phi_1 placeholder obtained as {"
<< placeholder1 << "} ----" << std::endl
<< std::endl;
/* We omit the check that we can elapse to the placeholder;
* We will check that once at the end */
DBMList placeholder2(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder2, discrete_state);
placeholder2.cf();
do_proof_place(discrete_state, lhs_succ, &placeholder2, *formula.getRight());
placeholder2.cf();
cpplog(cpplogging::debug)
<< "----() Formula \\phi_2 placeholder obtained as {" << placeholder2
<< "} ----" << std::endl
<< std::endl;
// Reset place parent to nullptr
parentPlaceRef = nullptr;
if (placeholder2.emptiness()) { // \phi_2 is satisfied nowhere.
retVal = false;
} else if (placeholder2 >= lhs_succ) {
/* In this simple case, all possible times satisfy \phi_2
* so we can avoid many checks. */
retVal = true;
} else {
/* Now do a succ check on phi_2 to get \phi_forall
* and a predCheck using both phi_1 and phi_2 to get phi_exists */
/* we also note that the times satisfying \phi_1
* (the relativization formula condition) are neither empty
* nor everything. */
DBMList placeholder_forall(INFTYDBM);
establish_forall_place_sidecondition(&placeholder_forall, discrete_state, zone, placeholder2);
placeholder_forall.cf();
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, true,
lhs_succ, placeholder2, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() FORALL (of FORALL_REL) Placeholder Check obtained FA "
"Placeholder := {"
<< placeholder_forall << "} ----" << std::endl
<< std::endl;
}
/* Now we do the pred check to find the exists placeholder;
* This involves the predCheck method and checking that time can
* can elapse. Note that the exists is a simplified version
* where \phi_2 (the right) is the relativized clause and
* \phi_1 (the left) is the formula. By using the placeholders
* computed previously, we save time by not having to recompute
* the formulas. */
DBMList placeholder_exists(INFTYDBM);
/*--- PredCheck code----*/
DBMList placeholder_and(placeholder2);
placeholder_and.intersect(placeholder1);
placeholder_and.cf();
establish_exists_rel_sidecondition(&placeholder_exists, zone, placeholder2, placeholder_and);
placeholder_exists.cf();
cpplog(cpplogging::debug)
<< "----() FORALL Rel Exists predCheck placeholder obtained as := {"
<< placeholder_exists << "} ----" << std::endl
<< std::endl;
if (!placeholder_exists.emptiness()) {
/* Now check that it works. */
placeholder_exists.pre();
/* This cf() is needed. */
placeholder_exists.cf();
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, true,
zone, placeholder_exists, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() FORALL Rel Exists placeholder after time elapse check "
"is := {"
<< placeholder_exists << "} ----" << std::endl
<< std::endl;
}
}
placeholder_exists.union_(placeholder_forall);
placeholder_exists.cf();
retVal = placeholder_exists >= zone;
// Debug information here?
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, retVal, zone,
placeholder_exists, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() Final FORALL REL Placeholder is := {"
<< placeholder_exists << "} ----" << std::endl
<< std::endl;
}
}
}
return retVal;
}
// [FC14] Proof rule \exists_{t1}
inline bool prover::do_proof_exists(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
/* Support for exists(), written by Peter Fontana */
// This support gives a placeholder variable
// and uses a similar method do_proof_place
// which recursively uses (slightly more complex rules)
// to solve for the placeholders.
/* First Try to get a placeholder value that works */
DBM lhs_succ(zone);
lhs_succ.suc();
/* The proper derivation for EXISTS is to incorporate the invariant
* in the placeholder, and not the LHS. */
DBMList placeholder(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder, discrete_state);
placeholder.cf();
DBMList placeholder_dbg_copy(placeholder); // Check assumption on do_proof_place
do_proof_place(discrete_state, lhs_succ, &placeholder, *formula.getQuant());
// Reset place parent to nullptr
parentPlaceRef = nullptr;
placeholder.cf();
assert(placeholder <= placeholder_dbg_copy);
placeholder.pre();
placeholder.cf(true);
bool retVal = placeholder >= zone;
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, retVal, zone,
placeholder, discrete_state, formula.getOpType());
if (placeholder.emptiness()) {
cpplog(cpplogging::debug) << "----(Invalid) Empty Placeholder: No Need "
"for Placeholder Check-----" << std::endl
<< std::endl;
} else if (retVal) {
cpplog(cpplogging::debug)
<< "----(Valid) Placeholder Check Passed (Check Only)-----" << std::endl
<< "----With Placeholder := {" << placeholder << "} ----"
<< std::endl << std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
return retVal;
}
inline bool prover::do_proof_exists_rel(const SubstList& discrete_state,
const DBM& zone,
const ExprNode& formula) {
bool retVal = false;
/* First Try to get a placeholder value that works */
DBM zone_succ(zone);
zone_succ.suc();
DBMList placeholder2(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder2, discrete_state);
placeholder2.cf();
do_proof_place(discrete_state, zone_succ, &placeholder2, *formula.getRight());
// Reset place parent to nullptr
parentPlaceRef = nullptr;
placeholder2.cf();
if (placeholder2.emptiness()) {
retVal = false;
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, retVal, zone,
placeholder2, discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----(Invalid) Empty First Placeholder: No "
"Need for additional Placeholder Checks-----"
<< std::endl
<< std::endl;
}
} else {
retVal = true;
/* We find all the times that satisfy phi_1, and then intersect it
* with the time predecessor of the phi_2 placeholders. */
DBMList placeholder1(INFTYDBM);
// Since invariants are past closed, we do not need to intersect
// this placeholder with the invariant.
do_proof_place(discrete_state, zone_succ, &placeholder1, *formula.getLeft());
/* Second step: tighten and check the predecessor */
// Must check for emptiness to handle the corner case when it is empty
cpplog(cpplogging::debug)
<< "----() Placeholder of times where \\phi_1 is true----- {"
<< placeholder1 << "} ----" << std::endl
<< std::endl;
/* Now check for the relativization.
* First, find the subset of the predecessor_< of the placeholder
* that satisfies the left clause.
* Second: utilize a pred_check() method to further tighten the
* placeholder in order that the entire predecessor does satisfy
* the relativization formaula. */
/* First step */
DBMList placeholder2_predecessor(placeholder2);
placeholder2_predecessor.pre();
// pred Closure makes sure that the exact valuation for the placeholder
// is excluded.
placeholder2_predecessor.predClosureRev();
placeholder2_predecessor.cf();
/* At this point, placeholder2_predecessor is the time predecessor_{<} of
* the placeholders that satisfy phi_2, the right hand formula */
// This provides a preliminary check.
// If the left hand side and right hand side never hold at the same time, we
// only need to check whether the right hand side holds immediately
DBMList placeholder1_intersect_placeholder2_pred(placeholder1);
placeholder1_intersect_placeholder2_pred.intersect(placeholder2_predecessor);
placeholder1_intersect_placeholder2_pred.cf();
if (placeholder1_intersect_placeholder2_pred.emptiness()) {
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(
cpplogGet(cpplogging::debug), step - 1, false, zone_succ,
placeholder1_intersect_placeholder2_pred, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() Empty Second Placeholder: Relativization Formula "
"\\phi_1 is never true-----"
<< std::endl
<< std::endl;
}
/* Now determine if $\phi_2$ is true without a time elapse.
* If so, make a non-empty placeholder. In this case, the third
* Check will be true by default and can be skipped.
* Else, return empty and break */
// FIXME: the following code can be simplified significantly (only the inclusion is needed)
placeholder2.intersect(zone); // zone here is before the time elapse
placeholder2.cf();
if (placeholder2.emptiness()) {
retVal = false;
cpplog(cpplogging::debug)
<< "----(Invalid) Time Elapsed required for formula to be true; "
"hence, relativized formula cannot always be false."
<< std::endl
<< std::endl;
} else {
/* While a time elapse is not required, the placeholder
* must span all of zone */
retVal = placeholder2 >= zone;
if (retVal) {
assert(placeholder2 == zone);
cpplog(cpplogging::debug)
<< "----(Valid) Time Elapse not required and placeholder spans "
"zone; hence, formula is true-----"
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) While Time Elapse not required, placeholder is "
"not large enough-----"
<< std::endl;
}
cpplog(cpplogging::debug) << "----With resulting Placeholder := {"
<< placeholder2 << "} ----" << std::endl
<< std::endl;
}
} else {
// There are locations where both left-hand side and right-hand side hold.
// we therefore need to check the side-conditions
DBMList placeholder(placeholder1); // tightened placeholder for the
// result; copy since placeholder1 is
// used in the sidecondition
// computation
/*--- PredCheck code----*/
establish_exists_rel_sidecondition(&placeholder, zone, placeholder1, placeholder2);
placeholder.cf();
if (placeholder.emptiness()) {
retVal = false;
cpplog(cpplogging::debug)
<< "----(Invalid) Relativization placeholder failed-----"
<< std::endl
<< "----With resulting Placeholder := {" << placeholder << "} ----"
<< std::endl
<< std::endl;
} else {
// if it is nonempty, it passes the second check and we continue
if (cpplogEnabled(cpplogging::debug)) {
print_sequent_place(std::cerr, step - 1, retVal, zone_succ,
placeholder2_predecessor, *formula.getLeft(),
discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----(Valid) Relativization Placeholder "
"Check Passed (Check Only)-----"
<< std::endl
<< "----With resulting Placeholder := {"
<< placeholder << "} ----" << std::endl
<< std::endl;
}
// Allow for the possibility of the time instant after the elapse
//placeholder.closure();
/* Extract the new refined placeholder. */
//placeholder.intersect(placeholder2);
//placeholder.cf();
assert(placeholder <= placeholder2);
/* Now check that it works. */
placeholder.pre();
/* This cf() is needed. */
placeholder.cf();
retVal = placeholder >= zone;
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, retVal, zone,
placeholder, discrete_state, formula.getOpType());
if (retVal) {
cpplog(cpplogging::debug)
<< "----(Valid) Last Placeholder Check Passed (Check Only)-----"
<< std::endl
<< "----With Placeholder := {" << placeholder << "} ----"
<< std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Last Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
}
}
}
return retVal;
}
inline bool prover::do_proof_allact(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
bool retVal = true;
/* Enumerate through all transitions */
cpplog(cpplogging::debug) << "\t Proving ALLACT Transitions:----\n"
<< std::endl;
for (Transition* const transition: input_pes.transitions()) {
/* Obtain the entire ExprNode and prove it */
DBM guard_zone(zone);
if (comp_ph(guard_zone, *(transition->guard()), discrete_state)) {
// guard is satisfiable
/* Now check the invariant; if the invariant is satisfiable, we update the
left hand side to be the part of the left hand side that satisfies the
location invariant. */
DBM invariant_zone(INFTYDBM);
bool has_nonvacuous_invariant = restrict_to_invariant(
input_pes.invariants(), invariant_zone, transition->destination_location(&discrete_state));
assert(has_nonvacuous_invariant || invariant_zone.isInCf());
// If he invariant of the target location is non-vacuous, compute the weakest precondition
// and intersect with the guard.
if (has_nonvacuous_invariant) {
invariant_zone.cf();
// Some clocks are reset on this transition
const clock_set* reset_clocks = transition->reset_clocks();
if (reset_clocks != nullptr) {
invariant_zone.preset(*reset_clocks);
invariant_zone.cf();
}
/* Now perform clock assignments sequentially: perform the
* front assignments first */
const std::vector<std::pair<DBM::size_type, clock_value_t>>* clock_assignments =
transition->clock_assignments();
if (clock_assignments != nullptr) {
// Iterate over the vector and print it
for (const std::pair<DBM::size_type, clock_value_t>& clock_assignment: *clock_assignments) {
invariant_zone.preset(clock_assignment.first, clock_assignment.second);
invariant_zone.cf();
}
}
guard_zone.intersect(invariant_zone);
guard_zone.cf();
if (guard_zone.emptiness()) {
cpplog(cpplogging::debug)
<< "Transition: " << transition
<< " cannot be taken; entering invariant is false." << std::endl
<< "\tExtra invariant condition: " << invariant_zone << std::endl;
continue;
}
} // end if has_nonvacuous_invariant
// We add the body of the allact to the formula that holds after the transition.
// Note that this formula after the transition already contains the resets and assignments,
// so, when we call getRightExpr() later, we in fact look at the weakest precondition of
// formula.getQuant with respect to this transition.
transition->getNewTrans(formula.getQuant());
/* Constraints are bounded by input_pes.max_constant() */
/* This is to extend the LHS to make sure that
* the RHS is satisfied by any zone that satisfies
* the LHS by expanding the zone so it contains
* all the proper regions where the clocks
* exceed a certain constant value. */
guard_zone.bound(input_pes.max_constant());
guard_zone.cf();
cpplog(cpplogging::debug)
<< "Executing transition (with destination) " << transition << std::endl
<< "\tExtra invariant condition: " << invariant_zone << std::endl;
++numLocations;
// Recursively prove that the weakest precondition of the body of allact
// is satisfied. See the remark about getNewTrans above.
retVal = do_proof(discrete_state, guard_zone, *transition->getRightExpr());
if (!retVal) {
cpplog(cpplogging::debug)
<< "Trainsition: " << transition << std::endl
<< "\tinvalidates property and breaks transition executions. "
<< std::endl;
break;
}
} else {
cpplog(cpplogging::debug)
<< "Transition: " << transition << " cannot be taken." << std::endl;
}
}
cpplog(cpplogging::debug) << "\t --- end of ALLACT." << std::endl;
return retVal;
}
inline bool prover::do_proof_existact(const SubstList& discrete_state,
const DBM& zone,
const ExprNode& formula) {
bool retVal = false;
/* Enumerate through all transitions */
cpplog(cpplogging::debug) << "\t Proving EXISTACT Transitions:----\n"
<< std::endl;
/* Use placeholders to split rules */
DBMList placeholder(INFTYDBM);
placeholder.makeEmpty();
for (Transition* const transition: input_pes.transitions()) {
/* Obtain the entire ExprNode and prove it */
// Make a similar comp function for exists so
// because the entire zone must be able to transition
// or split by placeholders
DBMList guard_placeholder(INFTYDBM);
DBM guard_zone(zone);
bool guard_satisfied = comp_ph_exist_place(
guard_zone, guard_placeholder, *(transition->guard()), discrete_state);
if (!guard_satisfied) {
cpplog(cpplogging::debug)
<< "Transition: " << transition << " cannot be taken." << std::endl;
continue;
}
/* Now check the invariant */
DBM invariant_zone(INFTYDBM);
bool invariant_satisfiable = restrict_to_invariant(
input_pes.invariants(), invariant_zone, transition->destination_location(&discrete_state));
if (invariant_satisfiable) {
invariant_zone.cf();
const clock_set* reset_clocks = transition->reset_clocks();
if (reset_clocks != nullptr) {
invariant_zone.preset(*reset_clocks);
}
invariant_zone.cf();
/* Now perform clock assignments sequentially: perform the
* front assignments first */
const std::vector<std::pair<DBM::size_type, clock_value_t>>* clock_assignments =
transition->clock_assignments();
if (clock_assignments != nullptr) {
for (const std::pair<DBM::size_type, clock_value_t>& clock_assignment: *clock_assignments) {
invariant_zone.preset(clock_assignment.first, clock_assignment.second);
invariant_zone.cf();
}
}
/* Check if invariant preset is satisfied by the zone.
* If not, tighten the placeholder */
if (!(guard_zone <= invariant_zone)) {
// for performance reasons, also tighten the left hand side
guard_placeholder.intersect(invariant_zone);
guard_placeholder.cf();
if (guard_placeholder.emptiness()) {
cpplog(cpplogging::debug)
<< "Transition: " << transition
<< " cannot be taken; entering invariant is false." << std::endl
<< "\tExtra invariant condition: " << invariant_zone
<< std::endl;
continue;
}
guard_zone.intersect(invariant_zone);
guard_zone.cf();
}
}
transition->getNewTrans(formula.getQuant());
/* Constraints are bounded by input_pes.max_constant() */
/* This is to extend the LHS to make sure that
* the RHS is satisfied by any zone that satisfies
* the LHS by expanding the zone so it contains
* all the proper regions where the clocks
* exceed a certain constant value. */
guard_zone.bound(input_pes.max_constant());
guard_zone.cf();
// Above placeholder restricted to satisfy incoming invariant
cpplog(cpplogging::debug) << "Executing transition (with destination) "
<< transition << std::endl;
numLocations++;
// Compute states satisfying weakest precondition of body of forall.
do_proof_place(discrete_state, guard_zone, &guard_placeholder,
*transition->getRightExpr());
// Reset place parent to nullptr
parentPlaceRef = nullptr;
placeholder.union_(guard_placeholder); // union more efficient than addDBMList here in general.
placeholder.cf();
if(placeholder >= zone) {
// The entire left hand side side is covered, we're done.
retVal = true;
break;
}
}
placeholder.cf();
retVal = retVal || placeholder >= zone;
cpplog(cpplogging::debug) << "\t --- end of EXISTACT." << std::endl;
return retVal;
}
inline bool prover::do_proof_imply(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
bool retVal = false;
/* Here is the one call to comp_ph(...) outside of comp_ph(...) */
DBM zone_lhs(zone);
if (comp_ph(zone_lhs, *(formula.getLeft()), discrete_state)) {
/* Constraints are bounded by input_pes.max_constant() */
/* This is to extend the LHS to make sure that
* the RHS is satisfied by any zone that satisfies
* the LHS by expanding the zone so it contains
* all the proper regions where the clocks
* exceed a certain constant value. */
zone_lhs.bound(input_pes.max_constant());
zone_lhs.cf();
retVal = do_proof(discrete_state, zone_lhs, *formula.getRight());
} else {
/* The set of states does not satisfy the premises of the IF
* so thus the proof is true */
retVal = true;
cpplog(cpplogging::debug)
<< "---(Valid) Leaf IMPLY Reached, Premise Not Satisfied----"
<< std::endl
<< std::endl;
}
return retVal;
}
inline bool prover::do_proof_constraint(const DBM& zone,
const ExprNode& formula) const {
bool retVal = (zone <= *(formula.dbm()));
cpplog(cpplogging::debug)
<< "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf DBM (CONSTRAINT) Reached----" << std::endl
<< std::endl;
return retVal;
}
inline bool prover::do_proof_sublist(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
SubstList st(formula.getSublist(), &discrete_state);
return do_proof(st, zone, *formula.getExpr());
}
inline bool prover::do_proof_reset(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
DBM lhs_reset(zone);
lhs_reset.reset(*formula.getClockSet());
lhs_reset.cf();
return do_proof(discrete_state, lhs_reset, *formula.getExpr());
}
inline bool prover::do_proof_assign(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
// Formula is phi[x:=y] with x and y clocks.
DBM lhs_assign(zone);
lhs_assign.reset(formula.getcX(), formula.getcY());
lhs_assign.cf();
return do_proof(discrete_state, lhs_assign, *formula.getExpr());
}
inline bool prover::do_proof_replace(const SubstList& discrete_state,
const DBM& zone, const ExprNode& formula) {
SubstList sub_(discrete_state);
sub_[formula.getcX()] = discrete_state.at(formula.getcY());
return do_proof(sub_, zone, *formula.getExpr());
}
/* IMPLEMENTATION PROVER WITH PLACEHOLDERS */
inline void prover::do_proof_place_predicate(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula) {
ExprNode* e = input_pes.lookup_equation(formula.getPredicate());
/* First look in known true and false sequent tables */
if (options.useCaching) {
cpplog(cpplogging::debug1) << "Looking for sequent in known-false and known-true cache" << std::endl;
if (cache.is_known_false_sequent(discrete_state, zone, formula, parentRef, parentPlaceRef)) {
cpplog(cpplogging::debug)
<< "---(Invalid) Located a Known False Sequent ----" << std::endl
<< std::endl;
place->makeEmpty();
return;
} else {
DBMList cached_placeholder(INFTYDBM);
if (cache.is_known_true_sequent(discrete_state, zone, formula, &cached_placeholder, parentRef, parentPlaceRef)) {
*place = std::move(cached_placeholder);
if(!place->emptiness()) {
cpplog(cpplogging::debug)
<< "---(Valid) Located a Known True Sequent ----" << std::endl
<< std::endl;
}
return;
}
}
}
/* Now deal with greatest fixpoint and least fixpoint circularity */
SequentPlace* cached_fp_sequent = nullptr;
// Restricted scope for detecting circularities
if (formula.is_gfp()) { // Thus a Greatest Fixpoint
std::pair<SequentPlace*, bool> gfp_cycle = cache.completes_gfp_cycle(discrete_state, zone, formula, place, parentRef, parentPlaceRef);
if (gfp_cycle.second) {
cpplog(cpplogging::debug)
<< "---(Valid) Located True Sequent or gfp Circularity ----"
<< std::endl
<< std::endl;
// Add sequent to known true cache
if (options.useCaching) {
cache.cache_true_sequent(discrete_state, zone, formula, *place);
}
return;
} else {
cached_fp_sequent = gfp_cycle.first;
}
} else { // Thus, a least fixpoint
std::pair<SequentPlace*, bool> lfp_cycle = cache.completes_lfp_cycle(discrete_state, zone, formula, place, parentRef, parentPlaceRef);
if (lfp_cycle.second) {
place->makeEmpty();
cpplog(cpplogging::debug)
<< "---(Invalid) Located lfp Circularity ----" << std::endl
<< std::endl;
// Now Put Sequent in False Cache
if (options.useCaching) {
cache.cache_false_sequent(discrete_state, zone, formula, *place);
}
return;
} else {
cached_fp_sequent = lfp_cycle.first;
}
}
assert(cached_fp_sequent != nullptr);
cached_fp_sequent->push_sequent(std::make_pair(new DBM(zone), new DBMList(*place)));
// no least/greatest fixed point circularity was found; the sequent has been
// added to the appropriate cache
// NO CIRCULARITY FOUND
/* Assign parent value after caching since during caching we may have
* to use the previous parent */
SequentPlace* tempParentPlace = parentPlaceRef;
/* Get the current variable */
parentPlaceRef = cached_fp_sequent;
do_proof_place(discrete_state, zone, place, *e);
/* Now update the parent so it points to the previous parent, and not this
* predicate */
parentPlaceRef = tempParentPlace;
cached_fp_sequent->pop_sequent(); // XXX Why do this at a different place than in the
// non-placeholder case? (JK)
// ds might be empty, but we leave it in
// Now Purge updated premise
place->cf();
if (options.useCaching) {
if (!place->emptiness()) {
cache.purge_false_sequent(discrete_state, zone, formula, *place);
cache.cache_true_sequent(discrete_state, zone, formula, *place);
} else {
cache.purge_true_sequent(discrete_state, zone, formula, *place);
cache.cache_false_sequent(discrete_state, zone, formula, *place);
}
}
}
inline void prover::do_proof_place_and(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula) {
do_proof_place(discrete_state, zone, place, *formula.getLeft());
place->cf();
if (!place->emptiness()) {
do_proof_place(discrete_state, zone, place, *formula.getRight());
}
}
// [FC14] Proof rule \lor_{s2}
inline void prover::do_proof_place_or(const SubstList& discrete_state,
const DBM& zone, DBMList* place,
const ExprNode& formula) {
DBMList placeholder_left(*place);
do_proof_place(discrete_state, zone, &placeholder_left, *formula.getLeft());
placeholder_left.cf();
if (!(placeholder_left >= *place))
{
// We use place here, since the result of the second call is likely to be
// part of the result anyway. If not, we will roll back later.
// *place is thus placeholder_right.
do_proof_place(discrete_state, zone, place, *formula.getRight());
place->cf();
if (cpplogEnabled(cpplogging::debug)) {
// Check Debugging Here to make sure it is giving the right output
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false, zone,
placeholder_left, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "Left Placeholder of OR (P): " << placeholder_left
<< "\nRight Placeholder of OR (P): " << *place << std::endl;
}
place->union_(placeholder_left);
place->cf();
cpplog(cpplogging::debug)
<< "Final Placeholder of OR (P): " << *place << std::endl
<< std::endl;
}
}
inline void prover::do_proof_place_or_simple(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
/* In OR_SIMPLE, the placeholder will either be empty or completely full
* in one of the two cases. Hence, fewer comparisons with unions of zones
* are needed. */
DBMList placeholder_left(*place);
do_proof_place(discrete_state, zone, &placeholder_left, *formula.getLeft());
placeholder_left.cf();
// Now do the right proof, and take the right if its placeholder is
// larger that from the left side.
if (!(placeholder_left >= *place)) {
// We anticipate the right placeholder is the correct result here.
// if not, we roll back later.
do_proof_place(discrete_state, zone, place, *formula.getRight());
place->cf();
/* If the left is simple, then we have an empty left or
* left is the entire placeholder. */
/* If both are non-empty then the left is not the
* entire placeholder. Hence, the left was not the simple
* disjunct. Therefore, the right must be the simple disjunct
* and must be the entire placeholder. */
if (place->emptiness()) {
// Take previous DBM
*place = std::move(placeholder_left);
}
}
}
// [FC14] Proof rule \forall_{t2}
inline void prover::do_proof_place_forall(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
/* Here the model checker looks at the zone of
* all time sucessors and then substitutes in
* the substitued constraints and sees if the
* zone satifies the constraints */
DBM lhs_succ(zone);
lhs_succ.suc();
/* Per proof rules with the placeholder,
* do not incorporate the invariant into the FORALL here */
do_proof_place(discrete_state, lhs_succ, place, *formula.getQuant());
place->cf();
// must we consider not the invariant even if the placeholder is empty. (?)
if (!place->emptiness()) { // Only do if a nonempty placeholder
/* Now do the second proof rule to compute the first placeholder
*/
DBMList placeholder_forall(*place);
establish_forall_place_sidecondition(&placeholder_forall, discrete_state, zone, *place);
place->intersect(placeholder_forall);
if (cpplogEnabled(cpplogging::debug)) {
place->cf();
// Result only used for printing the correct value below.
bool result = !place->emptiness();
// This work is done in the succCheck method.
// Perhaps I should move the debug rule there?
DBM succLHS(zone);
succLHS.suc();
succLHS.cf();
DBMList succRuleConseq(zone);
succRuleConseq.intersect(*place);
succRuleConseq.cf();
succRuleConseq.suc();
succRuleConseq.cf();
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, result,
succLHS, succRuleConseq, discrete_state, formula.getOpType());
if (result) {
cpplog(cpplogging::debug)
<< "----(Valid) Placeholder Check Passed-----" << std::endl
<< "--With Placeholder := {" << *place << "} ----" << std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
}
}
inline void prover::do_proof_place_forall_rel(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
/* Proof methodology:
* first, see if \phi_1 is satisfied during the time advance.
* If it is, check that phi_2 is true both at and before those
* times (time predecessor).
* If this is not satisfactory, then do a regular FORALL proof
* without a placeholder. */
/* First, see if \exists(phi_1) is true. The common case is that it
* will not be. */
/* First try to get a new placeholder value that works */
DBM lhs_succ(zone);
lhs_succ.suc();
DBMList placeholder1(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder1, discrete_state);
placeholder1.cf();
do_proof_place(discrete_state, lhs_succ, &placeholder1, *formula.getLeft());
placeholder1.cf();
if (placeholder1.emptiness()) {
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false,
lhs_succ, placeholder1, discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "--------() Empty Relativization "
"Placeholder: phi1 is never true ----------"
<< std::endl
<< std::endl;
}
/* Since here, \forall phi_2 computes the entire placeholder */
/* Here the model checker looks at the zone of
* all time sucessors and then substitutes in
* the substitued constraints and sees if the
* zone satifies the constraints */
DBMList placeholder2(*place);
do_proof_place(discrete_state, lhs_succ, &placeholder2, *formula.getRight());
placeholder2.cf();
if (placeholder2.emptiness()) {
place->makeEmpty();
} else { // Only do if a nonempty placeholder
/* Now do the second proof rule to compute the first placeholder
*/
establish_forall_place_sidecondition(place, discrete_state, zone, placeholder2);
place->cf();
if (cpplogEnabled(cpplogging::debug)) {
// This work is done in the succCheck method.
// Perhaps I should move the debug rule there?
bool retVal = !place->emptiness();
DBMList succRuleConseq(zone);
succRuleConseq.intersect(*place);
succRuleConseq.cf();
succRuleConseq.suc();
succRuleConseq.cf();
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, retVal,
lhs_succ, succRuleConseq, discrete_state, formula.getOpType());
if (retVal) {
cpplog(cpplogging::debug)
<< "----(Valid) FORALL (FORALL_REL) Placeholder Check Passed-----"
<< std::endl
<< "--With Placeholder := {" << *place << "} ----"
<< std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug) << "----(Invalid) FORALL (FORALL_REL) "
"Placeholder Check Failed-----"
<< std::endl
<< std::endl;
}
}
}
} else if (placeholder1 == INFTYDBM) {
// First check for the simplest case: no time elapse is needed
/* Perhaps we can reduce INFTYDBM to be *place
* given the proof rules. */
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false, zone,
placeholder1, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----(Valid) EXISTS (in FORALL_REL) Placeholder indicates no "
"time elapse is needed (Check Only)-----"
<< std::endl
<< "----With Placeholder := {" << placeholder1 << "} ----"
<< std::endl
<< std::endl;
}
// If here, we neither need a placeholder nor to elapse time
do_proof_place(discrete_state, zone, place, *formula.getRight());
place->cf();
if (!place->emptiness()) { // Only do if a nonempty placeholder
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, true,
zone, *place, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----(Valid) Placeholder Check Passed-----" << std::endl
<< "--With Placeholder := {" << *place << "} ----"
<< std::endl
<< std::endl;
}
}
} else {
// This is the more complicated case that requires a placeholder
// for the FORALL
/* Now check that we can elapse to the placeholder. */
// Store the set of times that satisfy phi1
cpplog(cpplogging::debug)
<< "----() Relativization \\phi_1 placeholder obtained as {"
<< placeholder1 << "} ----" << std::endl
<< std::endl;
/* We omit the check that we can elapse to the placeholder;
* We will check that once at the end */
DBMList placeholder2(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder2, discrete_state);
placeholder2.cf();
do_proof_place(discrete_state, lhs_succ, &placeholder2, *formula.getRight());
placeholder2.cf();
cpplog(cpplogging::debug)
<< "----() Formula \\phi_2 placeholder obtained as {" << placeholder2
<< "} ----" << std::endl
<< std::endl;
// Reset place parent to nullptr
parentPlaceRef = nullptr;
if (placeholder2.emptiness()) {
*place = std::move(placeholder2);
} else if (placeholder2 >= lhs_succ) {
/* \forallrel(\phi_2) holds, avoid extra work. */
*place = std::move(placeholder2);
} else {
/* Now do a succ check on phi_2 to get \phi_forall
* and a predCheck using both phi_1 and phi_2 to get phi_exists */
/* we also note that the times satisfying \phi_1
* (the relativization formula condition) are neither empty
* nor everything. */
DBMList placeholder_forall(INFTYDBM);
establish_forall_place_sidecondition(&placeholder_forall, discrete_state, zone, placeholder2);
placeholder_forall.cf();
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false,
lhs_succ, placeholder2, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() FORALL (of FORALL_REL) Placeholder Check obtained FA "
"Placeholder := {"
<< placeholder_forall << "} ----" << std::endl
<< std::endl;
}
DBMList placeholder_exists(INFTYDBM);
DBMList placeholder_and(placeholder2);
placeholder_and.intersect(placeholder1);
placeholder_and.cf();
establish_exists_rel_sidecondition(&placeholder_exists, zone, placeholder2, placeholder_and);
placeholder_exists.cf();
cpplog(cpplogging::debug)
<< "----() FORALL Rel Exists placeholder obtained as := {"
<< placeholder2 << "} ----" << std::endl
<< std::endl;
if (!placeholder_exists.emptiness()) {
/* Now check that it works. */
/* Since we are not using retPlace anymore, we do not
* need to copy it for the check. */
placeholder_exists.pre();
/* This cf() is needed. */
placeholder_exists.cf();
// check elapse further?
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false,
zone, placeholder_exists, discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----() FORALL Rel Exists placeholder "
"after time elapse check is := {"
<< placeholder_exists << "} ----" << std::endl
<< std::endl;
}
}
*place = std::move(placeholder_exists);
place->union_(placeholder_forall);
place->cf();
}
cpplog(cpplogging::debug)
<< "Final Placeholder of FORALL_REL (P): " << *place
<< std::endl
<< std::endl;
}
}
inline void prover::do_proof_place_exists(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
/* First try to get a new placeholder value that works */
DBM lhs_succ(zone);
lhs_succ.suc();
// The invariant goes into the placeholder, not the left hand side
DBMList placeholder(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder, discrete_state);
placeholder.cf();
do_proof_place(discrete_state, lhs_succ, &placeholder, *formula.getQuant());
placeholder.cf();
if (placeholder.emptiness()) {
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false,
lhs_succ, placeholder, discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----(Invalid) Empty First Placeholder: No "
"Need for additional Placeholder Checks-----"
<< std::endl
<< std::endl;
}
place->makeEmpty();
} else {
/* Now check that it works (the new placeholder can be
* obtained from the old
* For the placeholder rule, we use this check
* to give us the value of the old placeholder */
placeholder.pre();
place->intersect(placeholder);
place->cf();
if (cpplogEnabled(cpplogging::debug)) {
bool result = !place->emptiness();
print_sequent_placeCheck(std::cerr, step - 1, result, zone, *place, *place,
discrete_state, formula.getOpType());
if (result) {
cpplog(cpplogging::debug)
<< "----(Valid) Placeholder Check Passed-----" << std::endl
<< "--With Placeholder := {" << *place << "} ----" << std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
}
}
inline void prover::do_proof_place_exists_rel(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
/* First Try to get a placeholder value that works */
DBM zone_succ(zone);
zone_succ.suc();
DBMList placeholder2(INFTYDBM);
restrict_to_invariant(input_pes.invariants(), placeholder2, discrete_state);
placeholder2.cf();
do_proof_place(discrete_state, zone_succ, &placeholder2, *formula.getRight());
// Reset place parent to nullptr
parentPlaceRef = nullptr;
placeholder2.cf();
if (placeholder2.emptiness()) {
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false, zone,
placeholder2, discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----(Invalid) Empty First Placeholder: No "
"Need for additional Placeholder Checks-----"
<< std::endl
<< std::endl;
}
place->makeEmpty();
} else {
/* Now check for the relativization.
* First, find the subset of the predecessor_< of the placeholder
* that satisfies the left clause.
* Second: utilize a pred_check() method to further tighten the
* placeholder in order that all */
/* First step */
DBMList placeholder2_predecessor(placeholder2);
placeholder2_predecessor.pre();
// pred Closure makes sure that the exact valuation for the placeholder
// is excluded.
placeholder2_predecessor.predClosureRev();
placeholder2_predecessor.cf();
/* At this point, phi2PredPlace is the time predecessor_{<} of the
* placeholders that satisfy phi_2, the right hand formula */
/* We find all the times that satisfy phi_1, and then intersect it
* with the time predecessor of the phi_2 placeholders. */
DBMList placeholder1(INFTYDBM);
do_proof_place(discrete_state, zone_succ, &placeholder1, *formula.getLeft());
/* Second step: tighten and check the predecessor */
// Must check for emptiness to handle the corner case when it is empty
cpplog(cpplogging::debug)
<< "----() Placeholder of times where \\phi_1 is true----- {" << placeholder1
<< "} ----" << std::endl
<< std::endl;
DBMList placeholder1_intersect_placeholder2_pred(placeholder1);
placeholder1_intersect_placeholder2_pred.intersect(placeholder2_predecessor);
placeholder1_intersect_placeholder2_pred.cf();
if (placeholder1_intersect_placeholder2_pred.emptiness()) {
if (cpplogEnabled(cpplogging::debug)) {
print_sequentCheck(cpplogGet(cpplogging::debug), step - 1, false, zone_succ,
placeholder1_intersect_placeholder2_pred, discrete_state, formula.getOpType());
cpplog(cpplogging::debug)
<< "----() Empty Second Placeholder: Relativization Formula \\phi_1 "
"is never true-----"
<< std::endl
<< std::endl;
}
/* Now determine if $\phi_2$ is true without a time elapse.
* If so, make a non-empty placeholder. In this case, the third
* Check will be true by default and can be skipped.
* Else, return empty and break */
placeholder2.intersect(zone); // zone here is before the time elapse
placeholder2.cf();
*place = std::move(placeholder2);
if (place->emptiness()) {
cpplog(cpplogging::debug)
<< "----(Invalid) Time Elapsed required for formula to be true; "
"hence, relativized formula cannot always be false."
<< std::endl
<< std::endl;
} else {
/* While a time elapse is not required, the placeholder
* must span all of zone */
if (*place >= zone) {
cpplog(cpplogging::debug)
<< "----(Valid) Time Elapse not required and placeholder spans "
"zone; hence, formula is true-----"
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) While Time Elapse not required, placeholder is "
"not large enough-----"
<< std::endl;
}
cpplog(cpplogging::debug) << "----With resulting Placeholder := {"
<< *place << "} ----" << std::endl
<< std::endl;
}
} else {
/*--- PredCheck code----*/
DBMList placeholder(placeholder1);
establish_exists_rel_sidecondition(&placeholder, zone, placeholder1, placeholder2);
placeholder.cf();
if (placeholder.emptiness()) {
cpplog(cpplogging::debug)
<< "----(Invalid) Relativization placeholder failed-----" << std::endl
<< "----With resulting Placeholder := {" << placeholder << "} ----"
<< std::endl
<< std::endl;
place->makeEmpty();
}
else
{
// if it is still nonempty, it passes the second check and we continue
if (cpplogEnabled(cpplogging::debug)) {
print_sequent_place(std::cerr, step - 1, true, zone_succ, placeholder2_predecessor,
*formula.getLeft(), discrete_state, formula.getOpType());
cpplog(cpplogging::debug) << "----(Valid) Relativization Placeholder Check "
"Passed (Check Only)-----"
<< std::endl
<< "----With resulting Placeholder := {"
<< placeholder << "} ----" << std::endl
<< std::endl;
}
/* Now check that it works (the new placeholder can be
* obtained from the old
* For the placeholder rule, we use this check
* to give us the value of the old placeholder */
placeholder.pre();
place->intersect(placeholder);
place->cf();
if (cpplogEnabled(cpplogging::debug)) {
print_sequent_placeCheck(std::cerr, step - 1, !place->emptiness(), zone, *place,
*place, discrete_state, formula.getOpType());
if (!place->emptiness()) {
cpplog(cpplogging::debug)
<< "----(Valid) Final Placeholder Check Passed-----" << std::endl
<< "--With Placeholder := {" << *place << "} ----" << std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Final Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
}
}
}
}
inline void prover::do_proof_place_allact(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
/* Enumerate through all transitions */
cpplog(cpplogging::debug) << "\t Proving ALLACT Transitions:----\n"
<< std::endl;
/* For reasons to avoid convexity until the end, find all of the
* placeholders for each clause individually. For all transitions
* that can be executed, store the resulting placeholders with transitions
* so that we only need to give a non-convex placeholder when finished */
for (Transition* const transition: input_pes.transitions()) {
/* Obtain the entire ExprNode and prove it */
// Restrict both zone and placeholder to the guard, and check whether both are
// satisfiable.
DBM guard_zone(zone);
DBMList guard_placeholder(*place);
bool guard_satisfied =
comp_ph_all_place(guard_zone, guard_placeholder, *(transition->guard()),
discrete_state);
assert(guard_zone.isInCf());
assert(guard_placeholder.isInCf());
if (guard_satisfied) {
// guard_placeholder is the largest placeholder that satisfies the guard.
DBMList transition_placeholder(*place);
DBM invariant_zone(INFTYDBM);
bool invariant_satisfiable = restrict_to_invariant(input_pes.invariants(),
invariant_zone,
transition->destination_location(&discrete_state));
assert(invariant_satisfiable || invariant_zone.isInCf());
if (invariant_satisfiable) {
invariant_zone.cf();
const clock_set* reset_clocks = transition->reset_clocks();
if (reset_clocks != nullptr) {
invariant_zone.preset(*reset_clocks);
invariant_zone.cf();
}
/* Now perform clock assignments sequentially: perform the
* front assignments first */
const std::vector<std::pair<DBM::size_type, clock_value_t>>* clock_assignments =
transition->clock_assignments();
if (clock_assignments != nullptr) {
// Iterate over the vector and print it
for (const std::pair<DBM::size_type, clock_value_t>& clock_assignment: *clock_assignments) {
invariant_zone.preset(clock_assignment.first, clock_assignment.second);
invariant_zone.cf();
}
}
// invariant_zone corresponds to the invariant.
if (!(guard_zone <= invariant_zone)) {
guard_zone.intersect(invariant_zone);
guard_zone.cf();
if (guard_zone.emptiness()) {
cpplog(cpplogging::debug)
<< "Transition: " << transition
<< " cannot be taken; entering invariant is false." << std::endl
<< "\tExtra invariant condition: " << invariant_zone << std::endl;
continue;
}
transition_placeholder.intersect(invariant_zone);
transition_placeholder.cf();
}
}
assert(invariant_zone.isInCf());
transition->getNewTrans(formula.getQuant());
/* Constraints are bounded by input_pes.max_constant() */
/* This is to extend the LHS to make sure that
* the RHS is satisfied by any zone that satisfies
* the LHS by expanding the zone so it contains
* all the proper regions where the clocks
* exceed a certain constant value. */
guard_zone.bound(input_pes.max_constant());
guard_zone.cf();
// The transition RHS handles resets and substitutions
cpplog(cpplogging::debug)
<< "Executing transition (with destination) " << transition << std::endl;
// use phLHS since the zone is tightened to satisfy
// the invariant
++numLocations;
do_proof_place(discrete_state, guard_zone, &transition_placeholder, *transition->getRightExpr());
transition_placeholder.cf();
DBMList not_invariant_zone(invariant_zone);
!not_invariant_zone;
not_invariant_zone.cf();
!guard_placeholder;
guard_placeholder.cf();
if(transition_placeholder.emptiness() && not_invariant_zone.emptiness() && guard_placeholder.emptiness()) {
place->makeEmpty();
break;
} else {
transition_placeholder.addDBMList(not_invariant_zone); // no need to perform union_ since we intersect anyway
transition_placeholder.addDBMList(guard_placeholder);
place->intersect(transition_placeholder);
place->cf();
// If the placeholder is empty, the property cannot be satisfied
if(place->emptiness()) {
break;
}
}
} else { // !guard_satisfied
cpplog(cpplogging::debug)
<< "Transition: " << transition << " cannot be taken." << std::endl;
}
}
cpplog(cpplogging::debug)
<< "\t --- end of ALLACT. Returned plhold: " << *place << std::endl;
}
inline void prover::do_proof_place_existact(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
DBMList result(INFTYDBM); // DBM to accumulate the result.
result.makeEmpty();
/* Enumerate through all transitions */
cpplog(cpplogging::debug) << "\t Proving EXISTACT Transitions:----\n"
<< std::endl;
for (Transition* const transition: input_pes.transitions()) {
/* Obtain the entire ExprNode and prove it */
DBMList guard_placeholder(*place);
DBM guard_zone(zone);
// Method tightens zone and place to those subsets satisfying the guard
// (leftExpr).
bool guard_satisfied = comp_ph_exist_place(guard_zone, guard_placeholder,
*(transition->guard()), discrete_state);
if (!guard_satisfied) {
cpplog(cpplogging::debug)
<< "Transition: " << transition << " cannot be taken." << std::endl;
continue;
}
/* Now check the invariant of the target location (getEnteringLocation gives
the destination location of the transition */
DBM invariant_region(INFTYDBM);
bool invariant_satisfiable = restrict_to_invariant(
input_pes.invariants(), invariant_region, transition->destination_location(&discrete_state));
if (invariant_satisfiable) { // the invariant does not hold vacuously.
invariant_region.cf();
const clock_set* reset_clocks = transition->reset_clocks();
if (reset_clocks != nullptr) {
invariant_region.preset(*reset_clocks);
invariant_region.cf();
}
/* Now perform clock assignments sequentially: perform the
* front assignments first */
const std::vector<std::pair<DBM::size_type, clock_value_t>>* clock_assignments =
transition->clock_assignments();
if (clock_assignments != nullptr) {
// Iterate over the vector and print it
for (const std::pair<DBM::size_type, clock_value_t>& clock_assignment: *clock_assignments) {
invariant_region.preset(clock_assignment.first, clock_assignment.second);
invariant_region.cf();
}
}
/* Check if invariant preset is satisfied by the zone.
* If not, tighten the placeholder */
// For performace reasons, also tighten the left hand side
if (!(guard_zone <= invariant_region)) {
guard_placeholder.intersect(invariant_region);
guard_placeholder.cf();
if (guard_placeholder.emptiness()) {
cpplog(cpplogging::debug)
<< "Transition: " << transition
<< " cannot be taken; entering invariant is false." << std::endl
<< "\tExtra invariant condition: " << invariant_region << std::endl;
continue;
}
guard_zone.intersect(invariant_region);
guard_zone.cf();
}
}
transition->getNewTrans(formula.getQuant());
/* Constraints are bounded by input_pes.max_constant() */
/* This is to extend the LHS to make sure that
* the RHS is satisfied by any zone that satisfies
* the LHS by expanding the zone so it contains
* all the proper regions where the clocks
* exceed a certain constant value. */
guard_zone.bound(input_pes.max_constant());
guard_zone.cf();
cpplog(cpplogging::debug)
<< "Executing transition (with destination) " << transition << std::endl
<< "\tExtra invariant condition: " << invariant_region << std::endl;
numLocations++;
do_proof_place(discrete_state, guard_zone, &guard_placeholder, *transition->getRightExpr());
guard_placeholder.cf();
result.addDBMList(guard_placeholder); // no union here, it is inefficient; also, no need to make a cf()
//result.cf();
/*if(result >= *place || result >= zone) {
break;
}*/
}
result.cf();
cpplog(cpplogging::debug)
<< "\t --- end of EXISTACT. Returned plhold: " << result
<< std::endl;
place->intersect(result);
}
inline void prover::do_proof_place_imply(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
DBM zone_copy(zone);
/* call comp_ph() for efficient proving of IMPLY's left. */
if (comp_ph(zone_copy, *(formula.getLeft()), discrete_state)) {
/* Constraints are bounded by input_pes.max_constant() */
/* This is to extend the LHS to make sure that
* the RHS is satisfied by any zone that satisfies
* the LHS by expanding the zone so it contains
* all the proper regions where the clocks
* exceed a certain constant value. */
zone_copy.bound(input_pes.max_constant());
zone_copy.cf();
do_proof_place(discrete_state, zone_copy, place, *formula.getRight());
} else {
/* The set of states does not satisfy the premises of the IF
* so thus the proof is true */
cpplog(cpplogging::debug)
<< "---(Valid) Leaf IMPLY Reached, Premise Not Satisfied----"
<< std::endl
<< std::endl;
}
}
inline void prover::do_proof_place_constraint(const DBM& zone,
DBMList* place,
const ExprNode& formula) const {
if (zone <= *(formula.dbm())) {
cpplog(cpplogging::debug) << "---(Valid) Leaf DBM (CONSTRAINT) Reached "
"with no need for Placeholder----"
<< std::endl
<< std::endl;
} else {
/* Here, since we only have a single constraint here,
* DBM will tighten only to match the single constraint
* Since multiple constraints are represented as an
* AND of Constraints */
place->intersect(*(formula.dbm()));
place->cf();
// Test if the constraint is satisfiable within the zone; if not, clear the
// placeholder.
// FIXME: this should be fine if we just use place here (although, strictly
// speaking, the placeholder may become a bit smaller in that case).
DBMList tPlace(*place);
tPlace.intersect(zone);
tPlace.cf();
if (tPlace.emptiness()) {
// New Combined DBM Does not satisfy Constraint
place->makeEmpty();
cpplog(cpplogging::debug)
<< "---(Invalid, Placeholder) Leaf DBM (CONSTRAINT) Unsatisfied "
"regardless of placeholder----"
<< std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "---(Valid, Placeholder) Leaf DBM (CONSTRAINT) Reached and "
"Placeholder Computed----"
<< std::endl
<< "----Placeholder := {" << *place << "}----" << std::endl
<< std::endl;
}
}
}
inline bool prover::do_proof_place_bool(DBMList* place,
const ExprNode& formula) const {
bool retVal = (formula.getBool());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf BOOL Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline bool prover::do_proof_place_atomic(const SubstList& discrete_state,
DBMList* place,
const ExprNode& formula) const {
bool retVal = (discrete_state.at(formula.getAtomic()) == formula.getIntVal());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf ATOMIC == Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline bool prover::do_proof_place_atomic_not(const SubstList& discrete_state,
DBMList* place,
const ExprNode& formula) const {
bool retVal = (discrete_state.at(formula.getAtomic()) != formula.getIntVal());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf ATOMIC != Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline bool prover::do_proof_place_atomic_lt(const SubstList& discrete_state,
DBMList* place,
const ExprNode& formula) const {
bool retVal = (discrete_state.at(formula.getAtomic()) < formula.getIntVal());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf ATOMIC < Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline bool prover::do_proof_place_atomic_gt(const SubstList& discrete_state,
DBMList* place,
const ExprNode& formula) const {
bool retVal = (discrete_state.at(formula.getAtomic()) > formula.getIntVal());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf ATOMIC > Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline bool prover::do_proof_place_atomic_le(const SubstList& discrete_state,
DBMList* place,
const ExprNode& formula) const {
bool retVal = (discrete_state.at(formula.getAtomic()) <= formula.getIntVal());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf ATOMIC < Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline bool prover::do_proof_place_atomic_ge(const SubstList& discrete_state,
DBMList* place,
const ExprNode& formula) const {
bool retVal = (discrete_state.at(formula.getAtomic()) >= formula.getIntVal());
cpplog(cpplogging::debug) << "---(" << (retVal ? "V" : "Inv")
<< "alid) Leaf ATOMIC > Reached----" << std::endl
<< std::endl;
if (!retVal && place != nullptr) {
place->makeEmpty();
}
return retVal;
}
inline void prover::do_proof_place_sublist(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
SubstList st(formula.getSublist(), &discrete_state);
do_proof_place(st, zone, place, *formula.getExpr());
}
inline void prover::do_proof_place_reset(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
DBM lhs_reset(zone);
// JK: It does not become clear why this is necessary here
// lhs_reset.bound(input_pes.max_constant());
// lhs_reset.cf();
lhs_reset.reset(*formula.getClockSet());
lhs_reset.cf();
DBMList placeholder1(INFTYDBM);
do_proof_place(discrete_state, lhs_reset, &placeholder1, *formula.getExpr());
placeholder1.cf();
if (placeholder1.emptiness()) {
place->makeEmpty();
} else {
// Apply the preset (weakest precondition operator)
placeholder1.preset(*formula.getClockSet());
// Use the rule to compute what the old place holder should be
place->intersect(placeholder1);
place->cf();
if (cpplogEnabled(cpplogging::debug)) {
placeholder1.cf();
print_sequent_placeCheck(std::cerr, step - 1, !place->emptiness(), zone, *place, placeholder1,
discrete_state, formula.getOpType());
if (!place->emptiness()) {
cpplog(cpplogging::debug)
<< "----(Valid) Placeholder Check Passed-----" << std::endl
<< "--With Placeholder := {" << *place << "} ----" << std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
}
}
inline void prover::do_proof_place_assign(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
DBM lhs_assign(zone);
/* Here the DBM zone is where the value of
* clock x is reset to clock y, which is possibly
* a constant or a value*/
short int cX = formula.getcX();
short int cY = formula.getcY();
lhs_assign.reset(cX, cY);
lhs_assign.cf();
DBMList placeB(INFTYDBM);
do_proof_place(discrete_state, lhs_assign, &placeB, *formula.getExpr());
placeB.cf();
if (placeB.emptiness()) {
place->makeEmpty();
} else {
// Double Check that the new placeholder follows from the first
placeB.preset(cX, cY);
// Now assign the old placeholder accordingly
place->intersect(placeB);
place->cf();
if (cpplogEnabled(cpplogging::debug)) {
bool retVal = !place->emptiness();
print_sequent_placeCheck(std::cerr, step - 1, retVal, zone, *place, placeB,
discrete_state, formula.getOpType());
if (retVal) {
cpplog(cpplogging::debug)
<< "----(Valid) Placeholder Check Passed-----" << std::endl
<< "--With Placeholder := {" << *place << "} ----" << std::endl
<< std::endl;
} else {
cpplog(cpplogging::debug)
<< "----(Invalid) Placeholder Check Failed-----" << std::endl
<< std::endl;
}
}
}
}
inline void prover::do_proof_place_replace(const SubstList& discrete_state,
const DBM& zone,
DBMList* place,
const ExprNode& formula) {
SubstList sub_(discrete_state);
sub_[formula.getcX()] = discrete_state.at(formula.getcY());
do_proof_place(sub_, zone, place, *formula.getExpr());
}
inline bool prover::do_proof_place_ablewaitinf(const SubstList& discrete_state,
const DBM& zone,
DBMList* place) const {
DBMList ph(zone);
if(place != nullptr) {
ph.intersect(*place);
}
ph.cf();
ph.suc();
restrict_to_invariant(input_pes.invariants(), ph, discrete_state);
ph.cf();
/* Time can diverge if and only if there are no upper bound
* constraints in the successor. By design of succ() and invariants,
* either all DBMs have an upper bound constraint, or none
* of them do. Hence, checking the first is always good enough. */
assert(!ph.empty());
const DBM& firstDBM = *(ph.begin());
bool retVal = !firstDBM.hasUpperConstraint();
if(!retVal && place != nullptr)
{
place->makeEmpty();
}
cpplog(cpplogging::debug)
<< "---(" << (retVal ? "V" : "Inv") << "alid) Time "
<< (retVal ? "" : "un")
<< "able to diverge to INFTY in current location---" << std::endl
<< std::endl;
return retVal;
}
inline bool prover::do_proof_place_unablewaitinf(const SubstList& discrete_state,
const DBM& zone,
DBMList* place) const {
DBMList ph(zone);
if(place != nullptr) {
ph.intersect(*place);
}
ph.cf();
ph.suc();
restrict_to_invariant(input_pes.invariants(), ph, discrete_state);
ph.cf();
/* Time cannot diverge if and only if there is an upper bound
* constraint in the successor. By design of succ() and invariants,
* either all DBMs have an upper bound constraint, or none
* of them do. Hence, checking the first is always good enough. */
assert(!ph.empty());
const DBM& firstDBM = *(ph.begin());
bool retVal = firstDBM.hasUpperConstraint();
if(!retVal && place != nullptr) {
place->makeEmpty();
}
cpplog(cpplogging::debug)
<< "---(" << (retVal ? "V" : "Inv") << "alid) Time "
<< (retVal ? "un" : "")
<< "able to diverge to INFTY in current location---" << std::endl
<< std::endl;
return retVal;
}
#endif /* PROOF_HH */
| 40.102368 | 176 | 0.60669 | jkeiren |
161c3bd38812f910febb041729d9d9625ce01c7e | 1,691 | cpp | C++ | 454 Anagrams.cpp | zihadboss/UVA-Solutions | 020fdcb09da79dc0a0411b04026ce3617c09cd27 | [
"Apache-2.0"
] | 86 | 2016-01-20T11:36:50.000Z | 2022-03-06T19:43:14.000Z | 454 Anagrams.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | null | null | null | 454 Anagrams.cpp | Mehedishihab/UVA-Solutions | 474fe3d9d9ba574b97fd40ca5abb22ada95654a1 | [
"Apache-2.0"
] | 113 | 2015-12-04T06:40:57.000Z | 2022-02-11T02:14:28.000Z | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
bool lexicographic(const string& first, const string& second)
{
return lexicographical_compare(first.begin(), first.end(), second.begin(), second.end());
}
const vector<int> letterBase(128, 0);
vector<int> GetLetterCounts(string word)
{
vector<int> letterCounts(letterBase);
for (string::const_iterator iter = word.begin(); iter != word.end(); ++iter)
{
if (*iter != ' ')
++letterCounts[*iter];
}
return letterCounts;
}
bool Equal(const vector<int>& first, const vector<int>& second)
{
for (int i = 0; i < 128; ++i)
if (first[i] != second[i])
return false;
return true;
}
int main()
{
int T;
cin >> T;
cin.ignore();
string temp;
getline(cin, temp);
string separator = "";
while (T--)
{
vector<string> phrases;
while (getline(cin, temp) && temp != "")
{
phrases.push_back(temp);
}
sort(phrases.begin(), phrases.end(), lexicographic);
vector<vector<int> > letterCounts(phrases.size());
for (int i = 0; i < phrases.size(); ++i)
letterCounts[i] = GetLetterCounts(phrases[i]);
cout << separator;
separator = "\n";
for (int i = 0; i < phrases.size(); ++i)
{
for (int j = i + 1; j < phrases.size(); ++j)
{
if (Equal(letterCounts[i], letterCounts[j]))
cout << phrases[i] << " = " << phrases[j] << '\n';
}
}
}
} | 21.961039 | 93 | 0.506801 | zihadboss |
1621b7ddaa1c3f98bf723935fc741fb89f7865e9 | 553 | cpp | C++ | examples/q13_timer/src/process/faucet.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | examples/q13_timer/src/process/faucet.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | examples/q13_timer/src/process/faucet.cpp | ubc333/library | 069d68e822992950739661f5f7a7bdffe8d425d4 | [
"MIT"
] | null | null | null | #include <string>
#include <iostream>
#include <cpen333/process/event.h>
int main(int argc, char* argv[]) {
if (argc < 4) {
std::cout << "Not enough arguments, needed 3: clock_event_name, id, # drips" << std::endl;
return -1;
}
std::string event_name = argv[1];
int id = atoi(argv[2]);
int drips = atoi(argv[3]);
cpen333::process::event tic(event_name); // create named event
for (int i = 0; i < drips; ++i) {
tic.wait();
std::cout << "Faucet " << id << ": drip" << std::endl;
}
return 0;
} | 23.041667 | 95 | 0.562387 | ubc333 |
16256d643420b1409f162fbda6387fc24e5c7d59 | 632 | hh | C++ | source/fit/KBCurve.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 3 | 2021-05-24T19:43:30.000Z | 2022-01-06T21:03:23.000Z | source/fit/KBCurve.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 4 | 2020-05-04T15:52:26.000Z | 2021-09-13T10:51:03.000Z | source/fit/KBCurve.hh | ggfdsa10/KEBI_AT-TPC | 40e00fcd10d3306b93fff93be5fb0988f87715a7 | [
"MIT"
] | 3 | 2020-06-14T10:53:58.000Z | 2022-01-06T21:03:30.000Z | #ifndef KBCURVE_HH
#define KBCURVE_HH
#include "TGraph.h"
class KBCurve : public TGraph
{
public:
KBCurve();
KBCurve(Int_t nPoints);
virtual ~KBCurve() {};
void SetUnitLength(Double_t unitLength);
Double_t GetUnitLength();
void SetTension(Double_t tension);
Double_t GetTension();
Double_t GetXLow();
Double_t GetXHigh();
void Push(Double_t x, Double_t y, Double_t fx, Double_t fy);
KBCurve *GetDifferentialCurve();
Double_t DistanceToCurve(Double_t x, Double_t y);
private:
Double_t fUnitLength = 1;
Double_t fTension = 0.01;
ClassDef(KBCurve, 1)
};
#endif
| 17.555556 | 64 | 0.681962 | ggfdsa10 |
1625d579a73047472e7de0805adef62f4f4a9354 | 635 | cc | C++ | Code/1199-hexspeak.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 2 | 2019-12-06T14:08:57.000Z | 2020-01-15T15:25:32.000Z | Code/1199-hexspeak.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | 1 | 2020-01-15T16:29:16.000Z | 2020-01-26T12:40:13.000Z | Code/1199-hexspeak.cc | SMartQi/Leetcode | 9e35c65a48ba1ecd5436bbe07dd65f993588766b | [
"MIT"
] | null | null | null | class Solution {
public:
string toHexspeak(string num) {
long long llnum = stoll(num);
string result = "";
while (true) {
int n = llnum % 16;
if (n == 0) {
result = 'O' + result;
} else if (n == 1) {
result = 'I' + result;
} else if (n > 9) {
char c = 'A' + n - 10;
result = c + result;
} else {
return "ERROR";
}
llnum /= 16;
if (llnum == 0) {
return result;
}
}
return result;
}
}; | 25.4 | 38 | 0.344882 | SMartQi |
162d134f7db3456f3d73f91e3d43a5318628459f | 1,578 | hxx | C++ | stdxx/matrix/matrix3op.hxx | JeneLitsch/stdxx | c83fedb802baf523b654b5c39ba03d3425902948 | [
"MIT"
] | 1 | 2022-03-08T10:14:38.000Z | 2022-03-08T10:14:38.000Z | stdxx/matrix/matrix3op.hxx | JeneLitsch/stdxx | c83fedb802baf523b654b5c39ba03d3425902948 | [
"MIT"
] | 1 | 2022-03-11T11:43:31.000Z | 2022-03-11T23:18:06.000Z | stdxx/matrix/matrix3op.hxx | JeneLitsch/stdxx | c83fedb802baf523b654b5c39ba03d3425902948 | [
"MIT"
] | null | null | null | #pragma once
#include "matrix3.hxx"
namespace stx {
template<typename T>
std::ostream & operator<<(std::ostream & out, const matrix3<T> & m) {
out << "[";
for(std::size_t y = 0; y < 3; y++) {
out << (y ? "|" : "");
for(std::size_t x = 0; x < 3; x++) {
out << (x ? "," : "") << m(x,y);
}
}
out << "]";
return out;
}
template<typename T>
constexpr matrix3<T> operator+(const matrix3<T> & l, const matrix3<T> & r) {
matrix3<T> m;
for(std::size_t x = 0; x < 3; x++) {
for(std::size_t y = 0; y < 3; y++) {
m(x,y) = l(x,y) + r(x,y);
}
}
return m;
}
template<typename T>
constexpr matrix3<T> operator-(const matrix3<T> & l, const matrix3<T> & r) {
matrix3<T> m;
for(std::size_t x = 0; x < 3; x++) {
for(std::size_t y = 0; y < 3; y++) {
m(x,y) = l(x,y) - r(x,y);
}
}
return m;
}
template<typename T>
constexpr matrix3<T> operator*(const matrix3<T> & l, const matrix3<T> & r) {
matrix3<T> m;
for(std::size_t x = 0; x < 3; x++) {
for(std::size_t y = 0; y < 3; y++) {
T value = 0;
for(std::size_t i = 0; i < 3; i++) {
value += l(i,y) * r(x,i);
}
m(x,y) = value;
}
}
return m;
}
template<typename T, class Flavor>
constexpr vector3<T, Flavor> operator*(
const matrix3<T> & l,
const vector3<T, Flavor> & r) {
vector3<T, Flavor> v;
v.x += r.x * l(0, 0);
v.x += r.y * l(1, 0);
v.x += r.z * l(2, 0);
v.y += r.x * l(0, 1);
v.y += r.y * l(1, 1);
v.y += r.z * l(2, 1);
v.z += r.x * l(0, 2);
v.z += r.y * l(1, 2);
v.z += r.z * l(2, 2);
return v;
}
} | 21.324324 | 77 | 0.481622 | JeneLitsch |
162d46690fc654b4d7cde774d65c85ed797c068a | 2,321 | hpp | C++ | test/tostring.hpp | magicmoremagic/bengine-texi | e7a6f476ccb85262db8958e39674bc9570956bbe | [
"MIT"
] | null | null | null | test/tostring.hpp | magicmoremagic/bengine-texi | e7a6f476ccb85262db8958e39674bc9570956bbe | [
"MIT"
] | null | null | null | test/tostring.hpp | magicmoremagic/bengine-texi | e7a6f476ccb85262db8958e39674bc9570956bbe | [
"MIT"
] | 1 | 2022-02-19T08:08:21.000Z | 2022-02-19T08:08:21.000Z | #pragma once
#ifndef BE_GFX_CATCH_TOSTRING_HPP_
#define BE_GFX_CATCH_TOSTRING_HPP_
#include <glm/glm.hpp>
#include <be/core/glm.hpp>
#include <be/core/extents.hpp>
#include <sstream>
#include <iomanip>
namespace Catch {
inline std::string toString(const be::RGB& value) {
std::ostringstream oss;
oss << "rgb[ " << (int)value.r << ", " << (int)value.g << ", " << (int)value.b << " ]";
return oss.str();
}
inline std::string toString(const be::RGBA& value) {
std::ostringstream oss;
oss << "rgba[ " << (int)value.r << ", " << (int)value.g << ", " << (int)value.b << ", " << (int)value.a << " ]";
return oss.str();
}
inline std::string toString(const be::vec4& value) {
std::ostringstream oss;
oss << std::scientific << std::setprecision(12) << "vec4(" << value.r << ", " << value.g << ", " << value.b << ", " << value.a << ")";
return oss.str();
}
inline std::string toString(const be::vec3& value) {
std::ostringstream oss;
oss << std::scientific << std::setprecision(12) << "vec3(" << value.r << ", " << value.g << ", " << value.b << ")";
return oss.str();
}
inline std::string toString(const be::vec2& value) {
std::ostringstream oss;
oss << std::scientific << std::setprecision(12) << "vec2(" << value.r << ", " << value.g << ")";
return oss.str();
}
inline std::string toString(const be::ivec4& value) {
std::ostringstream oss;
oss << std::scientific << std::setprecision(12) << "ivec4(" << value.x << ", " << value.y << ", " << value.z << ", " << value.w << ")";
return oss.str();
}
inline std::string toString(const be::ivec3& value) {
std::ostringstream oss;
oss << std::scientific << std::setprecision(12) << "ivec3(" << value.x << ", " << value.y << ", " << value.z << ")";
return oss.str();
}
inline std::string toString(const be::ivec2& value) {
std::ostringstream oss;
oss << std::scientific << std::setprecision(12) << "ivec2(" << value.x << ", " << value.y << ")";
return oss.str();
}
inline std::string toString(const be::ibox& value) {
std::ostringstream oss;
oss << "ibox[ offset(" << value.offset.x << ", " << value.offset.y << ", " << value.offset.z
<< "), dim(" << value.dim.x << ", " << value.dim.y << ", " << value.dim.z << ") ]";
return oss.str();
}
} // Catch
#include <catch/catch.hpp>
#endif
| 31.794521 | 138 | 0.570444 | magicmoremagic |
162ff519ae045b904d687bee4e303bfcf6f5ffcf | 446 | hpp | C++ | include/mamap/arguments/properties/propertystring.hpp | JoshuaSBrown/MAMAP | 0a50455dd6c75726046fc040b0834a9d3273c6eb | [
"MIT"
] | null | null | null | include/mamap/arguments/properties/propertystring.hpp | JoshuaSBrown/MAMAP | 0a50455dd6c75726046fc040b0834a9d3273c6eb | [
"MIT"
] | null | null | null | include/mamap/arguments/properties/propertystring.hpp | JoshuaSBrown/MAMAP | 0a50455dd6c75726046fc040b0834a9d3273c6eb | [
"MIT"
] | 1 | 2020-12-10T05:18:17.000Z | 2020-12-10T05:18:17.000Z |
#ifndef _MAMAP_PROPERTY_STRING_HPP
#define _MAMAP_PROPERTY_STRING_HPP
#include "propertyobject.hpp"
namespace mamap {
class PropertyString : public PropertyObject {
private:
virtual PropertyType getPropertyType_(void) const noexcept final {
return PropertyType::STRING;
}
public:
PropertyString(void);
virtual bool propValid(const std::any& val) final;
};
} // namespace mamap
#endif // _MAMAP_PROPERTY_STRING_HPP
| 18.583333 | 70 | 0.755605 | JoshuaSBrown |
16309c68162ae51f513dd3d7e0021c772f9adb72 | 65,341 | cpp | C++ | libraries/app/application.cpp | totalgames/playchain-core | f543df51d78dafca09c56fbb7b9912ad550a9404 | [
"MIT"
] | 1 | 2019-07-05T14:37:30.000Z | 2019-07-05T14:37:30.000Z | libraries/app/application.cpp | totalgames/playchain-core | f543df51d78dafca09c56fbb7b9912ad550a9404 | [
"MIT"
] | null | null | null | libraries/app/application.cpp | totalgames/playchain-core | f543df51d78dafca09c56fbb7b9912ad550a9404 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2018 Total Games LLC and contributors.
*
* The MIT License
*
* 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 <graphene/app/api.hpp>
#include <graphene/app/api_access.hpp>
#include <graphene/app/application.hpp>
#include <graphene/app/plugin.hpp>
#include <graphene/chain/db_with.hpp>
#include <graphene/chain/genesis_state.hpp>
#include <graphene/chain/protocol/fee_schedule.hpp>
#include <graphene/chain/protocol/types.hpp>
#include <graphene/egenesis/egenesis.hpp>
#include <graphene/net/core_messages.hpp>
#include <graphene/net/exceptions.hpp>
#include <graphene/utilities/key_conversion.hpp>
#include <graphene/chain/worker_evaluator.hpp>
#include <fc/asio.hpp>
#include <fc/io/fstream.hpp>
#include <fc/rpc/api_connection.hpp>
#include <fc/rpc/websocket_api.hpp>
#include <fc/network/resolve.hpp>
#include <fc/crypto/base64.hpp>
#include <boost/filesystem.hpp>
#include <boost/signals2.hpp>
#include <boost/range/algorithm/reverse.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/ini_parser.hpp>
#include <boost/algorithm/string/predicate.hpp>
#include <boost/algorithm/string/classification.hpp>
#include <boost/algorithm/string/split.hpp>
#include <boost/container/flat_set.hpp>
#include <graphene/utilities/git_revision.hpp>
#include <boost/version.hpp>
#include <boost/algorithm/string/replace.hpp>
#include <websocketpp/version.hpp>
#include <iostream>
#include <fc/log/logger.hpp>
#include <fc/log/logger_config.hpp>
#include <fc/log/console_appender.hpp>
#include <fc/log/file_appender.hpp>
#include <fc/log/gelf_appender.hpp>
#include <boost/range/adaptor/reversed.hpp>
#include <boost/asio/ip/host_name.hpp>
#include <playchain/chain/playchain_config.hpp>
namespace graphene { namespace app {
using net::item_hash_t;
using net::item_id;
using net::message;
using net::block_message;
using net::trx_message;
using chain::block_header;
using chain::signed_block_header;
using chain::signed_block;
using chain::block_id_type;
using std::vector;
namespace bpo = boost::program_options;
namespace detail {
genesis_state_type create_example_genesis() {
auto witness_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("init")));
auto nathan_key = fc::ecc::private_key::regenerate(fc::sha256::hash(string("nathan")));
dlog("Allocating all stake to ${key}", ("key", utilities::key_to_wif(nathan_key)));
genesis_state_type initial_state;
initial_state.initial_parameters.get_mutable_fees() = fee_schedule::get_default();
initial_state.initial_active_witnesses = GRAPHENE_DEFAULT_MIN_WITNESS_COUNT;
initial_state.initial_timestamp = time_point_sec(time_point::now().sec_since_epoch() /
initial_state.initial_parameters.block_interval *
initial_state.initial_parameters.block_interval);
for( uint64_t i = 0; i < initial_state.initial_active_witnesses; ++i )
{
auto name = "init"+fc::to_string(i);
initial_state.initial_accounts.emplace_back(name,
witness_key.get_public_key(),
witness_key.get_public_key(),
true);
initial_state.initial_committee_candidates.push_back({name});
initial_state.initial_witness_candidates.push_back({name, witness_key.get_public_key()});
}
initial_state.initial_accounts.emplace_back("nathan",
nathan_key.get_public_key(),
nathan_key.get_public_key(),
false);
initial_state.initial_balances.push_back({nathan_key.get_public_key(),
GRAPHENE_SYMBOL,
GRAPHENE_MAX_SHARE_SUPPLY});
initial_state.initial_chain_id = fc::sha256::hash( "BOGUS" );
return initial_state;
}
}
}}
#include "application_impl.hxx"
namespace graphene { namespace app { namespace detail {
void application_impl::reset_p2p_node(const fc::path& data_dir, const seeds_type &external_seeds)
{ try {
_p2p_network = std::make_shared<net::node>("BitShares Reference Implementation");
_p2p_network->load_configuration(data_dir / "p2p");
_p2p_network->set_node_delegate(this);
std::set<string> uniq_seeds;
if( _options->count("seed-node") )
{
auto seeds = _options->at("seed-node").as<vector<string>>();
for( const string& endpoint_string : seeds )
{
uniq_seeds.emplace(endpoint_string);
}
}
if( _options->count("seed-nodes") )
{
auto seeds_str = _options->at("seed-nodes").as<string>();
auto seeds = fc::json::from_string(seeds_str).as<vector<string>>(2);
for( const string& endpoint_string : seeds )
{
uniq_seeds.emplace(endpoint_string);
}
}
else
{
vector<string> seeds = {
// TODO: Embeded defaults
};
for( const string& endpoint_string : seeds )
{
uniq_seeds.emplace(endpoint_string);
}
}
for( const string& endpoint_string : external_seeds )
{
uniq_seeds.emplace(endpoint_string);
}
for(const auto &endpoint_string: uniq_seeds)
{
try {
std::vector<fc::ip::endpoint> endpoints = resolve_string_to_ip_endpoints(endpoint_string);
for (const fc::ip::endpoint& endpoint : endpoints)
{
ilog("Adding seed node ${endpoint}", ("endpoint", endpoint));
_p2p_network->add_node(endpoint);
}
} catch( const fc::exception& e ) {
wlog( "caught exception ${e} while adding seed node ${endpoint}",
("e", e.to_detail_string())("endpoint", endpoint_string) );
}
}
if( _options->count("p2p-endpoint") )
_p2p_network->listen_on_endpoint(fc::ip::endpoint::from_string(_options->at("p2p-endpoint").as<string>()), true);
else
_p2p_network->listen_on_port(0, false);
_p2p_network->listen_to_p2p_network();
ilog("Configured p2p node to listen on ${ip}", ("ip", _p2p_network->get_actual_listening_endpoint()));
_p2p_network->connect_to_p2p_network();
_p2p_network->sync_from(net::item_id(net::core_message_type_enum::block_message_type,
_chain_db->head_block_id()),
std::vector<uint32_t>());
} FC_CAPTURE_AND_RETHROW() }
std::vector<fc::ip::endpoint> application_impl::resolve_string_to_ip_endpoints(const std::string& endpoint_string)
{
try
{
string::size_type colon_pos = endpoint_string.find(':');
if (colon_pos == std::string::npos)
FC_THROW("Missing required port number in endpoint string \"${endpoint_string}\"",
("endpoint_string", endpoint_string));
std::string port_string = endpoint_string.substr(colon_pos + 1);
try
{
uint16_t port = boost::lexical_cast<uint16_t>(port_string);
std::string hostname = endpoint_string.substr(0, colon_pos);
std::vector<fc::ip::endpoint> endpoints = fc::resolve(hostname, port);
if (endpoints.empty())
FC_THROW_EXCEPTION( fc::unknown_host_exception,
"The host name can not be resolved: ${hostname}",
("hostname", hostname) );
return endpoints;
}
catch (const boost::bad_lexical_cast&)
{
FC_THROW("Bad port: ${port}", ("port", port_string));
}
}
FC_CAPTURE_AND_RETHROW((endpoint_string))
}
void application_impl::new_connection( const fc::http::websocket_connection_ptr& c )
{
auto wsc = std::make_shared<fc::rpc::websocket_api_connection>(*c, GRAPHENE_NET_MAX_NESTED_OBJECTS);
auto login = std::make_shared<graphene::app::login_api>( std::ref(*_self) );
login->enable_api("database_api");
wsc->register_api(login->database());
wsc->register_api(fc::api<graphene::app::login_api>(login));
c->set_session_data( wsc );
std::string username = "*";
std::string password = "*";
// Try to extract login information from "Authorization" header if present
std::string auth = c->get_request_header("Authorization");
if( boost::starts_with(auth, "Basic ") ) {
FC_ASSERT( auth.size() > 6 );
auto user_pass = fc::base64_decode(auth.substr(6));
std::vector<std::string> parts;
boost::split( parts, user_pass, boost::is_any_of(":") );
FC_ASSERT(parts.size() == 2);
username = parts[0];
password = parts[1];
}
login->login(username, password);
}
void application_impl::reset_websocket_server()
{ try {
if( !_options->count("rpc-endpoint") )
return;
_websocket_server = std::make_shared<fc::http::websocket_server>();
_websocket_server->on_connection( std::bind(&application_impl::new_connection, this, std::placeholders::_1) );
ilog("Configured websocket rpc to listen on ${ip}", ("ip",_options->at("rpc-endpoint").as<string>()));
_websocket_server->listen( fc::ip::endpoint::from_string(_options->at("rpc-endpoint").as<string>()) );
_websocket_server->start_accept();
} FC_CAPTURE_AND_RETHROW() }
void application_impl::reset_websocket_tls_server()
{ try {
if( !_options->count("rpc-tls-endpoint") )
return;
if( !_options->count("server-pem") )
{
wlog( "Please specify a server-pem to use rpc-tls-endpoint" );
return;
}
string password = _options->count("server-pem-password") ? _options->at("server-pem-password").as<string>() : "";
_websocket_tls_server = std::make_shared<fc::http::websocket_tls_server>( _options->at("server-pem").as<string>(), password );
_websocket_tls_server->on_connection( std::bind(&application_impl::new_connection, this, std::placeholders::_1) );
ilog("Configured websocket TLS rpc to listen on ${ip}", ("ip",_options->at("rpc-tls-endpoint").as<string>()));
_websocket_tls_server->listen( fc::ip::endpoint::from_string(_options->at("rpc-tls-endpoint").as<string>()) );
_websocket_tls_server->start_accept();
} FC_CAPTURE_AND_RETHROW() }
void application_impl::set_dbg_init_key( graphene::chain::genesis_state_type& genesis, const std::string& init_key )
{
flat_set< std::string > initial_witness_names;
public_key_type init_pubkey( init_key );
for( uint64_t i=0; i<genesis.initial_active_witnesses; i++ )
genesis.initial_witness_candidates[i].block_signing_key = init_pubkey;
}
void application_impl::set_api_limit() {
if (_options->count("api-limit-get-account-history-operations")) {
_app_options.api_limit_get_account_history_operations = _options->at("api-limit-get-account-history-operations").as<uint64_t>();
}
if(_options->count("api-limit-get-account-history")){
_app_options.api_limit_get_account_history = _options->at("api-limit-get-account-history").as<uint64_t>();
}
if(_options->count("api-limit-get-grouped-limit-orders")){
_app_options.api_limit_get_grouped_limit_orders = _options->at("api-limit-get-grouped-limit-orders").as<uint64_t>();
}
if(_options->count("api-limit-get-relative-account-history")){
_app_options.api_limit_get_relative_account_history = _options->at("api-limit-get-relative-account-history").as<uint64_t>();
}
if(_options->count("api-limit-get-account-history-by-operations")){
_app_options.api_limit_get_account_history_by_operations = _options->at("api-limit-get-account-history-by-operations").as<uint64_t>();
}
if(_options->count("api-limit-get-asset-holders")){
_app_options.api_limit_get_asset_holders = _options->at("api-limit-get-asset-holders").as<uint64_t>();
}
if(_options->count("api-limit-get-key-references")){
_app_options.api_limit_get_key_references = _options->at("api-limit-get-key-references").as<uint64_t>();
}
if(_options->count("api-limit-get-htlc-by")) {
_app_options.api_limit_get_htlc_by = _options->at("api-limit-get-htlc-by").as<uint64_t>();
}
}
void application_impl::startup(const seeds_type &external_seeds)
{ try {
fc::create_directories(_data_dir / "blockchain");
auto initial_state = [this] {
ilog("Initializing database...");
if( _options->count("genesis-json") )
{
std::string genesis_str;
fc::read_file_contents( _options->at("genesis-json").as<boost::filesystem::path>(), genesis_str );
graphene::chain::genesis_state_type genesis = fc::json::from_string( genesis_str ).as<graphene::chain::genesis_state_type>( 20 );
bool modified_genesis = false;
if( _options->count("genesis-timestamp") )
{
genesis.initial_timestamp = fc::time_point_sec( fc::time_point::now() )
+ genesis.initial_parameters.block_interval
+ _options->at("genesis-timestamp").as<uint32_t>();
genesis.initial_timestamp -= ( genesis.initial_timestamp.sec_since_epoch()
% genesis.initial_parameters.block_interval );
modified_genesis = true;
ilog(
"Used genesis timestamp: ${timestamp} (PLEASE RECORD THIS)",
("timestamp", genesis.initial_timestamp.to_iso_string())
);
}
if( _options->count("dbg-init-key") )
{
std::string init_key = _options->at( "dbg-init-key" ).as<string>();
FC_ASSERT( genesis.initial_witness_candidates.size() >= genesis.initial_active_witnesses );
set_dbg_init_key( genesis, init_key );
modified_genesis = true;
ilog("Set init witness key to ${init_key}", ("init_key", init_key));
}
if( modified_genesis )
{
wlog("WARNING: GENESIS WAS MODIFIED, YOUR CHAIN ID MAY BE DIFFERENT");
genesis_str += "BOGUS";
genesis.initial_chain_id = fc::sha256::hash( genesis_str );
}
else
genesis.initial_chain_id = fc::sha256::hash( genesis_str );
return genesis;
}
else
{
std::string egenesis_json;
graphene::egenesis::compute_egenesis_json( egenesis_json );
FC_ASSERT( egenesis_json != "" );
FC_ASSERT( graphene::egenesis::get_egenesis_json_hash() == fc::sha256::hash( egenesis_json ) );
auto genesis = fc::json::from_string( egenesis_json ).as<graphene::chain::genesis_state_type>( 20 );
genesis.initial_chain_id = fc::sha256::hash( egenesis_json );
return genesis;
}
};
if( _options->count("resync-blockchain") )
_chain_db->wipe(_data_dir / "blockchain", true);
flat_map<uint32_t,block_id_type> loaded_checkpoints;
if( _options->count("checkpoint") )
{
auto cps = _options->at("checkpoint").as<vector<string>>();
loaded_checkpoints.reserve( cps.size() );
for( auto cp : cps )
{
auto item = fc::json::from_string(cp).as<std::pair<uint32_t,block_id_type> >( 2 );
loaded_checkpoints[item.first] = item.second;
}
}
_chain_db->add_checkpoints( loaded_checkpoints );
if( _options->count("enable-standby-votes-tracking") )
{
_chain_db->enable_standby_votes_tracking( _options->at("enable-standby-votes-tracking").as<bool>() );
}
if( _options->count("replay-blockchain") || _options->count("revalidate-blockchain") )
_chain_db->wipe( _data_dir / "blockchain", false );
try
{
// these flags are used in open() only, i. e. during replay
uint32_t skip;
if( _options->count("revalidate-blockchain") ) // see also handle_block()
{
if( !loaded_checkpoints.empty() )
wlog( "Warning - revalidate will not validate before last checkpoint" );
if( _options->count("force-validate") )
skip = graphene::chain::database::skip_nothing;
else
skip = graphene::chain::database::skip_transaction_signatures;
}
else // no revalidate, skip most checks
skip = graphene::chain::database::skip_witness_signature |
graphene::chain::database::skip_block_size_check |
graphene::chain::database::skip_merkle_check |
graphene::chain::database::skip_transaction_signatures |
graphene::chain::database::skip_transaction_dupe_check |
graphene::chain::database::skip_tapos_check |
graphene::chain::database::skip_witness_schedule_check;
graphene::chain::detail::with_skip_flags( *_chain_db, skip, [this,&initial_state] () {
_chain_db->open( _data_dir / "blockchain", initial_state, GRAPHENE_CURRENT_DB_VERSION );
});
}
catch( const fc::exception& e )
{
elog( "Caught exception ${e} in open(), you might want to force a replay", ("e", e.to_detail_string()) );
throw;
}
if( _options->count("force-validate") )
{
ilog( "All transaction signatures will be validated" );
_force_validate = true;
}
if ( _options->count("enable-subscribe-to-all") )
_app_options.enable_subscribe_to_all = _options->at( "enable-subscribe-to-all" ).as<bool>();
set_api_limit();
if( _active_plugins.find( "market_history" ) != _active_plugins.end() )
_app_options.has_market_history_plugin = true;
if( _options->count("api-access") ) {
fc::path api_access_file = _options->at("api-access").as<boost::filesystem::path>();
FC_ASSERT( fc::exists(api_access_file),
"Failed to load file from ${path}", ("path", api_access_file) );
_apiaccess = fc::json::from_file( api_access_file ).as<api_access>( 20 );
ilog( "Using api access file from ${path}",
("path", api_access_file) );
}
else
{
// TODO: Remove this generous default access policy
// when the UI logs in properly
_apiaccess = api_access();
api_access_info wild_access;
wild_access.password_hash_b64 = "*";
wild_access.password_salt_b64 = "*";
wild_access.allowed_apis.push_back( "database_api" );
wild_access.allowed_apis.push_back( "playchain_api" );
wild_access.allowed_apis.push_back( "network_broadcast_api" );
wild_access.allowed_apis.push_back( "history_api" );
wild_access.allowed_apis.push_back( "orders_api" );
_apiaccess.permission_map["*"] = wild_access;
}
reset_p2p_node(_data_dir, external_seeds);
reset_websocket_server();
reset_websocket_tls_server();
} FC_LOG_AND_RETHROW() }
optional< api_access_info > application_impl::get_api_access_info(const string& username)const
{
optional< api_access_info > result;
auto it = _apiaccess.permission_map.find(username);
if( it == _apiaccess.permission_map.end() )
{
it = _apiaccess.permission_map.find("*");
if( it == _apiaccess.permission_map.end() )
return result;
}
return it->second;
}
void application_impl::set_api_access_info(const string& username, api_access_info&& permissions)
{
_apiaccess.permission_map.insert(std::make_pair(username, std::move(permissions)));
}
/**
* If delegate has the item, the network has no need to fetch it.
*/
bool application_impl::has_item(const net::item_id& id)
{
try
{
if( id.item_type == graphene::net::block_message_type )
return _chain_db->is_known_block(id.item_hash);
else
return _chain_db->is_known_transaction(id.item_hash);
}
FC_CAPTURE_AND_RETHROW( (id) )
}
/**
* @brief allows the application to validate an item prior to broadcasting to peers.
*
* @param sync_mode true if the message was fetched through the sync process, false during normal operation
* @returns true if this message caused the blockchain to switch forks, false if it did not
*
* @throws exception if error validating the item, otherwise the item is safe to broadcast on.
*/
bool application_impl::handle_block(const graphene::net::block_message& blk_msg, bool sync_mode,
std::vector<fc::uint160_t>& contained_transaction_message_ids)
{ try {
auto latency = fc::time_point::now() - blk_msg.block.timestamp;
if (sync_mode && blk_msg.block.block_num() % 5000 == 0)
{
ilog("Sync block: #${n} time: ${t}",
("n", blk_msg.block.block_num())
("t", blk_msg.block.timestamp));
}
else if (!sync_mode || blk_msg.block.block_num() % 10000 == 0)
{
const auto& witness = blk_msg.block.witness(*_chain_db);
const auto& witness_account = witness.witness_account(*_chain_db);
auto last_irr = _chain_db->get_dynamic_global_properties().last_irreversible_block_num;
string block_mark = (!sync_mode)?"Got block":"Sync block";
ilog("${mark}: #${n} time: ${t} latency: ${l} ms from: ${w} irreversible: ${i} (-${d})",
("mark", block_mark)
("t", blk_msg.block.timestamp)
("n", blk_msg.block.block_num())
("l", (latency.count()/1000))
("w",witness_account.name)
("i",last_irr)("d",blk_msg.block.block_num()-last_irr) );
}
FC_ASSERT( (latency.count()/1000) > -5000, "Rejecting block with timestamp in the future" );
try {
const uint32_t skip = (_is_block_producer | _force_validate) ?
database::skip_nothing : database::skip_transaction_signatures;
#if 1 // TODO: precompute_parallel causes the application thread HARD freezing during synchronization
bool result = _chain_db->push_block( blk_msg.block, skip );
#else
bool result = valve.do_serial( [this,&blk_msg,skip] () {
_chain_db->precompute_parallel( blk_msg.block, skip ).wait();
}, [this,&blk_msg,skip] () {
// TODO: in the case where this block is valid but on a fork that's too old for us to switch to,
// you can help the network code out by throwing a block_older_than_undo_history exception.
// when the net code sees that, it will stop trying to push blocks from that chain, but
// leave that peer connected so that they can get sync blocks from us
return _chain_db->push_block( blk_msg.block, skip );
});
#endif
// the block was accepted, so we now know all of the transactions contained in the block
if (!sync_mode)
{
// if we're not in sync mode, there's a chance we will be seeing some transactions
// included in blocks before we see the free-floating transaction itself. If that
// happens, there's no reason to fetch the transactions, so construct a list of the
// transaction message ids we no longer need.
// during sync, it is unlikely that we'll see any old
contained_transaction_message_ids.reserve( contained_transaction_message_ids.size()
+ blk_msg.block.transactions.size() );
for (const processed_transaction& transaction : blk_msg.block.transactions)
{
graphene::net::trx_message transaction_message(transaction);
contained_transaction_message_ids.emplace_back(graphene::net::message(transaction_message).id());
}
}
return result;
} catch ( const graphene::chain::unlinkable_block_exception& e ) {
// translate to a graphene::net exception
elog("Error when pushing block:\n${e}", ("e", e.to_detail_string()));
FC_THROW_EXCEPTION( graphene::net::unlinkable_block_exception,
"Error when pushing block:\n${e}",
("e", e.to_detail_string()) );
} catch( const fc::exception& e ) {
elog("Error when pushing block:\n${e}", ("e", e.to_detail_string()));
throw;
}
if( !_is_finished_syncing && !sync_mode )
{
_is_finished_syncing = true;
_self->syncing_finished();
}
} FC_CAPTURE_AND_RETHROW( (blk_msg)(sync_mode) ) return false; }
void application_impl::handle_transaction(const graphene::net::trx_message& transaction_message)
{ try {
static fc::time_point last_call;
static int trx_count = 0;
++trx_count;
auto now = fc::time_point::now();
if( now - last_call > fc::seconds(1) ) {
ilog("Got ${c} transactions from network", ("c",trx_count) );
last_call = now;
trx_count = 0;
}
_chain_db->precompute_parallel( transaction_message.trx ).wait();
_chain_db->push_transaction( transaction_message.trx );
} FC_CAPTURE_AND_RETHROW( (transaction_message) ) }
void application_impl::handle_message(const message& message_to_process)
{
// not a transaction, not a block
FC_THROW( "Invalid Message Type" );
}
bool application_impl::is_included_block(const block_id_type& block_id)
{
uint32_t block_num = block_header::num_from_id(block_id);
block_id_type block_id_in_preferred_chain = _chain_db->get_block_id_for_num(block_num);
return block_id == block_id_in_preferred_chain;
}
/**
* Assuming all data elements are ordered in some way, this method should
* return up to limit ids that occur *after* the last ID in synopsis that
* we recognize.
*
* On return, remaining_item_count will be set to the number of items
* in our blockchain after the last item returned in the result,
* or 0 if the result contains the last item in the blockchain
*/
std::vector<item_hash_t> application_impl::get_block_ids(const std::vector<item_hash_t>& blockchain_synopsis,
uint32_t& remaining_item_count,
uint32_t limit)
{ try {
vector<block_id_type> result;
remaining_item_count = 0;
if( _chain_db->head_block_num() == 0 )
return result;
result.reserve(limit);
block_id_type last_known_block_id;
if (blockchain_synopsis.empty() ||
(blockchain_synopsis.size() == 1 && blockchain_synopsis[0] == block_id_type()))
{
// peer has sent us an empty synopsis meaning they have no blocks.
// A bug in old versions would cause them to send a synopsis containing block 000000000
// when they had an empty blockchain, so pretend they sent the right thing here.
// do nothing, leave last_known_block_id set to zero
}
else
{
bool found_a_block_in_synopsis = false;
for (const item_hash_t& block_id_in_synopsis : boost::adaptors::reverse(blockchain_synopsis))
if (block_id_in_synopsis == block_id_type() ||
(_chain_db->is_known_block(block_id_in_synopsis) && is_included_block(block_id_in_synopsis)))
{
last_known_block_id = block_id_in_synopsis;
found_a_block_in_synopsis = true;
break;
}
if (!found_a_block_in_synopsis)
FC_THROW_EXCEPTION( graphene::net::peer_is_on_an_unreachable_fork,
"Unable to provide a list of blocks starting at any of the blocks in peer's synopsis" );
}
for( uint32_t num = block_header::num_from_id(last_known_block_id);
num <= _chain_db->head_block_num() && result.size() < limit;
++num )
if( num > 0 )
result.push_back(_chain_db->get_block_id_for_num(num));
if( !result.empty() && block_header::num_from_id(result.back()) < _chain_db->head_block_num() )
remaining_item_count = _chain_db->head_block_num() - block_header::num_from_id(result.back());
return result;
} FC_CAPTURE_AND_RETHROW( (blockchain_synopsis)(remaining_item_count)(limit) ) }
/**
* Given the hash of the requested data, fetch the body.
*/
message application_impl::get_item(const item_id& id)
{ try {
// ilog("Request for item ${id}", ("id", id));
if( id.item_type == graphene::net::block_message_type )
{
auto opt_block = _chain_db->fetch_block_by_id(id.item_hash);
if( !opt_block )
elog("Couldn't find block ${id} -- corresponding ID in our chain is ${id2}",
("id", id.item_hash)("id2", _chain_db->get_block_id_for_num(block_header::num_from_id(id.item_hash))));
FC_ASSERT( opt_block.valid() );
// ilog("Serving up block #${num}", ("num", opt_block->block_num()));
return block_message(std::move(*opt_block));
}
return trx_message( _chain_db->get_recent_transaction( id.item_hash ) );
} FC_CAPTURE_AND_RETHROW( (id) ) }
chain_id_type application_impl::get_chain_id() const
{
return _chain_db->get_chain_id();
}
/**
* Returns a synopsis of the blockchain used for syncing. This consists of a list of
* block hashes at intervals exponentially increasing towards the genesis block.
* When syncing to a peer, the peer uses this data to determine if we're on the same
* fork as they are, and if not, what blocks they need to send us to get us on their
* fork.
*
* In the over-simplified case, this is a straighforward synopsis of our current
* preferred blockchain; when we first connect up to a peer, this is what we will be sending.
* It looks like this:
* If the blockchain is empty, it will return the empty list.
* If the blockchain has one block, it will return a list containing just that block.
* If it contains more than one block:
* the first element in the list will be the hash of the highest numbered block that
* we cannot undo
* the second element will be the hash of an item at the half way point in the undoable
* segment of the blockchain
* the third will be ~3/4 of the way through the undoable segment of the block chain
* the fourth will be at ~7/8...
* &c.
* the last item in the list will be the hash of the most recent block on our preferred chain
* so if the blockchain had 26 blocks labeled a - z, the synopsis would be:
* a n u x z
* the idea being that by sending a small (<30) number of block ids, we can summarize a huge
* blockchain. The block ids are more dense near the end of the chain where because we are
* more likely to be almost in sync when we first connect, and forks are likely to be short.
* If the peer we're syncing with in our example is on a fork that started at block 'v',
* then they will reply to our synopsis with a list of all blocks starting from block 'u',
* the last block they know that we had in common.
*
* In the real code, there are several complications.
*
* First, as an optimization, we don't usually send a synopsis of the entire blockchain, we
* send a synopsis of only the segment of the blockchain that we have undo data for. If their
* fork doesn't build off of something in our undo history, we would be unable to switch, so there's
* no reason to fetch the blocks.
*
* Second, when a peer replies to our initial synopsis and gives us a list of the blocks they think
* we are missing, they only send a chunk of a few thousand blocks at once. After we get those
* block ids, we need to request more blocks by sending another synopsis (we can't just say "send me
* the next 2000 ids" because they may have switched forks themselves and they don't track what
* they've sent us). For faster performance, we want to get a fairly long list of block ids first,
* then start downloading the blocks.
* The peer doesn't handle these follow-up block id requests any different from the initial request;
* it treats the synopsis we send as our blockchain and bases its response entirely off that. So to
* get the response we want (the next chunk of block ids following the last one they sent us, or,
* failing that, the shortest fork off of the last list of block ids they sent), we need to construct
* a synopsis as if our blockchain was made up of:
* 1. the blocks in our block chain up to the fork point (if there is a fork) or the head block (if no fork)
* 2. the blocks we've already pushed from their fork (if there's a fork)
* 3. the block ids they've previously sent us
* Segment 3 is handled in the p2p code, it just tells us the number of blocks it has (in
* number_of_blocks_after_reference_point) so we can leave space in the synopsis for them.
* We're responsible for constructing the synopsis of Segments 1 and 2 from our active blockchain and
* fork database. The reference_point parameter is the last block from that peer that has been
* successfully pushed to the blockchain, so that tells us whether the peer is on a fork or on
* the main chain.
*/
std::vector<item_hash_t> application_impl::get_blockchain_synopsis(const item_hash_t& reference_point,
uint32_t number_of_blocks_after_reference_point)
{ try {
std::vector<item_hash_t> synopsis;
synopsis.reserve(30);
uint32_t high_block_num;
uint32_t non_fork_high_block_num;
uint32_t low_block_num = _chain_db->last_non_undoable_block_num();
std::vector<block_id_type> fork_history;
if (reference_point != item_hash_t())
{
// the node is asking for a summary of the block chain up to a specified
// block, which may or may not be on a fork
// for now, assume it's not on a fork
if (is_included_block(reference_point))
{
// reference_point is a block we know about and is on the main chain
uint32_t reference_point_block_num = block_header::num_from_id(reference_point);
assert(reference_point_block_num > 0);
high_block_num = reference_point_block_num;
non_fork_high_block_num = high_block_num;
if (reference_point_block_num < low_block_num)
{
// we're on the same fork (at least as far as reference_point) but we've passed
// reference point and could no longer undo that far if we diverged after that
// block. This should probably only happen due to a race condition where
// the network thread calls this function, and then immediately pushes a bunch of blocks,
// then the main thread finally processes this function.
// with the current framework, there's not much we can do to tell the network
// thread what our current head block is, so we'll just pretend that
// our head is actually the reference point.
// this *may* enable us to fetch blocks that we're unable to push, but that should
// be a rare case (and correctly handled)
low_block_num = reference_point_block_num;
}
}
else
{
// block is a block we know about, but it is on a fork
try
{
fork_history = _chain_db->get_block_ids_on_fork(reference_point);
// returns a vector where the last element is the common ancestor with the preferred chain,
// and the first element is the reference point you passed in
assert(fork_history.size() >= 2);
if( fork_history.front() != reference_point )
{
edump( (fork_history)(reference_point) );
assert(fork_history.front() == reference_point);
}
block_id_type last_non_fork_block = fork_history.back();
fork_history.pop_back(); // remove the common ancestor
boost::reverse(fork_history);
if (last_non_fork_block == block_id_type()) // if the fork goes all the way back to genesis (does graphene's fork db allow this?)
non_fork_high_block_num = 0;
else
non_fork_high_block_num = block_header::num_from_id(last_non_fork_block);
high_block_num = non_fork_high_block_num + fork_history.size();
assert(high_block_num == block_header::num_from_id(fork_history.back()));
}
catch (const fc::exception& e)
{
// unable to get fork history for some reason. maybe not linked?
// we can't return a synopsis of its chain
elog( "Unable to construct a blockchain synopsis for reference hash ${hash}: ${exception}",
("hash", reference_point)("exception", e) );
throw;
}
if (non_fork_high_block_num < low_block_num)
{
wlog("Unable to generate a usable synopsis because the peer we're generating it for forked too long ago "
"(our chains diverge after block #${non_fork_high_block_num} but only undoable to block #${low_block_num})",
("low_block_num", low_block_num)
("non_fork_high_block_num", non_fork_high_block_num));
FC_THROW_EXCEPTION(graphene::net::block_older_than_undo_history, "Peer is are on a fork I'm unable to switch to");
}
}
}
else
{
// no reference point specified, summarize the whole block chain
high_block_num = _chain_db->head_block_num();
non_fork_high_block_num = high_block_num;
if (high_block_num == 0)
return synopsis; // we have no blocks
}
if( low_block_num == 0)
low_block_num = 1;
// at this point:
// low_block_num is the block before the first block we can undo,
// non_fork_high_block_num is the block before the fork (if the peer is on a fork, or otherwise it is the same as high_block_num)
// high_block_num is the block number of the reference block, or the end of the chain if no reference provided
// true_high_block_num is the ending block number after the network code appends any item ids it
// knows about that we don't
uint32_t true_high_block_num = high_block_num + number_of_blocks_after_reference_point;
do
{
// for each block in the synopsis, figure out where to pull the block id from.
// if it's <= non_fork_high_block_num, we grab it from the main blockchain;
// if it's not, we pull it from the fork history
if (low_block_num <= non_fork_high_block_num)
synopsis.push_back(_chain_db->get_block_id_for_num(low_block_num));
else
synopsis.push_back(fork_history[low_block_num - non_fork_high_block_num - 1]);
low_block_num += (true_high_block_num - low_block_num + 2) / 2;
}
while (low_block_num <= high_block_num);
//idump((synopsis));
return synopsis;
} FC_CAPTURE_AND_RETHROW() }
/**
* Call this after the call to handle_message succeeds.
*
* @param item_type the type of the item we're synchronizing, will be the same as item passed to the sync_from() call
* @param item_count the number of items known to the node that haven't been sent to handle_item() yet.
* After `item_count` more calls to handle_item(), the node will be in sync
*/
void application_impl::sync_status(uint32_t item_type, uint32_t item_count)
{
// any status reports to GUI go here
}
/**
* Call any time the number of connected peers changes.
*/
void application_impl::connection_count_changed(uint32_t c)
{
// any status reports to GUI go here
}
uint32_t application_impl::get_block_number(const item_hash_t& block_id)
{ try {
return block_header::num_from_id(block_id);
} FC_CAPTURE_AND_RETHROW( (block_id) ) }
/**
* Returns the time a block was produced (if block_id = 0, returns genesis time).
* If we don't know about the block, returns time_point_sec::min()
*/
fc::time_point_sec application_impl::get_block_time(const item_hash_t& block_id)
{ try {
auto opt_block = _chain_db->fetch_block_by_id( block_id );
if( opt_block.valid() ) return opt_block->timestamp;
return fc::time_point_sec::min();
} FC_CAPTURE_AND_RETHROW( (block_id) ) }
item_hash_t application_impl::get_head_block_id() const
{
return _chain_db->head_block_id();
}
uint32_t application_impl::estimate_last_known_fork_from_git_revision_timestamp(uint32_t unix_timestamp) const
{
return 0; // there are no forks in graphene
}
void application_impl::error_encountered(const std::string& message, const fc::oexception& error)
{
// notify GUI or something cool
}
uint8_t application_impl::get_current_block_interval_in_seconds() const
{
return _chain_db->get_global_properties().parameters.block_interval;
}
} } } // namespace graphene namespace app namespace detail
namespace graphene { namespace app {
application::application()
: my(new detail::application_impl(this))
{}
application::~application()
{
if( my->_p2p_network )
{
my->_p2p_network->close();
my->_p2p_network.reset();
}
if( my->_chain_db )
{
my->_chain_db->close();
}
}
void application::set_program_options(boost::program_options::options_description& command_line_options,
boost::program_options::options_description& configuration_file_options) const
{
configuration_file_options.add_options()
("data-dir,d", bpo::value<boost::filesystem::path>()->default_value("playchain_node_data"),
"Directory containing databases, logs, etc.")
("p2p-endpoint", bpo::value<string>(), "Endpoint for P2P node to listen on")
("seed-node,s", bpo::value<vector<string>>()->composing(),
"P2P nodes to connect to on startup (may specify multiple times)")
("seed-nodes", bpo::value<string>()->composing(),
"JSON array of P2P nodes to connect to on startup")
("checkpoint,c", bpo::value<vector<string>>()->composing(),
"Pairs of [BLOCK_NUM,BLOCK_ID] that should be enforced as checkpoints.")
("rpc-endpoint", bpo::value<string>()->implicit_value("127.0.0.1:8090"),
"Endpoint for websocket RPC to listen on")
("rpc-tls-endpoint", bpo::value<string>()->implicit_value("127.0.0.1:8089"),
"Endpoint for TLS websocket RPC to listen on")
("server-pem,p", bpo::value<string>()->implicit_value("server.pem"),
"The TLS certificate file for this server")
("server-pem-password,P", bpo::value<string>()->implicit_value(""), "Password for this certificate")
("genesis-json", bpo::value<boost::filesystem::path>(), "File to read Genesis State from")
("dbg-init-key", bpo::value<string>(),
"Block signing key to use for init witnesses, overrides genesis file")
("api-access", bpo::value<boost::filesystem::path>(), "JSON file specifying API permissions")
("io-threads", bpo::value<uint16_t>()->implicit_value(0), "Number of IO threads, default to 0 for auto-configuration")
("enable-subscribe-to-all", bpo::value<bool>()->implicit_value(true),
"Whether allow API clients to subscribe to universal object creation and removal events")
("enable-standby-votes-tracking", bpo::value<bool>()->implicit_value(true),
"Whether to enable tracking of votes of standby witnesses and committee members. "
"Set it to true to provide accurate data to API clients, set to false for slightly better performance.")
("plugins", bpo::value<string>(), "Space-separated list of plugins to activate")
("api-limit-get-account-history-operations",boost::program_options::value<uint64_t>()->default_value(100),
"For history_api::get_account_history_operations to set its default limit value as 100")
("api-limit-get-account-history",boost::program_options::value<uint64_t>()->default_value(100),
"For history_api::get_account_history to set its default limit value as 100")
("api-limit-get-grouped-limit-orders",boost::program_options::value<uint64_t>()->default_value(101),
"For orders_api::get_grouped_limit_orders to set its default limit value as 101")
("api-limit-get-relative-account-history",boost::program_options::value<uint64_t>()->default_value(100),
"For history_api::get_relative_account_history to set its default limit value as 100")
("api-limit-get-account-history-by-operations",boost::program_options::value<uint64_t>()->default_value(100),
"For history_api::get_account_history_by_operations to set its default limit value as 100")
("api-limit-get-asset-holders",boost::program_options::value<uint64_t>()->default_value(100),
"For asset_api::get_asset_holders to set its default limit value as 100")
("api-limit-get-key-references",boost::program_options::value<uint64_t>()->default_value(100),
"For database_api_impl::get_key_references to set its default limit value as 100")
("replay-blockchain", "Rebuild object graph by replaying all blocks without validation")
("resync-blockchain", "Delete all blocks and re-sync with network from scratch")
("revalidate-blockchain", "Rebuild object graph by replaying all blocks with full validation")
("force-validate", "Force validation of all transactions during normal operation")
("genesis-timestamp", bpo::value<uint32_t>(),
"Replace timestamp from genesis.json with current time plus this many seconds (experts only!)");
command_line_options.add(configuration_file_options);
command_line_options.add_options()("version,v", "Print version number and exit.");
command_line_options.add(_plugins_cli_options);
configuration_file_options.add(_plugins_cfg_options);
}
void application::initialize(const fc::path& data_dir, const boost::program_options::variables_map& options)
{
my->_data_dir = data_dir;
my->_options = &options;
if ( options.count("io-threads") )
{
const uint16_t num_threads = options["io-threads"].as<uint16_t>();
fc::asio::default_io_service_scope::set_num_threads(num_threads);
}
std::vector<string> wanted;
if( options.count("plugins") )
{
boost::split(wanted, options.at("plugins").as<std::string>(), [](char c){return c == ' ';});
}
std::set<string> uniq_wanted;
for (const auto& it : wanted)
{
if(it == "default")
{
uniq_wanted.insert("witness");
uniq_wanted.insert("account_history");
uniq_wanted.insert("market_history");
uniq_wanted.insert("grouped_orders");
}else if (!it.empty())
{
uniq_wanted.insert(it);
}
}
int es_ah_conflict_counter = 0;
for (auto& it : uniq_wanted)
{
if(it == "account_history")
++es_ah_conflict_counter;
if(it == "elasticsearch")
++es_ah_conflict_counter;
if(es_ah_conflict_counter > 1) {
elog("Can't start program with elasticsearch and account_history plugin at the same time");
std::exit(EXIT_FAILURE);
}
enable_plugin(it);
}
}
void application::startup(const seeds_type &external_seeds)
{
try {
my->startup(external_seeds);
} catch ( const fc::exception& e ) {
elog( "${e}", ("e",e.to_detail_string()) );
throw;
} catch ( ... ) {
elog( "unexpected exception" );
throw;
}
}
void application::set_api_limit()
{
try {
my->set_api_limit();
} catch ( const fc::exception& e ) {
elog( "${e}", ("e",e.to_detail_string()) );
throw;
} catch ( ... ) {
elog( "unexpected exception" );
throw;
}
}
std::shared_ptr<abstract_plugin> application::get_plugin(const string& name) const
{
return my->_active_plugins[name];
}
net::node_ptr application::p2p_node()
{
return my->_p2p_network;
}
std::shared_ptr<chain::database> application::chain_database() const
{
return my->_chain_db;
}
void application::set_block_production(bool producing_blocks)
{
my->_is_block_producer = producing_blocks;
}
optional< api_access_info > application::get_api_access_info( const string& username )const
{
return my->get_api_access_info( username );
}
void application::set_api_access_info(const string& username, api_access_info&& permissions)
{
my->set_api_access_info(username, std::move(permissions));
}
bool application::is_finished_syncing() const
{
return my->_is_finished_syncing;
}
void graphene::app::application::enable_plugin(const string& name)
{
FC_ASSERT(my->_available_plugins[name], "Unknown plugin '" + name + "'");
my->_active_plugins[name] = my->_available_plugins[name];
my->_active_plugins[name]->plugin_set_app(this);
}
chain_id_type graphene::app::application::get_chain_id() const
{
return my->get_chain_id();
}
void graphene::app::application::add_available_plugin(std::shared_ptr<graphene::app::abstract_plugin> p)
{
my->_available_plugins[p->plugin_name()] = p;
}
void application::shutdown_plugins()
{
for( auto& entry : my->_active_plugins )
entry.second->plugin_shutdown();
return;
}
void application::shutdown()
{
if( my->_p2p_network )
my->_p2p_network->close();
if( my->_chain_db )
{
my->_chain_db->close();
my->_chain_db = nullptr;
}
}
void application::initialize_plugins( const boost::program_options::variables_map& options )
{
for( auto& entry : my->_active_plugins )
entry.second->plugin_initialize( options );
return;
}
void application::startup_plugins()
{
for( auto& entry : my->_active_plugins )
{
entry.second->plugin_startup();
ilog( "Plugin ${name} started", ( "name", entry.second->plugin_name() ) );
}
return;
}
const application_options& application::get_options()
{
return my->_app_options;
}
const char *options_helper::get_config_file_name()
{
return "config.ini";
}
void options_helper::print_application_version(std::ostream& stream)
{
stream << PLAYCHAIN << " Version: " << fc::string(PLAYCHAIN_VERSION) << "\n";
// TODO: print chain id, create table view
stream << "Bitshares Core Version: " << GRAPHENE_CURRENT_DB_VERSION << "\n";
stream << PLAYCHAIN << " Git Version: " << graphene::utilities::git_revision_description << "\n";
stream << "SHA: " << graphene::utilities::git_revision_sha << "\n";
stream << "Timestamp: " << fc::get_approximate_relative_time_string(fc::time_point_sec(graphene::utilities::git_revision_unix_timestamp)) << "\n";
stream << "SSL: " << OPENSSL_VERSION_TEXT << "\n";
stream << "Boost: " << boost::replace_all_copy(std::string(BOOST_LIB_VERSION), "_", ".") << "\n";
stream << "Websocket++: " << websocketpp::major_version << "." << websocketpp::minor_version << "." << websocketpp::patch_version << "\n";
}
void options_helper::print_program_options(std::ostream& stream, const boost::program_options::options_description& options)
{
for (const boost::shared_ptr<bpo::option_description> od : options.options())
{
if (!od->description().empty())
stream << "# " << od->description() << "\n";
boost::any store;
if (!od->semantic()->apply_default(store))
{
stream << "# " << od->long_name() << " = \n";
}
else
{
auto example = od->format_parameter();
if (example.empty())
{
// This is a boolean switch
stream << od->long_name() << " = "
<< "false\n";
}
else
{
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length() - 1);
stream << od->long_name() << " = " << example << "\n";
}
}
stream << "\n";
}
}
fc::path options_helper::get_config_file_path(const boost::program_options::variables_map& options)
{
namespace bfs = boost::filesystem;
bfs::path config_ini_path = get_data_dir_path(options) / get_config_file_name();
if (options.count("config-file"))
{
config_ini_path = bfs::absolute(options["config-file"].as<bfs::path>());
}
return config_ini_path;
}
fc::path options_helper::get_data_dir_path(const boost::program_options::variables_map& options)
{
namespace bfs = boost::filesystem;
FC_ASSERT(options.count("data-dir"), "Default value for 'data-dir' should be set.");
bfs::path data_dir_path = bfs::absolute(options["data-dir"].as<bfs::path>());
return data_dir_path;
}
namespace
{
// logging config is too complicated to be parsed by boost::program_options,
// so we do it by hand
//
// Currently, you can only specify the filenames and logging levels, which
// are all most users would want to change. At a later time, options can
// be added to control rotation intervals, compression, and other seldom-
// used features
void write_default_logging_config_to_stream(std::ostream& out)
{
out << "# declare an appender named \"stderr\" that writes messages to the console\n"
"[log.console_appender.stderr]\n"
"stream=std_error\n\n"
"# declare an appender named \"p2p\" that writes messages to p2p.log\n"
"[log.file_appender.p2p]\n"
"filename=logs/p2p/p2p.log\n"
"# filename can be absolute or relative to this config file\n\n"
"# route any messages logged to the default logger to the \"stderr\" logger we\n"
"# declared above, if they are info level are higher\n"
"[logger.default]\n"
"level=info\n"
"appenders=stderr\n\n"
"# route messages sent to the \"p2p\" logger to the p2p appender declared above\n"
"[logger.p2p]\n"
"level=info\n"
"appenders=p2p\n\n";
}
class deduplicator
{
public:
deduplicator() : modifier(nullptr) {}
deduplicator(const boost::shared_ptr<bpo::option_description> (*mod_fn)(const boost::shared_ptr<bpo::option_description>&))
: modifier(mod_fn) {}
const boost::shared_ptr<bpo::option_description> next(const boost::shared_ptr<bpo::option_description>& o)
{
const std::string name = o->long_name();
if( seen.find( name ) != seen.end() )
return nullptr;
seen.insert(name);
return modifier ? modifier(o) : o;
}
private:
boost::container::flat_set<std::string> seen;
const boost::shared_ptr<bpo::option_description> (*modifier)(const boost::shared_ptr<bpo::option_description>&);
};
const boost::shared_ptr<bpo::option_description> new_option_description( const std::string& name,
const bpo::value_semantic* value,
const std::string& description )
{
bpo::options_description helper("");
helper.add_options()( name.c_str(), value, description.c_str() );
return helper.options()[0];
}
void create_new_config_file( const fc::path& config_ini_path,
const bpo::options_description& cfg_options )
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
auto modify_option_defaults = [](const boost::shared_ptr<bpo::option_description>& o) -> const boost::shared_ptr<bpo::option_description> {
const std::string& name = o->long_name();
if( name == "partial-operations" )
return new_option_description( name, bpo::value<bool>()->default_value(true), o->description() );
if( name == "max-ops-per-account" )
return new_option_description( name, bpo::value<int>()->default_value(1000), o->description() );
return o;
};
deduplicator dedup(modify_option_defaults);
std::ofstream out_cfg(config_ini_path.preferred_string());
for( const boost::shared_ptr<bpo::option_description> opt : cfg_options.options() )
{
const boost::shared_ptr<bpo::option_description> od = dedup.next(opt);
if( !od ) continue;
if( !od->description().empty() )
out_cfg << "# " << od->description() << "\n";
boost::any store;
if( !od->semantic()->apply_default(store) )
out_cfg << "# " << od->long_name() << " = \n";
else {
auto example = od->format_parameter();
if( example.empty() )
// This is a boolean switch
out_cfg << od->long_name() << " = " << "false\n";
else {
// The string is formatted "arg (=<interesting part>)"
example.erase(0, 6);
example.erase(example.length()-1);
out_cfg << od->long_name() << " = " << example << "\n";
}
}
out_cfg << "\n";
}
write_default_logging_config_to_stream(out_cfg);
out_cfg.close();
}
fc::optional<fc::logging_config> get_ext_config_from_ini_file(
const fc::path& config_ini_path, seeds_type &external_seeds)
{
try
{
fc::logging_config logging_config;
bool found_logging_config = false;
boost::property_tree::ptree config_ini_tree;
boost::property_tree::ini_parser::read_ini(config_ini_path.preferred_string().c_str(), config_ini_tree);
for (const auto& section : config_ini_tree)
{
const std::string& section_name = section.first;
const boost::property_tree::ptree& section_tree = section.second;
#ifndef NDEBUG
std::cout << section_name << std::endl;
#endif //DEBUG
const std::string console_appender_section_prefix = "log.console_appender.";
const std::string file_appender_section_prefix = "log.file_appender.";
const std::string gelf_appender_section_prefix = "log.gelf_appender.";
const std::string logger_section_prefix = "logger.";
const std::string seed_section_prefix = "seed.";
if (boost::starts_with(section_name, console_appender_section_prefix))
{
std::string console_appender_name = section_name.substr(console_appender_section_prefix.length());
std::string stream_name = section_tree.get<std::string>("stream");
// construct a default console appender config here
// stdout/stderr will be taken from ini file, everything else hard-coded here
fc::console_appender::config console_appender_config;
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::debug,
fc::console_appender::color::green));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::warn,
fc::console_appender::color::brown));
console_appender_config.level_colors.emplace_back(
fc::console_appender::level_color(fc::log_level::error,
fc::console_appender::color::cyan));
console_appender_config.stream = fc::variant(stream_name).as<fc::console_appender::stream::type>(GRAPHENE_MAX_NESTED_OBJECTS);
logging_config.appenders.push_back(fc::appender_config(console_appender_name, "console", fc::variant(console_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, file_appender_section_prefix))
{
std::string file_appender_name = section_name.substr(file_appender_section_prefix.length());
fc::path file_name = section_tree.get<std::string>("filename");
if (file_name.is_relative())
file_name = fc::absolute(config_ini_path).parent_path() / file_name;
// construct a default file appender config here
// filename will be taken from ini file, everything else hard-coded here
fc::file_appender::config file_appender_config;
file_appender_config.filename = file_name;
file_appender_config.flush = true;
file_appender_config.rotate = true;
file_appender_config.rotation_interval = fc::hours(1);
file_appender_config.rotation_limit = fc::days(1);
logging_config.appenders.push_back(fc::appender_config(file_appender_name, "file", fc::variant(file_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, gelf_appender_section_prefix))
{
std::string gelf_appender_name = section_name.substr(file_appender_section_prefix.length());
std::string endpoint = section_tree.get<std::string>("endpoint");
fc::gelf_appender::config gelf_appender_config;
gelf_appender_config.endpoint = endpoint;
gelf_appender_config.host = boost::asio::ip::host_name();
gelf_appender_config.additional_info = std::to_string(fc::ip::endpoint::from_string(config_ini_tree.get<std::string>("p2p-endpoint")).port());
logging_config.appenders.push_back(fc::appender_config(gelf_appender_name, "gelf", fc::variant(gelf_appender_config, GRAPHENE_MAX_NESTED_OBJECTS)));
found_logging_config = true;
}
else if (boost::starts_with(section_name, logger_section_prefix))
{
std::string logger_name = section_name.substr(logger_section_prefix.length());
std::string level_string = section_tree.get<std::string>("level");
std::string appenders_string = section_tree.get<std::string>("appenders");
fc::logger_config logger_config(logger_name);
logger_config.level = fc::variant(level_string).as<fc::log_level>(5);
boost::split(logger_config.appenders, appenders_string,
boost::is_any_of(" ,"),
boost::token_compress_on);
logging_config.loggers.push_back(logger_config);
found_logging_config = true;
}
else if (boost::starts_with(section_name, seed_section_prefix))
{
std::string node_string = section_tree.get<std::string>("node");
external_seeds.emplace_back(node_string);
}
}
if (found_logging_config)
return logging_config;
else
return fc::optional<fc::logging_config>();
}
FC_RETHROW_EXCEPTIONS(warn, "")
}
}
void options_helper::create_config_file_if_not_exist(const fc::path& config_ini_path,
const boost::program_options::options_description& cfg_options)
{
FC_ASSERT(config_ini_path.is_absolute(), "config-file path should be absolute");
if (!fc::exists(config_ini_path))
{
ilog("Writing new config file at ${path}", ("path", config_ini_path));
if (!fc::exists(config_ini_path.parent_path()))
{
fc::create_directories(config_ini_path.parent_path());
}
create_new_config_file(config_ini_path, cfg_options);
}
}
void options_helper::load_config_file(const fc::path& config_ini_path,
const boost::program_options::options_description& cfg_options,
boost::program_options::variables_map& options,
seeds_type &external_seeds)
{
std::cout << "Load configuration from " << config_ini_path.preferred_string() << std::endl;
// get the basic options
bpo::store(bpo::parse_config_file<char>(config_ini_path.preferred_string().c_str(), cfg_options, true), options);
// try to get logging options from the config file.
try
{
auto logging_config = get_ext_config_from_ini_file(config_ini_path, external_seeds);
if (logging_config)
fc::configure_logging(*logging_config);
}
catch (const fc::exception& err)
{
wdump((err.what()))
wlog("Error parsing logging config from config file ${config}, using default config", ("config", config_ini_path.preferred_string()));
}
}
// namespace detail
} }
| 42.567427 | 173 | 0.653984 | totalgames |
163253d691d9e2ba6090e9c5b14f7ff95ed761af | 3,271 | cpp | C++ | watchX/lib/BMP280/pressure.cpp | murataka/watchX | 74fddc87d90af88197cb83ee7c8c4439330c9957 | [
"Apache-2.0"
] | 6 | 2018-06-29T04:34:57.000Z | 2020-08-04T05:37:52.000Z | watchX/lib/BMP280/pressure.cpp | murataka/watchX | 74fddc87d90af88197cb83ee7c8c4439330c9957 | [
"Apache-2.0"
] | null | null | null | watchX/lib/BMP280/pressure.cpp | murataka/watchX | 74fddc87d90af88197cb83ee7c8c4439330c9957 | [
"Apache-2.0"
] | 2 | 2018-06-22T23:08:14.000Z | 2020-08-05T22:53:41.000Z | #include "pressure.h"
#include <Wire.h>
#define Addr 0x76
void getPressure(){
unsigned int b1[24];
unsigned int data[8];
for (int i = 0; i < 24; i++)
{
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select data register
Wire.write((136 + i));
// Stop I2C Transmission
Wire.endTransmission();
// Request 1 byte of data
Wire.requestFrom(Addr, 1);
// Read 1 byte of data
if (Wire.available() == 1)
{
b1[i] = Wire.read();
}
}
// Convert the data
// temp coefficients
unsigned int dig_T1 = (b1[0] & 0xFF) + ((b1[1] & 0xFF) * 256);
int dig_T2 = b1[2] + (b1[3] * 256);
int dig_T3 = b1[4] + (b1[5] * 256);
// pressure coefficients
unsigned int dig_P1 = (b1[6] & 0xFF) + ((b1[7] & 0xFF) * 256);
int dig_P2 = b1[8] + (b1[9] * 256);
int dig_P3 = b1[10] + (b1[11] * 256);
int dig_P4 = b1[12] + (b1[13] * 256);
int dig_P5 = b1[14] + (b1[15] * 256);
int dig_P6 = b1[16] + (b1[17] * 256);
int dig_P7 = b1[18] + (b1[19] * 256);
int dig_P8 = b1[20] + (b1[21] * 256);
int dig_P9 = b1[22] + (b1[23] * 256);
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select control measurement register
Wire.write(0xF4);
// Normal mode, temp and pressure over sampling rate = 1
Wire.write(0x27);
// Stop I2C Transmission
Wire.endTransmission();
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select config register
Wire.write(0xF5);
// Stand_by time = 1000ms
Wire.write(0xA0);
// Stop I2C Transmission
Wire.endTransmission();
for (int i = 0; i < 8; i++)
{
// Start I2C Transmission
Wire.beginTransmission(Addr);
// Select data register
Wire.write((247 + i));
// Stop I2C Transmission
Wire.endTransmission();
// Request 1 byte of data
Wire.requestFrom(Addr, 1);
// Read 1 byte of data
if (Wire.available() == 1)
{
data[i] = Wire.read();
}
}
// Convert pressure and temperature data to 19-bits
long adc_p = (((long)(data[0] & 0xFF) * 65536) + ((long)(data[1] & 0xFF) * 256) + (long)(data[2] & 0xF0)) / 16;
long adc_t = (((long)(data[3] & 0xFF) * 65536) + ((long)(data[4] & 0xFF) * 256) + (long)(data[5] & 0xF0)) / 16;
// Temperature offset calculations
double var1 = (((double)adc_t) / 16384.0 - ((double)dig_T1) / 1024.0) * ((double)dig_T2);
double var2 = ((((double)adc_t) / 131072.0 - ((double)dig_T1) / 8192.0) *
(((double)adc_t) / 131072.0 - ((double)dig_T1) / 8192.0)) * ((double)dig_T3);
double t_fine = (long)(var1 + var2);
double cTemp = (var1 + var2) / 5120.0;
double fTemp = cTemp * 1.8 + 32;
// Pressure offset calculations
var1 = ((double)t_fine / 2.0) - 64000.0;
var2 = var1 * var1 * ((double)dig_P6) / 32768.0;
var2 = var2 + var1 * ((double)dig_P5) * 2.0;
var2 = (var2 / 4.0) + (((double)dig_P4) * 65536.0);
var1 = (((double) dig_P3) * var1 * var1 / 524288.0 + ((double) dig_P2) * var1) / 524288.0;
var1 = (1.0 + var1 / 32768.0) * ((double)dig_P1);
double p = 1048576.0 - (double)adc_p;
p = (p - (var2 / 4096.0)) * 6250.0 / var1;
var1 = ((double) dig_P9) * p * p / 2147483648.0;
var2 = p * ((double) dig_P8) / 32768.0;
double pressure = (p + (var1 + var2 + ((double)dig_P7)) / 16.0) / 100;
}
| 29.468468 | 113 | 0.580862 | murataka |
163474d01da8a5f8172bac0823c7232f4aee3967 | 969 | cpp | C++ | src/BehavioralDesignPatterns/Observer/observer.cpp | straceX/DesignPatterns | d35a5afb936deaf8cad5ea3899d70b38070f720a | [
"Apache-2.0"
] | null | null | null | src/BehavioralDesignPatterns/Observer/observer.cpp | straceX/DesignPatterns | d35a5afb936deaf8cad5ea3899d70b38070f720a | [
"Apache-2.0"
] | null | null | null | src/BehavioralDesignPatterns/Observer/observer.cpp | straceX/DesignPatterns | d35a5afb936deaf8cad5ea3899d70b38070f720a | [
"Apache-2.0"
] | null | null | null | #include "observer.h"
#include <iostream>
int Observer::m_currentId = 0;
Observer::Observer(Observable &observable)
: m_observable(observable)
, m_id{++Observer::m_currentId}
{
m_observable.Attach(this);
std::cout<< "New observer(" << m_id << ") is created.\n";
}
Observer::~Observer()
{
std::cout<< "Observer(" << m_id << ") is destructed.\n";
}
auto Observer::Detach()
-> void
{
m_observable.Detach(this);
std::cout<< "Observer(" << m_id << ") is detached.\n";
}
auto Observer::Action() const
-> void
{
std::cout<< "Observer(" << m_id << ") : wheater is updated : " << m_statusInfoFromObservable << "\n";
}
auto Observer::Alert() const
-> void
{
std::cout<< "Tornado is coming!..\n";
}
//---IObserver---
auto Observer::UpdateStatus(const std::string &newMesg)
-> void
{
m_statusInfoFromObservable = newMesg;
if (m_statusInfoFromObservable == "Tornado")
{
Alert();
return;
}
Action();
} | 19.38 | 103 | 0.610939 | straceX |
16357609b78e8315152b0b14eb682f03da804cce | 3,685 | cpp | C++ | MonoNative/mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_DirectorySecurity.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 7 | 2015-03-10T03:36:16.000Z | 2021-11-05T01:16:58.000Z | MonoNative/mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_DirectorySecurity.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | 1 | 2020-06-23T10:02:33.000Z | 2020-06-24T02:05:47.000Z | MonoNative/mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_DirectorySecurity.cpp | brunolauze/MonoNative | 959fb52c2c1ffe87476ab0d6e4fcce0ad9ce1e66 | [
"BSD-2-Clause"
] | null | null | null | #include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_DirectorySecurity.h>
#include <mscorlib/System/mscorlib_System_Type.h>
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_AccessRule.h>
#include <mscorlib/System/Security/Principal/mscorlib_System_Security_Principal_IdentityReference.h>
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_FileSystemAccessRule.h>
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_AuditRule.h>
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_FileSystemAuditRule.h>
#include <mscorlib/System/Security/AccessControl/mscorlib_System_Security_AccessControl_AuthorizationRuleCollection.h>
#include <mscorlib/System/mscorlib_System_Byte.h>
namespace mscorlib
{
namespace System
{
namespace Security
{
namespace AccessControl
{
//Public Methods
//Get Set Properties Methods
// Get:AccessRightType
mscorlib::System::Type DirectorySecurity::get_AccessRightType() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "FileSystemSecurity", 0, NULL, "get_AccessRightType", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Type(__result__);
}
// Get:AccessRuleType
mscorlib::System::Type DirectorySecurity::get_AccessRuleType() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "FileSystemSecurity", 0, NULL, "get_AccessRuleType", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Type(__result__);
}
// Get:AuditRuleType
mscorlib::System::Type DirectorySecurity::get_AuditRuleType() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "FileSystemSecurity", 0, NULL, "get_AuditRuleType", __native_object__, 0, NULL, NULL, NULL);
return mscorlib::System::Type(__result__);
}
// Get:AreAccessRulesCanonical
mscorlib::System::Boolean DirectorySecurity::get_AreAccessRulesCanonical() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "ObjectSecurity", 0, NULL, "get_AreAccessRulesCanonical", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
// Get:AreAccessRulesProtected
mscorlib::System::Boolean DirectorySecurity::get_AreAccessRulesProtected() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "ObjectSecurity", 0, NULL, "get_AreAccessRulesProtected", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
// Get:AreAuditRulesCanonical
mscorlib::System::Boolean DirectorySecurity::get_AreAuditRulesCanonical() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "ObjectSecurity", 0, NULL, "get_AreAuditRulesCanonical", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
// Get:AreAuditRulesProtected
mscorlib::System::Boolean DirectorySecurity::get_AreAuditRulesProtected() const
{
MonoObject *__result__ = Global::InvokeMethod("mscorlib", "System.Security.AccessControl", "ObjectSecurity", 0, NULL, "get_AreAuditRulesProtected", __native_object__, 0, NULL, NULL, NULL);
return *(mscorlib::System::Boolean*)mono_object_unbox(__result__);
}
}
}
}
}
| 43.352941 | 194 | 0.766621 | brunolauze |
16363101665f96a106508fd22e0d8c316daaf86d | 40,694 | cpp | C++ | packages/monte_carlo/estimator/native/src/MonteCarlo_EstimatorHandlerFactory_Root.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_EstimatorHandlerFactory_Root.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | packages/monte_carlo/estimator/native/src/MonteCarlo_EstimatorHandlerFactory_Root.cpp | lkersting/SCR-2123 | 06ae3d92998664a520dc6a271809a5aeffe18f72 | [
"BSD-3-Clause"
] | null | null | null | //---------------------------------------------------------------------------//
//!
//! \file MonteCarlo_EstimatorHandlerFactory_Root.cpp
//! \author Alex Robinson, Eli Moll
//! \brief Estimator handler factory class declaration.
//!
//---------------------------------------------------------------------------//
// Std Lib Includes
#include <set>
// FRENSIE Includes
#include "MonteCarlo_EstimatorHandlerFactoryDecl.hpp"
#include "MonteCarlo_EstimatorHandlerFactory_Root.hpp"
#include "MonteCarlo_ResponseFunctionFactory.hpp"
#include "MonteCarlo_CellPulseHeightEstimator.hpp"
#include "MonteCarlo_CellTrackLengthFluxEstimator.hpp"
#include "MonteCarlo_CellCollisionFluxEstimator.hpp"
#include "MonteCarlo_SurfaceFluxEstimator.hpp"
#include "MonteCarlo_SurfaceCurrentEstimator.hpp"
#include "MonteCarlo_TetMeshTrackLengthFluxEstimator.hpp"
#ifdef HAVE_FRENSIE_ROOT
#include "Geometry_ModuleInterface_Root.hpp"
#endif
#include "Utility_ArrayString.hpp"
#include "Utility_ExceptionTestMacros.hpp"
#include "Utility_ContractException.hpp"
namespace MonteCarlo{
#ifdef HAVE_FRENSIE_ROOT
// Initialize static member data
const std::string EstimatorHandlerFactory<Geometry::Root>::surface_current_name =
"Surface Current";
const std::string EstimatorHandlerFactory<Geometry::Root>::surface_flux_name =
"Surface Flux";
const std::string EstimatorHandlerFactory<Geometry::Root>::cell_pulse_height_name =
"Cell Pulse Height";
const std::string EstimatorHandlerFactory<Geometry::Root>::cell_track_length_flux_name =
"Cell Track-Length Flux";
const std::string EstimatorHandlerFactory<Geometry::Root>::cell_collision_flux_name =
"Cell Collision Flux";
const std::string EstimatorHandlerFactory<Geometry::Root>::tet_mesh_track_length_flux_name =
"Tet Mesh Track-Length Flux";
std::ostream* EstimatorHandlerFactory<Geometry::Root>::s_os_warn = NULL;
// Initialize the estimator handler using Root
void EstimatorHandlerFactory<Geometry::Root>::initializeHandler(
const Teuchos::ParameterList& response_reps,
const Teuchos::ParameterList& estimator_reps,
std::ostream& os_warn )
{
// Set the warning output stream
s_os_warn = &os_warn;
// Create the response functions
boost::unordered_map<unsigned,Teuchos::RCP<ResponseFunction> >
response_id_map;
ResponseFunctionFactory::createResponseFunctions( response_reps,
response_id_map );
// Validate the estimators
Teuchos::ParameterList::ConstIterator it = estimator_reps.begin();
while( it != estimator_reps.end() )
{
const Teuchos::ParameterList& estimator_rep =
Teuchos::any_cast<Teuchos::ParameterList>( it->second.getAny() );
EstimatorHandlerFactory<Geometry::Root>::validateEstimatorRep( estimator_rep,
response_id_map );
++it;
}
// Create the estimator data maps
boost::unordered_map<unsigned,std::string> estimator_id_type_map;
boost::unordered_map<unsigned,std::string> estimator_id_ptype_map;
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >
estimator_id_cells_map;
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle> >
estimator_id_surfaces_map;
EstimatorHandlerFactory<Geometry::Root>::createEstimatorDataMaps(
estimator_id_type_map,
estimator_id_ptype_map,
estimator_id_cells_map,
estimator_id_surfaces_map );
// Append the data in the xml file to the estimator data maps
EstimatorHandlerFactory<Geometry::Root>::appendDataToEstimatorDataMaps(
estimator_reps,
estimator_id_type_map,
estimator_id_ptype_map,
estimator_id_cells_map,
estimator_id_surfaces_map );
// Create the cell volume map
boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,double>
cell_volume_map;
EstimatorHandlerFactory<Geometry::Root>::createCellVolumeMap( estimator_id_cells_map,
cell_volume_map );
// Create the surface area map
boost::unordered_map<Geometry::ModuleTraits::InternalSurfaceHandle,double>
surface_area_map;
EstimatorHandlerFactory<Geometry::Root>::createSurfaceAreaMap( estimator_id_surfaces_map,
surface_area_map );
// Create the estimators
it = estimator_reps.begin();
while( it != estimator_reps.end() )
{
const Teuchos::ParameterList& estimator_rep =
Teuchos::any_cast<Teuchos::ParameterList>( it->second.getAny() );
// Get the estimator id
unsigned id = estimator_rep.get<unsigned int> ( "Id" );
// Get the estimator multiplier
double multiplier = 1.0;
if( estimator_rep.isParameter( "Multiplier" ) )
multiplier = estimator_rep.get<double>( "Multiplier" );
TEST_FOR_EXCEPTION( multiplier <= 0.0,
InvalidEstimatorRepresentation,
"Error: estimator " << id << " has a negative "
"multiplier specified!" );
// Check if energy multiplication was requested
bool energy_mult = false;
if( estimator_rep.isParameter( "Energy Multiplication" ) )
energy_mult = estimator_rep.get<bool>("Energy Multiplication");
const Teuchos::ParameterList* estimator_bins = NULL;
if( estimator_rep.isParameter( "Bins" ) )
estimator_bins = &estimator_rep.get<Teuchos::ParameterList>( "Bins" );
// Get the particle types assigned to the estimator
Teuchos::Array<ParticleType> particle_types( 1 );
particle_types[0] =
convertParticleTypeNameToParticleTypeEnum( estimator_id_ptype_map[id] );
// Get the response functions assigned to the estimator
Teuchos::Array<Teuchos::RCP<ResponseFunction> > response_functions;
if( estimator_rep.isParameter( "Response Functions" ) )
{
const Utility::ArrayString& array_string =
estimator_rep.get<Utility::ArrayString>( "Response Functions" );
Teuchos::Array<unsigned> requested_response_functions;
try{
requested_response_functions =
array_string.getConcreteArray<unsigned>();
}
EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the response functions requested for"
" estimator " << id << " are not valid!" );
response_functions.resize( requested_response_functions.size() );
for( unsigned i = 0; i < requested_response_functions.size(); ++i )
{
TEST_FOR_EXCEPTION(
response_id_map.find( requested_response_functions[i] ) ==
response_id_map.end(),
InvalidEstimatorRepresentation,
"Error: estimator " << id << " has requested response "
"function " << requested_response_functions[i] <<
" which does not exist!" );
response_functions[i] =
response_id_map[requested_response_functions[i]];
}
}
// Create cell estimator
if( estimator_id_cells_map.find( id ) != estimator_id_cells_map.end() )
{
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells =
estimator_id_cells_map[id];
Teuchos::Array<double> cell_volumes;
if( EstimatorHandlerFactory<Geometry::Root>::isCellPulseHeightEstimator( estimator_id_type_map[id] ) )
{
EstimatorHandlerFactory<Geometry::Root>::createPulseHeightEstimator(
id,
multiplier,
particle_types,
cells,
response_functions,
energy_mult,
estimator_bins );
}
else if( EstimatorHandlerFactory<Geometry::Root>::isCellTrackLengthFluxEstimator( estimator_id_type_map[id] ) )
{
EstimatorHandlerFactory<Geometry::Root>::fillCellVolumesArray( cells,
cell_volume_map,
cell_volumes );
EstimatorHandlerFactory<Geometry::Root>::createCellTrackLengthFluxEstimator(
id,
multiplier,
particle_types,
cells,
cell_volumes,
response_functions,
energy_mult,
estimator_bins );
}
else if( EstimatorHandlerFactory<Geometry::Root>::isCellCollisionFluxEstimator( estimator_id_type_map[id] ) )
{
EstimatorHandlerFactory<Geometry::Root>::fillCellVolumesArray( cells,
cell_volume_map,
cell_volumes );
EstimatorHandlerFactory<Geometry::Root>::createCellCollisionFluxEstimator(
id,
multiplier,
particle_types,
cells,
cell_volumes,
response_functions,
energy_mult,
estimator_bins );
}
else
{
*s_os_warn << "Warning: Estimator type: " << estimator_id_type_map[id] <<
" is not a valid estimator type for the Root geometry " <<
"handler. Therefore, estimator " << id << " will be ignored." <<
std::endl;
}
estimator_id_cells_map.erase( id );
}
// Create surface estimator
else if( estimator_id_surfaces_map.find( id ) !=
estimator_id_surfaces_map.end() )
{
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle>&
surfaces = estimator_id_surfaces_map[id];
Teuchos::Array<double> surface_areas;
if( EstimatorHandlerFactory<Geometry::Root>::isSurfaceFluxEstimator( estimator_id_type_map[id] ) ||
EstimatorHandlerFactory<Geometry::Root>::isSurfaceCurrentEstimator( estimator_id_type_map[id] ) )
{
*s_os_warn << "Warning: Surface estimators are not supported by the "
"Root geometry handler. Estimator " << id << " will be " <<
"ignored." << std::endl;
}
else
{
*s_os_warn << "Warning: Estimator type: " << estimator_id_type_map[id] <<
" is not a valid estimator type for the Root geometry " <<
"handler. Therefore, estimator " << id << " will be ignored."
<< std::endl;
}
estimator_id_surfaces_map.erase( id );
}
// Create a tet mesh track length flux estimator
/* Warning: Mesh tallies are not currently supported by ROOT and thus have
* been turned off for the ROOT specialization.
*/
else if( estimator_id_type_map[id] ==
EstimatorHandlerFactory<Geometry::Root>::tet_mesh_track_length_flux_name )
{
*s_os_warn << "Warning: Root does not currently support the tetrahedral " <<
"mesh track length flux estimator. As such, estimator " <<
id << " will not be implemented." << std::endl;
}
// Remove the ids from the maps
estimator_id_type_map.erase( id );
estimator_id_ptype_map.erase( id );
estimator_rep.unused( *s_os_warn );
++it;
}
/* There can be no remaining tallies to create, as the Root input cannot
* be used to specify tallies on surfaces/volumes.
*/
}
// Validate an estimator representation
void EstimatorHandlerFactory<Geometry::Root>::validateEstimatorRep(
const Teuchos::ParameterList& estimator_rep,
const boost::unordered_map<unsigned,Teuchos::RCP<ResponseFunction> >&
response_id_map )
{
// Make sure the estimator id has been specified
TEST_FOR_EXCEPTION( !estimator_rep.isParameter( "Id" ),
InvalidEstimatorRepresentation,
"Error: the estimator id was not specified in estimator "
<< estimator_rep.name() << "!" );
// Make sure the estimator type has been specified
TEST_FOR_EXCEPTION( !estimator_rep.isParameter( "Type" ),
InvalidEstimatorRepresentation,
"Error: the estimator type was not specified in "
"estimator " << estimator_rep.name() << "!" );
}
// Test if two estimator types are equivalent
bool EstimatorHandlerFactory<Geometry::Root>::areEstimatorTypesEquivalent(
const std::string& geometry_module_type,
const std::string& xml_type )
{
if( geometry_module_type == xml_type )
return true;
}
// Create the estimator data maps using Root information
/* Note that ROOT does not have estimator data, therefore this is an empty
* function call.
*/
void EstimatorHandlerFactory<Geometry::Root>::createEstimatorDataMaps(
boost::unordered_map<unsigned,std::string>& estimator_id_type_map,
boost::unordered_map<unsigned,std::string>& estimator_id_ptype_map,
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >&
estimator_id_cells_map,
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle> >&
estimator_id_surfaces_map )
{ /* ... */ }
// Append data to estimator data maps
/* Note that ROOT does not have estimator data, therefore this is an empty
* function call.
*/
void EstimatorHandlerFactory<Geometry::Root>::appendDataToEstimatorDataMaps(
const Teuchos::ParameterList& estimator_reps,
boost::unordered_map<unsigned,std::string>& estimator_id_type_map,
boost::unordered_map<unsigned,std::string>& estimator_id_ptype_map,
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >&
estimator_id_cells_map,
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle> >&
estimator_id_surfaces_map )
{
#ifdef HAVE_FRENSIE_ROOT
Teuchos::ParameterList::ConstIterator it = estimator_reps.begin();
while( it != estimator_reps.end() )
{
const Teuchos::ParameterList& estimator_rep =
Teuchos::any_cast<Teuchos::ParameterList>( it->second.getAny() );
unsigned id = estimator_rep.get<unsigned>( "Id" );
std::string estimator_type = estimator_rep.get<std::string>( "Type" );
if( estimator_id_type_map.find( id ) != estimator_id_type_map.end() )
{
// Append cells to the estimator cells map
if( EstimatorHandlerFactory<Geometry::Root>::isCellEstimatorTypeValid(estimator_type) )
{
if( estimator_rep.isParameter( "Cells" ) )
{
const Utility::ArrayString& array_string =
estimator_rep.get<Utility::ArrayString>( "Cells" );
Teuchos::Array<unsigned> extra_cells;
try{
extra_cells = array_string.getConcreteArray<unsigned>();
}
EXCEPTION_CATCH_RETHROW_AS(Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the cells requested for "
"estimator " << id <<
" are not valid!" );
EstimatorHandlerFactory<Geometry::Root>::appendCellsToAssignedCells(
id,
estimator_id_cells_map[id],
extra_cells );
}
}
else
{
if( estimator_rep.isParameter( "Surfaces" ) )
{
const Utility::ArrayString& array_string =
estimator_rep.get<Utility::ArrayString>( "Surfaces" );
Teuchos::Array<unsigned> extra_surfaces;
try{
extra_surfaces = array_string.getConcreteArray<unsigned>();
}
EXCEPTION_CATCH_RETHROW_AS(Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the surfaces requested for "
"estimator " << id << " are not valid!" );
EstimatorHandlerFactory<Geometry::Root>::appendSurfacesToAssignedSurfaces(
id,
estimator_id_surfaces_map[id],
extra_surfaces );
}
}
}
else
{
// Assign the estimator type
std::string estimator_type = estimator_rep.get<std::string>( "Type" );
TEST_FOR_EXCEPTION(
!EstimatorHandlerFactory<Geometry::Root>::isCellEstimatorTypeValid(estimator_type) &&
!EstimatorHandlerFactory<Geometry::Root>::isSurfaceEstimatorTypeValid(estimator_type) &&
!EstimatorHandlerFactory<Geometry::Root>::isEstimatorTypeValid(estimator_type),
InvalidEstimatorRepresentation,
"Error: estimator " << id << " has estimator type "
<< estimator_type << " specified in the xml file, which is "
"invalid!" );
estimator_id_type_map[id] = estimator_type;
// Assign the estimator particle type
TEST_FOR_EXCEPTION( !estimator_rep.isParameter( "Particle Type" ),
InvalidEstimatorRepresentation,
"Error: estimator " << id << " does not have a "
"particle type specified!" );
const std::string& particle_type =
estimator_rep.get<std::string>( "Particle Type" );
TEST_FOR_EXCEPTION( !isValidParticleTypeName( particle_type ),
InvalidEstimatorRepresentation,
"Error: estimator " << id << " specified particle "
"type " << particle_type << " which is not valid ("
"choose Neutron or Photon)" );
estimator_id_ptype_map[id] = particle_type;
if( EstimatorHandlerFactory<Geometry::Root>::isCellEstimatorTypeValid(estimator_type) )
{
TEST_FOR_EXCEPTION( !estimator_rep.isParameter( "Cells" ),
InvalidEstimatorRepresentation,
"Error: estimator " << id << " does not have "
"cells specified!" );
const Utility::ArrayString& array_string =
estimator_rep.get<Utility::ArrayString>( "Cells" );
Teuchos::Array<unsigned> cells;
try{
cells = array_string.getConcreteArray<unsigned>();
}
EXCEPTION_CATCH_RETHROW_AS(Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the cells requested for "
"estimator " << id <<
" are not valid!" );
EstimatorHandlerFactory<Geometry::Root>::appendCellsToAssignedCells(
id,
estimator_id_cells_map[id],
cells );
}
else if( EstimatorHandlerFactory<Geometry::Root>::isSurfaceEstimatorTypeValid( estimator_type ) )
{
TEST_FOR_EXCEPTION( !estimator_rep.isParameter( "Surfaces" ),
InvalidEstimatorRepresentation,
"Error: estimator " << id << " does not have "
"surfaces specified!" );
const Utility::ArrayString& array_string =
estimator_rep.get<Utility::ArrayString>( "Surfaces" );
Teuchos::Array<unsigned> surfaces;
try{
surfaces = array_string.getConcreteArray<unsigned>();
}
EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the surfaces requested for "
"estimator " << id << " are not valid!" );
EstimatorHandlerFactory<Geometry::Root>::appendSurfacesToAssignedSurfaces(
id,
estimator_id_surfaces_map[id],
surfaces );
}
}
++it;
}
// Make sure the maps have the correct sizes
testPostcondition( estimator_id_type_map.size() ==
estimator_id_ptype_map.size() );
testPostcondition( estimator_id_type_map.size() >=
estimator_id_cells_map.size() +
estimator_id_surfaces_map.size() );
#endif // end HAVE_FRENSIE_ROOT
}
// Append cells to assigned cells
// If Root is not enabled, this function will be empty
void EstimatorHandlerFactory<Geometry::Root>::appendCellsToAssignedCells(
const unsigned estimator_id,
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>&
assigned_cells,
const Teuchos::Array<unsigned>& extra_cells )
{
#ifdef HAVE_FRENSIE_ROOT
std::set<Geometry::ModuleTraits::InternalCellHandle>
cells( assigned_cells.begin(), assigned_cells.end() );
// Verify that the extra cells exist
for( unsigned i = 0u; i < extra_cells.size(); ++i )
{
TEST_FOR_EXCEPTION(
!Geometry::ModuleInterface<Geometry::Root>::doesCellExist( extra_cells[i] ),
InvalidEstimatorRepresentation,
"Error: estimator " << estimator_id << " specified "
"cell " << extra_cells[i] << " in the xml "
"file, which does not exists!" );
cells.insert( extra_cells[i] );
}
assigned_cells.clear();
assigned_cells.assign( cells.begin(), cells.end() );
#endif // end HAVE_FRENSIE_ROOT
}
// Append surfaces to assigned surfaces
// If Root is not enabled, this function will be empty
void EstimatorHandlerFactory<Geometry::Root>::appendSurfacesToAssignedSurfaces(
const unsigned estimator_id,
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle>&
assigned_surfaces,
const Teuchos::Array<unsigned>& extra_surfaces )
{
#ifdef HAVE_FRENSIE_ROOT
std::set<Geometry::ModuleTraits::InternalSurfaceHandle>
surfaces( assigned_surfaces.begin(), assigned_surfaces.end() );
// Verify that the extra surfaces exist
for( unsigned i = 0u; i < extra_surfaces.size(); ++i )
{
TEST_FOR_EXCEPTION(
!Geometry::ModuleInterface<Geometry::Root>::doesSurfaceExist(
extra_surfaces[i] ),
InvalidEstimatorRepresentation,
"Error: estimator " << estimator_id << " specified "
"surface " << extra_surfaces[i] << " in the "
"xml file, which does not exists!" );
surfaces.insert( extra_surfaces[i] );
}
assigned_surfaces.clear();
assigned_surfaces.assign( surfaces.begin(), surfaces.end() );
#endif // end HAVE_FRENSIE_ROOT
}
// Create the cell volume map
// If Root is not enabled, this function will be empty
void EstimatorHandlerFactory<Geometry::Root>::createCellVolumeMap(
const boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >&
estimator_id_cells_map,
boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,double>&
cell_volume_map )
{
#ifdef HAVE_FRENSIE_ROOT
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle> >::const_iterator
it = estimator_id_cells_map.begin();
TObjArray* volume_list = Geometry::Root::getManager()->GetListOfVolumes();
TIterator* volume_list_iterator = volume_list->MakeIterator();
int number_volumes = volume_list->GetEntries();
for (int i=0; i < number_volumes; i++)
{
TObject* current_object = volume_list_iterator->Next();
TGeoVolume* current_volume = dynamic_cast<TGeoVolume*>( current_object );
if ( current_volume->GetUniqueID() == 0 )
{
THROW_EXCEPTION( std::runtime_error,
"Error: Root contains a cell which has not been "
" assigned a unique cell ID in the input file." );
}
}
while( it != estimator_id_cells_map.end() )
{
for( unsigned i = 0u; i < it->second.size(); ++i )
{
if( cell_volume_map.find( it->second[i] ) == cell_volume_map.end() )
{
cell_volume_map[ it->second[i] ] =
Geometry::ModuleInterface<Geometry::Root>::getCellVolume( it->second[i] );
}
}
++it;
}
#endif // end HAVE_FRENSIE_ROOT
}
// Create the surface area map
// If Root is not enabled, this function will be empty
void EstimatorHandlerFactory<Geometry::Root>::createSurfaceAreaMap(
const boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle> >&
estimator_id_surfaces_map,
boost::unordered_map<Geometry::ModuleTraits::InternalSurfaceHandle,double>&
surface_area_map )
{
#ifdef HAVE_FRENSIE_ROOT
boost::unordered_map<unsigned,
Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle> >::const_iterator
it = estimator_id_surfaces_map.begin();
while( it != estimator_id_surfaces_map.end() )
{
for( unsigned i = 0u; i < it->second.size(); ++i )
{
if( surface_area_map.find( it->second[i] ) == surface_area_map.end() )
{
surface_area_map[it->second[i]] =
Geometry::ModuleInterface<Geometry::Root>::getCellSurfaceArea(
it->second[i],
0 );
}
}
++it;
}
#endif // end HAVE_FRENSIE_ROOT
}
// Create a cell pulse height estimator
void EstimatorHandlerFactory<Geometry::Root>::createPulseHeightEstimator(
const unsigned id,
const double multiplier,
const Teuchos::Array<ParticleType> particle_types,
const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells,
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_funcs,
const bool energy_multiplication,
const Teuchos::ParameterList* bins )
{
// Create the estimator
Teuchos::RCP<Estimator> estimator;
if( energy_multiplication )
{
estimator.reset( new CellPulseHeightEstimator<WeightAndEnergyMultiplier>(
id,
multiplier,
cells ) );
}
else
{
estimator.reset( new CellPulseHeightEstimator<WeightMultiplier>(id,
multiplier,
cells ) );
}
// Set the particle type
estimator->setParticleTypes( particle_types );
// Set the response functions
if( response_funcs.size() > 0 )
estimator->setResponseFunctions( response_funcs );
// Assign estimator bins
if( bins )
EstimatorHandlerFactory<Geometry::Root>::assignBinsToEstimator( *bins, estimator );
// Add this estimator to the handler
if( energy_multiplication )
{
Teuchos::RCP<CellPulseHeightEstimator<WeightAndEnergyMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<CellPulseHeightEstimator<WeightAndEnergyMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, cells );
}
else
{
Teuchos::RCP<CellPulseHeightEstimator<WeightMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<CellPulseHeightEstimator<WeightMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, cells );
}
}
// Create a cell track length flux estimator
void EstimatorHandlerFactory<Geometry::Root>::createCellTrackLengthFluxEstimator(
const unsigned id,
const double multiplier,
const Teuchos::Array<ParticleType> particle_types,
const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells,
const Teuchos::Array<double>& cell_volumes,
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_funcs,
const bool energy_multiplication,
const Teuchos::ParameterList* bins )
{
// Create the estimator
Teuchos::RCP<Estimator> estimator;
if( energy_multiplication )
{
estimator.reset(
new CellTrackLengthFluxEstimator<WeightAndEnergyMultiplier>(
id,
multiplier,
cells,
cell_volumes ) );
}
else
{
estimator.reset( new CellTrackLengthFluxEstimator<WeightMultiplier>(
id,
multiplier,
cells,
cell_volumes ) );
}
// Set the particle type
estimator->setParticleTypes( particle_types );
// Set the response functions
if( response_funcs.size() > 0 )
estimator->setResponseFunctions( response_funcs );
// Assign estimator bins
if( bins )
EstimatorHandlerFactory<Geometry::Root>::assignBinsToEstimator( *bins, estimator );
// Add this estimator to the handler
if( energy_multiplication )
{
Teuchos::RCP<CellTrackLengthFluxEstimator<WeightAndEnergyMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<CellTrackLengthFluxEstimator<WeightAndEnergyMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, cells );
}
else
{
Teuchos::RCP<CellTrackLengthFluxEstimator<WeightMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<CellTrackLengthFluxEstimator<WeightMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, cells );
}
}
// Create a cell collision flux estimator
void EstimatorHandlerFactory<Geometry::Root>::createCellCollisionFluxEstimator(
const unsigned id,
const double multiplier,
const Teuchos::Array<ParticleType> particle_types,
const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells,
const Teuchos::Array<double>& cell_volumes,
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_funcs,
const bool energy_multiplication,
const Teuchos::ParameterList* bins )
{
// Create the estimator
Teuchos::RCP<Estimator> estimator;
if( energy_multiplication )
{
estimator.reset( new CellCollisionFluxEstimator<WeightAndEnergyMultiplier>(
id,
multiplier,
cells,
cell_volumes ) );
}
else
{
estimator.reset( new CellCollisionFluxEstimator<WeightMultiplier>(
id,
multiplier,
cells,
cell_volumes ) );
}
// Set the particle type
estimator->setParticleTypes( particle_types );
// Set the response functions
if( response_funcs.size() > 0 )
estimator->setResponseFunctions( response_funcs );
// Assign estimator bins
if( bins )
EstimatorHandlerFactory<Geometry::Root>::assignBinsToEstimator( *bins, estimator );
// Add this estimator to the handler
if( energy_multiplication )
{
Teuchos::RCP<CellCollisionFluxEstimator<WeightAndEnergyMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<CellCollisionFluxEstimator<WeightAndEnergyMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, cells );
}
else
{
Teuchos::RCP<CellCollisionFluxEstimator<WeightMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<CellCollisionFluxEstimator<WeightMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, cells );
}
}
// Create a surface flux estimator
void EstimatorHandlerFactory<Geometry::Root>::createSurfaceFluxEstimator(
const unsigned id,
const double multiplier,
const Teuchos::Array<ParticleType> particle_types,
const Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle>&
surfaces,
const Teuchos::Array<double>& surface_areas,
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_funcs,
const bool energy_multiplication,
const Teuchos::ParameterList* bins )
{
// Create the estimator
Teuchos::RCP<Estimator> estimator;
if( energy_multiplication )
{
estimator.reset( new SurfaceFluxEstimator<WeightAndEnergyMultiplier>(
id,
multiplier,
surfaces,
surface_areas ) );
}
else
{
estimator.reset( new SurfaceFluxEstimator<WeightMultiplier>(
id,
multiplier,
surfaces,
surface_areas ) );
}
// Set the particle type
estimator->setParticleTypes( particle_types );
// Set the response functions
if( response_funcs.size() > 0 )
estimator->setResponseFunctions( response_funcs );
// Assign estimator bins
if( bins )
EstimatorHandlerFactory<Geometry::Root>::assignBinsToEstimator( *bins, estimator );
// Add this estimator to the handler
if( energy_multiplication )
{
Teuchos::RCP<SurfaceFluxEstimator<WeightAndEnergyMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<SurfaceFluxEstimator<WeightAndEnergyMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, surfaces );
}
else
{
Teuchos::RCP<SurfaceFluxEstimator<WeightMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<SurfaceFluxEstimator<WeightMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, surfaces );
}
}
// Create a surface current estimator
void EstimatorHandlerFactory<Geometry::Root>::createSurfaceCurrentEstimator(
const unsigned id,
const double multiplier,
const Teuchos::Array<ParticleType> particle_types,
const Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle>&
surfaces,
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_funcs,
const bool energy_multiplication,
const Teuchos::ParameterList* bins )
{
// Create the estimator
Teuchos::RCP<Estimator> estimator;
if( energy_multiplication )
{
estimator.reset( new SurfaceCurrentEstimator<WeightAndEnergyMultiplier>(
id,
multiplier,
surfaces ) );
}
else
{
estimator.reset( new SurfaceCurrentEstimator<WeightMultiplier>(
id,
multiplier,
surfaces ) );
}
// Set the particle type
estimator->setParticleTypes( particle_types );
// Set the response functions
if( response_funcs.size() > 0 )
estimator->setResponseFunctions( response_funcs );
// Assign estimator bins
if( bins )
EstimatorHandlerFactory<Geometry::Root>::assignBinsToEstimator( *bins, estimator );
// Add this estimator to the handler
if( energy_multiplication )
{
Teuchos::RCP<SurfaceCurrentEstimator<WeightAndEnergyMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<SurfaceCurrentEstimator<WeightAndEnergyMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, surfaces );
}
else
{
Teuchos::RCP<SurfaceCurrentEstimator<WeightMultiplier> >
derived_estimator = Teuchos::rcp_dynamic_cast<SurfaceCurrentEstimator<WeightMultiplier> >( estimator );
EstimatorHandler::addEstimator( derived_estimator, surfaces );
}
}
// Create a tet mesh track length flux estimator
void EstimatorHandlerFactory<Geometry::Root>::createTetMeshTrackLengthFluxEstimator(
const unsigned id,
const double multiplier,
const Teuchos::Array<ParticleType> particle_types,
const Teuchos::Array<Teuchos::RCP<ResponseFunction> >& response_funcs,
const std::string& mesh_file_name,
const std::string& output_mesh_file_name,
const bool energy_multiplication,
const Teuchos::ParameterList* bins )
{
// ROOT does not currently support the creation of a tet mesh track length
// flux estimator...
}
// Assign bins to an estimator
void EstimatorHandlerFactory<Geometry::Root>::assignBinsToEstimator(
const Teuchos::ParameterList& bins,
Teuchos::RCP<Estimator>& estimator )
{
Teuchos::ParameterList::ConstIterator it = bins.begin();
while( it != bins.end() )
{
if( bins.name( it ) == "Energy Bins" )
{
const Utility::ArrayString& array_string =
Teuchos::any_cast<Utility::ArrayString>( it->second.getAny() );
Teuchos::Array<double> energy_bins;
try{
energy_bins = array_string.getConcreteArray<double>();
}
EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the energy bins requested for "
"estimator " << estimator->getId() <<
" are not valid!" );
TEST_FOR_EXCEPTION(!Utility::Sort::isSortedAscending(energy_bins.begin(),
energy_bins.end() ),
InvalidEstimatorRepresentation,
"Error: the energy bins requested for estimator "
<< estimator->getId() << " are not sorted from "
"lowest to highest!" );
estimator->setBinBoundaries<ENERGY_DIMENSION>( energy_bins );
}
else if( bins.name( it ) == "Time Bins" )
{
const Utility::ArrayString& array_string =
Teuchos::any_cast<Utility::ArrayString>( it->second.getAny() );
Teuchos::Array<double> time_bins;
try{
time_bins = array_string.getConcreteArray<double>();
}
EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the time bins requested for "
"estimator " << estimator->getId() <<
" are not valid!" );
TEST_FOR_EXCEPTION( !Utility::Sort::isSortedAscending( time_bins.begin(),
time_bins.end() ),
InvalidEstimatorRepresentation,
"Error: the time bins requested for estimator "
<< estimator->getId() << " are not sorted from "
"lowest to highest!" );
estimator->setBinBoundaries<TIME_DIMENSION>( time_bins );
}
else if( bins.name( it ) == "Collision Number Bins" )
{
const Utility::ArrayString& array_string =
Teuchos::any_cast<Utility::ArrayString>( it->second.getAny() );
Teuchos::Array<unsigned> col_num_bins;
try{
col_num_bins = array_string.getConcreteArray<unsigned>();
}
EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the collision number bins requested "
"for estimator " << estimator->getId() <<
" are not valid!" );
TEST_FOR_EXCEPTION( !Utility::Sort::isSortedAscending(
col_num_bins.begin(),
col_num_bins.end() ),
InvalidEstimatorRepresentation,
"Error: the collision number bins requested for "
"estimator " << estimator->getId() << " are not "
"sorted from lowest to highest!" );
estimator->setBinBoundaries<COLLISION_NUMBER_DIMENSION>( col_num_bins );
}
else if( bins.name( it ) == "Cosine Bins" )
{
const Utility::ArrayString& array_string =
Teuchos::any_cast<Utility::ArrayString>( it->second.getAny() );
Teuchos::Array<double> cosine_bins;
try{
cosine_bins = array_string.getConcreteArray<double>();
}
EXCEPTION_CATCH_RETHROW_AS( Teuchos::InvalidArrayStringRepresentation,
InvalidEstimatorRepresentation,
"Error: the cosine bins requested "
"for estimator " << estimator->getId() <<
" are not valid!" );
TEST_FOR_EXCEPTION(!Utility::Sort::isSortedAscending(cosine_bins.begin(),
cosine_bins.end() ),
InvalidEstimatorRepresentation,
"Error: the cosine bins requested for estimator "
<< estimator->getId() << " are not sorted from "
"lowest to highest!" );
estimator->setBinBoundaries<COSINE_DIMENSION>( cosine_bins );
}
++it;
}
bins.unused( *s_os_warn );
}
// Fill cell volumes array
void EstimatorHandlerFactory<Geometry::Root>::fillCellVolumesArray(
const Teuchos::Array<Geometry::ModuleTraits::InternalCellHandle>& cells,
const boost::unordered_map<Geometry::ModuleTraits::InternalCellHandle,
double>& cell_volume_map,
Teuchos::Array<double>& cell_volumes )
{
cell_volumes.clear();
cell_volumes.resize( cells.size() );
for( unsigned i = 0; i < cells.size(); ++i )
cell_volumes[i] = cell_volume_map.find( cells[i] )->second;
}
// Fill the surface areas array
void EstimatorHandlerFactory<Geometry::Root>::fillSurfaceAreasArray(
const Teuchos::Array<Geometry::ModuleTraits::InternalSurfaceHandle>&
surfaces,
const boost::unordered_map<Geometry::ModuleTraits::InternalSurfaceHandle,
double>& surface_area_map,
Teuchos::Array<double>& surface_areas )
{
surface_areas.clear();
surface_areas.resize( surfaces.size() );
for( unsigned i = 0; i < surfaces.size(); ++i )
surface_areas[i] = surface_area_map.find( surfaces[i] )->second;
}
// Check if the estimator type is valid
bool EstimatorHandlerFactory<Geometry::Root>::isEstimatorTypeValid(
const std::string& estimator_type )
{
return EstimatorHandlerFactory<Geometry::Root>::isCellEstimatorTypeValid( estimator_type ) ||
EstimatorHandlerFactory<Geometry::Root>::isSurfaceEstimatorTypeValid( estimator_type ) ||
EstimatorHandlerFactory<Geometry::Root>::isMeshEstimatorTypeValid( estimator_type );
}
// Check if a cell estimator type is valid
bool EstimatorHandlerFactory<Geometry::Root>::isCellEstimatorTypeValid(
const std::string& estimator_type )
{
if( estimator_type == EstimatorHandlerFactory<Geometry::Root>::cell_track_length_flux_name )
return true;
else if( estimator_type == EstimatorHandlerFactory<Geometry::Root>::cell_collision_flux_name )
return true;
else if( estimator_type == EstimatorHandlerFactory<Geometry::Root>::cell_pulse_height_name )
return true;
else
return false;
}
// Check if a surface estimator type is valid
bool EstimatorHandlerFactory<Geometry::Root>::isSurfaceEstimatorTypeValid(
const std::string& estimator_type )
{
if( estimator_type == EstimatorHandlerFactory<Geometry::Root>::surface_current_name )
return true;
else if( estimator_type == EstimatorHandlerFactory<Geometry::Root>::surface_flux_name )
return true;
else
return false;
}
// Check if a mesh estimator type is valid
bool EstimatorHandlerFactory<Geometry::Root>::isMeshEstimatorTypeValid(
const std::string& estimator_type )
{
if( estimator_type == EstimatorHandlerFactory<Geometry::Root>::tet_mesh_track_length_flux_name )
return true;
else
return false;
}
#endif // end HAVE_FRENSIE_ROOT
} // end MonteCarlo namespace
//---------------------------------------------------------------------------//
// end MonteCarlo_EstimatorHandlerFactory_Root.cpp
//---------------------------------------------------------------------------//
| 34.544992 | 123 | 0.682189 | lkersting |
163a6e7527f717d8fe00b547b87a5d7c7ac998aa | 9,783 | cc | C++ | packager/media/formats/mp2t/es_parser_audio.cc | MarcusWichelmann/shaka-packager | 02ac2dfb3990403984c53275a983443bb520ebe1 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | packager/media/formats/mp2t/es_parser_audio.cc | MarcusWichelmann/shaka-packager | 02ac2dfb3990403984c53275a983443bb520ebe1 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | packager/media/formats/mp2t/es_parser_audio.cc | MarcusWichelmann/shaka-packager | 02ac2dfb3990403984c53275a983443bb520ebe1 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "packager/media/formats/mp2t/es_parser_audio.h"
#include <stdint.h>
#include <algorithm>
#include <list>
#include "packager/base/logging.h"
#include "packager/base/strings/string_number_conversions.h"
#include "packager/media/base/audio_timestamp_helper.h"
#include "packager/media/base/bit_reader.h"
#include "packager/media/base/media_sample.h"
#include "packager/media/base/timestamp.h"
#include "packager/media/formats/mp2t/ac3_header.h"
#include "packager/media/formats/mp2t/adts_header.h"
#include "packager/media/formats/mp2t/mp2t_common.h"
#include "packager/media/formats/mp2t/mpeg1_header.h"
#include "packager/media/formats/mp2t/ts_stream_type.h"
namespace shaka {
namespace media {
namespace mp2t {
// Look for a syncword.
// |new_pos| returns
// - either the byte position of the frame (if found)
// - or the byte position of 1st byte that was not processed (if not found).
// In every case, the returned value in |new_pos| is such that new_pos >= pos
// |audio_header| is updated with the new audio frame info if a syncword is
// found.
// Return whether a syncword was found.
static bool LookForSyncWord(const uint8_t* raw_es,
int raw_es_size,
int pos,
int* new_pos,
AudioHeader* audio_header) {
DCHECK_GE(pos, 0);
DCHECK_LE(pos, raw_es_size);
const int max_offset =
raw_es_size - static_cast<int>(audio_header->GetMinFrameSize());
if (pos >= max_offset) {
// Do not change the position if:
// - max_offset < 0: not enough bytes to get a full header
// Since pos >= 0, this is a subcase of the next condition.
// - pos >= max_offset: might be the case after reading one full frame,
// |pos| is then incremented by the frame size and might then point
// to the end of the buffer.
*new_pos = pos;
return false;
}
for (int offset = pos; offset < max_offset; offset++) {
const uint8_t* cur_buf = &raw_es[offset];
if (!audio_header->IsSyncWord(cur_buf))
continue;
const size_t remaining_size = static_cast<size_t>(raw_es_size - offset);
const int kSyncWordSize = 2;
const size_t frame_size =
audio_header->GetFrameSizeWithoutParsing(cur_buf, remaining_size);
if (frame_size < audio_header->GetMinFrameSize())
// Too short to be a valid frame.
continue;
if (remaining_size < frame_size)
// Not a full frame: will resume when we have more data.
return false;
// Check whether there is another frame |size| apart from the current one.
if (remaining_size >= frame_size + kSyncWordSize &&
!audio_header->IsSyncWord(&cur_buf[frame_size])) {
continue;
}
if (!audio_header->Parse(cur_buf, frame_size))
continue;
*new_pos = offset;
return true;
}
*new_pos = max_offset;
return false;
}
EsParserAudio::EsParserAudio(uint32_t pid,
std::shared_ptr<DiscontinuityTracker> discontinuity_tracker,
TsStreamType stream_type,
const NewStreamInfoCB& new_stream_info_cb,
const EmitSampleCB& emit_sample_cb,
bool sbr_in_mimetype)
: EsParser(pid, discontinuity_tracker),
stream_type_(stream_type),
new_stream_info_cb_(new_stream_info_cb),
emit_sample_cb_(emit_sample_cb),
sbr_in_mimetype_(sbr_in_mimetype) {
if (stream_type == TsStreamType::kAc3) {
audio_header_.reset(new Ac3Header);
} else if (stream_type == TsStreamType::kMpeg1Audio) {
audio_header_.reset(new Mpeg1Header);
} else {
DCHECK_EQ(stream_type, TsStreamType::kAdtsAac);
audio_header_.reset(new AdtsHeader);
}
}
EsParserAudio::~EsParserAudio() {}
bool EsParserAudio::Parse(const uint8_t* buf,
int size,
int64_t pts,
int64_t dts) {
int raw_es_size;
const uint8_t* raw_es;
// The incoming PTS applies to the access unit that comes just after
// the beginning of |buf|.
if (pts != kNoTimestamp) {
es_byte_queue_.Peek(&raw_es, &raw_es_size);
pts_list_.push_back(EsPts(raw_es_size, pts));
}
// Copy the input data to the ES buffer.
es_byte_queue_.Push(buf, static_cast<int>(size));
es_byte_queue_.Peek(&raw_es, &raw_es_size);
// Look for every frame in the ES buffer starting at offset = 0
int es_position = 0;
while (LookForSyncWord(raw_es, raw_es_size, es_position, &es_position,
audio_header_.get())) {
const uint8_t* frame_ptr = raw_es + es_position;
DVLOG(LOG_LEVEL_ES) << "syncword @ pos=" << es_position
<< " frame_size=" << audio_header_->GetFrameSize();
DVLOG(LOG_LEVEL_ES) << "header: "
<< base::HexEncode(frame_ptr,
audio_header_->GetHeaderSize());
// Do not process the frame if this one is a partial frame.
int remaining_size = raw_es_size - es_position;
if (static_cast<int>(audio_header_->GetFrameSize()) > remaining_size)
break;
// Update the audio configuration if needed.
if (!UpdateAudioConfiguration(*audio_header_))
return false;
// Get the PTS & the duration of this access unit.
while (!pts_list_.empty() && pts_list_.front().first <= es_position) {
audio_timestamp_helper_->SetBaseTimestamp(pts_list_.front().second);
pts_list_.pop_front();
}
int64_t current_pts = audio_timestamp_helper_->GetTimestamp();
int64_t frame_duration = audio_timestamp_helper_->GetFrameDuration(
audio_header_->GetSamplesPerFrame());
// Emit an audio frame.
bool is_key_frame = true;
std::shared_ptr<MediaSample> sample = MediaSample::CopyFrom(
frame_ptr + audio_header_->GetHeaderSize(),
audio_header_->GetFrameSize() - audio_header_->GetHeaderSize(),
is_key_frame);
sample->set_pts(current_pts);
sample->set_dts(current_pts);
sample->set_duration(frame_duration);
emit_sample_cb_.Run(sample);
// Update the PTS of the next frame.
audio_timestamp_helper_->AddFrames(audio_header_->GetSamplesPerFrame());
// Skip the current frame.
es_position += static_cast<int>(audio_header_->GetFrameSize());
}
// Discard all the bytes that have been processed.
DiscardEs(es_position);
return true;
}
bool EsParserAudio::Flush() {
return true;
}
void EsParserAudio::Reset() {
es_byte_queue_.Reset();
pts_list_.clear();
last_audio_decoder_config_ = std::shared_ptr<AudioStreamInfo>();
}
bool EsParserAudio::UpdateAudioConfiguration(const AudioHeader& audio_header) {
const uint8_t kAacSampleSizeBits(16);
std::vector<uint8_t> audio_specific_config;
audio_header.GetAudioSpecificConfig(&audio_specific_config);
if (last_audio_decoder_config_) {
// Verify that the audio decoder config has not changed.
if (last_audio_decoder_config_->codec_config() == audio_specific_config) {
// Audio configuration has not changed.
return true;
}
NOTIMPLEMENTED() << "Varying audio configurations are not supported.";
return false;
}
// The following code is written according to ISO 14496 Part 3 Table 1.11 and
// Table 1.22. (Table 1.11 refers to the capping to 48000, Table 1.22 refers
// to SBR doubling the AAC sample rate.)
int samples_per_second = audio_header.GetSamplingFrequency();
// TODO(kqyang): Review if it makes sense to have |sbr_in_mimetype_| in
// es_parser.
int extended_samples_per_second =
sbr_in_mimetype_ ? std::min(2 * samples_per_second, 48000)
: samples_per_second;
const Codec codec =
stream_type_ == TsStreamType::kAc3
? kCodecAC3
: (stream_type_ == TsStreamType::kMpeg1Audio ? kCodecMP3 : kCodecAAC);
last_audio_decoder_config_ = std::make_shared<AudioStreamInfo>(
pid(), kMpeg2Timescale, kInfiniteDuration, codec,
AudioStreamInfo::GetCodecString(codec, audio_header.GetObjectType()),
audio_specific_config.data(), audio_specific_config.size(),
kAacSampleSizeBits, audio_header.GetNumChannels(),
extended_samples_per_second, 0 /* seek preroll */, 0 /* codec delay */,
0 /* max bitrate */, 0 /* avg bitrate */, std::string(), false);
DVLOG(1) << "Sampling frequency: " << samples_per_second;
DVLOG(1) << "Extended sampling frequency: " << extended_samples_per_second;
DVLOG(1) << "Channel config: "
<< static_cast<int>(audio_header.GetNumChannels());
DVLOG(1) << "Object type: " << static_cast<int>(audio_header.GetObjectType());
// Reset the timestamp helper to use a new sampling frequency.
if (audio_timestamp_helper_) {
int64_t base_timestamp = audio_timestamp_helper_->GetTimestamp();
audio_timestamp_helper_.reset(
new AudioTimestampHelper(kMpeg2Timescale, samples_per_second));
audio_timestamp_helper_->SetBaseTimestamp(base_timestamp);
} else {
audio_timestamp_helper_.reset(
new AudioTimestampHelper(kMpeg2Timescale, extended_samples_per_second));
}
// Audio config notification.
new_stream_info_cb_.Run(last_audio_decoder_config_);
return true;
}
void EsParserAudio::DiscardEs(int nbytes) {
DCHECK_GE(nbytes, 0);
if (nbytes <= 0)
return;
// Adjust the ES position of each PTS.
for (EsPtsList::iterator it = pts_list_.begin(); it != pts_list_.end(); ++it)
it->first -= nbytes;
// Discard |nbytes| of ES.
es_byte_queue_.Pop(nbytes);
}
} // namespace mp2t
} // namespace media
} // namespace shaka
| 35.966912 | 89 | 0.682102 | MarcusWichelmann |
163b1d2e6e32094a5f4fc7850b2e88ccaf0997e5 | 1,318 | cpp | C++ | examples/cpp/comm/event/event.cpp | grisharav/bond | db05b170c83f74d0ea561d109ea90ed63b13cfa6 | [
"MIT"
] | null | null | null | examples/cpp/comm/event/event.cpp | grisharav/bond | db05b170c83f74d0ea561d109ea90ed63b13cfa6 | [
"MIT"
] | null | null | null | examples/cpp/comm/event/event.cpp | grisharav/bond | db05b170c83f74d0ea561d109ea90ed63b13cfa6 | [
"MIT"
] | null | null | null |
//
// This is an example of a service, that waits for events.
//
// Include auto-generated files.
#include "event_reflection.h"
#include "event_comm.h"
// Include preferred transport
#include <bond/comm/transport/epoxy.h>
#include <future>
using namespace examples::event;
// Implement service
class ServiceImpl : public Service
{
void Poke(const bond::comm::payload<Signal>& input) override
{
// Store incoming signal
m_promise.set_value(input.value().Deserialize());
}
std::promise<Signal> m_promise;
public:
ServiceImpl(std::promise<Signal>&& promise)
: m_promise(std::move(promise))
{}
};
int BOND_CALL main()
{
bond::comm::SocketAddress loopback("127.0.0.1", TEST_PORT_1);
bond::comm::epoxy::EpoxyTransport transport;
// Setup event confirmation
std::promise<Signal> promise;
std::future<Signal> future = promise.get_future();
// Instantiate service to be published
ServiceImpl service(std::move(promise));
auto server = transport.Bind(loopback, boost::ref(service));
// Signal to send
Signal signal;
signal.x = 42;
Service::Proxy proxy(transport.Connect(loopback));
proxy.Poke(signal);
// Not an error, expected signal received by server.
assert(42 == future.get().x);
return 0;
}
| 21.258065 | 65 | 0.672989 | grisharav |
163cc95c6a97ea9b78a1919f26670e1fc8ae7228 | 115 | cpp | C++ | 22-matrix/cpp/matrix.cpp | skaadin/learning-projects | 977efa1eabab038566d57c455e649da8b440c7e9 | [
"MIT"
] | 143 | 2016-07-28T06:00:43.000Z | 2022-03-30T14:08:50.000Z | 22-matrix/cpp/matrix.cpp | skaadin/learning-projects | 977efa1eabab038566d57c455e649da8b440c7e9 | [
"MIT"
] | 3 | 2017-11-28T10:09:52.000Z | 2021-08-30T09:20:41.000Z | 22-matrix/cpp/matrix.cpp | skaadin/learning-projects | 977efa1eabab038566d57c455e649da8b440c7e9 | [
"MIT"
] | 24 | 2016-10-27T02:02:44.000Z | 2022-02-06T07:37:07.000Z | #include "matrix.h"
template<typename T>
Matrix<T>::Matrix(unsigned _rows, unsigned _cols, const T& _initial) {
} | 19.166667 | 70 | 0.730435 | skaadin |
163f9a502544c4964749390feb397ba8a80596bf | 2,047 | hpp | C++ | src/Instruction.hpp | zlin888/irispl | ee2228eb1155c4cffb906a327b7257fb1d360590 | [
"MIT"
] | 4 | 2020-04-01T05:45:30.000Z | 2020-05-14T06:38:25.000Z | src/Instruction.hpp | zlin888/typed-scheme | ee2228eb1155c4cffb906a327b7257fb1d360590 | [
"MIT"
] | null | null | null | src/Instruction.hpp | zlin888/typed-scheme | ee2228eb1155c4cffb906a327b7257fb1d360590 | [
"MIT"
] | null | null | null | //
// Created by Zhitao Lin on 2020/2/7.
//
#ifndef TYPED_SCHEME_INSTRUCTION_HPP
#define TYPED_SCHEME_INSTRUCTION_HPP
#include "Utils.hpp"
#include "IrisObject.hpp"
#include <string>
#include <regex>
enum class InstructionType {
LABEL, COMMENT, INSTRUCTION
};
typedef Type InstructionArgumentType;
using namespace std;
class Instruction{
public:
InstructionType type;
InstructionArgumentType argumentType{};
string instructionStr{};
string mnemonic{};
string argument{};
explicit Instruction(string instString);
static InstructionArgumentType getArgumentType(string arg);
};
Instruction::Instruction(string instString){
//process the instString and construct Instruction object
instString = utils::trim(instString);
if (instString[0] == ';'){
this->type = InstructionType::COMMENT;
this->instructionStr = instString;
this->argument = instString;
} else if(instString[0] == '@'){
this->type = InstructionType::LABEL;
this->instructionStr = instString;
this->argument = instString;
} else {
this->type = InstructionType::INSTRUCTION;
this->instructionStr = instString;
//Split instructionStr string by whitespace, the first split is mnemonic and the last is argument
string delimiter = " ";
int splitIndex = instString.find(delimiter);
this->mnemonic = instString.substr(0, splitIndex);
if (splitIndex != -1 && splitIndex + 1 < instString.size()) {
this->argument = instString.substr(splitIndex + 1, instString.size());
}
this->argumentType = this->getArgumentType(this->argument);
// cout << "arg -> " + this->argument + " -- " + this->argumentType + "\n";
// string fields = instString.split(/\s+/i);
// this->mnemonic = fields[0].toLowerCase();
// this->argument = fields[1];
}
}
InstructionArgumentType Instruction::getArgumentType(string arg) {
return typeOfStr(arg);
};
#endif //TYPED_SCHEME_INSTRUCTION_HPP
| 28.430556 | 105 | 0.66683 | zlin888 |
164015c21310c532e9555386da829ef2916f23c7 | 1,027 | cc | C++ | nox/src/lib/errno_exception.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 28 | 2015-02-04T13:59:25.000Z | 2021-12-29T03:44:47.000Z | nox/src/lib/errno_exception.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 552 | 2015-01-05T18:25:54.000Z | 2022-03-16T18:51:13.000Z | nox/src/lib/errno_exception.cc | ayjazz/OESS | deadc504d287febc7cbd7251ddb102bb5c8b1f04 | [
"Apache-2.0"
] | 25 | 2015-02-04T18:48:20.000Z | 2020-06-18T15:51:05.000Z | /* Copyright 2008 (C) Nicira, Inc.
*
* This file is part of NOX.
*
* NOX 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.
*
* NOX 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 NOX. If not, see <http://www.gnu.org/licenses/>.
*/
#include "errno_exception.hh"
#include <cstring>
#include <sstream>
namespace vigil {
std::string errno_exception::format(int error, const std::string& msg)
{
if (error != 0) {
std::ostringstream stream;
stream << msg << ": " << ::strerror(error);
return stream.str();
} else {
return msg;
}
}
} // namespace vigil
| 28.527778 | 71 | 0.700097 | ayjazz |
f37eb3020f4934146d3ad4cfa9d402c19d058026 | 11,557 | cxx | C++ | Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx | lfyater/Orfeo | eb3d4d56089065b99641d8ae7338d2ed0358d28a | [
"Apache-2.0"
] | 2 | 2019-02-13T14:48:19.000Z | 2019-12-03T02:54:28.000Z | Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx | lfyater/Orfeo | eb3d4d56089065b99641d8ae7338d2ed0358d28a | [
"Apache-2.0"
] | null | null | null | Modules/Applications/AppClassification/app/otbTrainVectorClassifier.cxx | lfyater/Orfeo | eb3d4d56089065b99641d8ae7338d2ed0358d28a | [
"Apache-2.0"
] | 2 | 2019-01-17T10:36:14.000Z | 2019-12-03T02:54:36.000Z | /*
* Copyright (C) 2005-2017 Centre National d'Etudes Spatiales (CNES)
*
* This file is part of Orfeo Toolbox
*
* https://www.orfeo-toolbox.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 "otbTrainVectorBase.h"
// Validation
#include "otbConfusionMatrixCalculator.h"
#include "otbContingencyTableCalculator.h"
namespace otb
{
namespace Wrapper
{
class TrainVectorClassifier : public TrainVectorBase
{
public:
typedef TrainVectorClassifier Self;
typedef TrainVectorBase Superclass;
typedef itk::SmartPointer<Self> Pointer;
typedef itk::SmartPointer<const Self> ConstPointer;
itkNewMacro( Self )
itkTypeMacro( Self, Superclass )
typedef Superclass::SampleType SampleType;
typedef Superclass::ListSampleType ListSampleType;
typedef Superclass::TargetListSampleType TargetListSampleType;
// Estimate performance on validation sample
typedef otb::ConfusionMatrixCalculator<TargetListSampleType, TargetListSampleType> ConfusionMatrixCalculatorType;
typedef ConfusionMatrixCalculatorType::ConfusionMatrixType ConfusionMatrixType;
typedef ConfusionMatrixCalculatorType::MapOfIndicesType MapOfIndicesType;
typedef ConfusionMatrixCalculatorType::ClassLabelType ClassLabelType;
typedef ContingencyTable<ClassLabelType> ContingencyTableType;
typedef ContingencyTableType::Pointer ContingencyTablePointerType;
protected:
void DoInit()
{
SetName( "TrainVectorClassifier" );
SetDescription( "Train a classifier based on labeled geometries and a "
"list of features to consider." );
SetDocName( "Train Vector Classifier" );
SetDocLongDescription( "This application trains a classifier based on "
"labeled geometries and a list of features to consider for "
"classification." );
SetDocLimitations( " " );
SetDocAuthors( "OTB Team" );
SetDocSeeAlso( " " );
SetOfficialDocLink();
Superclass::DoInit();
}
void DoUpdateParameters()
{
Superclass::DoUpdateParameters();
}
void DoExecute()
{
m_FeaturesInfo.SetClassFieldNames( GetChoiceNames( "cfield" ), GetSelectedItems( "cfield" ) );
if( m_FeaturesInfo.m_SelectedCFieldIdx.empty() && GetClassifierCategory() == Supervised )
{
otbAppLogFATAL( << "No field has been selected for data labelling!" );
}
Superclass::DoExecute();
if (GetClassifierCategory() == Supervised)
{
ConfusionMatrixCalculatorType::Pointer confMatCalc = ComputeConfusionMatrix( m_PredictedList,
m_ClassificationSamplesWithLabel.labeledListSample );
WriteConfusionMatrix( confMatCalc );
}
else
{
ContingencyTablePointerType table = ComputeContingencyTable( m_PredictedList,
m_ClassificationSamplesWithLabel.labeledListSample );
WriteContingencyTable( table );
}
}
ContingencyTablePointerType ComputeContingencyTable(const TargetListSampleType::Pointer &predictedListSample,
const TargetListSampleType::Pointer &performanceLabeledListSample)
{
typedef ContingencyTableCalculator<ClassLabelType> ContigencyTableCalcutaltorType;
ContigencyTableCalcutaltorType::Pointer contingencyTableCalculator = ContigencyTableCalcutaltorType::New();
contingencyTableCalculator->Compute(performanceLabeledListSample->Begin(),
performanceLabeledListSample->End(),predictedListSample->Begin(), predictedListSample->End());
if(IsParameterEnabled("v"))
{
otbAppLogINFO( "Training performances:" );
otbAppLogINFO(<<"Contingency table: reference labels (rows) vs. produced labels (cols)\n"
<<contingencyTableCalculator->BuildContingencyTable());
}
return contingencyTableCalculator->BuildContingencyTable();
}
void WriteContingencyTable(const ContingencyTablePointerType& table)
{
if(IsParameterEnabled("io.confmatout"))
{
// Write contingency table
std::ofstream outFile;
outFile.open( this->GetParameterString( "io.confmatout" ).c_str() );
outFile << table->ToCSV();
}
}
ConfusionMatrixCalculatorType::Pointer
ComputeConfusionMatrix(const TargetListSampleType::Pointer &predictedListSample,
const TargetListSampleType::Pointer &performanceLabeledListSample)
{
ConfusionMatrixCalculatorType::Pointer confMatCalc = ConfusionMatrixCalculatorType::New();
otbAppLogINFO( "Predicted list size : " << predictedListSample->Size() );
otbAppLogINFO( "ValidationLabeledListSample size : " << performanceLabeledListSample->Size() );
confMatCalc->SetReferenceLabels( performanceLabeledListSample );
confMatCalc->SetProducedLabels( predictedListSample );
confMatCalc->Compute();
otbAppLogINFO( "Training performances:" );
LogConfusionMatrix( confMatCalc );
for( unsigned int itClasses = 0; itClasses < confMatCalc->GetNumberOfClasses(); itClasses++ )
{
ConfusionMatrixCalculatorType::ClassLabelType classLabel = confMatCalc->GetMapOfIndices()[itClasses];
otbAppLogINFO( "Precision of class [" << classLabel << "] vs all: " << confMatCalc->GetPrecisions()[itClasses] );
otbAppLogINFO( "Recall of class [" << classLabel << "] vs all: " << confMatCalc->GetRecalls()[itClasses] );
otbAppLogINFO(
"F-score of class [" << classLabel << "] vs all: " << confMatCalc->GetFScores()[itClasses] << "\n" );
}
otbAppLogINFO( "Global performance, Kappa index: " << confMatCalc->GetKappaIndex() );
return confMatCalc;
}
/**
* Write the confidence matrix into a file if output is provided.
* \param confMatCalc the input matrix to write.
*/
void WriteConfusionMatrix(const ConfusionMatrixCalculatorType::Pointer &confMatCalc)
{
if( this->HasValue( "io.confmatout" ) )
{
// Writing the confusion matrix in the output .CSV file
MapOfIndicesType::iterator itMapOfIndicesValid, itMapOfIndicesPred;
ClassLabelType labelValid = 0;
ConfusionMatrixType confusionMatrix = confMatCalc->GetConfusionMatrix();
MapOfIndicesType mapOfIndicesValid = confMatCalc->GetMapOfIndices();
unsigned long nbClassesPred = mapOfIndicesValid.size();
/////////////////////////////////////////////
// Filling the 2 headers for the output file
const std::string commentValidStr = "#Reference labels (rows):";
const std::string commentPredStr = "#Produced labels (columns):";
const char separatorChar = ',';
std::ostringstream ossHeaderValidLabels, ossHeaderPredLabels;
// Filling ossHeaderValidLabels and ossHeaderPredLabels for the output file
ossHeaderValidLabels << commentValidStr;
ossHeaderPredLabels << commentPredStr;
itMapOfIndicesValid = mapOfIndicesValid.begin();
while( itMapOfIndicesValid != mapOfIndicesValid.end() )
{
// labels labelValid of mapOfIndicesValid are already sorted in otbConfusionMatrixCalculator
labelValid = itMapOfIndicesValid->second;
otbAppLogINFO( "mapOfIndicesValid[" << itMapOfIndicesValid->first << "] = " << labelValid );
ossHeaderValidLabels << labelValid;
ossHeaderPredLabels << labelValid;
++itMapOfIndicesValid;
if( itMapOfIndicesValid != mapOfIndicesValid.end() )
{
ossHeaderValidLabels << separatorChar;
ossHeaderPredLabels << separatorChar;
}
else
{
ossHeaderValidLabels << std::endl;
ossHeaderPredLabels << std::endl;
}
}
std::ofstream outFile;
outFile.open( this->GetParameterString( "io.confmatout" ).c_str() );
outFile << std::fixed;
outFile.precision( 10 );
/////////////////////////////////////
// Writing the 2 headers
outFile << ossHeaderValidLabels.str();
outFile << ossHeaderPredLabels.str();
/////////////////////////////////////
unsigned int indexLabelValid = 0, indexLabelPred = 0;
for( itMapOfIndicesValid = mapOfIndicesValid.begin();
itMapOfIndicesValid != mapOfIndicesValid.end(); ++itMapOfIndicesValid )
{
indexLabelPred = 0;
for( itMapOfIndicesPred = mapOfIndicesValid.begin();
itMapOfIndicesPred != mapOfIndicesValid.end(); ++itMapOfIndicesPred )
{
// Writing the confusion matrix (sorted in otbConfusionMatrixCalculator) in the output file
outFile << confusionMatrix( indexLabelValid, indexLabelPred );
if( indexLabelPred < ( nbClassesPred - 1 ) )
{
outFile << separatorChar;
}
else
{
outFile << std::endl;
}
++indexLabelPred;
}
++indexLabelValid;
}
outFile.close();
}
}
/**
* Display the log of the confusion matrix computed with
* \param confMatCalc the input confusion matrix to display
*/
void LogConfusionMatrix(ConfusionMatrixCalculatorType *confMatCalc)
{
ConfusionMatrixCalculatorType::ConfusionMatrixType matrix = confMatCalc->GetConfusionMatrix();
// Compute minimal width
size_t minwidth = 0;
for( unsigned int i = 0; i < matrix.Rows(); i++ )
{
for( unsigned int j = 0; j < matrix.Cols(); j++ )
{
std::ostringstream os;
os << matrix( i, j );
size_t size = os.str().size();
if( size > minwidth )
{
minwidth = size;
}
}
}
MapOfIndicesType mapOfIndices = confMatCalc->GetMapOfIndices();
MapOfIndicesType::const_iterator it = mapOfIndices.begin();
MapOfIndicesType::const_iterator end = mapOfIndices.end();
for( ; it != end; ++it )
{
std::ostringstream os;
os << "[" << it->second << "]";
size_t size = os.str().size();
if( size > minwidth )
{
minwidth = size;
}
}
// Generate matrix string, with 'minwidth' as size specifier
std::ostringstream os;
// Header line
for( size_t i = 0; i < minwidth; ++i )
os << " ";
os << " ";
it = mapOfIndices.begin();
end = mapOfIndices.end();
for( ; it != end; ++it )
{
os << "[" << it->second << "]" << " ";
}
os << std::endl;
// Each line of confusion matrix
for( unsigned int i = 0; i < matrix.Rows(); i++ )
{
ConfusionMatrixCalculatorType::ClassLabelType label = mapOfIndices[i];
os << "[" << std::setw( minwidth - 2 ) << label << "]" << " ";
for( unsigned int j = 0; j < matrix.Cols(); j++ )
{
os << std::setw( minwidth ) << matrix( i, j ) << " ";
}
os << std::endl;
}
otbAppLogINFO( "Confusion matrix (rows = reference labels, columns = produced labels):\n" << os.str() );
}
};
}
}
OTB_APPLICATION_EXPORT( otb::Wrapper::TrainVectorClassifier )
| 33.792398 | 136 | 0.652332 | lfyater |
f37ed7c34d6a0e5fa8dbf7eabe786acbdb52c244 | 12,168 | cc | C++ | src/crawler_robot_ros/src/teleop_crawler.cc | m-shimizu/Samples_Gazebo_ROS | 54ecfc2d77dc8aacce010151593d1d08d04f7bce | [
"MIT"
] | 5 | 2019-01-08T12:54:10.000Z | 2022-02-18T10:08:22.000Z | src/crawler_robot_ros/src/teleop_crawler.cc | RoboCup-RSVRL/RoboCup2021RVRL_Demo | 431e18505abf34353de526c2b4f5ad75046ea07e | [
"MIT"
] | 2 | 2019-01-11T14:32:07.000Z | 2020-01-17T10:20:08.000Z | src/crawler_robot_ros/src/teleop_crawler.cc | m-shimizu/Samples_Gazebo_ROS | 54ecfc2d77dc8aacce010151593d1d08d04f7bce | [
"MIT"
] | 2 | 2019-03-20T04:51:08.000Z | 2020-06-22T06:32:16.000Z | //=============================================================================
// This program is a modification of
// $(find hector_quadrotor_teleop)/src/quadrotor_teleop.cpp
// Editor : Masaru Shimizu
// E-mail : shimizu@sist.chukyo-u.ac.jp
// Updated : 25 Mar.2018
//=============================================================================
// Copyright (c) 2012-2016, Institute of Flight Systems and Automatic Control,
// Technische Universität Darmstadt.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of hector_quadrotor 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 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 <ros/ros.h>
#include <sensor_msgs/Joy.h>
#include <geometry_msgs/TwistStamped.h>
#include <tf2_geometry_msgs/tf2_geometry_msgs.h>
#include <actionlib/client/simple_action_client.h>
namespace teleop_crawler
{
class Teleop
{
private:
ros::NodeHandle node_handle_;
ros::Subscriber joy_subscriber;
ros::Publisher velocity_publisher, flipper_publisher;
std::string topicname_cmd_vel,
topicname_cmd_flipper,
topicname_joy,
framename_base_link,
framename_world;
struct Axis
{
Axis(const std::string& _name)
: axis(0), factor(0.0), offset(0.0), name(_name)
{}
int axis;
double factor;
double offset;
std::string name;
};
struct Velocity
{
Velocity()
: speed("Speed"), turn("Turn")
{}
Axis speed, turn;
} velocity;
struct Flipper
{
Flipper(const std::string& _name)
: w(5.0), currentAngle(0.0), defaultAngle(M_PI/4.0),
upButton(0), downButton(0), name(_name)
{}
int upButton, downButton, last_upB, last_downB;
double w;
double currentAngle;
double defaultAngle;
std::string name;
};
struct Flippers
{
Flippers()
: fr("fr"), fl("fl"), rr("rr"), rl("rl")
{}
Flipper fr, fl, rr, rl;
} flipper;
public:
void Usage(void)
{
printf("==================== Joystick Usage ====================\n");
printf("\n");
printf(" Robot Moving : The left analog stick\n");
printf("--------------------------------------------------------\n");
printf(" Flipper Moving : (followings are number of button)\n");
printf(" Front Right : up=%d , down=%d\n"
, flipper.fr.upButton+1, flipper.fr.downButton+1);
printf(" Front Left : up=%d , down=%d\n"
, flipper.fl.upButton+1, flipper.fl.downButton+1);
printf(" Rear Right : up=%d , down=%d\n"
, flipper.rr.upButton+1, flipper.rr.downButton+1);
printf(" Rear Left : up=%d , down=%d\n"
, flipper.rl.upButton+1, flipper.rl.downButton+1);
printf("\n");
printf("========================================================\n");
}
Teleop()
{
// Make a nodehandle for reading parameters from the local namespace.
ros::NodeHandle _nh("~");
// TODO Read Topicnames and framenames
_nh.param<std::string>("topicNameJoy", topicname_joy, "joy");
_nh.param<std::string>("frameNameWorld", framename_world,"world");
_nh.param<std::string>("frameNameBaselink", framename_base_link,
"base_link");
_nh.param<std::string>("topicNameCmdvel", topicname_cmd_vel,
"cmd_vel");
_nh.param<std::string>("topicNameCmdflipper", topicname_cmd_flipper,
"cmd_flipper");
// Read parameters for structure velocity
_nh.param<int>( "speedAxis", velocity.speed.axis, 1);
_nh.param<int>( "turnAxis", velocity.turn.axis, 0);
_nh.param<double>("maxSpeed", velocity.speed.factor, .5);
_nh.param<double>("maxTurnW", velocity.turn.factor, 2.0*M_PI/4.0);
// Read parameters for structure flipper.fr
_nh.param<int>( "frUpButton", flipper.fr.upButton, 9);
_nh.param<int>( "frDownButton", flipper.fr.downButton, 7);
_nh.param<double>("frW", flipper.fr.w, 2.0*M_PI/20.0);
_nh.param<double>("frDefaultAngle", flipper.fr.defaultAngle, M_PI/4.0);
flipper.fr.currentAngle = flipper.fr.defaultAngle;
flipper.fr.last_upB = flipper.fr.last_downB = 0;
// Read parameters for structure flipper.fr
_nh.param<int>( "flUpButton", flipper.fl.upButton, 8);
_nh.param<int>( "flDownButton", flipper.fl.downButton, 6);
_nh.param<double>("flW", flipper.fl.w, 2.0*M_PI/20.0);
_nh.param<double>("flDefaultAngle", flipper.fl.defaultAngle, M_PI/4.0);
flipper.fl.currentAngle = flipper.fl.defaultAngle;
flipper.fl.last_upB = flipper.fl.last_downB = 0;
// Read parameters for structure flipper.fr
_nh.param<int>( "rrUpButton", flipper.rr.upButton, 13);
_nh.param<int>( "rrDownButton", flipper.rr.downButton, 15);
_nh.param<double>("rrW", flipper.rr.w, 2.0*M_PI/20.0);
_nh.param<double>("rrDefaultAngle", flipper.rr.defaultAngle, M_PI/4.0);
flipper.rr.currentAngle = flipper.rr.defaultAngle;
flipper.rr.last_upB = flipper.rr.last_downB = 0;
// Read parameters for structure flipper.fr
_nh.param<int>( "rlUpButton", flipper.rl.upButton, 12);
_nh.param<int>( "rlDownButton", flipper.rl.downButton, 14);
_nh.param<double>("rlW", flipper.rl.w, 2.0*M_PI/20.0);
_nh.param<double>("rlDefaultAngle", flipper.rl.defaultAngle, M_PI/4.0);
flipper.rl.currentAngle = flipper.rl.defaultAngle;
flipper.rl.last_upB = flipper.rl.last_downB = 0;
joy_subscriber = node_handle_.subscribe<sensor_msgs::Joy>(topicname_joy, 1,
boost::bind(&Teleop::joyCallback, this, _1));
velocity_publisher = node_handle_.advertise<geometry_msgs::TwistStamped>
(topicname_cmd_vel, 10);
flipper_publisher = node_handle_.advertise<geometry_msgs::TwistStamped>
(topicname_cmd_flipper, 10);
}
~Teleop()
{
stop();
}
double updateCurrentFlipperAngle(Flipper& flpr,
const sensor_msgs::JoyConstPtr& joy)
{
int currentUpButton, currentDownButton;
currentUpButton = getUpButton(joy, flpr);
currentDownButton = getDownButton(joy, flpr);
if(currentUpButton && currentDownButton)
flpr.currentAngle = flpr.defaultAngle;
else if(currentUpButton)
flpr.currentAngle += flpr.w;
else if(currentDownButton)
flpr.currentAngle -= flpr.w;
return flpr.currentAngle;
}
void publish_flipper(void)
{
geometry_msgs::TwistStamped flp_ts;
flp_ts.header.frame_id = framename_base_link;
flp_ts.header.stamp = ros::Time::now();
flp_ts.twist.linear.x = flipper.fr.currentAngle;
flp_ts.twist.linear.y = flipper.fl.currentAngle;
flp_ts.twist.linear.z = 0;
flp_ts.twist.angular.x = flipper.rr.currentAngle;
flp_ts.twist.angular.y = flipper.rl.currentAngle;
flp_ts.twist.angular.z = 0;
flipper_publisher.publish(flp_ts);
/*MEMO
geometry_msgs::Twist flp_ts;
flp_ts.linear.x = flipper.fr.currentAngle;
flp_ts.linear.y = flipper.fl.currentAngle;
flp_ts.linear.z = 0;
flp_ts.angular.x = flipper.rr.currentAngle;
flp_ts.angular.y = flipper.rl.currentAngle;
flp_ts.angular.z = 0;
flipper_publisher.publish(flp_ts);
*/
}
void joyCallback(const sensor_msgs::JoyConstPtr &joy)
{
// Publish about velocity
geometry_msgs::TwistStamped vel_ts;
vel_ts.header.frame_id = framename_base_link;
vel_ts.header.stamp = ros::Time::now();
vel_ts.twist.linear.x = getAxis(joy, velocity.speed);
vel_ts.twist.linear.y = vel_ts.twist.linear.z = 0;
vel_ts.twist.angular.x = vel_ts.twist.angular.y = 0;
vel_ts.twist.angular.z = getAxis(joy, velocity.turn)
*((vel_ts.twist.linear.x<0)?-1:1);
velocity_publisher.publish(vel_ts);
/*MEMO
geometry_msgs::Twist vel_ts;
vel_ts.linear.x = getAxis(joy, velocity.speed);
vel_ts.linear.y = vel_ts.linear.z = 0;
vel_ts.angular.x = vel_ts.angular.y = 0;
vel_ts.angular.z = getAxis(joy, velocity.turn)*((vel_ts.linear.x<0)?-1:1);
velocity_publisher.publish(vel_ts);
*/
// Publish about flippers
updateCurrentFlipperAngle(flipper.fr, joy);
updateCurrentFlipperAngle(flipper.fl, joy);
updateCurrentFlipperAngle(flipper.rr, joy);
updateCurrentFlipperAngle(flipper.rl, joy);
publish_flipper();
}
double getAxis(const sensor_msgs::JoyConstPtr &joy, const Axis &axis)
{
if(axis.axis < 0 || axis.axis >= joy->axes.size())
{
ROS_ERROR_STREAM("Axis " << axis.name << " is out of range, joy has " << joy->axes.size() << " axes");
return 0;
}
double output = joy->axes[axis.axis] * axis.factor + axis.offset;
// TODO keep or remove deadzone? may not be needed
// if(std::abs(output) < axis.max_ * 0.2)
// {
// output = 0.0;
// }
return output;
}
bool getUpButton(const sensor_msgs::JoyConstPtr &joy, Flipper &flpr)
{
int current_Button;
if(flpr.upButton < 0 || flpr.upButton >= joy->buttons.size())
{
ROS_ERROR_STREAM("upButton of " << flpr.name << " is out of range, joy has " << joy->buttons.size() << " buttons");
return false;
}
current_Button = joy->buttons[flpr.upButton];
if(flpr.last_upB != current_Button)
{
flpr.last_upB = current_Button;
if(current_Button != 0)
return true;
}
return false;
}
bool getDownButton(const sensor_msgs::JoyConstPtr &joy, Flipper &flpr)
{
int current_Button;
if(flpr.downButton < 0 || flpr.downButton >= joy->buttons.size())
{
ROS_ERROR_STREAM("downButton of " << flpr.name << " is out of range, joy has " << joy->buttons.size() << " buttons");
return false;
}
current_Button = joy->buttons[flpr.downButton];
if(flpr.last_downB != current_Button)
{
flpr.last_downB = current_Button;
if(current_Button != 0)
return true;
}
return false;
}
void stop()
{
if(velocity_publisher.getNumSubscribers() > 0)
{
velocity_publisher.publish(geometry_msgs::TwistStamped());
}
if(flipper_publisher.getNumSubscribers() > 0)
{
flipper_publisher.publish(geometry_msgs::TwistStamped());
}
}
};
} // namespace teleop_crawler
int main(int argc, char **argv)
{
ros::init(argc, argv, "teleop_crawler");
teleop_crawler::Teleop teleop;
teleop.Usage();
teleop.publish_flipper();
ros::spin();
return 0;
}
| 37.78882 | 123 | 0.623192 | m-shimizu |
f381d82ade9cf79577fc7f5f4381a32ff13f55af | 18,359 | cpp | C++ | arangod/Aql/AqlItemBlock.cpp | specimen151/arangodb | 1a3a31dace16293426a19364eb4d93c8f17c0d68 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | arangod/Aql/AqlItemBlock.cpp | specimen151/arangodb | 1a3a31dace16293426a19364eb4d93c8f17c0d68 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | arangod/Aql/AqlItemBlock.cpp | specimen151/arangodb | 1a3a31dace16293426a19364eb4d93c8f17c0d68 | [
"BSL-1.0",
"Zlib",
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2014-2016 ArangoDB GmbH, Cologne, Germany
/// Copyright 2004-2014 triAGENS GmbH, Cologne, Germany
///
/// Licensed under the Apache License, Version 2.0 (the "License");
/// you may not use this file except in compliance with the License.
/// You may obtain a copy of the License at
///
/// http://www.apache.org/licenses/LICENSE-2.0
///
/// Unless required by applicable law or agreed to in writing, software
/// distributed under the License is distributed on an "AS IS" BASIS,
/// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
/// See the License for the specific language governing permissions and
/// limitations under the License.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Max Neunhoeffer
////////////////////////////////////////////////////////////////////////////////
#include "AqlItemBlock.h"
#include "Aql/BlockCollector.h"
#include "Aql/ExecutionBlock.h"
#include "Aql/ExecutionNode.h"
#include "Basics/VelocyPackHelper.h"
#include <velocypack/Iterator.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::aql;
using VelocyPackHelper = arangodb::basics::VelocyPackHelper;
/// @brief create the block
AqlItemBlock::AqlItemBlock(ResourceMonitor* resourceMonitor, size_t nrItems, RegisterId nrRegs)
: _nrItems(nrItems), _nrRegs(nrRegs), _resourceMonitor(resourceMonitor) {
TRI_ASSERT(resourceMonitor != nullptr);
TRI_ASSERT(nrItems > 0); // empty AqlItemBlocks are not allowed!
if (nrRegs > 0) {
// check that the nrRegs value is somewhat sensible
// this compare value is arbitrary, but having so many registers in a single
// query seems unlikely
TRI_ASSERT(nrRegs <= ExecutionNode::MaxRegisterId);
increaseMemoryUsage(sizeof(AqlValue) * nrItems * nrRegs);
try {
_data.resize(nrItems * nrRegs);
} catch (...) {
decreaseMemoryUsage(sizeof(AqlValue) * nrItems * nrRegs);
throw;
}
}
}
/// @brief create the block from VelocyPack, note that this can throw
AqlItemBlock::AqlItemBlock(ResourceMonitor* resourceMonitor, VPackSlice const slice)
: _nrItems(0), _nrRegs(0), _resourceMonitor(resourceMonitor) {
TRI_ASSERT(resourceMonitor != nullptr);
bool exhausted = VelocyPackHelper::getBooleanValue(slice, "exhausted", false);
if (exhausted) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"exhausted must be false");
}
int64_t nrItems = VelocyPackHelper::getNumericValue<int64_t>(slice, "nrItems", 0);
if (nrItems <= 0) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL, "nrItems must be > 0");
}
_nrItems = static_cast<size_t>(nrItems);
_nrRegs = VelocyPackHelper::getNumericValue<RegisterId>(slice, "nrRegs", 0);
// Initialize the data vector:
if (_nrRegs > 0) {
increaseMemoryUsage(sizeof(AqlValue) * _nrItems * _nrRegs);
try {
_data.resize(_nrItems * _nrRegs);
} catch (...) {
decreaseMemoryUsage(sizeof(AqlValue) * _nrItems * _nrRegs);
throw;
}
}
// Now put in the data:
VPackSlice data = slice.get("data");
VPackSlice raw = slice.get("raw");
std::vector<AqlValue> madeHere;
madeHere.reserve(static_cast<size_t>(raw.length()));
madeHere.emplace_back(); // an empty AqlValue
madeHere.emplace_back(); // another empty AqlValue, indices start w. 2
VPackArrayIterator dataIterator(data);
VPackArrayIterator rawIterator(raw);
try {
// skip the first two records
rawIterator.next();
rawIterator.next();
int64_t emptyRun = 0;
for (RegisterId column = 0; column < _nrRegs; column++) {
for (size_t i = 0; i < _nrItems; i++) {
if (emptyRun > 0) {
emptyRun--;
} else {
VPackSlice dataEntry = dataIterator.value();
dataIterator.next();
if (!dataEntry.isNumber()) {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"data must contain only numbers");
}
int64_t n = dataEntry.getNumericValue<int64_t>();
if (n == 0) {
// empty, do nothing here
} else if (n == -1) {
// empty run:
VPackSlice runLength = dataIterator.value();
dataIterator.next();
TRI_ASSERT(runLength.isNumber());
emptyRun = runLength.getNumericValue<int64_t>();
emptyRun--;
} else if (n == -2) {
// a range
VPackSlice lowBound = dataIterator.value();
dataIterator.next();
VPackSlice highBound = dataIterator.value();
dataIterator.next();
int64_t low =
VelocyPackHelper::getNumericValue<int64_t>(lowBound, 0);
int64_t high =
VelocyPackHelper::getNumericValue<int64_t>(highBound, 0);
AqlValue a(low, high);
try {
setValue(i, column, a);
} catch (...) {
a.destroy();
throw;
}
} else if (n == 1) {
// a VelocyPack value
AqlValue a(rawIterator.value());
rawIterator.next();
try {
setValue(i, column, a); // if this throws, a is destroyed again
} catch (...) {
a.destroy();
throw;
}
madeHere.emplace_back(a);
} else if (n >= 2) {
setValue(i, column, madeHere[static_cast<size_t>(n)]);
// If this throws, all is OK, because it was already put into
// the block elsewhere.
} else {
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"found undefined data value");
}
}
}
}
} catch (...) {
destroy();
// TODO: rethrow?
}
}
/// @brief destroy the block, used in the destructor and elsewhere
void AqlItemBlock::destroy() {
if (_valueCount.empty()) {
return;
}
for (auto& it : _data) {
if (it.requiresDestruction()) {
try { // can find() really throw???
auto it2 = _valueCount.find(it);
if (it2 != _valueCount.end()) { // if we know it, we are still responsible
TRI_ASSERT((*it2).second > 0);
if (--((*it2).second) == 0) {
decreaseMemoryUsage(it.memoryUsage());
it.destroy();
try {
_valueCount.erase(it2);
} catch (...) {
}
}
}
} catch (...) {
}
// Note that if we do not know it the thing it has been stolen from us!
} else {
it.erase();
}
}
_valueCount.clear();
}
/// @brief shrink the block to the specified number of rows
/// the superfluous rows are cleaned
void AqlItemBlock::shrink(size_t nrItems) {
TRI_ASSERT(nrItems > 0);
if (nrItems == _nrItems) {
// nothing to do
return;
}
if (nrItems > _nrItems) {
// cannot use shrink() to increase the size of the block
THROW_ARANGO_EXCEPTION_MESSAGE(TRI_ERROR_INTERNAL,
"cannot use shrink() to increase block");
}
decreaseMemoryUsage(sizeof(AqlValue) * (_nrItems - nrItems) * _nrRegs);
// adjust the size of the block
_nrItems = nrItems;
_data.resize(_nrItems * _nrRegs);
}
void AqlItemBlock::rescale(size_t nrItems, RegisterId nrRegs) {
TRI_ASSERT(_valueCount.empty());
TRI_ASSERT(nrRegs > 0);
TRI_ASSERT(nrRegs <= ExecutionNode::MaxRegisterId);
size_t const targetSize = nrItems * nrRegs;
size_t const currentSize = _nrItems * _nrRegs;
TRI_ASSERT(currentSize <= _data.size());
if (targetSize > _data.size()) {
increaseMemoryUsage(sizeof(AqlValue) * (targetSize - currentSize));
try {
_data.resize(targetSize);
} catch (...) {
decreaseMemoryUsage(sizeof(AqlValue) * (targetSize - currentSize));
throw;
}
} else if (targetSize < _data.size()) {
decreaseMemoryUsage(sizeof(AqlValue) * (currentSize - targetSize));
try {
_data.resize(targetSize);
} catch (...) {
increaseMemoryUsage(sizeof(AqlValue) * (currentSize - targetSize));
throw;
}
}
TRI_ASSERT(_data.size() >= targetSize);
_nrItems = nrItems;
_nrRegs = nrRegs;
}
/// @brief clears out some columns (registers), this deletes the values if
/// necessary, using the reference count.
void AqlItemBlock::clearRegisters(
std::unordered_set<RegisterId> const& toClear) {
for (size_t i = 0; i < _nrItems; i++) {
for (auto const& reg : toClear) {
AqlValue& a(_data[_nrRegs * i + reg]);
if (a.requiresDestruction()) {
auto it = _valueCount.find(a);
if (it != _valueCount.end()) {
TRI_ASSERT((*it).second > 0);
if (--((*it).second) == 0) {
decreaseMemoryUsage(a.memoryUsage());
a.destroy();
try {
_valueCount.erase(it);
continue; // no need for an extra a.erase() here
} catch (...) {
}
}
}
}
a.erase();
}
}
}
/// @brief slice/clone, this does a deep copy of all entries
AqlItemBlock* AqlItemBlock::slice(size_t from, size_t to) const {
TRI_ASSERT(from < to && to <= _nrItems);
std::unordered_set<AqlValue> cache;
cache.reserve((to - from) * _nrRegs / 4 + 1);
auto res = std::make_unique<AqlItemBlock>(_resourceMonitor, to - from, _nrRegs);
for (size_t row = from; row < to; row++) {
for (RegisterId col = 0; col < _nrRegs; col++) {
AqlValue const& a(_data[row * _nrRegs + col]);
if (!a.isEmpty()) {
if (a.requiresDestruction()) {
auto it = cache.find(a);
if (it == cache.end()) {
AqlValue b = a.clone();
try {
res->setValue(row - from, col, b);
} catch (...) {
b.destroy();
throw;
}
cache.emplace(b);
} else {
res->setValue(row - from, col, (*it));
}
} else {
// simple copying of values
res->setValue(row - from, col, a);
}
}
}
}
return res.release();
}
/// @brief slice/clone, this does a deep copy of all entries
AqlItemBlock* AqlItemBlock::slice(
size_t row, std::unordered_set<RegisterId> const& registers) const {
std::unordered_set<AqlValue> cache;
auto res = std::make_unique<AqlItemBlock>(_resourceMonitor, 1, _nrRegs);
for (RegisterId col = 0; col < _nrRegs; col++) {
if (registers.find(col) == registers.end()) {
continue;
}
AqlValue const& a(_data[row * _nrRegs + col]);
if (!a.isEmpty()) {
if (a.requiresDestruction()) {
auto it = cache.find(a);
if (it == cache.end()) {
AqlValue b = a.clone();
try {
res->setValue(0, col, b);
} catch (...) {
b.destroy();
throw;
}
cache.emplace(b);
} else {
res->setValue(0, col, (*it));
}
} else {
res->setValue(0, col, a);
}
}
}
return res.release();
}
/// @brief slice/clone chosen rows for a subset, this does a deep copy
/// of all entries
AqlItemBlock* AqlItemBlock::slice(std::vector<size_t> const& chosen, size_t from,
size_t to) const {
TRI_ASSERT(from < to && to <= chosen.size());
std::unordered_set<AqlValue> cache;
cache.reserve((to - from) * _nrRegs / 4 + 1);
auto res = std::make_unique<AqlItemBlock>(_resourceMonitor, to - from, _nrRegs);
for (size_t row = from; row < to; row++) {
for (RegisterId col = 0; col < _nrRegs; col++) {
AqlValue const& a(_data[chosen[row] * _nrRegs + col]);
if (!a.isEmpty()) {
if (a.requiresDestruction()) {
auto it = cache.find(a);
if (it == cache.end()) {
AqlValue b = a.clone();
try {
res->setValue(row - from, col, b);
} catch (...) {
b.destroy();
}
cache.emplace(b);
} else {
res->setValue(row - from, col, (*it));
}
} else {
res->setValue(row - from, col, a);
}
}
}
}
return res.release();
}
/// @brief steal for a subset, this does not copy the entries, rather,
/// it remembers which it has taken. This is stored in the
/// this by removing the value counts in _valueCount.
/// It is highly recommended to delete this object right after this
/// operation, because it is unclear, when the values to which our
/// AqlValues point will vanish! In particular, do not use setValue
/// any more.
AqlItemBlock* AqlItemBlock::steal(std::vector<size_t> const& chosen, size_t from,
size_t to) {
TRI_ASSERT(from < to && to <= chosen.size());
auto res = std::make_unique<AqlItemBlock>(_resourceMonitor, to - from, _nrRegs);
for (size_t row = from; row < to; row++) {
for (RegisterId col = 0; col < _nrRegs; col++) {
AqlValue& a(_data[chosen[row] * _nrRegs + col]);
if (!a.isEmpty()) {
steal(a);
try {
res->setValue(row - from, col, a);
} catch (...) {
a.destroy();
}
eraseValue(chosen[row], col);
}
}
}
return res.release();
}
/// @brief concatenate multiple blocks
AqlItemBlock* AqlItemBlock::concatenate(ResourceMonitor* resourceMonitor,
BlockCollector* collector) {
return concatenate(resourceMonitor, collector->_blocks);
}
/// @brief concatenate multiple blocks, note that the new block now owns all
/// AqlValue pointers in the old blocks, therefore, the latter are all
/// set to nullptr, just to be sure.
AqlItemBlock* AqlItemBlock::concatenate(ResourceMonitor* resourceMonitor,
std::vector<AqlItemBlock*> const& blocks) {
TRI_ASSERT(!blocks.empty());
size_t totalSize = 0;
RegisterId nrRegs = 0;
for (auto& it : blocks) {
totalSize += it->size();
if (nrRegs == 0) {
nrRegs = it->getNrRegs();
} else {
TRI_ASSERT(it->getNrRegs() == nrRegs);
}
}
TRI_ASSERT(totalSize > 0);
TRI_ASSERT(nrRegs > 0);
auto res = std::make_unique<AqlItemBlock>(resourceMonitor, totalSize, nrRegs);
size_t pos = 0;
for (auto& it : blocks) {
size_t const n = it->size();
for (size_t row = 0; row < n; ++row) {
for (RegisterId col = 0; col < nrRegs; ++col) {
// copy over value
AqlValue const& a = it->getValueReference(row, col);
if (!a.isEmpty()) {
res->setValue(pos + row, col, a);
}
}
}
it->eraseAll();
pos += n;
}
return res.release();
}
/// @brief toJson, transfer a whole AqlItemBlock to Json, the result can
/// be used to recreate the AqlItemBlock via the Json constructor
/// Here is a description of the data format: The resulting Json has
/// the following attributes:
/// "nrItems": the number of rows of the AqlItemBlock
/// "nrRegs": the number of registers of the AqlItemBlock
/// "error": always set to false
/// "data": this contains the actual data in the form of a list of
/// numbers. The AqlItemBlock is stored columnwise, starting
/// from the first column (top to bottom) and going right.
/// Each entry found is encoded in the following way:
/// 0 means a single empty entry
/// -1 followed by a positive integer N (encoded as number)
/// means a run of that many empty entries
/// -2 followed by two numbers LOW and HIGH means a range
/// and LOW and HIGH are the boundaries (inclusive)
/// 1 means a JSON entry at the "next" position in "raw"
/// the "next" position starts with 2 and is increased
/// by one for every 1 found in data
/// integer values >= 2 mean a JSON entry, in this
/// case the "raw" list contains an entry in the
/// corresponding position
/// "raw": List of actual values, positions 0 and 1 are always null
/// such that actual indices start at 2
void AqlItemBlock::toVelocyPack(transaction::Methods* trx,
VPackBuilder& result) const {
VPackOptions options(VPackOptions::Defaults);
options.buildUnindexedArrays = true;
options.buildUnindexedObjects = true;
VPackBuilder raw(&options);
raw.openArray();
// Two nulls in the beginning such that indices start with 2
raw.add(VPackValue(VPackValueType::Null));
raw.add(VPackValue(VPackValueType::Null));
std::unordered_map<AqlValue, size_t> table; // remember duplicates
result.add("nrItems", VPackValue(_nrItems));
result.add("nrRegs", VPackValue(_nrRegs));
result.add("error", VPackValue(false));
result.add("exhausted", VPackValue(false));
result.add("data", VPackValue(VPackValueType::Array));
size_t emptyCount = 0; // here we count runs of empty AqlValues
auto commitEmpties = [&result, &emptyCount]() { // this commits an empty run to the result
if (emptyCount > 0) {
if (emptyCount == 1) {
result.add(VPackValue(0));
} else {
result.add(VPackValue(-1));
result.add(VPackValue(emptyCount));
}
emptyCount = 0;
}
};
size_t pos = 2; // write position in raw
for (RegisterId column = 0; column < _nrRegs; column++) {
for (size_t i = 0; i < _nrItems; i++) {
AqlValue const& a(_data[i * _nrRegs + column]);
if (a.isEmpty()) {
emptyCount++;
} else {
commitEmpties();
if (a.isRange()) {
result.add(VPackValue(-2));
result.add(VPackValue(a.range()->_low));
result.add(VPackValue(a.range()->_high));
} else {
auto it = table.find(a);
if (it == table.end()) {
a.toVelocyPack(trx, raw, false);
result.add(VPackValue(1));
table.emplace(a, pos++);
} else {
result.add(VPackValue(it->second));
}
}
}
}
}
commitEmpties();
result.close(); // closes "data"
raw.close();
result.add("raw", raw.slice());
}
| 31.382906 | 95 | 0.58086 | specimen151 |
f38c7428cc403ad2c6895dfc5acd40986d8d32a7 | 3,525 | cpp | C++ | src/connectivity/nrf_pipe.cpp | Niels-Post/cpp_mesh | 2750d9e824bffd820d872f6e57dbadf6a1138246 | [
"BSL-1.0"
] | null | null | null | src/connectivity/nrf_pipe.cpp | Niels-Post/cpp_mesh | 2750d9e824bffd820d872f6e57dbadf6a1138246 | [
"BSL-1.0"
] | null | null | null | src/connectivity/nrf_pipe.cpp | Niels-Post/cpp_mesh | 2750d9e824bffd820d872f6e57dbadf6a1138246 | [
"BSL-1.0"
] | null | null | null | /*
*
* Copyright Niels Post 2019.
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* https://www.boost.org/LICENSE_1_0.txt)
*
*/
#include <mesh/connectivity/nrf_pipe.hpp>
using nrf24l01::nrf24l01plus;
using std::array;
using nrf24l01::NRF_REGISTER;
namespace mesh {
namespace connectivity {
void nrf_pipe::flush(nrf24l01plus &nrf) {
uint8_t old_mode = nrf.get_mode();
nrf.mode(nrf.MODE_NONE);
switch (connection_state) {
case mesh::DISCONNECTED:
nrf.rx_enabled(pipe_number, false);
break;
case mesh::WAITING:
case mesh::RESPONDED:
case mesh::ACCEPTED:
nrf.rx_set_address(pipe_number, nrf_address);
nrf.rx_enabled(pipe_number, true);
if (pipe_number == 0) {
nrf.tx_set_address(nrf_address);
}
break;
}
nrf.mode(old_mode);
}
bool nrf_pipe::send_message(array<nrf_pipe, 6> &all_pipes, nrf24l01plus &nrf,
uint8_t n,
uint8_t *data) {
uint8_t old_mode = nrf.get_mode();
nrf.mode(nrf.MODE_PTX);
uint8_t old_pipe = pipe_number;
if (pipe_number != 0) {
nrf.rx_enabled(pipe_number, false);
pipe_number = 0;
flush(nrf);
}
nrf.tx_flush();
nrf.write_register(NRF_REGISTER::NRF_STATUS, 0x60); //clear previous sent bit
nrf.write_register(NRF_REGISTER::NRF_STATUS, 0x10); // Clear Max RT
nrf.tx_write_payload(data, n, old_pipe == 0);
bool success = true;
do {
nrf.no_operation();
if ((nrf.last_status & nrf24l01::NRF_STATUS::MAX_RT) > 0) {
success = false;
nrf.write_register(NRF_REGISTER::NRF_STATUS, 0x10); // Clear Max RT
break;
}
} while ((nrf.last_status & nrf24l01::NRF_STATUS::TX_DS) == 0);
if (old_pipe != 0) {
pipe_number = old_pipe;
flush(nrf);
all_pipes[0].flush(nrf);
}
nrf.mode(old_mode);
return success;
}
void nrf_pipe::setConnectionState(mesh::mesh_connection_state cS) {
nrf_pipe::connection_state = cS;
}
void nrf_pipe::setNodeId(node_id nodeId) {
connected_node = nodeId;
}
void nrf_pipe::setNrfAddress(const nrf24l01::address &nrfAddress) {
nrf_address = nrfAddress;
}
mesh::mesh_connection_state nrf_pipe::getConnectionState() const {
return connection_state;
}
uint8_t nrf_pipe::getNodeId() const {
return connected_node;
}
const nrf24l01::address &nrf_pipe::getNrfAddress() const {
return nrf_address;
}
hwlib::ostream &operator<<(hwlib::ostream &os, const nrf_pipe &pipe) {
os << "connection_state: " << pipe.connection_state << " pipe_number: " << pipe.pipe_number
<< " connected_node: " << hwlib::hex << pipe.connected_node << " address: "
<< pipe.nrf_address.address_bytes[4];
return os;
}
}
} | 32.943925 | 103 | 0.524255 | Niels-Post |
f38e728136bd47738a2e51e2ed8c70a9b4871006 | 4,032 | cpp | C++ | src/Library/Lights/PointLight.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | 1 | 2018-12-20T19:31:02.000Z | 2018-12-20T19:31:02.000Z | src/Library/Lights/PointLight.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | src/Library/Lights/PointLight.cpp | aravindkrishnaswamy/rise | 297d0339a7f7acd1418e322a30a21f44c7dbbb1d | [
"BSD-2-Clause"
] | null | null | null | //////////////////////////////////////////////////////////////////////
//
// PointLight.cpp - Implementation of the PointLight class
//
// Author: Aravind Krishnaswamy
// Date of Birth: November 23, 2001
// Tabs: 4
// Comments:
//
// License Information: Please see the attached LICENSE.TXT file
//
//////////////////////////////////////////////////////////////////////
#include "pch.h"
#include "PointLight.h"
#include "../Animation/KeyframableHelper.h"
using namespace RISE;
using namespace RISE::Implementation;
PointLight::PointLight(
const Scalar radiantEnergy_,
const RISEPel& c,
const Scalar linearAtten,
const Scalar quadraticAtten
) :
radiantEnergy( radiantEnergy_ ),
ptPosition( Point3( 0, 0, 0 ) ),
cColor( c ),
linearAttenuation( linearAtten ),
quadraticAttenuation( quadraticAtten )
{
}
PointLight::~PointLight( )
{
}
void PointLight::ComputeDirectLighting(
const RayIntersectionGeometric& ri,
const IRayCaster& pCaster,
const IBSDF& brdf,
const bool bReceivesShadows,
RISEPel& amount
) const
{
//
// Computing direct lighting for point lights
//
amount = RISEPel(0.0);
// Vector to the light from the surface
Vector3 vToLight = Vector3Ops::mkVector3( ptPosition, ri.ptIntersection );
const Scalar fDistFromLight = Vector3Ops::NormalizeMag(vToLight);
// This dot product tells us the angle of incidence between the light ray
// and the surface normal. This angle tells us what illumination this surface
// should recieve. If this value is negative, then the light is
// behind the object and we can stop.
const Scalar fDot = Vector3Ops::Dot( vToLight, ri.vNormal );
if( fDot <= 0.0 ) {
return;
}
if( bReceivesShadows ) {
// Check to see if there is a shadow
Ray rayToLight;
rayToLight.origin = ri.ptIntersection;
rayToLight.dir = vToLight;
if( pCaster.CastShadowRay( rayToLight, fDistFromLight ) ) {
return;
}
}
Scalar attenuation = 1.0;
if( linearAttenuation ) {
attenuation += (linearAttenuation * fDistFromLight);
}
if( quadraticAttenuation) {
attenuation += (quadraticAttenuation * fDistFromLight * fDistFromLight);
}
amount = (cColor * brdf.value( vToLight, ri )) * ((1.0/attenuation) * fDot * radiantEnergy);
}
void PointLight::FinalizeTransformations( )
{
// Tells out transform helper to finalize transformations
Transformable::FinalizeTransformations();
// Then calculate the real-world position of this light...
ptPosition = Point3Ops::Transform( m_mxFinalTrans, Point3( 0, 0, 0 ) );
}
static const unsigned int COLOR_ID = 100;
static const unsigned int ENERGY_ID = 101;
static const unsigned int LINEARATTEN_ID = 102;
static const unsigned int QUADRATICATTEN_ID = 103;
IKeyframeParameter* PointLight::KeyframeFromParameters( const String& name, const String& value )
{
IKeyframeParameter* p = 0;
// Check the name and see if its something we recognize
if( name == "color" ) {
double d[3];
if( sscanf( value.c_str(), "%lf %lf %lf", &d[0], &d[1], &d[2] ) == 3 ) {
p = new Parameter<RISEPel>( RISEPel(d), COLOR_ID );
}
} else if( name == "energy" ) {
p = new Parameter<Scalar>( atof(value.c_str()), ENERGY_ID );
} else if( name == "linear_attenuation" ) {
p = new Parameter<Scalar>( atof(value.c_str()), LINEARATTEN_ID );
} else if( name == "quadratic_attenuation" ) {
p = new Parameter<Scalar>( atof(value.c_str()), QUADRATICATTEN_ID );
} else {
return Transformable::KeyframeFromParameters( name, value );
}
GlobalLog()->PrintNew( p, __FILE__, __LINE__, "keyframe parameter" );
return p;
}
void PointLight::SetIntermediateValue( const IKeyframeParameter& val )
{
switch( val.getID() )
{
case COLOR_ID:
{
cColor = *(RISEPel*)val.getValue();
}
break;
case ENERGY_ID:
{
radiantEnergy = *(Scalar*)val.getValue();
}
break;
case LINEARATTEN_ID:
{
linearAttenuation = *(Scalar*)val.getValue();
}
break;
case QUADRATICATTEN_ID:
{
quadraticAttenuation = *(Scalar*)val.getValue();
}
break;
}
Transformable::SetIntermediateValue( val );
}
| 25.518987 | 97 | 0.678075 | aravindkrishnaswamy |
f3908c189a183597f84f29fd60b95505608abae2 | 239 | hpp | C++ | include/zisa/math/cartesian.hpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | include/zisa/math/cartesian.hpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | null | null | null | include/zisa/math/cartesian.hpp | 1uc/ZisaFVM | 75fcedb3bece66499e011228a39d8a364b50fd74 | [
"MIT"
] | 1 | 2021-08-24T11:52:51.000Z | 2021-08-24T11:52:51.000Z | // SPDX-License-Identifier: MIT
// Copyright (c) 2021 ETH Zurich, Luc Grosheintz-Laval
#ifndef CARTESIAN_H_RGB4Z
#define CARTESIAN_H_RGB4Z
#include "cartesian_decl.hpp"
// #include "cartesian_impl.hpp"
#endif /* end of include guard */
| 21.727273 | 54 | 0.757322 | 1uc |
f39b386621000227146d97e26b37e3345670db71 | 6,513 | cpp | C++ | src/app-output-model.cpp | mattbucknall/font2c | 8823ae1c441217c1ea18c506899e88be24682778 | [
"0BSD"
] | null | null | null | src/app-output-model.cpp | mattbucknall/font2c | 8823ae1c441217c1ea18c506899e88be24682778 | [
"0BSD"
] | null | null | null | src/app-output-model.cpp | mattbucknall/font2c | 8823ae1c441217c1ea18c506899e88be24682778 | [
"0BSD"
] | null | null | null | /*
* font2c - Command-line utility for converting font glyphs into bitmap images
* embeddable in C source code.
*
* https://github.com/mattbucknall/font2c
*
* Copyright (C) 2022 Matthew T. Bucknall
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
* IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <cassert>
#include <cerrno>
#include <cstdio>
#include <cstring>
#include <filesystem>
#include <utility>
#include <fmt/format.h>
#include "app-output-model.hpp"
#include "app-version.hpp"
using namespace app;
OutputModel::OutputModel(int depth, bool msb_first, RasterizerFunc rasterizer_func):
m_rasterizer_func(std::move(rasterizer_func)),
m_line_ascent(0),
m_line_descent(0),
m_line_height(0),
m_current_byte(0) {
assert(depth == 1 || depth == 2 || depth == 4 || depth == 8);
m_shift = 8 - depth;
if ( msb_first ) {
m_start = depth - 1;
m_delta = -depth;
} else {
m_start = 0;
m_delta = depth;
};
m_bit_pos = m_start;
}
int OutputModel::line_ascent() const {
return m_line_ascent;
}
int OutputModel::line_descent() const {
return m_line_descent;
}
int OutputModel::line_height() const {
return m_line_height;
}
std::optional<font2c_glyph_t> OutputModel::find_glyph(char32_t codepoint) const {
for(const auto& glyph: m_glyphs) {
if ( glyph.codepoint == codepoint ) {
return glyph;
}
}
return std::nullopt;
}
const std::vector<uint8_t>& OutputModel::pixel_data() const {
return m_pixel_data;
}
void OutputModel::add_glyph(const app::Glyph& glyph) {
font2c_glyph_t f2c_glyph = {
.codepoint = glyph.codepoint(),
.offset = static_cast<uint32_t>(m_pixel_data.size()),
.x_bearing = static_cast<int16_t>(glyph.x_bearing()),
.y_bearing = static_cast<int16_t>(glyph.y_bearing()),
.width = static_cast<uint16_t>(glyph.width()),
.height = static_cast<uint16_t>(glyph.height()),
.x_advance = static_cast<int16_t>(glyph.x_advance()),
.y_advance = static_cast<int16_t>(glyph.y_advance())
};
m_glyphs.push_back(f2c_glyph);
m_rasterizer_func(*this, glyph);
m_line_ascent = std::max(m_line_ascent, static_cast<int>(f2c_glyph.y_bearing));
m_line_descent = std::max(m_line_descent, f2c_glyph.height - f2c_glyph.y_bearing);
m_line_height = std::max(m_line_height, m_line_ascent + m_line_descent);
}
void OutputModel::add_pixel(uint8_t opacity) {
opacity >>= m_shift;
opacity <<= m_bit_pos;
m_current_byte |= opacity;
m_bit_pos += m_delta;
if ( m_bit_pos < 0 || m_bit_pos >= 8 ) {
flush_pixels();
}
}
void OutputModel::flush_pixels() {
if ( m_bit_pos != m_start ) {
m_pixel_data.push_back(m_current_byte);
m_bit_pos = m_start;
m_current_byte = 0;
}
}
void OutputModel::write(std::string_view path, std::string_view font_path, const app::Options& options) const {
struct File {
FILE* f;
explicit File(std::string_view path) :
f(std::fopen(path.data(), "w")) {
if (f == nullptr) {
throw app::Error("{}", std::strerror(errno));
}
}
~File() {
std::fclose(f);
}
operator FILE*() const { // NOLINT(google-explicit-constructor)
return f;
}
};
File f(path);
size_t total_size = m_pixel_data.size() + (m_glyphs.size() * sizeof(font2c_glyph_t));
fmt::print(f, "/*\n");
fmt::print(f, " * Generated by font2c, version {}\n", APP_VERSION_STR);
fmt::print(f, " * https://github.com/mattbucknall/font2c\n");
fmt::print(f, " *\n");
fmt::print(f, " * Source Font: {}\n", std::filesystem::path(font_path).filename().string());
fmt::print(f, " * Font Size: {}px\n", options.size);
fmt::print(f, " * Pixel Depth: {}bpp\n", options.pixel_depth);
fmt::print(f, " * Raster Order: {}\n", options.raster_type);
fmt::print(f, " * Bit Order: {}\n", options.msb_first ? "msb first" : "lsb first");
fmt::print(f, " * Antialiased: {}\n", options.antialiasing ? "yes" : "no");
fmt::print(f, " * Hinting: {}\n", options.no_hinting ? "no" : "yes");
fmt::print(f, " * Glyph Count: {}\n", m_glyphs.size());
fmt::print(f, " * Combined Table Size: {} bytes\n", total_size);
fmt::print(f, " */\n\n");
fmt::print(f, "#include <font2c-types.h>\n\n\n");
fmt::print(f, "static const uint8_t PIXELS[{}] = {{\n ", m_pixel_data.size());
int count = 0;
for (auto byte: m_pixel_data) {
fmt::print(f, "0x{:02X}, ", byte);
count++;
if ( count == 16 ) {
fmt::print(f, "\n ");
count = 0;
}
}
if ( count > 0 ) {
fmt::print(f, "\n");
}
fmt::print(f, "}};\n\n\n");
fmt::print(f, "static const font2c_glyph_t GLYPHS[{}] = {{\n", m_glyphs.size());
for (const auto& glyph: m_glyphs) {
fmt::print(f, " 0x{:08X}, 0x{:08X}, {:>6}, {:>6}, {:>6}, {:>6}, {:>6}, {:>6}\n",
glyph.codepoint, glyph.offset, glyph.x_bearing, glyph.y_bearing,
glyph.width, glyph.height, glyph.x_advance, glyph.y_advance);
}
fmt::print(f, "}};\n\n\n");
fmt::print(f, "const font2c_font_t {} = {{\n", options.symbol_name);
fmt::print(f, " .pixels = PIXELS,\n");
fmt::print(f, " .glyphs = GLYPHS,\n");
fmt::print(f, " .n_glyphs = {},\n", m_glyphs.size());
fmt::print(f, " .ascent = {},\n", m_line_ascent);
fmt::print(f, " .descent = {},\n", m_line_descent);
fmt::print(f, " .line_height = {},\n", m_line_height);
fmt::print(f, " .compression = FONT2C_COMPRESSION_NONE\n");
fmt::print(f, "}};\n\n\n");
fmt::print(f, "/* === end of file === */\n\n");
}
| 30.577465 | 111 | 0.589283 | mattbucknall |
f39badab9c1be08f0b51d335f9e89d4b6c088d84 | 732 | hpp | C++ | ad_map_access/src/route/RouteOperationPrivate.hpp | woojinjjang/map-1 | d12bb410f03d078a995130b4e671746ace8b6287 | [
"MIT"
] | 61 | 2019-12-19T20:57:24.000Z | 2022-03-29T15:20:51.000Z | ad_map_access/src/route/RouteOperationPrivate.hpp | woojinjjang/map-1 | d12bb410f03d078a995130b4e671746ace8b6287 | [
"MIT"
] | 54 | 2020-04-05T05:32:47.000Z | 2022-03-15T18:42:33.000Z | ad_map_access/src/route/RouteOperationPrivate.hpp | woojinjjang/map-1 | d12bb410f03d078a995130b4e671746ace8b6287 | [
"MIT"
] | 31 | 2019-12-20T07:37:39.000Z | 2022-03-16T13:06:16.000Z | // ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2020-2021 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#pragma once
#include "ad/map/lane/Types.hpp"
#include "ad/map/route/Types.hpp"
namespace ad {
namespace map {
namespace route {
void updateRouteLaneOffset(bool const rightNeighbor, RouteLaneOffset &routeLaneOffset, FullRoute &route);
void alignRouteStartingPoints(point::ParaPoint const &alignmentParaPoint, route::FullRoute &route);
void alignRouteEndingPoints(point::ParaPoint const &alignmentParaPoint, route::FullRoute &route);
} // namespace route
} // namespace map
} // namespace ad
| 29.28 | 105 | 0.655738 | woojinjjang |
f3a0a846bb5ea5754b7a0c0aa7630ac4c19aa1e7 | 74 | cpp | C++ | src/Main.cpp | ArrowganceStudios/Gladiators-of-Nyquistborgh | 753be76066dff0e2ad2db540babd91dd1462c545 | [
"Apache-2.0"
] | null | null | null | src/Main.cpp | ArrowganceStudios/Gladiators-of-Nyquistborgh | 753be76066dff0e2ad2db540babd91dd1462c545 | [
"Apache-2.0"
] | null | null | null | src/Main.cpp | ArrowganceStudios/Gladiators-of-Nyquistborgh | 753be76066dff0e2ad2db540babd91dd1462c545 | [
"Apache-2.0"
] | null | null | null | #include "Core.h"
int main(void)
{
Core core;
core.Run();
return 0;
} | 8.222222 | 17 | 0.608108 | ArrowganceStudios |
f3a2e4b8cfda9db61192f49680bbbff61180175c | 7,273 | cpp | C++ | library/src/blas1/rocblas_axpy_strided_batched.cpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | null | null | null | library/src/blas1/rocblas_axpy_strided_batched.cpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | null | null | null | library/src/blas1/rocblas_axpy_strided_batched.cpp | zjunweihit/rocBLAS | c8bda2d15a7772d810810492ebed616eec0959a5 | [
"MIT"
] | null | null | null | /* ************************************************************************
* Copyright 2016-2019 Advanced Micro Devices, Inc.
* ************************************************************************ */
#include "rocblas_axpy_strided_batched.hpp"
#include "logging.h"
namespace
{
template <typename>
constexpr char rocblas_axpy_strided_batched_name[] = "unknown";
template <>
constexpr char rocblas_axpy_strided_batched_name<float>[] = "rocblas_saxpy_strided_batched";
template <>
constexpr char rocblas_axpy_strided_batched_name<double>[] = "rocblas_daxpy_strided_batched";
template <>
constexpr char rocblas_axpy_strided_batched_name<rocblas_half>[]
= "rocblas_haxpy_strided_batched";
template <>
constexpr char rocblas_axpy_strided_batched_name<rocblas_float_complex>[]
= "rocblas_caxpy_strided_batched";
template <>
constexpr char rocblas_axpy_strided_batched_name<rocblas_double_complex>[]
= "rocblas_zaxpy_strided_batched";
template <int NB, typename T>
rocblas_status rocblas_axpy_strided_batched_impl(rocblas_handle handle,
rocblas_int n,
const T* alpha,
const T* x,
rocblas_int incx,
rocblas_stride stridex,
T* y,
rocblas_int incy,
rocblas_stride stridey,
rocblas_int batch_count,
const char* name,
const char* bench_name)
{
if(!handle)
{
return rocblas_status_invalid_handle;
}
RETURN_ZERO_DEVICE_MEMORY_SIZE_IF_QUERIED(handle);
if(!alpha)
{
return rocblas_status_invalid_pointer;
}
auto layer_mode = handle->layer_mode;
if(handle->pointer_mode == rocblas_pointer_mode_host)
{
if(layer_mode & rocblas_layer_mode_log_trace)
{
log_trace(handle,
name,
n,
log_trace_scalar_value(alpha),
x,
incx,
stridex,
y,
incy,
stridey,
batch_count);
}
if(layer_mode & rocblas_layer_mode_log_bench)
{
log_bench(handle,
"./rocblas-bench",
"-f",
bench_name,
"-r",
rocblas_precision_string<T>,
"-n",
n,
LOG_BENCH_SCALAR_VALUE(alpha),
"--incx",
incx,
"--stride_x",
stridex,
"--incy",
incy,
"--stride_y",
stridey,
"--batch",
batch_count);
}
}
else if(layer_mode & rocblas_layer_mode_log_trace)
{
log_trace(handle, name, n, alpha, x, incx, stridex, y, incy, stridey, batch_count);
}
if(layer_mode & rocblas_layer_mode_log_profile)
{
log_profile(handle,
name,
"N",
n,
"incx",
incx,
"stride_x",
stridex,
"incy",
incy,
"stride_y",
stridey,
"batch",
batch_count);
}
if(!x || !y)
{
return rocblas_status_invalid_pointer;
}
if(n <= 0 || 0 == batch_count) // Quick return if possible. Not Argument error
{
return rocblas_status_success;
}
if(batch_count < 0)
{
return rocblas_status_invalid_size;
}
return rocblas_axpy_strided_batched_template<NB>(
handle, n, alpha, x, incx, stridex, y, incy, stridey, batch_count);
}
}
/*
* ===========================================================================
* C wrapper
* ===========================================================================
*/
extern "C" {
#ifdef IMPL
#error IMPL ALREADY DEFINED
#endif
#define IMPL(routine_name_, T_) \
rocblas_status routine_name_(rocblas_handle handle, \
rocblas_int n, \
const T_* alpha, \
const T_* x, \
rocblas_int incx, \
rocblas_stride stridex, \
T_* y, \
rocblas_int incy, \
rocblas_stride stridey, \
rocblas_int batch_count) \
{ \
return rocblas_axpy_strided_batched_impl<256>(handle, \
n, \
alpha, \
x, \
incx, \
stridex, \
y, \
incy, \
stridey, \
batch_count, \
#routine_name_, \
"axpy_strided_batched"); \
}
IMPL(rocblas_saxpy_strided_batched, float);
IMPL(rocblas_daxpy_strided_batched, double);
IMPL(rocblas_caxpy_strided_batched, rocblas_float_complex);
IMPL(rocblas_zaxpy_strided_batched, rocblas_double_complex);
IMPL(rocblas_haxpy_strided_batched, rocblas_half);
#undef IMPL
} // extern "C"
| 39.527174 | 97 | 0.348824 | zjunweihit |
f3a47c6dfad18480ead9ba1530ba53b0536f859b | 7,029 | cpp | C++ | tests/benchmark.cpp | MateusMP/TightECS | 2abc21bd40496814c3a8460c406b57a1a78bd78d | [
"MIT"
] | null | null | null | tests/benchmark.cpp | MateusMP/TightECS | 2abc21bd40496814c3a8460c406b57a1a78bd78d | [
"MIT"
] | null | null | null | tests/benchmark.cpp | MateusMP/TightECS | 2abc21bd40496814c3a8460c406b57a1a78bd78d | [
"MIT"
] | null | null | null | #include <iostream>
#include <chrono>
#include <string_view>
#include "catch2/catch.hpp"
#define TECS_LOG_ERROR(message) std::cout << message << std::endl;
#define TECS_ASSERT(expr, message) REQUIRE(expr)
#include <tecs/tecs.h>
#define MEGABYTES(bytes) 1024 * 1024 * (double)bytes
class Timer {
typedef std::chrono::time_point<std::chrono::high_resolution_clock> TimePoint;
public:
Timer()
{
start();
}
void start()
{
startTime = std::chrono::high_resolution_clock::now();
}
/***
* @return Time in seconds
* */
void stop(std::string_view message)
{
auto finish = std::chrono::high_resolution_clock::now();
std::chrono::duration<double> diffSec = finish - startTime;
std::cout << message << " took: " << diffSec.count() << " seconds" << std::endl;
}
private:
TimePoint startTime;
};
struct Component1 {
long x;
};
struct Component2 {
long x;
long y;
};
CREATE_COMPONENT_TYPES(ComponentTypes);
REGISTER_COMPONENT_TYPE(ComponentTypes, Component1, 1);
REGISTER_COMPONENT_TYPE(ComponentTypes, Component2, 2);
class MemoryReadyEcs : public tecs::Ecs<ComponentTypes, 8> {
public:
MemoryReadyEcs(u32 memSize, u32 maxEntities)
{
memory = std::make_unique<char[]>(memSize);
this->init(tecs::ArenaAllocator(memory.get(), memSize), maxEntities);
}
std::unique_ptr<char[]> memory;
};
TEST_CASE("Create many entities", "[Benchmark]")
{
const auto entitiesCount = 100'000;
MemoryReadyEcs ecs(MEGABYTES(10), entitiesCount);
Timer timer;
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
}
timer.stop("Create 100.000 entities");
}
TEST_CASE("Create many entities with 2 components", "[Benchmark]")
{
const auto entitiesCount = 100'000;
MemoryReadyEcs ecs(MEGABYTES(10), entitiesCount);
Timer timer;
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
ecs.addComponent<Component1>(entity) = {i};
ecs.addComponent<Component2>(entity) = {i, i};
}
timer.stop("Create 100.000 entities with 2 components");
}
TEST_CASE("Iterate over many entities with 2 components", "[Benchmark]")
{
const auto entitiesCount = 100'000;
MemoryReadyEcs ecs(MEGABYTES(10), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
ecs.addComponent<Component1>(entity) = {i};
ecs.addComponent<Component2>(entity) = {i, i};
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Create 100.000 entities with 2 components");
}
TEST_CASE("Iterate over many entities with 2 components, sparse", "[Benchmark]")
{
const auto entitiesCount = 100'000;
MemoryReadyEcs ecs(MEGABYTES(10), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
ecs.addComponent<Component1>(entity) = {i};
if (i > 1000 && i < 5000 || (i > 20'000 && i < 40'000) || i > 80'000) {
ecs.addComponent<Component2>(entity) = {i, i};
}
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Create 100.000 entities with 2 components sparse");
}
TEST_CASE("Iterate over many entities with 2 components some missing",
"[Benchmark]")
{
const auto entitiesCount = 100'000;
MemoryReadyEcs ecs(MEGABYTES(10), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
if ((i % 7) != 0) {
ecs.addComponent<Component1>(entity) = {i};
}
if ((i % 13) != 0) {
ecs.addComponent<Component2>(entity) = {i, i};
}
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Create 100.000 entities with 2 components some missing");
}
TEST_CASE("Iterate over 1M entities with 2 components",
"[Benchmark]")
{
const auto entitiesCount = 1'000'000;
MemoryReadyEcs ecs(MEGABYTES(32), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
ecs.addComponent<Component1>(entity) = {i};
ecs.addComponent<Component2>(entity) = {i, i};
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Iterate over 1M with 2 components");
}
TEST_CASE("Iterate over 1M entities with 2 components, some missing",
"[Benchmark]")
{
const auto entitiesCount = 1'000'000;
MemoryReadyEcs ecs(MEGABYTES(30), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
if ((i % 7) != 0) {
ecs.addComponent<Component1>(entity) = {i};
}
if ((i % 13) != 0) {
ecs.addComponent<Component2>(entity) = {i, i};
}
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Iterate over 1M with 2 components, some missing");
}
TEST_CASE("Iterate over 1M entities with 2 components, half contain components",
"[Benchmark]")
{
const auto entitiesCount = 1'000'000;
MemoryReadyEcs ecs(MEGABYTES(28), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
if ((i % 2) != 0) {
ecs.addComponent<Component1>(entity) = {i};
}
ecs.addComponent<Component2>(entity) = {i, i};
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Iterate over 1M with 2 components, half contain components");
}
TEST_CASE("Iterate over 1M entities with 2 components, less than half",
"[Benchmark]")
{
const auto entitiesCount = 1'000'000;
MemoryReadyEcs ecs(MEGABYTES(28), entitiesCount);
for (long i = 0; i < entitiesCount; ++i) {
tecs::EntityHandle entity = ecs.newEntity();
if ((i % 2) != 0) {
ecs.addComponent<Component1>(entity) = {i};
}
if ((i % 3) != 0) {
ecs.addComponent<Component2>(entity) = {i, i};
}
}
Timer timer;
ecs.forEach<Component1, Component2>([](auto, Component1& c1, Component2& c2) {
c1.x = 0;
c2.x = 1;
c2.y = 2;
});
timer.stop("Iterate over 1M with 2 components, less than half");
} | 27.892857 | 88 | 0.596529 | MateusMP |
f3a4d651405c54ce59e6cd1dd7db2f9079ec058b | 1,558 | cpp | C++ | SDK/ARKSurvivalEvolved_CannonMuzzleFlashEmitter_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_CannonMuzzleFlashEmitter_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_CannonMuzzleFlashEmitter_functions.cpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | // ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_CannonMuzzleFlashEmitter_parameters.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Functions
//---------------------------------------------------------------------------
// Function CannonMuzzleFlashEmitter.CannonMuzzleFlashEmitter_C.UserConstructionScript
// ()
void ACannonMuzzleFlashEmitter_C::UserConstructionScript()
{
static auto fn = UObject::FindObject<UFunction>("Function CannonMuzzleFlashEmitter.CannonMuzzleFlashEmitter_C.UserConstructionScript");
ACannonMuzzleFlashEmitter_C_UserConstructionScript_Params params;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
// Function CannonMuzzleFlashEmitter.CannonMuzzleFlashEmitter_C.ExecuteUbergraph_CannonMuzzleFlashEmitter
// ()
// Parameters:
// int EntryPoint (Parm, ZeroConstructor, IsPlainOldData)
void ACannonMuzzleFlashEmitter_C::ExecuteUbergraph_CannonMuzzleFlashEmitter(int EntryPoint)
{
static auto fn = UObject::FindObject<UFunction>("Function CannonMuzzleFlashEmitter.CannonMuzzleFlashEmitter_C.ExecuteUbergraph_CannonMuzzleFlashEmitter");
ACannonMuzzleFlashEmitter_C_ExecuteUbergraph_CannonMuzzleFlashEmitter_Params params;
params.EntryPoint = EntryPoint;
auto flags = fn->FunctionFlags;
UObject::ProcessEvent(fn, ¶ms);
fn->FunctionFlags = flags;
}
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 27.333333 | 155 | 0.716945 | 2bite |
f3ad4241486ead3d1bd43ec06a52c44e528fc940 | 2,307 | hpp | C++ | engine/gems/composite/part_ref.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-04-14T13:55:16.000Z | 2020-04-14T13:55:16.000Z | engine/gems/composite/part_ref.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 4 | 2020-09-25T22:34:29.000Z | 2022-02-09T23:45:12.000Z | engine/gems/composite/part_ref.hpp | stereoboy/isaac_sdk_20191213 | 73c863254e626c8d498870189fbfb20be4e10fb3 | [
"FSFAP"
] | 1 | 2020-07-02T11:51:17.000Z | 2020-07-02T11:51:17.000Z | /*
Copyright (c) 2019, NVIDIA CORPORATION. All rights reserved.
NVIDIA CORPORATION and its licensors retain all intellectual property
and proprietary rights in and to this software, related documentation
and any modifications thereto. Any use, reproduction, disclosure or
distribution of this software and related documentation without an express
license agreement from NVIDIA CORPORATION is strictly prohibited.
*/
#pragma once
#include "engine/gems/composite/traits.hpp"
namespace isaac {
// Provides reference support for parts when they are stored in a flat array
template <typename T>
class PartRef {
public:
using Scalar = typename PartTraits<T>::Scalar;
PartRef(const PartRef&) = delete;
void operator=(const PartRef&) = delete;
PartRef(PartRef&&) = default;
void operator=(PartRef&&) = delete;
// Creates reference backed by given scalar pack
PartRef(Scalar* scalars) : scalars_(scalars) {}
// Writes a part to scalars using part traits
template <typename Other>
void operator=(const Other& value) {
PartTraits<T>::WriteToScalars(value, scalars_);
}
T get() const {
return PartTraits<T>::CreateFromScalars(scalars_);
}
operator T() const {
return get();
}
private:
Scalar* scalars_;
};
// Similar to PartRef, but provides only const access
template <typename T>
class PartConstRef {
public:
using Scalar = typename PartTraits<T>::Scalar;
PartConstRef(const PartConstRef&) = delete;
void operator=(const PartConstRef&) = delete;
PartConstRef(PartConstRef&&) = default;
void operator=(PartConstRef&&) = delete;
PartConstRef(const Scalar* scalars) : scalars_(scalars) {}
T get() const {
return PartTraits<T>::CreateFromScalars(scalars_);
}
operator T() const {
return get();
}
private:
const Scalar* scalars_;
};
// Evaluates a part ref to the corresponding type (creating a copy)
template <typename T>
T Evaluate(const PartRef<T>& ref) {
return ref.get();
}
// Evaluates a part ref to the corresponding type (creating a copy)
template <typename T>
T Evaluate(const PartConstRef<T>& ref) {
return ref.get();
}
// Evaluates a part to the corresponding type by return a reference to the original value
template <typename T>
const T& Evaluate(const T& value) {
return value;
}
} // namespace isaac
| 24.542553 | 89 | 0.727352 | stereoboy |
f3ae6222b0e2a760eb5af4abf5431c9d0de2a3a1 | 31,931 | cpp | C++ | code/components/ros-patches-five/src/SCUIStub.cpp | liquiad/fivem | 36e943be678cd8b677b8c0a32831ccf592d2e84d | [
"MIT"
] | null | null | null | code/components/ros-patches-five/src/SCUIStub.cpp | liquiad/fivem | 36e943be678cd8b677b8c0a32831ccf592d2e84d | [
"MIT"
] | null | null | null | code/components/ros-patches-five/src/SCUIStub.cpp | liquiad/fivem | 36e943be678cd8b677b8c0a32831ccf592d2e84d | [
"MIT"
] | null | null | null | /*
* This file is part of the CitizenFX project - http://citizen.re/
*
* See LICENSE and MENTIONS in the root of the source tree for information
* regarding licensing.
*/
#include "StdInc.h"
#include <ros/EndpointMapper.h>
#include <fstream>
#include <cpr/cpr.h>
#include "base64.h"
#include <botan/botan.h>
#include <botan/hash.h>
#include <botan/stream_cipher.h>
#include <botan/base64.h>
#include <boost/algorithm/string.hpp>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
// XOR auto-vectorization is broken in VS15.7+, so don't optimize this file
#pragma optimize("", off)
// gta5
//#define ROS_PLATFORM_KEY "C4pWJwWIKGUxcHd69eGl2AOwH2zrmzZAoQeHfQFcMelybd32QFw9s10px6k0o75XZeB5YsI9Q9TdeuRgdbvKsxc="
// we launcher now
#define ROS_PLATFORM_KEY_LAUNCHER "C6fU6TQTPgUVmy3KIB5g8ElA7DrenVpGogSZjsh+lqJaQHqv4Azoctd/v4trfX6cBjbEitUKBG/hRINF4AhQqcg="
#define ROS_PLATFORM_KEY_RDR2 "CxdAElo3H1WNntCCLZ0WEW6WaH1cFFyvF6JCK5Oo1+UqczD626BPGczMnOuv532+AqT/7n3lIQEYxO3hhuXJItk="
class ROSCryptoState
{
private:
Botan::StreamCipher* m_rc4;
uint8_t m_rc4Key[32];
uint8_t m_xorKey[16];
uint8_t m_hashKey[16];
public:
ROSCryptoState();
inline const uint8_t* GetXorKey()
{
return m_xorKey;
}
inline const uint8_t* GetHashKey()
{
return m_hashKey;
}
};
class SCUIHandler : public net::HttpHandler
{
private:
std::string m_scuiData;
public:
SCUIHandler()
{
std::ifstream scuiFile(MakeRelativeCitPath(L"citizen/ros/scui.html"));
m_scuiData = std::string(std::istreambuf_iterator<char>(scuiFile), std::istreambuf_iterator<char>());
boost::algorithm::replace_all(m_scuiData, "{{ TITLE }}",
#if GTA_FIVE
"gta5"
#elif IS_RDR3
"rdr2"
#else
"gta4"
#endif
);
}
bool HandleRequest(fwRefContainer<net::HttpRequest> request, fwRefContainer<net::HttpResponse> response) override
{
response->SetStatusCode(200);
response->SetHeader("Content-Type", "text/html; charset=utf-8");
response->End(m_scuiData);
return true;
}
};
#include <rapidjson/document.h>
#include <rapidjson/writer.h>
#include <tinyxml2.h>
namespace
{
template<typename TValue>
void GetJsonValue(TValue value, rapidjson::Document& document, rapidjson::Value& outValue)
{
outValue.CopyFrom(rapidjson::Value(value), document.GetAllocator());
}
template<>
void GetJsonValue<const char*>(const char* value, rapidjson::Document& document, rapidjson::Value& outValue)
{
outValue.CopyFrom(rapidjson::Value(value, document.GetAllocator()), document.GetAllocator());
}
template<>
void GetJsonValue<std::nullptr_t>(std::nullptr_t value, rapidjson::Document& document, rapidjson::Value& outValue)
{
rapidjson::Value val;
val.SetNull();
outValue.CopyFrom(val, document.GetAllocator());
}
}
const char* GetROSVersionString()
{
const char* baseString = va("e=%d,t=%s,p=%s,v=%d", 1, "launcher", "pcros", 11);
// create the XOR'd buffer
std::vector<uint8_t> xorBuffer(strlen(baseString) + 4);
// set the key for the XOR buffer
*(uint32_t*)&xorBuffer[0] = 0xC5C5C5C5;
for (int i = 4; i < xorBuffer.size(); i++)
{
xorBuffer[i] = baseString[i - 4] ^ 0xC5;
}
// base64 the string
size_t base64len;
char* base64str = base64_encode(&xorBuffer[0], xorBuffer.size(), &base64len);
// create a wide string version
std::string str(base64str, base64len);
free(base64str);
// return va() version of the base64 string
return va("ros %s", str);
}
void SaveAccountData(const std::string& data);
bool LoadAccountData(boost::property_tree::ptree& tree);
bool LoadAccountData(std::string& str);
std::string BuildPOSTString(const std::map<std::string, std::string>& fields)
{
std::stringstream retval;
for (auto& field : fields)
{
retval << field.first << "=" << url_encode(field.second) << "&";
}
std::string str = std::string(retval.str().c_str());
return str.substr(0, str.length() - 1);
}
template<typename TAlloc>
auto HeadersHmac(const std::vector<uint8_t, TAlloc>& challenge, const char* method, const char* path, const std::string& sessionKey, const std::string& sessionTicket)
{
auto hmac = std::unique_ptr<Botan::MessageAuthenticationCode>(Botan::get_mac("HMAC(SHA1)")->clone());
ROSCryptoState cryptoState;
// set the key
uint8_t hmacKey[16];
// xor the RC4 key with the platform key (and optionally the session key)
auto rc4Xor = Botan::base64_decode(sessionKey);
for (int i = 0; i < sizeof(hmacKey); i++)
{
hmacKey[i] = rc4Xor[i] ^ cryptoState.GetXorKey()[i];
}
hmac->set_key(hmacKey, sizeof(hmacKey));
// method
hmac->update(method);
hmac->update(0);
// path
hmac->update(path);
hmac->update(0);
// ros-SecurityFlags
hmac->update("239");
hmac->update(0);
// ros-SessionTicket
hmac->update(sessionTicket);
hmac->update(0);
// ros-Challenge
hmac->update(Botan::base64_encode(challenge));
hmac->update(0);
// platform hash key
hmac->update(cryptoState.GetHashKey(), 16);
// set the request header
auto hmacValue = hmac->final();
return hmacValue;
}
class LoginHandler2 : public net::HttpHandler
{
private:
std::future<void> m_future;
public:
std::string DecryptROSData(const char* data, size_t size, const std::string& sessionKey = "");
std::string EncryptROSData(const std::string& input, const std::string& sessionKey = "");
void ProcessLogin(const std::string& username, const std::string& password, const std::function<void(const std::string&, const std::string&)>& cb)
{
m_future = cpr::PostCallback([=](cpr::Response r)
{
if (r.error)
{
trace("ROS error: %s\n", r.error.message);
cb("Error contacting Rockstar Online Services.", "");
}
else
{
std::string returnedXml = DecryptROSData(r.text.data(), r.text.size());
std::istringstream stream(returnedXml);
boost::property_tree::ptree tree;
boost::property_tree::read_xml(stream, tree);
if (tree.get("Response.Status", 0) == 0)
{
auto code = tree.get<std::string>("Response.Error.<xmlattr>.Code");
auto codeEx = tree.get<std::string>("Response.Error.<xmlattr>.CodeEx");
if (code == "AuthenticationFailed" && codeEx == "LoginAttempts")
{
cb(va(
"Login attempts exceeded. Please log in on https://socialclub.rockstargames.com/ and fill out the CAPTCHA, then try again."
), "");
}
else
{
cb(va(
"Could not sign on to the Social Club. Error code: %s/%s",
code,
codeEx
), "");
}
return;
}
else
{
cb("", returnedXml);
}
}
}, cpr::Url{ "http://ros.citizenfx.internal/launcher/11/launcherservices/auth.asmx/CreateTicketSc3" }, cpr::Body{ EncryptROSData(BuildPOSTString({
{"ticket", ""},
{"email", (username.find('@') != std::string::npos) ? username : "" },
{"nickname", (username.find('@') == std::string::npos) ? username : "" },
{"password", password},
{"platformName", "pcros"}}))
}, cpr::Header{
{"User-Agent", GetROSVersionString()},
{"Host", "prod.ros.rockstargames.com"}
});
}
void HandleValidateRequest(const rapidjson::Document& document, fwRefContainer<net::HttpResponse> response)
{
trace(__FUNCTION__ ": ENTER\n");
std::string ticket = document["ticket"].GetString();
std::string sessionKey = document["sessionKey"].GetString();
std::string sessionTicket = document["sessionTicket"].GetString();
std::string machineHash;
bool isEntitlementsV3 = false;
if (document.HasMember("machineHash"))
{
machineHash = document["machineHash"].GetString();
}
else if (document.HasMember("payload"))
{
machineHash = document["payload"].GetString();
isEntitlementsV3 = true;
}
auto cb = [=](const std::string& error, const std::string& data)
{
if (!error.empty())
{
response->SetStatusCode(403);
response->SetHeader("Content-Type", "text/plain; charset=utf-8");
response->End(error);
}
else
{
response->SetStatusCode(200);
response->SetHeader("Content-Type", "text/plain; charset=utf-8");
if (isEntitlementsV3)
{
response->End(data);
}
else
{
std::istringstream stream(data);
boost::property_tree::ptree tree;
boost::property_tree::read_xml(stream, tree);
response->End(tree.get<std::string>("Response.Result.Data"));
}
}
};
Botan::AutoSeeded_RNG rng;
auto challenge = rng.random_vec(8);
std::string titleAccessToken;
{
auto r = cpr::Post(cpr::Url{ "http://ros.citizenfx.internal/launcher/11/launcherservices/app.asmx/GetTitleAccessToken" }, cpr::Body{ EncryptROSData(BuildPOSTString({
{ "ticket", ticket },
#ifdef IS_RDR3
{ "titleId", "13" },
#else
{ "titleId", (isEntitlementsV3) ? "13" : "11" }, // gta5 is 11
#endif
}), sessionKey)
}, cpr::Header{
{ "User-Agent", GetROSVersionString() },
{ "Host", "prod.ros.rockstargames.com" },
{ "ros-SecurityFlags", "239" },
{ "ros-SessionTicket", sessionTicket },
{ "ros-Challenge", Botan::base64_encode(challenge) },
{ "ros-HeadersHmac", Botan::base64_encode(HeadersHmac(challenge, "POST", "/launcher/11/launcherservices/app.asmx/GetTitleAccessToken", sessionKey, sessionTicket)) }
});
if (r.error || r.status_code != 200)
{
trace("ROS error: %s\n", r.error.message);
trace("ROS error text: %s\n", DecryptROSData(r.text.c_str(), r.text.size(), sessionKey));
cb("Error contacting Rockstar Online Services.", "");
return;
}
else
{
std::string returnedXml = DecryptROSData(r.text.data(), r.text.size(), sessionKey);
std::istringstream stream(returnedXml);
boost::property_tree::ptree tree;
boost::property_tree::read_xml(stream, tree);
if (tree.get("Response.Status", 0) == 0)
{
cb(va(
"Could not get title access token from the Social Club. Error code: %s/%s",
tree.get<std::string>("Response.Error.<xmlattr>.Code").c_str(),
tree.get<std::string>("Response.Error.<xmlattr>.CodeEx").c_str()
), "");
return;
}
else
{
titleAccessToken = tree.get<std::string>("Response.Result");
}
}
}
auto method = (isEntitlementsV3)
? "GetTitleAccessTokenEntitlementBlock"
: "GetEntitlementBlock";
auto cprUrl = cpr::Url{ fmt::sprintf("http://ros.citizenfx.internal/launcher/11/launcherservices/entitlements.asmx/%s", method) };
auto map = std::map<std::string, std::string>{
{ "ticket", ticket },
{ "titleAccessToken", titleAccessToken },
};
if (!isEntitlementsV3)
{
map["locale"] = "en-US";
map["machineHash"] = machineHash;
}
else
{
map["requestedVersion"] = "1";
map["payload"] = machineHash;
}
trace(__FUNCTION__ ": Performing request.\n");
auto cprBody = cpr::Body{ EncryptROSData(BuildPOSTString(map), sessionKey) };
auto cprHeaders = cpr::Header{
{ "User-Agent", GetROSVersionString() },
{ "Host", "prod.ros.rockstargames.com" },
{ "ros-SecurityFlags", "239" },
{ "ros-SessionTicket", sessionTicket },
{ "ros-Challenge", Botan::base64_encode(challenge) },
{ "ros-HeadersHmac", Botan::base64_encode(HeadersHmac(challenge, "POST", static_cast<std::string>(cprUrl).substr(29).c_str(), sessionKey, sessionTicket)) }
};
m_future = cpr::PostCallback([=](cpr::Response r)
{
trace(__FUNCTION__ ": Performed request.\n");
if (r.error || r.status_code != 200)
{
trace("ROS error: %s\n", r.error.message);
trace("ROS error text: %s\n", r.text);
cb("Error contacting Rockstar Online Services.", "");
}
else
{
std::string returnedXml = DecryptROSData(r.text.data(), r.text.size(), sessionKey);
std::istringstream stream(returnedXml);
boost::property_tree::ptree tree;
boost::property_tree::read_xml(stream, tree);
if (tree.get("Response.Status", 0) == 0)
{
auto code = tree.get<std::string>("Response.Error.<xmlattr>.Code");
auto codeEx = tree.get<std::string>("Response.Error.<xmlattr>.CodeEx");
if (code == "NotAllowed" && codeEx == "TitleAccessToken")
{
#ifdef GTA_FIVE
cb(va("The Social Club account specified does not own a valid license to Grand Theft Auto V."), "");
#else
cb(va("The Social Club account specified does not own a valid license to Red Dead Redemption 2."), "");
#endif
}
else
{
cb(va(
"Could not get entitlement block from the Social Club. Error code: %s/%s",
code,
codeEx),
"");
}
return;
}
else
{
cb("", returnedXml);
}
}
}, cprUrl, cprBody, cprHeaders);
}
bool HandleRequest(fwRefContainer<net::HttpRequest> request, fwRefContainer<net::HttpResponse> response) override
{
request->SetDataHandler([=](const std::vector<uint8_t>& data)
{
// get the string
std::string str(data.begin(), data.end());
// parse the data
rapidjson::Document document;
document.Parse(str.c_str());
if (document.HasParseError())
{
response->SetStatusCode(200);
response->End(va("{ \"error\": \"pe %d\" }", document.GetParseError()));
return;
}
if (request->GetPath() == "/ros/validate")
{
HandleValidateRequest(document, response);
return;
}
auto handleResponse = [=](const std::string& error, const std::string& loginData)
{
if (!error.empty())
{
// and write HTTP response
response->SetStatusCode(403);
response->SetHeader("Content-Type", "text/plain; charset=utf-8");
response->End(error);
return;
}
std::istringstream stream(loginData);
boost::property_tree::ptree tree;
boost::property_tree::read_xml(stream, tree);
// generate initial XML to be contained by JSON
tinyxml2::XMLDocument document;
auto rootElement = document.NewElement("Response");
document.InsertFirstChild(rootElement);
// set root attributes
rootElement->SetAttribute("ms", 30.0);
rootElement->SetAttribute("xmlns", "CreateTicketResponse");
// elements
auto appendChildElement = [&](tinyxml2::XMLNode* node, const char* key, auto value)
{
auto element = document.NewElement(key);
element->SetText(value);
node->InsertEndChild(element);
return element;
};
auto appendElement = [&](const char* key, auto value)
{
return appendChildElement(rootElement, key, value);
};
// create the document
appendElement("Status", 1);
appendElement("Ticket", tree.get<std::string>("Response.Ticket").c_str()); // 'a' repeated
appendElement("PosixTime", static_cast<unsigned int>(time(nullptr)));
appendElement("SecsUntilExpiration", 86399);
appendElement("PlayerAccountId", tree.get<int>("Response.PlayerAccountId"));
appendElement("PublicIp", "127.0.0.1");
appendElement("SessionId", tree.get<std::string>("Response.SessionId").c_str());
appendElement("SessionKey", tree.get<std::string>("Response.SessionKey").c_str()); // '0123456789abcdef'
appendElement("SessionTicket", tree.get<std::string>("Response.SessionTicket").c_str());
appendElement("CloudKey", "8G8S9JuEPa3kp74FNQWxnJ5BXJXZN1NFCiaRRNWaAUR=");
// services
auto servicesElement = appendElement("Services", "");
servicesElement->SetAttribute("Count", 0);
// Rockstar account
tinyxml2::XMLNode* rockstarElement = appendElement("RockstarAccount", "");
appendChildElement(rockstarElement, "RockstarId", tree.get<std::string>("Response.RockstarAccount.RockstarId").c_str());
appendChildElement(rockstarElement, "Age", 18);
appendChildElement(rockstarElement, "AvatarUrl", "Bully/b20.png");
appendChildElement(rockstarElement, "CountryCode", "CA");
appendChildElement(rockstarElement, "Email", tree.get<std::string>("Response.RockstarAccount.Email").c_str());
appendChildElement(rockstarElement, "LanguageCode", "en");
appendChildElement(rockstarElement, "Nickname", fmt::sprintf("R%08x", ROS_DUMMY_ACCOUNT_ID).c_str());
appendElement("Privileges", "1,2,3,4,5,6,8,9,10,11,14,15,16,17,18,19,21,22,27");
auto privsElement = appendElement("Privs", "");
auto privElement = appendChildElement(privsElement, "p", "");
privElement->SetAttribute("id", "27");
privElement->SetAttribute("g", "True");
// format as string
tinyxml2::XMLPrinter printer;
document.Print(&printer);
// JSON document
rapidjson::Document json;
// this is an object
json.SetObject();
// append data
auto appendJson = [&](const char* key, auto value)
{
rapidjson::Value jsonKey(key, json.GetAllocator());
rapidjson::Value jsonValue;
GetJsonValue(value, json, jsonValue);
json.AddMember(jsonKey, jsonValue, json.GetAllocator());
};
appendJson("SessionKey", tree.get<std::string>("Response.SessionKey").c_str());
appendJson("SessionTicket", tree.get<std::string>("Response.SessionTicket").c_str());
appendJson("Ticket", tree.get<std::string>("Response.Ticket").c_str());
appendJson("Email", tree.get<std::string>("Response.RockstarAccount.Email").c_str());
appendJson("SaveEmail", true);
appendJson("SavePassword", true);
appendJson("Password", "DetCon1");
appendJson("Nickname", fmt::sprintf("R%08x", ROS_DUMMY_ACCOUNT_ID).c_str());
appendJson("RockstarId", tree.get<std::string>("Response.RockstarAccount.RockstarId").c_str());
appendJson("CallbackData", 2);
appendJson("Local", false);
appendJson("SignedIn", true);
appendJson("SignedOnline", true);
appendJson("AutoSignIn", false);
appendJson("Expiration", 86399);
appendJson("AccountId", tree.get<std::string>("Response.PlayerAccountId").c_str());
appendJson("Age", 18);
appendJson("AvatarUrl", "Bully/b20.png");
appendJson("XMLResponse", printer.CStr());
appendJson("OrigNickname", tree.get<std::string>("Response.RockstarAccount.Nickname").c_str());
// serialize json
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Accept(writer);
// and write HTTP response
response->SetStatusCode(200);
response->SetHeader("Content-Type", "application/json; charset=utf-8");
response->End(std::string(buffer.GetString(), buffer.GetSize()));
};
bool local = (document.HasMember("local") && document["local"].GetBool());
if (!local)
{
std::string username = document["username"].GetString();
std::string password = document["password"].GetString();
ProcessLogin(username, password, [=](const std::string& error, const std::string& loginData)
{
if (error.empty())
{
SaveAccountData(loginData);
}
handleResponse(error, loginData);
});
}
else
{
std::string str;
bool hasData = LoadAccountData(str);
if (!hasData)
{
handleResponse("No login data.", "");
}
else
{
handleResponse("", str);
}
}
});
return true;
}
};
std::string LoginHandler2::EncryptROSData(const std::string& input, const std::string& sessionKey /* = "" */)
{
// initialize state
ROSCryptoState state;
std::stringstream output;
// decode session key, if needed
bool hasSecurity = (!sessionKey.empty());
uint8_t sessKey[16];
if (hasSecurity)
{
auto keyData = Botan::base64_decode(sessionKey);
memcpy(sessKey, keyData.data(), sizeof(sessKey));
}
// get a random RC4 key
uint8_t rc4Key[16];
Botan::AutoSeeded_RNG rng;
rng.randomize(rc4Key, sizeof(rc4Key));
// XOR the key with the global XOR key and write it to the output
for (int i = 0; i < sizeof(rc4Key); i++)
{
char thisChar = rc4Key[i] ^ state.GetXorKey()[i];
output << std::string(&thisChar, 1);
if (hasSecurity)
{
rc4Key[i] ^= sessKey[i];
}
}
// create a RC4 cipher for the data
Botan::StreamCipher* rc4 = Botan::get_stream_cipher("RC4")->clone();
rc4->set_key(rc4Key, sizeof(rc4Key));
// encrypt the passed user data using the key
std::vector<uint8_t> inData(input.size());
memcpy(&inData[0], input.c_str(), inData.size());
rc4->encipher(inData);
// write the inData to the output stream
output << std::string(reinterpret_cast<const char*>(&inData[0]), inData.size());
// get a hash for the stream's content so far
std::string tempContent = output.str();
Botan::Buffered_Computation* sha1;
if (!hasSecurity)
{
sha1 = Botan::get_hash("SHA1")->clone();
}
else
{
auto hmac = Botan::get_mac("HMAC(SHA1)")->clone();
hmac->set_key(rc4Key, sizeof(rc4Key));
sha1 = hmac;
}
sha1->update(reinterpret_cast<const uint8_t*>(tempContent.c_str()), tempContent.size());
sha1->update(state.GetHashKey(), 16);
auto hashData = sha1->final();
// free the algorithms
delete rc4;
delete sha1;
// and return the appended output
return tempContent + std::string(reinterpret_cast<const char*>(&hashData[0]), hashData.size());
}
#pragma optimize("", off)
std::string LoginHandler2::DecryptROSData(const char* data, size_t size, const std::string& sessionKey)
{
// initialize state
ROSCryptoState state;
// read the packet RC4 key from the packet
uint8_t rc4Key[16];
bool hasSecurity = (!sessionKey.empty());
uint8_t sessKey[16];
if (hasSecurity)
{
auto keyData = Botan::base64_decode(sessionKey);
memcpy(sessKey, keyData.data(), sizeof(sessKey));
}
for (int i = 0; i < sizeof(rc4Key); i++)
{
rc4Key[i] = data[i] ^ state.GetXorKey()[i];
if (hasSecurity)
{
rc4Key[i] ^= sessKey[i];
}
}
// initialize RC4 with the packet key
Botan::StreamCipher* rc4 = Botan::get_stream_cipher("RC4")->clone();
rc4->set_key(rc4Key, sizeof(rc4Key));
// read the block size from the data
uint8_t blockSizeData[4];
uint8_t blockSizeDataLE[4];
rc4->cipher(reinterpret_cast<const uint8_t*>(&data[16]), blockSizeData, 4);
// swap endianness
blockSizeDataLE[3] = blockSizeData[0];
blockSizeDataLE[2] = blockSizeData[1];
blockSizeDataLE[1] = blockSizeData[2];
blockSizeDataLE[0] = blockSizeData[3];
uint32_t blockSize = (*(uint32_t*)&blockSizeDataLE) + 20;
// create a buffer for the block
std::vector<uint8_t> blockData(blockSize);
// a result stringstream as well
std::stringstream result;
// loop through packet blocks
size_t start = 20;
while (start < size)
{
// calculate the end of this block
int end = fwMin(size, start + blockSize);
// remove the size of the SHA1 hash from the end
end -= 20;
int thisLen = end - start;
// decrypt the block
rc4->cipher(reinterpret_cast<const uint8_t*>(&data[start]), &blockData[0], thisLen);
// TODO: compare the resulting hash
// append to the result buffer
result << std::string(reinterpret_cast<const char*>(&blockData[0]), thisLen);
// increment the counter
start += blockSize;
}
delete rc4;
return result.str();
}
#pragma optimize("", on)
ROSCryptoState::ROSCryptoState()
{
// initialize the key inputs
size_t outLength;
uint8_t* platformStr;
platformStr = base64_decode(ROS_PLATFORM_KEY_LAUNCHER, strlen(ROS_PLATFORM_KEY_LAUNCHER), &outLength);
memcpy(m_rc4Key, &platformStr[1], sizeof(m_rc4Key));
memcpy(m_xorKey, &platformStr[33], sizeof(m_xorKey));
memcpy(m_hashKey, &platformStr[49], sizeof(m_hashKey));
free(platformStr);
// create the RC4 cipher and decode the keys
m_rc4 = Botan::get_stream_cipher("RC4")->clone();
// set the key
m_rc4->set_key(m_rc4Key, sizeof(m_rc4Key));
// decode the xor key
m_rc4->cipher1(m_xorKey, sizeof(m_xorKey));
// reset the key
m_rc4->set_key(m_rc4Key, sizeof(m_rc4Key));
// decode the hash key
m_rc4->cipher1(m_hashKey, sizeof(m_hashKey));
// and we're done
delete m_rc4;
}
std::string GetRockstarTicketXml()
{
// generate initial XML to be contained by JSON
tinyxml2::XMLDocument document;
auto rootElement = document.NewElement("Response");
document.InsertFirstChild(rootElement);
// set root attributes
rootElement->SetAttribute("ms", 30.0);
rootElement->SetAttribute("xmlns", "CreateTicketResponse");
// elements
auto appendChildElement = [&](tinyxml2::XMLNode * node, const char* key, auto value)
{
auto element = document.NewElement(key);
element->SetText(value);
node->InsertEndChild(element);
return element;
};
auto appendElement = [&](const char* key, auto value)
{
return appendChildElement(rootElement, key, value);
};
// create the document
appendElement("Status", 1);
appendElement("Ticket", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh"); // 'a' repeated
appendElement("PosixTime", static_cast<unsigned int>(time(nullptr)));
appendElement("SecsUntilExpiration", 86399);
appendElement("PlayerAccountId", va("%lld", ROS_DUMMY_ACCOUNT_ID));
appendElement("PublicIp", "127.0.0.1");
appendElement("SessionId", 5);
appendElement("SessionKey", "MDEyMzQ1Njc4OWFiY2RlZg=="); // '0123456789abcdef'
appendElement("SessionTicket", "vhASmPR0NnA7MZsdVCTCV/3XFABWGa9duCEscmAM0kcCDVEa7YR/rQ4kfHs2HIPIttq08TcxIzuwyPWbaEllvQ==");
appendElement("CloudKey", "8G8S9JuEPa3kp74FNQWxnJ5BXJXZN1NFCiaRRNWaAUR=");
// services
auto servicesElement = appendElement("Services", "");
servicesElement->SetAttribute("Count", 0);
// Rockstar account
tinyxml2::XMLNode* rockstarElement = appendElement("RockstarAccount", "");
appendChildElement(rockstarElement, "RockstarId", va("%lld", ROS_DUMMY_ACCOUNT_ID));
appendChildElement(rockstarElement, "Age", 18);
appendChildElement(rockstarElement, "AvatarUrl", "Bully/b20.png");
appendChildElement(rockstarElement, "CountryCode", "CA");
appendChildElement(rockstarElement, "Email", "onlineservices@fivem.net");
appendChildElement(rockstarElement, "LanguageCode", "en");
appendChildElement(rockstarElement, "Nickname", fmt::sprintf("R%08x", ROS_DUMMY_ACCOUNT_ID).c_str());
appendElement("Privileges", "1,2,3,4,5,6,8,9,10,11,14,15,16,17,18,19,21,22,27");
auto privsElement = appendElement("Privs", "");
auto privElement = appendChildElement(privsElement, "p", "");
privElement->SetAttribute("id", "27");
privElement->SetAttribute("g", "True");
// format as string
tinyxml2::XMLPrinter printer;
document.Print(&printer);
return printer.CStr();
}
std::string HandleCfxLogin()
{
auto rockstarTicket = GetRockstarTicketXml();
// JSON document
rapidjson::Document json;
// this is an object
json.SetObject();
// append data
auto appendJson = [&](const char* key, auto value)
{
rapidjson::Value jsonKey(key, json.GetAllocator());
rapidjson::Value jsonValue;
GetJsonValue(value, json, jsonValue);
json.AddMember(jsonKey, jsonValue, json.GetAllocator());
};
appendJson("SessionKey", "MDEyMzQ1Njc4OWFiY2RlZg==");
appendJson("Ticket", "YWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFh");
appendJson("Email", "onlineservices@fivem.net");
appendJson("SaveEmail", true);
appendJson("SavePassword", true);
appendJson("Password", "DetCon1");
appendJson("Nickname", fmt::sprintf("R%08x", ROS_DUMMY_ACCOUNT_ID).c_str());
appendJson("RockstarId", va("%lld", ROS_DUMMY_ACCOUNT_ID));
appendJson("CallbackData", 2);
appendJson("Local", false);
appendJson("SignedIn", true);
appendJson("SignedOnline", true);
appendJson("AutoSignIn", false);
appendJson("Expiration", 86399);
appendJson("AccountId", va("%lld", ROS_DUMMY_ACCOUNT_ID));
appendJson("Age", 18);
appendJson("AvatarUrl", "Bully/b20.png");
appendJson("XMLResponse", rockstarTicket.c_str());
// serialize json
rapidjson::StringBuffer buffer;
rapidjson::Writer<rapidjson::StringBuffer> writer(buffer);
json.Accept(writer);
return { buffer.GetString(), buffer.GetSize() };
}
class LoginHandler : public net::HttpHandler
{
public:
bool HandleRequest(fwRefContainer<net::HttpRequest> request, fwRefContainer<net::HttpResponse> response) override
{
auto buffer = HandleCfxLogin();
// and write HTTP response
response->SetStatusCode(200);
response->SetHeader("Content-Type", "application/json; charset=utf-8");
response->End(std::move(buffer));
return true;
}
};
static InitFunction initFunction([] ()
{
EndpointMapper* endpointMapper = Instance<EndpointMapper>::Get();
endpointMapper->AddPrefix("/scui/v2/desktop", new SCUIHandler()); // TODO: have a generic static HTTP handler someplace?
endpointMapper->AddPrefix("/cfx/login", new LoginHandler());
endpointMapper->AddPrefix("/ros/login", new LoginHandler2());
endpointMapper->AddPrefix("/ros/validate", new LoginHandler2());
// somehow launcher likes using two slashes - this should be handled better tbh
endpointMapper->AddPrefix("//scui/v2/desktop", new SCUIHandler());
// MTL
endpointMapper->AddPrefix("/scui/mtl/launcher", new SCUIHandler());
endpointMapper->AddPrefix("//scui/mtl/launcher", new SCUIHandler());
});
| 31.614851 | 241 | 0.619805 | liquiad |
f3b1489269e8bd438d5c8da7c260fa8ac1d55d51 | 2,165 | hpp | C++ | alpaka/test/unit/math/src/Defines.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | 6 | 2021-02-01T09:01:39.000Z | 2021-11-14T17:09:03.000Z | alpaka/test/unit/math/src/Defines.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | 17 | 2020-11-09T14:13:50.000Z | 2021-11-03T11:54:54.000Z | alpaka/test/unit/math/src/Defines.hpp | alpaka-group/mallocMC | ddba224b764885f816c42a7719551b14e6f5752b | [
"MIT"
] | null | null | null | /** Copyright 2019 Jakob Krude, Benjamin Worpitz
*
* This file is part of alpaka.
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
#pragma once
#include <cmath>
#include <iomanip>
#include <iostream>
#include <limits>
namespace alpaka
{
namespace test
{
namespace unit
{
namespace math
{
// New types need to be added to the switch-case in DataGen.hpp
enum class Range
{
OneNeighbourhood,
PositiveOnly,
PositiveAndZero,
NotZero,
Unrestricted
};
// New types need to be added to the operator() function in Functor.hpp
enum class Arity
{
Unary = 1,
Binary = 2
};
template<typename T, Arity Tarity>
struct ArgsItem
{
static constexpr Arity arity = Tarity;
static constexpr size_t arity_nr = static_cast<size_t>(Tarity);
T arg[arity_nr]; // represents arg0, arg1, ...
friend std::ostream& operator<<(std::ostream& os, const ArgsItem& argsItem)
{
os.precision(17);
os << "[ ";
for(size_t i = 0; i < argsItem.arity_nr; ++i)
os << std::setprecision(std::numeric_limits<T>::digits10 + 1) << argsItem.arg[i] << ", ";
os << "]";
return os;
}
};
template<typename T>
auto rsqrt(T const& arg) -> decltype(std::sqrt(arg))
{
return static_cast<T>(1) / std::sqrt(arg);
}
} // namespace math
} // namespace unit
} // namespace test
} // namespace alpaka
| 30.492958 | 117 | 0.455427 | alpaka-group |
f3b1ab508b6600f27ff7b25ec38b851a4d0af170 | 868 | cpp | C++ | packages/nextalign/src/translate/translate.cpp | Centralize/nextclade | 22115d497a877369f1e8b765e80ddc68cbbca65f | [
"MIT"
] | null | null | null | packages/nextalign/src/translate/translate.cpp | Centralize/nextclade | 22115d497a877369f1e8b765e80ddc68cbbca65f | [
"MIT"
] | null | null | null | packages/nextalign/src/translate/translate.cpp | Centralize/nextclade | 22115d497a877369f1e8b765e80ddc68cbbca65f | [
"MIT"
] | null | null | null | #include "translate.h"
#include <nextalign/nextalign.h>
#include <common/contract.h>
#include "../utils/safe_cast.h"
#include "decode.h"
AminoacidSequence translate(const NucleotideSequenceView& seq, bool translatePastStop /* = false */) {
const int seqLength = safe_cast<int>(seq.size());
// NOTE: rounds the result to the multiple of 3 (floor),
// so that translation does not overrun the buffer
const int peptideLength = seqLength / 3;
AminoacidSequence peptide(peptideLength, Aminoacid::GAP);
for (int i_aa = 0; i_aa < peptideLength; ++i_aa) {
const auto i_nuc = i_aa * 3;
const auto codon = seq.substr(i_nuc, 3);
const auto aminoacid = decode(codon);
invariant_less(i_aa, peptide.size());
peptide[i_aa] = aminoacid;
if (!translatePastStop && aminoacid == Aminoacid::STOP) {
break;
}
}
return peptide;
}
| 25.529412 | 102 | 0.686636 | Centralize |
f3b224f34fdcdac455d84b7699f1eafc88c52504 | 1,645 | cpp | C++ | src/lib/cpp/jsontest.cpp | chetmurthy/thrift-nicejson | 3ce7a84af55591be4388f93c095032d739ee3917 | [
"Apache-2.0"
] | 8 | 2017-11-14T13:22:09.000Z | 2020-07-30T02:33:18.000Z | src/lib/cpp/jsontest.cpp | chetmurthy/thrift-nicejson | 3ce7a84af55591be4388f93c095032d739ee3917 | [
"Apache-2.0"
] | null | null | null | src/lib/cpp/jsontest.cpp | chetmurthy/thrift-nicejson | 3ce7a84af55591be4388f93c095032d739ee3917 | [
"Apache-2.0"
] | 3 | 2017-11-18T10:53:10.000Z | 2018-01-16T20:11:28.000Z | #include <list>
#include <boost/smart_ptr.hpp>
#include "gtest/gtest.h"
#include "json.hpp"
using boost::shared_ptr;
using std::cout;
using std::endl;
using std::string;
using std::map;
using std::list;
using std::set;
using nlohmann::json;
TEST( JSON, ParseEmpty )
{
json j = "{}"_json ;
ASSERT_TRUE( j.empty() );
ASSERT_FALSE( j.is_null() );
ASSERT_TRUE( j.is_object() );
}
TEST( JSON, Null )
{
json j;
ASSERT_TRUE( j.empty() );
ASSERT_TRUE( j.is_null() );
ASSERT_FALSE( j.is_object() );
}
TEST( JSON, Array )
{
json j = std::vector<int>{} ;
ASSERT_TRUE( j.empty() );
ASSERT_FALSE( j.is_null() );
ASSERT_TRUE( j.is_array() );
ASSERT_TRUE( j.size() == 0 );
}
TEST( JSON, ParseArray )
{
json j = "[]"_json ;
ASSERT_TRUE( j.empty() );
ASSERT_FALSE( j.is_null() );
ASSERT_TRUE( j.is_array() );
ASSERT_TRUE( j.size() == 0 );
}
TEST( JSON, Object )
{
json j = R"foo(
{ "a": 10,
"b": "bar"
}
)foo"_json ;
json j2 = { { "a", 10 }, { "b", "bar" } } ;
ASSERT_TRUE( j == j2) ;
}
TEST( JSON, Object2 )
{
json j = R"foo(
{ "1": 10,
"2": "bar"
}
)foo"_json ;
ASSERT_TRUE( j.is_object()) ;
}
TEST( JSON, Object2StringException )
{
json j = "{}"_json ;
ASSERT_THROW ( j.get<string>() , std::exception ) ;
}
TEST( JSON, NumericLimits )
{
json j ;
j = std::numeric_limits<int32_t>::max() ;
ASSERT_EQ(j.get<int32_t>(), std::numeric_limits<int32_t>::max()) ;
j = 1ll + (int64_t)std::numeric_limits<int32_t>::max() ;
ASSERT_EQ(j.get<int64_t>(), 1ll + (int64_t)std::numeric_limits<int32_t>::max()) ;
ASSERT_NE(j.get<int32_t>(), 1ll + (int64_t)std::numeric_limits<int32_t>::max()) ;
}
| 18.076923 | 83 | 0.604863 | chetmurthy |
f3b363767bf31e84477c936caa92f14fde7d5b17 | 1,257 | cpp | C++ | DOJ/#271.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | DOJ/#271.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | 1 | 2021-11-18T15:10:29.000Z | 2021-11-20T07:13:31.000Z | DOJ/#271.cpp | Nickel-Angel/ACM-and-OI | 79d13fd008c3a1fe9ebf35329aceb1fcb260d5d9 | [
"MIT"
] | null | null | null | /*
* @author Nickel_Angel (1239004072@qq.com)
* @copyright Copyright (c) 2022
*/
#include <algorithm>
#include <cstdio>
#include <cstring>
int n, m, a[1010], w[1010], par[1010], rev[1010], dfn[1010], R[1010], timer;
int head[1010], to[1010], next[1010], tot, f[1010][10010];
inline void add_edge(int u, int v)
{
to[++tot] = v;
next[tot] = head[u];
head[u] = tot;
}
void dfs(int u)
{
dfn[u] = ++timer;
rev[timer] = u;
for (int c = head[u], v; c; c = next[c])
{
v = to[c];
dfs(v);
}
R[u] = timer + 1;
}
int main()
{
scanf("%d%d", &n, &m);
for (int i = 2; i <= n; ++i)
{
scanf("%d", par + i);
add_edge(par[i], i);
}
for (int i = 1; i <= n; ++i)
scanf("%d", a + i);
for (int i = 1; i <= n; ++i)
scanf("%d", w + i);
dfs(1);
for (int i = 1; i <= m; ++i)
f[n + 1][i] = -0x3f3f3f3f;
for (int i = n; i > 0; --i)
{
for (int j = 0; j <= m; ++j)
{
f[i][j] = f[R[rev[i]]][j];
if (j >= w[rev[i]])
f[i][j] = std::max(f[i][j], f[i + 1][j - w[rev[i]]] + a[rev[i]]);
}
}
for (int i = 0; i <= m; ++i)
printf("%d\n", f[1][i] > 0 ? f[1][i] : 0);
return 0;
} | 21.305085 | 81 | 0.411297 | Nickel-Angel |
f3ba6502ac1ae470689769379110d397b47903da | 12,489 | cpp | C++ | extras/Projucer/Source/Project/UI/jucer_HeaderComponent.cpp | sukoi26/JUCE | e3233ae230ac0c13f73ee2d08bd8f2c9b12c4b19 | [
"ISC",
"Unlicense"
] | 1 | 2016-08-15T14:11:21.000Z | 2016-08-15T14:11:21.000Z | extras/Projucer/Source/Project/UI/jucer_HeaderComponent.cpp | sukoi26/JUCE | e3233ae230ac0c13f73ee2d08bd8f2c9b12c4b19 | [
"ISC",
"Unlicense"
] | 4 | 2019-02-11T11:52:13.000Z | 2020-10-09T06:39:18.000Z | extras/Projucer/Source/Project/UI/jucer_HeaderComponent.cpp | sukoi26/JUCE | e3233ae230ac0c13f73ee2d08bd8f2c9b12c4b19 | [
"ISC",
"Unlicense"
] | null | null | null | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2017 - ROLI Ltd.
JUCE is an open source library subject to commercial or open-source
licensing.
By using JUCE, you agree to the terms of both the JUCE 5 End-User License
Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
27th April 2017).
End User License Agreement: www.juce.com/juce-5-licence
Privacy Policy: www.juce.com/juce-5-privacy-policy
Or: You may also use this code under the terms of the GPL v3 (see
www.gnu.org/licenses).
JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
DISCLAIMED.
==============================================================================
*/
#include "jucer_HeaderComponent.h"
#include "../../ProjectSaving/jucer_ProjectExporter.h"
#include "../../Project/UI/jucer_ProjectContentComponent.h"
#include "../../LiveBuildEngine/jucer_MessageIDs.h"
#include "../../LiveBuildEngine/jucer_SourceCodeRange.h"
#include "../../LiveBuildEngine/jucer_ClassDatabase.h"
#include "../../LiveBuildEngine/jucer_DiagnosticMessage.h"
#include "../../LiveBuildEngine/jucer_CompileEngineClient.h"
//======================================================================
HeaderComponent::HeaderComponent()
{
addAndMakeVisible (configLabel);
addAndMakeVisible (exporterBox);
exporterBox.onChange = [this] { updateExporterButton(); };
juceIcon.reset (new ImageComponent ("icon"));
addAndMakeVisible (juceIcon.get());
juceIcon->setImage (ImageCache::getFromMemory (BinaryData::juce_icon_png, BinaryData::juce_icon_pngSize),
RectanglePlacement::centred);
projectNameLabel.setText ({}, dontSendNotification);
addAndMakeVisible (projectNameLabel);
initialiseButtons();
}
HeaderComponent::~HeaderComponent()
{
if (userSettingsWindow != nullptr)
userSettingsWindow->dismiss();
if (childProcess != nullptr)
{
childProcess->activityList.removeChangeListener(this);
childProcess->errorList.removeChangeListener (this);
}
}
//======================================================================
void HeaderComponent::resized()
{
auto bounds = getLocalBounds();
configLabel.setFont ({ bounds.getHeight() / 3.0f });
//======================================================================
{
auto headerBounds = bounds.removeFromLeft (tabsWidth);
const int buttonSize = 25;
auto buttonBounds = headerBounds.removeFromRight (buttonSize);
projectSettingsButton->setBounds (buttonBounds.removeFromBottom (buttonSize).reduced (2));
juceIcon->setBounds (headerBounds.removeFromLeft (headerBounds.getHeight()).reduced (2));
headerBounds.removeFromRight (5);
projectNameLabel.setBounds (headerBounds);
}
//======================================================================
auto exporterWidth = jmin (400, bounds.getWidth() / 2);
Rectangle<int> exporterBounds (0, 0, exporterWidth, bounds.getHeight());
exporterBounds.setCentre (bounds.getCentre());
runAppButton->setBounds (exporterBounds.removeFromRight (exporterBounds.getHeight()).reduced (2));
saveAndOpenInIDEButton->setBounds (exporterBounds.removeFromRight (exporterBounds.getHeight()).reduced (2));
exporterBounds.removeFromRight (5);
exporterBox.setBounds (exporterBounds.removeFromBottom (roundToInt (exporterBounds.getHeight() / 1.8f)));
configLabel.setBounds (exporterBounds);
bounds.removeFromRight (5);
userSettingsButton->setBounds (bounds.removeFromRight (bounds.getHeight()).reduced (2));
}
void HeaderComponent::paint (Graphics& g)
{
g.fillAll (findColour (backgroundColourId));
if (isBuilding)
getLookAndFeel().drawSpinningWaitAnimation (g, findColour (treeIconColourId),
runAppButton->getX(), runAppButton->getY(),
runAppButton->getWidth(), runAppButton->getHeight());
}
//======================================================================
void HeaderComponent::setCurrentProject (Project* p) noexcept
{
project = p;
exportersTree = project->getExporters();
exportersTree.addListener (this);
updateExporters();
project->addChangeListener (this);
updateName();
isBuilding = false;
stopTimer();
repaint();
childProcess = ProjucerApplication::getApp().childProcessCache->getExisting (*project);
if (childProcess != nullptr)
{
childProcess->activityList.addChangeListener (this);
childProcess->errorList.addChangeListener (this);
}
if (childProcess != nullptr)
{
runAppButton->setTooltip ({});
runAppButton->setEnabled (true);
}
else
{
runAppButton->setTooltip ("Enable live-build engine to launch application");
runAppButton->setEnabled (false);
}
}
//======================================================================
void HeaderComponent::updateExporters() noexcept
{
auto selectedName = getSelectedExporterName();
exporterBox.clear();
auto preferredExporterIndex = -1;
int i = 0;
for (Project::ExporterIterator exporter (*project); exporter.next(); ++i)
{
exporterBox.addItem (exporter->getName(), i + 1);
if (selectedName == exporter->getName())
exporterBox.setSelectedId (i + 1);
if (exporter->canLaunchProject() && preferredExporterIndex == -1)
preferredExporterIndex = i;
}
if (exporterBox.getSelectedItemIndex() == -1)
exporterBox.setSelectedItemIndex (preferredExporterIndex != -1 ? preferredExporterIndex
: 0);
updateExporterButton();
}
String HeaderComponent::getSelectedExporterName() const noexcept
{
return exporterBox.getItemText (exporterBox.getSelectedItemIndex());
}
bool HeaderComponent::canCurrentExporterLaunchProject() const noexcept
{
for (Project::ExporterIterator exporter (*project); exporter.next();)
if (exporter->getName() == getSelectedExporterName() && exporter->canLaunchProject())
return true;
return false;
}
//======================================================================
int HeaderComponent::getUserButtonWidth() const noexcept
{
return userSettingsButton->getWidth();
}
void HeaderComponent::sidebarTabsWidthChanged (int newWidth) noexcept
{
tabsWidth = newWidth;
resized();
}
//======================================================================
void HeaderComponent::showUserSettings() noexcept
{
#if JUCER_ENABLE_GPL_MODE
auto settingsPopupHeight = 40;
auto settingsPopupWidth = 200;
#else
auto settingsPopupHeight = 150;
auto settingsPopupWidth = 250;
#endif
auto* content = new UserSettingsPopup (false);
content->setSize (settingsPopupWidth, settingsPopupHeight);
userSettingsWindow = &CallOutBox::launchAsynchronously (content, userSettingsButton->getScreenBounds(), nullptr);
}
//==========================================================================
void HeaderComponent::lookAndFeelChanged()
{
if (userSettingsWindow != nullptr)
userSettingsWindow->sendLookAndFeelChange();
}
void HeaderComponent::changeListenerCallback (ChangeBroadcaster* source)
{
if (source == project)
{
updateName();
updateExporters();
}
else if (childProcess != nullptr)
{
if (childProcess->activityList.getNumActivities() > 0)
buildPing();
else
buildFinished (childProcess->errorList.getNumErrors() == 0);
}
}
void HeaderComponent::timerCallback()
{
repaint();
}
//======================================================================
static void sendProjectButtonAnalyticsEvent (StringRef label)
{
StringPairArray data;
data.set ("label", label);
Analytics::getInstance()->logEvent ("Project Button", data, ProjucerAnalyticsEvent::projectEvent);
}
void HeaderComponent::initialiseButtons() noexcept
{
auto& icons = getIcons();
projectSettingsButton.reset (new IconButton ("Project Settings", &icons.settings));
addAndMakeVisible (projectSettingsButton.get());
projectSettingsButton->onClick = [this]
{
sendProjectButtonAnalyticsEvent ("Project Settings");
if (auto* pcc = findParentComponentOfClass<ProjectContentComponent>())
pcc->showProjectSettings();
};
saveAndOpenInIDEButton.reset (new IconButton ("Save and Open in IDE", nullptr));
addAndMakeVisible (saveAndOpenInIDEButton.get());
saveAndOpenInIDEButton->isIDEButton = true;
saveAndOpenInIDEButton->onClick = [this]
{
sendProjectButtonAnalyticsEvent ("Save and Open in IDE (" + exporterBox.getText() + ")");
if (auto* pcc = findParentComponentOfClass<ProjectContentComponent>())
pcc->openInSelectedIDE (true);
};
userSettingsButton.reset (new IconButton ("User Settings", &icons.user));
addAndMakeVisible (userSettingsButton.get());
userSettingsButton->isUserButton = true;
userSettingsButton->onClick = [this]
{
sendProjectButtonAnalyticsEvent ("User Settings");
if (auto* pcc = findParentComponentOfClass<ProjectContentComponent>())
showUserSettings();
};
runAppButton.reset (new IconButton ("Run Application", &icons.play));
addAndMakeVisible (runAppButton.get());
runAppButton->onClick = [this]
{
sendProjectButtonAnalyticsEvent ("Run Application");
if (childProcess != nullptr)
childProcess->launchApp();
};
updateExporterButton();
updateUserAvatar();
}
void HeaderComponent::updateName() noexcept
{
projectNameLabel.setText (project->getDocumentTitle(), dontSendNotification);
}
void HeaderComponent::updateExporterButton() noexcept
{
auto currentExporterName = getSelectedExporterName();
for (auto info : ProjectExporter::getExporterTypes())
{
if (currentExporterName.contains (info.name))
{
saveAndOpenInIDEButton->iconImage = info.getIcon();
saveAndOpenInIDEButton->repaint();
saveAndOpenInIDEButton->setEnabled (canCurrentExporterLaunchProject());
}
}
}
void HeaderComponent::updateUserAvatar() noexcept
{
if (auto* controller = ProjucerApplication::getApp().licenseController.get())
{
auto state = controller->getState();
userSettingsButton->iconImage = state.avatar;
userSettingsButton->repaint();
}
}
//======================================================================
void HeaderComponent::buildPing()
{
if (! isTimerRunning())
{
isBuilding = true;
runAppButton->setEnabled (false);
runAppButton->setTooltip ("Building...");
startTimer (50);
}
}
void HeaderComponent::buildFinished (bool success)
{
stopTimer();
isBuilding = false;
repaint();
setRunAppButtonState (success);
}
void HeaderComponent::setRunAppButtonState (bool buildWasSuccessful)
{
bool shouldEnableButton = false;
if (buildWasSuccessful)
{
if (childProcess != nullptr)
{
if (childProcess->isAppRunning() || (! childProcess->isAppRunning() && childProcess->canLaunchApp()))
{
runAppButton->setTooltip ("Launch application");
shouldEnableButton = true;
}
else
{
runAppButton->setTooltip ("Application can't be launched");
}
}
else
{
runAppButton->setTooltip ("Enable live-build engine to launch application");
}
}
else
{
runAppButton->setTooltip ("Error building application");
}
runAppButton->setEnabled (shouldEnableButton);
}
| 31.69797 | 118 | 0.601409 | sukoi26 |
f3bc3d85cca6953aa2fdb72863e5fa5e0f7b49ae | 406 | cpp | C++ | 12/1252. Cells with Odd Values in a Matrix.cpp | eagleoflqj/LeetCode | ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9 | [
"MIT"
] | null | null | null | 12/1252. Cells with Odd Values in a Matrix.cpp | eagleoflqj/LeetCode | ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9 | [
"MIT"
] | 1 | 2021-12-25T10:33:23.000Z | 2022-02-16T00:34:05.000Z | 12/1252. Cells with Odd Values in a Matrix.cpp | eagleoflqj/LeetCode | ca5dd06cad4c7fe5bf679cca7ee60f4348b316e9 | [
"MIT"
] | null | null | null | class Solution {
public:
int oddCells(int n, int m, vector<vector<int>>& indices) {
vector<char> row(n), col(m);
for(auto &p : indices) {
row[p[0]] ^= 1;
col[p[1]] ^= 1;
}
int odd_row = count(row.begin(), row.end(), 1);
int odd_col = count(col.begin(), col.end(), 1);
return odd_row * m + (n - (odd_row << 1)) * odd_col;
}
};
| 29 | 62 | 0.480296 | eagleoflqj |
f3bd4cc65abe5ab8574c58d5683e5480c27636ee | 4,358 | hpp | C++ | modules/boost/simd/base/include/boost/simd/swar/functions/simd/sse/ssse3/lookup.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 34 | 2017-05-19T18:10:17.000Z | 2022-01-04T02:18:13.000Z | modules/boost/simd/base/include/boost/simd/swar/functions/simd/sse/ssse3/lookup.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | null | null | null | modules/boost/simd/base/include/boost/simd/swar/functions/simd/sse/ssse3/lookup.hpp | psiha/nt2 | 5e829807f6b57b339ca1be918a6b60a2507c54d0 | [
"BSL-1.0"
] | 7 | 2017-12-02T12:59:17.000Z | 2021-07-31T12:46:14.000Z | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef BOOST_SIMD_SWAR_FUNCTIONS_SIMD_SSE_SSSE3_LOOKUP_HPP_INCLUDED
#define BOOST_SIMD_SWAR_FUNCTIONS_SIMD_SSE_SSSE3_LOOKUP_HPP_INCLUDED
#ifdef BOOST_SIMD_HAS_SSSE3_SUPPORT
#include <boost/simd/swar/functions/lookup.hpp>
#include <boost/simd/include/functions/simd/shift_left.hpp>
#include <boost/simd/include/functions/simd/plus.hpp>
#include <boost/simd/include/functions/simd/make.hpp>
#include <boost/dispatch/attributes.hpp>
namespace boost { namespace simd { namespace ext
{
BOOST_DISPATCH_IMPLEMENT ( lookup_
, boost::simd::tag::ssse3_
, (A0)(A1)
, ((simd_<type8_<A0>,boost::simd::tag::sse_>))
((simd_<ints8_<A1>,boost::simd::tag::sse_>))
)
{
typedef A0 result_type;
BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)
{
return _mm_shuffle_epi8(a0, a1);
}
};
BOOST_DISPATCH_IMPLEMENT ( lookup_
, boost::simd::tag::ssse3_
, (A0)(A1)
, ((simd_<type16_<A0>,boost::simd::tag::sse_>))
((simd_<ints16_<A1>,boost::simd::tag::sse_>))
)
{
typedef A0 result_type;
BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)
{
typedef typename A0::template rebind<char>::type type8;
const type8 inc = make<type8>(0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1);
const type8 dup = make<type8>(0,0,2,2,4,4,6,6,8,8,10,10,12,12,14,14);
const type8 i1 = _mm_shuffle_epi8(shl(a1, 1), dup);
return _mm_shuffle_epi8(simd::bitwise_cast<type8>(a0),i1+inc);
}
};
BOOST_DISPATCH_IMPLEMENT ( lookup_
, boost::simd::tag::ssse3_
, (A0)(A1)
, ((simd_<type32_<A0>,boost::simd::tag::sse_>))
((simd_<ints32_<A1>,boost::simd::tag::sse_>))
)
{
typedef A0 result_type;
BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)
{
typedef typename A0::template rebind<char>::type type8;
const type8 inc = make<type8> ( 0, 1, 2, 3, 0, 1, 2, 3
, 0, 1, 2, 3, 0, 1, 2, 3
);
const type8 dup = make<type8> ( 0, 0, 0, 0, 4, 4, 4, 4
, 8, 8, 8, 8, 12, 12, 12, 12
);
type8 i1 = _mm_shuffle_epi8(shl(a1, 2), dup);
type8 r = _mm_shuffle_epi8(simd::bitwise_cast<type8>(a0), i1+inc );
return simd::bitwise_cast<A0>(r);
}
};
BOOST_DISPATCH_IMPLEMENT ( lookup_
, boost::simd::tag::ssse3_
, (A0)(A1)
, ((simd_<type64_<A0>,boost::simd::tag::sse_>))
((simd_<ints64_<A1>,boost::simd::tag::sse_>))
)
{
typedef A0 result_type;
BOOST_FORCEINLINE BOOST_SIMD_FUNCTOR_CALL(2)
{
typedef typename A0::template rebind<char>::type type8;
const type8 inc = make<type8> ( 0, 1, 2, 3, 4, 5, 6, 7
, 0, 1, 2, 3, 4, 5, 6, 7
);
const type8 dup = make<type8> ( 0, 0, 0, 0, 0, 0, 0, 0
, 8, 8, 8, 8, 8, 8, 8, 8
);
const type8 i1 = _mm_shuffle_epi8(shl(a1, 3), dup);
const type8 r = _mm_shuffle_epi8(simd::bitwise_cast<type8>(a0), i1+inc);
return simd::bitwise_cast<A0>(r);
}
};
} } }
#endif
#endif
| 37.568966 | 83 | 0.465351 | psiha |
f3bd882b23304c981cc8597b8a54a839997c3928 | 1,776 | cpp | C++ | src/OpenLoco/GameCommands/ChangeLoan.cpp | JimmyAllnighter/OpenLoco | dda8245be39a033db5cadfa455f1679a3f24ff24 | [
"MIT"
] | 180 | 2018-01-18T07:56:44.000Z | 2019-02-18T21:33:45.000Z | src/OpenLoco/GameCommands/ChangeLoan.cpp | JimmyAllnighter/OpenLoco | dda8245be39a033db5cadfa455f1679a3f24ff24 | [
"MIT"
] | 186 | 2018-01-18T13:17:58.000Z | 2019-02-10T12:28:35.000Z | src/OpenLoco/GameCommands/ChangeLoan.cpp | JimmyAllnighter/OpenLoco | dda8245be39a033db5cadfa455f1679a3f24ff24 | [
"MIT"
] | 35 | 2018-01-18T12:38:26.000Z | 2018-11-14T16:01:32.000Z | #include "../CompanyManager.h"
#include "../Economy/Economy.h"
#include "../Localisation/StringIds.h"
#include "../Ui/WindowManager.h"
#include "GameCommands.h"
using namespace OpenLoco::Interop;
namespace OpenLoco::GameCommands
{
// 0x0046DE88
static uint32_t changeLoan(const currency32_t newLoan, const uint8_t flags)
{
GameCommands::setExpenditureType(ExpenditureType::LoanInterest);
auto* company = CompanyManager::get(CompanyManager::getUpdatingCompanyId());
const currency32_t loanDifference = company->currentLoan - newLoan;
if (company->currentLoan > newLoan)
{
if (company->cash < loanDifference)
{
GameCommands::setErrorText(StringIds::not_enough_cash_available);
return FAILURE;
}
}
else
{
const auto maxLoan = Economy::getInflationAdjustedCost(CompanyManager::getMaxLoanSize(), 0, 8);
if (newLoan > maxLoan)
{
GameCommands::setErrorText(StringIds::bank_refuses_to_increase_loan);
return FAILURE;
}
}
if (flags & Flags::apply)
{
company->currentLoan = newLoan;
company->cash -= loanDifference;
Ui::WindowManager::invalidate(Ui::WindowType::company, static_cast<uint16_t>(CompanyManager::getUpdatingCompanyId()));
if (CompanyManager::getControllingId() == CompanyManager::getUpdatingCompanyId())
{
Ui::Windows::PlayerInfoPanel::invalidateFrame();
}
}
return 0;
}
void changeLoan(registers& regs)
{
ChangeLoanArgs args(regs);
regs.ebx = changeLoan(args.newLoan, regs.bl);
}
}
| 31.714286 | 130 | 0.608108 | JimmyAllnighter |
f3c03b0daea9ca0d5c3e8d5fbc08a11e39101eb5 | 1,046 | hpp | C++ | llog/loggable.hpp | Roslaniec/LLog | b75930e137a90f12fa9b5ade2b998e27d2da81ec | [
"MIT"
] | 2 | 2020-07-24T18:23:14.000Z | 2021-05-02T10:42:51.000Z | llog/loggable.hpp | Roslaniec/LLog | b75930e137a90f12fa9b5ade2b998e27d2da81ec | [
"MIT"
] | null | null | null | llog/loggable.hpp | Roslaniec/LLog | b75930e137a90f12fa9b5ade2b998e27d2da81ec | [
"MIT"
] | 2 | 2018-04-04T13:54:56.000Z | 2019-08-28T20:33:59.000Z | //
// Copyright (C) 2013 Karol Roslaniec <llog@roslaniec.net>
//
#ifndef LINKO_LOGGABLE_HPP
#define LINKO_LOGGABLE_HPP
#include "logger.hpp"
#include "loglevel.hpp"
/*
* Normally Log instances are created for each thread.
* Loggable/Logger classes create Log instance for a single object (module).
* Motivation for it was to allow per class/module log level definition,
* eg. you can anable Debug level for TFTP client module/class.
*
* IMPORTANT:
* Don't use it for short-living objects.
* Might be used for long-living objects.
*/
namespace linko {
class Log;
class Loggable
{
public:
Log &log(LogLevel l);
Log &logA();
Log &logE();
Log &logW();
Log &logI();
Log &logD();
Log &logP();
bool lvl(LogLevel l);
bool lvlW();
bool lvlI();
bool lvlD();
bool lvlP();
Logger logger() const { return _logger; }
protected:
Loggable(const Logger &logger) : _logger(logger) {}
private:
Logger _logger;
};
}
#endif
| 16.34375 | 76 | 0.623327 | Roslaniec |
f3c0531d6ea7fcb8eeb8ca82263e885c8b03a7f3 | 1,111 | cpp | C++ | core/runtime/binaryen/runtime_api/metadata_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/runtime_api/metadata_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | core/runtime/binaryen/runtime_api/metadata_impl.cpp | igor-egorov/kagome | b2a77061791aa7c1eea174246ddc02ef5be1b605 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Soramitsu Co., Ltd. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0
*/
#include "runtime/binaryen/runtime_api/metadata_impl.hpp"
namespace kagome::runtime::binaryen {
using primitives::OpaqueMetadata;
MetadataImpl::MetadataImpl(
const std::shared_ptr<RuntimeEnvironmentFactory> &runtime_env_factory,
std::shared_ptr<blockchain::BlockHeaderRepository> header_repo)
: RuntimeApi(runtime_env_factory), header_repo_(std::move(header_repo)) {
BOOST_ASSERT(header_repo_ != nullptr);
}
outcome::result<OpaqueMetadata> MetadataImpl::metadata(
const boost::optional<primitives::BlockHash> &block_hash) {
if (block_hash) {
OUTCOME_TRY(header, header_repo_->getBlockHeader(block_hash.value()));
return executeAt<OpaqueMetadata>(
"Metadata_metadata",
header.state_root,
CallConfig{.persistency = CallPersistency::EPHEMERAL});
}
return execute<OpaqueMetadata>(
"Metadata_metadata",
CallConfig{.persistency = CallPersistency::EPHEMERAL});
}
} // namespace kagome::runtime::binaryen
| 34.71875 | 79 | 0.718272 | igor-egorov |
f3c51551c8b30ae7dfe299ad87002fdbcc97fc3c | 3,196 | cpp | C++ | examples/lowlevel/benchmark_getifaddrs.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | 3 | 2020-02-13T02:08:06.000Z | 2020-10-06T16:26:30.000Z | examples/lowlevel/benchmark_getifaddrs.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | examples/lowlevel/benchmark_getifaddrs.cpp | hrissan/crablib | db86e5f52acddcc233aec755d5fce0e6f19c0e21 | [
"MIT"
] | null | null | null | // Copyright (c) 2007-2020, Grigory Buteyko aka Hrissan
// Licensed under the MIT License. See LICENSE for details.
// This code is based on work of https://gist.github.com/alessandro40/7e24df0a17803b71bbdf
// Answers the following question - will filling UDP buffer return EAGAIN from sendto (expected, allows 100% channel
// utilisation) Or will simply drop packets (would be disastrous for design)
// Turns out, on both Linux, behaviour is correct
// On Mac OSX, no EAGAIN returned, WireShark must be used to investigate dropped packets
// TODO - test on Windows
#if defined(_WIN32)
int main() { return 0; }
#else
#include <arpa/inet.h>
#include <errno.h>
#include <ifaddrs.h>
#include <net/if.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <chrono>
int get_once() {
struct ifaddrs *ifaddr, *ifa;
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
int result = 0; // Prevent optimizations
for (ifa = ifaddr; ifa != NULL; ifa = ifa->ifa_next) {
if (ifa->ifa_addr == NULL)
continue;
result += ifa->ifa_addr->sa_family;
}
freeifaddrs(ifaddr);
return result;
}
int main() {
// Listen to interface changes on Linux
// https://github.com/angt/ipevent/blob/e0a4c4dfe8ac193345315d55f320ab212dbda784/ipevent.c
// Multicast with IPv6
// https://linux.die.net/man/3/if_nametoindex
// https://stackoverflow.com/questions/53309453/sending-packet-to-interface-via-multicast?noredirect=1&lq=1
struct ifaddrs *ifaddr, *ifa;
int family, s, n;
char host[NI_MAXHOST];
if (getifaddrs(&ifaddr) == -1) {
perror("getifaddrs");
exit(EXIT_FAILURE);
}
/* Walk through linked list, maintaining head pointer so we
can free list later */
printf("%-12s %-8s family\n", "name", "idx");
for (ifa = ifaddr, n = 0; ifa != NULL; ifa = ifa->ifa_next, n++) {
if (ifa->ifa_addr == NULL)
continue;
family = ifa->ifa_addr->sa_family;
/* Display interface name and family (including symbolic
form of the latter for the common families) */
unsigned idx = if_nametoindex(ifa->ifa_name);
printf("%-12s %-8u %s (%d)\n", ifa->ifa_name, idx,
(family == AF_INET) ? "AF_INET" : (family == AF_INET6) ? "AF_INET6" : "???", family);
/* For an AF_INET* interface address, display the address */
if (family == AF_INET || family == AF_INET6) {
s = getnameinfo(ifa->ifa_addr,
(family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), host, NI_MAXHOST,
NULL, 0, NI_NUMERICHOST);
if (s != 0) {
printf("getnameinfo() failed: %s\n", gai_strerror(s));
exit(EXIT_FAILURE);
}
printf("\t\taddress: <%s>\n", host);
}
}
freeifaddrs(ifaddr);
const size_t MAX_COUNT = 10000;
printf("Benchmarking %d counts\n", int(MAX_COUNT));
auto start = std::chrono::steady_clock::now();
int result = 0;
for (size_t i = 0; i != MAX_COUNT; ++i)
result += get_once();
auto now = std::chrono::steady_clock::now();
printf("Result %f microseconds per call\n",
float(std::chrono::duration_cast<std::chrono::microseconds>(now - start).count()) / MAX_COUNT);
return result;
}
#endif | 29.321101 | 116 | 0.679599 | hrissan |
f3cdb83991c26672aeb097a3c65d862867469b00 | 1,306 | cpp | C++ | Source/KEngine/src/KEngine/Entity/Entity.cpp | yxbh/KEngine | 04d2aced738984f53bf1b2b84b49fbbabfbe6587 | [
"Zlib"
] | 1 | 2020-05-29T03:30:08.000Z | 2020-05-29T03:30:08.000Z | Source/KEngine/src/KEngine/Entity/Entity.cpp | yxbh/KEngine | 04d2aced738984f53bf1b2b84b49fbbabfbe6587 | [
"Zlib"
] | null | null | null | Source/KEngine/src/KEngine/Entity/Entity.cpp | yxbh/KEngine | 04d2aced738984f53bf1b2b84b49fbbabfbe6587 | [
"Zlib"
] | null | null | null | #include <KEngine/Entity/Entity.hpp>
#include <KEngine/Entity/EntityComponentID.hpp>
#include <KEngine/Entity/IEntityComponent.hpp>
#include <cassert>
namespace ke
{
Entity::Entity(const ke::EntityID p_ID)
: m_EntityID(p_ID)
{}
Entity::Entity(ke::Entity && p_rrEntity)
: m_ComponentSPMap(std::move(p_rrEntity.m_ComponentSPMap))
, m_EntityID(std::move(p_rrEntity.getId()))
, m_EntityType(std::move(p_rrEntity.getType()))
{}
Entity & Entity::operator=(ke::Entity && p_rrEntity)
{
m_ComponentSPMap = std::move(p_rrEntity.m_ComponentSPMap);
m_EntityID = std::move(p_rrEntity.getId());
m_EntityType = std::move(p_rrEntity.getType());
return *this;
}
Entity::~Entity(void)
{
assert(m_ComponentSPMap.empty());
}
void Entity::addComponent(ke::EntityComponentSptr p_spEntityComponent)
{
assert(p_spEntityComponent != nullptr); // should not be null.
assert(p_spEntityComponent->getId() != ke::Invalid_EntityComponentID); //
const auto result = m_ComponentSPMap.insert(std::make_pair(p_spEntityComponent->getId(), p_spEntityComponent));
assert(result.second); // fails if insertion failed.
}
void Entity::updateAll(const ke::Time p_ElapsedTime)
{
for (auto & it : m_ComponentSPMap) it.second->update(p_ElapsedTime);
}
} // KE ns
| 27.208333 | 115 | 0.712098 | yxbh |
f3d138a0c233bb7ae6d56da60ceeb78fcfaa0298 | 896 | hpp | C++ | libs/scenic/include/sge/scenic/render_context/manager_base.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/scenic/include/sge/scenic/render_context/manager_base.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/scenic/include/sge/scenic/render_context/manager_base.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_SCENIC_RENDER_CONTEXT_MANAGER_BASE_HPP_INCLUDED
#define SGE_SCENIC_RENDER_CONTEXT_MANAGER_BASE_HPP_INCLUDED
#include <sge/core/detail/class_symbol.hpp>
#include <sge/renderer/context/core_ref.hpp>
#include <sge/scenic/detail/symbol.hpp>
#include <sge/scenic/render_context/base_unique_ptr.hpp>
#include <fcppt/nonmovable.hpp>
namespace sge::scenic::render_context
{
class SGE_CORE_DETAIL_CLASS_SYMBOL manager_base
{
FCPPT_NONMOVABLE(manager_base);
public:
[[nodiscard]] virtual sge::scenic::render_context::base_unique_ptr
create_context(sge::renderer::context::core_ref) = 0;
virtual ~manager_base();
protected:
manager_base();
};
}
#endif
| 25.6 | 68 | 0.768973 | cpreh |
f3d5e5c9725dab8afe3bcbcae2d3126cb8eb97af | 258 | cpp | C++ | src/Networking/log.cpp | jonahbardos/PY2020 | af4f61b86ae5013e58faf4842bf20863b3de3957 | [
"Apache-2.0"
] | null | null | null | src/Networking/log.cpp | jonahbardos/PY2020 | af4f61b86ae5013e58faf4842bf20863b3de3957 | [
"Apache-2.0"
] | null | null | null | src/Networking/log.cpp | jonahbardos/PY2020 | af4f61b86ae5013e58faf4842bf20863b3de3957 | [
"Apache-2.0"
] | null | null | null |
#include "log.h"
#include <iostream>
int LOG_LEVEL = LOG_INFO;
int LOG_DEBUG = 0;
int LOG_INFO = 1;
int LOG_WARN = 2;
int LOG_ERROR = 3;
void log(int level, std::string const &msg)
{
if (level >= LOG_LEVEL)
{
std::cout << msg << std::endl;
}
}
| 13.578947 | 43 | 0.624031 | jonahbardos |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.