hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 108 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 67k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
03b7ea5a8fac86854d23be6a42d2ca35a016276e | 9,127 | cpp | C++ | Plugin/Popup.cpp | wuzijing111/EU4dll | 5bc107bb7c1f90296bddc1e8643b89f3a7283ef9 | [
"MIT"
] | 483 | 2018-08-17T12:44:22.000Z | 2022-03-30T16:49:44.000Z | Plugin/Popup.cpp | Dawn-of-Higaara/EU4dll | c516f00bf729dc2c95cccedb65508c05283e1268 | [
"MIT"
] | 111 | 2018-08-24T18:43:15.000Z | 2022-03-07T11:20:10.000Z | Plugin/Popup.cpp | hangingman/EU4dll | e0d2e15eaa10b4642f4f76474c678044acbc9cdd | [
"MIT"
] | 95 | 2018-09-17T07:56:04.000Z | 2022-03-19T04:56:27.000Z | #include "stdinc.h"
#include "byte_pattern.h"
// これはpopup windowではなくて、map上で浮かび上がる文字の部分の修正
namespace PopupCharOnMap {
/*-----------------------------------------------*/
uintptr_t func1_v125_end;
__declspec(naked) void func1_v125_start()
{
__asm {
mov eax, [eax + edi];
mov[ebp - 0x5C], eax;
lea ecx, [ebp - 0xAC];
push func1_v125_end;
ret;
}
}
uintptr_t func2_v125_end;
__declspec(naked) void func2_v125_start()
{
__asm {
cmp byte ptr[eax], ESCAPE_SEQ_1;
jz x_4;
cmp byte ptr[eax], ESCAPE_SEQ_2;
jz x_4;
cmp byte ptr[eax], ESCAPE_SEQ_3;
jz x_4;
cmp byte ptr[eax], ESCAPE_SEQ_4;
jz x_4;
jmp x_3;
x_4:
mov ecx, [ebp - 0x5C];
mov[eax], ecx;
lea ecx, [eax];
mov byte ptr[ecx + 0x10], 3;
x_3:
push 0xFFFFFFFF;
push 0;
push eax;
push func2_v125_end;
ret;
}
}
uintptr_t func1_v127_end;
__declspec(naked) void func1_v127_start()
{
__asm {
mov eax, [eax + edi];
mov[ebp - 0x28], eax;
lea ecx, [ebp - 0xD8];
push func1_v127_end;
ret;
}
}
uintptr_t func2_v127_end;
__declspec(naked) void func2_v127_start()
{
__asm {
cmp byte ptr[eax], ESCAPE_SEQ_1;
jz x_4;
cmp byte ptr[eax], ESCAPE_SEQ_2;
jz x_4;
cmp byte ptr[eax], ESCAPE_SEQ_3;
jz x_4;
cmp byte ptr[eax], ESCAPE_SEQ_4;
jz x_4;
jmp x_3;
x_4:
mov ecx, [ebp - 0x28];
mov[eax], ecx;
lea ecx, [eax];
mov byte ptr[ecx + 0x10], 3;
x_3:
push 0xFFFFFFFF;
push 0;
push eax;
push func2_v127_end;
ret;
}
}
/*-----------------------------------------------*/
errno_t func1_2_hook(EU4Version version) {
std::string desc = "func1,2";
switch (version) {
case v1_28_3:
case v1_28_X:
case v1_27_X:
byte_pattern::temp_instance().find_pattern("8A 04 38 8D 8D 28 FF FF FF 88 45 D8");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// mov al,[eax+edi]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), func1_v127_start);
// push [ebp+var_28]
func1_v127_end = byte_pattern::temp_instance().get_first().address(0xC);
// push 0FFFFFFFFh
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(0x14), func2_v127_start);
// lea ecx,[ebp+var_AC]
func2_v127_end = byte_pattern::temp_instance().get_first().address(0x19);
}
else return EU4_ERROR1;
return NOERROR;
case v1_25_X:
case v1_26_X:
byte_pattern::temp_instance().find_pattern("8A 04 38 8D 8D 54");
if (byte_pattern::temp_instance().has_size(2, desc)) {
// mov al,[eax+edi]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), func1_v125_start);
// push [ebp+var_5C]
func1_v125_end = byte_pattern::temp_instance().get_first().address(0xC);
// push 0FFFFFFFFh
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(0x14), func2_v125_start);
// lea ecx,[ebp+var_7C]
func2_v125_end = byte_pattern::temp_instance().get_first().address(0x19);
}
else return EU4_ERROR1;
return NOERROR;
}
return EU4_ERROR1;
}
/*-----------------------------------------------*/
uintptr_t func3_v125_end;
__declspec(naked) void func3_v125_start()
{
__asm {
cmp byte ptr[eax + edi], ESCAPE_SEQ_1;
jz y_10;
cmp byte ptr[eax + edi], ESCAPE_SEQ_2;
jz y_11;
cmp byte ptr[eax + edi], ESCAPE_SEQ_3;
jz y_12;
cmp byte ptr[eax + edi], ESCAPE_SEQ_4;
jz y_13;
jmp y_7;
y_10:
movzx eax, word ptr[eax + edi + 1];
jmp y_1x;
y_11:
movzx eax, word ptr[eax + edi + 1];
sub eax, SHIFT_2;
jmp y_1x;
y_12:
movzx eax, word ptr[eax + edi + 1];
add eax, SHIFT_3;
jmp y_1x;
y_13:
movzx eax, word ptr[eax + edi + 1];
add eax, SHIFT_4;
y_1x:
movzx eax, ax;
cmp eax, NO_FONT;
ja y_4;
mov eax, NOT_DEF;
y_4:
add edi, 2;
jmp y_6;
y_7:
mov al, [eax + edi];
movzx eax, al;
y_6:
push func3_v125_end;
ret;
}
}
uintptr_t func3_v127_end;
__declspec(naked) void func3_v127_start()
{
__asm {
cmp byte ptr[eax + edi], ESCAPE_SEQ_1;
jz y_10;
cmp byte ptr[eax + edi], ESCAPE_SEQ_2;
jz y_11;
cmp byte ptr[eax + edi], ESCAPE_SEQ_3;
jz y_12;
cmp byte ptr[eax + edi], ESCAPE_SEQ_4;
jz y_13;
jmp y_7;
y_10:
movzx eax, word ptr[eax + edi + 1];
jmp y_1x;
y_11:
movzx eax, word ptr[eax + edi + 1];
sub eax, SHIFT_2;
jmp y_1x;
y_12:
movzx eax, word ptr[eax + edi + 1];
add eax, SHIFT_3;
jmp y_1x;
y_13:
movzx eax, word ptr[eax + edi + 1];
add eax, SHIFT_4;
y_1x:
movzx eax, ax;
cmp eax, NO_FONT;
ja y_4;
mov eax, NOT_DEF;
y_4:
add edi, 2;
jmp y_6;
y_7:
mov al, [eax + edi];
movzx eax, al;
y_6:
mov ecx, [ebp - 0x10];
add ecx, 0xB4;
mov[ebp - 0x20], ecx;
push func3_v127_end;
ret;
}
}
/*-----------------------------------------------*/
errno_t func3_hook(EU4Version version) {
std::string desc = "func 3";
switch (version) {
case v1_28_3:
case v1_28_X:
case v1_27_X:
byte_pattern::temp_instance().find_pattern("8A 04 38 8B 4D F0");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// mov al, [eax+edi]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), func3_v127_start);
// mov ecx, [ecx+eax*4]
func3_v127_end = byte_pattern::temp_instance().get_first().address(0x12);
}
else return EU4_ERROR1;
return NOERROR;
case v1_25_X:
case v1_26_X:
byte_pattern::temp_instance().find_pattern("8A 04 38 0F B6");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// mov al, [eax+edi]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), func3_v125_start);
// mov edx, [ebx+eax*4+0xB4]
func3_v125_end = byte_pattern::temp_instance().get_first().address(0x6);
}
else return EU4_ERROR1;
return NOERROR;
}
return EU4_ERROR1;
}
/*-----------------------------------------------*/
uintptr_t func4_v125_end;
__declspec(naked) void func4_v125_start()
{
__asm {
cmp byte ptr[eax + esi], ESCAPE_SEQ_1;
jz z_10;
cmp byte ptr[eax + esi], ESCAPE_SEQ_2;
jz z_11;
cmp byte ptr[eax + esi], ESCAPE_SEQ_3;
jz z_12;
cmp byte ptr[eax + esi], ESCAPE_SEQ_4;
jz z_13;
jmp z_5;
z_10:
movzx eax, word ptr[eax + esi + 1];
jmp z_1x;
z_11:
movzx eax, word ptr[eax + esi + 1];
sub eax, SHIFT_2;
jmp z_1x;
z_12:
movzx eax, word ptr[eax + esi + 1];
add eax, SHIFT_3;
jmp z_1x;
z_13:
movzx eax, word ptr[eax + esi + 1];
add eax, SHIFT_4;
z_1x:
movzx eax, ax;
cmp eax, NO_FONT;
ja z_4;
mov eax, NOT_DEF;
z_4:
add esi, 2;
z_6:
mov edx, [edx + eax * 4];
push func4_v125_end;
ret;
z_5:
movzx eax, byte ptr[eax + esi];
jmp z_6;
}
}
uintptr_t func4_v127_end;
__declspec(naked) void func4_v127_start()
{
__asm {
cmp byte ptr[eax + esi], ESCAPE_SEQ_1;
jz z_10;
cmp byte ptr[eax + esi], ESCAPE_SEQ_2;
jz z_11;
cmp byte ptr[eax + esi], ESCAPE_SEQ_3;
jz z_12;
cmp byte ptr[eax + esi], ESCAPE_SEQ_4;
jz z_13;
movzx eax, byte ptr[eax + esi];
jmp z_6;
z_10:
movzx eax, word ptr[eax + esi + 1];
jmp z_1x;
z_11:
movzx eax, word ptr[eax + esi + 1];
sub eax, SHIFT_2;
jmp z_1x;
z_12:
movzx eax, word ptr[eax + esi + 1];
add eax, SHIFT_3;
jmp z_1x;
z_13:
movzx eax, word ptr[eax + esi + 1];
add eax, SHIFT_4;
z_1x:
movzx eax, ax;
cmp eax, NO_FONT;
ja z_4;
mov eax, NOT_DEF;
z_4:
add esi, 2;
mov dword ptr[ebp - 0x2C], esi; // ローカル変数更新
z_6:
movss [ebp - 0xBC], xmm4;
mov eax, [ecx + eax * 4 + 0xB4];
push func4_v127_end;
ret;
}
}
/*-----------------------------------------------*/
errno_t func4_hook(EU4Version version) {
std::string desc = "func 4";
switch (version) {
case v1_28_3:
case v1_28_X:
case v1_27_X:
byte_pattern::temp_instance().find_pattern("0F B6 04 30 F3 0F 11 A5 44 FF FF FF");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// movzx eax, byte ptr [eax+esi]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), func4_v127_start);
// mov [ebp+var_20],eax
func4_v127_end = byte_pattern::temp_instance().get_first().address(0x13);
}
else return EU4_ERROR1;
return NOERROR;
case v1_25_X:
case v1_26_X:
byte_pattern::temp_instance().find_pattern("0F B6 04 30 8B 14 82 89 55");
if (byte_pattern::temp_instance().has_size(1, desc)) {
// movzx eax, byte ptr [eax+esi]
injector::MakeJMP(byte_pattern::temp_instance().get_first().address(), func4_v125_start);
// mov [ebp+var_34],edx
func4_v125_end = byte_pattern::temp_instance().get_first().address(0x7);
}
else return EU4_ERROR1;
return NOERROR;
}
return EU4_ERROR1;
}
/*-----------------------------------------------*/
errno_t init(EU4Version version) {
errno_t result = 0;
byte_pattern::temp_instance().debug_output2("popup char on map fix");
//
result |= func1_2_hook(version);
//
result |= func3_hook(version);
//
result |= func4_hook(version);
return result;
}
} | 20.743182 | 97 | 0.610058 | wuzijing111 |
03c2ca34dc47f33f8f85ec761d45823555fa989f | 1,146 | cpp | C++ | stage0/src/runtime/exception.cpp | JLimperg/lean4 | 24fe2875c68549b5481f07c57eab4ad4a0ae5305 | [
"Apache-2.0"
] | 1 | 2021-07-19T04:47:46.000Z | 2021-07-19T04:47:46.000Z | stage0/src/runtime/exception.cpp | JLimperg/lean4 | 24fe2875c68549b5481f07c57eab4ad4a0ae5305 | [
"Apache-2.0"
] | 12 | 2020-12-18T21:11:28.000Z | 2020-12-19T17:38:22.000Z | stage0/src/runtime/exception.cpp | JLimperg/lean4 | 24fe2875c68549b5481f07c57eab4ad4a0ae5305 | [
"Apache-2.0"
] | 1 | 2021-04-23T09:35:46.000Z | 2021-04-23T09:35:46.000Z | /*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <string>
#include <sstream>
#include <lean/exception.h>
#include <lean/thread.h>
#include <lean/sstream.h>
namespace lean {
throwable::throwable(char const * msg):m_msg(msg) {}
throwable::throwable(std::string const & msg):m_msg(msg) {}
throwable::throwable(sstream const & strm):m_msg(strm.str()) {}
throwable::~throwable() noexcept {}
char const * throwable::what() const noexcept { return m_msg.c_str(); }
stack_space_exception::stack_space_exception(char const * component_name):
m_msg((sstream() << "deep recursion was detected at '" << component_name << "' (potential solution: increase stack space in your system)").str()) {
}
memory_exception::memory_exception(char const * component_name):
m_msg((sstream() << "excessive memory consumption detected at '" << component_name << "' (potential solution: increase memory consumption threshold)").str()) {
}
char const * heartbeat_exception::what() const noexcept {
return "(deterministic) timeout";
}
}
| 35.8125 | 163 | 0.731239 | JLimperg |
03c308a2ae4955c3931c71645b6f26a01e8d3f0f | 1,399 | cpp | C++ | UVA/vol-105/10582.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | 3 | 2017-05-12T14:45:37.000Z | 2020-01-18T16:51:25.000Z | UVA/vol-105/10582.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | UVA/vol-105/10582.cpp | arash16/prays | 0fe6bb2fa008b8fc46c80b01729f68308114020d | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
#define TOP 0
#define RIGHT 1
#define BOTTOM 2
#define LEFT 3
int di[] = { -1, 0, 1, 0 },
dj[] = { 0, 1, 0, -1 };
int M[77][77], r, c;
int dfs(int i, int j, int dir) {
if (i<0 || i>=r || j<0 || j>=c || !M[i][j]) return 0;
if (i==r-1 && j==c-1) return 1;
int o = M[i][j];
M[i][j] = 0;
int r = 0;
if (o == 1)
r += dfs(i-di[dir], j-dj[dir], dir);
else if (dir==TOP || dir==BOTTOM) {
r += dfs(i+di[LEFT], j+dj[LEFT], RIGHT);
r += dfs(i+di[RIGHT], j+dj[RIGHT], LEFT);
}
else if (dir==LEFT || dir==RIGHT) {
r += dfs(i+di[TOP], j+dj[TOP], BOTTOM);
r += dfs(i+di[BOTTOM], j+dj[BOTTOM], TOP);
}
M[i][j] = o;
return r;
}
int main() {
ios_base::sync_with_stdio(0);cin.tie(0);
int T;
cin >> T;
char S[3][512];
while (T-- && cin >> r >> c) {
cin.ignore(512, '\n');
for (int i=0; i<r; ++i) {
cin.ignore(512, '\n');
for (int j=0; j<3; ++j)
cin.getline(S[j], 512);
for (int j=0; j<c; ++j) {
int o = j<<2;
M[i][j] = (S[1][o+2]==' ') ? 0 : (S[0][o+2]==S[2][o+2] || S[1][o+1]==S[1][o+3]) ? 1 : 2;
}
}
cin.ignore(512, '\n');
cout << "Number of solutions: " << (dfs(0, 0, TOP)+dfs(0, 0, LEFT)) << '\n';
}
}
| 22.564516 | 104 | 0.406719 | arash16 |
03c5d75fa61abc9e9dc540d7b58122aa7821a8ee | 6,653 | cc | C++ | build/ARM/cpu/TimingExpr.py.cc | msharmavikram/gem5_experiments | 87353d28df55b9a6a5be6cbb19bce87a500ab3b4 | [
"BSD-3-Clause"
] | null | null | null | build/ARM/cpu/TimingExpr.py.cc | msharmavikram/gem5_experiments | 87353d28df55b9a6a5be6cbb19bce87a500ab3b4 | [
"BSD-3-Clause"
] | null | null | null | build/ARM/cpu/TimingExpr.py.cc | msharmavikram/gem5_experiments | 87353d28df55b9a6a5be6cbb19bce87a500ab3b4 | [
"BSD-3-Clause"
] | null | null | null | #include "sim/init.hh"
namespace {
const uint8_t data_m5_objects_TimingExpr[] = {
120,156,181,152,221,115,219,68,16,192,79,242,71,108,231,203,
77,93,55,180,3,213,19,227,97,166,117,27,146,240,213,233,
208,164,1,194,132,54,35,39,48,132,7,143,44,157,109,181,
150,100,116,167,52,97,250,86,102,120,228,133,87,158,120,229,
127,132,221,149,37,75,182,147,54,173,149,68,23,221,234,180,
218,219,253,105,239,86,38,27,253,228,224,248,90,99,76,84,
21,198,44,248,83,216,128,177,35,60,83,217,64,97,142,202,
78,84,166,88,57,198,85,214,85,152,149,103,191,51,246,154,
177,159,79,114,204,42,48,158,35,105,49,150,230,153,181,192,
120,158,164,165,88,90,96,86,57,26,91,137,165,69,102,45,
70,210,165,88,186,192,172,229,72,186,18,75,75,204,90,141,
164,213,88,90,102,214,53,198,43,36,93,139,165,139,204,186,
30,141,173,197,210,37,102,221,136,164,245,88,186,204,172,155,
145,116,61,150,174,48,235,3,214,106,220,2,239,216,255,193,
79,3,188,195,36,54,159,132,167,101,104,90,182,243,172,243,
156,155,82,86,160,119,100,59,182,219,219,59,27,250,102,228,
92,28,185,131,206,69,61,156,177,19,5,93,12,254,4,47,
131,251,192,75,224,24,189,213,80,225,178,142,141,88,131,198,
28,6,77,73,202,218,28,180,221,235,247,27,69,124,100,9,
154,118,219,53,28,222,110,211,19,219,109,199,179,130,1,118,
243,56,224,124,200,73,110,158,157,181,251,220,176,184,79,242,
35,63,224,116,179,209,17,210,55,76,217,64,219,198,141,120,
4,77,179,239,57,188,121,42,156,141,166,233,5,190,224,47,
61,255,69,115,111,119,111,235,193,131,102,143,59,91,109,199,
16,146,251,77,225,155,77,180,112,60,221,123,195,115,50,254,
62,234,66,75,139,10,254,202,107,41,167,28,216,112,183,49,
136,125,163,70,190,217,152,233,27,160,15,80,226,5,246,28,
32,201,177,215,32,92,24,193,7,40,128,207,10,248,180,15,
161,25,41,214,182,55,181,142,45,181,192,21,118,207,229,150,
118,106,12,2,174,151,47,246,170,88,6,241,96,116,55,141,
54,213,145,97,120,236,162,113,56,228,149,194,94,129,179,25,
182,45,138,254,211,144,1,52,129,238,163,0,146,175,5,31,
116,245,202,188,221,75,81,21,92,182,135,134,111,56,226,33,
246,242,4,88,89,105,224,12,117,124,141,117,130,96,129,192,
176,60,179,221,214,209,64,189,24,153,122,136,55,75,236,30,
239,187,114,123,147,236,212,151,82,198,206,13,8,180,106,11,
117,85,98,32,138,234,170,42,23,83,80,220,159,126,85,106,
51,113,24,189,36,2,173,221,245,220,83,238,218,220,149,218,
125,155,140,206,167,92,160,99,208,38,130,48,183,121,85,49,
95,70,254,39,204,171,169,25,181,124,83,231,189,249,82,142,
126,252,198,118,45,77,246,185,38,192,104,147,107,62,239,217,
104,166,230,6,78,7,254,117,125,207,161,235,102,224,251,232,
26,219,21,82,191,118,9,253,235,32,6,165,252,12,134,74,
143,198,107,48,103,212,44,222,225,69,32,85,97,38,195,24,
235,107,115,119,61,198,254,224,18,244,195,184,199,204,235,43,
108,148,52,143,71,41,129,108,202,10,120,116,245,147,9,224,
115,0,124,45,133,135,14,105,25,94,190,185,35,242,17,206,
12,116,107,134,171,25,190,217,135,172,102,202,0,19,91,4,
138,94,187,132,5,92,159,98,162,124,227,165,22,130,1,88,
248,160,244,138,52,228,66,101,9,22,110,100,194,194,79,87,
100,129,22,41,178,37,43,6,208,197,135,108,58,233,45,167,
24,56,224,114,58,248,143,223,62,248,188,68,221,60,117,203,
184,9,67,22,42,200,2,206,85,224,12,119,6,158,249,66,
243,186,154,197,205,1,228,125,105,123,174,208,235,111,72,7,
120,206,133,192,177,90,215,243,97,61,117,45,24,35,196,42,
92,236,120,214,185,54,30,97,162,175,115,73,40,234,41,40,
84,58,81,146,116,168,81,174,176,120,23,178,77,126,244,196,
70,46,6,229,38,54,235,153,208,130,46,167,221,9,210,2,
188,44,94,198,11,45,83,63,194,43,228,249,180,106,134,232,
220,140,73,90,207,16,34,116,227,47,108,180,214,197,16,41,
83,24,233,188,59,223,28,114,7,231,140,219,25,228,198,208,
58,94,0,75,142,8,58,119,199,65,215,111,93,66,80,53,
69,80,152,66,174,150,58,194,69,35,235,53,196,187,106,222,
184,30,217,146,85,200,209,171,253,25,121,99,41,21,240,103,
195,56,222,181,40,222,223,39,227,13,193,134,72,67,128,33,
180,144,21,160,40,131,82,12,138,48,40,189,160,232,130,82,
11,138,44,40,173,160,168,130,82,10,138,40,40,157,160,104,
130,82,169,87,67,86,128,3,212,75,152,201,248,169,143,45,
107,66,210,10,58,114,37,37,57,254,33,24,76,138,158,216,
167,19,162,214,244,168,22,142,90,75,223,184,203,237,1,138,
87,83,226,189,95,3,99,48,49,244,169,39,67,241,245,180,
134,3,32,240,168,111,184,178,158,150,127,11,139,25,4,129,
46,165,111,105,93,112,75,43,121,75,53,117,105,31,54,161,
190,156,112,13,88,52,233,62,215,162,48,142,37,207,124,218,
19,36,30,98,255,198,247,221,29,91,10,121,107,226,66,207,
221,59,147,220,181,62,221,56,242,182,55,39,85,119,68,152,
58,199,155,127,108,160,34,17,25,48,122,27,245,224,161,33,
163,106,72,105,142,142,233,223,9,114,143,221,247,91,240,160,
91,186,100,193,67,166,142,93,195,63,215,188,33,20,115,144,
180,245,7,23,231,41,218,18,70,3,169,178,122,255,69,77,
37,149,180,243,49,252,94,98,65,219,196,102,43,147,52,246,
39,187,194,130,22,38,178,219,177,73,106,100,87,86,41,13,
3,240,7,123,243,42,182,99,207,96,227,240,157,217,24,117,
11,212,173,140,190,75,157,44,34,42,88,24,211,70,6,30,
153,98,101,251,98,86,244,141,136,175,131,239,90,137,205,15,
137,244,148,200,68,175,231,147,232,220,153,141,78,142,78,212,
36,67,185,40,46,244,2,15,120,87,210,54,201,183,123,125,
25,22,183,99,152,62,195,230,243,76,136,250,27,117,149,98,
162,128,169,165,43,51,21,155,151,21,88,24,173,191,162,168,
36,192,82,166,214,203,253,25,251,163,43,146,21,111,179,75,
81,183,16,37,161,226,56,9,17,89,184,235,222,239,222,133,
18,220,189,203,7,130,143,249,250,226,98,190,232,107,135,233,
193,46,27,55,232,73,192,104,245,243,97,47,150,144,225,2,
212,53,80,247,252,176,35,226,208,2,74,139,248,68,116,29,
125,222,164,71,97,47,129,224,151,216,124,133,205,195,76,16,
252,119,10,193,183,72,107,234,180,101,89,209,135,177,252,103,
54,125,79,27,20,51,244,156,179,117,47,252,82,71,68,66,
47,254,82,172,43,177,193,180,241,196,144,210,167,3,170,29,
105,239,79,187,65,10,203,158,27,56,225,251,133,217,148,200,
39,3,230,63,47,10,254,195,240,107,242,163,143,81,39,86,
56,21,165,90,174,23,234,139,245,124,125,9,218,101,56,106,
208,174,254,15,45,107,21,22,
};
EmbeddedPython embedded_m5_objects_TimingExpr(
"m5/objects/TimingExpr.py",
"/home/vsm2/coursework/ECE511/gem5_master/src/cpu/TimingExpr.py",
"m5.objects.TimingExpr",
data_m5_objects_TimingExpr,
1624,
6205);
} // anonymous namespace
| 55.907563 | 69 | 0.665264 | msharmavikram |
03c7850465d7a16defa548b1eb42750238879a4b | 30,853 | cpp | C++ | src/SDIMCompiler/Parser.cpp | DamienHenderson/SDIM | 623ac00402a68a504451c3b7c76cd16fde2fa57e | [
"MIT"
] | null | null | null | src/SDIMCompiler/Parser.cpp | DamienHenderson/SDIM | 623ac00402a68a504451c3b7c76cd16fde2fa57e | [
"MIT"
] | null | null | null | src/SDIMCompiler/Parser.cpp | DamienHenderson/SDIM | 623ac00402a68a504451c3b7c76cd16fde2fa57e | [
"MIT"
] | null | null | null | #include "Parser.hpp"
#include <Utils.hpp>
#include <random>
#include <unordered_map>
#include "BytecodeGenerator.hpp"
namespace SDIM
{
Token GetToken(const std::vector<Token>& tokens, size_t idx)
{
if (idx >= tokens.size())
{
Utils::Log("Attempted to read past end of tokens");
return Token(TokenType::Unknown, "");
}
return tokens[idx];
}
Parser::Parser()
{
rng_ = std::make_unique<std::default_random_engine>((std::random_device())());
}
Parser::~Parser()
{
}
bool Parser::Parse(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
#ifdef SDIM_VERBOSE
// for (const auto& token : tokens )
// {
// Utils::Log(token.ToString());
// }
#endif
// Utilises pratt parsing
// inspired by this webpage http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
// also inspired by this webpage http://craftinginterpreters.com/compiling-expressions.html
// also inspired by other sources
current_token = 0;
bool res = ParseModuleDeclaration(tokens, program_data, generator);
generator->WriteHaltInstruction(program_data);
return res;
}
bool Parser::ParseModuleDeclaration(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
Token expect_module_token = GetToken(tokens, current_token++);
if (!MatchToken(expect_module_token, TokenType::Module))
{
Error(expect_module_token, "Expected module keyword");
return false;
}
// module so the following token should be an identifier
Token expect_module_name_token = GetToken(tokens, current_token++);
if (MatchToken(expect_module_name_token, TokenType::Identifier))
{
Token expect_left_brace = GetToken(tokens, current_token++);
if (MatchToken(expect_left_brace, TokenType::LeftBrace))
{
// brackets_.push(expect_left_brace.token_type);
// correctly formed module statement
// scopes_.push_back(ScopingBlock(expect_module_name_token.lexeme));
// TODO: handle modules correctly
Utils::Log("Found module: ", expect_module_name_token.lexeme);
OpenScope();
// TODO: ParseTopLevelScope Function
// Top level scopes should only contain functions
while (ParseFunctionDeclaration(tokens, program_data, generator))
{
}
--current_token;
CloseScope();
return ConsumeToken(tokens, TokenType::RightBrace, "Expected } before EOF token");
}
else
{
Error(expect_module_name_token, "Expected { to open scoping block for module");
return false;
}
}
else
{
// Module names must be an identifier
Error(expect_module_name_token, "Expected module name");
return false;
}
}
bool Parser::ParseExpression(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
bool res = ParsePrecedence(tokens, program_data, generator, Precedence::Assignment);
if (!res)
{
return false;
}
return true;
// return ConsumeToken(tokens, TokenType::SemiColon, "Expected ;");
/*
#ifdef SDIM_VERBOSE
for (const auto& it : scopes_)
{
// newlines between scopes
Utils::Log("");
it.PrintScope();
}
#endif
Utils::Log("");
if (GetToken(tokens, .empty())
{
Utils::Log("No GetToken(tokens, found in compilation input");
return false;
}
if (current_token >= GetToken(tokens, .size())
{
Utils::Log("Reached end of GetToken(tokens, ");
return true;
}
Token next_token = GetToken(tokens, [current_token];
Utils::Log("Parsing token ", next_token.ToString());
// TODO: move all of these into functions to make this tidier
if (next_token.token_type == TokenType::NumericLiteral)
{
bool res = ParseNumericLiteral(tokens, program_data, generator);
if (!res)
{
Utils::Log("Failed to parse numeric literal");
}
// return ParseExpression(tokens, program_data, generator, current_token + 1);
}
if (next_token.token_type == TokenType::Return)
{
// return
// return will need to process an expression stopping at a semicolon
// for now do it the hacky way
// TODO: string returns?
// TODO: return value in variable
if (GetToken(tokens, [current_token + 1].token_type == TokenType::NumericLiteral && GetToken(tokens, [current_token + 2].token_type == TokenType::SemiColon)
{
Advance();
bool res = ParseNumericLiteral(tokens, program_data, generator);
if (!res)
{
Utils::Log("Failed to parse numeric literal following return statement");
}
}
generator->WriteReturnInstruction(program_data);
}
if (next_token.token_type == TokenType::Identifier)
{
ScopingBlock& current_scope = scopes_.back();
// test against built in types
for (UInt8 i = 0; i < Utils::VariableTypeToUInt8(VariableType::Unknown); i++)
{
if (next_token.lexeme == variable_type_strings[i])
{
Utils::Log("Found Type specifier for type: ", variable_type_strings[i]);
Token expect_identifier_token = GetToken(tokens, [current_token + 1];
if (expect_identifier_token.token_type == TokenType::Identifier)
{
// found identifier for type declaration good
std::string var_name = expect_identifier_token.lexeme;
Token expect_bracket_or_equal_token = GetToken(tokens, [current_token + 2];
// TODO: process args
if (expect_bracket_or_equal_token.token_type == TokenType::LeftBracket)
{
// function
// add the left bracket to the bracket matching
brackets_.push(expect_bracket_or_equal_token.token_type);
// size_t next_token_idx = 0;
bool res = ParseFunctionDeclaration(tokens, program_data, generator, static_cast<VariableType>(i), var_name);
if (!res)
{
// malformed function declaration
}
return ParseExpression(tokens, program_data, generator);
}
else if (expect_bracket_or_equal_token.token_type == TokenType::Equal)
{
// var assignment
// need to verify validity of assignment
Utils::Log("Attempting declaration and assignment of ", var_name, " in scope ", current_scope.GetName());
// temporary
current_token += 4;
return ParseExpression(tokens, program_data, generator);
}
else if (expect_bracket_or_equal_token.token_type == TokenType::SemiColon)
{
// just declaration without initialisation
// ScopingBlock& current_scope = scopes_.back();
Utils::Log("Attempting to add variable to scope ", current_scope.GetName());
bool res = current_scope.AddVariable(var_name, SDIM::Variable(static_cast<VariableType>(i)));
if (!res)
{
Utils::Log("Attempt to redeclare ", var_name);
}
Utils::Log("Added variable ", var_name, " to scope ", current_scope.GetName());
switch (static_cast<VariableType>(i))
{
case VariableType::UInt8:
generator->WritePushUInt8Instruction(program_data, 0);
break;
case VariableType::UInt16:
generator->WritePushUInt16Instruction(program_data, 0);
break;
case VariableType::UInt32:
generator->WritePushUInt32Instruction(program_data, 0);
break;
case VariableType::UInt64:
generator->WritePushUInt64Instruction(program_data, 0);
break;
case VariableType::Int8:
generator->WritePushInt8Instruction(program_data, 0);
break;
case VariableType::Int16:
generator->WritePushInt16Instruction(program_data, 0);
break;
case VariableType::Int32:
generator->WritePushInt32Instruction(program_data, 0);
break;
case VariableType::Int64:
generator->WritePushInt64Instruction(program_data, 0);
break;
case VariableType::F32:
generator->WritePushF32Instruction(program_data, 0.0f);
break;
case VariableType::F64:
generator->WritePushF64Instruction(program_data, 0.0);
break;
default:
break;
}
return ParseExpression(tokens, program_data, generator);
}
else
{
Utils::Log("Malformed variable or function definition ", var_name);
// malformed
return ParseExpression(tokens, program_data, generator);
}
}
// TODO: process type specifier for function and variable declarations
return ParseExpression(tokens, program_data, generator);
}
}
}
++current_token;
return ParseExpression(tokens, program_data, generator);
// return true;
*/
}
bool Parser::ParseFunctionDeclaration(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
(void)program_data;
(void)generator;
if (current_token >= tokens.size())
{
Error(GetToken(tokens, tokens.size() - 1), "Reached end of file");
return false;
}
Token expect_type = GetToken(tokens, current_token++);
if (!MatchToken(expect_type, TokenType::Identifier))
{
Error(expect_type, "Expected type specifier for function declaration");
return false;
}
VariableType func_return = TokenToVariableType(expect_type);
if (func_return == VariableType::Unknown)
{
Error(expect_type, "Expected type specifier for function declaration");
return false;
}
Token expect_func_name = GetToken(tokens, current_token++);
if (!MatchToken(expect_type, TokenType::Identifier))
{
Error(expect_func_name, "Expected function name for function declaration");
return false;
}
std::string func_name = expect_func_name.lexeme;
Function func;
func.name = func_name;
for (const auto& it : funcs_)
{
if (it.name == func.name)
{
Error(expect_func_name, "Redefinition of previously defined function (SDIM does not currently support overloaded functions)");
return false;
}
}
func.addr = program_data.size();
func.func_ret = func_return;
funcs_.push_back(func);
Utils::Log("Found func: ", func_name);
// TODO: make this function handle function scope generating bytecode under a function
// Is that even necessary because the bytecode for a function will be written after the function declaration is processed anyway
// separate scopes for args and the function to allow redecleration of variables in function scope which exist in args scope
// this pattern follows the way C++ does it, not in terms of scope naming however
// the best part of this is the scope name doesn't even have to be unique so name collisions with other functions and modules are not an issue
if (!ConsumeToken(tokens, TokenType::LeftBracket, "Expected left bracket for function declaration"))
{
return false;
}
// Parse args list here
if (!ConsumeToken(tokens, TokenType::RightBracket, "Expected right bracket to close function args list declaration"))
{
return false;
}
const char* entrypoint_name = "Main";
Utils::Log("Function ", variable_type_strings[static_cast<UInt8>(func_return)], " ", func_name, " defined at bytecode address ", program_data.size());
if (func_name == entrypoint_name)
{
// found main
Utils::Log("Found entrypoint at: ", program_data.size());
BytecodeGenerator* gen = (BytecodeGenerator*)generator;
gen->GetHeader().entrypoint_idx = program_data.size();
}
// args scope
OpenScope();
// scopes_.push_back(func_args_scope);
// handle args list
ConsumeToken(tokens, TokenType::LeftBrace, "Expected opening brace for function scope");
// func scope
bool res = ParseBlock(tokens, program_data, generator);
if (!res)
{
return false;
}
ConsumeToken(tokens, TokenType::RightBrace, "Expected closing brace for function scope");
// pop func scope
// CloseScope();
// pop args scope
CloseScope();
// next_token_idx = current_token + 1;
return true;
}
bool Parser::ParseNumericLiteral(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
Token token = GetToken(tokens, current_token - 1);
Utils::Log("Numeric literal: ", token.lexeme);
if (token.lexeme.find(".") != token.lexeme.npos)
{
if (token.lexeme.find("f") != token.lexeme.npos)
{
// 32 bit float
F32 num = static_cast<F32>(std::atof(token.lexeme.c_str()));
generator->WritePushF32Instruction(program_data, num);
}
else
{
// 64 bit float
F64 num = std::atof(token.lexeme.c_str());
generator->WritePushF64Instruction(program_data, num);
}
}
else
{
// integer literal
Int64 num = std::atoll(token.lexeme.c_str());
generator->WritePushInt64Instruction(program_data, num);
}
return true;
}
bool Parser::ParseStringLiteral(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
Token expect_string = GetToken(tokens, current_token - 1);
if (!MatchToken(expect_string, TokenType::StringLiteral))
{
Error(expect_string, "Expected string literal");
return false;
}
generator->WritePushStringInstruction(program_data, expect_string.lexeme.c_str());
// Advance();
return true;
}
/*
bool Parser::ParseVariableDeclaration(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
(void)tokens;
(void)program_data;
(void)generator;
return false;
}
*/
bool Parser::ParseAssignment(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
(void)tokens;
(void)program_data;
(void)generator;
// TODO: handle assignment
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
return true;
}
bool Parser::ParseGrouping(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
bool close_bracket = MatchToken(GetToken(tokens, current_token), TokenType::RightBracket);
if (!close_bracket)
{
Error(GetToken(tokens, current_token), "Expected closing right bracket in grouped expression");
return false;
}
Advance();
return true;
}
bool Parser::ParseUnary(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
TokenType op_type = GetToken(tokens, current_token - 1).token_type;
// evaluate the rest of the expression the unary operator is operating on
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
if (op_type == TokenType::Minus)
{
generator->WriteNegateInstruction(program_data);
return true;
}
else if (op_type == TokenType::MinusMinus)
{
generator->WritePushInt64Instruction(program_data, -1);
generator->WriteSubtractInstruction(program_data);
return true;
}
else if (op_type == TokenType::PlusPlus)
{
generator->WritePushUInt64Instruction(program_data, 1);
generator->WriteAddInstruction(program_data);
return true;
}
else
{
return false;
}
}
bool Parser::ParsePrecedence(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator, Precedence current_precedence)
{
(void)tokens;
(void)program_data;
(void)generator;
(void)current_precedence;
// handle prefix expressions
// if(GetToken(tokens, [current_token])
Token prev = GetToken(tokens, current_token);
Advance();
ParseFunc prefix_func = GetParseRule(prev.token_type).prefix;
if (prefix_func == nullptr)
{
Error(prev, "Expected prefix expression");
return false;
}
bool res = prefix_func(this, tokens, program_data, generator);
if (!res)
{
Error(prev, "Expected prefix expression");
return false;
}
while (current_precedence <= GetParseRule(GetToken(tokens, current_token).token_type).prec)
{
Advance();
ParseFunc infix_func = GetParseRule(GetToken(tokens, current_token - 1).token_type).infix;
// if (infix_func == nullptr)
// {
// Error(GetToken(tokens, current_token), "Expression is not a valid infix expression");
// return false;
// }
infix_func(this, tokens, program_data, generator);
}
return true;
}
bool Parser::ParseReturn(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
Token op = GetToken(tokens, current_token - 1);
if (op.token_type != TokenType::Return)
{
Error(op, "Expected return keyword");
}
// parse operators with higher precedence
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
generator->WriteReturnInstruction(program_data);
return true;
}
bool Parser::ParseBlock(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
(void)tokens;
(void)program_data;
(void)generator;
OpenScope();
while (!MatchToken(tokens[current_token], TokenType::RightBrace) && !MatchToken(tokens[current_token], TokenType::EOFToken))
{
bool res = ParseDeclaration(tokens, program_data, generator);
if (!res)
{
return false;
}
}
ConsumeToken(tokens, TokenType::RightBrace, "Expected closing brace for scoping block");
CloseScope();
return true;
}
bool Parser::ParseDeclaration(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
if (MatchToken(GetToken(tokens, current_token), TokenType::Identifier))
{
// declaration
Token expect_type = GetToken(tokens, current_token);
if (IsBuiltInType(expect_type))
{
bool res = DeclareVariable(tokens, program_data, generator);
if (!res)
{
return false;
}
return ConsumeToken(tokens, TokenType::SemiColon, "expect ; at end of declaration");
}
else
{
return ExpressionStatement(tokens, program_data, generator);
}
}
else
{
// statement
return ParseStatement(tokens, program_data, generator);
}
// return false;
}
bool Parser::ParseStatement(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
(void)tokens;
(void)program_data;
(void)generator;
Utils::Log("Statement");
Token curr = GetToken(tokens, current_token);
Advance();
if (MatchToken(curr, TokenType::Return))
{
return ParseReturn(tokens, program_data, generator);
}
else if (MatchToken(curr, TokenType::Print))
{
return ParsePrint(tokens, program_data, generator);
}
else if (MatchToken(curr, TokenType::For))
{
return ParseFor(tokens, program_data, generator);
}
else if (MatchToken(curr, TokenType::Identifier))
{
return ExpressionStatement(tokens, program_data, generator);
}
return false;
}
bool Parser::ParseIdentifier(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
(void)tokens;
(void)program_data;
(void)generator;
Token expect_type_or_identifier = GetToken(tokens, current_token - 1);
if (IsBuiltInType(expect_type_or_identifier))
{
Utils::Log("Found type specifier ", expect_type_or_identifier.lexeme);
// var declaration
Token expect_var_name = GetToken(tokens, current_token);
if (!MatchToken(expect_var_name, TokenType::Identifier))
{
Error(expect_var_name, "Expected Identifier in variable declaration");
return false;
}
Token next_token = GetToken(tokens, current_token + 1);
if (MatchToken(next_token, TokenType::SemiColon))
{
// ScopingBlock current_scope = scopes_.back();
// just declaration
LocalVar var;
var.var = Variable(TokenToVariableType(expect_type_or_identifier));
generator->WriteLocalVarInstruction(program_data, locals_.size());
var.scope = scope_idx_;
locals_.push_back(var);
}
bool res = ParsePrecedence(tokens, program_data, generator, Precedence::Assignment);
if (!res)
{
return false;
}
}
else if(expect_type_or_identifier.token_type == TokenType::Identifier)
{
Utils::Log("Found identifier ", expect_type_or_identifier.lexeme);
// generator->WritePushLocalInstruction(program_data, it->second);
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
}
return true;
}
bool Parser::BinaryExpression(const std::vector<SDIM::Token> & tokens, std::vector<unsigned char> & program_data, Generator * generator)
{
Token op = GetToken(tokens, current_token - 1);
// parse operators with higher precedence
bool res = ParsePrecedence(tokens, program_data, generator, GetPrecedence(op.token_type));
if (!res)
{
return false;
}
Utils::Log("Wrote instruction for binary operator ", Utils::TokenTypeToString(op.token_type));
switch (op.token_type)
{
// arithmetic
case TokenType::Plus:
generator->WriteAddInstruction(program_data);
Utils::Log("Wrote add instruction");
return true;
case TokenType::Minus:
generator->WriteSubtractInstruction(program_data);
return true;
case TokenType::Asterisk:
generator->WriteMultiplyInstruction(program_data);
return true;
case TokenType::ForwardSlash:
generator->WriteDivideInstruction(program_data);
return true;
case TokenType::Percent:
generator->WriteModuloInstruction(program_data);
return true;
case TokenType::Ampersand:
generator->WriteAndInstruction(program_data);
return true;
case TokenType::VerticalBar:
generator->WriteOrInstruction(program_data);
return true;
case TokenType::Caret:
generator->WriteXorInstruction(program_data);
return true;
//logical
case TokenType::EqualEqual:
generator->WriteEqualInstruction(program_data);
return true;
case TokenType::BangEqual:
generator->WriteNotEqualInstruction(program_data);
return true;
case TokenType::Bang:
generator->WriteNotInstruction(program_data);
return true;
// relational
case TokenType::LessThan:
generator->WriteLessInstruction(program_data);
return true;
case TokenType::LessEqual:
generator->WriteLessEqualInstruction(program_data);
return true;
case TokenType::GreaterThan:
generator->WriteGreaterInstruction(program_data);
return true;
case TokenType::GreaterEqual:
generator->WriteGreaterEqualInstruction(program_data);
return true;
//case TokenType::Tilde:
// generator->WriteBitwiseNotInstruction(program_data);
default:
Error(op, "Expected binary operator");
return false;
}
return false;
}
bool Parser::DeclareVariable(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
Token type_token = GetToken(tokens, current_token);
VariableType var_type = TokenToVariableType(type_token);
Advance();
Token name_token = GetToken(tokens, current_token);
Advance();
Token expect_equal_or_semicolon = GetToken(tokens, current_token);
if (MatchToken(expect_equal_or_semicolon, TokenType::Equal))
{
Advance();
ParseExpression(tokens, program_data, generator);
}
else
{
// TODO: do this properly based on the type of the variable being declared
generator->WritePushInt64Instruction(program_data, 0);
}
LocalVar local_var;
local_var.var.type = var_type;
local_var.name = name_token.lexeme;
local_var.scope = scope_idx_;
local_var.local_idx = locals_.size();
// check for name conflicts
if (AddLocal(local_var))
{
locals_.push_back(local_var);
Utils::Log("Added local var ", variable_type_strings[static_cast<UInt8>(local_var.var.type)], " ", local_var.name);
generator->WriteLocalVarInstruction(program_data, locals_.size());
// ConsumeToken(tokens, TokenType::SemiColon, "Expected ; at end of variable declaration");
return true;
}
return false;
}
bool Parser::ParsePrint(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
Token print = GetToken(tokens, current_token - 1);
if (!MatchToken(print, TokenType::Print))
{
Error(print, "Expected print statement");
return false;
}
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
return ConsumeToken(tokens, TokenType::SemiColon, "Expected semicolon to end print statement");
}
bool Parser::ExpressionStatement(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
(void)tokens;
(void)program_data;
(void)generator;
bool res = ParseExpression(tokens, program_data, generator);
if (!res)
{
return false;
}
return ConsumeToken(tokens, TokenType::SemiColon, "Expected ; at end of expression statement");
}
bool Parser::ParseFor(const std::vector<SDIM::Token>& tokens, std::vector<unsigned char>& program_data, Generator* generator)
{
(void)program_data;
(void)generator;
if (!ConsumeToken(tokens, TokenType::LeftBracket, "Expected ( to open for loop declaration"))
{
return false;
}
bool res = ParseDeclaration(tokens, program_data, generator);
if (!res)
{
Error(GetToken(tokens, current_token), "Malformed for loop");
return false;
}
if (!ConsumeToken(tokens, TokenType::SemiColon, "Malformed for loop statement"))
{
return false;
}
return true;
}
void Parser::OpenScope()
{
++scope_idx_;
}
void Parser::CloseScope()
{
--scope_idx_;
if (locals_.empty())
{
return;
}
for (auto it = locals_.begin(); it != locals_.end();)
{
if (it->scope > scope_idx_)
{
it = locals_.erase(it);
}
else
{
++it;
}
}
}
bool Parser::ConsumeToken(const std::vector<SDIM::Token> & tokens, TokenType expect, const char* error_message)
{
Token consume = GetToken(tokens, current_token);
if (consume.token_type == expect)
{
// handle brackets here
// bool res = HandleBrackets(GetToken(tokens, );
// if (!res)
// {
// return false;
// }
Advance();
return true;
}
Error(GetToken(tokens, current_token), error_message);
return false;
}
/*
bool Parser::HandleBrackets(const std::vector<SDIM::Token>& GetToken(tokens, )
{
Token token = GetToken(tokens, [current_token];
if (Utils::IsOpeningBracket(token.token_type))
{
brackets_.push(token.token_type);
return true;
}
else if (Utils::IsClosingBracket(token.token_type))
{
if (brackets_.empty())
{
Utils::Log("Closing bracket: ", token.lexeme, " found with no matching opening bracket");
return false;
}
TokenType current_bracket = brackets_.top();
if (!Utils::IsMatchingBracketPair(current_bracket, token.token_type))
{
Utils::Log("Expected matching bracket for ", Utils::TokenTypeToString(current_bracket), " but got ", Utils::TokenTypeToString(token.token_type), "Instead");
return false;
}
Utils::Log("Matched opening bracket ", Utils::TokenTypeToString(current_bracket), " with ", Utils::TokenTypeToString(token.token_type));
if (token.token_type == TokenType::RightBrace)
{
// close scope
ScopingBlock closed_scope = scopes_.back();
Utils::Log("Closed Scoping block ", closed_scope.GetName());
scopes_.pop_back();
}
brackets_.pop();
}
return false;
}
*/
bool Parser::MatchToken(const Token & token, TokenType expect)
{
return token.token_type == expect;
}
bool Parser::AddLocal(const LocalVar& local)
{
for (auto it = locals_.begin(); it != locals_.end(); it++)
{
if (it->scope == local.scope && it->name == local.name)
{
// var exists in same scope
return false;
}
}
return true;
}
void Parser::Advance()
{
++current_token;
}
bool Parser::IsBuiltInType(const Token & token)
{
for (UInt8 i = 0; i < Utils::VariableTypeToUInt8(VariableType::Unknown); i++)
{
if (token.lexeme == variable_type_strings[i])
{
return true;
}
}
return false;
}
void Parser::Error(const Token & at, const char* message)
{
Utils::Log("[ERROR] line(", at.line, "):column(", at.col, ") near ", at.lexeme, ": ", message);
}
VariableType Parser::TokenToVariableType(const Token & token)
{
for (UInt8 i = 0; i < Utils::VariableTypeToUInt8(VariableType::Unknown); i++)
{
if (token.lexeme == variable_type_strings[i])
{
return static_cast<VariableType>(i);
}
}
return VariableType::Unknown;
}
// make it quicker to type parser rules
#define DefParseRule(token, prefix, infix) {token, {infix, prefix, GetPrecedence(token)}}
ParseRule Parser::GetParseRule(TokenType token)
{
static const std::unordered_map<TokenType, ParseRule> parse_rules =
{
// brackets
DefParseRule(TokenType::LeftBracket, &Parser::ParseGrouping, nullptr),
// {TokenType::LeftBracket, {nullptr, &Parser::ParseGrouping, GetPrecedence(TokenType::LeftBracket)} },
// arithmetic
DefParseRule(TokenType::PlusPlus, &Parser::ParseUnary, nullptr),
DefParseRule(TokenType::MinusMinus, &Parser::ParseUnary, nullptr),
DefParseRule(TokenType::Minus, &Parser::ParseUnary, &Parser::BinaryExpression),
DefParseRule(TokenType::Plus, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::Asterisk, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::ForwardSlash, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::Percent, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::Ampersand, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::VerticalBar, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::Caret, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::Tilde, &Parser::ParseUnary, nullptr),
// logical
DefParseRule(TokenType::EqualEqual, &Parser::ParseUnary, nullptr),
DefParseRule(TokenType::BangEqual, &Parser::ParseUnary, nullptr),
DefParseRule(TokenType::GreaterThan, &Parser::ParseUnary, &Parser::BinaryExpression),
DefParseRule(TokenType::LessThan, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::GreaterEqual, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::LessEqual, nullptr, &Parser::BinaryExpression),
DefParseRule(TokenType::Bang, &Parser::ParseUnary, nullptr),
// literals
DefParseRule(TokenType::StringLiteral, &Parser::ParseStringLiteral, nullptr),
DefParseRule(TokenType::NumericLiteral, &Parser::ParseNumericLiteral, nullptr),
// Assignment
DefParseRule(TokenType::Equal, nullptr, &Parser::ParseAssignment),
// semicolon
DefParseRule(TokenType::SemiColon, nullptr, nullptr),
// return
DefParseRule(TokenType::Return, &Parser::ParseReturn, nullptr),
// variables and types
DefParseRule(TokenType::Identifier, &Parser::ParseIdentifier, nullptr)
};
const auto& it = parse_rules.find(token);
if(it == parse_rules.cend())
{
return ParseRule{ nullptr, nullptr, Precedence::None };
}
return it->second;
}
}
| 29.38381 | 167 | 0.699835 | DamienHenderson |
03c9bf4181ba5a15a8a686021ecae98ec1e0489f | 531 | cpp | C++ | tests/template_named_values.cpp | riskybacon/cpp-named-params | da72b3556e5c5ed31e2ac47976db283c7e394e93 | [
"MIT"
] | null | null | null | tests/template_named_values.cpp | riskybacon/cpp-named-params | da72b3556e5c5ed31e2ac47976db283c7e394e93 | [
"MIT"
] | null | null | null | tests/template_named_values.cpp | riskybacon/cpp-named-params | da72b3556e5c5ed31e2ac47976db283c7e394e93 | [
"MIT"
] | null | null | null | #define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "template_named_values"
#include <boost/test/unit_test.hpp>
#include <iostream>
#include <cpp_named_params/template_named_values.hpp>
BOOST_AUTO_TEST_CASE(test_named_values) {
using namespace rb;
rectangle<
width < 10 >,
height < 30 >,
scale < 1, 3 >
> rect;
BOOST_CHECK(rect.width() == 10);
BOOST_CHECK(rect.height() == 30);
BOOST_CHECK(rect.area() == 10 * 30);
BOOST_CHECK(rect.scale() == float(1) / float(3));
}
| 24.136364 | 53 | 0.653484 | riskybacon |
03cd3af2e7bec6214fe3d263c288ec9bd81baf37 | 10,059 | cpp | C++ | mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp | akashhansda/llvm-project | 32f146010968ded160f54af464673451ad574135 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp | akashhansda/llvm-project | 32f146010968ded160f54af464673451ad574135 | [
"Apache-2.0"
] | null | null | null | mlir/lib/Dialect/Utils/ReshapeOpsUtils.cpp | akashhansda/llvm-project | 32f146010968ded160f54af464673451ad574135 | [
"Apache-2.0"
] | null | null | null | //===- ReshapeOpsUtils.cpp - Utilities used by structured ops -------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "mlir/Dialect/Utils/ReshapeOpsUtils.h"
#include "mlir/IR/AffineMap.h"
#include "mlir/IR/Builders.h"
#include <numeric>
using namespace mlir;
Optional<SmallVector<ReassociationIndices>>
mlir::getReassociationIndicesForReshape(ShapedType sourceType,
ShapedType targetType) {
// Make the sourceType greater rank than the targetType. If they are same
// rank, then its an unsupported reshape op.
if (sourceType.getRank() == targetType.getRank())
return llvm::None;
if (sourceType.getRank() < targetType.getRank())
std::swap(sourceType, targetType);
ArrayRef<int64_t> sourceShape = sourceType.getShape();
ArrayRef<int64_t> targetShape = targetType.getShape();
unsigned sourceDim = 0;
SmallVector<ReassociationIndices> reassociationMap;
reassociationMap.reserve(targetType.getRank());
ReassociationIndices currIndices;
int64_t prodOfCollapsedDims = 1;
while (sourceDim < sourceShape.size()) {
unsigned targetDim = reassociationMap.size();
// If we have mapped all the target dimensions stop and handle the remaining
// tail of size-1 dimensions explictly.
if (targetDim == targetType.getRank())
break;
int64_t currTargetShape = targetShape[targetDim];
while (sourceShape[sourceDim] != ShapedType::kDynamicSize &&
prodOfCollapsedDims * sourceShape[sourceDim] < currTargetShape &&
sourceDim < sourceShape.size()) {
prodOfCollapsedDims *= sourceShape[sourceDim];
currIndices.push_back(sourceDim++);
}
// If the current expanded dimension is dynamic, then the collapsed
// dimensions should also be dynamic and product of all previous unprocessed
// dimensions of the expanded shape should be 1.
if (sourceShape[sourceDim] == ShapedType::kDynamicSize &&
(currTargetShape != ShapedType::kDynamicSize ||
prodOfCollapsedDims != 1))
return llvm::None;
// If the collapsed dim is dynamic, the current expanded dim should also
// be dynamic.
if (currTargetShape == ShapedType::kDynamicSize &&
sourceShape[sourceDim] != ShapedType::kDynamicSize)
return llvm::None;
// For static shapes, if the product of dimensions of the expanded shape
// should match the collapsed dimension shape.
if (prodOfCollapsedDims * sourceShape[sourceDim] != currTargetShape)
return llvm::None;
currIndices.push_back(sourceDim++);
reassociationMap.emplace_back(ReassociationIndices{});
std::swap(reassociationMap.back(), currIndices);
prodOfCollapsedDims = 1;
}
// All the dimensions in the target must have been processed.
if (reassociationMap.size() != targetShape.size())
return llvm::None;
// Process any remaining entries in the source shape. They all need to be
// 1 or dynamic.
for (; sourceDim < sourceShape.size(); sourceDim++) {
if (sourceShape[sourceDim] != ShapedType::kDynamicSize &&
sourceShape[sourceDim] != 1)
return llvm::None;
// The map is empty when the target type is a scalar.
if (!reassociationMap.empty())
reassociationMap.back().push_back(sourceDim);
}
return reassociationMap;
}
Optional<SmallVector<ReassociationIndices>> mlir::composeReassociationIndices(
ArrayRef<ReassociationIndices> producerReassociations,
ArrayRef<ReassociationIndices> consumerReassociations,
MLIRContext *context) {
SmallVector<ReassociationIndices> composedIndices;
// Make the producer the larger sized vector. If they are of same size, the
// resulting reshape is not a supported reshape op.
if (producerReassociations.size() == consumerReassociations.size())
return llvm::None;
if (producerReassociations.size() < consumerReassociations.size())
std::swap(producerReassociations, consumerReassociations);
// Handle the corner case of the result being a rank 0 shaped type. Return an
// empty reassociation.
if (consumerReassociations.empty())
return composedIndices;
size_t consumerDims = std::accumulate(
consumerReassociations.begin(), consumerReassociations.end(), 0,
[](size_t all, ReassociationIndicesRef indices) {
return all + indices.size();
});
if (producerReassociations.size() != consumerDims)
return llvm::None;
for (ReassociationIndicesRef consumerIndices : consumerReassociations) {
ReassociationIndices reassociations;
for (int64_t consumerIndex : consumerIndices) {
llvm::append_range(reassociations, producerReassociations[consumerIndex]);
}
composedIndices.push_back(std::move(reassociations));
}
return composedIndices;
}
SmallVector<SmallVector<AffineExpr, 2>, 2>
mlir::convertReassociationIndicesToExprs(
MLIRContext *context, ArrayRef<ReassociationIndices> reassociationIndices) {
SmallVector<SmallVector<AffineExpr, 2>, 2> reassociationMaps;
for (const auto &indices : reassociationIndices) {
SmallVector<AffineExpr, 2> reassociationMap;
reassociationMap.reserve(indices.size());
for (int64_t index : indices)
reassociationMap.push_back(mlir::getAffineDimExpr(index, context));
reassociationMaps.push_back(std::move(reassociationMap));
}
return reassociationMaps;
}
template <typename AffineExprTy>
unsigned getMaxPosOfType(ArrayRef<ReassociationExprs> exprArrays) {
unsigned pos = 0;
for (const auto &exprs : exprArrays) {
for (auto expr : exprs) {
expr.walk([&pos](AffineExpr e) {
if (auto d = e.dyn_cast<AffineExprTy>())
pos = std::max(pos, d.getPosition());
});
}
}
return pos;
}
ArrayAttr mlir::getReassociationIndicesAttribute(
OpBuilder &b, ArrayRef<ReassociationIndices> reassociation) {
SmallVector<Attribute, 4> reassociationAttr =
llvm::to_vector<4>(llvm::map_range(
reassociation, [&](const ReassociationIndices &indices) -> Attribute {
return b.getI64ArrayAttr(indices).cast<Attribute>();
}));
return b.getArrayAttr(reassociationAttr);
}
SmallVector<ReassociationIndices, 2> mlir::convertReassociationMapsToIndices(
OpBuilder &b, ArrayRef<ReassociationExprs> reassociationExprs) {
SmallVector<ReassociationIndices, 2> reassociationIndices;
for (const auto &exprs : reassociationExprs) {
ReassociationIndices indices;
indices.reserve(exprs.size());
for (const auto &expr : exprs)
indices.push_back(expr.cast<AffineDimExpr>().getPosition());
reassociationIndices.push_back(indices);
}
return reassociationIndices;
}
SmallVector<AffineMap, 4>
mlir::getSymbolLessAffineMaps(ArrayRef<ReassociationExprs> reassociation) {
unsigned maxDim = getMaxPosOfType<AffineDimExpr>(reassociation);
assert(getMaxPosOfType<AffineSymbolExpr>(reassociation) == 0 &&
"Expected symbol-less expressions");
SmallVector<AffineMap, 4> maps;
maps.reserve(reassociation.size());
for (const auto &exprs : reassociation) {
assert(!exprs.empty());
maps.push_back(AffineMap::get(maxDim + 1, 0, exprs, exprs[0].getContext()));
}
return maps;
}
bool mlir::isReassociationValid(ArrayRef<AffineMap> reassociation,
int *invalidIndex) {
if (reassociation.empty())
return true;
unsigned nDims = reassociation[0].getNumDims();
unsigned nextExpectedDim = 0;
for (const auto &it : llvm::enumerate(reassociation)) {
auto m = it.value();
if (m.getNumDims() != nDims || m.getNumSymbols() != 0) {
if (invalidIndex)
*invalidIndex = it.index();
return false;
}
for (auto e : m.getResults()) {
auto d = e.dyn_cast<AffineDimExpr>();
if (!d || d.getPosition() != nextExpectedDim++) {
if (invalidIndex)
*invalidIndex = it.index();
return false;
}
}
}
if (nextExpectedDim != nDims) {
if (invalidIndex)
*invalidIndex = reassociation.size() - 1;
return false;
}
return true;
}
LogicalResult mlir::reshapeLikeShapesAreCompatible(
function_ref<LogicalResult(const Twine &)> emitError,
ArrayRef<int64_t> collapsedShape, ArrayRef<int64_t> expandedShape,
ArrayRef<ReassociationIndices> reassociationMaps, bool isExpandingReshape) {
unsigned expandedDimStart = 0;
for (const auto &map : llvm::enumerate(reassociationMaps)) {
Optional<int64_t> dynamicShape;
int64_t linearizedStaticShape = 1;
for (const auto &dim : llvm::enumerate(
expandedShape.slice(expandedDimStart, map.value().size()))) {
if (ShapedType::isDynamic(dim.value())) {
if (isExpandingReshape && dynamicShape) {
return emitError("invalid to have a single dimension (" +
Twine(map.index()) +
") expanded into multiple dynamic dims (" +
Twine(expandedDimStart + dynamicShape.getValue()) +
"," + Twine(expandedDimStart + dim.index()) + ")");
}
dynamicShape = dim.index();
} else {
linearizedStaticShape *= dim.value();
}
}
if (dynamicShape) {
if (!ShapedType::isDynamic(collapsedShape[map.index()])) {
return emitError(
"expected dimension " + Twine(map.index()) +
" of collapsed type to be dynamic since one or more of the "
"corresponding dimensions in the expanded type is dynamic");
}
} else {
if (collapsedShape[map.index()] != linearizedStaticShape) {
return emitError("expected dimension " + Twine(map.index()) +
" of collapsed type to be static value of " +
Twine(linearizedStaticShape));
}
}
expandedDimStart += map.value().size();
}
return success();
}
| 38.54023 | 80 | 0.681877 | akashhansda |
03cdcf420c5680fb327da8c84945c8a869dd134f | 4,732 | cpp | C++ | Fogo.cpp | Ivan-Sandro/Fire_Doom_Algorithm | f33af2826f8d16cd8b8cc6086f8ba8b3ba21733f | [
"MIT"
] | null | null | null | Fogo.cpp | Ivan-Sandro/Fire_Doom_Algorithm | f33af2826f8d16cd8b8cc6086f8ba8b3ba21733f | [
"MIT"
] | null | null | null | Fogo.cpp | Ivan-Sandro/Fire_Doom_Algorithm | f33af2826f8d16cd8b8cc6086f8ba8b3ba21733f | [
"MIT"
] | null | null | null |
#include "Fogo.h"
#include <iostream>
void FOGO::_Get_Paleta_Regular_Cor(const char* Nome_Paleta, int Ponto_Inicial_X, int Ponto_Inicial_Y, int Distancia_Pixeis_X, int Distancia_Pixeis_Y, int Matriz_Paleta_X, int Matriz_Paleta_Y){
ALLEGRO_BITMAP *Paleta = NULL;
Paleta = al_load_bitmap(Nome_Paleta);
if(!Paleta){
_Erro_Box("Erro ao carregar a Paleta do Fogo");
system("pause");
return;
}
for (int Y = Ponto_Inicial_Y ; Y < Ponto_Inicial_Y + Matriz_Paleta_Y * Distancia_Pixeis_Y ; Y += Distancia_Pixeis_Y){
for (int X = Ponto_Inicial_X ; X < Ponto_Inicial_X + Matriz_Paleta_X * Distancia_Pixeis_X ; X += Distancia_Pixeis_X){
Paleta_Cores.push_back(al_get_pixel(Paleta, X, Y));
}
}
al_destroy_bitmap(Paleta);
}
void FOGO::_Definir_Matriz_Fogo(int X, int Y, short int Tamanho_Quadrados_Fogo){
Px_Tamanho_Quadrados_Fogo = Tamanho_Quadrados_Fogo;
Chance_Fogo_Esquerda = 40;
Chance_Fogo_Subir = 70;
Intensidade_Esquerda = 3;
Intensidade_Subir = 2;
Largura_Matriz = 1 + int(X/Tamanho_Quadrados_Fogo);
Altura_Matriz = 1 + int(Y/Tamanho_Quadrados_Fogo);
std::vector <char> Linha;
for(int A = 0 ; A < Largura_Matriz ; A++){
Linha.push_back(0);
}
for(int B = 0 ; B < Altura_Matriz ; B++){
Matriz_Fogo.push_back(Linha);
}
}
void FOGO::_Mover_Fogo(){
for(int X = 0 ; X < Largura_Matriz ; X++){
for(int Y = 0 ; Y < Altura_Matriz ; Y++){
if(rand() % 100 < Chance_Fogo_Subir && Y > 0){
Matriz_Fogo[Y-1][X] = Matriz_Fogo[Y][X] -rand() % Intensidade_Subir;
if(Matriz_Fogo[Y-1][X] < 0)Matriz_Fogo[Y-1][X] = 0;
}
if(rand () % 100 < Chance_Fogo_Esquerda && X > 0 && Y > 0){
Matriz_Fogo[Y-1][X-1] = Matriz_Fogo[Y][X]-rand() % Intensidade_Esquerda;
if(Matriz_Fogo[Y-1][X-1] < 0)Matriz_Fogo[Y-1][X-1] = 0;
}
}
}
}
void FOGO::_Desenhar_Fogo(void){
int X_Quadrado_Fogo;
int Y_Quadrado_Fogo;
for(int X = 0 ; X < Largura_Matriz ; X++){
for(int Y = 0 ; Y < Altura_Matriz ; Y++){
if(Matriz_Fogo[Y][X] > 0){
X_Quadrado_Fogo = X * Px_Tamanho_Quadrados_Fogo;
Y_Quadrado_Fogo = Y * Px_Tamanho_Quadrados_Fogo;
al_draw_filled_rectangle(X_Quadrado_Fogo, Y_Quadrado_Fogo, X_Quadrado_Fogo + Px_Tamanho_Quadrados_Fogo, Y_Quadrado_Fogo + Px_Tamanho_Quadrados_Fogo,
Paleta_Cores[Matriz_Fogo[Y][X]]);
}
}
}
}
void FOGO::_Desenhar_Com_Mouse(int X, int Y){
short int dX, dY;
short int lugar_Pintado_X = X/Px_Tamanho_Quadrados_Fogo;
short int lugar_Pintado_Y = Y/Px_Tamanho_Quadrados_Fogo;
for(dX = -2 ; dX < 3 ; dX++){
for(dY = -2 ; dY < 3; dY++){
if(dX + lugar_Pintado_X < 0 || dX + lugar_Pintado_X > Largura_Matriz-2 ||
dY + lugar_Pintado_Y < 0 || dY + lugar_Pintado_Y > Altura_Matriz-1)
break;
else
Matriz_Fogo[dY + lugar_Pintado_Y][dX + lugar_Pintado_X] = Paleta_Cores.size()-1;
}
}
}
void FOGO::_Manter_Fogo_Padrao(void){
for(int A = 0 ; A < Largura_Matriz-1 ; A++)
Matriz_Fogo[Altura_Matriz-1][A] = Paleta_Cores.size()-1;
}
void FOGO::_Apagar_Fogo(void){
for(int X = 0 ; X < Largura_Matriz ; X++){
for(int Y = 0 ; Y < Altura_Matriz ; Y++){
Matriz_Fogo[Y][X] = 0;
}
}
}
void FOGO::_Zerar_Ultima_Fileira_Fogo(void){
for(int X = 0 ; X < Largura_Matriz ; X++)
Matriz_Fogo[Altura_Matriz-1][X] = 0;
}
void FOGO::_Aumentar_Chance_Fogo_Subir (void){
if(Chance_Fogo_Subir < 100)
Chance_Fogo_Subir += 1;
}
void FOGO::_Diminuir_Chance_Fogo_Subir (void){
if(Chance_Fogo_Subir > 0)
Chance_Fogo_Subir -= 1;
}
void FOGO::_Aumentar_Chance_Fogo_Esquerda (void){
if(Chance_Fogo_Esquerda < 100)
Chance_Fogo_Esquerda += 1;
}
void FOGO::_Diminuir_Chance_Fogo_Esquerda (void){
if(Chance_Fogo_Esquerda > 0)
Chance_Fogo_Esquerda -= 1;
}
void FOGO::_Aumentar_Subtrair_Subir (void){
if(Intensidade_Subir < 10)
Intensidade_Subir += 1;
}
void FOGO::_Diminuir_Subtrair_Subir (void){
if(Intensidade_Subir > 1)
Intensidade_Subir -= 1;
}
void FOGO::_Aumentar_Subtrair_Esquerda (void){
if(Intensidade_Esquerda < 10)
Intensidade_Esquerda += 1;
}
void FOGO::_Diminuir_Subtrair_Esquerda (void){
if(Intensidade_Esquerda > 1)
Intensidade_Esquerda -= 1;
}
| 31.758389 | 193 | 0.60186 | Ivan-Sandro |
03d0c1fb4f771720ff38a0c2b21e32944057ea13 | 565 | cpp | C++ | 1-100/124. Binary Tree Maximum Path Sum.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1-100/124. Binary Tree Maximum Path Sum.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | 1-100/124. Binary Tree Maximum Path Sum.cpp | erichuang1994/leetcode-solution | d5b3bb3ce2a428a3108f7369715a3700e2ba699d | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution
{
public:
int maxPathSum(TreeNode *root)
{
int ret = INT_MIN;
dfs(root, ret);
return ret;
}
int dfs(TreeNode *root, int &ret)
{
if (root == NULL)
return 0;
auto l = max(0, dfs(root->left, ret));
auto r = max(0, dfs(root->right, ret));
ret = max(ret, l + r + root->val);
return max(l, r) + root->val;
}
}; | 20.178571 | 59 | 0.541593 | erichuang1994 |
03d0d2cb120465470c82d73346407232d581923d | 6,519 | hpp | C++ | renderer/ocean.hpp | VulkanWorks/Granite-scene-graph-gui-ffmpeg-dsp | a725ec78eeb5de2d3c25257b1a9372f5e38910f6 | [
"MIT"
] | 1,003 | 2017-08-13T17:47:04.000Z | 2022-03-29T15:56:55.000Z | renderer/ocean.hpp | VulkanWorks/Granite-scene-graph-gui-ffmpeg-dsp | a725ec78eeb5de2d3c25257b1a9372f5e38910f6 | [
"MIT"
] | 10 | 2017-08-14T19:11:35.000Z | 2021-12-10T12:51:53.000Z | renderer/ocean.hpp | VulkanWorks/Granite-scene-graph-gui-ffmpeg-dsp | a725ec78eeb5de2d3c25257b1a9372f5e38910f6 | [
"MIT"
] | 107 | 2017-08-16T16:13:26.000Z | 2022-03-03T06:42:19.000Z | /* Copyright (c) 2017-2020 Hans-Kristian Arntzen
*
* 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.
*/
#pragma once
#include "abstract_renderable.hpp"
#include "scene.hpp"
#include "application_wsi_events.hpp"
#include "fft/glfft.hpp"
#include "glfft_granite_interface.hpp"
#include "application_events.hpp"
#include <vector>
namespace Granite
{
class RenderTextureResource;
class RenderBufferResource;
static constexpr unsigned MaxOceanLayers = 4;
struct OceanConfig
{
unsigned fft_resolution = 512;
unsigned displacement_downsample = 1;
unsigned grid_count = 32;
unsigned grid_resolution = 128;
vec2 ocean_size = vec2(512.0f);
vec2 wind_velocity = vec2(10.0f, 5.0f);
float normal_mod = 7.3f;
float amplitude = 0.2f;
struct
{
std::string input;
float uv_scale = 0.01f;
float depth[MaxOceanLayers] = { 2.0f, 4.0f, 6.0f, 8.0f };
float emissive_mod = 1.0f;
bool bandlimited_pixel = false;
bool input_is_render_graph = false;
} refraction;
};
class Ocean : public AbstractRenderable,
public PerFrameRefreshable,
public RenderPassCreator,
public EventHandler
{
public:
Ocean(const OceanConfig &config);
struct Handles
{
Entity *entity;
Ocean *ocean;
};
static Handles add_to_scene(Scene &scene, const OceanConfig &config = {});
enum { FrequencyBands = 8 };
void set_frequency_band_amplitude(unsigned band, float amplitude);
void set_frequency_band_modulation(bool enable);
private:
OceanConfig config;
void on_device_created(const Vulkan::DeviceCreatedEvent &e);
void on_device_destroyed(const Vulkan::DeviceCreatedEvent &);
bool on_frame_tick(const FrameTickEvent &e);
std::unique_ptr<GLFFT::FFT> height_fft;
std::unique_ptr<GLFFT::FFT> normal_fft;
std::unique_ptr<GLFFT::FFT> displacement_fft;
FFTInterface fft_iface;
FFTDeferredCommandBuffer deferred_cmd;
float frequency_bands[FrequencyBands];
bool freq_band_modulation = false;
bool has_static_aabb() const override
{
return false;
}
void get_render_info(const RenderContext &context,
const RenderInfoComponent *transform,
RenderQueue &queue) const override;
const RenderContext *context = nullptr;
void refresh(const RenderContext &context, TaskComposer &composer) override;
void add_render_passes(RenderGraph &graph) override;
void set_base_renderer(const RendererSuite *suite) override;
void set_base_render_context(const RenderContext *context) override;
void setup_render_pass_dependencies(RenderGraph &graph,
RenderPass &target) override;
void setup_render_pass_resources(RenderGraph &graph) override;
void set_scene(Scene *scene) override;
std::vector<Vulkan::ImageViewHandle> vertex_mip_views;
std::vector<Vulkan::ImageViewHandle> fragment_mip_views;
std::vector<Vulkan::ImageViewHandle> normal_mip_views;
Vulkan::BufferHandle distribution_buffer;
Vulkan::BufferHandle distribution_buffer_displacement;
Vulkan::BufferHandle distribution_buffer_normal;
RenderTextureResource *ocean_lod = nullptr;
RenderBufferResource *lod_data = nullptr;
RenderBufferResource *lod_data_counters = nullptr;
RenderBufferResource *height_fft_input = nullptr;
RenderBufferResource *displacement_fft_input = nullptr;
RenderBufferResource *normal_fft_input = nullptr;
RenderTextureResource *height_fft_output = nullptr;
RenderTextureResource *displacement_fft_output = nullptr;
RenderTextureResource *normal_fft_output = nullptr;
RenderTextureResource *height_displacement_output = nullptr;
RenderTextureResource *gradient_jacobian_output = nullptr;
RenderGraph *graph = nullptr;
void build_lod_map(Vulkan::CommandBuffer &cmd);
void cull_blocks(Vulkan::CommandBuffer &cmd);
void init_counter_buffer(Vulkan::CommandBuffer &cmd);
void update_lod_pass(Vulkan::CommandBuffer &cmd);
void update_fft_pass(Vulkan::CommandBuffer &cmd);
void update_fft_input(Vulkan::CommandBuffer &cmd);
void compute_fft(Vulkan::CommandBuffer &cmd);
void bake_maps(Vulkan::CommandBuffer &cmd);
void generate_mipmaps(Vulkan::CommandBuffer &cmd);
vec3 last_camera_position = vec3(0.0f);
double current_time = 0.0;
vec2 wind_direction;
float phillips_L;
struct LOD
{
Vulkan::BufferHandle vbo;
Vulkan::BufferHandle ibo;
unsigned count;
};
std::vector<LOD> quad_lod;
Vulkan::BufferHandle border_vbo;
Vulkan::BufferHandle border_ibo;
unsigned border_count = 0;
VkIndexType index_type = VK_INDEX_TYPE_UINT16;
void build_buffers(Vulkan::Device &device);
void build_lod(Vulkan::Device &device, unsigned size, unsigned stride);
void init_distributions(Vulkan::Device &device);
void build_border(std::vector<vec3> &positions, std::vector<uint16_t> &indices,
ivec2 base, ivec2 dx, ivec2 dy);
void build_corner(std::vector<vec3> &positions, std::vector<uint16_t> &indices,
ivec2 base, ivec2 dx, ivec2 dy);
void build_fill_edge(std::vector<vec3> &positions, std::vector<uint16_t> &indices,
vec2 base_outer, vec2 end_outer,
ivec2 base_inner, ivec2 delta, ivec2 corner_delta);
void add_lod_update_pass(RenderGraph &graph);
void add_fft_update_pass(RenderGraph &graph);
vec2 get_snapped_grid_center() const;
vec2 get_grid_size() const;
ivec2 get_grid_base_coord() const;
vec2 heightmap_world_size() const;
vec2 normalmap_world_size() const;
Vulkan::ImageView *refraction = nullptr;
RenderTextureResource *refraction_resource = nullptr;
};
} | 33.777202 | 83 | 0.762694 | VulkanWorks |
03d1a2055d5a71db2b12661f975ee6018fa00eab | 117 | cpp | C++ | WithMemento/SchoolBackup.cpp | mateusz-talma/MementoPattern | 9ea3cd819822cc4521faa63ed1fd4a116ef34c4e | [
"MIT"
] | null | null | null | WithMemento/SchoolBackup.cpp | mateusz-talma/MementoPattern | 9ea3cd819822cc4521faa63ed1fd4a116ef34c4e | [
"MIT"
] | null | null | null | WithMemento/SchoolBackup.cpp | mateusz-talma/MementoPattern | 9ea3cd819822cc4521faa63ed1fd4a116ef34c4e | [
"MIT"
] | null | null | null | #include "SchoolBackup.hpp"
#include "School.hpp"
SchoolBackup::SchoolBackup(School school)
: school_(school) {} | 23.4 | 41 | 0.74359 | mateusz-talma |
03d3b489a6b62f9d642c8ccb9bc5ecaa54db0d4b | 664 | cpp | C++ | 0090_Subsets_II/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | 2 | 2019-02-18T15:32:57.000Z | 2019-03-18T12:55:35.000Z | 0090_Subsets_II/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | null | null | null | 0090_Subsets_II/solution.cpp | Heliovic/LeetCode_Solutions | 73d5a7aaffe62da9a9cd8a80288b260085fda08f | [
"MIT"
] | null | null | null | class Solution {
public:
vector<vector<int>> ans;
void dfs(vector<int>& v, int pos, vector<int>& nums)
{
ans.push_back(v);
for (int i = pos; i < nums.size();)
{
v.push_back(nums[i]);
dfs(v, i + 1, nums);
v.pop_back();
i++;
while (i < nums.size() && nums[i] == nums[i - 1])
i++;
}
}
vector<vector<int>> subsetsWithDup(vector<int>& nums) {
sort(nums.begin(), nums.end());
vector<int> tmp;
dfs(tmp, 0, nums);
return ans;
}
};
| 20.121212 | 61 | 0.391566 | Heliovic |
03d5135a91778fbf5fc9e4d9a41d689974658487 | 1,290 | cpp | C++ | atto/tests/opengl/0-glfw/color.cpp | ubikoo/libfish | 7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39 | [
"MIT"
] | null | null | null | atto/tests/opengl/0-glfw/color.cpp | ubikoo/libfish | 7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39 | [
"MIT"
] | null | null | null | atto/tests/opengl/0-glfw/color.cpp | ubikoo/libfish | 7f0b5e06b2bf1d6ff490ddfda9cc7aab69cdbf39 | [
"MIT"
] | null | null | null | /*
* color.cpp
*
* Copyright (c) 2020 Carlos Braga
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the MIT License.
*
* See accompanying LICENSE.md or https://opensource.org/licenses/MIT.
*/
#include "atto/opengl/opengl.hpp"
#include "color.hpp"
using namespace atto;
/** ---------------------------------------------------------------------------
* Color::Color
*/
Color::Color()
: r(0.0f)
, g(0.0f)
, b(0.0f)
, a(1.0f)
, d(1.0f)
{}
/** ---------------------------------------------------------------------------
* Color::handle
*/
void Color::handle(const gl::Event &event)
{}
/** ---------------------------------------------------------------------------
* Color::draw
*/
void Color::draw(void *data)
{
GLFWwindow *window = gl::Renderer::window();
if (window == nullptr) {
return;
}
/*
* Update OpenGL color and depth buffer values.
*/
{
const double wr = 0.3;
const double wg = 0.2;
const double wb = 0.1;
const double t = glfwGetTime();
r = 0.5*(std::cos(wr*t) + 1.0);
g = 0.5*(std::cos(wg*t) + 1.0);
b = 0.5*(std::cos(wb*t) + 1.0);
a = 1.0;
}
gl::Renderer::clear(r, g, b, a, 1.0);
}
| 21.864407 | 79 | 0.44186 | ubikoo |
03d5a36a9d28886bdee82fe15d23e667e3c14bcd | 1,861 | cpp | C++ | leetcode/239.sliding-window-maximum.cpp | geemaple/algorithm | 68bc5032e1ee52c22ef2f2e608053484c487af54 | [
"MIT"
] | 177 | 2017-08-21T08:57:43.000Z | 2020-06-22T03:44:22.000Z | leetcode/239.sliding-window-maximum.cpp | geemaple/algorithm | 68bc5032e1ee52c22ef2f2e608053484c487af54 | [
"MIT"
] | 2 | 2018-09-06T13:39:12.000Z | 2019-06-03T02:54:45.000Z | leetcode/239.sliding-window-maximum.cpp | geemaple/algorithm | 68bc5032e1ee52c22ef2f2e608053484c487af54 | [
"MIT"
] | 23 | 2017-08-23T06:01:28.000Z | 2020-04-20T03:17:36.000Z | /*
* @lc app=leetcode id=239 lang=cpp
*
* [239] Sliding Window Maximum
*
* https://leetcode.com/problems/sliding-window-maximum/description/
*
* algorithms
* Hard (36.17%)
* Total Accepted: 151.8K
* Total Submissions: 401.3K
* Testcase Example: '[1,3,-1,-3,5,3,6,7]\n3'
*
* Given an array nums, there is a sliding window of size k which is moving
* from the very left of the array to the very right. You can only see the k
* numbers in the window. Each time the sliding window moves right by one
* position. Return the max sliding window.
*
* Example:
*
*
* Input: nums = [1,3,-1,-3,5,3,6,7], and k = 3
* Output: [3,3,5,5,6,7]
* Explanation:
*
* Window position Max
* --------------- -----
* [1 3 -1] -3 5 3 6 7 3
* 1 [3 -1 -3] 5 3 6 7 3
* 1 3 [-1 -3 5] 3 6 7 5
* 1 3 -1 [-3 5 3] 6 7 5
* 1 3 -1 -3 [5 3 6] 7 6
* 1 3 -1 -3 5 [3 6 7] 7
*
*
* Note:
* You may assume k is always valid, 1 ≤ k ≤ input array's size for non-empty
* array.
*
* Follow up:
* Could you solve it in linear time?
*/
class Solution {
public:
vector<int> maxSlidingWindow(vector<int>& nums, int k) {
vector<int> results;
deque<int> q;
for (int i = 0; i < nums.size(); i++) {
// detect if front shoud move out of window
// i - j + 1 = k + 1, so j = i + 1 - k
if (!q.empty() && i - k == q.front()) {
q.pop_front();
}
while (!q.empty() && nums[q.back()] < nums[i]) {
q.pop_back();
}
q.push_back(i);
if (i >= k - 1) {
results.push_back(nums[q.front()]);
}
}
return results;
}
};
| 26.585714 | 77 | 0.468565 | geemaple |
03d6a111cde580b535d3ec5c7a65950cb38de8d0 | 296 | hpp | C++ | source/Objects/Edge.hpp | 1pkg/halfo | a57dc4b68d29165d6ab7ed36c7886326e414e269 | [
"MIT"
] | null | null | null | source/Objects/Edge.hpp | 1pkg/halfo | a57dc4b68d29165d6ab7ed36c7886326e414e269 | [
"MIT"
] | null | null | null | source/Objects/Edge.hpp | 1pkg/halfo | a57dc4b68d29165d6ab7ed36c7886326e414e269 | [
"MIT"
] | null | null | null | #ifndef OBJECTS_EDGE
#define OBJECTS_EDGE
#include "include.hpp"
#include "Views/Object/Edge.hpp"
namespace Objects
{
class Edge : public Application::Object
{
public:
Edge();
Views::Object::Edge * view() const override;
private:
std::unique_ptr<Views::Object::Edge> _view;
};
}
#endif | 12.333333 | 45 | 0.719595 | 1pkg |
03da52fe2bbe06f3814fc799a37c2290cada142a | 221 | cpp | C++ | src/10.DarkChannelPriorHazeRemoval/main.cpp | rzwm/OpenCVImageProcessing | 192c6c62acb0c03f606f7d468276a5f1d78925eb | [
"Apache-2.0"
] | 35 | 2017-12-15T04:34:40.000Z | 2022-03-20T13:37:40.000Z | src/10.DarkChannelPriorHazeRemoval/main.cpp | Sevryy/OpenCVImageProcessing | 192c6c62acb0c03f606f7d468276a5f1d78925eb | [
"Apache-2.0"
] | null | null | null | src/10.DarkChannelPriorHazeRemoval/main.cpp | Sevryy/OpenCVImageProcessing | 192c6c62acb0c03f606f7d468276a5f1d78925eb | [
"Apache-2.0"
] | 20 | 2018-04-08T08:04:56.000Z | 2021-09-17T08:48:45.000Z | // http://blog.csdn.net/matrix_space/article/details/40652883
// 暗通道先验去雾
#include "opencv2/core/core.hpp"
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
int main()
{
// TODO
return 0;
}
| 18.416667 | 62 | 0.728507 | rzwm |
03df8967b85406e89b7c4ed866aa22d0d16e4a6b | 1,214 | cc | C++ | onnxruntime/core/platform/posix/ort_mutex.cc | codemzs/onnxruntime | c69194ec4c8c9674368113aa6044d0db708cd813 | [
"MIT"
] | 4 | 2019-06-06T23:48:57.000Z | 2021-06-03T11:51:45.000Z | onnxruntime/core/platform/posix/ort_mutex.cc | codemzs/onnxruntime | c69194ec4c8c9674368113aa6044d0db708cd813 | [
"MIT"
] | 17 | 2020-07-21T11:13:27.000Z | 2022-03-27T02:37:05.000Z | onnxruntime/core/platform/posix/ort_mutex.cc | Surfndez/onnxruntime | 9d748afff19e9604a00632d66b97159b917dabb2 | [
"MIT"
] | 3 | 2019-05-07T01:29:04.000Z | 2020-08-09T08:36:12.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#include "core/platform/ort_mutex.h"
#include <assert.h>
#include <stdexcept>
#include <system_error>
#include <sstream>
namespace onnxruntime {
void OrtCondVar::timed_wait_impl(std::unique_lock<OrtMutex>& lk,
std::chrono::time_point<std::chrono::system_clock, std::chrono::nanoseconds> tp) {
using namespace std::chrono;
#ifndef NDEBUG
if (!lk.owns_lock())
throw std::runtime_error("condition_variable::timed wait: mutex not locked");
#endif
nanoseconds d = tp.time_since_epoch();
timespec abs_deadline;
seconds s = duration_cast<seconds>(d);
using ts_sec = decltype(abs_deadline.tv_sec);
constexpr ts_sec ts_sec_max = std::numeric_limits<ts_sec>::max();
if (s.count() < ts_sec_max) {
abs_deadline.tv_sec = static_cast<ts_sec>(s.count());
abs_deadline.tv_nsec = static_cast<decltype(abs_deadline.tv_nsec)>((d - s).count());
} else {
abs_deadline.tv_sec = ts_sec_max;
abs_deadline.tv_nsec = 999999999;
}
nsync::nsync_cv_wait_with_deadline(&native_cv_object, lk.mutex()->native_handle(), abs_deadline, nullptr);
}
} // namespace onnxruntime | 36.787879 | 115 | 0.718287 | codemzs |
03e0476f309cd01cd66a771f8bfb6c0cec599b8b | 67,699 | cc | C++ | src/falcon/reval.cc | codeclimate-testing/falcon | c2d0b9da4d4cffd39cd489ffa886ee745d06f063 | [
"Apache-2.0"
] | 115 | 2015-01-18T13:28:05.000Z | 2022-03-01T23:45:44.000Z | src/falcon/reval.cc | codeclimate-testing/falcon | c2d0b9da4d4cffd39cd489ffa886ee745d06f063 | [
"Apache-2.0"
] | null | null | null | src/falcon/reval.cc | codeclimate-testing/falcon | c2d0b9da4d4cffd39cd489ffa886ee745d06f063 | [
"Apache-2.0"
] | 8 | 2015-02-12T04:08:42.000Z | 2018-09-11T20:55:29.000Z | #include "py_include.h"
#include <opcode.h>
#include <marshal.h>
#include <string.h>
#include <stdint.h>
#include <stdarg.h>
#include "reval.h"
#include "rcompile.h"
#ifdef FALCON_DEBUG
static bool logging_enabled() {
static bool _is_logging = getenv("EVAL_LOG") != NULL;
return _is_logging;
}
#define EVAL_LOG(...) if (logging_enabled()) { fprintf(stderr, __VA_ARGS__); fputs("\n", stderr); }
#define CHECK_VALID(obj) { Reg_AssertGt(obj->ob_refcnt, 0); }
#else
#define EVAL_LOG(...)
#define CHECK_VALID(obj) { }
//#define CHECK_VALID(obj) Reg_AssertGt(obj->ob_refcnt, 0);
#endif
// Register load/store helpers
#define STORE_REG(regnum, val)\
decltype(val) v__ = val;\
Register& r__ = registers[regnum];\
r__.decref();\
r__.store(v__);
static f_inline PyObject* load_obj(Register* registers, int regnum) {
PyObject* o = registers[regnum].as_obj();
return o;
}
#define LOAD_OBJ(regnum) load_obj(registers, regnum)
#define LOAD_INT(regnum) registers[regnum].as_int()
#define LOAD_FLOAT(regnum) registers[regnum].as_float()
typedef long (*IntegerBinaryOp)(long, long);
typedef PyObject* (*PythonBinaryOp)(PyObject*, PyObject*);
typedef PyObject* (*UnaryFunction)(PyObject*);
// Some scoped object helpers for tracking refcounts.
struct GilHelper {
PyGILState_STATE state_;
GilHelper() :
state_(PyGILState_Ensure()) {
}
~GilHelper() {
PyGILState_Release(state_);
}
};
// Catch bad case of RefHelper(x) (goes immediately out of scope
#define GilHelper(v) static int MustInitWithVar[-1];
#define RefHelper(v) static int MustInitWithVar[-1];
// Wrapper around PyXXXObject* which allows implicit casting to PyObject.
// This let's us access member variables and call API functions easily.
template<class T>
struct PyObjHelper {
const T& val_;
PyObjHelper(const T& t) :
val_(t) {
}
operator PyObject*() {
return (PyObject*) val_;
}
operator T() {
return val_;
}
operator void*() {
return val_;
}
bool operator==(void* v) const {
return val_ == v;
}
bool operator!=(void* v) const {
return val_ != v;
}
T operator->() {
return val_;
}
};
RegisterFrame::RegisterFrame(RegisterCode* rcode, PyObject* obj, const ObjVector& args, const ObjVector& kw) :
code(rcode) {
instructions_ = code->instructions.data();
if (rcode->function) {
globals_ = PyFunction_GetGlobals(rcode->function);
locals_ = NULL;
} else {
globals_ = PyEval_GetGlobals();
locals_ = PyEval_GetGlobals();
}
Reg_Assert(kw.empty(), "Keyword args not supported.");
builtins_ = PyEval_GetBuiltins();
names_ = code->names();
consts_ = code->consts();
#if ! STACK_ALLOC_REGISTERS
registers = new Register[rcode->num_registers];
#endif
const int num_args = args.size();
if (rcode->num_cells > 0) {
#if ! STACK_ALLOC_REGISTERS
freevars = new PyObject*[rcode->num_cells];
#endif
int i;
for (i = 0; i < rcode->num_cellvars; ++i) {
bool found_argname = false;
char *cellname = PyString_AS_STRING(PyTuple_GET_ITEM(rcode->code()->co_cellvars, i));
for (int arg_idx = 0; arg_idx < num_args; ++arg_idx) {
char* argname = PyString_AS_STRING(PyTuple_GET_ITEM(rcode->code()->co_varnames, arg_idx));
if (strcmp(cellname, argname) == 0) {
PyObject* arg_value = args[arg_idx].as_obj();
freevars[i] = PyCell_New(arg_value);
found_argname = true;
break;
}
}
if (!found_argname) {
freevars[i] = PyCell_New(NULL);
}
}
PyObject* closure = ((PyFunctionObject*) rcode->function)->func_closure;
if (closure) {
for (int i = rcode->num_cellvars; i < rcode->num_cells; ++i) {
freevars[i] = PyTuple_GET_ITEM(closure, i - rcode->num_cellvars) ;
Py_INCREF(freevars[i]);
}
} else {
for (int i = rcode->num_cellvars; i < rcode->num_cells; ++i) {
freevars[i] = PyCell_New(NULL);
}
}
} else {
#if ! STACK_ALLOC_REGISTERS
freevars = NULL;
#endif
}
// Log_Info("Alignments: reg: %d code: %d consts: %d globals: %d, this: %d",
// ((long)registers) % 64, ((long)rcode->instructions.data()) % 64, (long)consts_ % 64, (long)globals_ % 64, (long)this % 64);
const int num_registers = code->num_registers;
// setup const and local register aliases.
int num_consts = PyTuple_GET_SIZE(consts());
for (int i = 0; i < num_consts; ++i) {
PyObject* v = PyTuple_GET_ITEM(consts(), i) ;
Py_INCREF(v);
registers[i].store(v);
}
int needed_args = code->code()->co_argcount;
int offset = num_consts;
if (PyMethod_Check(obj)) {
PyObject* self = PyMethod_GET_SELF(obj);
Reg_Assert(self != NULL, "Method call without a bound self.");
Py_INCREF(self);
registers[offset].store(self);
++offset;
needed_args--;
}
if (code->function) {
PyObject* def_args = PyFunction_GET_DEFAULTS(code->function);
int num_def_args = def_args == NULL ? 0 : PyTuple_GET_SIZE(def_args);
int num_args = args.size();
if (num_args + num_def_args < needed_args) {
throw RException(PyExc_TypeError, "Wrong number of arguments for %s, expected %d, got %d.",
PyEval_GetFuncName(code->function), needed_args - num_def_args, num_args);
}
int default_start = needed_args - num_def_args;
EVAL_LOG("Calling function with defaults: %s", obj_to_str(def_args));
for (int i = 0; i < needed_args; ++i) {
if (i < num_args) {
EVAL_LOG("Assigning arguments: %d <- args[%d] %s", offset, i, obj_to_str(args[i].as_obj()));
registers[offset].store(args[i]);
} else {
PyObject* default_arg = PyTuple_GET_ITEM(def_args, i - default_start);
EVAL_LOG("Assigning arguments: %d <- defaults[%d] %s", offset, i, obj_to_str(default_arg));
registers[offset].store(default_arg);
}
registers[offset].incref();
++offset;
}
}
Reg_AssertLt(num_registers, kMaxRegisters);
for (register int i = offset; i < num_registers; ++i) {
registers[i].reset();
}
}
RegisterFrame::~RegisterFrame() {
const int num_registers = code->num_registers;
for (register int i = 0; i < num_registers; ++i) {
registers[i].decref();
}
for (register int i = 0; i < this->code->num_cells; ++i) {
Py_XDECREF(freevars[i]);
}
#if ! STACK_ALLOC_REGISTERS
delete[] registers;
delete[] freevars;
#endif
}
Evaluator::Evaluator() {
bzero(op_counts_, sizeof(op_counts_));
bzero(op_times_, sizeof(op_times_));
total_count_ = 0;
last_clock_ = 0;
hint_hits_ = 0;
hint_misses_ = 0;
compiler = new Compiler;
bzero(hints, sizeof(Hint) * kMaxHints);
// We use a sentinel value for the invalid hint index.
hints[kInvalidHint].guard.obj = NULL;
hints[kInvalidHint].key = NULL;
hints[kInvalidHint].value = NULL;
hints[kInvalidHint].version = (unsigned int) -1;
}
Evaluator::~Evaluator() {
delete compiler;
}
void RegisterFrame::fill_locals(PyObject* ldict) {
PyObject* varnames = code->varnames();
for (int i = 0; i < PyTuple_GET_SIZE(varnames) ; ++i) {
PyObject* name = PyTuple_GET_ITEM(varnames, i) ;
PyObject* value = PyDict_GetItem(ldict, name);
registers[num_consts() + i].store(value);
}
Py_INCREF(ldict);
locals_ = ldict;
}
PyObject* RegisterFrame::locals() {
if (!locals_) {
locals_ = PyDict_New();
}
PyObject* varnames = code->varnames();
const int num_consts = PyTuple_Size(consts());
const int num_locals = code->code()->co_nlocals;
for (int i = 0; i < num_locals; ++i) {
PyObject* v = LOAD_OBJ(num_consts + i);
if (v != NULL) {
Py_INCREF(v);
PyDict_SetItem(locals_, PyTuple_GetItem(varnames, i), v);
}
}
return locals_;
}
PyObject* Evaluator::eval_frame_to_pyobj(RegisterFrame* frame) {
try {
Register result = eval(frame);
//bool needs_incref = !result.is_obj();
PyObject* result_obj = result.as_obj();
//if (needs_incref) Py_INCREF(result_obj);
EVAL_LOG("Returning to python: %s", obj_to_str(result_obj));
// only delete after incref since deleting the frame decreases reference counts
delete frame;
return result_obj;
} catch (RException& r) {
delete frame;
return NULL;
}
}
PyObject* Evaluator::eval_python_module(PyObject* code, PyObject* module_dict) {
RegisterFrame* frame = frame_from_pyfunc(code, PyTuple_New(0), PyDict_New());
if (frame == NULL) {
Log_Error("Couldn't compile module, calling CPython.");
return PyEval_EvalCode((PyCodeObject*) code, module_dict, module_dict);
} else {
return eval_frame_to_pyobj(frame);
}
}
PyObject* Evaluator::eval_python(PyObject* func, PyObject* args, PyObject* kw) {
RegisterFrame* frame = frame_from_pyfunc(func, args, kw);
if (frame == NULL) {
EVAL_LOG("Couldn't compile function, calling CPython.");
return PyObject_Call(func, args, kw);
} else {
return eval_frame_to_pyobj(frame);
}
}
RegisterFrame* Evaluator::frame_from_pyframe(PyFrameObject* frame) {
RegisterCode* regcode = compiler->compile((PyObject*) frame->f_code);
if (regcode == NULL) {
return NULL;
}
ObjVector v_args;
ObjVector kw_args;
RegisterFrame* f = new RegisterFrame(regcode, (PyObject*) frame->f_code, v_args, kw_args);
PyFrame_FastToLocals(frame);
f->fill_locals(frame->f_locals);
return f;
}
RegisterFrame* Evaluator::frame_from_pyfunc(PyObject* obj, PyObject* args, PyObject* kw) {
if (args == NULL || !PyTuple_Check(args)) {
throw RException(PyExc_TypeError, "Expected function argument tuple, got: %s", obj_to_str(PyObject_Type(args)));
}
RegisterCode* regcode = compiler->compile(obj);
if (regcode == NULL) {
return NULL;
}
ObjVector v_args;
v_args.resize(PyTuple_GET_SIZE(args) );
for (size_t i = 0; i < v_args.size(); ++i) {
v_args[i].store(PyTuple_GET_ITEM(args, i) );
}
ObjVector kw_args;
size_t n_kwds = 0;
if (kw != NULL && PyDict_Check(kw)) {
n_kwds = PyDict_Size(kw);
}
for (size_t i = 0; i < n_kwds; ++i) {
throw RException(PyExc_ValueError, "Keywords not yet supported, n_given = %d", n_kwds);
// should check whether kw is present in the args
// and use default otherwise
// kw_args.push_back()
}
return new RegisterFrame(regcode, obj, v_args, kw_args);
}
RegisterFrame* Evaluator::frame_from_codeobj(PyObject* code) {
ObjVector args, kw;
RegisterCode *regcode = compiler->compile(code);
return new RegisterFrame(regcode, code, args, kw);
}
void Evaluator::dump_status() {
Log_Info("Evaluator status:");
Log_Info("%d operations executed.", total_count_);
for (int i = 0; i < 256; ++i) {
if (op_counts_[i] > 0) {
Log_Info("%20s : %10d, %.3f", OpUtil::name(i), op_counts_[i], op_times_[i] / 1e9);
}
}
}
void Evaluator::collect_info(int opcode) {
++total_count_;
// ++op_counts_[opcode];
// if (total_count_ % 113 == 0) {
// op_times_[opcode] += rdtsc() - last_clock_;
// last_clock_ = rdtsc();
// }
if (total_count_ > 1e9) {
dump_status();
throw RException(PyExc_SystemError, "Execution entered infinite loop.");
}
}
template <class OpType>
static f_inline void log_operation(RegisterFrame* frame, const OpType* op, Register* registers, const char* pc) {
EVAL_LOG("%5d %s %s", frame->offset(pc), frame->str().c_str(), op->str(registers).c_str());
}
template<class OpType, class SubType>
struct RegOpImpl {
static f_inline const char* eval(Evaluator* eval, RegisterFrame* frame, const char* pc, Register* registers) {
OpType& op = *((OpType*) pc);
log_operation(frame, &op, registers, pc);
pc += op.size();
SubType::_eval(eval, frame, op, registers);
return pc;
}
};
template<class SubType>
struct VarArgsOpImpl {
static f_inline const char* eval(Evaluator* eval, RegisterFrame* frame, const char* pc, Register* registers) {
VarRegOp *op = (VarRegOp*) pc;
log_operation(frame, op, registers, pc);
pc += op->size();
SubType::_eval(eval, frame, op, registers);
return pc;
}
};
template<class OpType, class SubType>
struct BranchOpImpl {
static f_inline const char* eval(Evaluator* eval, RegisterFrame* frame, const char* pc, Register* registers) {
OpType& op = *((OpType*) pc);
log_operation(frame, &op, registers, pc);
SubType::_eval(eval, frame, op, &pc, registers);
return pc;
}
};
#define OP_OVERFLOWED(a, b, i) ((i ^ a) < 0 && (i ^ b) < 0)
struct IntegerOps {
#define _OP(name, op)\
static f_inline long name(long a, long b) {\
return (long) ((unsigned long) a op b);\
}
_OP(add, +)
_OP(sub, -)
_OP(mul, *)
_OP(div, /)
_OP(mod, %)
_OP(Or, |)
_OP(Xor, ^)
_OP(And, &)
_OP(Rshift, >>)
_OP(Lshift, <<)
static f_inline PyObject* compare(long a, long b, int arg) {
switch (arg) {
case PyCmp_LT:
return a < b ? Py_True : Py_False ;
case PyCmp_LE:
return a <= b ? Py_True : Py_False ;
case PyCmp_EQ:
return a == b ? Py_True : Py_False ;
case PyCmp_NE:
return a != b ? Py_True : Py_False ;
case PyCmp_GT:
return a > b ? Py_True : Py_False ;
case PyCmp_GE:
return a >= b ? Py_True : Py_False ;
case PyCmp_IS:
return a == b ? Py_True : Py_False ;
case PyCmp_IS_NOT:
return a != b ? Py_True : Py_False ;
default:
return NULL;
}
return NULL;
}
};
struct FloatOps {
static f_inline PyObject* compare(PyObject* w, PyObject* v, int arg) {
if (!PyFloat_CheckExact(v) || !PyFloat_CheckExact(w)) {
return NULL;
}
double a = PyFloat_AS_DOUBLE(w);
double b = PyFloat_AS_DOUBLE(v);
switch (arg) {
case PyCmp_LT:
return a < b ? Py_True : Py_False ;
case PyCmp_LE:
return a <= b ? Py_True : Py_False ;
case PyCmp_EQ:
return a == b ? Py_True : Py_False ;
case PyCmp_NE:
return a != b ? Py_True : Py_False ;
case PyCmp_GT:
return a > b ? Py_True : Py_False ;
case PyCmp_GE:
return a >= b ? Py_True : Py_False ;
case PyCmp_IS:
return v == w ? Py_True : Py_False ;
case PyCmp_IS_NOT:
return v != w ? Py_True : Py_False ;
default:
return NULL;
}
return NULL;
}
};
template<int OpCode, PythonBinaryOp ObjF, IntegerBinaryOp IntegerF, bool CanOverFlow>
struct BinaryOpWithSpecialization: public RegOpImpl<RegOp<3>,
BinaryOpWithSpecialization<OpCode, ObjF, IntegerF, CanOverFlow> > {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
Register& r1 = registers[op.reg[0]];
Register& r2 = registers[op.reg[1]];
if (r1.get_type() == IntType && r2.get_type() == IntType) {
register long a = r1.as_int();
register long b = r2.as_int();
register long val = IntegerF(a, b);
if (!CanOverFlow || !OP_OVERFLOWED(a, b, val)) {
STORE_REG(op.reg[2], val);
return;
}
}
STORE_REG(op.reg[2], ObjF(r1.as_obj(), r2.as_obj()));
}
};
template<int OpCode, PythonBinaryOp ObjF>
struct BinaryOp: public RegOpImpl<RegOp<3>, BinaryOp<OpCode, ObjF> > {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* r1 = LOAD_OBJ(op.reg[0]);
PyObject* r2 = LOAD_OBJ(op.reg[1]);
CHECK_VALID(r1);
CHECK_VALID(r2);
PyObject* r3 = ObjF(r1, r2);
STORE_REG(op.reg[2], r3);
}
};
template<int OpCode, UnaryFunction ObjF>
struct UnaryOp: public RegOpImpl<RegOp<2>, UnaryOp<OpCode, ObjF> > {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* r1 = LOAD_OBJ(op.reg[0]);
CHECK_VALID(r1);
PyObject* r2 = ObjF(r1);
STORE_REG(op.reg[1], r2);
}
};
struct UnaryNot: public RegOpImpl<RegOp<2>, UnaryNot> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* r1 = LOAD_OBJ(op.reg[0]);
PyObject* res = PyObject_IsTrue(r1) ? Py_False : Py_True;
Py_INCREF(res);
STORE_REG(op.reg[1], res);
}
};
struct BinaryModulo: public RegOpImpl<RegOp<3>, BinaryModulo> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
Register& r1 = registers[op.reg[0]];
Register& r2 = registers[op.reg[1]];
if (r1.get_type() == IntType && r2.get_type() == IntType) {
long x = r1.as_int();
long y = r2.as_int();
// C's modulo differs from Python's remainder when
// args can be negative
if (x >= 0 && y >= 0) {
Register& dst = registers[op.reg[2]];
dst.decref();
dst.store(x % y);
return;
}
}
PyObject* o1 = r1.as_obj();
PyObject* o2 = r2.as_obj();
PyObject* dst = NULL;
if (PyString_CheckExact(o1)) {
dst = PyString_Format(o1, o2);
} else {
dst = PyNumber_Remainder(o1, o2);
}
if (!dst) {
throw RException();
}
STORE_REG(op.reg[2], dst);
}
};
struct BinaryPower: public RegOpImpl<RegOp<3>, BinaryPower> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* r1 = LOAD_OBJ(op.reg[0]);
CHECK_VALID(r1);
PyObject* r2 = LOAD_OBJ(op.reg[1]);
CHECK_VALID(r2);
PyObject* r3 = PyNumber_Power(r1, r2, Py_None);
CHECK_VALID(r3);
STORE_REG(op.reg[2], r3);
}
};
struct BinarySubscr: public RegOpImpl<RegOp<3>, BinarySubscr> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* list = LOAD_OBJ(op.reg[0]);
Register& key = registers[op.reg[1]];
CHECK_VALID(list);
PyObject* res = NULL;
if (PyList_CheckExact(list) && key.get_type() == IntType) {
Py_ssize_t i = key.as_int();
if (i < 0) i += PyList_GET_SIZE(list);
if (i >= 0 && i < PyList_GET_SIZE(list) ) {
res = PyList_GET_ITEM(list, i);
Py_INCREF(res);
CHECK_VALID(res);
STORE_REG(op.reg[2], res);
return;
}
}
res = PyObject_GetItem(list, key.as_obj());
if (!res) {
throw RException();
}
CHECK_VALID(res);
STORE_REG(op.reg[2], res);
}
};
struct BinarySubscrList: public RegOpImpl<RegOp<3>, BinarySubscrList> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* list = LOAD_OBJ(op.reg[0]);
Register& key = registers[op.reg[1]];
CHECK_VALID(list);
PyObject* res = NULL;
if (key.get_type() == IntType) {
Py_ssize_t i = key.as_int();
Py_ssize_t n = PyList_GET_SIZE(list);
if (i < 0) i += n;
if (i >= 0 && i < n) {
res = PyList_GET_ITEM(list, i);
Py_INCREF(res);
CHECK_VALID(res);
STORE_REG(op.reg[2], res);
return;
}
}
res = PyObject_GetItem(list, key.as_obj());
if (!res) {
throw RException();
}
CHECK_VALID(res);
STORE_REG(op.reg[2], res);
}
};
struct BinarySubscrDict: public RegOpImpl<RegOp<3>, BinarySubscrDict> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* dict = LOAD_OBJ(op.reg[0]);
PyObject* key = LOAD_OBJ(op.reg[1]);
CHECK_VALID(dict);
CHECK_VALID(key);
PyObject* res = PyDict_GetItem(dict, key);
if (res != 0) {
Py_INCREF(res);
CHECK_VALID(res);
STORE_REG(op.reg[2], res);
return;
}
res = PyObject_GetItem(dict, key);
if (!res) {
throw RException();
}
CHECK_VALID(res);
STORE_REG(op.reg[2], res);
}
};
struct InplacePower: public RegOpImpl<RegOp<3>, InplacePower> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* r1 = LOAD_OBJ(op.reg[0]);
CHECK_VALID(r1);
PyObject* r2 = LOAD_OBJ(op.reg[1]);
CHECK_VALID(r2);
PyObject* r3 = PyNumber_Power(r1, r2, Py_None);
if (!r3) {
throw RException();
}
STORE_REG(op.reg[2], r3);
}
};
#define Py3kExceptionClass_Check(x) \
(PyType_Check((x)) && \
PyType_FastSubclass((PyTypeObject*)(x), Py_TPFLAGS_BASE_EXC_SUBCLASS))
#define CANNOT_CATCH_MSG "catching classes that don't inherit from " \
"BaseException is not allowed in 3.x"
/* slow path for comparisons, copied from ceval */
static f_inline PyObject* cmp_outcome(int op, PyObject *v, PyObject *w) {
int res = 0;
switch (op) {
case PyCmp_IS:
res = (v == w);
break;
case PyCmp_IS_NOT:
res = (v != w);
break;
case PyCmp_IN:
res = PySequence_Contains(w, v);
if (res < 0) return NULL;
break;
case PyCmp_NOT_IN:
res = PySequence_Contains(w, v);
if (res < 0) return NULL;
res = !res;
break;
case PyCmp_EXC_MATCH:
if (PyTuple_Check(w)) {
Py_ssize_t i, length;
length = PyTuple_Size(w);
for (i = 0; i < length; i += 1) {
PyObject *exc = PyTuple_GET_ITEM(w, i) ;
if (PyString_Check(exc)) {
int ret_val;
ret_val = PyErr_WarnEx(
PyExc_DeprecationWarning,
"catching of string "
"exceptions is deprecated", 1);
if (ret_val < 0)
return NULL;
}
else if (Py_Py3kWarningFlag &&
!PyTuple_Check(exc) &&
!Py3kExceptionClass_Check(exc))
{
int ret_val;
ret_val = PyErr_WarnEx(
PyExc_DeprecationWarning,
CANNOT_CATCH_MSG, 1);
if (ret_val < 0)
return NULL;
}
}
}
else {
if (PyString_Check(w)) {
int ret_val;
ret_val = PyErr_WarnEx(
PyExc_DeprecationWarning,
"catching of string "
"exceptions is deprecated", 1);
if (ret_val < 0)
return NULL;
}
else if (Py_Py3kWarningFlag &&
!PyTuple_Check(w) &&
!Py3kExceptionClass_Check(w))
{
int ret_val;
ret_val = PyErr_WarnEx(
PyExc_DeprecationWarning,
CANNOT_CATCH_MSG, 1);
if (ret_val < 0)
return NULL;
}
}
res = PyErr_GivenExceptionMatches(v, w);
break;
default:
return PyObject_RichCompare(v, w, op);
}
v = res ? Py_True : Py_False;
Py_INCREF(v);
return v;
}
struct CompareOp: public RegOpImpl<RegOp<3>, CompareOp> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
Register& r1 = registers[op.reg[0]];
Register& r2 = registers[op.reg[1]];
PyObject* r3 = NULL;
if (r1.get_type() == IntType && r2.get_type() == IntType) {
r3 = IntegerOps::compare(r1.as_int(), r2.as_int(), op.arg);
} /* else {
r3 = FloatOps::compare(r1.as_obj(), r2.as_obj(), op.arg);
}
*/
if (r3 != NULL) {
Py_INCREF(r3);
} else {
// r3 = PyObject_RichCompare(r1.as_obj(), r2.as_obj(), op.arg);
r3 = cmp_outcome(op.arg, r1.as_obj(), r2.as_obj());
}
if (!r3) {
throw RException();
}
STORE_REG(op.reg[2], r3);
}
};
struct DictContains: public RegOpImpl<RegOp<3>, DictContains> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* dict = LOAD_OBJ(op.reg[0]);
CHECK_VALID(dict);
PyObject* elt = LOAD_OBJ(op.reg[1]);
CHECK_VALID(elt);
int result_code = PyDict_Contains(dict, elt);
if (result_code == -1) {
result_code = PySequence_Contains(dict, elt);
if (result_code == -1) {
throw RException();
}
}
PyObject* result = result_code ? Py_True : Py_False;
Py_INCREF(result);
STORE_REG(op.reg[2], result);
}
};
struct DictGet: public RegOpImpl<RegOp<3>, DictGet> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* dict = LOAD_OBJ(op.reg[0]);
CHECK_VALID(dict);
PyObject* key = LOAD_OBJ(op.reg[1]);
CHECK_VALID(key);
PyObject* result = PyDict_GetItem(dict, key);
if (result == NULL) {
result = Py_None;
}
Py_INCREF(result);
STORE_REG(op.reg[2], result);
}
};
struct DictGetDefault: public RegOpImpl<RegOp<4>, DictGetDefault> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<4>& op, Register* registers) {
PyObject* dict = LOAD_OBJ(op.reg[0]);
CHECK_VALID(dict);
PyObject* key = LOAD_OBJ(op.reg[1]);
CHECK_VALID(key);
PyObject* result = PyDict_GetItem(dict, key);
if (result == NULL) {
result = LOAD_OBJ(op.reg[2]);
}
Py_INCREF(result);
STORE_REG(op.reg[3], result);
}
};
struct IncRef: public RegOpImpl<RegOp<1>, IncRef> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
CHECK_VALID(LOAD_OBJ(op.reg[0]));
Py_INCREF(LOAD_OBJ(op.reg[0]));
}
};
struct DecRef: public RegOpImpl<RegOp<1>, DecRef> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
CHECK_VALID(LOAD_OBJ(op.reg[0]));
Py_DECREF(LOAD_OBJ(op.reg[0]));
}
};
struct LoadLocals: public RegOpImpl<RegOp<1>, LoadLocals> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
Py_INCREF(frame->locals());
STORE_REG(op.reg[0], frame->locals());
}
};
struct LoadGlobal: public RegOpImpl<RegOp<1>, LoadGlobal> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* key = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyObject* value = PyDict_GetItem(frame->globals(), key);
if (value != NULL) {
Py_INCREF(value);
STORE_REG(op.reg[0], value);
return;
}
value = PyDict_GetItem(frame->builtins(), key);
if (value != NULL) {
Py_INCREF(value);
STORE_REG(op.reg[0], value);
return;
}
throw RException(PyExc_NameError, "Global name %.200s not defined.", obj_to_str(key));
}
};
struct StoreGlobal: public RegOpImpl<RegOp<1>, StoreGlobal> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* key = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyObject* val = LOAD_OBJ(op.reg[0]);
PyDict_SetItem(frame->globals(), key, val);
}
};
struct DeleteGlobal: public RegOpImpl<RegOp<0>, DeleteGlobal> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<0>& op, Register* registers) {
PyObject* key = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyDict_DelItem(frame->globals(), key);
}
};
struct LoadName: public RegOpImpl<RegOp<1>, LoadName> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* r1 = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyObject* r2 = PyDict_GetItem(frame->locals(), r1);
if (r2 == NULL) {
r2 = PyDict_GetItem(frame->globals(), r1);
}
if (r2 == NULL) {
r2 = PyDict_GetItem(frame->builtins(), r1);
}
if (r2 == NULL) {
throw RException(PyExc_NameError, "Name %.200s not defined.", obj_to_str(r1));
}
Py_INCREF(r2);
STORE_REG(op.reg[0], r2);
}
};
struct StoreName: public RegOpImpl<RegOp<1>, StoreName> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* r1 = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyObject* r2 = LOAD_OBJ(op.reg[0]);
CHECK_VALID(r1);
CHECK_VALID(r2);
PyObject_SetItem(frame->locals(), r1, r2);
}
};
struct DeleteName: public RegOpImpl<RegOp<0>, DeleteName> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<0>& op, Register* registers) {
PyObject* key = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyObject_DelItem(frame->locals(), key);
}
};
// LOAD_FAST and STORE_FAST both perform the same operation in the register VM.
struct LoadFast: public RegOpImpl<RegOp<2>, LoadFast> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
Register& a = registers[op.reg[0]];
Register& b = registers[op.reg[1]];
a.incref();
b.decref();
b.store(a);
}
};
typedef LoadFast StoreFast;
struct StoreAttr: public RegOpImpl<RegOp<2>, StoreAttr> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* obj = LOAD_OBJ(op.reg[0]);
PyObject* key = PyTuple_GET_ITEM(frame->names(), op.arg);
PyObject* value = LOAD_OBJ(op.reg[1]);
CHECK_VALID(obj);
CHECK_VALID(key);
CHECK_VALID(value);
if (PyObject_SetAttr(obj, key, value) != 0) {
throw RException();
}
}
};
struct StoreSubscr: public RegOpImpl<RegOp<3>, StoreSubscr> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* key = LOAD_OBJ(op.reg[0]);
PyObject* list = LOAD_OBJ(op.reg[1]);
PyObject* value = LOAD_OBJ(op.reg[2]);
CHECK_VALID(key);
CHECK_VALID(list);
CHECK_VALID(value);
if (PyObject_SetItem(list, key, value) != 0) {
throw RException();
}
}
};
struct StoreSubscrList: public RegOpImpl<RegOp<3>, StoreSubscrList> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* list = LOAD_OBJ(op.reg[1]);
PyObject* value = LOAD_OBJ(op.reg[2]);
CHECK_VALID(list);
CHECK_VALID(value);
Register& idx_reg = registers[op.reg[0]];
if (idx_reg.get_type() != IntType) {
PyObject* idx_obj = LOAD_OBJ(op.reg[0]);
CHECK_VALID(idx_obj);
if (PyObject_SetItem(list, idx_obj, value) != 0) {
throw RException();
}
} else {
Py_ssize_t idx = idx_reg.as_int();
if (PyList_SetItem(list, idx, value) != 0) {
throw RException();
}
}
}
};
struct StoreSubscrDict: public RegOpImpl<RegOp<3>, StoreSubscrDict> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* key = LOAD_OBJ(op.reg[0]);
PyObject* list = LOAD_OBJ(op.reg[1]);
PyObject* value = LOAD_OBJ(op.reg[2]);
CHECK_VALID(key);
CHECK_VALID(list);
CHECK_VALID(value);
if (PyDict_SetItem(list, key, value) != 0) {
throw RException();
}
}
};
// Copied from ceval.cc:
#define ISINDEX(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
static int assign_slice(PyObject *u, PyObject *v, PyObject *w, PyObject *x) {
PyTypeObject *tp = u->ob_type;
PySequenceMethods *sq = tp->tp_as_sequence;
if (sq && sq->sq_ass_slice && ISINDEX(v) && ISINDEX(w)) {
Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
if (!_PyEval_SliceIndex(v, &ilow)) return -1;
if (!_PyEval_SliceIndex(w, &ihigh)) return -1;
if (x == NULL) return PySequence_DelSlice(u, ilow, ihigh);
else return PySequence_SetSlice(u, ilow, ihigh, x);
} else {
PyObject *slice = PySlice_New(v, w, NULL);
if (slice != NULL) {
int res;
if (x != NULL) res = PyObject_SetItem(u, slice, x);
else res = PyObject_DelItem(u, slice);
Py_DECREF(slice);
return res;
} else return -1;
}
}
struct StoreSlice: public RegOpImpl<RegOp<4>, StoreSlice> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<4>& op, Register* registers) {
PyObject* list = LOAD_OBJ(op.reg[0]);
PyObject* left = op.reg[1] != kInvalidRegister ? LOAD_OBJ(op.reg[1]) : NULL;
PyObject* right = op.reg[2] != kInvalidRegister ? LOAD_OBJ(op.reg[2]) : NULL;
PyObject* value = LOAD_OBJ(op.reg[3]);
if (assign_slice(list, left, right, value) != 0) {
throw RException();
}
}
};
struct ConstIndex: public RegOpImpl<RegOp<2>, ConstIndex> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* list = LOAD_OBJ(op.reg[0]);
uint8_t key = op.arg;
if (op.reg[1] == kInvalidRegister) {
return;
}
PyObject* pykey = PyInt_FromLong(key);
STORE_REG(op.reg[1], PyObject_GetItem(list, pykey));
Py_DECREF(pykey);
}
};
static PyDictObject* obj_getdictptr(PyObject* obj, PyTypeObject* type) {
Py_ssize_t dictoffset;
PyObject **dictptr;
dictoffset = type->tp_dictoffset;
if (dictoffset != 0) {
if (dictoffset < 0) {
Py_ssize_t tsize;
size_t size;
tsize = ((PyVarObject *) obj)->ob_size;
if (tsize < 0) tsize = -tsize;
size = _PyObject_VAR_SIZE(type, tsize);
dictoffset += (long) size;
Reg_AssertGt(dictoffset, 0);
Reg_AssertEq(dictoffset % SIZEOF_VOID_P, 0);
}
dictptr = (PyObject **) ((char *) obj + dictoffset);
return (PyDictObject*) *dictptr;
}
return NULL;
}
static size_t dict_getoffset(PyDictObject* dict, PyObject* key) {
long hash;
if (!PyString_CheckExact(key) || (hash = ((PyStringObject *) key)->ob_shash) == -1) {
hash = PyObject_Hash(key);
}
PyDictEntry* pos = dict->ma_lookup(dict, key, hash);
return pos - dict->ma_table;
}
// LOAD_ATTR is common enough to warrant inlining some common code.
// Most of this is taken from _PyObject_GenericGetAttrWithDict
static PyObject * obj_getattr(Evaluator* eval, RegOp<2>& op, PyObject *obj, PyObject *name) {
PyObjHelper<PyTypeObject*> type(Py_TYPE(obj) );
PyObjHelper<PyDictObject*> dict(obj_getdictptr(obj, type));
PyObject *descr = NULL;
#if GETATTR_HINTS
const Hint &op_hint = eval->hints[op.hint_pos];
// A hint for an instance dictionary lookup.
if (dict.val_ && op_hint.guard.dict_size == dict->ma_mask) {
const PyDictEntry &e(dict->ma_table[op_hint.version]);
if (e.me_key == name) {
Py_INCREF(e.me_value);
return e.me_value;
}
}
#endif
if (!PyString_Check(name)) {
throw RException(PyExc_SystemError, "attribute name must be string, not '%.200s'", Py_TYPE(name) ->tp_name);
}
if (type->tp_dict == NULL) {
if (PyType_Ready(type) < 0) {
throw RException();
}
}
// A hint for a type dictionary lookup, we've cached the 'descr' object.
// if (op_hint.guard.obj == type && op_hint.key == name && op_hint.version == type->tp_version_tag) {
// descr = op_hint.value;
// } else {
descr = _PyType_Lookup(type, name);
// }
descrgetfunc getter = NULL;
if (descr != NULL && PyType_HasFeature(descr->ob_type, Py_TPFLAGS_HAVE_CLASS)) {
getter = descr->ob_type->tp_descr_get;
if (getter != NULL && PyDescr_IsData(descr)) {
return getter(descr, obj, (PyObject*) type);
}
}
// Look for a match in our object dictionary
if (dict != NULL) {
PyObject* res = PyDict_GetItem(dict, name);
// We found a match. Create a hint for where to look next time.
if (res != NULL) {
#if GETATTR_HINTS
size_t hint_pos = hint_offset(type, name);
size_t dict_pos = dict_getoffset(dict, name);
Hint h;
h.guard.dict_size = dict->ma_mask;
h.key = name;
h.value = type;
h.version = dict_pos;
eval->hints[hint_pos] = h;
op.hint_pos = hint_pos;
#endif
Py_INCREF(res);
return res;
}
}
// Instance dictionary lookup failed, try to find a match in the class hierarchy.
if (getter != NULL) {
PyObject* res = getter(descr, obj, (PyObject*) type);
if (res != NULL) {
// size_t hint_pos = hint_offset(type, name);
// Hint h;
// h.guard.obj = type;
// h.key = name;
// h.value = descr;
// h.version = type->tp_version_tag;
// eval->hints[hint_pos] = h;
// op.hint_pos = hint_pos;
return res;
}
}
if (descr != NULL) {
return descr;
}
throw RException(PyExc_AttributeError, "'%.50s' object has no attribute '%.400s'", type->tp_name,
PyString_AS_STRING(name) );
}
struct LoadAttr: public RegOpImpl<RegOp<2>, LoadAttr> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* obj = LOAD_OBJ(op.reg[0]);
PyObject* name = PyTuple_GET_ITEM(frame->names(), op.arg);
PyObject* res = obj_getattr(eval, op, obj, name);
STORE_REG(op.reg[1], res);
}
};
struct LoadDeref: public RegOpImpl<RegOp<1>, LoadDeref> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* closure_cell = frame->freevars[op.arg];
PyObject* closure_value = PyCell_Get(closure_cell);
STORE_REG(op.reg[0], closure_value);
Py_INCREF(closure_value);
}
};
struct StoreDeref: public RegOpImpl<RegOp<1>, StoreDeref> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* value = LOAD_OBJ(op.reg[0]);
PyObject* dest_cell = frame->freevars[op.arg];
PyCell_Set(dest_cell, value);
}
};
struct LoadClosure: public RegOpImpl<RegOp<1>, LoadClosure> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* closure_cell = frame->freevars[op.arg];
Py_INCREF(closure_cell);
STORE_REG(op.reg[0], closure_cell);
}
};
struct MakeFunction: public VarArgsOpImpl<MakeFunction> {
static f_inline void _eval(Evaluator* eval, RegisterFrame* frame, VarRegOp *op, Register* registers) {
PyObject* code = LOAD_OBJ(op->reg[0]);
PyObject* func = PyFunction_New(code, frame->globals());
PyObject* defaults = PyTuple_New(op->arg);
for (int i = 0; i < op->arg; ++i) {
PyTuple_SetItem(defaults, i, LOAD_OBJ(op->reg[i + 1]));
}
PyFunction_SetDefaults(func, defaults);
STORE_REG(op->reg[op->arg + 1], func);
}
};
struct MakeClosure: public VarArgsOpImpl<MakeClosure> {
static f_inline void _eval(Evaluator* eval, RegisterFrame* frame, VarRegOp *op, Register* registers) {
// first register argument is the code object
// second is the closure args tuple
// rest of the registers are default argument values
PyObject* code = LOAD_OBJ(op->reg[0]);
PyObject* func = PyFunction_New(code, frame->globals());
PyObject* closure_values = LOAD_OBJ(op->reg[1]);
PyFunction_SetClosure(func, closure_values);
PyObject* defaults = PyTuple_New(op->arg);
for (int i = 0; i < op->arg; ++i) {
PyObject* val = LOAD_OBJ(op->reg[i + 2]);
Py_INCREF(val);
PyTuple_SetItem(defaults, i, val);
}
PyFunction_SetDefaults(func, defaults);
STORE_REG(op->reg[op->arg + 2], func);
}
};
template<bool HasVarArgs, bool HasKwDict>
struct CallFunction: public VarArgsOpImpl<CallFunction<HasVarArgs, HasKwDict> > {
static f_inline void _eval(Evaluator* eval, RegisterFrame* frame, VarRegOp *op, Register* registers) {
int na = op->arg & 0xff;
int nk = (op->arg >> 8) & 0xff;
int n = nk * 2 + na;
if (HasVarArgs) n++;
if (HasKwDict) n++;
int dst = op->reg[n + 1];
PyObject* fn = LOAD_OBJ(op->reg[0]);
Reg_AssertEq(n + 2, op->num_registers);
RegisterCode* code = NULL;
/* TODO:
* Actually accelerate object construction in Falcon by
* first creating the raw/unitialized object and then
* compiling the __init__ method of the called class.
*
* To actually get a performance gain from this we would need
* special instance dictionaries which store Falcon registers
* and only lazily construct PyObject representations when asked
* by other Python C API code.
*/
// Log_Info("Calling...");
if (!PyCFunction_Check(fn) &&
!PyClass_Check(fn) &&
!PyType_Check(fn)) {
// Log_Info("Compiling...");
code = eval->compiler->compile(fn);
}
if (code == NULL || nk > 0) {
// Log_Info("Going to Python for function %s", PyEval_GetFuncName(fn));
PyObject* args = PyTuple_New(na);
for (register int i = 0; i < na; ++i) {
PyObject* v = LOAD_OBJ(op->reg[i+1]);
Py_INCREF(v);
PyTuple_SET_ITEM(args, i, v);
}
PyObject* kwdict = NULL;
if (nk > 0) {
kwdict = PyDict_New();
for (register int i = na; i < nk * 2; i += 2) {
// starting at +1 since the first register was the fn
// so keyword args actually start at na+1
PyObject* k = LOAD_OBJ(op->reg[i+1]);
PyObject* v = LOAD_OBJ(op->reg[i+2]);
Reg_Assert(PyString_Check(k), "Expected key to be string");
char* kstr = PyString_AsString(k);
PyDict_SetItemString(kwdict, kstr, v);
//PyDict_SetItem(kwdict, k, v);
}
}
PyObject* res = NULL;
if (PyCFunction_Check(fn)) {
res = PyCFunction_Call(fn, args, kwdict);
} else {
res = PyObject_Call(fn, args, kwdict);
}
Py_DECREF(args);
if (res == NULL) {
throw RException();
}
STORE_REG(dst, res);
} else {
// Log_Info("Native call");
ObjVector args, kw;
args.resize(na);
for (register int i = 0; i < na; ++i) {
args[i].store(registers[op->reg[i + 1]]);
}
RegisterFrame f(code, fn, args, kw);
STORE_REG(dst, eval->eval(&f));
}
}
};
typedef CallFunction<false, false> CallFunctionSimple;
typedef CallFunction<true, false> CallFunctionVar;
typedef CallFunction<false, true> CallFunctionKw;
typedef CallFunction<true, true> CallFunctionVarKw;
struct GetIter: public RegOpImpl<RegOp<2>, GetIter> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* res = PyObject_GetIter(LOAD_OBJ(op.reg[0]));
STORE_REG(op.reg[1], res);
}
};
struct ForIter: public BranchOpImpl<BranchOp<2>, ForIter> {
static f_inline void _eval(Evaluator* eval, RegisterFrame *frame, BranchOp<2>& op, const char **pc,
Register* registers) {
CHECK_VALID(LOAD_OBJ(op.reg[0]));
PyObject* iter = PyIter_Next(LOAD_OBJ(op.reg[0]));
if (iter) {
STORE_REG(op.reg[1], iter);
*pc += sizeof(BranchOp<2> );
} else {
*pc = frame->instructions() + op.label;
}
}
};
struct JumpIfFalseOrPop: public BranchOpImpl<BranchOp<1>, JumpIfFalseOrPop> {
static f_inline void _eval(Evaluator* eval, RegisterFrame *frame, BranchOp<1>& op, const char **pc,
Register* registers) {
PyObject *r1 = LOAD_OBJ(op.reg[0]);
if (r1 == Py_False || (PyObject_IsTrue(r1) == 0)) {
// EVAL_LOG("Jumping: %s -> %d", obj_to_str(r1), op.label);
*pc = frame->instructions() + op.label;
} else {
*pc += sizeof(BranchOp<1>);
}
}
};
struct JumpIfTrueOrPop: public BranchOpImpl<BranchOp<1>, JumpIfTrueOrPop> {
static f_inline void _eval(Evaluator* eval, RegisterFrame *frame, BranchOp<1>& op, const char **pc,
Register* registers) {
PyObject* r1 = LOAD_OBJ(op.reg[0]);
if (r1 == Py_True || (PyObject_IsTrue(r1) == 1)) {
*pc = frame->instructions() + op.label;
} else {
*pc += sizeof(BranchOp<1>);
}
}
};
struct JumpAbsolute: public BranchOpImpl<BranchOp<0>, JumpAbsolute> {
static f_inline void _eval(Evaluator* eval, RegisterFrame *frame, BranchOp<0>& op, const char **pc,
Register* registers) {
EVAL_LOG("Jumping to: %d", op.label);
*pc = frame->instructions() + op.label;
}
};
struct BreakLoop: public BranchOpImpl<BranchOp<0>, BreakLoop> {
static f_inline void _eval(Evaluator* eval, RegisterFrame *frame, BranchOp<0>& op, const char **pc,
Register* registers) {
EVAL_LOG("Jumping to: %d", op.label);
*pc = frame->instructions() + op.label;
}
};
// Evaluation of RETURN_VALUE is special. g++ exceptions are excrutiatingly slow, so we
// can't use the exception mechanism to jump to our exit point. Instead, we return a value
// here and jump to the exit of our frame.
struct ReturnValue {
static f_inline Register* eval(Evaluator* eval, RegisterFrame* frame, const char* pc, Register* registers) {
RegOp<1>& op = *((RegOp<1>*) pc);
log_operation(frame, (RegOp<1>*)pc, registers, pc);
Register& r = registers[op.reg[0]];
r.incref();
return &r;
}
};
struct Nop: public RegOpImpl<RegOp<0>, Nop> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<0>& op, Register* registers) {
}
};
struct BuildTuple: public VarArgsOpImpl<BuildTuple> {
static f_inline void _eval(Evaluator* eval, RegisterFrame* frame, VarRegOp *op, Register* registers) {
register int count = op->arg;
PyObject* t = PyTuple_New(count);
for (register int i = 0; i < count; ++i) {
PyObject* v = LOAD_OBJ(op->reg[i]);
Py_INCREF(v);
PyTuple_SET_ITEM(t, i, v);
}
STORE_REG(op->reg[count], t);
}
};
struct BuildList: public VarArgsOpImpl<BuildList> {
static f_inline void _eval(Evaluator* eval, RegisterFrame* frame, VarRegOp *op, Register* registers) {
register int count = op->arg;
PyObject* t = PyList_New(count);
for (register int i = 0; i < count; ++i) {
PyObject* v = LOAD_OBJ(op->reg[i]);
Py_INCREF(v);
PyList_SET_ITEM(t, i, v);
}
STORE_REG(op->reg[count], t);
}
};
struct BuildMap: public RegOpImpl<RegOp<1>, BuildMap> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
// for now ignore the size hint in the op arg
PyObject* dict = PyDict_New();
STORE_REG(op.reg[0], dict);
}
};
struct BuildSlice: public RegOpImpl<RegOp<4>, BuildSlice> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<4>& op, Register* registers) {
PyObject* w = LOAD_OBJ(op.reg[0]);
PyObject* v = LOAD_OBJ(op.reg[1]);
PyObject* u = LOAD_OBJ(op.reg[2]);
STORE_REG(op.reg[3], PySlice_New(u, v, w))
}
};
struct BuildClass: public RegOpImpl<RegOp<4>, BuildClass> {
static void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<4>& op, Register* registers) {
PyObject* methods = LOAD_OBJ(op.reg[0]);
PyObject* bases = LOAD_OBJ(op.reg[1]);
PyObject* name = LOAD_OBJ(op.reg[2]);
// Begin: build_class from ceval.c
PyObject *metaclass = NULL, *result, *base;
if (PyDict_Check(methods)) metaclass = PyDict_GetItemString(methods, "__metaclass__");
if (metaclass != NULL)
Py_INCREF(metaclass);
else if (PyTuple_Check(bases) && PyTuple_GET_SIZE(bases) > 0) {
base = PyTuple_GET_ITEM(bases, 0);
metaclass = PyObject_GetAttrString(base, "__class__");
if (metaclass == NULL) {
PyErr_Clear();
metaclass = (PyObject *)base->ob_type;
Py_INCREF(metaclass);
}
}
else {
PyObject *g = PyEval_GetGlobals();
if (g != NULL && PyDict_Check(g))
metaclass = PyDict_GetItemString(g, "__metaclass__");
if (metaclass == NULL)
metaclass = (PyObject *) &PyClass_Type;
Py_INCREF(metaclass);
}
result = PyObject_CallFunctionObjArgs(metaclass, name, bases, methods, NULL);
// EVAL_LOG("Building a class -- methods: %s\n bases: %s\n name: %s\n result: %s",
// obj_to_str(methods), obj_to_str(bases), obj_to_str(name), obj_to_str(result));
Py_DECREF(metaclass);
if (result == NULL && PyErr_ExceptionMatches(PyExc_TypeError)) {
/* A type error here likely means that the user passed
in a base that was not a class (such the random module
instead of the random.random type). Help them out with
by augmenting the error message with more information.*/
PyObject *ptype, *pvalue, *ptraceback;
PyErr_Fetch(&ptype, &pvalue, &ptraceback);
if (PyString_Check(pvalue)) {
PyObject *newmsg;
newmsg = PyString_FromFormat("Error when calling the metaclass bases\n"
" %s",
PyString_AS_STRING(pvalue) );
if (newmsg != NULL) {
Py_DECREF(pvalue);
pvalue = newmsg;
}
}
PyErr_Restore(ptype, pvalue, ptraceback);
throw RException();
}
// End: build_class()
STORE_REG(op.reg[3], result);
}
};
struct StoreMap: public RegOpImpl<RegOp<3>, StoreMap> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* key = LOAD_OBJ(op.reg[0]);
PyObject* value = LOAD_OBJ(op.reg[1]);
PyObject* dict = LOAD_OBJ(op.reg[2]);
if (PyDict_SetItem(dict, key, value) != 0) {
throw RException();
}
}
};
struct PrintItem: public RegOpImpl<RegOp<2>, PrintItem> {
static void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* v = LOAD_OBJ(op.reg[0]);
PyObject* w = op.reg[1] != kInvalidRegister ? LOAD_OBJ(op.reg[1]) : PySys_GetObject((char*) "stdout");
int err = 0;
if (w != NULL && PyFile_SoftSpace(w, 0)) {
err = PyFile_WriteString(" ", w);
}
if (err == 0) {
err = PyFile_WriteObject(v, w, Py_PRINT_RAW);
}
if (err == 0) {
/* XXX move into writeobject() ? */
if (PyString_Check(v)) {
char *s = PyString_AS_STRING(v);
Py_ssize_t len = PyString_GET_SIZE(v);
if (len == 0 || !isspace(Py_CHARMASK(s[len-1]) ) || s[len - 1] == ' ') PyFile_SoftSpace(w, 1);
}
#ifdef Py_USING_UNICODE
else if (PyUnicode_Check(v)) {
Py_UNICODE *s = PyUnicode_AS_UNICODE(v);
Py_ssize_t len = PyUnicode_GET_SIZE(v);
if (len == 0 || !Py_UNICODE_ISSPACE(s[len-1]) || s[len - 1] == ' ') PyFile_SoftSpace(w, 1);
}
#endif
else PyFile_SoftSpace(w, 1);
}
if (err != 0) {
throw RException();
}
}
};
struct PrintNewline: public RegOpImpl<RegOp<1>, PrintNewline> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* w = op.reg[0] != kInvalidRegister ? LOAD_OBJ(op.reg[0]): PySys_GetObject((char*) "stdout");
int err = PyFile_WriteString("\n", w);
if (err == 0) PyFile_SoftSpace(w, 0);
}
};
struct ListAppend: public RegOpImpl<RegOp<2>, ListAppend> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyList_Append(LOAD_OBJ(op.reg[0]), LOAD_OBJ(op.reg[1]));
}
};
#define ISINDEX(x) ((x) == NULL || PyInt_Check(x) || PyLong_Check(x) || PyIndex_Check(x))
static PyObject * apply_slice(PyObject *u, PyObject *v, PyObject *w) {
PyTypeObject *tp = u->ob_type;
PySequenceMethods *sq = tp->tp_as_sequence;
if (sq && sq->sq_slice && ISINDEX(v) && ISINDEX(w)) {
Py_ssize_t ilow = 0, ihigh = PY_SSIZE_T_MAX;
if (!_PyEval_SliceIndex(v, &ilow)) return NULL;
if (!_PyEval_SliceIndex(w, &ihigh)) return NULL;
return PySequence_GetSlice(u, ilow, ihigh);
} else {
PyObject *slice = PySlice_New(v, w, NULL);
if (slice != NULL) {
PyObject *res = PyObject_GetItem(u, slice);
Py_DECREF(slice);
return res;
}
return NULL;
}
}
struct Slice: public RegOpImpl<RegOp<4>, Slice> {
static f_inline void _eval(Evaluator *eval, RegisterFrame* frame, RegOp<4>& op, Register* registers) {
PyObject* list = LOAD_OBJ(op.reg[0]);
PyObject* left = op.reg[1] != kInvalidRegister ? LOAD_OBJ(op.reg[1]) : NULL;
PyObject* right = op.reg[2] != kInvalidRegister ? LOAD_OBJ(op.reg[2]) : NULL;
PyObject* result = apply_slice(list, left, right);
if (!result) {
throw RException();
}
STORE_REG(op.reg[3], result);
}
};
template<int Opcode>
struct BadOp {
static n_inline void eval(Evaluator *eval, RegisterFrame* frame, Register* registers) {
const char* name = OpUtil::name(Opcode);
throw RException(PyExc_SystemError, "Bad opcode %s", name);
}
};
// Imports
struct ImportName: public RegOpImpl<RegOp<3>, ImportName> {
static void _eval(Evaluator* eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
PyObject* name = PyTuple_GET_ITEM(frame->names(), op.arg) ;
PyObject* import = PyDict_GetItemString(frame->builtins(), "__import__");
if (import == NULL) {
throw RException(PyExc_ImportError, "__import__ not found in builtins.");
}
PyObject* args = NULL;
PyObject* v = LOAD_OBJ(op.reg[0]);
PyObject* u = LOAD_OBJ(op.reg[1]);
if (PyInt_AsLong(u) != -1 || PyErr_Occurred()) {
PyErr_Clear();
args = PyTuple_Pack(5, name, frame->globals(), frame->locals(), v, u);
} else {
args = PyTuple_Pack(4, name, frame->globals(), frame->locals(), v);
}
PyObject* res = PyEval_CallObject(import, args);
if (res == NULL) {
PyErr_Print();
throw RException(PyExc_ImportError, "Failed to import name %s",
PyString_AsString(name));
}
// band-aid to prevent segfaults, not sure why this incref makes things work
Py_IncRef(res);
STORE_REG(op.reg[2], res);
}
};
struct ImportStar: public RegOpImpl<RegOp<1>, ImportStar> {
static void _eval(Evaluator* eval, RegisterFrame* frame, RegOp<1>& op, Register* registers) {
PyObject* module = LOAD_OBJ(op.reg[0]);
PyObject *all = PyObject_GetAttrString(module, "__all__");
bool skip_leading_underscores = (all == NULL);
if (all == NULL) {
PyObject* dict = PyObject_GetAttrString(module, "__dict__");
all = PyMapping_Keys(dict);
}
for (int pos = 0, err = 0;; pos++) {
PyObject* name = PySequence_GetItem(all, pos);
if (name == NULL) {
if (!PyErr_ExceptionMatches(PyExc_IndexError)) err = -1;
else PyErr_Clear();
break;
}
if (skip_leading_underscores && PyString_Check(name) && PyString_AS_STRING(name) [0] == '_') {
Py_DECREF(name);
continue;
}
PyObject* value = PyObject_GetAttr(module, name);
if (value == NULL) err = -1;
else {
PyObject_SetItem(frame->locals(), name, value);
}
Py_DECREF(name);
Py_XDECREF(value);
if (err != 0) break;
}
}
};
struct ImportFrom: public RegOpImpl<RegOp<2>, ImportFrom> {
static void _eval(Evaluator* eval, RegisterFrame* frame, RegOp<2>& op, Register* registers) {
PyObject* name = PyTuple_GetItem(frame->names(), op.arg);
PyObject* module = LOAD_OBJ(op.reg[0]);
Py_XDECREF(LOAD_OBJ(op.reg[1]));
PyObject* val = PyObject_GetAttr(module, name);
if (val == NULL) {
if (PyErr_ExceptionMatches(PyExc_AttributeError)) {
throw RException(PyExc_ImportError, "cannot import name %.230s", PyString_AsString(name));
} else {
throw RException();
}
}
STORE_REG(op.reg[1], val);
}
};
struct SetupExcept: public BranchOpImpl<BranchOp<0>, SetupExcept> {
static f_inline void _eval(Evaluator* eval, RegisterFrame *frame, BranchOp<0>& op, const char **pc,
Register* registers) {
EVAL_LOG("Pushing handler: %d", op.label);
frame->exc_handlers_.push_back(op.label);
*pc += sizeof(BranchOp<0> );
}
};
typedef SetupExcept SetupFinally;
struct RaiseVarArgs: public RegOpImpl<RegOp<3>, RaiseVarArgs> {
static void _eval(Evaluator* eval, RegisterFrame* frame, RegOp<3>& op, Register* registers) {
// Log_Info("Raising exception: %d %d %d", op.reg[0], op.reg[1], op.reg[2]);
PyObject* type;
PyObject* value;
PyObject* tb;
// Jump to the nearest exception handler.
type = LOAD_OBJ(op.reg[0]);
if (op.reg[1] != kInvalidRegister) {
value = LOAD_OBJ(op.reg[1]);
} else {
value = Py_None;
}
if (op.reg[2] != kInvalidRegister) {
tb = LOAD_OBJ(op.reg[2]);
} else {
tb = Py_None;
}
throw RException(type, value, tb);
}
};
#define DISPATCH_HEADER\
dispatch_header: try {
#define CONCAT(...) __VA_ARGS__
#if USE_THREADED_DISPATCH == 0
#define JUMP_TO_NEXT goto dispatch_header;
#define START_DISPATCH switch (((OpHeader*)pc)->code) {
#define END_DISPATCH } JUMP_TO_NEXT
#define FALLTHROUGH(opname) case opname:
#define START_OP(opname) case opname: {
#define END_OP(opname) break; }
#else
#define JUMP_TO_NEXT goto *labels[((OpHeader*)pc)->code]
#define START_DISPATCH JUMP_TO_NEXT;
#define END_DISPATCH
#define _FALLTHROUGH(opname) op_ ## opname:
#define FALLTHROUGH(opname) _FALLTHROUGH(opname)
#define _START_OP(opname) op_##opname: {
#define START_OP(opname) _START_OP(opname)
#define END_OP(opname) JUMP_TO_NEXT; }
#define _OFFSET(opname) &&op_##opname
#define OFFSET(opname) _OFFSET(opname)
#endif
#define _DEFINE_OP(opname, impl)\
pc = impl::eval(this, frame, pc, registers);\
#define DEFINE_OP(opname, impl)\
START_OP(opname)\
_DEFINE_OP(opname, impl)\
END_OP(opname)
#define BAD_OP(opname)\
START_OP(opname)\
BadOp<opname>::eval(this, frame, registers);\
END_OP(opname)
#define BINARY_OP3(opname, objfn, intfn, can_overflow)\
START_OP(opname)\
_DEFINE_OP(opname, BinaryOpWithSpecialization<CONCAT(opname, objfn, intfn, can_overflow)>)\
END_OP(opname)
#define BINARY_OP2(opname, objfn)\
START_OP(opname)\
_DEFINE_OP(opname, BinaryOp<CONCAT(opname, objfn)>)\
END_OP(opname)
#define UNARY_OP2(opname, objfn)\
START_OP(opname)\
_DEFINE_OP(opname, UnaryOp<CONCAT(opname, objfn)>)\
END_OP(opname)
Register Evaluator::eval(RegisterFrame* f) {
register RegisterFrame* frame = f;
register Register* registers asm("r15") = frame->registers;
register const char* pc asm("r14") = frame->instructions();
Reg_Assert(frame != NULL, "NULL frame object.");
Register* result;
// The index of each offset MUST correspond to the opcode number!
#if USE_THREADED_DISPATCH == 1
static const void* labels[] = {
OFFSET(STOP_CODE),
OFFSET(POP_TOP),
OFFSET(ROT_TWO),
OFFSET(ROT_THREE),
OFFSET(DUP_TOP),
OFFSET(ROT_FOUR),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(NOP),
OFFSET(UNARY_POSITIVE),
OFFSET(UNARY_NEGATIVE),
OFFSET(UNARY_NOT),
OFFSET(UNARY_CONVERT),
OFFSET(STOP_CODE),
OFFSET(UNARY_INVERT),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(BINARY_POWER),
OFFSET(BINARY_MULTIPLY),
OFFSET(BINARY_DIVIDE),
OFFSET(BINARY_MODULO),
OFFSET(BINARY_ADD),
OFFSET(BINARY_SUBTRACT),
OFFSET(BINARY_SUBSCR),
OFFSET(BINARY_FLOOR_DIVIDE),
OFFSET(BINARY_TRUE_DIVIDE),
OFFSET(INPLACE_FLOOR_DIVIDE),
OFFSET(INPLACE_TRUE_DIVIDE),
OFFSET(SLICE),
OFFSET(SLICE),
OFFSET(SLICE),
OFFSET(SLICE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STORE_SLICE),
OFFSET(STORE_SLICE),
OFFSET(STORE_SLICE),
OFFSET(STORE_SLICE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(DELETE_SLICE),
OFFSET(DELETE_SLICE),
OFFSET(DELETE_SLICE),
OFFSET(DELETE_SLICE),
OFFSET(STORE_MAP),
OFFSET(INPLACE_ADD),
OFFSET(INPLACE_SUBTRACT),
OFFSET(INPLACE_MULTIPLY),
OFFSET(INPLACE_DIVIDE),
OFFSET(INPLACE_MODULO),
OFFSET(STORE_SUBSCR),
OFFSET(DELETE_SUBSCR),
OFFSET(BINARY_LSHIFT),
OFFSET(BINARY_RSHIFT),
OFFSET(BINARY_AND),
OFFSET(BINARY_XOR),
OFFSET(BINARY_OR),
OFFSET(INPLACE_POWER),
OFFSET(GET_ITER),
OFFSET(STOP_CODE),
OFFSET(PRINT_EXPR),
OFFSET(PRINT_ITEM),
OFFSET(PRINT_NEWLINE),
OFFSET(PRINT_ITEM_TO),
OFFSET(PRINT_NEWLINE_TO),
OFFSET(INPLACE_LSHIFT),
OFFSET(INPLACE_RSHIFT),
OFFSET(INPLACE_AND),
OFFSET(INPLACE_XOR),
OFFSET(INPLACE_OR),
OFFSET(BREAK_LOOP),
OFFSET(WITH_CLEANUP),
OFFSET(LOAD_LOCALS),
OFFSET(RETURN_VALUE),
OFFSET(IMPORT_STAR),
OFFSET(EXEC_STMT),
OFFSET(YIELD_VALUE),
OFFSET(POP_BLOCK),
OFFSET(END_FINALLY),
OFFSET(BUILD_CLASS),
OFFSET(STORE_NAME),
OFFSET(DELETE_NAME),
OFFSET(UNPACK_SEQUENCE),
OFFSET(FOR_ITER),
OFFSET(LIST_APPEND),
OFFSET(STORE_ATTR),
OFFSET(DELETE_ATTR),
OFFSET(STORE_GLOBAL),
OFFSET(DELETE_GLOBAL),
OFFSET(DUP_TOPX),
OFFSET(LOAD_CONST),
OFFSET(LOAD_NAME),
OFFSET(BUILD_TUPLE),
OFFSET(BUILD_LIST),
OFFSET(BUILD_SET),
OFFSET(BUILD_MAP),
OFFSET(LOAD_ATTR),
OFFSET(COMPARE_OP),
OFFSET(IMPORT_NAME),
OFFSET(IMPORT_FROM),
OFFSET(JUMP_FORWARD),
OFFSET(JUMP_IF_FALSE_OR_POP),
OFFSET(JUMP_IF_TRUE_OR_POP),
OFFSET(JUMP_ABSOLUTE),
OFFSET(POP_JUMP_IF_FALSE),
OFFSET(POP_JUMP_IF_TRUE),
OFFSET(LOAD_GLOBAL),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(CONTINUE_LOOP),
OFFSET(SETUP_LOOP),
OFFSET(SETUP_EXCEPT),
OFFSET(SETUP_FINALLY),
OFFSET(STOP_CODE),
OFFSET(LOAD_FAST),
OFFSET(STORE_FAST),
OFFSET(DELETE_FAST),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(RAISE_VARARGS),
OFFSET(CALL_FUNCTION),
OFFSET(MAKE_FUNCTION),
OFFSET(BUILD_SLICE),
OFFSET(MAKE_CLOSURE),
OFFSET(LOAD_CLOSURE),
OFFSET(LOAD_DEREF),
OFFSET(STORE_DEREF),
OFFSET(STOP_CODE),
OFFSET(STOP_CODE),
OFFSET(CALL_FUNCTION_VAR),
OFFSET(CALL_FUNCTION_KW),
OFFSET(CALL_FUNCTION_VAR_KW),
OFFSET(SETUP_WITH),
OFFSET(STOP_CODE),
OFFSET(EXTENDED_ARG),
OFFSET(SET_ADD),
OFFSET(MAP_ADD),
OFFSET(INCREF),
OFFSET(DECREF),
OFFSET(CONST_INDEX),
OFFSET(BINARY_SUBSCR_LIST),
OFFSET(BINARY_SUBSCR_DICT),
OFFSET(STORE_SUBSCR_LIST),
OFFSET(STORE_SUBSCR_DICT),
OFFSET(DICT_CONTAINS),
OFFSET(DICT_GET),
OFFSET(DICT_GET_DEFAULT),
};
#endif
DISPATCH_HEADER
START_DISPATCH
START_OP(RETURN_VALUE)
result = ReturnValue::eval(this, frame, pc, registers);
goto done;\
END_OP(RETURN_VALUE)
START_OP(STOP_CODE)
EVAL_LOG("Jump to invalid opcode.");
throw RException(PyExc_SystemError, "Invalid jump.");
END_OP(STOP_CODE)
BINARY_OP3(BINARY_MULTIPLY, PyNumber_Multiply, IntegerOps::mul, true);
BINARY_OP3(BINARY_DIVIDE, PyNumber_Divide, IntegerOps::div, true);
BINARY_OP3(BINARY_ADD, PyNumber_Add, IntegerOps::add, true);
BINARY_OP3(BINARY_SUBTRACT, PyNumber_Subtract, IntegerOps::sub, true);
BINARY_OP3(BINARY_OR, PyNumber_Or, IntegerOps::Or, false);
BINARY_OP3(BINARY_XOR, PyNumber_Xor, IntegerOps::Xor, false);
BINARY_OP3(BINARY_AND, PyNumber_And, IntegerOps::And, false);
BINARY_OP3(BINARY_RSHIFT, PyNumber_Rshift, IntegerOps::Rshift, false);
BINARY_OP3(BINARY_LSHIFT, PyNumber_Lshift, IntegerOps::Lshift, false);
BINARY_OP2(BINARY_TRUE_DIVIDE, PyNumber_TrueDivide);
BINARY_OP2(BINARY_FLOOR_DIVIDE, PyNumber_FloorDivide);
DEFINE_OP(BINARY_POWER, BinaryPower);
DEFINE_OP(BINARY_MODULO, BinaryModulo);
DEFINE_OP(BINARY_SUBSCR, BinarySubscr);
DEFINE_OP(BINARY_SUBSCR_LIST, BinarySubscrList);
DEFINE_OP(BINARY_SUBSCR_DICT, BinarySubscrDict);
DEFINE_OP(CONST_INDEX, ConstIndex);
BINARY_OP3(INPLACE_MULTIPLY, PyNumber_InPlaceMultiply, IntegerOps::mul, true);
BINARY_OP3(INPLACE_DIVIDE, PyNumber_InPlaceDivide, IntegerOps::div, true);
BINARY_OP3(INPLACE_ADD, PyNumber_InPlaceAdd, IntegerOps::add, true);
BINARY_OP3(INPLACE_SUBTRACT, PyNumber_InPlaceSubtract, IntegerOps::sub, true);
BINARY_OP3(INPLACE_MODULO, PyNumber_InPlaceRemainder, IntegerOps::mod, true);
BINARY_OP2(INPLACE_OR, PyNumber_InPlaceOr);
BINARY_OP2(INPLACE_XOR, PyNumber_InPlaceXor);
BINARY_OP2(INPLACE_AND, PyNumber_InPlaceAnd);
BINARY_OP2(INPLACE_RSHIFT, PyNumber_InPlaceRshift);
BINARY_OP2(INPLACE_LSHIFT, PyNumber_InPlaceLshift);
BINARY_OP2(INPLACE_TRUE_DIVIDE, PyNumber_InPlaceTrueDivide);
BINARY_OP2(INPLACE_FLOOR_DIVIDE, PyNumber_InPlaceFloorDivide);
DEFINE_OP(INPLACE_POWER, InplacePower);
UNARY_OP2(UNARY_INVERT, PyNumber_Invert);
UNARY_OP2(UNARY_CONVERT, PyObject_Repr);
UNARY_OP2(UNARY_NEGATIVE, PyNumber_Negative);
UNARY_OP2(UNARY_POSITIVE, PyNumber_Positive);
DEFINE_OP(UNARY_NOT, UnaryNot);
DEFINE_OP(LOAD_FAST, LoadFast);
DEFINE_OP(LOAD_LOCALS, LoadLocals);
DEFINE_OP(LOAD_NAME, LoadName);
DEFINE_OP(LOAD_ATTR, LoadAttr);
DEFINE_OP(STORE_NAME, StoreName);
DEFINE_OP(STORE_ATTR, StoreAttr);
DEFINE_OP(STORE_SUBSCR, StoreSubscr);
DEFINE_OP(STORE_SUBSCR_LIST, StoreSubscrList);
DEFINE_OP(STORE_SUBSCR_DICT, StoreSubscrDict);
DEFINE_OP(STORE_FAST, StoreFast);
DEFINE_OP(STORE_SLICE, StoreSlice);
DEFINE_OP(LOAD_GLOBAL, LoadGlobal);
DEFINE_OP(STORE_GLOBAL, StoreGlobal);
DEFINE_OP(DELETE_GLOBAL, DeleteGlobal);
DEFINE_OP(DELETE_NAME, DeleteName);
DEFINE_OP(LOAD_CLOSURE, LoadClosure);
DEFINE_OP(LOAD_DEREF, LoadDeref);
DEFINE_OP(STORE_DEREF, StoreDeref);
DEFINE_OP(GET_ITER, GetIter);
DEFINE_OP(FOR_ITER, ForIter);
DEFINE_OP(BREAK_LOOP, BreakLoop);
DEFINE_OP(BUILD_TUPLE, BuildTuple);
DEFINE_OP(BUILD_LIST, BuildList);
DEFINE_OP(BUILD_MAP, BuildMap);
DEFINE_OP(BUILD_SLICE, BuildSlice);
DEFINE_OP(STORE_MAP, StoreMap);
DEFINE_OP(PRINT_NEWLINE, PrintNewline);
DEFINE_OP(PRINT_NEWLINE_TO, PrintNewline);
DEFINE_OP(PRINT_ITEM, PrintItem);
DEFINE_OP(PRINT_ITEM_TO, PrintItem);
DEFINE_OP(CALL_FUNCTION, CallFunctionSimple);
DEFINE_OP(CALL_FUNCTION_VAR, CallFunctionVar);
DEFINE_OP(CALL_FUNCTION_KW, CallFunctionKw);
DEFINE_OP(CALL_FUNCTION_VAR_KW, CallFunctionVarKw);
FALLTHROUGH(POP_JUMP_IF_FALSE);
DEFINE_OP(JUMP_IF_FALSE_OR_POP, JumpIfFalseOrPop);
FALLTHROUGH(POP_JUMP_IF_TRUE);
DEFINE_OP(JUMP_IF_TRUE_OR_POP, JumpIfTrueOrPop);
DEFINE_OP(JUMP_ABSOLUTE, JumpAbsolute);
DEFINE_OP(COMPARE_OP, CompareOp);
DEFINE_OP(INCREF, IncRef);
DEFINE_OP(DECREF, DecRef);
DEFINE_OP(LIST_APPEND, ListAppend);
DEFINE_OP(DICT_CONTAINS, DictContains);
DEFINE_OP(DICT_GET, DictGet);
DEFINE_OP(DICT_GET_DEFAULT, DictGetDefault);
DEFINE_OP(SLICE, Slice);
DEFINE_OP(IMPORT_STAR, ImportStar);
DEFINE_OP(IMPORT_FROM, ImportFrom);
DEFINE_OP(IMPORT_NAME, ImportName);
DEFINE_OP(MAKE_FUNCTION, MakeFunction);
DEFINE_OP(MAKE_CLOSURE, MakeClosure);
DEFINE_OP(BUILD_CLASS, BuildClass);
DEFINE_OP(SETUP_EXCEPT, SetupExcept);
DEFINE_OP(SETUP_FINALLY, SetupFinally);
DEFINE_OP(RAISE_VARARGS, RaiseVarArgs);
BAD_OP(SETUP_LOOP);
BAD_OP(POP_BLOCK);
BAD_OP(LOAD_CONST);
BAD_OP(JUMP_FORWARD);
BAD_OP(MAP_ADD);
BAD_OP(SET_ADD);
BAD_OP(EXTENDED_ARG);
BAD_OP(SETUP_WITH);
BAD_OP(DELETE_FAST);
BAD_OP(CONTINUE_LOOP);
BAD_OP(BUILD_SET);
BAD_OP(DUP_TOPX);
BAD_OP(DELETE_ATTR);
BAD_OP(UNPACK_SEQUENCE);
BAD_OP(END_FINALLY);
BAD_OP(YIELD_VALUE);
BAD_OP(EXEC_STMT);
BAD_OP(WITH_CLEANUP);
BAD_OP(PRINT_EXPR);
BAD_OP(DELETE_SUBSCR);
BAD_OP(DELETE_SLICE);
BAD_OP(NOP);
BAD_OP(ROT_FOUR);
BAD_OP(DUP_TOP);
BAD_OP(ROT_THREE);
BAD_OP(ROT_TWO);
BAD_OP(POP_TOP);
END_DISPATCH
} catch (const RException &error) {
if (!frame->exc_handlers_.empty()) {
int handler_offset = frame->exc_handlers_.pop();
EVAL_LOG("Jumping to handler: %d", handler_offset);
pc = frame->instructions() + handler_offset;
JUMP_TO_NEXT;
}
Log_Info("ERROR: Leaving frame: %s", frame->str().c_str());
if (error.exception != NULL && !PyErr_Occurred()) {
PyErr_SetObject(error.exception, error.value);
}
PyFrameObject* py_frame = PyFrame_New(PyThreadState_GET(),
frame->code->code(),
frame->globals(),
frame->locals());
py_frame->f_lineno = 0;
PyTraceBack_Here(py_frame);
throw RException();
}
done: {
// EVAL_LOG("SUCCESS: Leaving frame: %s; result %s",
// frame->str().c_str(), obj_to_str(result->as_obj()));
return *result;
}
}
| 30.688577 | 136 | 0.64964 | codeclimate-testing |
03e190045fc10fc3452fbecb0cb3a9cb239152fc | 1,451 | hh | C++ | z2/inc/LZespolona.hh | PatrykAlexGajda/TestLiczbZespolonych | 0b070182368e64aff405d16d2461e8ed75b4d1f2 | [
"MIT"
] | null | null | null | z2/inc/LZespolona.hh | PatrykAlexGajda/TestLiczbZespolonych | 0b070182368e64aff405d16d2461e8ed75b4d1f2 | [
"MIT"
] | null | null | null | z2/inc/LZespolona.hh | PatrykAlexGajda/TestLiczbZespolonych | 0b070182368e64aff405d16d2461e8ed75b4d1f2 | [
"MIT"
] | null | null | null | #ifndef LZESPOLONA_HH
#define LZESPOLONA_HH
#include "Statystyka.hh"
#include <iostream>
/*! Plik zawiera definicje struktury LZesplona oraz zapowiedzi
* przeciazen operatorow arytmetycznych dzialajacych na tej
* strukturze. */
/*! Modeluje pojecie liczby zespolonej */
struct LZespolona {
double re; /*! Pole repezentuje czesc rzeczywista. */
double im; /*! Pole repezentuje czesc urojona. */
};
/* Naglowki funkcji dzialajacych na liczbach zespolonych
lub liczacych je na podstawie zawartosci struktury LZespolona */
LZespolona Utworz(double x, double y);
LZespolona Sprzezenie (LZespolona Skl);
double Modul(LZespolona Skl);
/* Naglowki przeciazen operatorow ktore pozwalaja im operowac na strukturze
liczb zespolonych */
std::ostream &operator<<(std::ostream &str, const LZespolona &zesp);
std::istream &operator>>(std::istream &str, LZespolona &zesp);
/* Naglowki przeciazen operatorow ktore pozwalaja im obliczac wyniki
wyrazen zespolonych. */
LZespolona operator + (LZespolona Skl1, LZespolona Skl2);
LZespolona operator - (LZespolona Skl1, LZespolona Skl2);
LZespolona operator * (LZespolona Skl1, LZespolona Skl2);
LZespolona operator / (LZespolona Skl1, LZespolona Skl2);
LZespolona operator / (LZespolona Skl, double r);
/* Naglowki przeciazen operatorow porownujacych liczby zespolone. */
bool operator == (LZespolona Skl1, LZespolona Skl2);
bool operator != (LZespolona Skl1, LZespolona Skl2);
#endif
| 30.87234 | 75 | 0.7643 | PatrykAlexGajda |
03e3ef5daddd90928567222cdc393c2dd7126773 | 47 | cpp | C++ | Physx.NetCore/Source/ContactPatch.cpp | ronbrogan/Physx.NetCore | ac788494b6aefc4b6633c46e857f199e6ab0a47a | [
"MIT"
] | 187 | 2015-01-02T15:58:10.000Z | 2022-02-20T05:23:13.000Z | PhysX.Net-3.4/PhysX.Net-3/Source/ContactPatch.cpp | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | 37 | 2015-01-10T04:38:23.000Z | 2022-03-18T00:52:27.000Z | PhysX.Net-3.4/PhysX.Net-3/Source/ContactPatch.cpp | Golangltd/PhysX.Net | fb71e0422d441a16a05ed51348d8afb0328d4b90 | [
"MIT"
] | 63 | 2015-01-11T12:12:44.000Z | 2022-02-05T14:12:49.000Z | #include "StdAfx.h"
#include "ContactPatch.h"
| 11.75 | 25 | 0.723404 | ronbrogan |
03e63dae25e3b1a91752f52f0d52243f14172447 | 572 | cpp | C++ | source/ShaderAST/Stmt/StmtSpecialisationConstantDecl.cpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | 148 | 2018-10-11T16:51:37.000Z | 2022-03-26T13:55:08.000Z | source/ShaderAST/Stmt/StmtSpecialisationConstantDecl.cpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | 30 | 2019-11-30T11:43:07.000Z | 2022-01-25T21:09:47.000Z | source/ShaderAST/Stmt/StmtSpecialisationConstantDecl.cpp | Praetonus/ShaderWriter | 1c5b3961e3e1b91cb7158406998519853a4add07 | [
"MIT"
] | 8 | 2020-04-17T13:18:30.000Z | 2021-11-20T06:24:44.000Z | /*
See LICENSE file in root folder
*/
#include "ShaderAST/Stmt/StmtSpecialisationConstantDecl.hpp"
#include "ShaderAST/Stmt/StmtVisitor.hpp"
namespace ast::stmt
{
SpecialisationConstantDecl::SpecialisationConstantDecl( var::VariablePtr variable
, uint32_t location
, expr::LiteralPtr value )
: Stmt{ Kind::eSpecialisationConstantDecl }
, m_variable{ std::move( variable ) }
, m_location{ location }
, m_value{ std::move( value ) }
{
}
void SpecialisationConstantDecl::accept( VisitorPtr vis )
{
vis->visitSpecialisationConstantDeclStmt( this );
}
}
| 22.88 | 82 | 0.744755 | Praetonus |
03e6eb8645c643bc5dc467bb8e34cd43d88a9508 | 35 | cpp | C++ | CullingModule/MaskedSWOcclusionCulling/Utility/DepthValueComputer.cpp | SungJJinKang/Parallel_Culling | 17d1302f500bd38df75583c81a7091b975a3ef91 | [
"MIT"
] | 10 | 2021-12-25T09:22:39.000Z | 2022-02-27T19:39:45.000Z | CullingModule/MaskedSWOcclusionCulling/Utility/DepthValueComputer.cpp | SungJJinKang/Parallel_Culling | 17d1302f500bd38df75583c81a7091b975a3ef91 | [
"MIT"
] | 1 | 2021-11-17T03:15:13.000Z | 2021-11-18T02:51:55.000Z | CullingModule/MaskedSWOcclusionCulling/Utility/DepthValueComputer.cpp | SungJJinKang/Parallel_Culling | 17d1302f500bd38df75583c81a7091b975a3ef91 | [
"MIT"
] | 1 | 2022-01-09T23:14:30.000Z | 2022-01-09T23:14:30.000Z | #include "DepthValueComputer.h"
| 7 | 31 | 0.742857 | SungJJinKang |
03e7f62ed784909e14a6b30b8ec786f1040972bf | 2,270 | cpp | C++ | Thread.Win32/ThreadBase/main.cpp | Phoebus-Ma/Win32-Helper | c2a895c4bc06c0904d74a50c1656c36fcf30d8f0 | [
"MIT"
] | null | null | null | Thread.Win32/ThreadBase/main.cpp | Phoebus-Ma/Win32-Helper | c2a895c4bc06c0904d74a50c1656c36fcf30d8f0 | [
"MIT"
] | null | null | null | Thread.Win32/ThreadBase/main.cpp | Phoebus-Ma/Win32-Helper | c2a895c4bc06c0904d74a50c1656c36fcf30d8f0 | [
"MIT"
] | null | null | null | /**
* Win32 Thread sample code.
*
* License - MIT.
*/
#include <iostream>
#include <Windows.h>
/**
* ThreadTestHandler - Thread callback function.
*/
DWORD WINAPI
ThreadTestHandler(LPVOID lpParam)
{
int id = *(int *)lpParam;
for (int i = 0; i < 5; i++)
{
std::cout << "ID: " << id << ", Loop: " << i << std::endl;
Sleep(1000);
}
return 0;
}
/**
* MultiThreadTest - Multi thread test.
*/
int
MultiThreadTest(int threadCount)
{
int i = 0;
int status = 0;
HANDLE *pHandles = NULL;
pHandles = new HANDLE[threadCount];
/* Create thread. */
for (i = 0; i < threadCount; i++)
{
pHandles[i] = CreateThread(
NULL,
0,
ThreadTestHandler,
&pHandles[i],
CREATE_SUSPENDED,
NULL);
if (NULL == pHandles[i])
{
status = -1;
std::cout << "Error in CreateThread.\n";
goto err_mul_create;
}
}
/* Awake all threads.. */
for (i = 0; i < threadCount; i++)
ResumeThread(pHandles[i]);
/* Wait multi threads done.. */
WaitForMultipleObjects(threadCount, pHandles, TRUE, INFINITE);
err_mul_create:
/* Close handle. */
for (i = 0; i < threadCount; i++)
{
if (NULL != pHandles[i])
CloseHandle(pHandles[i]);
}
delete[] pHandles;
return status;
}
/**
* SingleThreadTest - Single thread test.
*/
int
SingleThreadTest()
{
int id = 1;
int status = 0;
HANDLE thrdHandle = NULL;
/* Create thread. */
thrdHandle = CreateThread(
NULL,
0,
ThreadTestHandler,
&id,
CREATE_SUSPENDED,
NULL);
if (NULL == thrdHandle)
{
status = -1;
std::cout << "Error in CreateThread.\n";
goto err_sin_create;
}
/* Awake thread. */
ResumeThread(thrdHandle);
/* Wait thread done. */
WaitForSingleObject(thrdHandle, INFINITE);
/* Close handle. */
CloseHandle(thrdHandle);
err_sin_create:
return status;
}
/**
* Main function.
*/
int
main(void)
{
std::cout << "single thread test.\n";
SingleThreadTest();
std::cout << "multi thread test.\n";
MultiThreadTest(5);
return 0;
}
| 17.19697 | 66 | 0.534361 | Phoebus-Ma |
03e809b3766f2c5c84fea836248e9f0f3208fa45 | 13,449 | cc | C++ | app/GL/GLSpineElement.cc | hailongz/kk-game | 56463c13347a5608e54ae0a069b0b9263f32d7c8 | [
"MIT"
] | null | null | null | app/GL/GLSpineElement.cc | hailongz/kk-game | 56463c13347a5608e54ae0a069b0b9263f32d7c8 | [
"MIT"
] | null | null | null | app/GL/GLSpineElement.cc | hailongz/kk-game | 56463c13347a5608e54ae0a069b0b9263f32d7c8 | [
"MIT"
] | null | null | null | //
// GLSpineElement.cc
// KKGame
//
// Created by zhanghailong on 2018/5/2.
// Copyright © 2018年 kkmofang.cn. All rights reserved.
//
#include "kk-config.h"
#include "GLSpineElement.h"
#if defined(KK_PLATFORM_IOS)
#include <KKObject/KKObject.h>
#else
#include "kk-string.h"
#endif
#include <spine/spine.h>
#include <spine/extension.h>
void _spAtlasPage_createTexture (spAtlasPage* page, const char* path) {
kk::GL::SpineElement * e = (kk::GL::SpineElement *) page->atlas->rendererObject;
page->rendererObject = e->image(path);
}
void _spAtlasPage_disposeTexture (spAtlasPage* page) {
page->rendererObject = nullptr;
}
char* _spUtil_readFile (const char* path, int* length) {
struct stat st;
if( stat(path, &st) == -1) {
kk::Log("Not Open %s",path);
if(length) {
* length = 0;
}
return nullptr;
}
FILE * fd = fopen(path, "r");
if(fd == nullptr ){
kk::Log("Not Open %s",path);
* length = 0;
return nullptr;
}
char * data = MALLOC(char, (size_t) st.st_size +1);
size_t n = fread(data, 1, (size_t) st.st_size, fd);
assert(n == st.st_size);
data[n] = 0;
if(length) {
*length = (int) n;
}
fclose(fd);
return data;
}
namespace kk {
namespace GL {
IMP_SCRIPT_CLASS_BEGIN_NOALLOC(&Element::ScriptClass, SpineElement, GLSpineElement)
IMP_SCRIPT_CLASS_END
KK_IMP_ELEMENT_CREATE(SpineElement)
SpineElement::SpineElement(kk::Document * document,kk::CString name, kk::ElementKey elementId)
:Element(document,name,elementId)
,_loaded(false),_spAtlas(nullptr),_spSkeletonData(nullptr)
,_spSkeleton(nullptr),_spAnimationStateData(nullptr)
,_spAnimationState(nullptr),_context(nullptr),_prevTimeInterval(0)
,_updatting(false),_spTrackEntry(nullptr),_spClipping(nullptr) {
}
SpineElement::~SpineElement() {
if(_spAnimationState) {
spAnimationState_dispose(_spAnimationState);
}
if(_spAnimationStateData) {
spAnimationStateData_dispose(_spAnimationStateData);
}
if(_spSkeleton) {
spSkeleton_dispose(_spSkeleton);
}
if(_spSkeletonData) {
spSkeletonData_dispose(_spSkeletonData);
}
if(_spAtlas) {
spAtlas_dispose(_spAtlas);
}
if(_spClipping) {
spSkeletonClipping_dispose(_spClipping);
}
}
void SpineElement::changedKey(String& key) {
Element::changedKey(key);
_updatting = true;
}
#define MAX_VERTICES_PER_ATTACHMENT 2048
static float worldVerticesPositions[MAX_VERTICES_PER_ATTACHMENT];
static TextureVertex vertices[MAX_VERTICES_PER_ATTACHMENT];
static void addVertex(float x, float y, float u, float v, int* index) {
TextureVertex* vertex = &vertices[*index];
vertex->position.x = x;
vertex->position.y = - y;
vertex->position.z = 0;
vertex->texCoord.x = u;
vertex->texCoord.y = v;
*index += 1;
}
void SpineElement::onDraw(Context * context) {
Element::onDraw(context);
_context = context;
if(!_loaded) {
kk::String path = get("path");
if(!path.empty()) {
path = context->absolutePath(path.c_str());
kk::String basePath = kk::CStringPathDeleteExtension(path.c_str());
kk::String atlas = basePath + ".atlas";
_spAtlas = spAtlas_createFromFile(atlas.c_str(), this);
if(_spAtlas == nullptr) {
kk::Log("Not Open %s",atlas.c_str());
_loaded = true;
return;
}
spSkeletonBinary* binary = spSkeletonBinary_create(_spAtlas);
binary->scale = 1.0f;
_spSkeletonData = spSkeletonBinary_readSkeletonDataFile(binary, path.c_str());
if (_spSkeletonData == nullptr) {
kk::Log("Not Open %s",path.c_str());
_loaded = true;
spSkeletonBinary_dispose(binary);
return;
}
spSkeletonBinary_dispose(binary);
_spClipping = spSkeletonClipping_create();
_spAnimationStateData = spAnimationStateData_create(_spSkeletonData);
_spAnimationState = spAnimationState_create(_spAnimationStateData);
_spSkeleton = spSkeleton_create(_spSkeletonData);
_updatting = true;
_loaded = true;
}
}
if(_spSkeleton) {
float dt = 0;
if(_prevTimeInterval != 0) {
dt = (float) (context->current() - _prevTimeInterval) * 0.001f;
}
_prevTimeInterval = context->current();
if(_updatting) {
kk::CString name = get("animation");
if(name != nullptr) {
spAnimation * anim = spSkeletonData_findAnimation(_spSkeletonData, name);
if(anim) {
if(_spTrackEntry == nullptr || _spTrackEntry->animation != anim) {
_spTrackEntry = spAnimationState_setAnimation(_spAnimationState, 0, anim, kk::GA::booleanValue(get("loop")) ? 1 : 0);
}
} else {
kk::Log("Spine Not Found Animation %s",name);
}
}
_updatting = false;
}
spAnimationState_update(_spAnimationState, dt);
spAnimationState_apply(_spAnimationState, _spSkeleton);
spSkeleton_updateWorldTransform(_spSkeleton);
for (int i = 0; i < _spSkeleton->slotsCount; ++i) {
spSlot* slot = _spSkeleton->drawOrder[i];
if(slot == nullptr) {
continue;
}
spAttachment* attachment = slot->attachment;
if (!attachment) continue;
switch (slot->data->blendMode) {
case SP_BLEND_MODE_NORMAL:
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_ALPHA);
break;
case SP_BLEND_MODE_ADDITIVE:
glBlendFunc(GL_ONE , GL_ONE);
break;
case SP_BLEND_MODE_MULTIPLY:
glBlendFunc(GL_DST_COLOR , GL_ONE_MINUS_SRC_ALPHA);
break;
case SP_BLEND_MODE_SCREEN:
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_COLOR);
break;
default:
glBlendFunc(GL_ONE , GL_ONE_MINUS_SRC_ALPHA);
}
float tintR = _spSkeleton->color.r * slot->color.r;
float tintG = _spSkeleton->color.g * slot->color.g;
float tintB = _spSkeleton->color.b * slot->color.b;
float tintA = _spSkeleton->color.a * slot->color.a;
Image* texture = 0;
int vertexIndex = 0;
if (attachment->type == SP_ATTACHMENT_REGION) {
spRegionAttachment* regionAttachment = (spRegionAttachment*)attachment;
texture = (Image*)((spAtlasRegion*)regionAttachment->rendererObject)->page->rendererObject;
spRegionAttachment_computeWorldVertices(regionAttachment, slot->bone, worldVerticesPositions, 0, 2);
addVertex(worldVerticesPositions[0], worldVerticesPositions[1],
regionAttachment->uvs[0], regionAttachment->uvs[1],
&vertexIndex);
addVertex(worldVerticesPositions[2], worldVerticesPositions[3],
regionAttachment->uvs[2], regionAttachment->uvs[3],
&vertexIndex);
addVertex(worldVerticesPositions[4], worldVerticesPositions[5],
regionAttachment->uvs[4], regionAttachment->uvs[5],
&vertexIndex);
addVertex(worldVerticesPositions[4], worldVerticesPositions[5],
regionAttachment->uvs[4], regionAttachment->uvs[5],
&vertexIndex);
addVertex(worldVerticesPositions[6], worldVerticesPositions[7],
regionAttachment->uvs[6], regionAttachment->uvs[7],
&vertexIndex);
addVertex(worldVerticesPositions[0], worldVerticesPositions[1],
regionAttachment->uvs[0], regionAttachment->uvs[1],
&vertexIndex);
} else if (attachment->type == SP_ATTACHMENT_MESH) {
spMeshAttachment* mesh = (spMeshAttachment*)attachment;
if (mesh->super.worldVerticesLength > MAX_VERTICES_PER_ATTACHMENT) continue;
texture = (Image*)((spAtlasRegion*)mesh->rendererObject)->page->rendererObject;
spVertexAttachment_computeWorldVertices(SUPER(mesh), slot, 0, mesh->super.worldVerticesLength, worldVerticesPositions, 0, 2);
for (int i = 0; i < mesh->trianglesCount; ++i) {
int index = mesh->triangles[i] << 1;
addVertex(worldVerticesPositions[index], worldVerticesPositions[index + 1],
mesh->uvs[index], mesh->uvs[index + 1],
&vertexIndex);
}
}
if(texture != nullptr && texture->status() == ImageStatusLoaded) {
context->store();
ContextState & state = context->state();
state.opacity = tintR * tintG * tintB * tintA;
context->drawTexture(texture, GL_TRIANGLES, vertices, vertexIndex);
context->restore();
}
}
}
_context = nullptr;
}
Image * SpineElement::image(kk::CString path) {
if(path == nullptr) {
return nullptr;
}
std::map<kk::String,kk::Strong>::iterator i = _images.find(path);
if(i != _images.end()) {
return i->second.as<Image>();
}
if(_context != nullptr) {
kk::String p = _context->relativePath(path);
kk::Strong v = _context->image(p.c_str());
Image * image = v.as<Image>();
if(image){
_images[path] = image;
}
return image;
}
return nullptr;
}
}
}
| 35.67374 | 149 | 0.431184 | hailongz |
03eb4a7dcb331f1c214bd6b6e5051672697fb7c3 | 1,774 | cc | C++ | 3rdparty.old/libcvd/cvd_src/draw.cc | BeLioN-github/PTAM | 436ebc2d78ace26644f296cd2d3ddd185bb0370e | [
"Intel",
"X11"
] | 14 | 2015-01-19T15:36:37.000Z | 2016-09-17T15:19:05.000Z | 3rdparty.old/libcvd/cvd_src/draw.cc | Pandinosaurus/PTAM-opencv | 1281564b9737dcc29ccacfbf7dc88a85916f7cc6 | [
"Intel",
"X11"
] | 2 | 2015-03-20T01:04:53.000Z | 2015-07-27T07:01:38.000Z | 3rdparty.old/libcvd/cvd_src/draw.cc | Pandinosaurus/PTAM-opencv | 1281564b9737dcc29ccacfbf7dc88a85916f7cc6 | [
"Intel",
"X11"
] | 14 | 2015-04-29T19:27:49.000Z | 2016-12-07T06:10:20.000Z | /*
This file is part of the CVD Library.
Copyright (C) 2005 The Authors
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <cvd/draw.h>
namespace CVD {
std::vector<ImageRef> getCircle(int radius) {
std::vector<ImageRef> points;
int y = 0;
for (int x=-radius; x<=0; x++) {
int nexty2 = radius*radius - ((x+1)*(x+1));
while (true) {
points.push_back(ImageRef(x,y));
if (y*y >= nexty2)
break;
++y;
}
}
size_t i;
for (i=points.size()-1;i>0;i--)
points.push_back(ImageRef(-points[i-1].x, points[i-1].y));
for (i=points.size()-1;i>1;i--)
points.push_back(ImageRef(points[i-1].x, -points[i-1].y));
return points;
}
std::vector<ImageRef> getDisc(float radius)
{
std::vector<ImageRef> points;
int r = (int)ceil(radius + 1);
for(ImageRef p(0,-r); p.y <= r; p.y++)
for(p.x = -r; p.x <= r; p.x++)
if(p.mag_squared() <= radius*radius)
points.push_back(p);
return points;
}
};
| 28.612903 | 75 | 0.616122 | BeLioN-github |
03ec04925b0dc51e5ffde9d73047481ab8a001f9 | 27,512 | cpp | C++ | core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/test/test-triad.cpp | qiuhere/Bench | 80f15facb81120b754547586cf3a7e5f46ca1551 | [
"Apache-2.0"
] | 13 | 2020-04-16T21:45:10.000Z | 2022-02-03T15:38:12.000Z | core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/test/test-triad.cpp | qiuhere/Bench | 80f15facb81120b754547586cf3a7e5f46ca1551 | [
"Apache-2.0"
] | 1 | 2021-11-18T14:23:44.000Z | 2021-11-18T14:23:44.000Z | core/src/main/java/site/ycsb/data_gen/Graph_gen/Graph_gen/test/test-triad.cpp | qiuhere/Bench | 80f15facb81120b754547586cf3a7e5f46ca1551 | [
"Apache-2.0"
] | 4 | 2020-04-21T08:52:16.000Z | 2022-02-16T20:12:45.000Z | #include <gtest/gtest.h>
#include "Snap.h"
PUNGraph TriadGetTestTUNGraph();
PNGraph TriadGetTestTNGraph();
PNEGraph TriadGetTestTNEGraph();
void TestOpenCloseVector(TIntTrV& NIdCOTriadV);
void TestDegToCCfVector(TFltPrV& DegToCCfV);
void VerifyNodeClustCf(int NId, double ClustCf);
void VerifyClosedTriads(int NId, int ClosedTriads);
void VerifyOpenTriads(int NId, int OpenTriads);
void GetGroupSet(int NId, TIntSet& GroupSet);
void VerifyInGroupEdges(int NId, int InGroupEdges);
void VerifyInOutGroupEdges(int NId, int InOutGroupEdges);
void VerifyOutGroupEdges(int NId, int OutGroupEdges);
void VerifyGetTriadParticip(TIntPrV& TriadCntV);
void VerifyCmnNbrs(int NId1, int NId2, int CmnNbrs);
void VerifyLen2Paths(int NId1, int NId2, int Len2Paths, int type);
// Test GetTriads Close/Open Triad Vector for each NId
TEST(triad, TestGetTriadsVector) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
TIntTrV NIdCOTriadV;
TSnap::GetTriads(GraphTUN, NIdCOTriadV);
TestOpenCloseVector(NIdCOTriadV);
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
NIdCOTriadV.Clr();
ASSERT_TRUE(NIdCOTriadV.Empty());
TSnap::GetTriads(GraphTN, NIdCOTriadV);
TestOpenCloseVector(NIdCOTriadV);
// TNEGraph should be treated as TUNGraph for calculations
PNEGraph GraphTNE = TriadGetTestTNEGraph();
NIdCOTriadV.Clr();
ASSERT_TRUE(NIdCOTriadV.Empty());
TestOpenCloseVector(NIdCOTriadV);
}
// Test GetTriads for Whole Graph (Open and Closed)
TEST(triad, TestGetTriadsOpenClosed) {
const int ExpClosedTr = 3; // Expected closed triads
const int ExpOpenTr = 9; // Expected open triads
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
int64 ClosedTr = 0;
int64 OpenTr = 0;
TSnap::GetTriads(GraphTUN, ClosedTr, OpenTr);
EXPECT_EQ(ExpClosedTr, ClosedTr);
EXPECT_EQ(ExpOpenTr, OpenTr);
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
ClosedTr = 0;
OpenTr = 0;
TSnap::GetTriads(GraphTN, ClosedTr, OpenTr);
EXPECT_EQ(ExpClosedTr, ClosedTr);
EXPECT_EQ(ExpOpenTr, OpenTr);
// TNEGraph should be treated as TUNGraph for calculations
PNEGraph GraphTNE = TriadGetTestTNEGraph();
ClosedTr = 0;
OpenTr = 0;
TSnap::GetTriads(GraphTNE, ClosedTr, OpenTr);
EXPECT_EQ(ExpClosedTr, ClosedTr);
EXPECT_EQ(ExpOpenTr, OpenTr);
}
// Test GetTriads for Whole Graph (Only Closed)
TEST(triad, TestGetTriadsClosed) {
const int ExpClosedTr = 3; // Expected closed triads
int64 ClosedTr = 0;
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
ClosedTr = TSnap::GetTriads(GraphTUN);
EXPECT_EQ(ExpClosedTr, ClosedTr);
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
ClosedTr = TSnap::GetTriads(GraphTN);
EXPECT_EQ(ExpClosedTr, ClosedTr);
// TNEGraph should be treated as TUNGraph for calculations
PNEGraph GraphTNE = TriadGetTestTNEGraph();
ClosedTr = TSnap::GetTriads(GraphTNE);
EXPECT_EQ(ExpClosedTr, ClosedTr);
}
// Test GetClustCf (Average Clustering Coefficient)
TEST(triad, TestGetClustCf) {
const double ExpClustCf = 109.0/180.0; // Expected ClustCf (0.60555..)
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
double ClustCf = 0.0;
ClustCf = TSnap::GetClustCf(GraphTUN);
EXPECT_EQ(ExpClustCf, ClustCf);
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
ClustCf = TSnap::GetClustCf(GraphTN);
EXPECT_EQ(ExpClustCf, ClustCf);
// TNEGraph should be treated as TUNGraph for calculations
PNEGraph GraphTNE = TriadGetTestTNEGraph();
ClustCf = TSnap::GetClustCf(GraphTNE);
EXPECT_EQ(ExpClustCf, ClustCf);
}
// Test GetClustCf (Distribution of Average Clustering Coefficients)
TEST(triad, TestGetClustCfDist) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
TFltPrV DegToCCfV;
TSnap::GetClustCf(GraphTUN, DegToCCfV);
TestDegToCCfVector(DegToCCfV);
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
DegToCCfV.Clr();
TSnap::GetClustCf(GraphTN, DegToCCfV);
TestDegToCCfVector(DegToCCfV);
// TNEGraph is not treated the same! Be careful with multigraphs
PNEGraph GraphTNE = TriadGetTestTNEGraph();
DegToCCfV.Clr();
TSnap::GetClustCf(GraphTNE, DegToCCfV);
for (TFltPr *Pair = DegToCCfV.BegI(); Pair < DegToCCfV.EndI(); Pair++) {
double Diff = Pair->Val2 - 5.0/9.0; // Used for case 4
Diff = (Diff < 0) ? -1.0*Diff : Diff; // Used for case 4
switch ((int) Pair->Val1) {
case 2:
EXPECT_EQ(1.0, Pair->Val2);
break;
case 4:
EXPECT_GT(0.00001, Diff); // Due to floats being imprecise
break;
case 7:
EXPECT_EQ(2.0/3.0, Pair->Val2);
break;
case 15:
EXPECT_EQ(0.3, Pair->Val2);
break;
default:
ASSERT_FALSE(true); // Shouldn't have degrees other than listed
break;
}
}
}
// Test GetClustCf (Distribution and Closed and Open)
TEST(triad, TestGetClustCfDistCO) {
const int ExpClosedTr = 3; // Expected closed triads
const int ExpOpenTr = 9; // Expected open triads
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
TFltPrV DegToCCfV;
int64 ClosedTr = 0;
int64 OpenTr = 0;
TSnap::GetClustCf(GraphTUN, DegToCCfV, ClosedTr, OpenTr);
TestDegToCCfVector(DegToCCfV);
EXPECT_EQ(ExpClosedTr, ClosedTr);
EXPECT_EQ(ExpOpenTr, OpenTr);
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
DegToCCfV.Clr();
ClosedTr = 0;
OpenTr = 0;
TSnap::GetClustCf(GraphTN, DegToCCfV, ClosedTr, OpenTr);
TestDegToCCfVector(DegToCCfV);
EXPECT_EQ(ExpClosedTr, ClosedTr);
EXPECT_EQ(ExpOpenTr, OpenTr);
// TNEGraph is not treated the same! Be careful with multigraphs
PNEGraph GraphTNE = TriadGetTestTNEGraph();
DegToCCfV.Clr();
ClosedTr = 0;
OpenTr = 0;
TSnap::GetClustCf(GraphTNE, DegToCCfV, ClosedTr, OpenTr);
for (TFltPr *Pair = DegToCCfV.BegI(); Pair < DegToCCfV.EndI(); Pair++) {
double Diff = Pair->Val2 - 5.0/9.0; // Used for case 4
Diff = (Diff < 0) ? -1.0*Diff : Diff; // Used for case 4
switch ((int) Pair->Val1) {
case 2:
EXPECT_EQ(1.0, Pair->Val2);
break;
case 4:
EXPECT_GT(0.00001, Diff); // Due to floats being imprecise
break;
case 7:
EXPECT_EQ(2.0/3.0, Pair->Val2);
break;
case 15:
EXPECT_EQ(0.3, Pair->Val2);
break;
default:
ASSERT_FALSE(true); // Shouldn't have degrees other than listed
break;
}
}
EXPECT_EQ(ExpClosedTr, ClosedTr);
EXPECT_EQ(ExpOpenTr, OpenTr);
}
// Test GetNodeClustCf (Specific Node)
TEST(triad, TestGetNodeClustCfSpecific) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
double ClustCf = TSnap::GetNodeClustCf(GraphTUN, i);
VerifyNodeClustCf(i, ClustCf);
}
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
for (int i = 0; i < GraphTN->GetNodes(); i++) {
double ClustCf = TSnap::GetNodeClustCf(GraphTN, i);
VerifyNodeClustCf(i, ClustCf);
}
// TNEGraph should be treated as TUNGraph for calculations
PNEGraph GraphTNE = TriadGetTestTNEGraph();
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
double ClustCf = TSnap::GetNodeClustCf(GraphTNE, i);
VerifyNodeClustCf(i, ClustCf);
}
}
// Test GetNodeClustCf (Vector)
TEST(triad, TestGetNodeClustCfVector) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
TIntFltH NIdCCfH;
TSnap::GetNodeClustCf(GraphTUN, NIdCCfH);
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
double ClustCf = NIdCCfH.GetDat(i);
VerifyNodeClustCf(i, ClustCf);
}
// TNGraph should be treated as TUNGraph for calculations
PNGraph GraphTN = TriadGetTestTNGraph();
NIdCCfH.Clr();
TSnap::GetNodeClustCf(GraphTN, NIdCCfH);
for (int i = 0; i < GraphTN->GetNodes(); i++) {
double ClustCf = NIdCCfH.GetDat(i);
VerifyNodeClustCf(i, ClustCf);
}
// TNEGraph should be treated as TUNGraph for calculations
PNEGraph GraphTNE = TriadGetTestTNEGraph();
NIdCCfH.Clr();
TSnap::GetNodeClustCf(GraphTNE, NIdCCfH);
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
double ClustCf = NIdCCfH.GetDat(i);
VerifyNodeClustCf(i, ClustCf);
}
}
// Test GetTriadEdges
TEST(triad, TestGetTriadEdges) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
EXPECT_EQ(7, TSnap::GetTriadEdges(GraphTUN));
// TNGraph is not treated the same! Each directed will be counted
PNGraph GraphTN = TriadGetTestTNGraph();
EXPECT_EQ(7, TSnap::GetTriadEdges(GraphTN));
// TNEGraph is not treated the same! Be careful with multigraphs
PNEGraph GraphTNE = TriadGetTestTNEGraph();
EXPECT_EQ(14, TSnap::GetTriadEdges(GraphTNE));
}
// Test GetNodeTriads
TEST(triad, TestGetNodeTriads) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
VerifyClosedTriads(i, TSnap::GetNodeTriads(GraphTUN, i));
}
// TNGraph is not treated the same! Each directed will be counted
PNGraph GraphTN = TriadGetTestTNGraph();
for (int i = 0; i < GraphTN->GetNodes(); i++) {
VerifyClosedTriads(i, TSnap::GetNodeTriads(GraphTN, i));
}
// TNEGraph is not treated the same! Be careful with multigraphs
PNEGraph GraphTNE = TriadGetTestTNEGraph();
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
VerifyClosedTriads(i, TSnap::GetNodeTriads(GraphTNE, i));
}
}
// Test GetNodeTriads (Open and Closed)
TEST(triad, TestGetNodeCOTriads) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
int ClosedTr = -1, OpenTr = -1;
TSnap::GetNodeTriads(GraphTUN, i, ClosedTr, OpenTr);
VerifyClosedTriads(i, ClosedTr);
VerifyOpenTriads(i, OpenTr);
}
// Test TNGraph which is treated same as undirected.
PNGraph GraphTN = TriadGetTestTNGraph();
for (int i = 0; i < GraphTN->GetNodes(); i++) {
int ClosedTr = -1, OpenTr = -1;
TSnap::GetNodeTriads(GraphTN, i, ClosedTr, OpenTr);
VerifyClosedTriads(i, ClosedTr);
VerifyOpenTriads(i, OpenTr);
}
// Test TNEGraph which is treated same as undirected.
PNEGraph GraphTNE = TriadGetTestTNEGraph();
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
int ClosedTr = -1, OpenTr = -1;
TSnap::GetNodeTriads(GraphTNE, i, ClosedTr, OpenTr);
VerifyClosedTriads(i, ClosedTr);
VerifyOpenTriads(i, OpenTr);
}
}
// Test GetNodeTriads (GroupSet, InGroupEdges, InOutGroupEdges, OutGroupEdges)
TEST(triad, TestGetNodeTriadsGroupSetAndOut) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
TIntSet GroupSet;
GetGroupSet(i, GroupSet);
int InGroupEdges = -1, InOutGroupEdges = -1, OutGroupEdges = -1;
TSnap::GetNodeTriads(GraphTUN, i, GroupSet,
InGroupEdges, InOutGroupEdges, OutGroupEdges);
VerifyInGroupEdges(i, InGroupEdges);
VerifyInOutGroupEdges(i, InOutGroupEdges);
VerifyOutGroupEdges(i, OutGroupEdges);
}
// Test TNGraph which is same as undirected.
PNGraph GraphTN = TriadGetTestTNGraph();
for (int i = 0; i < GraphTN->GetNodes(); i++) {
TIntSet GroupSet;
GetGroupSet(i, GroupSet);
int InGroupEdges = -1, InOutGroupEdges = -1, OutGroupEdges = -1;
TSnap::GetNodeTriads(GraphTN, i, GroupSet,
InGroupEdges, InOutGroupEdges, OutGroupEdges);
VerifyInGroupEdges(i, InGroupEdges);
VerifyInOutGroupEdges(i, InOutGroupEdges);
VerifyOutGroupEdges(i, OutGroupEdges);
}
// Test TNEGraph which is same as undirected.
PNEGraph GraphTNE = TriadGetTestTNEGraph();
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
TIntSet GroupSet;
GetGroupSet(i, GroupSet);
int InGroupEdges = -1, InOutGroupEdges = -1, OutGroupEdges = -1;
TSnap::GetNodeTriads(GraphTNE, i, GroupSet,
InGroupEdges, InOutGroupEdges, OutGroupEdges);
VerifyInGroupEdges(i, InGroupEdges);
VerifyInOutGroupEdges(i, InOutGroupEdges);
VerifyOutGroupEdges(i, OutGroupEdges);
}
}
// Test GetTriadParticip
// Number of nodes with x number of triangles it participates in
TEST(triad, TestGetTriadParticip) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
TIntPrV TriadCntV;
TSnap::GetTriadParticip(GraphTUN, TriadCntV);
VerifyGetTriadParticip(TriadCntV);
// Test TNGraph which is same as undirected.
PNGraph GraphTN = TriadGetTestTNGraph();
TriadCntV.Clr();
TSnap::GetTriadParticip(GraphTN, TriadCntV);
VerifyGetTriadParticip(TriadCntV);
// Test TNEGraph which is same as undirected.
PNEGraph GraphTNE = TriadGetTestTNEGraph();
TriadCntV.Clr();
TSnap::GetTriadParticip(GraphTN, TriadCntV);
VerifyGetTriadParticip(TriadCntV);
}
// Test GetCmnNbrs: the number of neighbors in common
TEST(triad, TestGetCmnNbrs) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
for (int j = i + 1; j < GraphTUN->GetNodes(); j++) {
VerifyCmnNbrs(i, j, TSnap::GetCmnNbrs(GraphTUN, i, j));
}
}
// Test TNGraph which is same as undirected.
PNGraph GraphTN = TriadGetTestTNGraph();
for (int i = 0; i < GraphTN->GetNodes(); i++) {
for (int j = i + 1; j < GraphTN->GetNodes(); j++) {
VerifyCmnNbrs(i, j, TSnap::GetCmnNbrs(GraphTN, i, j));
}
}
// Test TNEGraph which is same as undirected.
PNEGraph GraphTNE = TriadGetTestTNEGraph();
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
for (int j = i + 1; j < GraphTNE->GetNodes(); j++) {
VerifyCmnNbrs(i, j, TSnap::GetCmnNbrs(GraphTNE, i, j));
}
}
}
// Test GetLen2Paths: Number of path lengths 2 between pair of nodes
TEST(triad, TestGetLen2Paths) {
// Test TUNGraph
PUNGraph GraphTUN = TriadGetTestTUNGraph();
for (int i = 0; i < GraphTUN->GetNodes(); i++) {
for (int j = i + 1; j < GraphTUN->GetNodes(); j++) {
VerifyLen2Paths(i, j, TSnap::GetLen2Paths(GraphTUN, i, j), 0);
}
}
// Test TNGraph which is different from undirected due to out neighbors.
PNGraph GraphTN = TriadGetTestTNGraph();
for (int i = 0; i < GraphTN->GetNodes(); i++) {
for (int j = i + 1; j < GraphTN->GetNodes(); j++) {
VerifyLen2Paths(i, j, TSnap::GetLen2Paths(GraphTN, i, j), 1);
}
}
// Test TNEGraph which is different from undirected due to out neighbors.
PNEGraph GraphTNE = TriadGetTestTNEGraph();
for (int i = 0; i < GraphTNE->GetNodes(); i++) {
for (int j = i + 1; j < GraphTNE->GetNodes(); j++) {
VerifyLen2Paths(i, j, TSnap::GetLen2Paths(GraphTNE, i, j), 2);
}
}
}
// Helper: Testing Opened/Closed Triads for Specific Generated Graph
void TestOpenCloseVector(TIntTrV& NIdCOTriadV) {
for (TIntTr *Vec = NIdCOTriadV.BegI(); Vec < NIdCOTriadV.EndI(); Vec++) {
switch (Vec->Val1) {
case 0:
EXPECT_EQ(3, Vec->Val2);
EXPECT_EQ(7, Vec->Val3);
break;
case 1:
EXPECT_EQ(1, Vec->Val2);
EXPECT_EQ(0, Vec->Val3);
break;
case 2:
EXPECT_EQ(2, Vec->Val2);
EXPECT_EQ(1, Vec->Val3);
break;
case 3:
EXPECT_EQ(1, Vec->Val2);
EXPECT_EQ(0, Vec->Val3);
break;
case 4:
EXPECT_EQ(0, Vec->Val2);
EXPECT_EQ(0, Vec->Val3);
break;
case 5:
EXPECT_EQ(2, Vec->Val2);
EXPECT_EQ(1, Vec->Val3);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
}
// Helper: Testing Degree to Clustering Coefficient Distribution
void TestDegToCCfVector(TFltPrV& DegToCCfV) {
for (TFltPr *Pair = DegToCCfV.BegI(); Pair < DegToCCfV.EndI(); Pair++) {
switch ((int) Pair->Val1) {
case 1:
EXPECT_EQ(0.0, Pair->Val2);
break;
case 2:
EXPECT_EQ(1.0, Pair->Val2);
break;
case 3:
EXPECT_EQ(2.0/3.0, Pair->Val2);
break;
case 5:
EXPECT_EQ(0.3, Pair->Val2);
break;
default:
ASSERT_FALSE(true); // Shouldn't have degrees other than listed
break;
}
}
}
// Helper: Tests the Clustering Coefficient for a Node
void VerifyNodeClustCf(int NId, double ClustCf) {
switch (NId) {
case 0:
EXPECT_EQ(0.3, ClustCf);
break;
case 1:
EXPECT_EQ(1.0, ClustCf);
break;
case 2:
EXPECT_EQ(2.0/3.0, ClustCf);
break;
case 3:
EXPECT_EQ(1, ClustCf);
break;
case 4:
EXPECT_EQ(0, ClustCf);
break;
case 5:
EXPECT_EQ(2.0/3.0, ClustCf);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Tests the Closed Triads a node participates in
void VerifyClosedTriads(int NId, int ClosedTriads) {
switch (NId) {
case 0:
EXPECT_EQ(3, ClosedTriads);
break;
case 1:
EXPECT_EQ(1, ClosedTriads);
break;
case 2:
EXPECT_EQ(2, ClosedTriads);
break;
case 3:
EXPECT_EQ(1, ClosedTriads);
break;
case 4:
EXPECT_EQ(0, ClosedTriads);
break;
case 5:
EXPECT_EQ(2, ClosedTriads);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Tests the Open Triads a node participates in
void VerifyOpenTriads(int NId, int OpenTriads) {
switch (NId) {
case 0:
EXPECT_EQ(7, OpenTriads);
break;
case 1:
EXPECT_EQ(0, OpenTriads);
break;
case 2:
EXPECT_EQ(1, OpenTriads);
break;
case 3:
EXPECT_EQ(0, OpenTriads);
break;
case 4:
EXPECT_EQ(0, OpenTriads);
break;
case 5:
EXPECT_EQ(1, OpenTriads);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Return GroupSet based on NodeID
void GetGroupSet(int NId, TIntSet& GroupSet) {
GroupSet.Clr();
switch (NId) {
case 0:
GroupSet.AddKey(2);
GroupSet.AddKey(4);
GroupSet.AddKey(5);
break;
case 1:
// Empty Set
break;
case 2:
GroupSet.AddKey(0);
GroupSet.AddKey(3);
GroupSet.AddKey(5);
break;
case 3:
GroupSet.AddKey(0);
break;
case 4:
GroupSet.AddKey(0);
break;
case 5:
GroupSet.AddKey(0);
GroupSet.AddKey(1);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Tests InGroupEdges for GetNodeTriads
void VerifyInGroupEdges(int NId, int InGroupEdges) {
switch (NId) {
case 0:
EXPECT_EQ(1, InGroupEdges);
break;
case 1:
EXPECT_EQ(0, InGroupEdges);
break;
case 2:
EXPECT_EQ(2, InGroupEdges);
break;
case 3:
EXPECT_EQ(0, InGroupEdges);
break;
case 4:
EXPECT_EQ(0, InGroupEdges);
break;
case 5:
EXPECT_EQ(1, InGroupEdges);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Tests InOutGroupEdges for GetNodeTriads
void VerifyInOutGroupEdges(int NId, int InOutGroupEdges) {
switch (NId) {
case 0:
EXPECT_EQ(2, InOutGroupEdges);
break;
case 1:
EXPECT_EQ(0, InOutGroupEdges);
break;
case 2:
EXPECT_EQ(0, InOutGroupEdges);
break;
case 3:
EXPECT_EQ(1, InOutGroupEdges);
break;
case 4:
EXPECT_EQ(0, InOutGroupEdges);
break;
case 5:
EXPECT_EQ(1, InOutGroupEdges);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Tests OutGroupEdges for GetNodeTriads
void VerifyOutGroupEdges(int NId, int OutGroupEdges) {
switch (NId) {
case 0:
EXPECT_EQ(0, OutGroupEdges);
break;
case 1:
EXPECT_EQ(1, OutGroupEdges);
break;
case 2:
EXPECT_EQ(0, OutGroupEdges);
break;
case 3:
EXPECT_EQ(0, OutGroupEdges);
break;
case 4:
EXPECT_EQ(0, OutGroupEdges);
break;
case 5:
EXPECT_EQ(0, OutGroupEdges);
break;
default:
ASSERT_FALSE(true); // NId Outside Graph Construction FAIL
break;
}
}
// Helper: Verify the distribution of how many triangles a node participates in
void VerifyGetTriadParticip(TIntPrV& TriadCntV) {
for (TIntPr *Vec = TriadCntV.BegI(); Vec < TriadCntV.EndI(); Vec++) {
switch (Vec->Val1) {
case 0:
EXPECT_EQ(1, Vec->Val2);
break;
case 1:
EXPECT_EQ(2, Vec->Val2);
break;
case 2:
EXPECT_EQ(2, Vec->Val2);
break;
case 3:
EXPECT_EQ(1, Vec->Val2);
break;
default:
EXPECT_FALSE(true); // Not suppose to have more than 3
break;
}
}
}
// Helper: Verify the common neighbors between nodes
void VerifyCmnNbrs(int NId1, int NId2, int CmnNbrs) {
switch (NId1) {
case 0:
switch (NId2) {
case 1:
EXPECT_EQ(1, CmnNbrs);
break;
case 2:
EXPECT_EQ(2, CmnNbrs);
break;
case 3:
EXPECT_EQ(1, CmnNbrs);
break;
case 4:
EXPECT_EQ(0, CmnNbrs);
break;
case 5:
EXPECT_EQ(2, CmnNbrs);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 1:
switch (NId2) {
case 2:
EXPECT_EQ(2, CmnNbrs);
break;
case 3:
EXPECT_EQ(1, CmnNbrs);
break;
case 4:
EXPECT_EQ(1, CmnNbrs);
break;
case 5:
EXPECT_EQ(1, CmnNbrs);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 2:
switch (NId2) {
case 3:
EXPECT_EQ(1, CmnNbrs);
break;
case 4:
EXPECT_EQ(1, CmnNbrs);
break;
case 5:
EXPECT_EQ(1, CmnNbrs);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 3:
switch (NId2) {
case 4:
EXPECT_EQ(1, CmnNbrs);
break;
case 5:
EXPECT_EQ(2, CmnNbrs);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 4:
switch (NId2) {
case 5:
EXPECT_EQ(1, CmnNbrs);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
}
// Helper: Verify the number of paths of length 2
// Type: 0 = Undirected | 1 = Directed | 2 = Multi-Directed
void VerifyLen2Paths(int NId1, int NId2, int Len2Paths, int type) {
switch (NId1) {
case 0:
switch (NId2) {
case 1:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 2:
if (type == 0)
EXPECT_EQ(2, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 3:
if (type == 0 || type == 1)
EXPECT_EQ(1, Len2Paths);
else if (type == 2)
EXPECT_EQ(2, Len2Paths);
break;
case 4:
EXPECT_EQ(0, Len2Paths);
break;
case 5:
if (type == 0 || type == 1)
EXPECT_EQ(2, Len2Paths);
else if (type == 2)
EXPECT_EQ(3, Len2Paths);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 1:
switch (NId2) {
case 2:
if (type == 0)
EXPECT_EQ(2, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 3:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 4:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 5:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 2:
switch (NId2) {
case 3:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 4:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 5:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 3:
switch (NId2) {
case 4:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
case 5:
if (type == 0)
EXPECT_EQ(2, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
case 4:
switch (NId2) {
case 5:
if (type == 0)
EXPECT_EQ(1, Len2Paths);
else if (type == 1 || type == 2)
EXPECT_EQ(0, Len2Paths);
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
break;
default:
EXPECT_FALSE(true); // Should not get to here
break;
}
}
// Generate TUNGraph
PUNGraph TriadGetTestTUNGraph() {
PUNGraph Graph = TUNGraph::New();
for (int i = 0; i < 6; i++) {
Graph->AddNode(i);
}
for (int i = 1; i < 6; i++) {
Graph->AddEdge(0, i);
}
Graph->AddEdge(2, 3);
Graph->AddEdge(1, 5);
Graph->AddEdge(2, 5);
return Graph;
}
// Generate TNGraph
PNGraph TriadGetTestTNGraph() {
PNGraph Graph = TNGraph::New();
for (int i = 0; i < 6; i++) {
Graph->AddNode(i);
}
for (int i = 1; i < 6; i++) {
Graph->AddEdge(0, i);
}
Graph->AddEdge(2, 3);
Graph->AddEdge(1, 5);
Graph->AddEdge(2, 5);
return Graph;
}
// Generate TNEGraph
PNEGraph TriadGetTestTNEGraph() {
PNEGraph Graph = TNEGraph::New();
for (int i = 0; i < 6; i++) {
Graph->AddNode(i);
}
for (int i = 1; i < 6; i++) {
for (int j = 0; j < i; j++) {
Graph->AddEdge(0, i);
}
}
Graph->AddEdge(2, 3);
Graph->AddEdge(1, 5);
Graph->AddEdge(2, 5);
return Graph;
}
| 26.736638 | 79 | 0.61097 | qiuhere |
03f044e8409affc3fbf02b51a3b68ca2649b3a59 | 568 | cpp | C++ | vkcup2016qual/b.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | 1 | 2021-10-24T00:46:37.000Z | 2021-10-24T00:46:37.000Z | vkcup2016qual/b.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | vkcup2016qual/b.cpp | vladshablinsky/algo | 815392708d00dc8d3159b4866599de64fa9d34fa | [
"MIT"
] | null | null | null | #include <iostream>
#include <map>
#include <string>
#include <cstdio>
#include <algorithm>
#include <vector>
using namespace std;
map<string, int> mp;
vector<pair<int, string> > ans;
int main() {
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
string s;
cin >> s;
mp[s] = i + 1;
}
for (map<string, int>::iterator it = mp.begin(); it != mp.end(); ++it) {
ans.push_back(make_pair(it->second, it->first));
}
sort(ans.begin(), ans.end());
for (int i = ans.size() - 1; i >= 0; --i) {
cout << ans[i].second << "\n";
}
return 0;
}
| 18.322581 | 74 | 0.545775 | vladshablinsky |
03f0cedc2ecc5455e338fc01ca4aaf265a168c20 | 3,212 | cpp | C++ | tab/json/cgeneratejson.cpp | YujieChuck/QT_HPC_study0723 | 01b1926bf09bf3e6b85de07a7149467932b15d29 | [
"MIT"
] | null | null | null | tab/json/cgeneratejson.cpp | YujieChuck/QT_HPC_study0723 | 01b1926bf09bf3e6b85de07a7149467932b15d29 | [
"MIT"
] | null | null | null | tab/json/cgeneratejson.cpp | YujieChuck/QT_HPC_study0723 | 01b1926bf09bf3e6b85de07a7149467932b15d29 | [
"MIT"
] | null | null | null | #include "cgeneratejson.h"
#include "Poco/File.h"
#include "Poco/Logger.h"
#include "Poco/FileStream.h"
CGenerateJson::CGenerateJson(QWidget *parent) : QWidget(parent)
{
}
int CGenerateJson::ParseJson(const std::string& jsonFile, JSON::Object::Ptr &jsonObj)
{
int parserStatus=0;
//此处判断是否是json还是其中的内容对象
Poco::File jf(jsonFile);
std::string jsonStr;
size_t preIndex=jsonFile.find_first_of("{");
size_t rearIndex=jsonFile.find_last_of("}");
if (preIndex!=-1&&rearIndex!=-1)
{
jsonStr=jsonFile;
}else
{
if (!jf.exists()){
Poco::Logger::get("TraceLog").error("Cannot find the json.");
parserStatus=-201;
// exit(-1);
}
Poco::FileInputStream fis(jsonFile);
std::ostringstream ostr;
StreamCopier::copyStream(fis, ostr);
jsonStr= ostr.str();
}
Poco::JSON::Parser sparser;
Poco::Dynamic::Var result;
try
{
result = sparser.parse(jsonStr);
}
catch (Poco::JSON::JSONException* jsone)
{
Poco::Logger::get("TraceLog").fatal(jsone->displayText());
// exit(-1);
}
catch (Poco::Exception& e)
{
Poco::Logger::get("TraceLog").fatal(e.displayText());
parserStatus=-203;
// exit(-1);
}
if (result.type() == typeid(Poco::JSON::Object::Ptr))
{
jsonObj = result.extract<Poco::JSON::Object::Ptr>();
}
else
{
Poco::Logger::get("TraceLog").fatal("Error json format.");
parserStatus=-202;
// exit(-1);
}
return parserStatus;
}
int CGenerateJson::testSetArrayElement(std::string &strJson)
{
std::string json = "[]";
Parser parser;
Var result = parser.parse(json);
Poco::JSON::Array::Ptr array = result.extract<Poco::JSON::Array::Ptr>();
Poco::Dynamic::Array dynArray = *array;
assert(dynArray.size() == 0);
// array[0] = 7
array->set(0, 7);
assert(array->size() == 1);
assert(array->getElement<int>(0) == 7);
dynArray = *array;
assert(dynArray.size() == 1);
assert(dynArray[0] == 7);
// array[2] = "foo"
array->set(2, std::string("foo"));
assert(array->size() == 3);
assert(array->getElement<int>(0) == 7);
assert(array->isNull(1));
assert(array->getElement<std::string>(2) == "foo");
dynArray = *array;
assert(dynArray.size() == 3);
assert(dynArray[0] == 7);
assert(dynArray[1].isEmpty());
assert(dynArray[2] == "foo");
// array[1] = 13
array->set(1, 13);
assert(array->size() == 3);
assert(array->getElement<int>(0) == 7);
assert(array->getElement<int>(1) == 13);
assert(array->getElement<std::string>(2) == "foo");
//Json object to string
JSON::Object jsnObj;
jsnObj.set("ArrayData",array);
std::stringstream jsnString;
jsnObj.stringify(jsnString, 3);
strJson = jsnString.str();
//#ifdef POCO_ENABLE_CPP11
// dynArray = std::move(*array);
// assert(dynArray.size() == 3);
// assert(dynArray[0] == 7);
// assert(dynArray[1] == 13);
// assert(dynArray[2] == "foo");
//#endif // POCO_ENABLE_CPP11
// dynArray.clear();
// assert(dynArray.size() == 0);
return 0;
}
| 24.519084 | 85 | 0.578456 | YujieChuck |
03f2f78abb1ec817c11f8f97da13bce6e6f7e45b | 2,142 | hh | C++ | Trajectory/ClosestApproachData.hh | orionning676/KinKal | 689ec932155b7fe31d46c398bcb78bcac93581d7 | [
"Apache-1.1"
] | 2 | 2020-04-21T18:24:55.000Z | 2020-09-24T19:01:47.000Z | Trajectory/ClosestApproachData.hh | orionning676/KinKal | 689ec932155b7fe31d46c398bcb78bcac93581d7 | [
"Apache-1.1"
] | 45 | 2020-03-16T18:27:59.000Z | 2022-01-13T05:18:35.000Z | Trajectory/ClosestApproachData.hh | orionning676/KinKal | 689ec932155b7fe31d46c398bcb78bcac93581d7 | [
"Apache-1.1"
] | 15 | 2020-02-21T01:10:49.000Z | 2022-03-24T12:13:35.000Z | #ifndef KinKal_ClosestApproachData_hh
#define KinKal_ClosestApproachData_hh
//
// data payload for CA calculations
//
#include "KinKal/General/Vectors.hh"
#include <string>
#include <vector>
#include <ostream>
namespace KinKal {
struct ClosestApproachData {
enum TPStat{converged=0,unconverged,oscillating,diverged,pocafailed,invalid};
static std::string const& statusName(TPStat status);
//accessors
VEC4 const& particlePoca() const { return partCA_; }
VEC4 const& sensorPoca() const { return sensCA_; }
double particleToca() const { return partCA_.T(); }
double sensorToca() const { return sensCA_.T(); }
VEC3 const& particleDirection() const { return pdir_; }
VEC3 const& sensorDirection() const { return sdir_; }
TPStat status() const { return status_; }
std::string const& statusName() const { return statusName(status_); }
double doca() const { return doca_; } // DOCA signed by angular momentum
double docaVar() const { return docavar_; } // uncertainty on doca due to particle trajectory parameter uncertainties (NOT sensory uncertainties)
double tocaVar() const { return tocavar_; } // uncertainty on toca due to particle trajectory parameter uncertainties (NOT sensory uncertainties)
double dirDot() const { return pdir_.Dot(sdir_); }
double lSign() const { return lsign_; } // sign of angular momentum
// utility functions
VEC4 delta() const { return sensCA_-partCA_; } // measurement - prediction convention
double deltaT() const { return sensCA_.T() - partCA_.T(); }
bool usable() const { return status_ < diverged; }
ClosestApproachData() : status_(invalid), doca_(-1.0), docavar_(-1.0), tocavar_(-1.0) {}
TPStat status_; // status of computation
double doca_, docavar_, tocavar_, lsign_;
VEC3 pdir_, sdir_; // particle and sensor directions at CA, signed by time propagation
VEC4 partCA_, sensCA_; //CA for particle and sensor
void reset() {status_ = unconverged;}
const static std::vector<std::string> statusNames_;
};
std::ostream& operator << (std::ostream& ost, ClosestApproachData const& cadata);
}
#endif
| 48.681818 | 149 | 0.715219 | orionning676 |
03f6798e427da5b86552649e7a6eae02ec32f92f | 3,011 | cpp | C++ | tc 160+/ChatTranscript.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 3 | 2015-05-25T06:24:37.000Z | 2016-09-10T07:58:00.000Z | tc 160+/ChatTranscript.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | null | null | null | tc 160+/ChatTranscript.cpp | ibudiselic/contest-problem-solutions | 88082981b4d87da843472e3ca9ed5f4c42b3f0aa | [
"BSD-2-Clause"
] | 5 | 2015-05-25T06:24:40.000Z | 2021-08-19T19:22:29.000Z | #include <algorithm>
#include <cassert>
#include <cstdio>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
#include <cstring>
using namespace std;
bool sw(const string &a, const string &b) {
if (a.size() < b.size())
return false;
for (int i=0; i<(int)b.size(); ++i)
if (a[i] != b[i])
return false;
return true;
}
class ChatTranscript {
public:
int howMany(vector <string> transcript, string name) {
name += ':';
int sol = 0;
for (int i=0; i<(int)transcript.size(); ++i)
sol += sw(transcript[i], name);
return sol;
}
// 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() { string Arr0[] = {
"Bob: Hello Tim.",
"Tim: Hello Bob.",
"Bob: How are ya Tim?",
"Frank: Stop chatting!"
}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Bob"; int Arg2 = 2; verify_case(0, Arg2, howMany(Arg0, Arg1)); }
void test_case_1() { string Arr0[] = {
"Bob: This is a long",
"sentence that takes 2 lines.",
"Tim: Yes it is.",
"Bob : I am not Bob.",
"Frank: No you aren't!",
" Bob: Neither am I."
}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Bob"; int Arg2 = 1; verify_case(1, Arg2, howMany(Arg0, Arg1)); }
void test_case_2() { string Arr0[] = {
"Crazy1010: !@LK%#L%K @#L%K @#L%K@#L%K2kl53k2",
"Bob: You are crazy.",
"Crazy1010 Yup #@LK%$L!K%LK%!K% !K afmas,"
}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "Crazy1010"; int Arg2 = 1; verify_case(2, Arg2, howMany(Arg0, Arg1)); }
void test_case_3() { string Arr0[] = {
"A:A:A:A:A:A:A:A:A",
"b:b:b:b:b:b:b:b:b"
}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "B"; int Arg2 = 0; verify_case(3, Arg2, howMany(Arg0, Arg1)); }
void test_case_4() { string Arr0[] = {"A:A:A:A:A:A:A:A:A"}; vector <string> Arg0(Arr0, Arr0 + (sizeof(Arr0) / sizeof(Arr0[0]))); string Arg1 = "A"; int Arg2 = 1; verify_case(4, Arg2, howMany(Arg0, Arg1)); }
// END CUT HERE
};
// BEGIN CUT HERE
int main()
{
ChatTranscript ___test;
___test.run_test(-1);
}
// END CUT HERE
| 36.719512 | 309 | 0.580206 | ibudiselic |
03f69f8a989c6df70458ffdf05d0b5b3ca851d46 | 2,651 | cpp | C++ | code/ch_4-STRUCTURAL_PATTERNS/05-facade/main.cpp | ordinary-developer/book_design_patterns_4_d_e_gamma_r_helm_r_johnson_j_vlissides | 69b80ee82446e15e9f76547a3fe5cb71e8e0e147 | [
"MIT"
] | null | null | null | code/ch_4-STRUCTURAL_PATTERNS/05-facade/main.cpp | ordinary-developer/book_design_patterns_4_d_e_gamma_r_helm_r_johnson_j_vlissides | 69b80ee82446e15e9f76547a3fe5cb71e8e0e147 | [
"MIT"
] | null | null | null | code/ch_4-STRUCTURAL_PATTERNS/05-facade/main.cpp | ordinary-developer/book_design_patterns_4_d_e_gamma_r_helm_r_johnson_j_vlissides | 69b80ee82446e15e9f76547a3fe5cb71e8e0e147 | [
"MIT"
] | null | null | null |
class CodeGenerator;
class ProgramNode {
public:
ProgramNode() = default;
virtual ~ProgramNode() = default;
virtual void GetSourcePotision(int& line, int& index) { }
virtual void Add(ProgramNode*) { }
virtual void Remove(ProgramNode*) { }
virtual void Traverse(CodeGenerator&) { }
};
class ProgramNodeBuilder {
public:
ProgramNodeBuilder() : _node(new ProgramNode()) { }
virtual ~ProgramNodeBuilder() = default;
virtual ProgramNode*
NewVariable(const char* variableName) const
{
return new ProgramNode();
}
virtual ProgramNode* NewAssignment(ProgramNode* variable,
ProgramNode* expr) const
{
return new ProgramNode();
}
virtual ProgramNode* NewReturnStatement(ProgramNode* value)
const
{
return new ProgramNode();
}
virtual ProgramNode* NewCondition(ProgramNode* condition,
ProgramNode* truePart,
ProgramNode* falsePart) const
{
return new ProgramNode();
}
ProgramNode* GetRootNode() { return _node; }
private:
ProgramNode* _node;
};
class Stream { };
class Token { };
class Scanner {
public:
Scanner(Stream& inputStream)
: _inputStream(inputStream) { }
virtual ~Scanner() = default;
virtual Token& Scan() { return _token; }
private:
Token _token;
Stream& _inputStream;
};
class Parser {
public:
Parser() = default;
virtual ~Parser() = default;
virtual void Parse(Scanner&, ProgramNodeBuilder&) { }
};
class BytecodeStream { };
class CodeGenerator {
public:
CodeGenerator(BytecodeStream& output)
: _output(output) { }
virtual void Visit(ProgramNode*) { }
private:
BytecodeStream& _output;
};
class Compiler {
public:
Compiler() = default;
virtual void Compile(Stream& input, BytecodeStream& output) {
Scanner scanner(input);
ProgramNodeBuilder builder;
Parser parser;
parser.Parse(scanner, builder);
CodeGenerator generator(output);
ProgramNode* parseTree = builder.GetRootNode();
parseTree->Traverse(generator);
}
};
int main() {
Stream input;
BytecodeStream output;
Compiler().Compile(input, output);
return 0;
}
| 22.65812 | 71 | 0.548472 | ordinary-developer |
03f8b61fb1f009bd5d97ff79b04ea8309f11f927 | 9,152 | cpp | C++ | src/components/store/nvmestore/unit_test/test-nvmestore.cpp | fengggli/comanche | 035f2a87e0236e9ff744c10331250dcfab835ee1 | [
"Apache-2.0"
] | null | null | null | src/components/store/nvmestore/unit_test/test-nvmestore.cpp | fengggli/comanche | 035f2a87e0236e9ff744c10331250dcfab835ee1 | [
"Apache-2.0"
] | 13 | 2019-06-12T17:50:29.000Z | 2019-08-08T21:15:16.000Z | src/components/store/nvmestore/unit_test/test-nvmestore.cpp | fengggli/comanche | 035f2a87e0236e9ff744c10331250dcfab835ee1 | [
"Apache-2.0"
] | 1 | 2019-07-26T21:39:13.000Z | 2019-07-26T21:39:13.000Z | /*
* (C) Copyright IBM Corporation 2018. All rights reserved.
*
*/
/*
* Authors:
*
* Feng Li (fengggli@yahoo.com)
*
*/
/* note: we do not include component source, only the API definition */
#include "data.h"
#include <gtest/gtest.h>
#include <common/utils.h>
#include <common/str_utils.h>
#include <core/physical_memory.h>
#include <api/components.h>
#include <api/kvstore_itf.h>
#include <api/block_itf.h>
#include <api/block_allocator_itf.h>
#include <stdlib.h>
#include <gperftools/profiler.h>
#define PMEM_PATH "/mnt/pmem0/pool-nvmestore"
#define POOL_NAME "test-basic.pool"
#define DO_BASIC_TEST
//#define USE_FILESTORE
#undef USE_FILESTORE
using namespace Component;
struct
{
std::string pci;
} opt;
namespace {
// The fixture for testing class Foo.
class KVStore_test : public ::testing::Test {
protected:
// If the constructor and destructor are not enough for setting up
// and cleaning up each test, you can define the following methods:
virtual void SetUp() {
// Code here will be called immediately after the constructor (right
// before each test).
}
virtual void TearDown() {
// Code here will be called immediately after each test (right
// before the destructor).
}
// Objects declared here can be used by all tests in the test case
static Component::IKVStore * _kvstore;
static Component::IKVStore * _kvstore2;
static Component::IKVStore::pool_t _pool;
static bool _pool_is_reopen; // this run is open a previously created pool
using kv_t = std::tuple<std::string, std::string>;
static std::vector<kv_t> kvv;
static constexpr unsigned single_value_length = MB(8);
};
Component::IKVStore * KVStore_test::_kvstore;
Component::IKVStore * KVStore_test::_kvstore2;
Component::IKVStore::pool_t KVStore_test::_pool;
bool KVStore_test::_pool_is_reopen;
constexpr unsigned KVStore_test::single_value_length;
std::vector<KVStore_test::kv_t> KVStore_test::kvv;
TEST_F(KVStore_test, Instantiate)
{
/* create object instance through factory */
#ifndef USE_FILESTORE
Component::IBase * comp = Component::load_component("libcomanche-nvmestore.so",
Component::nvmestore_factory);
ASSERT_TRUE(comp);
IKVStore_factory * fact = (IKVStore_factory *) comp->query_interface(IKVStore_factory::iid());
// this nvme-store use a block device and a block allocator
_kvstore = fact->create("owner","name", opt.pci);
#else
Component::IBase * comp = Component::load_component("libcomanche-storefile.so",
Component::filestore_factory);
ASSERT_TRUE(comp);
IKVStore_factory * fact = (IKVStore_factory *) comp->query_interface(IKVStore_factory::iid());
// this nvme-store use a block device and a block allocator
_kvstore = fact->create("owner","name");
#endif
fact->release_ref();
}
TEST_F(KVStore_test, OpenPool)
{
PLOG(" test-nvmestore: try to openpool");
ASSERT_TRUE(_kvstore);
// pass blk and alloc here
std::string pool_path;
std::string pool_name;
pool_name = "basic-nr-"+std::to_string(Data::NUM_ELEMENTS) + "-sz-" + std::to_string(Data::VAL_LEN)+ ".pool";
#ifndef USE_FILESTORE
pool_path = PMEM_PATH;
#else
pool_path = "./";
#endif
try{
_pool = _kvstore->create_pool(pool_path + pool_name, MB(128));
_pool_is_reopen = false;
}
catch(...){
// open the pool if it exists
_pool = _kvstore->open_pool(pool_path + pool_name);
_pool_is_reopen = true;
PINF("NVMEStore:open a exsiting pool instead!");
}
ASSERT_TRUE(_pool > 0);
}
#ifdef DO_BASIC_TEST
TEST_F(KVStore_test, BasicPut)
{
ASSERT_TRUE(_pool);
std::string key = "MyKey";
std::string value = "Hello world!";
// value.resize(value.length()+1); /* append /0 */
value.resize(single_value_length);
kvv.emplace_back(key, value);
EXPECT_TRUE(S_OK == _kvstore->put(_pool, key, value.c_str(), value.length()));
}
TEST_F(KVStore_test, GetDirect)
{
/*Register Mem is only from gdr memory*/
//ASSERT_TRUE(S_OK == _kvstore->register_direct_memory(user_buf, MB(8)));
io_buffer_t handle;
Core::Physical_memory mem_alloc; // aligned and pinned mem allocator, TODO: should be provided through IZerocpy Memory interface of NVMestore
std::string key = "MyKey";
void * value = nullptr;
size_t value_len = 0;
handle = mem_alloc.allocate_io_buffer(single_value_length, 4096, Component::NUMA_NODE_ANY);
ASSERT_TRUE(handle);
value = mem_alloc.virt_addr(handle);
_kvstore->get_direct(_pool, key, value, value_len, 0);
EXPECT_FALSE(strcmp("Hello world!", (char*)value));
PINF("Value=(%.50s) %lu", ((char*)value), value_len);
mem_alloc.free_io_buffer(handle);
}
TEST_F(KVStore_test, BasicGet)
{
std::string key = "MyKey";
void * value = nullptr;
size_t value_len = 0;
_kvstore->get(_pool, key, value, value_len);
EXPECT_FALSE(strcmp("Hello world!", (char*)value));
PINF("Value=(%.50s) %lu", ((char*)value), value_len);
free(value);
}
// TEST_F(KVStore_test, BasicGetRef)
// {
// std::string key = "MyKey";
// void * value = nullptr;
// size_t value_len = 0;
// _kvstore->get_reference(_pool, key, value, value_len);
// PINF("Ref Value=(%.50s) %lu", ((char*)value), value_len);
// _kvstore->release_reference(_pool, value);
// }
#if 0
TEST_F(KVStore_test, BasicMap)
{
_kvstore->map(_pool,[](uint64_t key,
const void * value,
const size_t value_len) -> int
{
PINF("key:%lx value@%p value_len=%lu", key, value, value_len);
return 0;;
});
}
#endif
/* lock */
TEST_F(KVStore_test, LockBasic)
{
unsigned ct = 0;
Component::IKVStore::pool_t pool = _pool;
for ( auto &kv : kvv )
{
//if ( ct == lock_count ) { break; }
const auto &key = std::get<0>(kv);
const auto &ev = std::get<1>(kv);
const auto key_new = std::get<0>(kv) + "x";
void *value0 = nullptr;
std::size_t value0_len = 0;
auto r0 = _kvstore->lock(pool, key, IKVStore::STORE_LOCK_READ, value0, value0_len);
EXPECT_NE(r0, nullptr);
EXPECT_EQ(value0_len, single_value_length);
EXPECT_EQ(0, memcmp(ev.data(), value0, ev.size()));
void * value1 = nullptr;
std::size_t value1_len = 0;
auto r1 = _kvstore->lock(pool, key, IKVStore::STORE_LOCK_READ, value1, value1_len);
EXPECT_NE(r1, nullptr);
EXPECT_EQ(value1_len, single_value_length);
EXPECT_EQ(0, memcmp(ev.data(), value1, ev.size()));
/* Exclusive locking test. Skip if the library is built without locking. */
if ( _kvstore->thread_safety() == IKVStore::THREAD_MODEL_MULTI_PER_POOL )
{
void * value2 = nullptr;
std::size_t value2_len = 0;
auto r2 = _kvstore->lock(pool, key, IKVStore::STORE_LOCK_WRITE, value2, value2_len);
EXPECT_EQ(r2, nullptr);
}
void * value3 = nullptr;
std::size_t value3_len = single_value_length;
auto r3 = _kvstore->lock(pool, key_new, IKVStore::STORE_LOCK_WRITE, value3, value3_len);
EXPECT_NE(r3, nullptr);
EXPECT_EQ(value3_len, single_value_length);
EXPECT_NE(value3, nullptr);
auto r0x = _kvstore->unlock(pool, r0);
EXPECT_EQ(r0x, S_OK);
auto r1x = _kvstore->unlock(pool, r1);
EXPECT_EQ(r1x, S_OK);
auto r3x = _kvstore->unlock(pool, r3);
EXPECT_EQ(r3x, S_OK);
++ct;
}
}
TEST_F(KVStore_test, BasicErase)
{
_kvstore->erase(_pool, "MyKey");
}
TEST_F(KVStore_test, BasicApply)
{
void * data;
size_t data_len = 0;
std::string key = "Elephant";
PLOG("Allocate: key_hash=%s", key.c_str());
PLOG("test 1");
ASSERT_TRUE(_kvstore->apply(_pool, key,
[](void*p, const size_t plen) { memset(p,0xE,plen); },
MB(8),
true) == S_OK);
_kvstore->get(_pool, key, data, data_len);
EXPECT_EQ(MB(8), data_len);
EXPECT_EQ(0xE, *(char *)data);
EXPECT_EQ(0xE, *((char *)data+5));
}
#endif
#ifdef DO_ERASE
TEST_F(KVStore_test, ErasePool)
{
_kvstore->delete_pool(_pool);
}
#endif
TEST_F(KVStore_test, ClosePool)
{
_kvstore->close_pool(_pool);
}
/*
* multiple store on same nvmedevice will use the same _block and the _blk_alloc
*/
TEST_F(KVStore_test, Multiplestore)
{
/* create object instance through factory */
Component::IBase * comp = Component::load_component("libcomanche-nvmestore.so",
Component::nvmestore_factory);
ASSERT_TRUE(comp);
IKVStore_factory * fact = (IKVStore_factory *) comp->query_interface(IKVStore_factory::iid());
// this nvme-store use a block device and a block allocator
_kvstore2 = fact->create("owner","name2", opt.pci);
fact->release_ref();
_pool = _kvstore2->create_pool(PMEM_PATH "test-nvme2.pool", MB(128));
_kvstore2->release_ref();
}
TEST_F(KVStore_test, ReleaseStore)
{
_kvstore->release_ref();
}
} // namespace
int main(int argc, char **argv) {
if(argc!=2) {
PINF("test-nvmestore <pci-address>");
return 0;
}
opt.pci = argv[1];
::testing::InitGoogleTest(&argc, argv);
auto r = RUN_ALL_TESTS();
return r;
}
| 26 | 144 | 0.662697 | fengggli |
03fc84a50e04e2d8e75f2c8d959ca73530426dd9 | 5,450 | cpp | C++ | dependencies/MyGui/Tools/SkinEditor/SeparatorListControl.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 5 | 2016-04-18T23:12:51.000Z | 2022-03-06T05:12:07.000Z | dependencies/MyGui/Tools/SkinEditor/SeparatorListControl.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 2 | 2015-10-09T19:13:25.000Z | 2018-12-25T17:16:54.000Z | dependencies/MyGui/Tools/SkinEditor/SeparatorListControl.cpp | amvb/GUCEF | 08fd423bbb5cdebbe4b70df24c0ae51716b65825 | [
"Apache-2.0"
] | 15 | 2015-02-23T16:35:28.000Z | 2022-03-25T13:40:33.000Z | /*!
@file
@author Albert Semenov
@date 08/2010
*/
#include "Precompiled.h"
#include "SeparatorListControl.h"
#include "SkinManager.h"
#include "Binary.h"
#include "Localise.h"
namespace tools
{
enum SeparatorPreset
{
SeparatorPresetScale = Binary<0>::value,
SeparatorPreset9Slice = Binary<1111>::value,
SeparatorPreset3SliceHorScale = Binary<1100>::value,
SeparatorPreset3SliceVertScale = Binary<11>::value
};
SeparatorListControl::SeparatorListControl(MyGUI::Widget* _parent) :
wraps::BaseLayout("SeparatorListControl.layout", _parent),
mList(nullptr),
mPresets(nullptr)
{
mTypeName = MyGUI::utility::toString((size_t)this);
assignWidget(mList, "List");
assignWidget(mPresets, "Presets");
fillPresets();
mList->eventListChangePosition += MyGUI::newDelegate(this, &SeparatorListControl::notifyChangePosition);
mPresets->eventComboChangePosition += MyGUI::newDelegate(this, &SeparatorListControl::notifyComboChangePosition);
initialiseAdvisor();
}
SeparatorListControl::~SeparatorListControl()
{
shutdownAdvisor();
mPresets->eventComboChangePosition -= MyGUI::newDelegate(this, &SeparatorListControl::notifyComboChangePosition);
mList->eventListChangePosition -= MyGUI::newDelegate(this, &SeparatorListControl::notifyChangePosition);
}
void SeparatorListControl::notifyChangePosition(MyGUI::ListBox* _sender, size_t _index)
{
if (getCurrentSkin() != nullptr)
{
SeparatorItem* item = nullptr;
if (_index != MyGUI::ITEM_NONE)
item = *mList->getItemDataAt<SeparatorItem*>(_index);
getCurrentSkin()->getSeparators().setItemSelected(item);
}
}
void SeparatorListControl::updateSeparatorProperty(Property* _sender, const MyGUI::UString& _owner)
{
if (_sender->getName() == "Visible")
updateList();
if (_owner != mTypeName)
updatePreset();
}
void SeparatorListControl::updateSeparatorProperties()
{
updateList();
}
void SeparatorListControl::updateSkinProperties()
{
updatePreset();
}
void SeparatorListControl::updateList()
{
if (getCurrentSkin() != nullptr)
{
SeparatorItem* selectedItem = getCurrentSkin()->getSeparators().getItemSelected();
size_t selectedIndex = MyGUI::ITEM_NONE;
size_t index = 0;
ItemHolder<SeparatorItem>::EnumeratorItem separators = getCurrentSkin()->getSeparators().getChildsEnumerator();
while (separators.next())
{
SeparatorItem* item = separators.current();
MyGUI::UString name;
if (item->getPropertySet()->getPropertyValue("Visible") != "True")
name = replaceTags("ColourDisabled") + item->getName();
else
name = item->getName();
if (index < mList->getItemCount())
{
mList->setItemNameAt(index, name);
mList->setItemDataAt(index, item);
}
else
{
mList->addItem(name, item);
}
if (item == selectedItem)
selectedIndex = index;
index ++;
}
while (index < mList->getItemCount())
mList->removeItemAt(mList->getItemCount() - 1);
mList->setIndexSelected(selectedIndex);
}
}
void SeparatorListControl::fillPresets()
{
mPresets->removeAllItems();
mPresets->addItem(replaceTags("PresetRegionOneScale"), SeparatorPresetScale);
mPresets->addItem(replaceTags("PresetRegion9Grid"), SeparatorPreset9Slice);
mPresets->addItem(replaceTags("PresetRegion3Hor"), SeparatorPreset3SliceHorScale);
mPresets->addItem(replaceTags("PresetRegion3Vert"), SeparatorPreset3SliceVertScale);
mPresets->beginToItemFirst();
}
void SeparatorListControl::notifyComboChangePosition(MyGUI::ComboBox* _sender, size_t _index)
{
if (getCurrentSkin() == nullptr)
return;
if (_index == MyGUI::ITEM_NONE)
return;
SeparatorPreset preset = *_sender->getItemDataAt<SeparatorPreset>(_index);
size_t index = 0;
ItemHolder<SeparatorItem>::EnumeratorItem separators = getCurrentSkin()->getSeparators().getChildsEnumerator();
while (separators.next())
{
SeparatorItem* item = separators.current();
MyGUI::UString value = ((preset & (1 << index)) != 0) ? "True" : "False";
item->getPropertySet()->setPropertyValue("Visible", value, mTypeName);
++index;
}
// для обновления пропертей
getCurrentSkin()->getSeparators().setItemSelected(nullptr);
updateList();
}
void SeparatorListControl::updatePreset()
{
mPresets->setEnabled(getCurrentSkin() != nullptr);
if (getCurrentSkin() != nullptr)
{
int currentPreset = 0;
int bitIndex = 0;
ItemHolder<SeparatorItem>::EnumeratorItem separators = getCurrentSkin()->getSeparators().getChildsEnumerator();
while (separators.next())
{
SeparatorItem* item = separators.current();
bool visible = item->getPropertySet()->getPropertyValue("Visible") == "True";
if (visible)
currentPreset |= (1 << bitIndex);
++ bitIndex;
}
size_t indexSelected = MyGUI::ITEM_NONE;
size_t count = mPresets->getItemCount();
for (size_t index = 0; index < count; ++index)
{
SeparatorPreset preset = *mPresets->getItemDataAt<SeparatorPreset>(index);
if (preset == currentPreset)
{
indexSelected = index;
break;
}
}
mPresets->setIndexSelected(indexSelected);
mPresets->setEnabled(true);
}
else
{
mPresets->setEnabled(false);
}
}
} // namespace tools
| 26.585366 | 116 | 0.682569 | amvb |
03fdb20e35d65e9e83ef0bcf18bd3b06a3595462 | 3,405 | cxx | C++ | Modules/Filtering/FFT/test/itkVnlFFTWD_FFTTest.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 2 | 2019-09-15T10:17:06.000Z | 2019-09-15T10:19:06.000Z | Modules/Filtering/FFT/test/itkVnlFFTWD_FFTTest.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | null | null | null | Modules/Filtering/FFT/test/itkVnlFFTWD_FFTTest.cxx | lassoan/ITK | 4634cb0490934f055065230e3db64df8f546b72a | [
"Apache-2.0"
] | 1 | 2021-09-23T08:33:37.000Z | 2021-09-23T08:33:37.000Z | /*=========================================================================
*
* Copyright Insight Software Consortium
*
* 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.txt
*
* 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 "itkFFTTest.h"
#if defined(ITK_USE_FFTWD)
// Compare FFT using VNL and FFTW Libraries. The test is performed for 2 3d
// array one of them having the same dimension(4,4,4) and the other having
// different dimensions (3,4,5). Images are created with different dimensions
// in the test function based on the second template argument and the size
// of these dimensions are taken from the array.The data types used are float
// and double.
int
itkVnlFFTWD_FFTTest(int, char *[])
{
using ImageD1 = itk::Image<double, 1>;
using ImageD2 = itk::Image<double, 2>;
using ImageD3 = itk::Image<double, 3>;
# ifndef ITK_USE_CUFFTW
std::cout << "WriteWisdomCache " << itk::FFTWGlobalConfiguration::GetWriteWisdomCache() << std::endl;
std::cout << "ReadWisdomCache " << itk::FFTWGlobalConfiguration::GetReadWisdomCache() << std::endl;
std::cout << "PlanRigor " << itk::FFTWGlobalConfiguration::GetPlanRigor() << std::endl;
std::cout << "WisdomCacheBase " << itk::FFTWGlobalConfiguration::GetWisdomCacheBase() << std::endl;
std::cout << "WisdomeFile " << itk::FFTWGlobalConfiguration::GetWisdomFileDefaultBaseName() << std::endl;
# endif
unsigned int SizeOfDimensions1[] = { 4, 4, 4 };
unsigned int SizeOfDimensions2[] = { 3, 5, 4 };
int rval = 0;
std::cerr << "VnlFFTWD:double,1 (4,4,4)" << std::endl;
if ((test_fft_rtc<double, 1, itk::VnlForwardFFTImageFilter<ImageD1>, itk::FFTWForwardFFTImageFilter<ImageD1>>(
SizeOfDimensions1)) != 0)
rval++;
std::cerr << "VnlFFTWD:double,2 (4,4,4)" << std::endl;
if ((test_fft_rtc<double, 2, itk::VnlForwardFFTImageFilter<ImageD2>, itk::FFTWForwardFFTImageFilter<ImageD2>>(
SizeOfDimensions1)) != 0)
rval++;
std::cerr << "VnlFFTWD:double,3 (4,4,4)" << std::endl;
if ((test_fft_rtc<double, 3, itk::VnlForwardFFTImageFilter<ImageD3>, itk::FFTWForwardFFTImageFilter<ImageD3>>(
SizeOfDimensions1)) != 0)
rval++;
std::cerr << "VnlFFTWD:double,1 (3,5,4)" << std::endl;
if ((test_fft_rtc<double, 1, itk::VnlForwardFFTImageFilter<ImageD1>, itk::FFTWForwardFFTImageFilter<ImageD1>>(
SizeOfDimensions2)) != 0)
rval++;
std::cerr << "VnlFFTWD:double,2 (3,5,4)" << std::endl;
if ((test_fft_rtc<double, 2, itk::VnlForwardFFTImageFilter<ImageD2>, itk::FFTWForwardFFTImageFilter<ImageD2>>(
SizeOfDimensions2)) != 0)
rval++;
std::cerr << "VnlFFTWD:double,3 (3,5,4)" << std::endl;
if ((test_fft_rtc<double, 3, itk::VnlForwardFFTImageFilter<ImageD3>, itk::FFTWForwardFFTImageFilter<ImageD3>>(
SizeOfDimensions2)) != 0)
rval++;
return (rval == 0) ? 0 : -1;
}
#endif
| 45.4 | 112 | 0.659325 | lassoan |
03ff25390780aa564c57c1f4fba9cd900c2cde99 | 1,350 | cpp | C++ | attacker/SSL/AttackSplitPacket.cpp | satadriver/attacker | 24e4434d8a836e040e48df195f2ca8919ab52609 | [
"Apache-2.0"
] | null | null | null | attacker/SSL/AttackSplitPacket.cpp | satadriver/attacker | 24e4434d8a836e040e48df195f2ca8919ab52609 | [
"Apache-2.0"
] | null | null | null | attacker/SSL/AttackSplitPacket.cpp | satadriver/attacker | 24e4434d8a836e040e48df195f2ca8919ab52609 | [
"Apache-2.0"
] | 1 | 2022-03-20T03:21:00.000Z | 2022-03-20T03:21:00.000Z |
#include "AttackSplitPacket.h"
#include "../HttpUtils.h"
char *iqiyiandroidhdr = "GET /fusion/3.0/plugin?";
int iqiyiandroidhdrlen = lstrlenA(iqiyiandroidhdr);
char * qqnewshdr = "GET /getVideoSo?version=";
int qqnewshdrlen = lstrlenA(qqnewshdr);
int AttackSplitPacket::splitPacket(char * recvbuf, int &icount, LPHTTPPROXYPARAM lphttp,
string & httphdr, char ** httpdata, string &url, string & host, int &port) {
for(int i = 0; i < 8; i ++)
{
if (icount >= 8192)
{
break;
}
int nextlen = recv(lphttp->sockToClient, recvbuf + icount, NETWORK_BUFFER_SIZE - icount, 0);
if (nextlen <= 0)
{
break;
}
else {
icount += nextlen;
*(recvbuf + icount) = 0;
}
}
int type = 0;
return HttpUtils::parseHttpHdr(recvbuf, icount, type, httphdr, httpdata, url, host, port);
}
int AttackSplitPacket::splitPacket(char * recvbuf, int &icount, LPSSLPROXYPARAM lpssl,
string & httphdr, char ** httpdata, string &url, string &host, int &port) {
for (int i = 0; i < 8; i++) {
if (icount >= 8192)
{
break;
}
int nextlen = SSL_read(lpssl->SSLToClient, recvbuf + icount, NETWORK_BUFFER_SIZE - icount);
if (nextlen <= 0)
{
break;
}
else {
icount += nextlen;
*(recvbuf + icount) = 0;
}
}
int type = 0;
return HttpUtils::parseHttpHdr(recvbuf, icount, type, httphdr, httpdata, url, host, port);
} | 21.774194 | 94 | 0.651852 | satadriver |
ff00326efae8a6e4994ce48a01ba5c5cf6a8a509 | 10,086 | ipp | C++ | protean/detail/data_table_variant_iterator.ipp | llawall/protean | 31496f177704dc31b24cda5863e5ca921f5f0945 | [
"BSL-1.0"
] | null | null | null | protean/detail/data_table_variant_iterator.ipp | llawall/protean | 31496f177704dc31b24cda5863e5ca921f5f0945 | [
"BSL-1.0"
] | null | null | null | protean/detail/data_table_variant_iterator.ipp | llawall/protean | 31496f177704dc31b24cda5863e5ca921f5f0945 | [
"BSL-1.0"
] | null | null | null | // (C) Copyright Johan Ditmar, Karel Hruda, Paul O'Neill & Luke Stedman 2009.
// Use, modification and distribution are subject to the Boost Software License,
// Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt).
#include <algorithm>
namespace protean { namespace detail {
/* Column iterator implementations */
/***********************************/
template <typename T, typename IteratorTraits>
data_table_column_variant_iterator_interface<T, IteratorTraits>::
data_table_column_variant_iterator_interface(const source_iterator_type& iterator)
: m_iterator(iterator)
{}
template <typename T, typename IteratorTraits>
const std::string& data_table_column_variant_iterator_interface<T, IteratorTraits>::key() const
{
boost::throw_exception(variant_error("Attempt to call key() on data table column variant iterator"));
}
template <typename T, typename IteratorTraits>
//const typename data_table_column_variant_iterator_interface<T, IteratorTraits>::base::date_time_t&
const typename data_table_column_variant_iterator_interface<T, IteratorTraits>::date_time_type&
data_table_column_variant_iterator_interface<T, IteratorTraits>::time() const
{
boost::throw_exception(variant_error("Attempt to call time() on data table column variant iterator"));
}
template <typename T, typename IteratorTraits>
typename data_table_column_variant_iterator_interface<T, IteratorTraits>::reference
data_table_column_variant_iterator_interface<T, IteratorTraits>::value() const
{
make_copy<T>();
return m_copy;
}
template <typename T, typename IteratorTraits>
void data_table_column_variant_iterator_interface<T, IteratorTraits>::increment()
{
++m_iterator;
}
template <typename T, typename IteratorTraits>
void data_table_column_variant_iterator_interface<T, IteratorTraits>::decrement()
{
--m_iterator;
}
template <typename T, typename IteratorTraits>
bool data_table_column_variant_iterator_interface<T, IteratorTraits>::equal(const variant_const_iterator_base* rhs) const
{
const data_table_column_variant_iterator_interface<T>* cast_rhs =
dynamic_cast<const data_table_column_variant_iterator_interface<T>*>(rhs);
if (cast_rhs == 0)
boost::throw_exception(variant_error("Unable to convert iterator to data table column variant iterator"));
return m_iterator == cast_rhs->m_iterator;
}
template <typename T, typename IteratorTraits>
typename data_table_column_variant_iterator_interface<T, IteratorTraits>::base*
data_table_column_variant_iterator_interface<T, IteratorTraits>::clone()
{
return new data_table_column_variant_iterator_interface(m_iterator);
}
template <typename T, typename IteratorTraits>
variant_const_iterator_base* data_table_column_variant_iterator_interface<T, IteratorTraits>::to_const() const
{
return new data_table_column_variant_iterator_interface<T, const_iterator_traits>(m_iterator);
}
/* Variant column specialization */
/*********************************/
template <typename IteratorTraits>
data_table_column_variant_iterator_interface<variant, IteratorTraits>::
data_table_column_variant_iterator_interface(const source_iterator_type& iterator)
: m_iterator(iterator)
{}
template <typename IteratorTraits>
const std::string& data_table_column_variant_iterator_interface<variant, IteratorTraits>::key() const
{
boost::throw_exception(variant_error("Attempt to call key() on data table column variant iterator"));
}
template <typename IteratorTraits>
const typename data_table_column_variant_iterator_interface<variant, IteratorTraits>::date_time_type&
data_table_column_variant_iterator_interface<variant, IteratorTraits>::time() const
{
boost::throw_exception(variant_error("Attempt to call time() on data table column variant iterator"));
}
template <typename IteratorTraits>
typename data_table_column_variant_iterator_interface<variant, IteratorTraits>::reference
data_table_column_variant_iterator_interface<variant, IteratorTraits>::value() const
{
return *m_iterator;
}
template <typename IteratorTraits>
void data_table_column_variant_iterator_interface<variant, IteratorTraits>::increment()
{
++m_iterator;
}
template <typename IteratorTraits>
void data_table_column_variant_iterator_interface<variant, IteratorTraits>::decrement()
{
--m_iterator;
}
template <typename IteratorTraits>
bool data_table_column_variant_iterator_interface<variant, IteratorTraits>::
equal(const variant_const_iterator_base* rhs) const
{
const data_table_column_variant_iterator_interface<variant>* cast_rhs =
dynamic_cast<const data_table_column_variant_iterator_interface<variant>*>(rhs);
if (cast_rhs == 0)
boost::throw_exception(variant_error("Unable to convert iterator to data table column variant iterator"));
return m_iterator == cast_rhs->m_iterator;
}
template <typename IteratorTraits>
typename data_table_column_variant_iterator_interface<variant, IteratorTraits>::base*
data_table_column_variant_iterator_interface<variant, IteratorTraits>::clone()
{
return new data_table_column_variant_iterator_interface(m_iterator);
}
template <typename IteratorTraits>
variant_const_iterator_base* data_table_column_variant_iterator_interface<variant, IteratorTraits>::
to_const() const
{
return new data_table_column_variant_iterator_interface<variant, const_iterator_traits>(m_iterator);
}
/* Row iterator implementations */
/********************************/
template <
typename IteratorTraits,
typename Base
>
data_table_variant_iterator_interface<IteratorTraits, Base>::
data_table_variant_iterator_interface(const column_iterator_container& column_iterators)
: m_column_iterators(column_iterators)
{}
template <
typename IteratorTraits,
typename Base
>
const std::string& data_table_variant_iterator_interface<IteratorTraits, Base>::key() const
{
boost::throw_exception(variant_error("Attempt to call key() on data table variant iterator"));
}
template <
typename IteratorTraits,
typename Base
>
const typename Base::date_time_t& data_table_variant_iterator_interface<IteratorTraits, Base>::time() const
{
boost::throw_exception(variant_error("Attempt to call time() on data table"));
}
template <
typename IteratorTraits,
typename Base
>
typename data_table_variant_iterator_interface<IteratorTraits, Base>::reference
data_table_variant_iterator_interface<IteratorTraits, Base>::value() const
{
variant tuple(variant_base::Tuple, m_column_iterators.size());
for (size_t i = 0; i < m_column_iterators.size(); ++i)
tuple.at(i) = *(m_column_iterators[i]);
m_copy = tuple;
return m_copy;
}
template <
typename IteratorTraits,
typename Base
>
void data_table_variant_iterator_interface<IteratorTraits, Base>::increment()
{
for (typename column_iterator_container::iterator iter = m_column_iterators.begin()
; iter != m_column_iterators.end()
; ++iter)
++(*iter);
}
template <
typename IteratorTraits,
typename Base
>
void data_table_variant_iterator_interface<IteratorTraits, Base>::decrement()
{
for (typename column_iterator_container::iterator iter = m_column_iterators.begin()
; iter != m_column_iterators.end()
; ++iter)
--(*iter);
}
template <
typename IteratorTraits,
typename Base
>
bool data_table_variant_iterator_interface<IteratorTraits, Base>::equal(const variant_const_iterator_base* rhs) const
{
const data_table_variant_iterator_interface<const_iterator_traits>* cast_rhs =
dynamic_cast<const data_table_variant_iterator_interface<const_iterator_traits>*>(rhs);
if (cast_rhs == 0)
boost::throw_exception(variant_error("Unable to convert iterator to data table variant iterator"));
if (m_column_iterators.size() != cast_rhs->m_column_iterators.size())
boost::throw_exception(variant_error("Unable to compare variant iterators of two DataTables that have a different number of columns"));
for (size_t i = 0; i < m_column_iterators.size(); ++i)
if (m_column_iterators[i] != cast_rhs->m_column_iterators[i])
return false;
return true;
}
template <
typename IteratorTraits,
typename Base
>
Base* data_table_variant_iterator_interface<IteratorTraits, Base>::clone()
{
return new data_table_variant_iterator_interface(m_column_iterators);
}
template <
typename IteratorTraits,
typename Base
>
variant_const_iterator_base* data_table_variant_iterator_interface<IteratorTraits, Base>::to_const() const
{
typedef typename data_table_variant_iterator_interface<const_iterator_traits>::column_iterator_container
const_column_iterator_container;
const_column_iterator_container const_column_iterators;
const_column_iterators.reserve( m_column_iterators.size() );
std::copy( m_column_iterators.begin(), m_column_iterators.end(), std::back_inserter( const_column_iterators ) );
return new data_table_variant_iterator_interface<const_iterator_traits>(const_column_iterators);
}
}} // namespace protean::detail
| 38.496183 | 147 | 0.706226 | llawall |
ff0047913e194669a248b5e48f3d40f365114b8c | 1,058 | hpp | C++ | module-gui/test/test-google/TestBoxLayout.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 369 | 2021-11-10T09:20:29.000Z | 2022-03-30T06:36:58.000Z | module-gui/test/test-google/TestBoxLayout.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 149 | 2021-11-10T08:38:35.000Z | 2022-03-31T23:01:52.000Z | module-gui/test/test-google/TestBoxLayout.hpp | bitigchi/MuditaOS | 425d23e454e09fd6ae274b00f8d19c57a577aa94 | [
"BSL-1.0"
] | 41 | 2021-11-10T08:30:37.000Z | 2022-03-29T08:12:46.000Z | // Copyright (c) 2017-2021, Mudita Sp. z.o.o. All rights reserved.
// For licensing, see https://github.com/mudita/MuditaOS/LICENSE.md
#pragma once
#include <gtest/gtest.h>
#include <module-gui/gui/widgets/BoxLayout.hpp>
class TestBoxLayout : public gui::BoxLayout
{
public:
friend class BoxLayoutTesting;
FRIEND_TEST(BoxLayoutTesting, Constructor_Destructor_Test);
FRIEND_TEST(BoxLayoutTesting, Fill_Box_Test);
FRIEND_TEST(BoxLayoutTesting, Navigate_Test);
FRIEND_TEST(BoxLayoutTesting, Border_Callback_Test);
FRIEND_TEST(BoxLayoutTesting, Box_Alignment_Test);
FRIEND_TEST(BoxLayoutTesting, Box_Widget_Min_Max_Resize_Test);
FRIEND_TEST(BoxLayoutTesting, Box_Widgets_Alignment_Test);
FRIEND_TEST(BoxLayoutTesting, Box_Widgets_Alignment_Magrin_Test);
FRIEND_TEST(BoxLayoutTesting, Box_Margins_Test);
FRIEND_TEST(BoxLayoutTesting, Box_Content_Change_Test);
TestBoxLayout(Item *parent, uint32_t x, uint32_t y, uint32_t w, uint32_t h) : BoxLayout(parent, x, y, w, h){};
~TestBoxLayout() = default;
};
| 35.266667 | 114 | 0.775047 | bitigchi |
ff01803da7289057a631b20c6010fef2a9131fac | 6,822 | cpp | C++ | src/unit_tests/test_rexi_pde2x2.cpp | valentinaschueller/sweet | 27e99c7a110c99deeadee70688c186d82b39ac90 | [
"MIT"
] | 6 | 2017-11-20T08:12:46.000Z | 2021-03-11T15:32:36.000Z | src/unit_tests/test_rexi_pde2x2.cpp | valentinaschueller/sweet | 27e99c7a110c99deeadee70688c186d82b39ac90 | [
"MIT"
] | 4 | 2018-02-02T21:46:33.000Z | 2022-01-11T11:10:27.000Z | src/unit_tests/test_rexi_pde2x2.cpp | valentinaschueller/sweet | 27e99c7a110c99deeadee70688c186d82b39ac90 | [
"MIT"
] | 12 | 2016-03-01T18:33:34.000Z | 2022-02-08T22:20:31.000Z | /*
* test_rexi_file.cpp
*
* Created on: 25 Dec 2018
* Author: Martin Schreiber <schreiberx@gmail.com>
*/
#include <iostream>
#include <sweet/SimulationVariables.hpp>
#include <quadmath.h>
#include <rexi/EXPFunctions.hpp>
#include <rexi/REXI.hpp>
#include <rexi/REXICoefficients.hpp>
#define TEST_REXI_PDE_QUADPRECISION 0
#if TEST_REXI_PDE_QUADPRECISION
typedef __float128 T;
#else
typedef double T;
#endif
EXPFunctions<T> rexiFunctions;
std::complex<double> fromTtoComplexDouble(
const std::complex<T> &i_value
)
{
std::complex<double> value;
value.real(i_value.real());
value.imag(i_value.imag());
return value;
}
std::complex<T> fromComplexDoubleToT(
const std::complex<double> &i_value
)
{
std::complex<T> value;
value.real(i_value.real());
value.imag(i_value.imag());
return value;
}
typedef std::complex<T> Tcomplex;
void solveLalpha(
const Tcomplex i_lambda, ///< stiffness
const T i_dt, ///< timestep size
const Tcomplex &i_alpha, ///< REXI shift
const Tcomplex &i_beta, ///< REXI shift
const Tcomplex i_u[2], ///< state variable
Tcomplex o_u[2] ///< output after REXI computation
)
{
Tcomplex i(0, 1);
const Tcomplex alpha = i_alpha/i_dt;
const Tcomplex beta = i_beta/i_dt;
Tcomplex val = Tcomplex(1.0)/(i_lambda*i_lambda - alpha*alpha);
Tcomplex ia = i*i_lambda;
o_u[0] = beta*(val*(alpha*i_u[0] + ia*i_u[1]));
o_u[1] = beta*(val*(-ia*i_u[0] + alpha*i_u[1]));
}
void computeLU(
const Tcomplex &i_lambda,
const Tcomplex i_u[2], ///< state variable
Tcomplex o_LU[2] ///< output after REXI computation
)
{
o_LU[0] = (i_u[1]*i_lambda);
o_LU[1] = (-i_u[0]*i_lambda);
}
void analyticalIntegration(
const Tcomplex &i_lambda, ///< stiffness
T i_dt, ///< timestep size
const Tcomplex i_u[2], ///< state variable
Tcomplex o_u[2] ///< output after REXI computation
)
{
Tcomplex I(0, 1);
Tcomplex tmp[2];
tmp[0] = Tcomplex(0.5)*(-I*i_u[0] + i_u[1]);
tmp[1] = Tcomplex(0.5)*(I*i_u[0] + i_u[1]);
Tcomplex K = i_dt*i_lambda;
tmp[0] = rexiFunctions.eval(K)*tmp[0];
tmp[1] = rexiFunctions.eval(-K)*tmp[1];
o_u[0] = I*tmp[0] - I*tmp[1];
o_u[1] = tmp[0] + tmp[1];
}
void rexiIntegrationBasedOnPDE(
const Tcomplex &i_lambda, ///< stiffness
T i_dt, ///< timestep size
const REXICoefficients<T> &i_rexiCoefficients,
Tcomplex io_u[2] ///< state variable
)
{
Tcomplex o_u[2] = {0.0, 0.0};
for (std::size_t i = 0; i < i_rexiCoefficients.alphas.size(); i++)
{
Tcomplex ru[2];
solveLalpha(
i_lambda, ///< stiffness
i_dt,
i_rexiCoefficients.alphas[i], ///< REXI shift
i_rexiCoefficients.betas[i],
io_u, ///< state variable
ru
);
o_u[0] += ru[0];
o_u[1] += ru[1];
}
o_u[0] += i_rexiCoefficients.gamma * io_u[0];
o_u[1] += i_rexiCoefficients.gamma * io_u[1];
io_u[0] = o_u[0];
io_u[1] = o_u[1];
}
/**
* \return \f$ Re(cos(x) + i*sin(x)) = cos(x) \f$
*/
std::complex<T> approx_returnComplex(
std::vector< std::complex<T> > &alpha,
std::vector< std::complex<T> > &beta_re,
T i_x
)
{
std::complex<T> sum = 0;
std::size_t S = alpha.size();
for (std::size_t n = 0; n < S; n++)
sum += beta_re[n] / (std::complex<T>(0, i_x) - alpha[n]);
return sum;
}
double lmax(
const Tcomplex Uanal[2],
const Tcomplex U[2]
)
{
return std::max(
std::abs( (double)Uanal[0].real() - (double)U[0].real() ),
std::abs( (double)Uanal[1].real() - (double)U[1].real() )
);
}
int main(
int i_argc,
char *const i_argv[]
)
{
SimulationVariables simVars;
if (!simVars.setupFromMainParameters(i_argc, i_argv, nullptr, false))
return -1;
simVars.outputConfig();
if (simVars.rexi.exp_method != "file")
{
if (simVars.rexi.exp_method == "terry")
{
simVars.rexi.p_rexi_files_processed.push_back(EXP_SimulationVariables::REXIFile("phi0", ""));
}
else if (simVars.rexi.exp_method == "ci")
{
std::string function_names[9] =
{
"phi0",
"phi1",
"phi2",
"phi3",
"phi4",
"phi5",
"ups1",
"ups2",
"ups3",
};
for (int i = 0; i < 9; i++)
simVars.rexi.p_rexi_files_processed.push_back(EXP_SimulationVariables::REXIFile(function_names[i], ""));
}
else
{
SWEETError("rexi_method not supported");
}
}
T max_error_threshold = 1e-8;
for (std::size_t i = 0; i < simVars.rexi.p_rexi_files_processed.size(); i++)
{
const std::string &function_name = simVars.rexi.p_rexi_files_processed[i].function_name;
std::cout << "******************************************************" << std::endl;
std::cout << " Function name: " << function_name << std::endl;
std::cout << "******************************************************" << std::endl;
rexiFunctions.setup(function_name);
REXICoefficients<T> rexiCoefficients;
REXI<T>::load(
&simVars.rexi,
function_name,
rexiCoefficients,
simVars.misc.verbosity
);
/*
* Initial conditions: U(0)
*
* Note, that this is a real-valued initial condition
*/
Tcomplex U0[2];
U0[0] = 1.0;
U0[1] = 0.0;
/*
* Current state: U(t)
*/
Tcomplex U[2];
U[0] = U0[0];
U[1] = U0[1];
/*
* Stiffness is specified here
*
* Oscillatory stiffness: imaginary-only
*/
Tcomplex lambda = {0.0, 1.0/M_PI};
/*
* Analytic solution
*/
Tcomplex Uanal[2];
double timestep_size = 0.3;
double simtime = 0;
//cplx evalue = lambda*timestep_size;
//std::cout << "Effective stiffness (lambda*dt): " << fromTtoComplexDouble(evalue) << std::endl;
int tnr_max = 100;
//int tnr_max = (int)(M_PI*2.0/(timestep_size*lambda.imag()));
int tnr = 0;
while (tnr < tnr_max)
{
tnr++;
simtime += timestep_size;
analyticalIntegration(
lambda,
simtime,
U0,
Uanal
);
if (function_name == "phi0")
{
rexiIntegrationBasedOnPDE(
lambda,
timestep_size,
rexiCoefficients,
U
);
}
else
{
/*
* Integrate over entire interval since there's a damping,
* hence a memorization of the current state
*/
U[0] = U0[0];
U[1] = U0[1];
rexiIntegrationBasedOnPDE(
lambda,
simtime,
rexiCoefficients,
U
);
}
U[0].imag(0);
U[1].imag(0);
double error = lmax(Uanal, U);
std::cout << "t = " << (double)simtime;
std::cout << "\tU=(" << fromTtoComplexDouble(U[0]) << ", " << fromTtoComplexDouble(U[1]) << ")";
std::cout << "\tUanal=(" << fromTtoComplexDouble(Uanal[0]) << ", " << fromTtoComplexDouble(Uanal[1]) << ")";
// std::cout << "\tUreallen=(" << (double)lenreal(U[0], U[1]) << ")";
// std::cout << "\tUanalreallen=(" << (double)lenreal(Uanal[0], Uanal[1]) << ")";
std::cout << "\tlmax=" << error << "";
std::cout << std::endl;
#if 1
if (error > max_error_threshold)
SWEETError("Error too high");
#endif
}
}
return 0;
}
| 19.831395 | 111 | 0.602316 | valentinaschueller |
ff062297f7959320468560f260d19a14159c15ca | 793 | cpp | C++ | src/AST/expressions/ternary.cpp | Asixa/Dragonfly | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | [
"Apache-2.0"
] | 2 | 2020-10-23T08:17:47.000Z | 2020-10-25T06:36:58.000Z | src/AST/expressions/ternary.cpp | Asixa/Dragonfly | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | [
"Apache-2.0"
] | null | null | null | src/AST/expressions/ternary.cpp | Asixa/Dragonfly | ef599c8a7f9d756159cd80a61dcc70fd128ef67f | [
"Apache-2.0"
] | null | null | null | #include "AST/expressions/ternary.h"
#include "frontend/debug.h"
#include "AST/program.h"
namespace AST {
void expr::Ternary::ToString() {
*Debugger::out << "[";
a->ToString();
*Debugger::out << "?";
b->ToString();
*Debugger::out << ":";
c->ToString();
*Debugger::out << "]";
}
std::shared_ptr<AST::Type> expr::Ternary::Analysis(std::shared_ptr<DFContext>) { return nullptr; }
std::shared_ptr<expr::Expr> expr::Ternary::Parse() {
const auto a = Binary::Sub7();
if (Lexer::token->type != '?')return a;
Lexer::Next();
const auto b = Binary::Sub7();
Lexer::Match(':');
const auto c = Binary::Sub7();
return std::make_shared<Ternary>(a, b, c);
}
llvm::Value* expr::Ternary::Gen(std::shared_ptr<DFContext> context, bool is_ptr) {
return nullptr;
}
}
| 24.030303 | 102 | 0.620429 | Asixa |
ff0bcb30decfd7c4567b5cc7aa703492752432dc | 2,495 | cpp | C++ | src/Base64.cpp | kgbook/tupu-cpp-sdk | 4b3449ff3914cd05b628e39ded41197e8492c5eb | [
"MIT"
] | 2 | 2016-12-29T01:36:58.000Z | 2018-06-08T16:03:39.000Z | src/Base64.cpp | kgbook/tupu-cpp-sdk | 4b3449ff3914cd05b628e39ded41197e8492c5eb | [
"MIT"
] | null | null | null | src/Base64.cpp | kgbook/tupu-cpp-sdk | 4b3449ff3914cd05b628e39ded41197e8492c5eb | [
"MIT"
] | 4 | 2017-03-21T01:40:06.000Z | 2021-07-07T12:20:20.000Z | /******************************************************************************
* TUPU Recognition API SDK
* Copyright(c)2013-2016, TUPU Technology
* http://www.tuputech.com
*****************************************************************************/
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <limits.h>
// #include <stdexcept>
// #include <cctype>
#include <iostream>
#include <openssl/evp.h>
#include <openssl/bio.h>
#include <openssl/buffer.h>
#include "Base64.hpp"
using namespace std;
string TUPU::base64_encode(const void * input, size_t input_len)
{
BIO *bmem, *b64;
BUF_MEM * bptr = NULL;
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new(BIO_s_mem());
b64 = BIO_push(b64, bmem);
//Ignore newlines - write everything in one line
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
BIO_write(b64, input, input_len);
if (BIO_flush(b64) != 1) {
BIO_free_all(b64);
return "";
}
BIO_get_mem_ptr(b64, &bptr);
char * buffer = (char *)malloc(bptr->length + 1);
memcpy(buffer, bptr->data, bptr->length);
buffer[bptr->length] = 0;
string result(buffer, bptr->length + 1);
free(buffer);
//BIO_set_close(b64, BIO_NOCLOSE);
BIO_free_all(b64);
return result;
}
//Calculates the length of a decoded string
size_t calcDecodeLength(const char* b64input)
{
size_t len = strlen(b64input),
padding = 0;
if (b64input[len-1] == '=' && b64input[len-2] == '=') //last two chars are =
padding = 2;
else if (b64input[len-1] == '=') //last char is =
padding = 1;
return (len*3)/4 - padding;
}
int TUPU::base64_decode(const string & ascdata, void **buf_ptr, size_t *but_len)
{
BIO *bmem, *b64;
size_t input_len = ascdata.size() + 1;
char *input = (char *)malloc(input_len);
memset(input, 0, input_len);
strcpy(input, ascdata.c_str());
int length = calcDecodeLength(input);
unsigned char *buffer = (unsigned char*)malloc(length + 1);
memset(buffer, 0, length + 1);
b64 = BIO_new(BIO_f_base64());
bmem = BIO_new_mem_buf(input, -1);
b64 = BIO_push(b64, bmem);
//Do not use newlines to flush buffer
BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
size_t len = BIO_read(b64, buffer, length);
assert(len == (size_t)length);
//string result((char*)buffer, length);
//free(buffer);
BIO_free_all(b64);
*buf_ptr = buffer;
*but_len = length;
free(input);
return 0;
}
| 24.70297 | 80 | 0.593186 | kgbook |
ff0c608a22e5866bb12a0d90baf14d7eea58689e | 863 | cpp | C++ | src/services.tests/depend.cpp | moducom/services | fc148e5f72c403481951f0063c639b58377187f7 | [
"MIT"
] | null | null | null | src/services.tests/depend.cpp | moducom/services | fc148e5f72c403481951f0063c639b58377187f7 | [
"MIT"
] | null | null | null | src/services.tests/depend.cpp | moducom/services | fc148e5f72c403481951f0063c639b58377187f7 | [
"MIT"
] | null | null | null | #include "catch2/catch.hpp"
#include "services.h"
using namespace moducom::services;
TEST_CASE("dependency")
{
EventGenerator eventGenerator;
entt::registry registry;
agents::EnttHelper enttHelper(registry, registry.create());
agents::Event<Event1> agent1(enttHelper);
agents::Event<Event1> agent2(enttHelper);
SECTION("Depends 1")
{
agents::Depender depender;
depender.add(agent1);
REQUIRE(depender.anyNotRunning());
REQUIRE(!depender.satisfied());
depender.add(agent2);
agent1.construct(eventGenerator);
REQUIRE(depender.anyNotRunning());
REQUIRE(!depender.satisfied());
agent2.construct(eventGenerator);
REQUIRE(!depender.anyNotRunning());
REQUIRE(depender.satisfied());
agent1.destruct();
agent2.destruct();
}
} | 22.128205 | 63 | 0.648899 | moducom |
ff0cbf57a9d6d7c89e59727f4067a0952e7872a2 | 6,594 | cpp | C++ | src/random.cpp | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | src/random.cpp | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | src/random.cpp | gatarelib/qtl2 | 4aba67a3a43ca16888c18f913934098bb28895c0 | [
"RSA-MD"
] | null | null | null | // random number generation (e.g., permutations)
#include "random.h"
#include <vector>
#include <map>
#include <Rcpp.h>
using namespace Rcpp;
using std::vector;
using std::map;
// random integer from {low, low+1, ..., high}
int random_int(const int low, const int high)
{
return (int)R::runif((double)low, double(high+1));
}
// vector of random integers from {low, low+1, ..., high}
// [[Rcpp::export]]
IntegerVector random_int(const int n, const int low, const int high)
{
IntegerVector result(n);
for(int i=0; i<n; i++)
result[i] = random_int(low, high);
return result;
}
// permute a vector of numbers
NumericVector permute_nvector(const NumericVector x)
{
const int n = x.size();
NumericVector result(clone(x));
for(int i=n-1; i>0; i--)
std::swap(result[i], result[random_int(0, i)]);
return result;
}
// permute a vector of integers
IntegerVector permute_ivector(const IntegerVector x)
{
const int n = x.size();
IntegerVector result(clone(x));
for(int i=n-1; i>0; i--)
std::swap(result[i], result[random_int(0, i)]);
return result;
}
// permute a vector of numbers
vector<double> permute_nvector(const vector<double> x)
{
const int n = x.size();
vector<double> result(x);
for(int i=n-1; i>0; i--)
std::swap(result[i], result[random_int(0, i)]);
return result;
}
// permute a vector of numbers
vector<int> permute_ivector(const vector<int> x)
{
const int n = x.size();
vector<int> result(x);
for(int i=n-1; i>0; i--)
std::swap(result[i], result[random_int(0, i)]);
return result;
}
// permute a vector of numbers in place
void permute_nvector_inplace(NumericVector x)
{
const int n = x.size();
for(int i=n-1; i>0; i--)
std::swap(x[i], x[random_int(0, i)]);
}
// permute a vector of integers in place
void permute_ivector_inplace(IntegerVector x)
{
const int n = x.size();
for(int i=n-1; i>0; i--)
std::swap(x[i], x[random_int(0, i)]);
}
// permute a vector of numbers in place
void permute_nvector_inplace(vector<double> x)
{
const int n = x.size();
for(int i=n-1; i>0; i--)
std::swap(x[i], x[random_int(0, i)]);
}
// permute a vector of integers in place
void permute_ivector_inplace(vector<int> x)
{
const int n = x.size();
for(int i=n-1; i>0; i--)
std::swap(x[i], x[random_int(0, i)]);
}
// get permutation of {0..(n-1)}
// [[Rcpp::export]]
IntegerVector get_permutation(const int n)
{
IntegerVector result(n);
for(int i=0; i<n; i++) result[i] = i;
permute_ivector_inplace(result);
return result;
}
// get a set of permutations of a vector, as columns of a matrix
// [[Rcpp::export]]
NumericMatrix permute_nvector(const int n_perm, const NumericVector x)
{
const int length = x.size();
NumericMatrix result(length,n_perm);
for(int i=0; i<n_perm; i++) {
NumericVector permx = permute_nvector(x);
std::copy(permx.begin(), permx.end(), result.begin()+i*length);
}
return result;
}
// get a set of permutations of a vector, as columns of a matrix
// [[Rcpp::export]]
IntegerMatrix permute_ivector(const int n_perm, const IntegerVector x)
{
const int length = x.size();
IntegerMatrix result(length,n_perm);
for(int i=0; i<n_perm; i++) {
IntegerVector permx = permute_ivector(x);
std::copy(permx.begin(), permx.end(), result.begin()+i*length);
}
return result;
}
// permute x within strata
// strata is integer vector {0, 1, 2, ..., n_strata-1}
// n_strata is the number of strata; if == -1, it is calculated
// [[Rcpp::export]]
NumericMatrix permute_nvector_stratified(const int n_perm, const NumericVector& x,
const IntegerVector& strata, int n_strata = -1)
{
const int n = x.size();
NumericMatrix result(n,n_perm);
if(strata.size() != n)
throw std::length_error("length(x) != length(strata)");
if(n_strata < 0) // find maximum strata
n_strata = max(strata) + 1;
// map of indices for the strata
map<int, vector<int> > strata_index;
for(int i=0; i<n; ++i) {
if(strata[i] >= n_strata || strata[i] < 0)
throw std::domain_error("strata should be in [0, n_strata)");
strata_index[strata[i]].push_back(i);
}
for(int perm=0; perm<n_perm; ++perm) {
// for each stratum:
for(int stratum=0; stratum < n_strata; ++stratum) {
// permute indices
vector<int> index_permuted = permute_ivector(strata_index[stratum]);
int n = strata_index[stratum].size();
for(int i=0; i<n; ++i)
result(strata_index[stratum][i],perm) = x[index_permuted[i]];
}
}
return result;
}
// permute x within strata
// strata is integer vector {0, 1, 2, ..., n_strata-1}
// n_strata is the number of strata; if == -1, it is calculated
// [[Rcpp::export]]
IntegerMatrix permute_ivector_stratified(const int n_perm, const IntegerVector& x,
const IntegerVector& strata, int n_strata = -1)
{
const int n = x.size();
IntegerMatrix result(n,n_perm);
if(strata.size() != n)
throw std::length_error("length(x) != length(strata)");
if(n_strata < 0) // find maximum strata
n_strata = max(strata) + 1;
// map of indices for the strata
map<int, vector<int> > strata_index;
for(int i=0; i<n; ++i) {
if(strata[i] >= n_strata || strata[i] < 0)
throw std::domain_error("strata should be in [0, n_strata)");
strata_index[strata[i]].push_back(i);
}
for(int perm=0; perm<n_perm; ++perm) {
// for each stratum:
for(int stratum=0; stratum < n_strata; ++stratum) {
// permute indices
vector<int> index_permuted = permute_ivector(strata_index[stratum]);
int n = strata_index[stratum].size();
for(int i=0; i<n; ++i)
result(strata_index[stratum][i],perm) = x[index_permuted[i]];
}
}
return result;
}
// sample random integer from 0, 1, 2, ..., n-1 with probability p[0], p[1], ...
int random_int(NumericVector probs)
{
int n=probs.size();
int result;
double u = R::runif(0.0, 1.0);
for(result=0; result < n; result++) {
if(u <= probs[result]) return result;
u -= probs[result];
}
return NA_INTEGER;
}
// sample random integer from 0, 1, 2, ..., n-1 with equal probabilities
int random_int(int n)
{
return (int)(unif_rand()*n);
}
| 24.977273 | 88 | 0.605247 | gatarelib |
ff0d262b9c112571acbfdb3b78ae896c50a79944 | 20,538 | cpp | C++ | src/core/unittest/UnitTestPolyElements.cpp | AnthonyTudorov/PALISADE-SizeOf-Fork | 05e9903da0971933adb1ba0b9c98398c9722a45c | [
"BSD-2-Clause"
] | 1 | 2021-09-02T07:20:28.000Z | 2021-09-02T07:20:28.000Z | src/core/unittest/UnitTestPolyElements.cpp | uishi/Modified_PALISADEv1.9.2 | d8bf4739144e53340481721b1df83dfff2f65cd8 | [
"BSD-2-Clause"
] | null | null | null | src/core/unittest/UnitTestPolyElements.cpp | uishi/Modified_PALISADEv1.9.2 | d8bf4739144e53340481721b1df83dfff2f65cd8 | [
"BSD-2-Clause"
] | 3 | 2021-09-02T07:21:06.000Z | 2022-01-19T15:24:20.000Z | /*
* @file
* @author TPOC: contact@palisade-crypto.org
*
* @copyright Copyright (c) 2019, New Jersey Institute of Technology (NJIT)
* 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.
* 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.
*
*/
/*
This code tests the transform feature of the PALISADE lattice encryption library.
*/
#include "include/gtest/gtest.h"
#include <iostream>
#include <vector>
#include "math/backend.h"
#include "lattice/backend.h"
#include "utils/inttypes.h"
#include "math/distrgen.h"
#include "utils/parmfactory.h"
#include "lattice/elemparamfactory.h"
using namespace std;
using namespace lbcrypto;
/*-TESTING METHODS OF LATTICE ELEMENTS ----------------*/
// these tests only work on Poly, and have not been ported to DCRT
// NOTE tests that only work on Poly because DCRT versions have not been
// coded are here
// When they are completed and run for both types, they move to
// UnitTestCommonElements.cpp
template<typename Element>
void rounding_ops(const string& msg) {
DEBUG_FLAG(false);
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
usint m = 8;
typename VecType::Integer q("73");
typename VecType::Integer primitiveRootOfUnity("22");
typename VecType::Integer p("8");
shared_ptr<ParmType> ilparams( new ParmType(m, q, primitiveRootOfUnity) );
//temporary larger modulus that is used for polynomial multiplication before rounding
typename VecType::Integer q2("16417");
typename VecType::Integer primitiveRootOfUnity2("13161");
shared_ptr<ParmType> ilparams2( new ParmType(m, q2, primitiveRootOfUnity2) );
Element ilvector2n1(ilparams,COEFFICIENT);
ilvector2n1 = { "31","21","15","34"};
DEBUGEXP(ilvector2n1);
//test for bug where length was 0
EXPECT_EQ(ilvector2n1.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
Element ilvector2n2(ilparams,COEFFICIENT);
ilvector2n2 = { "21","11","35","32" };
DEBUGEXP(ilvector2n2);
DEBUG("unit test for MultiplyAndRound");
Element roundingCorrect1(ilparams, COEFFICIENT);
roundingCorrect1 = { "3","2","2","4" };
DEBUGEXP(ilvector2n1);
Element rounding1 = ilvector2n1.MultiplyAndRound(p, q);
EXPECT_EQ(roundingCorrect1, rounding1)
<< msg << " Failure: Rounding p*polynomial/q";
DEBUG("unit test for MultiplyAndRound after a polynomial");
DEBUG("multiplication using the larger modulus");
Element roundingCorrect2(ilparams2, COEFFICIENT);
roundingCorrect2 = { "16316","16320","60","286" };
ilvector2n1.SwitchModulus(q2, primitiveRootOfUnity2);
ilvector2n2.SwitchModulus(q2, primitiveRootOfUnity2);
DEBUGEXP(ilvector2n1);
DEBUGEXP(ilvector2n2);
ilvector2n1.SwitchFormat();
ilvector2n2.SwitchFormat();
DEBUGEXP(ilvector2n1);
DEBUGEXP(ilvector2n2);
Element rounding2 = ilvector2n1 * ilvector2n2;
DEBUGEXP(rounding2);
rounding2.SwitchFormat();
DEBUGEXP(rounding2);
rounding2 = rounding2.MultiplyAndRound(p, q);
DEBUGEXP(rounding2);
EXPECT_EQ(roundingCorrect2, rounding2)
<< msg << " Failure: Rounding p*polynomial1*polynomial2/q";
DEBUG("makes sure the result is correct after");
DEBUG("going back to the original modulus");
rounding2.SwitchModulus(q, primitiveRootOfUnity);
DEBUGEXP(rounding2);
Element roundingCorrect3(ilparams, COEFFICIENT);
roundingCorrect3 = { "45","49","60","67" };
EXPECT_EQ(roundingCorrect3, rounding2)
<< msg << " Failure p*polynomial1*polynomial2/q (mod q)";
}
// instantiate various test for rounding_ops()
TEST(UTPoly, rounding_ops) {
RUN_ALL_POLYS(rounding_ops, "Poly rounding_ops");
}
// FIXME DCRTPoly needs an assignment op/ctor
TEST(UTDCRTPoly, rounding_ops) {
//std::cerr<<"*** skipping DCRT rounding_ops till MultiplyAndRound is coded"<<std::endl;
//RUN_BIG_DCRTPOLYS(rounding_ops, "DCRT rounding_ops");
}
//template for set_get_values()
template<typename Element>
void set_get_values(const string& msg) {
DEBUG_FLAG(false);
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
{ //test SetValues()
Element ilvector2n(ilparams);
VecType bbv(m/2, primeModulus);
bbv = { "3","0","0","0"};
ilvector2n.SetValues(bbv, Format::COEFFICIENT);
DEBUGEXP(ilvector2n);
//test for bug where length was 0
EXPECT_EQ(ilvector2n.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
Element ilvector2n2(ilparams);
VecType bbv2(m/2, primeModulus);
bbv2={"3","3","3","3"};
ilvector2n2.SetValues(bbv2, Format::COEFFICIENT);
// test SetValues()
EXPECT_NE(ilvector2n, ilvector2n2) << msg << " Failure: SetValues NE";
bbv2=bbv;
ilvector2n2.SetValues(bbv2, Format::COEFFICIENT);
EXPECT_EQ(ilvector2n, ilvector2n2) << msg << " Failure: SetValues EQ";
}
{//test GetValue() and at()
Element ilvector2n(ilparams);
ilvector2n = {"1", "2", "0", "1"};
Element bbv(ilparams);
bbv = {"1", "2", "0", "1"};
DEBUGEXP(ilvector2n);
DEBUGEXP(bbv);
EXPECT_EQ(bbv.GetValues(), ilvector2n.GetValues())
<<msg<< "Failure: GetValues()";
usint index = 3;
bbv[index] = 11;
for (usint i = 0; i < m/2; ++i) {
if (i ==index) {
EXPECT_NE(bbv.at(i),
ilvector2n.at(i))
<<msg<< " Failure: lhs[] at("<<i<< ")";
}else{
EXPECT_EQ(bbv.at(i),
ilvector2n.at(i))
<<msg<< " Failure: lhs[] at("<<i<< ")";
}
}
}
}
// instantiate various test for set_get_values()
TEST(UTPoly, set_get_values) {
RUN_ALL_POLYS(set_get_values, "Poly set_get_values");
}
// FIXME DCRTPoly needs a set_get_values()
TEST(UTDCRTPoly, set_get_values) {
//std::cerr<<"*** skipping DCRT set_get_values till coded"<<std::endl;
//RUN_BIG_DCRTPOLYS(set_get_values, "DCRT set_values");
}
//template for at()
template<typename Element>
void at(const string& msg) {
DEBUG_FLAG(false);
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
{//test and at() and []
Element ilvector2n(ilparams);
ilvector2n = {"1", "2", "0", "1"};
Element bbv(ilparams);
bbv = {"1", "2", "0", "1"};
DEBUGEXP(ilvector2n);
DEBUGEXP(bbv);
//test for bug where length was 0
EXPECT_EQ(ilvector2n.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
usint index = 3;
bbv[index] = 11;
for (usint i = 0; i < m/2; ++i) {
if (i ==index) {
EXPECT_NE(bbv.at(i),
ilvector2n.at(i))
<<msg<< " Failure: lhs[] at("<<i<< ")";
}else{
EXPECT_EQ(bbv.at(i),
ilvector2n.at(i))
<<msg<< " Failure: lhs[] at("<<i<< ")";
}
}
bbv.at(index) = 1;
for (usint i = 0; i < m/2; ++i) {
EXPECT_EQ(bbv.at(i),
ilvector2n.at(i))
<<msg<< " Failure: lhs[] at("<<i<< ")";
}
}
}
// instantiate various test for at()
TEST(UTPoly, at) {
RUN_ALL_POLYS(at, "Poly at");
}
// FIXME DCRTPoly needs a at() and []
TEST(UTDCRTPoly, at) {
//std::cerr<<"*** skipping DCRT at till coded"<<std::endl;
//RUN_BIG_DCRTPOLYS(at, "DCRT at");
}
//template for switch_modulus
template<typename Element>
void switch_modulus(const string& msg) {
DEBUG_FLAG(false);
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
//using IntType = typename Element::Vector::Integer;
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
DEBUG("SwitchModulus");
{
Element ilv(ilparams, COEFFICIENT);
ilv ={"56","1","37","2"};
//test for bug where length was 0
EXPECT_EQ(ilv.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
typename VecType::Integer modulus("17");
typename VecType::Integer rootOfUnity("15");
ilv.SwitchModulus(modulus, rootOfUnity);
shared_ptr<ParmType> ilparams2( new ParmType(m,
modulus,
rootOfUnity) );
Element expected(ilparams2,COEFFICIENT);
expected = {"0","1","15","2"};
EXPECT_EQ(expected, ilv)
<< msg << " Failure: SwitchModulus()";
Element ilv1(ilparams, COEFFICIENT);
ilv1 ={"56","43","35","28"};
typename VecType::Integer modulus1("193");
typename VecType::Integer rootOfUnity1("150");
ilv1.SwitchModulus(modulus1, rootOfUnity1);
shared_ptr<ParmType> ilparams3( new ParmType(m,
modulus1,
rootOfUnity1) );
Element expected2(ilparams3,COEFFICIENT);
expected2 = {"176","163","35","28"};
EXPECT_EQ(expected2, ilv1)
<< msg << " Failure: SwitchModulus()";
}
}
//instantiations for switch_modulus()
TEST(UTPoly, switch_modulus) {
RUN_ALL_POLYS(switch_modulus, "Poly switch_modulus");
}
TEST(UTDCRTPoly, switch_modulus) {
//std::cerr<<"*** skipping DCRT switch_modulus till coded"<<std::endl; //RUN_BIG_DCRTPOLYS(switch_modulus, "Poly switch_modulus");
}
//template fore rn_generators()
template<typename Element>
void rn_generators(const string& msg) {
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
DEBUG_FLAG(false);
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
float stdDev = 4.0;
typename Element::DggType dgg(stdDev);
typename Element::BugType bug;
typename Element::DugType dug;
dug.SetModulus(primeModulus);
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
DEBUG("DestroyPreComputedSamples");
{
Element ilv(ilparams, COEFFICIENT);
ilv = {"2","1","3","2"};
//test for bug where length was 0
EXPECT_EQ(ilv.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
Element ilvector2n1(ilparams);
Element ilvector2n2(ilparams);
Element ilvector2n3(ilv);
Element ilvector2n4(dgg, ilparams);
Element ilvector2n5(bug, ilparams);
Element ilvector2n6(dug, ilparams);
EXPECT_EQ(true, ilvector2n1.IsEmpty())
<< msg << " Failure: DestroyPreComputedSamples() 2n1";
EXPECT_EQ(true, ilvector2n2.IsEmpty())
<< msg << " Failure: DestroyPreComputedSamples() 2n2";
EXPECT_EQ(false, ilvector2n3.IsEmpty())
<< msg << " Failure: DestroyPreComputedSamples() 2n3";
EXPECT_EQ(false, ilvector2n4.IsEmpty())
<< msg << " Failure: DestroyPreComputedSamples() 2n4";
EXPECT_EQ(false, ilvector2n5.IsEmpty())
<< msg << " Failure: DestroyPreComputedSamples() 2n5";
EXPECT_EQ(false, ilvector2n6.IsEmpty())
<< msg << " Failure: DestroyPreComputedSamples() 2n6";
}
}
//Instantiations of rn_generators()
TEST(UTPoly, rn_generators) {
RUN_ALL_POLYS(rn_generators, "Poly rn_generators");
}
TEST(UTDCRTPoly, rn_generators) {
//std::cerr<<"*** skipping DCRT rn_generators till coded"<<std::endl;
//RUN_BIG_DCRTPOLYS(rn_generators, "DCRT rn_generators");
}
//template fore poly_other_methods()
template<typename Element>
void poly_other_methods(const string& msg) {
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
DEBUG_FLAG(false);
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
Element ilvector2n(ilparams);
ilvector2n = {"2","1","3","2"};
//test for bug where length was 0
EXPECT_EQ(ilvector2n.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
DEBUG("SwitchFormat");
{
Element ilv(ilparams,COEFFICIENT);
ilv = {"2","1","3","2"};
ilv.SwitchFormat();
EXPECT_EQ(primeModulus, ilv.GetModulus())
<< msg << " Failure: SwitchFormat() ilv modulus";
EXPECT_EQ(primitiveRootOfUnity, ilv.GetRootOfUnity())
<< msg << " Failure: SwitchFormat() ilv rootOfUnity";
EXPECT_EQ(Format::EVALUATION, ilv.GetFormat())
<< msg << " Failure: SwitchFormat() ilv format";
Element expected(ilparams);
expected = {"69","65","44","49"};
EXPECT_EQ(expected, ilv)
<< msg << " Failure: ivl.SwitchFormat() values";
Element ilv1(ilparams, EVALUATION);
ilv1 = {"2","3","1","2"};
ilv1.SwitchFormat();
EXPECT_EQ(primeModulus, ilv1.GetModulus())
<< msg << " Failure: SwitchFormat() ilv1 modulus";
EXPECT_EQ(primitiveRootOfUnity, ilv1.GetRootOfUnity())
<< msg << " Failure: SwitchFormat() ilv1 rootOfUnity";
EXPECT_EQ(Format::COEFFICIENT, ilv1.GetFormat())
<< msg << " Failure: SwitchFormat() ilv1 format";
Element expected2(ilparams,COEFFICIENT);
expected2 = {"2","3","50","3"};
EXPECT_EQ(expected2, ilv1)
<< msg << " Failure: ivl1.SwitchFormat() values";
}
DEBUG("MultiplicativeInverse");
{
Element ilv1(ilparams, EVALUATION);
ilv1 = {"2","4","3","2"};
Element ilvInverse1 = ilv1.MultiplicativeInverse();
Element ilvProduct1 = ilv1 * ilvInverse1;
for (usint i = 0; i < m/2; ++i)
{
EXPECT_EQ(ilvProduct1.at(i), typename Element::Integer(1))
<< msg << " Failure: ilvProduct1.MultiplicativeInverse() @ index "<<i;
}
}
DEBUG("Norm");
{
Element ilv(ilparams, COEFFICIENT);
ilv = {"56","1","37","1"};
EXPECT_EQ(36, ilv.Norm()) << msg << " Failure: Norm()";
}
}
//Instantiations of poly_other_methods()
TEST(UTPoly, poly_other_methods) {
RUN_ALL_POLYS(poly_other_methods, "poly_other_methods");
}
//FIXME
TEST(UTDCRTPoly, poly_other_methods) {
//std::cerr<<"*** skipping DCRT poly_other_methods till these functions are coded"<<std::endl;
// RUN_BIG_DCRTPOLYS(poly_other_methods, "DCRT poly_other_methods");
}
// Signed mod must handle the modulo operation for both positive and negative numbers
// It is used in decoding/decryption of homomorphic encryption schemes
template<typename Element>
void signed_mod(const string& msg) {
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
Element ilvector2n1(ilparams,COEFFICIENT);
ilvector2n1 = {"62","7","65","8"};
//test for bug where length was 0
EXPECT_EQ(ilvector2n1.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
{
Element ilv1(ilparams, COEFFICIENT);
ilv1 = ilvector2n1.Mod(2);
Element expected(ilparams, COEFFICIENT);
expected = {"1","1","0","0"};
EXPECT_EQ(expected, ilv1)
<< msg << " Failure: ilv1.Mod(TWO)";
}
{
Element ilv1(ilparams, COEFFICIENT);
ilv1 = ilvector2n1.Mod(5);
Element expected(ilparams, COEFFICIENT);
expected = {"4","2","2","3"};
EXPECT_EQ(expected, ilv1)
<< msg << " Failure: ilv1.Mod(FIVE)";
}
}
//Instantiations of signed_mod()
TEST(UTPoly, signed_mod) {
RUN_ALL_POLYS(signed_mod, "signed_mod");
}
// FIXME
TEST(UTDCRTPoly, signed_mod) {
//std::cerr<<"*** skipping DCRT signed_mod till coded"<<std::endl;
// RUN_BIG_DCRTPOLYS(signed_mod, "signed_mod");
}
//template fore automorphismTransform()
template<typename Element>
void automorphismTransform(const string& msg) {
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
DEBUG_FLAG(false);
usint m = 8;
typename VecType::Integer primeModulus("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams( new ParmType(m, primeModulus, primitiveRootOfUnity) );
Element ilvector2n(ilparams);
ilvector2n = {"2","1","3","2"};
//test for bug where length was 0
EXPECT_EQ(ilvector2n.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
DEBUG("AutomorphismTransform");
{
Element ilv(ilparams, COEFFICIENT);
ilv = {"56","1","37","2"};
usint index = 3;
Element ilvAuto(ilv.AutomorphismTransform(index));
Element expected(ilparams,COEFFICIENT);
expected = {"56","2","36","1"};
EXPECT_EQ(expected, ilvAuto)
<< msg << " Failure: AutomorphismTransform()";
}
}
//Instantiations of automorphismTransform()
TEST(UTPoly, automorphismTransform) {
RUN_ALL_POLYS(automorphismTransform, "Poly automorphismTransform");
}
// FIXME
TEST(UTDCRTPoly, automorphismTransform) {
//std::cerr<<"*** skipping DCRT automorphismTransform till coded"<<std::endl;
// RUN_BIG_DCRTPOLYS(automorphismTransform, "DCRT automorphismTransform");
}
template<typename Element>
void transposition(const string& msg) {
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
DEBUG_FLAG(false);
usint m = 8;
typename VecType::Integer q("73");
typename VecType::Integer primitiveRootOfUnity("22");
shared_ptr<ParmType> ilparams(new ParmType(m, q, primitiveRootOfUnity));
Element ilvector2n1(ilparams, COEFFICIENT);
ilvector2n1 = {"31","21","15","34"};
//test for bug where length was 0
EXPECT_EQ(ilvector2n1.GetLength(), m/2)
<< msg << " Failure: ={init list string}";
// converts to evaluation representation
ilvector2n1.SwitchFormat();
DEBUG("ilvector2n1 a "<<ilvector2n1);
ilvector2n1 = ilvector2n1.Transpose();
DEBUG("ilvector2n1 b "<<ilvector2n1);
// converts back to coefficient representation
ilvector2n1.SwitchFormat();
DEBUG("ilvector2n1 c "<<ilvector2n1);
Element ilvector2n2(ilparams,COEFFICIENT);
ilvector2n2 = {"31","39","58","52"};
DEBUG("ilvector2n2 a "<<ilvector2n2);
EXPECT_EQ(ilvector2n2, ilvector2n1)
<< msg << " Failure: transposition test";
}
//Instantiations of transposition()
TEST(UTPoly, transposition) {
RUN_ALL_POLYS(transposition, "transposition");
}
// FIXME
TEST(UTDCRTPoly, transposition) {
//std::cerr<<"*** skipping DCRT transposition till coded"<<std::endl;
// RUN_BIG_DCRTPOLYS(transposition, "transposition");
}
template<typename Element>
void Poly_mod_ops_on_two_elements(const string& msg) {
using VecType = typename Element::Vector;
using ParmType = typename Element::Params;
usint order = 8;
usint nBits = 7;
typename VecType::Integer primeModulus = lbcrypto::FirstPrime<typename VecType::Integer>(nBits, order);
typename VecType::Integer primitiveRootOfUnity = lbcrypto::RootOfUnity<typename VecType::Integer>(order, primeModulus);
shared_ptr<ParmType> ilparams( new ParmType(order, primeModulus, primitiveRootOfUnity) );
typename Element::DugType distrUniGen = typename Element::DugType();
distrUniGen.SetModulus(primeModulus);
Element ilv1(distrUniGen, ilparams);
VecType bbv1 (ilv1.GetValues());
Element ilv2(distrUniGen, ilparams);
VecType bbv2(ilv2.GetValues());
{
Element ilvResult = ilv1 + ilv2;
VecType bbvResult(ilvResult.GetValues());
for (usint i=0; i<order/2; i++) {
EXPECT_EQ(bbvResult.at(i), (bbv1.at(i) + bbv2.at(i)).Mod(primeModulus)) << msg << " Poly + operation returns incorrect results.";
}
}
{
Element ilvResult = ilv1 * ilv2;
VecType bbvResult(ilvResult.GetValues());
for (usint i=0; i<order/2; i++) {
EXPECT_EQ(bbvResult.at(i), (bbv1.at(i) * bbv2.at(i)).Mod(primeModulus)) << msg << " Poly * operation returns incorrect results.";
}
}
}
TEST(UTPoly, Poly_mod_ops_on_two_elements) {
RUN_ALL_POLYS(Poly_mod_ops_on_two_elements, "Poly Poly_mod_ops_on_two_elements");
}
| 29.895197 | 132 | 0.700701 | AnthonyTudorov |
ff0e6153bb3af28368018877109b0fabb4689a74 | 820 | cpp | C++ | cpp/leetcode/ValidWordSub.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/ValidWordSub.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | cpp/leetcode/ValidWordSub.cpp | danyfang/SourceCode | 8168f6058648f2a330a7354daf3a73a4d8a4e730 | [
"MIT"
] | null | null | null | //Leetcode Problem No 1003. Check If Word Is Valid After Substitutions
//Solution written by Xuqiang Fang on 12 March, 2019
/*
A classic problem with classic stack solution!!!
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <unordered_map>
#include <unordered_set>
#include <stack>
#include <queue>
using namespace std;
class Solution{
public:
bool isValid(string S){
vector<int> s;
for(auto& c : S){
if(c == 'c'){
const int n = s.size();
if(n < 2 || s[n-1] != 'b' || s[n-2] != 'a')
return false;
s.pop_back();
s.pop_back();
}
else{
s.push_back(c);
}
}
return s.empty();
}
};
int main(){
Solution s;
string S = "aabbcc";
cout << s.isValid(S) << endl;
S = "abcabcababcc";
cout << s.isValid(S) << endl;
return 0;
}
| 18.636364 | 70 | 0.609756 | danyfang |
ff1232199e2ebcd560e0dbee9edb4292728dc1e6 | 1,142 | cpp | C++ | src/utils/RandomUtils.cpp | lidaobing/nacos-sdk-cpp | 9b54f96d50ae79efc5884617eb9877320eed7352 | [
"Apache-2.0"
] | 1 | 2021-10-17T09:43:08.000Z | 2021-10-17T09:43:08.000Z | src/utils/RandomUtils.cpp | fawdlstty/nacos-sdk-cpp | a52c776c780a9c92b1f2d3706b39fe294670cc92 | [
"Apache-2.0"
] | 1 | 2020-10-10T09:25:02.000Z | 2020-10-10T09:25:02.000Z | src/utils/RandomUtils.cpp | yzz-ihep/nacos-sdk-cpp | de082c76262bb0a7e904b71c43c952b585eb6035 | [
"Apache-2.0"
] | null | null | null | #include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include "utils/RandomUtils.h"
namespace nacos{
int RandomUtils::fd;
ThreadLocal<bool> RandomUtils::initedForThisThread(false);
void RandomUtils::Init() {
fd = open("/dev/urandom", O_RDONLY);
}
void RandomUtils::DeInit() {
if (fd != 0) {
close(fd);
fd = 0;
}
}
size_t RandomUtils::getRandomBuffer(void *dest, size_t size) {
size_t bytes_read = 0;
while (bytes_read < size)
{
bytes_read += read(fd, (char*)dest + bytes_read, size - bytes_read);
}
return bytes_read;
}
int RandomUtils::random_inner(){
if (!initedForThisThread.get()){
srand(time(NULL));
initedForThisThread.set(true);
}
return rand();
}
int RandomUtils::random(int begin, int end) throw (NacosException) {
//sanity check
if (begin == end || begin > end) {
throw NacosException(NacosException::INVALID_PARAM, "end must be greater than begin");
}
long offset = random_inner() % (end - begin + 1);
return begin + offset;
}
}//namespace nacos | 21.961538 | 94 | 0.637478 | lidaobing |
ff13fc3a814bedf56af5a149937e1d1d912ed8cb | 439 | cpp | C++ | InputOutputTemplate/WhyWhileCinWorks.cpp | zyzkevin/C-Programming-and-Algorithms | be9642b62a3285341990c25bdc3c124c4dd8c38b | [
"MIT"
] | null | null | null | InputOutputTemplate/WhyWhileCinWorks.cpp | zyzkevin/C-Programming-and-Algorithms | be9642b62a3285341990c25bdc3c124c4dd8c38b | [
"MIT"
] | null | null | null | InputOutputTemplate/WhyWhileCinWorks.cpp | zyzkevin/C-Programming-and-Algorithms | be9642b62a3285341990c25bdc3c124c4dd8c38b | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
class MyCin
{
// 在此处补充你的代码
bool input = true;
public:
MyCin & operator >> ( int & n)
{
cin >> n;
if (n == -1) input = false;
return *this;
}
operator bool()
{
return input;
}
};
int main()
{
MyCin m;
int n1,n2;
while( m >> n1 >> n2)
cout << n1 << " " << n2 << endl;
system("pause");
return 0;
} | 15.137931 | 41 | 0.451025 | zyzkevin |
d4309ffadb86d7db607904b60d597a2bf09a4262 | 2,256 | cxx | C++ | test/core/util/SynchronizedQueueTest.cxx | dlopes7/openkit-native | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | [
"Apache-2.0"
] | null | null | null | test/core/util/SynchronizedQueueTest.cxx | dlopes7/openkit-native | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | [
"Apache-2.0"
] | null | null | null | test/core/util/SynchronizedQueueTest.cxx | dlopes7/openkit-native | 669871b0f48d85534c3ecfdfca2c9fb6de5811f9 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2018-2019 Dynatrace LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "core/util/SynchronizedQueue.h"
#include "gtest/gtest.h"
#include <memory>
template <typename T>
using SynchronizedQueue_t = core::util::SynchronizedQueue<T>;
class SynchronizedQueueTest : public testing::Test
{
protected:
std::shared_ptr<int32_t> elementOne = std::make_shared<int32_t>(1);
std::shared_ptr<int32_t> elementTwo = std::make_shared<int32_t>(1);
SynchronizedQueue_t<std::shared_ptr<int32_t>> synchronizedQueue;
};
TEST_F(SynchronizedQueueTest, elementCanBeAdded)
{
//when
synchronizedQueue.put(elementOne);
//then
ASSERT_FALSE(synchronizedQueue.isEmpty());
}
TEST_F(SynchronizedQueueTest, elementCanBeAddedAndRemoved)
{
//when
synchronizedQueue.put(elementOne);
//then
ASSERT_FALSE(synchronizedQueue.isEmpty());
//when
synchronizedQueue.remove(elementOne);
//then
ASSERT_TRUE(synchronizedQueue.isEmpty());
}
TEST_F(SynchronizedQueueTest, onlyFirstOccurenceOfAnElementValueIsDeleted)
{
//when
synchronizedQueue.put(elementOne);
synchronizedQueue.put(elementTwo);
//then
ASSERT_FALSE(synchronizedQueue.isEmpty());
//when
synchronizedQueue.remove(elementOne);
//then
ASSERT_FALSE(synchronizedQueue.isEmpty());
//when
auto list = synchronizedQueue.toStdVector();
//then
ASSERT_GT(list.size(),0u);
ASSERT_EQ(list[0], elementTwo);
}
TEST_F(SynchronizedQueueTest, getCalledOnEmptyList)
{
auto element = synchronizedQueue.get();
ASSERT_EQ(element, nullptr);
}
TEST_F(SynchronizedQueueTest, removeCalledOnEmptyList)
{
//when
synchronizedQueue.remove(elementTwo);
ASSERT_TRUE(synchronizedQueue.isEmpty());
}
TEST_F(SynchronizedQueueTest, checkEmptyList)
{
ASSERT_TRUE(synchronizedQueue.isEmpty());
} | 23.020408 | 74 | 0.774379 | dlopes7 |
d430fceec13566adbac1a751a496768c07ef1f91 | 597 | hpp | C++ | src/ecs/components/BlockedComponent.hpp | Gegel85/IndieStudio | 63e58c61416b3c16885d35d75d126e3db5ed3cc8 | [
"MIT"
] | null | null | null | src/ecs/components/BlockedComponent.hpp | Gegel85/IndieStudio | 63e58c61416b3c16885d35d75d126e3db5ed3cc8 | [
"MIT"
] | 12 | 2019-05-22T12:22:44.000Z | 2019-06-15T17:31:04.000Z | src/ecs/components/BlockedComponent.hpp | Gegel85/IndieStudio | 63e58c61416b3c16885d35d75d126e3db5ed3cc8 | [
"MIT"
] | 1 | 2019-06-18T15:53:48.000Z | 2019-06-18T15:53:48.000Z | /*
** EPITECH PROJECT, 2019
** bomberman
** File description:
** BlockedComponent.hpp
*/
#ifndef BOMBERMAN_BLOCKCOMPONENT_HPP
#define BOMBERMAN_BLOCKCOMPONENT_HPP
#include "../Component.hpp"
#include "../Ressources.hpp"
#include "../Entity.hpp"
namespace ECS {
class BlockedComponent : public Component {
public:
std::vector<Entity*> whitelistId;
BlockedComponent();
BlockedComponent(unsigned id, Ressources &ressources, std::istream &stream);
std::ostream &serialize(std::ostream &stream) const override;
};
}
#endif //BOMBERMAN_BLOCKCOMPONENT_HPP
| 22.961538 | 84 | 0.708543 | Gegel85 |
d435824eeaea38ef1b52d7cf0bc29a111b811a6e | 2,212 | cpp | C++ | main.cpp | soda92/basic-ffmpeg | dd2473217f05c66be6e7059df5945bbcf75384eb | [
"Apache-2.0"
] | null | null | null | main.cpp | soda92/basic-ffmpeg | dd2473217f05c66be6e7059df5945bbcf75384eb | [
"Apache-2.0"
] | null | null | null | main.cpp | soda92/basic-ffmpeg | dd2473217f05c66be6e7059df5945bbcf75384eb | [
"Apache-2.0"
] | null | null | null | #include "ctfolder.hpp"
#include "ctffmpeg.hpp"
CtFfmpeg *ff;
#include <fmt/core.h>
int main(int argc, char **argv)
{
ff = new CtFfmpeg();
ff->in_filename = "rtsp://admin:hk123456@192.168.104.72:554/Streaming/Channels/101";
ff->init();
ff->getInput();
string filename;
videoRecorder obj;
int start, now;
start = obj.get_current_min();
if (obj.create_folder(0755))
cout << "Cannot create folder, maybe it already exists" << endl;
else
cout << "Create folder succesfully" << endl;
int skip = 0;
while (1)
{
filename = obj.update_filename();
ff->getOutputName(filename.c_str());
int64_t pts_offset = AV_NOPTS_VALUE;
while ((now = obj.get_current_min()) == start)
{
ff->ret = av_read_frame(ff->ifmt_ctx, &(ff->pkt));
skip++;
if (skip == 1)
continue;
if (skip > 2)
skip = 2;
if (ff->ret < 0)
continue;
ff->pkt.pts = av_rescale_q_rnd(ff->pkt.pts, ff->in_stream->time_base, ff->out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
if (pts_offset == AV_NOPTS_VALUE)
{
pts_offset = ff->pkt.pts;
}
ff->pkt.pts -= pts_offset;
ff->pkt.dts = av_rescale_q_rnd(ff->pkt.dts, ff->in_stream->time_base, ff->out_stream->time_base, (AVRounding)(AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX));
ff->pkt.duration = av_rescale_q(ff->pkt.duration, ff->in_stream->time_base, ff->out_stream->time_base);
ff->pkt.pos = -1;
ff->ret = av_interleaved_write_frame(ff->ofmt_ctx, &(ff->pkt));
if (ff->ret < 0)
{
fprintf(stderr, "Error muxing packet\n");
continue;
}
av_free_packet(&(ff->pkt));
}
ff->release();
cout << "New minute!" << endl;
if (obj.create_folder(0755))
cout << "Cannot create folder, something's wrong" << endl;
else
cout << "Create folder succesfully" << endl;
start = now;
}
return 0;
} | 28.358974 | 165 | 0.539783 | soda92 |
d437cf2a6d085015941d4446e92fd53ce872ba3a | 26,175 | cpp | C++ | isis/src/control/objs/BundleUtilities/BundleControlPoint.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/control/objs/BundleUtilities/BundleControlPoint.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | null | null | null | isis/src/control/objs/BundleUtilities/BundleControlPoint.cpp | ihumphrey-usgs/ISIS3_old | 284cc442b773f8369d44379ee29a9b46961d8108 | [
"Unlicense"
] | 1 | 2021-07-12T06:05:03.000Z | 2021-07-12T06:05:03.000Z | #include "BundleControlPoint.h"
#include <QDebug>
#include "ControlMeasure.h"
#include "Latitude.h"
#include "Longitude.h"
#include "SpecialPixel.h"
namespace Isis {
/**
* Constructs a BundleControlPoint object from a ControlPoint. Only the
* non-ignored measures are added to the BundleControlPoint.
*
* @param controlPoint Pointer to a ControlPoint that will be used to
* construct this BundleControlPoint.
*/
BundleControlPoint::BundleControlPoint(ControlPoint *controlPoint) {
m_controlPoint = controlPoint;
// setup vector of BundleMeasures for this control point
int numMeasures = controlPoint->GetNumMeasures();
for (int i = 0; i < numMeasures; i++) {
ControlMeasure *controlMeasure = controlPoint->GetMeasure(i);
if (controlMeasure->IsIgnored()) {
continue;
}
addMeasure(controlMeasure);
}
// initialize to 0.0
m_corrections.clear();
m_weights.clear();
m_nicVector.clear();
// initialize to Null for consistency with other bundle classes...
m_aprioriSigmas.clear();
m_aprioriSigmas[0] = Isis::Null;
m_aprioriSigmas[1] = Isis::Null;
m_aprioriSigmas[2] = Isis::Null;
m_adjustedSigmas.clear();
m_adjustedSigmas[0] = Isis::Null;
m_adjustedSigmas[1] = Isis::Null;
m_adjustedSigmas[2] = Isis::Null;
}
/**
* Copy constructor. Constructs a BundleControlPoint object from an existing
* BundleControlPoint.
*
* @param src The BundleControlPoint to be copied.
*/
BundleControlPoint::BundleControlPoint(const BundleControlPoint &src) {
copy(src);
}
/**
* Destructor for BundleControlPoint.
*/
BundleControlPoint::~BundleControlPoint() {
}
/**
* Copies given BundleControlPoint to this BundleControlPoint.
*
* @param src The BundleControlPoint to be copied.
*/
void BundleControlPoint::copy(const BundleControlPoint &src) {
// sanity check
clear();
m_controlPoint = src.m_controlPoint;
int numMeasures = src.size();
for (int i = 0; i < numMeasures; i++)
append(BundleMeasureQsp( new BundleMeasure(*(src.at(i))) ));
m_corrections = src.m_corrections;
m_aprioriSigmas = src.m_aprioriSigmas;
m_adjustedSigmas = src.m_adjustedSigmas;
m_weights = src.m_weights;
m_nicVector = src.m_nicVector;
}
/**
* Creates a BundleMeasure from the given ControlMeasure and appends it to
* this BundleControlPoint's measure list.
*
* @param controlMeasure The ControlMeasure to be converted.
*
* @return @b BundleMeasure* A pointer to the new BundleMeasure.
*/
BundleMeasureQsp BundleControlPoint::addMeasure(ControlMeasure *controlMeasure) {
BundleMeasureQsp bundleMeasure = BundleMeasureQsp( new BundleMeasure(controlMeasure, this) );
append(bundleMeasure);
return bundleMeasure;
}
/**
* Computes the residuals for this BundleControlPoint.
*
* @see ControlPoint::ComputeResiduals()
*/
void BundleControlPoint::computeResiduals() {
m_controlPoint->ComputeResiduals();
}
/**
* Sets the adjusted surface point for this BundleControlPoint.
*
* @param surfacePoint The surface point to be set.
*/
void BundleControlPoint::setAdjustedSurfacePoint(SurfacePoint surfacePoint) {
m_controlPoint->SetAdjustedSurfacePoint(surfacePoint);
}
/**
* Sets the number of rejected measures for this BundleControlPoint.
*
* @param numRejected Number of rejected measures.
*
* @see ControlPoint::SetNumberOfRejectedMeasures(int numRejected)
*/
void BundleControlPoint::setNumberOfRejectedMeasures(int numRejected) {
m_controlPoint->SetNumberOfRejectedMeasures(numRejected);
}
/**
* Sets this BundleControlPoint to rejected or not rejected.
*
* @param reject True will set the BundleControlPoint to rejected.
*
* @see ControlPoint::SetRejected(bool reject)
*/
void BundleControlPoint::setRejected(bool reject) {
m_controlPoint->SetRejected(reject);
}
/**
* Sets the weights using the given BundleSettings QSharedPointer and a
* conversion value for meters to radians.
*
* @param settings A QSharedPointer to BundleSettings object.
* @param metersToRadians A double precision conversion factor.
*/
void BundleControlPoint::setWeights(const BundleSettingsQsp settings, double metersToRadians) {
double d;
double globalLatitudeAprioriSigma = settings->globalLatitudeAprioriSigma();
double globalLongitudeAprioriSigma = settings->globalLongitudeAprioriSigma();
double globalRadiusAprioriSigma = settings->globalRadiusAprioriSigma();
if (m_controlPoint->GetType() == ControlPoint::Fixed) {
m_weights[0] = 1.0e+50;
m_weights[1] = 1.0e+50;
m_weights[2] = 1.0e+50;
// m_aprioriSigmas = Isis::Null by default
}
if (m_controlPoint->GetType() == ControlPoint::Free) {
if (!IsSpecial(globalLatitudeAprioriSigma)) {
m_aprioriSigmas[0] = globalLatitudeAprioriSigma;
d = globalLatitudeAprioriSigma*metersToRadians;
m_weights[0] = 1.0/(d*d);
} // else m_aprioriSigma = Isis::Null
// m_weights = 0.0
if (!IsSpecial(globalLongitudeAprioriSigma)) {
m_aprioriSigmas[1] = globalLongitudeAprioriSigma;
d = globalLongitudeAprioriSigma*metersToRadians;
m_weights[1] = 1.0/(d*d);
} // else m_aprioriSigma = Isis::Null
// m_weights = 0.0
if (!settings->solveRadius()) {
m_weights[2] = 1.0e+50;
}
else {
if (!IsSpecial(globalRadiusAprioriSigma)) {
m_aprioriSigmas[2] = globalRadiusAprioriSigma;
d = globalRadiusAprioriSigma*0.001;
m_weights[2] = 1.0/(d*d);
}
}
}
if (m_controlPoint->GetType() == ControlPoint::Constrained) {
if ( m_controlPoint->IsLatitudeConstrained() ) {
m_aprioriSigmas[0] = m_controlPoint->GetAprioriSurfacePoint().GetLatSigmaDistance().meters();
m_weights[0] = m_controlPoint->GetAprioriSurfacePoint().GetLatWeight();
}
else if (!IsSpecial(globalLatitudeAprioriSigma)) {
m_aprioriSigmas[0] = globalLatitudeAprioriSigma;
d = globalLatitudeAprioriSigma*metersToRadians;
m_weights[0] = 1.0/(d*d);
} // else not constrained and global sigma is Null, then m_aprioriSigmas = Isis::Null
// m_weights = 0.0
if ( m_controlPoint->IsLongitudeConstrained() ) {
m_aprioriSigmas[1] = m_controlPoint->GetAprioriSurfacePoint().GetLonSigmaDistance().meters();
m_weights[1] = m_controlPoint->GetAprioriSurfacePoint().GetLonWeight();
}
else if (!IsSpecial(globalLongitudeAprioriSigma)) {
m_aprioriSigmas[1] = globalLongitudeAprioriSigma;
d = globalLongitudeAprioriSigma*metersToRadians;
m_weights[1] = 1.0/(d*d);
} // else not constrained and global sigma is Null, then m_aprioriSigmas = Isis::Null
// m_weights = 0.0
if (!settings->solveRadius()) {
m_weights[2] = 1.0e+50;
}
else {
if ( m_controlPoint->IsRadiusConstrained() ) {
m_aprioriSigmas[2] = m_controlPoint->GetAprioriSurfacePoint().GetLocalRadiusSigma().meters();
m_weights[2] = m_controlPoint->GetAprioriSurfacePoint().GetLocalRadiusWeight();
}
else if (!IsSpecial(globalRadiusAprioriSigma)) {
m_aprioriSigmas[2] = globalRadiusAprioriSigma;
d = globalRadiusAprioriSigma*0.001;
m_weights[2] = 1.0/(d*d);
} // else not constrained and global sigma is Null, then m_aprioriSigmas = Isis::Null
// m_weights = 0.0
}
}
}
/**
* Resets the number of rejected measures for this BundleControlPoint to zero.
*
* @see ControlPoint::ZeroNumberOfRejectedMeasures()
*/
void BundleControlPoint::zeroNumberOfRejectedMeasures() {
m_controlPoint->ZeroNumberOfRejectedMeasures();
}
/**
* Accessor for the raw ControlPoint object used for this BundleControlPoint.
*
* @return @b ControlPoint* A pointer to the raw ControlPoint.
*/
ControlPoint *BundleControlPoint::rawControlPoint() const {
return m_controlPoint;
}
/**
* Method used to determine whether this control point is rejected.
*
* @return @b bool Indicates whether this control point is rejected.
*/
bool BundleControlPoint::isRejected() const {
return m_controlPoint->IsRejected();
}
/**
* Accesses number of measures associated with this BundleControlPoint.
*
* @return @b int The number of measures for this point.
*/
int BundleControlPoint::numberOfMeasures() const {
return this->size();
}
/**
* Accesses the number of rejected measures for this BundleControlPoint.
*
* @return @b int Returns the number of rejected measures.
*
* @see ControlPoint::GetNumberOfRejectedMeasures()
*/
int BundleControlPoint::numberOfRejectedMeasures() const {
return m_controlPoint->GetNumberOfRejectedMeasures();
}
/**
* Gets the root-mean-square (rms) of the BundleControlPoint's residuals.
*
* @return @b double Returns the rms of the residuals.
*
* @see ControlPoint::GetResidualRms()
*/
double BundleControlPoint::residualRms() const {
return m_controlPoint->GetResidualRms();
}
/**
* Accesses the adjusted SurfacePoint associated with this BundleControlPoint.
*
* @return @b SurfacePoint The adjusted surface point.
*/
SurfacePoint BundleControlPoint::adjustedSurfacePoint() const {
return m_controlPoint->GetAdjustedSurfacePoint();
}
/**
* Accesses the Point ID associated with this BundleControlPoint.
*
* @return @b QString The ID for this point.
*/
QString BundleControlPoint::id() const {
return m_controlPoint->GetId();
}
/**
* Accesses BundleControlPoint's type.
*
* @return @b ControlPoint::PointType The BundleControlPoint's type. Options are:
* Fixed = 0, Constrained = 1, Free = 2.
*
* @see ControlPoint::GetType()
*/
ControlPoint::PointType BundleControlPoint::type() const{
return m_controlPoint->GetType();
}
// ??? why bounded vector ??? can we use linear algebra vector ???
/**
* Accesses the 3 dimensional ordered vector of correction values associated
* with latitude, longitude, and radius.
*
* @return @b boost::numeric::ublas::bounded_vector<double,3>& The vector of correction values.
*/
boost::numeric::ublas::bounded_vector< double, 3 > &BundleControlPoint::corrections() {
return m_corrections;
}
/**
* Accesses the 3 dimenstional ordered vector of apriori sigmas (apriori
* latitude, apriori longitude, apriori radius).
*
* @return @b boost::numeric::ublas::bounded_vector<double,3>& The vector of apriori sigmas.
*/
boost::numeric::ublas::bounded_vector< double, 3 > &BundleControlPoint::aprioriSigmas() {
return m_aprioriSigmas;
}
/**
* Accesses the 3 dimenstional ordered vector of adjusted sigmas (adjusted
* latitude, adjusted longitude, adjusted radius).
*
* @return @b boost::numeric::ublas::bounded_vector<double,3>& The vector of adjusted sigmas.
*/
boost::numeric::ublas::bounded_vector< double, 3 > &BundleControlPoint::adjustedSigmas() {
return m_adjustedSigmas;
}
/**
* Accesses the 3 dimensional ordered vector of weight values associated
* with latitude, longitude, and radius.
*
* @return @b boost::numeric::ublas::bounded_vector<double,3>& The vector of weight values.
*/
boost::numeric::ublas::bounded_vector< double, 3 > &BundleControlPoint::weights() {
return m_weights;
}
/**
* Accesses the 3 dimensional ordered NIC vector.
*
* @return @b boost::numeric::ublas::bounded_vector<double,3>& The NIC vector.
*/
boost::numeric::ublas::bounded_vector<double, 3> &BundleControlPoint::nicVector() {
return m_nicVector;
}
/**
* Accesses the CholMod matrix associated with this BundleControlPoint.
*
* @return @b SparseBlockRowMatrix& The CholMod row matrix.
*/
SparseBlockRowMatrix &BundleControlPoint::cholmodQMatrix() {
return m_cholmodQMatrix;
}
/**
* Formats an output summary string for this BundleControlPoint. This string
* includes ID, point type, number of rays from non-rejected measures,
* residual RMS, adjusted latitude and longitude (in degrees), adjusted radius
* (in km), and the adjusted sigmas (for latitude, longitude and radius).
*
* @param errorPropagation Indicates whether error propagation was selected.
*
* @return @b QString The formatted output summary string.
*/
QString BundleControlPoint::formatBundleOutputSummaryString(bool errorPropagation) const {
int numRays = numberOfMeasures(); // should this depend on the raw point, as written, or this->size()???
int numGoodRays = numRays - numberOfRejectedMeasures();
double ResidualRms = residualRms();
double lat = m_controlPoint->GetAdjustedSurfacePoint().GetLatitude().degrees();
double lon = m_controlPoint->GetAdjustedSurfacePoint().GetLongitude().degrees();
double rad = m_controlPoint->GetAdjustedSurfacePoint().GetLocalRadius().kilometers();
QString pointType = ControlPoint::PointTypeToString(type()).toUpper();
QString output = QString("%1%2%3 of %4%5%6%7%8%9%10%11\n")
.arg(id(), 16)
.arg(pointType, 15)
.arg(numGoodRays, 5)
.arg(numRays)
.arg(formatValue(ResidualRms, 6, 2))
.arg(formatValue(lat, 16, 8)) // deg
.arg(formatValue(lon, 16, 8)) // deg
.arg(formatValue(rad, 16, 8)) // km
.arg(formatLatitudeAdjustedSigmaString(16,8,errorPropagation)) // m
.arg(formatLongitudeAdjustedSigmaString(16,8,errorPropagation)) // m
.arg(formatRadiusAdjustedSigmaString(16,8,errorPropagation)); // m
return output;
}
/**
* Formats a detailed output string table for this BundleControlPoint.
*
* @param errorPropagation Indicates whether error propagation was selected.
* @param RTM Conversion factor from radians to meters. Used to convert the
* latitude and longitude corrections to meters.
*
* @return @b QString The formatted output detailed string.
*/
QString BundleControlPoint::formatBundleOutputDetailString(bool errorPropagation,
double RTM,
bool solveRadius) const {
int numRays = numberOfMeasures();
int numGoodRays = numRays - numberOfRejectedMeasures();
double lat = m_controlPoint->GetAdjustedSurfacePoint().GetLatitude().degrees();
double lon = m_controlPoint->GetAdjustedSurfacePoint().GetLongitude().degrees();
double rad = m_controlPoint->GetAdjustedSurfacePoint().GetLocalRadius().kilometers();
// ??? corrections is always zero ??? never set in this class ???
// point corrections and initial sigmas
double cor_lat_dd = m_corrections(0) * RAD2DEG; // lat correction, decimal degs
double cor_lon_dd = m_corrections(1) * RAD2DEG; // lon correction, decimal degs
double cor_rad_m = m_corrections(2) * 1000.0; // radius correction, meters
double cor_lat_m = m_corrections(0) * RTM; // lat correction, meters
double cor_lon_m = m_corrections(1) * RTM * cos(lat*DEG2RAD); // lon correction, meters
double latInit = Isis::Null;
if (!IsSpecial(lat)) {
latInit = lat - cor_lat_dd;
}
double lonInit = Isis::Null;
if (!IsSpecial(lon)) {
lonInit = lon - cor_lon_dd;
}
double radInit = Isis::Null;
if (!IsSpecial(rad)) {
radInit = rad - m_corrections(2); // km
}
QString pointType = ControlPoint::PointTypeToString(type()).toUpper();
QString output;
output = QString(" Label: %1\nStatus: %2\n Rays: %3 of %4\n")
.arg(id())
.arg(pointType)
.arg(numGoodRays)
.arg(numRays);
QString labels = "\n Point Initial Total Total "
" Final Initial Final\n"
"Coordinate Value Correction Correction "
" Value Accuracy Accuracy\n"
" (dd/dd/km) (dd/dd/km) (Meters) "
" (dd/dd/km) (Meters) (Meters)\n";
output += labels;
output += QString(" LATITUDE%1%2%3%4%5%6\n")
.arg(formatValue(latInit, 17, 8)) // deg
.arg(formatValue(cor_lat_dd, 21, 8)) // deg
.arg(formatValue(cor_lat_m, 20, 8)) // m
.arg(formatValue(lat, 20, 8)) // deg
.arg(formatLatitudeAprioriSigmaString(18,8)) // m
.arg(formatLatitudeAdjustedSigmaString(18,8,errorPropagation)); // m
output += QString(" LONGITUDE%1%2%3%4%5%6\n")
.arg(formatValue(lonInit, 17, 8)) // deg
.arg(formatValue(cor_lon_dd, 21, 8)) // deg
.arg(formatValue(cor_lon_m, 20, 8)) // m
.arg(formatValue(lon, 20, 8)) // deg
.arg(formatLongitudeAprioriSigmaString(18,8)) // m
.arg(formatLongitudeAdjustedSigmaString(18,8,errorPropagation)); // m
output += QString(" RADIUS%1%2%3%4%5%6\n\n")
.arg(formatValue(radInit, 17, 8)) // km
.arg(formatValue(m_corrections(2), 21, 8)) // km
.arg(formatValue(cor_rad_m, 20, 8)) // m
.arg(formatValue(rad, 20, 8)) // km
.arg(formatRadiusAprioriSigmaString(18,8,solveRadius)) // m
.arg(formatRadiusAdjustedSigmaString(18,8,errorPropagation)); // m
return output;
}
/**
* Formats the given double precision value using the specified field width
* and precision. If the given value is special, then "Null" is returned.
*
* @param value The double value to be formattted.
* @param fieldWidth The return string's field width.
* @param precision The precision of the given double value to be saved off.
*
* @return @b QString The formatted value, as a string.
*/
QString BundleControlPoint::formatValue(double value, int fieldWidth, int precision) const {
QString output;
IsSpecial(value) ?
output = QString("%1").arg("Null", fieldWidth) :
output = QString("%1").arg(value, fieldWidth, 'f', precision);
return output;
}
/**
* Formats the apriori sigma value indicated by the given type code. If no
* sigma was set, then the string "N/A" will be returned.
*
* @param type Integer code that indicates which apriori sigma value will be
* formatted. Latitude=0, Longitude=1, Radius=2.
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
*
* @return @b QString The formatted value, as a string.
*/
QString BundleControlPoint::formatAprioriSigmaString(int version, int fieldWidth,
int precision, bool solveRadius) const {
QString aprioriSigmaStr;
QString pointType = ControlPoint::PointTypeToString(type()).toUpper();
if (pointType == "CONSTRAINED"||!solveRadius) {
pointType = "N/A";
}
double sigma = m_aprioriSigmas[version];
if (IsSpecial(sigma)) { // if globalAprioriSigma <= 0 (including Isis::NUll), then m_aprioriSigmas = Null
aprioriSigmaStr = QString("%1").arg(pointType, fieldWidth);
}
else {
aprioriSigmaStr = QString("%1").arg(sigma, fieldWidth, 'f', precision);
}
return aprioriSigmaStr;
}
/**
* Formats the apriori latitude sigma value.
*
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
*
* @return @b QString The formatted apriori latitude sigma value, as a string.
*
* @see formatAprioriSigmaString()
*/
QString BundleControlPoint::formatLatitudeAprioriSigmaString(int fieldWidth,
int precision) const {
return formatAprioriSigmaString(0, fieldWidth, precision, true);
}
/**
* Formats the apriori longitude sigma value.
*
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
*
* @return @b QString The formatted apriori longitude sigma value, as a string.
*
* @see formatAprioriSigmaString()
*/
QString BundleControlPoint::formatLongitudeAprioriSigmaString(int fieldWidth,
int precision) const {
return formatAprioriSigmaString(1, fieldWidth, precision, true);
}
/**
* Formats the apriori radius sigma value.
*
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
*
* @return @b QString The formatted apriori radius sigma value, as a string.
*
* @see formatAprioriSigmaString()
*/
QString BundleControlPoint::formatRadiusAprioriSigmaString(int fieldWidth,
int precision,
bool solveRadius) const {
return formatAprioriSigmaString(2, fieldWidth, precision, solveRadius);
}
/**
* Formats the adjusted sigma value indicated by the given type code. If error
* propagation is false or the selected sigma type was set to Null, then only
* "N/A" will be returned.
*
* @param type Integer code that indicates which apriori sigma value will be
* formatted. Latitude=0, Longitude=1, Radius=2.
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
* @param errorPropagation Indicates whether error propagation was selected.
*
* @return @b QString The formatted value, as a string.
*/
QString BundleControlPoint::formatAdjustedSigmaString(int type, int fieldWidth, int precision,
bool errorPropagation) const {
QString adjustedSigmaStr;
if (!errorPropagation) {
adjustedSigmaStr = QString("%1").arg("N/A",fieldWidth);
}
else {
double sigma = Isis::Null;
if (type == 0) {
sigma = m_controlPoint->GetAdjustedSurfacePoint().GetLatSigmaDistance().meters();
}
if (type == 1) {
sigma = m_controlPoint->GetAdjustedSurfacePoint().GetLonSigmaDistance().meters();
}
if (type == 2) {
sigma = m_controlPoint->GetAdjustedSurfacePoint().GetLocalRadiusSigma().meters();
}
if (IsSpecial(sigma)) {
adjustedSigmaStr = QString("%1").arg("N/A",fieldWidth);
}
else {
adjustedSigmaStr = QString("%1").arg(sigma, fieldWidth, 'f', precision);
}
}
return adjustedSigmaStr;
}
/**
* Formats the adjusted latitude sigma value.
*
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
* @param errorPropagation Indicates whether error propagation was selected.
*
* @return @b QString The formatted adjusted latitude sigma value, as a string.
*
* @see formatAdjustedSigmaString()
*/
QString BundleControlPoint::formatLatitudeAdjustedSigmaString(int fieldWidth, int precision,
bool errorPropagation) const {
return formatAdjustedSigmaString(0, fieldWidth, precision, errorPropagation);
}
/**
* Formats the adjusted longitude sigma value.
*
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
* @param errorPropagation Indicates whether error propagation was selected.
*
* @return @b QString The formatted adjusted longitude sigma value, as a string.
*
* @see formatAdjustedSigmaString()
*/
QString BundleControlPoint::formatLongitudeAdjustedSigmaString(int fieldWidth, int precision,
bool errorPropagation) const {
return formatAdjustedSigmaString(1, fieldWidth, precision, errorPropagation);
}
/**
* Formats the adjusted radius sigma value.
*
* @param fieldWidth The return string's field width.
* @param precision The precision of the double to be saved off.
* @param errorPropagation Indicates whether error propagation was selected.
*
* @return @b QString The formatted adjusted radius sigma value, as a string.
*
* @see formatAdjustedSigmaString()
*/
QString BundleControlPoint::formatRadiusAdjustedSigmaString(int fieldWidth, int precision,
bool errorPropagation) const {
return formatAdjustedSigmaString(2, fieldWidth, precision, errorPropagation);
}
}
| 36.103448 | 115 | 0.626208 | ihumphrey-usgs |
d438a41ab0350358d0614e6742f915b043b820ce | 17,511 | cpp | C++ | Siv3D/src/ThirdParty/lunasvg/svgpaintelement.cpp | Siv3D/siv6 | 090e82b2f6398640638dfa43da3f829ba977d0e2 | [
"MIT"
] | 2 | 2020-07-26T05:14:33.000Z | 2020-08-11T08:00:54.000Z | Siv3D/src/ThirdParty/lunasvg/svgpaintelement.cpp | Siv3D/siv6 | 090e82b2f6398640638dfa43da3f829ba977d0e2 | [
"MIT"
] | 6 | 2020-03-03T04:01:10.000Z | 2020-09-27T14:33:19.000Z | Siv3D/src/ThirdParty/lunasvg/svgpaintelement.cpp | Siv3D/siv6 | 090e82b2f6398640638dfa43da3f829ba977d0e2 | [
"MIT"
] | 5 | 2020-03-03T03:34:27.000Z | 2020-09-05T18:42:55.000Z | #include "svgpaintelement.h"
#include "svgdocumentimpl.h"
#include "svgstopelement.h"
#include "svgcolor.h"
#include "rendercontext.h"
namespace lunasvg {
SVGPaintElement::SVGPaintElement(DOMElementID elementId, SVGDocument* document)
: SVGStyledElement(elementId, document)
{
}
void SVGPaintElement::render(RenderContext& context) const
{
context.skipElement();
}
SVGGradientElement::SVGGradientElement(DOMElementID elementId, SVGDocument* document)
: SVGPaintElement(elementId, document),
SVGURIReference (this),
m_gradientTransform(DOMPropertyIdGradientTransform),
m_spreadMethod(DOMPropertyIdSpreadMethod),
m_gradientUnits(DOMPropertyIdGradientUnits)
{
addToPropertyMap(m_gradientTransform);
addToPropertyMap(m_spreadMethod);
addToPropertyMap(m_gradientUnits);
}
void SVGGradientElement::setGradientAttributes(GradientAttributes& attributes) const
{
if(!attributes.gradientTransform && m_gradientTransform.isSpecified())
attributes.gradientTransform = m_gradientTransform.property();
if(!attributes.spreadMethod && m_spreadMethod.isSpecified())
attributes.spreadMethod = m_spreadMethod.property();
if(!attributes.gradientUnits && m_gradientUnits.isSpecified())
attributes.gradientUnits = m_gradientUnits.property();
if(attributes.gradientStops.empty())
{
const SVGElementImpl* e = next;
while(e != tail)
{
if(e->elementId()==DOMElementIdStop)
attributes.gradientStops.push_back(to<SVGStopElement>(e));
e = e->next;
}
}
}
GradientStops SVGGradientElement::buildGradientStops(const std::vector<const SVGStopElement*>& gradientStops) const
{
GradientStops stops(gradientStops.size());
double prevOffset = 0.0;
for(unsigned int i = 0;i < gradientStops.size();i++)
{
const SVGStopElement* stop = gradientStops[i];
double offset = std::min(std::max(prevOffset, stop->offsetValue()), 1.0);
prevOffset = offset;
stops[i] = GradientStop(offset, stop->stopColorWithOpacity());
}
return stops;
}
SVGLinearGradientElement::SVGLinearGradientElement(SVGDocument* document)
: SVGGradientElement(DOMElementIdLinearGradient, document),
m_x1(DOMPropertyIdX1, LengthModeWidth, AllowNegativeLengths),
m_y1(DOMPropertyIdY1, LengthModeHeight, AllowNegativeLengths),
m_x2(DOMPropertyIdX2, LengthModeWidth, AllowNegativeLengths),
m_y2(DOMPropertyIdY2, LengthModeHeight, AllowNegativeLengths)
{
m_x2.setDefaultValue(hundredPercent());
addToPropertyMap(m_x1);
addToPropertyMap(m_y1);
addToPropertyMap(m_x2);
addToPropertyMap(m_y2);
}
void SVGLinearGradientElement::collectGradientAttributes(LinearGradientAttributes& attributes) const
{
std::set<const SVGGradientElement*> processedGradients;
const SVGGradientElement* current = this;
while(true)
{
current->setGradientAttributes(attributes);
if(current->elementId() == DOMElementIdLinearGradient)
{
const SVGLinearGradientElement* linear = to<SVGLinearGradientElement>(current);
if(!attributes.x1 && linear->m_x1.isSpecified())
attributes.x1 = linear->m_x1.property();
if(!attributes.y1 && linear->m_y1.isSpecified())
attributes.y1 = linear->m_y1.property();
if(!attributes.x2 && linear->m_x2.isSpecified())
attributes.x2 = linear->m_x2.property();
if(!attributes.y2 && linear->m_y2.isSpecified())
attributes.y2 = linear->m_y2.property();
}
processedGradients.insert(current);
SVGElementImpl* ref = document()->impl()->resolveIRI(current->hrefValue());
if(!ref || !ref->isSVGGradientElement())
break;
current = to<SVGGradientElement>(ref);
if(processedGradients.find(current)!=processedGradients.end())
break;
}
}
Paint SVGLinearGradientElement::getPaint(const RenderState& state) const
{
LinearGradientAttributes attributes;
collectGradientAttributes(attributes);
if(attributes.gradientStops.empty())
return Paint();
double x1, y1, x2, y2;
UnitType units = attributes.gradientUnits ? attributes.gradientUnits->enumValue() : UnitTypeObjectBoundingBox;
if(units == UnitTypeObjectBoundingBox)
{
x1 = attributes.x1 ? attributes.x1->value(state, 1) : 0.0;
y1 = attributes.y1 ? attributes.y1->value(state, 1) : 0.0;
x2 = attributes.x2 ? attributes.x2->value(state, 1) : 1.0;
y2 = attributes.y2 ? attributes.y2->value(state, 1) : 0.0;
}
else
{
x1 = attributes.x1 ? attributes.x1->valueX(state) : 0.0;
y1 = attributes.y1 ? attributes.y1->valueY(state) : 0.0;
x2 = attributes.x2 ? attributes.x2->valueX(state) : hundredPercent()->valueX(state);
y2 = attributes.y2 ? attributes.y2->valueY(state) : 0.0;
}
GradientStops stops = buildGradientStops(attributes.gradientStops);
if((x1 == x2 && y1 == y2) || stops.size() == 1)
return stops.back().second;
SpreadMethod spread = attributes.spreadMethod ? attributes.spreadMethod->enumValue() : SpreadMethodPad;
AffineTransform matrix;
if(units == UnitTypeObjectBoundingBox)
{
matrix.translate(state.bbox.x, state.bbox.y);
matrix.scale(state.bbox.width, state.bbox.height);
}
if(attributes.gradientTransform)
matrix.multiply(attributes.gradientTransform->value());
LinearGradient gradient(x1, y1, x2, y2);
gradient.setStops(stops);
gradient.setSpread(spread);
gradient.setMatrix(matrix);
return gradient;
}
SVGElementImpl* SVGLinearGradientElement::clone(SVGDocument* document) const
{
SVGLinearGradientElement* e = new SVGLinearGradientElement(document);
baseClone(*e);
return e;
}
SVGRadialGradientElement::SVGRadialGradientElement(SVGDocument* document)
: SVGGradientElement(DOMElementIdRadialGradient, document),
m_cx(DOMPropertyIdCx, LengthModeWidth, AllowNegativeLengths),
m_cy(DOMPropertyIdCy, LengthModeHeight, AllowNegativeLengths),
m_r(DOMPropertyIdR, LengthModeBoth, ForbidNegativeLengths),
m_fx(DOMPropertyIdFx, LengthModeWidth, AllowNegativeLengths),
m_fy(DOMPropertyIdFy, LengthModeHeight, AllowNegativeLengths)
{
m_cx.setDefaultValue(fiftyPercent());
m_cy.setDefaultValue(fiftyPercent());
m_r.setDefaultValue(fiftyPercent());
addToPropertyMap(m_cx);
addToPropertyMap(m_cy);
addToPropertyMap(m_r);
addToPropertyMap(m_fx);
addToPropertyMap(m_fy);
}
void SVGRadialGradientElement::collectGradientAttributes(RadialGradientAttributes& attributes) const
{
std::set<const SVGGradientElement*> processedGradients;
const SVGGradientElement* current = this;
while(true)
{
current->setGradientAttributes(attributes);
if(current->elementId() == DOMElementIdRadialGradient)
{
const SVGRadialGradientElement* radial = to<SVGRadialGradientElement>(current);
if(!attributes.cx && radial->m_cx.isSpecified())
attributes.cx = radial->m_cx.property();
if(!attributes.cy && radial->m_cy.isSpecified())
attributes.cy = radial->m_cy.property();
if(!attributes.r && radial->m_r.isSpecified())
attributes.r = radial->m_r.property();
if(!attributes.fx && radial->m_fx.isSpecified())
attributes.fx = radial->m_fx.property();
if(!attributes.fy && radial->m_fy.isSpecified())
attributes.fy = radial->m_fy.property();
}
processedGradients.insert(current);
SVGElementImpl* ref = document()->impl()->resolveIRI(current->hrefValue());
if(!ref || !ref->isSVGGradientElement())
break;
current = to<SVGGradientElement>(ref);
if(processedGradients.find(current)!=processedGradients.end())
break;
}
}
Paint SVGRadialGradientElement::getPaint(const RenderState& state) const
{
RadialGradientAttributes attributes;
collectGradientAttributes(attributes);
if(attributes.gradientStops.empty())
return Paint();
double cx, cy, r, fx, fy;
UnitType units = attributes.gradientUnits ? attributes.gradientUnits->enumValue() : UnitTypeObjectBoundingBox;
if(units == UnitTypeObjectBoundingBox)
{
cx = attributes.cx ? attributes.cx->value(state, 1) : 0.5;
cy = attributes.cy ? attributes.cy->value(state, 1) : 0.5;
r = attributes.r ? attributes.r->value(state, 1) : 0.5;
fx = attributes.fx ? attributes.fx->value(state, 1) : cx;
fy = attributes.fy ? attributes.fy->value(state, 1) : cy;
}
else
{
cx = attributes.cx ? attributes.cx->valueX(state) : fiftyPercent()->valueX(state);
cy = attributes.cy ? attributes.cy->valueY(state) : fiftyPercent()->valueY(state);
r = attributes.r ? attributes.r->value(state) : fiftyPercent()->value(state);
fx = attributes.fx ? attributes.fx->valueX(state) : cx;
fy = attributes.fy ? attributes.fy->valueY(state) : cy;
}
GradientStops stops = buildGradientStops(attributes.gradientStops);
if(r == 0.0 || stops.size() == 1)
return stops.back().second;
SpreadMethod spread = attributes.spreadMethod ? attributes.spreadMethod->enumValue() : SpreadMethodPad;
AffineTransform matrix;
if(units == UnitTypeObjectBoundingBox)
{
matrix.translate(state.bbox.x, state.bbox.y);
matrix.scale(state.bbox.width, state.bbox.height);
}
if(attributes.gradientTransform)
matrix.multiply(attributes.gradientTransform->value());
RadialGradient gradient(cx, cy, r, fx, fy);
gradient.setStops(stops);
gradient.setSpread(spread);
gradient.setMatrix(matrix);
return gradient;
}
SVGElementImpl* SVGRadialGradientElement::clone(SVGDocument* document) const
{
SVGRadialGradientElement* e = new SVGRadialGradientElement(document);
baseClone(*e);
return e;
}
SVGPatternElement::SVGPatternElement(SVGDocument* document)
: SVGPaintElement(DOMElementIdPattern, document),
SVGURIReference(this),
SVGFitToViewBox(this),
m_x(DOMPropertyIdX, LengthModeWidth, AllowNegativeLengths),
m_y(DOMPropertyIdY, LengthModeHeight, AllowNegativeLengths),
m_width(DOMPropertyIdWidth, LengthModeWidth, ForbidNegativeLengths),
m_height(DOMPropertyIdHeight, LengthModeHeight, ForbidNegativeLengths),
m_patternTransform(DOMPropertyIdPatternTransform),
m_patternUnits(DOMPropertyIdPatternUnits),
m_patternContentUnits(DOMPropertyIdPatternContentUnits)
{
addToPropertyMap(m_x);
addToPropertyMap(m_y);
addToPropertyMap(m_width);
addToPropertyMap(m_height);
addToPropertyMap(m_patternTransform);
addToPropertyMap(m_patternUnits);
addToPropertyMap(m_patternContentUnits);
}
void SVGPatternElement::collectPatternAttributes(PatternAttributes& attributes) const
{
std::set<const SVGPatternElement*> processedGradients;
const SVGPatternElement* current = this;
while(true)
{
if(!attributes.x && current->x().isSpecified())
attributes.x = current->x().property();
if(!attributes.y && current->y().isSpecified())
attributes.y = current->y().property();
if(!attributes.width && current->width().isSpecified())
attributes.width = current->width().property();
if(!attributes.height && current->height().isSpecified())
attributes.height = current->height().property();
if(!attributes.patternTransform && current->patternTransform().isSpecified())
attributes.patternTransform = current->patternTransform().property();
if(!attributes.patternUnits && current->patternUnits().isSpecified())
attributes.patternUnits = current->patternUnits().property();
if(!attributes.patternContentUnits && current->patternContentUnits().isSpecified())
attributes.patternContentUnits = current->patternContentUnits().property();
if(!attributes.viewBox && current->viewBox().isSpecified())
attributes.viewBox = current->viewBox().property();
if(!attributes.preserveAspectRatio && current->preserveAspectRatio().isSpecified())
attributes.preserveAspectRatio = current->preserveAspectRatio().property();
if(!attributes.patternContentElement && current->next != current->tail)
attributes.patternContentElement = current;
processedGradients.insert(current);
SVGElementImpl* ref = document()->impl()->resolveIRI(current->hrefValue());
if(!ref || ref->elementId() != DOMElementIdPattern)
break;
current = to<SVGPatternElement>(ref);
if(processedGradients.find(current)!=processedGradients.end())
break;
}
}
Paint SVGPatternElement::getPaint(const RenderState& state) const
{
PatternAttributes attributes;
collectPatternAttributes(attributes);
double x, y, w, h;
UnitType units = attributes.patternUnits ? attributes.patternUnits->enumValue() : UnitTypeObjectBoundingBox;
if(units == UnitTypeObjectBoundingBox)
{
x = attributes.x ? state.bbox.x + attributes.x->value(state, 1) * state.bbox.width : 0;
y = attributes.y ? state.bbox.y + attributes.y->value(state, 1) * state.bbox.height : 0;
w = attributes.width ? attributes.width->value(state, 1) * state.bbox.width : 0;
h = attributes.height ? attributes.height->value(state, 1) * state.bbox.height : 0;
}
else
{
x = attributes.x ? attributes.x->valueX(state) : 0;
y = attributes.y ? attributes.y->valueY(state) : 0;
w = attributes.width ? attributes.width->valueX(state) : 0;
h = attributes.height ? attributes.height->valueY(state) : 0;
}
AffineTransform transform(state.matrix);
if(attributes.patternTransform)
transform.multiply(attributes.patternTransform->value());
const double* m = transform.getMatrix();
double scalex = std::sqrt(m[0] * m[0] + m[2] * m[2]);
double scaley = std::sqrt(m[1] * m[1] + m[3] * m[3]);
double width = w * scalex;
double height = h * scaley;
if(width == 0.0 || height == 0.0 || attributes.patternContentElement == nullptr || RenderBreaker::hasElement(this))
return Paint();
RenderContext newContext(this, RenderModeDisplay);
RenderState& newState = newContext.state();
newState.element = this;
newState.canvas.reset(std::uint32_t(std::ceil(width)), std::uint32_t(std::ceil(height)));
newState.style.add(style());
newState.matrix.scale(scalex, scaley);
newState.viewPort = state.viewPort;
newState.color = KRgbBlack;
newState.dpi = state.dpi;
if(attributes.viewBox)
{
const SVGPreserveAspectRatio* positioning = attributes.preserveAspectRatio ? attributes.preserveAspectRatio : SVGPreserveAspectRatio::defaultValue();
newState.matrix.multiply(positioning->getMatrix(Rect(0, 0, w, h), attributes.viewBox->value()));
newState.viewPort = attributes.viewBox->value();
}
else if(attributes.patternContentUnits && attributes.patternContentUnits->enumValue() == UnitTypeObjectBoundingBox)
{
newState.matrix.scale(state.bbox.width, state.bbox.height);
newState.viewPort = Rect(0, 0, 1, 1);
}
RenderBreaker::registerElement(this);
newContext.render(attributes.patternContentElement->next, attributes.patternContentElement->tail->prev);
RenderBreaker::unregisterElement(this);
AffineTransform matrix(1.0/scalex, 0, 0, 1.0/scaley, x, y);
if(attributes.patternTransform)
matrix.postmultiply(attributes.patternTransform->value());
Pattern pattern(newState.canvas);
pattern.setTileMode(TileModeRepeat);
pattern.setMatrix(matrix);
return pattern;
}
SVGElementImpl* SVGPatternElement::clone(SVGDocument* document) const
{
SVGPatternElement* e = new SVGPatternElement(document);
baseClone(*e);
return e;
}
SVGSolidColorElement::SVGSolidColorElement(SVGDocument* document)
: SVGPaintElement(DOMElementIdSolidColor, document)
{
}
Paint SVGSolidColorElement::getPaint(const RenderState&) const
{
if(!style().isSpecified())
return KRgbBlack;
Rgb color;
if(const CSSPropertyBase* item = style().property()->getItem(CSSPropertyIdSolid_Color))
{
const SVGPropertyBase* property = !item->isInherited() ? item->property() : findInheritedProperty(CSSPropertyIdSolid_Color);
if(property)
{
const SVGColor* solidColor = to<SVGColor>(property);
color = solidColor->colorType() == ColorTypeCurrentColor ? currentColor() : solidColor->value();
}
}
if(const CSSPropertyBase* item = style().property()->getItem(CSSPropertyIdSolid_Opacity))
{
const SVGPropertyBase* property = !item->isInherited() ? item->property() : findInheritedProperty(CSSPropertyIdSolid_Opacity);
if(property)
{
const SVGNumber* solidOpacity = to<SVGNumber>(property);
color.a = std::uint8_t(solidOpacity->value() * 255.0);
}
}
return color;
}
SVGElementImpl* SVGSolidColorElement::clone(SVGDocument* document) const
{
SVGSolidColorElement* e = new SVGSolidColorElement(document);
baseClone(*e);
return e;
}
} // namespace lunasvg
| 38.233624 | 157 | 0.685226 | Siv3D |
d4392fcf9791eda5469f1cbfe7851256bbeaa0c7 | 493 | hpp | C++ | include/SequentialSink.hpp | Modzeleczek/WebcamFilter | 7af1a54565b405eae681f90dd59e22b099ead9f0 | [
"MIT"
] | null | null | null | include/SequentialSink.hpp | Modzeleczek/WebcamFilter | 7af1a54565b405eae681f90dd59e22b099ead9f0 | [
"MIT"
] | null | null | null | include/SequentialSink.hpp | Modzeleczek/WebcamFilter | 7af1a54565b405eae681f90dd59e22b099ead9f0 | [
"MIT"
] | null | null | null | #ifndef SequentialSink_HPP
#define SequentialSink_HPP
#include "Runner.hpp"
class SequentialSink : public Runner // przetwarzanie sekwencyjne bez bufora wyjściowego, do którego byśmy jawnie zapisywali w niniejszym programie
{
public:
SequentialSink(ISource &source, InPlaceProcessor &ipp, OutOfPlaceProcessor &oopp, ITarget &target);
SequentialSink(const SequentialSink &) = delete;
virtual ~SequentialSink();
virtual void Start() override;
};
#endif // SequentialSink_HPP
| 29 | 147 | 0.778905 | Modzeleczek |
d43b1b8b09d88a60e081f908d544e0b3f2aa2276 | 3,260 | cpp | C++ | src/OpenCascadeTest/OpenCascadeTest/OpenCascadeTest.cpp | devel0/SearchAThing.Solid | 4731d5fd90d2ba7ce5f14e8b8ac0633024983064 | [
"MIT"
] | 9 | 2019-08-15T08:35:56.000Z | 2022-02-08T09:15:16.000Z | src/OpenCascadeTest/OpenCascadeTest/OpenCascadeTest.cpp | simutaroman/SearchAThing.Solid | 19e1ba46fabc6b3267e7724acec48c24d0f96a92 | [
"MIT"
] | 2 | 2020-05-05T12:46:08.000Z | 2020-10-02T08:16:03.000Z | src/OpenCascadeTest/OpenCascadeTest/OpenCascadeTest.cpp | simutaroman/SearchAThing.Solid | 19e1ba46fabc6b3267e7724acec48c24d0f96a92 | [
"MIT"
] | 6 | 2018-12-19T08:15:36.000Z | 2020-10-01T14:30:09.000Z | #include "stdafx.h"
#include <gp_Pnt.hxx>
#include <gp_Lin.hxx>
#include <STEPControl_Controller.hxx>
#include <STEPControl_Writer.hxx>
#include <IGESControl_Controller.hxx>
#include <IGESControl_Writer.hxx>
#include <BRepBuilderAPI_MakeEdge.hxx>
#include <BRepBuilderAPI_MakeWire.hxx>
#include <BRepBuilderAPI_MakeFace.hxx>
#include <BRepBuilderAPI_MakePolygon.hxx>
#include <TopoDS_Edge.hxx>
#include <TopoDS_Wire.hxx>
#include <TopoDS_Shape.hxx>
#include <TopoDS_Face.hxx>
#include <GeomAPI_IntSS.hxx>
#include <GeomAPI_Interpolate.hxx>
#include <Geom_Line.hxx>
#include <TopOpeBRep_ShapeIntersector.hxx>
#include <BRepFill_FaceAndOrder.hxx>
#include <BRepTools.hxx>
#include <BRepTools_Modifier.hxx>
#include <BRepBuilderAPI_NurbsConvert.hxx>
#include <BRepOffset_Offset.hxx>
#include <BRepLib_FindSurface.hxx>
#include <BRepFill.hxx>
#include <BRep_TVertex.hxx>
#include <Geom_Curve.hxx>
#include <TopoDS.hxx>
#include <TopExp.hxx>
#include <BRep_Tool.hxx>
#include <GeomLProp_SLProps.hxx>
int main()
{
STEPControl_Controller::Init();
STEPControl_Writer STW;
IGESControl_Controller::Init();
IGESControl_Writer ICW("MM", 0);
TopoDS_Face face1;
TopoDS_Face face2;
{
gp_Pnt p1(0, 0, 0);
gp_Pnt p2(10, 0, 0);
gp_Pnt p3(0, 10, 0);
gp_Pnt p4(10, 10, 5);
auto edge12 = BRepBuilderAPI_MakeEdge(p1, p2);
auto edge23 = BRepBuilderAPI_MakeEdge(p2, p3);
auto edge34 = BRepBuilderAPI_MakeEdge(p3, p4);
auto edge41 = BRepBuilderAPI_MakeEdge(p4, p1);
face1 = BRepFill::Face(edge12, edge34);
ICW.AddShape(face1);
}
{
gp_Pnt p1(7.5, -5, -5);
gp_Pnt p2(7.5, 15, -5);
gp_Pnt p3(7.5, -5, 15);
gp_Pnt p4(7.5, 15, 15);
auto edge12 = BRepBuilderAPI_MakeEdge(p1, p2); auto edge21 = BRepBuilderAPI_MakeEdge(p2, p1);
auto edge34 = BRepBuilderAPI_MakeEdge(p3, p4); auto edge43 = BRepBuilderAPI_MakeEdge(p4, p3);
face2 = BRepFill::Face(edge12, edge34);
auto face2b = BRepFill::Face(edge21, edge43);
ICW.AddShape(face2);
ICW.AddShape(face2b);
{
auto umin = 0.0;
auto umax = 0.0;
auto vmin = 0.0;
auto vmax = 0.0;
BRepTools::UVBounds(face2, umin, umax, vmin, vmax);
auto surf = BRep_Tool::Surface(face2);
GeomLProp_SLProps props(surf, umin, vmin, 1, .01);
gp_Dir normal = props.Normal();
}
{
auto umin = 0.0;
auto umax = 0.0;
auto vmin = 0.0;
auto vmax = 0.0;
BRepTools::UVBounds(face2b, umin, umax, vmin, vmax);
auto surf = BRep_Tool::Surface(face2b);
GeomLProp_SLProps props(surf, umin, vmin, 1, .01);
gp_Dir normal = props.Normal();
}
auto off = BRepOffset_Offset(face2, 2);
ICW.AddShape(off.Face());
}
auto s1 = BRepLib_FindSurface(face1);
auto s2 = BRepLib_FindSurface(face2);
auto a = GeomAPI_IntSS(s1.Surface(), s2.Surface(), 1e-1);
printf("IsDone=%d\n", a.IsDone());
printf("lines = %d\n", a.NbLines());
Handle(Geom_Curve) C = a.Line(1);
BRepBuilderAPI_MakeEdge edge(C, C->FirstParameter(), C->LastParameter());
auto v1 = edge.Vertex1();
auto v2 = edge.Vertex2();
auto p1 = BRep_Tool::Pnt(v1);
auto p2 = BRep_Tool::Pnt(v2);
printf("Intersection line = (%f,%f,%f)-(%f,%f,%f)",
p1.X(), p1.Y(), p1.Z(),
p2.X(), p2.Y(), p2.Z());
ICW.AddGeom(C);
ICW.ComputeModel();
auto OK = ICW.Write("MyFile.igs");
return 0;
}
| 23.285714 | 97 | 0.692331 | devel0 |
d43c4bc1cb701bbf58ad995bc57abf1680c17e26 | 351 | cpp | C++ | Brickjoon_Src/Silver3/11659.cpp | waixxt3213/Brickjoon | 66b38d7026febb090d47db1c8c56793ff1e54617 | [
"MIT"
] | 1 | 2021-07-29T14:27:44.000Z | 2021-07-29T14:27:44.000Z | Brickjoon_Src/Silver3/11659.cpp | naixt1478/Brickjoon | 3aa8c7121baf508128ce4f7cbb2ba44ca8745a87 | [
"MIT"
] | null | null | null | Brickjoon_Src/Silver3/11659.cpp | naixt1478/Brickjoon | 3aa8c7121baf508128ce4f7cbb2ba44ca8745a87 | [
"MIT"
] | 1 | 2020-10-10T14:35:59.000Z | 2020-10-10T14:35:59.000Z | #include <bits/stdc++.h>
using namespace std;
int main()
{
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
int m, n, i, j;
cin >> m >> n;
vector<int> num(m+1), sum(m+1);
for (int k = 1; k <= m; k++)
{
cin >> num[k];
sum[k] = sum[k - 1] + num[k];
}
while (n--)
{
cin >> i >> j;
cout << sum[j] - sum[i-1] << '\n';
}
}
// solve
| 14.04 | 36 | 0.492877 | waixxt3213 |
d43c8ec1fb6df44cf40815799f7815be0c7f2d49 | 1,492 | cc | C++ | hbase-native-client/src/sync/hbase_admin.cc | jeffreyflukman/hbase | 8bf966c8e936dec4d83bcbe85c5aab543f14a0df | [
"Apache-2.0"
] | 4 | 2017-11-01T10:49:40.000Z | 2019-10-18T02:38:08.000Z | hbase-native-client/src/sync/hbase_admin.cc | jeffreyflukman/hbase | 8bf966c8e936dec4d83bcbe85c5aab543f14a0df | [
"Apache-2.0"
] | 131 | 2019-01-25T07:53:30.000Z | 2021-07-07T07:17:14.000Z | hbase-native-client/src/sync/hbase_admin.cc | jeffreyflukman/hbase | 8bf966c8e936dec4d83bcbe85c5aab543f14a0df | [
"Apache-2.0"
] | 15 | 2017-01-12T10:41:58.000Z | 2019-04-19T08:28:29.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include "sync/hbase_admin.h"
#include <stdlib.h>
#include <stdbool.h>
#include "core/admin.h"
int32_t hb_admin_create(hb_admin_t** admin_ptr) {
(*admin_ptr) = reinterpret_cast<hb_admin_t *>(new Admin());
return 0;
}
/*
* Disconnect the admin releasing any internal objects
* or connections created in the background.
*/
int32_t hb_admin_destroy(hb_admin_t * admin) {
Admin * adm = reinterpret_cast<Admin *>(admin);
delete adm;
return 0;
}
/*
* See if a table exists.
*/
int32_t hb_admin_table_exists(hb_admin_t * admin,
char * name_space, size_t name_space_length,
char * table, size_t table_length,
bool * exists) {
*exists = true;
return 0;
}
| 28.692308 | 75 | 0.727882 | jeffreyflukman |
d43e06a7e34f4f23ea46aa6feebd3779f78587e1 | 203 | cpp | C++ | L09-AVL/main.cpp | tlyon3/CS235 | 2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda | [
"MIT"
] | 1 | 2018-03-04T02:58:55.000Z | 2018-03-04T02:58:55.000Z | L09-AVL/main.cpp | tlyon3/CS235 | 2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda | [
"MIT"
] | 1 | 2015-02-09T21:29:12.000Z | 2015-02-09T21:32:06.000Z | L09-AVL/main.cpp | tlyon3/CS235 | 2bdb8eaf66c9adbfe7ec59c0535852fd1cc30eda | [
"MIT"
] | 4 | 2019-05-20T02:57:47.000Z | 2021-02-11T15:41:15.000Z | #include "./Student_Code/avl.cpp"
#include "./Student_Code/node.cpp"
using namespace std;
int main()
{
AVL myavl;
myavl.add(0);
//cout<<"Height of root: "<<myavl.height(myavl.getRootNode())<<endl;
} | 18.454545 | 69 | 0.684729 | tlyon3 |
d43e97b044036098211d498133d3ded5befcc95e | 309 | cpp | C++ | Notebook/codes/estruturas/busca_vector.cpp | rodrigoAMF7/Notebook---Maratonas | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | 4 | 2019-01-25T21:22:55.000Z | 2019-03-20T18:04:01.000Z | Notebook/codes/estruturas/busca_vector.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | Notebook/codes/estruturas/busca_vector.cpp | rodrigoAMF/competitive-programming-notebook | 06b38197a042bfbd27b20f707493e0a19fda7234 | [
"MIT"
] | null | null | null | iterator find(iterator first, iterator last, const T &value);
iterator find_if(iterator first, iterator last, const T &value, TestFunction test);
bool binary_search(iterator first, iterator last, const T &value);
bool binary_search(iterator first, iterator last, const T &value, LessThanOrEqualFunction comp); | 77.25 | 96 | 0.802589 | rodrigoAMF7 |
d44147fb6c1f0e22c11d31821a5da47e29c89a97 | 3,134 | hpp | C++ | src/px4/mavlink/common/mavlink_msg_attitude_quaternion_cov.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 10 | 2021-03-15T03:58:06.000Z | 2021-12-30T15:33:38.000Z | src/px4/mavlink/common/mavlink_msg_attitude_quaternion_cov.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 1 | 2021-07-08T10:26:06.000Z | 2021-07-08T10:31:11.000Z | src/px4/mavlink/common/mavlink_msg_attitude_quaternion_cov.hpp | mfkiwl/GLMocap | 72de3cc11256d0d8567e86b8a2487ffc81fc984e | [
"MIT"
] | 8 | 2021-10-09T08:47:53.000Z | 2022-01-17T07:45:33.000Z | // MESSAGE ATTITUDE_QUATERNION_COV support class
#pragma once
namespace mavlink {
namespace common {
namespace msg {
/**
* @brief ATTITUDE_QUATERNION_COV message
*
* The attitude in the aeronautical frame (right-handed, Z-down, X-front, Y-right), expressed as quaternion. Quaternion order is w, x, y, z and a zero rotation would be expressed as (1 0 0 0).
*/
struct ATTITUDE_QUATERNION_COV : mavlink::Message {
static constexpr msgid_t MSG_ID = 61;
static constexpr size_t LENGTH = 72;
static constexpr size_t MIN_LENGTH = 72;
static constexpr uint8_t CRC_EXTRA = 167;
static constexpr auto NAME = "ATTITUDE_QUATERNION_COV";
uint64_t time_usec; /*< [us] Timestamp (UNIX Epoch time or time since system boot). The receiving end can infer timestamp format (since 1.1.1970 or since system boot) by checking for the magnitude of the number. */
std::array<float, 4> q; /*< Quaternion components, w, x, y, z (1 0 0 0 is the null-rotation) */
float rollspeed; /*< [rad/s] Roll angular speed */
float pitchspeed; /*< [rad/s] Pitch angular speed */
float yawspeed; /*< [rad/s] Yaw angular speed */
std::array<float, 9> covariance; /*< Row-major representation of a 3x3 attitude covariance matrix (states: roll, pitch, yaw; first three entries are the first ROW, next three entries are the second row, etc.). If unknown, assign NaN value to first element in the array. */
inline std::string get_name(void) const override
{
return NAME;
}
inline Info get_message_info(void) const override
{
return { MSG_ID, LENGTH, MIN_LENGTH, CRC_EXTRA };
}
inline std::string to_yaml(void) const override
{
std::stringstream ss;
ss << NAME << ":" << std::endl;
ss << " time_usec: " << time_usec << std::endl;
ss << " q: [" << to_string(q) << "]" << std::endl;
ss << " rollspeed: " << rollspeed << std::endl;
ss << " pitchspeed: " << pitchspeed << std::endl;
ss << " yawspeed: " << yawspeed << std::endl;
ss << " covariance: [" << to_string(covariance) << "]" << std::endl;
return ss.str();
}
inline void serialize(mavlink::MsgMap &map) const override
{
map.reset(MSG_ID, LENGTH);
map << time_usec; // offset: 0
map << q; // offset: 8
map << rollspeed; // offset: 24
map << pitchspeed; // offset: 28
map << yawspeed; // offset: 32
map << covariance; // offset: 36
}
inline void deserialize(mavlink::MsgMap &map) override
{
map >> time_usec; // offset: 0
map >> q; // offset: 8
map >> rollspeed; // offset: 24
map >> pitchspeed; // offset: 28
map >> yawspeed; // offset: 32
map >> covariance; // offset: 36
}
};
} // namespace msg
} // namespace common
} // namespace mavlink
| 38.691358 | 277 | 0.565412 | mfkiwl |
d4425ec9f5d2f32c059567ac0121dafe2f40e538 | 1,224 | cpp | C++ | aws-cpp-sdk-glacier/source/model/ListVaultsResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-02-10T08:06:54.000Z | 2022-02-10T08:06:54.000Z | aws-cpp-sdk-glacier/source/model/ListVaultsResult.cpp | lintonv/aws-sdk-cpp | 15e19c265ffce19d2046b18aa1b7307fc5377e58 | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-glacier/source/model/ListVaultsResult.cpp | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-11-09T11:58:03.000Z | 2021-11-09T11:58:03.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/glacier/model/ListVaultsResult.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <aws/core/AmazonWebServiceResult.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/UnreferencedParam.h>
#include <utility>
using namespace Aws::Glacier::Model;
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
using namespace Aws;
ListVaultsResult::ListVaultsResult()
{
}
ListVaultsResult::ListVaultsResult(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
*this = result;
}
ListVaultsResult& ListVaultsResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result)
{
JsonView jsonValue = result.GetPayload().View();
if(jsonValue.ValueExists("VaultList"))
{
Array<JsonView> vaultListJsonList = jsonValue.GetArray("VaultList");
for(unsigned vaultListIndex = 0; vaultListIndex < vaultListJsonList.GetLength(); ++vaultListIndex)
{
m_vaultList.push_back(vaultListJsonList[vaultListIndex].AsObject());
}
}
if(jsonValue.ValueExists("Marker"))
{
m_marker = jsonValue.GetString("Marker");
}
return *this;
}
| 24.48 | 102 | 0.742647 | lintonv |
d4451031c3a61e4e88b0b72d5346efaa7969b95a | 4,635 | cc | C++ | src/third_party/mozc/session/internal/ime_context.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 9 | 2018-09-21T05:36:12.000Z | 2021-11-15T15:14:36.000Z | src/third_party/mozc/session/internal/ime_context.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | null | null | null | src/third_party/mozc/session/internal/ime_context.cc | jxjnjjn/chromium | 435c1d02fd1b99001dc9e1e831632c894523580d | [
"Apache-2.0"
] | 3 | 2018-11-28T14:54:13.000Z | 2020-07-02T07:36:07.000Z | // Copyright 2010-2011, Google Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above
// copyright notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the name of Google Inc. nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ImeContext class contains the whole internal variables representing
// a session.
#include "session/internal/ime_context.h"
#include "composer/composer.h"
#include "session/session_converter_interface.h"
namespace mozc {
namespace session {
ImeContext::ImeContext()
: create_time_(0),
last_command_time_(0),
composer_(NULL),
converter_(NULL),
state_(NONE) {}
ImeContext::~ImeContext() {}
uint64 ImeContext::create_time() const { return create_time_; }
void ImeContext::set_create_time(uint64 create_time) {
create_time_ = create_time;
}
uint64 ImeContext::last_command_time() const { return last_command_time_; }
void ImeContext::set_last_command_time(uint64 last_time) {
last_command_time_ = last_time;
}
const composer::Composer &ImeContext::composer() const {
DCHECK(composer_.get());
return *composer_;
}
composer::Composer *ImeContext::mutable_composer() {
DCHECK(composer_.get());
return composer_.get();
}
void ImeContext::set_composer(composer::Composer *composer) {
DCHECK(composer);
composer_.reset(composer);
}
const SessionConverterInterface &ImeContext::converter() const {
return *converter_;
}
SessionConverterInterface *ImeContext::mutable_converter() {
return converter_.get();
}
void ImeContext::set_converter(SessionConverterInterface *converter) {
converter_.reset(converter);
}
ImeContext::State ImeContext::state() const {
return state_;
}
void ImeContext::set_state(ImeContext::State state) {
state_ = state;
}
const TransformTable &ImeContext::transform_table() const {
return transform_table_;
}
TransformTable *ImeContext::mutable_transform_table() {
return &transform_table_;
}
config::Config::SessionKeymap ImeContext::keymap() const {
return keymap_;
}
void ImeContext::set_keymap(config::Config::SessionKeymap keymap) {
keymap_ = keymap;
}
const commands::Capability &ImeContext::client_capability() const {
return client_capability_;
}
commands::Capability *ImeContext::mutable_client_capability() {
return &client_capability_;
}
const commands::ApplicationInfo &ImeContext::application_info() const {
return application_info_;
}
commands::ApplicationInfo *ImeContext::mutable_application_info() {
return &application_info_;
}
const commands::Output &ImeContext::output() const {
return output_;
}
commands::Output *ImeContext::mutable_output() {
return &output_;
}
// static
void ImeContext::CopyContext(const ImeContext &src, ImeContext *dest) {
DCHECK(dest);
dest->mutable_output()->CopyFrom(src.output());
dest->mutable_converter()->CopyFrom(src.converter());
dest->set_state(src.state());
switch (dest->state()) {
case DIRECT:
case PRECOMPOSITION:
// Do nothing more.
return;
case COMPOSITION:
dest->mutable_composer()->CopyFromForSubmission(src.composer());
return;
case CONVERSION:
dest->mutable_composer()->CopyFromForConversion(src.composer());
return;
default:
LOG(ERROR) << "Unknown state: " << dest->state();
}
}
} // namespace session
} // namespace mozc
| 30.294118 | 75 | 0.747141 | jxjnjjn |
d445b98d3828228e3ff991f917e244f31462b2b0 | 288 | cpp | C++ | AtCoder/abc028/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | AtCoder/abc028/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | 1 | 2021-10-19T08:47:23.000Z | 2022-03-07T05:23:56.000Z | AtCoder/abc028/a/main.cpp | H-Tatsuhiro/Com_Pro-Cpp | fd79f7821a76b11f4a6f83bbb26a034db577a877 | [
"MIT"
] | null | null | null | #include <iostream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
int N; cin >> N;
if (N <= 59) cout << "Bad";
else if (N <= 89) cout << "Good";
else if (N <= 99) cout << "Great";
else cout << "Perfect";
cout << endl;
}
| 20.571429 | 38 | 0.548611 | H-Tatsuhiro |
d44702e9394d2828bc4b89d4decdcd8cc0b08972 | 1,856 | cpp | C++ | IMU/05-imu-navigation/src/imu_integration/src/subscriber/odom_subscriber.cpp | lanqing30/SensorFusionCourse | 3fcf935d6a4191563afcf2d95b34718fba7f705a | [
"Apache-2.0"
] | 7 | 2021-03-19T05:51:44.000Z | 2021-09-16T06:10:16.000Z | 05-imu-navigation/sensor-fusion-for-localization-and-mapping/workspace/assignments/05-imu-navigation/src/imu_integration/src/subscriber/odom_subscriber.cpp | WeihengXia0123/LiDar-SLAM | 834060da7ee0125cefd310d6215821551bac16c3 | [
"MIT"
] | null | null | null | 05-imu-navigation/sensor-fusion-for-localization-and-mapping/workspace/assignments/05-imu-navigation/src/imu_integration/src/subscriber/odom_subscriber.cpp | WeihengXia0123/LiDar-SLAM | 834060da7ee0125cefd310d6215821551bac16c3 | [
"MIT"
] | 6 | 2021-02-17T12:31:08.000Z | 2022-01-22T17:12:44.000Z | /*
* @Description: Subscribe to ROS odometry message
* @Author: Ge Yao
* @Date: 2020-11-10 14:25:03
*/
#include "imu_integration/subscriber/odom_subscriber.hpp"
#include "glog/logging.h"
#include <eigen3/Eigen/src/Geometry/RotationBase.h>
namespace imu_integration {
OdomSubscriber::OdomSubscriber(
ros::NodeHandle& nh,
std::string topic_name,
size_t buff_size
) :nh_(nh) {
subscriber_ = nh_.subscribe(topic_name, buff_size, &OdomSubscriber::msg_callback, this);
}
void OdomSubscriber::msg_callback(
const nav_msgs::OdometryConstPtr& odom_msg_ptr
) {
buff_mutex_.lock();
// convert ROS IMU to GeographicLib compatible GNSS message:
OdomData odom_data;
odom_data.time = odom_msg_ptr->header.stamp.toSec();
Eigen::Quaterniond q(
odom_msg_ptr->pose.pose.orientation.w,
odom_msg_ptr->pose.pose.orientation.x,
odom_msg_ptr->pose.pose.orientation.y,
odom_msg_ptr->pose.pose.orientation.z
);
Eigen::Vector3d t(
odom_msg_ptr->pose.pose.position.x,
odom_msg_ptr->pose.pose.position.y,
odom_msg_ptr->pose.pose.position.z
);
odom_data.pose.block<3, 3>(0, 0) = q.toRotationMatrix();
odom_data.pose.block<3, 1>(0, 3) = t;
odom_data.vel = Eigen::Vector3d(
odom_msg_ptr->twist.twist.linear.x,
odom_msg_ptr->twist.twist.linear.y,
odom_msg_ptr->twist.twist.linear.z
);
// add new message to buffer:
odom_data_.push_back(odom_data);
buff_mutex_.unlock();
}
void OdomSubscriber::ParseData(
std::deque<OdomData>& odom_data
) {
buff_mutex_.lock();
// pipe all available measurements to output buffer:
if (odom_data_.size() > 0) {
odom_data.insert(odom_data.end(), odom_data_.begin(), odom_data_.end());
odom_data_.clear();
}
buff_mutex_.unlock();
}
} // namespace imu_integration | 26.514286 | 90 | 0.686422 | lanqing30 |
d448f7ef6ae7fa13e116ce4da36d53284f9ea004 | 591 | hpp | C++ | src/include/duckdb/catalog/default/default_schemas.hpp | ankane/duckdb | 8a60a6144059067939092bdc30ca229093c984e5 | [
"MIT"
] | 1 | 2020-10-22T02:24:32.000Z | 2020-10-22T02:24:32.000Z | src/include/duckdb/catalog/default/default_schemas.hpp | ankane/duckdb | 8a60a6144059067939092bdc30ca229093c984e5 | [
"MIT"
] | null | null | null | src/include/duckdb/catalog/default/default_schemas.hpp | ankane/duckdb | 8a60a6144059067939092bdc30ca229093c984e5 | [
"MIT"
] | null | null | null | //===----------------------------------------------------------------------===//
// DuckDB
//
// duckdb/catalog/default/default_schemas.hpp
//
//
//===----------------------------------------------------------------------===//
#pragma once
#include "duckdb/catalog/default/default_generator.hpp"
namespace duckdb {
class DefaultSchemaGenerator : public DefaultGenerator {
public:
DefaultSchemaGenerator(Catalog &catalog);
public:
unique_ptr<CatalogEntry> CreateDefaultEntry(ClientContext &context, const string &entry_name) override;
};
} // namespace duckdb
| 24.625 | 104 | 0.536379 | ankane |
d453ad8eaa36fe67bf5c7781bf18cee0e863ca60 | 1,387 | cpp | C++ | src/third_party/angle/src/libANGLE/renderer/vulkan/FenceNVVk.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 6 | 2021-07-05T16:09:39.000Z | 2022-03-06T22:44:42.000Z | src/third_party/angle/src/libANGLE/renderer/vulkan/FenceNVVk.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | 7 | 2022-03-15T13:25:39.000Z | 2022-03-15T13:25:44.000Z | src/third_party/angle/src/libANGLE/renderer/vulkan/FenceNVVk.cpp | rhencke/engine | 1016db292c4e73374a0a11536b18303c9522a224 | [
"BSD-3-Clause"
] | null | null | null | //
// Copyright 2016 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// FenceNVVk.cpp:
// Implements the class methods for FenceNVVk.
//
#include "libANGLE/renderer/vulkan/FenceNVVk.h"
#include "common/debug.h"
#include "libANGLE/Context.h"
#include "libANGLE/renderer/vulkan/ContextVk.h"
#include "libANGLE/renderer/vulkan/vk_utils.h"
namespace rx
{
FenceNVVk::FenceNVVk() : FenceNVImpl() {}
FenceNVVk::~FenceNVVk() {}
void FenceNVVk::onDestroy(const gl::Context *context)
{
mFenceSync.releaseToRenderer(vk::GetImpl(context)->getRenderer());
}
angle::Result FenceNVVk::set(const gl::Context *context, GLenum condition)
{
ASSERT(condition == GL_ALL_COMPLETED_NV);
return mFenceSync.initialize(vk::GetImpl(context));
}
angle::Result FenceNVVk::test(const gl::Context *context, GLboolean *outFinished)
{
bool signaled = false;
ANGLE_TRY(mFenceSync.getStatus(vk::GetImpl(context), &signaled));
ASSERT(outFinished);
*outFinished = signaled ? GL_TRUE : GL_FALSE;
return angle::Result::Continue;
}
angle::Result FenceNVVk::finish(const gl::Context *context)
{
VkResult outResult;
ContextVk *contextVk = vk::GetImpl(context);
return mFenceSync.clientWait(contextVk, contextVk, true, UINT64_MAX, &outResult);
}
} // namespace rx
| 26.169811 | 85 | 0.729632 | rhencke |
d45532baa763a37b78fe4ce88d348bba9f8e259f | 4,065 | cpp | C++ | src/projections/cass.cpp | mlptownsend/PROJ | 4920c22637d05cd7aa0aecc6de69736dd4c6845b | [
"MIT"
] | 653 | 2015-03-27T10:12:52.000Z | 2019-06-03T02:00:49.000Z | src/projections/cass.cpp | mlptownsend/PROJ | 4920c22637d05cd7aa0aecc6de69736dd4c6845b | [
"MIT"
] | 987 | 2019-06-05T11:42:40.000Z | 2022-03-31T20:35:18.000Z | src/projections/cass.cpp | mlptownsend/PROJ | 4920c22637d05cd7aa0aecc6de69736dd4c6845b | [
"MIT"
] | 360 | 2019-06-20T23:50:36.000Z | 2022-03-31T11:47:00.000Z | #define PJ_LIB__
#include <errno.h>
#include <math.h>
#include "proj.h"
#include "proj_internal.h"
PROJ_HEAD(cass, "Cassini") "\n\tCyl, Sph&Ell";
# define C1 .16666666666666666666
# define C2 .00833333333333333333
# define C3 .04166666666666666666
# define C4 .33333333333333333333
# define C5 .06666666666666666666
namespace { // anonymous namespace
struct cass_data {
double *en;
double m0;
bool hyperbolic;
};
} // anonymous namespace
static PJ_XY cass_e_forward (PJ_LP lp, PJ *P) { /* Ellipsoidal, forward */
PJ_XY xy = {0.0, 0.0};
struct cass_data *Q = static_cast<struct cass_data*>(P->opaque);
const double sinphi = sin (lp.phi);
const double cosphi = cos (lp.phi);
const double M = pj_mlfn (lp.phi, sinphi, cosphi, Q->en);
const double nu_square = 1./(1. - P->es * sinphi*sinphi);
const double nu = sqrt(nu_square);
const double tanphi = tan(lp.phi);
const double T = tanphi * tanphi;
const double A = lp.lam * cosphi;
const double C = P->es * (cosphi * cosphi) / (1 - P->es);
const double A2 = A * A;
xy.x = nu * A * (1. - A2 * T *
(C1 - (8. - T + 8. * C) * A2 * C2));
xy.y = M - Q->m0 + nu * tanphi * A2 *
(.5 + (5. - T + 6. * C) * A2 * C3);
if( Q->hyperbolic )
{
const double rho = nu_square * (1. - P->es) * nu;
xy.y -= xy.y * xy.y * xy.y / (6 * rho * nu);
}
return xy;
}
static PJ_XY cass_s_forward (PJ_LP lp, PJ *P) { /* Spheroidal, forward */
PJ_XY xy = {0.0, 0.0};
xy.x = asin (cos (lp.phi) * sin (lp.lam));
xy.y = atan2 (tan (lp.phi), cos (lp.lam)) - P->phi0;
return xy;
}
static PJ_LP cass_e_inverse (PJ_XY xy, PJ *P) { /* Ellipsoidal, inverse */
PJ_LP lp = {0.0, 0.0};
struct cass_data *Q = static_cast<struct cass_data*>(P->opaque);
const double phi1 = pj_inv_mlfn (P->ctx, Q->m0 + xy.y, P->es, Q->en);
const double tanphi1 = tan (phi1);
const double T1 = tanphi1*tanphi1;
const double sinphi1 = sin (phi1);
const double nu1_square = 1. / (1. - P->es * sinphi1 * sinphi1);
const double nu1 = sqrt (nu1_square);
const double rho1 = nu1_square * (1. - P->es) * nu1;
const double D = xy.x / nu1;
const double D2 = D * D;
lp.phi = phi1 - (nu1 * tanphi1 / rho1) * D2 *
(.5 - (1. + 3. * T1) * D2 * C3);
lp.lam = D * (1. + T1 * D2 *
(-C4 + (1. + 3. * T1) * D2 * C5)) / cos (phi1);
if( Q->hyperbolic )
{
// EPSG guidance note 7-2 suggests a custom approximation for the
// 'Vanua Levu 1915 / Vanua Levu Grid' case, but better use the
// generic inversion method
lp = pj_generic_inverse_2d(xy, P, lp);
}
return lp;
}
static PJ_LP cass_s_inverse (PJ_XY xy, PJ *P) { /* Spheroidal, inverse */
PJ_LP lp = {0.0,0.0};
double dd;
lp.phi = asin(sin(dd = xy.y + P->phi0) * cos(xy.x));
lp.lam = atan2(tan(xy.x), cos(dd));
return lp;
}
static PJ *destructor (PJ *P, int errlev) { /* Destructor */
if (nullptr==P)
return nullptr;
if (nullptr==P->opaque)
return pj_default_destructor (P, errlev);
free (static_cast<struct cass_data*>(P->opaque)->en);
return pj_default_destructor (P, errlev);
}
PJ *PROJECTION(cass) {
/* Spheroidal? */
if (0==P->es) {
P->inv = cass_s_inverse;
P->fwd = cass_s_forward;
return P;
}
/* otherwise it's ellipsoidal */
auto Q = static_cast<struct cass_data*>(calloc (1, sizeof (struct cass_data)));
P->opaque = Q;
if (nullptr==P->opaque)
return pj_default_destructor (P, PROJ_ERR_OTHER /*ENOMEM*/);
P->destructor = destructor;
Q->en = pj_enfn (P->es);
if (nullptr==Q->en)
return pj_default_destructor (P, PROJ_ERR_OTHER /*ENOMEM*/);
Q->m0 = pj_mlfn (P->phi0, sin (P->phi0), cos (P->phi0), Q->en);
if (pj_param_exists(P->params, "hyperbolic"))
Q->hyperbolic = true;
P->inv = cass_e_inverse;
P->fwd = cass_e_forward;
return P;
}
| 27.842466 | 83 | 0.568512 | mlptownsend |
d4567ccd5f10992e55fca02a409dee0c28290648 | 1,810 | hpp | C++ | zen/fs.hpp | ZenLibraries/ZenLibraries | ae189b5080c75412cbd4f33cf6cfb51e15f6ee66 | [
"Apache-2.0"
] | null | null | null | zen/fs.hpp | ZenLibraries/ZenLibraries | ae189b5080c75412cbd4f33cf6cfb51e15f6ee66 | [
"Apache-2.0"
] | 2 | 2020-02-06T17:01:39.000Z | 2020-02-12T17:50:14.000Z | zen/fs.hpp | ZenLibraries/ZenLibraries | ae189b5080c75412cbd4f33cf6cfb51e15f6ee66 | [
"Apache-2.0"
] | null | null | null | #ifndef INFERA_FS_HPP
#define INFERA_FS_HPP
#include <string>
#include <memory>
#include "zen/config.h"
#include "zen/either.hpp"
ZEN_NAMESPACE_START
namespace fs {
template<typename T>
using Result = Either<int, T>;
using Path = std::string;
class File;
struct FileHandle;
struct FileContentsHandle;
/// @brief Represents the contents of an open file
///
/// This class efficiently shares resources with its clones so that the file
/// needs to be mapped into memory only once.
class FileContents {
friend class File;
std::shared_ptr<FileContentsHandle> handle;
inline FileContents(std::shared_ptr<FileContentsHandle> handle):
handle(handle) {}
public:
/// Create a freshly allocated std::string that will contain the entire
/// file contents.
std::string as_string() const;
/// Convert the contents of the associated file to a string
std::string_view as_string_view() const;
};
/// @brief A reference to a single regular file on the file system
///
/// This class cannot be directly constructed. Instead, you should obtain a
/// copy from a function such as `path::open`.
class File {
friend Result<File> file_from_path(Path p);
std::shared_ptr<FileHandle> handle;
inline File(std::shared_ptr<FileHandle> handle):
handle(handle) {}
public:
/// @brief Get a structure for querying the contents of this file
///
/// This method will try to use the operating system's best available APIs
/// to map the file into memory, falling back to a full scan if no
/// specialised functions exist.
Result<FileContents> get_contents();
};
Result<std::string> read_file(Path p);
Result<File> file_from_path(Path p);
}
ZEN_NAMESPACE_END
#endif // of #ifndef INFERA_FS_HPP
| 22.345679 | 78 | 0.696685 | ZenLibraries |
d45775f75e8b777c17239f491f4a0108e2691a40 | 1,161 | cc | C++ | no-tag-question/leetcode-7/solution.cc | hello-chenchen/leet-code-algorithms | 432132b8fa0a1f9575a9764743fbb79a01620102 | [
"WTFPL"
] | null | null | null | no-tag-question/leetcode-7/solution.cc | hello-chenchen/leet-code-algorithms | 432132b8fa0a1f9575a9764743fbb79a01620102 | [
"WTFPL"
] | null | null | null | no-tag-question/leetcode-7/solution.cc | hello-chenchen/leet-code-algorithms | 432132b8fa0a1f9575a9764743fbb79a01620102 | [
"WTFPL"
] | null | null | null | //LINK: https://leetcode.com/problems/reverse-integer/
//COMPILE: g++ solution.cc
//NOTICE: best solution
/***********************
while(x) {
res = res*10 + x%10;
x /= 10;
}
***********************/
#include <iostream>
class Solution {
public:
int reverse(int x) {
int* num = new int[1024];
int index = 0;
while(x <= -10 || x >= 10) {
num[index++] = x % 10;
x = x / 10;
}
long long y = x;
int count = index;
for(int i = 0; i < count; i++) {
y = y + num[i] * pow(10, index--);
}
return ((y < INT_MIN) || (y > INT_MAX)) ? 0 : y;
}
private:
inline long long pow(int x, int y) {
if(y == 0) {
return 1;
}
long long z = x;
for(int i = 1; i < y; i++) {
z = z * x;
}
return z;
}
};
int main(int argc, char const *argv[])
{
/* code */
Solution test;
int result = test.reverse(1534236469);
std::cout << result << std::endl;
return 0;
}
| 21.90566 | 60 | 0.386736 | hello-chenchen |
d4584c43dfd1ca98047edf85344f6e0615c9b90a | 3,530 | cpp | C++ | elenasrc2/ide/gtk-linux32/main.cpp | drkameleon/elena-lang | 8585e93a3bc0b19f8d60029ffbe01311d0b711a3 | [
"MIT"
] | 193 | 2015-07-03T22:23:27.000Z | 2022-03-15T18:56:02.000Z | elenasrc2/ide/gtk-linux32/main.cpp | drkameleon/elena-lang | 8585e93a3bc0b19f8d60029ffbe01311d0b711a3 | [
"MIT"
] | 531 | 2015-05-07T09:39:42.000Z | 2021-09-27T07:51:38.000Z | elenasrc2/ide/gtk-linux32/main.cpp | drkameleon/elena-lang | 8585e93a3bc0b19f8d60029ffbe01311d0b711a3 | [
"MIT"
] | 31 | 2015-09-30T13:07:36.000Z | 2021-10-15T13:08:04.000Z | //---------------------------------------------------------------------------
// E L E N A P r o j e c t: ELENA IDE
// Linux-GTK+ program entry
// (C)2005-2016, by Alexei Rakov
//---------------------------------------------------------------------------
#include "gtkide.h"
////#include "gtkideconst.h"
#include "../appwindow.h"
#include "../settings.h"
using namespace _GUI_;
//#pragma GCC diagnostic ignored "-Wwrite-strings"
// --- command line arguments ---
#define CMD_CONFIG_PATH _T("-c")
//// --- getBasePath --
//
//void getBasePath(_path_t* path)
//{
// pid_t pid = getpid();
//
// _ELENA_::String<char, 50> link;
//
// link.copy("/proc/");
// link.appendInt(pid);
// link.append("/exe");
//
// char proc[512];
// int ch = readlink(link, proc, 512);
// if (ch != -1) {
// proc[ch] = 0;
// int index = _ELENA_::StringHelper::findLast(proc, '/');
// _ELENA_::StringHelper::copy(path, proc, index);
// path[index] = 0;
// }
// else path[0] = 0;
//}
// --- loadCommandLine ---
inline void setOption(Model* model, const char* parameter)
{
if (parameter[0]!='-') {
if (_ELENA_::Path::checkExtension(parameter, "l")) {
model->defaultFiles.add(_ELENA_::StrFactory::clone(parameter));
}
else if (_ELENA_::Path::checkExtension(parameter, "prj")) {
model->defaultProject.copy(parameter);
}
}
}
void loadCommandLine(Model* model, int argc, char *argv[], _ELENA_::Path& configPath)
{
for (int i = 1 ; i < argc ; i++) {
if (_ELENA_::ident_t(argv[i]).compare(CMD_CONFIG_PATH, _ELENA_::getlength(CMD_CONFIG_PATH))) {
configPath.copy(argv[i] + _ELENA_::getlength(CMD_CONFIG_PATH));
}
else setOption(model, argv[i]);
}
}
// --- loadSettings ---
//void loadSettings(const _path_t* path, IDE& appWindow)
void loadSettings(_ELENA_::path_t path, Model* model, GTKIDEWindow* view)
{
_ELENA_::IniConfigFile file;
if (file.load(path, _ELENA_::feUTF8)) {
Settings::load(model, file);
// !! temporal
//view->appWindow.loadHistory(file, RECENTFILES_SECTION, RECENTRPOJECTS_SECTION);
//view->appWindow.reloadSettings();
}
}
// --- saveSettings ---
void saveSettings(_ELENA_::path_t path, Model* model, GTKIDEWindow* view)
{
_ELENA_::IniConfigFile file;
Settings::save(model, file);
// !! temporal
//view->appWindow.saveHistory(file, RECENTFILES_SECTION, RECENTRPOJECTS_SECTION);
file.save(path, _ELENA_::feUTF8);
}
// --- main ---
int main( int argc, char *argv[])
{
Model model;
// // get app path
// _path_t appPath[FILENAME_MAX];
// getBasePath(appPath);
//
// // get default path
// _path_t defPath[FILENAME_MAX];
// getcwd(defPath, FILENAME_MAX);
Gtk::Main kit(argc, argv);
// init paths & settings
// Paths::init(&model, appPath, defPath);
Settings::init(&model, "/usr/elena-lang/src/elena/src40", "/usr/lib/elena/lib40");
_ELENA_::Path configPath("/etc/elena");
configPath.combine(_T("ide.config"));
// load command line argiments
loadCommandLine(&model, argc, argv, configPath);
IDEController ide;
GTKIDEWindow view("IDE", &ide, &model);
// init IDE settings
loadSettings(configPath.str(), &model, &view);
// controller.assign(ide.getAppWindow());
// start IDE
ide.start(&view, &view, &model);
Gtk::Main::run(view);
saveSettings(configPath.str(), &model, &view);
// Font::releaseFontCache();
return 0;
}
| 25.035461 | 100 | 0.589518 | drkameleon |
d45afb1e36fa000207748883bfaab4f55bc9d774 | 1,914 | cpp | C++ | uva/tomo100/LongestPaths.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | 1 | 2016-02-11T21:28:22.000Z | 2016-02-11T21:28:22.000Z | uva/tomo100/LongestPaths.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | uva/tomo100/LongestPaths.cpp | civilian/competitive_programing | a6ae7ad0db84240667c1dd6231c51c586ba040c7 | [
"MIT"
] | null | null | null | //Uva 10000.
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <cmath>
#include <ctime>
#include <cctype>
#include <cassert>
#include <iostream>
#include <sstream>
#include <iomanip>
#include <string>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <list>
#include <set>
#include <map>
#include <bitset>
#include <algorithm>
#include <numeric>
#include <complex>
#define INF = 1000000000
#define D(x) cout << #x << " = " << (x) << endl;
#define REP(i,a,n) for(int i=(a); i<(int)(n); i++)
#define FOREACH(it,v) for(__typeof((v).begin()) it=(v).begin(); it!=(v).end(); ++it)
#define ALL(v) (v).begin(), (v).end()
using namespace std;
int V, E, u, v, w, AdjMatrix[110][110];
int s;
int main() {
ios_base::sync_with_stdio(false);
// freopen("LongestPaths.txt", "r", stdin);
// freopen("LongestPaths_out.txt", "w", stdout);
int V, s, caseId=0, mx,fin;//s start
int p,q;//pair places p q visitar q after p
while(scanf("%d", &V) && V){
REP(i,0,V){
REP(j,0,V){
AdjMatrix[i][j] = -1000000000;
}
AdjMatrix[i][i] = 0;
}
scanf("%d", &s);
s--;
while(scanf("%d %d", &p, &q) && (p || q) ){
p--; q--;
AdjMatrix[p][q]=1;
};
REP(k,0,V)
REP(i,0,V)
REP(j,0,V)
AdjMatrix[i][j] = max(AdjMatrix[i][j],
AdjMatrix[i][k] + AdjMatrix[k][j]);
mx=0;
fin=s;
REP(i,0, V){
// D(i);
// D(dist[i]);
if(AdjMatrix[s][i]>mx){
mx=AdjMatrix[s][i];
fin=i;
}
}
printf("Case %d: The longest path from %d has length %d, finishing at %d.\n\n",
++caseId, s+1, mx, fin+1);
}
}
| 22.255814 | 87 | 0.470742 | civilian |
d4612495d3b9894f639581507308a9614e594212 | 7,638 | cpp | C++ | SimilaritySearchCore/E2LSH/sources/QueryHashFunctions.cpp | HewlettPackard/SimilaritySearch | c0956f1b097a02e0f17f228816a18c14ef06856d | [
"BSD-3-Clause"
] | 5 | 2017-07-26T10:34:26.000Z | 2020-02-23T07:50:19.000Z | SimilaritySearchCore/E2LSH/sources/QueryHashFunctions.cpp | HewlettPackard/SimilaritySearch | c0956f1b097a02e0f17f228816a18c14ef06856d | [
"BSD-3-Clause"
] | 1 | 2019-01-08T03:44:29.000Z | 2019-01-19T18:35:21.000Z | SimilaritySearchCore/E2LSH/sources/QueryHashFunctions.cpp | HewlettPackard/SimilaritySearch | c0956f1b097a02e0f17f228816a18c14ef06856d | [
"BSD-3-Clause"
] | 2 | 2017-04-17T20:59:51.000Z | 2020-06-25T00:19:00.000Z | /** Similarity Search
“© Copyright 2017 Hewlett Packard Enterprise Development LP
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 of the copyright holder 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,
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.”
*/
/*
* QueryHashFunctions.cpp
*
* Created on: Mar 24, 2014
* Author: gomariat
*/
#include "QueryHashFunctions.h"
#include <random>
#include <cmath>
#include <iostream>
#include "IndexSearch.h"
#include "LSHManager.h"
#include "headers.h"
#include <unordered_set>
#include <vector>
#include <unistd.h>
#include <sys/time.h>
#include <armadillo>
#include <blaze/math/DynamicMatrix.h>
#include <blaze/math/DenseColumn.h>
#include <blaze/math/DynamicVector.h>
using blaze::DynamicMatrix;
using blaze::DynamicVector;
using namespace arma;
QueryHashFunctions::QueryHashFunctions() {
}
QueryHashFunctions::~QueryHashFunctions() {
// TODO Auto-generated destructor stub
cleanUp();
}
/**
* Init precomputed arrays for a given query length, L,K
* if the array is different of null, only clean the mmemory
* assuming that the querylengths are the same;
* parameters: lenght of each array
* return: false if the memory can not be alllocated
*/
bool QueryHashFunctions::init(int k, int L, int perTotal, int queryLenght){
kLength = k;
lLength = L;
perturbationNumber = perTotal;
queryLength = queryLenght;
long deltaLength = queryLength * perturbationNumber;
long aTimesXLength = lLength * kLength;
long aTimesDeltaLength = lLength * kLength * perturbationNumber;
if (deltaLength <0 || aTimesXLength<=0|| aTimesDeltaLength<0) {
std::cout << endl <<"Invalid range of parameters. Please verify L, K, or perturbation";
std::cout << endl <<"k:"<<k<<" L:"<<L<<" perTotal" << perTotal<<" queryLenght"<< queryLenght;
return false;
}
//delta.resize(deltaLength);
//aTimesDelta.resize(aTimesDeltaLength);
//aTimesX.resize(aTimesXLength);
return true;
}
/*
* Cleanup vectors and properties
*
*/
void QueryHashFunctions::cleanUp(){
//delta.resize(0);
//aTimesDelta.resize(0);
//aTimesX.resize(0);
kLength = 0;
lLength = 0;
perturbationNumber = 0;
queryLength = 0;
}
/**
* Compute precomputed vectors in order to compute g(v) = (a*x +b)/w, where W=c/R
* delta: store perturbations of the query
* atimesx:compute the a*x, where x is the points int the query
* atimesDelta: compute the a*delta, where delta is rand/sqrt(sum(x))
*/
bool QueryHashFunctions::computeVectors(vector<RealT>& query, int k, int L, int totalPerturbations, LSHFunctionT **lshR0Functions, DynamicMatrix<RealT> &a ) {
if (!init(k,L,totalPerturbations,query.size())) {
std:cout<<"Invalid memory allocation for vectors";
return false;
}
// the first column is for query point
DynamicVector<RealT> query_point(queryLength, query.data());
// Other columns for perturbation points
DynamicMatrix<RealT> query_pert(queryLength,1+totalPerturbations);
column(query_pert,0) = query_point;
// normalize the perturbation points
for (int n=1; n<=perturbationNumber; n++) {
arma_rng::set_seed(45354*n+n*n);
Col<RealT> nn = normalise(randn<Col<RealT>>(queryLength));
DynamicVector<RealT> delta_vec(queryLength, nn.memptr());
column(query_pert, n) = delta_vec;
}
// for debugging
//cout << "a size=" << a.rows() << "," << a.columns() << endl;
//cout << "query_pert size=" << query_pert.rows() << "," << query_pert.columns() << endl;
aTimesXDelta = a*query_pert; // using blaze matrix multiplication
return true;
}
/**
* Computing buckets, h1 and h2 indexs for a L lenght and a query
* using precomputed vectors
* retruns the values in h1yL and h2byL
*/
void QueryHashFunctions::getIndex(int W, RealT rValue, Uns32T *h1byL, Uns32T *h2byL,LSHFunctionT **lshR0Functions,PUHashStructureT & uHash) {
Uns32T pointULSHVectors[kLength];
Uns32T h1;
Uns32T h2;
int pos1 = 0;
int pos2 = 0;
RealT accValue = 0;
int val=0;
for (int l=0; l<lLength; l++) {
pos1=l*kLength;
for(int i = 0; i < kLength; i++){
//compute hashes h(v)= (ax+b)/w;
pointULSHVectors[i] = (Uns32T)(FLOOR_INT32((aTimesXDelta(pos1+i,0)/rValue + lshR0Functions[l][i].b) /W ));
}
h1 = computeProductModDefaultPrime(uHash->mainHashA, pointULSHVectors, kLength);
h2 = computeProductModDefaultPrime(uHash->controlHash1, pointULSHVectors, kLength);
if (h1 > UH_PRIME_DEFAULT){
h1 = h1 - UH_PRIME_DEFAULT;
}
h1= h1%uHash->hashTableSize;
if (h2 > UH_PRIME_DEFAULT){
h2 = h2 - UH_PRIME_DEFAULT;
}
h1byL[l]=h1;
h2byL[l]=h2;
}
}
/**
* Computing buckets, h1 and h2 indexs for a L lenght and a iPerturbation of the query
* using precomputed vectors
* returns the values in h1yL and h2byL
*/
void QueryHashFunctions::getIndex(int W, RealT rValue, Uns32T *h1byL, Uns32T *h2byL,LSHFunctionT **lshR0Functions,PUHashStructureT & uHash, int iPerturbation) {
Uns32T pointULSHVectors[kLength];
Uns32T h1;
Uns32T h2;
int pos1 = 0;
int pos2 = 0;
RealT accValue = 0;
for ( int l = 0; l< lLength; l++) {
pos1 = l*kLength;
//pos2 = iPerturbation*lLength*kLength+ l*kLength;
for(int i = 0; i < kLength; i++) {
//compute hashes g(v)= (sum(ax)+b)/w;
// h(v)= floor(( aTimesX/R + aTimesDelta +b)/w);
pointULSHVectors[i] = (Uns32T)(FLOOR_INT32(((aTimesXDelta(pos1+i,0)/rValue)+aTimesXDelta(pos1+i,iPerturbation+1)+lshR0Functions[l][i].b ) / W ));
}
//sum(r'*a)mod prime
h1 =computeProductModDefaultPrime(uHash->mainHashA, pointULSHVectors, kLength);
h2= computeProductModDefaultPrime(uHash->controlHash1, pointULSHVectors, kLength);
if (h1 > UH_PRIME_DEFAULT){
h1 = h1 - UH_PRIME_DEFAULT;
}
h1= h1% uHash->hashTableSize;
if (h2 > UH_PRIME_DEFAULT){
h2 = h2 - UH_PRIME_DEFAULT;
}
h1byL[l]=h1;
h2byL[l]=h2;
}
}
/**
* compute sum(r*a) for getting h index
* h(a1, a2,.. ak)= (sum(r'*a mod prime) mod prime)
* by applying h-(2^32-5 instead of mod prime
* See manual E2LSH code page 13
*/
inline Uns32T QueryHashFunctions::computeProductModDefaultPrime(Uns32T *a, Uns32T *b, IntT size){
LongUns64T h = 0;
IntT i = 0;
for(IntT i = 0; i < size; i++){
h = h + (LongUns64T)a[i] * (LongUns64T)b[i];
h = (h & TWO_TO_32_MINUS_1) + 5 * (h >> 32);
if (h >= UH_PRIME_DEFAULT) {
h = h - UH_PRIME_DEFAULT;
}
CR_ASSERT(h < UH_PRIME_DEFAULT);
}
return h;
}
| 32.641026 | 205 | 0.709217 | HewlettPackard |
d461ddb37a62fcda475619f4568060c7c34c30d9 | 991 | cpp | C++ | test/unit/math/random/random_test.cpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 27 | 2018-08-02T04:28:23.000Z | 2021-07-08T02:14:20.000Z | test/unit/math/random/random_test.cpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 200 | 2018-08-02T18:19:03.000Z | 2022-03-16T21:28:41.000Z | test/unit/math/random/random_test.cpp | PMDee/DCA | a8196ec3c88d07944e0499ff00358ea3c830b329 | [
"BSD-3-Clause"
] | 22 | 2018-08-15T15:50:00.000Z | 2021-09-30T13:41:46.000Z | // Copyright (C) 2018 ETH Zurich
// Copyright (C) 2018 UT-Battelle, LLC
// All rights reserved.
//
// See LICENSE for terms of usage.
// See CITATION.md for citation guidelines, if DCA++ is used for scientific publications.
//
// Author: Urs R. Haehner (haehneru@itp.phys.ethz.ch)
//
// This file tests some general behaviour of the random number generators.
#include "dca/math/random/random.hpp"
#include <utility> // for std::move
#include <vector>
#include "gtest/gtest.h"
template <typename Generator>
class RandomTest : public ::testing::Test {};
using Generators = ::testing::Types<dca::math::random::StdRandomWrapper<std::mt19937_64>>;
TYPED_TEST_CASE(RandomTest, Generators);
TYPED_TEST(RandomTest, MoveConstruction) {
using RngType = TypeParam;
RngType rng_1(0, 1);
const int global_id = rng_1.getGlobalId();
const uint64_t seed = rng_1.getSeed();
RngType rng_2(std::move(rng_1));
EXPECT_EQ(global_id, rng_2.getGlobalId());
EXPECT_EQ(seed, rng_2.getSeed());
}
| 28.314286 | 90 | 0.727548 | PMDee |
d4623c6db8abceb4ff4c2dc9ad38fc9a619b8989 | 3,548 | hpp | C++ | Libraries/C++/CommonHelpers/v1.0/CommonHelpers/Details/boost_extract/vmd/not_equal.hpp | davidbrownell/Common_cpp_Helpers | 9e68c95873b5a4eff3a32b991d2c18dff176d6c9 | [
"BSL-1.0"
] | null | null | null | Libraries/C++/CommonHelpers/v1.0/CommonHelpers/Details/boost_extract/vmd/not_equal.hpp | davidbrownell/Common_cpp_Helpers | 9e68c95873b5a4eff3a32b991d2c18dff176d6c9 | [
"BSL-1.0"
] | null | null | null | Libraries/C++/CommonHelpers/v1.0/CommonHelpers/Details/boost_extract/vmd/not_equal.hpp | davidbrownell/Common_cpp_Helpers | 9e68c95873b5a4eff3a32b991d2c18dff176d6c9 | [
"BSL-1.0"
] | null | null | null |
// (C) Copyright Edward Diener 2011-2015
// Use, modification and distribution are subject to 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).
#if !defined(BOOST_VMD_NOT_EQUAL_HPP)
#define BOOST_VMD_NOT_EQUAL_HPP
#include "detail/setup.hpp"
#if BOOST_PP_VARIADICS
#include "../preprocessor/logical/compl.hpp"
#include "equal.hpp"
/*
The succeeding comments in this file are in doxygen format.
*/
/** \file
*/
/** \def BOOST_VMD_NOT_EQUAL(sequence,...)
\brief Tests any two sequences for inequality.
sequence = First sequence.
... = variadic parameters, maximum of 2.
The first variadic parameter is required and is the second sequence to test.
The optional second variadic parameter is a VMD type as a filter.
The macro tests any two sequences for inequality. For sequences to be unequal
either the VMD types of each sequence must be unequal or the individual elements of the
sequence must be unequal.
The single optional parameter is a filter. The filter is a VMD type which specifies
that both sequences to test must be of that VMD type, as well as being equal to
each other, for the test to fail, else it succeeds.
returns = 1 upon success or 0 upon failure. Success means that the sequences are
unequal or, if the optional parameter is specified, that the sequences are
not of the optional VMD type; otherwise 0 is returned if the sequences
are equal.
The macro is implemented as the complement of BOOST_VMD_EQUAL, so that whenever
BOOST_VMD_EQUAL would return 1 the macro returns 0 and whenever BOOST_VMD_EQUAL
would return 0 the macro would return 1.
*/
#define BOOST_VMD_NOT_EQUAL(sequence,...) \
BOOST_PP_COMPL(BOOST_VMD_EQUAL(sequence,__VA_ARGS__)) \
/**/
/** \def BOOST_VMD_NOT_EQUAL_D(d,sequence,...)
\brief Tests any two sequences for inequality. Re-entrant version.
d = The next available BOOST_PP_WHILE iteration.
sequence = First sequence.
... = variadic parameters, maximum of 2.
The first variadic parameter is required and is the second sequence to test.
The optional second variadic parameter is a VMD type as a filter.
The macro tests any two sequences for inequality. For sequences to be unequal
either the VMD types of each sequence must be unequal or the individual elements of the
sequence must be unequal.
The single optional parameter is a filter. The filter is a VMD type which specifies
that both sequences to test must be of that VMD type, as well as being equal to
each other, for the test to fail, else it succeeds.
returns = 1 upon success or 0 upon failure. Success means that the sequences are
unequal or, if the optional parameter is specified, that the sequences are
not of the optional VMD type; otherwise 0 is returned if the sequences
are equal.
The macro is implemented as the complement of BOOST_VMD_EQUAL, so that whenever
BOOST_VMD_EQUAL would return 1 the macro returns 0 and whenever BOOST_VMD_EQUAL
would return 0 the macro would return 1.
*/
#define BOOST_VMD_NOT_EQUAL_D(d,sequence,...) \
BOOST_PP_COMPL(BOOST_VMD_EQUAL_D(d,sequence,__VA_ARGS__)) \
/**/
#endif /* BOOST_PP_VARIADICS */
#endif /* BOOST_VMD_NOT_EQUAL_HPP */
| 37.347368 | 92 | 0.701804 | davidbrownell |
d46248b1730e95316acbdf43671fc0bf3a690369 | 18,569 | cpp | C++ | external/bsd/atf/dist/tools/atf-run.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/atf/dist/tools/atf-run.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | external/bsd/atf/dist/tools/atf-run.cpp | calmsacibis995/minix | dfba95598f553b6560131d35a76658f1f8c9cf38 | [
"Unlicense"
] | null | null | null | //
// Automated Testing Framework (atf)
//
// Copyright (c) 2007 The NetBSD Foundation, Inc.
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 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.
//
// THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. 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 FOUNDATION 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.
//
extern "C" {
#include <sys/types.h>
#include <sys/param.h>
#include <sys/stat.h>
#include <sys/wait.h>
#include <unistd.h>
}
#include <algorithm>
#include <cassert>
#include <cerrno>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <map>
#include <string>
#include "application.hpp"
#include "atffile.hpp"
#include "config.hpp"
#include "config_file.hpp"
#include "env.hpp"
#include "exceptions.hpp"
#include "fs.hpp"
#include "parser.hpp"
#include "process.hpp"
#include "requirements.hpp"
#include "test-program.hpp"
#include "text.hpp"
namespace {
typedef std::map< std::string, std::string > vars_map;
} // anonymous namespace
class atf_run : public tools::application::app {
static const char* m_description;
vars_map m_cmdline_vars;
static vars_map::value_type parse_var(const std::string&);
void process_option(int, const char*);
std::string specific_args(void) const;
options_set specific_options(void) const;
void parse_vflag(const std::string&);
std::vector< std::string > conf_args(void) const;
size_t count_tps(std::vector< std::string >) const;
int run_test(const tools::fs::path&, tools::test_program::atf_tps_writer&,
const vars_map&);
int run_test_directory(const tools::fs::path&,
tools::test_program::atf_tps_writer&);
int run_test_program(const tools::fs::path&,
tools::test_program::atf_tps_writer&,
const vars_map&);
tools::test_program::test_case_result get_test_case_result(
const std::string&, const tools::process::status&,
const tools::fs::path&) const;
public:
atf_run(void);
int main(void);
};
static void
sanitize_gdb_env(void)
{
try {
tools::env::unset("TERM");
} catch (...) {
// Just swallow exceptions here; they cannot propagate into C, which
// is where this function is called from, and even if these exceptions
// appear they are benign.
}
}
static void
dump_stacktrace(const tools::fs::path& tp, const tools::process::status& s,
const tools::fs::path& workdir,
tools::test_program::atf_tps_writer& w)
{
assert(s.signaled() && s.coredump());
w.stderr_tc("Test program crashed; attempting to get stack trace");
const tools::fs::path corename = workdir /
(tp.leaf_name().substr(0, MAXCOMLEN) + ".core");
if (!tools::fs::exists(corename)) {
w.stderr_tc("Expected file " + corename.str() + " not found");
return;
}
const tools::fs::path gdb(GDB);
const tools::fs::path gdbout = workdir / "gdb.out";
const tools::process::argv_array args(gdb.leaf_name().c_str(), "-batch",
"-q", "-ex", "bt", tp.c_str(),
corename.c_str(), NULL);
tools::process::status status = tools::process::exec(
gdb, args,
tools::process::stream_redirect_path(gdbout),
tools::process::stream_redirect_path(tools::fs::path("/dev/null")),
sanitize_gdb_env);
if (!status.exited() || status.exitstatus() != EXIT_SUCCESS) {
w.stderr_tc("Execution of " GDB " failed");
return;
}
std::ifstream input(gdbout.c_str());
if (input) {
std::string line;
while (std::getline(input, line).good())
w.stderr_tc(line);
input.close();
}
w.stderr_tc("Stack trace complete");
}
const char* atf_run::m_description =
"atf-run is a tool that runs tests programs and collects their "
"results.";
atf_run::atf_run(void) :
app(m_description, "atf-run(1)", "atf(7)")
{
}
void
atf_run::process_option(int ch, const char* arg)
{
switch (ch) {
case 'v':
parse_vflag(arg);
break;
default:
std::abort();
}
}
std::string
atf_run::specific_args(void)
const
{
return "[test-program1 .. test-programN]";
}
atf_run::options_set
atf_run::specific_options(void)
const
{
using tools::application::option;
options_set opts;
opts.insert(option('v', "var=value", "Sets the configuration variable "
"`var' to `value'; overrides "
"values in configuration files"));
return opts;
}
void
atf_run::parse_vflag(const std::string& str)
{
if (str.empty())
throw std::runtime_error("-v requires a non-empty argument");
std::vector< std::string > ws = tools::text::split(str, "=");
if (ws.size() == 1 && str[str.length() - 1] == '=') {
m_cmdline_vars[ws[0]] = "";
} else {
if (ws.size() != 2)
throw std::runtime_error("-v requires an argument of the form "
"var=value");
m_cmdline_vars[ws[0]] = ws[1];
}
}
int
atf_run::run_test(const tools::fs::path& tp,
tools::test_program::atf_tps_writer& w,
const vars_map& config)
{
tools::fs::file_info fi(tp);
int errcode;
if (fi.get_type() == tools::fs::file_info::dir_type)
errcode = run_test_directory(tp, w);
else {
const vars_map effective_config =
tools::config_file::merge_configs(config, m_cmdline_vars);
errcode = run_test_program(tp, w, effective_config);
}
return errcode;
}
int
atf_run::run_test_directory(const tools::fs::path& tp,
tools::test_program::atf_tps_writer& w)
{
tools::atffile af = tools::read_atffile(tp / "Atffile");
vars_map test_suite_vars;
{
vars_map::const_iterator iter = af.props().find("test-suite");
assert(iter != af.props().end());
test_suite_vars = tools::config_file::read_config_files((*iter).second);
}
bool ok = true;
for (std::vector< std::string >::const_iterator iter = af.tps().begin();
iter != af.tps().end(); iter++) {
const bool result = run_test(tp / *iter, w,
tools::config_file::merge_configs(af.conf(), test_suite_vars));
ok &= (result == EXIT_SUCCESS);
}
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
tools::test_program::test_case_result
atf_run::get_test_case_result(const std::string& broken_reason,
const tools::process::status& s,
const tools::fs::path& resfile)
const
{
using tools::text::to_string;
using tools::test_program::read_test_case_result;
using tools::test_program::test_case_result;
if (!broken_reason.empty()) {
test_case_result tcr;
try {
tcr = read_test_case_result(resfile);
if (tcr.state() == "expected_timeout") {
return tcr;
} else {
return test_case_result("failed", -1, broken_reason);
}
} catch (const std::runtime_error&) {
return test_case_result("failed", -1, broken_reason);
}
}
if (s.exited()) {
test_case_result tcr;
try {
tcr = read_test_case_result(resfile);
} catch (const std::runtime_error& e) {
return test_case_result("failed", -1, "Test case exited "
"normally but failed to create the results file: " +
std::string(e.what()));
}
if (tcr.state() == "expected_death") {
return tcr;
} else if (tcr.state() == "expected_exit") {
if (tcr.value() == -1 || s.exitstatus() == tcr.value())
return tcr;
else
return test_case_result("failed", -1, "Test case was "
"expected to exit with a " + to_string(tcr.value()) +
" error code but returned " + to_string(s.exitstatus()));
} else if (tcr.state() == "expected_failure") {
if (s.exitstatus() == EXIT_SUCCESS)
return tcr;
else
return test_case_result("failed", -1, "Test case returned an "
"error in expected_failure mode but it should not have");
} else if (tcr.state() == "expected_signal") {
return test_case_result("failed", -1, "Test case exited cleanly "
"but was expected to receive a signal");
} else if (tcr.state() == "failed") {
if (s.exitstatus() == EXIT_SUCCESS)
return test_case_result("failed", -1, "Test case "
"exited successfully but reported failure");
else
return tcr;
} else if (tcr.state() == "passed") {
if (s.exitstatus() == EXIT_SUCCESS)
return tcr;
else
return test_case_result("failed", -1, "Test case exited as "
"passed but reported an error");
} else if (tcr.state() == "skipped") {
if (s.exitstatus() == EXIT_SUCCESS)
return tcr;
else
return test_case_result("failed", -1, "Test case exited as "
"skipped but reported an error");
}
} else if (s.signaled()) {
test_case_result tcr;
try {
tcr = read_test_case_result(resfile);
} catch (const std::runtime_error&) {
return test_case_result("failed", -1, "Test program received "
"signal " + tools::text::to_string(s.termsig()) +
(s.coredump() ? " (core dumped)" : ""));
}
if (tcr.state() == "expected_death") {
return tcr;
} else if (tcr.state() == "expected_signal") {
if (tcr.value() == -1 || s.termsig() == tcr.value())
return tcr;
else
return test_case_result("failed", -1, "Test case was "
"expected to exit due to a " + to_string(tcr.value()) +
" signal but got " + to_string(s.termsig()));
} else {
return test_case_result("failed", -1, "Test program received "
"signal " + tools::text::to_string(s.termsig()) +
(s.coredump() ? " (core dumped)" : "") + " and created a "
"bogus results file");
}
}
std::abort();
return test_case_result();
}
int
atf_run::run_test_program(const tools::fs::path& tp,
tools::test_program::atf_tps_writer& w,
const vars_map& config)
{
int errcode = EXIT_SUCCESS;
tools::test_program::metadata md;
try {
md = tools::test_program::get_metadata(tp, config);
} catch (const tools::parser::format_error& e) {
w.start_tp(tp.str(), 0);
w.end_tp("Invalid format for test case list: " + std::string(e.what()));
return EXIT_FAILURE;
} catch (const tools::parser::parse_errors& e) {
const std::string reason = tools::text::join(e, "; ");
w.start_tp(tp.str(), 0);
w.end_tp("Invalid format for test case list: " + reason);
return EXIT_FAILURE;
}
tools::fs::temp_dir resdir(
tools::fs::path(tools::config::get("atf_workdir")) / "atf-run.XXXXXX");
w.start_tp(tp.str(), md.test_cases.size());
if (md.test_cases.empty()) {
w.end_tp("Bogus test program: reported 0 test cases");
errcode = EXIT_FAILURE;
} else {
for (std::map< std::string, vars_map >::const_iterator iter
= md.test_cases.begin(); iter != md.test_cases.end(); iter++) {
const std::string& tcname = (*iter).first;
const vars_map& tcmd = (*iter).second;
w.start_tc(tcname);
try {
const std::string& reqfail = tools::check_requirements(
tcmd, config);
if (!reqfail.empty()) {
w.end_tc("skipped", reqfail);
continue;
}
} catch (const std::runtime_error& e) {
w.end_tc("failed", e.what());
errcode = EXIT_FAILURE;
continue;
}
const std::pair< int, int > user = tools::get_required_user(
tcmd, config);
tools::fs::path resfile = resdir.get_path() / "tcr";
assert(!tools::fs::exists(resfile));
try {
const bool has_cleanup = tools::text::to_bool(
(*tcmd.find("has.cleanup")).second);
tools::fs::temp_dir workdir(tools::fs::path(tools::config::get(
"atf_workdir")) / "atf-run.XXXXXX");
if (user.first != -1 && user.second != -1) {
if (::chown(workdir.get_path().c_str(), user.first,
user.second) == -1) {
throw tools::system_error("chown(" +
workdir.get_path().str() + ")", "chown(2) failed",
errno);
}
resfile = workdir.get_path() / "tcr";
}
std::pair< std::string, const tools::process::status > s =
tools::test_program::run_test_case(
tp, tcname, "body", tcmd, config,
resfile, workdir.get_path(), w);
if (s.second.signaled() && s.second.coredump())
dump_stacktrace(tp, s.second, workdir.get_path(), w);
if (has_cleanup)
(void)tools::test_program::run_test_case(
tp, tcname, "cleanup", tcmd,
config, resfile, workdir.get_path(), w);
// TODO: Force deletion of workdir.
tools::test_program::test_case_result tcr =
get_test_case_result(s.first, s.second, resfile);
w.end_tc(tcr.state(), tcr.reason());
if (tcr.state() == "failed")
errcode = EXIT_FAILURE;
} catch (...) {
if (tools::fs::exists(resfile))
tools::fs::remove(resfile);
throw;
}
if (tools::fs::exists(resfile))
tools::fs::remove(resfile);
}
w.end_tp("");
}
return errcode;
}
size_t
atf_run::count_tps(std::vector< std::string > tps)
const
{
size_t ntps = 0;
for (std::vector< std::string >::const_iterator iter = tps.begin();
iter != tps.end(); iter++) {
tools::fs::path tp(*iter);
tools::fs::file_info fi(tp);
if (fi.get_type() == tools::fs::file_info::dir_type) {
tools::atffile af = tools::read_atffile(tp / "Atffile");
std::vector< std::string > aux = af.tps();
for (std::vector< std::string >::iterator i2 = aux.begin();
i2 != aux.end(); i2++)
*i2 = (tp / *i2).str();
ntps += count_tps(aux);
} else
ntps++;
}
return ntps;
}
static
void
call_hook(const std::string& tool, const std::string& hook)
{
const tools::fs::path sh(tools::config::get("atf_shell"));
const tools::fs::path hooks =
tools::fs::path(tools::config::get("atf_pkgdatadir")) / (tool + ".hooks");
const tools::process::status s =
tools::process::exec(sh,
tools::process::argv_array(sh.c_str(), hooks.c_str(),
hook.c_str(), NULL),
tools::process::stream_inherit(),
tools::process::stream_inherit());
if (!s.exited() || s.exitstatus() != EXIT_SUCCESS)
throw std::runtime_error("Failed to run the '" + hook + "' hook "
"for '" + tool + "'");
}
int
atf_run::main(void)
{
tools::atffile af = tools::read_atffile(tools::fs::path("Atffile"));
std::vector< std::string > tps;
tps = af.tps();
if (m_argc >= 1) {
// TODO: Ensure that the given test names are listed in the
// Atffile. Take into account that the file can be using globs.
tps.clear();
for (int i = 0; i < m_argc; i++)
tps.push_back(m_argv[i]);
}
// Read configuration data for this test suite.
vars_map test_suite_vars;
{
vars_map::const_iterator iter = af.props().find("test-suite");
assert(iter != af.props().end());
test_suite_vars = tools::config_file::read_config_files((*iter).second);
}
tools::test_program::atf_tps_writer w(std::cout);
call_hook("atf-run", "info_start_hook");
w.ntps(count_tps(tps));
bool ok = true;
for (std::vector< std::string >::const_iterator iter = tps.begin();
iter != tps.end(); iter++) {
const bool result = run_test(tools::fs::path(*iter), w,
tools::config_file::merge_configs(af.conf(), test_suite_vars));
ok &= (result == EXIT_SUCCESS);
}
call_hook("atf-run", "info_end_hook");
return ok ? EXIT_SUCCESS : EXIT_FAILURE;
}
int
main(int argc, char* const* argv)
{
return atf_run().run(argc, argv);
}
| 33.277778 | 82 | 0.557919 | calmsacibis995 |
d465d01615e353378dec5d8f64839fdcc1b3010f | 2,233 | cpp | C++ | BZOJ/2595/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | BZOJ/2595/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | BZOJ/2595/code.cpp | sjj118/OI-Code | 964ea6e799d14010f305c7e4aee269d860a781f7 | [
"MIT"
] | null | null | null | #include<iostream>
#include<cstdio>
#include<queue>
#define maxn 11
#define inf 1e9
using namespace std;
const int dir[4][2]={{0,1},{0,-1},{1,0},{-1,0}};
int n,m,map[maxn][maxn],dp[1<<maxn][maxn][maxn],pre[1<<maxn][maxn][maxn],s[maxn][maxn],k;
int st[maxn][maxn];
queue<int> Q;int inq[maxn*maxn<<maxn];
inline void push(int x){if(!inq[x])Q.push(x);inq[x]=1;}
inline void pop(){inq[Q.front()]=0;Q.pop();}
inline int h(int sta,int x,int y){return sta*maxn*maxn+x*maxn+y;}
inline void fh(int h,int&sta,int&x,int&y){y=h%maxn;h/=maxn;x=h%maxn;h/=maxn;sta=h;}
inline bool avail(int x,int y){return x>=1&&x<=n&&y>=1&&y<=m;}
inline bool updata(int&x,int y){if(y<x){x=y;return 1;}return 0;}
void spfa(){
while(Q.size()){
int sta,x,y;fh(Q.front(),sta,x,y);pop();
for(int i=0;i<4;++i)if(avail(x+dir[i][0],y+dir[i][1])/*&&((sta|s[x+dir[i][0]][y+dir[i][1]])==sta)*/){
if(updata(dp[sta][x+dir[i][0]][y+dir[i][1]],dp[sta][x][y]+map[x+dir[i][0]][y+dir[i][1]]))push(h(sta,x+dir[i][0],y+dir[i][1])),pre[sta][x+dir[i][0]][y+dir[i][1]]=h(sta,x,y);
}
}
}
void go(int p){
if(!p)return;
int sta,x,y;fh(p,sta,x,y);
if(!st[x][y])st[x][y]=-1;
go(pre[sta][x][y]);
if(pre[sta][x][y]/maxn/maxn!=sta)go(pre[sta^(pre[sta][x][y]/maxn/maxn)][x][y]);
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1;i<=n;++i)for(int j=1;j<=m;++j){scanf("%d",&map[i][j]);if(!map[i][j])st[i][j]=1<<k,s[i][j]=++k;}
for(int x=0;x<maxn;++x)for(int y=0;y<maxn;++y)dp[0][x][y]=map[x][y];
for(int i=0;i<1<<maxn;++i){
for(int x=1;x<=n;++x)for(int y=1;y<=m;++y){
dp[i][x][y]=inf;
if(st[x][y]==i)dp[i][x][y]=0;
}
}
for(int sta=1;sta<1<<k;++sta){
for(int x=1;x<=n;++x){
for(int y=1;y<=m;++y){
for(int j=(sta-1)&sta;j;j=(j-1)&sta)if(updata(dp[sta][x][y],dp[j][x][y]+dp[sta^j][x][y]-map[x][y]))pre[sta][x][y]=h(j,x,y);
if(dp[sta][x][y]<inf)push(h(sta,x,y));
}
}
spfa();
}
int ans=inf,p;
for(int x=1;x<=n;++x)for(int y=1;y<=m;++y)ans=min(ans,dp[(1<<k)-1][x][y]);
printf("%d\n",ans);
for(int i=1;i<=n;++i)for(int j=1;j<=m;++j)if(st[i][j]){p=h((1<<k)-1,i,j);}
go(p);
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
if(st[i][j]==-1)printf("o");
else if(st[i][j]==0)printf("_");
else printf("x");
}
printf("\n");
}
return 0;
}
| 32.362319 | 175 | 0.537394 | sjj118 |
d466b87cccf2b14bf01337c02a67570add857f3e | 23,219 | cpp | C++ | fuego-0.4/go/test/GoBoardUtilTest.cpp | MisterTea/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 85 | 2015-02-08T20:36:17.000Z | 2021-11-14T20:38:31.000Z | fuego-0.4/go/test/GoBoardUtilTest.cpp | afcarl/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 9 | 2015-01-28T16:33:19.000Z | 2020-04-12T23:03:28.000Z | fuego-0.4/go/test/GoBoardUtilTest.cpp | afcarl/HyperNEAT | 516fef725621991ee709eb9b4afe40e0ce82640d | [
"BSD-3-Clause"
] | 27 | 2015-01-28T16:33:30.000Z | 2021-08-12T05:04:39.000Z | //----------------------------------------------------------------------------
/** @file GoBoardUtilTest.cpp
Unit tests for GoBoard.
*/
//----------------------------------------------------------------------------
#include "SgSystem.h"
#include "GoBoardUtil.h"
#include <boost/test/auto_unit_test.hpp>
#include <boost/test/floating_point_comparison.hpp>
#include "GoSetup.h"
#include "GoSetupUtil.h"
#include "SgPointSet.h"
using namespace std;
using namespace GoBoardUtil;
using SgPointUtil::Pt;
//----------------------------------------------------------------------------
namespace {
//----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(GoBlockIteratorTest)
{
GoSetup setup;
setup.AddBlack(Pt(1, 1));
setup.AddBlack(Pt(1, 2));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(2, 2));
setup.AddBlack(Pt(3, 7));
setup.AddWhite(Pt(19, 19));
GoBoard bd(19, setup);
GoBlockIterator it(bd);
BOOST_CHECK_EQUAL(*it, Pt(1, 1));
BOOST_CHECK(it);
++it;
BOOST_CHECK_EQUAL(*it, Pt(2, 1));
BOOST_CHECK(it);
++it;
BOOST_CHECK_EQUAL(*it, Pt(3, 7));
BOOST_CHECK(it);
++it;
BOOST_CHECK_EQUAL(*it, Pt(19, 19));
BOOST_CHECK(it);
++it;
BOOST_CHECK(! it);
}
//----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_AddWall)
{
GoBoard bd(19);
AddWall(bd, SG_BLACK, Pt(3,3), 10, SG_NS);
BOOST_CHECK_EQUAL(bd.TotalNumStones(SG_BLACK), 10);
BOOST_CHECK_EQUAL(bd.TotalNumStones(SG_WHITE), 0);
AddWall(bd, SG_WHITE, Pt(4,3), 5, SG_NS + SG_WE);
BOOST_CHECK_EQUAL(bd.TotalNumStones(SG_BLACK), 10);
BOOST_CHECK_EQUAL(bd.TotalNumStones(SG_WHITE), 5);
AddWall(bd, SG_WHITE, Pt(5,3), 4, SG_NS + 2 * SG_WE);
BOOST_CHECK_EQUAL(bd.TotalNumStones(SG_BLACK), 10);
BOOST_CHECK_EQUAL(bd.TotalNumStones(SG_WHITE), 9);
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_AdjacentBlocks_1)
{
// . . . . .
// @ O O @ .
// O O . @ .
GoSetup setup;
setup.AddBlack(Pt(1, 2));
setup.AddBlack(Pt(4, 1));
setup.AddBlack(Pt(4, 2));
setup.AddWhite(Pt(1, 1));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(2, 2));
setup.AddWhite(Pt(3, 2));
GoBoard bd(19, setup);
SgVector<SgPoint> blocks;
AdjacentBlocks(bd, Pt(2, 1), 10, &blocks);
BOOST_CHECK_EQUAL(blocks.Length(), 2);
BOOST_CHECK(blocks.Contains(Pt(1, 2)));
BOOST_CHECK(blocks.Contains(Pt(4, 1)));
AdjacentBlocks(bd, Pt(2, 1), 1, &blocks);
BOOST_CHECK_EQUAL(blocks.Length(), 1);
BOOST_CHECK(blocks.Contains(Pt(1, 2)));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_AdjacentBlocks_2)
{
GoSetup setup;
// . . . . .
// @ O O @ .
// O O @ @ .
setup.AddWhite(Pt(1, 1));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(2, 2));
setup.AddWhite(Pt(3, 2));
setup.AddBlack(Pt(1, 2));
setup.AddBlack(Pt(3, 1));
setup.AddBlack(Pt(4, 1));
setup.AddBlack(Pt(4, 2));
GoBoard bd(19, setup);
SgVector<SgPoint> blocks;
AdjacentBlocks(bd, Pt(2, 1), 10, &blocks);
BOOST_CHECK_EQUAL(blocks.Length(), 2);
BOOST_CHECK(blocks.Contains(Pt(1, 2)));
BOOST_CHECK(blocks.Contains(Pt(3, 1)));
AdjacentBlocks(bd, Pt(2, 1), 1, &blocks);
BOOST_CHECK_EQUAL(blocks.Length(), 1);
BOOST_CHECK(blocks.Contains(Pt(1, 2)));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_DiagonalsOfColor)
{
GoSetup setup;
setup.AddBlack(Pt(1, 1));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(1, 2));
GoBoard bd(19, setup);
SgVector<SgPoint> diags;
DiagonalsOfColor(bd, Pt(1, 1), SG_BLACK, &diags);
BOOST_CHECK_EQUAL(diags.Length(), 0);
DiagonalsOfColor(bd, Pt(1, 1), SG_WHITE, &diags);
BOOST_CHECK_EQUAL(diags.Length(), 0);
DiagonalsOfColor(bd, Pt(1, 1), SG_EMPTY, &diags);
BOOST_CHECK_EQUAL(diags.Length(), 1);
BOOST_CHECK(diags.Contains(Pt(2, 2)));
DiagonalsOfColor(bd, Pt(2, 2), SG_BLACK, &diags);
BOOST_CHECK_EQUAL(diags.Length(), 1);
BOOST_CHECK(diags.Contains(Pt(1, 1)));
DiagonalsOfColor(bd, Pt(2, 2), SG_WHITE, &diags);
BOOST_CHECK_EQUAL(diags.Length(), 0);
DiagonalsOfColor(bd, Pt(2, 2), SG_EMPTY, &diags);
BOOST_CHECK_EQUAL(diags.Length(), 3);
BOOST_CHECK(diags.Contains(Pt(3, 1)));
BOOST_CHECK(diags.Contains(Pt(1, 3)));
BOOST_CHECK(diags.Contains(Pt(3, 3)));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_HasAdjacentBlocks)
{
GoSetup setup;
setup.AddBlack(Pt(1, 1));
setup.AddBlack(Pt(2, 1));
GoBoard bd(19, setup);
BOOST_CHECK(! HasAdjacentBlocks(bd, Pt(2, 1), 2));
setup.AddWhite(Pt(1, 2));
bd.Init(19, setup);
BOOST_CHECK(! HasAdjacentBlocks(bd, Pt(2, 1), 1));
BOOST_CHECK(HasAdjacentBlocks(bd, Pt(2, 1), 2));
BOOST_CHECK(HasAdjacentBlocks(bd, Pt(2, 1), 3));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_IsSimpleChain_1)
{
std::string s("X...XOOX.\n"
".X..X..X.\n"
"....XOOX.\n"
".........\n"
"..X...X..\n"
"O.OX.XO.O\n"
"........O\n"
"..O...OOO\n"
".........");
int boardSize;
GoSetup setup = GoSetupUtil::CreateSetupFromString(s, boardSize);
GoBoard bd(boardSize, setup);
SgPoint other;
BOOST_CHECK(IsSimpleChain(bd, Pt(1, 9), other));
BOOST_CHECK_EQUAL(Pt(2, 8), other);
BOOST_CHECK(IsSimpleChain(bd, Pt(6, 9), other));
BOOST_CHECK_EQUAL(Pt(6, 7), other);
BOOST_CHECK(! IsSimpleChain(bd, Pt(3, 4), other));
BOOST_CHECK(IsSimpleChain(bd, Pt(7, 4), other));
BOOST_CHECK_EQUAL(Pt(7, 2), other);
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_IsSnapback_1)
{
GoSetup setup;
setup.AddBlack(Pt(2, 2));
setup.AddBlack(Pt(3, 1));
setup.AddWhite(Pt(1, 2));
setup.AddWhite(Pt(2, 1));
GoBoard bd(19, setup);
BOOST_CHECK(! IsSnapback(bd, Pt(2, 1)));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_IsSnapback_2)
{
GoSetup setup;
setup.AddBlack(Pt(3, 2));
setup.AddBlack(Pt(4, 1));
setup.AddBlack(Pt(1, 1));
setup.AddWhite(Pt(1, 2));
setup.AddWhite(Pt(2, 2));
setup.AddWhite(Pt(3, 1));
GoBoard bd(19, setup);
BOOST_CHECK(IsSnapback(bd, Pt(3, 1)));
}
/** Test GoBoardUtil::NeighborsOfColor */
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_NeighborsOfColor)
{
GoSetup setup;
setup.AddBlack(Pt(1, 1));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(1, 2));
GoBoard bd(19, setup);
SgSList<SgPoint,4> neighbors;
neighbors = NeighborsOfColor(bd, Pt(1, 1), SG_BLACK);
BOOST_CHECK_EQUAL(neighbors.Length(), 0);
neighbors = NeighborsOfColor(bd, Pt(1, 1), SG_WHITE);
BOOST_CHECK_EQUAL(neighbors.Length(), 2);
BOOST_CHECK(neighbors.Contains(Pt(2, 1)));
BOOST_CHECK(neighbors.Contains(Pt(1, 2)));
neighbors = NeighborsOfColor(bd, Pt(1, 1), SG_EMPTY);
BOOST_CHECK_EQUAL(neighbors.Length(), 0);
neighbors = NeighborsOfColor(bd, Pt(2, 2), SG_BLACK);
BOOST_CHECK_EQUAL(neighbors.Length(), 0);
neighbors = NeighborsOfColor(bd, Pt(2, 2), SG_WHITE);
BOOST_CHECK_EQUAL(neighbors.Length(), 2);
BOOST_CHECK(neighbors.Contains(Pt(2, 1)));
BOOST_CHECK(neighbors.Contains(Pt(1, 2)));
neighbors = NeighborsOfColor(bd, Pt(2, 2), SG_EMPTY);
BOOST_CHECK_EQUAL(neighbors.Length(), 2);
BOOST_CHECK(neighbors.Contains(Pt(3, 2)));
BOOST_CHECK(neighbors.Contains(Pt(2, 3)));
}
/** Test GoBoardUtil::NeighborsOfColor (SgVector version) */
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_NeighborsOfColor_SgVector)
{
GoSetup setup;
setup.AddBlack(Pt(1, 1));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(1, 2));
GoBoard bd(19, setup);
SgVector<SgPoint> neighbors;
NeighborsOfColor(bd, Pt(1, 1), SG_BLACK, &neighbors);
BOOST_CHECK_EQUAL(neighbors.Length(), 0);
NeighborsOfColor(bd, Pt(1, 1), SG_WHITE, &neighbors);
BOOST_CHECK_EQUAL(neighbors.Length(), 2);
BOOST_CHECK(neighbors.Contains(Pt(2, 1)));
BOOST_CHECK(neighbors.Contains(Pt(1, 2)));
NeighborsOfColor(bd, Pt(1, 1), SG_EMPTY, &neighbors);
BOOST_CHECK_EQUAL(neighbors.Length(), 0);
NeighborsOfColor(bd, Pt(2, 2), SG_BLACK, &neighbors);
BOOST_CHECK_EQUAL(neighbors.Length(), 0);
NeighborsOfColor(bd, Pt(2, 2), SG_WHITE, &neighbors);
BOOST_CHECK_EQUAL(neighbors.Length(), 2);
BOOST_CHECK(neighbors.Contains(Pt(2, 1)));
BOOST_CHECK(neighbors.Contains(Pt(1, 2)));
NeighborsOfColor(bd, Pt(2, 2), SG_EMPTY, &neighbors);
BOOST_CHECK_EQUAL(neighbors.Length(), 2);
BOOST_CHECK(neighbors.Contains(Pt(3, 2)));
BOOST_CHECK(neighbors.Contains(Pt(2, 3)));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_GetDirtyRegion)
{
SgRect s1, s2, l1, l2;
GoBoard bd(9);
// ..XO
// .XOX
// ..X.
// ....
// ....
s1 = GetDirtyRegion(bd, Pt(3,3), SG_BLACK, false, true);
l1 = GetDirtyRegion(bd, Pt(3,3), SG_BLACK, true, true);
bd.Play(Pt(3,3), SG_BLACK);
s2 = GetDirtyRegion(bd, Pt(3,3), SG_BLACK, false, false);
l2 = GetDirtyRegion(bd, Pt(3,3), SG_BLACK, true, false);
BOOST_CHECK_EQUAL(s1, SgRect(3,3,3,3));
BOOST_CHECK_EQUAL(l1, SgRect(3,3,3,3));
BOOST_CHECK_EQUAL(s2, SgRect(3,3,3,3));
BOOST_CHECK_EQUAL(l2, SgRect(3,3,3,3));
s1 = GetDirtyRegion(bd, Pt(3,4), SG_WHITE, false, true);
l1 = GetDirtyRegion(bd, Pt(3,4), SG_WHITE, true, true);
bd.Play(Pt(3,4), SG_WHITE);
s2 = GetDirtyRegion(bd, Pt(3,4), SG_WHITE, false, false);
l2 = GetDirtyRegion(bd, Pt(3,4), SG_WHITE, true, false);
BOOST_CHECK_EQUAL(s1, SgRect(3,3,4,4));
BOOST_CHECK_EQUAL(l1, SgRect(3,3,3,4));
BOOST_CHECK_EQUAL(s2, SgRect(3,3,4,4));
BOOST_CHECK_EQUAL(l2, SgRect(3,3,3,4));
s1 = GetDirtyRegion(bd, Pt(4,4), SG_BLACK, false, true);
l1 = GetDirtyRegion(bd, Pt(4,4), SG_BLACK, true, true);
bd.Play(Pt(4,4), SG_BLACK);
s2 = GetDirtyRegion(bd, Pt(4,4), SG_BLACK, false, false);
l2 = GetDirtyRegion(bd, Pt(4,4), SG_BLACK, true, false);
BOOST_CHECK_EQUAL(s1, SgRect(4,4,4,4));
BOOST_CHECK_EQUAL(l1, SgRect(3,4,4,4));
BOOST_CHECK_EQUAL(s2, SgRect(4,4,4,4));
BOOST_CHECK_EQUAL(l2, SgRect(3,4,4,4));
s1 = GetDirtyRegion(bd, Pt(4,5), SG_WHITE, false, true);
l1 = GetDirtyRegion(bd, Pt(4,5), SG_WHITE, true, true);
bd.Play(Pt(4,5), SG_WHITE);
s2 = GetDirtyRegion(bd, Pt(4,5), SG_WHITE, false, false);
l2 = GetDirtyRegion(bd, Pt(4,5), SG_WHITE, true, false);
BOOST_CHECK_EQUAL(s1, SgRect(4,4,5,5));
BOOST_CHECK_EQUAL(l1, SgRect(4,4,4,5));
BOOST_CHECK_EQUAL(s2, SgRect(4,4,5,5));
BOOST_CHECK_EQUAL(l2, SgRect(4,4,4,5));
s1 = GetDirtyRegion(bd, Pt(2,4), SG_BLACK, false, true);
l1 = GetDirtyRegion(bd, Pt(2,4), SG_BLACK, true, true);
bd.Play(Pt(2,4), SG_BLACK);
s2 = GetDirtyRegion(bd, Pt(2,4), SG_BLACK, false, false);
l2 = GetDirtyRegion(bd, Pt(2,4), SG_BLACK, true, false);
BOOST_CHECK_EQUAL(s1, SgRect(2,2,4,4));
BOOST_CHECK_EQUAL(l1, SgRect(2,3,4,4));
BOOST_CHECK_EQUAL(s2, SgRect(2,2,4,4));
BOOST_CHECK_EQUAL(l2, SgRect(2,3,4,4));
s1 = GetDirtyRegion(bd, SG_PASS, SG_WHITE, false, true);
l1 = GetDirtyRegion(bd, SG_PASS, SG_WHITE, true, true);
bd.Play(SG_PASS, SG_WHITE);
s2 = GetDirtyRegion(bd, SG_PASS, SG_WHITE, false, false);
l2 = GetDirtyRegion(bd, SG_PASS, SG_WHITE, true, false);
BOOST_CHECK_EQUAL(s1, SgRect());
BOOST_CHECK_EQUAL(l1, SgRect());
BOOST_CHECK_EQUAL(s2, SgRect());
BOOST_CHECK_EQUAL(l2, SgRect());
s1 = GetDirtyRegion(bd, Pt(3,5), SG_BLACK, false, true);
l1 = GetDirtyRegion(bd, Pt(3,5), SG_BLACK, true, true);
bd.Play(Pt(3,5), SG_BLACK);
s2 = GetDirtyRegion(bd, Pt(3,5), SG_BLACK, false, false);
l2 = GetDirtyRegion(bd, Pt(3,5), SG_BLACK, true, false);
BOOST_CHECK_EQUAL(s1, SgRect(3,3,4,5));
BOOST_CHECK_EQUAL(l1, SgRect(2,4,3,5));
BOOST_CHECK_EQUAL(s2, SgRect(3,3,4,5));
BOOST_CHECK_EQUAL(l2, SgRect(2,4,3,5));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_PassWins)
{
GoBoard bd(9);
GoRules& rules = bd.Rules();
rules.SetKomi(6.5);
rules.SetCaptureDead(true);
rules.SetJapaneseScoring(false);
bd.Play(Pt(5, 5), SG_BLACK);
BOOST_CHECK(! PassWins(bd, SG_BLACK)); // Last move was not a pass
bd.Play(SG_PASS, SG_WHITE);
BOOST_CHECK(PassWins(bd, SG_BLACK));
bd.Play(SG_PASS, SG_BLACK);
BOOST_CHECK(! PassWins(bd, SG_BLACK)); // Black is not to play
BOOST_CHECK(! PassWins(bd, SG_WHITE)); // Negative score for White
bd.Undo();
BOOST_CHECK(PassWins(bd, SG_BLACK));
rules.SetCaptureDead(false);
BOOST_CHECK(! PassWins(bd, SG_BLACK)); // Not Tromp-taylor rules
rules.SetCaptureDead(true);
BOOST_CHECK(PassWins(bd, SG_BLACK));
rules.SetJapaneseScoring(true);
BOOST_CHECK(! PassWins(bd, SG_BLACK)); // Not Tromp-taylor rules
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_ReduceToAnchors)
{
std::string s("XO.\n"
"XX.\n"
".OO");
int boardSize;
GoSetup setup = GoSetupUtil::CreateSetupFromString(s, boardSize);
GoBoard bd(boardSize, setup);
SgPointSet black = bd.All(SG_BLACK);
BOOST_CHECK_EQUAL(black.Size(), 3);
SgPointSet white = bd.All(SG_WHITE);
BOOST_CHECK_EQUAL(white.Size(), 3);
// SgVector version
{
SgVector<SgPoint> stones;
black.ToVector(&stones);
GoBoardUtil::ReduceToAnchors(bd, &stones);
BOOST_CHECK_EQUAL(stones.Length(), 1);
stones.Clear();
white.ToVector(&stones);
GoBoardUtil::ReduceToAnchors(bd, &stones);
BOOST_CHECK_EQUAL(stones.Length(), 2);
}
}
void CheckSelfAtari(const GoBoard& bd, SgPoint p, int nuExpectedStones)
{
// check both versions of SelfAtari
BOOST_CHECK(GoBoardUtil::SelfAtari(bd, p));
int nuStones = 0;
BOOST_CHECK(GoBoardUtil::SelfAtari(bd, p, nuStones));
BOOST_CHECK_EQUAL(nuStones, nuExpectedStones);
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_SelfAtari_1)
{
// . @ . O O . O O . 9
// @ @ @ @ @ . @ @ @ 8
// O . O . @ . @ @ @ 7
// @ @ @ @ . @ O . O 6
// O O . @ . @ O . O 5
// O O . @ . . @ @ @ 4
// @ @ . . . . + . . 3
// . . O O . . @ . . 2
// . O . @ . . . @ . 1
// 1 2 3 4 5 6 7 8 9
GoSetup setup;
setup.AddBlack(Pt(4, 1));
setup.AddBlack(Pt(8, 1));
setup.AddBlack(Pt(7, 2));
setup.AddBlack(Pt(1, 3));
setup.AddBlack(Pt(2, 3));
setup.AddBlack(Pt(4, 4));
setup.AddBlack(Pt(7, 4));
setup.AddBlack(Pt(8, 4));
setup.AddBlack(Pt(9, 4));
setup.AddBlack(Pt(4, 5));
setup.AddBlack(Pt(6, 5));
setup.AddBlack(Pt(1, 6));
setup.AddBlack(Pt(2, 6));
setup.AddBlack(Pt(3, 6));
setup.AddBlack(Pt(4, 6));
setup.AddBlack(Pt(6, 6));
setup.AddBlack(Pt(5, 7));
setup.AddBlack(Pt(7, 7));
setup.AddBlack(Pt(8, 7));
setup.AddBlack(Pt(9, 7));
setup.AddBlack(Pt(1, 8));
setup.AddBlack(Pt(2, 8));
setup.AddBlack(Pt(3, 8));
setup.AddBlack(Pt(4, 8));
setup.AddBlack(Pt(5, 8));
setup.AddBlack(Pt(7, 8));
setup.AddBlack(Pt(8, 8));
setup.AddBlack(Pt(9, 8));
setup.AddBlack(Pt(2, 9));
setup.AddWhite(Pt(2, 1));
setup.AddWhite(Pt(3, 2));
setup.AddWhite(Pt(4, 2));
setup.AddWhite(Pt(1, 4));
setup.AddWhite(Pt(2, 4));
setup.AddWhite(Pt(1, 5));
setup.AddWhite(Pt(2, 5));
setup.AddWhite(Pt(7, 5));
setup.AddWhite(Pt(9, 5));
setup.AddWhite(Pt(7, 6));
setup.AddWhite(Pt(9, 6));
setup.AddWhite(Pt(1, 7));
setup.AddWhite(Pt(3, 7));
setup.AddWhite(Pt(4, 9));
setup.AddWhite(Pt(5, 9));
setup.AddWhite(Pt(7, 9));
setup.AddWhite(Pt(8, 9));
GoBoard bd(9, setup);
bd.SetToPlay(SG_BLACK);
CheckSelfAtari(bd, Pt(1, 1), 1);
CheckSelfAtari(bd, Pt(3, 1), 2);
CheckSelfAtari(bd, Pt(6, 9), 1);
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(2, 2)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(5, 1)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(9, 1)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(1, 9)));
bd.SetToPlay(SG_WHITE);
CheckSelfAtari(bd, Pt(7, 1), 1);
CheckSelfAtari(bd, Pt(9, 1), 1);
CheckSelfAtari(bd, Pt(3, 5), 5);
CheckSelfAtari(bd, Pt(8, 5), 5);
CheckSelfAtari(bd, Pt(8, 6), 5);
CheckSelfAtari(bd, Pt(2, 7), 3);
CheckSelfAtari(bd, Pt(4, 7), 2);
CheckSelfAtari(bd, Pt(3, 9), 3);
CheckSelfAtari(bd, Pt(9, 9), 3);
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(5, 1)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(3, 1)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(1, 1)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(3, 4)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(6, 9)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(6, 8)));
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_SelfAtari_2)
{
// ko and capture - recapture cases
// . O @ . . . . . . 9
// O @ . . . @ @ O . 8
// @ . . . @ O . . O 7
// . . O @ . @ @ O . 6
// . O @ . @ O . . . 5
// . . O @ . @ @ O . 4
// . . . . . . . . . 3
// @ O . . . . . O @ 2
// . @ O . . . O . O 1
// 1 2 3 4 5 6 7 8 9
GoSetup setup;
setup.AddBlack(Pt(2, 1));
setup.AddBlack(Pt(1, 2));
setup.AddBlack(Pt(9, 2));
setup.AddBlack(Pt(4, 4));
setup.AddBlack(Pt(6, 4));
setup.AddBlack(Pt(7, 4));
setup.AddBlack(Pt(3, 5));
setup.AddBlack(Pt(5, 5));
setup.AddBlack(Pt(4, 6));
setup.AddBlack(Pt(6, 6));
setup.AddBlack(Pt(7, 6));
setup.AddBlack(Pt(1, 7));
setup.AddBlack(Pt(5, 7));
setup.AddBlack(Pt(2, 8));
setup.AddBlack(Pt(6, 8));
setup.AddBlack(Pt(7, 8));
setup.AddBlack(Pt(3, 9));
setup.AddWhite(Pt(3, 1));
setup.AddWhite(Pt(7, 1));
setup.AddWhite(Pt(9, 1));
setup.AddWhite(Pt(2, 2));
setup.AddWhite(Pt(8, 2));
setup.AddWhite(Pt(3, 4));
setup.AddWhite(Pt(8, 4));
setup.AddWhite(Pt(2, 5));
setup.AddWhite(Pt(6, 5));
setup.AddWhite(Pt(3, 6));
setup.AddWhite(Pt(8, 6));
setup.AddWhite(Pt(6, 7));
setup.AddWhite(Pt(9, 7));
setup.AddWhite(Pt(1, 8));
setup.AddWhite(Pt(8, 8));
setup.AddWhite(Pt(2, 9));
GoBoard bd(9, setup);
bd.SetToPlay(SG_BLACK);
CheckSelfAtari(bd, Pt(1, 1), 3);
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(8, 1))); // ko
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(1, 9))); // capture 2
bd.SetToPlay(SG_WHITE);
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(1, 1))); // ko
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(4, 5))); // ko
CheckSelfAtari(bd, Pt(7, 5), 2);
CheckSelfAtari(bd, Pt(7, 7), 2); // recapture situation
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_SelfAtari_3)
{
// sacrifice moves
// O . @ O . O @ . . 9
// @ @ @ O . O @ @ @ 8
// O O O . . O O O O 7
// @ O . . . . @ @ @ 6
// @ O . . . . @ O O 5
// . @ . . . . @ O O 4
// @ . . . . . @ @ O 3
// . . . . . . . O . 2
// . . . . . . . . O 1
// 1 2 3 4 5 6 7 8 9
GoSetup setup;
setup.AddBlack(Pt(1, 3));
setup.AddBlack(Pt(7, 3));
setup.AddBlack(Pt(8, 3));
setup.AddBlack(Pt(2, 4));
setup.AddBlack(Pt(7, 4));
setup.AddBlack(Pt(1, 5));
setup.AddBlack(Pt(7, 5));
setup.AddBlack(Pt(1, 6));
setup.AddBlack(Pt(7, 6));
setup.AddBlack(Pt(8, 6));
setup.AddBlack(Pt(9, 6));
setup.AddBlack(Pt(1, 8));
setup.AddBlack(Pt(2, 8));
setup.AddBlack(Pt(3, 8));
setup.AddBlack(Pt(7, 8));
setup.AddBlack(Pt(8, 8));
setup.AddBlack(Pt(9, 8));
setup.AddBlack(Pt(3, 9));
setup.AddBlack(Pt(7, 9));
setup.AddWhite(Pt(9, 1));
setup.AddWhite(Pt(8, 2));
setup.AddWhite(Pt(9, 3));
setup.AddWhite(Pt(8, 4));
setup.AddWhite(Pt(9, 4));
setup.AddWhite(Pt(2, 5));
setup.AddWhite(Pt(8, 5));
setup.AddWhite(Pt(9, 5));
setup.AddWhite(Pt(2, 6));
setup.AddWhite(Pt(1, 7));
setup.AddWhite(Pt(2, 7));
setup.AddWhite(Pt(3, 7));
setup.AddWhite(Pt(6, 7));
setup.AddWhite(Pt(7, 7));
setup.AddWhite(Pt(8, 7));
setup.AddWhite(Pt(9, 7));
setup.AddWhite(Pt(4, 8));
setup.AddWhite(Pt(6, 8));
setup.AddWhite(Pt(1, 9));
setup.AddWhite(Pt(4, 9));
setup.AddWhite(Pt(6, 9));
GoBoard bd(9, setup);
bd.SetToPlay(SG_BLACK);
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(9, 2))); // allow capture
CheckSelfAtari(bd, Pt(2, 9), 5); // capture 1 within eye, still in atari
CheckSelfAtari(bd, Pt(8, 9), 5);
CheckSelfAtari(bd, Pt(9, 9), 5);
bd.SetToPlay(SG_WHITE);
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(1, 4))); // allow capture
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(9, 2)));
BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(2, 9)));
//BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(8, 9))); // atari on opp.
//BOOST_CHECK(! GoBoardUtil::SelfAtari(bd, Pt(9, 9))); // atari on opp.
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_TrompTaylorScore)
{
// . . . . . . . . .
// . . . . . . . . .
// . . + . . . + . .
// . . . . . . . . .
// . . . . . . . . .
// O O O . . . . . .
// . . O . . . + . .
// @ @ O . . . . O O
// . @ O . . . . O .
GoSetup setup;
setup.AddBlack(Pt(1, 2));
setup.AddBlack(Pt(2, 1));
setup.AddBlack(Pt(2, 2));
setup.AddWhite(Pt(3, 1));
setup.AddWhite(Pt(3, 2));
setup.AddWhite(Pt(3, 3));
setup.AddWhite(Pt(3, 4));
setup.AddWhite(Pt(1, 4));
setup.AddWhite(Pt(2, 4));
setup.AddWhite(Pt(8, 1));
setup.AddWhite(Pt(8, 2));
setup.AddWhite(Pt(9, 2));
GoBoard bd(9, setup);
float komi = 6.5;
BOOST_CHECK_CLOSE(GoBoardUtil::TrompTaylorScore(bd, komi), -77.5f, 1e-4f);
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_TrompTaylorScore_Empty9)
{
GoBoard bd(9);
float komi = 6.5;
BOOST_CHECK_CLOSE(GoBoardUtil::TrompTaylorScore(bd, komi), -6.5f, 1e-4f);
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_TrompTaylorScore_Empty19)
{
GoBoard bd(19);
float komi = 6.5;
BOOST_CHECK_CLOSE(GoBoardUtil::TrompTaylorScore(bd, komi), -6.5f, 1e-4f);
}
BOOST_AUTO_TEST_CASE(GoBoardUtilTest_TwoPasses)
{
GoBoard bd(9);
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Play(Pt(1, 1), SG_BLACK);
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Play(SG_PASS, SG_WHITE);
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Play(Pt(2, 2), SG_BLACK);
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Play(SG_PASS, SG_WHITE);
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Play(SG_PASS, SG_WHITE);
// 2 passes by same color
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Play(SG_PASS, SG_BLACK);
BOOST_CHECK(GoBoardUtil::TwoPasses(bd));
bd.SetToPlay(SG_BLACK);
// wrong color order of pass moves wrt. current color to play
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
bd.Undo();
BOOST_CHECK(! GoBoardUtil::TwoPasses(bd));
}
//----------------------------------------------------------------------------
BOOST_AUTO_TEST_CASE(GoRestoreKoRuleTest)
{
GoBoard bd;
bd.Rules().SetKoRule(GoRules::SIMPLEKO);
{
GoRestoreKoRule restoreKoRule(bd);
bd.Rules().SetKoRule(GoRules::SUPERKO);
}
BOOST_CHECK_EQUAL(bd.Rules().GetKoRule(), GoRules::SIMPLEKO);
}
//----------------------------------------------------------------------------
} // namespace
| 32.33844 | 78 | 0.595633 | MisterTea |
d466d18ce84ba4acadbc6bc8a57ac82a2c6e7031 | 22,958 | cc | C++ | DQM/Physics/src/EwkDQM.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 852 | 2015-01-11T21:03:51.000Z | 2022-03-25T21:14:00.000Z | DQM/Physics/src/EwkDQM.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 30,371 | 2015-01-02T00:14:40.000Z | 2022-03-31T23:26:05.000Z | DQM/Physics/src/EwkDQM.cc | ckamtsikis/cmssw | ea19fe642bb7537cbf58451dcf73aa5fd1b66250 | [
"Apache-2.0"
] | 3,240 | 2015-01-02T05:53:18.000Z | 2022-03-31T17:24:21.000Z | /*
* See header file for a description of this class.
*
* \author Valentina Gori, University of Firenze
*/
#include "DQM/Physics/src/EwkDQM.h"
#include <vector>
#include <string>
#include <cmath>
#include "DataFormats/Candidate/interface/Candidate.h"
#include "FWCore/Framework/interface/Event.h"
#include "FWCore/Framework/interface/EventSetup.h"
#include "FWCore/ParameterSet/interface/ParameterSet.h"
#include "DQMServices/Core/interface/DQMStore.h"
#include "FWCore/ServiceRegistry/interface/Service.h"
#include "DataFormats/Common/interface/Handle.h"
#include "FWCore/MessageLogger/interface/MessageLogger.h"
#include "FWCore/Common/interface/TriggerNames.h"
// Physics Objects
#include "DataFormats/EgammaCandidates/interface/GsfElectron.h"
#include "DataFormats/MuonReco/interface/Muon.h"
#include "DataFormats/JetReco/interface/Jet.h"
#include "DataFormats/METReco/interface/MET.h"
#include "DataFormats/TrackReco/interface/Track.h"
#include "DataFormats/TrackReco/interface/TrackFwd.h"
#include "DataFormats/VertexReco/interface/Vertex.h"
#include "DataFormats/Math/interface/LorentzVector.h"
#include "TLorentzVector.h"
using namespace std;
using namespace edm;
using namespace reco;
// EwkDQM::EwkDQM(const ParameterSet& parameters) {
EwkDQM::EwkDQM(const ParameterSet& parameters) {
eJetMin_ = parameters.getUntrackedParameter<double>("EJetMin", 999999.);
// riguardare questa sintassi
// Get parameters from configuration file
thePFJetCollectionLabel_ = parameters.getParameter<InputTag>("PFJetCollection");
theCaloMETCollectionLabel_ = parameters.getParameter<InputTag>("caloMETCollection");
theTriggerResultsCollection_ = parameters.getParameter<InputTag>("triggerResultsCollection");
theElecTriggerPathToPass_ = parameters.getParameter<std::vector<string> >("elecTriggerPathToPass");
theMuonTriggerPathToPass_ = parameters.getParameter<std::vector<string> >("muonTriggerPathToPass");
theTriggerResultsToken_ =
consumes<edm::TriggerResults>(parameters.getParameter<InputTag>("triggerResultsCollection"));
theMuonCollectionLabel_ = consumes<reco::MuonCollection>(parameters.getParameter<InputTag>("muonCollection"));
theElectronCollectionLabel_ =
consumes<reco::GsfElectronCollection>(parameters.getParameter<InputTag>("electronCollection"));
thePFJetCollectionToken_ = consumes<edm::View<reco::Jet> >(parameters.getParameter<InputTag>("PFJetCollection"));
theCaloMETCollectionToken_ = consumes<edm::View<reco::MET> >(parameters.getParameter<InputTag>("caloMETCollection"));
theVertexToken_ = consumes<reco::VertexCollection>(parameters.getParameter<InputTag>("vertexCollection"));
// just to initialize
isValidHltConfig_ = false;
h_vertex_number = nullptr;
h_vertex_chi2 = nullptr;
h_vertex_numTrks = nullptr;
h_vertex_sumTrks = nullptr;
h_vertex_d0 = nullptr;
h_jet_count = nullptr;
h_jet_et = nullptr;
h_jet_pt = nullptr;
h_jet_eta = nullptr;
h_jet_phi = nullptr;
h_jet2_et = nullptr;
// h_jet2_pt = 0;
h_jet2_eta = nullptr;
h_jet2_phi = nullptr;
h_e1_et = nullptr;
h_e2_et = nullptr;
h_e1_eta = nullptr;
h_e2_eta = nullptr;
h_e1_phi = nullptr;
h_e2_phi = nullptr;
h_m1_pt = nullptr;
h_m2_pt = nullptr;
h_m1_eta = nullptr;
h_m2_eta = nullptr;
h_m1_phi = nullptr;
h_m2_phi = nullptr;
// h_t1_et = 0;
// h_t1_eta = 0;
// h_t1_phi = 0;
h_met = nullptr;
h_met_phi = nullptr;
h_e_invWMass = nullptr;
h_m_invWMass = nullptr;
h_mumu_invMass = nullptr;
h_ee_invMass = nullptr;
}
EwkDQM::~EwkDQM() {}
void EwkDQM::bookHistograms(DQMStore::IBooker& ibooker, edm::Run const&, edm::EventSetup const&) {
ibooker.setCurrentFolder("Physics/EwkDQM");
char chtitle[256] = "";
const size_t title_s = sizeof(chtitle);
logTraceName = "EwkAnalyzer";
LogTrace(logTraceName) << "Parameters initialization";
const float pi = 4 * atan(1);
// Keep the number of plots and number of bins to a minimum!
h_vertex_number = ibooker.book1D("vertex_number", "Number of event vertices in collection", 10, -0.5, 9.5);
h_vertex_chi2 = ibooker.book1D("vertex_chi2", "Event Vertex #chi^{2}/n.d.o.f.", 20, 0.0, 2.0);
h_vertex_numTrks = ibooker.book1D("vertex_numTrks", "Event Vertex, number of tracks", 20, -0.5, 59.5);
h_vertex_sumTrks = ibooker.book1D("vertex_sumTrks", "Event Vertex, sum of track pt", 20, 0.0, 100.0);
h_vertex_d0 = ibooker.book1D("vertex_d0", "Event Vertex d0", 20, 0.0, 0.05);
h_jet_count = ibooker.book1D("jet_count", chtitle, 8, -0.5, 7.5);
snprintf(
chtitle, title_s, "Leading jet E_{T} (from %s);E_{T}(1^{st} jet) (GeV)", thePFJetCollectionLabel_.label().data());
h_jet_et = ibooker.book1D("jet_et", chtitle, 20, 0., 200.0);
snprintf(chtitle,
title_s,
"Leading jet p_{T} (from %s);p_{T}(1^{st} jet) (GeV/c)",
thePFJetCollectionLabel_.label().data());
h_jet_pt = ibooker.book1D("jet_pt", chtitle, 20, 0., 200.0);
snprintf(chtitle, title_s, "Leading jet #eta (from %s); #eta (1^{st} jet)", thePFJetCollectionLabel_.label().data());
h_jet_eta = ibooker.book1D("jet_eta", chtitle, 20, -10., 10.0);
snprintf(chtitle, title_s, "Leading jet #phi (from %s); #phi(1^{st} jet)", thePFJetCollectionLabel_.label().data());
h_jet_phi = ibooker.book1D("jet_phi", chtitle, 22, -1.1 * pi, 1.1 * pi);
snprintf(chtitle,
title_s,
"2^{nd} leading jet E_{T} (from %s);E_{T}(2^{nd} jet) (GeV)",
thePFJetCollectionLabel_.label().data());
h_jet2_et = ibooker.book1D("jet2_et", chtitle, 20, 0., 200.0);
snprintf(chtitle,
title_s,
"2^{nd} leading jet #eta (from %s); #eta (2^{nd} jet)",
thePFJetCollectionLabel_.label().data());
h_jet2_eta = ibooker.book1D("jet2_eta", chtitle, 20, -10., 10.0);
snprintf(
chtitle, title_s, "2^{nd} leading jet #phi (from %s); #phi(2^{nd} jet)", thePFJetCollectionLabel_.label().data());
h_jet2_phi = ibooker.book1D("jet2_phi", chtitle, 22, -1.1 * pi, 1.1 * pi);
h_e1_et = ibooker.book1D("e1_et", "E_{T} of Leading Electron;E_{T} (GeV)", 20, 0.0, 100.0);
h_e2_et = ibooker.book1D("e2_et", "E_{T} of Second Electron;E_{T} (GeV)", 20, 0.0, 100.0);
h_e1_eta = ibooker.book1D("e1_eta", "#eta of Leading Electron;#eta", 20, -4.0, 4.0);
h_e2_eta = ibooker.book1D("e2_eta", "#eta of Second Electron;#eta", 20, -4.0, 4.0);
h_e1_phi = ibooker.book1D("e1_phi", "#phi of Leading Electron;#phi", 22, -1.1 * pi, 1.1 * pi);
h_e2_phi = ibooker.book1D("e2_phi", "#phi of Second Electron;#phi", 22, -1.1 * pi, 1.1 * pi);
h_m1_pt = ibooker.book1D("m1_pt", "p_{T} of Leading Muon;p_{T}(1^{st} #mu) (GeV)", 20, 0.0, 100.0);
h_m2_pt = ibooker.book1D("m2_pt", "p_{T} of Second Muon;p_{T}(2^{nd} #mu) (GeV)", 20, 0.0, 100.0);
h_m1_eta = ibooker.book1D("m1_eta", "#eta of Leading Muon;#eta(1^{st} #mu)", 20, -4.0, 4.0);
h_m2_eta = ibooker.book1D("m2_eta", "#eta of Second Muon;#eta(2^{nd} #mu)", 20, -4.0, 4.0);
h_m1_phi = ibooker.book1D(
"m1_phi", "#phi of Leading Muon;#phi(1^{st} #mu)", 20, (-1. - 1. / 10.) * pi, (1. + 1. / 10.) * pi);
h_m2_phi =
ibooker.book1D("m2_phi", "#phi of Second Muon;#phi(2^{nd} #mu)", 20, (-1. - 1. / 10.) * pi, (1. + 1. / 10.) * pi);
snprintf(chtitle, title_s, "Missing E_{T} (%s); GeV", theCaloMETCollectionLabel_.label().data());
h_met = ibooker.book1D("met", chtitle, 20, 0.0, 100);
h_met_phi =
ibooker.book1D("met_phi", "Missing E_{T} #phi;#phi(MET)", 22, (-1. - 1. / 10.) * pi, (1. + 1. / 10.) * pi);
h_e_invWMass = ibooker.book1D("we_invWMass", "W-> e #nu Transverse Mass;M_{T} (GeV)", 20, 0.0, 140.0);
h_m_invWMass = ibooker.book1D("wm_invWMass", "W-> #mu #nu Transverse Mass;M_{T} (GeV)", 20, 0.0, 140.0);
h_mumu_invMass = ibooker.book1D("z_mm_invMass", "#mu#mu Invariant Mass;InvMass (GeV)", 20, 40.0, 140.0);
h_ee_invMass = ibooker.book1D("z_ee_invMass", "ee Invariant Mass;InvMass (Gev)", 20, 40.0, 140.0);
}
///
void EwkDQM::dqmBeginRun(const edm::Run& theRun, const edm::EventSetup& theSetup) {
// passed as parameter to HLTConfigProvider::init(), not yet used
bool isConfigChanged = false;
// isValidHltConfig_ used to short-circuit analyze() in case of problems
const std::string hltProcessName(theTriggerResultsCollection_.process());
isValidHltConfig_ = hltConfigProvider_.init(theRun, theSetup, hltProcessName, isConfigChanged);
}
void EwkDQM::analyze(const Event& iEvent, const EventSetup& iSetup) {
// short-circuit if hlt problems
if (!isValidHltConfig_)
return;
LogTrace(logTraceName) << "Analysis of event # ";
// Did it pass certain HLT path?
Handle<TriggerResults> HLTresults;
iEvent.getByToken(theTriggerResultsToken_, HLTresults);
if (!HLTresults.isValid())
return;
const edm::TriggerNames& trigNames = iEvent.triggerNames(*HLTresults);
// a temporary, until we have a list of triggers of interest
std::vector<std::string> eleTrigPathNames;
std::vector<std::string> muTrigPathNames;
// eleTrigPathNames.push_back(theElecTriggerPathToPass_);
// muTrigPathNames.push_back(theMuonTriggerPathToPass_);
// end of temporary
bool passed_electron_HLT = false;
bool passed_muon_HLT = false;
for (unsigned int i = 0; i < HLTresults->size(); i++) {
const std::string& trigName = trigNames.triggerName(i);
// check if triggerName matches electronPath
for (unsigned int index = 0; index < theElecTriggerPathToPass_.size() && !passed_electron_HLT; index++) {
// 0 if found, pos if not
size_t trigPath = trigName.find(theElecTriggerPathToPass_[index]);
if (trigPath == 0) {
// cout << "MuonTrigger passed (=trigName): " << trigName <<endl;
passed_electron_HLT = HLTresults->accept(i);
}
}
// check if triggerName matches muonPath
for (unsigned int index = 0; index < theMuonTriggerPathToPass_.size() && !passed_muon_HLT; index++) {
// 0 if found, pos if not
size_t trigPath = trigName.find(theMuonTriggerPathToPass_[index]);
if (trigPath == 0) {
// cout << "MuonTrigger passed (=trigName): " << trigName <<endl;
passed_muon_HLT = HLTresults->accept(i);
}
}
}
// we are interested in events with a valid electron or muon
if (!(passed_electron_HLT || passed_muon_HLT))
return;
////////////////////////////////////////////////////////////////////////////////
// Vertex information
Handle<VertexCollection> vertexHandle;
iEvent.getByToken(theVertexToken_, vertexHandle);
if (!vertexHandle.isValid())
return;
VertexCollection vertexCollection = *(vertexHandle.product());
VertexCollection::const_iterator v = vertexCollection.begin();
int vertex_number = vertexCollection.size();
double vertex_chi2 = v->normalizedChi2(); // v->chi2();
double vertex_d0 = sqrt(v->x() * v->x() + v->y() * v->y());
double vertex_numTrks = v->tracksSize();
double vertex_sumTrks = 0.0;
// std::cout << "vertex_d0=" << vertex_d0 << "\n";
// double vertex_ndof = v->ndof();cout << "ndof="<<vertex_ndof<<endl;
for (Vertex::trackRef_iterator vertex_curTrack = v->tracks_begin(); vertex_curTrack != v->tracks_end();
vertex_curTrack++)
vertex_sumTrks += (*vertex_curTrack)->pt();
////////////////////////////////////////////////////////////////////////////////
// Missing ET
Handle<View<MET> > caloMETCollection;
iEvent.getByToken(theCaloMETCollectionToken_, caloMETCollection);
if (!caloMETCollection.isValid())
return;
float missing_et = caloMETCollection->begin()->et();
float met_phi = caloMETCollection->begin()->phi();
////////////////////////////////////////////////////////////////////////////////
// grab "gaussian sum fitting" electrons
Handle<GsfElectronCollection> electronCollection;
iEvent.getByToken(theElectronCollectionLabel_, electronCollection);
if (!electronCollection.isValid())
return;
// Find the highest and 2nd highest electron
float electron_et = -8.0;
float electron_eta = -8.0;
float electron_phi = -8.0;
float electron2_et = -9.0;
float electron2_eta = -9.0;
float electron2_phi = -9.0;
float ee_invMass = -9.0;
TLorentzVector e1, e2;
// If it passed electron HLT and the collection was found, find electrons near
// Z mass
if (passed_electron_HLT) {
for (reco::GsfElectronCollection::const_iterator recoElectron = electronCollection->begin();
recoElectron != electronCollection->end();
recoElectron++) {
// Require electron to pass some basic cuts
if (recoElectron->et() < 20 || fabs(recoElectron->eta()) > 2.5)
continue;
// Tighter electron cuts
if (recoElectron->deltaPhiSuperClusterTrackAtVtx() > 0.58 ||
recoElectron->deltaEtaSuperClusterTrackAtVtx() > 0.01 || recoElectron->sigmaIetaIeta() > 0.027)
continue;
if (recoElectron->et() > electron_et) {
electron2_et = electron_et; // 2nd highest gets values from current highest
electron2_eta = electron_eta;
electron2_phi = electron_phi;
electron_et = recoElectron->et(); // 1st highest gets values from new highest
electron_eta = recoElectron->eta();
electron_phi = recoElectron->phi();
e1 = TLorentzVector(recoElectron->momentum().x(),
recoElectron->momentum().y(),
recoElectron->momentum().z(),
recoElectron->p());
} else if (recoElectron->et() > electron2_et) {
electron2_et = recoElectron->et();
electron2_eta = recoElectron->eta();
electron2_phi = recoElectron->phi();
e2 = TLorentzVector(recoElectron->momentum().x(),
recoElectron->momentum().y(),
recoElectron->momentum().z(),
recoElectron->p());
}
} // end of loop over electrons
if (electron2_et > 0.0) {
TLorentzVector pair = e1 + e2;
ee_invMass = pair.M();
}
} // end of "are electrons valid"
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Take the STA muon container
Handle<MuonCollection> muonCollection;
iEvent.getByToken(theMuonCollectionLabel_, muonCollection);
if (!muonCollection.isValid())
return;
// Find the highest pt muons
float mm_invMass = -9.0;
float muon_pt = -9.0;
float muon_eta = -9.0;
float muon_phi = -9.0;
float muon2_pt = -9.0;
float muon2_eta = -9.0;
float muon2_phi = -9.0;
TLorentzVector m1, m2;
if (passed_muon_HLT) {
for (reco::MuonCollection::const_iterator recoMuon = muonCollection->begin(); recoMuon != muonCollection->end();
recoMuon++) {
// Require muon to pass some basic cuts
if (recoMuon->pt() < 20 || !recoMuon->isGlobalMuon())
continue;
// Some tighter muon cuts
if (recoMuon->globalTrack()->normalizedChi2() > 10)
continue;
if (recoMuon->pt() > muon_pt) {
muon2_pt = muon_pt; // 2nd highest gets values from current highest
muon2_eta = muon_eta;
muon2_phi = muon_phi;
muon_pt = recoMuon->pt(); // 1st highest gets values from new highest
muon_eta = recoMuon->eta();
muon_phi = recoMuon->phi();
m1 =
TLorentzVector(recoMuon->momentum().x(), recoMuon->momentum().y(), recoMuon->momentum().z(), recoMuon->p());
} else if (recoMuon->pt() > muon2_pt) {
muon2_pt = recoMuon->pt();
muon2_eta = recoMuon->eta();
muon2_phi = recoMuon->phi();
m2 =
TLorentzVector(recoMuon->momentum().x(), recoMuon->momentum().y(), recoMuon->momentum().z(), recoMuon->p());
}
}
}
if (muon2_pt > 0.0) {
TLorentzVector pair = m1 + m2;
mm_invMass = pair.M();
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Find the highest et jet
// Handle<CaloJetCollection> caloJetCollection;
Handle<View<Jet> > PFJetCollection;
iEvent.getByToken(thePFJetCollectionToken_, PFJetCollection);
if (!PFJetCollection.isValid())
return;
unsigned int muonCollectionSize = muonCollection->size();
// unsigned int jetCollectionSize = jetCollection->size();
unsigned int PFJetCollectionSize = PFJetCollection->size();
int jet_count = 0;
// int LEADJET=-1; double max_pt=0;
float jet_et = -80.0;
float jet_pt = -80.0; // prova
float jet_eta = -80.0; // now USED
float jet_phi = -80.0; // now USED
float jet2_et = -90.0;
float jet2_eta = -90.0; // now USED
float jet2_phi = -90.0; // now USED
// for (CaloJetCollection::const_iterator i_calojet =
// caloJetCollection->begin();
// i_calojet != caloJetCollection->end(); i_calojet++) {
// for (PFJetCollection::const_iterator i_pfjet = PFJetCollection->begin();
// i_pfjet != PFJetCollection->end(); i_pfjet++) {
// float jet_current_et = i_calojet->et();
// float jet_current_et = i_pfjet->et(); // e` identico a jet.et()
// jet_count++;
// cleaning: va messo prima del riempimento dell'istogramma // This is in
// order to use PFJets
for (unsigned int i = 0; i < PFJetCollectionSize; i++) {
const Jet& jet = PFJetCollection->at(i);
// la classe "jet" viene definita qui!!!
double minDistance = 99999;
for (unsigned int j = 0; j < muonCollectionSize; j++) {
const Muon& mu = muonCollection->at(j);
double distance =
sqrt((mu.eta() - jet.eta()) * (mu.eta() - jet.eta()) + (mu.phi() - jet.phi()) * (mu.phi() - jet.phi()));
if (minDistance > distance)
minDistance = distance;
}
if (minDistance < 0.3)
continue; // 0.3 is the isolation cone around the muon
// se la distanza muone-cono del jet e` minore di 0.3, passo avanti e non
// conteggio il mio jet
// If it overlaps with ELECTRON, it is not a jet
if (electron_et > 0.0 && fabs(jet.eta() - electron_eta) < 0.2 && calcDeltaPhi(jet.phi(), electron_phi) < 0.2)
continue;
if (electron2_et > 0.0 && fabs(jet.eta() - electron2_eta) < 0.2 && calcDeltaPhi(jet.phi(), electron2_phi) < 0.2)
continue;
// provo a cambiare la parte degli elettroni in modo simmetrico alla parte
// per i muoni
// ...
// ...
// if it has too low Et, throw away
if (jet.et() < eJetMin_)
continue;
jet_count++;
// ovvero: incrementa jet_count se:
// - non c'e un muone entro 0.3 di distanza dal cono del jet;
// - se il jet non si sovrappone ad un elettrone;
// - se l'energia trasversa e` maggiore della soglia impostata (15?)
// if(jet.et()>max_pt) { LEADJET=i; max_pt=jet.et();}
// se l'energia del jet e` maggiore di max_pt, diventa "i"
// l'indice del jet piu` energetico e max_pt la sua energia
// riguardare questo!!!
// fino ad ora, jet_et era inizializzato a -8.0
if (jet.et() > jet_et) {
jet2_et = jet_et; // 2nd highest jet gets et from current highest
// perche` prende l'energia del primo jet??
jet2_eta = jet_eta; // now USED
jet2_phi = jet_phi; // now USED
// jet_et = i_calojet->et(); // current highest jet gets
// et from the new highest
jet_et = jet.et(); // current highest jet gets et from the new highest
// ah, ok! lo riaggiorna solo dopo!
jet_pt = jet.pt(); // e` il pT del leading jet
jet_eta = jet.eta(); // now USED
jet_phi = jet.phi() * (Geom::pi() / 180.); // now USED
} else if (jet.et() > jet2_et) {
// jet2_et = i_calojet->et();
jet2_et = jet.et();
// jet2_eta = i_calojet->eta(); // UNUSED
// jet2_phi = i_calojet->phi(); // UNUSED
jet2_eta = jet.eta(); // now USED
jet2_phi = jet.phi(); // now USED
}
// questo elseif funziona
}
////////////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////////
// Fill Histograms //
////////////////////////////////////////////////////////////////////////////////
bool fill_e1 = false;
bool fill_e2 = false;
bool fill_m1 = false;
bool fill_m2 = false;
bool fill_met = false;
// Was Z->ee found?
if (ee_invMass > 0.0) {
h_ee_invMass->Fill(ee_invMass);
fill_e1 = true;
fill_e2 = true;
}
// Was Z->mu mu found?
if (mm_invMass > 0.0) {
h_mumu_invMass->Fill(mm_invMass);
fill_m1 = true;
fill_m2 = true;
h_jet2_et->Fill(jet2_et);
}
// Was W->e nu found?
if (electron_et > 0.0 && missing_et > 20.0) {
float dphiW = fabs(met_phi - electron_phi);
float W_mt_e = sqrt(2 * missing_et * electron_et * (1 - cos(dphiW)));
h_e_invWMass->Fill(W_mt_e);
fill_e1 = true;
fill_met = true;
}
// Was W->mu nu found?
if (muon_pt > 0.0 && missing_et > 20.0) {
float dphiW = fabs(met_phi - muon_phi);
float W_mt_m = sqrt(2 * missing_et * muon_pt * (1 - cos(dphiW)));
h_m_invWMass->Fill(W_mt_m);
fill_m1 = true;
fill_met = true;
}
if (jet_et > -10.0) {
h_jet_et->Fill(jet_et);
h_jet_count->Fill(jet_count);
}
if (jet_pt > 0.) {
h_jet_pt->Fill(jet_pt);
}
if (jet_eta > -50.) {
h_jet_eta->Fill(jet_eta);
}
if (jet_phi > -10.) {
h_jet_phi->Fill(jet_phi);
}
if (jet2_et > -10.0) {
h_jet2_et->Fill(jet2_et);
}
// if (jet2_pt>0.) {
// h_jet2_pt ->Fill(jet2_pt);
// }
if (jet2_eta > -50.) {
h_jet2_eta->Fill(jet2_eta);
}
if (jet2_phi > -10.) {
h_jet2_phi->Fill(jet2_phi);
}
if (fill_e1 || fill_m1) {
h_vertex_number->Fill(vertex_number);
h_vertex_chi2->Fill(vertex_chi2);
h_vertex_d0->Fill(vertex_d0);
h_vertex_numTrks->Fill(vertex_numTrks);
h_vertex_sumTrks->Fill(vertex_sumTrks);
}
if (fill_e1) {
h_e1_et->Fill(electron_et);
h_e1_eta->Fill(electron_eta);
h_e1_phi->Fill(electron_phi);
}
if (fill_e2) {
h_e2_et->Fill(electron2_et);
h_e2_eta->Fill(electron2_eta);
h_e2_phi->Fill(electron2_phi);
}
if (fill_m1) {
h_m1_pt->Fill(muon_pt);
h_m1_eta->Fill(muon_eta);
h_m1_phi->Fill(muon_phi);
}
if (fill_m2) {
h_m2_pt->Fill(muon2_pt);
h_m2_eta->Fill(muon2_eta);
h_m2_phi->Fill(muon2_phi);
}
if (fill_met) {
h_met->Fill(missing_et);
h_met_phi->Fill(met_phi);
}
////////////////////////////////////////////////////////////////////////////////
}
// This always returns only a positive deltaPhi
double EwkDQM::calcDeltaPhi(double phi1, double phi2) {
double deltaPhi = phi1 - phi2;
if (deltaPhi < 0)
deltaPhi = -deltaPhi;
if (deltaPhi > 3.1415926)
deltaPhi = 2 * 3.1415926 - deltaPhi;
return deltaPhi;
}
// Local Variables:
// show-trailing-whitespace: t
// truncate-lines: t
// End:
| 36.969404 | 120 | 0.624924 | ckamtsikis |
d46ca70032d9ca0e77631267eff8f921b909c4bf | 3,187 | cpp | C++ | src/Loaders/HeaderBLoader.cpp | driftyz700/EAlayer3-nfsw | 0bfe05ae18e5f1eb25917751c2772cfa49b60342 | [
"BSD-3-Clause"
] | 8 | 2021-01-26T15:30:21.000Z | 2021-08-29T19:44:26.000Z | src/Loaders/HeaderBLoader.cpp | driftyz700/EAlayer3-nfsw | 0bfe05ae18e5f1eb25917751c2772cfa49b60342 | [
"BSD-3-Clause"
] | 1 | 2020-10-31T00:40:01.000Z | 2020-10-31T00:40:01.000Z | src/Loaders/HeaderBLoader.cpp | Bo98/ealayer3 | ec3df1e5b4f27e91c919d1be6cb43fc992f37ece | [
"BSD-3-Clause"
] | 2 | 2021-01-27T14:24:01.000Z | 2021-02-12T10:51:42.000Z | /*
EA Layer 3 Extractor/Decoder
Copyright (C) 2010, Ben Moench.
See License.txt
*/
#include "Internal.h"
#include "HeaderBLoader.h"
#include "../Parsers/ParserVersion6.h"
elHeaderBLoader::elHeaderBLoader() :
m_SampleRate(0),
m_UseParser6(true)
{
return;
}
elHeaderBLoader::~elHeaderBLoader()
{
return;
}
const std::string elHeaderBLoader::GetName() const
{
return "Header B";
}
bool elHeaderBLoader::Initialize(std::istream* Input)
{
elBlockLoader::Initialize(Input);
// Read the small header
uint16_t BlockType;
uint16_t BlockSize;
m_Input->read((char*)&BlockType, 2);
m_Input->read((char*)&BlockSize, 2);
Swap(BlockType);
Swap(BlockSize);
if (BlockType != 0x4800)
{
VERBOSE("L: header B loader incorrect because of block type");
return false;
}
if (BlockSize < 8)
{
VERBOSE("L: header B loader incorrect because of block size");
return false;
}
// Read in the contents of the block
uint8_t Compression;
uint16_t SampleRate;
m_Input->read((char*)&Compression, 1);
m_Input->get();
m_Input->read((char*)&SampleRate, 2);
Swap(SampleRate);
// Different parsers for different values
if (Compression == 0x15)
{
m_UseParser6 = false;
}
else if (Compression == 0x16)
{
m_UseParser6 = true;
}
else
{
VERBOSE("L: header B loader incorrect because of compression");
return false;
}
m_SampleRate = SampleRate;
m_Input->seekg(BlockSize - 8, std::ios_base::cur);
VERBOSE("L: header B loader correct");
return true;
}
bool elHeaderBLoader::ReadNextBlock(elBlock& Block)
{
if (!m_Input)
{
return false;
}
if (m_Input->eof())
{
return false;
}
uint16_t BlockType;
uint16_t BlockSize;
uint32_t Samples;
const std::streamoff Offset = m_Input->tellg();
m_Input->read((char*)&BlockType, 2);
m_Input->read((char*)&BlockSize, 2);
m_Input->read((char*)&Samples, 4);
if (m_Input->eof())
{
return false;
}
Swap(BlockType);
Swap(BlockSize);
Swap(Samples);
if (BlockType == 0x4500)
{
return false;
}
else if (BlockType != 0x4400)
{
VERBOSE("L: header B invalid block type");
return false;
}
if (BlockSize <= 8)
{
VERBOSE("L: header B block too small");
return false;
}
BlockSize -= 8;
shared_array<uint8_t> Data(new uint8_t[BlockSize]);
m_Input->read((char*)Data.get(), BlockSize);
Block.Clear();
Block.Data = Data;
Block.SampleCount = Samples;
Block.Size = BlockSize;
Block.Offset = Offset;
m_CurrentBlockIndex++;
return true;
}
shared_ptr<elParser> elHeaderBLoader::CreateParser() const
{
if (m_UseParser6)
{
return make_shared<elParserVersion6>();
}
return make_shared<elParser>();
}
void elHeaderBLoader::ListSupportedParsers(std::vector<std::string>& Names) const
{
Names.push_back(make_shared<elParser>()->GetName());
Names.push_back(make_shared<elParserVersion6>()->GetName());
return;
}
| 20.044025 | 81 | 0.613743 | driftyz700 |
d46d9ba49dd329f337b83cc34588df1972ec0e7f | 31,041 | cpp | C++ | dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp | santosh90n/lumberyard-1 | 9608bcf905bb60e9f326bd3fe8297381c22d83a6 | [
"AML"
] | 1 | 2019-02-12T06:44:50.000Z | 2019-02-12T06:44:50.000Z | dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp | santosh90n/lumberyard-1 | 9608bcf905bb60e9f326bd3fe8297381c22d83a6 | [
"AML"
] | null | null | null | dev/Gems/EMotionFX/Code/EMotionFX/Source/BlendSpace1DNode.cpp | santosh90n/lumberyard-1 | 9608bcf905bb60e9f326bd3fe8297381c22d83a6 | [
"AML"
] | null | null | null | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
#include "BlendSpace1DNode.h"
#include "AnimGraphInstance.h"
#include "AnimGraphManager.h"
#include "BlendSpaceManager.h"
#include "ActorInstance.h"
#include "MotionInstance.h"
#include "AnimGraphAttributeTypes.h"
#include "AnimGraph.h"
#include "MotionSet.h"
#include "EMotionFXManager.h"
#include <MCore/Source/AttributeSettings.h>
#include <AzCore/std/sort.h>
#include <AzCore/Casting/numeric_cast.h>
namespace
{
class MotionSortComparer
{
public:
MotionSortComparer(const AZStd::vector<float>& motionCoordinates)
: m_motionCoordinates(motionCoordinates)
{
}
bool operator()(AZ::u32 a, AZ::u32 b) const
{
return m_motionCoordinates[a] < m_motionCoordinates[b];
}
private:
const AZStd::vector<float>& m_motionCoordinates;
};
}
namespace EMotionFX
{
BlendSpace1DNode::UniqueData::~UniqueData()
{
BlendSpaceNode::ClearMotionInfos(m_motionInfos);
}
BlendSpace1DNode* BlendSpace1DNode::Create(AnimGraph* animGraph)
{
return new BlendSpace1DNode(animGraph);
}
bool BlendSpace1DNode::GetValidCalculationMethodAndEvaluator() const
{
// if the evaluators is null, is in "manual" mode.
const ECalculationMethod calculationMethod = GetBlendSpaceCalculationMethod(ATTRIB_CALCULATION_METHOD);
if (calculationMethod == ECalculationMethod::MANUAL)
{
return true;
}
else
{
const BlendSpaceParamEvaluator* evaluator = GetBlendSpaceParamEvaluator(ATTRIB_EVALUATOR);
AZ_Assert(evaluator, "Expected non-null blend space param evaluator");
return !evaluator->IsNullEvaluator();
}
}
const char* BlendSpace1DNode::GetAxisLabel() const
{
BlendSpaceParamEvaluator* evaluator = GetBlendSpaceParamEvaluator(ATTRIB_EVALUATOR);
if (!evaluator || evaluator->IsNullEvaluator())
{
return "X-Axis";
}
return evaluator->GetName();
}
void BlendSpace1DNode::OnUpdateUniqueData(AnimGraphInstance* animGraphInstance)
{
// Find the unique data for this node, if it doesn't exist yet, create it.
UniqueData* uniqueData = static_cast<BlendSpace1DNode::UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
if (!uniqueData)
{
uniqueData = (UniqueData*)GetEMotionFX().GetAnimGraphManager()->GetObjectDataPool().RequestNew(TYPE_ID, this, animGraphInstance);
animGraphInstance->RegisterUniqueObjectData(uniqueData);
}
UpdateMotionInfos(animGraphInstance);
}
void BlendSpace1DNode::Init(AnimGraphInstance* animGraphInstance)
{
MCORE_UNUSED(animGraphInstance);
}
void BlendSpace1DNode::RegisterPorts()
{
InitInputPorts(1);
SetupInputPortAsNumber("X", INPUTPORT_VALUE, PORTID_INPUT_VALUE);
InitOutputPorts(1);
SetupOutputPortAsPose("Output Pose", OUTPUTPORT_POSE, PORTID_OUTPUT_POSE);
}
void BlendSpace1DNode::RegisterAttributes()
{
RegisterCalculationMethodAttribute("Calculation method (X-Axis)", "calculationMethodX", "Calculation method for the X Axis");
RegisterBlendSpaceEvaluatorAttribute("X-Axis Evaluator", "evaluatorX", "Evaluator for the X axis value of motions");
RegisterSyncAttribute();
RegisterMasterMotionAttribute();
RegisterBlendSpaceEventFilterAttribute();
MCore::AttributeSettings* attrib = RegisterAttribute("Motions", "motions", "Source motions for blend space", ATTRIBUTE_INTERFACETYPE_BLENDSPACEMOTIONS);
attrib->SetReinitGuiOnValueChange(true);
attrib->SetDefaultValue(MCore::AttributeArray::Create(AttributeBlendSpaceMotion::TYPE_ID));
}
const char* BlendSpace1DNode::GetTypeString() const
{
return "BlendSpace1DNode";
}
const char* BlendSpace1DNode::GetPaletteName() const
{
return "Blend Space 1D";
}
AnimGraphObject::ECategory BlendSpace1DNode::GetPaletteCategory() const
{
return AnimGraphObject::CATEGORY_BLENDING;
}
// This implementation currently just does what the other node classes in the
// EMFX code base are doing. This is not a proper implementation of
// "Clone" since "CopyBaseObjectTo" currently copies only the AnimGraphObject
AnimGraphObject* BlendSpace1DNode::Clone(AnimGraph* animGraph)
{
BlendSpace1DNode* clone = new BlendSpace1DNode(animGraph);
CopyBaseObjectTo(clone);
return clone;
}
AnimGraphObjectData* BlendSpace1DNode::CreateObjectData()
{
return new UniqueData(this, nullptr);
}
// Called when the attributes change.
void BlendSpace1DNode::OnUpdateAttributes()
{
if (mAttributeValues.GetIsEmpty())
{
return;
}
// Mark AttributeBlendSpaceMotion attributes as belonging to 1D blend space
MCore::AttributeArray* attributeArray = GetMotionAttributeArray();
if (attributeArray)
{
const uint32 numMotions = attributeArray->GetNumAttributes();
for (uint32 i = 0; i < numMotions; ++i)
{
AttributeBlendSpaceMotion* attrib = static_cast<AttributeBlendSpaceMotion*>(attributeArray->GetAttribute(i));
attrib->SetDimension(1);
}
}
const uint32 numAnimGraphInstances = mAnimGraph->GetNumAnimGraphInstances();
for (uint32 i = 0; i < numAnimGraphInstances; ++i)
{
AnimGraphInstance* animGraphInstance = mAnimGraph->GetAnimGraphInstance(i);
OnUpdateUniqueData(animGraphInstance);
}
// disable GUI items that have no influence
#ifdef EMFX_EMSTUDIOBUILD
EnableAllAttributes(true);
// Here, disable any attribute as needed.
const ECalculationMethod calculationMethod = GetBlendSpaceCalculationMethod(ATTRIB_CALCULATION_METHOD);
if (calculationMethod == ECalculationMethod::MANUAL)
{
SetAttributeDisabled(ATTRIB_EVALUATOR);
GetAttributeFloat(ATTRIB_EVALUATOR)->SetValue(0.0f);
}
else // Automatic calculation method
{
SetAttributeEnabled(ATTRIB_EVALUATOR);
}
#endif
}
void BlendSpace1DNode::Output(AnimGraphInstance* animGraphInstance)
{
// If the node is disabled, simply output a bind pose.
if (mDisabled)
{
SetBindPoseAtOutput(animGraphInstance);
return;
}
OutputAllIncomingNodes(animGraphInstance);
ActorInstance* actorInstance = animGraphInstance->GetActorInstance();
UniqueData* uniqueData = static_cast<UniqueData*>(FindUniqueNodeData(animGraphInstance));
RequestPoses(animGraphInstance);
AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue();
outputPose->InitFromBindPose(actorInstance);
Pose& outputLocalPose = outputPose->GetPose();
outputLocalPose.Zero();
const uint32 threadIndex = actorInstance->GetThreadIndex();
AnimGraphPosePool& posePool = GetEMotionFX().GetThreadData(threadIndex)->GetPosePool();
AnimGraphPose* bindPose = posePool.RequestPose(actorInstance);
bindPose->InitFromBindPose(actorInstance);
AnimGraphPose* motionOutPose = posePool.RequestPose(actorInstance);
Pose& motionOutLocalPose = motionOutPose->GetPose();
if (uniqueData->m_currentSegment.m_segmentIndex != MCORE_INVALIDINDEX32)
{
const AZ::u32 segIndex = uniqueData->m_currentSegment.m_segmentIndex;
for (int i = 0; i < 2; ++i)
{
MotionInstance* motionInstance = uniqueData->m_motionInfos[uniqueData->m_sortedMotions[segIndex + i]].m_motionInstance;
motionOutPose->InitFromBindPose(actorInstance);
motionInstance->GetMotion()->Update(&bindPose->GetPose(), &motionOutLocalPose, motionInstance);
if (motionInstance->GetMotionExtractionEnabled() && actorInstance->GetMotionExtractionEnabled())
{
motionOutLocalPose.CompensateForMotionExtractionDirect(motionInstance->GetMotion()->GetMotionExtractionFlags());
}
const float weight = (i == 0) ? (1 - uniqueData->m_currentSegment.m_weightForSegmentEnd) : uniqueData->m_currentSegment.m_weightForSegmentEnd;
outputLocalPose.Sum(&motionOutLocalPose, weight);
}
outputLocalPose.NormalizeQuaternions();
}
else if (!uniqueData->m_motionInfos.empty())
{
const AZ::u16 motionIdx = (uniqueData->m_currentPosition < uniqueData->GetRangeMin()) ? uniqueData->m_sortedMotions.front() : uniqueData->m_sortedMotions.back();
MotionInstance* motionInstance = uniqueData->m_motionInfos[motionIdx].m_motionInstance;
motionOutPose->InitFromBindPose(actorInstance);
motionInstance->GetMotion()->Update(&bindPose->GetPose(), &motionOutLocalPose, motionInstance);
if (motionInstance->GetMotionExtractionEnabled() && actorInstance->GetMotionExtractionEnabled())
{
motionOutLocalPose.CompensateForMotionExtractionDirect(motionInstance->GetMotion()->GetMotionExtractionFlags());
}
outputLocalPose.Sum(&motionOutLocalPose, 1.0f);
outputLocalPose.NormalizeQuaternions();
}
else
{
SetBindPoseAtOutput(animGraphInstance);
}
posePool.FreePose(motionOutPose);
posePool.FreePose(bindPose);
#ifdef EMFX_EMSTUDIOBUILD
if (GetCanVisualize(animGraphInstance))
{
animGraphInstance->GetActorInstance()->DrawSkeleton(outputPose->GetPose(), mVisualizeColor);
}
#endif
}
void BlendSpace1DNode::TopDownUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds)
{
if (mDisabled)
{
return;
}
UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
const ESyncMode syncMode = static_cast<ESyncMode>(static_cast<uint32>(GetAttributeFloat(ATTRIB_SYNC)->GetValue()));
DoTopDownUpdate(animGraphInstance, syncMode, uniqueData->m_masterMotionIdx,
uniqueData->m_motionInfos, uniqueData->m_allMotionsHaveSyncTracks);
EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection;
if (paramConnection)
{
AnimGraphNode* paramSrcNode = paramConnection->GetSourceNode();
if (paramSrcNode)
{
paramSrcNode->PerformTopDownUpdate(animGraphInstance, timePassedInSeconds);
}
}
}
void BlendSpace1DNode::Update(AnimGraphInstance* animGraphInstance, float timePassedInSeconds)
{
if (!mDisabled)
{
EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection;
if (paramConnection)
{
UpdateIncomingNode(animGraphInstance, paramConnection->GetSourceNode(), timePassedInSeconds);
}
}
UniqueData* uniqueData = static_cast<UniqueData*>(FindUniqueNodeData(animGraphInstance));
AZ_Assert(uniqueData, "UniqueData not found for BlendSpace1DNode");
uniqueData->Clear();
if (mDisabled)
{
return;
}
uniqueData->m_currentPosition = GetCurrentSamplePosition(animGraphInstance, *uniqueData);
// Set the duration and current play time etc to the master motion index, or otherwise just the first motion in the list if syncing is disabled.
const ESyncMode syncMode = (ESyncMode)((uint32)GetAttributeFloat(ATTRIB_SYNC)->GetValue());
AZ::u32 motionIndex = (uniqueData->m_masterMotionIdx != MCORE_INVALIDINDEX32) ? uniqueData->m_masterMotionIdx : MCORE_INVALIDINDEX32;
if (syncMode == ESyncMode::SYNCMODE_DISABLED || motionIndex == MCORE_INVALIDINDEX32)
motionIndex = 0;
UpdateBlendingInfoForCurrentPoint(*uniqueData);
DoUpdate(timePassedInSeconds, uniqueData->m_blendInfos, syncMode, uniqueData->m_masterMotionIdx, uniqueData->m_motionInfos);
if (!uniqueData->m_motionInfos.empty())
{
const MotionInfo& motionInfo = uniqueData->m_motionInfos[motionIndex];
uniqueData->SetDuration( motionInfo.m_motionInstance ? motionInfo.m_motionInstance->GetDuration() : 0.0f );
uniqueData->SetCurrentPlayTime( motionInfo.m_currentTime );
uniqueData->SetSyncTrack( motionInfo.m_syncTrack );
uniqueData->SetSyncIndex( motionInfo.m_syncIndex );
uniqueData->SetPreSyncTime( motionInfo.m_preSyncTime);
uniqueData->SetPlaySpeed( motionInfo.m_playSpeed );
}
}
void BlendSpace1DNode::PostUpdate(AnimGraphInstance* animGraphInstance, float timePassedInSeconds)
{
UniqueData* uniqueData = static_cast<UniqueData*>(FindUniqueNodeData(animGraphInstance));
if (mDisabled)
{
RequestRefDatas(animGraphInstance);
AnimGraphRefCountedData* data = uniqueData->GetRefCountedData();
data->ClearEventBuffer();
data->ZeroTrajectoryDelta();
return;
}
EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection;
if (paramConnection)
{
paramConnection->GetSourceNode()->PerformPostUpdate(animGraphInstance, timePassedInSeconds);
}
if (uniqueData->m_motionInfos.empty())
{
RequestRefDatas(animGraphInstance);
AnimGraphRefCountedData* data = uniqueData->GetRefCountedData();
data->ClearEventBuffer();
data->ZeroTrajectoryDelta();
return;
}
RequestRefDatas(animGraphInstance);
AnimGraphRefCountedData* data = uniqueData->GetRefCountedData();
data->ClearEventBuffer();
data->ZeroTrajectoryDelta();
const EBlendSpaceEventMode eventFilterMode = (EBlendSpaceEventMode)((uint32)GetAttributeFloat(ATTRIB_EVENTMODE)->GetValue());
DoPostUpdate(animGraphInstance, uniqueData->m_masterMotionIdx, uniqueData->m_blendInfos, uniqueData->m_motionInfos, eventFilterMode, data);
}
BlendSpace1DNode::BlendSpace1DNode(AnimGraph* animGraph)
: BlendSpaceNode(animGraph, nullptr, TYPE_ID)
, m_currentPositionSetInteractively(false)
{
CreateAttributeValues();
RegisterPorts();
InitInternalAttributesForAllInstances();
}
BlendSpace1DNode::~BlendSpace1DNode()
{
}
bool BlendSpace1DNode::UpdateMotionInfos(AnimGraphInstance* animGraphInstance)
{
ActorInstance* actorInstance = animGraphInstance->GetActorInstance();
if (!actorInstance)
{
return false;
}
UniqueData* uniqueData = static_cast<UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
ClearMotionInfos(uniqueData->m_motionInfos);
MotionSet* motionSet = animGraphInstance->GetMotionSet();
if (!motionSet)
{
return false;
}
// Initialize motion instance and parameter value arrays.
MCore::AttributeArray* attributeArray = GetMotionAttributeArray();
const uint32 numMotions = attributeArray->GetNumAttributes();
AZ_Assert(uniqueData->m_motionInfos.empty(), "This is assumed to have been cleared already");
uniqueData->m_motionInfos.reserve(numMotions);
MotionInstancePool& motionInstancePool = GetMotionInstancePool();
const AZStd::string masterMotionId(GetAttributeString(ATTRIB_SYNC_MASTERMOTION)->GetValue().AsChar());
uniqueData->m_masterMotionIdx = 0;
PlayBackInfo playInfo;// TODO: Init from attributes
for (uint32 i = 0; i < numMotions; ++i)
{
AttributeBlendSpaceMotion* attribute = static_cast<AttributeBlendSpaceMotion*>(attributeArray->GetAttribute(i));
const AZStd::string& motionId = attribute->GetMotionId();
Motion* motion = motionSet->RecursiveFindMotionByStringID(motionId.c_str());
if (!motion)
{
attribute->SetFlag(AttributeBlendSpaceMotion::TypeFlags::InvalidMotion);
continue;
}
attribute->UnsetFlag(AttributeBlendSpaceMotion::TypeFlags::InvalidMotion);
MotionInstance* motionInstance = motionInstancePool.RequestNew(motion, actorInstance, playInfo.mStartNodeIndex);
motionInstance->InitFromPlayBackInfo(playInfo, true);
motionInstance->SetRetargetingEnabled(animGraphInstance->GetRetargetingEnabled() && playInfo.mRetarget);
if (!motionInstance->GetIsReadyForSampling())
{
motionInstance->InitForSampling();
}
motionInstance->UnPause();
motionInstance->SetIsActive(true);
motionInstance->SetWeight(1.0f, 0.0f);
AddMotionInfo(uniqueData->m_motionInfos, motionInstance);
if (motionId == masterMotionId)
{
uniqueData->m_masterMotionIdx = (AZ::u32)uniqueData->m_motionInfos.size() - 1;
}
}
uniqueData->m_allMotionsHaveSyncTracks = DoAllMotionsHaveSyncTracks(uniqueData->m_motionInfos);
UpdateMotionPositions(*uniqueData);
SortMotionInstances(*uniqueData);
uniqueData->m_currentSegment.m_segmentIndex = MCORE_INVALIDINDEX32;
return true;
}
void BlendSpace1DNode::UpdateMotionPositions(UniqueData& uniqueData)
{
const BlendSpaceManager* blendSpaceManager = GetAnimGraphManager().GetBlendSpaceManager();
// Get the motion parameter evaluator.
BlendSpaceParamEvaluator* evaluator = nullptr;
const ECalculationMethod calculationMethod = GetBlendSpaceCalculationMethod(ATTRIB_CALCULATION_METHOD);
if (calculationMethod == ECalculationMethod::AUTO)
{
const size_t evaluatorIndex = static_cast<size_t>(GetAttributeFloatAsUint32(ATTRIB_EVALUATOR));
evaluator = blendSpaceManager->GetParameterEvaluator(evaluatorIndex);
if (evaluator && evaluator->IsNullEvaluator())
{
// "Null evaluator" is really not an evaluator.
evaluator = nullptr;
}
}
const MCore::AttributeArray* attributeArray = GetMotionAttributeArray();
// the motions in the attributes could not match the ones in the unique data. The attribute could have some invalid motions
const uint32 attributeMotionCount = attributeArray->GetNumAttributes();
const size_t uniqueDataMotionCount = uniqueData.m_motionInfos.size();
// Iterate through all motions and calculate their location in the blend space.
uniqueData.m_motionCoordinates.resize(uniqueDataMotionCount);
size_t uniqueDataMotionIndex = 0;
for (uint32 iAttributeMotionIndex = 0; iAttributeMotionIndex < attributeMotionCount; ++iAttributeMotionIndex)
{
const AttributeBlendSpaceMotion* attribute = static_cast<AttributeBlendSpaceMotion*>(attributeArray->GetAttribute(iAttributeMotionIndex));
if (attribute->TestFlag(AttributeBlendSpaceMotion::TypeFlags::InvalidMotion))
{
continue;
}
// Calculate the position of the motion in the blend space.
if (attribute->IsXCoordinateSetByUser())
{
// Did the user set the values manually? If so, use that.
uniqueData.m_motionCoordinates[uniqueDataMotionIndex] = attribute->GetXCoordinate();
}
else if (evaluator)
{
// Position was not set by user. Use evaluator for automatic computation.
MotionInstance* motionInstance = uniqueData.m_motionInfos[uniqueDataMotionIndex].m_motionInstance;
uniqueData.m_motionCoordinates[uniqueDataMotionIndex] = evaluator->ComputeParamValue(*motionInstance);
}
++uniqueDataMotionIndex;
}
}
void BlendSpace1DNode::SetCurrentPosition(float point)
{
m_currentPositionSetInteractively = point;
}
void BlendSpace1DNode::ComputeMotionPosition(const AZStd::string& motionId, AnimGraphInstance* animGraphInstance, AZ::Vector2& position)
{
UniqueData* uniqueData = static_cast<UniqueData*>(FindUniqueNodeData(animGraphInstance));
AZ_Assert(uniqueData, "Unique data not found for blend space 1D node '%s'.", GetName());
const uint32 attributeIndex = FindBlendSpaceMotionAttributeIndexByMotionId(ATTRIB_MOTIONS, motionId);
if (attributeIndex == MCORE_INVALIDINDEX32)
{
AZ_Assert(false, "Can't find blend space motion attribute for motion id '%s'.", motionId.c_str());
return;
}
// Get the motion parameter evaluator.
BlendSpaceParamEvaluator* evaluator = nullptr;
const ECalculationMethod calculationMethod = GetBlendSpaceCalculationMethod(ATTRIB_CALCULATION_METHOD);
if (calculationMethod == ECalculationMethod::AUTO)
{
const size_t evaluatorIndex = static_cast<size_t>(GetAttributeFloatAsUint32(ATTRIB_EVALUATOR));
const BlendSpaceManager* blendSpaceManager = GetAnimGraphManager().GetBlendSpaceManager();
evaluator = blendSpaceManager->GetParameterEvaluator(evaluatorIndex);
if (evaluator && evaluator->IsNullEvaluator())
{
// "Null evaluator" is really not an evaluator.
evaluator = nullptr;
}
}
if (!evaluator)
{
position = AZ::Vector2::CreateZero();
return;
}
// If the motion is invalid, we dont have anything to update.
MCore::AttributeArray* motionsAttribute = GetMotionAttributeArray();
AttributeBlendSpaceMotion* motionAttribute = static_cast<AttributeBlendSpaceMotion*>(motionsAttribute->GetAttribute(attributeIndex));
if (motionAttribute->TestFlag(AttributeBlendSpaceMotion::TypeFlags::InvalidMotion))
{
return;
}
// Compute the unique data motion index by skipping those motions from the attribute that are invalid
uint32 uniqueDataMotionIndex = 0;
for (uint32 i = 0; i < attributeIndex; ++i)
{
AttributeBlendSpaceMotion* theMotionAttribute = static_cast<AttributeBlendSpaceMotion*>(motionsAttribute->GetAttribute(i));
if (theMotionAttribute->TestFlag(AttributeBlendSpaceMotion::TypeFlags::InvalidMotion))
{
continue;
}
else
{
++uniqueDataMotionIndex;
}
}
AZ_Assert(uniqueDataMotionIndex < uniqueData->m_motionInfos.size(), "Invalid amount of motion infos in unique data");
MotionInstance* motionInstance = uniqueData->m_motionInfos[uniqueDataMotionIndex].m_motionInstance;
position.SetX(evaluator->ComputeParamValue(*motionInstance));
position.SetY(0.0f);
}
void BlendSpace1DNode::RestoreMotionCoords(const AZStd::string& motionId, AnimGraphInstance* animGraphInstance)
{
const ECalculationMethod calculationMethodX = GetBlendSpaceCalculationMethod(ATTRIB_CALCULATION_METHOD);
AZ::Vector2 computedMotionCoords;
ComputeMotionPosition(motionId, animGraphInstance, computedMotionCoords);
const uint32 attributeIndex = FindBlendSpaceMotionAttributeIndexByMotionId(ATTRIB_MOTIONS, motionId);
if (attributeIndex == MCORE_INVALIDINDEX32)
{
AZ_Assert(false, "Can't find blend space motion attribute for motion id '%s'.", motionId.c_str());
return;
}
MCore::AttributeArray* motionsAttribute = GetMotionAttributeArray();
AttributeBlendSpaceMotion* motionAttribute = static_cast<AttributeBlendSpaceMotion*>(motionsAttribute->GetAttribute(attributeIndex));
// Reset the motion coordinates in case the user manually set the value and we're in automatic mode.
if (!motionAttribute->IsXCoordinateSetByUser() && calculationMethodX == ECalculationMethod::AUTO)
{
motionAttribute->SetXCoordinate(computedMotionCoords.GetX());
motionAttribute->MarkXCoordinateSetByUser(false);
}
}
MCore::AttributeArray* BlendSpace1DNode::GetMotionAttributeArray() const
{
return GetAttributeArray(ATTRIB_MOTIONS);
}
void BlendSpace1DNode::SortMotionInstances(UniqueData& uniqueData)
{
const AZ::u16 numMotions = aznumeric_caster(uniqueData.m_motionCoordinates.size());
uniqueData.m_sortedMotions.resize(numMotions);
for (AZ::u16 i = 0; i < numMotions; ++i)
{
uniqueData.m_sortedMotions[i] = i;
}
MotionSortComparer comparer(uniqueData.m_motionCoordinates);
AZStd::sort(uniqueData.m_sortedMotions.begin(), uniqueData.m_sortedMotions.end(), comparer);
// Detect if we have coordinates overlapping
uniqueData.m_hasOverlappingCoordinates = false;
for (AZ::u32 i = 1; i < numMotions; ++i)
{
const AZ::u16 motionA = uniqueData.m_sortedMotions[i - 1];
const AZ::u16 motionB = uniqueData.m_sortedMotions[i];
if (AZ::IsClose(uniqueData.m_motionCoordinates[motionA],
uniqueData.m_motionCoordinates[motionB],
0.0001f))
{
uniqueData.m_hasOverlappingCoordinates = true;
break;
}
}
}
float BlendSpace1DNode::GetCurrentSamplePosition(AnimGraphInstance* animGraphInstance, const UniqueData& uniqueData)
{
if (IsInInteractiveMode())
{
return m_currentPositionSetInteractively;
}
else
{
EMotionFX::BlendTreeConnection* paramConnection = GetInputPort(INPUTPORT_VALUE).mConnection;
#ifdef EMFX_EMSTUDIOBUILD
// We do require the user to make connections into the value port.
SetHasError(animGraphInstance, (paramConnection == nullptr));
#endif
float samplePoint;
if (paramConnection)
{
samplePoint = GetInputNumberAsFloat(animGraphInstance, INPUTPORT_VALUE);
}
else
{
// Nothing connected to input port. Just return the middle of the parameter range as a default choice.
samplePoint = (uniqueData.GetRangeMin() + uniqueData.GetRangeMax()) / 2;
}
return samplePoint;
}
}
void BlendSpace1DNode::UpdateBlendingInfoForCurrentPoint(UniqueData& uniqueData)
{
uniqueData.m_currentSegment.m_segmentIndex = MCORE_INVALIDINDEX32;
FindLineSegmentForCurrentPoint(uniqueData);
uniqueData.m_blendInfos.clear();
if (uniqueData.m_currentSegment.m_segmentIndex != MCORE_INVALIDINDEX32)
{
const AZ::u32 segIndex = uniqueData.m_currentSegment.m_segmentIndex;
uniqueData.m_blendInfos.resize(2);
for (int i = 0; i < 2; ++i)
{
BlendInfo& blendInfo = uniqueData.m_blendInfos[i];
blendInfo.m_motionIndex = uniqueData.m_sortedMotions[segIndex + i];
blendInfo.m_weight = (i == 0) ? (1 - uniqueData.m_currentSegment.m_weightForSegmentEnd) : uniqueData.m_currentSegment.m_weightForSegmentEnd;
}
}
else if (!uniqueData.m_motionInfos.empty())
{
uniqueData.m_blendInfos.resize(1);
BlendInfo& blendInfo = uniqueData.m_blendInfos[0];
blendInfo.m_motionIndex = (uniqueData.m_currentPosition < uniqueData.GetRangeMin()) ? uniqueData.m_sortedMotions.front() : uniqueData.m_sortedMotions.back();
blendInfo.m_weight = 1.0f;
}
AZStd::sort(uniqueData.m_blendInfos.begin(), uniqueData.m_blendInfos.end());
}
bool BlendSpace1DNode::FindLineSegmentForCurrentPoint(UniqueData& uniqueData)
{
const AZ::u32 numPoints = (AZ::u32)uniqueData.m_sortedMotions.size();
if ((numPoints < 2) || (uniqueData.m_currentPosition < uniqueData.GetRangeMin()) || (uniqueData.m_currentPosition > uniqueData.GetRangeMax()))
{
uniqueData.m_currentSegment.m_segmentIndex = MCORE_INVALIDINDEX32;
return false;
}
for (AZ::u32 i = 1; i < numPoints; ++i)
{
const float segStart = uniqueData.m_motionCoordinates[uniqueData.m_sortedMotions[i - 1]];
const float segEnd = uniqueData.m_motionCoordinates[uniqueData.m_sortedMotions[i]];
AZ_Assert(segStart <= segEnd, "The values should have been sorted");
if ((uniqueData.m_currentPosition >= segStart) && (uniqueData.m_currentPosition <= segEnd))
{
uniqueData.m_currentSegment.m_segmentIndex = i - 1;
const float segLength = segEnd - segStart;
if (segLength <= 0)
{
uniqueData.m_currentSegment.m_weightForSegmentEnd = 0;
}
else
{
uniqueData.m_currentSegment.m_weightForSegmentEnd = (uniqueData.m_currentPosition - segStart) / segLength;
}
return true;
}
}
uniqueData.m_currentSegment.m_segmentIndex = MCORE_INVALIDINDEX32;
return false;
}
void BlendSpace1DNode::SetBindPoseAtOutput(AnimGraphInstance* animGraphInstance)
{
RequestPoses(animGraphInstance);
AnimGraphPose* outputPose = GetOutputPose(animGraphInstance, OUTPUTPORT_POSE)->GetValue();
ActorInstance* actorInstance = animGraphInstance->GetActorInstance();
outputPose->InitFromBindPose(actorInstance);
}
void BlendSpace1DNode::Rewind(AnimGraphInstance* animGraphInstance)
{
UniqueData* uniqueData = static_cast<BlendSpace1DNode::UniqueData*>(animGraphInstance->FindUniqueObjectData(this));
RewindMotions(uniqueData->m_motionInfos);
}
} // namespace EMotionFX
| 41.277926 | 173 | 0.66628 | santosh90n |
d46e4e6978cd34916711731f7a420ddbc62e140c | 416 | hpp | C++ | galaxy/src/galaxy/platform/specific/Unix.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | 6 | 2018-07-21T20:37:01.000Z | 2018-10-31T01:49:35.000Z | galaxy/src/galaxy/platform/specific/Unix.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | galaxy/src/galaxy/platform/specific/Unix.hpp | reworks/rework | 90508252c9a4c77e45a38e7ce63cfd99f533f42b | [
"Apache-2.0"
] | null | null | null | ///
/// Unix.hpp
/// galaxy
///
/// Refer to LICENSE.txt for more details.
///
#ifndef GALAXY_PLATFORM_SPECIFIC_UNIX_HPP_
#define GALAXY_PLATFORM_SPECIFIC_UNIX_HPP_
#include "galaxy/utils/Globals.hpp"
#ifdef GALAXY_UNIX_PLATFORM
namespace galaxy
{
namespace platform
{
///
/// Sets up debug terminal.
///
void configure_terminal() noexcept;
} // namespace platform
} // namespace galaxy
#endif
#endif | 15.407407 | 42 | 0.721154 | reworks |
d4726579794ff4318095d0b016a11686668b65c6 | 4,213 | cpp | C++ | test/template_vulkan-dynamic/flextVk.cpp | mosra/flextGL | bc3d4da8fc087cba17d64e9d908ae35b7e40f4fe | [
"MIT"
] | 119 | 2018-05-31T19:11:17.000Z | 2022-03-29T04:56:46.000Z | test/template_vulkan-dynamic/flextVk.cpp | ginkgo/flextGL | bc3d4da8fc087cba17d64e9d908ae35b7e40f4fe | [
"MIT"
] | 5 | 2015-01-16T12:24:22.000Z | 2018-05-27T14:52:45.000Z | test/template_vulkan-dynamic/flextVk.cpp | mosra/flextGL | bc3d4da8fc087cba17d64e9d908ae35b7e40f4fe | [
"MIT"
] | 8 | 2015-01-29T13:27:13.000Z | 2017-01-31T09:20:03.000Z | /*
This file was generated using https://github.com/mosra/flextgl:
path/to/flextGLgen.py -D generated -t somepath profile-vk.txt
Do not edit directly, modify the template or profile and regenerate.
*/
#include "flextVk.h"
/* The following definitions and flextDynamicLoader are borrowed/modified from vulkan.hpp DynamicLoader */
// Copyright (c) 2015-2020 The Khronos Group Inc.
//
// SPDX-License-Identifier: Apache-2.0 OR MIT
//
#if defined(__linux__) || defined(__APPLE__)
#include <dlfcn.h>
#elif defined(_WIN32)
typedef struct HINSTANCE__ *HINSTANCE;
#if defined(_WIN64)
typedef int64_t(__stdcall *FARPROC)();
#else
typedef int(__stdcall *FARPROC)();
#endif
extern "C" __declspec(dllimport) HINSTANCE __stdcall LoadLibraryA(char const *lpLibFileName);
extern "C" __declspec(dllimport) int __stdcall FreeLibrary(HINSTANCE hLibModule);
extern "C" __declspec(dllimport) FARPROC __stdcall GetProcAddress(HINSTANCE hModule, const char *lpProcName);
#endif
class flextDynamicLoader {
public:
flextDynamicLoader() : m_success(false), m_library(nullptr) {
}
~flextDynamicLoader() {
if (m_library) {
#if defined(__linux__) || defined(__APPLE__)
dlclose(m_library);
#elif defined(_WIN32)
::FreeLibrary(m_library);
#else
#error unsupported platform
#endif
}
}
bool init() {
if (m_success) return true;
#if defined(__linux__)
m_library = dlopen("libvulkan.so", RTLD_NOW | RTLD_LOCAL);
if (m_library == nullptr) {
m_library = dlopen("libvulkan.so.1", RTLD_NOW | RTLD_LOCAL);
}
m_success = (m_library != nullptr);
#elif defined(__APPLE__)
m_library = dlopen("libvulkan.dylib", RTLD_NOW | RTLD_LOCAL);
m_success = (m_library != nullptr);
#elif defined(_WIN32)
m_library = ::LoadLibraryA("vulkan-1.dll");
m_success = (m_library != nullptr);
#else
#error unsupported platform
#endif
return m_success;
}
#if defined(__linux__) || defined(__APPLE__)
void*
#elif defined(_WIN32)
FARPROC
#else
#error unsupported platform
#endif
getProcAddress(const char *function) const {
#if defined(__linux__) || defined(__APPLE__)
return dlsym(m_library, function);
#elif defined(_WIN32)
return ::GetProcAddress(m_library, function);
#else
#error unsupported platform
#endif
}
private:
bool m_success;
#if defined(__linux__) || defined(__APPLE__)
void *m_library;
#elif defined(_WIN32)
::HINSTANCE m_library;
#else
#error unsupported platform
#endif
};
VkResult(VKAPI_PTR *flextvkAcquireNextImageKHR)(VkDevice, VkSwapchainKHR, uint64_t, VkSemaphore, VkFence, uint32_t*) = nullptr;
VkResult(VKAPI_PTR *flextvkCreateBuffer)(VkDevice, const VkBufferCreateInfo*, const VkAllocationCallbacks*, VkBuffer*) = nullptr;
PFN_vkVoidFunction(VKAPI_PTR *flextvkGetDeviceProcAddr)(VkDevice, const char*) = nullptr;
PFN_vkVoidFunction(VKAPI_PTR *flextvkGetInstanceProcAddr)(VkInstance, const char*) = nullptr;
VkResult(VKAPI_PTR *flextvkEnumerateInstanceVersion)(uint32_t*) = nullptr;
bool flextVkInit() {
static flextDynamicLoader loader;
if (!loader.init()) return false;
flextvkGetInstanceProcAddr = reinterpret_cast<PFN_vkVoidFunction(VKAPI_PTR*)(VkInstance, const char*)>(loader.getProcAddress("vkGetInstanceProcAddr"));
if (flextvkGetInstanceProcAddr) {
flextvkEnumerateInstanceVersion = reinterpret_cast<VkResult(VKAPI_PTR*)(uint32_t*)>(flextvkGetInstanceProcAddr(nullptr, "vkEnumerateInstanceVersion"));
}
return true;
}
void flextVkInitInstance(VkInstance instance) {
flextvkAcquireNextImageKHR = reinterpret_cast<VkResult(VKAPI_PTR*)(VkDevice, VkSwapchainKHR, uint64_t, VkSemaphore, VkFence, uint32_t*)>(flextvkGetInstanceProcAddr(instance, "vkAcquireNextImageKHR"));
flextvkCreateBuffer = reinterpret_cast<VkResult(VKAPI_PTR*)(VkDevice, const VkBufferCreateInfo*, const VkAllocationCallbacks*, VkBuffer*)>(flextvkGetInstanceProcAddr(instance, "vkCreateBuffer"));
flextvkGetDeviceProcAddr = reinterpret_cast<PFN_vkVoidFunction(VKAPI_PTR*)(VkDevice, const char*)>(flextvkGetInstanceProcAddr(instance, "vkGetDeviceProcAddr"));
}
| 36.634783 | 204 | 0.733919 | mosra |
d4733c9efc905f1b6dfc769ea7e49836be28cbca | 7,594 | cpp | C++ | src/ClassOverviewVisitor.cpp | Gregofi/metrics | a8da292a98b66a36329f1e5c9423ec01d86c07a1 | [
"MIT"
] | null | null | null | src/ClassOverviewVisitor.cpp | Gregofi/metrics | a8da292a98b66a36329f1e5c9423ec01d86c07a1 | [
"MIT"
] | 1 | 2022-02-05T09:52:40.000Z | 2022-02-05T09:52:40.000Z | src/ClassOverviewVisitor.cpp | Gregofi/metrics | a8da292a98b66a36329f1e5c9423ec01d86c07a1 | [
"MIT"
] | null | null | null | #include "include/metrics/ClassOverviewVisitor.hpp"
#include "include/Logging.hpp"
#include "include/ASTMatcherVisitor.hpp"
#include "include/Utility.hpp"
bool ClassOverviewVisitor::VisitCXXRecordDecl(clang::CXXRecordDecl *decl)
{
/* Skip declarations that have no body and that aren't in main file */
if(!decl || !decl->isThisDeclarationADefinition() || ctx->getSourceManager().isInSystemHeader(decl->getLocation())
/* Also skip declarations which represents lambdas and classes that we already added(this happens if they are
* included from multiple files */
|| decl->isLambda() || classes.count(decl->getQualifiedNameAsString())
|| (!decl->isClass() && !decl->isStruct()))
return true;
/* Create new class in map, this is important because if there is an empty class (class A{};), it
* wouldn't be added otherwise */
if(!classes.count(decl->getQualifiedNameAsString()))
classes[decl->getQualifiedNameAsString()];
for(const auto &base : decl->bases())
{
/* Base can also be template argument, only count if its concrete class */
if(base.getType()->getAsCXXRecordDecl())
{
classes[base.getType()->getAsCXXRecordDecl()->getQualifiedNameAsString()].children_count += 1;
classes[decl->getQualifiedNameAsString()].inheritance_chain.emplace_back(base.getType()->getAsCXXRecordDecl()->getQualifiedNameAsString());
}
}
CalculateLorKiddMetrics(decl);
return true;
}
bool ClassOverviewVisitor::VisitCXXMethodDecl(clang::CXXMethodDecl *decl)
{
if(!decl || !decl->isThisDeclarationADefinition()
|| ctx->getSourceManager().isInSystemHeader(decl->getLocation()) || decl->getParent()->isLambda())
return true;
ASTMatcherVisitor vis(ctx);
MethodCallback callback(decl->getParent()->getQualifiedNameAsString(), &classes);
vis.AddMatchers({cxxMemberCallExpr().bind("member_call"), memberExpr().bind("member_access")}, &callback);
vis.TraverseDecl(decl);
classes[decl->getParent()->getQualifiedNameAsString()].functions.emplace_back(callback.GetInstanceVars());
auto vars = callback.GetInstanceVars();
return true;
}
int ClassOverviewVisitor::GetInheritanceChainLen(const std::string &s) const
{
const auto &chain = classes.at(s).inheritance_chain;
if(chain.empty())
return 0;
int res = 0;
for(const auto &c : chain)
res = std::max(GetInheritanceChainLen(c) + 1, res);
return res;
}
bool ClassOverviewVisitor::Similar(const std::set<std::string> &s1, const std::set<std::string> &s2)
{
for(auto it1 = s1.begin(), it2 = s2.begin(); it1 != s1.end() && it2 != s2.end();)
{
if(*it1 == *it2)
return true;
if(*it1 < *it2)
++it1;
else
++it2;
}
return false;
}
int ClassOverviewVisitor::LackOfCohesion(const std::string &s) const
{
auto c = classes.at(s);
c.functions.size();
int LOC = 0;
for(size_t i = 0; i < c.functions.size(); ++ i)
for(size_t j = i + 1; j < c.functions.size(); ++ j)
LOC += Similar(c.functions[i], c.functions[j]) ? -1 : 1;
return std::max(LOC, 0);
}
void MethodCallback::run(const MatchFinder::MatchResult &Result)
{
if(const auto *call = Result.Nodes.getNodeAs<CXXMemberCallExpr>("member_call"))
{
/* If this class calls method from other class its coupled with it. Check if the called
* method is from other class then this one */
if(const auto &s = call->getMethodDecl()->getParent()->getQualifiedNameAsString(); s != currClass)
{
(*classes)[currClass].fan_in.insert(s);
(*classes)[s].fan_out.insert(currClass);
}
}
if(const auto *access = Result.Nodes.getNodeAs<MemberExpr>("member_access"))
{
/* Check if member is from CXXClass (it can also be from enum or union) */
if(access->getMemberDecl()->isCXXClassMember())
{
const FieldDecl *d = llvm::dyn_cast<FieldDecl>(access->getMemberDecl());
if(d)
{
std::string parent_name = d->getParent()->getQualifiedNameAsString();
/* Get id of the class that the member belongs to, check its this class id */
if(parent_name == currClass)
{
instance_vars.insert(d->getNameAsString());
}
}
}
}
}
void ClassOverviewVisitor::CalculateLorKiddMetrics(clang::CXXRecordDecl *decl)
{
auto name = decl->getQualifiedNameAsString();
for(const auto &m : decl->methods())
{
if(!m->isDefaulted())
{
classes[name].methods_count += 1;
classes[name].public_methods_count += m->getAccess() == clang::AccessSpecifier::AS_public;
classes[name].overriden_methods_count += !m->overridden_methods().empty();
}
}
for(const auto &d: decl->fields())
{
if(d->isCXXInstanceMember())
{
classes[name].public_instance_vars_count += d->getAccess() == clang::AccessSpecifier::AS_public;
classes[name].instance_vars_count += 1;
}
}
}
void ClassOverviewVisitor::CalcMetrics(clang::ASTContext *ctx)
{
this->ctx = ctx;
TraverseDecl(ctx->getTranslationUnitDecl());
this->ctx = nullptr;
}
std::ostream &ClassOverviewVisitor::Export(const std::string &s, std::ostream &os) const
{
const auto& c = classes.at(s);
os << "Size:\n"
<< " Number of methods: " << c.methods_count << ", " << c.public_methods_count << " are public.\n"
<< " Number of attributes: " << c.instance_vars_count << ", " << c.public_instance_vars_count << " are public.\n"
<< "\n"
<< "Inheritance:\n"
<< " Number of children: " << c.children_count << "\n"
<< " Longest inheritance chain length: " << GetInheritanceChainLen(s) << "\n"
<< " Overriden methods: " << c.overriden_methods_count << "\n"
<< "Other:\n"
<< " fan in: " << c.fan_in.size() << "\n"
<< " fan out: " << c.fan_out.size() << "\n"
<< " Lack of cohesion: " << LackOfCohesion(s) << "\n";
return os;
}
template <typename T>
size_t UnionSize(const std::set<T> &s1, const std::set<T> s2)
{
std::vector<T> res;
std::set_union(s1.begin(), s1.end(), s2.begin(), s2.end(), std::back_inserter(res));
return res.size();
}
std::ostream &ClassOverviewVisitor::ExportXML(const std::string &s, std::ostream &os) const
{
const auto& c = classes.at(s);
os << Tag("size",
"\n"
+ Tag("methods", c.methods_count)
+ Tag("public_methods", c.public_methods_count)
+ Tag("attributes", c.instance_vars_count)
+ Tag("public_attributes", c.public_instance_vars_count))
<< Tag("inheritance",
"\n"
+ Tag("children", c.children_count)
+ Tag("inheritance_chain", GetInheritanceChainLen(s))
+ Tag("overriden_methods", c.overriden_methods_count))
<< Tag("other",
"\n"
+ Tag("fan_in", c.fan_in.size())
+ Tag("fan_out", c.fan_out.size())
+ Tag("coupling", UnionSize(c.fan_in, c.fan_out))
+ Tag("lack_of_cohesion", LackOfCohesion(s)));
return os;
}
bool ClassOverviewVisitor::TraverseDecl(clang::Decl *decl)
{
/* Skip files that are in system files */
if(!decl || ctx->getSourceManager().isInSystemHeader(decl->getLocation()))
return true;
return RecursiveASTVisitor::TraverseDecl(decl);
} | 37.97 | 151 | 0.613642 | Gregofi |
d473b02889735c9d1c07fce5cd2f55f0a3572637 | 13,568 | cpp | C++ | src/Core/Unicode.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | src/Core/Unicode.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | null | null | null | src/Core/Unicode.cpp | akumetsuv/flood | e0d6647df9b7fac72443a0f65c0003b0ead7ed3a | [
"BSD-2-Clause"
] | 1 | 2021-05-23T16:33:11.000Z | 2021-05-23T16:33:11.000Z | /* ================================================================ */
/*
File: ConvertUTF.C
Author: Mark E. Davis
Copyright (C) 1994 Taligent, Inc. All rights reserved.
This code is copyrighted. Under the copyright laws, this code may not
be copied, in whole or part, without prior written consent of Taligent.
Taligent grants the right to use or reprint this code as long as this
ENTIRE copyright notice is reproduced in the code or reproduction.
The code is provided AS-IS, AND TALIGENT DISCLAIMS ALL WARRANTIES,
EITHER EXPRESS OR IMPLIED, INCLUDING, BUT NOT LIMITED TO IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. IN
NO EVENT WILL TALIGENT BE LIABLE FOR ANY DAMAGES WHATSOEVER (INCLUDING,
WITHOUT LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS
INTERRUPTION, LOSS OF BUSINESS INFORMATION, OR OTHER PECUNIARY
LOSS) ARISING OUT OF THE USE OR INABILITY TO USE THIS CODE, EVEN
IF TALIGENT HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES.
BECAUSE SOME STATES DO NOT ALLOW THE EXCLUSION OR LIMITATION OF
LIABILITY FOR CONSEQUENTIAL OR INCIDENTAL DAMAGES, THE ABOVE
LIMITATION MAY NOT APPLY TO YOU.
RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the
government is subject to restrictions as set forth in subparagraph
(c)(l)(ii) of the Rights in Technical Data and Computer Software
clause at DFARS 252.227-7013 and FAR 52.227-19.
This code may be protected by one or more U.S. and International
Patents.
TRADEMARKS: Taligent and the Taligent Design Mark are registered
trademarks of Taligent, Inc.
*/
/* ================================================================ */
#include "Core/API.h"
#include "Core/Unicode.h"
#ifdef COMPILER_MSVC
#pragma warning(disable: 4244)
#endif
/* ================================================================ */
static const int halfShift = 10;
static const UCS4 halfBase = 0x0010000UL;
static const UCS4 halfMask = 0x3FFUL;
static const UCS4 kSurrogateHighStart = 0xD800UL;
static const UCS4 kSurrogateHighEnd = 0xDBFFUL;
static const UCS4 kSurrogateLowStart = 0xDC00UL;
static const UCS4 kSurrogateLowEnd = 0xDFFFUL;
/* ================================================================ */
UnicodeConversionResult::Enum
ConvertUCS4toUTF16(UCS4** sourceStart, const UCS4* sourceEnd,
UTF16** targetStart, const UTF16* targetEnd)
{
UnicodeConversionResult::Enum result = UnicodeConversionResult::OK;
register UCS4* source = *sourceStart;
register UTF16* target = *targetStart;
while (source < sourceEnd) {
register UCS4 ch;
if (target >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
ch = *source++;
if (ch <= kMaximumUCS2) {
*target++ = ch;
} else if (ch > kMaximumUTF16) {
*target++ = kReplacementCharacter;
} else {
if (target + 1 >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
ch -= halfBase;
*target++ = (ch >> halfShift) + kSurrogateHighStart;
*target++ = (ch & halfMask) + kSurrogateLowStart;
};
};
*sourceStart = source;
*targetStart = target;
return result;
};
/* ================================================================ */
UnicodeConversionResult::Enum ConvertUTF16toUCS4(UTF16** sourceStart, UTF16* sourceEnd,
UCS4** targetStart, const UCS4* targetEnd)
{
UnicodeConversionResult::Enum result = UnicodeConversionResult::OK;
register UTF16* source = *sourceStart;
register UCS4* target = *targetStart;
while (source < sourceEnd) {
register UCS4 ch;
ch = *source++;
if (ch >= kSurrogateHighStart &&
ch <= kSurrogateHighEnd &&
source < sourceEnd) {
register UCS4 ch2 = *source;
if (ch2 >= kSurrogateLowStart && ch2 <= kSurrogateLowEnd) {
ch = ((ch - kSurrogateHighStart) << halfShift)
+ (ch2 - kSurrogateLowStart) + halfBase;
++source;
};
};
if (target >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
*target++ = ch;
};
*sourceStart = source;
*targetStart = target;
return result;
};
/* ================================================================ */
static UCS4 offsetsFromUTF8[6] = {
0x00000000UL, 0x00003080UL, 0x000E2080UL,
0x03C82080UL, 0xFA082080UL, 0x82082080UL
};
static char bytesFromUTF8[256] = {
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 3,3,3,3,3,3,3,3,4,4,4,4,5,5,5,5
};
static UTF8 firstByteMark[7] = {0x00, 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC};
/* ================================================================ */
/* This code is similar in effect to making successive calls on the
mbtowc and wctomb routines in FSS-UTF. However, it is considerably
different in code:
* it is adapted to be consistent with UTF16,
* the interface converts a whole buffer to avoid function-call overhead
* constants have been gathered.
* loops & conditionals have been removed as much as possible for
efficiency, in favor of drop-through switch statements.
*/
/* ================================================================ */
int NSConvertUTF16toUTF8(unichar **sourceStart,
const unichar *sourceEnd,
unsigned char **targetStart,
const unsigned char *targetEnd)
{
UnicodeConversionResult::Enum result = UnicodeConversionResult::OK;
register UTF16* source = *sourceStart;
register UTF8* target = *targetStart;
while (source < sourceEnd) {
register UCS4 ch;
register unsigned short bytesToWrite = 0;
register const UCS4 byteMask = 0xBF;
register const UCS4 byteMark = 0x80;
ch = *source++;
if (ch >= kSurrogateHighStart && ch <= kSurrogateHighEnd
&& source < sourceEnd) {
register UCS4 ch2 = *source;
if (ch2 >= kSurrogateLowStart && ch2 <= kSurrogateLowEnd) {
ch = ((ch - kSurrogateHighStart) << halfShift)
+ (ch2 - kSurrogateLowStart) + halfBase;
++source;
};
};
if (ch < 0x80) { bytesToWrite = 1;
} else if (ch < 0x800) { bytesToWrite = 2;
} else if (ch < 0x10000) { bytesToWrite = 3;
} else if (ch < 0x200000) { bytesToWrite = 4;
} else if (ch < 0x4000000) { bytesToWrite = 5;
} else if (ch <= kMaximumUCS4){ bytesToWrite = 6;
} else { bytesToWrite = 2;
ch = kReplacementCharacter;
}; /* I wish there were a smart way to avoid this conditional */
target += bytesToWrite;
if (target > targetEnd) {
target -= bytesToWrite; result = UnicodeConversionResult::TargetExhausted; break;
};
switch (bytesToWrite) { /* note: code falls through cases! */
case 6: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 5: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 4: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 3: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 2: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 1: *--target = ch | firstByteMark[bytesToWrite];
};
target += bytesToWrite;
};
*sourceStart = source;
*targetStart = target;
return result;
};
/* ================================================================ */
int NSConvertUTF8toUTF16(unsigned char **sourceStart, unsigned char *sourceEnd,
unichar **targetStart, const unichar *targetEnd)
{
UnicodeConversionResult::Enum result = UnicodeConversionResult::OK;
register UTF8 *source = *sourceStart;
register UTF16 *target = *targetStart;
while (source < sourceEnd) {
register UCS4 ch = 0;
register unsigned short extraBytesToWrite = bytesFromUTF8[*source];
if (source + extraBytesToWrite > sourceEnd) {
result = UnicodeConversionResult::SourceExhausted; break;
};
switch(extraBytesToWrite) { /* note: code falls through cases! */
case 5: ch += *source++; ch <<= 6;
case 4: ch += *source++; ch <<= 6;
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
};
ch -= offsetsFromUTF8[extraBytesToWrite];
if (target >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
if (ch <= kMaximumUCS2) {
*target++ = ch;
} else if (ch > kMaximumUTF16) {
*target++ = kReplacementCharacter;
} else {
if (target + 1 >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
ch -= halfBase;
*target++ = (ch >> halfShift) + kSurrogateHighStart;
*target++ = (ch & halfMask) + kSurrogateLowStart;
};
};
*sourceStart = source;
*targetStart = target;
return result;
};
/* ================================================================ */
UnicodeConversionResult::Enum ConvertUCS4toUTF8 ( UCS4** sourceStart, const UCS4* sourceEnd,
UTF8** targetStart, const UTF8* targetEnd)
{
UnicodeConversionResult::Enum result = UnicodeConversionResult::OK;
register UCS4* source = *sourceStart;
register UTF8* target = *targetStart;
while (source < sourceEnd) {
register UCS4 ch;
register unsigned short bytesToWrite = 0;
register const UCS4 byteMask = 0xBF;
register const UCS4 byteMark = 0x80;
ch = *source++;
if (ch >= kSurrogateHighStart && ch <= kSurrogateHighEnd
&& source < sourceEnd) {
register UCS4 ch2 = *source;
if (ch2 >= kSurrogateLowStart && ch2 <= kSurrogateLowEnd) {
ch = ((ch - kSurrogateHighStart) << halfShift)
+ (ch2 - kSurrogateLowStart) + halfBase;
++source;
};
};
if (ch < 0x80) { bytesToWrite = 1;
} else if (ch < 0x800) { bytesToWrite = 2;
} else if (ch < 0x10000) { bytesToWrite = 3;
} else if (ch < 0x200000) { bytesToWrite = 4;
} else if (ch < 0x4000000) { bytesToWrite = 5;
} else if (ch <= kMaximumUCS4){ bytesToWrite = 6;
} else { bytesToWrite = 2;
ch = kReplacementCharacter;
}; /* I wish there were a smart way to avoid this conditional */
target += bytesToWrite;
if (target > targetEnd) {
target -= bytesToWrite; result = UnicodeConversionResult::TargetExhausted; break;
};
switch (bytesToWrite) { /* note: code falls through cases! */
case 6: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 5: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 4: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 3: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 2: *--target = (ch | byteMark) & byteMask; ch >>= 6;
case 1: *--target = ch | firstByteMark[bytesToWrite];
};
target += bytesToWrite;
};
*sourceStart = source;
*targetStart = target;
return result;
};
/* ================================================================ */
UnicodeConversionResult::Enum ConvertUTF8toUCS4 (UTF8** sourceStart, UTF8* sourceEnd,
UCS4** targetStart, const UCS4* targetEnd)
{
UnicodeConversionResult::Enum result = UnicodeConversionResult::OK;
register UTF8* source = *sourceStart;
register UCS4* target = *targetStart;
while (source < sourceEnd) {
register UCS4 ch = 0;
register unsigned short extraBytesToWrite = bytesFromUTF8[*source];
if (source + extraBytesToWrite > sourceEnd) {
result = UnicodeConversionResult::SourceExhausted; break;
};
switch(extraBytesToWrite) { /* note: code falls through cases! */
case 5: ch += *source++; ch <<= 6;
case 4: ch += *source++; ch <<= 6;
case 3: ch += *source++; ch <<= 6;
case 2: ch += *source++; ch <<= 6;
case 1: ch += *source++; ch <<= 6;
case 0: ch += *source++;
};
ch -= offsetsFromUTF8[extraBytesToWrite];
if (target >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
if (ch <= kMaximumUCS2) {
*target++ = ch;
} else if (ch > kMaximumUCS4) {
*target++ = kReplacementCharacter;
} else {
if (target + 1 >= targetEnd) {
result = UnicodeConversionResult::TargetExhausted; break;
};
ch -= halfBase;
*target++ = (ch >> halfShift) + kSurrogateHighStart;
*target++ = (ch & halfMask) + kSurrogateLowStart;
};
};
*sourceStart = source;
*targetStart = target;
return result;
};
| 39.327536 | 94 | 0.568028 | akumetsuv |
d473bb37ac3a542f4099d8a3968beb3cc1f8dca6 | 552 | cpp | C++ | BAC_2nd/ch10/UVa12716.cpp | Anyrainel/aoapc-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 3 | 2017-08-15T06:00:01.000Z | 2018-12-10T09:05:53.000Z | BAC_2nd/ch10/UVa12716.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | null | null | null | BAC_2nd/ch10/UVa12716.cpp | Anyrainel/aoapc-related-code | e787a01380698fb9236d933462052f97b20e6132 | [
"Apache-2.0"
] | 2 | 2017-09-16T18:46:27.000Z | 2018-05-22T05:42:03.000Z | // UVa12716 GCD XOR
// Rujia Liu
#include<cstdio>
#include<cstring>
using namespace std;
const int M = 30000000;
int cnt[M+1], sum[M+1];
void init() {
memset(cnt, 0, sizeof(cnt));
for(int c = 1; c <= M; c++)
for(int a = c*2; a <= M; a += c) {
int b = a - c;
if(c == (a ^ b)) cnt[a]++;
}
sum[0] = 0;
for(int i = 1; i <= M; i++) sum[i] = sum[i-1] + cnt[i];
}
int main() {
init();
int T, n, kase = 0;
scanf("%d", &T);
while(T--) {
scanf("%d", &n);
printf("Case %d: %d\n", ++kase, sum[n]);
}
return 0;
}
| 17.25 | 57 | 0.471014 | Anyrainel |
d4794305cc45ecc8e409faa83751a9df0757808c | 5,577 | cpp | C++ | tools/profiler/Profiler.cpp | prozum/SPPL | 77de5db600a89b84bc8e6e851c9a766cd5203ce2 | [
"MIT"
] | 4 | 2016-03-17T19:38:51.000Z | 2016-10-30T18:54:17.000Z | tools/profiler/Profiler.cpp | prozum/sppl | 77de5db600a89b84bc8e6e851c9a766cd5203ce2 | [
"MIT"
] | null | null | null | tools/profiler/Profiler.cpp | prozum/sppl | 77de5db600a89b84bc8e6e851c9a766cd5203ce2 | [
"MIT"
] | null | null | null | #include "Profiler.h"
#include "DataGenerator.h"
#include <random>
using namespace interpreter;
using namespace common;
using namespace std;
namespace profiler {
Profiler::Profiler(Program &node) {
this->node = &node;
}
void Profiler::instruction_time_profile(int runs)
{
mode = INSTRUCTION_TIME;
node->accept(*this);
}
void Profiler::user_time_profile(int runs)
{
mode = USER_TIME;
node->accept(*this);
}
void Profiler::visit(Program &node)
{
for (auto f : node.funcs) {
f->accept(*this);
}
}
void Profiler::visit(Function &node)
{
for (auto c : node.cases) {
c->accept(*this);
}
}
void Profiler::visit(Case &node)
{
if (mode == INSTRUCTION_TIME) {
} else if (mode == USER_TIME) {
// tbd
return;
}
}
void Profiler::visit(Or &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool&)node.left->val).value || ((Bool&)node.right->val).value);
}
void Profiler::visit(And &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value && ((Bool &)node.right->val).value);
}
void Profiler::visit(Equal &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value == ((Bool &)node.right->val).value);
}
void Profiler::visit(NotEqual &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value != ((Bool &)node.right->val).value);
}
void Profiler::visit(Lesser &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value < ((Bool &)node.left->val).value);
}
void Profiler::visit(LesserEq &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value <= ((Bool &)node.left->val).value);
}
void Profiler::visit(Greater &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value > ((Bool &)node.left->val).value);
}
void Profiler::visit(GreaterEq &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value >= ((Bool &)node.left->val).value);
}
void Profiler::visit(Add &node)
{
node.left->accept(*this);
node.right->accept(*this);
node.val = new Bool(((Bool &)node.left->val).value >= ((Bool &)node.left->val).value);
}
void Profiler::visit(Sub &node)
{
node.left->accept(*this);
node.right->accept(*this);
if (node.left->node_type->type == Types::INT) {
node.val = new Int(((Int &)node.left->val).value - ((Int &)node.left->val).value);
} else {
node.val = new Float(((Float &)node.left->val).value - ((Float &)node.left->val).value);
}
}
void Profiler::visit(Mul &node)
{
node.left->accept(*this);
node.right->accept(*this);
if (node.left->node_type->type == Types::INT) {
node.val = new Int(((Int &)node.left->val).value * ((Int &)node.left->val).value);
} else {
node.val = new Float(((Float &)node.left->val).value * ((Float &)node.left->val).value);
}
}
void Profiler::visit(Div &node)
{
node.left->accept(*this);
node.right->accept(*this);
if (node.left->node_type->type == Types::INT) {
node.val = new Int(((Int &)node.left->val).value / ((Int &)node.left->val).value);
} else {
node.val = new Float(((Float &)node.left->val).value / ((Float &)node.left->val).value);
}
}
void Profiler::visit(Mod &node)
{
if (node.left->node_type->type == Types::INT) {
node.val = new Int(((Int &)node.left->val).value % ((Int &)node.left->val).value);
} else {
//node.val = new Float(((Float &)node.left->val).value % ((Float &)node.left->val).value);
}
}
void Profiler::visit(ListAdd &node)
{
}
void Profiler::visit(Par &node)
{
node.child->accept(*this);
node.val = node.child;
}
void Profiler::visit(Not &node)
{
node.child->accept(*this);
node.val = new Bool(!((Bool &)node.child->val).value);
}
void Profiler::visit(ListPattern &node)
{
}
void Profiler::visit(TuplePattern &node)
{
}
void Profiler::visit(ListSplit &node)
{
}
void Profiler::visit(Int &node)
{
node.val = &node;
}
void Profiler::visit(Float &node)
{
node.val = &node;
}
void Profiler::visit(Bool &node)
{
node.val = &node;
}
void Profiler::visit(Char &node)
{
node.val = &node;
}
void Profiler::visit(String &node)
{
node.val = &node;
}
void Profiler::visit(List &node)
{
node.val = &node;
}
void Profiler::visit(Id &node)
{
node.val = &node;
}
void Profiler::visit(Call &node)
{
node.val = &node;
}
void Profiler::visit(Type &node)
{
//node.val = &node;
}
}
| 22.39759 | 102 | 0.523938 | prozum |
d47b9c18a4ec755d80009918d43ad3a5a0a0627c | 902 | cpp | C++ | rw_rh_engine_lib/rw_engine/rw_api_injectors.cpp | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 232 | 2016-08-29T00:33:32.000Z | 2022-03-29T22:39:51.000Z | rw_rh_engine_lib/rw_engine/rw_api_injectors.cpp | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 10 | 2021-01-02T12:40:49.000Z | 2021-08-31T06:31:04.000Z | rw_rh_engine_lib/rw_engine/rw_api_injectors.cpp | petrgeorgievsky/gtaRenderHook | 124358410c3edca56de26381e239ca29aa6dc1cc | [
"MIT"
] | 40 | 2017-12-18T06:14:39.000Z | 2022-01-29T16:35:23.000Z | #include "rw_api_injectors.h"
#include "common_headers.h"
#include "rw_raster/rw_raster.h"
#include "rw_stream/rw_stream.h"
#include "rw_texture/rw_texture.h"
namespace rh::rw::engine
{
RwTexture *RwTextureSetNameStub( RwTexture *texture, const char *name )
{
strncpy_s( texture->name, name, strlen( name ) );
return texture;
}
RwTexture *RwTextureSetMaskStub( RwTexture *texture, const char *name )
{
strncpy_s( texture->mask, name, strlen( name ) );
return texture;
}
RwTexturePointerTable g_pTexture_API = { RwTextureCreate, RwTextureSetNameStub,
RwTextureSetMaskStub };
RwIOPointerTable g_pIO_API = { RwStreamFindChunk, RwStreamRead };
RwRasterPointerTable g_pRaster_API = {
reinterpret_cast<RwRasterCreate_FN>( RwRasterCreate ),
reinterpret_cast<RwRasterDestroy_FN>( RwRasterDestroy ) };
} // namespace rh::rw::engine | 31.103448 | 79 | 0.717295 | petrgeorgievsky |
d47bc282383b0685fcc2ac9c7acd94cc5b18ef88 | 24,227 | cpp | C++ | src/vm/hosting.cpp | mans0954/debian-dotnet-coreclr | 5e42f510f19534800c8271bf83a9bf5e0c730b84 | [
"MIT"
] | 6 | 2017-09-22T06:55:45.000Z | 2021-07-02T07:07:08.000Z | src/vm/hosting.cpp | xets007/debian-dotnet-coreclr | 5e42f510f19534800c8271bf83a9bf5e0c730b84 | [
"MIT"
] | 2 | 2017-09-23T08:21:05.000Z | 2017-09-27T03:31:06.000Z | src/vm/hosting.cpp | xets007/debian-dotnet-coreclr | 5e42f510f19534800c8271bf83a9bf5e0c730b84 | [
"MIT"
] | 2 | 2019-02-03T12:50:05.000Z | 2021-11-10T07:28:14.000Z | // Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//
//
#include "common.h"
#include "hosting.h"
#include "mscoree.h"
#include "mscoreepriv.h"
#include "corhost.h"
#include "threads.h"
#define countof(x) (sizeof(x) / sizeof(x[0]))
//Copied from winbase.h
#ifndef STARTF_TITLEISAPPID
#define STARTF_TITLEISAPPID 0x00001000
#endif
#ifndef STARTF_PREVENTPINNING
#define STARTF_PREVENTPINNING 0x00002000
#endif
//Flags encoded in the first parameter of CorLaunchApplication.
#define MASK_NOTPINNABLE 0x80000000
#define MASK_HOSTTYPE 0x00000003
#define MASK_DONT_SHOW_INSTALL_DIALOG 0x00000100
#ifdef _DEBUG
// This function adds a static annotation read by SCAN to indicate HOST_CALLS. Its
// purpose is to be called from the BEGIN_SO_TOLERANT_CODE_CALLING_HOST macro, to
// effectively mark all functions that use BEGIN_SO_TOLERANT_CODE_CALLING_HOST as being
// HOST_CALLS. If you hit a SCAN violation that references AddHostCallsStaticMarker, then
// you have a function marked as HOST_NOCALLS that eventually calls into a function that
// uses BEGIN_SO_TOLERANT_CODE_CALLING_HOST.
DEBUG_NOINLINE void AddHostCallsStaticMarker()
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_SO_TOLERANT;
STATIC_CONTRACT_HOST_CALLS;
METHOD_CANNOT_BE_FOLDED_DEBUG;
}
#endif //_DEBUG
//
// memory management functions
//
// global debug only tracking utilities
#ifdef _DEBUG
static const LONG MaxGlobalAllocCount = 8;
class GlobalAllocStore {
public:
static void AddAlloc (LPVOID p)
{
LIMITED_METHOD_CONTRACT;
if (!p) {
return;
}
if (m_Disabled) {
return;
}
//InterlockedIncrement (&numMemWriter);
//if (CheckMemFree) {
// goto Return;
//}
//m_Count is number of allocation we've ever tried, it's OK to be bigger than
//size of m_Alloc[]
InterlockedIncrement (&m_Count);
//this is by no means an accurate record of heap allocation.
//the algorithm used here can't guarantee an allocation is saved in
//m_Alloc[] even there's enough free space. However this is only used
//for debugging purpose and most importantly, m_Count is accurate.
for (size_t n = 0; n < countof(m_Alloc); n ++) {
if (m_Alloc[n] == 0) {
if (InterlockedCompareExchangeT(&m_Alloc[n],p,0) == 0) {
return;
}
}
}
//InterlockedDecrement (&numMemWriter);
}
//this is called in non-host case where we don't care the free after
//alloc store is disabled
static BOOL RemoveAlloc (LPVOID p)
{
LIMITED_METHOD_CONTRACT;
if (m_Disabled)
{
return TRUE;
}
//decrement the counter even we might not find the allocation
//in m_Alloc. Because it's possible for an allocation not to be saved
//in the array
InterlockedDecrement (&m_Count);
// Binary search
for (size_t n = 0; n < countof(m_Alloc); n ++) {
if (m_Alloc[n] == p) {
m_Alloc[n] = 0;
return TRUE;
}
}
return FALSE;
}
//this is called in host case where if the store is disabled, we want to
//guarantee we don't try to free anything the host doesn't know about
static void ValidateFree(LPVOID p)
{
LIMITED_METHOD_CONTRACT;
if (p == 0) {
return;
}
if (m_Disabled) {
for (size_t n = 0; n < countof(m_Alloc); n ++) {
//there could be miss, because an allocation might not be saved
//in the array
if (m_Alloc[n] == p) {
_ASSERTE (!"Free a memory that host interface does not know");
return;
}
}
}
}
static void Validate()
{
LIMITED_METHOD_CONTRACT;
if (m_Count > MaxGlobalAllocCount) {
_ASSERTE (!"Using too many memory allocator before Host Interface is set up");
}
//while (numMemWriter != 0) {
// Sleep(5);
//}
//qsort (GlobalMemAddr, (MemAllocCount>MaxAllocCount)?MaxAllocCount:MemAllocCount, sizeof(LPVOID), MemAddrCompare);
}
static void Disable ()
{
LIMITED_METHOD_CONTRACT;
if (!m_Disabled)
{
// Let all threads know
InterlockedIncrement((LONG*)&m_Disabled);
}
}
private:
static BOOL m_Disabled;
static LPVOID m_Alloc[MaxGlobalAllocCount];
//m_Count is number of allocation we tried, it's legal to be bigger than
//size of m_Alloc[]
static LONG m_Count;
// static LONG numMemWriter = 0;
};
// used from corhost.cpp
void ValidateHostInterface()
{
WRAPPER_NO_CONTRACT;
GlobalAllocStore::Validate();
GlobalAllocStore::Disable();
}
void DisableGlobalAllocStore ()
{
WRAPPER_NO_CONTRACT;
GlobalAllocStore::Disable();
}
LPVOID GlobalAllocStore::m_Alloc[MaxGlobalAllocCount];
LONG GlobalAllocStore::m_Count = 0;
BOOL GlobalAllocStore::m_Disabled = FALSE;
#endif
HANDLE g_ExecutableHeapHandle = NULL;
#undef VirtualAlloc
LPVOID EEVirtualAlloc(LPVOID lpAddress, SIZE_T dwSize, DWORD flAllocationType, DWORD flProtect) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
#ifdef FAILPOINTS_ENABLED
if (RFS_HashStack ())
return NULL;
#endif
#ifdef _DEBUG
if (g_fEEStarted) {
_ASSERTE (!EEAllocationDisallowed());
}
_ASSERTE (lpAddress || (dwSize % g_SystemInfo.dwAllocationGranularity) == 0);
#endif
{
LPVOID p = NULL;
#ifdef _DEBUG
{
DEBUG_ONLY_REGION();
if (lpAddress == NULL && (flAllocationType & MEM_RESERVE) != 0 && PEDecoder::GetForceRelocs())
{
#ifdef _WIN64
// Try to allocate memory all over the place when we are stressing relocations on _WIN64.
// This will make sure that we generate jump stubs correctly among other things.
static BYTE* ptr = (BYTE*)0x234560000;
ptr += 0x123450000;
// Wrap around
if (ptr < (BYTE *)BOT_MEMORY || ptr > (BYTE *)TOP_MEMORY)
{
// Make sure to keep the alignment of the ptr so that we are not
// trying the same places over and over again
ptr = (BYTE*)BOT_MEMORY + (((SIZE_T)ptr) & 0xFFFFFFFF);
}
p = ::VirtualAlloc(ptr, dwSize, flAllocationType, flProtect);
#else
// Allocate memory top to bottom to stress ngen fixups with LARGEADDRESSAWARE support.
p = ::VirtualAlloc(lpAddress, dwSize, flAllocationType | MEM_TOP_DOWN, flProtect);
#endif // _WIN64
}
}
#endif // _DEBUG
// Fall back to the default method if the forced relocation failed
if (p == NULL)
{
p = ::VirtualAlloc (lpAddress, dwSize, flAllocationType, flProtect);
}
#ifdef _DEBUG
GlobalAllocStore::AddAlloc (p);
#endif
if(p == NULL){
STRESS_LOG_OOM_STACK(dwSize);
}
return p;
}
}
#define VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect) Dont_Use_VirtualAlloc(lpAddress, dwSize, flAllocationType, flProtect)
#undef VirtualFree
BOOL EEVirtualFree(LPVOID lpAddress, SIZE_T dwSize, DWORD dwFreeType) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
BOOL retVal = FALSE;
{
#ifdef _DEBUG
GlobalAllocStore::RemoveAlloc (lpAddress);
#endif
retVal = (BOOL)(BYTE)::VirtualFree (lpAddress, dwSize, dwFreeType);
}
return retVal;
}
#define VirtualFree(lpAddress, dwSize, dwFreeType) Dont_Use_VirtualFree(lpAddress, dwSize, dwFreeType)
#undef VirtualQuery
SIZE_T EEVirtualQuery(LPCVOID lpAddress, PMEMORY_BASIC_INFORMATION lpBuffer, SIZE_T dwLength)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
{
return ::VirtualQuery(lpAddress, lpBuffer, dwLength);
}
}
#define VirtualQuery(lpAddress, lpBuffer, dwLength) Dont_Use_VirtualQuery(lpAddress, lpBuffer, dwLength)
#undef VirtualProtect
BOOL EEVirtualProtect(LPVOID lpAddress, SIZE_T dwSize, DWORD flNewProtect, PDWORD lpflOldProtect)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
{
return ::VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect);
}
}
#define VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect) Dont_Use_VirtualProtect(lpAddress, dwSize, flNewProtect, lpflOldProtect)
#undef GetProcessHeap
HANDLE EEGetProcessHeap()
{
// Note: this can be called a little early for real contracts, so we use static contracts instead.
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_SO_TOLERANT;
{
return GetProcessHeap();
}
}
#define GetProcessHeap() Dont_Use_GetProcessHeap()
#undef HeapCreate
HANDLE EEHeapCreate(DWORD flOptions, SIZE_T dwInitialSize, SIZE_T dwMaximumSize)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
#ifndef FEATURE_PAL
{
return ::HeapCreate(flOptions, dwInitialSize, dwMaximumSize);
}
#else // !FEATURE_PAL
return NULL;
#endif // !FEATURE_PAL
}
#define HeapCreate(flOptions, dwInitialSize, dwMaximumSize) Dont_Use_HeapCreate(flOptions, dwInitialSize, dwMaximumSize)
#undef HeapDestroy
BOOL EEHeapDestroy(HANDLE hHeap)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
}
CONTRACTL_END;
#ifndef FEATURE_PAL
{
return ::HeapDestroy(hHeap);
}
#else // !FEATURE_PAL
UNREACHABLE();
#endif // !FEATURE_PAL
}
#define HeapDestroy(hHeap) Dont_Use_HeapDestroy(hHeap)
#ifdef _DEBUG
#ifdef _TARGET_X86_
#define OS_HEAP_ALIGN 8
#else
#define OS_HEAP_ALIGN 16
#endif
#endif
#undef HeapAlloc
LPVOID EEHeapAlloc(HANDLE hHeap, DWORD dwFlags, SIZE_T dwBytes)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_SO_INTOLERANT;
#ifdef FAILPOINTS_ENABLED
if (RFS_HashStack ())
return NULL;
#endif
{
LPVOID p = NULL;
#ifdef _DEBUG
// Store the heap handle to detect heap contamination
p = ::HeapAlloc (hHeap, dwFlags, dwBytes + OS_HEAP_ALIGN);
if(p)
{
*((HANDLE*)p) = hHeap;
p = (BYTE*)p + OS_HEAP_ALIGN;
}
GlobalAllocStore::AddAlloc (p);
#else
p = ::HeapAlloc (hHeap, dwFlags, dwBytes);
#endif
if(p == NULL
//under OOM, we might not be able to get Execution Engine and can't access stress log
&& GetExecutionEngine ()
// If we have not created StressLog ring buffer, we should not try to use it.
// StressLog is going to do a memory allocation. We may enter an endless loop.
&& ClrFlsGetValue(TlsIdx_StressLog) != NULL )
{
STRESS_LOG_OOM_STACK(dwBytes);
}
return p;
}
}
#define HeapAlloc(hHeap, dwFlags, dwBytes) Dont_Use_HeapAlloc(hHeap, dwFlags, dwBytes)
LPVOID EEHeapAllocInProcessHeap(DWORD dwFlags, SIZE_T dwBytes)
{
WRAPPER_NO_CONTRACT;
STATIC_CONTRACT_SO_TOLERANT;
#ifdef _DEBUG
// Check whether (indispensable) implicit casting in ClrAllocInProcessHeapBootstrap is safe.
static FastAllocInProcessHeapFunc pFunc = EEHeapAllocInProcessHeap;
#endif
static HANDLE ProcessHeap = NULL;
// We need to guarentee a very small stack consumption in allocating. And we can't allow
// an SO to happen while calling into the host. This will force a hard SO which is OK because
// we shouldn't ever get this close inside the EE in SO-intolerant code, so this should
// only fail if we call directly in from outside the EE, such as the JIT.
MINIMAL_STACK_PROBE_CHECK_THREAD(GetThread());
if (ProcessHeap == NULL)
ProcessHeap = EEGetProcessHeap();
return EEHeapAlloc(ProcessHeap,dwFlags,dwBytes);
}
#undef HeapFree
BOOL EEHeapFree(HANDLE hHeap, DWORD dwFlags, LPVOID lpMem)
{
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_SO_TOLERANT;
// @todo - Need a backout validation here.
CONTRACT_VIOLATION(SOToleranceViolation);
BOOL retVal = FALSE;
{
#ifdef _DEBUG
GlobalAllocStore::RemoveAlloc (lpMem);
// Check the heap handle to detect heap contamination
lpMem = (BYTE*)lpMem - OS_HEAP_ALIGN;
HANDLE storedHeapHandle = *((HANDLE*)lpMem);
if(storedHeapHandle != hHeap)
_ASSERTE(!"Heap contamination detected! HeapFree was called on a heap other than the one that memory was allocated from.\n"
"Possible cause: you used new (executable) to allocate the memory, but didn't use DeleteExecutable() to free it.");
#endif
// DON'T REMOVE THIS SEEMINGLY USELESS CAST
//
// On AMD64 the OS HeapFree calls RtlFreeHeap which returns a 1byte
// BOOLEAN, HeapFree then doesn't correctly clean the return value
// so the other 3 bytes which come back can be junk and in that case
// this return value can never be false.
retVal = (BOOL)(BYTE)::HeapFree (hHeap, dwFlags, lpMem);
}
return retVal;
}
#define HeapFree(hHeap, dwFlags, lpMem) Dont_Use_HeapFree(hHeap, dwFlags, lpMem)
BOOL EEHeapFreeInProcessHeap(DWORD dwFlags, LPVOID lpMem)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_TOLERANT;
MODE_ANY;
}
CONTRACTL_END;
#ifdef _DEBUG
// Check whether (indispensable) implicit casting in ClrFreeInProcessHeapBootstrap is safe.
static FastFreeInProcessHeapFunc pFunc = EEHeapFreeInProcessHeap;
#endif
// Take a look at comment in EEHeapFree and EEHeapAllocInProcessHeap, obviously someone
// needs to take a little time to think more about this code.
//CONTRACT_VIOLATION(SOToleranceViolation);
static HANDLE ProcessHeap = NULL;
if (ProcessHeap == NULL)
ProcessHeap = EEGetProcessHeap();
return EEHeapFree(ProcessHeap,dwFlags,lpMem);
}
#undef HeapValidate
BOOL EEHeapValidate(HANDLE hHeap, DWORD dwFlags, LPCVOID lpMem) {
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
#ifndef FEATURE_PAL
{
return ::HeapValidate(hHeap, dwFlags, lpMem);
}
#else // !FEATURE_PAL
return TRUE;
#endif // !FEATURE_PAL
}
#define HeapValidate(hHeap, dwFlags, lpMem) Dont_Use_HeapValidate(hHeap, dwFlags, lpMem)
HANDLE EEGetProcessExecutableHeap() {
// Note: this can be called a little early for real contracts, so we use static contracts instead.
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_GC_NOTRIGGER;
#ifndef FEATURE_PAL
//
// Create the executable heap lazily
//
#undef HeapCreate
#undef HeapDestroy
if (g_ExecutableHeapHandle == NULL)
{
HANDLE ExecutableHeapHandle = HeapCreate(
HEAP_CREATE_ENABLE_EXECUTE, // heap allocation attributes
0, // initial heap size
0 // maximum heap size; 0 == growable
);
if (ExecutableHeapHandle == NULL)
return NULL;
HANDLE ExistingValue = InterlockedCompareExchangeT(&g_ExecutableHeapHandle, ExecutableHeapHandle, NULL);
if (ExistingValue != NULL)
{
HeapDestroy(ExecutableHeapHandle);
}
}
#define HeapCreate(flOptions, dwInitialSize, dwMaximumSize) Dont_Use_HeapCreate(flOptions, dwInitialSize, dwMaximumSize)
#define HeapDestroy(hHeap) Dont_Use_HeapDestroy(hHeap)
#else // !FEATURE_PAL
UNREACHABLE();
#endif // !FEATURE_PAL
// TODO: implement hosted executable heap
return g_ExecutableHeapHandle;
}
#undef SleepEx
#undef Sleep
DWORD EESleepEx(DWORD dwMilliseconds, BOOL bAlertable)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
DWORD res;
{
res = ::SleepEx(dwMilliseconds, bAlertable);
}
return res;
}
#define SleepEx(dwMilliseconds,bAlertable) \
Dont_Use_SleepEx(dwMilliseconds,bAlertable)
#define Sleep(a) Dont_Use_Sleep(a)
// non-zero return value if this function causes the OS to switch to another thread
// See file:spinlock.h#SwitchToThreadSpinning for an explanation of dwSwitchCount
BOOL __SwitchToThread (DWORD dwSleepMSec, DWORD dwSwitchCount)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
}
CONTRACTL_END;
return __DangerousSwitchToThread(dwSleepMSec, dwSwitchCount, FALSE);
}
#undef SleepEx
BOOL __DangerousSwitchToThread (DWORD dwSleepMSec, DWORD dwSwitchCount, BOOL goThroughOS)
{
// If you sleep for a long time, the thread should be in Preemptive GC mode.
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
MODE_ANY;
SO_TOLERANT;
PRECONDITION(dwSleepMSec < 10000 || GetThread() == NULL || !GetThread()->PreemptiveGCDisabled());
}
CONTRACTL_END;
if (dwSleepMSec > 0)
{
// when called with goThroughOS make sure to not call into the host. This function
// may be called from GetRuntimeFunctionCallback() which is called by the OS to determine
// the personality routine when it needs to unwind managed code off the stack. when this
// happens in the context of an SO we want to avoid calling into the host
if (goThroughOS)
::SleepEx(dwSleepMSec, FALSE);
else
ClrSleepEx(dwSleepMSec,FALSE);
return TRUE;
}
// In deciding when to insert sleeps, we wait until we have been spinning
// for a long time and then always sleep. The former is to let short perf-critical
// __SwitchToThread loops avoid context switches. The latter is to ensure
// that if many threads are spinning waiting for a lower-priority thread
// to run that they will eventually all be asleep at the same time.
//
// The specific values are derived from the NDP 2.0 SP1 fix: it waits for
// 8 million cycles of __SwitchToThread calls where each takes ~300-500,
// which means we should wait in the neighborhood of 25000 calls.
//
// As of early 2011, ARM CPUs are much slower, so we need a lower threshold.
// The following two values appear to yield roughly equivalent spin times
// on their respective platforms.
//
#ifdef _TARGET_ARM_
#define SLEEP_START_THRESHOLD (5 * 1024)
#else
#define SLEEP_START_THRESHOLD (32 * 1024)
#endif
_ASSERTE(CALLER_LIMITS_SPINNING < SLEEP_START_THRESHOLD);
if (dwSwitchCount >= SLEEP_START_THRESHOLD)
{
if (goThroughOS)
::SleepEx(1, FALSE);
else
ClrSleepEx(1, FALSE);
}
{
return SwitchToThread();
}
}
#define SleepEx(dwMilliseconds,bAlertable) \
Dont_Use_SleepEx(dwMilliseconds,bAlertable)
// Locking routines supplied by the EE to the other DLLs of the CLR. In a _DEBUG
// build of the EE, we poison the Crst as a poor man's attempt to do some argument
// validation.
#define POISON_BITS 3
static inline CRITSEC_COOKIE CrstToCookie(Crst * pCrst) {
LIMITED_METHOD_CONTRACT;
_ASSERTE((((uintptr_t) pCrst) & POISON_BITS) == 0);
#ifdef _DEBUG
if (pCrst)
{
pCrst = (Crst *) (((uintptr_t) pCrst) | POISON_BITS);
}
#endif
return (CRITSEC_COOKIE) pCrst;
}
static inline Crst *CookieToCrst(CRITSEC_COOKIE cookie) {
LIMITED_METHOD_CONTRACT;
_ASSERTE((((uintptr_t) cookie) & POISON_BITS) == POISON_BITS);
#ifdef _DEBUG
cookie = (CRITSEC_COOKIE) (((uintptr_t) cookie) & ~POISON_BITS);
#endif
return (Crst *) cookie;
}
CRITSEC_COOKIE EECreateCriticalSection(CrstType crstType, CrstFlags flags) {
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
}
CONTRACTL_END;
CRITSEC_COOKIE ret = NULL;
EX_TRY
{
// This may be controversial, but seems like the correct discipline. If the
// EE has called out to any other DLL of the CLR in cooperative mode, we
// arbitrarily force lock acquisition to occur in preemptive mode. See our
// treatment of AcquireLock below.
//_ASSERTE((flags & (CRST_UNSAFE_COOPGC | CRST_UNSAFE_ANYMODE)) == 0);
ret = CrstToCookie(new Crst(crstType, flags));
}
EX_CATCH
{
}
EX_END_CATCH(SwallowAllExceptions);
// Note: we'll return NULL if the create fails. That's a true NULL, not a poisoned NULL.
return ret;
}
void EEDeleteCriticalSection(CRITSEC_COOKIE cookie)
{
CONTRACTL
{
NOTHROW;
WRAPPER(GC_NOTRIGGER);
SO_TOLERANT;
}
CONTRACTL_END;
VALIDATE_BACKOUT_STACK_CONSUMPTION;
Crst *pCrst = CookieToCrst(cookie);
_ASSERTE(pCrst);
delete pCrst;
}
DEBUG_NOINLINE void EEEnterCriticalSection(CRITSEC_COOKIE cookie) {
// Entering a critical section has many different contracts
// depending on the flags used to initialize the critical section.
// See CrstBase::Enter() for the actual contract. It's much too
// complex to repeat here.
CONTRACTL
{
WRAPPER(THROWS);
WRAPPER(GC_TRIGGERS);
SO_INTOLERANT;
}
CONTRACTL_END;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
Crst *pCrst = CookieToCrst(cookie);
_ASSERTE(pCrst);
pCrst->Enter();
}
DEBUG_NOINLINE void EELeaveCriticalSection(CRITSEC_COOKIE cookie)
{
CONTRACTL
{
NOTHROW;
GC_NOTRIGGER;
SO_INTOLERANT;
}
CONTRACTL_END;
ANNOTATION_SPECIAL_HOLDER_CALLER_NEEDS_DYNAMIC_CONTRACT;
Crst *pCrst = CookieToCrst(cookie);
_ASSERTE(pCrst);
pCrst->Leave();
}
LPVOID EETlsGetValue(DWORD slot)
{
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_CANNOT_TAKE_LOCK;
STATIC_CONTRACT_SO_TOLERANT;
//
// @todo: we don't want TlsGetValue to throw, but CheckThreadState throws right now. Either modify
// CheckThreadState to not throw, or catch any exception and just return NULL.
//
//CONTRACT_VIOLATION(ThrowsViolation);
SCAN_IGNORE_THROW;
void **pTlsData = CExecutionEngine::CheckThreadState(slot, FALSE);
if (pTlsData)
return pTlsData[slot];
else
return NULL;
}
BOOL EETlsCheckValue(DWORD slot, LPVOID * pValue)
{
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_NOTHROW;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_SO_TOLERANT;
//
// @todo: we don't want TlsGetValue to throw, but CheckThreadState throws right now. Either modify
// CheckThreadState to not throw, or catch any exception and just return NULL.
//
//CONTRACT_VIOLATION(ThrowsViolation);
SCAN_IGNORE_THROW;
void **pTlsData = CExecutionEngine::CheckThreadState(slot, FALSE);
if (pTlsData)
{
*pValue = pTlsData[slot];
return TRUE;
}
return FALSE;
}
VOID EETlsSetValue(DWORD slot, LPVOID pData)
{
STATIC_CONTRACT_GC_NOTRIGGER;
STATIC_CONTRACT_THROWS;
STATIC_CONTRACT_MODE_ANY;
STATIC_CONTRACT_SO_TOLERANT;
void **pTlsData = CExecutionEngine::CheckThreadState(slot);
if (pTlsData) // Yes, CheckThreadState(slot, TRUE) can return NULL now.
{
pTlsData[slot] = pData;
}
}
BOOL EEAllocationDisallowed()
{
WRAPPER_NO_CONTRACT;
#ifdef _DEBUG
// On Debug build we make sure that a thread is not going to do memory allocation
// after it suspends another thread, since the another thread may be suspended while
// having OS Heap lock.
return !Thread::Debug_AllowCallout();
#else
return FALSE;
#endif
}
| 27.251969 | 144 | 0.660007 | mans0954 |
d47c4fdd486eec7ba372d2a56ae0b434fac6d0ba | 52,350 | cpp | C++ | lib/KSpace/KSpaceSolverElastic.cpp | xschrodingerscat/kspaceFirstOrder | 99f326d420a5488693bcf9fdd633d2eff7447cca | [
"RSA-MD"
] | null | null | null | lib/KSpace/KSpaceSolverElastic.cpp | xschrodingerscat/kspaceFirstOrder | 99f326d420a5488693bcf9fdd633d2eff7447cca | [
"RSA-MD"
] | null | null | null | lib/KSpace/KSpaceSolverElastic.cpp | xschrodingerscat/kspaceFirstOrder | 99f326d420a5488693bcf9fdd633d2eff7447cca | [
"RSA-MD"
] | null | null | null |
#include <KSpace/KSpaceSolver.h>
#include <KSpace/KInterp.h>
using std::ios;
/* Shortcut for Simulation dimensions. */
using SD = Parameters::SimulationDimension;
/* Shortcut for Matrix id in the container. */
using MI = MatrixContainer::MatrixIdx;
/* Shortcut for Output stream id in the container. */
using OI = OutputStreamContainer::OutputStreamIdx;
KSpaceSolverElastic::ComputeElasticImp KSpaceSolverElastic::sComputeElasticImp
{
/*2D cases: SD rho0 bOnA c0 s0 alpha */
{
std::make_tuple(SD::k2D, false, false, false, false, false),
&KSpaceSolverElastic::computeElastic<SD::k2D,
false, false, false, false, false>
}
};
void
KSpaceSolverElastic::allocateMemory()
{
// Add matrices into the container and create all matrices
mMatrixContainer.init();
mMatrixContainer.createMatrices();
// Add output streams into container
mOutputStreamContainer.init(mMatrixContainer);
}
void
KSpaceSolverElastic::loadInputData()
{
// Load data from the input file
mMatrixContainer.loadDataFromKConfig();
Hdf5File &outputFile = mParameters.getOutputFile();
auto &koutput = mParameters.getKOutput();
auto filename = koutput.getOutputFileName();
if (koutput.isOutputToFileFlag() && !outputFile.canAccess(filename))
outputFile.create(filename);
mOutputStreamContainer.createStreams();
}
void
KSpaceSolverElastic::compute()
{
/* Initialize all used FFTW plans */
initializeFftwPlans();
preProcessing<SD::k2D>();
#if 0
std::cout << mParameters.getRho0ScalarFlag() << std::endl;
std::cout << mParameters.getBOnAScalarFlag() << std::endl;
std::cout << mParameters.getC0ScalarFlag() << std::endl;
std::cout << mParameters.getS0ScalarFlag() << std::endl;
std::cout << mParameters.getAlphaPower() << std::endl;
#endif
sComputeElasticImp[std::make_tuple(
mParameters.getSimulationDimension(),
mParameters.getRho0ScalarFlag(),
mParameters.getBOnAScalarFlag(),
mParameters.getC0ScalarFlag(),
mParameters.getS0ScalarFlag(),
mParameters.getAlphaCoeffScalarFlag())]
(*this);
/* Post processing phase */
// mPostProcessingTime.start();
postProcessing();
}
template <Parameters::SimulationDimension simulationDimension,
bool rho0ScalarFlag,
bool bOnAScalarFlag,
bool c0ScalarFlag,
bool s0ScalarFlag,
bool alphaCoefScalarFlag>
void
KSpaceSolverElastic::computeElastic()
{
auto ¶ms = mParameters;
mActPercent = 0;
// Set the actual progress percentage to correspond the time index
// after recovery
if (params.getTimeIndex() > 0)
mActPercent = (100 * params.getTimeIndex()) / params.getNt();
// Progress header
Logger::log(Logger::LogLevel::kBasic, kOutFmtSimulationHeader);
mIterationTime.start();
params.setTimeIndex(0);
// Execute main loop
while (params.getTimeIndex() < params.getNt()
&& !params.isTimeToCheckpoint(mTotalTime)) {
const size_t timeIndex = params.getTimeIndex();
computePressureGradient<simulationDimension>();
computeSplitVelocity<simulationDimension>();
computeVelocity<simulationDimension>();
// Compute gradient of velocity
computeVelocityGradient<simulationDimension>();
computeSplitPressure<simulationDimension>();
// Calculate initial pressure
if ((timeIndex <= 1) && (mParameters.getInitialPressureSourceFlag() == 1))
addInitialPressureSource<simulationDimension, rho0ScalarFlag,
c0ScalarFlag, s0ScalarFlag>();
// Compute new pressure
computePressure<simulationDimension,
rho0ScalarFlag,
bOnAScalarFlag,
c0ScalarFlag,
s0ScalarFlag,
alphaCoefScalarFlag>();
storeSensorData();
printStatistics();
mParameters.incrementTimeIndex();
} // Time loop
}
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::preProcessing()
{
// Get the correct sensor mask and recompute indices
auto ¶ms = mParameters;
// smooth
smooth<SD::k2D>(MI::kInitialPressureSourceInput, true);
smooth<SD::k2D>(MI::kRho0, false);
smooth<SD::k2D>(MI::kDtRho0Sgx, false);
smooth<SD::k2D>(MI::kDtRho0Sgy, false);
// smooth<SD::k2D>(MI::kC2, false);
// smooth<SD::k2D>(MI::kS2, false);
#ifndef __KSPACE_DEBUG__
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
double *dtRho0Sgx = getRealData(MI::kDtRho0Sgx);
double *rho0 = getRealData(MI::kRho0);
double dtRho0Sgx_norm = 0;
double rho0_norm = 0;
for (size_t i = 0; i < nElements; ++ i)
{
dtRho0Sgx_norm += std::abs(dtRho0Sgx[i]);
rho0_norm += std::abs(rho0[i]);
}
std::cout << "dtRho0Sgx_norm = " << dtRho0Sgx_norm << std::endl;
std::cout << "rho0_norm = " << rho0_norm << std::endl;
#endif
if (params.getSensorMaskType() == Parameters::SensorMaskType::kIndex)
getIndexMatrix(MI::kSensorMaskIndex).recomputeIndicesToCPP();
if (!params.getRho0ScalarFlag()) {
getRealMatrix(MI::kDtRho0Sgx).scalarDividedBy(params.getDt());
getRealMatrix(MI::kDtRho0Sgy).scalarDividedBy(params.getDt());
}
// Generate shift variables
generateDerivativeOperators();
// Generate absorption variables and kappa
switch (mParameters.getAbsorbingFlag()) {
case Parameters::AbsorptionType::kLossless:
generateKappa();
break;
default:
assert(false);
}
// Generate PML
generatePml();
generateLameConstant();
}
void
KSpaceSolverElastic::generateDerivativeOperators()
{
const DimensionSizes &dimensionSizes =
mParameters.getFullDimensionSizes();
const DimensionSizes &reducedDimensionSizes =
mParameters.getReducedDimensionSizes();
constexpr FloatComplex imagUnit = FloatComplex(0, 1);
constexpr FloatComplex posExp = FloatComplex(0, 1);
constexpr FloatComplex negExp = FloatComplex(0, -1);
constexpr double pi2 = 2.0f * double(M_PI);
const double dx = mParameters.getDx();
const double dy = mParameters.getDy();
FloatComplex *ddxKShiftPos = getComplexData(MI::kDdxKShiftPosR);
FloatComplex *ddyKShiftPos = getComplexData(MI::kDdyKShiftPos);
FloatComplex *ddxKShiftNeg = getComplexData(MI::kDdxKShiftNegR);
FloatComplex *ddyKShiftNeg = getComplexData(MI::kDdyKShiftNeg);
// Calculate ifft shift
auto iFftShift = [](ptrdiff_t i, ptrdiff_t size)
{
return (i + (size / 2)) % size - (size / 2);
};// end of iFftShift
for (size_t i = 0; i < reducedDimensionSizes.nx; i++) {
const ptrdiff_t shift = iFftShift(i, dimensionSizes.nx);
const double kx = (pi2 / dx) * (double(shift)
/ double(dimensionSizes.nx));
const double exponent = kx * dx * 0.5f;
ddxKShiftPos[i] = imagUnit * kx * std::exp(posExp * exponent);
ddxKShiftNeg[i] = imagUnit * kx * std::exp(negExp * exponent);
}
// ddyKShiftPos, ddyKShiftPos
for (size_t i = 0; i < dimensionSizes.ny; i++) {
const ptrdiff_t shift = iFftShift(i, dimensionSizes.ny);
const double ky = (pi2 / dy) * (double(shift)
/ double(dimensionSizes.ny));
const double exponent = ky * dy * 0.5f;
ddyKShiftPos[i] = imagUnit * ky * std::exp(posExp * exponent);
ddyKShiftNeg[i] = imagUnit * ky * std::exp(negExp * exponent);
}
}
template <Parameters::SimulationDimension simulationDimension,
bool rho0ScalarFlag,
bool c0ScalarFlag,
bool s0ScalarFlag>
void
KSpaceSolverElastic::addInitialPressureSource()
{
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
const DimensionSizes &dimensionSizes = mParameters.getFullDimensionSizes();
double *p0 = getRealData(MI::kInitialPressureSourceInput);
double *tmp1 = getRealData(MI::kSxxSplitX);
double *tmp2 = getRealData(MI::kSxxSplitY);
double *tmp3 = getRealData(MI::kSyySplitX);
double *tmp4 = getRealData(MI::kSyySplitY);
assert(dimensionSizes.is2D());
double N = 2.0;
for (size_t i = 0; i < nElements; i++) {
auto delta = -p0[i] / 2. / N;
tmp1[i] += delta;
tmp2[i] += delta;
tmp3[i] += delta;
tmp4[i] += delta;
}
#if 0
double* sxxSplitX = getRealData(MI::kSxxSplitX);
double* sxxSplitY = getRealData(MI::kSxxSplitY);
double* syySplitX = getRealData(MI::kSyySplitX);
double* syySplitY = getRealData(MI::kSyySplitY);
double* pmat = getRealData(MI::kSxxSplitY);
#endif
}
template <Parameters::SimulationDimension simulationDimension,
bool rho0ScalarFlag,
bool bOnAScalarFlag,
bool c0ScalarFlag,
bool s0ScalarFlag,
bool alphaCoefScalarFlag>
void
KSpaceSolverElastic::computePressure()
{
const auto &fullDimSizes = mParameters.getFullDimensionSizes();
double *p = getRealData(MI::kP);
const double *sxxSplitX = getRealData(MI::kSxxSplitX);
const double *sxxSplitY = getRealData(MI::kSxxSplitY);
const double *syySplitX = getRealData(MI::kSyySplitX);
const double *syySplitY = getRealData(MI::kSyySplitY);
/*
p = -(sxx_split_x + sxx_split_y + syy_split_x + syy_split_y) / 2;
*/
for (size_t i = 0; i < fullDimSizes.nElements(); ++i) {
p[i] = -(sxxSplitX[i] + sxxSplitY[i] + syySplitX[i] + syySplitY[i]) / 2;
}
#ifdef __KSPACE_DEBUG__
double p_norm = 0.0;
for (size_t i = 0; i < fullDimSizes.nElements(); ++i) {
p_norm += std::abs(p[i]);
}
std::cout << "p_norm = " << p_norm << std::endl;
#endif
}
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::computePressureGradient()
{
const auto ¶ms = mParameters;
const auto &fullDimSizes = params.getFullDimensionSizes();
const FloatComplex *ddxKShiftPos = getComplexData(MI::kDdxKShiftPosR);
const FloatComplex *ddyKShiftPos = getComplexData(MI::kDdyKShiftPos);
const FloatComplex *ddxKShiftNeg = getComplexData(MI::kDdxKShiftNegR);
const FloatComplex *ddyKShiftNeg = getComplexData(MI::kDdyKShiftNeg);
double *tmpReal1 = getRealData(MI::kTmpReal1);
double *tmpReal2 = getRealData(MI::kTmpReal2);
double *tmpReal3 = getRealData(MI::kTmpReal3);
double *tmpReal4 = getRealData(MI::kTmpReal4);
FloatComplex *ifftXXdx = getComplexData(MI::kTmpFftwXXdx);
FloatComplex *ifftYYdy = getComplexData(MI::kTmpFftwYYdy);
FloatComplex *ifftXYdx = getComplexData(MI::kTmpFftwXYdx);
FloatComplex *ifftXYdy = getComplexData(MI::kTmpFftwXYdy);
const double *sxxSplitX = getRealData(MI::kSxxSplitX);
const double *sxxSplitY = getRealData(MI::kSxxSplitY);
const double *syySplitX = getRealData(MI::kSyySplitX);
const double *syySplitY = getRealData(MI::kSyySplitY);
const double *sxySplitX = getRealData(MI::kSxySplitX);
const double *sxySPlitY = getRealData(MI::kSxySplitY);
auto nx = params.getFullDimensionSizes().nx;
auto ny = params.getFullDimensionSizes().ny;
const double dividerX = 1.0f / static_cast<double>(nx);
const double dividerY = 1.0f / static_cast<double>(ny);
/*
dsxxdx = real( ifft( bsxfun(@times, ddx_k_shift_pos,
fft(sxx_split_x + sxx_split_y, [], 1)), [], 1) );
dsyydy = real( ifft( bsxfun(@times, ddy_k_shift_pos,
fft(syy_split_x + syy_split_y, [], 2)), [], 2) );
dsxydx = real( ifft( bsxfun(@times, ddx_k_shift_neg,
fft(sxy_split_x + sxy_split_y, [], 1)), [], 1) );
dsxydy = real( ifft( bsxfun(@times, ddy_k_shift_neg,
fft(sxy_split_x + sxy_split_y, [], 2)), [], 2) );
*/
/* tmpRet = sxx_split_x + sxx_split_y */
for (size_t i = 0; i < fullDimSizes.nElements(); i++) {
tmpReal1[i] = sxxSplitX[i] + sxxSplitY[i];
tmpReal2[i] = syySplitX[i] + syySplitY[i];
tmpReal3[i] = sxySplitX[i] + sxySPlitY[i];
tmpReal4[i] = sxySplitX[i] + sxySPlitY[i];
}
/* tmpRet = fft(tmpRet, [], 1) */
getTempFftwXXdx().computeR2CFft1DX(getRealMatrix(MI::kTmpReal1));
getTempFftwYYdy().computeR2CFft1DY(getRealMatrix(MI::kTmpReal2));
getTempFftwXYdx().computeR2CFft1DX(getRealMatrix(MI::kTmpReal3));
getTempFftwXYdy().computeR2CFft1DY(getRealMatrix(MI::kTmpReal4));
/* tmpRet = bsxfun(@times, ddx_k_shift_pos, tmpRet) */
auto reducedDimXSizes = params.getReducedXDimensionSizes();
for (size_t z = 0; z < reducedDimXSizes.nz; z++) {
for (size_t y = 0; y < reducedDimXSizes.ny; y++) {
for (size_t x = 0; x < reducedDimXSizes.nx; x++) {
const size_t i = get1DIndex(z, y, x, reducedDimXSizes);
ifftXXdx[i] = ifftXXdx[i] * ddxKShiftPos[x] * dividerX;
ifftXYdx[i] = ifftXYdx[i] * ddxKShiftNeg[x] * dividerX;
}
}
}
auto reducedDimYSizes = params.getReducedYDimensionSizes();
for (size_t z = 0; z < reducedDimYSizes.nz; z++) {
for (size_t y = 0; y < reducedDimYSizes.ny; y++) {
for (size_t x = 0; x < reducedDimYSizes.nx; x++) {
const size_t i = get1DIndex(z, y, x, reducedDimYSizes);
ifftYYdy[i] = ifftYYdy[i] * ddyKShiftPos[y] * dividerY;
ifftXYdy[i] = ifftXYdy[i] * ddyKShiftNeg[y] * dividerY;
}
}
}
/* real(ifft(tmpRet)) */
getTempFftwXXdx().computeC2RFft1DX(getRealMatrix(MI::kDSxxdx));
getTempFftwYYdy().computeC2RFft1DY(getRealMatrix(MI::kDSyydy));
getTempFftwXYdx().computeC2RFft1DX(getRealMatrix(MI::kDSxydx));
getTempFftwXYdy().computeC2RFft1DY(getRealMatrix(MI::kDSxydy));
#ifdef __KSPACE_DEBUG__
auto pmat1 = getRealData(MI::kDSxxdx);
auto pmat2 = getRealData(MI::kDSyydy);
auto pmat3 = getRealData(MI::kDSxydx);
auto pmat4 = getRealData(MI::kDSxydy);
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
double dSxxdx_norm = 0;
double dSyydy_norm = 0;
double dSxydx_norm = 0;
double dSxydy_norm = 0;
for (size_t i = 0; i < nElements; ++i) {
dSxxdx_norm += std::abs(pmat1[i]);
dSyydy_norm += std::abs(pmat2[i]);
dSxydx_norm += std::abs(pmat3[i]);
dSxydy_norm += std::abs(pmat4[i]);
}
std::cout << "dSxxdx_norm = " << dSxxdx_norm << std::endl;
std::cout << "dSyydy_norm = " << dSyydy_norm << std::endl;
std::cout << "dSxydx_norm = " << dSxydx_norm << std::endl;
std::cout << "dSxydy_norm = " << dSxydy_norm << std::endl;
#endif
}
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::computeSplitVelocity()
{
const auto &fullDimSizes = mParameters.getFullDimensionSizes();
double *dsXXdx = getRealData(MI::kDSxxdx);
double *dsYYdy = getRealData(MI::kDSyydy);
double *dsXYdx = getRealData(MI::kDSxydx);
double *dsXYdy = getRealData(MI::kDSxydy);
double *mPmlX = getRealData(MI::kMPmlX);
double *mPmlY = getRealData(MI::kMPmlY);
double *mPmlXSgx = getRealData(MI::kMPmlXSgx);
double *mPmlYSgy = getRealData(MI::kMPmlYSgy);
double *pmlX = getRealData(MI::kPmlX);
double *pmlY = getRealData(MI::kPmlY);
double *pmlXSgx = getRealData(MI::kPmlXSgx);
double *pmlYSgy = getRealData(MI::kPmlYSgy);
double *uxSplitX = getRealData(MI::kUxSplitX);
double *uxSplitY = getRealData(MI::kUxSplitY);
double *uySplitX = getRealData(MI::kUySplitX);
double *uySplitY = getRealData(MI::kUySplitY);
double *dtRho0Sgx = getRealData(MI::kDtRho0Sgx);
double *dtRho0Sgy = getRealData(MI::kDtRho0Sgy);
/*
ux_split_x = bsxfun(@times, mpml_y, ...
bsxfun(@times, pml_x_sgx, ...
bsxfun(@times, mpml_y, ...
bsxfun(@times, pml_x_sgx, ux_split_x) ...
) + kgrid.dt .* rho0_sgx_inv .* dsxxdx ...
) ...
);
ux_split_y = bsxfun(@times, mpml_x_sgx, bsxfun(@times, pml_y, ...
bsxfun(@times, mpml_x_sgx, bsxfun(@times, pml_y, ux_split_y)) ...
+ kgrid.dt .* rho0_sgx_inv .* dsxydy));
uy_split_x = bsxfun(@times, mpml_y_sgy, bsxfun(@times, pml_x, ...
bsxfun(@times, mpml_y_sgy, bsxfun(@times, pml_x, uy_split_x)) ...
+ kgrid.dt .* rho0_sgy_inv .* dsxydx));
uy_split_y = bsxfun(@times, mpml_x, bsxfun(@times, pml_y_sgy, ...
bsxfun(@times, mpml_x, bsxfun(@times, pml_y_sgy, uy_split_y)) ...
+ kgrid.dt .* rho0_sgy_inv .* dsyydy));
*/
for (size_t z = 0; z < fullDimSizes.nz; z++)
for (size_t y = 0; y < fullDimSizes.ny; y++)
for (size_t x = 0; x < fullDimSizes.nx; x++) {
const size_t i = get1DIndex(z, y, x, fullDimSizes);
auto coef = mPmlY[y] * pmlXSgx[x];
auto expr = coef * uxSplitX[i] + dtRho0Sgx[i] * dsXXdx[i];
uxSplitX[i] = coef * expr;
coef = mPmlXSgx[x] * pmlY[y];
expr = coef * uxSplitY[i] + dtRho0Sgx[i] * dsXYdy[i];
uxSplitY[i] = coef * expr;
coef = mPmlYSgy[y] * pmlX[x];
expr = coef * uySplitX[i] + dtRho0Sgy[i] * dsXYdx[i];
uySplitX[i] = coef * expr;
coef = mPmlX[x] * pmlYSgy[y];
expr = coef * uySplitY[i] + dtRho0Sgy[i] * dsYYdy[i];
uySplitY[i] = coef * expr;
}
#ifdef __KSPACE_DEBUG__
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
double uxSplitX_norm = 0;
double uxSplitY_norm = 0;
double uySplitX_norm = 0;
double uySplitY_norm = 0;
double dtRho0Sgx_norm = 0;
for (size_t i = 0; i < nElements; ++i) {
uxSplitX_norm += std::abs(uxSplitX[i]);
uxSplitY_norm += std::abs(uxSplitY[i]);
uySplitX_norm += std::abs(uySplitX[i]);
uySplitY_norm += std::abs(uySplitY[i]);
dtRho0Sgx_norm += std::abs(dtRho0Sgx[i]);
}
std::cout << "uxSplitX_norm = " << uxSplitX_norm << std::endl;
std::cout << "uxSplitY_norm = " << uxSplitY_norm << std::endl;
std::cout << "uySplitX_norm = " << uySplitX_norm << std::endl;
std::cout << "uySplitY_norm = " << uySplitY_norm << std::endl;
std::cout << "dtRho0Sgx_norm = " << dtRho0Sgx_norm << std::endl;
#endif
}
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::computeVelocity()
{
const auto &fullDimSizes = mParameters.getFullDimensionSizes();
double *uxSplitX = getRealData(MI::kUxSplitX);
double *uxSplitY = getRealData(MI::kUxSplitY);
double *uySplitX = getRealData(MI::kUySplitX);
double *uySplitY = getRealData(MI::kUySplitY);
double *uxSgx = getRealData(MI::kUxSgx);
double *uySgy = getRealData(MI::kUySgy);
/* ux_sgx = ux_split_x + ux_split_y;
uy_sgy = uy_split_x + uy_split_y;
*/
for (size_t i = 0; i < fullDimSizes.nElements(); ++i) {
uxSgx[i] = uxSplitX[i] + uxSplitY[i];
uySgy[i] = uySplitX[i] + uySplitY[i];
}
#ifdef __KSPACE_DEBUG__
double uxSgx_norm = 0;
double uySgy_norm = 0;
for (size_t i = 0; i < fullDimSizes.nElements(); ++i) {
uxSgx_norm += std::abs(uxSgx[i]);
uySgy_norm += std::abs(uySgy[i]);
}
std::cout << "uxSgx_norm = " << uxSgx_norm << std::endl;
std::cout << "uySgy_norm = " << uySgy_norm << std::endl;
#endif
}
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::computeVelocityGradient()
{
const auto ¶ms = mParameters;
auto nx = params.getFullDimensionSizes().nx;
auto ny = params.getFullDimensionSizes().ny;
const double dividerX = 1.0f / static_cast<double>(nx);
const double dividerY = 1.0f / static_cast<double>(ny);
const FloatComplex *ddxKShiftPos = getComplexData(MI::kDdxKShiftPosR);
const FloatComplex *ddyKShiftPos = getComplexData(MI::kDdyKShiftPos);
const FloatComplex *ddxKShiftNeg = getComplexData(MI::kDdxKShiftNegR);
const FloatComplex *ddyKShiftNeg = getComplexData(MI::kDdyKShiftNeg);
FloatComplex *ifftXXdx = getComplexData(MI::kTmpFftwXXdx);
FloatComplex *ifftXXdy = getComplexData(MI::kTmpFftwXXdy);
FloatComplex *ifftYYdx = getComplexData(MI::kTmpFftwYYdx);
FloatComplex *ifftYYdy = getComplexData(MI::kTmpFftwYYdy);
/*
duxdx = real( ifft( bsxfun(@times, ddx_k_shift_neg,
fft(ux_sgx, [], 1)), [], 1));
duxdy = real( ifft( bsxfun(@times, ddy_k_shift_pos,
fft(ux_sgx, [], 2)), [], 2));
duydx = real( ifft( bsxfun(@times, ddx_k_shift_pos,
fft(uy_sgy, [], 1)), [], 1));
duydy = real( ifft( bsxfun(@times, ddy_k_shift_neg,
fft(uy_sgy, [], 2)), [], 2));
*/
getTempFftwXXdx().computeR2CFft1DX(getRealMatrix(MI::kUxSgx));
getTempFftwXXdy().computeR2CFft1DY(getRealMatrix(MI::kUxSgx));
getTempFftwYYdx().computeR2CFft1DX(getRealMatrix(MI::kUySgy));
getTempFftwYYdy().computeR2CFft1DY(getRealMatrix(MI::kUySgy));
auto reducedDimXSizes = params.getReducedXDimensionSizes();
for (size_t z = 0; z < reducedDimXSizes.nz; z++)
for (size_t y = 0; y < reducedDimXSizes.ny; y++)
for (size_t x = 0; x < reducedDimXSizes.nx; x++) {
const size_t i = get1DIndex(z, y, x, reducedDimXSizes);
ifftXXdx[i] *= ddxKShiftNeg[x] * dividerX;
ifftYYdx[i] *= ddxKShiftPos[x] * dividerX;
}
auto reducedDimYSizes = params.getReducedYDimensionSizes();
for (size_t z = 0; z < reducedDimYSizes.nz; z++)
for (size_t y = 0; y < reducedDimYSizes.ny; y++)
for (size_t x = 0; x < reducedDimYSizes.nx; x++) {
const size_t i = get1DIndex(z, y, x, reducedDimYSizes);
ifftXXdy[i] *= ddyKShiftPos[y] * dividerY;
ifftYYdy[i] *= ddyKShiftNeg[y] * dividerY;
}
getTempFftwXXdx().computeC2RFft1DX(getRealMatrix(MI::kDuxdx));
getTempFftwXXdy().computeC2RFft1DY(getRealMatrix(MI::kDuxdy));
getTempFftwYYdx().computeC2RFft1DX(getRealMatrix(MI::kDuydx));
getTempFftwYYdy().computeC2RFft1DY(getRealMatrix(MI::kDuydy));
#ifdef __KSPACE_DEBUG__
// double *duxdx = getRealData(MI::kDuxdx);
// double *duxdy = getRealData(MI::kDuxdy);
// double *duydx = getRealData(MI::kDuydx);
// double *duydy = getRealData(MI::kDuydy);
auto pmat1 = getRealData(MI::kDuxdx);
auto pmat2 = getRealData(MI::kDuydx);
auto pmat3 = getRealData(MI::kDuxdy);
auto pmat4 = getRealData(MI::kDuydy);
double duxdx_norm = 0;
double duydx_norm = 0;
double duxdy_norm = 0;
double duydy_norm = 0;
auto nElements = mParameters.getFullDimensionSizes().nElements();
for (size_t i = 0; i < nElements; ++i) {
duxdx_norm += std::abs(pmat1[i]);
duydx_norm += std::abs(pmat2[i]);
duxdy_norm += std::abs(pmat3[i]);
duydy_norm += std::abs(pmat4[i]);
}
std::cout << "duxdx_norm = " << duxdx_norm << std::endl;
std::cout << "duydx_norm = " << duydx_norm << std::endl;
std::cout << "duxdy_norm = " << duxdy_norm << std::endl;
std::cout << "duydy_norm = " << duydy_norm << std::endl;
#endif
}
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::computeSplitPressure()
{
const auto &fullDimSizes = mParameters.getFullDimensionSizes();
const double dt = mParameters.getDt();
double *mu = getRealData(MI::kMu);
double *lambda = getRealData(MI::kLambda);
double *musgxy = getRealData(MI::kMuSgxy);
double *sxxSplitX = getRealData(MI::kSxxSplitX);
double *sxxSplitY = getRealData(MI::kSxxSplitY);
double *syySplitX = getRealData(MI::kSyySplitX);
double *syySplitY = getRealData(MI::kSyySplitY);
double *sxySplitX = getRealData(MI::kSxySplitX);
double *sxySplitY = getRealData(MI::kSxySplitY);
double *mPmlX = getRealData(MI::kMPmlX);
double *mPmlY = getRealData(MI::kMPmlY);
double *mPmlXSgx = getRealData(MI::kMPmlXSgx);
double *mPmlYSgy = getRealData(MI::kMPmlYSgy);
double *pmlX = getRealData(MI::kPmlX);
double *pmlY = getRealData(MI::kPmlY);
double *pmlXSgx = getRealData(MI::kPmlXSgx);
double *pmlYSgy = getRealData(MI::kPmlYSgy);
double *duxdx = getRealData(MI::kDuxdx);
double *duxdy = getRealData(MI::kDuxdy);
double *duydx = getRealData(MI::kDuydx);
double *duydy = getRealData(MI::kDuydy);
/*
sxx_split_x = bsxfun(@times, mpml_y, ...
bsxfun(@times, pml_x, ...
bsxfun(@times, mpml_y, bsxfun(@times, pml_x, sxx_split_x)) ...
+ kgrid.dt .* (2 .* mu + lambda) .* duxdx ));
sxx_split_y = bsxfun(@times, mpml_x, bsxfun(@times, pml_y, ...
bsxfun(@times, mpml_x, bsxfun(@times, pml_y, sxx_split_y)) ...
+ kgrid.dt .* lambda .* duydy ));
syy_split_x = bsxfun(@times, mpml_y, bsxfun(@times, pml_x, ...
bsxfun(@times, mpml_y, bsxfun(@times, pml_x, syy_split_x)) ...
+ kgrid.dt .* lambda .* duxdx));
syy_split_y = bsxfun(@times, mpml_x, bsxfun(@times, pml_y, ...
bsxfun(@times, mpml_x, bsxfun(@times, pml_y, syy_split_y)) ...
+ kgrid.dt .* (2 .* mu + lambda) .* duydy ));
sxy_split_x = bsxfun(@times, mpml_y_sgy, bsxfun(@times, pml_x_sgx, ...
bsxfun(@times, mpml_y_sgy, bsxfun(@times, pml_x_sgx, sxy_split_x)) ...
+ kgrid.dt .* mu_sgxy .* duydx));
sxy_split_y = bsxfun(@times, mpml_x_sgx, bsxfun(@times, pml_y_sgy, ...
bsxfun(@times, mpml_x_sgx, bsxfun(@times, pml_y_sgy, sxy_split_y)) ...
+ kgrid.dt .* mu_sgxy .* duxdy));
*/
for (size_t z = 0; z < fullDimSizes.nz; z++)
for (size_t y = 0; y < fullDimSizes.ny; y++)
for (size_t x = 0; x < fullDimSizes.nx; x++) {
const size_t i = get1DIndex(z, y, x, fullDimSizes);
auto moduli = (2.f * mu[i] + lambda[i]);
auto coef = mPmlY[y] * pmlX[x];
auto expr = coef * sxxSplitX[i] + dt * moduli * duxdx[i];
sxxSplitX[i] = coef * expr;
coef = mPmlX[x] * pmlY[y];
expr = coef * sxxSplitY[i] + dt * lambda[i] * duydy[i];
sxxSplitY[i] = coef * expr;
coef = mPmlY[y] * pmlX[x];
expr = coef * syySplitX[i] + dt * lambda[i] * duxdx[i];
syySplitX[i] = coef * expr;
coef = mPmlX[x] * pmlY[y];
expr = coef * syySplitY[i] + dt * moduli * duydy[i];
syySplitY[i] = coef * expr;
coef = mPmlYSgy[y] * pmlXSgx[x];
expr = coef * sxySplitX[i] + dt * musgxy[i] * duydx[i];
sxySplitX[i] = coef * expr;
coef = mPmlXSgx[x] * pmlYSgy[y];
expr = coef * sxySplitY[i] + dt * musgxy[i] * duxdy[i];
sxySplitY[i] = coef * expr;
}
#ifdef __KSPACE_DEBUG__
double sxxSplitX_norm = 0;
double sxxSplitY_norm = 0;
double syySplitX_norm = 0;
double syySplitY_norm = 0;
double sxySplitX_norm = 0;
double sxySplitY_norm = 0;
for (size_t i = 0; i < fullDimSizes.nElements(); ++i)
{
sxxSplitX_norm += std::abs(sxxSplitX[i]);
sxxSplitY_norm += std::abs(sxxSplitY[i]);
syySplitX_norm += std::abs(syySplitX[i]);
syySplitY_norm += std::abs(syySplitY[i]);
sxySplitX_norm += std::abs(sxySplitX[i]);
sxySplitY_norm += std::abs(sxySplitY[i]);
}
std::cout << "sxxSplitX_norm = " << sxxSplitX_norm << std::endl;
std::cout << "sxxSplitY_norm = " << sxxSplitY_norm << std::endl;
std::cout << "syySplitX_norm = " << syySplitX_norm << std::endl;
std::cout << "syySplitY_norm = " << syySplitY_norm << std::endl;
std::cout << "sxySplitX_norm = " << sxySplitX_norm << std::endl;
std::cout << "sxySplitY_norm = " << sxySplitY_norm << std::endl;
#endif
}
void
KSpaceSolverElastic::generateLameConstant()
{
auto ¶ms = mParameters;
if (!params.getElasticFlag() || params.getC0ScalarFlag()
|| params.getS0ScalarFlag() || params.getRho0ScalarFlag())
return;
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
auto c2 = getRealData(MI::kC2);
auto s2 = getRealData(MI::kS2);
auto rho0 = getRealData(MI::kRho0);
auto mu = getRealData(MI::kMu);
auto lambda = getRealData(MI::kLambda);
auto musgxy = getRealData(MI::kMuSgxy);
for (size_t i = 0; i < nElements; i++) {
mu[i] = s2[i] * s2[i] * rho0[i];
lambda[i] = c2[i] * c2[i] * rho0[i] - 2 * mu[i];
musgxy[i] = mu[i];
}
#if 1
double rho0_norm = 0;
for (size_t i = 0; i < nElements; i++) {
rho0_norm += std::abs(rho0[i]);
}
std::cout << "rho0_norm = " << rho0_norm << std::endl;
#endif
}
void
KSpaceSolverElastic::generatePml()
{
const DimensionSizes dimensionSizes = mParameters.getFullDimensionSizes();
double pmlXAlpha = mParameters.getPmlXAlpha();
double pmlYAlpha = mParameters.getPmlYAlpha();
const size_t pmlXSize = mParameters.getPmlXSize();
const size_t pmlYSize = mParameters.getPmlYSize();
const double cRefDx = mParameters.getCRef() / mParameters.getDx();
const double cRefDy = mParameters.getCRef() / mParameters.getDy();
const double dt2 = mParameters.getDt() * 0.5f;
double *pmlX = getRealData(MI::kPmlX);
double *pmlY = getRealData(MI::kPmlY);
double *pmlXSgx = getRealData(MI::kPmlXSgx);
double *pmlYSgy = getRealData(MI::kPmlYSgy);
auto mPmlX = getRealData(MI::kMPmlX);
auto mPmlY = getRealData(MI::kMPmlY);
auto mPmlXSgx = getRealData(MI::kMPmlXSgx);
auto mPmlYSgy = getRealData(MI::kMPmlYSgy);
auto multiAxialPmlRatio = mParameters.getMultiAxialPmlRatio();
// Init arrays
auto initPml = [](double *pml, double *pmlSg, size_t size)
{
for (size_t i = 0; i < size; i++) {
pml[i] = 1.0f;
pmlSg[i] = 1.0f;
}
};// end of initPml
// Calculate left value of PML exponent,
// for staggered use i + 0.5f, i shifted by -1 (Matlab indexing).
auto pmlLeft = [dt2](double i, double cRef, double pmlAlpha, double pmlSize)
{
return exp(-dt2 * pmlAlpha * cRef * pow((i - pmlSize) / (-pmlSize), 4));
};// end of pmlLeft.
// Calculate right value of PML exponent,
// for staggered use i + 0.5f, i shifted by +1 (Matlab indexing).
auto pmlRight = [dt2](double i, double cRef, double pmlAlpha, double pmlSize)
{
return exp(-dt2 * pmlAlpha * cRef * pow((i + 1.0f) / pmlSize, 4));
};// end of pmlRight.
// PML in x dimension
initPml(pmlX, pmlXSgx, dimensionSizes.nx);
// Too difficult for SIMD
for (size_t i = 0; i < pmlXSize; i++) {
pmlX[i] = pmlLeft(double(i), cRefDx, pmlXAlpha, pmlXSize);
pmlXSgx[i] = pmlLeft(double(i) + 0.5f, cRefDx, pmlXAlpha, pmlXSize);
const size_t iR = dimensionSizes.nx - pmlXSize + i;
pmlX[iR] = pmlRight(double(i), cRefDx, pmlXAlpha, pmlXSize);
pmlXSgx[iR] = pmlRight(double(i) + 0.5f, cRefDx, pmlXAlpha, pmlXSize);
}
// PML in y dimension
initPml(pmlY, pmlYSgy, dimensionSizes.ny);
// Too difficult for SIMD
for (size_t i = 0; i < pmlYSize; i++) {
if (!mParameters.isSimulationAS()) { // for axisymmetric code the PML is only on the outer side
pmlY[i] = pmlLeft(double(i), cRefDy, pmlYAlpha, pmlYSize);
pmlYSgy[i] = pmlLeft(double(i) + 0.5f, cRefDy, pmlYAlpha, pmlYSize);
}
const size_t iR = dimensionSizes.ny - pmlYSize + i;
pmlY[iR] = pmlRight(double(i), cRefDy, pmlYAlpha, pmlYSize);
pmlYSgy[iR] = pmlRight(double(i) + 0.5f, cRefDy, pmlYAlpha, pmlYSize);
}
pmlXAlpha *= multiAxialPmlRatio;
pmlYAlpha *= multiAxialPmlRatio;
initPml(mPmlX, mPmlXSgx, dimensionSizes.nx);
// Too difficult for SIMD
for (size_t i = 0; i < pmlXSize; i++) {
mPmlX[i] = pmlLeft(double(i), cRefDx, pmlXAlpha, pmlXSize);
mPmlXSgx[i] = pmlLeft(double(i) + 0.5f, cRefDx, pmlXAlpha, pmlXSize);
const size_t iR = dimensionSizes.nx - pmlXSize + i;
mPmlX[iR] = pmlRight(double(i), cRefDx, pmlXAlpha, pmlXSize);
mPmlXSgx[iR] = pmlRight(double(i) + 0.5f, cRefDx, pmlXAlpha, pmlXSize);
}
// PML in y dimension
initPml(mPmlY, mPmlYSgy, dimensionSizes.ny);
// Too difficult for SIMD
for (size_t i = 0; i < pmlYSize; i++) {
if (!mParameters.isSimulationAS()) { // for axisymmetric code the PML is only on the outer side
mPmlY[i] = pmlLeft(double(i), cRefDy, pmlYAlpha, pmlYSize);
mPmlYSgy[i] = pmlLeft(double(i) + 0.5f, cRefDy, pmlYAlpha, pmlYSize);
}
const size_t iR = dimensionSizes.ny - pmlYSize + i;
mPmlY[iR] = pmlRight(double(i), cRefDy, pmlYAlpha, pmlYSize);
mPmlYSgy[iR] = pmlRight(double(i) + 0.5f, cRefDy, pmlYAlpha, pmlYSize);
}
#if 0
// double *pmlX = getRealData(MI::kPmlX);
// double *pmlY = getRealData(MI::kPmlY);
//
// double *pmlXSgx = getRealData(MI::kPmlXSgx);
// double *pmlYSgy = getRealData(MI::kPmlYSgy);
//
// auto mPmlX = getRealData(MI::kMPmlX);
// auto mPmlY = getRealData(MI::kMPmlY);
//
// auto mPmlXSgx = getRealData(MI::kMPmlXSgx);
// auto mPmlYSgy = getRealData(MI::kMPmlYSgy);
const size_t nElements = dimensionSizes.nElements();
double pmlX_norm = 0;
double pmlY_norm = 0;
double mPmlX_norm = 0;
double mPmlY_norm = 0;
double pmlXSgx_norm = 0;
double pmlYSgy_norm = 0;
double mPmlXSgx_norm = 0;
double mPmlYSgy_norm = 0;
for (size_t i = 0; i < dimensionSizes.nx; ++i) {
pmlX_norm += std::abs(pmlX[i]);
pmlY_norm += std::abs(pmlY[i]);
mPmlX_norm += std::abs(mPmlX[i]);
mPmlY_norm += std::abs(mPmlY[i]);
pmlXSgx_norm += std::abs(pmlXSgx[i]);
pmlYSgy_norm += std::abs(pmlYSgy[i]);
mPmlXSgx_norm += std::abs(mPmlXSgx[i]);
mPmlYSgy_norm += std::abs(mPmlYSgy[i]);
}
double max_pmlX = *std::max_element(pmlX, pmlX+nElements);
std::cout << "pmlX_norm = " << pmlX_norm << std::endl;
std::cout << "pmlXSgx_norm = " << pmlXSgx_norm << std::endl;
std::cout << "pmlY_norm = " << pmlY_norm << std::endl;
std::cout << "pmlYSgy_norm = " << pmlYSgy_norm << std::endl;
std::cout << "mPmlX_norm = " << mPmlX_norm << std::endl;
std::cout << "mPmlXSgx_norm = " << mPmlXSgx_norm << std::endl;
std::cout << "mPmlY_norm = " << mPmlY_norm << std::endl;
std::cout << "mPmlYSgy_norm = " << mPmlYSgy_norm << std::endl;
#endif
}
void KSpaceSolverElastic::storeSensorInfo()
{
// Unless the time for sampling has come, exit.
if (mParameters.getTimeIndex() >= mParameters.getSamplingStartTimeIndex()) {
if (mParameters.getStoreVelocityNonStaggeredRawFlag()) {
if (mParameters.isSimulation3D()) {
computeShiftedVelocity<SD::k3D>();
} else {
computeShiftedVelocity<SD::k2D>();
}
}
mOutputStreamContainer.sampleStreams();
}
}
void KSpaceSolverElastic::postProcessing()
{
auto ¶ms = mParameters;
auto koutput = params.getKOutput();
if (koutput.isOutputToFileFlag()) {
if (mParameters.getStorePressureFinalAllFlag()) {
getRealMatrix(MI::kP).writeData(mParameters.getOutputFile(),
mOutputStreamContainer.getStreamHdf5Name(OI::kFinalPressure),
mParameters.getCompressionLevel());
}// p_final
// Apply post-processing and close
mOutputStreamContainer.postProcessStreams();
mOutputStreamContainer.closeStreams();
writeOutputDataInfo();
params.getOutputFile().close();
}
}
std::pair<KSpaceSolverElastic::MatrixType, std::vector<double>>
KSpaceSolverElastic::getWindow(std::vector<size_t> a, std::vector<bool> s)
{
auto cosineSeries = [](std::vector<double> &n, double N, std::vector<double> &coef)
{
std::vector<double> r(n.size());
std::transform(n.begin(), n.end(), r.begin(),
[&](double &i)
{
// series = series + (-1)^(index-1) * coeffs(index) * cos((index - 1) * 2 * pi * n / (N - 1));
const auto pi = M_PI;
return coef[0]
- (coef[1] * std::cos(1. * 2. * pi * i / (N - 1.)))
+ (coef[2] * std::cos(2. * 2. * pi * i / (N - 1.)));
});
return std::move(r);
};
assert(a.size() == s.size());
const auto param = 0.16;
std::transform(a.cbegin(), a.cend(), s.cbegin(), a.begin(), [](size_t a, bool b) { return a + 1 * (!b); });
switch (a.size()) {
case 1: {
auto N = a[0];
auto symmetric = s[0];
auto coef = std::vector<double>{(1 - param) / 2, 0.5, param / 2};
struct f {
double operator()() { return init++; }
double init = 0;
};
auto n = std::vector<double>(N);
std::generate(n.begin(), n.end(), f());
auto win = cosineSeries(n, N, coef);
N = N - 1 * (!symmetric);
win.resize(N);
return std::make_pair(MatrixType(), std::move(win));
}
case 2: {
auto linearSpace = [](double b, double e, int n)
{
assert(n > 1 && e > b);
std::vector<double> r(n);
auto i = 0;
std::transform(r.begin(), r.end(), r.begin(), [&](double) { return b + (e - b) * i++ / (n - 1); });
return std::move(r);
};
auto ndGrid = [](std::vector<double> xx, std::vector<double> yy)
{
auto x = MatrixType(yy.size(), std::vector<double>(xx.size(), 0));
auto y = MatrixType(yy.size(), std::vector<double>(xx.size(), 0));
std::for_each(x.begin(), x.end(), [&](std::vector<double> &v) { v = xx; });
auto i = 0;
std::for_each(y.begin(), y.end(), [&](std::vector<double> &v)
{
std::fill(v.begin(), v.end(), yy[i++]);
});
return std::make_pair(x, y);
};
auto L = *std::max_element(a.begin(), a.end());
auto t = getWindow(std::vector<size_t>{L}, std::vector<bool>{true});
auto win_lin = std::get<1>(t);
auto radius = (L - 1) / 2.;
auto ll = linearSpace(-radius, radius, L);
auto xx = linearSpace(-radius, radius, a[0]);
auto yy = linearSpace(-radius, radius, a[1]);
auto xy = ndGrid(xx, yy);
auto x = std::get<0>(xy);
auto y = std::get<1>(xy);
auto r = x;
assert(x.size() > 0);
for (size_t i = 0; i < x.size(); ++i)
for (size_t j = 0; j < x[0].size(); ++j) {
auto ret = std::sqrt(x[i][j] * x[i][j] + y[i][j] * y[i][j]);
r[i][j] = ret > radius ? radius : ret;
}
auto win = r;
LinearInterp<double> interPn(ll, win_lin);
for (size_t i = 0; i < win.size(); ++i)
for (size_t j = 0; j < win[0].size(); ++j) {
win[i][j] = interPn.interp(r[i][j]);
if (win[i][j] <= radius)
win[i][j] = interPn.interp(r[i][j]);
}
std::transform(a.cbegin(), a.cend(), s.cbegin(), a.begin(), [](size_t a, bool b) { return a - 1 * (!b); });
win.resize(a[1]);
std::for_each(win.begin(), win.end(), [&](std::vector<double> &v) { v.resize(a[0]); });
return std::make_pair(win, std::vector<double>());
}
default:
assert(false);
return std::make_pair(MatrixType(), std::vector<double>());
}
/* error. */
}
/*
* matrixIdx : [in] and [out]
*/
template <Parameters::SimulationDimension simulationDimension>
void
KSpaceSolverElastic::smooth(const MatrixContainer::MatrixIdx matrixIdx, bool isRestoreMax)
{
const auto ¶ms = mParameters;
auto nx = params.getFullDimensionSizes().nx;
auto ny = params.getFullDimensionSizes().ny;
const double dividerX = 1.0f / static_cast<double>(nx);
const double dividerY = 1.0f / static_cast<double>(ny);
auto *mat = getRealData(matrixIdx);
auto *mat_sam = getRealData(MI::kTmpReal1);
auto *t = getRealData(MI::kTmpReal2);
// auto *win = getRealData(MI::kTmpReal3);
auto matrixPrint = [&](double *m)
{
const DimensionSizes &dimensionSizes = mParameters.getFullDimensionSizes();
for (size_t z = 0; z < dimensionSizes.nz; ++z)
for (size_t x = 0; x < dimensionSizes.nx; ++x) {
for (size_t y = 0; y < dimensionSizes.ny; ++y) {
const size_t i = get1DIndex(z, y, x, dimensionSizes);
std::cout << std::setw(8) << m[i] << " ";
}
std::cout << std::endl;
}
};
FloatComplex *iFftwX = getComplexData(MI::kTempFftwX);
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
const DimensionSizes &dimensionSizes = mParameters.getFullDimensionSizes();
const DimensionSizes &reducedDimensionSizes = mParameters.getReducedDimensionSizes();
std::vector<size_t> grid_size{dimensionSizes.nx, dimensionSizes.ny};
std::vector<bool> window_symmetry;
std::transform(grid_size.begin(), grid_size.end(), std::back_inserter(window_symmetry),
[](size_t i) { return i % 2 == 1; });
// assert(grid_size[0] == 8 && grid_size[1] == 8);
// assert(window_symmetry[0] == false && window_symmetry[1] == false);
// get the window
auto ret = getWindow(grid_size, window_symmetry);
auto twin = std::get<0>(ret);
std::for_each(twin.begin(), twin.end(),
[](std::vector<double> &v)
{
std::for_each(v.begin(), v.end(), [](double &i) { i = std::abs(i); });
});
getTempFftwX().computeR2CFftND(getRealMatrix(matrixIdx));
auto iFftShift = [](size_t i, size_t size)
{
return (i + (size / 2)) % size;
};
auto ifft_twin = twin;
for (size_t z = 0; z < dimensionSizes.nz; ++z)
for (size_t y = 0; y < dimensionSizes.ny; ++y)
for (size_t x = 0; x < dimensionSizes.nx; ++x) {
const size_t i = get1DIndex(z, y, x, dimensionSizes);
size_t x_pos = iFftShift(x, dimensionSizes.nx);
size_t y_pos = iFftShift(y, dimensionSizes.ny);
ifft_twin[y][x] = twin[y_pos][x_pos];
}
// for (size_t z = 0; z < dimensionSizes.nz; ++z)
// for (size_t x = 0; x < dimensionSizes.nx; ++x)
// {
// for (size_t y = 0; y < dimensionSizes.ny; ++y)
// {
// const size_t i = get1DIndex(z, y, x, dimensionSizes);
// std::cout << std::setw(12) << ifft_twin[y][x] << " ";
// }
// std::cout << std::endl;
// }
for (size_t z = 0; z < reducedDimensionSizes.nz; ++z)
for (size_t y = 0; y < reducedDimensionSizes.ny; ++y)
for (size_t x = 0; x < reducedDimensionSizes.nx; ++x) {
const size_t i = get1DIndex(z, y, x, reducedDimensionSizes);
iFftwX[i] = iFftwX[i] * ifft_twin[y][x] * dividerX * dividerY;
}
// for (size_t z = 0; z < reducedDimensionSizes.nz; ++z)
// for (size_t x = 0; x < reducedDimensionSizes.nx; ++x)
// {
// for (size_t y = 0; y < reducedDimensionSizes.ny; ++y)
// {
// const size_t i = get1DIndex(z, y, x, reducedDimensionSizes);
// std::cout << iFftwX[i] << " ";
// }
// std::cout << std::endl;
// }
getTempFftwX().computeC2RFftND(getRealMatrix(MI::kTmpReal1));
// auto p0 = getRealData(matrixIdx);
//
// for (size_t z = 0; z < dimensionSizes.nz; ++z)
// for (size_t x = 0; x < dimensionSizes.nx; ++x)
// {
// for (size_t y = 0; y < dimensionSizes.ny; ++y)
// {
// const size_t i = get1DIndex(z, y, x, dimensionSizes);
// std::cout << p0[i] << " ";
// }
// std::cout << std::endl;
// }
if (isRestoreMax) {
std::transform(mat, mat + nElements, t, [](double &i) { return std::abs(i); });
auto mat_max = *std::max_element(t, t + nElements);
std::transform(mat_sam, mat_sam + nElements, t, [](double &i) { return std::abs(i); });
auto mat_sam_max = *std::max_element(t, t + nElements);
auto ratio = mat_max / mat_sam_max;
std::transform(mat_sam, mat_sam + nElements, mat_sam, [ratio](double &i) { return ratio * i; });
}
getRealMatrix(matrixIdx).copyData(getRealMatrix(MI::kTmpReal1));
// auto p0 = getRealData(matrixIdx);
// for (size_t z = 0; z < dimensionSizes.nz; ++z)
// for (size_t x = 0; x < dimensionSizes.nx; ++x)
// {
// for (size_t y = 0; y < dimensionSizes.ny; ++y)
// {
// const size_t i = get1DIndex(z, y, x, dimensionSizes);
// std::cout << p0[i] << " ";
// }
// std::cout << std::endl;
// }
}
void
KSpaceSolverElastic::debugVariableNorm()
{
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
double *pmlX = getRealData(MI::kPmlX);
double *pmlY = getRealData(MI::kPmlY);
double *pmlXSgx = getRealData(MI::kPmlXSgx);
double *pmlYSgy = getRealData(MI::kPmlYSgy);
auto mPmlX = getRealData(MI::kMPmlX);
auto mPmlY = getRealData(MI::kMPmlY);
auto mPmlXSgx = getRealData(MI::kMPmlXSgx);
auto mPmlYSgy = getRealData(MI::kMPmlYSgy);
const double *sxxSplitX = getRealData(MI::kSxxSplitX);
const double *sxxSplitY = getRealData(MI::kSxxSplitY);
const double *syySplitX = getRealData(MI::kSyySplitX);
const double *syySplitY = getRealData(MI::kSyySplitY);
const double *sxySplitX = getRealData(MI::kSxySplitX);
const double *sxySPlitY = getRealData(MI::kSxySplitY);
double *p = getRealData(MI::kP);
}
void
KSpaceSolverElastic::miscVerify()
{
initializeFftwPlans();
std::cout << "KSpaceSolverElastic::miscVerify" << std::endl;
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
smooth<SD::k2D>(MI::kInitialPressureSourceInput, true);
}
void
KSpaceSolverElastic::fftwVerify()
{
// initializeFftwPlans();
// generateDerivativeOperators();
#if 0
FloatComplex *fftx = getComplexData(MI::kTmpFftwXXdx);
double *x = getRealData(MI::kTmpReal1);
x[49] = -5;
x[49 + 128 - 3] = -5;
x[49 + 128 - 2] = -5;
x[49 + 128 - 1] = -5;
x[49 + 128] = -5;
x[49 + 128 + 1] = -5;
x[49 + 128 + 2] = -5;
x[49 + 128 + 3] = -5;
getTempFftwXXdx().computeR2CFft1DX(getRealMatrix(MI::kTmpReal1));
std::cout << fftx[0] << std::endl;
std::cout << fftx[1] << std::endl;
std::cout << " -------------------- " << std::endl;
std::cout << fftx[62] << std::endl;
std::cout << fftx[63] << std::endl;
std::cout << fftx[64] << std::endl;
std::cout << fftx[65] << std::endl;
std::cout << fftx[66] << std::endl;
std::cout << " -------------------- " << std::endl;
std::cout << fftx[64] << std::endl;
std::cout << fftx[65] << std::endl;
std::cout << " -------------------- " << std::endl;
std::cout << fftx[64+62] << std::endl;
std::cout << fftx[64+63] << std::endl;
std::cout << fftx[64+64] << std::endl;
std::cout << fftx[64+65] << std::endl;
std::cout << fftx[64+66] << std::endl;
#endif
#if 0
FloatComplex *fftx = getComplexData(MI::kTmpFftwXXdx);
const double divider = 1.0f / double(mParameters.getFullDimensionSizes().nElements());
const auto & dimSizes = mParameters.getFullDimensionSizes();
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
const DimensionSizes& reducedDimSizes= mParameters.getReducedDimensionSizes();
double *p0 = getRealData(MI::kInitialPressureSourceInput);
double* sxxSplitX = getRealData(MI::kSxxSplitX);
double* sxxSplitY = getRealData(MI::kSxxSplitY);
double* tmp = getRealData(MI::kTmpReal1);
for (size_t i = 0; i < nElements; i++) {
tmp[i] = -p0[i] / 2.f;
}
getRealMatrix(MI::kSxxSplitX).copyData(getRealMatrix(MI::kTmpReal1));
getRealMatrix(MI::kSxxSplitY).copyData(getRealMatrix(MI::kTmpReal1));
double *tmpReal1 = getRealData(MI::kTmpReal1);
for (size_t i = 0; i < dimSizes.nElements(); i ++)
{
tmpReal1[i] = sxxSplitX[i] + sxxSplitY[i];
}
tmpReal1[49] = - 5;
getTempFftwXXdx().computeR2CFft1DX(getRealMatrix(MI::kTmpReal1));
for (size_t z = 0; z < reducedDimSizes.nz; z++)
{
for (size_t y = 0; y < reducedDimSizes.ny; y++)
{
for (size_t x = 0; x < reducedDimSizes.nx; x++)
{
const size_t i = get1DIndex(z, y, x, reducedDimSizes);
fftx[i] *= divider;
}
}
}
getTempFftwXXdx().computeC2RFft1DX(getRealMatrix(MI::kDSxxdx));
double *dsxxdx = getRealData(MI::kDSxxdx);
//std::cout << fftx[0 + 128] << std::endl;
//std::cout << fftx[1 + 128] << std::endl;
//std::cout << fftx[2 + 128] << std::endl;
#endif
#if 0
FloatComplex *ffty = getComplexData(MI::kTmpFftwYYdy);
const FloatComplex* ddyKShiftPos = getComplexData(MI::kDdyKShiftPos);
const auto & dimSizes = mParameters.getFullDimensionSizes();
const size_t nElements = mParameters.getFullDimensionSizes().nElements();
const DimensionSizes& reducedDimSizes= mParameters.getReducedDimensionSizes();
auto ny = dimSizes.ny;
const double divider = 1.f / static_cast<double>(ny);
double *p0 = getRealData(MI::kInitialPressureSourceInput);
double* syySplitX = getRealData(MI::kSyySplitX);
double* syySplitY = getRealData(MI::kSyySplitY);
double* tmp = getRealData(MI::kTmpReal2);
for (size_t i = 0; i < nElements; i++) {
tmp[i] = -p0[i] / 2.f;
}
getRealMatrix(MI::kSyySplitX).copyData(getRealMatrix(MI::kTmpReal2));
getRealMatrix(MI::kSyySplitY).copyData(getRealMatrix(MI::kTmpReal2));
double *tmpReal2 = getRealData(MI::kTmpReal2);
for (size_t i = 0; i < dimSizes.nElements(); i ++)
{
tmpReal2[i] = syySplitX[i] + syySplitY[i];
}
// tmpReal2[49 * 128 + 41] = - 5;
getTempFftwYYdy().computeR2CFft1DY(getRealMatrix(MI::kTmpReal2));
for (size_t z = 0; z < reducedDimSizes.nz; z++)
{
for (size_t y = 0; y < reducedDimSizes.ny; y++)
{
for (size_t x = 0; x < reducedDimSizes.nx; x++)
{
const size_t i = get1DIndex(z, y, x, reducedDimSizes);
ffty[i] *= ddyKShiftPos[y];
}
}
}
getTempFftwYYdy().computeC2RFft1DY(getRealMatrix(MI::kDSyydy));
double *dsyydy = getRealData(MI::kDSyydy);
for (size_t i = 0; i < nElements; ++ i)
dsyydy[i] *= divider;
//std::cout << fftx[0 + 128] << std::endl;
//std::cout << fftx[1 + 128] << std::endl;
//std::cout << fftx[2 + 128] << std::endl;
#endif
}
| 34.923282 | 121 | 0.590602 | xschrodingerscat |
d47eb421e3d74a567d8903fdfe101c1aaf303cd2 | 2,798 | cpp | C++ | src/attacks/noop/component.cpp | aws-robotics/ROS2-SecTest | f95683a0e78fac97d0de4ae14c871e098c25a91c | [
"Apache-2.0"
] | 12 | 2019-06-05T17:12:20.000Z | 2021-10-30T02:55:34.000Z | src/attacks/noop/component.cpp | aws-robotics/ROS2-SecTest | f95683a0e78fac97d0de4ae14c871e098c25a91c | [
"Apache-2.0"
] | 4 | 2019-06-07T01:32:44.000Z | 2019-08-29T17:55:16.000Z | src/attacks/noop/component.cpp | aws-robotics/ROS2-SecTest | f95683a0e78fac97d0de4ae14c871e098c25a91c | [
"Apache-2.0"
] | 4 | 2019-08-02T15:04:14.000Z | 2021-10-30T02:55:25.000Z | // Copyright 2019 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.
// 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 "ros_sec_test/attacks/noop/component.hpp"
#include "rclcpp/logging.hpp"
#include "rclcpp/node_options.hpp"
#include "rclcpp_lifecycle/lifecycle_node.hpp"
#include "rclcpp_lifecycle/node_interfaces/lifecycle_node_interface.hpp"
#include "rclcpp_lifecycle/state.hpp"
using CallbackReturn = rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn;
namespace ros_sec_test
{
namespace attacks
{
namespace noop
{
Component::Component()
: rclcpp_lifecycle::LifecycleNode("noop", "", rclcpp::NodeOptions().use_intra_process_comms(true))
{
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
Component::on_configure(const rclcpp_lifecycle::State & /* state */)
{
RCLCPP_INFO(get_logger(), "on_configure() is called.");
return CallbackReturn::SUCCESS;
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
Component::on_activate(const rclcpp_lifecycle::State & /* state */)
{
RCLCPP_INFO(get_logger(), "on_activate() is called.");
return CallbackReturn::SUCCESS;
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
Component::on_deactivate(const rclcpp_lifecycle::State & /* state */)
{
RCLCPP_INFO(get_logger(), "on_deactivate() is called.");
return CallbackReturn::SUCCESS;
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
Component::on_cleanup(const rclcpp_lifecycle::State & /* state */)
{
RCLCPP_INFO(get_logger(), "on_cleanup() is called.");
return CallbackReturn::SUCCESS;
}
rclcpp_lifecycle::node_interfaces::LifecycleNodeInterface::CallbackReturn
Component::on_shutdown(const rclcpp_lifecycle::State & /* state */)
{
RCLCPP_INFO(get_logger(), "on_shutdown() is called.");
return CallbackReturn::SUCCESS;
}
} // namespace noop
} // namespace attacks
} // namespace ros_sec_test
#include "class_loader/register_macro.hpp"
// Register the component with class_loader.
// This acts as a sort of entry point, allowing the component to be discoverable when its library
// is being loaded into a running process.
CLASS_LOADER_REGISTER_CLASS(ros_sec_test::attacks::noop::Component, rclcpp_lifecycle::LifecycleNode)
| 34.54321 | 100 | 0.779485 | aws-robotics |
d480126b35d0df22015a06c214258945fcc73e38 | 362 | cpp | C++ | code-emulator/src/hal/x64/Arduino.cpp | malavv/MrPlate | 458c844fa79e8d3c121d9d9ebe6ab51132c70156 | [
"MIT"
] | null | null | null | code-emulator/src/hal/x64/Arduino.cpp | malavv/MrPlate | 458c844fa79e8d3c121d9d9ebe6ab51132c70156 | [
"MIT"
] | null | null | null | code-emulator/src/hal/x64/Arduino.cpp | malavv/MrPlate | 458c844fa79e8d3c121d9d9ebe6ab51132c70156 | [
"MIT"
] | null | null | null | #include "Arduino.h"
ISerial Serial;
std::vector<DebugMsg*> debugMsg;
void debug(int8_t pin, const char* msg, int32_t value) {
DebugMsg *found = nullptr;
for (auto &it : debugMsg) {
if (it->pin == pin)
found = it;
}
if (found) {
found->msg = msg;
found->val = value;
} else
debugMsg.push_back(new DebugMsg(pin, msg, value));
} | 19.052632 | 56 | 0.616022 | malavv |
d4810b526a50894f5cea3a652b48ae4b1c99cc53 | 3,624 | hpp | C++ | dependencies/glm/glm/gtc/integer.hpp | Noaheasley/Bootstrap | fbcf53bffa42fe41233726ba42218568ce0dba60 | [
"MIT"
] | 13 | 2017-03-06T22:25:10.000Z | 2022-01-31T00:19:03.000Z | dependencies/glm/glm/gtc/integer.hpp | Noaheasley/Bootstrap | fbcf53bffa42fe41233726ba42218568ce0dba60 | [
"MIT"
] | 12 | 2016-12-03T01:36:31.000Z | 2019-12-11T00:40:02.000Z | dependencies/glm/glm/gtc/integer.hpp | Noaheasley/Bootstrap | fbcf53bffa42fe41233726ba42218568ce0dba60 | [
"MIT"
] | 37 | 2016-10-27T14:55:34.000Z | 2022-01-31T00:19:08.000Z | /// @ref gtc_integer
/// @file glm/gtc/integer.hpp
///
/// @see core (dependence)
/// @see gtc_integer (dependence)
///
/// @defgroup gtc_integer GLM_GTC_integer
/// @ingroup gtc
///
/// @brief Allow to perform bit operations on integer values
///
/// <glm/gtc/integer.hpp> need to be included to use these functionalities.
#pragma once
// Dependencies
#include "../detail/setup.hpp"
#include "../detail/precision.hpp"
#include "../detail/func_common.hpp"
#include "../detail/func_integer.hpp"
#include "../detail/func_exponential.hpp"
#include <limits>
#if GLM_MESSAGES == GLM_MESSAGES_ENABLED && !defined(GLM_EXT_INCLUDED)
# pragma message("GLM: GLM_GTC_integer extension included")
#endif
namespace glm
{
/// @addtogroup gtc_integer
/// @{
/// Returns the log2 of x for integer values. Can be reliably using to compute mipmap count from the texture size.
/// @see gtc_integer
template<typename genIUType>
GLM_FUNC_DECL genIUType log2(genIUType x);
/// Modulus. Returns x % y
/// for each component in x using the floating point value y.
///
/// @tparam genIUType Integer-point scalar or vector types.
///
/// @see gtc_integer
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/mod.xml">GLSL mod man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.3 Common Functions</a>
template<typename genIUType>
GLM_FUNC_DECL genIUType mod(genIUType x, genIUType y);
/// Modulus. Returns x % y
/// for each component in x using the floating point value y.
///
/// @tparam T Integer scalar types.
///
/// @see gtc_integer
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/mod.xml">GLSL mod man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.3 Common Functions</a>
template<length_t L, typename T, precision P>
GLM_FUNC_DECL vec<L, T, P> mod(vec<L, T, P> const& x, T y);
/// Modulus. Returns x % y
/// for each component in x using the floating point value y.
///
/// @tparam T Integer scalar types.
///
/// @see gtc_integer
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/mod.xml">GLSL mod man page</a>
/// @see <a href="http://www.opengl.org/registry/doc/GLSLangSpec.4.20.8.pdf">GLSL 4.20.8 specification, section 8.3 Common Functions</a>
template<length_t L, typename T, precision P>
GLM_FUNC_DECL vec<L, T, P> mod(vec<L, T, P> const& x, vec<L, T, P> const& y);
/// Returns a value equal to the nearest integer to x.
/// The fraction 0.5 will round in a direction chosen by the
/// implementation, presumably the direction that is fastest.
///
/// @param x The values of the argument must be greater or equal to zero.
/// @tparam T floating point scalar types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/round.xml">GLSL round man page</a>
/// @see gtc_integer
template<length_t L, typename T, precision P>
GLM_FUNC_DECL vec<L, int, P> iround(vec<L, T, P> const& x);
/// Returns a value equal to the nearest integer to x.
/// The fraction 0.5 will round in a direction chosen by the
/// implementation, presumably the direction that is fastest.
///
/// @param x The values of the argument must be greater or equal to zero.
/// @tparam T floating point scalar types.
///
/// @see <a href="http://www.opengl.org/sdk/docs/manglsl/xhtml/round.xml">GLSL round man page</a>
/// @see gtc_integer
template<length_t L, typename T, precision P>
GLM_FUNC_DECL vec<L, uint, P> uround(vec<L, T, P> const& x);
/// @}
} //namespace glm
#include "integer.inl"
| 36.606061 | 137 | 0.694536 | Noaheasley |
d481a18ca51734ceac9efaf66743070806af8035 | 979 | cpp | C++ | SwapNodesinPairs/SwapNodesinPairs_2.cpp | yergen/leetcode | 7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab | [
"MIT"
] | null | null | null | SwapNodesinPairs/SwapNodesinPairs_2.cpp | yergen/leetcode | 7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab | [
"MIT"
] | null | null | null | SwapNodesinPairs/SwapNodesinPairs_2.cpp | yergen/leetcode | 7b6dac49ac44e0bf43a4ecb4795ea8cfe6afa4ab | [
"MIT"
] | null | null | null | #include<iostream>
#include<string>
using namespace::std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* swapPairs(ListNode* head) {
ListNode **pp = &head, *first, *second;
//a->b->c->d->e->f
while ((first = *pp) && (second = first->next))
{
first->next = second->next;//*pp/head->a->c->d->e->f //b->*pp/a->c->e->f
second->next = first; //b->a->c->d->e->f //d->c->e->f
*pp = second; //*pp/head->b->a->c->d->e->f //b->*pp/a->d->c->e->f
pp = &(first->next); //b->*pp/a->c->d->e->f //b->a->d->*pp/c->e->f
}
return head;
}
};
int main()
{
int a[4] = { 1, 2, 3, 4 };
ListNode *head = new ListNode(0), *point = head;
for (int i = 0; i < 4; i++)
{
point->next = new ListNode(a[i]);
point = point->next;
}
Solution sol;
point = sol.swapPairs(head->next);
while (point)
{
cout << point->val;
point = point->next;
}
cout << endl;
return 0;
} | 20.829787 | 79 | 0.52809 | yergen |
d48302fcce0a0ff2c394d6154b1b0a45d755315d | 2,256 | hpp | C++ | rmf_task/include/rmf_task/Request.hpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | rmf_task/include/rmf_task/Request.hpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | rmf_task/include/rmf_task/Request.hpp | Rouein/rmf_task | 32de25ff127aed754ca760ef462ef8c3e7dd56a1 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2020 Open Source Robotics Foundation
*
* 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.
*
*/
#ifndef RMF_TASK__REQUEST_HPP
#define RMF_TASK__REQUEST_HPP
#include <memory>
#include <rmf_task/Task.hpp>
#include <rmf_utils/impl_ptr.hpp>
namespace rmf_task {
//==============================================================================
class Request
{
public:
/// Constructor
///
/// \param[in] earliest_start_time
/// The desired start time for this request
///
/// \param[in] priority
/// The priority for this request. This is provided by the Priority Scheme.
/// For requests that do not have any priority this is a nullptr.
///
/// \param[in] description
/// The description for this request
///
/// \param[in] automatic
/// True if this request is auto-generated
//
// TODO(MXG): Deprecate this constructor?
Request(
const std::string& id,
rmf_traffic::Time earliest_start_time,
ConstPriorityPtr priority,
Task::ConstDescriptionPtr description,
bool automatic = false);
/// Constructor
///
/// \param[in] booking
/// Booking information for this request
///
/// \param[in] description
/// Description for this request
Request(
Task::ConstBookingPtr booking,
Task::ConstDescriptionPtr description);
/// Get the tag of this request
const Task::ConstBookingPtr& booking() const;
/// Get the description of this request
const Task::ConstDescriptionPtr& description() const;
class Implementation;
private:
rmf_utils::impl_ptr<Implementation> _pimpl;
};
using RequestPtr = std::shared_ptr<Request>;
using ConstRequestPtr = std::shared_ptr<const Request>;
} // namespace rmf_task
#endif // RMF_TASK__REQUEST_HPP
| 26.857143 | 80 | 0.684397 | Rouein |
d487d715d6ea719fc27db2f8bf137b50190f395b | 1,740 | cpp | C++ | Dynamic_Memory_Allocation/Dynamic_Memory_Allocation/main.cpp | b01703020/Financial_Computing | d98d4f6e784997129ece15cdaf33c506e0f35c9e | [
"MIT"
] | null | null | null | Dynamic_Memory_Allocation/Dynamic_Memory_Allocation/main.cpp | b01703020/Financial_Computing | d98d4f6e784997129ece15cdaf33c506e0f35c9e | [
"MIT"
] | null | null | null | Dynamic_Memory_Allocation/Dynamic_Memory_Allocation/main.cpp | b01703020/Financial_Computing | d98d4f6e784997129ece15cdaf33c506e0f35c9e | [
"MIT"
] | null | null | null | //
// main.cpp
// Dynamic_Memory_Allocation
//
// Created by wu yen sun on 2022/2/4.
//
#include <iostream>
using namespace std;
int* getNum1() // Should not return the address of a local variable
{
int num = 10; // num i s a local variable
num += 1;
return # // its address is not reliable once the function is complete
}
int getNum2() // no issue
{
int num = 10;
num += 1;
return num; // the value of num is copied and the copy is returned to main function
}
void getNum3(int* ptr) // call by pointer, no issue
{ // address of y is passed to pointer ptr
*ptr += 1;
}
int* getNum4()
{
int* ptr = new int; // dynamic allocation
*ptr = 10; // deference and assign to 10
*ptr += 1; // deference and add 1
//delete ptr; // can not free memory inside the function as the pointer will be used in main as ptr2
//ptr = NULL;
return ptr; // return the pointer
}
int main()
{
// int* ptr1 = getNum1();
// *ptr1 += 1;
// cout << "*ptr1=" << *ptr1 << endl;
// Function must not return a pointer to a local variable in the function
int x = getNum2();
x += 1;
cout << "x=" << x << endl; // 12
int y = 10;
getNum3(&y);
y += 1;
cout << "y=" << y << endl; // 12
int* ptr2 = nullptr;
ptr2 = getNum4(); // ptr2 is pointing to the allocated memory
*ptr2 += 1;
cout << "*ptr2=" << *ptr2 << endl;
// 12 after comment out free memory and preventing dangling
// free memory before preventing dangling
delete ptr2; // free alocated memory
ptr2 = NULL; // prevent dangling
return 0;
}
| 23.513514 | 110 | 0.551149 | b01703020 |
d48b278d8eee1f8400c0e54d46afe8fdefb1baff | 1,164 | cpp | C++ | Core/src/latest/main/cpp/Capture/Camera.cpp | CJBuchel/CJ-Vision | 60fad66b807c6082fdcf01df9972b42dfc5c5ecc | [
"MIT"
] | 1 | 2020-09-07T09:15:15.000Z | 2020-09-07T09:15:15.000Z | Core/src/latest/main/cpp/Capture/Camera.cpp | CJBuchel/CJ-Vision | 60fad66b807c6082fdcf01df9972b42dfc5c5ecc | [
"MIT"
] | null | null | null | Core/src/latest/main/cpp/Capture/Camera.cpp | CJBuchel/CJ-Vision | 60fad66b807c6082fdcf01df9972b42dfc5c5ecc | [
"MIT"
] | 1 | 2020-09-02T02:02:11.000Z | 2020-09-02T02:02:11.000Z | #include "Capture/Camera.h"
namespace CJ {
Camera::~Camera() {
CJ_CORE_PRINT_WARN("Destroyed Camera, cap released");
cap.release();
}
int Camera::init() {
CJ_CORE_PRINT_INFO("Creating OpenCV Cap");
cap.set(cv::CAP_PROP_FPS, config.fps);
cap.open(config.port, config.apiID);
if (!cap.isOpened()) {
CJ_CORE_PRINT_ERROR(config.name + " Failed to open on port: " + std::to_string(config.port));
return 1;
}
CJ_CORE_PRINT_INFO("Setting frame res");
cap.set(cv::CAP_PROP_FRAME_HEIGHT, config.resHeight);
cap.set(cv::CAP_PROP_FRAME_WIDTH, config.resWidth);
if (config.autoExposure) {
CJ_CORE_PRINT_INFO("Auto exposure enabled");
cap.set(cv::CAP_PROP_AUTO_EXPOSURE, config.cap_prop_autoExpose);
} else {
CJ_CORE_PRINT_INFO("Auto exposure disabled");
cap.set(cv::CAP_PROP_AUTO_EXPOSURE, config.cap_prop_manualExpose);
cap.set(cv::CAP_PROP_EXPOSURE, config.exposure);
CJ_CORE_PRINT_INFO("Exposure: " + std::to_string(config.exposure));
}
return 0;
}
void Camera::capture(Image &image) {
cap.read(image.data);
if (image.data.empty()) {
CJ_CORE_PRINT_ERROR("Cannot get input image. Image empty");
}
}
} | 27.714286 | 96 | 0.710481 | CJBuchel |
d48f288d1cdeabbfc1745184bf55da6e1ad44958 | 2,867 | inl | C++ | MathLib/Include/GaussianQuadrature.inl | bgin/MissileSimulation | 90adcbf1c049daafb939f3fe9f9dfe792f26d5df | [
"MIT"
] | 23 | 2016-08-28T23:20:12.000Z | 2021-12-15T14:43:58.000Z | MathLib/Include/GaussianQuadrature.inl | bgin/MissileSimulation | 90adcbf1c049daafb939f3fe9f9dfe792f26d5df | [
"MIT"
] | 1 | 2018-06-02T21:29:51.000Z | 2018-06-05T05:59:31.000Z | MathLib/Include/GaussianQuadrature.inl | bgin/MissileSimulation | 90adcbf1c049daafb939f3fe9f9dfe792f26d5df | [
"MIT"
] | 1 | 2019-07-04T22:38:22.000Z | 2019-07-04T22:38:22.000Z | template<typename _Ty> __forceinline mathlib::GaussianQdrtr<_Ty>::GaussianQdrtr(const _Ty integr, const _Ty err) : integral(integr),
error(err)
{
}
template<typename _Ty> template<typename Function> __forceinline mathlib::GaussianQdrtr<_Ty> mathlib::GaussianQdrtr<_Ty>::integrate(Function f,
_Ty a, _Ty b)
{
_Ty sum = 0.0 , err = std::numeric_limits<_Ty>::quiet_NaN();
static const _Ty x_vals[] = {
0.1488743389816, 0.4333953941292,
0.6794095682990, 0.8650633666889,
0.9739065285171
};
static const _Ty w_vals[] = {
0.2955242247147, 0.26926671930999,
0.2190863625159, 0.14945134915058,
0.0666713443086
};
_Ty arg_m = 0.5 * (b - a);
_Ty arg_r = 0.5 * (b + a);
const int num_iter = 5;
for (auto i = 0; i != num_iter; ++i)
{
_Ty x = arg_r * x_vals[i];
sum += w_vals[i] * (f(arg_m + x) + f(arg_m - x));
}
return mathlib::GaussianQdrtr<_Ty>((sum * arg_r), err);
}
template<typename _Ty> __forceinline _Ty mathlib::GaussianQdrtr<_Ty>::get_integral() const
{
return this->integral;
}
template<typename _Ty> __forceinline _Ty mathlib::GaussianQdrtr<_Ty>::get_error() const
{
return this->error;
}
template<typename _Ty> __forceinline mathlib::GaussQuadrature<_Ty>::GaussQuadrature()
{
}
template<typename _Ty> __forceinline mathlib::GaussQuadrature<_Ty>::GaussQuadrature(const double aa, const double bb, _Ty &Func) : a(aa),
b(bb), functor(Func), integral(std::numeric_limits<double>::quiet_NaN())
{
}
template<typename _Ty> __forceinline mathlib::GaussQuadrature<_Ty>::GaussQuadrature(const mathlib::GaussQuadrature<_Ty> &rhs) : a(rhs.a),
b(rhs.b), functor(rhs.functor), integral(rhs.integral)
{
}
template<typename _Ty> __forceinline mathlib::GaussQuadrature<_Ty> & mathlib::GaussQuadrature<_Ty>::integrate()
{
static const double x[] =
{
0.1488743389816L, 0.4333953941292L,
0.6794095682990L, 0.8650633666889L,
0.9739065285171L
};
static const double w[] =
{
0.2955242247147L, 0.26926671930999L,
0.2190863625159L, 0.14945134915058L,
0.0666713443086L
};
double arg_m = 0.5L * (this->b - this->a);
double arg_r = 0.5L * (this->b + this->a);
const int num_iter = 5;
for (auto i = 0; i != num_iter; ++i)
{
double x = arg_r * x[i];
this->integral += w[i] * (this->functor(arg_m + x) + this->functor(arg_m - x));
}
this->integral *= arg_r;
return *this;
}
template<typename _Ty> __forceinline double mathlib::GaussQuadrature<_Ty>::get_a() const
{
return this->a;
}
template<typename _Ty> __forceinline double mathlib::GaussQuadrature<_Ty>::get_b() const
{
return this->b;
}
template<typename _Ty> __forceinline double mathlib::GaussQuadrature<_Ty>::get_integral() const
{
return this->integral;
}
template<typename _Ty> __forceinline std::function<double(double)> mathlib::GaussQuadrature<_Ty>::get_functor() const
{
return std::function<double(double)>{this->functor};
}
| 26.546296 | 145 | 0.705964 | bgin |
d4918f230082dd2cbec38248041103e55285940d | 499 | cpp | C++ | src/RE/BSExtraData/ExtraCharge.cpp | thallada/CommonLibSSE | b092c699c3ccd1af6d58d05f677f2977ec054cfe | [
"MIT"
] | 1 | 2021-08-30T20:33:43.000Z | 2021-08-30T20:33:43.000Z | src/RE/BSExtraData/ExtraCharge.cpp | thallada/CommonLibSSE | b092c699c3ccd1af6d58d05f677f2977ec054cfe | [
"MIT"
] | null | null | null | src/RE/BSExtraData/ExtraCharge.cpp | thallada/CommonLibSSE | b092c699c3ccd1af6d58d05f677f2977ec054cfe | [
"MIT"
] | 1 | 2020-10-08T02:48:33.000Z | 2020-10-08T02:48:33.000Z | #include "RE/BSExtraData/ExtraCharge.h"
namespace RE
{
ExtraCharge::ExtraCharge() :
BSExtraData(),
charge(0.0F),
pad14(0)
{
REL::Relocation<std::uintptr_t> vtbl{ Offset::ExtraCharge::Vtbl };
((std::uintptr_t*)this)[0] = vtbl.address();
}
ExtraDataType ExtraCharge::GetType() const
{
return ExtraDataType::kCannotWear;
}
bool ExtraCharge::IsNotEqual(const BSExtraData* a_rhs) const
{
auto rhs = static_cast<const ExtraCharge*>(a_rhs);
return charge != rhs->charge;
}
}
| 17.821429 | 68 | 0.693387 | thallada |
d49304852272523f2d86c823870a53154a52a1e3 | 5,112 | hpp | C++ | src/mgmt/nfd/forwarder-status.hpp | alvyC/ndn-cxx-vanet-ext | 48e8b214416d1b9d3534d26d28c147867f35d311 | [
"OpenSSL"
] | 1 | 2021-09-07T04:12:15.000Z | 2021-09-07T04:12:15.000Z | src/mgmt/nfd/forwarder-status.hpp | alvyC/ndn-cxx-vanet-ext | 48e8b214416d1b9d3534d26d28c147867f35d311 | [
"OpenSSL"
] | null | null | null | src/mgmt/nfd/forwarder-status.hpp | alvyC/ndn-cxx-vanet-ext | 48e8b214416d1b9d3534d26d28c147867f35d311 | [
"OpenSSL"
] | 1 | 2020-07-15T06:21:03.000Z | 2020-07-15T06:21:03.000Z | /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2013-2017 Regents of the University of California.
*
* This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
*
* ndn-cxx library is free software: you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any later version.
*
* ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
* PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details.
*
* You should have received copies of the GNU General Public License and GNU Lesser
* General Public License along with ndn-cxx, e.g., in COPYING.md file. If not, see
* <http://www.gnu.org/licenses/>.
*
* See AUTHORS.md for complete list of ndn-cxx authors and contributors.
*/
#ifndef NDN_MGMT_NFD_FORWARDER_STATUS_HPP
#define NDN_MGMT_NFD_FORWARDER_STATUS_HPP
#include "../../encoding/block.hpp"
#include "../../util/time.hpp"
namespace ndn {
namespace nfd {
/**
* \ingroup management
* \brief represents NFD General Status dataset
* \sa https://redmine.named-data.net/projects/nfd/wiki/ForwarderStatus#General-Status-Dataset
*/
class ForwarderStatus
{
public:
class Error : public tlv::Error
{
public:
explicit
Error(const std::string& what)
: tlv::Error(what)
{
}
};
ForwarderStatus();
explicit
ForwarderStatus(const Block& payload);
/** \brief prepend ForwarderStatus as a Content block to the encoder
*
* The outermost Content element isn't part of ForwarderStatus structure.
*/
template<encoding::Tag TAG>
size_t
wireEncode(EncodingImpl<TAG>& encoder) const;
/** \brief encode ForwarderStatus as a Content block
*
* The outermost Content element isn't part of ForwarderStatus structure.
*/
const Block&
wireEncode() const;
/** \brief decode ForwarderStatus from a Content block
*
* The outermost Content element isn't part of ForwarderStatus structure.
*/
void
wireDecode(const Block& wire);
public: // getters & setters
const std::string&
getNfdVersion() const
{
return m_nfdVersion;
}
ForwarderStatus&
setNfdVersion(const std::string& nfdVersion);
const time::system_clock::TimePoint&
getStartTimestamp() const
{
return m_startTimestamp;
}
ForwarderStatus&
setStartTimestamp(const time::system_clock::TimePoint& startTimestamp);
const time::system_clock::TimePoint&
getCurrentTimestamp() const
{
return m_currentTimestamp;
}
ForwarderStatus&
setCurrentTimestamp(const time::system_clock::TimePoint& currentTimestamp);
size_t
getNNameTreeEntries() const
{
return m_nNameTreeEntries;
}
ForwarderStatus&
setNNameTreeEntries(size_t nNameTreeEntries);
size_t
getNFibEntries() const
{
return m_nFibEntries;
}
ForwarderStatus&
setNFibEntries(size_t nFibEntries);
size_t
getNPitEntries() const
{
return m_nPitEntries;
}
ForwarderStatus&
setNPitEntries(size_t nPitEntries);
size_t
getNMeasurementsEntries() const
{
return m_nMeasurementsEntries;
}
ForwarderStatus&
setNMeasurementsEntries(size_t nMeasurementsEntries);
size_t
getNCsEntries() const
{
return m_nCsEntries;
}
ForwarderStatus&
setNCsEntries(size_t nCsEntries);
uint64_t
getNInInterests() const
{
return m_nInInterests;
}
ForwarderStatus&
setNInInterests(uint64_t nInInterests);
uint64_t
getNInData() const
{
return m_nInData;
}
ForwarderStatus&
setNInData(uint64_t nInData);
uint64_t
getNInNacks() const
{
return m_nInNacks;
}
ForwarderStatus&
setNInNacks(uint64_t nInNacks);
uint64_t
getNOutInterests() const
{
return m_nOutInterests;
}
ForwarderStatus&
setNOutInterests(uint64_t nOutInterests);
uint64_t
getNOutData() const
{
return m_nOutData;
}
ForwarderStatus&
setNOutData(uint64_t nOutData);
uint64_t
getNOutNacks() const
{
return m_nOutNacks;
}
ForwarderStatus&
setNOutNacks(uint64_t nOutNacks);
private:
std::string m_nfdVersion;
time::system_clock::TimePoint m_startTimestamp;
time::system_clock::TimePoint m_currentTimestamp;
size_t m_nNameTreeEntries;
size_t m_nFibEntries;
size_t m_nPitEntries;
size_t m_nMeasurementsEntries;
size_t m_nCsEntries;
uint64_t m_nInInterests;
uint64_t m_nInData;
uint64_t m_nInNacks;
uint64_t m_nOutInterests;
uint64_t m_nOutData;
uint64_t m_nOutNacks;
mutable Block m_wire;
};
NDN_CXX_DECLARE_WIRE_ENCODE_INSTANTIATIONS(ForwarderStatus);
bool
operator==(const ForwarderStatus& a, const ForwarderStatus& b);
inline bool
operator!=(const ForwarderStatus& a, const ForwarderStatus& b)
{
return !(a == b);
}
std::ostream&
operator<<(std::ostream& os, const ForwarderStatus& status);
} // namespace nfd
} // namespace ndn
#endif // NDN_MGMT_NFD_FORWARDER_STATUS_HPP
| 21.3 | 94 | 0.730243 | alvyC |
d49785c624ce4f7e8d5b88b8429f87a36083d462 | 7,107 | cpp | C++ | PineApple/Implment/StrFormat.cpp | BleedingChips/PineApple | 1133d40e93eb3bbad0bde8697f7e8002649c833d | [
"MIT"
] | null | null | null | PineApple/Implment/StrFormat.cpp | BleedingChips/PineApple | 1133d40e93eb3bbad0bde8697f7e8002649c833d | [
"MIT"
] | null | null | null | PineApple/Implment/StrFormat.cpp | BleedingChips/PineApple | 1133d40e93eb3bbad0bde8697f7e8002649c833d | [
"MIT"
] | null | null | null | #include "../Interface/StrFormat.h"
#include "../Interface/Nfa.h"
#include "../Interface/CharEncode.h"
namespace PineApple::StrFormat
{
static std::u32string_view PatternRex[] = {
UR"([^\{\}]+)",
UR"(\{\{)",
UR"(\}\})",
UR"(\{[^\{]*?\})",
};
static Nfa::Table table = Nfa::CreateTableFromRex(PatternRex, 4);
PatternRef CreatePatternRef(std::u32string_view Ref)
{
try {
auto Result = Nfa::Process(table, Ref);
std::vector<PatternRef::Element> patterns;
for (auto& ite : Result)
{
switch (ite.acception)
{
case 0: {
patterns.push_back({ PatternType::NormalString, ite.capture });
} break;
case 1: {
patterns.push_back({ PatternType::LeftBrace, ite.capture });
} break;
case 2: {
patterns.push_back({ PatternType::RightBrace, ite.capture });
} break;
case 3: {
patterns.push_back({ PatternType::Parameter, {ite.capture.data() + 1, ite.capture.size() - 2} });
} break;
default: assert(false);
}
}
return { std::move(patterns) };
}
catch (Nfa::Error::UnaccaptableString const& str)
{
throw Error::UnsupportPatternString{str.TotalString};
}
}
namespace Implement
{
std::tuple<size_t, size_t> LocateParmeters(PatternRef const& pattern, size_t pattern_index)
{
size_t Sum = 0;
for (; pattern_index < pattern.patterns.size(); ++pattern_index)
{
auto& [Type, str] = pattern.patterns[pattern_index];
switch (Type)
{
case PatternType::NormalString: {Sum += str.size(); } break;
case PatternType::RightBrace: {Sum += 1;} break;
case PatternType::LeftBrace: {Sum += 1; } break;
case PatternType::Parameter: {return { pattern_index, Sum}; } break;
default:
break;
}
}
return { pattern_index, Sum};
}
size_t FormatImp(PatternRef const& pattern, size_t pattern_index, std::vector<std::u32string>& output)
{
auto [PIndex, Sum] = LocateParmeters(pattern, pattern_index);
if (PIndex < pattern.patterns.size())
throw Error::LackOfFormatParas{ ExceptionLink(pattern) };
return Sum;
}
std::u32string Link(size_t require_space, PatternRef const& pattern, std::vector<std::u32string>& output)
{
std::u32string Result;
Result.resize(require_space);
size_t Sum = 0;
size_t ParasUsed = 0;
for (auto& ite : pattern.patterns)
{
auto [type, str] = ite;
switch (type)
{
case PatternType::NormalString:
assert(Sum + str.size()<= require_space);
std::memcpy(Result.data() + Sum, str.data(), str.size() * sizeof(char32_t));
Sum += str.size();
break;
case PatternType::Parameter:
if (ParasUsed < output.size())
{
auto& Str = output[ParasUsed++];
assert(Sum + Str.size() <= require_space);
std::memcpy(Result.data() + Sum, Str.data(), Str.size() * sizeof(char32_t));
Sum += Str.size();
}
else {
assert(false);
}
break;
case PatternType::LeftBrace:
assert(Sum + 1 <= require_space);
Result[Sum++] = U'{';
break;
case PatternType::RightBrace:
assert(Sum + 1 <= require_space);
Result[Sum++] = U'}';
break;
default:
assert(false);
break;
}
}
return std::move(Result);
}
std::u32string ExceptionLink(PatternRef const& pattern)
{
size_t size = 0;
for (auto [type, str] : pattern.patterns)
{
switch (type)
{
case PatternType::NormalString:
size += str.size();
break;
case PatternType::LeftBrace:
case PatternType::Parameter:
case PatternType::RightBrace:
size += 2;
break;
default:
assert(false);
break;
}
}
std::u32string Resource;
Resource.reserve(size);
for (auto [type, str] : pattern.patterns)
{
switch (type)
{
case PatternType::NormalString:
Resource += str;
break;
case PatternType::Parameter:
Resource += U"{}";
break;
case PatternType::LeftBrace:
Resource += U"{{";
break;
case PatternType::RightBrace:
Resource += U"}}";
break;
default:
assert(false);
break;
}
}
return Resource;
}
}
}
namespace PineApple::StrFormat
{
static std::u32string_view FormatRex[] = {
UR"(\s)",
UR"(-hex)",
//UR"(-e)"
};
static Nfa::Table FormatTable = Nfa::CreateTableFromRexReversal(FormatRex, 2);
struct Paras
{
bool IsHex = false;
};
Paras ParasTranslate(std::u32string_view Code)
{
Paras Result;
//std::optional<std::string> size_require;
auto Re = Nfa::Process(FormatTable, Code);
for (auto& ite : Re)
{
switch (ite.acception)
{
case 0: {} break;
case 1: {Result.IsHex = true; } break;
//case 2: {IsE = true; } break;
//case 3: {size_require = Encoding::EncodingWrapper<char32_t>({ ite.capture.data() + 1, ite.capture.size() - 1 }).To<char>();} break;
default:
break;
}
}
return Result;
}
std::u32string Formatter<char32_t*>::operator()(std::u32string_view par, char32_t const* Input) { return std::u32string(Input); }
std::u32string Formatter<std::u32string>::operator()(std::u32string_view par, std::u32string Input) { return std::move(Input); }
std::u32string Formatter<float>::operator()(std::u32string_view par, float input) {
char Buffer[100];
size_t t = sprintf_s(Buffer, 100, "%f", input);
return CharEncode::Wrapper<char>(std::string_view{Buffer, t}).To<char32_t>();
}
std::u32string Formatter<double>::operator()(std::u32string_view par, double input) {
char Buffer[100];
size_t t = sprintf_s(Buffer, 100, "%lf", input);
return CharEncode::Wrapper<char>(std::string_view{ Buffer, t }).To<char32_t>();
}
std::u32string Formatter<uint32_t>::operator()(std::u32string_view par, uint32_t input) {
Paras state = ParasTranslate(par);
char const* TarString = nullptr;
if (state.IsHex)
TarString = "%I32x";
else
TarString = "%I32u";
char Buffer[100];
size_t t = sprintf_s(Buffer, 100, TarString, input);
return CharEncode::Wrapper<char>(std::string_view{ Buffer, t }).To<char32_t>();
}
std::u32string Formatter<int32_t>::operator()(std::u32string_view par, int32_t input) {
//Paras state = ParasTranslate(par);
char const* TarString = nullptr;
TarString = "%I32d";
char Buffer[100];
size_t t = sprintf_s(Buffer, 100, TarString, input);
return CharEncode::Wrapper<char>(std::string_view{ Buffer, t }).To<char32_t>();
}
std::u32string Formatter<uint64_t>::operator()(std::u32string_view par, uint64_t input) {
Paras state = ParasTranslate(par);
char const* TarString = nullptr;
if (state.IsHex)
TarString = "%I64x";
else
TarString = "%I64u";
char Buffer[100];
size_t t = sprintf_s(Buffer, 100, TarString, input);
return CharEncode::Wrapper<char>(std::string_view{ Buffer, t }).To<char32_t>();
}
std::u32string Formatter<int64_t>::operator()(std::u32string_view par, int64_t input) {
//Paras state = ParasTranslate(par);
char const* TarString = nullptr;
TarString = "%I64d";
char Buffer[100];
size_t t = sprintf_s(Buffer, 100, TarString, input);
return CharEncode::Wrapper<char>(std::string_view{ Buffer, t }).To<char32_t>();
}
} | 27.761719 | 136 | 0.638525 | BleedingChips |
d4988c9dd0bdd35136e8902ce052e10cffa63e3d | 3,267 | cpp | C++ | src/MirkoInterface.cpp | stephan2nd/cpp-accelerator-toolkit | 1c82f87b50199ec216a0d8968ed320fa9a52c48f | [
"MIT"
] | null | null | null | src/MirkoInterface.cpp | stephan2nd/cpp-accelerator-toolkit | 1c82f87b50199ec216a0d8968ed320fa9a52c48f | [
"MIT"
] | null | null | null | src/MirkoInterface.cpp | stephan2nd/cpp-accelerator-toolkit | 1c82f87b50199ec216a0d8968ed320fa9a52c48f | [
"MIT"
] | null | null | null | #include "MirkoInterface.hpp"
#include "DriftTube.hpp"
#include "QuadrupoleMagnet.hpp"
#include "Screen.hpp"
#include "HKick.hpp"
#include "VKick.hpp"
#include "RectangularDipoleMagnet.hpp"
#include <sstream>
#include <fstream>
#include <cmath>
MirkoInterface::MirkoInterface() :
m_devices()
{ }
MirkoInterface::~MirkoInterface()
{ }
string
MirkoInterface::toString(unsigned int indent) const
{
string indention = "";
for( unsigned int i=0; i<indent; i++ ){
indention = indention + "\t";
}
stringstream ss;
ss << indention << toLine();
return ss.str();
}
string
MirkoInterface::toLine(void) const
{
return "MirkoInterface";
}
ostream&
operator<<(ostream& os, const MirkoInterface& mirkoInterface)
{
return os << mirkoInterface.toLine();
}
void
MirkoInterface::readMixFile(const string& filename)
{
const unsigned int STATE_UNKNOWN = 0;
const unsigned int STATE_DEVICES = 1;
unsigned int state = STATE_UNKNOWN;
ifstream file(filename);
string line;
while( std::getline(file, line) )
{
if( line.substr(0, 1) == "!" ){
;
} else if( line.substr(0, 1) == "$" ){
if( line.substr(0, 9) == "$ELEMENTE" ){
state = STATE_DEVICES;
} else {
state = STATE_UNKNOWN;
}
} else if( state == STATE_DEVICES ){
parseDeviceFromMixFileLine(line);
}
}
}
void
MirkoInterface::parseDeviceFromMixFileLine(const string& line)
{
string name = line.substr(3,16);
int vcode = 0;
int type = 0;
int sub = 1;
double arg1 = 0.0;
double arg2= 0.0;
double arg3 = 0.0;
double arg4 = 0.0;
try{
vcode = stoi(line.substr(19,4));
} catch( exception& e){
vcode = 0;
}
try{
type = stoi(line.substr(23,4));
} catch( exception& e){
type = 0;
cout << __FILE__ << " line " << __LINE__ << ": cannot parse type \"" << line.substr(23,4) << "\" to int, " << e.what() << endl;
}
try{
sub = stoi(line.substr(27,4));
} catch( exception& e){
sub = 1;
}
try{
arg1 = stod(line.substr(31,17));
} catch( exception& e){
arg1 = 0.0;
}
try{
arg2 = stod(line.substr(48,17));
} catch( exception& e){
arg2 = 0.0;
}
try{
arg3 = stod(line.substr(65,12));
} catch( exception& e){
arg3 = 0.0;
}
try{
arg4 = stod(line.substr(77,12));
} catch( exception& e){
arg4 = 0.0;
}
addDevice(name, vcode, type, sub, arg1, arg2, arg3, arg4);
}
void
MirkoInterface::addDevice(const string& name, int vcode, int type, int sub, double arg1, double arg2, double arg3, double arg4)
{
switch (type){
case 2:
m_devices.push_back( new DriftTube(name, 0.2, 0.2, arg1) );
break;
case 3:
m_devices.push_back( new QuadrupoleMagnet(name, arg3, arg4, arg1, 1000000*arg2*arg2) );
break;
case 5:
m_devices.push_back( new RectangularDipoleMagnet(name, arg3, arg4, arg2 * M_PI * arg1/180., M_PI * arg1/180.) );
break;
case 21:
m_devices.push_back( new HKick(name, arg1) );
break;
case 22:
m_devices.push_back( new VKick(name, arg1) );
break;
case 29:
m_devices.push_back( new Screen(name, 0.2, 0.2) );
break;
case 30:
break;
default:
cout << "MirkoInterface, unkown device type " << type << ". skipped!" << endl;
}
}
vector<Device*>
MirkoInterface::getDevices() const
{
return m_devices;
}
| 17.852459 | 129 | 0.628099 | stephan2nd |
d49bbdc3b0b40a4b9d18f4ad68cce2ed3634ca28 | 5,090 | cpp | C++ | contrib/MassSpectra/flexiblesusy/models/SSM/SSM_two_scale_susy_beta_Lambdax.cpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/MassSpectra/flexiblesusy/models/SSM/SSM_two_scale_susy_beta_Lambdax.cpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | contrib/MassSpectra/flexiblesusy/models/SSM/SSM_two_scale_susy_beta_Lambdax.cpp | aaronvincent/gambit_aaron | a38bd6fc10d781e71f2adafd401c76e1e3476b05 | [
"Unlicense"
] | null | null | null | // ====================================================================
// This file is part of FlexibleSUSY.
//
// FlexibleSUSY 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.
//
// FlexibleSUSY 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 FlexibleSUSY. If not, see
// <http://www.gnu.org/licenses/>.
// ====================================================================
// File generated at Sat 27 Aug 2016 12:40:17
#include "SSM_two_scale_susy_parameters.hpp"
#include "wrappers.hpp"
namespace flexiblesusy {
#define INPUT(parameter) input.parameter
#define TRACE_STRUCT susy_traces
/**
* Calculates the one-loop beta function of Lambdax.
*
* @return one-loop beta function
*/
double SSM_susy_parameters::calc_beta_Lambdax_one_loop(const Susy_traces& susy_traces) const
{
const double traceYdAdjYd = TRACE_STRUCT.traceYdAdjYd;
const double traceYeAdjYe = TRACE_STRUCT.traceYeAdjYe;
const double traceYuAdjYu = TRACE_STRUCT.traceYuAdjYu;
const double traceYdAdjYdYdAdjYd = TRACE_STRUCT.traceYdAdjYdYdAdjYd;
const double traceYeAdjYeYeAdjYe = TRACE_STRUCT.traceYeAdjYeYeAdjYe;
const double traceYuAdjYuYuAdjYu = TRACE_STRUCT.traceYuAdjYuYuAdjYu;
double beta_Lambdax;
beta_Lambdax = Re(oneOver16PiSqr*(0.27*Power(g1,4) + 2.25*Power(g2,4)
- 12*traceYdAdjYdYdAdjYd - 4*traceYeAdjYeYeAdjYe - 12*traceYuAdjYuYuAdjYu
+ 12*traceYdAdjYd*Lambdax + 4*traceYeAdjYe*Lambdax + 12*traceYuAdjYu*
Lambdax - 1.8*Lambdax*Sqr(g1) - 9*Lambdax*Sqr(g2) + 0.9*Sqr(g1)*Sqr(g2) +
Sqr(K2) + 12*Sqr(Lambdax)));
return beta_Lambdax;
}
/**
* Calculates the two-loop beta function of Lambdax.
*
* @return two-loop beta function
*/
double SSM_susy_parameters::calc_beta_Lambdax_two_loop(const Susy_traces& susy_traces) const
{
const double traceYdAdjYd = TRACE_STRUCT.traceYdAdjYd;
const double traceYeAdjYe = TRACE_STRUCT.traceYeAdjYe;
const double traceYuAdjYu = TRACE_STRUCT.traceYuAdjYu;
const double traceYdAdjYdYdAdjYd = TRACE_STRUCT.traceYdAdjYdYdAdjYd;
const double traceYdAdjYuYuAdjYd = TRACE_STRUCT.traceYdAdjYuYuAdjYd;
const double traceYeAdjYeYeAdjYe = TRACE_STRUCT.traceYeAdjYeYeAdjYe;
const double traceYuAdjYuYuAdjYu = TRACE_STRUCT.traceYuAdjYuYuAdjYu;
const double traceYdAdjYdYdAdjYdYdAdjYd =
TRACE_STRUCT.traceYdAdjYdYdAdjYdYdAdjYd;
const double traceYdAdjYdYdAdjYuYuAdjYd =
TRACE_STRUCT.traceYdAdjYdYdAdjYuYuAdjYd;
const double traceYdAdjYuYuAdjYdYdAdjYd =
TRACE_STRUCT.traceYdAdjYuYuAdjYdYdAdjYd;
const double traceYdAdjYuYuAdjYuYuAdjYd =
TRACE_STRUCT.traceYdAdjYuYuAdjYuYuAdjYd;
const double traceYeAdjYeYeAdjYeYeAdjYe =
TRACE_STRUCT.traceYeAdjYeYeAdjYeYeAdjYe;
const double traceYuAdjYuYuAdjYuYuAdjYu =
TRACE_STRUCT.traceYuAdjYuYuAdjYuYuAdjYu;
double beta_Lambdax;
beta_Lambdax = Re(twoLoop*(-3.411*Power(g1,6) + 38.125*Power(g2,6) - 4
*Power(K2,3) + 60*traceYdAdjYdYdAdjYdYdAdjYd - 24*
traceYdAdjYdYdAdjYuYuAdjYd + 12*traceYdAdjYuYuAdjYdYdAdjYd - 12*
traceYdAdjYuYuAdjYuYuAdjYd + 20*traceYeAdjYeYeAdjYeYeAdjYe - 3.42*Power(
g1,4)*traceYuAdjYu - 4.5*Power(g2,4)*traceYuAdjYu + 60*
traceYuAdjYuYuAdjYuYuAdjYu + 9.435*Power(g1,4)*Lambdax - 9.125*Power(g2,4
)*Lambdax - 3*traceYdAdjYdYdAdjYd*Lambdax - 42*traceYdAdjYuYuAdjYd*
Lambdax - traceYeAdjYeYeAdjYe*Lambdax - 3*traceYuAdjYuYuAdjYu*Lambdax -
78*Power(Lambdax,3) - 7.225*Power(g2,4)*Sqr(g1) + 1.6*traceYdAdjYdYdAdjYd
*Sqr(g1) - 4.8*traceYeAdjYeYeAdjYe*Sqr(g1) - 3.2*traceYuAdjYuYuAdjYu*Sqr(
g1) + 8.5*traceYuAdjYu*Lambdax*Sqr(g1) - 8.385*Power(g1,4)*Sqr(g2) + 22.5
*traceYuAdjYu*Lambdax*Sqr(g2) + 12.6*traceYuAdjYu*Sqr(g1)*Sqr(g2) + 5.85*
Lambdax*Sqr(g1)*Sqr(g2) - 64*traceYdAdjYdYdAdjYd*Sqr(g3) - 64*
traceYuAdjYuYuAdjYu*Sqr(g3) + 80*traceYuAdjYu*Lambdax*Sqr(g3) + 0.1*
traceYdAdjYd*(9*Power(g1,4) - 45*Power(g2,4) + 225*Lambdax*Sqr(g2) + Sqr(
g1)*(25*Lambdax + 54*Sqr(g2)) + 80*Lambdax*(-9*Lambdax + 10*Sqr(g3))) - 5
*Lambdax*Sqr(K2) - 72*traceYuAdjYu*Sqr(Lambdax) + 10.8*Sqr(g1)*Sqr(
Lambdax) + 54*Sqr(g2)*Sqr(Lambdax) - 0.3*traceYeAdjYe*(15*Power(g1,4) -
Sqr(g1)*(25*Lambdax + 22*Sqr(g2)) + 5*(Power(g2,4) - 5*Lambdax*Sqr(g2) +
16*Sqr(Lambdax)))));
return beta_Lambdax;
}
/**
* Calculates the three-loop beta function of Lambdax.
*
* @return three-loop beta function
*/
double SSM_susy_parameters::calc_beta_Lambdax_three_loop(const Susy_traces& susy_traces) const
{
DEFINE_PROJECTOR(3,3,3,3)
double beta_Lambdax;
beta_Lambdax = 0;
return beta_Lambdax;
}
} // namespace flexiblesusy
| 38.854962 | 94 | 0.718271 | aaronvincent |