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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1fc95d0aadecd40818e99d9d6f7727a1ef32315d | 596 | cpp | C++ | binary-search/binary_search.cpp | aydinsimsek/exercism-solutions-cpp | 6d7c8d37f628840559509d7f6e5b7788c8c637b6 | [
"MIT"
] | 1 | 2022-02-04T19:22:58.000Z | 2022-02-04T19:22:58.000Z | binary-search/binary_search.cpp | aydinsimsek/exercism-solutions-cpp | 6d7c8d37f628840559509d7f6e5b7788c8c637b6 | [
"MIT"
] | null | null | null | binary-search/binary_search.cpp | aydinsimsek/exercism-solutions-cpp | 6d7c8d37f628840559509d7f6e5b7788c8c637b6 | [
"MIT"
] | null | null | null | #include "binary_search.h"
#include <algorithm>
#include <stdexcept>
using namespace std;
namespace binary_search {
int find(vector <int> v, int key)
{
sort(v.begin(), v.end());
int first = 0;
int last = v.size() - 1;
while (first <= last)
{
if (v[(first + last) / 2] == key)
{
return (first + last) / 2;
}
else if (key < v[(first + last) / 2])
{
last = (first + last) / 2 - 1;
}
else if (key > v[(first + last) / 2])
{
first = (first + last) / 2 + 1;
}
}
throw domain_error("Key is not found");
}
} // namespace binary_search
| 19.225806 | 42 | 0.536913 | aydinsimsek |
1fc9874e28b560c0716ca47cf04fcab29e04ea94 | 3,486 | cpp | C++ | leetcode/2157/solution_4_1.cpp | mkmark/leetcode | 638a9d37fb3223107d2852ce493d831996a7649e | [
"MIT"
] | null | null | null | leetcode/2157/solution_4_1.cpp | mkmark/leetcode | 638a9d37fb3223107d2852ce493d831996a7649e | [
"MIT"
] | null | null | null | leetcode/2157/solution_4_1.cpp | mkmark/leetcode | 638a9d37fb3223107d2852ce493d831996a7649e | [
"MIT"
] | null | null | null | /*
author: mark@mkmark.net
time: O()
space: O()
Runtime: 1270 ms, faster than 64.18% of C++ online submissions for Groups of Strings.
Memory Usage: 68.5 MB, less than 69.73% of C++ online submissions for Groups of Strings.
*/
// profiled
#include <bits/stdc++.h>
using namespace std;
class disjoint_set {
public:
vector<int> parent;
vector<int> size;
vector<int> sum_val;
int set_cnt;
int max_sum_val;
disjoint_set(int max_size) {
parent.resize(max_size);
size.resize(max_size);
sum_val.resize(max_size);
for (int i=0; i<max_size; ++i) {
parent[i] = i;
size[i] = 1;
}
}
disjoint_set(int max_size, vector<int>& val): sum_val(val) {
parent.resize(max_size);
size.resize(max_size);
sum_val.resize(max_size);
for (int i=0; i<max_size; ++i) {
parent[i] = i;
size[i] = 1;
}
set_cnt = max_size;
max_sum_val = 1;
}
int get_set(int x) {
if (x == parent[x])
return x;
return parent[x] = get_set(parent[x]);
}
void union_set(int a, int b) {
a = get_set(a);
b = get_set(b);
if (a != b) {
if (size[a] > size[b])
swap(a, b);
parent[a] = b;
size[b] += size[a];
sum_val[b] += sum_val[a];
max_sum_val = max(max_sum_val, sum_val[b]);
--set_cnt;
}
}
};
class Solution {
public:
vector<int> groupStrings(vector<string>& words) {
bitset<26> words_b[20000];
unordered_map<int, int> words_b_count;
int n = words.size();
int cnt = 0;
for (int i=0; i<n; ++i){
auto word_b = to_b(words[i]);
auto mask = word_b.to_ulong();
if (words_b_count[mask]){
++words_b_count[mask];
} else {
words_b[cnt++] = word_b;
words_b_count[mask] = 1;
}
}
sort(words_b, words_b+cnt, [](bitset<26>& i, bitset<26>& j){return i.count() < j.count();});
int m = cnt;
if (m == 1){
vector<int> res = { 1, words_b_count[words_b[0].to_ulong()] };
return res;
}
vector<int> word_length(m);
vector<int> val(m);
for (int i=0; i<m; ++i){
val[i] = words_b_count[words_b[i].to_ulong()];
word_length[i] = words_b[i].count();
}
disjoint_set ds(m, val);
for (int i=0; i<m; ++i){
for (int j=i+1; j<m; ++j){
int diff_length = word_length[j] - word_length[i];
// rely on sorted vec
if (diff_length > 1){
break;
}
auto diff_cnt = (words_b[i] ^ words_b[j]).count();
if (
diff_cnt <= 1 ||
(diff_cnt == 2 && diff_length == 0)
){
ds.union_set(i, j);
}
}
}
vector<int> res = { ds.set_cnt, ds.max_sum_val };
return res;
}
inline bitset<26> to_b(string word){
bitset<26> b;
for (auto c : word) {
b |= (1<<(c-'a'));
}
return b;
}
};
const static auto initialize = [] {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
std::cout.tie(nullptr);
return nullptr;
}();
| 24.208333 | 100 | 0.468158 | mkmark |
1fca9e88a75f99b52e4f3db97003bff3fe704254 | 151,337 | cpp | C++ | cslbuild/generated-c/u37.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | cslbuild/generated-c/u37.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null | cslbuild/generated-c/u37.cpp | arthurcnorman/general | 5e8fef0cc7999fa8ab75d8fdf79ad5488047282b | [
"BSD-2-Clause"
] | null | null | null |
// $destdir/u37.c Machine generated C code
// $Id: 1fca9e88a75f99b52e4f3db97003bff3fe704254 $
#include "config.h"
#include "headers.h"
// Code for lessppair
static LispObject CC_lessppair(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_25, v_26, v_27, v_28;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_26 = v_3;
v_27 = v_2;
// end of prologue
v_25 = v_27;
if (!car_legal(v_25)) v_28 = carerror(v_25); else
v_28 = car(v_25);
v_25 = v_26;
if (!car_legal(v_25)) v_25 = carerror(v_25); else
v_25 = car(v_25);
if (equal(v_28, v_25)) goto v_7;
else goto v_8;
v_7:
v_25 = v_27;
if (!car_legal(v_25)) v_25 = cdrerror(v_25); else
v_25 = cdr(v_25);
if (!car_legal(v_26)) v_26 = cdrerror(v_26); else
v_26 = cdr(v_26);
return Llessp_2(nil, v_25, v_26);
v_8:
v_25 = v_27;
if (!car_legal(v_25)) v_25 = carerror(v_25); else
v_25 = car(v_25);
if (!car_legal(v_26)) v_26 = carerror(v_26); else
v_26 = car(v_26);
return Llessp_2(nil, v_25, v_26);
v_25 = nil;
return onevalue(v_25);
}
// Code for lalr_print_first_information
static LispObject CC_lalr_print_first_information(LispObject env)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_52, v_53;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
env = reclaim(env, "stack", GC_STACK, 0);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// end of prologue
v_52 = basic_elt(env, 1); // "=== FIRST sets for each nonterminal ==="
v_52 = Lprinc(nil, v_52);
env = stack[-2];
v_52 = Lterpri(nil);
env = stack[-2];
v_52 = qvalue(basic_elt(env, 2)); // nonterminals
stack[-1] = v_52;
v_9:
v_52 = stack[-1];
if (v_52 == nil) goto v_13;
else goto v_14;
v_13:
goto v_8;
v_14:
v_52 = stack[-1];
if (!car_legal(v_52)) v_52 = carerror(v_52); else
v_52 = car(v_52);
stack[0] = v_52;
v_52 = stack[0];
{ LispObject fn = basic_elt(env, 6); // lalr_prin_symbol
v_52 = (*qfn1(fn))(fn, v_52);
}
env = stack[-2];
v_52 = basic_elt(env, 3); // ":"
v_52 = Lprinc(nil, v_52);
env = stack[-2];
v_52 = static_cast<LispObject>(320)+TAG_FIXNUM; // 20
v_52 = Lttab(nil, v_52);
env = stack[-2];
v_53 = stack[0];
v_52 = basic_elt(env, 4); // lalr_first
v_52 = get(v_53, v_52);
env = stack[-2];
stack[0] = v_52;
v_29:
v_52 = stack[0];
if (v_52 == nil) goto v_35;
else goto v_36;
v_35:
goto v_28;
v_36:
v_52 = stack[0];
if (!car_legal(v_52)) v_52 = carerror(v_52); else
v_52 = car(v_52);
{ LispObject fn = basic_elt(env, 6); // lalr_prin_symbol
v_52 = (*qfn1(fn))(fn, v_52);
}
env = stack[-2];
v_52 = basic_elt(env, 5); // " "
v_52 = Lprinc(nil, v_52);
env = stack[-2];
v_52 = stack[0];
if (!car_legal(v_52)) v_52 = cdrerror(v_52); else
v_52 = cdr(v_52);
stack[0] = v_52;
goto v_29;
v_28:
v_52 = Lterpri(nil);
env = stack[-2];
v_52 = stack[-1];
if (!car_legal(v_52)) v_52 = cdrerror(v_52); else
v_52 = cdr(v_52);
stack[-1] = v_52;
goto v_9;
v_8:
return Lterpri(nil);
}
// Code for smt_prin2x
static LispObject CC_smt_prin2x(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_7, v_8;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
stack_popper stack_popper_var(1);
// copy arguments values to proper place
v_7 = v_2;
// end of prologue
v_8 = v_7;
v_7 = qvalue(basic_elt(env, 1)); // outl!*
v_7 = cons(v_8, v_7);
env = stack[0];
setvalue(basic_elt(env, 1), v_7); // outl!*
return onevalue(v_7);
}
// Code for ofsf_simplequal
static LispObject CC_ofsf_simplequal(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_64, v_65, v_66;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil, nil);
stack_popper stack_popper_var(5);
// copy arguments values to proper place
stack[-1] = v_3;
stack[-2] = v_2;
// end of prologue
v_64 = stack[-2];
{ LispObject fn = basic_elt(env, 8); // ofsf_posdefp
v_64 = (*qfn1(fn))(fn, v_64);
}
env = stack[-4];
stack[-3] = v_64;
v_65 = stack[-3];
v_64 = basic_elt(env, 1); // stsq
if (v_65 == v_64) goto v_14;
else goto v_15;
v_14:
v_64 = basic_elt(env, 2); // false
goto v_9;
v_15:
v_64 = stack[-2];
{ LispObject fn = basic_elt(env, 9); // sfto_sqfpartf
v_64 = (*qfn1(fn))(fn, v_64);
}
env = stack[-4];
stack[0] = v_64;
v_64 = stack[0];
{ LispObject fn = basic_elt(env, 8); // ofsf_posdefp
v_64 = (*qfn1(fn))(fn, v_64);
}
env = stack[-4];
v_66 = v_64;
v_65 = v_66;
v_64 = basic_elt(env, 1); // stsq
if (v_65 == v_64) goto v_25;
else goto v_26;
v_25:
v_64 = basic_elt(env, 2); // false
goto v_9;
v_26:
v_64 = qvalue(basic_elt(env, 3)); // !*rlsitsqspl
if (v_64 == nil) goto v_33;
v_64 = qvalue(basic_elt(env, 4)); // !*rlsiexpla
if (v_64 == nil) goto v_37;
else goto v_36;
v_37:
v_64 = qvalue(basic_elt(env, 5)); // !*rlsiexpl
if (v_64 == nil) goto v_39;
v_65 = stack[-1];
v_64 = basic_elt(env, 6); // and
if (v_65 == v_64) goto v_42;
else goto v_39;
v_42:
goto v_36;
v_39:
goto v_33;
v_36:
v_65 = v_66;
v_64 = basic_elt(env, 7); // tsq
if (v_65 == v_64) goto v_47;
else goto v_48;
v_47:
v_64 = stack[0];
{
LispObject fn = basic_elt(env, 10); // ofsf_tsqsplequal
return (*qfn1(fn))(fn, v_64);
}
v_48:
v_65 = stack[-3];
v_64 = basic_elt(env, 7); // tsq
if (v_65 == v_64) goto v_55;
else goto v_56;
v_55:
v_64 = stack[-2];
{
LispObject fn = basic_elt(env, 10); // ofsf_tsqsplequal
return (*qfn1(fn))(fn, v_64);
}
v_56:
goto v_31;
v_33:
v_31:
v_65 = stack[0];
v_64 = stack[-1];
{
LispObject fn = basic_elt(env, 11); // ofsf_facequal!*
return (*qfn2(fn))(fn, v_65, v_64);
}
v_9:
return onevalue(v_64);
}
// Code for pasf_exprng!-gand
static LispObject CC_pasf_exprngKgand(LispObject env, LispObject v_2,
LispObject v_3, LispObject v_4, LispObject _a4up_)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_86, v_87, v_88;
LispObject v_5;
if (_a4up_ == nil)
aerror1("not enough arguments provided", basic_elt(env, 0));
v_5 = car(_a4up_); _a4up_ = cdr(_a4up_);
if (_a4up_ != nil)
aerror1("too many arguments provided", basic_elt(env, 0));
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4,v_5);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_5,v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
real_push(nil);
stack_popper stack_popper_var(7);
// copy arguments values to proper place
stack[-1] = v_5;
stack[-2] = v_4;
stack[-3] = v_3;
stack[-4] = v_2;
// end of prologue
stack[0] = nil;
v_86 = lisp_true;
stack[-5] = v_86;
v_16:
v_86 = stack[-5];
if (v_86 == nil) goto v_19;
v_86 = stack[-3];
if (v_86 == nil) goto v_19;
goto v_20;
v_19:
goto v_15;
v_20:
v_86 = stack[-3];
if (!car_legal(v_86)) v_86 = carerror(v_86); else
v_86 = car(v_86);
v_87 = v_86;
v_86 = stack[-3];
if (!car_legal(v_86)) v_86 = cdrerror(v_86); else
v_86 = cdr(v_86);
stack[-3] = v_86;
v_86 = v_87;
{ LispObject fn = basic_elt(env, 4); // pasf_exprng
v_86 = (*qfn1(fn))(fn, v_86);
}
env = stack[-6];
v_88 = v_86;
v_87 = v_88;
v_86 = stack[-1];
if (v_87 == v_86) goto v_39;
else goto v_40;
v_39:
v_86 = nil;
stack[-5] = v_86;
goto v_38;
v_40:
v_87 = v_88;
v_86 = stack[-2];
if (equal(v_87, v_86)) goto v_45;
v_87 = v_88;
v_86 = stack[0];
v_86 = cons(v_87, v_86);
env = stack[-6];
stack[0] = v_86;
goto v_38;
v_45:
v_38:
goto v_16;
v_15:
v_86 = stack[-5];
if (v_86 == nil) goto v_53;
else goto v_54;
v_53:
v_86 = stack[-1];
goto v_12;
v_54:
v_86 = stack[0];
if (v_86 == nil) goto v_60;
v_86 = stack[0];
if (!car_legal(v_86)) v_86 = cdrerror(v_86); else
v_86 = cdr(v_86);
if (v_86 == nil) goto v_60;
v_87 = stack[-4];
v_86 = stack[0];
return cons(v_87, v_86);
v_60:
v_86 = stack[0];
if (v_86 == nil) goto v_69;
else goto v_70;
v_69:
v_87 = stack[-4];
v_86 = basic_elt(env, 1); // and
if (v_87 == v_86) goto v_74;
else goto v_75;
v_74:
v_86 = basic_elt(env, 2); // true
goto v_73;
v_75:
v_86 = basic_elt(env, 3); // false
goto v_73;
v_86 = nil;
v_73:
goto v_58;
v_70:
v_86 = stack[0];
if (!car_legal(v_86)) v_86 = carerror(v_86); else
v_86 = car(v_86);
goto v_58;
v_86 = nil;
v_58:
v_12:
return onevalue(v_86);
}
// Code for bvarom
static LispObject CC_bvarom(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_29, v_30;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
v_29 = stack[0];
if (!car_legal(v_29)) v_29 = carerror(v_29); else
v_29 = car(v_29);
v_29 = Lconsp(nil, v_29);
env = stack[-1];
if (v_29 == nil) goto v_9;
v_29 = stack[0];
if (!car_legal(v_29)) v_29 = carerror(v_29); else
v_29 = car(v_29);
if (!car_legal(v_29)) v_30 = carerror(v_29); else
v_30 = car(v_29);
v_29 = basic_elt(env, 1); // bvar
if (v_30 == v_29) goto v_15;
else goto v_16;
v_15:
v_29 = stack[0];
if (!car_legal(v_29)) v_29 = carerror(v_29); else
v_29 = car(v_29);
if (!car_legal(v_29)) v_29 = cdrerror(v_29); else
v_29 = cdr(v_29);
if (!car_legal(v_29)) v_29 = carerror(v_29); else
v_29 = car(v_29);
{ LispObject fn = basic_elt(env, 2); // objectom
v_29 = (*qfn1(fn))(fn, v_29);
}
env = stack[-1];
v_29 = stack[0];
if (!car_legal(v_29)) v_29 = cdrerror(v_29); else
v_29 = cdr(v_29);
{ LispObject fn = basic_elt(env, 0); // bvarom
v_29 = (*qfn1(fn))(fn, v_29);
}
goto v_14;
v_16:
v_14:
goto v_7;
v_9:
v_7:
v_29 = nil;
return onevalue(v_29);
}
// Code for s!-nextarg
static LispObject CC_sKnextarg(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_134, v_135, v_136;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
v_134 = qvalue(basic_elt(env, 1)); // !*udebug
if (v_134 == nil) goto v_11;
v_134 = nil;
{ LispObject fn = basic_elt(env, 12); // uprint
v_134 = (*qfn1(fn))(fn, v_134);
}
env = stack[-2];
goto v_9;
v_11:
v_9:
v_134 = qvalue(basic_elt(env, 2)); // comb
if (v_134 == nil) goto v_17;
else goto v_18;
v_17:
v_134 = qvalue(basic_elt(env, 3)); // i
v_134 = add1(v_134);
env = stack[-2];
setvalue(basic_elt(env, 3), v_134); // i
v_134 = stack[0];
{ LispObject fn = basic_elt(env, 13); // initcomb
v_134 = (*qfn1(fn))(fn, v_134);
}
env = stack[-2];
setvalue(basic_elt(env, 2), v_134); // comb
goto v_16;
v_18:
v_16:
v_135 = stack[0];
v_134 = qvalue(basic_elt(env, 2)); // comb
{ LispObject fn = basic_elt(env, 14); // getcomb
v_134 = (*qfn2(fn))(fn, v_135, v_134);
}
env = stack[-2];
stack[-1] = v_134;
if (v_134 == nil) goto v_27;
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
if (v_135 == v_134) goto v_37;
else goto v_38;
v_37:
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = qvalue(basic_elt(env, 4)); // upb
v_134 = static_cast<LispObject>(lesseq2(v_135, v_134));
v_134 = v_134 ? lisp_true : nil;
env = stack[-2];
goto v_36;
v_38:
v_134 = nil;
goto v_36;
v_134 = nil;
v_36:
if (v_134 == nil) goto v_34;
v_134 = stack[-1];
if (!car_legal(v_134)) v_134 = carerror(v_134); else
v_134 = car(v_134);
if (!car_legal(v_134)) v_135 = carerror(v_134); else
v_135 = car(v_134);
v_134 = stack[-1];
if (!car_legal(v_134)) v_134 = cdrerror(v_134); else
v_134 = cdr(v_134);
return cons(v_135, v_134);
v_34:
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
if (v_135 == v_134) goto v_57;
else goto v_58;
v_57:
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = qvalue(basic_elt(env, 4)); // upb
v_134 = static_cast<LispObject>(lesseq2(v_135, v_134));
v_134 = v_134 ? lisp_true : nil;
env = stack[-2];
goto v_56;
v_58:
v_134 = nil;
goto v_56;
v_134 = nil;
v_56:
if (v_134 == nil) goto v_54;
v_135 = basic_elt(env, 5); // (null!-fn)
v_134 = stack[0];
return cons(v_135, v_134);
v_54:
v_134 = qvalue(basic_elt(env, 6)); // acontract
if (v_134 == nil) goto v_71;
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = qvalue(basic_elt(env, 4)); // upb
v_134 = static_cast<LispObject>(lesseq2(v_135, v_134));
v_134 = v_134 ? lisp_true : nil;
env = stack[-2];
if (v_134 == nil) goto v_71;
v_136 = qvalue(basic_elt(env, 7)); // op
v_134 = stack[-1];
if (!car_legal(v_134)) v_135 = carerror(v_134); else
v_135 = car(v_134);
v_134 = stack[-1];
if (!car_legal(v_134)) v_134 = cdrerror(v_134); else
v_134 = cdr(v_134);
v_134 = acons(v_136, v_135, v_134);
env = stack[-2];
{
LispObject fn = basic_elt(env, 15); // mval
return (*qfn1(fn))(fn, v_134);
}
v_71:
v_134 = qvalue(basic_elt(env, 8)); // mcontract
if (v_134 == nil) goto v_86;
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = qvalue(basic_elt(env, 4)); // upb
v_134 = static_cast<LispObject>(lesseq2(v_135, v_134));
v_134 = v_134 ? lisp_true : nil;
env = stack[-2];
if (v_134 == nil) goto v_86;
v_136 = basic_elt(env, 9); // null!-fn
v_134 = stack[-1];
if (!car_legal(v_134)) v_135 = carerror(v_134); else
v_135 = car(v_134);
v_134 = stack[-1];
if (!car_legal(v_134)) v_134 = cdrerror(v_134); else
v_134 = cdr(v_134);
return acons(v_136, v_135, v_134);
v_86:
v_134 = qvalue(basic_elt(env, 10)); // expand
if (v_134 == nil) goto v_100;
v_134 = nil;
setvalue(basic_elt(env, 10), v_134); // expand
v_135 = qvalue(basic_elt(env, 11)); // identity
v_134 = stack[0];
return cons(v_135, v_134);
v_100:
v_134 = nil;
goto v_32;
v_134 = nil;
v_32:
goto v_25;
v_27:
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
if (v_135 == v_134) goto v_113;
else goto v_114;
v_113:
v_135 = qvalue(basic_elt(env, 3)); // i
v_134 = qvalue(basic_elt(env, 4)); // upb
v_134 = static_cast<LispObject>(lesseq2(v_135, v_134));
v_134 = v_134 ? lisp_true : nil;
env = stack[-2];
goto v_112;
v_114:
v_134 = nil;
goto v_112;
v_134 = nil;
v_112:
if (v_134 == nil) goto v_110;
v_135 = basic_elt(env, 5); // (null!-fn)
v_134 = stack[0];
return cons(v_135, v_134);
v_110:
v_134 = qvalue(basic_elt(env, 10)); // expand
if (v_134 == nil) goto v_127;
v_134 = nil;
setvalue(basic_elt(env, 10), v_134); // expand
v_135 = qvalue(basic_elt(env, 11)); // identity
v_134 = stack[0];
return cons(v_135, v_134);
v_127:
v_134 = nil;
v_25:
return onevalue(v_134);
}
// Code for wedgef
static LispObject CC_wedgef(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_150, v_151, v_152;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil);
stack_popper stack_popper_var(4);
// copy arguments values to proper place
stack[-1] = v_2;
// end of prologue
v_150 = stack[-1];
{ LispObject fn = basic_elt(env, 6); // dim!<deg
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
if (v_150 == nil) goto v_7;
v_150 = nil;
goto v_5;
v_7:
v_150 = stack[-1];
if (!car_legal(v_150)) v_151 = carerror(v_150); else
v_151 = car(v_150);
v_150 = basic_elt(env, 1); // hodge
if (!consp(v_151)) goto v_12;
v_151 = car(v_151);
if (v_151 == v_150) goto v_11;
else goto v_12;
v_11:
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
{ LispObject fn = basic_elt(env, 7); // deg!*form
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
stack[-2] = v_150;
stack[0] = stack[-2];
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
{ LispObject fn = basic_elt(env, 8); // deg!*farg
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
if (equal(stack[0], v_150)) goto v_25;
else goto v_26;
v_25:
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_152 = carerror(v_150); else
v_152 = car(v_150);
v_151 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_150 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_150 = list2star(v_152, v_151, v_150);
env = stack[-3];
stack[0] = ncons(v_150);
env = stack[-3];
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (v_150 == nil) goto v_46;
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
{ LispObject fn = basic_elt(env, 9); // mkuniquewedge1
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
goto v_44;
v_46:
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_152 = carerror(v_150); else
v_152 = car(v_150);
v_151 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_150 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_150 = list2star(v_152, v_151, v_150);
env = stack[-3];
v_150 = ncons(v_150);
env = stack[-3];
goto v_44;
v_150 = nil;
v_44:
{ LispObject fn = basic_elt(env, 10); // hodgepf
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 11); // mkunarywedge
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 12); // wedgepf2
stack[-1] = (*qfn2(fn))(fn, stack[0], v_150);
}
env = stack[-3];
stack[0] = stack[-2];
v_150 = qvalue(basic_elt(env, 2)); // dimex!*
{ LispObject fn = basic_elt(env, 13); // negf
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 14); // addf
v_150 = (*qfn2(fn))(fn, stack[-2], v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 15); // multf
v_150 = (*qfn2(fn))(fn, stack[0], v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 16); // mksgnsq
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{
LispObject v_156 = stack[-1];
LispObject fn = basic_elt(env, 17); // multpfsq
return (*qfn2(fn))(fn, v_156, v_150);
}
v_26:
v_150 = stack[-1];
{
LispObject fn = basic_elt(env, 18); // mkwedge
return (*qfn1(fn))(fn, v_150);
}
v_150 = nil;
goto v_5;
v_12:
v_150 = stack[-1];
if (!car_legal(v_150)) v_151 = carerror(v_150); else
v_151 = car(v_150);
v_150 = basic_elt(env, 3); // d
if (!consp(v_151)) goto v_78;
v_151 = car(v_151);
if (v_151 == v_150) goto v_77;
else goto v_78;
v_77:
v_151 = basic_elt(env, 3); // d
v_150 = basic_elt(env, 4); // noxpnd
v_150 = Lflagp(nil, v_151, v_150);
env = stack[-3];
if (v_150 == nil) goto v_86;
v_150 = lisp_true;
goto v_84;
v_86:
v_151 = qvalue(basic_elt(env, 5)); // lftshft!*
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
{ LispObject fn = basic_elt(env, 19); // smemqlp
v_150 = (*qfn2(fn))(fn, v_151, v_150);
}
env = stack[-3];
goto v_84;
v_150 = nil;
v_84:
goto v_76;
v_78:
v_150 = nil;
goto v_76;
v_150 = nil;
v_76:
if (v_150 == nil) goto v_74;
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_151 = carerror(v_150); else
v_151 = car(v_150);
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
v_150 = cons(v_151, v_150);
env = stack[-3];
{ LispObject fn = basic_elt(env, 20); // dwedge
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 11); // mkunarywedge
stack[-2] = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_152 = carerror(v_150); else
v_152 = car(v_150);
v_151 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_150 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_150 = list2star(v_152, v_151, v_150);
env = stack[-3];
stack[0] = ncons(v_150);
env = stack[-3];
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (v_150 == nil) goto v_126;
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
{ LispObject fn = basic_elt(env, 20); // dwedge
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
goto v_124;
v_126:
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
{ LispObject fn = basic_elt(env, 21); // exdfk
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
goto v_124;
v_150 = nil;
v_124:
{ LispObject fn = basic_elt(env, 11); // mkunarywedge
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 12); // wedgepf2
stack[0] = (*qfn2(fn))(fn, stack[0], v_150);
}
env = stack[-3];
v_150 = stack[-1];
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
if (!car_legal(v_150)) v_150 = cdrerror(v_150); else
v_150 = cdr(v_150);
if (!car_legal(v_150)) v_150 = carerror(v_150); else
v_150 = car(v_150);
{ LispObject fn = basic_elt(env, 7); // deg!*form
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 16); // mksgnsq
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 22); // negsq
v_150 = (*qfn1(fn))(fn, v_150);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 17); // multpfsq
v_150 = (*qfn2(fn))(fn, stack[0], v_150);
}
env = stack[-3];
{
LispObject v_157 = stack[-2];
LispObject fn = basic_elt(env, 23); // addpf
return (*qfn2(fn))(fn, v_157, v_150);
}
v_74:
v_150 = stack[-1];
{
LispObject fn = basic_elt(env, 18); // mkwedge
return (*qfn1(fn))(fn, v_150);
}
v_150 = nil;
v_5:
return onevalue(v_150);
}
// Code for apply_e
static LispObject CC_apply_e(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_17, v_18;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
stack_popper stack_popper_var(1);
// copy arguments values to proper place
v_17 = v_2;
// end of prologue
v_18 = v_17;
v_17 = nil;
{ LispObject fn = basic_elt(env, 2); // apply
v_18 = (*qfn2(fn))(fn, v_18, v_17);
}
env = stack[0];
v_17 = v_18;
v_18 = integerp(v_18);
if (v_18 == nil) goto v_7;
goto v_5;
v_7:
v_17 = basic_elt(env, 1); // "randpoly expons function must return an integer"
{
LispObject fn = basic_elt(env, 3); // rederr
return (*qfn1(fn))(fn, v_17);
}
v_17 = nil;
v_5:
return onevalue(v_17);
}
// Code for diff_vertex
static LispObject CC_diff_vertex(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_40, v_41, v_42;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_42 = nil;
v_8:
v_40 = stack[-1];
if (v_40 == nil) goto v_11;
else goto v_12;
v_11:
v_40 = v_42;
{
LispObject fn = basic_elt(env, 2); // nreverse
return (*qfn1(fn))(fn, v_40);
}
v_12:
v_40 = stack[-1];
if (!car_legal(v_40)) v_40 = carerror(v_40); else
v_40 = car(v_40);
if (!car_legal(v_40)) v_41 = carerror(v_40); else
v_41 = car(v_40);
v_40 = stack[0];
v_40 = Lassoc(nil, v_41, v_40);
if (v_40 == nil) goto v_17;
v_40 = stack[-1];
if (!car_legal(v_40)) v_40 = carerror(v_40); else
v_40 = car(v_40);
if (!car_legal(v_40)) v_41 = carerror(v_40); else
v_41 = car(v_40);
v_40 = qvalue(basic_elt(env, 1)); // !_0edge
if (!car_legal(v_40)) v_40 = carerror(v_40); else
v_40 = car(v_40);
if (v_41 == v_40) goto v_17;
v_40 = stack[-1];
if (!car_legal(v_40)) v_40 = cdrerror(v_40); else
v_40 = cdr(v_40);
stack[-1] = v_40;
goto v_8;
v_17:
v_40 = stack[-1];
if (!car_legal(v_40)) v_40 = carerror(v_40); else
v_40 = car(v_40);
v_41 = v_42;
v_40 = cons(v_40, v_41);
env = stack[-2];
v_42 = v_40;
v_40 = stack[-1];
if (!car_legal(v_40)) v_40 = cdrerror(v_40); else
v_40 = cdr(v_40);
stack[-1] = v_40;
goto v_8;
v_40 = nil;
return onevalue(v_40);
}
// Code for assert_kernelp
static LispObject CC_assert_kernelp(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_43, v_44;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
stack_popper stack_popper_var(1);
// copy arguments values to proper place
v_43 = v_2;
// end of prologue
v_44 = v_43;
if (symbolp(v_44)) goto v_9;
else goto v_10;
v_9:
v_43 = lisp_true;
goto v_6;
v_10:
v_44 = v_43;
v_44 = Lconsp(nil, v_44);
env = stack[0];
if (v_44 == nil) goto v_15;
else goto v_16;
v_15:
v_43 = nil;
goto v_6;
v_16:
v_44 = v_43;
if (!car_legal(v_44)) v_44 = carerror(v_44); else
v_44 = car(v_44);
if (!symbolp(v_44)) v_44 = nil;
else { v_44 = qfastgets(v_44);
if (v_44 != nil) { v_44 = elt(v_44, 38); // fkernfn
#ifdef RECORD_GET
if (v_44 != SPID_NOPROP)
record_get(elt(fastget_names, 38), 1);
else record_get(elt(fastget_names, 38), 0),
v_44 = nil; }
else record_get(elt(fastget_names, 38), 0); }
#else
if (v_44 == SPID_NOPROP) v_44 = nil; }}
#endif
if (v_44 == nil) goto v_23;
v_43 = lisp_true;
goto v_6;
v_23:
v_44 = v_43;
if (!car_legal(v_44)) v_44 = carerror(v_44); else
v_44 = car(v_44);
if (!consp(v_44)) goto v_30;
else goto v_31;
v_30:
v_44 = v_43;
if (!car_legal(v_44)) v_44 = carerror(v_44); else
v_44 = car(v_44);
if (!symbolp(v_44)) v_44 = nil;
else { v_44 = qfastgets(v_44);
if (v_44 != nil) { v_44 = elt(v_44, 24); // klist
#ifdef RECORD_GET
if (v_44 != SPID_NOPROP)
record_get(elt(fastget_names, 24), 1);
else record_get(elt(fastget_names, 24), 0),
v_44 = nil; }
else record_get(elt(fastget_names, 24), 0); }
#else
if (v_44 == SPID_NOPROP) v_44 = nil; }}
#endif
goto v_29;
v_31:
v_44 = qvalue(basic_elt(env, 1)); // exlist!*
goto v_29;
v_44 = nil;
v_29:
v_43 = Latsoc(nil, v_43, v_44);
v_6:
return onevalue(v_43);
}
// Code for evalgreaterp
static LispObject CC_evalgreaterp(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_67, v_68, v_69;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
v_68 = v_3;
v_67 = v_2;
// end of prologue
v_69 = basic_elt(env, 1); // difference
v_67 = list3(v_69, v_68, v_67);
env = stack[-1];
{ LispObject fn = basic_elt(env, 3); // simp!*
v_67 = (*qfn1(fn))(fn, v_67);
}
env = stack[-1];
stack[0] = v_67;
v_67 = stack[0];
if (!car_legal(v_67)) v_67 = cdrerror(v_67); else
v_67 = cdr(v_67);
if (!consp(v_67)) goto v_18;
v_67 = lisp_true;
goto v_16;
v_18:
v_67 = stack[0];
if (!car_legal(v_67)) v_67 = carerror(v_67); else
v_67 = car(v_67);
if (!consp(v_67)) goto v_26;
else goto v_27;
v_26:
v_67 = lisp_true;
goto v_25;
v_27:
v_67 = stack[0];
if (!car_legal(v_67)) v_67 = carerror(v_67); else
v_67 = car(v_67);
if (!car_legal(v_67)) v_67 = carerror(v_67); else
v_67 = car(v_67);
v_67 = (consp(v_67) ? nil : lisp_true);
goto v_25;
v_67 = nil;
v_25:
v_67 = (v_67 == nil ? lisp_true : nil);
goto v_16;
v_67 = nil;
v_16:
if (v_67 == nil) goto v_14;
v_67 = stack[0];
if (!car_legal(v_67)) v_67 = carerror(v_67); else
v_67 = car(v_67);
{ LispObject fn = basic_elt(env, 4); // minusf
v_67 = (*qfn1(fn))(fn, v_67);
}
env = stack[-1];
if (v_67 == nil) goto v_43;
v_67 = stack[0];
{ LispObject fn = basic_elt(env, 5); // negsq
v_67 = (*qfn1(fn))(fn, v_67);
}
env = stack[-1];
goto v_41;
v_43:
v_67 = stack[0];
goto v_41;
v_67 = nil;
v_41:
{ LispObject fn = basic_elt(env, 6); // mk!*sq
v_68 = (*qfn1(fn))(fn, v_67);
}
env = stack[-1];
v_67 = basic_elt(env, 2); // "number"
{
LispObject fn = basic_elt(env, 7); // typerr
return (*qfn2(fn))(fn, v_68, v_67);
}
v_14:
v_67 = stack[0];
if (!car_legal(v_67)) v_67 = carerror(v_67); else
v_67 = car(v_67);
if (v_67 == nil) goto v_57;
else goto v_58;
v_57:
v_67 = nil;
goto v_56;
v_58:
v_67 = stack[0];
if (!car_legal(v_67)) v_67 = carerror(v_67); else
v_67 = car(v_67);
{
LispObject fn = basic_elt(env, 8); // !:minusp
return (*qfn1(fn))(fn, v_67);
}
v_67 = nil;
v_56:
goto v_12;
v_67 = nil;
v_12:
return onevalue(v_67);
}
// Code for solvealgdepends
static LispObject CC_solvealgdepends(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_61, v_62;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_8:
v_62 = stack[-1];
v_61 = stack[0];
if (equal(v_62, v_61)) goto v_11;
else goto v_12;
v_11:
v_61 = lisp_true;
goto v_7;
v_12:
v_61 = stack[-1];
if (!consp(v_61)) goto v_16;
else goto v_17;
v_16:
v_61 = nil;
goto v_7;
v_17:
v_62 = stack[-1];
v_61 = basic_elt(env, 1); // root_of
if (!consp(v_62)) goto v_21;
v_62 = car(v_62);
if (v_62 == v_61) goto v_20;
else goto v_21;
v_20:
v_62 = stack[0];
v_61 = stack[-1];
if (!car_legal(v_61)) v_61 = cdrerror(v_61); else
v_61 = cdr(v_61);
if (!car_legal(v_61)) v_61 = cdrerror(v_61); else
v_61 = cdr(v_61);
if (!car_legal(v_61)) v_61 = carerror(v_61); else
v_61 = car(v_61);
if (equal(v_62, v_61)) goto v_27;
else goto v_28;
v_27:
v_61 = nil;
goto v_7;
v_28:
v_61 = stack[-1];
if (!car_legal(v_61)) v_61 = cdrerror(v_61); else
v_61 = cdr(v_61);
if (!car_legal(v_61)) v_61 = carerror(v_61); else
v_61 = car(v_61);
stack[-1] = v_61;
goto v_8;
goto v_10;
v_21:
v_61 = stack[-1];
if (!car_legal(v_61)) v_62 = carerror(v_61); else
v_62 = car(v_61);
v_61 = stack[0];
{ LispObject fn = basic_elt(env, 0); // solvealgdepends
v_61 = (*qfn2(fn))(fn, v_62, v_61);
}
env = stack[-2];
v_62 = v_61;
if (v_61 == nil) goto v_45;
v_61 = v_62;
goto v_7;
v_45:
v_61 = stack[-1];
if (!car_legal(v_61)) v_62 = cdrerror(v_61); else
v_62 = cdr(v_61);
v_61 = stack[0];
{ LispObject fn = basic_elt(env, 0); // solvealgdepends
v_61 = (*qfn2(fn))(fn, v_62, v_61);
}
v_62 = v_61;
if (v_61 == nil) goto v_52;
v_61 = v_62;
goto v_7;
v_52:
v_61 = nil;
goto v_7;
goto v_10;
v_10:
v_61 = nil;
v_7:
return onevalue(v_61);
}
// Code for make!-image
static LispObject CC_makeKimage(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_60, v_61, v_62;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil);
stack_popper stack_popper_var(4);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_60 = stack[-1];
if (!consp(v_60)) goto v_11;
else goto v_12;
v_11:
v_60 = lisp_true;
goto v_10;
v_12:
v_60 = stack[-1];
if (!car_legal(v_60)) v_60 = carerror(v_60); else
v_60 = car(v_60);
v_60 = (consp(v_60) ? nil : lisp_true);
goto v_10;
v_60 = nil;
v_10:
if (v_60 == nil) goto v_8;
v_60 = stack[-1];
goto v_6;
v_8:
v_60 = stack[-1];
if (!car_legal(v_60)) v_60 = carerror(v_60); else
v_60 = car(v_60);
if (!car_legal(v_60)) v_60 = carerror(v_60); else
v_60 = car(v_60);
if (!car_legal(v_60)) v_61 = carerror(v_60); else
v_61 = car(v_60);
v_60 = qvalue(basic_elt(env, 1)); // m!-image!-variable
if (equal(v_61, v_60)) goto v_21;
else goto v_22;
v_21:
v_60 = stack[-1];
if (!car_legal(v_60)) v_60 = carerror(v_60); else
v_60 = car(v_60);
if (!car_legal(v_60)) v_61 = cdrerror(v_60); else
v_61 = cdr(v_60);
v_60 = stack[0];
{ LispObject fn = basic_elt(env, 2); // evaluate!-in!-order
v_60 = (*qfn2(fn))(fn, v_61, v_60);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 3); // !*n2f
stack[-2] = (*qfn1(fn))(fn, v_60);
}
env = stack[-3];
v_60 = stack[-1];
if (!car_legal(v_60)) v_61 = cdrerror(v_60); else
v_61 = cdr(v_60);
v_60 = stack[0];
{ LispObject fn = basic_elt(env, 0); // make!-image
v_60 = (*qfn2(fn))(fn, v_61, v_60);
}
v_61 = stack[-2];
v_62 = v_61;
if (v_62 == nil) goto v_42;
else goto v_43;
v_42:
goto v_41;
v_43:
v_62 = stack[-1];
if (!car_legal(v_62)) v_62 = carerror(v_62); else
v_62 = car(v_62);
if (!car_legal(v_62)) v_62 = carerror(v_62); else
v_62 = car(v_62);
return acons(v_62, v_61, v_60);
v_60 = nil;
v_41:
goto v_6;
v_22:
v_61 = stack[-1];
v_60 = stack[0];
{ LispObject fn = basic_elt(env, 2); // evaluate!-in!-order
v_60 = (*qfn2(fn))(fn, v_61, v_60);
}
env = stack[-3];
{
LispObject fn = basic_elt(env, 3); // !*n2f
return (*qfn1(fn))(fn, v_60);
}
v_60 = nil;
v_6:
return onevalue(v_60);
}
// Code for giplus!:
static LispObject CC_giplusT(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_20, v_21;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil);
stack_popper stack_popper_var(4);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_20 = stack[-1];
if (!car_legal(v_20)) v_20 = cdrerror(v_20); else
v_20 = cdr(v_20);
if (!car_legal(v_20)) v_21 = carerror(v_20); else
v_21 = car(v_20);
v_20 = stack[0];
if (!car_legal(v_20)) v_20 = cdrerror(v_20); else
v_20 = cdr(v_20);
if (!car_legal(v_20)) v_20 = carerror(v_20); else
v_20 = car(v_20);
stack[-2] = plus2(v_21, v_20);
env = stack[-3];
v_20 = stack[-1];
if (!car_legal(v_20)) v_20 = cdrerror(v_20); else
v_20 = cdr(v_20);
if (!car_legal(v_20)) v_21 = cdrerror(v_20); else
v_21 = cdr(v_20);
v_20 = stack[0];
if (!car_legal(v_20)) v_20 = cdrerror(v_20); else
v_20 = cdr(v_20);
if (!car_legal(v_20)) v_20 = cdrerror(v_20); else
v_20 = cdr(v_20);
v_20 = plus2(v_21, v_20);
env = stack[-3];
{
LispObject v_25 = stack[-2];
LispObject fn = basic_elt(env, 1); // mkgi
return (*qfn2(fn))(fn, v_25, v_20);
}
}
// Code for ext_mult
static LispObject CC_ext_mult(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_41, v_42, v_43;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
v_41 = v_3;
v_42 = v_2;
// end of prologue
if (!car_legal(v_42)) v_42 = cdrerror(v_42); else
v_42 = cdr(v_42);
if (!car_legal(v_41)) v_41 = cdrerror(v_41); else
v_41 = cdr(v_41);
{ LispObject fn = basic_elt(env, 2); // merge_lists
v_41 = (*qfn2(fn))(fn, v_42, v_41);
}
env = stack[-1];
stack[0] = v_41;
v_41 = stack[0];
if (v_41 == nil) goto v_13;
else goto v_14;
v_13:
v_42 = nil;
v_41 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
return cons(v_42, v_41);
v_14:
v_41 = stack[0];
if (!car_legal(v_41)) v_41 = cdrerror(v_41); else
v_41 = cdr(v_41);
if (v_41 == nil) goto v_19;
else goto v_20;
v_19:
v_42 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_41 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
return cons(v_42, v_41);
v_20:
v_42 = basic_elt(env, 1); // ext
v_41 = stack[0];
if (!car_legal(v_41)) v_41 = cdrerror(v_41); else
v_41 = cdr(v_41);
v_41 = cons(v_42, v_41);
env = stack[-1];
{ LispObject fn = basic_elt(env, 3); // !*a2k
v_42 = (*qfn1(fn))(fn, v_41);
}
env = stack[-1];
v_41 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
{ LispObject fn = basic_elt(env, 4); // to
v_42 = (*qfn2(fn))(fn, v_42, v_41);
}
env = stack[-1];
v_41 = stack[0];
if (!car_legal(v_41)) v_41 = carerror(v_41); else
v_41 = car(v_41);
v_43 = cons(v_42, v_41);
v_42 = nil;
v_41 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
return acons(v_43, v_42, v_41);
v_41 = nil;
return onevalue(v_41);
}
// Code for gcd!-with!-number
static LispObject CC_gcdKwithKnumber(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_70, v_71, v_72;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
stack[0] = v_3;
v_71 = v_2;
// end of prologue
v_7:
v_72 = v_71;
v_70 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
if (v_72 == v_70) goto v_14;
else goto v_15;
v_14:
v_70 = lisp_true;
goto v_13;
v_15:
v_70 = v_71;
if (!consp(v_70)) goto v_24;
v_70 = lisp_true;
goto v_22;
v_24:
v_70 = qvalue(basic_elt(env, 1)); // dmode!*
if (!symbolp(v_70)) v_70 = nil;
else { v_70 = qfastgets(v_70);
if (v_70 != nil) { v_70 = elt(v_70, 3); // field
#ifdef RECORD_GET
if (v_70 == SPID_NOPROP)
record_get(elt(fastget_names, 3), 0),
v_70 = nil;
else record_get(elt(fastget_names, 3), 1),
v_70 = lisp_true; }
else record_get(elt(fastget_names, 3), 0); }
#else
if (v_70 == SPID_NOPROP) v_70 = nil; else v_70 = lisp_true; }}
#endif
goto v_22;
v_70 = nil;
v_22:
goto v_13;
v_70 = nil;
v_13:
if (v_70 == nil) goto v_11;
v_70 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
goto v_6;
v_11:
v_70 = stack[0];
if (!consp(v_70)) goto v_36;
else goto v_37;
v_36:
v_70 = lisp_true;
goto v_35;
v_37:
v_70 = stack[0];
if (!car_legal(v_70)) v_70 = carerror(v_70); else
v_70 = car(v_70);
v_70 = (consp(v_70) ? nil : lisp_true);
goto v_35;
v_70 = nil;
v_35:
if (v_70 == nil) goto v_33;
v_70 = stack[0];
if (v_70 == nil) goto v_47;
else goto v_48;
v_47:
v_70 = v_71;
return Labsval(nil, v_70);
v_48:
v_70 = stack[0];
if (!consp(v_70)) goto v_53;
v_70 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
goto v_6;
v_53:
v_70 = stack[0];
{
LispObject fn = basic_elt(env, 2); // gcddd
return (*qfn2(fn))(fn, v_71, v_70);
}
goto v_9;
v_33:
v_70 = stack[0];
if (!car_legal(v_70)) v_70 = carerror(v_70); else
v_70 = car(v_70);
if (!car_legal(v_70)) v_70 = cdrerror(v_70); else
v_70 = cdr(v_70);
{ LispObject fn = basic_elt(env, 0); // gcd!-with!-number
v_70 = (*qfn2(fn))(fn, v_71, v_70);
}
env = stack[-1];
v_71 = v_70;
v_70 = stack[0];
if (!car_legal(v_70)) v_70 = cdrerror(v_70); else
v_70 = cdr(v_70);
stack[0] = v_70;
goto v_7;
v_9:
v_70 = nil;
v_6:
return onevalue(v_70);
}
// Code for aex_sgn
static LispObject CC_aex_sgn(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_113, v_114;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
stack_popper stack_popper_var(6);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
goto v_15;
goto v_13;
v_15:
v_13:
v_113 = stack[0];
{ LispObject fn = basic_elt(env, 5); // aex_simpleratp
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
if (v_113 == nil) goto v_20;
v_113 = stack[0];
{ LispObject fn = basic_elt(env, 6); // aex_ex
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{
LispObject fn = basic_elt(env, 7); // rat_sgn
return (*qfn1(fn))(fn, v_113);
}
v_20:
v_113 = qvalue(basic_elt(env, 1)); // !*rlanuexsgnopt
if (v_113 == nil) goto v_29;
v_113 = stack[0];
{ LispObject fn = basic_elt(env, 8); // aex_containment
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
stack[-2] = v_113;
{ LispObject fn = basic_elt(env, 9); // rat_0
stack[-1] = (*qfn0(fn))(fn);
}
env = stack[-5];
v_113 = stack[-2];
{ LispObject fn = basic_elt(env, 10); // iv_lb
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 11); // rat_less
v_113 = (*qfn2(fn))(fn, stack[-1], v_113);
}
env = stack[-5];
if (v_113 == nil) goto v_36;
v_113 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
goto v_11;
v_36:
v_113 = stack[-2];
{ LispObject fn = basic_elt(env, 12); // iv_rb
stack[-1] = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 9); // rat_0
v_113 = (*qfn0(fn))(fn);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 11); // rat_less
v_113 = (*qfn2(fn))(fn, stack[-1], v_113);
}
env = stack[-5];
if (v_113 == nil) goto v_45;
v_113 = static_cast<LispObject>(-16)+TAG_FIXNUM; // -1
goto v_11;
v_45:
goto v_27;
v_29:
v_27:
v_113 = stack[0];
{ LispObject fn = basic_elt(env, 13); // aex_mvar
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
stack[-4] = v_113;
v_113 = stack[0];
{ LispObject fn = basic_elt(env, 14); // aex_ctx
v_114 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
v_113 = stack[-4];
{ LispObject fn = basic_elt(env, 15); // ctx_get
v_113 = (*qfn2(fn))(fn, v_114, v_113);
}
env = stack[-5];
stack[-3] = v_113;
v_114 = stack[0];
v_113 = stack[-4];
{ LispObject fn = basic_elt(env, 16); // aex_unbind
v_113 = (*qfn2(fn))(fn, v_114, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 17); // aex_reduce
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 18); // aex_mklcnt
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
stack[-1] = v_113;
v_113 = stack[-1];
{ LispObject fn = basic_elt(env, 5); // aex_simpleratp
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
if (v_113 == nil) goto v_65;
v_113 = stack[-1];
{ LispObject fn = basic_elt(env, 6); // aex_ex
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{
LispObject fn = basic_elt(env, 7); // rat_sgn
return (*qfn1(fn))(fn, v_113);
}
v_65:
v_113 = qvalue(basic_elt(env, 2)); // !*rlverbose
if (v_113 == nil) goto v_74;
v_113 = qvalue(basic_elt(env, 3)); // !*rlanuexverbose
if (v_113 == nil) goto v_74;
v_114 = stack[-1];
v_113 = stack[-4];
{ LispObject fn = basic_elt(env, 19); // aex_deg
v_114 = (*qfn2(fn))(fn, v_114, v_113);
}
env = stack[-5];
v_113 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
v_113 = static_cast<LispObject>(lesseq2(v_114, v_113));
v_113 = v_113 ? lisp_true : nil;
env = stack[-5];
if (v_113 == nil) goto v_82;
v_113 = basic_elt(env, 4); // "[aex_sgn:num!]"
v_113 = Lprinc(nil, v_113);
env = stack[-5];
goto v_80;
v_82:
v_80:
goto v_72;
v_74:
v_72:
v_113 = stack[-3];
{ LispObject fn = basic_elt(env, 20); // anu_dp
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
stack[0] = v_113;
v_114 = v_113;
v_113 = stack[-4];
{ LispObject fn = basic_elt(env, 21); // aex_diff
v_114 = (*qfn2(fn))(fn, v_114, v_113);
}
env = stack[-5];
v_113 = stack[-1];
{ LispObject fn = basic_elt(env, 22); // aex_mult
v_114 = (*qfn2(fn))(fn, v_114, v_113);
}
env = stack[-5];
v_113 = stack[-4];
{ LispObject fn = basic_elt(env, 23); // aex_sturmchain
v_113 = (*qfn3(fn))(fn, stack[0], v_114, v_113);
}
env = stack[-5];
stack[-2] = v_113;
stack[-1] = stack[-2];
stack[0] = stack[-4];
v_113 = stack[-3];
{ LispObject fn = basic_elt(env, 24); // anu_iv
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 10); // iv_lb
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 25); // aex_stchsgnch1
stack[0] = (*qfn3(fn))(fn, stack[-1], stack[0], v_113);
}
env = stack[-5];
stack[-1] = stack[-2];
stack[-2] = stack[-4];
v_113 = stack[-3];
{ LispObject fn = basic_elt(env, 24); // anu_iv
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 12); // iv_rb
v_113 = (*qfn1(fn))(fn, v_113);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 25); // aex_stchsgnch1
v_113 = (*qfn3(fn))(fn, stack[-1], stack[-2], v_113);
}
{
LispObject v_120 = stack[0];
return difference2(v_120, v_113);
}
v_11:
return onevalue(v_113);
}
// Code for containerom
static LispObject CC_containerom(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_97, v_98;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil, nil);
stack_popper stack_popper_var(5);
// copy arguments values to proper place
stack[-2] = v_2;
// end of prologue
// Binding name
// FLUIDBIND: reloadenv=4 litvec-offset=1 saveloc=0
{ bind_fluid_stack bind_fluid_var(-4, 1, 0);
setvalue(basic_elt(env, 1), nil); // name
v_97 = stack[-2];
if (!car_legal(v_97)) v_97 = cdrerror(v_97); else
v_97 = cdr(v_97);
if (!car_legal(v_97)) v_97 = carerror(v_97); else
v_97 = car(v_97);
stack[-1] = v_97;
v_97 = stack[-2];
if (!car_legal(v_97)) v_97 = carerror(v_97); else
v_97 = car(v_97);
setvalue(basic_elt(env, 1), v_97); // name
v_97 = basic_elt(env, 2); // "<OMA>"
{ LispObject fn = basic_elt(env, 14); // printout
v_97 = (*qfn1(fn))(fn, v_97);
}
env = stack[-4];
v_97 = lisp_true;
{ LispObject fn = basic_elt(env, 15); // indent!*
v_97 = (*qfn1(fn))(fn, v_97);
}
env = stack[-4];
v_98 = qvalue(basic_elt(env, 1)); // name
v_97 = basic_elt(env, 3); // vectorml
if (v_98 == v_97) goto v_21;
else goto v_22;
v_21:
v_97 = basic_elt(env, 4); // vector
setvalue(basic_elt(env, 1), v_97); // name
goto v_20;
v_22:
v_20:
v_98 = qvalue(basic_elt(env, 1)); // name
v_97 = qvalue(basic_elt(env, 5)); // valid_om!*
v_97 = Lassoc(nil, v_98, v_97);
if (!car_legal(v_97)) v_97 = cdrerror(v_97); else
v_97 = cdr(v_97);
if (!car_legal(v_97)) v_97 = carerror(v_97); else
v_97 = car(v_97);
stack[-3] = v_97;
v_97 = stack[-2];
if (!car_legal(v_97)) v_98 = carerror(v_97); else
v_98 = car(v_97);
v_97 = basic_elt(env, 6); // set
if (v_98 == v_97) goto v_37;
else goto v_38;
v_37:
v_97 = stack[-1];
v_97 = Lconsp(nil, v_97);
env = stack[-4];
goto v_36;
v_38:
v_97 = nil;
goto v_36;
v_97 = nil;
v_36:
if (v_97 == nil) goto v_34;
v_97 = stack[-1];
if (!car_legal(v_97)) v_97 = carerror(v_97); else
v_97 = car(v_97);
if (!car_legal(v_97)) v_97 = cdrerror(v_97); else
v_97 = cdr(v_97);
if (!car_legal(v_97)) v_97 = carerror(v_97); else
v_97 = car(v_97);
v_98 = Lintern(nil, v_97);
env = stack[-4];
v_97 = basic_elt(env, 7); // multiset
if (v_98 == v_97) goto v_49;
else goto v_50;
v_49:
v_97 = basic_elt(env, 8); // multiset1
stack[-3] = v_97;
goto v_48;
v_50:
v_48:
goto v_32;
v_34:
v_32:
v_97 = stack[-2];
if (!car_legal(v_97)) v_98 = carerror(v_97); else
v_98 = car(v_97);
v_97 = basic_elt(env, 3); // vectorml
if (v_98 == v_97) goto v_61;
else goto v_62;
v_61:
v_97 = basic_elt(env, 9); // "vector"
setvalue(basic_elt(env, 1), v_97); // name
goto v_60;
v_62:
v_60:
v_97 = stack[-2];
if (!car_legal(v_97)) v_98 = carerror(v_97); else
v_98 = car(v_97);
v_97 = basic_elt(env, 3); // vectorml
if (v_98 == v_97) goto v_69;
else goto v_70;
v_69:
v_98 = basic_elt(env, 4); // vector
v_97 = stack[-2];
if (!car_legal(v_97)) v_97 = cdrerror(v_97); else
v_97 = cdr(v_97);
v_97 = cons(v_98, v_97);
env = stack[-4];
stack[-2] = v_97;
goto v_68;
v_70:
v_68:
v_97 = basic_elt(env, 10); // "<OMS cd="""
{ LispObject fn = basic_elt(env, 14); // printout
v_97 = (*qfn1(fn))(fn, v_97);
}
env = stack[-4];
v_97 = stack[-3];
v_97 = Lprinc(nil, v_97);
env = stack[-4];
v_97 = basic_elt(env, 11); // """ name="""
v_97 = Lprinc(nil, v_97);
env = stack[-4];
v_97 = qvalue(basic_elt(env, 1)); // name
v_97 = Lprinc(nil, v_97);
env = stack[-4];
v_97 = basic_elt(env, 12); // """/>"
v_97 = Lprinc(nil, v_97);
env = stack[-4];
v_97 = stack[-2];
if (!car_legal(v_97)) v_97 = cdrerror(v_97); else
v_97 = cdr(v_97);
if (!car_legal(v_97)) v_97 = cdrerror(v_97); else
v_97 = cdr(v_97);
{ LispObject fn = basic_elt(env, 16); // multiom
v_97 = (*qfn1(fn))(fn, v_97);
}
env = stack[-4];
v_97 = nil;
{ LispObject fn = basic_elt(env, 15); // indent!*
v_97 = (*qfn1(fn))(fn, v_97);
}
env = stack[-4];
v_97 = basic_elt(env, 13); // "</OMA>"
{ LispObject fn = basic_elt(env, 14); // printout
v_97 = (*qfn1(fn))(fn, v_97);
}
v_97 = nil;
;} // end of a binding scope
return onevalue(v_97);
}
// Code for mkexdf
static LispObject CC_mkexdf(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_22, v_23;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
v_22 = v_2;
// end of prologue
v_23 = basic_elt(env, 1); // d
v_22 = list2(v_23, v_22);
env = stack[-1];
stack[0] = v_22;
{ LispObject fn = basic_elt(env, 2); // opmtch
v_22 = (*qfn1(fn))(fn, v_22);
}
env = stack[-1];
v_23 = v_22;
if (v_22 == nil) goto v_11;
v_22 = v_23;
{
LispObject fn = basic_elt(env, 3); // partitop
return (*qfn1(fn))(fn, v_22);
}
v_11:
v_22 = stack[0];
{
LispObject fn = basic_elt(env, 4); // mkupf
return (*qfn1(fn))(fn, v_22);
}
v_22 = nil;
return onevalue(v_22);
}
// Code for z!-roads
static LispObject CC_zKroads(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_59, v_60, v_61;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_60 = v_2;
// end of prologue
v_61 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
v_59 = v_60;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (v_61 == v_59) goto v_6;
else goto v_7;
v_6:
v_59 = v_60;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
goto v_5;
v_7:
v_61 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
v_59 = v_60;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (v_61 == v_59) goto v_16;
else goto v_17;
v_16:
v_59 = v_60;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
goto v_5;
v_17:
v_61 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
v_59 = v_60;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (v_61 == v_59) goto v_28;
else goto v_29;
v_28:
v_59 = v_60;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (!car_legal(v_59)) v_59 = cdrerror(v_59); else
v_59 = cdr(v_59);
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
goto v_5;
v_29:
v_59 = nil;
goto v_5;
v_59 = nil;
v_5:
v_61 = v_59;
v_59 = v_61;
if (v_59 == nil) goto v_48;
else goto v_49;
v_48:
v_59 = nil;
goto v_47;
v_49:
v_59 = v_61;
if (!car_legal(v_59)) v_59 = carerror(v_59); else
v_59 = car(v_59);
if (!car_legal(v_60)) v_60 = cdrerror(v_60); else
v_60 = cdr(v_60);
return cons(v_59, v_60);
v_59 = nil;
v_47:
return onevalue(v_59);
}
// Code for msolve!-psys1
static LispObject CC_msolveKpsys1(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_101, v_102;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
push(nil, nil);
stack_popper stack_popper_var(8);
// copy arguments values to proper place
stack[-5] = v_3;
stack[0] = v_2;
// end of prologue
v_101 = nil;
v_101 = ncons(v_101);
env = stack[-7];
v_102 = v_101;
v_101 = stack[0];
stack[-4] = v_101;
v_16:
v_101 = stack[-4];
if (v_101 == nil) goto v_20;
else goto v_21;
v_20:
goto v_15;
v_21:
v_101 = stack[-4];
if (!car_legal(v_101)) v_101 = carerror(v_101); else
v_101 = car(v_101);
stack[-3] = v_101;
v_101 = nil;
stack[-6] = v_101;
v_101 = v_102;
stack[-2] = v_101;
v_31:
v_101 = stack[-2];
if (v_101 == nil) goto v_35;
else goto v_36;
v_35:
goto v_30;
v_36:
v_101 = stack[-2];
if (!car_legal(v_101)) v_101 = carerror(v_101); else
v_101 = car(v_101);
stack[-1] = v_101;
v_102 = stack[-3];
v_101 = stack[-1];
{ LispObject fn = basic_elt(env, 1); // subf
v_101 = (*qfn2(fn))(fn, v_102, v_101);
}
env = stack[-7];
if (!car_legal(v_101)) v_101 = carerror(v_101); else
v_101 = car(v_101);
{ LispObject fn = basic_elt(env, 2); // moduntag
v_101 = (*qfn1(fn))(fn, v_101);
}
env = stack[-7];
{ LispObject fn = basic_elt(env, 3); // general!-reduce!-mod!-p
v_101 = (*qfn1(fn))(fn, v_101);
}
env = stack[-7];
v_102 = v_101;
v_101 = v_102;
if (v_101 == nil) goto v_50;
else goto v_51;
v_50:
v_102 = stack[-1];
v_101 = stack[-6];
v_101 = cons(v_102, v_101);
env = stack[-7];
stack[-6] = v_101;
goto v_49;
v_51:
v_101 = v_102;
if (!consp(v_101)) goto v_60;
else goto v_61;
v_60:
v_101 = lisp_true;
goto v_59;
v_61:
v_101 = v_102;
if (!car_legal(v_101)) v_101 = carerror(v_101); else
v_101 = car(v_101);
v_101 = (consp(v_101) ? nil : lisp_true);
goto v_59;
v_101 = nil;
v_59:
if (v_101 == nil) goto v_57;
goto v_49;
v_57:
v_101 = stack[-5];
{ LispObject fn = basic_elt(env, 4); // msolve!-poly
v_101 = (*qfn2(fn))(fn, v_102, v_101);
}
env = stack[-7];
stack[0] = v_101;
v_75:
v_101 = stack[0];
if (v_101 == nil) goto v_81;
else goto v_82;
v_81:
goto v_74;
v_82:
v_101 = stack[0];
if (!car_legal(v_101)) v_101 = carerror(v_101); else
v_101 = car(v_101);
v_102 = stack[-1];
v_102 = Lappend_2(nil, v_102, v_101);
env = stack[-7];
v_101 = stack[-6];
v_101 = cons(v_102, v_101);
env = stack[-7];
stack[-6] = v_101;
v_101 = stack[0];
if (!car_legal(v_101)) v_101 = cdrerror(v_101); else
v_101 = cdr(v_101);
stack[0] = v_101;
goto v_75;
v_74:
goto v_49;
v_49:
v_101 = stack[-2];
if (!car_legal(v_101)) v_101 = cdrerror(v_101); else
v_101 = cdr(v_101);
stack[-2] = v_101;
goto v_31;
v_30:
v_101 = stack[-6];
v_102 = v_101;
v_101 = stack[-4];
if (!car_legal(v_101)) v_101 = cdrerror(v_101); else
v_101 = cdr(v_101);
stack[-4] = v_101;
goto v_16;
v_15:
v_101 = v_102;
return onevalue(v_101);
}
// Code for ratlessp
static LispObject CC_ratlessp(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_11, v_12;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
stack_popper stack_popper_var(1);
// copy arguments values to proper place
v_11 = v_3;
v_12 = v_2;
// end of prologue
{ LispObject fn = basic_elt(env, 1); // ratdif
v_11 = (*qfn2(fn))(fn, v_12, v_11);
}
if (!car_legal(v_11)) v_12 = carerror(v_11); else
v_12 = car(v_11);
v_11 = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
return Llessp_2(nil, v_12, v_11);
}
// Code for lastcar
static LispObject CC_lastcar(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_23, v_24;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_23 = v_2;
// end of prologue
v_6:
v_24 = v_23;
if (v_24 == nil) goto v_9;
else goto v_10;
v_9:
v_23 = nil;
goto v_5;
v_10:
v_24 = v_23;
if (!car_legal(v_24)) v_24 = cdrerror(v_24); else
v_24 = cdr(v_24);
if (v_24 == nil) goto v_13;
else goto v_14;
v_13:
if (!car_legal(v_23)) v_23 = carerror(v_23); else
v_23 = car(v_23);
goto v_5;
v_14:
if (!car_legal(v_23)) v_23 = cdrerror(v_23); else
v_23 = cdr(v_23);
goto v_6;
v_23 = nil;
v_5:
return onevalue(v_23);
}
// Code for aex_divposcnt
static LispObject CC_aex_divposcnt(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_55, v_56;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil, nil);
stack_popper stack_popper_var(5);
// copy arguments values to proper place
v_55 = v_3;
stack[-2] = v_2;
// end of prologue
v_55 = stack[-2];
{ LispObject fn = basic_elt(env, 1); // aex_ex
v_55 = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
if (!car_legal(v_55)) v_55 = carerror(v_55); else
v_55 = car(v_55);
stack[0] = v_55;
v_55 = stack[0];
{ LispObject fn = basic_elt(env, 2); // sfto_ucontentf
v_55 = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
stack[-1] = v_55;
v_56 = stack[0];
v_55 = stack[-1];
{ LispObject fn = basic_elt(env, 3); // quotfx
v_55 = (*qfn2(fn))(fn, v_56, v_55);
}
env = stack[-4];
stack[0] = v_55;
v_56 = stack[-1];
v_55 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-3] = cons(v_56, v_55);
env = stack[-4];
v_55 = stack[-1];
{ LispObject fn = basic_elt(env, 4); // kernels
stack[-1] = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
v_55 = stack[-2];
{ LispObject fn = basic_elt(env, 5); // aex_ctx
v_55 = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
{ LispObject fn = basic_elt(env, 6); // ctx_filter
v_55 = (*qfn2(fn))(fn, stack[-1], v_55);
}
env = stack[-4];
{ LispObject fn = basic_elt(env, 7); // aex_mk
v_55 = (*qfn2(fn))(fn, stack[-3], v_55);
}
env = stack[-4];
{ LispObject fn = basic_elt(env, 8); // aex_sgn
v_55 = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
stack[-3] = v_55;
goto v_34;
goto v_32;
v_34:
v_32:
v_56 = stack[0];
v_55 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-1] = cons(v_56, v_55);
env = stack[-4];
v_55 = stack[0];
{ LispObject fn = basic_elt(env, 4); // kernels
stack[0] = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
v_55 = stack[-2];
{ LispObject fn = basic_elt(env, 5); // aex_ctx
v_55 = (*qfn1(fn))(fn, v_55);
}
env = stack[-4];
{ LispObject fn = basic_elt(env, 6); // ctx_filter
v_55 = (*qfn2(fn))(fn, stack[0], v_55);
}
env = stack[-4];
{ LispObject fn = basic_elt(env, 7); // aex_mk
v_55 = (*qfn2(fn))(fn, stack[-1], v_55);
}
env = stack[-4];
stack[0] = v_55;
v_56 = stack[-3];
v_55 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_55 = Leqn_2(nil, v_56, v_55);
env = stack[-4];
if (v_55 == nil) goto v_48;
v_55 = stack[0];
goto v_11;
v_48:
v_55 = stack[0];
{
LispObject fn = basic_elt(env, 9); // aex_neg
return (*qfn1(fn))(fn, v_55);
}
v_11:
return onevalue(v_55);
}
// Code for settcollectnonmultiprolongations
static LispObject CC_settcollectnonmultiprolongations(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_80, v_81;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
real_push(nil);
stack_popper stack_popper_var(7);
// copy arguments values to proper place
stack[-4] = v_2;
// end of prologue
v_80 = qvalue(basic_elt(env, 1)); // fluidbibasissett
if (!car_legal(v_80)) v_80 = carerror(v_80); else
v_80 = car(v_80);
if (v_80 == nil) goto v_7;
v_80 = qvalue(basic_elt(env, 1)); // fluidbibasissett
if (!car_legal(v_80)) v_80 = carerror(v_80); else
v_80 = car(v_80);
stack[-5] = v_80;
v_81 = stack[-5];
v_80 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_80 = Lgetv(nil, v_81, v_80);
env = stack[-6];
if (!car_legal(v_80)) v_80 = carerror(v_80); else
v_80 = car(v_80);
{ LispObject fn = basic_elt(env, 3); // monomgetfirstmultivar
v_80 = (*qfn1(fn))(fn, v_80);
}
env = stack[-6];
v_80 = static_cast<LispObject>(static_cast<std::intptr_t>(v_80) - 0x10);
stack[-2] = v_80;
v_80 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-1] = v_80;
v_28:
v_81 = stack[-2];
v_80 = stack[-1];
v_80 = difference2(v_81, v_80);
env = stack[-6];
v_80 = Lminusp(nil, v_80);
env = stack[-6];
if (v_80 == nil) goto v_33;
goto v_27;
v_33:
v_81 = stack[-5];
v_80 = stack[-1];
{ LispObject fn = basic_elt(env, 4); // tripleisprolongedby
v_80 = (*qfn2(fn))(fn, v_81, v_80);
}
env = stack[-6];
if (v_80 == nil) goto v_41;
else goto v_42;
v_41:
v_81 = stack[-5];
v_80 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[0] = Lgetv(nil, v_81, v_80);
env = stack[-6];
v_81 = qvalue(basic_elt(env, 2)); // fluidbibasissinglevariablemonomialss
v_80 = stack[-1];
v_80 = Lgetv(nil, v_81, v_80);
env = stack[-6];
{ LispObject fn = basic_elt(env, 5); // polynommultiplybymonom
v_80 = (*qfn2(fn))(fn, stack[0], v_80);
}
env = stack[-6];
stack[0] = v_80;
v_81 = stack[-5];
v_80 = stack[-1];
{ LispObject fn = basic_elt(env, 6); // triplesetprolongedby
v_80 = (*qfn2(fn))(fn, v_81, v_80);
}
env = stack[-6];
v_80 = stack[0];
if (!car_legal(v_80)) v_80 = carerror(v_80); else
v_80 = car(v_80);
if (v_80 == nil) goto v_59;
v_81 = stack[-5];
v_80 = static_cast<LispObject>(32)+TAG_FIXNUM; // 2
v_80 = Lgetv(nil, v_81, v_80);
env = stack[-6];
{ LispObject fn = basic_elt(env, 7); // createtriplewithancestor
v_80 = (*qfn2(fn))(fn, stack[0], v_80);
}
env = stack[-6];
stack[-3] = v_80;
stack[0] = stack[-3];
v_81 = stack[-5];
v_80 = static_cast<LispObject>(48)+TAG_FIXNUM; // 3
v_80 = Lgetv(nil, v_81, v_80);
env = stack[-6];
{ LispObject fn = basic_elt(env, 8); // triplesetprolongset
v_80 = (*qfn2(fn))(fn, stack[0], v_80);
}
env = stack[-6];
v_81 = stack[-4];
v_80 = stack[-3];
{ LispObject fn = basic_elt(env, 9); // sortedtriplelistinsert
v_80 = (*qfn2(fn))(fn, v_81, v_80);
}
env = stack[-6];
goto v_57;
v_59:
v_57:
goto v_40;
v_42:
v_40:
v_80 = stack[-1];
v_80 = add1(v_80);
env = stack[-6];
stack[-1] = v_80;
goto v_28;
v_27:
v_80 = nil;
goto v_5;
v_7:
v_80 = nil;
v_5:
return onevalue(v_80);
}
// Code for processpartitie1list1
static LispObject CC_processpartitie1list1(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_30, v_31, v_32;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
real_push(nil);
stack_popper stack_popper_var(7);
// copy arguments values to proper place
v_30 = v_3;
v_31 = v_2;
// end of prologue
v_8:
v_32 = v_31;
if (v_32 == nil) goto v_11;
else goto v_12;
v_11:
goto v_7;
v_12:
v_32 = v_31;
if (!car_legal(v_32)) v_32 = cdrerror(v_32); else
v_32 = cdr(v_32);
stack[-5] = v_32;
if (!car_legal(v_31)) stack[-4] = carerror(v_31); else
stack[-4] = car(v_31);
stack[-3] = static_cast<LispObject>(0)+TAG_FIXNUM; // 0
stack[-2] = nil;
stack[-1] = nil;
stack[0] = nil;
v_30 = ncons(v_30);
env = stack[-6];
v_30 = acons(stack[-1], stack[0], v_30);
env = stack[-6];
{ LispObject fn = basic_elt(env, 1); // processpartitie1
v_30 = (*qfn4up(fn))(fn, stack[-4], stack[-3], stack[-2], v_30);
}
env = stack[-6];
v_31 = stack[-5];
goto v_8;
v_30 = nil;
v_7:
return onevalue(v_30);
}
// Code for mk!+outer!+list
static LispObject CC_mkLouterLlist(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_10, v_11;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
v_10 = basic_elt(env, 1); // list
v_11 = ncons(v_10);
v_10 = stack[0];
return Lappend_2(nil, v_11, v_10);
return onevalue(v_10);
}
// Code for repr_ldeg
static LispObject CC_repr_ldeg(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_10;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_10 = v_2;
// end of prologue
if (!car_legal(v_10)) v_10 = cdrerror(v_10); else
v_10 = cdr(v_10);
if (!car_legal(v_10)) v_10 = cdrerror(v_10); else
v_10 = cdr(v_10);
if (!car_legal(v_10)) v_10 = cdrerror(v_10); else
v_10 = cdr(v_10);
if (!car_legal(v_10)) v_10 = cdrerror(v_10); else
v_10 = cdr(v_10);
if (!car_legal(v_10)) v_10 = carerror(v_10); else
v_10 = car(v_10);
return onevalue(v_10);
}
// Code for dip_f2dip2
static LispObject CC_dip_f2dip2(LispObject env, LispObject v_2,
LispObject v_3, LispObject v_4, LispObject _a4up_)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_34, v_35, v_36, v_37, v_38, v_39;
LispObject v_5, v_6;
if (_a4up_ == nil)
aerror1("not enough arguments provided", basic_elt(env, 0));
v_5 = car(_a4up_); _a4up_ = cdr(_a4up_);
if (_a4up_ == nil)
aerror1("not enough arguments provided", basic_elt(env, 0));
v_6 = car(_a4up_); _a4up_ = cdr(_a4up_);
if (_a4up_ != nil)
aerror1("too many arguments provided", basic_elt(env, 0));
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4,v_5,v_6);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_6,v_5,v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
stack_popper stack_popper_var(6);
// copy arguments values to proper place
stack[-3] = v_6;
v_36 = v_5;
v_37 = v_4;
v_38 = v_3;
v_39 = v_2;
// end of prologue
v_35 = v_39;
v_34 = qvalue(basic_elt(env, 1)); // dip_vars!*
v_34 = Lmemq(nil, v_35, v_34);
if (v_34 == nil) goto v_11;
stack[-4] = v_37;
stack[-2] = v_36;
stack[-1] = v_39;
stack[0] = v_38;
v_34 = qvalue(basic_elt(env, 1)); // dip_vars!*
v_34 = ncons(v_34);
env = stack[-5];
{ LispObject fn = basic_elt(env, 2); // ev_insert
v_35 = (*qfn4up(fn))(fn, stack[-2], stack[-1], stack[0], v_34);
}
env = stack[-5];
v_34 = stack[-3];
{
LispObject v_45 = stack[-4];
LispObject fn = basic_elt(env, 3); // dip_f2dip1
return (*qfn3(fn))(fn, v_45, v_35, v_34);
}
v_11:
stack[-1] = v_37;
stack[0] = v_36;
stack[-2] = stack[-3];
v_34 = v_39;
v_35 = v_38;
{ LispObject fn = basic_elt(env, 4); // bc_pmon
v_34 = (*qfn2(fn))(fn, v_34, v_35);
}
env = stack[-5];
{ LispObject fn = basic_elt(env, 5); // bc_prod
v_34 = (*qfn2(fn))(fn, stack[-2], v_34);
}
env = stack[-5];
{
LispObject v_46 = stack[-1];
LispObject v_47 = stack[0];
LispObject fn = basic_elt(env, 3); // dip_f2dip1
return (*qfn3(fn))(fn, v_46, v_47, v_34);
}
v_34 = nil;
return onevalue(v_34);
}
// Code for setfuncsnaryrd
static LispObject CC_setfuncsnaryrd(LispObject env)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_45, v_46;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
env = reclaim(env, "stack", GC_STACK, 0);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// end of prologue
{ LispObject fn = basic_elt(env, 3); // mathml
v_45 = (*qfn0(fn))(fn);
}
env = stack[-1];
stack[0] = v_45;
v_45 = stack[0];
v_45 = Lconsp(nil, v_45);
env = stack[-1];
if (v_45 == nil) goto v_10;
v_45 = stack[0];
if (!car_legal(v_45)) v_45 = cdrerror(v_45); else
v_45 = cdr(v_45);
if (!car_legal(v_45)) v_45 = carerror(v_45); else
v_45 = car(v_45);
if (v_45 == nil) goto v_16;
v_45 = stack[0];
if (!car_legal(v_45)) v_45 = cdrerror(v_45); else
v_45 = cdr(v_45);
if (!car_legal(v_45)) v_45 = carerror(v_45); else
v_45 = car(v_45);
if (!car_legal(v_45)) v_45 = carerror(v_45); else
v_45 = car(v_45);
if (!car_legal(v_45)) v_45 = cdrerror(v_45); else
v_45 = cdr(v_45);
if (!car_legal(v_45)) v_45 = carerror(v_45); else
v_45 = car(v_45);
v_46 = Lintern(nil, v_45);
env = stack[-1];
v_45 = basic_elt(env, 1); // multiset
if (v_46 == v_45) goto v_22;
else goto v_23;
v_22:
v_45 = basic_elt(env, 1); // multiset
setvalue(basic_elt(env, 2), v_45); // mmlatts
goto v_21;
v_23:
v_21:
goto v_14;
v_16:
v_14:
goto v_8;
v_10:
v_8:
v_45 = stack[0];
if (v_45 == nil) goto v_36;
else goto v_37;
v_36:
v_45 = nil;
goto v_35;
v_37:
{ LispObject fn = basic_elt(env, 0); // setfuncsnaryrd
v_45 = (*qfn0(fn))(fn);
}
{
LispObject v_48 = stack[0];
return cons(v_48, v_45);
}
v_45 = nil;
v_35:
return onevalue(v_45);
}
// Code for sqprint
static LispObject CC_sqprint(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_115, v_116, v_117;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil);
stack_popper stack_popper_var(4);
// copy arguments values to proper place
stack[-1] = v_2;
// end of prologue
// Binding !*prin!#
// FLUIDBIND: reloadenv=3 litvec-offset=1 saveloc=0
{ bind_fluid_stack bind_fluid_var(-3, 1, 0);
setvalue(basic_elt(env, 1), nil); // !*prin!#
v_115 = lisp_true;
setvalue(basic_elt(env, 1), v_115); // !*prin!#
v_115 = qvalue(basic_elt(env, 2)); // orig!*
stack[-2] = v_115;
v_115 = qvalue(basic_elt(env, 3)); // !*nat
if (v_115 == nil) goto v_15;
v_116 = qvalue(basic_elt(env, 4)); // posn!*
v_115 = static_cast<LispObject>(320)+TAG_FIXNUM; // 20
v_115 = static_cast<LispObject>(lessp2(v_116, v_115));
v_115 = v_115 ? lisp_true : nil;
env = stack[-3];
if (v_115 == nil) goto v_15;
v_115 = qvalue(basic_elt(env, 4)); // posn!*
setvalue(basic_elt(env, 2), v_115); // orig!*
goto v_13;
v_15:
v_13:
v_115 = qvalue(basic_elt(env, 5)); // !*pri
if (v_115 == nil) goto v_27;
else goto v_25;
v_27:
v_115 = qvalue(basic_elt(env, 6)); // wtl!*
if (v_115 == nil) goto v_29;
else goto v_25;
v_29:
goto v_26;
v_25:
v_115 = stack[-1];
{ LispObject fn = basic_elt(env, 8); // sqhorner!*
v_115 = (*qfn1(fn))(fn, v_115);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 9); // prepsq!*
v_115 = (*qfn1(fn))(fn, v_115);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 10); // prepreform
v_115 = (*qfn1(fn))(fn, v_115);
}
env = stack[-3];
{ LispObject fn = basic_elt(env, 11); // maprin
v_115 = (*qfn1(fn))(fn, v_115);
}
env = stack[-3];
goto v_24;
v_26:
v_115 = stack[-1];
if (!car_legal(v_115)) v_116 = cdrerror(v_115); else
v_116 = cdr(v_115);
v_115 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
if (v_116 == v_115) goto v_37;
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
if (!consp(v_115)) goto v_47;
else goto v_48;
v_47:
v_115 = lisp_true;
goto v_46;
v_48:
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
v_115 = (consp(v_115) ? nil : lisp_true);
goto v_46;
v_115 = nil;
v_46:
if (v_115 == nil) goto v_43;
else goto v_44;
v_43:
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
if (!car_legal(v_115)) v_115 = cdrerror(v_115); else
v_115 = cdr(v_115);
goto v_42;
v_44:
v_115 = nil;
goto v_42;
v_115 = nil;
v_42:
v_116 = stack[-1];
if (!car_legal(v_116)) v_117 = carerror(v_116); else
v_117 = car(v_116);
v_116 = v_115;
v_115 = nil;
{ LispObject fn = basic_elt(env, 12); // xprinf
v_115 = (*qfn3(fn))(fn, v_117, v_116, v_115);
}
env = stack[-3];
v_115 = basic_elt(env, 7); // " / "
{ LispObject fn = basic_elt(env, 13); // prin2!*
v_115 = (*qfn1(fn))(fn, v_115);
}
env = stack[-3];
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = cdrerror(v_115); else
v_115 = cdr(v_115);
if (!consp(v_115)) goto v_77;
else goto v_78;
v_77:
v_115 = lisp_true;
goto v_76;
v_78:
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = cdrerror(v_115); else
v_115 = cdr(v_115);
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
v_115 = (consp(v_115) ? nil : lisp_true);
goto v_76;
v_115 = nil;
v_76:
if (v_115 == nil) goto v_73;
else goto v_74;
v_73:
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = cdrerror(v_115); else
v_115 = cdr(v_115);
if (!car_legal(v_115)) v_115 = cdrerror(v_115); else
v_115 = cdr(v_115);
if (v_115 == nil) goto v_90;
else goto v_89;
v_90:
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = cdrerror(v_115); else
v_115 = cdr(v_115);
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
if (!car_legal(v_115)) v_116 = cdrerror(v_115); else
v_116 = cdr(v_115);
v_115 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_115 = Lneq_2(nil, v_116, v_115);
env = stack[-3];
v_89:
goto v_72;
v_74:
v_115 = nil;
goto v_72;
v_115 = nil;
v_72:
v_116 = stack[-1];
if (!car_legal(v_116)) v_117 = cdrerror(v_116); else
v_117 = cdr(v_116);
v_116 = v_115;
v_115 = nil;
{ LispObject fn = basic_elt(env, 12); // xprinf
v_115 = (*qfn3(fn))(fn, v_117, v_116, v_115);
}
env = stack[-3];
goto v_24;
v_37:
v_115 = stack[-1];
if (!car_legal(v_115)) v_115 = carerror(v_115); else
v_115 = car(v_115);
{ LispObject fn = basic_elt(env, 14); // xprinf2
v_115 = (*qfn1(fn))(fn, v_115);
}
env = stack[-3];
goto v_24;
v_24:
v_115 = stack[-2];
setvalue(basic_elt(env, 2), v_115); // orig!*
;} // end of a binding scope
return onevalue(v_115);
}
// Code for red_tailreddriver
static LispObject CC_red_tailreddriver(LispObject env,
LispObject v_2, LispObject v_3,
LispObject v_4)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_53;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
stack_popper stack_popper_var(6);
// copy arguments values to proper place
stack[-1] = v_4;
stack[-2] = v_3;
stack[-3] = v_2;
// end of prologue
v_53 = stack[-2];
{ LispObject fn = basic_elt(env, 1); // bas_dpoly
v_53 = (*qfn1(fn))(fn, v_53);
}
env = stack[-5];
if (v_53 == nil) goto v_12;
else goto v_13;
v_12:
v_53 = lisp_true;
goto v_11;
v_13:
v_53 = stack[-2];
{ LispObject fn = basic_elt(env, 1); // bas_dpoly
v_53 = (*qfn1(fn))(fn, v_53);
}
env = stack[-5];
if (!car_legal(v_53)) v_53 = cdrerror(v_53); else
v_53 = cdr(v_53);
if (v_53 == nil) goto v_21;
else goto v_22;
v_21:
v_53 = lisp_true;
goto v_20;
v_22:
v_53 = stack[-3];
v_53 = (v_53 == nil ? lisp_true : nil);
goto v_20;
v_53 = nil;
v_20:
goto v_11;
v_53 = nil;
v_11:
if (v_53 == nil) goto v_9;
v_53 = stack[-2];
goto v_7;
v_9:
v_38:
v_53 = stack[-2];
{ LispObject fn = basic_elt(env, 1); // bas_dpoly
v_53 = (*qfn1(fn))(fn, v_53);
}
env = stack[-5];
if (v_53 == nil) goto v_41;
else goto v_42;
v_41:
goto v_37;
v_42:
stack[-4] = stack[-1];
stack[0] = stack[-3];
v_53 = stack[-2];
{ LispObject fn = basic_elt(env, 2); // red!=hidelt
v_53 = (*qfn1(fn))(fn, v_53);
}
env = stack[-5];
v_53 = Lapply2(nil, stack[-4], stack[0], v_53);
env = stack[-5];
stack[-2] = v_53;
goto v_38;
v_37:
v_53 = stack[-2];
{
LispObject fn = basic_elt(env, 3); // red!=recover
return (*qfn1(fn))(fn, v_53);
}
goto v_7;
v_53 = nil;
v_7:
return onevalue(v_53);
}
// Code for getavalue
static LispObject CC_getavalue(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_18, v_19;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_18 = v_2;
// end of prologue
if (!symbolp(v_18)) v_18 = nil;
else { v_18 = qfastgets(v_18);
if (v_18 != nil) { v_18 = elt(v_18, 4); // avalue
#ifdef RECORD_GET
if (v_18 != SPID_NOPROP)
record_get(elt(fastget_names, 4), 1);
else record_get(elt(fastget_names, 4), 0),
v_18 = nil; }
else record_get(elt(fastget_names, 4), 0); }
#else
if (v_18 == SPID_NOPROP) v_18 = nil; }}
#endif
v_19 = v_18;
v_18 = v_19;
if (v_18 == nil) goto v_10;
v_18 = v_19;
if (!car_legal(v_18)) v_18 = cdrerror(v_18); else
v_18 = cdr(v_18);
if (!car_legal(v_18)) v_18 = carerror(v_18); else
v_18 = car(v_18);
goto v_8;
v_10:
v_18 = nil;
goto v_8;
v_18 = nil;
v_8:
return onevalue(v_18);
}
// Code for reduce!-eival!-powers
static LispObject CC_reduceKeivalKpowers(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_46, v_47, v_48, v_49;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
v_48 = v_3;
v_49 = v_2;
// end of prologue
v_46 = v_48;
if (!consp(v_46)) goto v_15;
else goto v_16;
v_15:
v_46 = lisp_true;
goto v_14;
v_16:
v_46 = v_48;
if (!car_legal(v_46)) v_46 = carerror(v_46); else
v_46 = car(v_46);
v_46 = (consp(v_46) ? nil : lisp_true);
goto v_14;
v_46 = nil;
v_14:
if (v_46 == nil) goto v_12;
v_46 = lisp_true;
goto v_10;
v_12:
v_46 = v_48;
if (!car_legal(v_46)) v_46 = carerror(v_46); else
v_46 = car(v_46);
if (!car_legal(v_46)) v_46 = carerror(v_46); else
v_46 = car(v_46);
if (!car_legal(v_46)) v_47 = carerror(v_46); else
v_47 = car(v_46);
v_46 = v_49;
if (!car_legal(v_46)) v_46 = carerror(v_46); else
v_46 = car(v_46);
if (!car_legal(v_46)) v_46 = carerror(v_46); else
v_46 = car(v_46);
v_46 = (v_47 == v_46 ? lisp_true : nil);
v_46 = (v_46 == nil ? lisp_true : nil);
goto v_10;
v_46 = nil;
v_10:
if (v_46 == nil) goto v_8;
v_47 = v_48;
v_46 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
return cons(v_47, v_46);
v_8:
stack[0] = v_49;
v_47 = v_48;
v_46 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_46 = cons(v_47, v_46);
env = stack[-1];
{
LispObject v_51 = stack[0];
LispObject fn = basic_elt(env, 1); // reduce!-eival!-powers1
return (*qfn2(fn))(fn, v_51, v_46);
}
v_46 = nil;
return onevalue(v_46);
}
// Code for find!-null!-space
static LispObject CC_findKnullKspace(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_36, v_37, v_38;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
push(nil, nil);
stack_popper stack_popper_var(8);
// copy arguments values to proper place
stack[-4] = v_3;
stack[-5] = v_2;
// end of prologue
// Binding null!-space!-basis
// FLUIDBIND: reloadenv=7 litvec-offset=1 saveloc=6
{ bind_fluid_stack bind_fluid_var(-7, 1, -6);
setvalue(basic_elt(env, 1), nil); // null!-space!-basis
v_36 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-3] = v_36;
v_12:
v_37 = stack[-4];
v_36 = stack[-3];
v_36 = static_cast<LispObject>(static_cast<std::uintptr_t>(v_37) - static_cast<std::uintptr_t>(v_36) + TAG_FIXNUM);
v_36 = (static_cast<std::intptr_t>(v_36) < 0 ? lisp_true : nil);
if (v_36 == nil) goto v_17;
goto v_11;
v_17:
stack[-2] = stack[-3];
stack[-1] = qvalue(basic_elt(env, 1)); // null!-space!-basis
stack[0] = stack[-5];
v_36 = stack[-4];
v_36 = ncons(v_36);
env = stack[-7];
{ LispObject fn = basic_elt(env, 2); // clear!-column
v_36 = (*qfn4up(fn))(fn, stack[-2], stack[-1], stack[0], v_36);
}
env = stack[-7];
setvalue(basic_elt(env, 1), v_36); // null!-space!-basis
v_36 = stack[-3];
v_36 = static_cast<LispObject>(static_cast<std::intptr_t>(v_36) + 0x10);
stack[-3] = v_36;
goto v_12;
v_11:
v_38 = qvalue(basic_elt(env, 1)); // null!-space!-basis
v_37 = stack[-5];
v_36 = stack[-4];
{ LispObject fn = basic_elt(env, 3); // tidy!-up!-null!-vectors
v_36 = (*qfn3(fn))(fn, v_38, v_37, v_36);
}
;} // end of a binding scope
return onevalue(v_36);
}
// Code for set_parser
static LispObject CC_set_parser(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_34, v_35;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
v_34 = stack[0];
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
{ LispObject fn = basic_elt(env, 8); // lex_restore_context
v_34 = (*qfn1(fn))(fn, v_34);
}
env = stack[-1];
v_34 = stack[0];
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
stack[0] = v_34;
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 1), v_34); // parser_action_table
v_34 = stack[0];
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
stack[0] = v_34;
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
v_35 = v_34;
v_34 = v_35;
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 2), v_34); // reduction_fn
v_34 = v_35;
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
v_35 = v_34;
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 3), v_34); // reduction_rhs_n
v_34 = v_35;
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 4), v_34); // reduction_lhs
v_34 = stack[0];
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
stack[0] = v_34;
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 5), v_34); // parser_goto_table
v_34 = stack[0];
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
stack[0] = v_34;
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 6), v_34); // nonterminal_codes
v_34 = stack[0];
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
setvalue(basic_elt(env, 7), v_34); // terminal_codes
v_34 = nil;
return onevalue(v_34);
}
// Code for sq_member
static LispObject CC_sq_member(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_16, v_17;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_17 = stack[-1];
v_16 = stack[0];
if (!car_legal(v_16)) v_16 = carerror(v_16); else
v_16 = car(v_16);
{ LispObject fn = basic_elt(env, 1); // sf_member
v_16 = (*qfn2(fn))(fn, v_17, v_16);
}
env = stack[-2];
if (v_16 == nil) goto v_7;
else goto v_6;
v_7:
v_17 = stack[-1];
v_16 = stack[0];
if (!car_legal(v_16)) v_16 = cdrerror(v_16); else
v_16 = cdr(v_16);
{
LispObject fn = basic_elt(env, 1); // sf_member
return (*qfn2(fn))(fn, v_17, v_16);
}
v_6:
return onevalue(v_16);
}
// Code for orddf
static LispObject CC_orddf(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_51, v_52;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_7:
v_51 = stack[-1];
if (v_51 == nil) goto v_10;
else goto v_11;
v_10:
v_51 = stack[0];
if (v_51 == nil) goto v_15;
else goto v_16;
v_15:
v_51 = basic_elt(env, 1); // "Orddf = case"
{
LispObject fn = basic_elt(env, 4); // interr
return (*qfn1(fn))(fn, v_51);
}
v_16:
v_51 = basic_elt(env, 2); // "Orddf v longer than u"
{
LispObject fn = basic_elt(env, 4); // interr
return (*qfn1(fn))(fn, v_51);
}
goto v_9;
v_11:
v_51 = stack[0];
if (v_51 == nil) goto v_24;
else goto v_25;
v_24:
v_51 = basic_elt(env, 3); // "Orddf u longer than v"
{
LispObject fn = basic_elt(env, 4); // interr
return (*qfn1(fn))(fn, v_51);
}
v_25:
v_51 = stack[-1];
if (!car_legal(v_51)) v_52 = carerror(v_51); else
v_52 = car(v_51);
v_51 = stack[0];
if (!car_legal(v_51)) v_51 = carerror(v_51); else
v_51 = car(v_51);
{ LispObject fn = basic_elt(env, 5); // exptcompare
v_51 = (*qfn2(fn))(fn, v_52, v_51);
}
env = stack[-2];
if (v_51 == nil) goto v_30;
v_51 = lisp_true;
goto v_6;
v_30:
v_51 = stack[0];
if (!car_legal(v_51)) v_52 = carerror(v_51); else
v_52 = car(v_51);
v_51 = stack[-1];
if (!car_legal(v_51)) v_51 = carerror(v_51); else
v_51 = car(v_51);
{ LispObject fn = basic_elt(env, 5); // exptcompare
v_51 = (*qfn2(fn))(fn, v_52, v_51);
}
env = stack[-2];
if (v_51 == nil) goto v_38;
v_51 = nil;
goto v_6;
v_38:
v_51 = stack[-1];
if (!car_legal(v_51)) v_51 = cdrerror(v_51); else
v_51 = cdr(v_51);
stack[-1] = v_51;
v_51 = stack[0];
if (!car_legal(v_51)) v_51 = cdrerror(v_51); else
v_51 = cdr(v_51);
stack[0] = v_51;
goto v_7;
v_9:
v_51 = nil;
v_6:
return onevalue(v_51);
}
// Code for cl_susiupdknowl
static LispObject CC_cl_susiupdknowl(LispObject env, LispObject v_2,
LispObject v_3, LispObject v_4, LispObject _a4up_)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_47, v_48, v_49;
LispObject v_5;
if (_a4up_ == nil)
aerror1("not enough arguments provided", basic_elt(env, 0));
v_5 = car(_a4up_); _a4up_ = cdr(_a4up_);
if (_a4up_ != nil)
aerror1("too many arguments provided", basic_elt(env, 0));
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4,v_5);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_5,v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
push(nil, nil);
stack_popper stack_popper_var(8);
// copy arguments values to proper place
stack[-3] = v_5;
v_48 = v_4;
stack[-4] = v_3;
stack[-5] = v_2;
// end of prologue
stack[-6] = nil;
v_12:
v_47 = stack[-4];
if (v_47 == nil) goto v_15;
else goto v_16;
v_15:
goto v_11;
v_16:
v_47 = stack[-4];
if (!car_legal(v_47)) v_47 = carerror(v_47); else
v_47 = car(v_47);
stack[-6] = v_47;
v_47 = stack[-4];
if (!car_legal(v_47)) v_47 = cdrerror(v_47); else
v_47 = cdr(v_47);
stack[-4] = v_47;
stack[-2] = stack[-5];
stack[-1] = stack[-6];
stack[0] = v_48;
v_47 = stack[-3];
v_47 = ncons(v_47);
env = stack[-7];
{ LispObject fn = basic_elt(env, 3); // cl_susiupdknowl1
v_47 = (*qfn4up(fn))(fn, stack[-2], stack[-1], stack[0], v_47);
}
env = stack[-7];
v_48 = v_47;
v_49 = v_48;
v_47 = basic_elt(env, 1); // false
if (v_49 == v_47) goto v_31;
else goto v_32;
v_31:
v_47 = nil;
stack[-4] = v_47;
v_47 = basic_elt(env, 2); // break
stack[-6] = v_47;
goto v_30;
v_32:
v_30:
goto v_12;
v_11:
v_49 = stack[-6];
v_47 = basic_elt(env, 2); // break
if (v_49 == v_47) goto v_39;
else goto v_40;
v_39:
v_47 = basic_elt(env, 1); // false
goto v_9;
v_40:
v_47 = v_48;
goto v_9;
v_47 = nil;
v_9:
return onevalue(v_47);
}
// Code for gftimes
static LispObject CC_gftimes(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_19, v_20, v_21;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_20 = v_3;
v_21 = v_2;
// end of prologue
v_19 = v_21;
if (!car_legal(v_19)) v_19 = carerror(v_19); else
v_19 = car(v_19);
if (!consp(v_19)) goto v_7;
else goto v_8;
v_7:
v_19 = v_21;
{
LispObject fn = basic_elt(env, 1); // gfftimes
return (*qfn2(fn))(fn, v_19, v_20);
}
v_8:
v_19 = v_21;
{
LispObject fn = basic_elt(env, 2); // gbftimes
return (*qfn2(fn))(fn, v_19, v_20);
}
v_19 = nil;
return onevalue(v_19);
}
// Code for calc_den_tar
static LispObject CC_calc_den_tar(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_25, v_26;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
stack_popper stack_popper_var(1);
// copy arguments values to proper place
v_25 = v_3;
v_26 = v_2;
// end of prologue
{ LispObject fn = basic_elt(env, 1); // denlist
v_25 = (*qfn2(fn))(fn, v_26, v_25);
}
env = stack[0];
v_26 = v_25;
v_25 = v_26;
if (v_25 == nil) goto v_11;
else goto v_12;
v_11:
v_25 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
goto v_10;
v_12:
v_25 = v_26;
if (!car_legal(v_25)) v_25 = cdrerror(v_25); else
v_25 = cdr(v_25);
if (v_25 == nil) goto v_15;
else goto v_16;
v_15:
v_25 = v_26;
if (!car_legal(v_25)) v_25 = carerror(v_25); else
v_25 = car(v_25);
goto v_10;
v_16:
v_25 = v_26;
{
LispObject fn = basic_elt(env, 2); // constimes
return (*qfn1(fn))(fn, v_25);
}
v_25 = nil;
v_10:
return onevalue(v_25);
}
// Code for no!-side!-effectp
static LispObject CC_noKsideKeffectp(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_48, v_49;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
v_48 = stack[0];
if (!consp(v_48)) goto v_6;
else goto v_7;
v_6:
v_48 = stack[0];
v_48 = (is_number(v_48) ? lisp_true : nil);
if (v_48 == nil) goto v_11;
else goto v_10;
v_11:
v_48 = stack[0];
if (symbolp(v_48)) goto v_17;
v_48 = nil;
goto v_15;
v_17:
v_48 = stack[0];
v_48 = Lsymbol_specialp(nil, v_48);
env = stack[-1];
if (v_48 == nil) goto v_24;
else goto v_23;
v_24:
v_48 = stack[0];
v_48 = Lsymbol_globalp(nil, v_48);
v_23:
v_48 = (v_48 == nil ? lisp_true : nil);
goto v_15;
v_48 = nil;
v_15:
v_10:
goto v_5;
v_7:
v_48 = stack[0];
if (!car_legal(v_48)) v_49 = carerror(v_48); else
v_49 = car(v_48);
v_48 = basic_elt(env, 1); // quote
if (v_49 == v_48) goto v_30;
else goto v_31;
v_30:
v_48 = lisp_true;
goto v_5;
v_31:
v_48 = stack[0];
if (!car_legal(v_48)) v_49 = carerror(v_48); else
v_49 = car(v_48);
v_48 = basic_elt(env, 2); // nosideeffects
v_48 = Lflagp(nil, v_49, v_48);
env = stack[-1];
if (v_48 == nil) goto v_37;
v_48 = stack[0];
if (!car_legal(v_48)) v_48 = cdrerror(v_48); else
v_48 = cdr(v_48);
{
LispObject fn = basic_elt(env, 3); // no!-side!-effect!-listp
return (*qfn1(fn))(fn, v_48);
}
v_37:
v_48 = nil;
goto v_5;
v_48 = nil;
v_5:
return onevalue(v_48);
}
// Code for atom_compare
static LispObject CC_atom_compare(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_32, v_33, v_34;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
stack_popper stack_popper_var(1);
// copy arguments values to proper place
v_33 = v_3;
v_34 = v_2;
// end of prologue
v_32 = v_34;
if (is_number(v_32)) goto v_7;
else goto v_8;
v_7:
v_32 = v_33;
if (is_number(v_32)) goto v_13;
v_32 = nil;
goto v_11;
v_13:
v_32 = v_34;
v_32 = static_cast<LispObject>(lessp2(v_32, v_33));
v_32 = v_32 ? lisp_true : nil;
v_32 = (v_32 == nil ? lisp_true : nil);
goto v_11;
v_32 = nil;
v_11:
goto v_6;
v_8:
v_32 = v_33;
if (symbolp(v_32)) goto v_22;
else goto v_23;
v_22:
v_32 = v_34;
return Lorderp(nil, v_32, v_33);
v_23:
v_32 = v_33;
v_32 = (is_number(v_32) ? lisp_true : nil);
goto v_6;
v_32 = nil;
v_6:
return onevalue(v_32);
}
// Code for lalr_expand_grammar
static LispObject CC_lalr_expand_grammar(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_34, v_35;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
v_34 = v_2;
// end of prologue
// Binding pending_rules!*
// FLUIDBIND: reloadenv=2 litvec-offset=1 saveloc=1
{ bind_fluid_stack bind_fluid_var(-2, 1, -1);
setvalue(basic_elt(env, 1), nil); // pending_rules!*
{ LispObject fn = basic_elt(env, 2); // lalr_check_grammar
v_34 = (*qfn1(fn))(fn, v_34);
}
env = stack[-2];
setvalue(basic_elt(env, 1), v_34); // pending_rules!*
v_34 = nil;
stack[0] = v_34;
v_16:
v_34 = qvalue(basic_elt(env, 1)); // pending_rules!*
if (v_34 == nil) goto v_19;
else goto v_20;
v_19:
goto v_15;
v_20:
v_34 = qvalue(basic_elt(env, 1)); // pending_rules!*
if (!car_legal(v_34)) v_34 = carerror(v_34); else
v_34 = car(v_34);
v_35 = v_34;
v_34 = qvalue(basic_elt(env, 1)); // pending_rules!*
if (!car_legal(v_34)) v_34 = cdrerror(v_34); else
v_34 = cdr(v_34);
setvalue(basic_elt(env, 1), v_34); // pending_rules!*
v_34 = v_35;
{ LispObject fn = basic_elt(env, 3); // expand_rule
v_35 = (*qfn1(fn))(fn, v_34);
}
env = stack[-2];
v_34 = stack[0];
v_34 = cons(v_35, v_34);
env = stack[-2];
stack[0] = v_34;
goto v_16;
v_15:
v_34 = stack[0];
v_34 = Lreverse(nil, v_34);
;} // end of a binding scope
return onevalue(v_34);
}
// Code for aex_stchsgnch1
static LispObject CC_aex_stchsgnch1(LispObject env,
LispObject v_2, LispObject v_3,
LispObject v_4)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_50, v_51, v_52;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
real_push(nil);
stack_popper stack_popper_var(7);
// copy arguments values to proper place
stack[-3] = v_4;
stack[-4] = v_3;
v_50 = v_2;
// end of prologue
stack[-5] = v_50;
v_50 = stack[-5];
if (v_50 == nil) goto v_16;
else goto v_17;
v_16:
v_50 = nil;
goto v_11;
v_17:
v_50 = stack[-5];
if (!car_legal(v_50)) v_50 = carerror(v_50); else
v_50 = car(v_50);
v_52 = v_50;
v_51 = stack[-4];
v_50 = stack[-3];
{ LispObject fn = basic_elt(env, 1); // aex_subrat1
v_50 = (*qfn3(fn))(fn, v_52, v_51, v_50);
}
env = stack[-6];
{ LispObject fn = basic_elt(env, 2); // aex_sgn
v_50 = (*qfn1(fn))(fn, v_50);
}
env = stack[-6];
v_50 = ncons(v_50);
env = stack[-6];
stack[-1] = v_50;
stack[-2] = v_50;
v_12:
v_50 = stack[-5];
if (!car_legal(v_50)) v_50 = cdrerror(v_50); else
v_50 = cdr(v_50);
stack[-5] = v_50;
v_50 = stack[-5];
if (v_50 == nil) goto v_33;
else goto v_34;
v_33:
v_50 = stack[-2];
goto v_11;
v_34:
stack[0] = stack[-1];
v_50 = stack[-5];
if (!car_legal(v_50)) v_50 = carerror(v_50); else
v_50 = car(v_50);
v_52 = v_50;
v_51 = stack[-4];
v_50 = stack[-3];
{ LispObject fn = basic_elt(env, 1); // aex_subrat1
v_50 = (*qfn3(fn))(fn, v_52, v_51, v_50);
}
env = stack[-6];
{ LispObject fn = basic_elt(env, 2); // aex_sgn
v_50 = (*qfn1(fn))(fn, v_50);
}
env = stack[-6];
v_50 = ncons(v_50);
env = stack[-6];
if (!car_legal(stack[0])) rplacd_fails(stack[0]);
setcdr(stack[0], v_50);
v_50 = stack[-1];
if (!car_legal(v_50)) v_50 = cdrerror(v_50); else
v_50 = cdr(v_50);
stack[-1] = v_50;
goto v_12;
v_11:
{
LispObject fn = basic_elt(env, 3); // lto_sgnchg
return (*qfn1(fn))(fn, v_50);
}
}
// Code for janettreenodebuild
static LispObject CC_janettreenodebuild(LispObject env,
LispObject v_2, LispObject v_3,
LispObject v_4)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_61, v_62;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
push(nil, nil, nil, nil);
stack_popper stack_popper_var(10);
// copy arguments values to proper place
stack[-5] = v_4;
stack[-6] = v_3;
stack[-7] = v_2;
// end of prologue
v_62 = stack[-5];
v_61 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_61 = Lgetv(nil, v_62, v_61);
env = stack[-9];
if (!car_legal(v_61)) v_61 = carerror(v_61); else
v_61 = car(v_61);
stack[-3] = v_61;
v_62 = stack[-3];
v_61 = stack[-6];
{ LispObject fn = basic_elt(env, 1); // monomgetvariabledegree
stack[-1] = (*qfn2(fn))(fn, v_62, v_61);
}
env = stack[-9];
stack[0] = nil;
v_61 = nil;
v_61 = ncons(v_61);
env = stack[-9];
v_61 = acons(stack[-1], stack[0], v_61);
env = stack[-9];
stack[-8] = v_61;
v_61 = stack[-8];
stack[-4] = v_61;
v_25:
stack[0] = stack[-7];
v_62 = stack[-3];
v_61 = stack[-6];
{ LispObject fn = basic_elt(env, 1); // monomgetvariabledegree
v_61 = (*qfn2(fn))(fn, v_62, v_61);
}
env = stack[-9];
if ((static_cast<std::intptr_t>(stack[0]) > static_cast<std::intptr_t>(v_61))) goto v_29;
goto v_24;
v_29:
stack[0] = stack[-7];
v_62 = stack[-3];
v_61 = stack[-6];
{ LispObject fn = basic_elt(env, 1); // monomgetvariabledegree
v_61 = (*qfn2(fn))(fn, v_62, v_61);
}
env = stack[-9];
v_61 = static_cast<LispObject>(static_cast<std::uintptr_t>(stack[0]) - static_cast<std::uintptr_t>(v_61) + TAG_FIXNUM);
stack[-7] = v_61;
v_61 = stack[-6];
v_61 = static_cast<LispObject>(static_cast<std::intptr_t>(v_61) + 0x10);
stack[-6] = v_61;
v_61 = stack[-4];
if (!car_legal(v_61)) stack[-2] = cdrerror(v_61); else
stack[-2] = cdr(v_61);
v_62 = stack[-3];
v_61 = stack[-6];
{ LispObject fn = basic_elt(env, 1); // monomgetvariabledegree
stack[-1] = (*qfn2(fn))(fn, v_62, v_61);
}
env = stack[-9];
stack[0] = nil;
v_61 = nil;
v_61 = ncons(v_61);
env = stack[-9];
v_61 = acons(stack[-1], stack[0], v_61);
env = stack[-9];
{ LispObject fn = basic_elt(env, 2); // setcdr
v_61 = (*qfn2(fn))(fn, stack[-2], v_61);
}
env = stack[-9];
v_61 = stack[-4];
if (!car_legal(v_61)) v_61 = cdrerror(v_61); else
v_61 = cdr(v_61);
if (!car_legal(v_61)) v_61 = cdrerror(v_61); else
v_61 = cdr(v_61);
stack[-4] = v_61;
goto v_25;
v_24:
v_61 = stack[-4];
if (!car_legal(v_61)) v_62 = carerror(v_61); else
v_62 = car(v_61);
v_61 = stack[-5];
{ LispObject fn = basic_elt(env, 2); // setcdr
v_61 = (*qfn2(fn))(fn, v_62, v_61);
}
v_61 = stack[-8];
return onevalue(v_61);
}
// Code for even_action_term
static LispObject CC_even_action_term(LispObject env, LispObject v_2,
LispObject v_3, LispObject v_4, LispObject _a4up_)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_33, v_34;
LispObject v_5;
if (_a4up_ == nil)
aerror1("not enough arguments provided", basic_elt(env, 0));
v_5 = car(_a4up_); _a4up_ = cdr(_a4up_);
if (_a4up_ != nil)
aerror1("too many arguments provided", basic_elt(env, 0));
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4,v_5);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_5,v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
push(nil, nil);
stack_popper stack_popper_var(8);
// copy arguments values to proper place
stack[-2] = v_5;
stack[-3] = v_4;
stack[-4] = v_3;
stack[-5] = v_2;
// end of prologue
stack[-6] = stack[-5];
v_33 = stack[-4];
if (!car_legal(v_33)) stack[-1] = carerror(v_33); else
stack[-1] = car(v_33);
stack[0] = stack[-3];
v_34 = stack[-2];
v_33 = stack[-4];
if (!car_legal(v_33)) v_33 = cdrerror(v_33); else
v_33 = cdr(v_33);
{ LispObject fn = basic_elt(env, 1); // multf
v_34 = (*qfn2(fn))(fn, v_34, v_33);
}
env = stack[-7];
v_33 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_33 = cons(v_34, v_33);
env = stack[-7];
v_33 = ncons(v_33);
env = stack[-7];
{ LispObject fn = basic_elt(env, 2); // even_action_pow
stack[-1] = (*qfn4up(fn))(fn, stack[-6], stack[-1], stack[0], v_33);
}
env = stack[-7];
v_33 = stack[-4];
if (!car_legal(v_33)) stack[0] = cdrerror(v_33); else
stack[0] = cdr(v_33);
v_33 = stack[-4];
if (!car_legal(v_33)) v_34 = carerror(v_33); else
v_34 = car(v_33);
v_33 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
v_33 = cons(v_34, v_33);
env = stack[-7];
v_33 = ncons(v_33);
env = stack[-7];
{ LispObject fn = basic_elt(env, 1); // multf
v_33 = (*qfn2(fn))(fn, stack[-2], v_33);
}
env = stack[-7];
v_33 = ncons(v_33);
env = stack[-7];
{ LispObject fn = basic_elt(env, 3); // even_action_sf
v_33 = (*qfn4up(fn))(fn, stack[-5], stack[0], stack[-3], v_33);
}
env = stack[-7];
{
LispObject v_42 = stack[-1];
LispObject fn = basic_elt(env, 4); // addsq
return (*qfn2(fn))(fn, v_42, v_33);
}
}
// Code for testord
static LispObject CC_testord(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_28, v_29;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_7:
v_28 = stack[-1];
if (v_28 == nil) goto v_10;
else goto v_11;
v_10:
v_28 = lisp_true;
goto v_6;
v_11:
v_28 = stack[-1];
if (!car_legal(v_28)) v_29 = carerror(v_28); else
v_29 = car(v_28);
v_28 = stack[0];
if (!car_legal(v_28)) v_28 = carerror(v_28); else
v_28 = car(v_28);
v_28 = static_cast<LispObject>(lesseq2(v_29, v_28));
v_28 = v_28 ? lisp_true : nil;
env = stack[-2];
if (v_28 == nil) goto v_15;
v_28 = stack[-1];
if (!car_legal(v_28)) v_28 = cdrerror(v_28); else
v_28 = cdr(v_28);
stack[-1] = v_28;
v_28 = stack[0];
if (!car_legal(v_28)) v_28 = cdrerror(v_28); else
v_28 = cdr(v_28);
stack[0] = v_28;
goto v_7;
v_15:
v_28 = nil;
goto v_6;
v_28 = nil;
v_6:
return onevalue(v_28);
}
// Code for my!+nullsq!+p
static LispObject CC_myLnullsqLp(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_13;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_13 = v_2;
// end of prologue
if (!car_legal(v_13)) v_13 = carerror(v_13); else
v_13 = car(v_13);
if (v_13 == nil) goto v_8;
else goto v_9;
v_8:
v_13 = lisp_true;
goto v_5;
v_9:
v_13 = nil;
v_5:
return onevalue(v_13);
}
// Code for pasf_varlat
static LispObject CC_pasf_varlat(LispObject env,
LispObject v_2)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_88, v_89;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil, nil, nil);
stack_popper stack_popper_var(5);
// copy arguments values to proper place
stack[0] = v_2;
// end of prologue
v_88 = stack[0];
if (!car_legal(v_88)) v_88 = cdrerror(v_88); else
v_88 = cdr(v_88);
if (!car_legal(v_88)) v_88 = carerror(v_88); else
v_88 = car(v_88);
{ LispObject fn = basic_elt(env, 3); // kernels
stack[-1] = (*qfn1(fn))(fn, v_88);
}
env = stack[-4];
v_88 = stack[0];
v_88 = Lconsp(nil, v_88);
env = stack[-4];
if (v_88 == nil) goto v_15;
v_88 = stack[0];
if (!car_legal(v_88)) v_88 = carerror(v_88); else
v_88 = car(v_88);
v_88 = Lconsp(nil, v_88);
env = stack[-4];
if (v_88 == nil) goto v_15;
v_88 = stack[0];
if (!car_legal(v_88)) v_88 = carerror(v_88); else
v_88 = car(v_88);
if (!car_legal(v_88)) v_89 = carerror(v_88); else
v_89 = car(v_88);
v_88 = basic_elt(env, 1); // (cong ncong)
v_88 = Lmemq(nil, v_89, v_88);
if (v_88 == nil) goto v_15;
v_88 = stack[0];
if (!car_legal(v_88)) v_88 = carerror(v_88); else
v_88 = car(v_88);
if (!car_legal(v_88)) v_88 = cdrerror(v_88); else
v_88 = cdr(v_88);
{ LispObject fn = basic_elt(env, 3); // kernels
v_88 = (*qfn1(fn))(fn, v_88);
}
env = stack[-4];
goto v_13;
v_15:
v_88 = nil;
goto v_13;
v_88 = nil;
v_13:
v_88 = Lappend_2(nil, stack[-1], v_88);
env = stack[-4];
v_89 = v_88;
v_88 = qvalue(basic_elt(env, 2)); // !*rlbrkcxk
if (v_88 == nil) goto v_40;
v_88 = v_89;
stack[-3] = v_88;
v_47:
v_88 = stack[-3];
if (v_88 == nil) goto v_52;
else goto v_53;
v_52:
v_88 = nil;
goto v_46;
v_53:
v_88 = stack[-3];
if (!car_legal(v_88)) v_88 = carerror(v_88); else
v_88 = car(v_88);
{ LispObject fn = basic_elt(env, 4); // lto_lpvarl
v_88 = (*qfn1(fn))(fn, v_88);
}
env = stack[-4];
stack[-2] = v_88;
v_88 = stack[-2];
{ LispObject fn = basic_elt(env, 5); // lastpair
v_88 = (*qfn1(fn))(fn, v_88);
}
env = stack[-4];
stack[-1] = v_88;
v_88 = stack[-3];
if (!car_legal(v_88)) v_88 = cdrerror(v_88); else
v_88 = cdr(v_88);
stack[-3] = v_88;
v_88 = stack[-1];
if (!consp(v_88)) goto v_67;
else goto v_68;
v_67:
goto v_47;
v_68:
v_48:
v_88 = stack[-3];
if (v_88 == nil) goto v_72;
else goto v_73;
v_72:
v_88 = stack[-2];
goto v_46;
v_73:
stack[0] = stack[-1];
v_88 = stack[-3];
if (!car_legal(v_88)) v_88 = carerror(v_88); else
v_88 = car(v_88);
{ LispObject fn = basic_elt(env, 4); // lto_lpvarl
v_88 = (*qfn1(fn))(fn, v_88);
}
env = stack[-4];
if (!car_legal(stack[0])) rplacd_fails(stack[0]);
setcdr(stack[0], v_88);
v_88 = stack[-1];
{ LispObject fn = basic_elt(env, 5); // lastpair
v_88 = (*qfn1(fn))(fn, v_88);
}
env = stack[-4];
stack[-1] = v_88;
v_88 = stack[-3];
if (!car_legal(v_88)) v_88 = cdrerror(v_88); else
v_88 = cdr(v_88);
stack[-3] = v_88;
goto v_48;
v_46:
v_89 = v_88;
goto v_38;
v_40:
v_38:
v_88 = v_89;
return onevalue(v_88);
}
// Code for rl_surep
static LispObject CC_rl_surep(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_10, v_11;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// copy arguments values to proper place
v_10 = v_3;
v_11 = v_2;
// end of prologue
stack[0] = qvalue(basic_elt(env, 1)); // rl_surep!*
v_10 = list2(v_11, v_10);
env = stack[-1];
{
LispObject v_13 = stack[0];
LispObject fn = basic_elt(env, 2); // apply
return (*qfn2(fn))(fn, v_13, v_10);
}
}
// Code for minusrd
static LispObject CC_minusrd(LispObject env)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_24, v_25, v_26;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
env = reclaim(env, "stack", GC_STACK, 0);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil);
stack_popper stack_popper_var(2);
// end of prologue
{ LispObject fn = basic_elt(env, 1); // mathml
v_24 = (*qfn0(fn))(fn);
}
env = stack[-1];
stack[0] = v_24;
{ LispObject fn = basic_elt(env, 1); // mathml
v_24 = (*qfn0(fn))(fn);
}
env = stack[-1];
v_25 = v_24;
if (v_25 == nil) goto v_11;
else goto v_12;
v_11:
v_24 = stack[0];
v_24 = ncons(v_24);
stack[0] = v_24;
goto v_10;
v_12:
v_26 = stack[0];
v_25 = v_24;
v_24 = nil;
v_24 = list2star(v_26, v_25, v_24);
env = stack[-1];
stack[0] = v_24;
{ LispObject fn = basic_elt(env, 2); // lex
v_24 = (*qfn0(fn))(fn);
}
goto v_10;
v_10:
v_24 = stack[0];
return onevalue(v_24);
}
// Code for assoc2
static LispObject CC_assoc2(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_26, v_27, v_28, v_29;
#ifdef CHECK_STACK
if_check_stack;
#endif
// copy arguments values to proper place
v_27 = v_3;
v_28 = v_2;
// end of prologue
v_7:
v_26 = v_27;
if (v_26 == nil) goto v_10;
else goto v_11;
v_10:
v_26 = nil;
goto v_6;
v_11:
v_29 = v_28;
v_26 = v_27;
if (!car_legal(v_26)) v_26 = carerror(v_26); else
v_26 = car(v_26);
if (!car_legal(v_26)) v_26 = cdrerror(v_26); else
v_26 = cdr(v_26);
if (equal(v_29, v_26)) goto v_14;
else goto v_15;
v_14:
v_26 = v_27;
if (!car_legal(v_26)) v_26 = carerror(v_26); else
v_26 = car(v_26);
goto v_6;
v_15:
v_26 = v_27;
if (!car_legal(v_26)) v_26 = cdrerror(v_26); else
v_26 = cdr(v_26);
v_27 = v_26;
goto v_7;
v_26 = nil;
v_6:
return onevalue(v_26);
}
// Code for rewrite
static LispObject CC_rewrite(LispObject env, LispObject v_2,
LispObject v_3, LispObject v_4, LispObject _a4up_)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_190, v_191, v_192;
LispObject v_5;
if (_a4up_ == nil)
aerror1("not enough arguments provided", basic_elt(env, 0));
v_5 = car(_a4up_); _a4up_ = cdr(_a4up_);
if (_a4up_ != nil)
aerror1("too many arguments provided", basic_elt(env, 0));
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3,v_4,v_5);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_5,v_4,v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
real_push(nil, nil, nil, nil, nil);
real_push(nil, nil, nil, nil, nil);
push(nil, nil, nil, nil);
stack_popper stack_popper_var(15);
// copy arguments values to proper place
stack[-9] = v_5;
stack[-10] = v_4;
stack[-11] = v_3;
stack[-12] = v_2;
// end of prologue
v_190 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-13] = v_190;
v_190 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-2] = v_190;
v_190 = stack[-12];
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = carerror(v_190); else
v_190 = car(v_190);
v_191 = v_190;
if (!car_legal(v_191)) v_191 = cdrerror(v_191); else
v_191 = cdr(v_191);
if (!car_legal(v_191)) v_191 = carerror(v_191); else
v_191 = car(v_191);
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = carerror(v_190); else
v_190 = car(v_190);
if (equal(v_191, v_190)) goto v_30;
else goto v_31;
v_30:
v_190 = stack[-11];
v_190 = add1(v_190);
env = stack[-14];
stack[-1] = v_190;
goto v_29;
v_31:
v_190 = stack[-11];
stack[-1] = v_190;
goto v_29;
v_29:
v_190 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[0] = v_190;
v_47:
v_191 = stack[-1];
v_190 = stack[0];
v_190 = difference2(v_191, v_190);
env = stack[-14];
v_190 = Lminusp(nil, v_190);
env = stack[-14];
if (v_190 == nil) goto v_52;
goto v_46;
v_52:
v_191 = stack[-12];
v_190 = stack[0];
{ LispObject fn = basic_elt(env, 1); // findrow
v_190 = (*qfn2(fn))(fn, v_191, v_190);
}
env = stack[-14];
v_191 = v_190;
v_190 = v_191;
if (v_190 == nil) goto v_64;
v_190 = v_191;
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
stack[-7] = v_190;
v_190 = stack[0];
stack[-3] = v_190;
v_191 = stack[-13];
v_190 = stack[-10];
if (equal(v_191, v_190)) goto v_71;
else goto v_72;
v_71:
v_190 = stack[-13];
v_190 = add1(v_190);
env = stack[-14];
stack[-13] = v_190;
goto v_70;
v_72:
v_70:
v_191 = stack[-3];
v_190 = stack[-13];
if (equal(v_191, v_190)) goto v_79;
else goto v_80;
v_79:
v_190 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-4] = v_190;
v_190 = static_cast<LispObject>(16)+TAG_FIXNUM; // 1
stack[-8] = v_190;
v_190 = nil;
stack[-5] = v_190;
v_88:
v_190 = stack[-7];
if (v_190 == nil) goto v_91;
stack[-3] = stack[-4];
v_190 = stack[-11];
v_190 = add1(v_190);
env = stack[-14];
if (equal(stack[-3], v_190)) goto v_91;
goto v_92;
v_91:
goto v_87;
v_92:
v_190 = stack[-7];
if (!car_legal(v_190)) v_190 = carerror(v_190); else
v_190 = car(v_190);
v_191 = v_190;
v_190 = v_191;
if (!car_legal(v_190)) v_190 = carerror(v_190); else
v_190 = car(v_190);
stack[-6] = v_190;
v_190 = v_191;
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
stack[-3] = v_190;
v_191 = stack[-4];
v_190 = stack[-9];
if (equal(v_191, v_190)) goto v_108;
else goto v_109;
v_108:
v_190 = stack[-8];
v_190 = add1(v_190);
env = stack[-14];
stack[-8] = v_190;
goto v_107;
v_109:
v_107:
v_191 = stack[-6];
v_190 = stack[-8];
if (equal(v_191, v_190)) goto v_116;
else goto v_117;
v_116:
v_192 = stack[-4];
v_191 = stack[-3];
v_190 = stack[-5];
v_190 = acons(v_192, v_191, v_190);
env = stack[-14];
stack[-5] = v_190;
v_190 = stack[-4];
v_190 = add1(v_190);
env = stack[-14];
stack[-4] = v_190;
v_190 = stack[-7];
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
stack[-7] = v_190;
v_190 = stack[-8];
v_190 = add1(v_190);
env = stack[-14];
stack[-8] = v_190;
goto v_115;
v_117:
v_190 = stack[-8];
v_190 = add1(v_190);
env = stack[-14];
stack[-8] = v_190;
v_190 = stack[-4];
v_190 = add1(v_190);
env = stack[-14];
stack[-4] = v_190;
goto v_115;
v_115:
goto v_88;
v_87:
v_191 = stack[-12];
v_190 = stack[-2];
stack[-4] = list2(v_191, v_190);
env = stack[-14];
v_190 = nil;
stack[-3] = ncons(v_190);
env = stack[-14];
v_190 = stack[-5];
v_190 = Lreverse(nil, v_190);
env = stack[-14];
stack[-5] = cons(stack[-3], v_190);
env = stack[-14];
stack[-3] = stack[-12];
v_190 = nil;
v_190 = ncons(v_190);
env = stack[-14];
{ LispObject fn = basic_elt(env, 2); // letmtr3
v_190 = (*qfn4up(fn))(fn, stack[-4], stack[-5], stack[-3], v_190);
}
env = stack[-14];
v_190 = stack[-2];
v_190 = add1(v_190);
env = stack[-14];
stack[-2] = v_190;
v_190 = stack[-13];
v_190 = add1(v_190);
env = stack[-14];
stack[-13] = v_190;
goto v_78;
v_80:
v_190 = stack[-13];
v_190 = add1(v_190);
env = stack[-14];
stack[-13] = v_190;
v_190 = stack[-2];
v_190 = add1(v_190);
env = stack[-14];
stack[-2] = v_190;
goto v_78;
v_78:
goto v_62;
v_64:
v_190 = stack[-13];
v_190 = add1(v_190);
env = stack[-14];
stack[-13] = v_190;
goto v_62;
v_62:
v_190 = stack[0];
v_190 = add1(v_190);
env = stack[-14];
stack[0] = v_190;
goto v_47;
v_46:
v_190 = stack[-11];
v_191 = add1(v_190);
env = stack[-14];
v_190 = stack[-12];
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = carerror(v_190); else
v_190 = car(v_190);
if (!car_legal(v_190)) v_190 = cdrerror(v_190); else
v_190 = cdr(v_190);
if (!car_legal(v_190)) v_190 = carerror(v_190); else
v_190 = car(v_190);
if (equal(v_191, v_190)) goto v_170;
else goto v_171;
v_170:
stack[0] = stack[-12];
v_190 = stack[-11];
v_190 = add1(v_190);
env = stack[-14];
stack[-2] = list2(stack[0], v_190);
env = stack[-14];
stack[-1] = nil;
stack[0] = stack[-12];
v_190 = nil;
v_190 = ncons(v_190);
env = stack[-14];
{ LispObject fn = basic_elt(env, 2); // letmtr3
v_190 = (*qfn4up(fn))(fn, stack[-2], stack[-1], stack[0], v_190);
}
goto v_169;
v_171:
v_169:
v_190 = stack[-12];
return onevalue(v_190);
}
// Code for ndepends
static LispObject CC_ndepends(LispObject env,
LispObject v_2, LispObject v_3)
{
env = qenv(env);
#if 0 // Start of trace output
#endif // End of trace output
LispObject v_142, v_143, v_144;
#ifdef CHECK_STACK
if_check_stack;
#endif
#ifdef CONSERVATIVE
poll();
#else // CONSERVATIVE
if (++reclaim_trigger_count == reclaim_trigger_target ||
stack >= stackLimit)
{
push(v_2,v_3);
env = reclaim(env, "stack", GC_STACK, 0);
pop(v_3,v_2);
}
#endif // CONSERVATIVE
real_push(env);
// space for vars preserved across procedure calls
push(nil, nil);
stack_popper stack_popper_var(3);
// copy arguments values to proper place
stack[0] = v_3;
stack[-1] = v_2;
// end of prologue
v_142 = stack[-1];
if (v_142 == nil) goto v_11;
else goto v_12;
v_11:
v_142 = lisp_true;
goto v_10;
v_12:
v_142 = stack[-1];
v_142 = (is_number(v_142) ? lisp_true : nil);
if (v_142 == nil) goto v_19;
else goto v_18;
v_19:
v_142 = stack[0];
v_142 = (is_number(v_142) ? lisp_true : nil);
v_18:
goto v_10;
v_142 = nil;
v_10:
if (v_142 == nil) goto v_8;
v_142 = nil;
goto v_6;
v_8:
v_143 = stack[-1];
v_142 = stack[0];
if (equal(v_143, v_142)) goto v_25;
else goto v_26;
v_25:
v_142 = stack[-1];
goto v_6;
v_26:
v_142 = stack[-1];
if (!consp(v_142)) goto v_34;
else goto v_35;
v_34:
v_143 = stack[-1];
v_142 = qvalue(basic_elt(env, 1)); // frlis!*
v_142 = Lmemq(nil, v_143, v_142);
goto v_33;
v_35:
v_142 = nil;
goto v_33;
v_142 = nil;
v_33:
if (v_142 == nil) goto v_31;
v_142 = lisp_true;
goto v_6;
v_31:
v_143 = stack[-1];
v_142 = qvalue(basic_elt(env, 2)); // depl!*
v_142 = Lassoc(nil, v_143, v_142);
v_143 = v_142;
v_142 = v_143;
if (v_142 == nil) goto v_52;
else goto v_53;
v_52:
v_142 = nil;
goto v_51;
v_53:
v_142 = v_143;
if (!car_legal(v_142)) v_143 = cdrerror(v_142); else
v_143 = cdr(v_142);
v_142 = stack[0];
{ LispObject fn = basic_elt(env, 4); // lndepends
v_142 = (*qfn2(fn))(fn, v_143, v_142);
}
env = stack[-2];
goto v_51;
v_142 = nil;
v_51:
if (v_142 == nil) goto v_45;
v_142 = lisp_true;
goto v_6;
v_45:
v_142 = stack[-1];
if (!consp(v_142)) goto v_68;
v_142 = stack[-1];
if (!car_legal(v_142)) v_142 = carerror(v_142); else
v_142 = car(v_142);
if (symbolp(v_142)) goto v_73;
v_142 = nil;
goto v_71;
v_73:
v_142 = stack[-1];
if (!car_legal(v_142)) v_142 = carerror(v_142); else
v_142 = car(v_142);
if (!symbolp(v_142)) v_142 = nil;
else { v_142 = qfastgets(v_142);
if (v_142 != nil) { v_142 = elt(v_142, 8); // dname
#ifdef RECORD_GET
if (v_142 != SPID_NOPROP)
record_get(elt(fastget_names, 8), 1);
else record_get(elt(fastget_names, 8), 0),
v_142 = nil; }
else record_get(elt(fastget_names, 8), 0); }
#else
if (v_142 == SPID_NOPROP) v_142 = nil; }}
#endif
goto v_71;
v_142 = nil;
v_71:
goto v_66;
v_68:
v_142 = nil;
goto v_66;
v_142 = nil;
v_66:
if (v_142 == nil) goto v_64;
v_142 = stack[-1];
if (!car_legal(v_142)) v_143 = carerror(v_142); else
v_143 = car(v_142);
v_142 = basic_elt(env, 3); // domain!-depends!-fn
v_142 = get(v_143, v_142);
v_143 = v_142;
v_142 = v_143;
if (v_142 == nil) goto v_93;
v_144 = v_143;
v_143 = stack[-1];
v_142 = stack[0];
return Lapply2(nil, v_144, v_143, v_142);
v_93:
v_142 = nil;
goto v_91;
v_142 = nil;
v_91:
goto v_6;
v_64:
v_142 = stack[-1];
{ LispObject fn = basic_elt(env, 5); // atomf
v_142 = (*qfn1(fn))(fn, v_142);
}
env = stack[-2];
if (v_142 == nil) goto v_106;
else goto v_107;
v_106:
v_142 = stack[-1];
if (!car_legal(v_142)) v_143 = cdrerror(v_142); else
v_143 = cdr(v_142);
v_142 = stack[0];
{ LispObject fn = basic_elt(env, 4); // lndepends
v_142 = (*qfn2(fn))(fn, v_143, v_142);
}
env = stack[-2];
if (v_142 == nil) goto v_112;
else goto v_111;
v_112:
v_142 = stack[-1];
if (!car_legal(v_142)) v_143 = carerror(v_142); else
v_143 = car(v_142);
v_142 = stack[0];
{ LispObject fn = basic_elt(env, 0); // ndepends
v_142 = (*qfn2(fn))(fn, v_143, v_142);
}
env = stack[-2];
v_111:
goto v_105;
v_107:
v_142 = nil;
goto v_105;
v_142 = nil;
v_105:
if (v_142 == nil) goto v_103;
v_142 = lisp_true;
goto v_6;
v_103:
v_142 = stack[0];
{ LispObject fn = basic_elt(env, 5); // atomf
v_142 = (*qfn1(fn))(fn, v_142);
}
if (v_142 == nil) goto v_127;
else goto v_125;
v_127:
v_142 = stack[0];
if (!car_legal(v_142)) v_142 = carerror(v_142); else
v_142 = car(v_142);
if (symbolp(v_142)) goto v_131;
else goto v_130;
v_131:
v_142 = stack[0];
if (!car_legal(v_142)) v_142 = carerror(v_142); else
v_142 = car(v_142);
if (!symbolp(v_142)) v_142 = nil;
else { v_142 = qfastgets(v_142);
if (v_142 != nil) { v_142 = elt(v_142, 8); // dname
#ifdef RECORD_GET
if (v_142 != SPID_NOPROP)
record_get(elt(fastget_names, 8), 1);
else record_get(elt(fastget_names, 8), 0),
v_142 = nil; }
else record_get(elt(fastget_names, 8), 0); }
#else
if (v_142 == SPID_NOPROP) v_142 = nil; }}
#endif
if (v_142 == nil) goto v_130;
goto v_125;
v_130:
goto v_126;
v_125:
v_142 = nil;
goto v_6;
v_126:
v_142 = nil;
goto v_6;
v_142 = nil;
v_6:
return onevalue(v_142);
}
setup_type const u37_setup[] =
{
{"lessppair", G0W2, G1W2, CC_lessppair,G3W2, G4W2},
{"lalr_print_first_information",CC_lalr_print_first_information,G1W0,G2W0,G3W0,G4W0},
{"smt_prin2x", G0W1, CC_smt_prin2x,G2W1, G3W1, G4W1},
{"ofsf_simplequal", G0W2, G1W2, CC_ofsf_simplequal,G3W2,G4W2},
{"pasf_exprng-gand", G0W4up, G1W4up, G2W4up, G3W4up, CC_pasf_exprngKgand},
{"bvarom", G0W1, CC_bvarom,G2W1, G3W1, G4W1},
{"s-nextarg", G0W1, CC_sKnextarg,G2W1, G3W1, G4W1},
{"wedgef", G0W1, CC_wedgef,G2W1, G3W1, G4W1},
{"apply_e", G0W1, CC_apply_e,G2W1, G3W1, G4W1},
{"diff_vertex", G0W2, G1W2, CC_diff_vertex,G3W2,G4W2},
{"assert_kernelp", G0W1, CC_assert_kernelp,G2W1,G3W1, G4W1},
{"evalgreaterp", G0W2, G1W2, CC_evalgreaterp,G3W2,G4W2},
{"solvealgdepends", G0W2, G1W2, CC_solvealgdepends,G3W2,G4W2},
{"make-image", G0W2, G1W2, CC_makeKimage,G3W2, G4W2},
{"giplus:", G0W2, G1W2, CC_giplusT,G3W2, G4W2},
{"ext_mult", G0W2, G1W2, CC_ext_mult,G3W2, G4W2},
{"gcd-with-number", G0W2, G1W2, CC_gcdKwithKnumber,G3W2,G4W2},
{"aex_sgn", G0W1, CC_aex_sgn,G2W1, G3W1, G4W1},
{"containerom", G0W1, CC_containerom,G2W1,G3W1, G4W1},
{"mkexdf", G0W1, CC_mkexdf,G2W1, G3W1, G4W1},
{"z-roads", G0W1, CC_zKroads,G2W1, G3W1, G4W1},
{"msolve-psys1", G0W2, G1W2, CC_msolveKpsys1,G3W2,G4W2},
{"ratlessp", G0W2, G1W2, CC_ratlessp,G3W2, G4W2},
{"lastcar", G0W1, CC_lastcar,G2W1, G3W1, G4W1},
{"aex_divposcnt", G0W2, G1W2, CC_aex_divposcnt,G3W2,G4W2},
{"settcollectnonmultiprolongations",G0W1,CC_settcollectnonmultiprolongations,G2W1,G3W1,G4W1},
{"processpartitie1list1", G0W2, G1W2, CC_processpartitie1list1,G3W2,G4W2},
{"mk+outer+list", G0W1, CC_mkLouterLlist,G2W1,G3W1, G4W1},
{"repr_ldeg", G0W1, CC_repr_ldeg,G2W1, G3W1, G4W1},
{"dip_f2dip2", G0W4up, G1W4up, G2W4up, G3W4up, CC_dip_f2dip2},
{"setfuncsnaryrd", CC_setfuncsnaryrd,G1W0,G2W0, G3W0, G4W0},
{"sqprint", G0W1, CC_sqprint,G2W1, G3W1, G4W1},
{"red_tailreddriver", G0W3, G1W3, G2W3, CC_red_tailreddriver,G4W3},
{"getavalue", G0W1, CC_getavalue,G2W1, G3W1, G4W1},
{"reduce-eival-powers", G0W2, G1W2, CC_reduceKeivalKpowers,G3W2,G4W2},
{"find-null-space", G0W2, G1W2, CC_findKnullKspace,G3W2,G4W2},
{"set_parser", G0W1, CC_set_parser,G2W1, G3W1, G4W1},
{"sq_member", G0W2, G1W2, CC_sq_member,G3W2, G4W2},
{"orddf", G0W2, G1W2, CC_orddf, G3W2, G4W2},
{"cl_susiupdknowl", G0W4up, G1W4up, G2W4up, G3W4up, CC_cl_susiupdknowl},
{"gftimes", G0W2, G1W2, CC_gftimes,G3W2, G4W2},
{"calc_den_tar", G0W2, G1W2, CC_calc_den_tar,G3W2,G4W2},
{"no-side-effectp", G0W1, CC_noKsideKeffectp,G2W1,G3W1, G4W1},
{"atom_compare", G0W2, G1W2, CC_atom_compare,G3W2,G4W2},
{"lalr_expand_grammar", G0W1, CC_lalr_expand_grammar,G2W1,G3W1,G4W1},
{"aex_stchsgnch1", G0W3, G1W3, G2W3, CC_aex_stchsgnch1,G4W3},
{"janettreenodebuild", G0W3, G1W3, G2W3, CC_janettreenodebuild,G4W3},
{"even_action_term", G0W4up, G1W4up, G2W4up, G3W4up, CC_even_action_term},
{"testord", G0W2, G1W2, CC_testord,G3W2, G4W2},
{"my+nullsq+p", G0W1, CC_myLnullsqLp,G2W1,G3W1, G4W1},
{"pasf_varlat", G0W1, CC_pasf_varlat,G2W1,G3W1, G4W1},
{"rl_surep", G0W2, G1W2, CC_rl_surep,G3W2, G4W2},
{"minusrd", CC_minusrd,G1W0, G2W0, G3W0, G4W0},
{"assoc2", G0W2, G1W2, CC_assoc2,G3W2, G4W2},
{"rewrite", G0W4up, G1W4up, G2W4up, G3W4up, CC_rewrite},
{"ndepends", G0W2, G1W2, CC_ndepends,G3W2, G4W2},
{nullptr,
reinterpret_cast<no_args *>(
reinterpret_cast<uintptr_t>("u37")),
reinterpret_cast<one_arg *>(
reinterpret_cast<uintptr_t>("151279 6388377 1372549")),
nullptr, nullptr, nullptr}
};
// end of generated code
| 26.065622 | 123 | 0.576819 | arthurcnorman |
1fcc7e469e970f97ae9d90ed18bb7ae530a941e9 | 5,453 | cpp | C++ | src/Cube/CubePlayer.cpp | austinkinross/rubiks-cube-solver | dac8c375502a2c002e3797a549d04b4e31e9e9c2 | [
"MIT"
] | 25 | 2015-09-02T10:25:51.000Z | 2022-02-26T03:50:51.000Z | src/Cube/CubePlayer.cpp | austinkinross/rubiks-cube-solver | dac8c375502a2c002e3797a549d04b4e31e9e9c2 | [
"MIT"
] | 1 | 2018-02-13T12:59:04.000Z | 2018-02-13T12:59:04.000Z | src/Cube/CubePlayer.cpp | austinkinross/rubiks-cube-solver | dac8c375502a2c002e3797a549d04b4e31e9e9c2 | [
"MIT"
] | 11 | 2017-05-06T09:40:21.000Z | 2021-04-21T04:09:15.000Z | #include "pch.h"
#include "CubePlayer.h"
CubePlayer::CubePlayer(CubePlayerDesc* desc)
{
mCube = new Cube();
mDesc = *desc;
Reset();
bPaused = false;
if (mDesc.populateColors)
{
mPlaybackState = PLAYBACK_STATE_POPULATING_COLORS;
mFoldingAngle = 3.141592653f / 2;
// Set all the faces to be nearly black
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
mCube->frontFaceStickers[i][j]->SetColor(StickerColor::CUBE_BLACK);
mCube->backFaceStickers[i][j]->SetColor(StickerColor::CUBE_BLACK);
mCube->topFaceStickers[i][j]->SetColor(StickerColor::CUBE_BLACK);
mCube->bottomFaceStickers[i][j]->SetColor(StickerColor::CUBE_BLACK);
mCube->leftFaceStickers[i][j]->SetColor(StickerColor::CUBE_BLACK);
mCube->rightFaceStickers[i][j]->SetColor(StickerColor::CUBE_BLACK);
}
}
}
else if (mDesc.unfoldCubeAtStart)
{
mPlaybackState = PLAYBACK_STATE_FOLDING;
mFoldingAngle = 3.141592653f / 2;
}
else
{
mPlaybackState = PLAYBACK_STATE_SOLVING;
mFoldingAngle = 0.0f;
}
mCube->SetFoldAngle(mFoldingAngle);
}
CubePlayer::~CubePlayer()
{
delete mCube;
}
void CubePlayer::Reset()
{
uiCurrentCommandPos = 0;
fCurrentCommandProportion = 0.0f;
}
void CubePlayer::UseCommandList(CubeCommandList *pCommandList)
{
mCubeCommandList = pCommandList;
Reset();
}
void CubePlayer::Pause()
{
bPaused = true;
}
void CubePlayer::Play()
{
bPaused = false;
}
unsigned int tempCount = 0;
//-------------------------------------------------------------------------------------------------------------------------------------------------------
// NOT NEEDED
//-------------------------------------------------------------------------------------------------------------------------------------------------------
void CubePlayer::Update(float timeTotal, float timeDelta)
{
// XMStoreFloat4x4(&pPlaybackCube->worldMatrix, XMMatrixTranspose(XMMatrixMultiply(XMMatrixRotationY(timeTotal * XM_PIDIV4), XMMatrixRotationX((float) sin(0/3) * XM_PIDIV4))));
if (!bPaused)
{
if (mPlaybackState == PLAYBACK_STATE_FOLDING)
{
mFoldingAngle -= timeDelta / mDesc.speeds.foldingSpeed;
if (mFoldingAngle < 0.0f)
{
mFoldingAngle = 0.0f;
mPlaybackState = PLAYBACK_STATE_SOLVING;
}
mCube->SetFoldAngle(mFoldingAngle);
}
else if (mPlaybackState == PLAYBACK_STATE_SOLVING)
{
if (uiCurrentCommandPos < mCubeCommandList->GetLength())
{
CubeCommand currentCommand = mCubeCommandList->GetCommandAt(uiCurrentCommandPos);
fCurrentCommandProportion += timeDelta / mDesc.speeds.solvingSpeed;
if (fCurrentCommandProportion >= 1.0f)
{
mCube->ApplyCommand(currentCommand);
fCurrentCommandProportion = 0.0f;
uiCurrentCommandPos += 1;
if (uiCurrentCommandPos < mCubeCommandList->GetLength())
{
CubeCommand nextCommand = mCubeCommandList->GetCommandAt(uiCurrentCommandPos);
while (nextCommand == CubeRotateY && uiCurrentCommandPos < mCubeCommandList->GetLength())
{
mCube->ApplyCommand(nextCommand);
uiCurrentCommandPos += 1;
if (uiCurrentCommandPos < mCubeCommandList->GetLength())
{
nextCommand = mCubeCommandList->GetCommandAt(uiCurrentCommandPos);
}
}
}
// Maybe call Update again with a reduced time delta?
}
// Now that we've performed the actual twist (if it was needed), we should update the slices' angles
float fRotationAngle = (-fCurrentCommandProportion*fCurrentCommandProportion*fCurrentCommandProportion + 2 * fCurrentCommandProportion*fCurrentCommandProportion) * (float)(3.141592f / 2);
if (IsPrimeCubeCommand(currentCommand))
{
fRotationAngle *= -1;
}
switch (currentCommand)
{
case CubeCommandLeft:
case CubeCommandLeftPrime:
mCube->pLeftSlice->SetAngle(fRotationAngle);
break;
case CubeCommandRight:
case CubeCommandRightPrime:
mCube->pRightSlice->SetAngle(fRotationAngle);
break;
case CubeCommandTop:
case CubeCommandTopPrime:
mCube->pTopSlice->SetAngle(fRotationAngle);
break;
case CubeCommandBottom:
case CubeCommandBottomPrime:
mCube->pBottomSlice->SetAngle(fRotationAngle);
break;
case CubeCommandFront:
case CubeCommandFrontPrime:
mCube->pFrontSlice->SetAngle(fRotationAngle);
break;
case CubeCommandBack:
case CubeCommandBackPrime:
mCube->pBackSlice->SetAngle(fRotationAngle);
break;
}
}
}
}
} | 33.048485 | 203 | 0.537502 | austinkinross |
1fcdd8cfaef7342c56d5f667712a70cc23694a8a | 3,749 | cc | C++ | agenda.cc | Ralusama19/AgendaPRO2 | fcbf56a4ef28d06b85845671c847725deb4e8ed0 | [
"MIT"
] | 1 | 2016-01-16T10:17:20.000Z | 2016-01-16T10:17:20.000Z | agenda.cc | Ralusama19/Agenda | fcbf56a4ef28d06b85845671c847725deb4e8ed0 | [
"MIT"
] | null | null | null | agenda.cc | Ralusama19/Agenda | fcbf56a4ef28d06b85845671c847725deb4e8ed0 | [
"MIT"
] | null | null | null | /** @file agenda.cc
@brief Codi de la classe Agenda
*/
#include "agenda.hh"
void Agenda::escriu(string expressio, map<Rellotge,Activitat>::iterator& principi,
map<Rellotge,Activitat>::iterator& final, bool passat){
//Buidem el menu abans de cada consulta
menu.clear();
int i = 1;
for(map<Rellotge,Activitat>::iterator it = principi; it != final; ++it){
if((expressio == "") or (it->second.compleix_expressio(expressio))){
//Si no es una consulta sobre el passat, actualitzem el menu amb els iteradors de les activitats escrites
if (not passat) menu.push_back(it);
cout << i << " " ;
it->second.escriu_titol();
cout << " " << it->first.consultar_data() << " " << it->first.consultar_horaminut();
it->second.escriu_etiquetes();
cout << endl;
++i;
}
}
}
// Constructora
Agenda::Agenda(){}
//Destructora
Agenda::~Agenda(){}
// Consultores
bool Agenda::i_valida(int i) const{
//Ens assegurem que la i es refereixi a una posicio del menu i que la tasca a la que es refereix existeixi
return (0 <= i and i < menu.size() and menu[i] != agenda.end());
}
void Agenda::consultar_rellotge_intern(Rellotge& rel) const{
rel = rellotge_intern;
}
void Agenda::consultar_rellotge_iessim(Rellotge & rel, int i) const{
rel = menu[i]->first;
}
void Agenda::consultar_activitat_iessima(Activitat & act, int i) const{
act = menu[i]->second;
}
//Modificadores
void Agenda::modifica_rellotge_intern(Rellotge& rel) {
//assignem rel al rellotge intern
rellotge_intern = rel;
int i = 0;
//actualitzem el menu perque no es puguin modificar tasques que formen part del passat
while (i < menu.size() and menu[i] != agenda.end()
and menu[i]->first < rellotge_intern){
menu[i] = agenda.end();
++i;
}
}
void Agenda::modifica_activitat_iessima(Activitat& act, int i) {
menu[i]->second = act;
}
bool Agenda::afegir_activitat(const Rellotge& rel,const Activitat& act){
pair<map<Rellotge, Activitat>::iterator, bool> result;
//ens assegurem de no crear una tasca ala mateixa data i hora que unaltre
result = agenda.insert(make_pair(rel, act));
return result.second;
}
bool Agenda::esborra_etiqueta(int i,string etiq){
return menu[i]->second.esborrar_etiqueta(etiq);
}
void Agenda::esborra_etiquetes(int i){
menu[i]->second.esborrar_totes_etiquetes();
}
bool Agenda::esborra_activitat(int i){
int num_borrats = agenda.erase(menu[i]->first);
if (num_borrats > 0) menu[i] = agenda.end();
return (num_borrats > 0);
}
// Escriptura
void Agenda::escriu_rellotge(){
rellotge_intern.escriu_rellotge();
}
void Agenda::escriu_passat(){
menu.clear();
map<Rellotge,Activitat>::iterator principi = agenda.begin();
map<Rellotge,Activitat>::iterator final = agenda.lower_bound(rellotge_intern);
escriu("", principi, final, true);
}
void Agenda::escriu_per_condicio(const bool& data, string primera_data, string segona_data,
const string& s, bool h){
map<Rellotge,Activitat>::iterator principi, final;
if(data){
Rellotge rel1("00:00", primera_data), rel2("23:59", segona_data);
if (h){
rel1 = rellotge_intern;
}
principi = agenda.lower_bound(rel1);
final = agenda.upper_bound(rel2);
}
else {
principi = agenda.lower_bound(rellotge_intern);
final = agenda.end();
}
escriu(s,principi,final, false);
}
void Agenda::escriu_futur(){
map<Rellotge,Activitat>::iterator principi = agenda.lower_bound(rellotge_intern);
map<Rellotge,Activitat>::iterator final = agenda.end();
escriu("", principi, final, false);
}
| 28.618321 | 117 | 0.656175 | Ralusama19 |
1fd01218c9038aeae853bee03be5380b47ef88dc | 845 | cpp | C++ | clang/test/CoverageMapping/branch-templates.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 2,338 | 2018-06-19T17:34:51.000Z | 2022-03-31T11:00:37.000Z | clang/test/CoverageMapping/branch-templates.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 3,740 | 2019-01-23T15:36:48.000Z | 2022-03-31T22:01:13.000Z | clang/test/CoverageMapping/branch-templates.cpp | mkinsner/llvm | 589d48844edb12cd357b3024248b93d64b6760bf | [
"Apache-2.0"
] | 500 | 2019-01-23T07:49:22.000Z | 2022-03-30T02:59:37.000Z | // Test that branch regions are generated for conditions in function template
// instantiations.
// RUN: %clang_cc1 -triple %itanium_abi_triple -std=c++11 -fprofile-instrument=clang -fcoverage-mapping -dump-coverage-mapping -emit-llvm-only -main-file-name branch-templates.cpp %s | FileCheck %s
template<typename T>
void unused(T x) {
return;
}
template<typename T>
int func(T x) {
if(x)
return 0;
else
return 1;
int j = 1;
}
int main() {
func<int>(0);
func<bool>(true);
func<float>(0.0);
return 0;
}
// CHECK-LABEL: _Z4funcIiEiT_:
// CHECK: Branch,File 0, [[@LINE-15]]:6 -> [[@LINE-15]]:7 = #1, (#0 - #1)
// CHECK-LABEL: _Z4funcIbEiT_:
// CHECK: Branch,File 0, [[@LINE-17]]:6 -> [[@LINE-17]]:7 = #1, (#0 - #1)
// CHECK-LABEL: _Z4funcIfEiT_:
// CHECK: Branch,File 0, [[@LINE-19]]:6 -> [[@LINE-19]]:7 = #1, (#0 - #1)
| 25.606061 | 197 | 0.628402 | mkinsner |
1fd019f5eae961b527c7274325f4a3aa76ad6f4b | 476 | hpp | C++ | libs/media/impl/include/sge/media/impl/log_name.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | libs/media/impl/include/sge/media/impl/log_name.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | libs/media/impl/include/sge/media/impl/log_name.hpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef SGE_MEDIA_IMPL_LOG_NAME_HPP_INCLUDED
#define SGE_MEDIA_IMPL_LOG_NAME_HPP_INCLUDED
#include <sge/media/detail/symbol.hpp>
#include <fcppt/log/name.hpp>
namespace sge::media::impl
{
SGE_MEDIA_DETAIL_SYMBOL
fcppt::log::name log_name();
}
#endif
| 22.666667 | 61 | 0.743697 | cpreh |
1fd2c78f8f8cb0adda77f14cbe70d968e5983560 | 7,815 | hpp | C++ | Code/Libs/Math/Bits.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | null | null | null | Code/Libs/Math/Bits.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | 8 | 2016-11-17T00:39:03.000Z | 2016-11-29T14:46:27.000Z | Code/Libs/Math/Bits.hpp | NotKyon/Tenshi | 9bd298c6ef4e6ae446a866c2918e15b4ab22f9e7 | [
"Zlib"
] | null | null | null | #pragma once
#include "../Platform/Platform.hpp"
#include "../Core/TypeTraits.hpp"
namespace Ax { namespace Math {
/// Unsigned bit-shift right
template< typename tInt >
inline tInt BitShiftRightU( tInt x, tInt y )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
typedef typename TMakeUnsigned< tInt >::type tUnsigned;
return
static_cast< tInt >(
static_cast< tUnsigned >( x ) >> y
);
}
/// Signed bit-shift right
template< typename tInt >
inline tInt BitShiftRightS( tInt x, tInt y )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
typedef typename TMakeSigned< tInt >::type tSigned;
return
static_cast< tInt >(
static_cast< tSigned >( x ) >> y
);
}
/// Put a zero bit between each of the lower bits of the given value
template< typename tInt >
inline tInt BitExpand( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
tInt r = 0;
for( uintcpu i = 0; i < ( sizeof( x )*8 )/2; ++i )
{
r |= ( x & ( 1 << i ) ) << i;
}
return r;
}
/// Take each other bit of a value and merge into one value
template< typename tInt >
inline tInt BitMerge( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
tInt r = 0;
for( uintcpu i = 0; i < ( sizeof( x )*8 )/2; ++i )
{
r |= ( x & ( 1 << ( i*2 ) ) ) >> i;
}
return r;
}
/// Specialization of BitExpand() for uint32
inline uint32 BitExpand( uint32 x )
{
// http://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
x &= 0xFFFF;
x = ( x ^ ( x << 8 ) ) & 0x00FF00FF;
x = ( x ^ ( x << 4 ) ) & 0x0F0F0F0F;
x = ( x ^ ( x << 2 ) ) & 0x33333333;
x = ( x ^ ( x << 1 ) ) & 0x55555555;
return x;
}
/// Specialization of BitMerge() for uint32
inline uint32 BitMerge( uint32 x )
{
// http://fgiesen.wordpress.com/2009/12/13/decoding-morton-codes/
x &= 0x55555555;
x = ( x ^ ( x >> 1 ) ) & 0x33333333;
x = ( x ^ ( x >> 2 ) ) & 0x0F0F0F0F;
x = ( x ^ ( x >> 4 ) ) & 0x00FF00FF;
x = ( x ^ ( x >> 8 ) ) & 0x0000FFFF;
return x;
}
/// Turn off the right-most set bit (e.g., 01011000 -> 01010000)
template< typename tInt >
inline tInt BitRemoveLowestSet( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return x & ( x - 1 );
}
/// Determine whether a number is a power of two
template< typename tInt >
inline bool BitIsPowerOfTwo( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return BitRemoveLowestSet( x ) == 0;
}
/// Isolate the right-most set bit (e.g., 01011000 -> 00001000)
template< typename tInt >
inline tInt BitIsolateLowestSet( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return x & ( -x );
}
/// Isolate the right-most clear bit (e.g., 10100111 -> 00001000)
template< typename tInt >
inline tInt BitIsolateLowestClear( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return -x & ( x + 1 );
}
/// Create a mask of the trailing clear bits (e.g., 01011000 -> 00000111)
template< typename tInt >
inline tInt BitIdentifyLowestClears( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return -x & ( x - 1 );
}
/// Create a mask that identifies the least significant set bit and the
/// trailing clear bits (e.g., 01011000 -> 00001111)
template< typename tInt >
inline tInt BitIdentifyLowestSetAndClears( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return x ^ ( x - 1 );
}
/// Propagate the lowest set bit to the lower clear bits
template< typename tInt >
inline tInt BitPropagateLowestSet( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return x | ( x - 1 );
}
/// Find the absolute value of an integer
template< typename tInt >
inline tInt BitAbs( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
const tInt y = BitShiftRightS( x, ( tInt )( sizeof( x )*8 - 1 ) );
return ( x ^ y ) - y;
}
/// Find the sign of an integer
template< typename tInt >
inline tInt BitSign( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
static const tInt s = sizeof( tInt )*8 - 1;
return BitShiftRightS( x, s ) | BitShiftRightU( -x, s );
}
/// Transfer the sign of src into dst
template< typename tInt >
inline tInt BitCopySign( tInt dst, tInt src )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
const tInt t = BitShiftRightS( src, ( tInt )( sizeof( tInt )*8 - 1 ) );
return ( BitAbs( dst ) + t ) ^ t;
}
/// Rotate a field of bits left
template< typename tInt >
inline tInt BitRotateLeft( tInt x, tInt y )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return ( x << y ) | BitShiftRightU( x, sizeof( x )*8 - y );
}
/// Rotate a field of bits right
template< typename tInt >
inline tInt BitRotateRight( tInt x, tInt y )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
return BitShiftRightU( x, y ) | ( x << ( sizeof( x )*8 - y ) );
}
/// Count the number of set bits
template< typename tInt >
inline tInt BitCount( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
tInt r = x;
for( int i = 0; i < sizeof( x )*8; ++i )
{
r -= x >> ( 1 << i );
}
return r;
}
/// Specialization of BitCount() for 32-bit integers
inline uint32 BitCount( uint32 x )
{
x = x - ( ( x >> 1 ) & 0x55555555 );
x = ( x & 0x33333333 ) + ( ( x >> 2 ) & 0x33333333 );
x = ( x + ( x >> 4 ) ) & 0x0F0F0F0F;
x = x + ( x >> 8 );
x = x + ( x >> 16 );
return x & 0x0000003F;
}
/// Compute the parity of an integer (true for odd, false for even)
template< typename tInt >
inline tInt BitParity( tInt x )
{
static_assert( TIsInt< tInt >::value, "Integer type required" );
x = x ^ ( x >> 1 );
x = x ^ ( x >> 2 );
x = x ^ ( x >> 4 );
if( sizeof( x ) > 1 )
{
x = x ^ ( x >> 8 );
if( sizeof( x ) > 2 )
{
x = x ^ ( x >> 16 );
if( sizeof( x ) > 4 )
{
x = x ^ ( x >> 32 );
int i = 8;
while( sizeof( x ) > i )
{
x = x ^ ( x >> ( i*8 ) );
i = i*2;
}
}
}
}
return x;
}
/// Treat the bits of a signed-integer as a float encoding.
inline float IntBitsToFloat( int32 x )
{
union
{
float f;
int32 i;
} v;
v.i = x;
return v.f;
}
inline double IntBitsToFloat( int64 x )
{
union
{
double f;
int64 i;
} v;
v.i = x;
return v.f;
}
/// Treat the bits of an unsigned-integer as a float encoding.
inline float UintBitsToFloat( uint32 x )
{
union
{
float f;
uint32 i;
} v;
v.i = x;
return v.f;
}
inline double UintBitsToFloat( uint64 x )
{
union
{
double f;
uint64 i;
} v;
v.i = x;
return v.f;
}
/// Retrieve the encoding of a float's bits as a signed-integer.
inline int32 FloatToIntBits( float x )
{
union
{
float f;
int32 i;
} v;
v.f = x;
return v.i;
}
inline int64 FloatToIntBits( double x )
{
union
{
double f;
int64 i;
} v;
v.f = x;
return v.i;
}
/// Retrieve the encoding of a float's bits as an unsigned-integer.
inline uint32 FloatToUintBits( float x )
{
union
{
float f;
uint32 i;
} v;
v.f = x;
return v.i;
}
inline uint64 FloatToUintBits( double x )
{
union
{
double f;
uint64 i;
} v;
v.f = x;
return v.i;
}
/// Check whether a floating-point value is a NAN.
inline bool IsNAN( float x )
{
const uint32 xi = FloatToUintBits( x );
return ( xi & 0x7F800000 ) == 0x7F800000 && ( xi & 0x7FFFFF ) != 0;
}
/// Check whether a floating-point value is infinity.
inline bool IsInf( float x )
{
return ( FloatToUintBits( x ) & 0x7FFFFFFF ) == 0x7F800000;
}
}}
| 22.456897 | 74 | 0.595777 | NotKyon |
1fd6a24b8cf03fef98d6657d9a9156ecfbc97a68 | 2,650 | hxx | C++ | OCC/inc/TDataXtd_Axis.hxx | cy15196/FastCAE | 0870752ec2e590f3ea6479e909ebf6c345ac2523 | [
"BSD-3-Clause"
] | 117 | 2020-03-07T12:07:05.000Z | 2022-03-27T07:35:22.000Z | opencascade/TDataXtd_Axis.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 33 | 2019-11-13T18:09:51.000Z | 2021-11-26T17:24:12.000Z | opencascade/TDataXtd_Axis.hxx | CadQuery/cpp-py-bindgen | 66e7376d3a27444393fc99acbdbef40bbc7031ae | [
"Apache-2.0"
] | 76 | 2020-03-16T01:47:46.000Z | 2022-03-21T16:37:07.000Z | // Created on: 2009-04-06
// Created by: Sergey ZARITCHNY
// Copyright (c) 2009-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _TDataXtd_Axis_HeaderFile
#define _TDataXtd_Axis_HeaderFile
#include <Standard.hxx>
#include <Standard_Type.hxx>
#include <TDF_Attribute.hxx>
#include <Standard_OStream.hxx>
class Standard_GUID;
class TDF_Label;
class gp_Lin;
class TDF_Attribute;
class TDF_RelocationTable;
class TDataXtd_Axis;
DEFINE_STANDARD_HANDLE(TDataXtd_Axis, TDF_Attribute)
//! The basis to define an axis attribute.
//!
//! Warning: Use TDataXtd_Geometry attribute to retrieve the
//! gp_Lin of the Axis attribute
class TDataXtd_Axis : public TDF_Attribute
{
public:
//! class methods
//! =============
//! Returns the GUID for an axis.
Standard_EXPORT static const Standard_GUID& GetID();
//! Finds or creates an axis attribute defined by the label.
//! In the case of a creation of an axis, a compatible
//! named shape should already be associated with label.
//! Exceptions
//! Standard_NullObject if no compatible named
//! shape is associated with the label.
Standard_EXPORT static Handle(TDataXtd_Axis) Set (const TDF_Label& label);
//! Find, or create, an Axis attribute and set <P> as
//! generated in the associated NamedShape.
//! Axis methods
//! ============
Standard_EXPORT static Handle(TDataXtd_Axis) Set (const TDF_Label& label, const gp_Lin& L);
Standard_EXPORT TDataXtd_Axis();
Standard_EXPORT const Standard_GUID& ID() const Standard_OVERRIDE;
Standard_EXPORT void Restore (const Handle(TDF_Attribute)& with) Standard_OVERRIDE;
Standard_EXPORT Handle(TDF_Attribute) NewEmpty() const Standard_OVERRIDE;
Standard_EXPORT void Paste (const Handle(TDF_Attribute)& into, const Handle(TDF_RelocationTable)& RT) const Standard_OVERRIDE;
Standard_EXPORT virtual Standard_OStream& Dump (Standard_OStream& anOS) const Standard_OVERRIDE;
DEFINE_STANDARD_RTTIEXT(TDataXtd_Axis,TDF_Attribute)
protected:
private:
};
#endif // _TDataXtd_Axis_HeaderFile
| 26.767677 | 128 | 0.753962 | cy15196 |
1fdadc0b7096a0bea6af82390e209a511cde7b36 | 299 | cpp | C++ | Library/Library.prj/TBButton.cpp | rrvt/RWracesDB | 4f01fed973df7dfb7ec516b2969b20fc6744d7fe | [
"MIT"
] | null | null | null | Library/Library.prj/TBButton.cpp | rrvt/RWracesDB | 4f01fed973df7dfb7ec516b2969b20fc6744d7fe | [
"MIT"
] | 1 | 2020-05-01T00:37:31.000Z | 2020-05-01T00:37:31.000Z | Library/Library.prj/TBButton.cpp | rrvt/RWracesDB | 4f01fed973df7dfb7ec516b2969b20fc6744d7fe | [
"MIT"
] | 1 | 2020-02-25T09:11:37.000Z | 2020-02-25T09:11:37.000Z | // Toolbar Button (i.e. MFC Tool Bar Button)
#include "stdafx.h"
#include "TBButton.h"
TBButton::TBButton(uint id) : CMFCToolBarButton(id, -1) { }
void TBButton::install(TCchar* caption)
{m_nStyle = TBBS_BUTTON | TBBS_AUTOSIZE; m_strText = caption; m_bText = true; m_bImage = false;}
| 21.357143 | 104 | 0.692308 | rrvt |
1fdce391236ceb9548c8c08c8d69194200f2a895 | 5,023 | cpp | C++ | src/cpp/Device.cpp | pongasoft/re-cva-7 | 62b80f681e75b64a98cce87ad64084712d1c3a36 | [
"Apache-2.0"
] | 9 | 2020-02-17T18:43:32.000Z | 2020-04-06T04:10:25.000Z | src/cpp/Device.cpp | pongasoft/re-cva-7 | 62b80f681e75b64a98cce87ad64084712d1c3a36 | [
"Apache-2.0"
] | 3 | 2020-05-16T14:00:37.000Z | 2020-09-20T15:26:38.000Z | src/cpp/Device.cpp | pongasoft/re-cva-7 | 62b80f681e75b64a98cce87ad64084712d1c3a36 | [
"Apache-2.0"
] | 2 | 2020-02-17T18:43:36.000Z | 2020-05-16T09:58:42.000Z | #include "Device.h"
#include <logging/logging.h>
Device::Device(int iSampleRate): CommonDevice(),
fFirstBatch(true),
fPreviousDeviceState(iSampleRate),
fCurrentDeviceState(iSampleRate)
{
DLOG_F(INFO, "Device()");
#ifndef __phdsp__
JBOX_TRACE("Local 45 XCode Mode!!!");
#endif // !__phdsp__
fCurrentDeviceState.fMotherboard.registerForUpdate(fJBoxPropertyManager);
}
Device::~Device()
{
// nothing to do
JBOX_TRACE("~Device()");
}
void Device::renderBatch(TJBox_PropertyDiff const iPropertyDiffs[], TJBox_UInt32 iDiffCount)
{
bool stateChanged = false;
if(fFirstBatch)
{
doInitDevice(iPropertyDiffs, iDiffCount);
stateChanged = true;
fFirstBatch = false;
}
else
{
if(iDiffCount > 0)
{
stateChanged |= fJBoxPropertyManager.onUpdate(iPropertyDiffs, iDiffCount);
}
}
stateChanged = fCurrentDeviceState.afterMotherboardUpdate(stateChanged, fPreviousDeviceState);
stateChanged |= doRenderBatch(stateChanged);
if(stateChanged)
fPreviousDeviceState.update(fCurrentDeviceState);
//fCurrentDeviceState.fMotherboard.fCVIn1.afterRenderBatch();
}
bool Device::doRenderBatch(bool propertyStateChange)
{
Motherboard &motherboard = fCurrentDeviceState.fMotherboard;
if(motherboard.fCVIn1.isConnected())
{
TJBox_Float64 const cvIn1Value = motherboard.fCVIn1.getValue();
// simply copy to out if necessary
for(int i = 0; i < MAX_CV_OUT; i++)
fCurrentDeviceState.setCVOut(*motherboard.fCVOut[i], cvIn1Value);
// handle pause/resume
if(!fCurrentDeviceState.isPaused())
{
if(cvIn1Value != MAX_TJbox_Float64)
{
CVPoint zoomedCVIn1Point(cvIn1Value);
// store in the buffer
fCurrentDeviceState.fCVIn1Buffer.setAt(0, cvIn1Value);
TJBox_Int32 arrayStart = motherboard.fPropArrayStart.getValue();
arrayStart++;
if(arrayStart >= MAX_ARRAY_SIZE)
arrayStart = 0;
if(fCurrentDeviceState.zoom(cvIn1Value, zoomedCVIn1Point))
{
propertyStateChange |= storeCVIn1Value(motherboard, zoomedCVIn1Point);
TJBox_Int32 cvIn1Display = fCurrentDeviceState.toDisplayValue(zoomedCVIn1Point.fAvg);
if(!fCurrentDeviceState.isScreenOff() && fCurrentDeviceState.shouldUpdateArrayStart(cvIn1Display))
{
if(fCurrentDeviceState.fPendingUpdates.hasPendingUpdates())
fCurrentDeviceState.fPendingUpdates.setPendingValue(arrayStart, cvIn1Display);
else
propertyStateChange |= motherboard.fPropArray[arrayStart]->storeValueToMotherboardOnUpdate(cvIn1Display);
propertyStateChange |= motherboard.fPropArrayStart.storeValueToMotherboardOnUpdate(arrayStart);
}
}
fCurrentDeviceState.fCVIn1Buffer.incrementHead();
}
}
else
{
// pause mode
// input page offset has changed or history offset has changed or zoom has changed
if(fPreviousDeviceState.fMotherboard.fPropInputPageOffset.getValue() != motherboard.fPropInputPageOffset.getValue()
|| fPreviousDeviceState.fMotherboard.fPropInputHistoryOffset.getValue() != fCurrentDeviceState.fMotherboard.fPropInputHistoryOffset.getValue()
|| fPreviousDeviceState.fMotherboard.fPropZoomFactorX.getValue() != motherboard.fPropZoomFactorX.getValue()
|| fPreviousDeviceState.fMotherboard.fPropCVIn1MinMaxReset.getValue() != motherboard.fPropCVIn1MinMaxReset.getValue())
{
propertyStateChange |= storeCVIn1Value(motherboard, fCurrentDeviceState.getCVIn1PausedValue());
}
}
}
propertyStateChange |= fCurrentDeviceState.handlePendingUpdates();
return propertyStateChange;
}
bool Device::storeCVIn1Value(Motherboard &motherboard, CVPoint const &cvIn1Point)
{
bool res = false;
// handle note
res |= fCurrentDeviceState.storePropCVIn1ValueAsNote(cvIn1Point.fAvg);
// updated only when reset is not being pressed
if(motherboard.fPropCVIn1MinMaxReset.getValue() == TJbox_FALSE)
{
// handle min
if(fCurrentDeviceState.fCVIn1MinValue > cvIn1Point.fMin)
{
res |= fCurrentDeviceState.setCVIn1MinValue(cvIn1Point.fMin);
}
// handle max
if(fCurrentDeviceState.fCVIn1MaxValue < cvIn1Point.fMax)
{
res |= fCurrentDeviceState.setCVIn1MaxValue(cvIn1Point.fMax);
}
}
// store current value
res |= fCurrentDeviceState.storePropCVIn1Value(cvIn1Point.fAvg);
return res;
}
void Device::doInitDevice(TJBox_PropertyDiff const iPropertyDiffs[], TJBox_UInt32 iDiffCount)
{
JBOX_TRACE("Initializing device...");
// initialize properties
fJBoxPropertyManager.initProperties();
// processes the updates
fJBoxPropertyManager.onUpdate(iPropertyDiffs, iDiffCount);
// initialize current device
fCurrentDeviceState.init();
// copy to previous state to initialize it too!
fPreviousDeviceState.update(fCurrentDeviceState);
JBOX_TRACE("Init complete.");
}
| 30.442424 | 150 | 0.715509 | pongasoft |
1fde1f386c04c4a1f8a36b5e634b98ea9cd96fbe | 2,788 | hh | C++ | LiteCore/RevTrees/RevID.hh | cedseat/couchbase-lite-core | 451cdfcf527073c595c7cc389f1bd70694e215fb | [
"Apache-2.0"
] | 1 | 2019-04-17T07:41:04.000Z | 2019-04-17T07:41:04.000Z | LiteCore/RevTrees/RevID.hh | cedseat/couchbase-lite-core | 451cdfcf527073c595c7cc389f1bd70694e215fb | [
"Apache-2.0"
] | 1 | 2020-03-17T11:11:30.000Z | 2020-03-17T11:11:30.000Z | LiteCore/RevTrees/RevID.hh | cedseat/couchbase-lite-core | 451cdfcf527073c595c7cc389f1bd70694e215fb | [
"Apache-2.0"
] | null | null | null | //
// RevID.hh
//
// Copyright (c) 2014 Couchbase, Inc All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
#pragma once
#include "Base.hh"
namespace litecore {
enum revidType {
kDigestType,
kClockType
};
/** A compressed revision ID.
Since this is based on slice, it doesn't own the memory it points to.
The data format is the generation as a varint, followed by the digest as raw binary. */
class revid : public slice {
public:
revid() :slice() {}
revid(const void* b, size_t s) :slice(b,s) {}
explicit revid(slice s) :slice(s) {}
alloc_slice expanded() const;
size_t expandedSize() const;
bool expandInto(slice &dst) const;
bool isClock() const {return (*this)[0] == 0;}
unsigned generation() const;
slice digest() const;
uint64_t getGenAndDigest(slice &digest) const;
bool operator< (const revid&) const;
bool operator> (const revid &r) const {return r < *this;}
explicit operator std::string() const;
private:
slice skipFlag() const;
void _expandInto(slice &dst) const;
};
/** A self-contained revid that includes its own data buffer. */
class revidBuffer : public revid {
public:
revidBuffer() :revid(&_buffer, 0) {}
revidBuffer(revid rev) :revid(&_buffer, rev.size)
{memcpy(&_buffer, rev.buf, rev.size);}
explicit revidBuffer(slice s, bool allowClock =false)
:revid(&_buffer, 0)
{parse(s, allowClock);}
revidBuffer(unsigned generation, slice digest, revidType);
revidBuffer(const revidBuffer&);
revidBuffer& operator= (const revidBuffer&);
revidBuffer& operator= (const revid&);
/** Parses a regular (uncompressed) revID and compresses it.
Throws BadRevisionID if the revID isn't in the proper format.*/
void parse(slice, bool allowClock =false);
void parseNew(slice s);
bool tryParse(slice ascii, bool allowClock =false);
private:
uint8_t _buffer[42];
};
}
| 32.8 | 95 | 0.607245 | cedseat |
1fe04dedb05770bc65276832e1c58bef77e13ee6 | 21,489 | cpp | C++ | source/Lib/TLibEncoder/SEIEncoder.cpp | henryhuang329/h266 | ff05b4a10abe3e992a11e5481fa86bc671574a3b | [
"BSD-3-Clause"
] | 9 | 2019-10-30T06:29:33.000Z | 2021-11-19T08:34:08.000Z | source/Lib/TLibEncoder/SEIEncoder.cpp | hexiaoyi95/DL-HM-16.6-JEM-7.0-dev | 80206bf91a2be1c62589bee0af4ca4251d0a7e09 | [
"BSD-3-Clause"
] | null | null | null | source/Lib/TLibEncoder/SEIEncoder.cpp | hexiaoyi95/DL-HM-16.6-JEM-7.0-dev | 80206bf91a2be1c62589bee0af4ca4251d0a7e09 | [
"BSD-3-Clause"
] | 2 | 2019-03-29T15:14:34.000Z | 2019-04-27T10:46:40.000Z | /* The copyright in this software is being made available under the BSD
* License, included below. This software may be subject to other third party
* and contributor rights, including patent rights, and no such rights are
* granted under this license.
*
* Copyright (c) 2010-2015, ITU/ISO/IEC
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
* * Neither the name of the ITU/ISO/IEC nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "TLibCommon/CommonDef.h"
#include "TLibCommon/SEI.h"
#include "TEncGOP.h"
#include "TEncTop.h"
//! \ingroup TLibEncoder
//! \{
Void SEIEncoder::initSEIActiveParameterSets (SEIActiveParameterSets *seiActiveParameterSets, const TComVPS *vps, const TComSPS *sps)
{
assert (m_isInitialized);
assert (seiActiveParameterSets!=NULL);
assert (vps!=NULL);
assert (sps!=NULL);
seiActiveParameterSets->activeVPSId = vps->getVPSId();
seiActiveParameterSets->m_selfContainedCvsFlag = false;
seiActiveParameterSets->m_noParameterSetUpdateFlag = false;
seiActiveParameterSets->numSpsIdsMinus1 = 0;
seiActiveParameterSets->activeSeqParameterSetId.resize(seiActiveParameterSets->numSpsIdsMinus1 + 1);
seiActiveParameterSets->activeSeqParameterSetId[0] = sps->getSPSId();
}
Void SEIEncoder::initSEIFramePacking(SEIFramePacking *seiFramePacking, Int currPicNum)
{
assert (m_isInitialized);
assert (seiFramePacking!=NULL);
seiFramePacking->m_arrangementId = m_pcCfg->getFramePackingArrangementSEIId();
seiFramePacking->m_arrangementCancelFlag = 0;
seiFramePacking->m_arrangementType = m_pcCfg->getFramePackingArrangementSEIType();
assert((seiFramePacking->m_arrangementType > 2) && (seiFramePacking->m_arrangementType < 6) );
seiFramePacking->m_quincunxSamplingFlag = m_pcCfg->getFramePackingArrangementSEIQuincunx();
seiFramePacking->m_contentInterpretationType = m_pcCfg->getFramePackingArrangementSEIInterpretation();
seiFramePacking->m_spatialFlippingFlag = 0;
seiFramePacking->m_frame0FlippedFlag = 0;
seiFramePacking->m_fieldViewsFlag = (seiFramePacking->m_arrangementType == 2);
seiFramePacking->m_currentFrameIsFrame0Flag = ((seiFramePacking->m_arrangementType == 5) && (currPicNum&1) );
seiFramePacking->m_frame0SelfContainedFlag = 0;
seiFramePacking->m_frame1SelfContainedFlag = 0;
seiFramePacking->m_frame0GridPositionX = 0;
seiFramePacking->m_frame0GridPositionY = 0;
seiFramePacking->m_frame1GridPositionX = 0;
seiFramePacking->m_frame1GridPositionY = 0;
seiFramePacking->m_arrangementReservedByte = 0;
seiFramePacking->m_arrangementPersistenceFlag = true;
seiFramePacking->m_upsampledAspectRatio = 0;
}
Void SEIEncoder::initSEISegmentedRectFramePacking(SEISegmentedRectFramePacking *seiSegmentedRectFramePacking)
{
assert (m_isInitialized);
assert (seiSegmentedRectFramePacking!=NULL);
seiSegmentedRectFramePacking->m_arrangementCancelFlag = m_pcCfg->getSegmentedRectFramePackingArrangementSEICancel();
seiSegmentedRectFramePacking->m_contentInterpretationType = m_pcCfg->getSegmentedRectFramePackingArrangementSEIType();
seiSegmentedRectFramePacking->m_arrangementPersistenceFlag = m_pcCfg->getSegmentedRectFramePackingArrangementSEIPersistence();
}
Void SEIEncoder::initSEIDisplayOrientation(SEIDisplayOrientation* seiDisplayOrientation)
{
assert (m_isInitialized);
assert (seiDisplayOrientation!=NULL);
seiDisplayOrientation->cancelFlag = false;
seiDisplayOrientation->horFlip = false;
seiDisplayOrientation->verFlip = false;
seiDisplayOrientation->anticlockwiseRotation = m_pcCfg->getDisplayOrientationSEIAngle();
}
Void SEIEncoder::initSEIToneMappingInfo(SEIToneMappingInfo *seiToneMappingInfo)
{
assert (m_isInitialized);
assert (seiToneMappingInfo!=NULL);
seiToneMappingInfo->m_toneMapId = m_pcCfg->getTMISEIToneMapId();
seiToneMappingInfo->m_toneMapCancelFlag = m_pcCfg->getTMISEIToneMapCancelFlag();
seiToneMappingInfo->m_toneMapPersistenceFlag = m_pcCfg->getTMISEIToneMapPersistenceFlag();
seiToneMappingInfo->m_codedDataBitDepth = m_pcCfg->getTMISEICodedDataBitDepth();
assert(seiToneMappingInfo->m_codedDataBitDepth >= 8 && seiToneMappingInfo->m_codedDataBitDepth <= 14);
seiToneMappingInfo->m_targetBitDepth = m_pcCfg->getTMISEITargetBitDepth();
assert(seiToneMappingInfo->m_targetBitDepth >= 1 && seiToneMappingInfo->m_targetBitDepth <= 17);
seiToneMappingInfo->m_modelId = m_pcCfg->getTMISEIModelID();
assert(seiToneMappingInfo->m_modelId >=0 &&seiToneMappingInfo->m_modelId<=4);
switch( seiToneMappingInfo->m_modelId)
{
case 0:
{
seiToneMappingInfo->m_minValue = m_pcCfg->getTMISEIMinValue();
seiToneMappingInfo->m_maxValue = m_pcCfg->getTMISEIMaxValue();
break;
}
case 1:
{
seiToneMappingInfo->m_sigmoidMidpoint = m_pcCfg->getTMISEISigmoidMidpoint();
seiToneMappingInfo->m_sigmoidWidth = m_pcCfg->getTMISEISigmoidWidth();
break;
}
case 2:
{
UInt num = 1u<<(seiToneMappingInfo->m_targetBitDepth);
seiToneMappingInfo->m_startOfCodedInterval.resize(num);
Int* ptmp = m_pcCfg->getTMISEIStartOfCodedInterva();
if(ptmp)
{
for(Int i=0; i<num;i++)
{
seiToneMappingInfo->m_startOfCodedInterval[i] = ptmp[i];
}
}
break;
}
case 3:
{
seiToneMappingInfo->m_numPivots = m_pcCfg->getTMISEINumPivots();
seiToneMappingInfo->m_codedPivotValue.resize(seiToneMappingInfo->m_numPivots);
seiToneMappingInfo->m_targetPivotValue.resize(seiToneMappingInfo->m_numPivots);
Int* ptmpcoded = m_pcCfg->getTMISEICodedPivotValue();
Int* ptmptarget = m_pcCfg->getTMISEITargetPivotValue();
if(ptmpcoded&&ptmptarget)
{
for(Int i=0; i<(seiToneMappingInfo->m_numPivots);i++)
{
seiToneMappingInfo->m_codedPivotValue[i]=ptmpcoded[i];
seiToneMappingInfo->m_targetPivotValue[i]=ptmptarget[i];
}
}
break;
}
case 4:
{
seiToneMappingInfo->m_cameraIsoSpeedIdc = m_pcCfg->getTMISEICameraIsoSpeedIdc();
seiToneMappingInfo->m_cameraIsoSpeedValue = m_pcCfg->getTMISEICameraIsoSpeedValue();
assert( seiToneMappingInfo->m_cameraIsoSpeedValue !=0 );
seiToneMappingInfo->m_exposureIndexIdc = m_pcCfg->getTMISEIExposurIndexIdc();
seiToneMappingInfo->m_exposureIndexValue = m_pcCfg->getTMISEIExposurIndexValue();
assert( seiToneMappingInfo->m_exposureIndexValue !=0 );
seiToneMappingInfo->m_exposureCompensationValueSignFlag = m_pcCfg->getTMISEIExposureCompensationValueSignFlag();
seiToneMappingInfo->m_exposureCompensationValueNumerator = m_pcCfg->getTMISEIExposureCompensationValueNumerator();
seiToneMappingInfo->m_exposureCompensationValueDenomIdc = m_pcCfg->getTMISEIExposureCompensationValueDenomIdc();
seiToneMappingInfo->m_refScreenLuminanceWhite = m_pcCfg->getTMISEIRefScreenLuminanceWhite();
seiToneMappingInfo->m_extendedRangeWhiteLevel = m_pcCfg->getTMISEIExtendedRangeWhiteLevel();
assert( seiToneMappingInfo->m_extendedRangeWhiteLevel >= 100 );
seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue = m_pcCfg->getTMISEINominalBlackLevelLumaCodeValue();
seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue = m_pcCfg->getTMISEINominalWhiteLevelLumaCodeValue();
assert( seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue > seiToneMappingInfo->m_nominalBlackLevelLumaCodeValue );
seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue = m_pcCfg->getTMISEIExtendedWhiteLevelLumaCodeValue();
assert( seiToneMappingInfo->m_extendedWhiteLevelLumaCodeValue >= seiToneMappingInfo->m_nominalWhiteLevelLumaCodeValue );
break;
}
default:
{
assert(!"Undefined SEIToneMapModelId");
break;
}
}
}
Void SEIEncoder::initSEISOPDescription(SEISOPDescription *sopDescriptionSEI, TComSlice *slice, Int picInGOP, Int lastIdr, Int currGOPSize)
{
assert (m_isInitialized);
assert (sopDescriptionSEI != NULL);
assert (slice != NULL);
Int sopCurrPOC = slice->getPOC();
sopDescriptionSEI->m_sopSeqParameterSetId = slice->getSPS()->getSPSId();
Int i = 0;
Int prevEntryId = picInGOP;
for (Int j = picInGOP; j < currGOPSize; j++)
{
Int deltaPOC = m_pcCfg->getGOPEntry(j).m_POC - m_pcCfg->getGOPEntry(prevEntryId).m_POC;
if ((sopCurrPOC + deltaPOC) < m_pcCfg->getFramesToBeEncoded())
{
sopCurrPOC += deltaPOC;
sopDescriptionSEI->m_sopDescVclNaluType[i] = m_pcEncGOP->getNalUnitType(sopCurrPOC, lastIdr, slice->getPic()->isField());
sopDescriptionSEI->m_sopDescTemporalId[i] = m_pcCfg->getGOPEntry(j).m_temporalId;
sopDescriptionSEI->m_sopDescStRpsIdx[i] = m_pcEncTop->getReferencePictureSetIdxForSOP(sopCurrPOC, j);
sopDescriptionSEI->m_sopDescPocDelta[i] = deltaPOC;
prevEntryId = j;
i++;
}
}
sopDescriptionSEI->m_numPicsInSopMinus1 = i - 1;
}
Void SEIEncoder::initSEIBufferingPeriod(SEIBufferingPeriod *bufferingPeriodSEI, TComSlice *slice)
{
assert (m_isInitialized);
assert (bufferingPeriodSEI != NULL);
assert (slice != NULL);
UInt uiInitialCpbRemovalDelay = (90000/2); // 0.5 sec
bufferingPeriodSEI->m_initialCpbRemovalDelay [0][0] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_initialCpbRemovalDelayOffset[0][0] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_initialCpbRemovalDelay [0][1] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_initialCpbRemovalDelayOffset[0][1] = uiInitialCpbRemovalDelay;
Double dTmp = (Double)slice->getSPS()->getVuiParameters()->getTimingInfo()->getNumUnitsInTick() / (Double)slice->getSPS()->getVuiParameters()->getTimingInfo()->getTimeScale();
UInt uiTmp = (UInt)( dTmp * 90000.0 );
uiInitialCpbRemovalDelay -= uiTmp;
uiInitialCpbRemovalDelay -= uiTmp / ( slice->getSPS()->getVuiParameters()->getHrdParameters()->getTickDivisorMinus2() + 2 );
bufferingPeriodSEI->m_initialAltCpbRemovalDelay [0][0] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_initialAltCpbRemovalDelayOffset[0][0] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_initialAltCpbRemovalDelay [0][1] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_initialAltCpbRemovalDelayOffset[0][1] = uiInitialCpbRemovalDelay;
bufferingPeriodSEI->m_rapCpbParamsPresentFlag = 0;
//for the concatenation, it can be set to one during splicing.
bufferingPeriodSEI->m_concatenationFlag = 0;
//since the temporal layer HRD is not ready, we assumed it is fixed
bufferingPeriodSEI->m_auCpbRemovalDelayDelta = 1;
bufferingPeriodSEI->m_cpbDelayOffset = 0;
bufferingPeriodSEI->m_dpbDelayOffset = 0;
}
//! initialize scalable nesting SEI message.
//! Note: The SEI message structures input into this function will become part of the scalable nesting SEI and will be
//! automatically freed, when the nesting SEI is disposed.
Void SEIEncoder::initSEIScalableNesting(SEIScalableNesting *scalableNestingSEI, SEIMessages &nestedSEIs)
{
assert (m_isInitialized);
assert (scalableNestingSEI != NULL);
scalableNestingSEI->m_bitStreamSubsetFlag = 1; // If the nested SEI messages are picture buffering SEI messages, picture timing SEI messages or sub-picture timing SEI messages, bitstream_subset_flag shall be equal to 1
scalableNestingSEI->m_nestingOpFlag = 0;
scalableNestingSEI->m_nestingNumOpsMinus1 = 0; //nesting_num_ops_minus1
scalableNestingSEI->m_allLayersFlag = 0;
scalableNestingSEI->m_nestingNoOpMaxTemporalIdPlus1 = 6 + 1; //nesting_no_op_max_temporal_id_plus1
scalableNestingSEI->m_nestingNumLayersMinus1 = 1 - 1; //nesting_num_layers_minus1
scalableNestingSEI->m_nestingLayerId[0] = 0;
scalableNestingSEI->m_nestedSEIs.clear();
for (SEIMessages::iterator it=nestedSEIs.begin(); it!=nestedSEIs.end(); it++)
{
scalableNestingSEI->m_nestedSEIs.push_back((*it));
}
}
Void SEIEncoder::initSEIRecoveryPoint(SEIRecoveryPoint *recoveryPointSEI, TComSlice *slice)
{
assert (m_isInitialized);
assert (recoveryPointSEI != NULL);
assert (slice != NULL);
recoveryPointSEI->m_recoveryPocCnt = 0;
recoveryPointSEI->m_exactMatchingFlag = ( slice->getPOC() == 0 ) ? (true) : (false);
recoveryPointSEI->m_brokenLinkFlag = false;
}
//! calculate hashes for entire reconstructed picture
Void SEIEncoder::initDecodedPictureHashSEI(SEIDecodedPictureHash *decodedPictureHashSEI, TComPic *pcPic, std::string &rHashString, const BitDepths &bitDepths)
{
assert (m_isInitialized);
assert (decodedPictureHashSEI!=NULL);
assert (pcPic!=NULL);
if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 1)
{
decodedPictureHashSEI->method = SEIDecodedPictureHash::MD5;
UInt numChar=calcMD5(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
}
else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 2)
{
decodedPictureHashSEI->method = SEIDecodedPictureHash::CRC;
UInt numChar=calcCRC(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
}
else if(m_pcCfg->getDecodedPictureHashSEIEnabled() == 3)
{
decodedPictureHashSEI->method = SEIDecodedPictureHash::CHECKSUM;
UInt numChar=calcChecksum(*pcPic->getPicYuvRec(), decodedPictureHashSEI->m_pictureHash, bitDepths);
rHashString = hashToString(decodedPictureHashSEI->m_pictureHash, numChar);
}
}
Void SEIEncoder::initTemporalLevel0IndexSEI(SEITemporalLevel0Index *temporalLevel0IndexSEI, TComSlice *slice)
{
assert (m_isInitialized);
assert (temporalLevel0IndexSEI!=NULL);
assert (slice!=NULL);
if (slice->getRapPicFlag())
{
m_tl0Idx = 0;
m_rapIdx = (m_rapIdx + 1) & 0xFF;
}
else
{
m_tl0Idx = (m_tl0Idx + (slice->getTLayer() ? 0 : 1)) & 0xFF;
}
temporalLevel0IndexSEI->tl0Idx = m_tl0Idx;
temporalLevel0IndexSEI->rapIdx = m_rapIdx;
}
Void SEIEncoder::initSEITempMotionConstrainedTileSets (SEITempMotionConstrainedTileSets *sei, const TComPPS *pps)
{
assert (m_isInitialized);
assert (sei!=NULL);
assert (pps!=NULL);
if(pps->getTilesEnabledFlag())
{
sei->m_mc_all_tiles_exact_sample_value_match_flag = false;
sei->m_each_tile_one_tile_set_flag = false;
sei->m_limited_tile_set_display_flag = false;
sei->setNumberOfTileSets((pps->getNumTileColumnsMinus1() + 1) * (pps->getNumTileRowsMinus1() + 1));
for(Int i=0; i < sei->getNumberOfTileSets(); i++)
{
sei->tileSetData(i).m_mcts_id = i; //depends the application;
sei->tileSetData(i).setNumberOfTileRects(1);
for(Int j=0; j<sei->tileSetData(i).getNumberOfTileRects(); j++)
{
sei->tileSetData(i).topLeftTileIndex(j) = i+j;
sei->tileSetData(i).bottomRightTileIndex(j) = i+j;
}
sei->tileSetData(i).m_exact_sample_value_match_flag = false;
sei->tileSetData(i).m_mcts_tier_level_idc_present_flag = false;
}
}
else
{
assert(!"Tile is not enabled");
}
}
Void SEIEncoder::initSEIKneeFunctionInfo(SEIKneeFunctionInfo *seiKneeFunctionInfo)
{
assert (m_isInitialized);
assert (seiKneeFunctionInfo!=NULL);
seiKneeFunctionInfo->m_kneeId = m_pcCfg->getKneeSEIId();
seiKneeFunctionInfo->m_kneeCancelFlag = m_pcCfg->getKneeSEICancelFlag();
if ( !seiKneeFunctionInfo->m_kneeCancelFlag )
{
seiKneeFunctionInfo->m_kneePersistenceFlag = m_pcCfg->getKneeSEIPersistenceFlag();
seiKneeFunctionInfo->m_kneeInputDrange = m_pcCfg->getKneeSEIInputDrange();
seiKneeFunctionInfo->m_kneeInputDispLuminance = m_pcCfg->getKneeSEIInputDispLuminance();
seiKneeFunctionInfo->m_kneeOutputDrange = m_pcCfg->getKneeSEIOutputDrange();
seiKneeFunctionInfo->m_kneeOutputDispLuminance = m_pcCfg->getKneeSEIOutputDispLuminance();
seiKneeFunctionInfo->m_kneeNumKneePointsMinus1 = m_pcCfg->getKneeSEINumKneePointsMinus1();
Int* piInputKneePoint = m_pcCfg->getKneeSEIInputKneePoint();
Int* piOutputKneePoint = m_pcCfg->getKneeSEIOutputKneePoint();
if(piInputKneePoint&&piOutputKneePoint)
{
seiKneeFunctionInfo->m_kneeInputKneePoint.resize(seiKneeFunctionInfo->m_kneeNumKneePointsMinus1+1);
seiKneeFunctionInfo->m_kneeOutputKneePoint.resize(seiKneeFunctionInfo->m_kneeNumKneePointsMinus1+1);
for(Int i=0; i<=seiKneeFunctionInfo->m_kneeNumKneePointsMinus1; i++)
{
seiKneeFunctionInfo->m_kneeInputKneePoint[i] = piInputKneePoint[i];
seiKneeFunctionInfo->m_kneeOutputKneePoint[i] = piOutputKneePoint[i];
}
}
}
}
Void SEIEncoder::initSEIChromaSamplingFilterHint(SEIChromaSamplingFilterHint *seiChromaSamplingFilterHint, Int iHorFilterIndex, Int iVerFilterIndex)
{
assert (m_isInitialized);
assert (seiChromaSamplingFilterHint!=NULL);
seiChromaSamplingFilterHint->m_verChromaFilterIdc = iVerFilterIndex;
seiChromaSamplingFilterHint->m_horChromaFilterIdc = iHorFilterIndex;
seiChromaSamplingFilterHint->m_verFilteringProcessFlag = 1;
seiChromaSamplingFilterHint->m_targetFormatIdc = 3;
seiChromaSamplingFilterHint->m_perfectReconstructionFlag = false;
if(seiChromaSamplingFilterHint->m_verChromaFilterIdc == 1)
{
seiChromaSamplingFilterHint->m_numVerticalFilters = 1;
seiChromaSamplingFilterHint->m_verTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int));
seiChromaSamplingFilterHint->m_verFilterCoeff = (Int**)malloc(seiChromaSamplingFilterHint->m_numVerticalFilters * sizeof(Int*));
for(Int i = 0; i < seiChromaSamplingFilterHint->m_numVerticalFilters; i ++)
{
seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] = 0;
seiChromaSamplingFilterHint->m_verFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_verTapLengthMinus1[i] * sizeof(Int));
for(Int j = 0; j < seiChromaSamplingFilterHint->m_verTapLengthMinus1[i]; j ++)
{
seiChromaSamplingFilterHint->m_verFilterCoeff[i][j] = 0;
}
}
}
else
{
seiChromaSamplingFilterHint->m_numVerticalFilters = 0;
seiChromaSamplingFilterHint->m_verTapLengthMinus1 = NULL;
seiChromaSamplingFilterHint->m_verFilterCoeff = NULL;
}
if(seiChromaSamplingFilterHint->m_horChromaFilterIdc == 1)
{
seiChromaSamplingFilterHint->m_numHorizontalFilters = 1;
seiChromaSamplingFilterHint->m_horTapLengthMinus1 = (Int*)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int));
seiChromaSamplingFilterHint->m_horFilterCoeff = (Int**)malloc(seiChromaSamplingFilterHint->m_numHorizontalFilters * sizeof(Int*));
for(Int i = 0; i < seiChromaSamplingFilterHint->m_numHorizontalFilters; i ++)
{
seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] = 0;
seiChromaSamplingFilterHint->m_horFilterCoeff[i] = (Int*)malloc(seiChromaSamplingFilterHint->m_horTapLengthMinus1[i] * sizeof(Int));
for(Int j = 0; j < seiChromaSamplingFilterHint->m_horTapLengthMinus1[i]; j ++)
{
seiChromaSamplingFilterHint->m_horFilterCoeff[i][j] = 0;
}
}
}
else
{
seiChromaSamplingFilterHint->m_numHorizontalFilters = 0;
seiChromaSamplingFilterHint->m_horTapLengthMinus1 = NULL;
seiChromaSamplingFilterHint->m_horFilterCoeff = NULL;
}
}
Void SEIEncoder::initSEITimeCode(SEITimeCode *seiTimeCode)
{
assert (m_isInitialized);
assert (seiTimeCode!=NULL);
// Set data as per command line options
seiTimeCode->numClockTs = m_pcCfg->getNumberOfTimesets();
for(Int i = 0; i < seiTimeCode->numClockTs; i++)
{
seiTimeCode->timeSetArray[i] = m_pcCfg->getTimeSet(i);
}
}
//! \}
| 46.014989 | 236 | 0.742799 | henryhuang329 |
1fe196daf49ff9a792ec33c15fcb291198ba2599 | 1,785 | cpp | C++ | Antiplagiat/Antiplagiat/bin/Debug/10806.cpp | DmitryTheFirst/AntiplagiatVkCup | 556d3fe2e5a630d06a7aa49f2af5dcb28667275a | [
"Apache-2.0"
] | 1 | 2015-07-04T14:45:32.000Z | 2015-07-04T14:45:32.000Z | Antiplagiat/Antiplagiat/bin/Debug/10806.cpp | DmitryTheFirst/AntiplagiatVkCup | 556d3fe2e5a630d06a7aa49f2af5dcb28667275a | [
"Apache-2.0"
] | null | null | null | Antiplagiat/Antiplagiat/bin/Debug/10806.cpp | DmitryTheFirst/AntiplagiatVkCup | 556d3fe2e5a630d06a7aa49f2af5dcb28667275a | [
"Apache-2.0"
] | null | null | null | #include <iostream>
#include <cstring>
#include <vector>
#include <set>
#include <map>
#include <algorithm>
#include <iomanip>
#include <cstdio>
#include <ctime>
#include <functional>
#include <iterator>
#include <complex>
#include <queue>
#include <cassert>
#include <sstream>
#include <cstdlib>
using namespace std;
typedef long long LL;
typedef long double LD;
const int MAX_N = 5010;
int n;
vector<int> g [MAX_N];
int mark [MAX_N], can [MAX_N];
vector< pair<int, int> > ans;
int dfs(int u, int p) {
int sz = 1;
for (int i = 0; i < g[u].size(); i++) {
int v = g[u][i];
if (v == p)
continue;
sz += dfs(v, u);
}
return sz;
}
int main() {
scanf("%d", &n);
for(int i = 0; i < n - 1; i++) {
int u, v;
scanf("%d%d", &u, &v);
u--, v--;
g[u].push_back(v);
g[v].push_back(u);
}
memset(can, -1, sizeof(can));
for (int u = 0; u < n; u++) {
vector<int> sz;
for (int i = 0; i < g[u].size(); i++)
sz.push_back(dfs(g[u][i], u));
#ifdef DEBUG
cerr << "sizes\n";
for (int i = 0; i < sz.size(); i++)
cerr << sz[i] << ' ';
cerr << '\n';
#endif
can[0] = u;
for (int i = 0; i < sz.size(); i++)
for (int j = n - 1; j - sz[i] >= 0; j--)
if (can[j - sz[i]] == u)
can[j] = u;
for (int j = 1; j < n - 1; j++)
if (can[j] == u)
mark[j] = 1;
}
for (int i = 1; i < n - 1; i++)
if (mark[i])
ans.push_back(make_pair(i, n - 1 - i));
cout << ans.size() << '\n';
for (int i = 0; i < ans.size(); i++)
cout << ans[i].first << ' ' << ans[i].second << '\n';
return 0;
}
| 20.517241 | 61 | 0.442017 | DmitryTheFirst |
1fe2bb489e8d44f5d70bbf26d34f9a9dfb270ddb | 17,794 | hpp | C++ | include/System/TermInfoDriver.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/TermInfoDriver.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | include/System/TermInfoDriver.hpp | darknight1050/BeatSaber-Quest-Codegen | a6eeecc3f0e8f6079630f9a9a72b3121ac7b2032 | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
// Including type: System.IConsoleDriver
#include "System/IConsoleDriver.hpp"
// Including type: System.ConsoleColor
#include "System/ConsoleColor.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: System
namespace System {
// Forward declaring type: TermInfoReader
class TermInfoReader;
// Forward declaring type: ByteMatcher
class ByteMatcher;
// Forward declaring type: ConsoleKeyInfo
struct ConsoleKeyInfo;
// Forward declaring type: TermInfoStrings
struct TermInfoStrings;
}
// Forward declaring namespace: System::IO
namespace System::IO {
// Forward declaring type: StreamReader
class StreamReader;
// Forward declaring type: CStreamWriter
class CStreamWriter;
}
// Forward declaring namespace: System::Collections
namespace System::Collections {
// Forward declaring type: Hashtable
class Hashtable;
}
// Completed forward declares
// Type namespace: System
namespace System {
// Size: 0x11C
#pragma pack(push, 1)
// Autogenerated type: System.TermInfoDriver
class TermInfoDriver : public ::Il2CppObject/*, public System::IConsoleDriver*/ {
public:
// private System.TermInfoReader reader
// Size: 0x8
// Offset: 0x10
System::TermInfoReader* reader;
// Field size check
static_assert(sizeof(System::TermInfoReader*) == 0x8);
// private System.Int32 cursorLeft
// Size: 0x4
// Offset: 0x18
int cursorLeft;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 cursorTop
// Size: 0x4
// Offset: 0x1C
int cursorTop;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.String title
// Size: 0x8
// Offset: 0x20
::Il2CppString* title;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String titleFormat
// Size: 0x8
// Offset: 0x28
::Il2CppString* titleFormat;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.Boolean cursorVisible
// Size: 0x1
// Offset: 0x30
bool cursorVisible;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: cursorVisible and: csrVisible
char __padding5[0x7] = {};
// private System.String csrVisible
// Size: 0x8
// Offset: 0x38
::Il2CppString* csrVisible;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String csrInvisible
// Size: 0x8
// Offset: 0x40
::Il2CppString* csrInvisible;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String clear
// Size: 0x8
// Offset: 0x48
::Il2CppString* clear;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String bell
// Size: 0x8
// Offset: 0x50
::Il2CppString* bell;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String term
// Size: 0x8
// Offset: 0x58
::Il2CppString* term;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.IO.StreamReader stdin
// Size: 0x8
// Offset: 0x60
System::IO::StreamReader* stdin;
// Field size check
static_assert(sizeof(System::IO::StreamReader*) == 0x8);
// private System.IO.CStreamWriter stdout
// Size: 0x8
// Offset: 0x68
System::IO::CStreamWriter* stdout;
// Field size check
static_assert(sizeof(System::IO::CStreamWriter*) == 0x8);
// private System.Int32 windowWidth
// Size: 0x4
// Offset: 0x70
int windowWidth;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 windowHeight
// Size: 0x4
// Offset: 0x74
int windowHeight;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 bufferHeight
// Size: 0x4
// Offset: 0x78
int bufferHeight;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 bufferWidth
// Size: 0x4
// Offset: 0x7C
int bufferWidth;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Char[] buffer
// Size: 0x8
// Offset: 0x80
::Array<::Il2CppChar>* buffer;
// Field size check
static_assert(sizeof(::Array<::Il2CppChar>*) == 0x8);
// private System.Int32 readpos
// Size: 0x4
// Offset: 0x88
int readpos;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 writepos
// Size: 0x4
// Offset: 0x8C
int writepos;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.String keypadXmit
// Size: 0x8
// Offset: 0x90
::Il2CppString* keypadXmit;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String keypadLocal
// Size: 0x8
// Offset: 0x98
::Il2CppString* keypadLocal;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.Boolean inited
// Size: 0x1
// Offset: 0xA0
bool inited;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: inited and: initLock
char __padding22[0x7] = {};
// private System.Object initLock
// Size: 0x8
// Offset: 0xA8
::Il2CppObject* initLock;
// Field size check
static_assert(sizeof(::Il2CppObject*) == 0x8);
// private System.Boolean initKeys
// Size: 0x1
// Offset: 0xB0
bool initKeys;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: initKeys and: origPair
char __padding24[0x7] = {};
// private System.String origPair
// Size: 0x8
// Offset: 0xB8
::Il2CppString* origPair;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String origColors
// Size: 0x8
// Offset: 0xC0
::Il2CppString* origColors;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String cursorAddress
// Size: 0x8
// Offset: 0xC8
::Il2CppString* cursorAddress;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.ConsoleColor fgcolor
// Size: 0x4
// Offset: 0xD0
System::ConsoleColor fgcolor;
// Field size check
static_assert(sizeof(System::ConsoleColor) == 0x4);
// Padding between fields: fgcolor and: setfgcolor
char __padding28[0x4] = {};
// private System.String setfgcolor
// Size: 0x8
// Offset: 0xD8
::Il2CppString* setfgcolor;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.String setbgcolor
// Size: 0x8
// Offset: 0xE0
::Il2CppString* setbgcolor;
// Field size check
static_assert(sizeof(::Il2CppString*) == 0x8);
// private System.Int32 maxColors
// Size: 0x4
// Offset: 0xE8
int maxColors;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Boolean noGetPosition
// Size: 0x1
// Offset: 0xEC
bool noGetPosition;
// Field size check
static_assert(sizeof(bool) == 0x1);
// Padding between fields: noGetPosition and: keymap
char __padding32[0x3] = {};
// private System.Collections.Hashtable keymap
// Size: 0x8
// Offset: 0xF0
System::Collections::Hashtable* keymap;
// Field size check
static_assert(sizeof(System::Collections::Hashtable*) == 0x8);
// private System.ByteMatcher rootmap
// Size: 0x8
// Offset: 0xF8
System::ByteMatcher* rootmap;
// Field size check
static_assert(sizeof(System::ByteMatcher*) == 0x8);
// private System.Int32 rl_startx
// Size: 0x4
// Offset: 0x100
int rl_startx;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Int32 rl_starty
// Size: 0x4
// Offset: 0x104
int rl_starty;
// Field size check
static_assert(sizeof(int) == 0x4);
// private System.Byte[] control_characters
// Size: 0x8
// Offset: 0x108
::Array<uint8_t>* control_characters;
// Field size check
static_assert(sizeof(::Array<uint8_t>*) == 0x8);
// private System.Char[] echobuf
// Size: 0x8
// Offset: 0x110
::Array<::Il2CppChar>* echobuf;
// Field size check
static_assert(sizeof(::Array<::Il2CppChar>*) == 0x8);
// private System.Int32 echon
// Size: 0x4
// Offset: 0x118
int echon;
// Field size check
static_assert(sizeof(int) == 0x4);
// Creating value type constructor for type: TermInfoDriver
TermInfoDriver(System::TermInfoReader* reader_ = {}, int cursorLeft_ = {}, int cursorTop_ = {}, ::Il2CppString* title_ = {}, ::Il2CppString* titleFormat_ = {}, bool cursorVisible_ = {}, ::Il2CppString* csrVisible_ = {}, ::Il2CppString* csrInvisible_ = {}, ::Il2CppString* clear_ = {}, ::Il2CppString* bell_ = {}, ::Il2CppString* term_ = {}, System::IO::StreamReader* stdin_ = {}, System::IO::CStreamWriter* stdout_ = {}, int windowWidth_ = {}, int windowHeight_ = {}, int bufferHeight_ = {}, int bufferWidth_ = {}, ::Array<::Il2CppChar>* buffer_ = {}, int readpos_ = {}, int writepos_ = {}, ::Il2CppString* keypadXmit_ = {}, ::Il2CppString* keypadLocal_ = {}, bool inited_ = {}, ::Il2CppObject* initLock_ = {}, bool initKeys_ = {}, ::Il2CppString* origPair_ = {}, ::Il2CppString* origColors_ = {}, ::Il2CppString* cursorAddress_ = {}, System::ConsoleColor fgcolor_ = {}, ::Il2CppString* setfgcolor_ = {}, ::Il2CppString* setbgcolor_ = {}, int maxColors_ = {}, bool noGetPosition_ = {}, System::Collections::Hashtable* keymap_ = {}, System::ByteMatcher* rootmap_ = {}, int rl_startx_ = {}, int rl_starty_ = {}, ::Array<uint8_t>* control_characters_ = {}, ::Array<::Il2CppChar>* echobuf_ = {}, int echon_ = {}) noexcept : reader{reader_}, cursorLeft{cursorLeft_}, cursorTop{cursorTop_}, title{title_}, titleFormat{titleFormat_}, cursorVisible{cursorVisible_}, csrVisible{csrVisible_}, csrInvisible{csrInvisible_}, clear{clear_}, bell{bell_}, term{term_}, stdin{stdin_}, stdout{stdout_}, windowWidth{windowWidth_}, windowHeight{windowHeight_}, bufferHeight{bufferHeight_}, bufferWidth{bufferWidth_}, buffer{buffer_}, readpos{readpos_}, writepos{writepos_}, keypadXmit{keypadXmit_}, keypadLocal{keypadLocal_}, inited{inited_}, initLock{initLock_}, initKeys{initKeys_}, origPair{origPair_}, origColors{origColors_}, cursorAddress{cursorAddress_}, fgcolor{fgcolor_}, setfgcolor{setfgcolor_}, setbgcolor{setbgcolor_}, maxColors{maxColors_}, noGetPosition{noGetPosition_}, keymap{keymap_}, rootmap{rootmap_}, rl_startx{rl_startx_}, rl_starty{rl_starty_}, control_characters{control_characters_}, echobuf{echobuf_}, echon{echon_} {}
// Creating interface conversion operator: operator System::IConsoleDriver
operator System::IConsoleDriver() noexcept {
return *reinterpret_cast<System::IConsoleDriver*>(this);
}
// Get static field: static private System.Int32* native_terminal_size
static int* _get_native_terminal_size();
// Set static field: static private System.Int32* native_terminal_size
static void _set_native_terminal_size(int* value);
// Get static field: static private System.Int32 terminal_size
static int _get_terminal_size();
// Set static field: static private System.Int32 terminal_size
static void _set_terminal_size(int value);
// Get static field: static private readonly System.String[] locations
static ::Array<::Il2CppString*>* _get_locations();
// Set static field: static private readonly System.String[] locations
static void _set_locations(::Array<::Il2CppString*>* value);
// Get static field: static private readonly System.Int32[] _consoleColorToAnsiCode
static ::Array<int>* _get__consoleColorToAnsiCode();
// Set static field: static private readonly System.Int32[] _consoleColorToAnsiCode
static void _set__consoleColorToAnsiCode(::Array<int>* value);
// static private System.String TryTermInfoDir(System.String dir, System.String term)
// Offset: 0x1B3E710
static ::Il2CppString* TryTermInfoDir(::Il2CppString* dir, ::Il2CppString* term);
// static private System.String SearchTerminfo(System.String term)
// Offset: 0x1B3E854
static ::Il2CppString* SearchTerminfo(::Il2CppString* term);
// private System.Void WriteConsole(System.String str)
// Offset: 0x1B3E9D0
void WriteConsole(::Il2CppString* str);
// public System.Void .ctor(System.String term)
// Offset: 0x1B3E9F4
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TermInfoDriver* New_ctor(::Il2CppString* term) {
static auto ___internal__logger = ::Logger::get().WithContext("System::TermInfoDriver::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TermInfoDriver*, creationType>(term)));
}
// public System.Boolean get_Initialized()
// Offset: 0x1B3F038
bool get_Initialized();
// public System.Void Init()
// Offset: 0x1B3F040
void Init();
// private System.Void IncrementX()
// Offset: 0x1B3FA80
void IncrementX();
// public System.Void WriteSpecialKey(System.ConsoleKeyInfo key)
// Offset: 0x1B3FB60
void WriteSpecialKey(System::ConsoleKeyInfo key);
// public System.Void WriteSpecialKey(System.Char c)
// Offset: 0x1B3FE38
void WriteSpecialKey(::Il2CppChar c);
// public System.Boolean IsSpecialKey(System.ConsoleKeyInfo key)
// Offset: 0x1B3FFF0
bool IsSpecialKey(System::ConsoleKeyInfo key);
// public System.Boolean IsSpecialKey(System.Char c)
// Offset: 0x1B40078
bool IsSpecialKey(::Il2CppChar c);
// private System.Void GetCursorPosition()
// Offset: 0x1B3F7D0
void GetCursorPosition();
// private System.Void CheckWindowDimensions()
// Offset: 0x1B401BC
void CheckWindowDimensions();
// public System.Int32 get_WindowHeight()
// Offset: 0x1B3FB28
int get_WindowHeight();
// public System.Int32 get_WindowWidth()
// Offset: 0x1B3FAF0
int get_WindowWidth();
// private System.Void AddToBuffer(System.Int32 b)
// Offset: 0x1B400AC
void AddToBuffer(int b);
// private System.Void AdjustBuffer()
// Offset: 0x1B4031C
void AdjustBuffer();
// private System.ConsoleKeyInfo CreateKeyInfoFromInt(System.Int32 n, System.Boolean alt)
// Offset: 0x1B3FE6C
System::ConsoleKeyInfo CreateKeyInfoFromInt(int n, bool alt);
// private System.Object GetKeyFromBuffer(System.Boolean cooked)
// Offset: 0x1B40330
::Il2CppObject* GetKeyFromBuffer(bool cooked);
// private System.ConsoleKeyInfo ReadKeyInternal(out System.Boolean fresh)
// Offset: 0x1B4061C
System::ConsoleKeyInfo ReadKeyInternal(bool& fresh);
// private System.Boolean InputPending()
// Offset: 0x1B40954
bool InputPending();
// private System.Void QueueEcho(System.Char c)
// Offset: 0x1B40984
void QueueEcho(::Il2CppChar c);
// private System.Void Echo(System.ConsoleKeyInfo key)
// Offset: 0x1B40A7C
void Echo(System::ConsoleKeyInfo key);
// private System.Void EchoFlush()
// Offset: 0x1B40AE0
void EchoFlush();
// public System.Int32 Read(in System.Char[] dest, System.Int32 index, System.Int32 count)
// Offset: 0x1B40B20
int Read(::Array<::Il2CppChar>*& dest, int index, int count);
// public System.ConsoleKeyInfo ReadKey(System.Boolean intercept)
// Offset: 0x1B40E44
System::ConsoleKeyInfo ReadKey(bool intercept);
// public System.String ReadLine()
// Offset: 0x1B40EAC
::Il2CppString* ReadLine();
// public System.String ReadToEnd()
// Offset: 0x1B4109C
::Il2CppString* ReadToEnd();
// private System.String ReadUntilConditionInternal(System.Boolean haltOnNewLine)
// Offset: 0x1B40EB4
::Il2CppString* ReadUntilConditionInternal(bool haltOnNewLine);
// public System.Void SetCursorPosition(System.Int32 left, System.Int32 top)
// Offset: 0x1B3FC88
void SetCursorPosition(int left, int top);
// private System.Void CreateKeyMap()
// Offset: 0x1B410A4
void CreateKeyMap();
// private System.Void InitKeys()
// Offset: 0x1B407F0
void InitKeys();
// private System.Void AddStringMapping(System.TermInfoStrings s)
// Offset: 0x1B42F2C
void AddStringMapping(System::TermInfoStrings s);
// static private System.Void .cctor()
// Offset: 0x1B43018
static void _cctor();
}; // System.TermInfoDriver
#pragma pack(pop)
static check_size<sizeof(TermInfoDriver), 280 + sizeof(int)> __System_TermInfoDriverSizeCheck;
static_assert(sizeof(TermInfoDriver) == 0x11C);
}
DEFINE_IL2CPP_ARG_TYPE(System::TermInfoDriver*, "System", "TermInfoDriver");
| 41.189815 | 2,128 | 0.664943 | darknight1050 |
1fe3576d02d756694334f39319acc9930986a1f8 | 32,597 | cpp | C++ | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_filesystems_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 17 | 2016-12-02T05:45:49.000Z | 2022-02-10T19:32:54.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_filesystems_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 2 | 2017-03-27T15:22:38.000Z | 2019-11-05T08:30:16.000Z | cisco-ios-xr/ydk/models/cisco_ios_xr/Cisco_IOS_XR_ipv4_filesystems_cfg.cpp | CiscoDevNet/ydk-cpp | ef7d75970f2ef1154100e0f7b0a2ee823609b481 | [
"ECL-2.0",
"Apache-2.0"
] | 11 | 2016-12-02T05:45:52.000Z | 2019-11-07T08:28:17.000Z |
#include <sstream>
#include <iostream>
#include <ydk/entity_util.hpp>
#include "bundle_info.hpp"
#include "generated_entity_lookup.hpp"
#include "Cisco_IOS_XR_ipv4_filesystems_cfg.hpp"
using namespace ydk;
namespace cisco_ios_xr {
namespace Cisco_IOS_XR_ipv4_filesystems_cfg {
Rcp::Rcp()
:
rcp_client(std::make_shared<Rcp::RcpClient>())
{
rcp_client->parent = this;
yang_name = "rcp"; yang_parent_name = "Cisco-IOS-XR-ipv4-filesystems-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
Rcp::~Rcp()
{
}
bool Rcp::has_data() const
{
if (is_presence_container) return true;
return (rcp_client != nullptr && rcp_client->has_data());
}
bool Rcp::has_operation() const
{
return is_set(yfilter)
|| (rcp_client != nullptr && rcp_client->has_operation());
}
std::string Rcp::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:rcp";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Rcp::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Rcp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "rcp-client")
{
if(rcp_client == nullptr)
{
rcp_client = std::make_shared<Rcp::RcpClient>();
}
return rcp_client;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Rcp::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(rcp_client != nullptr)
{
_children["rcp-client"] = rcp_client;
}
return _children;
}
void Rcp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Rcp::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Rcp::clone_ptr() const
{
return std::make_shared<Rcp>();
}
std::string Rcp::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Rcp::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Rcp::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Rcp::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Rcp::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "rcp-client")
return true;
return false;
}
Rcp::RcpClient::RcpClient()
:
username{YType::str, "username"},
source_interface{YType::str, "source-interface"}
{
yang_name = "rcp-client"; yang_parent_name = "rcp"; is_top_level_class = false; has_list_ancestor = false;
}
Rcp::RcpClient::~RcpClient()
{
}
bool Rcp::RcpClient::has_data() const
{
if (is_presence_container) return true;
return username.is_set
|| source_interface.is_set;
}
bool Rcp::RcpClient::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(username.yfilter)
|| ydk::is_set(source_interface.yfilter);
}
std::string Rcp::RcpClient::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:rcp/" << get_segment_path();
return path_buffer.str();
}
std::string Rcp::RcpClient::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "rcp-client";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Rcp::RcpClient::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (username.is_set || is_set(username.yfilter)) leaf_name_data.push_back(username.get_name_leafdata());
if (source_interface.is_set || is_set(source_interface.yfilter)) leaf_name_data.push_back(source_interface.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Rcp::RcpClient::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Rcp::RcpClient::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Rcp::RcpClient::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "username")
{
username = value;
username.value_namespace = name_space;
username.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source-interface")
{
source_interface = value;
source_interface.value_namespace = name_space;
source_interface.value_namespace_prefix = name_space_prefix;
}
}
void Rcp::RcpClient::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "username")
{
username.yfilter = yfilter;
}
if(value_path == "source-interface")
{
source_interface.yfilter = yfilter;
}
}
bool Rcp::RcpClient::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "username" || name == "source-interface")
return true;
return false;
}
Ftp::Ftp()
:
ftp_client(std::make_shared<Ftp::FtpClient>())
{
ftp_client->parent = this;
yang_name = "ftp"; yang_parent_name = "Cisco-IOS-XR-ipv4-filesystems-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
Ftp::~Ftp()
{
}
bool Ftp::has_data() const
{
if (is_presence_container) return true;
return (ftp_client != nullptr && ftp_client->has_data());
}
bool Ftp::has_operation() const
{
return is_set(yfilter)
|| (ftp_client != nullptr && ftp_client->has_operation());
}
std::string Ftp::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:ftp";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Ftp::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Ftp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "ftp-client")
{
if(ftp_client == nullptr)
{
ftp_client = std::make_shared<Ftp::FtpClient>();
}
return ftp_client;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Ftp::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(ftp_client != nullptr)
{
_children["ftp-client"] = ftp_client;
}
return _children;
}
void Ftp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Ftp::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Ftp::clone_ptr() const
{
return std::make_shared<Ftp>();
}
std::string Ftp::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Ftp::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Ftp::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Ftp::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Ftp::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "ftp-client")
return true;
return false;
}
Ftp::FtpClient::FtpClient()
:
passive{YType::empty, "passive"},
password{YType::str, "password"},
anonymous_password{YType::str, "anonymous-password"},
username{YType::str, "username"},
source_interface{YType::str, "source-interface"}
,
vrfs(std::make_shared<Ftp::FtpClient::Vrfs>())
{
vrfs->parent = this;
yang_name = "ftp-client"; yang_parent_name = "ftp"; is_top_level_class = false; has_list_ancestor = false;
}
Ftp::FtpClient::~FtpClient()
{
}
bool Ftp::FtpClient::has_data() const
{
if (is_presence_container) return true;
return passive.is_set
|| password.is_set
|| anonymous_password.is_set
|| username.is_set
|| source_interface.is_set
|| (vrfs != nullptr && vrfs->has_data());
}
bool Ftp::FtpClient::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(passive.yfilter)
|| ydk::is_set(password.yfilter)
|| ydk::is_set(anonymous_password.yfilter)
|| ydk::is_set(username.yfilter)
|| ydk::is_set(source_interface.yfilter)
|| (vrfs != nullptr && vrfs->has_operation());
}
std::string Ftp::FtpClient::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:ftp/" << get_segment_path();
return path_buffer.str();
}
std::string Ftp::FtpClient::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "ftp-client";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Ftp::FtpClient::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (passive.is_set || is_set(passive.yfilter)) leaf_name_data.push_back(passive.get_name_leafdata());
if (password.is_set || is_set(password.yfilter)) leaf_name_data.push_back(password.get_name_leafdata());
if (anonymous_password.is_set || is_set(anonymous_password.yfilter)) leaf_name_data.push_back(anonymous_password.get_name_leafdata());
if (username.is_set || is_set(username.yfilter)) leaf_name_data.push_back(username.get_name_leafdata());
if (source_interface.is_set || is_set(source_interface.yfilter)) leaf_name_data.push_back(source_interface.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Ftp::FtpClient::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "vrfs")
{
if(vrfs == nullptr)
{
vrfs = std::make_shared<Ftp::FtpClient::Vrfs>();
}
return vrfs;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Ftp::FtpClient::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(vrfs != nullptr)
{
_children["vrfs"] = vrfs;
}
return _children;
}
void Ftp::FtpClient::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "passive")
{
passive = value;
passive.value_namespace = name_space;
passive.value_namespace_prefix = name_space_prefix;
}
if(value_path == "password")
{
password = value;
password.value_namespace = name_space;
password.value_namespace_prefix = name_space_prefix;
}
if(value_path == "anonymous-password")
{
anonymous_password = value;
anonymous_password.value_namespace = name_space;
anonymous_password.value_namespace_prefix = name_space_prefix;
}
if(value_path == "username")
{
username = value;
username.value_namespace = name_space;
username.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source-interface")
{
source_interface = value;
source_interface.value_namespace = name_space;
source_interface.value_namespace_prefix = name_space_prefix;
}
}
void Ftp::FtpClient::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "passive")
{
passive.yfilter = yfilter;
}
if(value_path == "password")
{
password.yfilter = yfilter;
}
if(value_path == "anonymous-password")
{
anonymous_password.yfilter = yfilter;
}
if(value_path == "username")
{
username.yfilter = yfilter;
}
if(value_path == "source-interface")
{
source_interface.yfilter = yfilter;
}
}
bool Ftp::FtpClient::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrfs" || name == "passive" || name == "password" || name == "anonymous-password" || name == "username" || name == "source-interface")
return true;
return false;
}
Ftp::FtpClient::Vrfs::Vrfs()
:
vrf(this, {"vrf_name"})
{
yang_name = "vrfs"; yang_parent_name = "ftp-client"; is_top_level_class = false; has_list_ancestor = false;
}
Ftp::FtpClient::Vrfs::~Vrfs()
{
}
bool Ftp::FtpClient::Vrfs::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_data())
return true;
}
return false;
}
bool Ftp::FtpClient::Vrfs::has_operation() const
{
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Ftp::FtpClient::Vrfs::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:ftp/ftp-client/" << get_segment_path();
return path_buffer.str();
}
std::string Ftp::FtpClient::Vrfs::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrfs";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Ftp::FtpClient::Vrfs::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Ftp::FtpClient::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "vrf")
{
auto ent_ = std::make_shared<Ftp::FtpClient::Vrfs::Vrf>();
ent_->parent = this;
vrf.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Ftp::FtpClient::Vrfs::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : vrf.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Ftp::FtpClient::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Ftp::FtpClient::Vrfs::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Ftp::FtpClient::Vrfs::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf")
return true;
return false;
}
Ftp::FtpClient::Vrfs::Vrf::Vrf()
:
vrf_name{YType::str, "vrf-name"},
source_interface{YType::str, "source-interface"},
username{YType::str, "username"},
anonymous_password{YType::str, "anonymous-password"},
password{YType::str, "password"},
passive{YType::empty, "passive"}
{
yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = false;
}
Ftp::FtpClient::Vrfs::Vrf::~Vrf()
{
}
bool Ftp::FtpClient::Vrfs::Vrf::has_data() const
{
if (is_presence_container) return true;
return vrf_name.is_set
|| source_interface.is_set
|| username.is_set
|| anonymous_password.is_set
|| password.is_set
|| passive.is_set;
}
bool Ftp::FtpClient::Vrfs::Vrf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(vrf_name.yfilter)
|| ydk::is_set(source_interface.yfilter)
|| ydk::is_set(username.yfilter)
|| ydk::is_set(anonymous_password.yfilter)
|| ydk::is_set(password.yfilter)
|| ydk::is_set(passive.yfilter);
}
std::string Ftp::FtpClient::Vrfs::Vrf::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:ftp/ftp-client/vrfs/" << get_segment_path();
return path_buffer.str();
}
std::string Ftp::FtpClient::Vrfs::Vrf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrf";
ADD_KEY_TOKEN(vrf_name, "vrf-name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Ftp::FtpClient::Vrfs::Vrf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata());
if (source_interface.is_set || is_set(source_interface.yfilter)) leaf_name_data.push_back(source_interface.get_name_leafdata());
if (username.is_set || is_set(username.yfilter)) leaf_name_data.push_back(username.get_name_leafdata());
if (anonymous_password.is_set || is_set(anonymous_password.yfilter)) leaf_name_data.push_back(anonymous_password.get_name_leafdata());
if (password.is_set || is_set(password.yfilter)) leaf_name_data.push_back(password.get_name_leafdata());
if (passive.is_set || is_set(passive.yfilter)) leaf_name_data.push_back(passive.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Ftp::FtpClient::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Ftp::FtpClient::Vrfs::Vrf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Ftp::FtpClient::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "vrf-name")
{
vrf_name = value;
vrf_name.value_namespace = name_space;
vrf_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source-interface")
{
source_interface = value;
source_interface.value_namespace = name_space;
source_interface.value_namespace_prefix = name_space_prefix;
}
if(value_path == "username")
{
username = value;
username.value_namespace = name_space;
username.value_namespace_prefix = name_space_prefix;
}
if(value_path == "anonymous-password")
{
anonymous_password = value;
anonymous_password.value_namespace = name_space;
anonymous_password.value_namespace_prefix = name_space_prefix;
}
if(value_path == "password")
{
password = value;
password.value_namespace = name_space;
password.value_namespace_prefix = name_space_prefix;
}
if(value_path == "passive")
{
passive = value;
passive.value_namespace = name_space;
passive.value_namespace_prefix = name_space_prefix;
}
}
void Ftp::FtpClient::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "vrf-name")
{
vrf_name.yfilter = yfilter;
}
if(value_path == "source-interface")
{
source_interface.yfilter = yfilter;
}
if(value_path == "username")
{
username.yfilter = yfilter;
}
if(value_path == "anonymous-password")
{
anonymous_password.yfilter = yfilter;
}
if(value_path == "password")
{
password.yfilter = yfilter;
}
if(value_path == "passive")
{
passive.yfilter = yfilter;
}
}
bool Ftp::FtpClient::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf-name" || name == "source-interface" || name == "username" || name == "anonymous-password" || name == "password" || name == "passive")
return true;
return false;
}
Tftp::Tftp()
:
tftp_client(std::make_shared<Tftp::TftpClient>())
{
tftp_client->parent = this;
yang_name = "tftp"; yang_parent_name = "Cisco-IOS-XR-ipv4-filesystems-cfg"; is_top_level_class = true; has_list_ancestor = false;
}
Tftp::~Tftp()
{
}
bool Tftp::has_data() const
{
if (is_presence_container) return true;
return (tftp_client != nullptr && tftp_client->has_data());
}
bool Tftp::has_operation() const
{
return is_set(yfilter)
|| (tftp_client != nullptr && tftp_client->has_operation());
}
std::string Tftp::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:tftp";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Tftp::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Tftp::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "tftp-client")
{
if(tftp_client == nullptr)
{
tftp_client = std::make_shared<Tftp::TftpClient>();
}
return tftp_client;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Tftp::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(tftp_client != nullptr)
{
_children["tftp-client"] = tftp_client;
}
return _children;
}
void Tftp::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Tftp::set_filter(const std::string & value_path, YFilter yfilter)
{
}
std::shared_ptr<ydk::Entity> Tftp::clone_ptr() const
{
return std::make_shared<Tftp>();
}
std::string Tftp::get_bundle_yang_models_location() const
{
return ydk_cisco_ios_xr_models_path;
}
std::string Tftp::get_bundle_name() const
{
return "cisco_ios_xr";
}
augment_capabilities_function Tftp::get_augment_capabilities_function() const
{
return cisco_ios_xr_augment_lookup_tables;
}
std::map<std::pair<std::string, std::string>, std::string> Tftp::get_namespace_identity_lookup() const
{
return cisco_ios_xr_namespace_identity_lookup;
}
bool Tftp::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "tftp-client")
return true;
return false;
}
Tftp::TftpClient::TftpClient()
:
retry{YType::uint32, "retry"},
timeout{YType::uint32, "timeout"},
source_interface{YType::str, "source-interface"}
,
vrfs(std::make_shared<Tftp::TftpClient::Vrfs>())
{
vrfs->parent = this;
yang_name = "tftp-client"; yang_parent_name = "tftp"; is_top_level_class = false; has_list_ancestor = false;
}
Tftp::TftpClient::~TftpClient()
{
}
bool Tftp::TftpClient::has_data() const
{
if (is_presence_container) return true;
return retry.is_set
|| timeout.is_set
|| source_interface.is_set
|| (vrfs != nullptr && vrfs->has_data());
}
bool Tftp::TftpClient::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(retry.yfilter)
|| ydk::is_set(timeout.yfilter)
|| ydk::is_set(source_interface.yfilter)
|| (vrfs != nullptr && vrfs->has_operation());
}
std::string Tftp::TftpClient::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:tftp/" << get_segment_path();
return path_buffer.str();
}
std::string Tftp::TftpClient::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "tftp-client";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Tftp::TftpClient::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (retry.is_set || is_set(retry.yfilter)) leaf_name_data.push_back(retry.get_name_leafdata());
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
if (source_interface.is_set || is_set(source_interface.yfilter)) leaf_name_data.push_back(source_interface.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Tftp::TftpClient::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "vrfs")
{
if(vrfs == nullptr)
{
vrfs = std::make_shared<Tftp::TftpClient::Vrfs>();
}
return vrfs;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Tftp::TftpClient::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
if(vrfs != nullptr)
{
_children["vrfs"] = vrfs;
}
return _children;
}
void Tftp::TftpClient::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "retry")
{
retry = value;
retry.value_namespace = name_space;
retry.value_namespace_prefix = name_space_prefix;
}
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source-interface")
{
source_interface = value;
source_interface.value_namespace = name_space;
source_interface.value_namespace_prefix = name_space_prefix;
}
}
void Tftp::TftpClient::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "retry")
{
retry.yfilter = yfilter;
}
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
if(value_path == "source-interface")
{
source_interface.yfilter = yfilter;
}
}
bool Tftp::TftpClient::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrfs" || name == "retry" || name == "timeout" || name == "source-interface")
return true;
return false;
}
Tftp::TftpClient::Vrfs::Vrfs()
:
vrf(this, {"vrf_name"})
{
yang_name = "vrfs"; yang_parent_name = "tftp-client"; is_top_level_class = false; has_list_ancestor = false;
}
Tftp::TftpClient::Vrfs::~Vrfs()
{
}
bool Tftp::TftpClient::Vrfs::has_data() const
{
if (is_presence_container) return true;
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_data())
return true;
}
return false;
}
bool Tftp::TftpClient::Vrfs::has_operation() const
{
for (std::size_t index=0; index<vrf.len(); index++)
{
if(vrf[index]->has_operation())
return true;
}
return is_set(yfilter);
}
std::string Tftp::TftpClient::Vrfs::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:tftp/tftp-client/" << get_segment_path();
return path_buffer.str();
}
std::string Tftp::TftpClient::Vrfs::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrfs";
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Tftp::TftpClient::Vrfs::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Tftp::TftpClient::Vrfs::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
if(child_yang_name == "vrf")
{
auto ent_ = std::make_shared<Tftp::TftpClient::Vrfs::Vrf>();
ent_->parent = this;
vrf.append(ent_);
return ent_;
}
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Tftp::TftpClient::Vrfs::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
count_ = 0;
for (auto ent_ : vrf.entities())
{
if(_children.find(ent_->get_segment_path()) == _children.end())
_children[ent_->get_segment_path()] = ent_;
else
_children[ent_->get_segment_path()+count_++] = ent_;
}
return _children;
}
void Tftp::TftpClient::Vrfs::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
}
void Tftp::TftpClient::Vrfs::set_filter(const std::string & value_path, YFilter yfilter)
{
}
bool Tftp::TftpClient::Vrfs::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf")
return true;
return false;
}
Tftp::TftpClient::Vrfs::Vrf::Vrf()
:
vrf_name{YType::str, "vrf-name"},
source_interface{YType::str, "source-interface"},
retry{YType::uint32, "retry"},
timeout{YType::uint32, "timeout"}
{
yang_name = "vrf"; yang_parent_name = "vrfs"; is_top_level_class = false; has_list_ancestor = false;
}
Tftp::TftpClient::Vrfs::Vrf::~Vrf()
{
}
bool Tftp::TftpClient::Vrfs::Vrf::has_data() const
{
if (is_presence_container) return true;
return vrf_name.is_set
|| source_interface.is_set
|| retry.is_set
|| timeout.is_set;
}
bool Tftp::TftpClient::Vrfs::Vrf::has_operation() const
{
return is_set(yfilter)
|| ydk::is_set(vrf_name.yfilter)
|| ydk::is_set(source_interface.yfilter)
|| ydk::is_set(retry.yfilter)
|| ydk::is_set(timeout.yfilter);
}
std::string Tftp::TftpClient::Vrfs::Vrf::get_absolute_path() const
{
std::ostringstream path_buffer;
path_buffer << "Cisco-IOS-XR-ipv4-filesystems-cfg:tftp/tftp-client/vrfs/" << get_segment_path();
return path_buffer.str();
}
std::string Tftp::TftpClient::Vrfs::Vrf::get_segment_path() const
{
std::ostringstream path_buffer;
path_buffer << "vrf";
ADD_KEY_TOKEN(vrf_name, "vrf-name");
return path_buffer.str();
}
std::vector<std::pair<std::string, LeafData> > Tftp::TftpClient::Vrfs::Vrf::get_name_leaf_data() const
{
std::vector<std::pair<std::string, LeafData> > leaf_name_data {};
if (vrf_name.is_set || is_set(vrf_name.yfilter)) leaf_name_data.push_back(vrf_name.get_name_leafdata());
if (source_interface.is_set || is_set(source_interface.yfilter)) leaf_name_data.push_back(source_interface.get_name_leafdata());
if (retry.is_set || is_set(retry.yfilter)) leaf_name_data.push_back(retry.get_name_leafdata());
if (timeout.is_set || is_set(timeout.yfilter)) leaf_name_data.push_back(timeout.get_name_leafdata());
return leaf_name_data;
}
std::shared_ptr<ydk::Entity> Tftp::TftpClient::Vrfs::Vrf::get_child_by_name(const std::string & child_yang_name, const std::string & segment_path)
{
return nullptr;
}
std::map<std::string, std::shared_ptr<ydk::Entity>> Tftp::TftpClient::Vrfs::Vrf::get_children() const
{
std::map<std::string, std::shared_ptr<ydk::Entity>> _children{};
char count_=0;
return _children;
}
void Tftp::TftpClient::Vrfs::Vrf::set_value(const std::string & value_path, const std::string & value, const std::string & name_space, const std::string & name_space_prefix)
{
if(value_path == "vrf-name")
{
vrf_name = value;
vrf_name.value_namespace = name_space;
vrf_name.value_namespace_prefix = name_space_prefix;
}
if(value_path == "source-interface")
{
source_interface = value;
source_interface.value_namespace = name_space;
source_interface.value_namespace_prefix = name_space_prefix;
}
if(value_path == "retry")
{
retry = value;
retry.value_namespace = name_space;
retry.value_namespace_prefix = name_space_prefix;
}
if(value_path == "timeout")
{
timeout = value;
timeout.value_namespace = name_space;
timeout.value_namespace_prefix = name_space_prefix;
}
}
void Tftp::TftpClient::Vrfs::Vrf::set_filter(const std::string & value_path, YFilter yfilter)
{
if(value_path == "vrf-name")
{
vrf_name.yfilter = yfilter;
}
if(value_path == "source-interface")
{
source_interface.yfilter = yfilter;
}
if(value_path == "retry")
{
retry.yfilter = yfilter;
}
if(value_path == "timeout")
{
timeout.yfilter = yfilter;
}
}
bool Tftp::TftpClient::Vrfs::Vrf::has_leaf_or_child_of_name(const std::string & name) const
{
if(name == "vrf-name" || name == "source-interface" || name == "retry" || name == "timeout")
return true;
return false;
}
}
}
| 26.850906 | 173 | 0.675277 | CiscoDevNet |
1fe37d5624e6daa686b0129838d3a3034e0ac3f9 | 5,521 | cpp | C++ | Lecture4/main.cpp | zhang-zx/Computer-Aided-Design | 82f2b38c8209245761a8adcd6e1f75368057c7c6 | [
"MIT"
] | null | null | null | Lecture4/main.cpp | zhang-zx/Computer-Aided-Design | 82f2b38c8209245761a8adcd6e1f75368057c7c6 | [
"MIT"
] | null | null | null | Lecture4/main.cpp | zhang-zx/Computer-Aided-Design | 82f2b38c8209245761a8adcd6e1f75368057c7c6 | [
"MIT"
] | null | null | null | #include <iostream>
// GLAD
#include <glad.h>
// GLFW
#include <glfw3.h>
// GLM Mathematics
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
// Other includes
#include "shader.h"
// Function prototypes
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode);
// Window dimensions
const GLuint WIDTH = 800, HEIGHT = 600;
// The MAIN function, from here we start the application and run the game loop
int main()
{
// Init GLFW
glfwInit();
// Set all the required options for GLFW
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
/* Note that on Mac OS X you need to add glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
to your initialization code for it to work.*/
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
// Create a GLFWwindow object that we can use for GLFW's functions
GLFWwindow* window = glfwCreateWindow(WIDTH, HEIGHT, "LearnOpenGL", nullptr, nullptr);
glfwMakeContextCurrent(window);
// Set the required callback functions
glfwSetKeyCallback(window, key_callback);
// Initialize GLAD to setup the OpenGL Function pointers
if (!gladLoadGLLoader((GLADloadproc)glfwGetProcAddress))
{
std::cout << "Failed to initialize glad" << std::endl;
return -1;
};
// Define the viewport dimensions
glViewport(0, 0, WIDTH, HEIGHT);
// Setup OpenGL options
glEnable(GL_DEPTH_TEST);
// Build and compile our shader program
Shader ourShader("main.vert.glsl", "main.frag.glsl");
// Set up vertex data (and buffer(s)) and attribute pointers
GLfloat vertices[] = {
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
0.5f, -0.5f, -0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 1.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
0.5f, -0.5f, -0.5f, 1.0f, 1.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
0.5f, -0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, -0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, -0.5f, -0.5f, 0.0f, 1.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f,
0.5f, 0.5f, -0.5f, 1.0f, 1.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
0.5f, 0.5f, 0.5f, 1.0f, 0.0f,
-0.5f, 0.5f, 0.5f, 0.0f, 0.0f,
-0.5f, 0.5f, -0.5f, 0.0f, 1.0f
};
GLuint VBO, VAO;
glGenVertexArrays(1, &VAO);
glGenBuffers(1, &VBO);
glBindVertexArray(VAO);
glBindBuffer(GL_ARRAY_BUFFER, VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);
// Position attribute
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)0);
glEnableVertexAttribArray(0);
// TexCoord attribute
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(GLfloat), (GLvoid*)(3 * sizeof(GLfloat)));
glEnableVertexAttribArray(2);
glBindVertexArray(0); // Unbind VAO
// Game loop
while (!glfwWindowShouldClose(window))
{
// Check if any events have been activiated (key pressed, mouse moved etc.) and call corresponding response functions
glfwPollEvents();
// Render
// Clear the colorbuffer
glClearColor(0.2f, 0.3f, 0.3f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Activate shader
ourShader.Use();
// Create transformations
glm::mat4 model(1);
glm::mat4 view(1);
glm::mat4 projection(1);
model = glm::rotate(model, (GLfloat)glfwGetTime() * glm::radians(50.0f), glm::vec3(0.5f, 1.0f, 0.0f));
view = glm::translate(view, glm::vec3(0.0f, 0.0f, -3.0f));
// Note: currently we set the projection matrix each frame, but since the projection matrix rarely changes it's often best practice to set it outside the main loop only once.
projection = glm::perspective(glm::radians(45.0f), (GLfloat)WIDTH / (GLfloat)HEIGHT, 0.1f, 100.0f);
// Get their uniform location
GLint modelLoc = glGetUniformLocation(ourShader.Program, "model");
GLint viewLoc = glGetUniformLocation(ourShader.Program, "view");
GLint projLoc = glGetUniformLocation(ourShader.Program, "projection");
// Pass them to the shaders
glUniformMatrix4fv(modelLoc, 1, GL_FALSE, glm::value_ptr(model));
glUniformMatrix4fv(viewLoc, 1, GL_FALSE, glm::value_ptr(view));
glUniformMatrix4fv(projLoc, 1, GL_FALSE, glm::value_ptr(projection));
// Draw container
glBindVertexArray(VAO);
glDrawArrays(GL_TRIANGLES, 0, 36);
glBindVertexArray(0);
// Swap the screen buffers
glfwSwapBuffers(window);
}
// Properly de-allocate all resources once they've outlived their purpose
glDeleteVertexArrays(1, &VAO);
glDeleteBuffers(1, &VBO);
// Terminate GLFW, clearing any resources allocated by GLFW.
glfwTerminate();
return 0;
}
// Is called whenever a key is pressed/released via GLFW
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mode)
{
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
glfwSetWindowShouldClose(window, GL_TRUE);
} | 31.19209 | 176 | 0.675059 | zhang-zx |
1fe62d70db20f26857b21e63f7bd5509d9cfa45e | 1,854 | cpp | C++ | src/Text.cpp | Alissa0101/CI628 | f3401e9ea6a90d59572c4f079d27461148aab075 | [
"MIT"
] | null | null | null | src/Text.cpp | Alissa0101/CI628 | f3401e9ea6a90d59572c4f079d27461148aab075 | [
"MIT"
] | null | null | null | src/Text.cpp | Alissa0101/CI628 | f3401e9ea6a90d59572c4f079d27461148aab075 | [
"MIT"
] | null | null | null | #include "Text.h"
void Text::init(int xInit, int yInit, int fontSizeInit, bool boundRightInit, SDL_Color colorInit){
color = colorInit;
x = xInit;
y = yInit;
fontSize = fontSizeInit;
boundRight = boundRightInit;
font = TTF_OpenFont("Assets/pong.ttf", fontSize);
}
void Text::setText(std::string newText){
if (text.compare(newText)) {
color.a = 0;
}
text = newText;
}
void Text::setFontSize(int _fontSize) {
TTF_CloseFont(font);
font = TTF_OpenFont("Assets/pong.ttf", _fontSize);
fontSize = _fontSize;
}
/// <summary>
/// Render text
/// https://stackoverflow.com/questions/36198732/draw-text-to-screen
/// </summary>
/// <param name="renderer"></param>
/// <param name="text"></param>
/// <param name="fontSize"></param>
/// <param name="x"></param>
/// <param name="y"></param>
/// <param name="boundRight"></param>
void Text::render(SDL_Renderer* renderer){
if(text == ""){text = " "; }
//not great. Find a way to store this somewhere
SDL_Surface* textSurface = TTF_RenderText_Blended(font, text.c_str(), color);
SDL_Texture* textTexture = SDL_CreateTextureFromSurface(renderer, textSurface);
SDL_Rect dest = { x, y, textSurface->w, textSurface->h };
if (centerAlign) {
dest.x = dest.x - textSurface->w / 2;
}
if (boundRight) {
dest = { 800 - static_cast<int>(x) - textSurface->w, static_cast<int>(y), textSurface->w, textSurface->h };
}
SDL_RenderCopy(renderer, textTexture, NULL, &dest);
SDL_FreeSurface(textSurface);
SDL_DestroyTexture(textTexture);
//TTF_CloseFont(font);
//TTF_Quit();
if (color.a < 255) {
if (color.a + 10 > 255) {
color.a = 255;
}
else {
color.a += 10;
}
}
}
void Text::end(){
TTF_CloseFont(font);
TTF_Quit();
}
| 25.39726 | 116 | 0.612729 | Alissa0101 |
1fe766bf3be4e0571c3110346d7aaef3306c4513 | 979 | cpp | C++ | 27_remove/remove.cpp | neojou/leetcode_cplusplus | 760232172c1e753ee13c376038c8e7b41f6cded7 | [
"MIT"
] | null | null | null | 27_remove/remove.cpp | neojou/leetcode_cplusplus | 760232172c1e753ee13c376038c8e7b41f6cded7 | [
"MIT"
] | null | null | null | 27_remove/remove.cpp | neojou/leetcode_cplusplus | 760232172c1e753ee13c376038c8e7b41f6cded7 | [
"MIT"
] | null | null | null | #include <iostream>
#include <functional>
#include <algorithm>
#include <vector>
#include <unordered_map>
#include <thread>
#include <mutex>
#include <condition_variable>
using namespace std;
template <typename T>
void print_vector(vector<T> const &v)
{
cout << "[";
for (auto it = v.begin(); it != v.end(); it++) {
if (it != v.begin())
cout << ", ";
cout << *it;
}
cout << "]";
}
class Solution {
public:
int removeElement(vector<int>& nums, int val) {
int size = nums.size();
int count = 0;
for (int i = 0; i < size; i++) {
if (nums[i] == val)
continue;
nums[count++] = nums[i];
}
return count;
}
};
int main() {
Solution s;
vector<int> nums = {0, 1, 2, 2, 3, 0, 4, 2};
int val = 2;
int k = s.removeElement(nums, val);
vector<int> ret(nums.begin(), nums.begin() + k);
print_vector(ret);
cout << endl;
return 0;
}
| 18.471698 | 52 | 0.52094 | neojou |
1fea83f0b0aee856dcf4f75f6cfbd3c63c033ec7 | 3,309 | cpp | C++ | src/chapter_06_algorithms_and_data_structures/problem_051_transforming_a_list_of_phone_numbers.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_06_algorithms_and_data_structures/problem_051_transforming_a_list_of_phone_numbers.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | src/chapter_06_algorithms_and_data_structures/problem_051_transforming_a_list_of_phone_numbers.cpp | rturrado/TheModernCppChallenge | 648284fb417b6aaa43c21ea2b12a5a21c8cb9269 | [
"MIT"
] | null | null | null | #include "chapter_06_algorithms_and_data_structures/problem_051_transforming_a_list_of_phone_numbers.h"
#include "chapter_06_algorithms_and_data_structures/phone_numbers.h"
#include "rtc/print.h"
#include <algorithm> // erase_if, transform
#include <fmt/ostream.h>
#include <fmt/ranges.h>
#include <functional> // reference_wrapper
#include <iostream> // cout
#include <regex> // regex_match, regex_replace, smatch
#include <sstream> // ostringstream
using phone_numbers = tmcppc::phone_numbers;
using country_code = tmcppc::country_code;
void format_phone_numbers(phone_numbers& ph_nos, const country_code& cc) {
std::transform(begin(ph_nos), end(ph_nos), begin(ph_nos), [&cc](auto& ph_no) {
// Remove whitespaces
std::regex space_pattern{ R"([[:space:]])" };
ph_no = std::regex_replace(ph_no, space_pattern, "");
// Match a phone number. It can be of the form:
// - +, country code, 10-digit number
// - country code, 10-digit number
// - 0, and then a 10-digit number
// - 10 digit number
// Country codes and 10-digit numbers shouldn't start with 0
std::regex ph_no_pattern{R"((?:0?|([1-9][0-9]*)|\+([1-9][0-9]*))([1-9][0-9]{9}))"};
std::smatch matches{};
std::ostringstream oss{};
if (std::regex_match(ph_no, matches, ph_no_pattern) and
((not matches[1].matched and not matches[2].matched) or
(matches[1].matched and stoi(matches[1]) == static_cast<int>(cc)) or
(matches[2].matched and stoi(matches[2]) == static_cast<int>(cc)))) {
oss << "+" << static_cast<int>(cc) << matches[3]; // outputs +, country code, 10-digit number
}
// Returns whether a formatted phone number or an empty string
return oss.str();
});
// Removes empty strings from the list of phone numbers
std::erase_if(ph_nos, [](auto& ph_no) { return ph_no.empty(); });
}
void problem_51_main(std::ostream& os) {
phone_numbers good_cases{
"07555 111111",
"07555222222",
"+44 7555 333333",
"44 7555 444444",
"7555 555555"
};
phone_numbers bad_cases{
"+1 2345 666666", // correct format, but wrong country code
"34 987 7777777", // same as above
"0 12345678", // doesn't contain a 10-digit number
"+02 1234567890" // country code starts with 0
};
for (auto& ph_nos : std::vector<std::reference_wrapper<phone_numbers>>{ good_cases, bad_cases }) {
fmt::print(os, "List of phone numbers:\n\t{}\n", ph_nos.get());
format_phone_numbers(ph_nos.get(), country_code::UK);
fmt::print(os, "List of UK phone numbers after formatting:\n\t{}\n\n", ph_nos.get());
}
}
// Transforming a list of phone numbers
//
// Write a function that, given a list of phone numbers, transforms them so they all start with a specified country code,
// preceded by the + sign.
// Any whitespaces from a phone number should be removed.
// The following is a list of input and output examples:
//
// 07555 123456 => +447555123456
// 07555123456 => +447555123456
// +44 7555 123456 => +447555123456
// 44 7555 123456 => +447555123456
// 7555 123456 => +447555123456
void problem_51_main() {
problem_51_main(std::cout);
}
| 37.602273 | 121 | 0.64249 | rturrado |
1ff91a9753c47b7d114de191c3ae4a4a29d83fd1 | 2,217 | cpp | C++ | src/gtpV2Codec/ieClasses/epcTimerIe.cpp | badhrinathpa/openmme | 6975dc7ba007cd111fdce8e8f64d3d52bef0a625 | [
"Apache-2.0"
] | 46 | 2019-02-19T07:47:54.000Z | 2022-03-12T13:16:26.000Z | src/gtpV2Codec/ieClasses/epcTimerIe.cpp | omec-project/openmme | 181ee0a2a16fe4eea1b84986477f37d6ebbe55c3 | [
"Apache-2.0"
] | 71 | 2019-03-03T02:22:33.000Z | 2020-10-07T22:34:25.000Z | src/gtpV2Codec/ieClasses/epcTimerIe.cpp | badhrinathpa/openmme | 6975dc7ba007cd111fdce8e8f64d3d52bef0a625 | [
"Apache-2.0"
] | 38 | 2019-02-19T06:36:40.000Z | 2021-07-17T14:35:50.000Z | /*
* epcTimerIe.cpp
*
* Revisit header later
* Author: hariharanb
*/
#include "epcTimerIe.h"
#include "dataTypeCodecUtils.h"
EpcTimerIe::EpcTimerIe()
{
ieType = 156;
// TODO
}
EpcTimerIe::~EpcTimerIe() {
// TODO Auto-generated destructor stub
}
bool EpcTimerIe::encodeEpcTimerIe(MsgBuffer &buffer, EpcTimerIeData const &data)
{
if(!(buffer.writeBits(data.timerUnit, 3)))
{
errorStream.add("Encoding of timerUnit failed\n");
return false;
}
if(!(buffer.writeBits(data.timerValue, 5)))
{
errorStream.add("Encoding of timerValue failed\n");
return false;
}
return true;
}
bool EpcTimerIe::decodeEpcTimerIe(MsgBuffer &buffer, EpcTimerIeData &data, Uint16 length)
{
// TODO optimize the length checks
Uint16 lengthLeft = length;
Uint16 ieBoundary = buffer.getCurrentIndex() + length;
data.timerUnit = buffer.readBits(3);
// confirm that we are not reading beyond the IE boundary
if (buffer.getCurrentIndex() > ieBoundary)
{
errorStream.add("Attempt to read beyond IE boundary: timerUnit\n");
return false;
}
data.timerValue = buffer.readBits(5);
// confirm that we are not reading beyond the IE boundary
if (buffer.getCurrentIndex() > ieBoundary)
{
errorStream.add("Attempt to read beyond IE boundary: timerValue\n");
return false;
}
// The IE is decoded now. The buffer index should be pointing to the
// IE Boundary. If not, we have some more data left for the IE which we don't know
// how to decode
if (ieBoundary == buffer.getCurrentIndex())
{
return true;
}
else
{
errorStream.add("Unable to decode IE EpcTimerIe\n");
return false;
}
}
void EpcTimerIe::displayEpcTimerIe_v(EpcTimerIeData const &data, Debug &stream)
{
stream.incrIndent();
stream.add("EpcTimerIeData:");
stream.incrIndent();
stream.endOfLine();
stream.add( "timerUnit: ");
stream.add((Uint8)data.timerUnit);
stream.endOfLine();
stream.add( "timerValue: ");
stream.add((Uint8)data.timerValue);
stream.endOfLine();
stream.decrIndent();
stream.decrIndent();
}
| 25.193182 | 89 | 0.649977 | badhrinathpa |
1ffcf852d9b042489b6ec50e9d04a6df8bec03f3 | 6,167 | cpp | C++ | src/application/test_yolo_map.cpp | hito0512/tensorRT_Pro | d577fbab615a3d84cb50824d2418655659fd61af | [
"MIT"
] | 537 | 2021-10-03T10:51:49.000Z | 2022-03-31T10:07:05.000Z | src/application/test_yolo_map.cpp | hito0512/tensorRT_Pro | d577fbab615a3d84cb50824d2418655659fd61af | [
"MIT"
] | 52 | 2021-10-04T09:05:35.000Z | 2022-03-31T07:35:22.000Z | src/application/test_yolo_map.cpp | hito0512/tensorRT_Pro | d577fbab615a3d84cb50824d2418655659fd61af | [
"MIT"
] | 146 | 2021-10-11T00:46:19.000Z | 2022-03-31T02:19:37.000Z |
#include <builder/trt_builder.hpp>
#include <infer/trt_infer.hpp>
#include <common/ilogger.hpp>
#include <common/json.hpp>
#include "app_yolo/yolo.hpp"
#include <vector>
#include <string>
using namespace std;
static const char* cocolabels[] = {
"person", "bicycle", "car", "motorcycle", "airplane",
"bus", "train", "truck", "boat", "traffic light", "fire hydrant",
"stop sign", "parking meter", "bench", "bird", "cat", "dog", "horse",
"sheep", "cow", "elephant", "bear", "zebra", "giraffe", "backpack",
"umbrella", "handbag", "tie", "suitcase", "frisbee", "skis",
"snowboard", "sports ball", "kite", "baseball bat", "baseball glove",
"skateboard", "surfboard", "tennis racket", "bottle", "wine glass",
"cup", "fork", "knife", "spoon", "bowl", "banana", "apple", "sandwich",
"orange", "broccoli", "carrot", "hot dog", "pizza", "donut", "cake",
"chair", "couch", "potted plant", "bed", "dining table", "toilet", "tv",
"laptop", "mouse", "remote", "keyboard", "cell phone", "microwave",
"oven", "toaster", "sink", "refrigerator", "book", "clock", "vase",
"scissors", "teddy bear", "hair drier", "toothbrush"
};
bool requires(const char* name);
struct BoxLabel{
int label;
float cx, cy, width, height;
float confidence;
};
struct ImageItem{
string image_file;
Yolo::BoxArray detections;
};
vector<ImageItem> scan_dataset(const string& images_root){
vector<ImageItem> output;
auto image_files = iLogger::find_files(images_root, "*.jpg");
for(int i = 0; i < image_files.size(); ++i){
auto& image_file = image_files[i];
if(!iLogger::exists(image_file)){
INFOW("Not found: %s", image_file.c_str());
continue;
}
ImageItem item;
item.image_file = image_file;
output.emplace_back(item);
}
return output;
}
static void inference(vector<ImageItem>& images, int deviceid, const string& engine_file, TRT::Mode mode, Yolo::Type type, const string& model_name){
auto engine = Yolo::create_infer(
engine_file, type, deviceid, 0.001f, 0.65f,
Yolo::NMSMethod::CPU, 10000
);
if(engine == nullptr){
INFOE("Engine is nullptr");
return;
}
int nimages = images.size();
vector<shared_future<Yolo::BoxArray>> image_results(nimages);
for(int i = 0; i < nimages; ++i){
if(i % 100 == 0){
INFO("Commit %d / %d", i+1, nimages);
}
image_results[i] = engine->commit(cv::imread(images[i].image_file));
}
for(int i = 0; i < nimages; ++i)
images[i].detections = image_results[i].get();
}
void detect_images(vector<ImageItem>& images, Yolo::Type type, TRT::Mode mode, const string& model){
int deviceid = 0;
auto mode_name = TRT::mode_string(mode);
TRT::set_device(deviceid);
auto int8process = [=](int current, int count, const vector<string>& files, shared_ptr<TRT::Tensor>& tensor){
INFO("Int8 %d / %d", current, count);
for(int i = 0; i < files.size(); ++i){
auto image = cv::imread(files[i]);
Yolo::image_to_tensor(image, tensor, type, i);
}
};
const char* name = model.c_str();
INFO("===================== test %s %s %s ==================================", Yolo::type_name(type), mode_name, name);
if(not requires(name))
return;
string onnx_file = iLogger::format("%s.onnx", name);
string model_file = iLogger::format("%s.%s.trtmodel", name, mode_name);
int test_batch_size = 16;
if(not iLogger::exists(model_file)){
TRT::compile(
mode, // FP32、FP16、INT8
test_batch_size, // max batch size
onnx_file, // source
model_file, // save to
{},
int8process,
"inference"
);
}
inference(images, deviceid, model_file, mode, type, name);
}
bool save_to_json(const vector<ImageItem>& images, const string& file){
int to_coco90_class_map[] = {
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90
};
Json::Value predictions(Json::arrayValue);
for(int i = 0; i < images.size(); ++i){
auto& image = images[i];
auto file_name = iLogger::file_name(image.image_file, false);
int image_id = atoi(file_name.c_str());
auto& boxes = image.detections;
for(auto& box : boxes){
Json::Value jitem;
jitem["image_id"] = image_id;
jitem["category_id"] = to_coco90_class_map[box.class_label];
jitem["score"] = box.confidence;
auto& bbox = jitem["bbox"];
bbox.append(box.left);
bbox.append(box.top);
bbox.append(box.right - box.left);
bbox.append(box.bottom - box.top);
predictions.append(jitem);
}
}
return iLogger::save_file(file, predictions.toStyledString());
}
int test_yolo_map(){
/*
结论:
1. YoloV5在tensorRT下和pytorch下,只要输入一样,输出的差距最大值是1e-3
2. YoloV5-6.0的mAP,官方代码跑下来是mAP@.5:.95 = 0.367, mAP@.5 = 0.554,与官方声称的有差距
3. 这里的tensorRT版本测试的精度为:mAP@.5:.95 = 0.357, mAP@.5 = 0.539,与pytorch结果有差距
4. cv2.imread与cv::imread,在操作jpeg图像时,在我这里测试读出的图像值不同,最大差距有19。而png图像不会有这个问题
若想完全一致,请用png图像
5. 预处理部分,若采用letterbox的方式做预处理,由于tensorRT这里是固定640x640大小,测试采用letterbox并把多余部分
设置为0. 其推理结果与pytorch相近,但是依旧有差别
6. 采用warpAffine和letterbox两种方式的预处理结果,在mAP上没有太大变化(小数点后三位差)
7. mAP差一个点的原因可能在固定分辨率这件事上,还有是pytorch实现的所有细节并非完全加入进来。这些细节可能有没有
找到的部分
*/
auto images = scan_dataset("/data/sxai/dataset/coco/images/val2017");
INFO("images.size = %d", images.size());
string model = "yolov5s";
detect_images(images, Yolo::Type::V5, TRT::Mode::FP32, model);
save_to_json(images, model + ".prediction.json");
return 0;
} | 34.452514 | 149 | 0.587157 | hito0512 |
1ffd58b46b8d05e4695749e984a01dd8c8b2e5be | 1,707 | cc | C++ | coset.cc | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | coset.cc | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | coset.cc | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | #include <stdexcept>
#include <iostream>
#include "coset.h"
#include "group.h"
#include "permutation.h"
#include "ext.h"
Group Coset::supergroup() const {
return _G;
}
Group Coset::subgroup() const {
return _H;
}
bool Coset::isRightCoset() const {
return _right;
}
const Permutation& Coset::representative() const {
return _sigma;
}
bool Coset::operator==( const Coset& other ) const {
if( subgroup()->hasSubgroup(other.subgroup()) && other.subgroup()->hasSubgroup( subgroup() ) && isRightCoset() == other.isRightCoset() )
return subgroup()->contains( representative().inverse() * other.representative() );
throw std::range_error( "Cosets are incomparable" );
}
Coset::Coset( Group G, Group H, Permutation sigma, bool right ) : _sigma( std::move( sigma ) ) {
_G = std::move( G );
_H = std::move( H );
if( _H == nullptr or !_G->hasSubgroup( _H ) )
throw std::range_error( "Can't construct coset since argument is not a subgroup" );
_right = right;
}
std::ostream& operator<<( std::ostream& os, const Coset& c ) {
if( c.isRightCoset() )
return os << c.subgroup()->generators() << c.representative();
else
return os << c.representative() << c.subgroup()->generators();
}
bool Iso::isEmpty() const {
return isSecond();
}
const Coset& Iso::coset() const {
return getFirst();
}
Coset operator*( const Permutation& sigma, const Coset& tauH ) {
// std::cout << tauH << std::endl;
assert( not tauH.isRightCoset() );
Permutation sigmatau = sigma * tauH.representative();
return Coset( tauH.supergroup(), tauH.subgroup(), sigmatau, false );
}
Iso operator*( const Permutation& sigma, const Iso& tauH ) {
if( tauH.isEmpty() )
return tauH;
else
return sigma * tauH.coset();
}
| 25.477612 | 137 | 0.674282 | MadPidgeon |
1ffe2843c6a414142cadc13f523a0ede6464f440 | 753 | hpp | C++ | poo/tema2/arbore_oarecare.hpp | FloaterTS/teme-fmi | 624296d3b3341f1c18fb26768e361ce2e1faa68c | [
"MIT"
] | 54 | 2020-03-17T10:00:15.000Z | 2022-03-31T06:40:30.000Z | poo/tema2/arbore_oarecare.hpp | florinalexandrunecula/teme-fmi | b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e | [
"MIT"
] | null | null | null | poo/tema2/arbore_oarecare.hpp | florinalexandrunecula/teme-fmi | b4d7a416a5ca71b76d66b9407ad2b8ee2af9301e | [
"MIT"
] | 59 | 2020-01-22T11:39:59.000Z | 2022-03-28T00:19:06.000Z | #pragma once
#include "arbore.hpp"
#include "nod_fiu_frate.hpp"
/// Arbore oarecare in reprezentare inlantuita
class ArboreOarecare : public Arbore {
NodFiuFrate* rad;
const Nod* getRadacina() const;
public:
/// Construieste un nou arbore vid
ArboreOarecare();
ArboreOarecare(const ArboreOarecare& rhs);
~ArboreOarecare();
ArboreOarecare& operator=(const ArboreOarecare& rhs);
void goleste() override;
/// Insereaza un nod in arbore, locul acestuia fiind determinat te lista de parinti.
void inserare(const int parinti[], int nrP, int valoare);
friend std::ostream& operator<<(std::ostream& out, const ArboreOarecare& a);
friend std::istream& operator>>(std::istream& in, ArboreOarecare& a);
};
| 25.1 | 88 | 0.706507 | FloaterTS |
1fffb3f0211b6425028dd3500cab786e788a2019 | 7,950 | cpp | C++ | src/calibrationfilter.cpp | elvisdukaj/calibration_filter | 2c2c0e9023994977d3d5550f3673e60baadf16eb | [
"BSD-2-Clause"
] | null | null | null | src/calibrationfilter.cpp | elvisdukaj/calibration_filter | 2c2c0e9023994977d3d5550f3673e60baadf16eb | [
"BSD-2-Clause"
] | null | null | null | src/calibrationfilter.cpp | elvisdukaj/calibration_filter | 2c2c0e9023994977d3d5550f3673e60baadf16eb | [
"BSD-2-Clause"
] | null | null | null | // Copyright (c) 2017 Elvis Dukaj
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#include "calibrationfilter.h"
#include <opencv2/core/types_c.h>
#include <opencv2/core.hpp>
#include <opencv2/calib3d.hpp>
#include <opencv2/imgproc.hpp>
#include <QDebug>
#include <stdexcept>
#include <sstream>
#include <iostream>
#include <fstream>
using namespace std;
// Print camera parameters to the output file
static void saveCameraParams(const cv::Mat& cameraMatrix, const cv::Mat& distCoeffs, double totalAvgErr )
{
cv::FileStorage fs( "cameraCalibration.xml", cv::FileStorage::WRITE );
fs << "CameraMatrix" << cameraMatrix;
fs << "DistortionCoefficients" << distCoeffs;
fs << "AvgReprojection_Error" << totalAvgErr;
}
QVideoFilterRunnable* CalibrationFilter::createFilterRunnable()
{
return new CalibrationFilterRunnable(this);
}
CalibrationFilterRunnable::CalibrationFilterRunnable(CalibrationFilter* filter)
: m_filter{filter}
{
}
QVideoFrame CalibrationFilterRunnable::run(QVideoFrame* frame, const QVideoSurfaceFormat&, QVideoFilterRunnable::RunFlags)
{
if (!isFrameValid(frame))
{
qDebug() << "Frame is NOT valid";
return QVideoFrame{};
}
if (!frame->map(QAbstractVideoBuffer::ReadWrite))
{
qDebug() << "Unable to map the videoframe in memory" << endl;
return *frame;
}
try
{
if (m_filter->hasToShowNegative())
showNegative(frame);
else if (!m_filter->isCalibrated())
acquireFrame(frame);
else if(m_filter->isCalibrated() && m_filter->showUnsistorted())
showUndistorted(frame);
else
showFlipped(frame);
}
catch(const std::exception& exc)
{
qDebug() << exc.what();
}
frame->unmap();
return *frame;
}
void CalibrationFilterRunnable::showFlipped(QVideoFrame* frame)
{
cv::Mat frameMat;
convertToCvMat(frame, frameMat);
cv::flip(frameMat, frameMat, 1);
}
void CalibrationFilterRunnable::showNegative(QVideoFrame* frame)
{
cv::Mat frameMat;
convertToCvMat(frame, frameMat);
cv::flip(frameMat, frameMat, 1);
m_lastFrameWithChessBoard.copyTo(
frameMat(cv::Rect{
20, 20,
m_lastFrameWithChessBoard.cols,
m_lastFrameWithChessBoard.rows
}
)
);
}
void CalibrationFilterRunnable::showUndistorted(QVideoFrame* frame)
{
cv::Mat frameMat;
convertToCvMat(frame, frameMat);
cv::flip(frameMat, frameMat, 1);
m_calibrator.remap(frameMat, frameMat );
}
void CalibrationFilterRunnable::acquireFrame(QVideoFrame* frame)
{
cv::Mat frameMat, grayscale;
videoFrameInGrayScaleAndColor(frame, grayscale, frameMat);
auto corners = m_calibrator.findChessboard(grayscale);
if (!corners.empty())
{
cv::drawChessboardCorners(
frameMat,
m_calibrator.boardSize(),
corners,
true
);
emit m_filter->chessBoardFound();
cv::bitwise_not(frameMat, m_lastFrameWithChessBoard);
cv::resize(m_lastFrameWithChessBoard, m_lastFrameWithChessBoard,
cv::Size{0, 0}, 0.25, 0.25
);
m_filter->addGoodFrame();
if (m_filter->goodFrames() == m_filter->maxFrames())
{
auto error = m_calibrator.calibrate(frameMat.size());
saveCameraParams(m_calibrator.cameraMatrix(), m_calibrator.distortion(), error);
qDebug() << "calibration done! Error: " << error;
m_filter->setCalibrated();
emit m_filter->calibrationFinished();
}
}
}
void CalibrationFilterRunnable::convertToCvMat(QVideoFrame *frame, cv::Mat& frameMat)
{
auto width = frame->width();
auto height = frame->height();
auto data = frame->bits();
switch (frame->pixelFormat()) {
case QVideoFrame::Format_RGB32:
frameMat = cv::Mat{height, width, CV_8UC4, data};
return;
case QVideoFrame::Format_RGB24:
frameMat = cv::Mat{height, width, CV_8UC3, data};
return;
case QVideoFrame::Format_YUV420P:
frameMat = cv::Mat{height, width, CV_8UC1, data};
return;
default:
throw std::runtime_error{"Unknown video frame type"};
}
}
vector<cv::Point2f> CameraCalibrator::findChessboard(const cv::Mat& grayscale)
{
vector<cv::Point2f> imageCorners;
if (cv::findChessboardCorners(grayscale, m_boardSize, imageCorners, cv::CALIB_CB_FAST_CHECK))
{
cv::cornerSubPix(
grayscale, imageCorners, m_boardSize,
cv::Size(-1, -1),
cv::TermCriteria{
CV_TERMCRIT_EPS + CV_TERMCRIT_ITER,
300, 0.01}
);
if (imageCorners.size() == m_boardSize.area())
addPoints(imageCorners);
else
imageCorners.clear();
}
return imageCorners;
}
void CameraCalibrator::addPoints(const std::vector<cv::Point2f> &imageCorners)
{
vector<cv::Point3f> objectCorners;
for (auto y = 0; y < m_boardSize.height; ++y)
for (auto x = 0; x < m_boardSize.width; ++x)
objectCorners.push_back(cv::Point3f(y, x, 0.0f));
m_worldObjectPoints.push_back(objectCorners);
m_imagePoints.push_back(imageCorners);
}
using namespace cv;
double CameraCalibrator::calibrate(cv::Size& imageSize)
{
qDebug() << "Calibrating...";
m_mustInitUndistort = true;
// start calibration
auto res = cv::calibrateCamera(
m_worldObjectPoints,
m_imagePoints,
imageSize,
m_cameraMatrix,
m_distCoeffs,
m_rotationVecs,
m_translationtVecs
);
cout << "Camera matrix: " << m_cameraMatrix << '\n'
<< "Camera distortion: " << m_distCoeffs << '\n'
<< endl;
return res;
}
void CameraCalibrator::CameraCalibrator::remap(const cv::Mat& image, cv::Mat& outImage)
{
if (m_mustInitUndistort)
{
cv::initUndistortRectifyMap(
m_cameraMatrix, // computed camera matrix
m_distCoeffs, // computed distortion matrix
cv::Mat(), // optional rectification (none)
cv::Mat(), // camera matrix to generate undistorted
image.size(), // size of undistorted
CV_32FC1, // type of output map
m_mapX, m_mapY // the x and y mapping functions
);
m_mustInitUndistort = false;
}
// Apply mapping functions
cv::remap(image, outImage, m_mapX, m_mapY, cv::INTER_LINEAR);
}
| 30.113636 | 122 | 0.619623 | elvisdukaj |
95019acff0b42b3b77a730c4be4450b8d3b45c09 | 4,117 | cpp | C++ | bindings/python/src/LibraryPhysicsPy/Environment/Objects/Celestial.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryPhysicsPy/Environment/Objects/Celestial.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | bindings/python/src/LibraryPhysicsPy/Environment/Objects/Celestial.cpp | cowlicks/library-physics | dd314011132430fcf074a9a1633b24471745cf92 | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/// @project Library ▸ Physics
/// @file LibraryPhysicsPy/Environment/Objects/Celestial.cpp
/// @author Lucas Brémond <lucas@loftorbital.com>
/// @license Apache License 2.0
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
#include <Library/Physics/Environment/Objects/Celestial.hpp>
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
inline void LibraryPhysicsPy_Environment_Objects_Celestial ( )
{
using namespace boost::python ;
using library::core::types::Shared ;
using library::core::types::Real ;
using library::core::types::String ;
using library::physics::time::Instant ;
using library::physics::units::Length ;
using library::physics::units::Derived ;
using library::physics::env::Ephemeris ;
using library::physics::env::Object ;
using library::physics::env::obj::Celestial ;
using GravitationalModel = library::physics::environment::gravitational::Model ;
using MagneticModel = library::physics::environment::magnetic::Model ;
scope in_Celestial = class_<Celestial, bases<Object>>("Celestial", init<const String&, const Celestial::Type&, const Derived& , const Length&, const Real&, const Real&, const Shared<Ephemeris>&, const Shared<GravitationalModel>&, const Shared<MagneticModel>&, const Instant&>())
.def(init<const String&, const Celestial::Type&, const Derived& , const Length&, const Real&, const Real&, const Shared<Ephemeris>&, const Shared<GravitationalModel>&, const Shared<MagneticModel>&, const Instant&, const Object::Geometry&>())
// .def(self == self)
// .def(self != self)
.def(self_ns::str(self_ns::self))
.def(self_ns::repr(self_ns::self))
.def("isDefined", &Celestial::isDefined)
.def("accessEphemeris", &Celestial::accessEphemeris)
.def("accessGravitationalModel", &Celestial::accessGravitationalModel)
.def("accessMagneticModel", &Celestial::accessMagneticModel)
.def("getType", &Celestial::getType)
.def("getGravitationalParameter", &Celestial::getGravitationalParameter)
.def("getEquatorialRadius", &Celestial::getEquatorialRadius)
.def("getFlattening", &Celestial::getFlattening)
.def("getJ2", &Celestial::getJ2)
// .def("accessFrame", &Celestial::accessFrame)
.def("getPositionIn", &Celestial::getPositionIn)
.def("getTransformTo", &Celestial::getTransformTo)
.def("getAxesIn", &Celestial::getAxesIn)
.def("getGravitationalFieldAt", &Celestial::getGravitationalFieldAt)
.def("getMagneticFieldAt", &Celestial::getMagneticFieldAt)
.def("getFrameAt", &Celestial::getFrameAt)
.def("Undefined", &Celestial::Undefined).staticmethod("Undefined")
.def("StringFromFrameType", &Celestial::StringFromFrameType).staticmethod("StringFromFrameType")
;
enum_<Celestial::Type>("Type")
.value("Undefined", Celestial::Type::Undefined)
.value("Sun", Celestial::Type::Sun)
.value("Mercury", Celestial::Type::Mercury)
.value("Venus", Celestial::Type::Venus)
.value("Earth", Celestial::Type::Earth)
.value("Moon", Celestial::Type::Moon)
.value("Mars", Celestial::Type::Mars)
;
enum_<Celestial::FrameType>("FrameType")
.value("Undefined", Celestial::FrameType::Undefined)
.value("NED", Celestial::FrameType::NED)
;
register_ptr_to_python<Shared<const Celestial>>() ;
implicitly_convertible<Shared<Celestial>, Shared<const Celestial>>() ;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
| 44.268817 | 282 | 0.564732 | cowlicks |
9506265b265d32b0372b9e77ce96ec2d9806cdc4 | 10,239 | cc | C++ | src/table_file_iterator.cc | tobecontinued/Jungle | d06eb7915de4b1489b4cd0ead5b7281e8a8b82c4 | [
"Apache-2.0"
] | 157 | 2019-12-27T18:12:19.000Z | 2022-03-27T13:34:52.000Z | src/table_file_iterator.cc | tobecontinued/Jungle | d06eb7915de4b1489b4cd0ead5b7281e8a8b82c4 | [
"Apache-2.0"
] | 11 | 2020-01-02T18:30:33.000Z | 2021-09-28T03:10:09.000Z | src/table_file_iterator.cc | tobecontinued/Jungle | d06eb7915de4b1489b4cd0ead5b7281e8a8b82c4 | [
"Apache-2.0"
] | 32 | 2019-12-28T18:17:27.000Z | 2021-12-24T02:05:10.000Z | /************************************************************************
Copyright 2017-2019 eBay Inc.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
https://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 "table_file.h"
#include "table_mgr.h"
namespace jungle {
// === iterator ===============================================================
TableFile::Iterator::Iterator()
: tFile(nullptr)
, tFileSnap(nullptr)
, fdbSnap(nullptr)
, fdbItr(nullptr)
, minSeq(NOT_INITIALIZED)
, maxSeq(NOT_INITIALIZED)
{}
TableFile::Iterator::~Iterator() {
close();
}
Status TableFile::Iterator::init(DB* snap_handle,
TableFile* t_file,
const SizedBuf& start_key,
const SizedBuf& end_key)
{
tFile = t_file;
fdb_status fs;
Status s;
// Get last snap marker.
fdb_kvs_handle* fdb_snap = nullptr;
if (snap_handle) {
// Snapshot.
mGuard l(t_file->snapHandlesLock);
auto entry = t_file->snapHandles.find(snap_handle);
if (entry == t_file->snapHandles.end()) return Status::SNAPSHOT_NOT_FOUND;
fdb_kvs_handle* snap_src = entry->second;
fdb_seqnum_t snap_seqnum = 0;
fs = fdb_get_kvs_seqnum(snap_src, &snap_seqnum);
if (fs != FDB_RESULT_SUCCESS) return Status::INVALID_SNAPSHOT;
fs = fdb_snapshot_open( snap_src,
&fdbSnap,
snap_seqnum );
if (fs != FDB_RESULT_SUCCESS) return Status::FDB_OPEN_KVS_FAIL;
fdb_snap = fdbSnap;
} else {
// Normal, use latest snapshot.
tFile->leaseSnapshot(tFileSnap);
fs = fdb_snapshot_open( tFileSnap->fdbSnap,
&fdbSnap,
tFileSnap->fdbSeqnum );
if (fs != FDB_RESULT_SUCCESS) return Status::FDB_OPEN_KVS_FAIL;
fdb_snap = fdbSnap;
}
// if (valid_number(chk) && snap_seqnum > chk) snap_seqnum = chk;
fs = fdb_iterator_init(fdb_snap, &fdbItr,
start_key.data, start_key.size,
end_key.data, end_key.size,
FDB_ITR_NO_DELETES);
if (fs != FDB_RESULT_SUCCESS) return Status::FDB_OPEN_KVS_FAIL;
type = BY_KEY;
return Status();
}
Status TableFile::Iterator::initSN(DB* snap_handle,
TableFile* t_file,
const uint64_t min_seq,
const uint64_t max_seq)
{
tFile = t_file;
fdb_status fs;
Status s;
// Get last snap marker.
fdb_seqnum_t snap_seqnum = 0;
fdb_kvs_handle* fdb_snap = nullptr;
if (snap_handle) {
// Snapshot.
mGuard l(t_file->snapHandlesLock);
auto entry = t_file->snapHandles.find(snap_handle);
if (entry == t_file->snapHandles.end()) return Status::SNAPSHOT_NOT_FOUND;
fdb_kvs_handle* snap_src = entry->second;
fs = fdb_get_kvs_seqnum(snap_src, &snap_seqnum);
if (fs != FDB_RESULT_SUCCESS) return Status::INVALID_SNAPSHOT;
fs = fdb_snapshot_open( snap_src,
&fdbSnap,
snap_seqnum );
if (fs != FDB_RESULT_SUCCESS) return Status::FDB_OPEN_KVS_FAIL;
fdb_snap = fdbSnap;
} else {
// Normal, use latest snapshot.
tFile->leaseSnapshot(tFileSnap);
fs = fdb_snapshot_open( tFileSnap->fdbSnap,
&fdbSnap,
tFileSnap->fdbSeqnum );
if (fs != FDB_RESULT_SUCCESS) return Status::FDB_OPEN_KVS_FAIL;
fdb_snap = fdbSnap;
}
// if (valid_number(chk) && snap_seqnum > chk) snap_seqnum = chk;
if (valid_number(min_seq)) {
minSeq = min_seq;
} else {
minSeq = 0;
}
if (valid_number(max_seq)) {
// If `snap_seqnum` is zero and `max_seq` is given,
// we should honor `max_seq`.
if (snap_seqnum) {
maxSeq = std::min(snap_seqnum, max_seq);
} else {
maxSeq = max_seq;
}
} else {
maxSeq = 0;
}
fs = fdb_iterator_sequence_init(fdb_snap, &fdbItr,
minSeq, maxSeq,
FDB_ITR_NO_DELETES);
if (fs != FDB_RESULT_SUCCESS) return Status::FDB_OPEN_KVS_FAIL;
type = BY_SEQ;
return Status();
}
Status TableFile::Iterator::get(Record& rec_out) {
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fdb_doc tmp_doc;
memset(&tmp_doc, 0x0, sizeof(tmp_doc));
fdb_doc *doc = &tmp_doc;
fs = fdb_iterator_get(fdbItr, &doc);
if (fs != FDB_RESULT_SUCCESS) {
return Status::ERROR;
}
rec_out.kv.key.set(doc->keylen, doc->key);
rec_out.kv.key.setNeedToFree();
rec_out.kv.value.set(doc->bodylen, doc->body);
rec_out.kv.value.setNeedToFree();
// Decode meta.
SizedBuf user_meta_out;
SizedBuf raw_meta(doc->metalen, doc->meta);;
SizedBuf::Holder h_raw_meta(raw_meta); // auto free raw meta.
raw_meta.setNeedToFree();
InternalMeta i_meta;
TableFile::rawMetaToUserMeta(raw_meta, i_meta, user_meta_out);
user_meta_out.moveTo( rec_out.meta );
// Decompress if needed.
DB* parent_db = tFile->tableMgr->getParentDb();
const DBConfig* db_config = tFile->tableMgr->getDbConfig();
try {
Status s;
TC( tFile->decompressValue(parent_db, db_config, rec_out, i_meta) );
rec_out.seqNum = doc->seqnum;
rec_out.type = (i_meta.isTombstone || doc->deleted)
? Record::DELETION
: Record::INSERTION;
return Status();
} catch (Status s) {
rec_out.kv.free();
rec_out.meta.free();
return s;
}
}
Status TableFile::Iterator::getMeta(Record& rec_out,
size_t& valuelen_out,
uint64_t& offset_out)
{
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fdb_doc tmp_doc;
memset(&tmp_doc, 0x0, sizeof(tmp_doc));
fdb_doc *doc = &tmp_doc;
fs = fdb_iterator_get_metaonly(fdbItr, &doc);
if (fs != FDB_RESULT_SUCCESS) {
return Status::ERROR;
}
rec_out.kv.key.set(doc->keylen, doc->key);
rec_out.kv.key.setNeedToFree();
valuelen_out = doc->bodylen;
offset_out = doc->offset;
// Decode meta.
SizedBuf user_meta_out;
SizedBuf raw_meta(doc->metalen, doc->meta);;
SizedBuf::Holder h_raw_meta(raw_meta); // auto free raw meta.
raw_meta.setNeedToFree();
InternalMeta i_meta;
TableFile::rawMetaToUserMeta(raw_meta, i_meta, user_meta_out);
user_meta_out.moveTo( rec_out.meta );
rec_out.seqNum = doc->seqnum;
rec_out.type = (i_meta.isTombstone || doc->deleted)
? Record::DELETION
: Record::INSERTION;
return Status();
}
Status TableFile::Iterator::prev() {
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fs = fdb_iterator_prev(fdbItr);
if (fs != FDB_RESULT_SUCCESS) {
fs = fdb_iterator_next(fdbItr);
assert(fs == FDB_RESULT_SUCCESS);
return Status::OUT_OF_RANGE;
}
return Status();
}
Status TableFile::Iterator::next() {
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fs = fdb_iterator_next(fdbItr);
if (fs != FDB_RESULT_SUCCESS) {
fs = fdb_iterator_prev(fdbItr);
assert(fs == FDB_RESULT_SUCCESS);
return Status::OUT_OF_RANGE;
}
return Status();
}
Status TableFile::Iterator::seek(const SizedBuf& key, SeekOption opt) {
if (key.empty()) return gotoBegin();
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fdb_iterator_seek_opt_t fdb_seek_opt =
(opt == GREATER)
? FDB_ITR_SEEK_HIGHER
: FDB_ITR_SEEK_LOWER;
fs = fdb_iterator_seek(fdbItr, key.data, key.size, fdb_seek_opt);
if (fs != FDB_RESULT_SUCCESS) {
if (opt == GREATER) {
fs = fdb_iterator_seek_to_max(fdbItr);
} else {
fs = fdb_iterator_seek_to_min(fdbItr);
}
if (fs != FDB_RESULT_SUCCESS) return Status::OUT_OF_RANGE;
}
return Status();
}
Status TableFile::Iterator::seekSN(const uint64_t seqnum, SeekOption opt) {
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fdb_iterator_seek_opt_t fdb_seek_opt =
(opt == GREATER)
? FDB_ITR_SEEK_HIGHER
: FDB_ITR_SEEK_LOWER;
fs = fdb_iterator_seek_byseq(fdbItr, seqnum, fdb_seek_opt);
if (fs != FDB_RESULT_SUCCESS) {
if (opt == GREATER) {
fs = fdb_iterator_seek_to_max(fdbItr);
} else {
fs = fdb_iterator_seek_to_min(fdbItr);
}
assert(fs == FDB_RESULT_SUCCESS);
}
return Status();
}
Status TableFile::Iterator::gotoBegin() {
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fs = fdb_iterator_seek_to_min(fdbItr);
(void)fs;
return Status();
}
Status TableFile::Iterator::gotoEnd() {
if (!tFile || !fdbItr) return Status::NOT_INITIALIZED;
fdb_status fs;
fs = fdb_iterator_seek_to_max(fdbItr);
(void)fs;
return Status();
}
Status TableFile::Iterator::close() {
if (fdbItr) {
fdb_iterator_close(fdbItr);
fdbItr = nullptr;
}
if (fdbSnap) {
fdb_kvs_close(fdbSnap);
fdbSnap = nullptr;
}
if (tFileSnap) {
tFile->returnSnapshot(tFileSnap);
tFileSnap = nullptr;
}
return Status();
}
}; // namespace jungle
| 28.600559 | 82 | 0.589608 | tobecontinued |
9507904b1fb189149a19d72c8f53d83af78b66a9 | 547 | hpp | C++ | src/canvas.hpp | kalsipp/SDL-turbo-enigma | f5883e5b766ea701a5343bc36d21d078eeba0e79 | [
"MIT"
] | null | null | null | src/canvas.hpp | kalsipp/SDL-turbo-enigma | f5883e5b766ea701a5343bc36d21d078eeba0e79 | [
"MIT"
] | null | null | null | src/canvas.hpp | kalsipp/SDL-turbo-enigma | f5883e5b766ea701a5343bc36d21d078eeba0e79 | [
"MIT"
] | null | null | null | #pragma once
#include <SDL2/SDL.h>
#include <SDL2/SDL_image.h>
#include <SDL2/SDL_ttf.h>
#include <SDL2/SDL_mixer.h>
#include "logger.hpp"
#include "texture.hpp"
class Texture;
class Canvas{
public:
Canvas();
~Canvas();
void addTexture(Texture * );
void paint();
void clear();
SDL_Surface * getSurface();
SDL_Renderer * getRenderer();
private:
bool init();
Logger * m_log = NULL;
SDL_Window * m_window = NULL;
SDL_Surface * m_surface = NULL;
SDL_Renderer * m_renderer = NULL;
int m_screen_width = 1000;
int m_screen_height = 1000;
}; | 21.038462 | 34 | 0.709324 | kalsipp |
950ab831ac04f4f87452086c91d9aa28a35b4d4a | 341 | cpp | C++ | Sandbox/test.cpp | pr0me7heu2/CSCI_121 | 001cdb29b94b94b29417a494e4d0fca4af38c138 | [
"Apache-2.0"
] | 2 | 2020-09-15T04:03:40.000Z | 2020-10-14T01:37:32.000Z | Sandbox/test.cpp | pr0me7heu2/CSCI_121 | 001cdb29b94b94b29417a494e4d0fca4af38c138 | [
"Apache-2.0"
] | null | null | null | Sandbox/test.cpp | pr0me7heu2/CSCI_121 | 001cdb29b94b94b29417a494e4d0fca4af38c138 | [
"Apache-2.0"
] | null | null | null | //
// Created by bryan on 2/10/19.
//
#include <iostream>
#include <cassert>
int main()
{
using namespace std;
int n1, n2;
cout << "how many" << endl;
cin >> n1 >> n2;
//assert(n1 > 0);
cout <<"n1 is not bigger than zero." << endl;
cout << "here they are." << endl;
cout << n1 << n2;
return 0;
} | 12.62963 | 49 | 0.513196 | pr0me7heu2 |
950f5165090f49a1c8c9e98b5fc7957bac9ab7b0 | 749 | hpp | C++ | Feather/src/Feather.hpp | pedrolmcastro/feather | e4581fb119706505dfcb25b5d982b47ee21e0746 | [
"Apache-2.0"
] | null | null | null | Feather/src/Feather.hpp | pedrolmcastro/feather | e4581fb119706505dfcb25b5d982b47ee21e0746 | [
"Apache-2.0"
] | null | null | null | Feather/src/Feather.hpp | pedrolmcastro/feather | e4581fb119706505dfcb25b5d982b47ee21e0746 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Precompiled.hpp"
#include "Core/Time.hpp"
#include "Core/Event.hpp"
#include "Core/Layer.hpp"
#include "Core/Application.hpp"
#include "Debug/Log.hpp"
#include "Debug/Assert.hpp"
#include "Input/Key.hpp"
#include "Input/Input.hpp"
#include "Input/Mouse.hpp"
#include "Math/Bool.hpp"
#include "Math/Matrix.hpp"
#include "Math/Vector.hpp"
#include "Math/Quaternion.hpp"
// TODO: Review Render Exposition
#include "Render/Index.hpp"
#include "Render/Vertex.hpp"
#include "Render/Shader.hpp"
#include "Render/Window.hpp"
#include "Render/Command.hpp"
#include "Render/Texture.hpp"
#include "Scene/Scene.hpp"
#include "Scene/Entity.hpp"
#include "Scene/Viewer.hpp"
#include "Scene/Component.hpp"
#include "Core/Entry.hpp"
| 20.243243 | 33 | 0.740988 | pedrolmcastro |
95118a49614bed4fafb6a6e67d39fc851ec2076e | 2,230 | cpp | C++ | 201804/dec201804_1.cpp | jibsen/aocpp2018 | fdaa1adfd12963ef8f530bbe3f8542843486e1c9 | [
"MIT"
] | 2 | 2020-04-26T17:31:29.000Z | 2020-10-03T00:54:15.000Z | 201804/dec201804_1.cpp | jibsen/aocpp2018 | fdaa1adfd12963ef8f530bbe3f8542843486e1c9 | [
"MIT"
] | null | null | null | 201804/dec201804_1.cpp | jibsen/aocpp2018 | fdaa1adfd12963ef8f530bbe3f8542843486e1c9 | [
"MIT"
] | null | null | null | //
// Advent of Code 2018, day 4, part one
//
#include <algorithm>
#include <array>
#include <cstdio>
#include <iostream>
#include <map>
#include <numeric>
#include <string>
#include <vector>
using Event = std::pair<long long, std::string>;
using SleepSchedule = std::vector<std::pair<int, int>>;
bool get_timestamp(long long &ts)
{
int year, month, day, hour, minute;
if (scanf("[%d-%d-%d %d:%d] ", &year, &month, &day, &hour, &minute) == 5) {
ts = year * 100000000LL
+ month * 1000000LL
+ day * 10000LL
+ hour * 100LL
+ minute;
return true;
}
return false;
}
std::vector<Event> read_events()
{
std::vector<Event> events;
std::string line;
long long ts = 0;
while (get_timestamp(ts) && std::getline(std::cin, line)) {
events.emplace_back(ts, line);
}
return events;
}
std::map<int, SleepSchedule> get_guard_sleep_schedules(const std::vector<Event> &events)
{
std::map<int, SleepSchedule> schedules;
int guard = -1;
std::vector<int> minutes;
for (const auto &[ts, line] : events) {
if (auto p = line.find('#'); p != std::string::npos) {
guard = std::stoi(line.substr(p + 1));
continue;
}
minutes.push_back(ts % 100);
if (minutes.size() == 2) {
schedules[guard].push_back({minutes[0], minutes[1]});
minutes.clear();
}
}
return schedules;
}
int minute_most_asleep(const SleepSchedule &schedule)
{
std::array<int, 60> sleep_freq = {};
for (const auto &period : schedule) {
for (int i = period.first; i < period.second; ++i) {
sleep_freq[i]++;
}
}
return std::distance(sleep_freq.begin(), std::max_element(sleep_freq.begin(), sleep_freq.end()));
}
int main()
{
auto events = read_events();
std::sort(events.begin(), events.end());
auto schedules = get_guard_sleep_schedules(events);
int max_time = std::numeric_limits<int>::min();
int max_guard = -1;
for (const auto &[guard, schedule] : schedules) {
int time = std::accumulate(schedule.begin(), schedule.end(), 0,
[](int acc, const auto &period) {
return acc + (period.second - period.first);
});
if (time > max_time) {
max_time = time;
max_guard = guard;
}
}
std::cout << max_guard * minute_most_asleep(schedules[max_guard]) << '\n';
return 0;
}
| 20.09009 | 98 | 0.638565 | jibsen |
951782d3d7d71d56e25e75b5d02271395d29c296 | 812 | cc | C++ | LeetCode/Hard/waterTrap.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | LeetCode/Hard/waterTrap.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | LeetCode/Hard/waterTrap.cc | ChakreshSinghUC/CPPCodes | d82a3f467303566afbfcc927b660b0f7bf7c0432 | [
"MIT"
] | null | null | null | #include <iostream>
#include <vector>
using namespace std;
class Solution
{
public:
int trap(vector<int> &height)
{
int left = 0, right = height.size() - 1;
int ans = 0;
int left_max = 0, right_max = 0;
while (left < right)
{
if (height[left] < height[right])
{
height[left] >= left_max ? (left_max = height[left]) : ans += (left_max - height[left]);
++left;
}
else
{
height[right] >= right_max ? (right_max = height[right]) : ans += (right_max - height[right]);
--right;
}
}
};
int main()
{
Solution o;
vector<int> h = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
cout << o.trap(h);
} | 26.193548 | 110 | 0.439655 | ChakreshSinghUC |
951908950b6eb51f9420cfd4e39482a835803e3a | 3,169 | cc | C++ | whale/src/dbi/x86_64/instruction_rewriter_x86_64.cc | QiYueColdRain/whale | ab62303c8146d7a79f89c7b26a6625cbcf65b0f9 | [
"Apache-2.0"
] | 1,333 | 2019-01-27T03:46:51.000Z | 2022-03-31T05:28:23.000Z | whale/src/dbi/x86_64/instruction_rewriter_x86_64.cc | QiYueColdRain/whale | ab62303c8146d7a79f89c7b26a6625cbcf65b0f9 | [
"Apache-2.0"
] | 59 | 2019-02-01T09:57:25.000Z | 2022-03-09T09:40:33.000Z | whale/src/dbi/x86_64/instruction_rewriter_x86_64.cc | QiYueColdRain/whale | ab62303c8146d7a79f89c7b26a6625cbcf65b0f9 | [
"Apache-2.0"
] | 309 | 2019-01-29T11:41:14.000Z | 2022-03-31T06:10:38.000Z | #include "dbi/x86/instruction_rewriter_x86.h"
#include "instruction_rewriter_x86_64.h"
#include "dbi/x86/distorm/distorm.h"
#include "dbi/x86/distorm/mnemonics.h"
#define __ masm_->
namespace whale {
namespace x86_64 {
constexpr static const unsigned kRIP_index = 74;
void X86_64InstructionRewriter::Rewrite() {
u1 *instructions = code_->GetInstructions<u1>();
int pos = 0;
size_t count = code_->GetCount<u1>();
u8 pc = cfg_pc_;
while (pos < code_->GetCount<u1>()) {
u1 *current = instructions + pos;
_DInst insn = Decode(current, count - pos, 1);
pc += insn.size;
switch (insn.opcode) {
case I_MOV:
Rewrite_Mov(current, pc, insn);
break;
case I_CALL:
Rewrite_Call(current, pc, insn);
break;
case I_JMP:
Rewrite_Jmp(current, pc, insn);
break;
case I_JECXZ:
case I_JRCXZ:
Rewrite_JRCXZ(current, pc, insn);
break;
default:
EmitCode(current, insn.size);
break;
}
pos += insn.size;
}
}
void X86_64InstructionRewriter::Rewrite_Mov(u1 *current, u8 pc, _DInst insn) {
_Operand op0 = insn.ops[0];
_Operand op1 = insn.ops[1];
if (op0.type == O_REG && op1.type == O_SMEM && op1.index == kRIP_index) {
// mov rd, nword ptr [rip + disp]
int rd = insn.ops[0].index % 16;
__ movq(rd, Immediate(pc + insn.disp));
__ movl(rd, Address(rd, 0));
} else if (op0.type == O_SMEM && op1.type == O_IMM && op1.index == kRIP_index) {
// mov nword ptr [rip + disp], imm
__ pushq(RAX);
__ movq(RAX, Immediate(pc + insn.disp));
if (op1.size <= 32) {
__ movl(Address(RAX, 0), Immediate(insn.imm.dword));
} else {
__ movq(Address(RAX, 0), Immediate(insn.imm.qword));
}
__ popq(RAX);
} else {
EmitCode(current, insn.size);
}
}
void X86_64InstructionRewriter::Rewrite_Call(u1 *current, u8 pc, _DInst insn) {
_Operand op = insn.ops[0];
if (op.type == O_PC) {
__ movq(R11, Immediate(pc + insn.imm.qword));
__ call(R11);
} else {
EmitCode(current, insn.size);
}
}
void X86_64InstructionRewriter::Rewrite_Jmp(u1 *current, u8 pc, _DInst insn) {
_Operand op = insn.ops[0];
if (op.type == O_PC) {
__ movq(R11, Immediate(pc + insn.imm.qword));
__ jmp(R11);
} else {
EmitCode(current, insn.size);
}
}
void X86_64InstructionRewriter::Rewrite_JRCXZ(u1 *current, u8 pc, _DInst insn) {
bool rewritten = false;
u8 pcrel_address = pc + insn.imm.qword;
if (pcrel_address >= tail_pc_) {
NearLabel true_label, false_label;
__ jrcxz(&true_label);
__ jmp(&false_label);
__ Bind(&true_label);
__ movq(R11, Immediate(pcrel_address));
__ jmp(R11);
__ Bind(&false_label);
rewritten = true;
}
if (!rewritten) {
EmitCode(current, insn.size);
}
}
} // namespace x86
} // namespace whale
| 28.294643 | 84 | 0.561691 | QiYueColdRain |
951a7b5a163b16a75c84f4de27a1baff6d6ef171 | 3,697 | cpp | C++ | src/Subsystems/Mechanisms.cpp | 3197Software/2018Season | 5454ea97234ee5bf63b434302744c40785262356 | [
"MIT"
] | 3 | 2018-04-06T14:28:50.000Z | 2018-04-06T14:33:27.000Z | src/Subsystems/Mechanisms.cpp | 3197Software/2018Season | 5454ea97234ee5bf63b434302744c40785262356 | [
"MIT"
] | null | null | null | src/Subsystems/Mechanisms.cpp | 3197Software/2018Season | 5454ea97234ee5bf63b434302744c40785262356 | [
"MIT"
] | 1 | 2019-01-20T07:57:38.000Z | 2019-01-20T07:57:38.000Z | #include "Mechanisms.h"
#include "../Commands/AuxiliaryMotors.h"
#include "../RobotMap.h"
#include <math.h>
#include "WPILib.h"
#include "ctre/Phoenix.h"
#define MAXRPM 534
#define LARGE_AMOUNT_OF_CURRENT 50
#define PEAK_CLAW_CURRENT 5
Mechanisms::Mechanisms() :
Subsystem("AuxiliaryMotors") {
winchA = new WPI_TalonSRX(5);
winchB = new WPI_TalonSRX(6);
claw = new WPI_TalonSRX(7);
elevatorWinch = new WPI_TalonSRX(8);
elevatorClawA = new WPI_TalonSRX(9);
elevatorClawB = new WPI_TalonSRX(10);
elevatorClawB->Follow(*elevatorClawA);
elevatorClawB->SetInverted(true);
winchB->Follow(*winchA);
}
void Mechanisms::InitDefaultCommand() {
SetDefaultCommand(new AuxiliaryMotors());
maxObservedClawCurrent = 0;
}
void Mechanisms::Winch(float speed) {
winchA->Set(speed);
SmartDashboard::PutNumber("Winch Current", winchA->GetOutputCurrent());
}
void Mechanisms::Claw(float speed) {
claw->Set(speed);
SmartDashboard::PutNumber("Claw Current", claw->GetOutputCurrent());
}
void Mechanisms::ElevatorWinch(float speed) {
elevatorWinch->Set(speed);
// SmartDashboard::PutNumber("Elevator Winch Encoder",
// elevatorWinch->GetSensorCollection().GetQuadraturePosition());
SmartDashboard::PutNumber("Winch Current",
elevatorWinch->GetOutputCurrent());
}
void Mechanisms::ElevatorClaw(float speed) {
elevatorClawA->Set(speed);
float currentA = elevatorClawA->GetOutputCurrent();
float currentB = elevatorClawB->GetOutputCurrent();
if (currentA > maxObservedClawCurrent)
maxObservedClawCurrent = currentA;
if(currentB > maxObservedClawCurrent)
maxObservedClawCurrent =currentB;
SmartDashboard::PutNumber("Max ElevatorClaw Current", maxObservedClawCurrent);
SmartDashboard::PutNumber("ElevatorClawA Current", currentA);
SmartDashboard::PutNumber("ElevatorClawB Current", currentB);
}
bool Mechanisms::ClawRetractLim() {
bool trip = 0 != claw->GetSensorCollection().IsFwdLimitSwitchClosed();
// SmartDashboard::PutBoolean("Claw Forward Limit (retract)", trip);
return trip;
}
bool Mechanisms::ClawGrabLim() {
bool trip = 0 != claw->GetSensorCollection().IsRevLimitSwitchClosed();
// SmartDashboard::PutBoolean("Claw Reverse Limit (grab)", trip);
return trip;
}
bool Mechanisms::ElevatorClawBotLim() {
bool trip = 0
!= elevatorClawA->GetSensorCollection().IsRevLimitSwitchClosed();
// SmartDashboard::PutBoolean("Elevator Claw Forward Limit (bot)", trip);
return trip;
}
bool Mechanisms::ElevatorClawTopLim() {
bool trip = 0
!= elevatorClawA->GetSensorCollection().IsFwdLimitSwitchClosed();
// SmartDashboard::PutBoolean("Elevator Claw Reverse Limit (top)", trip);
return trip;
}
bool Mechanisms::ElevatorWinchForwardLimit() {
bool trip = 0
!= elevatorWinch->GetSensorCollection().IsFwdLimitSwitchClosed();
// SmartDashboard::PutBoolean("Elevator Winch Forward Limit (bot)", trip);
return trip;
}
bool Mechanisms::ElevatorWinchReverseLimit() {
bool trip = 0
!= elevatorWinch->GetSensorCollection().IsRevLimitSwitchClosed();
// SmartDashboard::PutBoolean("Elevator Winch Reverse Limit (top)", trip);
return trip;
}
void Mechanisms::UpdateCurrent() {
float clawCurrent = claw->GetOutputCurrent();
SmartDashboard::PutNumber("Claw Current", clawCurrent);
float winchCurrentA = winchA->GetOutputCurrent();
SmartDashboard::PutNumber("Winch A Current", winchCurrentA);
float winchCurrentB = winchB->GetOutputCurrent();
SmartDashboard::PutNumber("Winch B Current", winchCurrentB);
float eleClawCurrent = elevatorClawA->GetOutputCurrent();
SmartDashboard::PutNumber("Ele Claw Current", eleClawCurrent);
float eleWinchCurrent = elevatorWinch->GetOutputCurrent();
SmartDashboard::PutNumber("Ele Winch Current", eleWinchCurrent);
}
| 29.34127 | 79 | 0.760887 | 3197Software |
951d9f59a64e608eb91f1ff4f913522fd8eed1db | 1,701 | hpp | C++ | src/Data/GradedNote.hpp | Subject38/jujube | 664b995cc65fa6045433b4837d765c62fe6490b4 | [
"MIT"
] | 19 | 2020-02-28T20:34:12.000Z | 2022-01-28T20:18:25.000Z | src/Data/GradedNote.hpp | Subject38/jujube | 664b995cc65fa6045433b4837d765c62fe6490b4 | [
"MIT"
] | 7 | 2019-10-22T09:43:16.000Z | 2022-03-12T00:15:13.000Z | src/Data/GradedNote.hpp | Subject38/jujube | 664b995cc65fa6045433b4837d765c62fe6490b4 | [
"MIT"
] | 5 | 2019-10-22T08:14:57.000Z | 2021-03-13T06:32:04.000Z | #pragma once
#include <optional>
#include <SFML/System/Time.hpp>
#include "../Resources/Marker.hpp"
#include "Note.hpp"
namespace Data {
enum class Judgement {
Perfect,
Great,
Good,
Poor,
Miss,
};
bool judgement_breaks_combo(Judgement j);
Resources::MarkerAnimation judgement_to_animation(Judgement j);
Judgement delta_to_judgement(const sf::Time& delta);
Judgement release_to_judgement(const sf::Time& duration_held, const sf::Time& note_duration, const int tail_length);
struct TimedJudgement {
TimedJudgement() : delta(sf::Time::Zero), judgement(Judgement::Miss) {};
TimedJudgement(const sf::Time& d, const Judgement& j) : delta(d), judgement(j) {};
explicit TimedJudgement(const sf::Time& t) : delta(t), judgement(delta_to_judgement(t)) {};
explicit TimedJudgement(
const sf::Time& duration_held,
const sf::Time& t,
const sf::Time& duration,
const int tail_length
) :
delta(t),
judgement(release_to_judgement(duration_held, duration, tail_length))
{};
sf::Time delta = sf::Time::Zero;
Judgement judgement = Judgement::Miss;
};
struct GradedNote : Data::Note {
GradedNote() = default;
GradedNote(const Data::Note& n) : Note::Note(n) {};
GradedNote(const Data::Note& n, const sf::Time& t) : Note::Note(n), tap_judgement(t) {};
GradedNote(const Data::Note& n, const TimedJudgement& t) : Note::Note(n), tap_judgement(t) {};
std::optional<TimedJudgement> tap_judgement = {};
std::optional<TimedJudgement> long_release = {};
};
}
| 32.711538 | 120 | 0.623163 | Subject38 |
951ed4e530557eab827025ca97ae5acb3333b393 | 937 | cc | C++ | src/common/gm_apply_compiler_stage.cc | messinguelethomas/modified_green_marl | fc05b5e2bf7bf131015478f39d54c84e49d1239a | [
"DOC"
] | 58 | 2015-02-06T00:50:43.000Z | 2021-12-03T07:13:13.000Z | src/common/gm_apply_compiler_stage.cc | messinguelethomas/modified_green_marl | fc05b5e2bf7bf131015478f39d54c84e49d1239a | [
"DOC"
] | 1 | 2022-01-19T19:04:09.000Z | 2022-01-19T19:04:09.000Z | src/common/gm_apply_compiler_stage.cc | messinguelethomas/modified_green_marl | fc05b5e2bf7bf131015478f39d54c84e49d1239a | [
"DOC"
] | 16 | 2015-02-18T01:30:57.000Z | 2021-01-09T03:59:33.000Z | #include "gm_frontend.h"
bool gm_apply_compiler_stage(std::list<gm_compile_step*>& LIST) {
bool is_okay = true;
std::list<gm_compile_step*>::iterator I;
int i = 0;
// for each compilation step
for (I = LIST.begin(); I != LIST.end(); I++, i++) {
gm_compile_step* step = (*I);
gm_begin_minor_compiler_stage(i + 1, step->get_description());
is_okay = gm_apply_all_proc(step) && is_okay;
gm_end_minor_compiler_stage();
if (!is_okay) break;
}
return is_okay;
}
bool gm_apply_all_proc(gm_compile_step* org) {
bool is_okay = true;
// apply to every procedure
FE.prepare_proc_iteration();
ast_procdef* p;
while ((p = FE.get_next_proc()) != NULL) {
gm_compile_step* step = org->get_instance();
step->process(p);
bool okay = step->is_okay();
is_okay = is_okay && okay;
delete step;
}
return is_okay;
}
| 24.025641 | 70 | 0.607257 | messinguelethomas |
9522e8d08863f9aa4c49cf3229343e65b9f4b1a9 | 4,997 | cpp | C++ | Cpp/ACM/2019NAQ/zLeak.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | Cpp/ACM/2019NAQ/zLeak.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | Cpp/ACM/2019NAQ/zLeak.cpp | kchevali/OnlineJudge | c1d1894078fa45eef05c8785aba29758d9adf0c6 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
typedef long long l;
#define fpp(i, a, b) for (i = a; i < b; i++)
#define PB emplace_back
#define C cout <<
#define E << "\n"
#define _ << " " <<
#define gc getchar_unlocked
#define fmm(i, a, b) for (i = b; i-- > a;)
#define v(t) vector<t>
typedef double o;
#define dc(x) cout << fixed << setprecision(x) <<
#define MID(x, y) x + (y - x) / 2
#define iinf 100000000000LL
const double pi = 2 * acos(0.0);
const double EPS = 1e-6;
#define count __builtin_popcountll // number of 'on' bits in long long
#define trail __builtin_ffsll // index of first 'on' (1-64)
#define lead __builtin_clzll // index of last 'on' (1-64)
#define bit(x, b) bitset<b>(x).to_string() // prints x with b bits
#define xx first
#define yy second
// #define v(t) pair<t,t>
// TYPES
typedef v(l) vl;
typedef v(vl) vvl;
typedef pair<l, l> ll;
typedef v(ll) vll;
typedef v(vll) vvll;
typedef pair<bool, bool> bb;
typedef v(bool) vb;
typedef v(vb) vvb;
typedef v(bb) vbb;
typedef v(o) vo;
typedef v(vo) vvo;
typedef pair<o, o> oo;
typedef v(oo) voo;
typedef v(voo) vvoo;
typedef pair<o, l> ol;
typedef v(ol) vol;
typedef v(vol) vvol;
typedef unsigned long long ul;
typedef v(ul) vul;
typedef v(vul) vvul;
typedef pair<ul, ul> ull;
typedef v(ull) vull;
typedef v(double) vd;
typedef v(vd) vvd;
typedef pair<double, double> dd;
typedef v(dd) vdd;
typedef v(string) vs;
typedef v(vs) vvs;
typedef pair<string, string> ss;
typedef v(ss) vss;
// DATA STRUCTURES
typedef priority_queue<ll, vll, less<ll>> pql; // min out
typedef priority_queue<ll, vll, greater<ll>> pqg; // max out
typedef queue<l> ql;
//---------------------------------------------------------------DEBUGGING
#define con(x, a, b) \
if (x < a || x >= b) cerr << "Out of Bounds: " << #x << endl;
#define arr(x) \
C "["; \
for (auto &y : x) C y << " "; \
C "]" E;
#define db(args...) \
{ \
string _s = #args; \
replace(_s.begin(), _s.end(), ',', ' '); \
stringstream _ss(_s); \
istream_iterator<string> _it(_ss); \
err(_it, args); \
cerr E; \
}
void err(istream_iterator<string> it) {}
template <typename T, typename... Args>
void err(istream_iterator<string> it, T a, Args... args) {
cerr << *it << " = " << a << " ";
err(++it, args...);
}
void tokenize() {
string line, token;
while (getline(cin, line)) {
cout << line << "\n";
stringstream ss(line);
while (ss >> token) {
cout << "Token: " << token << "\n";
}
}
}
//---------------------------------------------------------------Sorting
// sort(v.begin(), v.end(), [](const auto &a, const auto &b) {
// return a.first == b.first ? a.second > b.second : a.first < b.first;
// });
void read(l &x) {
l c = gc();
x = 0;
int neg = 0;
for (; ((c < 48 || c > 57) && c != '-'); c = gc())
;
if (c == '-') {
neg = 1;
c = gc();
}
for (; c > 47 && c < 58; c = gc()) {
x = (x << 1) + (x << 3) + c - 48;
}
if (neg) x = -x;
}
const l N = 510;
vll adj[N];
l dis[N];
l r[N];
bool vis[N];
bool isRepair[N];
struct edge {
l b, w, rem;
bool operator<(edge a) const { return w > a.w; }
};
edge make_e(l b, l w, l rem) {
edge start;
start.b = b;
start.w = w;
start.rem = rem;
return start;
}
l n, m, t, d;
void dijkstra(l source, l n) {
for (l i = 0; i < n; i++) {
dis[i] = iinf;
vis[i] = 0;
r[i] = 0;
}
priority_queue<edge> pq; // w, node
dis[source] = 0;
pq.push(make_e(source, 0, d));
while (!pq.empty()) {
auto curr = pq.top();
pq.pop();
l a = curr.b, W = curr.w;
l rem = (isRepair[a] ? d : curr.rem);
// cout << "POP: " << a << " size: " << adj[a].size() << "\n";
// if (vis[a]) continue;
vis[a] = true;
for (l i = 0; i < adj[a].size(); i++) {
l b = adj[a][i].second, w = adj[a][i].first;
// cout << "\n";
// db(a, b, W, w, rem);
if ((W + w < dis[b] || rem - w > r[b]) && rem >= w) {
dis[b] = min(dis[b], w + W);
r[b] = max(r[b], rem - w);
// cout << "ADDING TO QUEUE:" << b << "\n";
pq.push(make_e(b, w + W, rem - w));
}
}
}
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin >> n >> m >> t >> d;
for (l i = 0; i < n; i++) {
isRepair[i] = false;
adj[i] = vll();
}
for (l i = 0; i < t; i++) {
l a;
cin >> a;
a--;
isRepair[a] = true;
}
for (l i = 0; i < m; i++) {
l a, b, w;
cin >> a >> b >> w;
a--;
b--;
adj[a].emplace_back(make_pair(w, b));
adj[b].emplace_back(make_pair(w, a));
}
dijkstra(0, n);
cout << (dis[n - 1] == iinf ? "stuck" : to_string(dis[n - 1])) << "\n";
}
/*
2 1 0 1
1 2 1
5 5 1 5
2
1 2 6
2 3 1
3 5 1
1 4 2
4 5 4
4 4 1 10
2
1 2 10
2 3 1
1 3 2
3 4 9
*/ | 21.538793 | 79 | 0.484691 | kchevali |
9525abcbf47687d65ffc49ab5cfe3f1b1fc363cd | 8,377 | cpp | C++ | Tests/Source/UnitTests/ElementDocument.cpp | aquawicket/RmlUi | d56f17e49ca2ee88aadeb304228cd1eae14e3f51 | [
"MIT"
] | null | null | null | Tests/Source/UnitTests/ElementDocument.cpp | aquawicket/RmlUi | d56f17e49ca2ee88aadeb304228cd1eae14e3f51 | [
"MIT"
] | null | null | null | Tests/Source/UnitTests/ElementDocument.cpp | aquawicket/RmlUi | d56f17e49ca2ee88aadeb304228cd1eae14e3f51 | [
"MIT"
] | null | null | null | /*
* This source file is part of RmlUi, the HTML/CSS Interface Middleware
*
* For the latest information, see http://github.com/mikke89/RmlUi
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
* Copyright (c) 2019 The RmlUi Team, and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
#include "../Common/Mocks.h"
#include "../Common/TestsShell.h"
#include <RmlUi/Core/Context.h>
#include <RmlUi/Core/Element.h>
#include <RmlUi/Core/ElementDocument.h>
#include <RmlUi/Core/Factory.h>
#include <doctest.h>
#include <algorithm>
using namespace Rml;
static const String document_focus_rml = R"(
<rml>
<head>
<link type="text/rcss" href="/assets/rml.rcss"/>
<link type="text/rcss" href="/assets/invader.rcss"/>
<style>
button {
display: inline-block;
tab-index: auto;
}
:focus {
image-color: #af0;
}
:disabled {
image-color: #666;
}
.hide {
visibility: hidden;
}
.nodisplay {
display: none;
}
</style>
</head>
<body id="body" onload="something">
<input type="checkbox" id="p1"/> P1
<label><input type="checkbox" id="p2"/> P2</label>
<p>
<input type="checkbox" id="p3"/><label for="p3"> P3</label>
</p>
<p class="nodisplay">
<input type="checkbox" id="p4"/><label for="p4"> P4</label>
</p>
<input type="checkbox" id="p5"/> P5
<p>
<input type="checkbox" id="p6" disabled/><label for="p6"> P6</label>
</p>
<div>
<label><input type="checkbox" id="p7"/> P7</label>
<label class="hide"><input type="checkbox" id="p8"/> P8</label>
<label><button id="p9"> P9</button></label>
<label><input type="checkbox" id="p10"/> P10</label>
</div>
<div id="container">
<p> Deeply nested
<span>
<input type="checkbox" id="p11"/> P11
</span>
<input type="checkbox" id="p12"/> P12
</p>
<input type="checkbox" id="p13"/> P13
</div>
</body>
</rml>
)";
static const String focus_forward = "p1 p2 p3 p5 p7 p9 p10 p11 p12 p13";
TEST_SUITE_BEGIN("ElementDocument");
TEST_CASE("Focus")
{
Context* context = TestsShell::GetContext();
REQUIRE(context);
ElementDocument* document = context->LoadDocumentFromMemory(document_focus_rml);
REQUIRE(document);
document->Show();
context->Update();
context->Render();
TestsShell::RenderLoop();
SUBCASE("Tab order")
{
StringList ids;
StringUtilities::ExpandString(ids, focus_forward, ' ');
REQUIRE(!ids.empty());
document->Focus();
SUBCASE("Forward")
{
for(const String& id : ids)
{
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == id);
}
// Wrap around
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == ids[0]);
}
SUBCASE("Reverse")
{
std::reverse(ids.begin(), ids.end());
for (const String& id : ids)
{
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == id);
}
// Wrap around (reverse)
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == ids[0]);
}
}
SUBCASE("Tab to document")
{
Element* element = document->GetElementById("p13");
REQUIRE(element);
element->Focus();
document->SetProperty("tab-index", "auto");
document->UpdateDocument();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "body");
}
SUBCASE("Tab from container element")
{
Element* container = document->GetElementById("container");
REQUIRE(container);
container->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "p11");
container->Focus();
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "p10");
}
SUBCASE("Single element")
{
document->SetProperty("tab-index", "none");
document->SetInnerRML(R"(<input type="checkbox" id="p1"/> P1)");
document->UpdateDocument();
document->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "p1");
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "p1");
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "p1");
document->SetProperty("tab-index", "auto");
document->UpdateDocument();
document->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "p1");
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "body");
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "p1");
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "body");
}
SUBCASE("Single, non-tabable element")
{
document->SetProperty("tab-index", "none");
document->SetInnerRML(R"(<div id="child"/>)");
document->UpdateDocument();
Element* child = document->GetChild(0);
document->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "body");
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "body");
child->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "child");
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "child");
document->SetProperty("tab-index", "auto");
document->UpdateDocument();
document->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "body");
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "body");
child->Focus();
context->ProcessKeyDown(Input::KI_TAB, 0);
CHECK(context->GetFocusElement()->GetId() == "body");
child->Focus();
context->ProcessKeyDown(Input::KI_TAB, Input::KM_SHIFT);
CHECK(context->GetFocusElement()->GetId() == "body");
}
document->Close();
TestsShell::ShutdownShell();
}
TEST_CASE("Load")
{
namespace tl = trompeloeil;
constexpr auto BODY_TAG = "body";
Context* context = TestsShell::GetContext();
REQUIRE(context);
MockEventListener mockEventListener;
MockEventListenerInstancer mockEventListenerInstancer;
tl::sequence sequence;
REQUIRE_CALL(mockEventListenerInstancer, InstanceEventListener("something", tl::_))
.WITH(_2->GetTagName() == BODY_TAG)
.IN_SEQUENCE(sequence)
.LR_RETURN(&mockEventListener);
ALLOW_CALL(mockEventListener, OnAttach(tl::_));
ALLOW_CALL(mockEventListener, OnDetach(tl::_));
REQUIRE_CALL(mockEventListener, ProcessEvent(tl::_))
.WITH(_1.GetId() == EventId::Load && _1.GetTargetElement()->GetTagName() == BODY_TAG)
.IN_SEQUENCE(sequence);
Factory::RegisterEventListenerInstancer(&mockEventListenerInstancer);
ElementDocument* document = context->LoadDocumentFromMemory(document_focus_rml);
REQUIRE(document);
document->Close();
TestsShell::ShutdownShell();
}
TEST_CASE("ReloadStyleSheet")
{
Context* context = TestsShell::GetContext();
ElementDocument* document = context->LoadDocument("basic/demo/data/demo.rml");
// There should be no warnings when reloading style sheets.
document->ReloadStyleSheet();
document->Close();
TestsShell::ShutdownShell();
}
TEST_SUITE_END();
| 28.886207 | 87 | 0.694282 | aquawicket |
95292ec38078ffd19f5b93f7713115960dc1251a | 4,047 | cpp | C++ | zero_python/debug_event.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 2 | 2018-03-19T23:27:47.000Z | 2018-06-24T16:15:19.000Z | zero_python/debug_event.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | null | null | null | zero_python/debug_event.cpp | cristivlas/zerobugs | 5f080c8645b123d7887fd8a64f60e8d226e3b1d5 | [
"BSL-1.0"
] | 1 | 2021-11-28T05:39:05.000Z | 2021-11-28T05:39:05.000Z | //
// $Id$
//
// -------------------------------------------------------------------------
// This file is part of ZeroBugs, Copyright (c) 2010 Cristian L. Vlasceanu
//
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
// -------------------------------------------------------------------------
//
#include <iostream>
#include <stdexcept>
#include <boost/python.hpp>
#include "generic/lock.h"
#include "zdk/check_ptr.h"
#include "zdk/get_pointer.h"
#include "debug_event.h"
using namespace boost;
using namespace boost::python;
Mutex DebugEvent::mutex_;
std::vector<int> DebugEvent::pendingCalls_;
static const uint64_t traceSyscalls =
Debugger::OPT_TRACE_SYSCALLS | Debugger::OPT_BREAK_ON_SYSCALLS;
DebugEvent::DebugEvent(Type type, Thread* thread, int syscallNum)
: type_(type)
, thread_(thread)
, syscall_(syscallNum)
{
if (syscallNum >= 0)
{
// we get one notification when the Syscall enters, and
// another one when it completes; we match them with the
// pendingCalls_ stack
Lock<Mutex> lock(mutex_);
if (!pendingCalls_.empty() && (pendingCalls_.back() == syscallNum))
{
type_ = SYSCALL_LEAVE;
}
else
{
pendingCalls_.push_back(syscallNum);
}
}
else if (type == SYSCALL_ENTER)
{
type_ = SYSCALL_LEAVE;
}
if (type_ == SYSCALL_LEAVE)
{
Lock<Mutex> lock(mutex_);
if (pendingCalls_.empty())
{
#if 0
throw std::logic_error("SYSCALL_LEAVE: empty pending stack");
#else
std::cerr << "SYSCALL_LEAVE: empty pending calls" << std::endl;
#endif
}
else
{
assert(syscall_ == pendingCalls_.back() || syscall_ < 0);
syscall_ = pendingCalls_.back();
pendingCalls_.pop_back();
}
}
}
DebugEvent::~DebugEvent() throw()
{
try
{
switch (type_)
{
case SYSCALL_ENTER:
// syscall tracing got turned off?
if (thread_ &&
(thread_->debugger()->options() & traceSyscalls) == 0
)
{
Lock<Mutex> lock(mutex_);
assert(!pendingCalls_.empty());
pendingCalls_.pop_back();
}
break;
default:
break;
}
}
catch (...)
{
}
}
int DebugEvent::syscall() const
{
switch (type_)
{
case SYSCALL_ENTER:
case SYSCALL_LEAVE:
break;
default:
PyErr_SetString(PyExc_RuntimeError, "syscall: incorrect event type");
}
return syscall_;
}
void export_debug_event()
{
register_ptr_to_python<RefPtr<DebugEvent> >();
scope in_DebugEvent =
class_<DebugEvent, bases<>, noncopyable>("DebugEvent")
.def("process", &DebugEvent::process,
"return the target process on which the event occurred"
)
.def("syscall", &DebugEvent::syscall)
.def("type", &DebugEvent::type, "return the type of the event")
.def("thread", &DebugEvent::thread,
"return the target thread on which the event occurred"
)
;
enum_<DebugEvent::Type>("Type")
.value("Update", DebugEvent::UPDATE)
.value("None", DebugEvent::NONE)
.value("Signal", DebugEvent::SIGNAL)
.value("Breakpoint", DebugEvent::BREAKPOINT)
.value("BreakPoint", DebugEvent::BREAKPOINT)
.value("Finished", DebugEvent::FINISHED)
.value("SysCallEnter", DebugEvent::SYSCALL_ENTER)
.value("SysCallLeave", DebugEvent::SYSCALL_LEAVE)
.value("SingleStep", DebugEvent::SINGLE_STEP)
.value("EvalComplete", DebugEvent::EVAL_COMPLETE)
.value("DoneStepping", DebugEvent::DONE_STEPPING)
.value("CallReturned", DebugEvent::RETURNED)
;
}
// vim: tabstop=4:softtabstop=4:expandtab:shiftwidth=4
| 26.279221 | 77 | 0.56684 | cristivlas |
95296d8a08b2f3b48a7d9a22611c2407146b59ac | 29,516 | cpp | C++ | src/pcre_check/PcreChecker.cpp | petabi/regexbench | 51f602266bb1a509a8362cd9647b65cb24ea7100 | [
"Apache-2.0"
] | 11 | 2017-04-19T03:01:13.000Z | 2020-08-03T05:21:31.000Z | src/pcre_check/PcreChecker.cpp | petabi/regexbench | 51f602266bb1a509a8362cd9647b65cb24ea7100 | [
"Apache-2.0"
] | 14 | 2016-05-24T00:20:42.000Z | 2019-02-11T18:36:36.000Z | src/pcre_check/PcreChecker.cpp | petabi/regexbench | 51f602266bb1a509a8362cd9647b65cb24ea7100 | [
"Apache-2.0"
] | 4 | 2017-04-03T08:03:11.000Z | 2019-08-20T04:48:50.000Z | #include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <memory>
#include <sstream>
#include <utility>
#include <vector>
#include <boost/program_options.hpp>
#include <hs/hs_compile.h>
#include <hs/hs_runtime.h>
#define PCRE2_CODE_UNIT_WIDTH 8
#include <pcre2.h>
#include <rematch/compile.h>
#include <rematch/execute.h>
#include <rematch/rematch.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "../Rule.h"
#include "PcreChecker.h"
#include "litesql_helper.h"
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::vector;
using regexbench::Rule;
namespace po = boost::program_options;
// pcre_check namespace aliases
using pcre_check::PcreCheckDb;
using DbRule = pcre_check::Rule;
using pcre_check::Engine;
using pcre_check::Grammar;
using pcre_check::Pattern;
using pcre_check::Result;
using pcre_check::Test;
using pcre_check::TestGrammar;
using pcre_check::TestResult;
// litesql namespace aliases
using litesql::Blob;
using litesql::Eq;
using litesql::Except;
using litesql::NotFound;
using litesql::select;
const std::string PcreChecker::DB_PREFIX = "database=";
const char* PcreChecker::TMP_TEMPLATE = "tmpdbfilXXXXXX";
PcreChecker::PcreChecker(const std::string& dbFileNam, bool debug)
: dbFile(dbFileNam)
{
if (dbFile.empty()) {
tmpFile = std::make_unique<char[]>(strlen(TMP_TEMPLATE) + 1);
strncpy(tmpFile.get(), TMP_TEMPLATE, strlen(TMP_TEMPLATE));
int tmpFd = mkstemp(tmpFile.get());
if (tmpFd == -1)
throw std::runtime_error("Could not make temporary db file");
close(tmpFd);
dbFile = tmpFile.get();
}
dbFile = DB_PREFIX + dbFile;
pDb = std::make_unique<PcreCheckDb>("sqlite3", dbFile);
if (debug)
pDb->verbose = true;
if (pDb->needsUpgrade())
pDb->upgrade();
}
PcreChecker::~PcreChecker()
{
pDb.reset();
// make sure db is closed before unlinking temp file
if (tmpFile)
unlink(tmpFile.get());
}
int PcreChecker::attach(std::string& dbFileNam, bool debug)
{
if (pDb) {
dbFileNam = dbFile.substr(dbFile.find(DB_PREFIX) + DB_PREFIX.size());
return -1;
}
if (dbFileNam.empty())
throw std::runtime_error("Must specify DB file name to attach");
dbFile = DB_PREFIX + dbFileNam;
pDb = std::make_unique<PcreCheckDb>("sqlite3", dbFile);
if (debug)
pDb->verbose = true;
if (pDb->needsUpgrade())
pDb->upgrade();
return 0;
}
void PcreChecker::detach()
{
pDb.reset();
if (tmpFile) {
unlink(tmpFile.get());
tmpFile.reset();
}
}
void PcreChecker::setupDb(const std::string& jsonIn)
{
if (jsonIn.empty())
throw std::runtime_error("input json file is not specified");
std::ifstream jsonFile(jsonIn);
// Parse json file
Json::Value root;
try {
jsonFile >> root;
} catch (const std::exception& e) {
cerr << "json file parse error" << e.what() << endl;
return;
}
try {
pDb->begin();
// Parse 'rules'
json2DbTables<DbRule, JsonFillNameContentDesc<DbRule>>("rules", root);
// Parse 'grammars'
json2DbTables<Grammar, JsonFillNameContentDesc<Grammar>>("grammars", root);
// Parse 'patterns'
json2DbTables<Pattern, JsonFillNameContentDesc<Pattern>>("patterns", root);
json2DbTables<Engine, JsonFillNameOnly<Engine>>("engines", root);
json2DbTables<Result, JsonFillNameOnly<Result>>("results", root);
// Parse 'tests' (involves tables 'Test', 'TestGrammar', 'TestResult')
jsonTests2DbTables(root);
pDb->commit(); // commit changes
} catch (Except e) {
cerr << e << endl;
throw std::runtime_error(
"litesql exception caught setting up db from json input");
}
updateDbMeta();
}
int PcreChecker::clearResultTable()
{
if (!pDb) {
cerr << "DB must be attached beforehand" << endl;
return -1;
}
pDb->query("DELETE FROM " + TestResult::table__);
pDb->commit();
return 0;
}
void PcreChecker::updateDbMeta()
{
// scan result ids
dbMeta.resMatchId =
select<Result>(*pDb, Result::Name == "match").one().id.value();
dbMeta.resNomatchId =
select<Result>(*pDb, Result::Name == "nomatch").one().id.value();
dbMeta.resErrorId =
select<Result>(*pDb, Result::Name == "error").one().id.value();
// engine ids
dbMeta.engRematchId =
select<Engine>(*pDb, Engine::Name == "rematch").one().id.value();
dbMeta.engHyperscanId =
select<Engine>(*pDb, Engine::Name == "hyperscan").one().id.value();
dbMeta.engPcreId =
select<Engine>(*pDb, Engine::Name == "pcre").one().id.value();
// transform DB rules into regexbench rules (most importantly with id info)
dbMeta.rules.clear();
vector<DbRule> dbRules = select<DbRule>(*pDb).orderBy(DbRule::Id).all();
for (const auto& dbRule : dbRules) {
auto blob = dbRule.content.value();
size_t len = blob.length();
auto temp = std::make_unique<char[]>(len);
blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0);
std::string line(temp.get(), len);
dbMeta.rules.emplace_back(
regexbench::Rule(line, static_cast<size_t>(dbRule.id.value())));
}
dbMeta.needsUpdate = 0;
}
void PcreChecker::checkDb()
{
if (dbMeta.needsUpdate)
updateDbMeta();
try {
pDb->begin();
checkRematch();
checkHyperscan();
checkPcre();
pDb->commit(); // commit changes
} catch (Except e) {
cerr << e << endl;
throw std::runtime_error(
"litesql exception caught updating match result to db");
}
}
std::array<int, 3> PcreChecker::checkSingle(const std::string& rule,
const std::string& data, bool hex)
{
std::array<int, 3> results;
std::string trans;
const std::string* pData = &data;
regexbench::Rule singleRule(rule, 1);
if (hex) {
trans = convertHexData(data);
pData = &trans;
}
results[0] = checkRematch(&singleRule, pData);
results[1] = checkHyperscan(&singleRule, pData);
results[2] = checkPcre(&singleRule, pData);
return results;
}
void PcreChecker::writeJson(const std::string& jsonOut)
{
if (jsonOut.empty())
throw std::runtime_error("input json file is not specified");
if (!pDb)
throw std::runtime_error("DB must have been attached for writing json");
std::ofstream jsonFile(jsonOut);
Json::Value root;
// rules
dbTables2Json<DbRule, JsonFillNameContentDesc<DbRule>>("rules", root);
// patterns
dbTables2Json<Pattern, JsonFillNameContentDesc<Pattern>>("patterns", root);
// grammars
dbTables2Json<Grammar, JsonFillNameContentDesc<Grammar>>("grammars", root);
// engines & results
dbTables2Json<Engine, JsonFillNameOnly<Engine>>("engines", root);
dbTables2Json<Result, JsonFillNameOnly<Result>>("results", root);
// tests : these are tricky parts because we should mix rule, pattern, grammar
// and result altogether
dbTables2JsonTests(root); // TBD
// time to write to a file
Json::StreamWriterBuilder wbuilder;
jsonFile << Json::writeString(wbuilder, root);
jsonFile << endl;
}
void PcreChecker::dbTables2JsonTests(Json::Value& root) const
{
JoinedSource<Test, DbRule, Pattern, Result> source(*pDb,
true); // use left join
// result table can be empty (because expectid can be 0)
source.joinCond(Eq(DbRule::Id, Test::Ruleid))
.joinCond(Eq(Pattern::Id, Test::Patternid))
.joinCond(Eq(Result::Id, Test::Expectid));
auto tuples = source.orderBy(Test::Id).query();
for (const auto& t : tuples) {
Json::Value entry;
const auto& test = std::get<Test>(t);
const auto& rule = std::get<DbRule>(t);
const auto& pattern = std::get<Pattern>(t);
const auto& result = std::get<Result>(t); // result can be empty
entry["rule"] = rule.name.value();
entry["pattern"] = pattern.name.value();
if (result.id.value() > 0)
entry["expect"] = result.name.value();
// now check TestGrammar
JoinedSource<TestGrammar, Grammar> grSource(*pDb, true);
auto grs = grSource.joinCond(Eq(Grammar::Id, TestGrammar::Grammarid))
.orderBy(Grammar::Id)
.query(TestGrammar::Testid == test.id.value());
for (const auto& gr : grs)
entry["grammars"].append(std::get<Grammar>(gr).name.value());
// now check TestResult
JoinedSource<TestResult, Result, Engine> trSource(*pDb, true);
auto trs = trSource.joinCond(Eq(Result::Id, TestResult::Resultid))
.joinCond(Eq(Engine::Id, TestResult::Engineid))
.orderBy(TestResult::Id)
.query(TestResult::Testid == test.id.value());
for (const auto& tr : trs)
entry["result"][std::get<Engine>(tr).name.value()] =
std::get<Result>(tr).name.value();
root["tests"].append(entry);
}
}
void PcreChecker::jsonTests2DbTables(const Json::Value& root)
{
const auto& tests = root["tests"];
if (tests.empty())
return;
if (!tests.isArray()) {
throw std::runtime_error("tests should be array type");
}
std::map<string, int> engineMap;
std::map<string, int> resultMap;
std::vector<Engine> engineSels = select<Engine>(*pDb).all();
for (const auto& e : engineSels) {
engineMap[e.name.value()] = e.id.value();
}
std::vector<Result> resultSels = select<Result>(*pDb).all();
for (const auto& r : resultSels) {
resultMap[r.name.value()] = r.id.value();
}
// rule => DbRule name
// pattern => Pattern name
// grammars => array of Grammar names
// result => json object of result for each engine
for (const auto& test : tests) {
if (test["rule"].empty() || !test["rule"].isString())
throw std::runtime_error("test rule name must be specfied (as string)");
if (test["pattern"].empty() || !test["pattern"].isString())
throw std::runtime_error(
"test pattern name must be specfied (as string)");
const auto& rulename = test["rule"].asString();
const auto& patternname = test["pattern"].asString();
// find ids of rule, pattern, grammar
int rule_id;
int pattern_id;
try {
const auto& rule_db =
select<DbRule>(*pDb, DbRule::Name == rulename).one();
rule_id = rule_db.id.value();
const auto& pattern_db =
select<Pattern>(*pDb, Pattern::Name == patternname).one();
pattern_id = pattern_db.id.value();
} catch (NotFound e) {
cerr << "rule(" << rulename << ") or pattern(" << patternname
<< ") not found (" << e << ") (skipping this)" << endl;
continue;
}
// find expect id : this is actually a result id
int expect_id = 0;
if (!test["expect"].empty() && test["expect"].isString()) {
if (resultMap.count(test["expect"].asString()))
expect_id = resultMap.at(test["expect"].asString());
}
// now rule_id, pattern_id, expect_id are valid
// find out Test table id if any or create one
int test_id;
try {
const auto& test_db =
select<Test>(*pDb,
Test::Ruleid == rule_id && Test::Patternid == pattern_id)
.one();
test_id = test_db.id.value();
} catch (NotFound) {
Test test_db(*pDb);
test_db.ruleid = rule_id;
test_db.patternid = pattern_id;
test_db.expectid = expect_id;
test_db.update();
test_id = test_db.id.value();
}
std::vector<int> grammar_ids;
if (!test["grammars"].empty()) {
const auto& grammars = test["grammars"];
for (const auto& gr : grammars) {
if (!gr.isString())
continue; // TODO
try {
const auto& gr_db =
select<Grammar>(*pDb, Grammar::Name == gr.asString()).one();
grammar_ids.push_back(gr_db.id.value());
} catch (NotFound) {
// just register this grammar on the fly (w/o description)
Grammar new_gr(*pDb);
new_gr.name = gr.asString();
new_gr.update();
grammar_ids.push_back(new_gr.id.value());
}
}
}
for (auto gid : grammar_ids) {
try {
select<TestGrammar>(*pDb, TestGrammar::Testid == test_id &&
TestGrammar::Grammarid == gid)
.one();
} catch (NotFound) {
TestGrammar tg(*pDb);
tg.testid = test_id;
tg.grammarid = gid;
tg.update();
}
}
std::map<string, string> verdictMap;
if (!test["result"].empty() && test["result"].isObject()) {
const auto& result = test["result"];
for (const auto& engine : result.getMemberNames()) {
if (engineMap.find(engine) != engineMap.end()) { // engine names
const auto& verdict = result[engine].asString();
if (result[engine].isString() &&
resultMap.find(verdict) != resultMap.end()) {
verdictMap[engine] = verdict;
} else {
cerr << "result for engine " << engine << " set incorrectly"
<< endl;
}
} else {
cerr << "unknown engine " << engine << " for result" << endl;
}
}
}
for (auto e2V : verdictMap) {
try {
auto resEntry =
*(select<TestResult>(*pDb, TestResult::Testid == test_id &&
TestResult::Engineid ==
engineMap[e2V.first])
.cursor());
resEntry.resultid = resultMap[e2V.second];
resEntry.update();
} catch (NotFound) {
TestResult resEntry(*pDb);
resEntry.testid = test_id;
resEntry.engineid = engineMap[e2V.first];
resEntry.resultid = resultMap[e2V.second];
resEntry.update();
}
}
}
}
static int onMatch(unsigned id, unsigned long long from, unsigned long long to,
unsigned flags, void* ctx)
{
auto res = static_cast<rematchResult*>(ctx);
res->pushId(id);
return 0; // continue till there's no more match
}
int PcreChecker::checkRematch(const regexbench::Rule* singleRule,
const std::string* data)
{
int result = 0;
int engineId = dbMeta.engRematchId;
if (singleRule && !data)
throw std::runtime_error(
"If rule was given data should also be given in single check mode");
rematch2_t* matcher;
rematch_scratch_t* scratch;
rematch_match_context_t* context;
vector<const char*> rematchExps;
vector<unsigned> rematchMods;
vector<unsigned> rematchIds;
if (singleRule) {
const auto& rule = *singleRule;
rematchExps.push_back(rule.getRegexp().data());
rematchIds.push_back(static_cast<unsigned>(rule.getID()));
uint32_t opt = 0;
if (rule.isSet(regexbench::MOD_CASELESS))
opt |= REMATCH_MOD_CASELESS;
if (rule.isSet(regexbench::MOD_MULTILINE))
opt |= REMATCH_MOD_MULTILINE;
if (rule.isSet(regexbench::MOD_DOTALL))
opt |= REMATCH_MOD_DOTALL;
rematchMods.push_back(opt);
} else {
for (const auto& rule : dbMeta.rules) {
rematchExps.push_back(rule.getRegexp().data());
rematchIds.push_back(static_cast<unsigned>(rule.getID()));
uint32_t opt = 0;
if (rule.isSet(regexbench::MOD_CASELESS))
opt |= REMATCH_MOD_CASELESS;
if (rule.isSet(regexbench::MOD_MULTILINE))
opt |= REMATCH_MOD_MULTILINE;
if (rule.isSet(regexbench::MOD_DOTALL))
opt |= REMATCH_MOD_DOTALL;
rematchMods.push_back(opt);
}
}
matcher = rematch2_compile_with_shortcuts(
rematchIds.data(), rematchExps.data(), rematchMods.data(),
rematchIds.size(), false /* reduce */
,
false);
if (!matcher)
throw std::runtime_error("Could not build REmatch2 matcher.");
scratch = rematch_alloc_scratch(matcher);
context = rematch2ContextInit(matcher);
if (context == nullptr)
throw std::runtime_error("Could not initialize context.");
rematchResult matchRes;
// prepare data (only need the data specified in Test table)
int lastPid = -1;
if (singleRule) { // single test mode
matchRes.clear(); // must be done to get right result
int ret = rematch_scan_block(matcher, data->data(), data->size(), context,
scratch, onMatch, &matchRes);
if (ret == MREG_FAILURE)
cerr << "rematch failed during matching for a packet" << endl;
result = matchRes.isMatched() ? 1 : 0;
} else {
vector<Test> tests = select<Test>(*pDb).orderBy(Test::Patternid).all();
for (const auto& t : tests) {
if (t.patternid.value() == lastPid)
continue;
lastPid = t.patternid.value();
// we can get excption below
// (which should not happen with a db correctly set up)
const auto& pattern = select<Pattern>(*pDb, Pattern::Id == lastPid).one();
auto blob = pattern.content.value();
size_t len = blob.length();
auto temp = std::make_unique<char[]>(len);
blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0);
// for debugging
// cout << "pattern " << lastPid << " content : " << string(temp.get(),
// len)
// << endl;
// set up Rule-id to (Test-id, result) mapping to be used for TestResult
// update
std::map<int, std::pair<int, bool>> rule2TestMap;
auto curTest = select<Test>(*pDb, Test::Patternid == lastPid).cursor();
for (; curTest.rowsLeft(); curTest++) {
rule2TestMap[(*curTest).ruleid.value()] =
std::make_pair((*curTest).id.value(), false);
}
// do match
matchRes.clear(); // must be done to get right result
int ret = rematch_scan_block(matcher, temp.get(), len, context, scratch,
onMatch, &matchRes);
if (ret == MREG_FAILURE)
cerr << "rematch failed during matching for a packet" << endl;
if (matchRes.isMatched()) {
// for debugging
// cout << "pattern " << lastPid;
// cout << " matched rules :" << endl;
for (auto id : matchRes) {
// for debugging
// cout << " " << id;
if (rule2TestMap.count(static_cast<int>(id)) > 0)
rule2TestMap[static_cast<int>(id)].second = true;
}
} else {
cout << "pattern " << lastPid << " has no match" << endl;
}
// cout << endl;
rematch2ContextClear(context, true);
// for debugging
// cout << "Matched rule and test id for pattern id " << lastPid << endl;
// for (const auto& p : rule2TestMap) {
// cout << " rule id " << p.first << " test id " << p.second.first
// << " matched? " << p.second.second << endl;
//}
for (const auto& p : rule2TestMap) {
try {
auto cur =
*(select<TestResult>(*pDb, TestResult::Testid == p.second.first &&
TestResult::Engineid == engineId)
.cursor());
cur.resultid =
(p.second.second ? dbMeta.resMatchId : dbMeta.resNomatchId);
cur.update();
// for debugging
// cout << " TestResult id " << cur.id << " updated to result "
// << cur.resultid << "(" << p.second.second << ")" << endl;
} catch (NotFound) {
TestResult res(*pDb);
res.testid = p.second.first;
res.engineid = engineId;
res.resultid =
(p.second.second ? dbMeta.resMatchId : dbMeta.resNomatchId);
res.update();
}
}
} // for loop for Test table entries
}
// clean-up of REmatch related objects
rematch_free_scratch(scratch);
rematch2ContextFree(context);
rematch2Free(matcher);
return result;
}
static int hsOnMatch(unsigned int, unsigned long long, unsigned long long,
unsigned int, void* ctx)
{
size_t& nmatches = *static_cast<size_t*>(ctx);
nmatches++;
return 0;
}
int PcreChecker::checkHyperscan(const regexbench::Rule* singleRule,
const std::string* data)
{
if (singleRule && !data)
throw std::runtime_error(
"If rule was given data should also be given in single check mode");
int result = 0;
int engineId = dbMeta.engHyperscanId;
hs_database_t* hsDb = nullptr;
hs_scratch_t* hsScratch = nullptr;
// hs_platform_info_t hsPlatform;
hs_compile_error_t* hsErr = nullptr;
if (singleRule) {
const auto& rule = *singleRule;
unsigned flag = HS_FLAG_ALLOWEMPTY;
if (rule.isSet(regexbench::MOD_CASELESS))
flag |= HS_FLAG_CASELESS;
if (rule.isSet(regexbench::MOD_MULTILINE))
flag |= HS_FLAG_MULTILINE;
if (rule.isSet(regexbench::MOD_DOTALL))
flag |= HS_FLAG_DOTALL;
auto resCompile = hs_compile(rule.getRegexp().data(), flag, HS_MODE_BLOCK,
nullptr, &hsDb, &hsErr);
if (resCompile == HS_SUCCESS) {
auto resAlloc = hs_alloc_scratch(hsDb, &hsScratch);
if (resAlloc != HS_SUCCESS) {
hs_free_database(hsDb);
throw std::bad_alloc();
}
} else {
hs_free_compile_error(hsErr);
return -1;
}
size_t nmatches = 0;
hs_scan(hsDb, data->data(), static_cast<unsigned>(data->size()), 0,
hsScratch, hsOnMatch, &nmatches);
result = (nmatches > 0) ? 1 : 0;
hs_free_scratch(hsScratch);
hs_free_database(hsDb);
return result;
}
auto cur = select<Test>(*pDb).orderBy(Test::Ruleid).cursor();
if (!cur.rowsLeft()) // nothing to do
return result;
// map of Test-id to Result-id
std::map<int, int> test2ResMap;
// Entering into this loop, please make sure that
// rules and cur are all sorted w.r.t rule id
// (only, cur can have multiple occurrences of rule id's)
// and also rules be super set of the iteration cur points to
// in terms of containing rule id's.
// Below outer and inner loop is assuming the above constraints
// to prevent multiple rule compile for a same rule
for (const auto& rule : dbMeta.rules) {
if (!cur.rowsLeft())
break;
if (rule.getID() != static_cast<size_t>((*cur).ruleid.value()))
continue;
unsigned flag = HS_FLAG_ALLOWEMPTY;
if (rule.isSet(regexbench::MOD_CASELESS))
flag |= HS_FLAG_CASELESS;
if (rule.isSet(regexbench::MOD_MULTILINE))
flag |= HS_FLAG_MULTILINE;
if (rule.isSet(regexbench::MOD_DOTALL))
flag |= HS_FLAG_DOTALL;
hsDb = nullptr;
hsScratch = nullptr;
hsErr = nullptr;
auto resCompile = hs_compile(rule.getRegexp().data(), flag, HS_MODE_BLOCK,
nullptr, &hsDb, &hsErr);
if (resCompile == HS_SUCCESS) {
auto resAlloc = hs_alloc_scratch(hsDb, &hsScratch);
if (resAlloc != HS_SUCCESS) {
hs_free_database(hsDb);
throw std::bad_alloc();
}
} else
hs_free_compile_error(hsErr);
for (; cur.rowsLeft() &&
rule.getID() == static_cast<size_t>((*cur).ruleid.value());
cur++) {
if (resCompile != HS_SUCCESS) {
test2ResMap[(*cur).id.value()] = dbMeta.resErrorId;
continue;
}
const auto& pattern =
select<Pattern>(*pDb, Pattern::Id == (*cur).patternid).one();
auto blob = pattern.content.value();
size_t len = blob.length();
auto temp = std::make_unique<char[]>(len);
blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0);
size_t nmatches = 0;
hs_scan(hsDb, temp.get(), static_cast<unsigned>(len), 0, hsScratch,
hsOnMatch, &nmatches);
test2ResMap[(*cur).id.value()] =
(nmatches > 0) ? dbMeta.resMatchId : dbMeta.resNomatchId;
}
hs_free_scratch(hsScratch);
hs_free_database(hsDb);
}
// cout << "Hyper scan result" << endl << endl;
for (const auto& p : test2ResMap) {
try {
auto curT =
*(select<TestResult>(*pDb, TestResult::Testid == p.first &&
TestResult::Engineid == engineId)
.cursor());
curT.resultid = p.second;
curT.update();
} catch (NotFound) {
TestResult res(*pDb);
res.testid = p.first;
res.engineid = engineId;
res.resultid = p.second;
res.update();
}
// for debugging
// const auto& test = select<Test>(*pDb, Test::Id == p.first).one();
// cout << "test " << test.id.value() << " (rule id " << test.ruleid.value()
// << ", pattern id " << test.patternid.value()
// << ") => result : " << p.second << endl;
}
return result;
}
int PcreChecker::checkPcre(const regexbench::Rule* singleRule,
const std::string* data)
{
if (singleRule && !data)
throw std::runtime_error(
"If rule was given data should also be given in single check mode");
int result = 0;
int engineId = dbMeta.engPcreId;
if (singleRule) {
const auto& rule = *singleRule;
PCRE2_SIZE erroffset = 0;
int errcode = 0;
pcre2_code* re =
pcre2_compile(reinterpret_cast<PCRE2_SPTR>(rule.getRegexp().data()),
PCRE2_ZERO_TERMINATED, rule.getPCRE2Options(), &errcode,
&erroffset, nullptr);
pcre2_match_data* mdata = nullptr;
if (re != nullptr) {
mdata = pcre2_match_data_create_from_pattern(re, nullptr);
} else
return -1;
int rc = pcre2_match(
re, reinterpret_cast<PCRE2_SPTR>(data->data()), data->size(), 0,
PCRE2_NOTEMPTY_ATSTART | PCRE2_NOTEMPTY, mdata, nullptr);
result = (rc >= 0) ? 1 : 0;
pcre2_code_free(re);
pcre2_match_data_free(mdata);
return result;
}
auto cur = select<Test>(*pDb).orderBy(Test::Ruleid).cursor();
if (!cur.rowsLeft()) // nothing to do
return result;
// map of Test-id to Result-id
std::map<int, int> test2ResMap;
// Entering into this loop, please make sure that
// rules and cur are all sorted w.r.t rule id
// (only, cur can have multiple occurrences of rule id's)
// and also rules be super set of the iteration cur points to
// in terms of containing rule id's.
// Below outer and inner loop is assuming the above constraints
// to prevent multiple rule compile for a same rule
for (const auto& rule : dbMeta.rules) {
if (!cur.rowsLeft())
break;
if (rule.getID() != static_cast<size_t>((*cur).ruleid.value()))
continue;
PCRE2_SIZE erroffset = 0;
int errcode = 0;
pcre2_code* re =
pcre2_compile(reinterpret_cast<PCRE2_SPTR>(rule.getRegexp().data()),
PCRE2_ZERO_TERMINATED, rule.getPCRE2Options(), &errcode,
&erroffset, nullptr);
pcre2_match_data* mdata = nullptr;
if (re != nullptr) {
mdata = pcre2_match_data_create_from_pattern(re, nullptr);
}
for (; cur.rowsLeft() &&
rule.getID() == static_cast<size_t>((*cur).ruleid.value());
cur++) {
if (re == nullptr) {
test2ResMap[(*cur).id.value()] = dbMeta.resErrorId;
continue;
}
const auto& pattern =
select<Pattern>(*pDb, Pattern::Id == (*cur).patternid).one();
auto ctype = pattern.ctype.value();
auto blob = pattern.content.value();
size_t len = blob.length();
auto temp = std::make_unique<char[]>(len);
blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0);
int rc =
pcre2_match(re, reinterpret_cast<PCRE2_SPTR>(temp.get()), len, 0,
PCRE2_NOTEMPTY_ATSTART | PCRE2_NOTEMPTY, mdata, nullptr);
test2ResMap[(*cur).id.value()] =
(rc >= 0) ? dbMeta.resMatchId : dbMeta.resNomatchId;
}
pcre2_code_free(re);
pcre2_match_data_free(mdata);
}
// cout << "PCRE match result" << endl << endl;
for (const auto& p : test2ResMap) {
try {
auto curT =
*(select<TestResult>(*pDb, TestResult::Testid == p.first &&
TestResult::Engineid == engineId)
.cursor());
curT.resultid = p.second;
curT.update();
} catch (NotFound) {
TestResult res(*pDb);
res.testid = p.first;
res.engineid = engineId;
res.resultid = p.second;
res.update();
}
// for debugging
// const auto& test = select<Test>(*pDb, Test::Id == p.first).one();
// cout << "test " << test.id.value() << " (rule id " << test.ruleid.value()
// << ", pattern id " << test.patternid.value()
// << ") => result : " << p.second << endl;
}
return result;
}
std::string convertHexData(const std::string& data)
{
size_t pos = 0;
std::string tmpStr, convCh, resultStr = data;
while ((pos = resultStr.find("\\x", pos)) != std::string::npos) {
tmpStr = resultStr.substr(pos + 2, 2);
if (hexToCh(tmpStr, convCh)) {
resultStr.erase(pos, 4);
resultStr.insert(pos, convCh);
} else {
pos += 2;
continue;
}
}
return resultStr;
}
std::string convertBlob2String(const litesql::Blob& blobConst)
{
auto blob = blobConst; // ugly but
// getData is not declared const
size_t len = blob.length();
auto temp = std::make_unique<char[]>(len);
blob.getData(reinterpret_cast<unsigned char*>(temp.get()), len, 0);
return std::string(temp.get(), len);
}
bool hexToCh(std::string& hex, std::string& conv)
{
for (auto d : hex) {
if (!isxdigit(d)) {
return false;
}
}
try {
char data = static_cast<char>(std::stoi(hex, 0, 16));
conv = std::string(1, data);
} catch (const std::exception& e) {
cerr << "hex convert fail " << e.what() << endl;
return false;
}
return true;
}
| 31.4 | 80 | 0.604926 | petabi |
952a3563cf948c4b22142babed8fe5ecfe16cd60 | 341 | cpp | C++ | src/frontg8/error.cpp | frontg8/frontg8lib | c1c6a436ae6ddd6ad15b0270ac233cd9d19f33d8 | [
"BSD-3-Clause"
] | 3 | 2016-08-29T09:17:57.000Z | 2016-10-18T05:01:25.000Z | src/frontg8/error.cpp | frontg8/frontg8lib | c1c6a436ae6ddd6ad15b0270ac233cd9d19f33d8 | [
"BSD-3-Clause"
] | null | null | null | src/frontg8/error.cpp | frontg8/frontg8lib | c1c6a436ae6ddd6ad15b0270ac233cd9d19f33d8 | [
"BSD-3-Clause"
] | null | null | null | #include "impl/error.hpp"
#include "frontg8/error.h"
extern "C"
{
FG8_DLL_EXPORT char const * fg8_error_message(fg8_error_t const error)
{
if(error)
{
return error->message.c_str();
}
return NULL;
}
FG8_DLL_EXPORT void fg8_error_destroy(fg8_error_t const error)
{
delete error;
}
}
| 14.826087 | 72 | 0.627566 | frontg8 |
952cbc7eb26169d59db76921164bf6e0e80be9be | 9,238 | cpp | C++ | test/decompiler/test_FormExpressionBuild2.cpp | joegoldin/jak-project | 9969445cf78b43745b5910a2b09dbe6672f0ec92 | [
"0BSD"
] | null | null | null | test/decompiler/test_FormExpressionBuild2.cpp | joegoldin/jak-project | 9969445cf78b43745b5910a2b09dbe6672f0ec92 | [
"0BSD"
] | null | null | null | test/decompiler/test_FormExpressionBuild2.cpp | joegoldin/jak-project | 9969445cf78b43745b5910a2b09dbe6672f0ec92 | [
"0BSD"
] | null | null | null | #include "gtest/gtest.h"
#include "FormRegressionTest.h"
using namespace decompiler;
// tests stack variables
TEST_F(FormRegressionTest, MatrixPMult) {
std::string func =
"sll r0, r0, 0\n"
" daddiu sp, sp, -112\n"
" sd ra, 0(sp)\n"
" sq s5, 80(sp)\n"
" sq gp, 96(sp)\n"
" or gp, a0, r0\n"
" daddiu s5, sp, 16\n"
" sq r0, 0(s5)\n"
" sq r0, 16(s5)\n"
" sq r0, 32(s5)\n"
" sq r0, 48(s5)\n"
" lw t9, matrix*!(s7)\n"
" or a0, s5, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" lq v1, 0(s5)\n"
" sq v1, 0(gp)\n"
" lq v1, 16(s5)\n"
" sq v1, 16(gp)\n"
" lq v1, 32(s5)\n"
" sq v1, 32(gp)\n"
" lq v1, 48(s5)\n"
" sq v1, 48(gp)\n"
" or v0, gp, r0\n"
" ld ra, 0(sp)\n"
" lq gp, 96(sp)\n"
" lq s5, 80(sp)\n"
" jr ra\n"
" daddiu sp, sp, 112";
std::string type = "(function matrix matrix matrix matrix)";
std::string expected =
"(begin\n"
" (let ((s5-0 (new (quote stack) (quote matrix))))\n"
" (set! (-> s5-0 vector 0 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 1 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 2 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 3 quad) (the-as uint128 0))\n"
" (matrix*! s5-0 arg1 arg2)\n"
" (set! (-> arg0 vector 0 quad) (-> s5-0 vector 0 quad))\n"
" (set! (-> arg0 vector 1 quad) (-> s5-0 vector 1 quad))\n"
" (set! (-> arg0 vector 2 quad) (-> s5-0 vector 2 quad))\n"
" (set! (-> arg0 vector 3 quad) (-> s5-0 vector 3 quad))\n"
" )\n"
" arg0\n"
" )";
test_with_stack_vars(func, type, expected,
"[\n"
" [16, \"matrix\"]\n"
" ]");
}
// TODO- this should also work without the cast, but be uglier.
TEST_F(FormRegressionTest, VectorXQuaternionWithCast) {
std::string func =
"sll r0, r0, 0\n"
" daddiu sp, sp, -112\n"
" sd ra, 0(sp)\n"
" sq s5, 80(sp)\n"
" sq gp, 96(sp)\n"
" or gp, a0, r0\n"
" daddiu s5, sp, 16\n"
" sq r0, 0(s5)\n"
" sq r0, 16(s5)\n"
" sq r0, 32(s5)\n"
" sq r0, 48(s5)\n"
" lw t9, quaternion->matrix(s7)\n"
" or a0, s5, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" daddu v1, r0, s5\n"
" lq v1, 0(v1)\n"
" sq v1, 0(gp)\n"
" or v0, gp, r0\n"
" ld ra, 0(sp)\n"
" lq gp, 96(sp)\n"
" lq s5, 80(sp)\n"
" jr ra\n"
" daddiu sp, sp, 112";
std::string type = "(function quaternion quaternion quaternion)";
std::string expected =
"(begin\n"
" (let ((s5-0 (new (quote stack) (quote matrix))))\n"
" (set! (-> s5-0 vector 0 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 1 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 2 quad) (the-as uint128 0))\n"
" (set! (-> s5-0 vector 3 quad) (the-as uint128 0))\n"
" (quaternion->matrix s5-0 arg1)\n"
" (set! (-> arg0 vec quad) (-> (the-as (pointer uint128) (-> s5-0 data)) 0))\n"
" )\n"
" arg0\n"
" )";
test_with_stack_vars(func, type, expected,
"[\n"
" [16, \"matrix\"]\n"
" ]",
"[[10, \"v1\", \"(pointer uint128)\"]]");
}
TEST_F(FormRegressionTest, EliminateFloatDeadSet) {
std::string func =
"sll r0, r0, 0\n"
"L32:\n"
" daddiu sp, sp, -16\n"
" sd fp, 8(sp)\n"
" or fp, t9, r0\n"
" lwu v1, 4(a0)\n"
" mtc1 f0, v1\n"
" cvt.s.w f1, f0\n"
//" lwc1 f0, L83(fp)\n"
" mtc1 f0, r0\n"
" lw a1, *display*(s7)\n"
" ld a1, 780(a1)\n"
" divu a1, v1\n"
" mfhi v1\n"
" mtc1 f2, v1\n"
" cvt.s.w f2, f2\n"
" lwc1 f3, 0(a0)\n"
" add.s f2, f2, f3\n"
" div.s f3, f2, f1\n"
" cvt.w.s f3, f3\n"
" cvt.s.w f3, f3\n"
" mul.s f3, f3, f1\n"
" sub.s f2, f2, f3\n"
" div.s f1, f2, f1\n"
" mul.s f0, f0, f1\n"
//" lwc1 f1, L84(fp)\n"
" mtc1 f1, r0\n"
//" lwc1 f2, L83(fp)\n"
" mtc1 f2, r0\n"
" lwc1 f3, 12(a0)\n"
" mul.s f2, f2, f3\n"
" sub.s f1, f1, f2\n"
//" lwc1 f2, L84(fp)\n"
" mtc1 f2, r0\n"
//" lwc1 f3, L83(fp)\n"
" mtc1 f3, r0\n"
" lwc1 f4, 8(a0)\n"
" mul.s f3, f3, f4\n"
" sub.s f2, f2, f3\n"
//" lwc1 f3, L84(fp)\n"
" mtc1 f3, r0\n"
" add.s f3, f3, f1\n"
" c.lt.s f0, f3\n"
" bc1t L33\n"
" sll r0, r0, 0\n"
" mtc1 f0, r0\n"
" mfc1 v1, f0\n"
" beq r0, r0, L36\n"
" sll r0, r0, 0\n"
"L33:\n"
//" lwc1 f3, L84(fp)\n"e
" mtc1 f3, r0\n"
" c.lt.s f3, f0\n"
" bc1f L34\n"
" sll r0, r0, 0\n"
//" lwc1 f2, L84(fp)\n"
" mtc1 f2, r0\n"
//" lwc1 f3, L82(fp)\n"
" mtc1 f3, r0\n"
" add.s f0, f3, f0\n"
" div.s f0, f0, f1\n"
" sub.s f0, f2, f0\n"
" mfc1 v1, f0\n"
" beq r0, r0, L36\n"
" sll r0, r0, 0\n"
"L34:\n"
" c.lt.s f0, f2\n"
" bc1t L35\n"
" sll r0, r0, 0\n"
//" lwc1 f0, L84(fp)\n"
" mtc1 f0, r0\n"
" mfc1 v1, f0\n"
" beq r0, r0, L36\n"
" sll r0, r0, 0\n"
"L35:\n"
" div.s f0, f0, f2\n"
" mfc1 v1, f0\n"
"L36:\n"
" mfc1 v0, f0\n"
" ld fp, 8(sp)\n"
" jr ra\n"
" daddiu sp, sp, 16";
std::string type = "(function sync-info-paused float)";
std::string expected =
"(let* ((v1-0 (-> arg0 period))\n"
" (f1-0 (the float v1-0))\n"
" (f0-1 0.0)\n"
" (f2-2\n"
" (+\n"
" (the float (mod (-> *display* base-frame-counter) v1-0))\n"
" (-> arg0 offset)\n"
" )\n"
" )\n"
" (f0-2\n"
" (* f0-1 (/ (- f2-2 (* (the float (the int (/ f2-2 f1-0))) f1-0)) f1-0))\n"
" )\n"
" (f1-3 (- 0.0 (* 0.0 (-> arg0 pause-after-in))))\n"
" (f2-7 (- 0.0 (* 0.0 (-> arg0 pause-after-out))))\n"
" )\n"
" (cond\n"
" ((>= f0-2 (+ 0.0 f1-3))\n"
" 0.0\n"
" )\n"
" ((< 0.0 f0-2)\n"
" (- 0.0 (/ (+ 0.0 f0-2) f1-3))\n"
" )\n"
" ((>= f0-2 f2-7)\n"
" 0.0\n"
" )\n"
" (else\n"
" (/ f0-2 f2-7)\n"
" )\n"
" )\n"
" )";
test_with_stack_vars(func, type, expected, "[]");
}
TEST_F(FormRegressionTest, IterateProcessTree) {
std::string func =
"sll r0, r0, 0\n"
" daddiu sp, sp, -80\n"
" sd ra, 0(sp)\n"
" sq s3, 16(sp)\n"
" sq s4, 32(sp)\n"
" sq s5, 48(sp)\n"
" sq gp, 64(sp)\n"
" or s3, a0, r0\n"
" or gp, a1, r0\n"
" or s5, a2, r0\n"
" lwu v1, 4(s3)\n"
" andi v1, v1, 256\n"
" bnel v1, r0, L113\n"
" daddiu s4, s7, 8\n"
" or t9, gp, r0\n"
" or a0, s3, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" or s4, v0, r0\n"
"L113:\n"
" daddiu v1, s7, dead\n"
" bne s4, v1, L114\n"
" sll r0, r0, 0\n"
" or v1, s7, r0\n"
" beq r0, r0, L117\n"
" sll r0, r0, 0\n"
"L114:\n"
" lwu v1, 16(s3)\n"
" beq r0, r0, L116\n"
" sll r0, r0, 0\n"
"L115:\n"
" lwu a0, 0(v1)\n"
" lwu s3, 12(a0)\n"
" lw t9, iterate-process-tree(s7)\n"
" lwu a0, 0(v1)\n"
" or a1, gp, r0\n"
" or a2, s5, r0\n"
" jalr ra, t9\n"
" sll v0, ra, 0\n"
" or v1, s3, r0\n"
" or a0, v1, r0\n"
"L116:\n"
" bne s7, v1, L115\n"
" sll r0, r0, 0\n"
" or v1, s7, r0\n"
"L117:\n"
" or v0, s4, r0\n"
" ld ra, 0(sp)\n"
" lq gp, 64(sp)\n"
" lq s5, 48(sp)\n"
" lq s4, 32(sp)\n"
" lq s3, 16(sp)\n"
" jr ra\n"
" daddiu sp, sp, 80";
std::string type = "(function process-tree (function object object) kernel-context object)";
std::string expected =
"(let ((s4-0 (or (nonzero? (logand (-> arg0 mask) 256)) (arg1 arg0))))\n"
" (cond\n"
" ((= s4-0 (quote dead))\n"
" )\n"
" (else\n"
" (let ((v1-4 (-> arg0 child)))\n"
" (while v1-4\n"
" (let ((s3-1 (-> v1-4 0 brother)))\n"
" (iterate-process-tree (-> v1-4 0) arg1 arg2)\n"
" (set! v1-4 s3-1)\n"
" )\n"
" )\n"
" )\n"
" )\n"
" )\n"
" s4-0\n"
" )";
test_with_stack_vars(func, type, expected, "[]");
} | 28.164634 | 94 | 0.38688 | joegoldin |
9531a43f49ea66a40cc1482392f437e9a03b6849 | 7,538 | cpp | C++ | CUDA/Example/7_CUDALibraries/conjugateGradient/main.cpp | lacie-life/ProgrammingLanguageCollection | bc8487b494e8af42838e30e1ca3e40f2112477cb | [
"MIT"
] | 9 | 2016-04-06T02:48:16.000Z | 2021-01-29T23:11:05.000Z | CUDA/Example/7_CUDALibraries/conjugateGradient/main.cpp | lacie-life/ProgrammingLanguageCollection | bc8487b494e8af42838e30e1ca3e40f2112477cb | [
"MIT"
] | null | null | null | CUDA/Example/7_CUDALibraries/conjugateGradient/main.cpp | lacie-life/ProgrammingLanguageCollection | bc8487b494e8af42838e30e1ca3e40f2112477cb | [
"MIT"
] | 3 | 2017-01-11T16:34:35.000Z | 2019-08-27T15:50:30.000Z | /*
* Copyright 1993-2015 NVIDIA Corporation. All rights reserved.
*
* Please refer to the NVIDIA end user license agreement (EULA) associated
* with this source code for terms and conditions that govern your use of
* this software. Any use, reproduction, disclosure, or distribution of
* this software and related documentation outside the terms of the EULA
* is strictly prohibited.
*
*/
/*
* This sample implements a conjugate gradient solver on GPU
* using CUBLAS and CUSPARSE
*
*/
// includes, system
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
/* Using updated (v2) interfaces to cublas */
#include <cuda_runtime.h>
#include <cusparse.h>
#include <cublas_v2.h>
// Utilities and system includes
#include <helper_functions.h> // helper for shared functions common to CUDA Samples
#include <helper_cuda.h> // helper function CUDA error checking and initialization
const char *sSDKname = "conjugateGradient";
/* genTridiag: generate a random tridiagonal symmetric matrix */
void genTridiag(int *I, int *J, float *val, int N, int nz)
{
I[0] = 0, J[0] = 0, J[1] = 1;
val[0] = (float)rand()/RAND_MAX + 10.0f;
val[1] = (float)rand()/RAND_MAX;
int start;
for (int i = 1; i < N; i++)
{
if (i > 1)
{
I[i] = I[i-1]+3;
}
else
{
I[1] = 2;
}
start = (i-1)*3 + 2;
J[start] = i - 1;
J[start+1] = i;
if (i < N-1)
{
J[start+2] = i + 1;
}
val[start] = val[start-1];
val[start+1] = (float)rand()/RAND_MAX + 10.0f;
if (i < N-1)
{
val[start+2] = (float)rand()/RAND_MAX;
}
}
I[N] = nz;
}
int main(int argc, char **argv)
{
int M = 0, N = 0, nz = 0, *I = NULL, *J = NULL;
float *val = NULL;
const float tol = 1e-5f;
const int max_iter = 10000;
float *x;
float *rhs;
float a, b, na, r0, r1;
int *d_col, *d_row;
float *d_val, *d_x, dot;
float *d_r, *d_p, *d_Ax;
int k;
float alpha, beta, alpham1;
// This will pick the best possible CUDA capable device
cudaDeviceProp deviceProp;
int devID = findCudaDevice(argc, (const char **)argv);
if (devID < 0)
{
printf("exiting...\n");
exit(EXIT_SUCCESS);
}
checkCudaErrors(cudaGetDeviceProperties(&deviceProp, devID));
// Statistics about the GPU device
printf("> GPU device has %d Multi-Processors, SM %d.%d compute capabilities\n\n",
deviceProp.multiProcessorCount, deviceProp.major, deviceProp.minor);
int version = (deviceProp.major * 0x10 + deviceProp.minor);
if (version < 0x11)
{
printf("%s: requires a minimum CUDA compute 1.1 capability\n", sSDKname);
// cudaDeviceReset causes the driver to clean up all state. While
// not mandatory in normal operation, it is good practice. It is also
// needed to ensure correct operation when the application is being
// profiled. Calling cudaDeviceReset causes all profile data to be
// flushed before the application exits
cudaDeviceReset();
exit(EXIT_SUCCESS);
}
/* Generate a random tridiagonal symmetric matrix in CSR format */
M = N = 1048576;
nz = (N-2)*3 + 4;
I = (int *)malloc(sizeof(int)*(N+1));
J = (int *)malloc(sizeof(int)*nz);
val = (float *)malloc(sizeof(float)*nz);
genTridiag(I, J, val, N, nz);
x = (float *)malloc(sizeof(float)*N);
rhs = (float *)malloc(sizeof(float)*N);
for (int i = 0; i < N; i++)
{
rhs[i] = 1.0;
x[i] = 0.0;
}
/* Get handle to the CUBLAS context */
cublasHandle_t cublasHandle = 0;
cublasStatus_t cublasStatus;
cublasStatus = cublasCreate(&cublasHandle);
checkCudaErrors(cublasStatus);
/* Get handle to the CUSPARSE context */
cusparseHandle_t cusparseHandle = 0;
cusparseStatus_t cusparseStatus;
cusparseStatus = cusparseCreate(&cusparseHandle);
checkCudaErrors(cusparseStatus);
cusparseMatDescr_t descr = 0;
cusparseStatus = cusparseCreateMatDescr(&descr);
checkCudaErrors(cusparseStatus);
cusparseSetMatType(descr,CUSPARSE_MATRIX_TYPE_GENERAL);
cusparseSetMatIndexBase(descr,CUSPARSE_INDEX_BASE_ZERO);
checkCudaErrors(cudaMalloc((void **)&d_col, nz*sizeof(int)));
checkCudaErrors(cudaMalloc((void **)&d_row, (N+1)*sizeof(int)));
checkCudaErrors(cudaMalloc((void **)&d_val, nz*sizeof(float)));
checkCudaErrors(cudaMalloc((void **)&d_x, N*sizeof(float)));
checkCudaErrors(cudaMalloc((void **)&d_r, N*sizeof(float)));
checkCudaErrors(cudaMalloc((void **)&d_p, N*sizeof(float)));
checkCudaErrors(cudaMalloc((void **)&d_Ax, N*sizeof(float)));
cudaMemcpy(d_col, J, nz*sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_row, I, (N+1)*sizeof(int), cudaMemcpyHostToDevice);
cudaMemcpy(d_val, val, nz*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_x, x, N*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_r, rhs, N*sizeof(float), cudaMemcpyHostToDevice);
alpha = 1.0;
alpham1 = -1.0;
beta = 0.0;
r0 = 0.;
cusparseScsrmv(cusparseHandle,CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nz, &alpha, descr, d_val, d_row, d_col, d_x, &beta, d_Ax);
cublasSaxpy(cublasHandle, N, &alpham1, d_Ax, 1, d_r, 1);
cublasStatus = cublasSdot(cublasHandle, N, d_r, 1, d_r, 1, &r1);
k = 1;
while (r1 > tol*tol && k <= max_iter)
{
if (k > 1)
{
b = r1 / r0;
cublasStatus = cublasSscal(cublasHandle, N, &b, d_p, 1);
cublasStatus = cublasSaxpy(cublasHandle, N, &alpha, d_r, 1, d_p, 1);
}
else
{
cublasStatus = cublasScopy(cublasHandle, N, d_r, 1, d_p, 1);
}
cusparseScsrmv(cusparseHandle, CUSPARSE_OPERATION_NON_TRANSPOSE, N, N, nz, &alpha, descr, d_val, d_row, d_col, d_p, &beta, d_Ax);
cublasStatus = cublasSdot(cublasHandle, N, d_p, 1, d_Ax, 1, &dot);
a = r1 / dot;
cublasStatus = cublasSaxpy(cublasHandle, N, &a, d_p, 1, d_x, 1);
na = -a;
cublasStatus = cublasSaxpy(cublasHandle, N, &na, d_Ax, 1, d_r, 1);
r0 = r1;
cublasStatus = cublasSdot(cublasHandle, N, d_r, 1, d_r, 1, &r1);
cudaThreadSynchronize();
printf("iteration = %3d, residual = %e\n", k, sqrt(r1));
k++;
}
cudaMemcpy(x, d_x, N*sizeof(float), cudaMemcpyDeviceToHost);
float rsum, diff, err = 0.0;
for (int i = 0; i < N; i++)
{
rsum = 0.0;
for (int j = I[i]; j < I[i+1]; j++)
{
rsum += val[j]*x[J[j]];
}
diff = fabs(rsum - rhs[i]);
if (diff > err)
{
err = diff;
}
}
cusparseDestroy(cusparseHandle);
cublasDestroy(cublasHandle);
free(I);
free(J);
free(val);
free(x);
free(rhs);
cudaFree(d_col);
cudaFree(d_row);
cudaFree(d_val);
cudaFree(d_x);
cudaFree(d_r);
cudaFree(d_p);
cudaFree(d_Ax);
// cudaDeviceReset causes the driver to clean up all state. While
// not mandatory in normal operation, it is good practice. It is also
// needed to ensure correct operation when the application is being
// profiled. Calling cudaDeviceReset causes all profile data to be
// flushed before the application exits
cudaDeviceReset();
printf("Test Summary: Error amount = %f\n", err);
exit((k <= max_iter) ? 0 : 1);
}
| 28.992308 | 137 | 0.606129 | lacie-life |
95327f0344b50e233bd4726c36c37b26d2e6fe74 | 5,608 | cc | C++ | tests/client.cc | kborkows/libiqxmlrpc | 046ac8a55b1b674f7406442dee533e1ecbfbb88d | [
"BSD-2-Clause"
] | null | null | null | tests/client.cc | kborkows/libiqxmlrpc | 046ac8a55b1b674f7406442dee533e1ecbfbb88d | [
"BSD-2-Clause"
] | null | null | null | tests/client.cc | kborkows/libiqxmlrpc | 046ac8a55b1b674f7406442dee533e1ecbfbb88d | [
"BSD-2-Clause"
] | null | null | null | #define BOOST_TEST_MODULE test_client
#include <stdlib.h>
#include <openssl/md5.h>
#include <iostream>
#include <memory>
#include <boost/test/test_tools.hpp>
#include <boost/test/unit_test.hpp>
#include "libiqxmlrpc/libiqxmlrpc.h"
#include "libiqxmlrpc/http_client.h"
#include "libiqxmlrpc/http_errors.h"
#include "client_common.h"
#include "client_opts.h"
#if defined(WIN32)
#include <winsock2.h>
#endif
using namespace boost::unit_test;
using namespace iqxmlrpc;
// Global
Client_opts test_config;
Client_base* test_client = 0;
class ClientFixture {
public:
ClientFixture()
{
#if defined(WIN32)
WORD wVersionRequested;
WSADATA wsaData;
wVersionRequested = MAKEWORD(2, 2);
WSAStartup(wVersionRequested, &wsaData);
#endif
int argc = boost::unit_test::framework::master_test_suite().argc;
char** argv = boost::unit_test::framework::master_test_suite().argv;
test_config.configure(argc, argv);
test_client = test_config.create_instance();
}
};
BOOST_GLOBAL_FIXTURE( ClientFixture );
BOOST_AUTO_TEST_CASE( introspection_test )
{
BOOST_REQUIRE(test_client);
Introspection_proxy introspect(test_client);
Response retval( introspect() );
BOOST_REQUIRE_MESSAGE(!retval.is_fault(), retval.fault_string());
BOOST_TEST_MESSAGE("system.listMethods output:");
const Value& v = retval.value();
for (Array::const_iterator i = v.arr_begin(); i != v.arr_end(); ++i)
{
BOOST_TEST_MESSAGE("\t" + i->get_string());
}
}
BOOST_AUTO_TEST_CASE( auth_test )
{
BOOST_REQUIRE(test_client);
BOOST_CHECKPOINT("Successful authorization");
test_client->set_authinfo("goodman", "loooooooooooooooooongpaaaaaaaaaaaassssswwwwwwoooooord");
Response retval( test_client->execute("echo_user", 0) );
BOOST_CHECK( !retval.is_fault() );
BOOST_CHECK_EQUAL( retval.value().get_string(), "goodman" );
try {
BOOST_CHECKPOINT("Unsuccessful authorization");
test_client->set_authinfo("badman", "");
retval = test_client->execute("echo_user", 0);
} catch (const iqxmlrpc::http::Error_response& e) {
BOOST_CHECK_EQUAL(e.response_header()->code(), 401);
test_client->set_authinfo("", "");
return;
}
test_client->set_authinfo("", "");
BOOST_ERROR("'401 Unauthrozied' required");
}
BOOST_AUTO_TEST_CASE( echo_test )
{
BOOST_REQUIRE(test_client);
Echo_proxy echo(test_client);
Response retval(echo("Hello"));
BOOST_CHECK(retval.value().get_string() == "Hello");
}
BOOST_AUTO_TEST_CASE( error_method_test )
{
BOOST_REQUIRE(test_client);
Error_proxy err(test_client);
Response retval(err(""));
BOOST_CHECK(retval.is_fault());
BOOST_CHECK(retval.fault_code() == 123 && retval.fault_string() == "My fault");
}
BOOST_AUTO_TEST_CASE( get_file_test )
{
BOOST_REQUIRE(test_client);
Get_file_proxy get_file(test_client);
Response retval( get_file(1024*1024*10) ); // request 10Mb
const Value& v = retval.value();
const Binary_data& d = v["data"];
const Binary_data& m = v["md5"];
typedef const unsigned char md5char;
typedef const char strchar;
unsigned char md5[16];
MD5(reinterpret_cast<md5char*>(d.get_data().data()),
d.get_data().length(), md5);
std::auto_ptr<Binary_data> gen_md5( Binary_data::from_data(
reinterpret_cast<strchar*>(md5), sizeof(md5)) );
BOOST_TEST_MESSAGE("Recieved MD5: " + m.get_base64());
BOOST_TEST_MESSAGE("Calculated MD5: " + gen_md5->get_base64());
// "TODO: Binary_data::operator ==(const Binary_data&)");
BOOST_CHECK(gen_md5->get_base64() == m.get_base64());
}
BOOST_AUTO_TEST_CASE( stop_server )
{
if (!test_config.stop_server())
return;
BOOST_REQUIRE(test_client);
Stop_server_proxy stop(test_client);
try {
stop();
} catch (const iqnet::network_error&) {}
}
BOOST_AUTO_TEST_CASE( trace_all ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Correlation-ID"] = "123";
h["X-Span-ID"] = "456";
test_client->set_xheaders(h);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "123456");
}
BOOST_AUTO_TEST_CASE( trace_all_exec ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Correlation-ID"] = "580";
h["X-Span-ID"] = "111";
Trace_proxy trace(test_client);
Response retval(trace("", h));
BOOST_CHECK(retval.value().get_string() == "580111");
}
BOOST_AUTO_TEST_CASE( trace_all_exec_override ) {
BOOST_REQUIRE(test_client);
XHeaders gh;
gh["X-Correlation-ID"] = "123";
gh["X-Span-ID"] = "456";
test_client->set_xheaders(gh);
XHeaders h;
h["X-Span-ID"] = "111";
Trace_proxy trace(test_client);
Response retval(trace("", h));
BOOST_CHECK(retval.value().get_string() == "123111");
}
BOOST_AUTO_TEST_CASE( trace_corr ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Correlation-ID"] = "123";
test_client->set_xheaders(h);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "123");
}
BOOST_AUTO_TEST_CASE( trace_span ) {
BOOST_REQUIRE(test_client);
XHeaders h;
h["X-Span-ID"] = "456";
test_client->set_xheaders(h);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "456");
}
BOOST_AUTO_TEST_CASE( trace_no ) {
BOOST_REQUIRE(test_client);
test_client->set_xheaders(XHeaders());
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "");
}
BOOST_AUTO_TEST_CASE( trace_empty ) {
BOOST_REQUIRE(test_client);
Trace_proxy trace(test_client);
Response retval(trace(""));
BOOST_CHECK(retval.value().get_string() == "");
}
// vim:ts=2:sw=2:et
| 26.832536 | 96 | 0.709522 | kborkows |
953511a713690c1077b6f8891cdbe53b0f124127 | 9,760 | cpp | C++ | jme3-bullet-native/src/native/cpp/jmePhysicsSpace.cpp | MeFisto94/test-bot-1 | c761210e199fc2e3cae5db0b2fbf13043d8d4b48 | [
"BSD-3-Clause"
] | 3 | 2020-11-08T14:55:48.000Z | 2021-09-28T08:33:26.000Z | jme3-bullet-native/src/native/cpp/jmePhysicsSpace.cpp | MeFisto94/test-bot-1 | c761210e199fc2e3cae5db0b2fbf13043d8d4b48 | [
"BSD-3-Clause"
] | 2 | 2020-09-24T22:09:36.000Z | 2020-09-24T22:29:30.000Z | jme3-bullet-native/src/native/cpp/jmePhysicsSpace.cpp | Akshita-tewatia/jmonkeyengine | ff4b8d6a3b953a6899e31b787cb91094bced9ae6 | [
"BSD-3-Clause"
] | 1 | 2017-08-31T15:17:31.000Z | 2017-08-31T15:17:31.000Z | /*
* Copyright (c) 2009-2019 jMonkeyEngine
* 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 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "jmePhysicsSpace.h"
#include "jmeBulletUtil.h"
/**
* Author: Normen Hansen
*/
jmePhysicsSpace::jmePhysicsSpace(JNIEnv* env, jobject javaSpace) {
//TODO: global ref? maybe not -> cleaning, rather callback class?
this->javaPhysicsSpace = env->NewWeakGlobalRef(javaSpace);
this->env = env;
env->GetJavaVM(&vm);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return;
}
}
void jmePhysicsSpace::attachThread() {
#ifdef ANDROID
vm->AttachCurrentThread((JNIEnv**) &env, NULL);
#elif defined (JNI_VERSION_1_2)
vm->AttachCurrentThread((void**) &env, NULL);
#else
vm->AttachCurrentThread(&env, NULL);
#endif
}
JNIEnv* jmePhysicsSpace::getEnv() {
attachThread();
return this->env;
}
void jmePhysicsSpace::stepSimulation(jfloat tpf, jint maxSteps, jfloat accuracy) {
dynamicsWorld->stepSimulation(tpf, maxSteps, accuracy);
}
void jmePhysicsSpace::createPhysicsSpace(jfloat minX, jfloat minY, jfloat minZ, jfloat maxX, jfloat maxY, jfloat maxZ, jint broadphaseId, jboolean threading /*unused*/) {
btCollisionConfiguration* collisionConfiguration = new btDefaultCollisionConfiguration();
btVector3 min = btVector3(minX, minY, minZ);
btVector3 max = btVector3(maxX, maxY, maxZ);
btBroadphaseInterface* broadphase;
switch (broadphaseId) {
case 0: // SIMPLE
broadphase = new btSimpleBroadphase();
break;
case 1: // AXIS_SWEEP_3
broadphase = new btAxisSweep3(min, max);
break;
case 2: // AXIS_SWEEP_3_32
broadphase = new bt32BitAxisSweep3(min, max);
break;
case 3: // DBVT
broadphase = new btDbvtBroadphase();
break;
}
btCollisionDispatcher* dispatcher = new btCollisionDispatcher(collisionConfiguration);
btGImpactCollisionAlgorithm::registerAlgorithm(dispatcher);
btConstraintSolver* solver = new btSequentialImpulseConstraintSolver();
//create dynamics world
btDiscreteDynamicsWorld* world = new btDiscreteDynamicsWorld(dispatcher, broadphase, solver, collisionConfiguration);
dynamicsWorld = world;
dynamicsWorld->setWorldUserInfo(this);
broadphase->getOverlappingPairCache()->setInternalGhostPairCallback(new btGhostPairCallback());
dynamicsWorld->setGravity(btVector3(0, -9.81f, 0));
struct jmeFilterCallback : public btOverlapFilterCallback {
// return true when pairs need collision
virtual bool needBroadphaseCollision(btBroadphaseProxy* proxy0, btBroadphaseProxy * proxy1) const {
// bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
// collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
bool collides = (proxy0->m_collisionFilterGroup & proxy1->m_collisionFilterMask) != 0;
collides = collides && (proxy1->m_collisionFilterGroup & proxy0->m_collisionFilterMask);
if (collides) {
btCollisionObject* co0 = (btCollisionObject*) proxy0->m_clientObject;
btCollisionObject* co1 = (btCollisionObject*) proxy1->m_clientObject;
jmeUserPointer *up0 = (jmeUserPointer*) co0 -> getUserPointer();
jmeUserPointer *up1 = (jmeUserPointer*) co1 -> getUserPointer();
if (up0 != NULL && up1 != NULL) {
collides = (up0->group & up1->groups) != 0 || (up1->group & up0->groups) != 0;
if(collides){
jmePhysicsSpace *dynamicsWorld = (jmePhysicsSpace *)up0->space;
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
jobject javaCollisionObject0 = env->NewLocalRef(up0->javaCollisionObject);
jobject javaCollisionObject1 = env->NewLocalRef(up1->javaCollisionObject);
jboolean notifyResult = env->CallBooleanMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_notifyCollisionGroupListeners, javaCollisionObject0, javaCollisionObject1);
env->DeleteLocalRef(javaPhysicsSpace);
env->DeleteLocalRef(javaCollisionObject0);
env->DeleteLocalRef(javaCollisionObject1);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return collides;
}
collides = (bool) notifyResult;
}
//add some additional logic here that modified 'collides'
return collides;
}
return false;
}
return collides;
}
};
dynamicsWorld->getPairCache()->setOverlapFilterCallback(new jmeFilterCallback());
dynamicsWorld->setInternalTickCallback(&jmePhysicsSpace::preTickCallback, static_cast<void *> (this), true);
dynamicsWorld->setInternalTickCallback(&jmePhysicsSpace::postTickCallback, static_cast<void *> (this));
if (gContactStartedCallback == NULL) {
gContactStartedCallback = &jmePhysicsSpace::contactStartedCallback;
}
}
void jmePhysicsSpace::preTickCallback(btDynamicsWorld *world, btScalar timeStep) {
jmePhysicsSpace* dynamicsWorld = (jmePhysicsSpace*) world->getWorldUserInfo();
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
if (javaPhysicsSpace != NULL) {
env->CallVoidMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_preTick, timeStep);
env->DeleteLocalRef(javaPhysicsSpace);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return;
}
}
}
void jmePhysicsSpace::postTickCallback(btDynamicsWorld *world, btScalar timeStep) {
jmePhysicsSpace* dynamicsWorld = (jmePhysicsSpace*) world->getWorldUserInfo();
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
if (javaPhysicsSpace != NULL) {
env->CallVoidMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_postTick, timeStep);
env->DeleteLocalRef(javaPhysicsSpace);
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
return;
}
}
}
void jmePhysicsSpace::contactStartedCallback(btPersistentManifold* const &pm) {
const btCollisionObject* co0 = pm->getBody0();
const btCollisionObject* co1 = pm->getBody1();
jmeUserPointer *up0 = (jmeUserPointer*) co0 -> getUserPointer();
jmeUserPointer *up1 = (jmeUserPointer*) co1 -> getUserPointer();
if (up0 != NULL) {
jmePhysicsSpace *dynamicsWorld = (jmePhysicsSpace *)up0->space;
if (dynamicsWorld != NULL) {
JNIEnv* env = dynamicsWorld->getEnv();
jobject javaPhysicsSpace = env->NewLocalRef(dynamicsWorld->getJavaPhysicsSpace());
if (javaPhysicsSpace != NULL) {
jobject javaCollisionObject0 = env->NewLocalRef(up0->javaCollisionObject);
jobject javaCollisionObject1 = env->NewLocalRef(up1->javaCollisionObject);
for(int i=0;i<pm->getNumContacts();i++){
env->CallVoidMethod(javaPhysicsSpace, jmeClasses::PhysicsSpace_addCollisionEvent, javaCollisionObject0, javaCollisionObject1, (jlong) & pm->getContactPoint(i));
if (env->ExceptionCheck()) {
env->Throw(env->ExceptionOccurred());
}
}
env->DeleteLocalRef(javaPhysicsSpace);
env->DeleteLocalRef(javaCollisionObject0);
env->DeleteLocalRef(javaCollisionObject1);
}
}
}
}
btDynamicsWorld* jmePhysicsSpace::getDynamicsWorld() {
return dynamicsWorld;
}
jobject jmePhysicsSpace::getJavaPhysicsSpace() {
return javaPhysicsSpace;
}
jmePhysicsSpace::~jmePhysicsSpace() {
delete(dynamicsWorld);
}
| 43.766816 | 189 | 0.665984 | MeFisto94 |
95388ef254ece677e4b85484eb47258c1b9b592a | 931 | cpp | C++ | codes/TEAMSCODE/2020/TC_MOCK/2/9.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 2 | 2021-03-07T03:34:02.000Z | 2021-03-09T01:22:21.000Z | codes/TEAMSCODE/2020/TC_MOCK/2/9.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 1 | 2021-03-27T15:01:23.000Z | 2021-03-27T15:55:34.000Z | codes/TEAMSCODE/2020/TC_MOCK/2/9.cpp | chessbot108/solved-problems | 0945be829a8ea9f0d5896c89331460d70d076691 | [
"MIT"
] | 1 | 2021-03-27T05:02:33.000Z | 2021-03-27T05:02:33.000Z | //code by daniel. aaron worked on this, but daniel's code was much cleaner
#include <iostream>
#include <vector>
using namespace std;
string s1, s2;
string multiply(){
int len1 = s1.length();
int len2 = s2.length();
if (len1 == 0 || len2 == 0){
return "0";
}
vector<int> v(len1 + len2, 0);
int i1 = 0;
int i2 = 0;
for (int i = len1 - 1; i >= 0; i--){
int carry = 0;
int n1 = s1[i] - '0';
i2 = 0;
for (int j = len2 - 1; j >= 0; j--){
int n2 = s2[j] - '0';
int sum = n1*n2 + v[i1 + i2] + carry;
carry = sum/10;
v[i1 + i2] = sum % 10;
i2++;
}
v[i1 + i2] += carry;
i1++;
}
int i = v.size() - 1;
while (i >= 0 && v[i] == 0){
i--;
}
if (i == -1){
return "0";
}
string ret = "";
while (i >= 0){
ret += to_string(v[i--]);
}
return ret;
}
int main(){
cin >> s1 >> s2;
cout << multiply() << endl;
return 0;
}
| 14.777778 | 74 | 0.459721 | chessbot108 |
953a02caf2851a8833b57cdab5b60749e31f2290 | 1,883 | cpp | C++ | cpp-leetcode/leetcode23-merge-k-sorted-lists.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 45 | 2021-07-25T00:45:43.000Z | 2022-03-24T05:10:43.000Z | cpp-leetcode/leetcode23-merge-k-sorted-lists.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | null | null | null | cpp-leetcode/leetcode23-merge-k-sorted-lists.cpp | yanglr/LeetCodeOJ | 27dd1e4a2442b707deae7921e0118752248bef5e | [
"MIT"
] | 15 | 2021-07-25T00:40:52.000Z | 2021-12-27T06:25:31.000Z | #include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode
{
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists)
{
if (lists.empty())
return NULL;
ListNode *res;
auto cmp = [](ListNode *n1, ListNode *n2)
{
return n1->val > n2->val;
};
/* 使用node的val构造一个小顶堆 */
priority_queue<ListNode *, vector<ListNode *>, decltype(cmp)> nodesQ(cmp);
for (auto list : lists)
{
if (list != NULL)
{
nodesQ.push(list);
}
}
ListNode *fakeHead = new ListNode(-1); /* 创建虚拟头结点 */
ListNode *cur = fakeHead;
while (!nodesQ.empty())
{
cur->next = nodesQ.top(); /* 取出最小值对应的结点指针,挂接在游标指针上 */
cur = cur->next;
nodesQ.pop();
if (cur->next != NULL) /* 只要挂接点后面还有结点,则将其压入栈,继续从中拿出最大值,循环往复 */
{
nodesQ.push(cur->next);
}
}
return fakeHead->next;
}
};
// Test
int main()
{
Solution sol;
// l1 = {1,2,4}, l2 = {1,3,4}
ListNode *l1 = new ListNode(1);
l1 -> next = new ListNode(2);
l1 -> next -> next = new ListNode(4);
ListNode *l2 = new ListNode(1);
l1 -> next = new ListNode(3);
l1 -> next -> next = new ListNode(4);
vector<ListNode*> vec;
vec.push_back(l1);
vec.push_back(l2);
ListNode* res = sol.mergeKLists(vec);
ListNode *p = res;
while (p != NULL)
{
cout << p->val << endl;
p = p->next;
}
return 0;
} | 22.416667 | 82 | 0.501859 | yanglr |
953e9b2d46dd7cf10559f005761e8c30362055e9 | 6,711 | cpp | C++ | 20220108_json_parsing/ws_mng.cpp | 3x3x3/Presentations | 3c31b136ed4d9214bb3730fa41a4a575da38edc9 | [
"MIT"
] | null | null | null | 20220108_json_parsing/ws_mng.cpp | 3x3x3/Presentations | 3c31b136ed4d9214bb3730fa41a4a575da38edc9 | [
"MIT"
] | null | null | null | 20220108_json_parsing/ws_mng.cpp | 3x3x3/Presentations | 3c31b136ed4d9214bb3730fa41a4a575da38edc9 | [
"MIT"
] | null | null | null | // ws_mng.cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////
#include "ws_mng.h"
#include <string>
#include <websocketpp/common/thread.hpp>
//////////////////////////////////////////////////////////////////////////////////////////////////////
ConnMetadata::ConnMetadata(int id, websocketpp::connection_hdl hdl, const std::function<void(int)> cbf_on_open, const std::function<void(int)> cbf_on_close, const std::function<void(int, std::string)> cbf_on_fail, const std::function<void(std::string)> cbf_on_msg)
: m_id(id), m_hdl(hdl), m_is_opened(false), m_cbf_on_open(cbf_on_open), m_cbf_on_close(cbf_on_close), m_cbf_on_fail(cbf_on_fail), m_cbf_on_msg(cbf_on_msg) {
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
void ConnMetadata::on_open(websocketpp::client<websocketpp::config::asio_tls_client>* client, websocketpp::connection_hdl hdl) {
m_is_opened = true;
m_cbf_on_open(m_id);
}
void ConnMetadata::on_close(websocketpp::client<websocketpp::config::asio_tls_client>* client, websocketpp::connection_hdl hdl) {
m_is_opened = false;
m_cbf_on_close(m_id);
}
void ConnMetadata::on_fail(websocketpp::client<websocketpp::config::asio_tls_client>* client, websocketpp::connection_hdl hdl) {
m_is_opened = false;
websocketpp::client<websocketpp::config::asio_tls_client>::connection_ptr con = client->get_con_from_hdl(hdl);
const std::string buffer = con->get_ec().message();
m_cbf_on_fail(m_id, buffer);
}
void ConnMetadata::on_message(websocketpp::connection_hdl hdl, websocketpp::client<websocketpp::config::asio_tls_client>::message_ptr msg) {
const websocketpp::frame::opcode::value opcode = msg->get_opcode();
if ( websocketpp::frame::opcode::binary == opcode || websocketpp::frame::opcode::text == opcode ) {
const std::string buffer = msg->get_payload();
m_cbf_on_msg(buffer);
}
}
bool ConnMetadata::on_ping(websocketpp::connection_hdl hdl, std::string msg) {
return true;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
WsMng::WsMng() : m_next_id(0) {
m_endpoint.set_access_channels(websocketpp::log::alevel::all);
m_endpoint.set_error_channels(websocketpp::log::elevel::all);
m_endpoint.clear_access_channels(websocketpp::log::alevel::control);
m_endpoint.clear_access_channels(websocketpp::log::alevel::frame_header);
m_endpoint.clear_access_channels(websocketpp::log::alevel::frame_payload);
m_endpoint.init_asio();
m_endpoint.set_tls_init_handler(websocketpp::lib::bind(&WsMng::on_tls_init, this, websocketpp::lib::placeholders::_1));
m_endpoint.start_perpetual();
m_thread.reset(new websocketpp::lib::thread(&websocketpp::client<websocketpp::config::asio_tls_client>::run, &m_endpoint));
}
WsMng::~WsMng() {
m_endpoint.stop_perpetual();
for (std::map<int,ConnMetadata::ptr>::const_iterator it = m_connection_list.begin(); it != m_connection_list.end(); ++it) {
if ( !it->second->is_opened() ) {
// Only close open connections
continue;
}
std::cout << "> Closing connection " << it->second->get_id() << std::endl;
websocketpp::lib::error_code ec;
m_endpoint.close(it->second->get_hdl(), websocketpp::close::status::going_away, "", ec);
if (ec) {
std::cout << "> Error closing connection " << it->second->get_id() << ": " << ec.message() << std::endl;
}
}
m_thread->join();
}
//////////////////////////////////////////////////////////////////////////////////////////////////////
std::shared_ptr<boost::asio::ssl::context> WsMng::on_tls_init(websocketpp::connection_hdl) {
std::shared_ptr<boost::asio::ssl::context> ctx = std::make_shared<boost::asio::ssl::context>(boost::asio::ssl::context::tls);
try {
ctx->set_options(boost::asio::ssl::context::default_workarounds |
boost::asio::ssl::context::no_sslv2 |
boost::asio::ssl::context::no_sslv3 |
boost::asio::ssl::context::single_dh_use
);
ctx->set_verify_mode(boost::asio::ssl::verify_none);
} catch (std::exception &e) {
std::cout << "Error in context pointer: " << e.what() << std::endl;;
}
return ctx;
}
int WsMng::connect(const std::string& uri, const std::function<void(int)> cbf_on_open, const std::function<void(int)> cbf_on_close, const std::function<void(int, std::string)> cbf_on_fail, const std::function<void(std::string)> cbf_on_msg) {
websocketpp::lib::error_code ec;
websocketpp::client<websocketpp::config::asio_tls_client>::connection_ptr con = m_endpoint.get_connection(uri, ec);
if (ec) {
std::cout << "> Connect initialization error: " << ec.message() << std::endl;
return -1;
}
int new_id = m_next_id++;
ConnMetadata::ptr metadata_ptr(new ConnMetadata(new_id, con->get_handle(), cbf_on_open, cbf_on_close, cbf_on_fail, cbf_on_msg));
m_connection_list[new_id] = metadata_ptr;
con->set_open_handler(websocketpp::lib::bind(
&ConnMetadata::on_open,
metadata_ptr,
&m_endpoint,
websocketpp::lib::placeholders::_1
));
con->set_fail_handler(websocketpp::lib::bind(
&ConnMetadata::on_fail,
metadata_ptr,
&m_endpoint,
websocketpp::lib::placeholders::_1
));
con->set_close_handler(websocketpp::lib::bind(
&ConnMetadata::on_close,
metadata_ptr,
&m_endpoint,
websocketpp::lib::placeholders::_1
));
con->set_message_handler(websocketpp::lib::bind(
&ConnMetadata::on_message,
metadata_ptr,
websocketpp::lib::placeholders::_1,
websocketpp::lib::placeholders::_2
));
con->set_ping_handler(websocketpp::lib::bind(
&ConnMetadata::on_ping,
metadata_ptr,
websocketpp::lib::placeholders::_1,
websocketpp::lib::placeholders::_2
));
m_endpoint.connect(con);
return new_id;
}
void WsMng::send(int id, std::string message) {
websocketpp::lib::error_code ec;
std::map<int,ConnMetadata::ptr>::const_iterator metadata_it = m_connection_list.find(id);
if (metadata_it == m_connection_list.end()) {
std::cout << "> No connection found with id " << id << std::endl;
return;
}
m_endpoint.send(metadata_it->second->get_hdl(), message, websocketpp::frame::opcode::text, ec);
if (ec) {
std::cout << "> Error sending message: " << ec.message() << std::endl;
return;
}
} | 39.245614 | 264 | 0.613917 | 3x3x3 |
953f8c953f12670d750c6c26ceb4291a089c7e17 | 3,446 | cpp | C++ | PolyRender/TransformationAdapterTest.cpp | pauldoo/scratch | 1c8703d8b8e5cc5a026bfd5f0b036b9632faf161 | [
"0BSD"
] | null | null | null | PolyRender/TransformationAdapterTest.cpp | pauldoo/scratch | 1c8703d8b8e5cc5a026bfd5f0b036b9632faf161 | [
"0BSD"
] | 4 | 2021-08-31T22:03:39.000Z | 2022-02-19T07:12:05.000Z | PolyRender/TransformationAdapterTest.cpp | pauldoo/scratch | 1c8703d8b8e5cc5a026bfd5f0b036b9632faf161 | [
"0BSD"
] | 1 | 2022-02-23T13:46:49.000Z | 2022-02-23T13:46:49.000Z | #include "stdafx.h"
#include "TransformationAdapterTest.h"
#include "TransformationAdapter.h"
#include "Line.h"
#include "Intersect.h"
#include "Maybe.h"
#include "DummySolid.h"
#include "Plane.h"
#include "Auto.h"
#include "Solid.h"
std::string TransformationAdapterTest::Name() const {
return "TransformationAdapter Test";
}
void TransformationAdapterTest::Execute()
{
RenderMemory renderMemory;
const Line dummyLight(Point(1,2,3), Point());
const Auto<const Solid> dummySolid = MakeDummySolid(Point(1,2,3), Point(0,0,1));
// Simple case
{
const Auto<const Solid> trans = MakeTransformationAdapter(dummySolid, IdentityMatrix(), Point());
const Auto<const Intersect> intersect = trans->DetermineClosestIntersectionPoint(
dummyLight, eRender, renderMemory).Get();
AssertEqual("Identity TransformationAdapter does nothing to position", intersect->PositionAt(), Point(1,2,3));
AssertEqual("Identity TransformationAdapter does nothing to normal", intersect->NormalAt(), Point(0,0,1));
}
// Translated by (0,0,1)
{
const Auto<const Solid> trans =
MakeTransformationAdapter(dummySolid, IdentityMatrix(), Point(0,0,1));
const Auto<const Intersect> intersect = trans->DetermineClosestIntersectionPoint(
dummyLight, eRender, renderMemory).Get();
AssertEqual("TransformationAdapter moves position", intersect->PositionAt(), Point(1,2,4));
AssertEqual("TransformationAdapter does nothing to normal", intersect->NormalAt(), Point(0,0,1));
}
// Rotated from XY to XZ
{
const Auto<const Solid> trans =
MakeTransformationAdapter(dummySolid, Matrix(Point(1,0,0), Point(0,0,1), Point(0,1,0)), Point());
const Auto<const Intersect> intersect = trans->DetermineClosestIntersectionPoint(
dummyLight, eRender, renderMemory).Get();
AssertEqual("TransformationAdapter moves position", intersect->PositionAt(), Point(1,3,2));
AssertEqual("TransformationAdapter rotates normal", intersect->NormalAt(), Point(0,1,0));
}
// Now both together
{
const Auto<const Solid> trans =
MakeTransformationAdapter(dummySolid, Matrix(Point(1,0,0), Point(0,0,1), Point(0,1,0)), Point(0,0,1));
const Auto<const Intersect> intersect = trans->DetermineClosestIntersectionPoint(
dummyLight, eRender, renderMemory).Get();
AssertEqual("TransformationAdapter moves position", intersect->PositionAt(), Point(1,3,3));
AssertEqual("TransformationAdapter rotates normal", intersect->NormalAt(), Point(0,1,0));
}
// Now Lets test 30 degree rotation around X
{
const double sin30 = 1/2.;
const double cos30 = sqrt(3.)/2;
const Auto<const Solid> trans =
MakeTransformationAdapter(
MakeDummySolid(Point(0,0,2), Point(0,0,1)),
Matrix(Point(1,0,0), Point(0,cos30,-sin30), Point(0,sin30,cos30)),
Point()
);
const Auto<const Intersect> intersect = trans->DetermineClosestIntersectionPoint(
dummyLight, eRender, renderMemory).Get();
AssertEqual("TransformationAdapter moves position", intersect->PositionAt(), 2*Point(0,-sin30,cos30));
AssertEqual("TransformationAdapter rotates normal", intersect->NormalAt(), Point(0,-sin30,cos30));
}
// InsideQ works
{
const Auto<const Solid> plane = MakeTransformationAdapter(
MakePlane(),
IdentityMatrix(),
Point(0,0,10)
);
Assert("Should be inside", plane->InsideQ(Point(0,0,11)));
Assert("Shouldn't be inside", !plane->InsideQ(Point(0,0,9)));
}
}
| 41.02381 | 113 | 0.713581 | pauldoo |
9541c1871a6635bb284608e103d81e3fd8c2e37a | 3,316 | cc | C++ | code/SuffixArray_new.cc | tulsyan/ACM-ICPC-Handbook | fbadfd66017991d264071af3f2fa8e050e4f8e40 | [
"MIT"
] | 32 | 2017-12-24T20:00:47.000Z | 2021-04-09T14:53:25.000Z | code/SuffixArray_new.cc | Zindastart/ACM-ICPC-Handbook | fbadfd66017991d264071af3f2fa8e050e4f8e40 | [
"MIT"
] | null | null | null | code/SuffixArray_new.cc | Zindastart/ACM-ICPC-Handbook | fbadfd66017991d264071af3f2fa8e050e4f8e40 | [
"MIT"
] | 16 | 2017-12-13T14:35:27.000Z | 2021-12-24T04:40:32.000Z | // Begins Suffix Arrays implementation
// O(n log n) - Manber and Myers algorithm
// SA = The suffix array. Contains the n suffixes of txt sorted in lexicographical order.
// Each suffix is represented as a single integer (the SAition of txt where it starts).
// iSA = The inverse of the suffix array. iSA[i] = the index of the suffix txt[i..n)
// in the SA array. (In other words, SA[i] = k <==> iSA[k] = i)
// With this array, you can compare two suffixes in O(1): Suffix txt[i..n) is smaller
// than txt[j..n) if and only if iSA[i] < iSA[j]
const int MAX = 1000100;
char txt[MAX]; //input
int iSA[MAX], SA[MAX]; //output
int cnt[MAX];
int nex[MAX]; //internal
bool bh[MAX], b2h[MAX];
// Compares two suffixes according to their first characters
bool smaller_first_char(int a, int b){
return txt[a] < txt[b];
}
void suffixSort(int n){
//sort suffixes according to their first characters
for (int i=0; i<n; ++i){
SA[i] = i;
}
sort(SA, SA + n, smaller_first_char);
//{SA contains the list of suffixes sorted by their first character}
for (int i=0; i<n; ++i){
bh[i] = i == 0 || txt[SA[i]] != txt[SA[i-1]];
b2h[i] = false;
}
for (int h = 1; h < n; h <<= 1){
//{bh[i] == false if the first h characters of SA[i-1] == the first h characters of SA[i]}
int buckets = 0;
for (int i=0, j; i < n; i = j){
j = i + 1;
while (j < n && !bh[j]) j++;
nex[i] = j; buckets++;
}
if (buckets == n) break; // We are done! Lucky bastards!
//{suffixes are separted in buckets containing txtings starting with the same h characters}
for (int i = 0; i < n; i = nex[i]){
cnt[i] = 0;
for (int j = i; j < nex[i]; ++j){
iSA[SA[j]] = i;
}
}
cnt[iSA[n - h]]++;
b2h[iSA[n - h]] = true;
for (int i = 0; i < n; i = nex[i]){
for (int j = i; j < nex[i]; ++j){
int s = SA[j] - h;
if (s >= 0){
int head = iSA[s];
iSA[s] = head + cnt[head]++; b2h[iSA[s]] = true;
}
}
for (int j = i; j < nex[i]; ++j){
int s = SA[j] - h;
if (s >= 0 && b2h[iSA[s]]){
for (int k = iSA[s]+1; !bh[k] && b2h[k]; k++) b2h[k] = false;
}
}
}
for (int i=0; i<n; ++i){
SA[iSA[i]] = i; bh[i] |= b2h[i];
}
}
for (int i=0; i<n; ++i)
iSA[SA[i]] = i;
}
// End of suffix array algorithm
// Begin of the O(n) longest common prefix algorithm
// Refer to "Linear-Time Longest-Common-Prefix Computation in Suffix
// Arrays and Its Applications" by Toru Kasai, Gunho Lee, Hiroki
// Arimura, Setsuo Arikawa, and Kunsoo Park.
int lcp[MAX];
// lcp[i] = length of the longest common prefix of suffix SA[i] and suffix SA[i-1]
// lcp[0] = 0
void getlcp(int n)
{
for (int i=0; i<n; ++i)
iSA[SA[i]] = i;
lcp[0] = 0;
for (int i=0, h=0; i<n; ++i) {
if (iSA[i] > 0) {
int j = SA[iSA[i]-1];
while (i + h < n && j + h < n && txt[i+h] == txt[j+h])
h++;
lcp[iSA[i]] = h;
if (h > 0) h--;
}
}
}
// End of longest common prefixes algorithm
int main() {
int len;
// gets(txt);
for(int i = 0; i < 1000000; i++)
txt[i] = 'a';
txt[1000000] = '\0';
len = strlen(txt);
printf("%d",len);
suffixSort(len);
getlcp(len);
return 0;
} | 28.834783 | 95 | 0.528347 | tulsyan |
9542f2fa62e1c13870b3484a6ff2e59dd95a364b | 1,939 | cpp | C++ | module04/ex03/main.cpp | mathias-mrsn/CPP_modules | 726bb5bd25f5e366550c79e5f01aed1d3d95c7fc | [
"MIT"
] | null | null | null | module04/ex03/main.cpp | mathias-mrsn/CPP_modules | 726bb5bd25f5e366550c79e5f01aed1d3d95c7fc | [
"MIT"
] | null | null | null | module04/ex03/main.cpp | mathias-mrsn/CPP_modules | 726bb5bd25f5e366550c79e5f01aed1d3d95c7fc | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.cpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mamaurai <mamaurai@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2022/05/03 10:02:00 by mamaurai #+# #+# */
/* Updated: 2022/05/11 14:06:41 by mamaurai ### ########.fr */
/* */
/* ************************************************************************** */
#include "ICharacter.hpp"
#include "Character.hpp"
#include "AMateria.hpp"
#include "IMateriaSource.hpp"
#include "MateriaSource.hpp"
#include "Ice.hpp"
#include "Cure.hpp"
int main()
{
IMateriaSource* src = new MateriaSource();
src->learnMateria(new Ice());
src->learnMateria(new Cure());
ICharacter* me = new Character("me");
ICharacter* ennemi = new Character("ennemi");
AMateria* tmp;
tmp = src->createMateria("ice");
me->equip(tmp);
me->use(0, *ennemi);
tmp = src->createMateria("cure");
me->equip(tmp);
me->use(1, *ennemi);
tmp = src->createMateria("unknown materia");
me->equip(tmp);
me->use(2, *ennemi);
me->unequip(1);
me->use(1, *ennemi);
IMateriaSource* src2 = new MateriaSource();
src2->learnMateria(new Cure());
src2->learnMateria(new Ice());
me->equip(src2->createMateria("cure"));
me->equip(src2->createMateria("ice"));
std::cout << std::endl;
for (int i = 0; i < NBR_MATERIA; i++)
me->use(i, *ennemi);
delete src2;
delete me;
delete src;
delete ennemi;
AMateria::clean();
return 0;
} | 29.830769 | 80 | 0.407942 | mathias-mrsn |
95454efe95736a10e0c0eb54ae565a60cf4f32a5 | 5,442 | hpp | C++ | src/ivorium_core/Instancing/Instance.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | 3 | 2021-02-26T02:59:09.000Z | 2022-02-08T16:44:21.000Z | src/ivorium_core/Instancing/Instance.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | src/ivorium_core/Instancing/Instance.hpp | ivorne/ivorium | 1d876b6dcabe29b3110d3058f997e59c40cd6a2b | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "../Basics/LogId.hpp"
#include "../Basics/SrcInfo.hpp"
#include "../Basics/volatile_set.hpp"
#include "../Basics/StringIO_defs.hpp"
#include <unordered_set>
#include <string>
#include <sstream>
#include <type_traits>
#include <vector>
#include <functional>
#include <typeindex>
#include <list>
#include <type_traits>
namespace iv
{
class InstanceSystem;
class DebugInstanceListener;
class SystemContainer;
class instance_ptr_interface;
class ClientMarker;
class TextDebugView;
/**
*/
class Instance
{
public:
//------------------------- structors ------------------------------
Instance( const SystemContainer * sc );
virtual ~Instance( );
Instance * instance(){ return this; }
//------------------------- SystemContainer manipulation -----------
/**
* Returns SystemContainer given in constructor.
* Do not use it directly, only Properties and Components should use this to communicate with systems.
*/
SystemContainer const * getSystemContainer() const;
/**
* SystemContainer of this Instance will be duplicated (to contain the same systems as the original SystemContainer).
* From now on, all children of this Instance will receive the new SystemContainer in the constructor.
* This Instance will still use the old SystemContainer.
* If the SystemContainer is already duplicated, this will just return pointer to it.
* Instance can change which systems are contained in the new SystemContainer (using the pointer returned from this method).
*
* Call SystemContainer::createProxies after/if you create new systems in that SystemContainer.
*/
SystemContainer * duplicateSystemContainer();
/**
Shortcut for getSystemContainer()->getSystem< TypedSystem >().
*/
template< class TypedSystem >
TypedSystem * getSystem() const;
/**
*/
unsigned frame_id() const;
//------------------------- instance introspection --------------------------
/**
Name for introspection purposes.
*/
std::string const & instance_name();
/**
Creates two way relation that is automaticaly cleaned when either Instance is destroyed.
Instance can has only one parent, can be nullptr to clear existing relation.
*/
void instance_parent( Instance * parent );
/**
Usually assigned right after instantiation.
Can be called only once.
This finalizes the Instance instanciation, so the instance is registered to InstanceSystem and debug listeners from this method.
*/
void instance_finalize( std::string const & inst_name, ClientMarker const * root_client );
/**
Called automatically from ClientMarker.
*/
void client_register( ClientMarker const * marker );
void client_unregister( ClientMarker const * marker );
//------------------------- logging --------------------------------
void client_log( ClientMarker const * cm, SrcInfo const & info, LogId id, std::string const & message );
bool client_log_enabled( ClientMarker const * cm, LogId id );
//------------------------- debug access ---------------------------------
void debug_print_clients( TextDebugView * view );
/**
*/
Instance * Debug_Parent();
std::unordered_set< Instance * > const & Debug_Children();
ClientMarker const * Debug_RootClient();
std::unordered_set< ClientMarker const * > const & Debug_Clients();
/**
Helper method, iterates over set returned by DebugClientMarkers(), checks type and casts client if type is equal.
NOTE - currently unsafe - changes to Instance clients (adding or removing) may corrupt iterators used in this method and cause segfault
- should be refactored in future to support some kind of safe listener based approach
*/
template< class TypedClient >
void Debug_ForeachClient( std::function< void( TypedClient * ) > const & lambda );
private:
InstanceSystem * getOS();
private:
//------------------ systems -------------------------------
SystemContainer const * sc;
SystemContainer * sc_dup;
InstanceSystem * os;
//----------------- structure introspection -------------------------------
std::string _instance_name;
Instance * _parent;
std::unordered_set< Instance * > _children;
ClientMarker const * _root_client;
std::unordered_set< ClientMarker const * > _clients;
//------------- debug ----------------------
int _logging_cnt;
//------------- weak pointer impl ----------
friend class instance_ptr_interface;
std::unordered_set< instance_ptr_interface * > instance_pointers;
};
}
#include "SystemContainer.hpp"
#include "InstanceSystem.hpp"
#include "ClientMarker.hpp"
#include "Instance.inl"
| 36.52349 | 143 | 0.564866 | ivorne |
9547d6faf5a19ef65bd54e4aeada5d3cc0e8e5b2 | 1,163 | cpp | C++ | Week 03 - Complexity/469A-I Wanna Be the Guy.cpp | AAlab1819/dennyraymond-01082170017 | d4a278744b42aadf355aa3e5dc8fd849ead71da6 | [
"MIT"
] | null | null | null | Week 03 - Complexity/469A-I Wanna Be the Guy.cpp | AAlab1819/dennyraymond-01082170017 | d4a278744b42aadf355aa3e5dc8fd849ead71da6 | [
"MIT"
] | null | null | null | Week 03 - Complexity/469A-I Wanna Be the Guy.cpp | AAlab1819/dennyraymond-01082170017 | d4a278744b42aadf355aa3e5dc8fd849ead71da6 | [
"MIT"
] | null | null | null | #include <iostream>
using namespace std;
int main()
{
int gameLevel, xSolved, ySolved;
int levelCanPassed;
//total level
cin>>gameLevel;
int allLevels[gameLevel];
bool unsolved = false;
//assign all level to 1, 1 indicate level that unsolved
for(int i=0;i<gameLevel;i++){
allLevels[i]=1;
}
//input level that X can passed
cin>>xSolved;
for(int i=0;i<xSolved;i++){
cin>>levelCanPassed;
//delete number in array level that solved
allLevels[levelCanPassed-1]=0;
}
//input level that Y can passed
cin>>ySolved;
for(int i=0;i<ySolved;i++){
cin>>levelCanPassed;
//delete number in array level that solved
allLevels[levelCanPassed-1]=0;
}
//to check if there's unsolved level
for (int i=0;i<gameLevel;i++){
if(allLevels[i]==1){
unsolved=true;
break;
}
}
//to print if there's unsolved level
if(unsolved==true){
cout<<"Oh, my keyboard!"<<endl;
}
else{
cout<<"I become the guy."<<endl;
}
return 0;
}
| 22.803922 | 60 | 0.550301 | AAlab1819 |
954b05e24ee6b9d7467ec3bacb6ead43c4170edb | 615 | cc | C++ | chrome/browser/automation/automation_resource_routing_delegate.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-09-02T19:08:28.000Z | 2021-11-15T15:15:14.000Z | chrome/browser/automation/automation_resource_routing_delegate.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-07-25T09:37:22.000Z | 2017-08-04T07:18:56.000Z | chrome/browser/automation/automation_resource_routing_delegate.cc | SlimKatLegacy/android_external_chromium | bc611cda58cc18d0dbaa8a7aee05eb3c0742e573 | [
"BSD-3-Clause"
] | 2 | 2017-08-09T09:03:23.000Z | 2020-05-26T09:14:49.000Z | // Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/automation/automation_resource_routing_delegate.h"
void AutomationResourceRoutingDelegate::RegisterRenderViewHost(
RenderViewHost* render_view_host) {
}
void AutomationResourceRoutingDelegate::UnregisterRenderViewHost(
RenderViewHost* render_view_host) {
}
AutomationResourceRoutingDelegate::AutomationResourceRoutingDelegate() {
}
AutomationResourceRoutingDelegate::~AutomationResourceRoutingDelegate() {
}
| 30.75 | 75 | 0.821138 | SlimKatLegacy |
954c6b17697851a69064cb4947dde42d3c6fb6ad | 2,094 | cpp | C++ | DlgDocGe.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 12 | 2019-06-07T10:06:41.000Z | 2021-03-22T22:13:59.000Z | DlgDocGe.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 1 | 2019-05-09T07:38:12.000Z | 2019-07-10T04:20:55.000Z | DlgDocGe.cpp | RDamman/SpeakerWorkshop | 87a38d04197a07a9a7878b3f60d5e0706782163c | [
"OML"
] | 3 | 2020-09-08T08:27:33.000Z | 2021-05-13T09:25:43.000Z | // DlgDocGe.cpp : implementation file
//
#include "stdafx.h"
#include "audtest.h"
#include "DlgDocGe.h"
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
/////////////////////////////////////////////////////////////////////////////
// CDlgDocGeneral property page
IMPLEMENT_DYNCREATE(CDlgDocGeneral, CPropertyPage)
CDlgDocGeneral::CDlgDocGeneral() : CPropertyPage(CDlgDocGeneral::IDD)
{
//{{AFX_DATA_INIT(CDlgDocGeneral)
m_csDate = _T("");
m_csDescript = _T("");
m_csLastEdit = _T("");
//}}AFX_DATA_INIT
m_pDocument = NULL;
}
CDlgDocGeneral::~CDlgDocGeneral()
{
}
void CDlgDocGeneral::DoDataExchange(CDataExchange* pDX)
{
CPropertyPage::DoDataExchange(pDX);
//{{AFX_DATA_MAP(CDlgDocGeneral)
DDX_Text(pDX, IDC_DATE, m_csDate);
DDX_Text(pDX, IDC_DESCRIPT, m_csDescript);
DDX_Text(pDX, IDC_LASTEDIT, m_csLastEdit);
//}}AFX_DATA_MAP
}
BEGIN_MESSAGE_MAP(CDlgDocGeneral, CPropertyPage)
//{{AFX_MSG_MAP(CDlgDocGeneral)
ON_EN_CHANGE(IDC_DESCRIPT, OnChangeDescript)
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
/////////////////////////////////////////////////////////////////////////////
// CDlgDocGeneral message handlers
void CDlgDocGeneral::PostDialog(CAudtestDoc *pDoc)
{
CFolder *proot = pDoc->GetRoot();
if ( proot)
{
CString csold = proot->GetDescription();
if ( csold.Compare( m_csDescript)) // has it changed???
{
proot->SetDescription( m_csDescript);
proot->SetLastEdit();
pDoc->SetModifiedFlag( TRUE);
}
}
}
void CDlgDocGeneral::PreDialog(CAudtestDoc *pDoc)
{
CFolder *proot = pDoc->GetRoot();
m_pDocument = pDoc;
if ( proot)
{
proot->SetDateStrings( m_csDate, m_csLastEdit);
m_csDescript = proot->GetDescription();
}
SetModified( FALSE);
}
void CDlgDocGeneral::OnChangeDescript()
{
SetModified( TRUE);
}
BOOL CDlgDocGeneral::OnApply()
{
// TODO: Add your specialized code here and/or call the base class
if ( m_pDocument)
{
ASSERT( m_pDocument->IsKindOf( RUNTIME_CLASS( CAudtestDoc)));
PostDialog( m_pDocument);
SetModified( FALSE);
}
return CPropertyPage::OnApply();
}
| 19.942857 | 77 | 0.674308 | RDamman |
9550b1d2bd8ebd57c23c65a69f4782dbb33270eb | 2,585 | cpp | C++ | src/utils/bluetooth/socket_bluetooth_linux.cpp | Andrey1994/brainflow | 6b776859fba6a629b1acd471ae5d1320bffe9ca5 | [
"MIT"
] | 53 | 2018-12-11T13:35:47.000Z | 2020-04-21T00:08:13.000Z | src/utils/bluetooth/socket_bluetooth_linux.cpp | neuroidss/brainflow | c01ec6d4aa9a87cb75d99b464e43765fbeb5c1fe | [
"MIT"
] | 14 | 2019-06-12T05:22:27.000Z | 2020-04-20T19:14:44.000Z | src/utils/bluetooth/socket_bluetooth_linux.cpp | neuroidss/brainflow | c01ec6d4aa9a87cb75d99b464e43765fbeb5c1fe | [
"MIT"
] | 9 | 2019-04-13T19:03:16.000Z | 2020-04-07T16:42:20.000Z | #include "bluetooth_functions.h"
#include "bluetooth_types.h"
#include "socket_bluetooth.h"
#include <fcntl.h>
#include <stdlib.h>
#include <sys/ioctl.h>
#include <sys/poll.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/hci.h>
#include <bluetooth/hci_lib.h>
#include <bluetooth/rfcomm.h>
#include <bluetooth/sdp.h>
#include <bluetooth/sdp_lib.h>
SocketBluetooth::SocketBluetooth (std::string mac_addr, int port)
{
this->mac_addr = mac_addr;
this->port = port;
socket_bt = -1;
}
int SocketBluetooth::connect ()
{
struct sockaddr_rc addr;
memset (&addr, 0, sizeof (addr));
socket_bt = socket (AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
addr.rc_family = AF_BLUETOOTH;
addr.rc_channel = (uint8_t)port;
str2ba (mac_addr.c_str (), &addr.rc_bdaddr);
int status = ::connect (socket_bt, (struct sockaddr *)&addr, sizeof (addr));
if (status != 0)
{
return (int)SocketBluetoothReturnCodes::CONNECT_ERROR;
}
int sock_flags = fcntl (socket_bt, F_GETFL, 0);
fcntl (socket_bt, F_SETFL, sock_flags | O_NONBLOCK);
return (int)SocketBluetoothReturnCodes::STATUS_OK;
}
int SocketBluetooth::send (const char *data, int size)
{
if (socket_bt < 0)
{
return -1;
}
int res = ::send (socket_bt, data, size, 0);
return res;
}
int SocketBluetooth::recv (char *data, int size)
{
if (socket_bt < 0)
{
return -1;
}
// waiting for exact amount of bytes
int e = bytes_available ();
if (e < size)
{
return 0;
}
fd_set set;
FD_ZERO (&set);
FD_SET (socket_bt, &set);
int res = -1;
struct timeval timeout;
timeout.tv_sec = 0;
timeout.tv_usec = 0;
if (select (socket_bt + 1, &set, NULL, NULL, &timeout) >= 0)
{
if (FD_ISSET (socket_bt, &set))
{
res = ::recv (socket_bt, data, size, 0);
}
}
return res;
}
int SocketBluetooth::bytes_available ()
{
if (socket_bt < 0)
{
return -1;
}
int count;
ioctl (socket_bt, FIONREAD, &count);
return count;
}
int SocketBluetooth::close ()
{
int result = ::close (socket_bt);
socket_bt = -1;
return result == 0 ? (int)SocketBluetoothReturnCodes::STATUS_OK :
(int)SocketBluetoothReturnCodes::DISCONNECT_ERROR;
}
std::pair<std::string, int> SocketBluetooth::discover (char *selector)
{
return std::make_pair<std::string, int> (
"", (int)SocketBluetoothReturnCodes::UNIMPLEMENTED_ERROR);
} | 22.675439 | 80 | 0.629014 | Andrey1994 |
9552c0a5e35e75fefcde2c42636cf1609ae032e3 | 3,422 | cpp | C++ | cmds/statsd/src/external/StatsPuller.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 164 | 2015-01-05T16:49:11.000Z | 2022-03-29T20:40:27.000Z | cmds/statsd/src/external/StatsPuller.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 127 | 2015-01-12T12:02:32.000Z | 2021-11-28T08:46:25.000Z | cmds/statsd/src/external/StatsPuller.cpp | rio-31/android_frameworks_base-1 | 091a068a3288d27d77636708679dde58b7b7fd25 | [
"Apache-2.0"
] | 1,141 | 2015-01-01T22:54:40.000Z | 2022-02-09T22:08:26.000Z | /*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#define DEBUG false // STOPSHIP if true
#include "Log.h"
#include "StatsPuller.h"
#include "StatsPullerManager.h"
#include "guardrail/StatsdStats.h"
#include "puller_util.h"
#include "stats_log_util.h"
namespace android {
namespace os {
namespace statsd {
using std::lock_guard;
sp<UidMap> StatsPuller::mUidMap = nullptr;
void StatsPuller::SetUidMap(const sp<UidMap>& uidMap) { mUidMap = uidMap; }
StatsPuller::StatsPuller(const int tagId)
: mTagId(tagId), mLastPullTimeNs(0) {
}
bool StatsPuller::Pull(std::vector<std::shared_ptr<LogEvent>>* data) {
lock_guard<std::mutex> lock(mLock);
int64_t elapsedTimeNs = getElapsedRealtimeNs();
StatsdStats::getInstance().notePull(mTagId);
const bool shouldUseCache = elapsedTimeNs - mLastPullTimeNs <
StatsPullerManager::kAllPullAtomInfo.at(mTagId).coolDownNs;
if (shouldUseCache) {
if (mHasGoodData) {
(*data) = mCachedData;
StatsdStats::getInstance().notePullFromCache(mTagId);
}
return mHasGoodData;
}
if (mLastPullTimeNs > 0) {
StatsdStats::getInstance().updateMinPullIntervalSec(
mTagId, (elapsedTimeNs - mLastPullTimeNs) / NS_PER_SEC);
}
mCachedData.clear();
mLastPullTimeNs = elapsedTimeNs;
mHasGoodData = PullInternal(&mCachedData);
if (!mHasGoodData) {
return mHasGoodData;
}
const int64_t pullDurationNs = getElapsedRealtimeNs() - elapsedTimeNs;
StatsdStats::getInstance().notePullTime(mTagId, pullDurationNs);
const bool pullTimeOut =
pullDurationNs > StatsPullerManager::kAllPullAtomInfo.at(mTagId).pullTimeoutNs;
if (pullTimeOut) {
// Something went wrong. Discard the data.
clearCacheLocked();
mHasGoodData = false;
StatsdStats::getInstance().notePullTimeout(mTagId);
ALOGW("Pull for atom %d exceeds timeout %lld nano seconds.", mTagId,
(long long)pullDurationNs);
return mHasGoodData;
}
if (mCachedData.size() > 0) {
mapAndMergeIsolatedUidsToHostUid(mCachedData, mUidMap, mTagId);
}
(*data) = mCachedData;
return mHasGoodData;
}
int StatsPuller::ForceClearCache() {
return clearCache();
}
int StatsPuller::clearCache() {
lock_guard<std::mutex> lock(mLock);
return clearCacheLocked();
}
int StatsPuller::clearCacheLocked() {
int ret = mCachedData.size();
mCachedData.clear();
mLastPullTimeNs = 0;
return ret;
}
int StatsPuller::ClearCacheIfNecessary(int64_t timestampNs) {
if (timestampNs - mLastPullTimeNs >
StatsPullerManager::kAllPullAtomInfo.at(mTagId).coolDownNs) {
return clearCache();
} else {
return 0;
}
}
} // namespace statsd
} // namespace os
} // namespace android
| 30.283186 | 91 | 0.684395 | rio-31 |
9553172cdf814db84af12100ee8324f8ba0d0472 | 1,879 | cpp | C++ | Src/MapEditor/vehiclepath.cpp | vox-1/MapEditor | f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e | [
"MIT"
] | null | null | null | Src/MapEditor/vehiclepath.cpp | vox-1/MapEditor | f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e | [
"MIT"
] | null | null | null | Src/MapEditor/vehiclepath.cpp | vox-1/MapEditor | f1b8a3df64c91e9c3aef7ee21e997f4f1163fa0e | [
"MIT"
] | null | null | null |
#include "stdafx.h"
#include "vehiclepath.h"
using namespace graphic;
using namespace tms;
cVehiclePath::cVehiclePath()
: m_idx(0)
, m_velocity(10)
, m_incTime(0)
, m_initialDirection(0,0,1)
, m_rotTime(0.333f)
{
m_path.reserve(32);
}
cVehiclePath::~cVehiclePath()
{
}
bool cVehiclePath::SetPath(const vector<Vector3> &path, const Vector3 &direction)
{
m_initialDirection = direction;
m_path.resize(path.size());
for (u_int i=0; i < path.size(); ++i)
m_path[i] = path[i];
if (!m_path.empty())
{
m_idx = -1;
NextMove();
}
return true;
}
// If Finish Path, return true
bool cVehiclePath::Update(const float deltaSeconds)
{
if (m_idx >= (int)(m_path.size() - 1))
{
m_idx = -1;
//NextMove();
return true;
}
m_incTime += deltaSeconds;
if (m_elapsedTime < m_incTime)
{
NextMove();
}
else
{
common::lerp(m_pos, m_path[m_idx], m_path[m_idx + 1], m_incTime / m_elapsedTime);
if (m_incTime < m_rotTime)
m_rot = m_rot.Interpolate(m_nextRot, m_incTime / m_rotTime);
else
m_rot = m_nextRot;
if (m_pos.LengthRoughly(m_path[m_idx + 1]) < 0.01f)
NextMove();
}
return false;
}
bool cVehiclePath::IsEmpty()
{
return m_path.empty();
}
void cVehiclePath::NextMove()
{
++m_idx;
m_incTime = 0;
m_pos = m_path[m_idx];
if ((int)m_path.size() > (m_idx+1))
{
Vector3 dir = m_path[m_idx+1] - m_path[m_idx];
m_elapsedTime = dir.Length() / m_velocity;
dir.Normalize();
if (m_elapsedTime > 0)
{
// initial direction is Vector3(1,0,0)
// but Camera initial direction is Vector3(0,0,1)
// so rotation y
Matrix44 rot;
rot.SetRotationY(-MATH_PI / 2.f);
Vector3 newDir = dir * rot;
Matrix44 mDir;
mDir.SetView(Vector3(0, 0, 0), newDir, Vector3(0, 1, 0));
mDir.Inverse2();
m_nextRot = mDir.GetQuaternion();
//m_nextRot.SetRotationArc(m_initialDirection, dir, Vector3(0, 1, 0));
}
}
}
| 17.398148 | 83 | 0.653539 | vox-1 |
9554eeba67fee4a1c1a7e99ea09a32575706a32e | 539 | cpp | C++ | Samsung SW Expert Academy/2071.cpp | SiverPineValley/algo | 29c75c6b226fdb15a3b6695e763ee49d4871094e | [
"Apache-2.0"
] | null | null | null | Samsung SW Expert Academy/2071.cpp | SiverPineValley/algo | 29c75c6b226fdb15a3b6695e763ee49d4871094e | [
"Apache-2.0"
] | null | null | null | Samsung SW Expert Academy/2071.cpp | SiverPineValley/algo | 29c75c6b226fdb15a3b6695e763ee49d4871094e | [
"Apache-2.0"
] | null | null | null | // 2071. 평균값 구하기
#include <iostream>
#include <cmath>
using namespace std;
int main(void)
{
int n;
cin >> n;
for(int t = 1; t <= n; t++)
{
float temp2;
int ans, temp;
float sum = 0;
for(int i = 0; i < 10; i++)
{
cin >> temp;
sum += temp;
}
temp2 = sum/10;
temp = (int) temp2;
temp2 -= temp;
if(temp2 >= 0.5) ans = temp+1;
else ans = temp;
cout << "#" << t << " " << ans << "\n";
}
return 0;
} | 19.962963 | 47 | 0.397032 | SiverPineValley |
9555b8faf972198f583a9f3e42f82f755841be12 | 1,141 | cpp | C++ | third_party/WebKit/Source/modules/payments/PaymentResponse.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | 1 | 2020-09-15T08:43:34.000Z | 2020-09-15T08:43:34.000Z | third_party/WebKit/Source/modules/payments/PaymentResponse.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | third_party/WebKit/Source/modules/payments/PaymentResponse.cpp | maidiHaitai/haitaibrowser | a232a56bcfb177913a14210e7733e0ea83a6b18d | [
"BSD-3-Clause"
] | null | null | null | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "modules/payments/PaymentResponse.h"
#include "bindings/core/v8/JSONValuesForV8.h"
#include "modules/payments/PaymentCompleter.h"
#include "wtf/Assertions.h"
namespace blink {
PaymentResponse::PaymentResponse(mojom::blink::PaymentResponsePtr response, PaymentCompleter* paymentCompleter)
: m_methodName(response->method_name)
, m_stringifiedDetails(response->stringified_details)
, m_paymentCompleter(paymentCompleter)
{
DCHECK(m_paymentCompleter);
}
PaymentResponse::~PaymentResponse()
{
}
ScriptValue PaymentResponse::details(ScriptState* scriptState, ExceptionState& exceptionState) const
{
return ScriptValue(scriptState, fromJSONString(scriptState, m_stringifiedDetails, exceptionState));
}
ScriptPromise PaymentResponse::complete(ScriptState* scriptState, bool success)
{
return m_paymentCompleter->complete(scriptState, success);
}
DEFINE_TRACE(PaymentResponse)
{
visitor->trace(m_paymentCompleter);
}
} // namespace blink
| 27.829268 | 111 | 0.791411 | maidiHaitai |
95585e6b406ae394657489a38412eb01de9cfdae | 2,316 | cc | C++ | src/codegen/codegen_function.cc | nitnelave/hopper | 2d71fe2c9944b9cc8bc29ef8c4b9e068e7a54881 | [
"BSD-3-Clause"
] | 2 | 2017-07-27T14:08:43.000Z | 2021-11-12T17:30:58.000Z | src/codegen/codegen_function.cc | nitnelave/hopper | 2d71fe2c9944b9cc8bc29ef8c4b9e068e7a54881 | [
"BSD-3-Clause"
] | 61 | 2017-05-22T12:38:28.000Z | 2017-09-21T08:10:46.000Z | src/codegen/codegen_function.cc | nitnelave/hopper | 2d71fe2c9944b9cc8bc29ef8c4b9e068e7a54881 | [
"BSD-3-Clause"
] | null | null | null | #include "codegen/codegen.h"
#include "llvm/IR/CallingConv.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/Function.h"
#include "ast/block_statement.h"
#include "ast/function_call.h"
#include "ast/function_declaration.h"
#include "ast/return_statement.h"
#include "ast/value.h"
#include "ast/value_statement.h"
#include "ast/variable_declaration.h"
#include "ast/variable_reference.h"
#include "util/logging.h"
namespace codegen {
using namespace llvm; // NOLINT
void CodeGenerator::visit(ast::ValueStatement* node) {
node->value()->accept(*this);
CHECK(gen_value_.is_ok()) << "No value generated by the visitor";
}
void CodeGenerator::visit(ast::FunctionDeclaration* node) {
std::vector<Type*> param_types; // fill by visiting.
for (std::size_t i = 0; i < node->arguments().size(); ++i) {
// TODO: put real type here.
param_types.push_back(IntegerType::get(context_, 32));
}
ArrayRef<Type*> param_types_array(param_types);
// TODO: put real return type here.
FunctionType* t = FunctionType::get(IntegerType::get(context_, 32),
param_types_array, /*isVarArg=*/false);
Constant* c = module_->getOrInsertFunction(node->id().short_name(), t);
Function* llvm_function = cast<Function>(c);
current_function_ = llvm_function;
llvm_function->setCallingConv(CallingConv::C);
functions_[node] = llvm_function;
// Name the parameters.
CHECK(llvm_function->arg_size() == node->arguments().size())
<< "There should be as much arguments in the llvm function as in the "
"ASTNode object";
auto llvm_arg = llvm_function->arg_begin();
auto gh_arg = std::begin(node->arguments());
for (; llvm_arg != llvm_function->arg_end(); llvm_arg++, gh_arg++) {
llvm_arg->setName((*gh_arg)->id().to_string());
functions_args_[(*gh_arg).get()] = &*llvm_arg;
}
// Create body of the function.
CHECK(node->body().is<ast::FunctionDeclaration::StatementsBody>())
<< "FunctionDeclaration body was not transformed, still a value";
BasicBlock* body_block = BasicBlock::Create(context_, node->id().to_string(),
current_function_.value_or_die());
ir_builder_.SetInsertPoint(body_block);
node->accept_body(*this);
consume_return_value();
}
} // namespace codegen
| 34.567164 | 80 | 0.685233 | nitnelave |
955c5571cb638173671c0632373109fd6717acb1 | 10,020 | cpp | C++ | src/main.cpp | lishi0927/BRDF | d9d2fc44b3d70d57a375dd85cb3624462874326a | [
"MIT"
] | null | null | null | src/main.cpp | lishi0927/BRDF | d9d2fc44b3d70d57a375dd85cb3624462874326a | [
"MIT"
] | null | null | null | src/main.cpp | lishi0927/BRDF | d9d2fc44b3d70d57a375dd85cb3624462874326a | [
"MIT"
] | null | null | null | // Include standard headers
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <vector>
// Include GLEW
#include <GL/glew.h>
// Include GLFW
#include <glfw3.h>
GLFWwindow* window;
// Include GLM
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
using namespace glm;
#include "ground.h"
#include "shader.hpp"
#include "texture.hpp"
#include "controls.hpp"
#include "objloader.hpp"
#define WINDOW_WIDTH 1024
#define WINDOW_HEIGHT 768
#define COOK_Torrance
#ifdef DIFFUSE_LIGHT
#include "diffuselight.h"
#endif
#ifdef SPECULAR_LIGHT
#include "specularlight.h"
#endif
#ifdef COOK_Torrance
#include "brdf_cooktorrance.h"
float m_scale;
#endif
Texture* m_pTexture;
GLuint VertexArrayID;
GLuint vertexbuffer;
GLuint uvbuffer;
GLuint normalbuffer;
int verticenumber;
static const float FieldDepth = 20.0f;
static const float FieldWidth = 10.0f;
GLuint m_VBO;
void CreateVertexBuffer()
{
const glm::vec3 Normal = glm::vec3(0.0, 1.0f, 0.0f);
Vertex Vertices[6] = {
Vertex(glm::vec3(0.0f, 0.0f, 0.0f), glm::vec2(0.0f, 0.0f), Normal),
Vertex(glm::vec3(0.0f, 0.0f, FieldDepth), glm::vec2(0.0f, 1.0f), Normal),
Vertex(glm::vec3(FieldWidth, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f), Normal),
Vertex(glm::vec3(FieldWidth, 0.0f, 0.0f), glm::vec2(1.0f, 0.0f), Normal),
Vertex(glm::vec3(0.0f, 0.0f, FieldDepth), glm::vec2(0.0f, 1.0f), Normal),
Vertex(glm::vec3(FieldWidth, 0.0f, FieldDepth), glm::vec2(1.0f, 1.0f), Normal)
};
glGenBuffers(1, &m_VBO);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glBufferData(GL_ARRAY_BUFFER, sizeof(Vertices), Vertices, GL_STATIC_DRAW);
}
void init()
{
LightInit();
// Enable depth test
glEnable(GL_DEPTH_TEST);
// Accept fragment if it closer to the camera than the former one
glDepthFunc(GL_LESS);
// Cull triangles which normal is not towards the camera
glEnable(GL_CULL_FACE);
CreateVertexBuffer();
glGenVertexArrays(1, &VertexArrayID);
glBindVertexArray(VertexArrayID);
/*
// Load the texture
// TextureI = loadDDS("uvmap.DDS");
// Read our .obj file
std::vector<glm::vec3> vertices;
std::vector<glm::vec2> uvs;
std::vector<glm::vec3> normals;
bool res = loadOBJ("suzanne.obj", vertices, uvs, normals);
// Load it into a VBO
verticenumber = vertices.size();
glGenBuffers(1, &vertexbuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glBufferData(GL_ARRAY_BUFFER, vertices.size() * sizeof(glm::vec3), &vertices[0], GL_STATIC_DRAW);
glGenBuffers(1, &uvbuffer);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glBufferData(GL_ARRAY_BUFFER, uvs.size() * sizeof(glm::vec2), &uvs[0], GL_STATIC_DRAW);
glGenBuffers(1, &normalbuffer);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glBufferData(GL_ARRAY_BUFFER, normals.size() * sizeof(glm::vec3), &normals[0], GL_STATIC_DRAW);
vertices.clear();
uvs.clear();
normals.clear();
*/
#ifdef DIFFUSE_LIGHT
Diffuseshader.shader = LoadShaders("shader/diffuse_vert.glsl", "shader/diffuse_fragment.glsl");
if (!Diffuseshader.Init())
{
std::cout << "DiffuseShader ERROR!" << std::endl;
exit(-1);
}
Diffuseshader.Enable();
Diffuseshader.SetTextureUnit(0);
#endif
#ifdef SPECULAR_LIGHT
SpecularShader.shader = LoadShaders("shader/specular_vert.glsl", "shader/specular_fragment.glsl");
if (!SpecularShader.Init())
{
std::cout << "SpecularShader ERROR!" << std::endl;
exit(-1);
}
SpecularShader.Enable();
SpecularShader.SetTextureUnit(0);
#endif
#ifdef COOK_Torrance
m_scale = 0;
CookShader.shader = LoadShaders("shader/cooktorrance_vert.glsl", "shader/cooktorrance_fragment.glsl");
if (!CookShader.Init())
{
std::cout << "CookTorrance Error!" << std::endl;
exit(-1);
}
CookShader.Enable();
CookShader.SetTextureUnit(0);
#endif
m_pTexture = new Texture(GL_TEXTURE_2D, "test.png");
if (!m_pTexture->Load()) {
std::cout << "Texture ERROR!" << std::endl;
exit(-1);
}
}
void render()
{
// Clear the screen
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
// Compute the MVP matrix from keyboard and mouse input
computeMatricesFromInputs();
glm::mat4 ProjectionMatrix = getProjectionMatrix();
glm::mat4 ViewMatrix = getViewMatrix();
glm::mat4 ModelMatrix = glm::mat4(1.0);
glm::mat4 MVP = ProjectionMatrix * ViewMatrix * ModelMatrix;
glm::vec3 camerapos = getCameraPosition();
#ifdef DIFFUSE_LIGHT
Diffuseshader.Enable();
Diffuseshader.SetWVP(MVP);
Diffuseshader.SetWorldMatrix(ModelMatrix);
Diffuseshader.SetDirectionalLight(m_directionalLight);
#endif
#ifdef SPECULAR_LIGHT
SpecularShader.Enable();
SpecularShader.SetWVP(MVP);
SpecularShader.SetWorldMatrix(ModelMatrix);
SpecularShader.SetDirectionalLight(m_directionalLight);
SpecularShader.SetEyeWorldPos(camerapos);
SpecularShader.SetMatSpecularIntensity(1.0f);
SpecularShader.SetMatSpecularPower(32);
#endif
#ifdef COOK_Torrance
m_scale += 0.0057f;
PointLight pl[2];
pl[0].DiffuseIntensity = 0.5f;
pl[0].Color = glm::vec3(1.0f, 0.5f, 0.0f);
pl[0].Position = glm::vec3(3.0f, 1.0f, 20 * (cosf(m_scale) + 1.0f) / 2.0f);
pl[0].Attenuation.Linear = 0.1f;
pl[1].DiffuseIntensity = 0.5f;
pl[1].Color = glm::vec3(0.0f, 0.5f, 1.0f);
pl[1].Position = glm::vec3(7.0f, 1.0f, 20 * (sinf(m_scale) + 1.0f) / 2.0f);
pl[1].Attenuation.Linear = 0.1f;
// CookShader.Enable();
CookShader.SetPointLights(2, pl);
CookShader.SetWVP(MVP);
CookShader.SetWorldMatrix(ModelMatrix);
CookShader.SetDirectionalLight(m_directionalLight);
CookShader.SetEyeWorldPos(camerapos);
CookShader.SetRoughness(0.3);
CookShader.SetFresnel(0.8);
CookShader.SetGK(0.2);
#endif
// m_pTexture->Bind(GL_TEXTURE0);
/*
// 1rst attribute buffer : vertices
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexbuffer);
glVertexAttribPointer(
0, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 2nd attribute buffer : UVs
glEnableVertexAttribArray(1);
glBindBuffer(GL_ARRAY_BUFFER, uvbuffer);
glVertexAttribPointer(
1, // attribute
2, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// 3rd attribute buffer : normals
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, normalbuffer);
glVertexAttribPointer(
2, // attribute
3, // size
GL_FLOAT, // type
GL_FALSE, // normalized?
0, // stride
(void*)0 // array buffer offset
);
// Draw the triangles !
glDrawArrays(GL_TRIANGLES, 0, verticenumber);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
*/
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
glEnableVertexAttribArray(2);
glBindBuffer(GL_ARRAY_BUFFER, m_VBO);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), 0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)12);
glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (const GLvoid*)20);
m_pTexture->Bind(GL_TEXTURE0);
glDrawArrays(GL_TRIANGLES, 0, 6);
glDisableVertexAttribArray(0);
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(2);
}
void keyCallback(GLFWwindow *window, int key, int scancode, int action, int mods) {
if (action != GLFW_PRESS) return;
switch (key) {
case GLFW_KEY_ESCAPE:
glfwSetWindowShouldClose(window, GL_TRUE);
break;
case GLFW_KEY_A:
m_directionalLight.AmbientIntensity += 0.05f;
break;
case GLFW_KEY_S:
m_directionalLight.AmbientIntensity -= 0.05f;
break;
case GLFW_KEY_Z:
m_directionalLight.DiffuseIntensity += 0.05f;
break;
case GLFW_KEY_X:
m_directionalLight.DiffuseIntensity -= 0.05f;
break;
}
}
int main(void)
{
// Initialise GLFW
if (!glfwInit())
{
fprintf(stderr, "Failed to initialize GLFW\n");
getchar();
return -1;
}
glfwWindowHint(GLFW_SAMPLES, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE); // To make MacOS happy; should not be needed
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
// Open a window and create its OpenGL context
window = glfwCreateWindow(WINDOW_WIDTH, WINDOW_HEIGHT, "Tutorial 01", NULL, NULL);
if (window == NULL) {
fprintf(stderr, "Failed to open GLFW window. If you have an Intel GPU, they are not 3.3 compatible. Try the 2.1 version of the tutorials.\n");
getchar();
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(window);
// Initialize GLEW
glewExperimental = true; // Needed for core profile
// Initialize GLEW
if (glewInit() != GLEW_OK) {
fprintf(stderr, "Failed to initialize GLEW\n");
getchar();
glfwTerminate();
return -1;
}
// Hide the mouse and enable unlimited mouvement
glfwSetInputMode(window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
glfwSetKeyCallback(window, keyCallback);
// Set the mouse at the center of the screen
glfwPollEvents();
glfwSetCursorPos(window, 1024 / 2, 768 / 2);
// Dark blue background
glClearColor(0.0f, 0.0f, 0.4f, 0.0f);
init();
do {
// Clear the screen. It's not mentioned before Tutorial 02, but it can cause flickering, so it's there nonetheless.
glClear(GL_COLOR_BUFFER_BIT);
// Draw nothing, see you in tutorial 2 !
render();
// Swap buffers
glfwSwapBuffers(window);
glfwPollEvents();
} // Check if the ESC key was pressed or the window was closed
while (glfwWindowShouldClose(window) == 0);
glDeleteBuffers(1, &vertexbuffer);
glDeleteBuffers(1, &uvbuffer);
glDeleteBuffers(1, &normalbuffer);
delete m_pTexture;
// Close OpenGL window and terminate GLFW
glfwTerminate();
return 0;
}
| 25.561224 | 144 | 0.694511 | lishi0927 |
955ed946ec4b79f23915a2f23e7206f62d37a087 | 1,832 | cpp | C++ | examples/lennard_jones.cpp | PetterS/spii | 98c5847223d7c3febea5a1aac6f4978dfef207ec | [
"BSD-2-Clause"
] | 35 | 2015-03-03T16:21:40.000Z | 2020-09-16T08:02:12.000Z | examples/lennard_jones.cpp | nashdingsheng/spii | 3130d0dc43af8ae79d1fdf315a8b5fc05fe00321 | [
"BSD-2-Clause"
] | 2 | 2015-07-16T14:41:55.000Z | 2018-04-09T19:27:22.000Z | examples/lennard_jones.cpp | nashdingsheng/spii | 3130d0dc43af8ae79d1fdf315a8b5fc05fe00321 | [
"BSD-2-Clause"
] | 11 | 2015-09-21T23:09:37.000Z | 2021-07-24T20:20:30.000Z | // Petter Strandmark 2012.
//
// See http://doye.chem.ox.ac.uk/jon/structures/LJ/tables.150.html
// for best known minima for N <= 150.
//
#include <functional>
#include <iomanip>
#include <iostream>
#include <random>
#include <spii/auto_diff_term.h>
#include <spii/solver.h>
#include <spii/solver-callbacks.h>
using namespace spii;
struct LennardJonesTerm
{
template<typename R>
R operator()(const R* const p1, const R* const p2) const
{
R dx = p1[0] - p2[0];
R dy = p1[1] - p2[1];
R dz = p1[2] - p2[2];
R r2 = dx*dx + dy*dy + dz*dz;
R r6 = r2*r2*r2;
R r12 = r6*r6;
return 1.0 / r12 - 2.0 / r6;
}
};
int main()
{
using namespace std;
mt19937 prng(1);
normal_distribution<double> normal;
auto randn = bind(normal, ref(prng));
int N = -1;
cout << "Enter N = " << endl;
cin >> N;
Function potential;
vector<Eigen::Vector3d> points(N);
int n = int(ceil(pow(double(N), 1.0/3.0)));
// Initial position is a cubic grid with random pertubations.
for (int i = 0; i < N; ++i) {
int x = i % n;
int y = (i / n) % n;
int z = (i / n) / n;
potential.add_variable(&points[i][0], 3);
points[i][0] = x + 0.05 * randn();
points[i][1] = y + 0.05 * randn();
points[i][2] = z + 0.05 * randn();
}
for (int i = 0; i < N; ++i) {
for (int j = i + 1; j < N; ++j) {
potential.add_term<AutoDiffTerm<LennardJonesTerm, 3, 3>>(
&points[i][0],
&points[j][0]);
}
}
LBFGSSolver solver;
//solver.sparsity_mode = Solver::DENSE; // For NewtonSolver.
solver.maximum_iterations = 3000;
ofstream file("convergence.data");
FileCallback callback(file);
solver.callback_function = callback;
SolverResults results;
solver.solve(potential, &results);
cout << results;
potential.print_timing_information(cout);
cout << "Energy = " << setprecision(10) << potential.evaluate() << endl;
}
| 21.552941 | 73 | 0.621179 | PetterS |
95637a52191c30ceb46b0bb053029d76d08f1ef3 | 1,709 | cpp | C++ | src/etc/subclassing.cpp | rosasurfer/mt4-expander | dc2fb04aaaa62f4ba575d7c16a266169daac417a | [
"WTFPL"
] | 25 | 2017-02-16T16:58:18.000Z | 2021-12-06T06:42:54.000Z | src/etc/subclassing.cpp | rosasurfer/mt4-expander | dc2fb04aaaa62f4ba575d7c16a266169daac417a | [
"WTFPL"
] | 5 | 2016-12-13T05:58:11.000Z | 2020-09-23T17:49:33.000Z | src/etc/subclassing.cpp | rosasurfer/mt4-expander | dc2fb04aaaa62f4ba575d7c16a266169daac417a | [
"WTFPL"
] | 26 | 2017-02-08T13:34:28.000Z | 2022-03-12T10:53:41.000Z | #include "expander.h"
HWND last_hWnd;
WNDPROC origWndProc;
/**
* Custom window procedure
*/
LRESULT WINAPI CustomWndProc(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) {
debug("hWnd=%d, msg=%d, wParam=%p, lParam=%p", hWnd, msg, wParam, lParam);
return(CallWindowProc(origWndProc, hWnd, msg, wParam, lParam));
}
/**
* There is already a macro SubclassWindow in windowsx.h
*/
BOOL WINAPI _SubclassWindow(HWND hWnd) {
if (!IsWindow(hWnd)) return(error(ERR_INVALID_PARAMETER, "invalid parameter hWnd: %d (not a window)", hWnd));
DWORD processId; GetWindowThreadProcessId(hWnd, &processId);
if (processId != GetCurrentProcessId()) return(error(ERR_INVALID_PARAMETER, "window hWnd=%d not owned by the current process", hWnd));
origWndProc = (WNDPROC)SetWindowLong(hWnd, GWL_WNDPROC, (LONG)CustomWndProc);
if (!origWndProc) return(error(ERR_WIN32_ERROR+GetLastError(), "SetWindowLong()"));
last_hWnd = hWnd;
debug("replaced window procedure 0x%p with 0x%p", origWndProc, CustomWndProc);
return(TRUE);
#pragma EXPANDER_EXPORT
}
/**
*
*/
BOOL WINAPI UnsubclassWindow(HWND hWnd) {
if (!hWnd) return(error(ERR_INVALID_PARAMETER, "invalid parameter hWnd: %d (not a window)", hWnd));
if (hWnd != last_hWnd) return(error(ERR_INVALID_PARAMETER, "invalid parameter hWnd: %d (not a subclassed window)", hWnd));
if (!SetWindowLong(hWnd, GWL_WNDPROC, (LONG)origWndProc))
return(error(ERR_WIN32_ERROR+GetLastError(), "SetWindowLong() failed to restore original window procedure"));
last_hWnd = NULL;
origWndProc = NULL;
debug("original window procedure restored");
return(TRUE);
#pragma EXPANDER_EXPORT
}
| 31.648148 | 137 | 0.705091 | rosasurfer |
95690d6c582585067a8f90637256cc0f15103af2 | 562 | cpp | C++ | examples/cpp/factorial-recursion.cpp | vietnux/CodeEditorMobile | acd29a6a647342276eb557f3af579535092ab377 | [
"Apache-2.0"
] | null | null | null | examples/cpp/factorial-recursion.cpp | vietnux/CodeEditorMobile | acd29a6a647342276eb557f3af579535092ab377 | [
"Apache-2.0"
] | null | null | null | examples/cpp/factorial-recursion.cpp | vietnux/CodeEditorMobile | acd29a6a647342276eb557f3af579535092ab377 | [
"Apache-2.0"
] | null | null | null | // C++ program to Calculate Factorial of a Number Using Recursion
// Example to find factorial of a non-negative integer (entered by the user) using recursion.
#include<iostream>
using namespace std;
int factorial(int n);
int main()
{
int n;
cout << "Enter a positive integer: ";
cin >> n;
cout << "Factorial of " << n << " = " << factorial(n);
return 0;
}
int factorial(int n)
{
if(n > 1)
return n * factorial(n - 1);
else
return 1;
}
// https://www.programiz.com/cpp-programming/examples/factorial-recursion | 18.733333 | 93 | 0.629893 | vietnux |
956a84f757664515ab460661f16b9a12aafdd4cd | 1,476 | cpp | C++ | tests.boost/write_xml_with_property_tree.cpp | virgiliosanz/Tests | f24f210b7ef3ef8c8a6b3e915c33ce4f9cf26694 | [
"Unlicense"
] | null | null | null | tests.boost/write_xml_with_property_tree.cpp | virgiliosanz/Tests | f24f210b7ef3ef8c8a6b3e915c33ce4f9cf26694 | [
"Unlicense"
] | null | null | null | tests.boost/write_xml_with_property_tree.cpp | virgiliosanz/Tests | f24f210b7ef3ef8c8a6b3e915c33ce4f9cf26694 | [
"Unlicense"
] | null | null | null | #include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
//<Root>
// <Set Name="1">
// <Field Name="Hello 1"/>
// <Field Name="World 1"/>
// </Set>
// <Set Name="2">
// <Field Name="Hello 2"/>
// <Field Name="World 2"/>
// </Set>
//</Root>
int main(int argc, char* argv[])
{
using boost::property_tree::ptree;
ptree pt;
boost::property_tree::ptree rootNode;
boost::property_tree::ptree setNode1;
boost::property_tree::ptree setNode2;
boost::property_tree::ptree fieldNode1;
boost::property_tree::ptree fieldNode2;
boost::property_tree::ptree fieldNode3;
boost::property_tree::ptree fieldNode4;
fieldNode1.put("<xmlattr>.Name", "Hello 1");
fieldNode2.put("<xmlattr>.Name", "World 1");
fieldNode3.put("<xmlattr>.Name", "Hello 2");
fieldNode4.put("<xmlattr>.Name", "World 2");
setNode1.add_child("Field", fieldNode1);
setNode1.add_child("Field", fieldNode2);
setNode2.add_child("Field", fieldNode3);
setNode2.add_child("Field", fieldNode4);
setNode1.put("<xmlattr>.Name", "1");
setNode2.put("<xmlattr>.Name", "2");
rootNode.add_child("Set", setNode1);
rootNode.add_child("Set", setNode2);
pt.add_child("Root", rootNode);
// boost::property_tree::xml_writer_settings<char> settings('\t', 1);
// write_xml("testXml.xml", pt, std::locale(), settings);
write_xml("testXml.xml", pt, std::locale());
return 0;
}
| 28.941176 | 76 | 0.638211 | virgiliosanz |
956f75011ae92a722898e80f4d7008a1d951494b | 382 | cpp | C++ | VeshApiBattle/battle.cpp | FireAlfa/VeshApi-BattleSystem | 03356f77a61b69597870d7f4773f6744fd78c360 | [
"MIT"
] | null | null | null | VeshApiBattle/battle.cpp | FireAlfa/VeshApi-BattleSystem | 03356f77a61b69597870d7f4773f6744fd78c360 | [
"MIT"
] | null | null | null | VeshApiBattle/battle.cpp | FireAlfa/VeshApi-BattleSystem | 03356f77a61b69597870d7f4773f6744fd78c360 | [
"MIT"
] | null | null | null | #include "battle.h"
Battle::Battle(std::string _name) : name(_name)
{
}
Battle::~Battle()
{
}
void Battle::AddPlayer(Player* p)
{
if (!playerCreated)
{
players.insert(players.begin(), p);
}
playerCreated = true;
}
void Battle::CreateEnemy(std::string _name)
{
Player* p = new Player(_name);
AddEnemy(p);
}
void Battle::AddEnemy(Player* p)
{
players.push_back(p);
} | 11.575758 | 47 | 0.659686 | FireAlfa |
9570cc112d93525ede31d9eddaa9df7c358de5f0 | 433 | cpp | C++ | SOCTestProject/SOCTestProject/Code/main.cpp | Jin02/SOCEngine | 7a04d914149783f54aecf2fbbc4e78a7325f0fbd | [
"MIT"
] | 14 | 2015-12-24T03:08:59.000Z | 2021-12-13T13:29:07.000Z | SOCTestProject/SOCTestProject/Code/main.cpp | Jin02/SOCEngine | 7a04d914149783f54aecf2fbbc4e78a7325f0fbd | [
"MIT"
] | 106 | 2015-08-16T10:32:47.000Z | 2018-10-08T19:01:44.000Z | SOCTestProject/SOCTestProject/Code/main.cpp | Jin02/SOCEngine | 7a04d914149783f54aecf2fbbc4e78a7325f0fbd | [
"MIT"
] | 2 | 2018-03-02T06:17:08.000Z | 2020-02-11T11:19:41.000Z | #include "Launcher.h"
#include "TestScene.h"
using namespace Core;
using namespace Device;
INT WINAPI wWinMain( HINSTANCE hInst, HINSTANCE, LPWSTR, INT )
{
WinApp::Desc desc;
{
desc.rect = Rect<uint>(0, 0, 800, 600);
desc.instance = hInst;
desc.name = "Refactoring";
desc.windowMode = true;
desc.isChild = false;
desc.parentHandle = NULL;
}
Launcher::Run(desc, desc.rect, false, new TestScene);
return 0;
} | 20.619048 | 62 | 0.681293 | Jin02 |
957178ac2813ba9d6f9e33327ecb7f33df76a88d | 823 | hpp | C++ | include/ecst/context/storage/component/chunk/impl/empty.hpp | SuperV1234/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 475 | 2016-05-03T13:34:30.000Z | 2021-11-26T07:02:47.000Z | include/ecst/context/storage/component/chunk/impl/empty.hpp | vittorioromeo/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 28 | 2016-08-30T06:37:40.000Z | 2017-11-24T11:14:07.000Z | include/ecst/context/storage/component/chunk/impl/empty.hpp | vittorioromeo/ecst | b3c42e2c28978f1cd8ea620ade62613c6c875432 | [
"AFL-3.0"
] | 60 | 2016-05-11T22:16:15.000Z | 2021-08-02T20:42:35.000Z | // Copyright (c) 2015-2016 Vittorio Romeo
// License: Academic Free License ("AFL") v. 3.0
// AFL License page: http://opensource.org/licenses/AFL-3.0
// http://vittorioromeo.info | vittorio.romeo@outlook.com
#pragma once
#include <ecst/config.hpp>
#include <ecst/aliases.hpp>
ECST_CONTEXT_STORAGE_COMPONENT_NAMESPACE
{
namespace chunk
{
namespace impl
{
struct empty_metadata
{
};
}
template <typename TComponentTagList>
class empty
{
public:
using component_tag_list_type = TComponentTagList;
using metadata = impl::empty_metadata;
template <typename... Ts>
void add(Ts&&...)
{
}
};
}
}
ECST_CONTEXT_STORAGE_COMPONENT_NAMESPACE_END
| 22.243243 | 62 | 0.589307 | SuperV1234 |
9577a841090e2aca4c6844b31c2bee77695e9685 | 223 | cpp | C++ | src/kasm/externalLoaders.cpp | knoxaramav2/KASM | e678374e579768cc2c9654ee53225684198b00ad | [
"MIT"
] | null | null | null | src/kasm/externalLoaders.cpp | knoxaramav2/KASM | e678374e579768cc2c9654ee53225684198b00ad | [
"MIT"
] | null | null | null | src/kasm/externalLoaders.cpp | knoxaramav2/KASM | e678374e579768cc2c9654ee53225684198b00ad | [
"MIT"
] | null | null | null | #include "externalLoaders.hpp"
#include "instructionRegistery.hpp"
#include "controller.hpp"
#include "graphics.hpp"
void KASM::LoadGraphics(KASM::AsmController&ctrl){
KASM::GRAPHICS::InitGraphics(ctrl);
} | 24.777778 | 51 | 0.726457 | knoxaramav2 |
9578f3f23f9322f4389a65f4c5994e22a9358967 | 9,323 | cpp | C++ | Filtering/Filtering/Probability_Functions.cpp | rnsheehan/Data_Filtering | d187c13065d32358a0ec3276dc0873bb539b02a3 | [
"MIT"
] | null | null | null | Filtering/Filtering/Probability_Functions.cpp | rnsheehan/Data_Filtering | d187c13065d32358a0ec3276dc0873bb539b02a3 | [
"MIT"
] | null | null | null | Filtering/Filtering/Probability_Functions.cpp | rnsheehan/Data_Filtering | d187c13065d32358a0ec3276dc0873bb539b02a3 | [
"MIT"
] | null | null | null | #ifndef ATTACH_H
#include "Attach.h"
#endif
// Implementation of a namespace that contains functions used to compute probabilities in Statistics
// R. Sheehan 5 - 9 - 2017
double probability::gammln(double xx)
{
// Return the value of ln[gamma(xx)] for xx>0
try{
if(xx > 0.0){
double x,tmp,ser;
static double cof[6]={76.18009173,-86.50532033,24.01409822,-1.231739516,0.120858003e-2,-0.536382e-5};
int j;
x=xx-1.0;
tmp=x+5.5;
tmp-=(x+0.5)*log(tmp);
ser=1.0;
for (j=0;j<=5;j++){
x+=1.0;
ser+=(cof[j]/x);
}
return -tmp+log(2.50662827465*ser);
}
else{
std::string reason;
reason = "Error: double probability::gammln(double xx)\n";
reason += "xx input with value = " + template_funcs::toString(xx, 2) + "\n";
throw std::invalid_argument(reason);
}
}
catch(std::invalid_argument &e){
useful_funcs::exit_failure_output(e.what());
exit(EXIT_FAILURE);
}
}
double probability::gammp(double a,double x)
{
// Computes the incomplete gamma function P(a,x) from the functions gser and gcf
try{
if(x > 0.0 && a > 0.0){
double gamser,gammcf,gln;
if(x<(a+1.0)){
gser(&gamser,a,x,&gln);
return gamser;
}
else{
gcf(&gammcf,a,x,&gln);
return 1.0-gammcf;
}
}
else{
std::string reason;
reason = "Error: double probability::gammp(double a,double x)\n";
if(x < 0.0) reason += "x input with value = " + template_funcs::toString(x, 2) + "\n";
if(a <= 0.0) reason += "a input with value = " + template_funcs::toString(a, 2) + "\n";
throw std::invalid_argument(reason);
}
}
catch(std::invalid_argument &e){
useful_funcs::exit_failure_output(e.what());
exit(EXIT_FAILURE);
}
}
double probability::gammq(double a,double x)
{
// Computes the incomplete gamma function Q(a,x)=1-P(a,x) from the functions gser and gcf
try{
if(x > 0.0 && a > 0.0){
double gamser,gammcf,gln;
if(x<(a+1.0)){
gser(&gamser,a,x,&gln);
return 1.0-gamser;
}
else{
gcf(&gammcf,a,x,&gln);
return gammcf;
}
}
else{
std::string reason;
reason = "Error: double probability::gammq(double a,double x)\n";
if(x < 0.0) reason += "x input with value = " + template_funcs::toString(x, 2) + "\n";
if(a <= 0.0) reason += "a input with value = " + template_funcs::toString(a, 2) + "\n";
throw std::invalid_argument(reason);
}
}
catch(std::invalid_argument &e){
useful_funcs::exit_failure_output(e.what());
exit(EXIT_FAILURE);
}
}
void probability::gser(double *gamser,double a,double x,double *gln)
{
// This function returns the incomplete gamma function P(a,x), calculated by its series representation
// Also returns ln[gamma(a)] as gln
try{
if(x > 0.0 && a > 0.0){
int n;
double sum,del,ap;
static const int ITMAX=(150);
static const double EPS=(3.0e-7);
*gln=gammln(a);
if(x<=0.0){
if(x<0.0)
std::cerr<<"x less than 0 in routine GSER"<<"\n";
*gamser=0.0;
return;
}else{
ap=a;
del=sum=1.0/a;
for(n=1;n<=ITMAX;n++){
ap+=1.0;
del*=x/ap;
sum+=del;
if(fabs(del)<fabs(sum)*EPS){
*gamser=sum*exp(-x+a*log(x)-(*gln));
return;
}
}
std::cerr<<"a too large, ITMAX too small in routine GSER"<<"\n";
return;
}
}
else{
std::string reason;
reason = "Error: void probability::gser(double *gamser,double a,double x,double *gln)\n";
if(x < 0.0) reason += "x input with value = " + template_funcs::toString(x, 2) + "\n";
if(a <= 0.0) reason += "a input with value = " + template_funcs::toString(a, 2) + "\n";
throw std::invalid_argument(reason);
}
}
catch(std::invalid_argument &e){
useful_funcs::exit_failure_output(e.what());
exit(EXIT_FAILURE);
}
}
void probability::gcf(double *gammcf, double a, double x, double *gln)
{
// This function returns the incomplete gamma function Q(a,x), calculated by its continued fraction representation
// Also returns ln[gamma(a)] as gln
try{
if(x > 0.0 && a > 0.0){
int n;
double gold=0.0,g,fac=1.0,b1=1.0;
double b0=0.0,anf,ana,an,a1,a0=1.0;
static const int ITMAX=(100);
static const double EPS=(3.0e-7);
*gln=gammln(a);
a1=x;
for(n=1;n<=ITMAX;n++){
an=static_cast<double>(n);
ana=an-a;
a0=(a1+a0*ana)*fac;
b0=(b1+b0*ana)*fac;
anf=an*fac;
a1=x*a0+anf*a1;
b1=x*b0+anf*b1;
if(a1){
fac=1.0/a1;
g=b1*fac;
if(fabs((g-gold)/g)<EPS){
*gammcf=exp(-x+a*log(x)-(*gln))*g;
return;
}
gold=g;
}
}
std::cerr<<"a too large, ITMAX too small in routine GCF"<<"\n";
}
else{
std::string reason;
reason = "Error: void probability::gcf(double *gammcf, double a, double x, double *gln)\n";
if(x < 0.0) reason += "x input with value = " + template_funcs::toString(x, 2) + "\n";
if(a <= 0.0) reason += "a input with value = " + template_funcs::toString(a, 2) + "\n";
throw std::invalid_argument(reason);
}
}
catch(std::invalid_argument &e){
useful_funcs::exit_failure_output(e.what());
exit(EXIT_FAILURE);
}
}
double probability::erff(double x)
{
// Return the error function erf(x)
return ( x < 0.0 ? -gammp(0.5, template_funcs::DSQR(x) ) : gammp(0.5, template_funcs::DSQR(x) ) ) ;
}
double probability::erffc(double x)
{
// Return the complementary error function erfc(x)
return ( x < 0.0 ? 1.0 + gammp(0.5, template_funcs::DSQR(x) ) : gammq(0.5, template_funcs::DSQR(x) ) ) ;
}
double probability::erfcc(double x)
{
// Returns the complementary error function erfc(x) with fractional error everywhere less than 1.2e-7
double t,z,ans;
z=fabs(x);
t=1.0/(1.0+0.5*z);
ans=t*exp(-z*z-1.26551223+t*(1.00002368+t*(0.37409196+t*(0.09678418+
t*(-0.18628806+t*(0.27886807+t*(-1.13520398+t*(1.48851587+
t*(-0.82215223+t*0.17087277)))))))));
return x >= 0.0 ? ans : 2.0-ans;
}
double probability::factorial(int n)
{
// return the factorial of n by recursion
// It is possible to represent 170! as a floating point number
// Attempting to compute 171! will cause numerical overflow
// Factorials up to 22! are exact, 23! and higher are numerically approximate
// See NRinC, sect 6.1.
// R. Sheehan 15 - 4 - 2014
if(n >-1 && n < 170){
if(n == 0 || n == 1){
return 1.0;
}
else if(n == 2){
return 2.0;
}
else if(n == 3){
return 6.0;
}
else if(n == 4){
return 24.0;
}
else if(n == 5){
return 120.0;
}
else if(n == 6){
return 720.0;
}
else{
// recursively compute n!
return ( static_cast<double>(n)*factorial(n-1) );
}
}
else{
std::cerr<<"Cannot compute "<<n<<"! by this method\nc.f. gammln routine for factorials of large numbers";
return 0.0;
}
}
double probability::betacf(double a, double b, double x)
{
// Evaluation of continued fraction expansion for incomplete beta function
// NRinC equation 6.4.5, 6.4.6
try{
int m,m2;
int MAXIT = 100;
double EPS1 = 3.0E-7;
static const double FPMIN=(1.0e-30);
double aa,c,d,del,h,qab,qam,qap;
qab=a+b;
qap=a+1.0;
qam=a-1.0;
c=1.0;
d=1.0-qab*x/qap;
if (fabs(d) < FPMIN) d=FPMIN;
d=1.0/d;
h=d;
for (m=1;m<=MAXIT;m++) {
m2=2*m;
aa=m*(b-m)*x/((qam+m2)*(a+m2));
d=1.0+aa*d;
if (fabs(d) < FPMIN) d=FPMIN;
c=1.0+aa/c;
if (fabs(c) < FPMIN) c=FPMIN;
d=1.0/d;
h *= d*c;
aa = -(a+m)*(qab+m)*x/((a+m2)*(qap+m2));
d=1.0+aa*d;
if (fabs(d) < FPMIN) d=FPMIN;
c=1.0+aa/c;
if (fabs(c) < FPMIN) c=FPMIN;
d=1.0/d;
del=d*c;
h *= del;
if (fabs(del-1.0) < EPS1) break;
}
if (m > MAXIT){
std::string reason;
reason = "Error: probability::betacf()\na or b too big, or MAXIT too small in betacf\n";
throw std::runtime_error(reason);
}
return h;
}
catch(std::runtime_error &e){
std::cerr<<e.what();
return 0.0;
}
}
double probability::betai(double a, double b, double x)
{
// Return the value of the incomplete Beta function I_{x}(a, b)
// NRinC equation 6.4.1
// this is used to compute probabilities related to Student's distribution
try{
if(x < 0.0 || x > 1.0){
std::string reason;
reason = "Error: probability::betai()\n";
reason += "Bad x value\n";
throw std::invalid_argument(reason);
}
else{
double bt;
if (x == 0.0 || x == 1.0){
bt=0.0;
}
else{
bt=exp(gammln(a+b)-gammln(a)-gammln(b)+a*log(x)+b*log(1.0-x));
}
if (x < (a+1.0)/(a+b+2.0)){
return bt*betacf(a,b,x)/a;
}
else{
return 1.0-bt*betacf(b,a,1.0-x)/b;
}
}
}
catch(std::invalid_argument &e){
std::cerr<<e.what();
return 0.0;
}
}
double probability::probks(double alam)
{
// Kolmorgorov-Smirnov Probability Function
try{
if(alam < 0.0){
std::string reason;
reason = "Error: double probability::probks(double alam)\n";
reason += "alam = " + template_funcs::toString(alam) + " < 0\n";
throw std::invalid_argument(reason);
}
else{
int j;
static const double EPS1 = 0.001;
static const double EPS2 = 1.0e-8;
double a2,fac=2.0,sum=0.0,term,termbf=0.0;
a2 = -2.0*alam*alam;
for (j=1;j<=100;j++) {
term=fac*exp(a2*j*j);
sum += term;
if (fabs(term) <= EPS1*termbf || fabs(term) <= EPS2*sum) return sum;
fac = -fac;
termbf=fabs(term);
}
return 1.0;
}
}
catch(std::invalid_argument &e){
std::cerr<<e.what();
return 0.0;
}
} | 23.84399 | 115 | 0.595731 | rnsheehan |
9579502c15e235c8d916c537e50edde00da63ec2 | 419 | cpp | C++ | Plugins/VisCreationHelper/Source/VisCreationHelper/Private/PerfomanceStats/VCHTimerCounter.cpp | Mihalo15z/VisCreationHelper | dcac82b304542a7d4768b2a292cc2408118bf4aa | [
"MIT"
] | null | null | null | Plugins/VisCreationHelper/Source/VisCreationHelper/Private/PerfomanceStats/VCHTimerCounter.cpp | Mihalo15z/VisCreationHelper | dcac82b304542a7d4768b2a292cc2408118bf4aa | [
"MIT"
] | null | null | null | Plugins/VisCreationHelper/Source/VisCreationHelper/Private/PerfomanceStats/VCHTimerCounter.cpp | Mihalo15z/VisCreationHelper | dcac82b304542a7d4768b2a292cc2408118bf4aa | [
"MIT"
] | 1 | 2022-01-17T10:07:17.000Z | 2022-01-17T10:07:17.000Z | #include "PerfomanceStats/VCHTimerCounter.h"
DECLARE_LOG_CATEGORY_CLASS(VCH_PerfomansceLog, Log, All);
FVCHTimeConter::FVCHTimeConter(const FString & InCounterInfo) :CounterInfo(InCounterInfo)
{
StartCicles = FPlatformTime::Cycles();
}
FVCHTimeConter::~FVCHTimeConter()
{
UE_LOG(VCH_PerfomansceLog, Log, TEXT("%s: time = %f"), *CounterInfo, FPlatformTime::ToMilliseconds(FPlatformTime::Cycles() - StartCicles));
}
| 29.928571 | 140 | 0.782816 | Mihalo15z |
957d6b554cc3aabcff4165c63897e11974d3a6fc | 250 | hpp | C++ | dali/sasha/saxref.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 286 | 2015-01-03T12:45:17.000Z | 2022-03-25T18:12:57.000Z | dali/sasha/saxref.hpp | miguelvazq/HPCC-Platform | 22ad8e5fcb59626abfd8febecbdfccb1e9fb0aa5 | [
"Apache-2.0"
] | 9,034 | 2015-01-02T08:49:19.000Z | 2022-03-31T20:34:44.000Z | dali/sasha/saxref.hpp | cloLN/HPCC-Platform | 42ffb763a1cdcf611d3900831973d0a68e722bbe | [
"Apache-2.0"
] | 208 | 2015-01-02T03:27:28.000Z | 2022-02-11T05:54:52.000Z | #ifndef SAXREFIF_HPP
#define SAXREFIF_HPP
interface ISashaServer;
interface ISashaCommand;
extern ISashaServer *createSashaXrefServer();
extern void processXRefRequest(ISashaCommand *cmd);
extern ISashaServer *createSashaFileExpiryServer();
#endif
| 22.727273 | 51 | 0.848 | miguelvazq |
957e61b06d9c417500f98c7f6941d251f4aa958e | 39,293 | cc | C++ | src/mica/test/netbench.cc | yxd886/mica2 | 32dc94af10c8f77c53b06a413e9a466bfc3910e3 | [
"Apache-2.0"
] | null | null | null | src/mica/test/netbench.cc | yxd886/mica2 | 32dc94af10c8f77c53b06a413e9a466bfc3910e3 | [
"Apache-2.0"
] | null | null | null | src/mica/test/netbench.cc | yxd886/mica2 | 32dc94af10c8f77c53b06a413e9a466bfc3910e3 | [
"Apache-2.0"
] | null | null | null | /*-
* BSD LICENSE
*
* Copyright(c) 2010-2016 Intel Corporation. All rights reserved.
* 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 Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "mica/datagram/datagram_client.h"
#include "mica/util/lcore.h"
#include "mica/util/hash.h"
#include "mica/util/zipf.h"
#include "mica/network/dpdk.h"
#include <vector>
#include <map>
#include <iostream>
#include "mica/nf/firewall.h"
#include "mica/nf/load_balancer.h"
#include "mica/nf/nat.h"
#include "mica/nf/ips.h"
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <sys/types.h>
#include <string.h>
#include <sys/queue.h>
#include <stdarg.h>
#include <errno.h>
#include <getopt.h>
#include <string.h>
#include <stdint.h>
#include <setjmp.h>
#include <stdarg.h>
#include <ctype.h>
#include <errno.h>
#include <getopt.h>
#include <signal.h>
#include <stdbool.h>
struct rte_ring* worker2interface[10];
struct rte_ring* interface2worker[10];
#if RTE_LOG_LEVEL >= RTE_LOG_DEBUG
#define L3FWDACL_DEBUG
#endif
#define DO_RFC_1812_CHECKS
#define RTE_LOGTYPE_L3FWD RTE_LOGTYPE_USER1
#define MAX_JUMBO_PKT_LEN 9600
#define MEMPOOL_CACHE_SIZE 256
/*
* This expression is used to calculate the number of mbufs needed
* depending on user input, taking into account memory for rx and tx hardware
* rings, cache per lcore and mtable per port per lcore.
* RTE_MAX is used to ensure that NB_MBUF never goes below a
* minimum value of 8192
*/
#define NB_MBUF RTE_MAX(\
(nb_ports * nb_rx_queue*RTE_TEST_RX_DESC_DEFAULT + \
nb_ports * nb_lcores * MAX_PKT_BURST + \
nb_ports * n_tx_queue * RTE_TEST_TX_DESC_DEFAULT + \
nb_lcores * MEMPOOL_CACHE_SIZE), \
(unsigned)8192)
#define MAX_PKT_BURST 32
#define BURST_TX_DRAIN_US 100 /* TX drain every ~100us */
#define NB_SOCKETS 8
/* Configure how many packets ahead to prefetch, when reading packets */
#define PREFETCH_OFFSET 3
/*
* Configurable number of RX/TX ring descriptors
*/
#define RTE_TEST_RX_DESC_DEFAULT 128
#define RTE_TEST_TX_DESC_DEFAULT 512
static uint16_t nb_rxd = RTE_TEST_RX_DESC_DEFAULT;
static uint16_t nb_txd = RTE_TEST_TX_DESC_DEFAULT;
/* ethernet addresses of ports */
static struct ether_addr ports_eth_addr[RTE_MAX_ETHPORTS];
/* mask of enabled ports */
static uint32_t enabled_port_mask;
static int promiscuous_on; /**< Ports set in promiscuous mode off by default. */
static int numa_on = 1; /**< NUMA is enabled by default. */
struct lcore_rx_queue {
uint8_t port_id;
uint8_t queue_id;
} __rte_cache_aligned;
#define MAX_RX_QUEUE_PER_LCORE 16
#define MAX_TX_QUEUE_PER_PORT RTE_MAX_ETHPORTS
#define MAX_RX_QUEUE_PER_PORT 128
#define MAX_LCORE_PARAMS 1024
struct lcore_params {
uint8_t port_id;
uint8_t queue_id;
uint8_t lcore_id;
} __rte_cache_aligned;
static struct lcore_params lcore_params_array[MAX_LCORE_PARAMS];
static struct lcore_params lcore_params_array_default[] = {
{0, 0, 2},
{0, 1, 2},
{0, 2, 2},
{1, 0, 2},
{1, 1, 2},
{1, 2, 2},
{2, 0, 2},
{3, 0, 3},
{3, 1, 3},
};
static struct lcore_params *lcore_params = lcore_params_array_default;
static uint16_t nb_lcore_params = sizeof(lcore_params_array_default) /
sizeof(lcore_params_array_default[0]);
struct rte_eth_conf port_conf;
static struct rte_mempool *pktmbuf_pool[NB_SOCKETS];
/***********************start of ACL part******************************/
#ifdef DO_RFC_1812_CHECKS
static inline int
is_valid_ipv4_pkt(struct ipv4_hdr *pkt, uint32_t link_len);
#endif
static inline void
send_single_packet(struct rte_mbuf *m, uint8_t port);
#define MAX_ACL_RULE_NUM 100000
#define DEFAULT_MAX_CATEGORIES 1
#define L3FWD_ACL_IPV4_NAME "l3fwd-acl-ipv4"
#define L3FWD_ACL_IPV6_NAME "l3fwd-acl-ipv6"
#define ACL_LEAD_CHAR ('@')
#define ROUTE_LEAD_CHAR ('R')
#define COMMENT_LEAD_CHAR ('#')
#define OPTION_CONFIG "config"
#define OPTION_NONUMA "no-numa"
#define OPTION_ENBJMO "enable-jumbo"
#define OPTION_RULE_IPV4 "rule_ipv4"
#define OPTION_RULE_IPV6 "rule_ipv6"
#define OPTION_SCALAR "scalar"
#define ACL_DENY_SIGNATURE 0xf0000000
#define RTE_LOGTYPE_L3FWDACL RTE_LOGTYPE_USER3
#define acl_log(format, ...) RTE_LOG(ERR, L3FWDACL, format, ##__VA_ARGS__)
#define uint32_t_to_char(ip, a, b, c, d) do {\
*a = (unsigned char)(ip >> 24 & 0xff);\
*b = (unsigned char)(ip >> 16 & 0xff);\
*c = (unsigned char)(ip >> 8 & 0xff);\
*d = (unsigned char)(ip & 0xff);\
} while (0)
#define OFF_ETHHEAD (sizeof(struct ether_hdr))
#define OFF_IPV42PROTO (offsetof(struct ipv4_hdr, next_proto_id))
#define OFF_IPV62PROTO (offsetof(struct ipv6_hdr, proto))
#define MBUF_IPV4_2PROTO(m) \
rte_pktmbuf_mtod_offset((m), uint8_t *, OFF_ETHHEAD + OFF_IPV42PROTO)
#define MBUF_IPV6_2PROTO(m) \
rte_pktmbuf_mtod_offset((m), uint8_t *, OFF_ETHHEAD + OFF_IPV62PROTO)
#define GET_CB_FIELD(in, fd, base, lim, dlm) do { \
unsigned long val; \
char *end; \
errno = 0; \
val = strtoul((in), &end, (base)); \
if (errno != 0 || end[0] != (dlm) || val > (lim)) \
return -EINVAL; \
(fd) = (typeof(fd))val; \
(in) = end + 1; \
} while (0)
/*
* ACL rules should have higher priorities than route ones to ensure ACL rule
* always be found when input packets have multi-matches in the database.
* A exception case is performance measure, which can define route rules with
* higher priority and route rules will always be returned in each lookup.
* Reserve range from ACL_RULE_PRIORITY_MAX + 1 to
* RTE_ACL_MAX_PRIORITY for route entries in performance measure
*/
#define ACL_RULE_PRIORITY_MAX 0x10000000
/*
* Forward port info save in ACL lib starts from 1
* since ACL assume 0 is invalid.
* So, need add 1 when saving and minus 1 when forwarding packets.
*/
#define FWD_PORT_SHIFT 1
/*
* Rule and trace formats definitions.
*/
enum {
PROTO_FIELD_IPV4,
SRC_FIELD_IPV4,
DST_FIELD_IPV4,
SRCP_FIELD_IPV4,
DSTP_FIELD_IPV4,
NUM_FIELDS_IPV4
};
/*
* That effectively defines order of IPV4VLAN classifications:
* - PROTO
* - VLAN (TAG and DOMAIN)
* - SRC IP ADDRESS
* - DST IP ADDRESS
* - PORTS (SRC and DST)
*/
enum {
RTE_ACL_IPV4VLAN_PROTO,
RTE_ACL_IPV4VLAN_VLAN,
RTE_ACL_IPV4VLAN_SRC,
RTE_ACL_IPV4VLAN_DST,
RTE_ACL_IPV4VLAN_PORTS,
RTE_ACL_IPV4VLAN_NUM
};
#define IPV6_ADDR_LEN 16
#define IPV6_ADDR_U16 (IPV6_ADDR_LEN / sizeof(uint16_t))
#define IPV6_ADDR_U32 (IPV6_ADDR_LEN / sizeof(uint32_t))
enum {
PROTO_FIELD_IPV6,
SRC1_FIELD_IPV6,
SRC2_FIELD_IPV6,
SRC3_FIELD_IPV6,
SRC4_FIELD_IPV6,
DST1_FIELD_IPV6,
DST2_FIELD_IPV6,
DST3_FIELD_IPV6,
DST4_FIELD_IPV6,
SRCP_FIELD_IPV6,
DSTP_FIELD_IPV6,
NUM_FIELDS_IPV6
};
enum {
CB_FLD_SRC_ADDR,
CB_FLD_DST_ADDR,
CB_FLD_SRC_PORT_LOW,
CB_FLD_SRC_PORT_DLM,
CB_FLD_SRC_PORT_HIGH,
CB_FLD_DST_PORT_LOW,
CB_FLD_DST_PORT_DLM,
CB_FLD_DST_PORT_HIGH,
CB_FLD_PROTO,
CB_FLD_USERDATA,
CB_FLD_NUM,
};
//RTE_ACL_RULE_DEF(acl4_rule, RTE_DIM(ipv4_defs));
//RTE_ACL_RULE_DEF(acl6_rule, RTE_DIM(ipv6_defs));
struct acl_search_t {
const uint8_t *data_ipv4[MAX_PKT_BURST];
struct rte_mbuf *m_ipv4[MAX_PKT_BURST];
uint32_t res_ipv4[MAX_PKT_BURST];
int num_ipv4;
const uint8_t *data_ipv6[MAX_PKT_BURST];
struct rte_mbuf *m_ipv6[MAX_PKT_BURST];
uint32_t res_ipv6[MAX_PKT_BURST];
int num_ipv6;
};
static struct{
const char *rule_ipv4_name;
const char *rule_ipv6_name;
int scalar;
} parm_config;
const char cb_port_delim[] = ":";
struct lcore_conf {
uint16_t n_rx_queue;
struct lcore_rx_queue rx_queue_list[MAX_RX_QUEUE_PER_LCORE];
uint16_t n_tx_port;
uint16_t tx_port_id[RTE_MAX_ETHPORTS];
uint16_t tx_queue_id[RTE_MAX_ETHPORTS];
struct rte_eth_dev_tx_buffer *tx_buffer[RTE_MAX_ETHPORTS];
} __rte_cache_aligned;
static struct lcore_conf lcore_conf[RTE_MAX_LCORE];
/* Enqueue a single packet, and send burst if queue is filled */
static inline void
send_single_packet(struct rte_mbuf *m, uint8_t port)
{
uint32_t lcore_id;
struct lcore_conf *qconf;
lcore_id = rte_lcore_id();
qconf = &lcore_conf[lcore_id];
rte_eth_tx_buffer(port, qconf->tx_queue_id[port],
qconf->tx_buffer[port], m);
}
static void
l2fwd_simple_forward(struct rte_mbuf *m, unsigned portid, void* function_ptr )
{
//printf("creating firewall\n");
//
//Firewall* a=(Firewall*)function_ptr;
//IPS* a=(IPS*)function_ptr;
//NAT* a=(NAT*)function_ptr;
Load_balancer* a=(Load_balancer*)function_ptr;
struct ether_hdr *eth;
void *tmp;
unsigned dst_port;
int sent;
struct rte_eth_dev_tx_buffer *buffer;
unsigned lcore_id;
lcore_id = rte_lcore_id();
dst_port = portid;
eth = rte_pktmbuf_mtod(m, struct ether_hdr *);
/* 02:00:00:00:00:xx */
// tmp = ð->d_addr.addr_bytes[0];
// *((uint64_t *)tmp) = 0x000000000002 + ((uint64_t)dst_port << 40);
/* src addr */
// ether_addr_copy(&l2fwd_ports_eth_addr[dst_port], ð->s_addr);
a->process_packet(m);
if(a->_drop){
rte_pktmbuf_free(m);
}else{
send_single_packet(m,portid);
}
}
/* main processing loop */
static int
main_loop(__attribute__((unused)) void *dummy)
{
struct rte_mbuf *pkts_burst[MAX_PKT_BURST];
struct rte_mbuf *m;
unsigned lcore_id;
uint64_t prev_tsc, diff_tsc, cur_tsc;
int i, nb_rx;
uint8_t portid, queueid;
struct lcore_conf *qconf;
int socketid;
const uint64_t drain_tsc = (rte_get_tsc_hz() + US_PER_S - 1)
/ US_PER_S * BURST_TX_DRAIN_US;
prev_tsc = 0;
lcore_id = rte_lcore_id();
qconf = &lcore_conf[lcore_id];
socketid = rte_lcore_to_socket_id(lcore_id);
RTE_LOG(INFO, L3FWD, "lcore launched\n", lcore_id);
//load network function
//Firewall a(worker2interface,interface2worker);
//IPS a(worker2interface,interface2worker);
// NAT a(worker2interface,interface2worker,1);
Load_balancer a(worker2interface,interface2worker,1);
if (qconf->n_rx_queue == 0) {
RTE_LOG(INFO, L3FWD, "lcore %u has nothing to do\n", lcore_id);
return 0;
}
RTE_LOG(INFO, L3FWD, "entering main loop on lcore %u\n", lcore_id);
for (i = 0; i < qconf->n_rx_queue; i++) {
portid = qconf->rx_queue_list[i].port_id;
queueid = qconf->rx_queue_list[i].queue_id;
RTE_LOG(INFO, L3FWD,
" -- lcoreid=%u portid=%hhu rxqueueid=%hhu\n",
lcore_id, portid, queueid);
}
while (1) {
cur_tsc = rte_rdtsc();
/*
* TX burst queue drain
*/
diff_tsc = cur_tsc - prev_tsc;
if (unlikely(diff_tsc > drain_tsc)) {
for (i = 0; i < qconf->n_tx_port; ++i) {
portid = qconf->tx_port_id[i];
rte_eth_tx_buffer_flush(portid,
qconf->tx_queue_id[portid],
qconf->tx_buffer[portid]);
}
prev_tsc = cur_tsc;
}
/*
* Read packet from RX queues
*/
for (i = 0; i < qconf->n_rx_queue; ++i) {
portid = qconf->rx_queue_list[i].port_id;
queueid = qconf->rx_queue_list[i].queue_id;
nb_rx = rte_eth_rx_burst(portid, queueid,
pkts_burst, MAX_PKT_BURST);
if (nb_rx > 0) {
//
for (int j = 0; j < nb_rx; j++) {
m = pkts_burst[j];
rte_prefetch0(rte_pktmbuf_mtod(m, void *));
l2fwd_simple_forward(m, portid,static_cast<void*>(&a));
}
}
}
}
}
static int
check_lcore_params(void)
{
uint8_t queue, lcore;
uint16_t i;
int socketid;
for (i = 0; i < nb_lcore_params; ++i) {
queue = lcore_params[i].queue_id;
if (queue >= MAX_RX_QUEUE_PER_PORT) {
printf("invalid queue number: %hhu\n", queue);
return -1;
}
lcore = lcore_params[i].lcore_id;
if (!rte_lcore_is_enabled(lcore)) {
printf("error: lcore %hhu is not enabled in "
"lcore mask\n", lcore);
return -1;
}
socketid = rte_lcore_to_socket_id(lcore);
if (socketid != 0 && numa_on == 0) {
printf("warning: lcore %hhu is on socket %d "
"with numa off\n",
lcore, socketid);
}
}
return 0;
}
static int
check_port_config(const unsigned nb_ports)
{
unsigned portid;
uint16_t i;
for (i = 0; i < nb_lcore_params; ++i) {
portid = lcore_params[i].port_id;
if ((enabled_port_mask & (1 << portid)) == 0) {
printf("port %u is not enabled in port mask\n", portid);
return -1;
}
if (portid >= nb_ports) {
printf("port %u is not present on the board\n", portid);
return -1;
}
}
return 0;
}
static uint8_t
get_port_n_rx_queues(const uint8_t port)
{
int queue = -1;
uint16_t i;
for (i = 0; i < nb_lcore_params; ++i) {
if (lcore_params[i].port_id == port &&
lcore_params[i].queue_id > queue)
queue = lcore_params[i].queue_id;
}
return (uint8_t)(++queue);
}
static int
init_lcore_rx_queues(void)
{
uint16_t i, nb_rx_queue;
uint8_t lcore;
for (i = 0; i < nb_lcore_params; ++i) {
lcore = lcore_params[i].lcore_id;
nb_rx_queue = lcore_conf[lcore].n_rx_queue;
if (nb_rx_queue >= MAX_RX_QUEUE_PER_LCORE) {
printf("error: too many queues (%u) for lcore: %u\n",
(unsigned)nb_rx_queue + 1, (unsigned)lcore);
return -1;
} else {
lcore_conf[lcore].rx_queue_list[nb_rx_queue].port_id =
lcore_params[i].port_id;
lcore_conf[lcore].rx_queue_list[nb_rx_queue].queue_id =
lcore_params[i].queue_id;
lcore_conf[lcore].n_rx_queue++;
}
}
return 0;
}
/* display usage */
static void
print_usage(const char *prgname)
{
printf("%s [EAL options] -- -p PORTMASK -P"
"--"OPTION_RULE_IPV4"=FILE"
"--"OPTION_RULE_IPV6"=FILE"
" [--"OPTION_CONFIG" (port,queue,lcore)[,(port,queue,lcore]]"
" [--"OPTION_ENBJMO" [--max-pkt-len PKTLEN]]\n"
" -p PORTMASK: hexadecimal bitmask of ports to configure\n"
" -P : enable promiscuous mode\n"
" --"OPTION_CONFIG": (port,queue,lcore): "
"rx queues configuration\n"
" --"OPTION_NONUMA": optional, disable numa awareness\n"
" --"OPTION_ENBJMO": enable jumbo frame"
" which max packet len is PKTLEN in decimal (64-9600)\n"
" --"OPTION_RULE_IPV4"=FILE: specify the ipv4 rules entries "
"file. "
"Each rule occupy one line. "
"2 kinds of rules are supported. "
"One is ACL entry at while line leads with character '%c', "
"another is route entry at while line leads with "
"character '%c'.\n"
" --"OPTION_RULE_IPV6"=FILE: specify the ipv6 rules "
"entries file.\n"
" --"OPTION_SCALAR": Use scalar function to do lookup\n",
prgname, ACL_LEAD_CHAR, ROUTE_LEAD_CHAR);
}
static int
parse_max_pkt_len(const char *pktlen)
{
char *end = NULL;
unsigned long len;
/* parse decimal string */
len = strtoul(pktlen, &end, 10);
if ((pktlen[0] == '\0') || (end == NULL) || (*end != '\0'))
return -1;
if (len == 0)
return -1;
return len;
}
static int
parse_portmask(const char *portmask)
{
char *end = NULL;
unsigned long pm;
/* parse hexadecimal string */
pm = strtoul(portmask, &end, 16);
if ((portmask[0] == '\0') || (end == NULL) || (*end != '\0'))
return -1;
if (pm == 0)
return -1;
return pm;
}
static int
parse_config(const char *q_arg)
{
char s[256];
const char *p, *p0 = q_arg;
char *end;
enum fieldnames {
FLD_PORT = 0,
FLD_QUEUE,
FLD_LCORE,
_NUM_FLD
};
unsigned long int_fld[_NUM_FLD];
char *str_fld[_NUM_FLD];
int i;
unsigned size;
nb_lcore_params = 0;
while ((p = strchr(p0, '(')) != NULL) {
++p;
if ((p0 = strchr(p, ')')) == NULL)
return -1;
size = p0 - p;
if (size >= sizeof(s))
return -1;
snprintf(s, sizeof(s), "%.*s", size, p);
if (rte_strsplit(s, sizeof(s), str_fld, _NUM_FLD, ',') !=
_NUM_FLD)
return -1;
for (i = 0; i < _NUM_FLD; i++) {
errno = 0;
int_fld[i] = strtoul(str_fld[i], &end, 0);
if (errno != 0 || end == str_fld[i] || int_fld[i] > 255)
return -1;
}
if (nb_lcore_params >= MAX_LCORE_PARAMS) {
printf("exceeded max number of lcore params: %hu\n",
nb_lcore_params);
return -1;
}
lcore_params_array[nb_lcore_params].port_id =
(uint8_t)int_fld[FLD_PORT];
lcore_params_array[nb_lcore_params].queue_id =
(uint8_t)int_fld[FLD_QUEUE];
lcore_params_array[nb_lcore_params].lcore_id =
(uint8_t)int_fld[FLD_LCORE];
++nb_lcore_params;
}
lcore_params = lcore_params_array;
return 0;
}
/* Parse the argument given in the command line of the application */
static int
parse_args(int argc, char **argv)
{
int opt, ret;
char **argvopt;
int option_index;
char *prgname = argv[0];
static struct option lgopts[] = {
{OPTION_CONFIG, 1, 0, 0},
{OPTION_NONUMA, 0, 0, 0},
{OPTION_ENBJMO, 0, 0, 0},
{OPTION_RULE_IPV4, 1, 0, 0},
{OPTION_RULE_IPV6, 1, 0, 0},
{OPTION_SCALAR, 0, 0, 0},
{NULL, 0, 0, 0}
};
argvopt = argv;
while ((opt = getopt_long(argc, argvopt, "p:P",
lgopts, &option_index)) != EOF) {
switch (opt) {
/* portmask */
case 'p':
enabled_port_mask = parse_portmask(optarg);
if (enabled_port_mask == 0) {
printf("invalid portmask\n");
print_usage(prgname);
return -1;
}
break;
case 'P':
printf("Promiscuous mode selected\n");
promiscuous_on = 1;
break;
/* long options */
case 0:
if (!strncmp(lgopts[option_index].name,
OPTION_CONFIG,
sizeof(OPTION_CONFIG))) {
ret = parse_config(optarg);
if (ret) {
printf("invalid config\n");
print_usage(prgname);
return -1;
}
}
if (!strncmp(lgopts[option_index].name,
OPTION_NONUMA,
sizeof(OPTION_NONUMA))) {
printf("numa is disabled\n");
numa_on = 0;
}
if (!strncmp(lgopts[option_index].name,
OPTION_ENBJMO, sizeof(OPTION_ENBJMO))) {
struct option lenopts = {
"max-pkt-len",
required_argument,
0,
0
};
printf("jumbo frame is enabled\n");
port_conf.rxmode.jumbo_frame = 1;
/*
* if no max-pkt-len set, then use the
* default value ETHER_MAX_LEN
*/
if (0 == getopt_long(argc, argvopt, "",
&lenopts, &option_index)) {
ret = parse_max_pkt_len(optarg);
if ((ret < 64) ||
(ret > MAX_JUMBO_PKT_LEN)) {
printf("invalid packet "
"length\n");
print_usage(prgname);
return -1;
}
port_conf.rxmode.max_rx_pkt_len = ret;
}
printf("set jumbo frame max packet length "
"to %u\n",
(unsigned int)
port_conf.rxmode.max_rx_pkt_len);
}
if (!strncmp(lgopts[option_index].name,
OPTION_RULE_IPV4,
sizeof(OPTION_RULE_IPV4)))
parm_config.rule_ipv4_name = optarg;
if (!strncmp(lgopts[option_index].name,
OPTION_RULE_IPV6,
sizeof(OPTION_RULE_IPV6))) {
parm_config.rule_ipv6_name = optarg;
}
if (!strncmp(lgopts[option_index].name,
OPTION_SCALAR, sizeof(OPTION_SCALAR)))
parm_config.scalar = 1;
break;
default:
print_usage(prgname);
return -1;
}
}
if (optind >= 0)
argv[optind-1] = prgname;
ret = optind-1;
optind = 0; /* reset getopt lib */
return ret;
}
static void
print_ethaddr(const char *name, const struct ether_addr *eth_addr)
{
char buf[ETHER_ADDR_FMT_SIZE];
ether_format_addr(buf, ETHER_ADDR_FMT_SIZE, eth_addr);
printf("%s%s", name, buf);
}
static int
init_mem(unsigned nb_mbuf)
{
int socketid;
unsigned lcore_id;
char s[64];
for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
if (rte_lcore_is_enabled(lcore_id) == 0)
continue;
if (numa_on){
socketid = rte_lcore_to_socket_id(lcore_id);
printf("socketid= %d\n",socketid);
}else
socketid = 0;
if (socketid >= NB_SOCKETS) {
rte_exit(EXIT_FAILURE,
"Socket %d of lcore %u is out of range %d\n",
socketid, lcore_id, NB_SOCKETS);
}
if (pktmbuf_pool[socketid] == NULL) {
snprintf(s, sizeof(s), "mbuf_pool_%d", socketid);
printf("s: %s, nb_mbuf:%d,MEMPOOL_CACHE_SIZE:%d, RTE_MBUF_DEFAULT_BUF_SIZE: %d\n",s,nb_mbuf,MEMPOOL_CACHE_SIZE,RTE_MBUF_DEFAULT_BUF_SIZE);
pktmbuf_pool[socketid] =
rte_pktmbuf_pool_create(s, nb_mbuf,
MEMPOOL_CACHE_SIZE, 0,
RTE_MBUF_DEFAULT_BUF_SIZE,
socketid);
if (pktmbuf_pool[socketid] == NULL)
rte_exit(EXIT_FAILURE,
"Cannot init mbuf pool on socket %d,errno: %s\n",
socketid,rte_strerror(rte_errno));
else
printf("Allocated mbuf pool on socket %d\n",
socketid);
}
}
return 0;
}
/* Check the link status of all ports in up to 9s, and print them finally */
static void
check_all_ports_link_status(uint8_t port_num, uint32_t port_mask)
{
#define CHECK_INTERVAL 100 /* 100ms */
#define MAX_CHECK_TIME 90 /* 9s (90 * 100ms) in total */
uint8_t portid, count, all_ports_up, print_flag = 0;
struct rte_eth_link link;
printf("\nChecking link status");
fflush(stdout);
for (count = 0; count <= MAX_CHECK_TIME; count++) {
all_ports_up = 1;
for (portid = 0; portid < port_num; portid++) {
if ((port_mask & (1 << portid)) == 0)
continue;
memset(&link, 0, sizeof(link));
rte_eth_link_get_nowait(portid, &link);
/* print link status if flag set */
if (print_flag == 1) {
if (link.link_status)
printf("Port %d Link Up - speed %u "
"Mbps - %s\n", (uint8_t)portid,
(unsigned)link.link_speed,
(link.link_duplex == ETH_LINK_FULL_DUPLEX) ?
("full-duplex") : ("half-duplex\n"));
else
printf("Port %d Link Down\n",
(uint8_t)portid);
continue;
}
/* clear all_ports_up flag if any link down */
if (link.link_status == ETH_LINK_DOWN) {
all_ports_up = 0;
break;
}
}
/* after finally printing all link status, get out */
if (print_flag == 1)
break;
if (all_ports_up == 0) {
printf(".");
fflush(stdout);
rte_delay_ms(CHECK_INTERVAL);
}
/* set the print_flag if all ports up or timeout */
if (all_ports_up == 1 || count == (MAX_CHECK_TIME - 1)) {
print_flag = 1;
printf("done\n");
}
}
}
void prepare_rte_ring(){
for(int i=0; i<10; i++){
worker2interface[i] = rte_ring_create(("worker2interface"+std::to_string(i)).c_str(), 1024,
rte_socket_id(), RING_F_SC_DEQ | RING_F_SP_ENQ);
interface2worker[i] = rte_ring_create(("interface2worker"+std::to_string(i)).c_str(), 1024,
rte_socket_id(), RING_F_SC_DEQ | RING_F_SP_ENQ);
}
}
void port_config(){
port_conf.rxmode.mq_mode = ETH_MQ_RX_RSS,
port_conf.rxmode.max_rx_pkt_len = ETHER_MAX_LEN,
port_conf.rxmode.split_hdr_size = 0,
port_conf.rxmode.header_split = 0, /**< Header Split disabled */
port_conf.rxmode.hw_ip_checksum = 1, /**< IP checksum offload enabled */
port_conf.rxmode.hw_vlan_filter = 0, /**< VLAN filtering disabled */
port_conf.rxmode.jumbo_frame = 0, /**< Jumbo Frame Support disabled */
port_conf.rxmode.hw_strip_crc = 0, /**< CRC stripped by hardware */
port_conf.rx_adv_conf.rss_conf.rss_key = NULL,
port_conf.rx_adv_conf.rss_conf.rss_hf = ETH_RSS_IP | ETH_RSS_UDP |
ETH_RSS_TCP | ETH_RSS_SCTP,
port_conf.txmode.mq_mode = ETH_MQ_TX_NONE;
}
void checkok(struct session_state* stat){
if(stat->_action==WRITE&&stat->lcore_id==0&&stat->_firewall_state._recv_ack==10086&&stat->_ips_state._dfa_id==100&&stat->_load_balancer_state._dst_ip_addr==1234&&stat->_nat_state._dst_port==4399){
printf("OK\n");
}else{
printf("ERROR\n");
}
}
//for mica
class ResponseHandle
: public ::mica::datagram::ResponseHandlerInterface<Client> {
public:
ResponseHandle(std::map<uint64_t,uint64_t> *lcore_map,struct rte_ring** worker2interface,struct rte_ring** interface2worker):_lcore_map(lcore_map),_worker2interface(worker2interface),_interface2worker(interface2worker){
}
void handle(Client::RequestDescriptor rd, Result result, const char* value,
size_t value_length,uint64_t key_hash, const Argument& arg) {
struct session_state* hash_rcv_state=nullptr;
char* rcv_value=(char*)value;
std::map<uint64_t,uint64_t>::iterator iter;
if(result==::mica::table::Result::kSuccess||result==::mica::table::Result::setSuccess){
if(result==::mica::table::Result::kSuccess){
if(DEBUG==1) printf("result==::mica::table::Result::kSuccess\n");
hash_rcv_state=reinterpret_cast<struct session_state*>(rcv_value);
checkok(hash_rcv_state);
}
if(result==::mica::table::Result::setSuccess){
if(DEBUG==1) printf("result==::mica::table::Result::setSuccess\n");
}
}else if(result==::mica::table::Result::kNotFound){
if(DEBUG==1) printf("NOT FIND THE KEY FROM SERVER\n");
}else if(result==::mica::table::Result::kPartialValue){
if(DEBUG==1) printf("result==::mica::table::Result::kPartialValue\n");
}else if(result==::mica::table::Result::kError){
if(DEBUG==1) printf("result==::mica::table::Result::kError\n");
}else if(result==::mica::table::Result::kExists){
if(DEBUG==1) printf("result==::mica::table::Result::kExists\n");
}else if(result==::mica::table::Result::kInsufficientSpace){
if(DEBUG==1) printf("result==::mica::table::Result::kInsufficientSpace\n");
}
}
struct rte_ring** _worker2interface;
struct rte_ring** _interface2worker;
std::map<uint64_t,uint64_t> *_lcore_map;
};
int
main(int argc, char **argv)
{
struct lcore_conf *qconf;
struct rte_eth_dev_info dev_info;
struct rte_eth_txconf *txconf;
int ret;
unsigned nb_ports;
uint16_t queueid;
unsigned lcore_id;
uint32_t n_tx_queue, nb_lcores;
uint8_t portid, nb_rx_queue, queue, socketid;
//::mica::util::lcore.pin_thread(0);
port_config();
/* init EAL */
ret = rte_eal_init(argc, argv);
if (ret < 0)
rte_exit(EXIT_FAILURE, "Invalid EAL parameters\n");
argc -= ret;
argv += ret;
/* parse application arguments (after the EAL ones) */
ret = parse_args(argc, argv);
if (ret < 0)
rte_exit(EXIT_FAILURE, "Invalid L3FWD parameters\n");
if (check_lcore_params() < 0)
rte_exit(EXIT_FAILURE, "check_lcore_params failed\n");
ret = init_lcore_rx_queues();
if (ret < 0)
rte_exit(EXIT_FAILURE, "init_lcore_rx_queues failed\n");
nb_ports = rte_eth_dev_count(); //leave one port for mica
printf("number of port: %d\n",nb_ports);
if (check_port_config(nb_ports) < 0)
rte_exit(EXIT_FAILURE, "check_port_config failed\n");
/* Add ACL rules and route entries, build trie */
//if (app_acl_init() < 0)
// rte_exit(EXIT_FAILURE, "app_acl_init failed\n");
nb_lcores = rte_lcore_count();
prepare_rte_ring();
/* initialize all ports */
for (portid = 0; portid < nb_ports; portid++) {
/* skip ports that are not enabled */
if ((enabled_port_mask & (1 << portid)) == 0) {
printf("\nSkipping disabled port %d\n", portid);
continue;
}
/* init port */
printf("Initializing port %d ... ", portid);
fflush(stdout);
nb_rx_queue = get_port_n_rx_queues(portid);
n_tx_queue = nb_lcores;
if (n_tx_queue > MAX_TX_QUEUE_PER_PORT)
n_tx_queue = MAX_TX_QUEUE_PER_PORT;
printf("Creating queues: nb_rxq=%d nb_txq=%u... ",
nb_rx_queue, (unsigned)n_tx_queue);
ret = rte_eth_dev_configure(portid, nb_rx_queue,
(uint16_t)n_tx_queue, &port_conf);
if (ret < 0)
rte_exit(EXIT_FAILURE,
"Cannot configure device: err=%d, port=%d\n",
ret, portid);
rte_eth_macaddr_get(portid, &ports_eth_addr[portid]);
print_ethaddr(" Address:", &ports_eth_addr[portid]);
printf(", ");
/* init memory */
ret = init_mem(NB_MBUF);
if (ret < 0)
rte_exit(EXIT_FAILURE, "init_mem failed\n");
for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
if (rte_lcore_is_enabled(lcore_id) == 0)
continue;
/* Initialize TX buffers */
qconf = &lcore_conf[lcore_id];
qconf->tx_buffer[portid] = (struct rte_eth_dev_tx_buffer *)rte_zmalloc_socket("tx_buffer",
RTE_ETH_TX_BUFFER_SIZE(MAX_PKT_BURST), 0,
rte_eth_dev_socket_id(portid));
if (qconf->tx_buffer[portid] == NULL)
rte_exit(EXIT_FAILURE, "Can't allocate tx buffer for port %u\n",
(unsigned) portid);
rte_eth_tx_buffer_init(qconf->tx_buffer[portid], MAX_PKT_BURST);
}
/* init one TX queue per couple (lcore,port) */
queueid = 0;
for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
if (rte_lcore_is_enabled(lcore_id) == 0)
continue;
if (numa_on)
socketid = (uint8_t)
rte_lcore_to_socket_id(lcore_id);
else
socketid = 0;
printf("txq=%u,%d,%d ", lcore_id, queueid, socketid);
fflush(stdout);
rte_eth_dev_info_get(portid, &dev_info);
txconf = &dev_info.default_txconf;
if (port_conf.rxmode.jumbo_frame)
txconf->txq_flags = 0;
ret = rte_eth_tx_queue_setup(portid, queueid, nb_txd,
socketid, txconf);
if (ret < 0)
rte_exit(EXIT_FAILURE,
"rte_eth_tx_queue_setup: err=%d, "
"port=%d\n", ret, portid);
qconf = &lcore_conf[lcore_id];
qconf->tx_queue_id[portid] = queueid;
queueid++;
qconf->tx_port_id[qconf->n_tx_port] = portid;
qconf->n_tx_port++;
}
printf("\n");
}
for (lcore_id = 0; lcore_id < RTE_MAX_LCORE; lcore_id++) {
if (rte_lcore_is_enabled(lcore_id) == 0)
continue;
qconf = &lcore_conf[lcore_id];
printf("\nInitializing rx queues on lcore %u ... ", lcore_id);
fflush(stdout);
/* init RX queues */
for (queue = 0; queue < qconf->n_rx_queue; ++queue) {
portid = qconf->rx_queue_list[queue].port_id;
queueid = qconf->rx_queue_list[queue].queue_id;
if (numa_on)
socketid = (uint8_t)
rte_lcore_to_socket_id(lcore_id);
else
socketid = 0;
printf("rxq=%d,%d,%d ", portid, queueid, socketid);
fflush(stdout);
ret = rte_eth_rx_queue_setup(portid, queueid, nb_rxd,
socketid, NULL,
pktmbuf_pool[socketid]);
if (ret < 0)
rte_exit(EXIT_FAILURE,
"rte_eth_rx_queue_setup: err=%d,"
"port=%d\n", ret, portid);
}
}
printf("\n");
/* start ports */
for (portid = 0; portid < nb_ports; portid++) {
if ((enabled_port_mask & (1 << portid)) == 0)
continue;
/* Start device */
ret = rte_eth_dev_start(portid);
if (ret < 0)
rte_exit(EXIT_FAILURE,
"rte_eth_dev_start: err=%d, port=%d\n",
ret, portid);
/*
* If enabled, put device in promiscuous mode.
* This allows IO forwarding mode to forward packets
* to itself through 2 cross-connected ports of the
* target machine.
*/
if (promiscuous_on)
rte_eth_promiscuous_enable(portid);
}
check_all_ports_link_status((uint8_t)nb_ports, enabled_port_mask);
/* launch per-lcore init on every lcore */
//rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
int num=rte_lcore_count();
//lcore_id=0;
// RTE_LCORE_FOREACH_SLAVE(lcore_id){
// printf("launch network function on core %d\n",lcore_id);
// rte_eal_remote_launch(main_loop, NULL, lcore_id);
// }
// rte_eal_mp_remote_launch(main_loop, NULL, CALL_MASTER);
if(DEBUG==1) printf("master core ready to run mica client\n");
//start mica client
auto config = ::mica::util::Config::load_file("client.json");
DatagramClientConfig::Network network(config.get("network"),true);
network.start();
Client::DirectoryClient dir_client(config.get("dir_client"));
Client client(config.get("client"), &network, &dir_client);
client.discover_servers();
int master = rte_get_master_lcore();
::mica::util::lcore.pin_thread(master);
client.probe_reachability();
std::map<uint64_t,uint64_t> lcore_map;
ResponseHandle rh(&lcore_map,worker2interface,interface2worker);
size_t num_items = 192 * 1048576;
// double get_ratio = 0.95;
double get_ratio = 0.50;
uint32_t get_threshold = (uint32_t)(get_ratio * (double)((uint32_t)-1));
::mica::util::Rand op_type_rand(static_cast<uint64_t>(master) + 1000);
::mica::util::ZipfGen zg(num_items, 0.5,
static_cast<uint64_t>(master));
::mica::util::Stopwatch sw;
sw.init_start();
sw.init_end();
uint64_t key_i=100;
uint64_t key_hash;
size_t value_length;
char* value;
size_t rcv_value_length;
char* rcv_value;
IPS a(worker2interface,interface2worker);
char* key = reinterpret_cast<char*>(&key_i);
size_t key_length = sizeof(key_i);
struct session_state stat;
stat._action=WRITE;
stat.lcore_id=0;
stat._firewall_state._recv_ack=10086;
stat._ips_state._dfa_id=100;
stat._load_balancer_state._dst_ip_addr=1234;
stat._nat_state._dst_port=4399;
value=reinterpret_cast<char*>(&stat);
value_length=sizeof(stat);
key_hash= hash(key, key_length);
client.set(key_hash, key, key_length, value, value_length, true);
// bool use_noop = true;
uint64_t last_handle_response_time = sw.now();
// Check the response after sending some requests.
// Ideally, packets per batch for both RX and TX should be similar.
uint64_t response_check_interval = 20 * sw.c_1_usec();
void* dequeue_output[1];
struct rte_ring_item* rcv_item;
struct session_state* rcv_state;
struct session_state* hash_rcv_state;
while (true) {
// Determine the operation type.
uint32_t op_r = op_type_rand.next_u32();
bool is_get = op_r <= get_threshold;
// Generate the key.
uint64_t now = sw.now();
while (!client.can_request(key_hash) ||
sw.diff_in_cycles(now, last_handle_response_time) >=
response_check_interval) {
last_handle_response_time = now;
//printf("master handle_response now\n");
client.handle_response(rh);
//printf("master handle_response finished\n");
}
client.get(key_hash, key, key_length);
}
return 0;
}
| 30.202152 | 220 | 0.599216 | yxd886 |
9580c7627e712a3d93592d20d2cfb45532525717 | 17,564 | cc | C++ | src/ctm-cluster-io.cc | jurajHasik/pi-peps | 69da1380a0971a2f1bc58f743553368e4353232d | [
"MIT"
] | 12 | 2019-03-24T02:52:10.000Z | 2020-03-19T01:38:07.000Z | src/ctm-cluster-io.cc | jurajHasik/p-ipeps | 69da1380a0971a2f1bc58f743553368e4353232d | [
"MIT"
] | 11 | 2019-02-22T09:39:21.000Z | 2019-04-03T09:16:11.000Z | src/ctm-cluster-io.cc | jurajHasik/pi-peps | 69da1380a0971a2f1bc58f743553368e4353232d | [
"MIT"
] | 3 | 2019-07-24T10:26:52.000Z | 2021-03-11T08:52:07.000Z | #include "pi-peps/config.h"
#include "pi-peps/ctm-cluster-io.h"
using namespace std;
IO_ENV_FMT toIO_ENV_FMT(string const& ioFmt) {
if (ioFmt == "IO_ENV_FMT_txt")
return IO_ENV_FMT_txt;
if (ioFmt == "IO_ENV_FMT_bin")
return IO_ENV_FMT_bin;
cout << "Unsupported IO_ENV_FMT" << std::endl;
exit(EXIT_FAILURE);
// return -1;
}
// ############################################################################
// IO for cluster definition using JSON data format
std::unique_ptr<Cluster> p_readCluster(string const& filename) {
ifstream infile;
infile.open(filename, ios::in);
nlohmann::json jsonCls;
infile >> jsonCls;
jsonCls["initBy"] = "FILE";
return p_readCluster(jsonCls);
}
// TODO build register-enable factory
std::unique_ptr<Cluster> p_readCluster(nlohmann::json const& jsonCls) {
ClusterFactory cf = ClusterFactory();
auto p_cls = cf.create(jsonCls);
for (const auto& mapEntry : jsonCls["map"].get<vector<nlohmann::json>>()) {
p_cls->cToS[make_pair(mapEntry["x"].get<int>(), mapEntry["y"].get<int>())] =
mapEntry["siteId"].get<string>();
p_cls->vToId[Vertex(mapEntry["x"].get<int>(), mapEntry["y"].get<int>())] =
mapEntry["siteId"].get<string>();
p_cls->idToV[mapEntry["siteId"].get<string>()] =
Vertex(mapEntry["x"].get<int>(), mapEntry["y"].get<int>());
}
for (const auto& siteIdEntry : jsonCls["siteIds"].get<vector<string>>()) {
p_cls->siteIds.push_back(siteIdEntry);
p_cls->SI[siteIdEntry] = p_cls->siteIds.size() - 1;
}
for (const auto& siteEntry : jsonCls["sites"]) {
auto id = siteEntry["siteId"].get<string>();
auto tmp = readIndsAndTfromJSON(siteEntry);
p_cls->mphys[id] = tmp.first[0];
p_cls->caux[id] = std::vector<itensor::Index>(tmp.first.size() - 1);
for (int i = 1; i < tmp.first.size(); i++)
p_cls->caux[id][i - 1] = tmp.first[i];
// std::copy( tmp.first.begin()+1, tmp.first.end(), c.caux[id] );
p_cls->sites[id] = tmp.second; // tensor
}
// construction of weights on links within c
if (jsonCls.value("linkWeightsUsed", false)) {
readClusterWeights(*p_cls, jsonCls); // reads the link-weights data
initClusterWeights(*p_cls); // creates the link-weight tensors
}
return p_cls;
}
void readClusterWeights(Cluster& cls, nlohmann::json const& jsonCls) {
for (const auto& siteIdEntry : jsonCls["siteIds"].get<vector<string>>())
cls.siteToWeights[siteIdEntry] = vector<LinkWeight>();
for (const auto& lwEntry :
jsonCls["linkWeights"].get<vector<nlohmann::json>>()) {
LinkWeight lw = {lwEntry["sites"].get<vector<string>>(),
lwEntry["directions"].get<vector<int>>(),
lwEntry["weightId"].get<string>()};
LinkWeight rlw = lw;
reverse(rlw.sId.begin(), rlw.sId.end());
reverse(rlw.dirs.begin(), rlw.dirs.end());
cls.siteToWeights[lw.sId[0]].push_back(lw);
cls.siteToWeights[rlw.sId[0]].push_back(rlw);
}
}
/*
* TODO object Cluster contains map with actual ITensor objects
* which are not suitable for json representations
*
*/
void writeCluster(string const& filename, Cluster const& cls) {
ofstream outf;
outf.open(filename, ios::out);
nlohmann::json jCls;
jCls["type"] = cls.cluster_type;
jCls["meta"] = cls.metaInfo;
jCls["simParam"] = cls.simParam;
jCls["lX"] = cls.lX;
jCls["lY"] = cls.lY;
vector<nlohmann::json> jcToS;
for (auto const& entry : cls.cToS) {
nlohmann::json jentry;
jentry["x"] = entry.first.first;
jentry["y"] = entry.first.second;
jentry["siteId"] = entry.second;
jcToS.push_back(jentry);
}
jCls["map"] = jcToS;
jCls["siteIds"] = cls.siteIds;
if (cls.siteToWeights.size() > 0) {
jCls["linkWeightsUsed"] = true;
vector<nlohmann::json> jlws;
vector<std::string> lwIds;
for (auto const& stw : cls.siteToWeights)
for (auto const& lw : stw.second)
if (std::find(lwIds.begin(), lwIds.end(), lw.wId) == lwIds.end()) {
nlohmann::json jentry;
jentry["sites"] = lw.sId;
jentry["directions"] = lw.dirs;
jentry["weightId"] = lw.wId;
jlws.push_back(jentry);
lwIds.push_back(lw.wId);
}
jCls["linkWeights"] = jlws;
}
vector<nlohmann::json> jsites;
for (auto const& entry : cls.sites) {
auto siteId = entry.first;
nlohmann::json jentry;
jentry["siteId"] = siteId;
jentry["physDim"] = cls.mphys.at(siteId).m();
vector<nlohmann::json> auxInds(cls.caux.at(siteId).size());
for (int i = 0; i < cls.caux.at(siteId).size(); i++) {
auto ind = cls.caux.at(siteId)[i];
auxInds[i] = {{"dir", i}, {"ad", ind.m()}, {"name", ind.rawname()}};
}
jentry["auxInds"] = auxInds;
vector<string> tensorElems;
writeOnSiteTElems(tensorElems, cls, siteId);
jentry["numEntries"] = tensorElems.size();
jentry["entries"] = tensorElems;
jsites.push_back(jentry);
}
jCls["sites"] = jsites;
outf << jCls.dump(4) << endl;
}
/*
* TODO? implement named indices in input file processing
* TODO? expose indices of returned tensor
* TODO? check auxBondDim vs auxDim per site consistency
*
*/
pair<int, itensor::Index> readAuxIndex(nlohmann::json const& j) {
auto dir = j["dir"].get<int>();
auto auxDim = j["ad"].get<int>();
auto name = j["name"].get<string>();
return make_pair(dir, itensor::Index(name, auxDim, AUXLINK, dir));
}
itensor::ITensor readTfromJSON(nlohmann::json const& j, int offset) {
auto result = readIndsAndTfromJSON(j, offset);
return result.second;
}
// returns pair < indices, tensor >
// IndexSet of ITensor, where 0th index is the physical one. Remaining
// indices are auxiliary
pair<vector<itensor::Index>, itensor::ITensor> readIndsAndTfromJSON(
nlohmann::json const& j,
int offset) {
auto id = j["siteId"].get<string>();
vector<itensor::Index> ti(5, itensor::Index());
ti[0] = itensor::Index(id + "-" + TAG_I_PHYS, j["physDim"].get<int>(), PHYS);
// check if tensor has custom set of auxiliary indices provided
auto p_json_inds_array = j.find("auxInds");
if (p_json_inds_array == j.end()) {
std::cout << "[readOnSiteT] " << id << " : auxInds array not found. "
<< " Assuming identical auxiliary indices on all bonds."
<< std::endl;
ti[1] =
itensor::Index(id + "-" + TAG_I_AUX, j["auxDim"].get<int>(), AUXLINK);
for (int i = 2; i < ti.size(); i++)
ti[i] = prime(ti[1], i - 1);
} else {
if (j["auxInds"].size() != 4) {
std::cout << "[readOnSiteT] " << id << " : auxInds has to contain"
<< " four auxiliary indices" << std::endl;
throw std::runtime_error("Invalid input");
}
for (const auto& i : j["auxInds"]) {
auto tmp = readAuxIndex(i);
ti[1 + tmp.first] = tmp.second;
}
// verify, that indices for each direction have been read
for (int i = 1; i < ti.size(); i++) {
if (not ti[i]) {
std::cout << "[readOnSiteT] " << id << " : auxInds does not contain "
<< " auxiliary index for direction " << i - 1 << std::endl;
throw std::runtime_error("Invalid input");
}
}
}
auto t = itensor::ITensor(ti);
string token[7];
int pI, aI0, aI1, aI2, aI3;
char delim = ' ';
for (const auto& tEntry : j["entries"].get<vector<string>>()) {
istringstream iss(tEntry);
token[6] = "0.0";
for (int i = 0; i < 7; i++) {
getline(iss, token[i], delim);
}
// ITensor indices start from 1, hence if input file indices start from
// 0 use offset 1
pI = offset + stoi(token[0]);
aI0 = offset + stoi(token[1]);
aI1 = offset + stoi(token[2]);
aI2 = offset + stoi(token[3]);
aI3 = offset + stoi(token[4]);
t.set(ti[0](pI), ti[1](aI0), ti[2](aI1), ti[3](aI2), ti[4](aI3),
complex<double>(stod(token[5]), stod(token[6])));
}
return make_pair(ti, t);
}
void setOnSiteTensorsFromFile(Cluster& c, string const& filename, bool dbg) {
ifstream infile;
infile.open(filename, ios::in);
nlohmann::json jsonCls;
infile >> jsonCls;
// TODO - Warnings
// if (jsonCls["physDim"] != c.physDim) {}
// if (jsonCls["auxBondDim"] > c.auxBondDim) {}
setOnSiteTensorsFromJSON(c, jsonCls, dbg);
}
void setOnSiteTensorsFromJSON(Cluster& c, nlohmann::json const& j, bool dbg) {
for (const auto& siteEntry : j["sites"].get<vector<nlohmann::json>>()) {
pair<vector<itensor::Index>, itensor::ITensor> tmp =
readIndsAndTfromJSON(siteEntry);
auto id = siteEntry["siteId"].get<string>();
c.mphys[id] = tmp.first[0];
c.caux[id] = std::vector<itensor::Index>(tmp.first.size() - 1);
for (int i = 1; i < tmp.first.size(); i++)
c.caux[id][i - 1] = tmp.first[i];
c.sites[id] = tmp.second; // tensor
}
}
void writeOnSiteTElems(vector<string>& tEs,
Cluster const& c,
std::string id,
int offset,
double threshold) {
auto pI = c.mphys.at(id);
auto aI = c.caux.at(id);
string t_entry_str;
// ostringstream ost;
// ost.precision( numeric_limits< double >::max_digits10 );
for (int p = 0; p < pI.m(); p++) {
for (int a0 = 0; a0 < aI[0].m(); a0++) {
for (int a1 = 0; a1 < aI[1].m(); a1++) {
for (int a2 = 0; a2 < aI[2].m(); a2++) {
for (int a3 = 0; a3 < aI[3].m(); a3++) {
complex<double> elem = c.sites.at(id).cplx(
pI(p + offset), aI[0](a0 + offset), aI[1](a1 + offset),
aI[2](a2 + offset), aI[3](a3 + offset));
if (abs(elem) >= threshold) {
t_entry_str = to_string(p) + " " + to_string(a0) + " " +
to_string(a1) + " " + to_string(a2) + " " +
to_string(a3) + " ";
ostringstream ost;
ost.precision(numeric_limits<double>::max_digits10);
ost << elem.real() << " " << elem.imag();
t_entry_str += ost.str();
// ost.clear();
// ost.seekp(0);
tEs.push_back(t_entry_str);
}
}
}
}
}
}
}
/*
* Write out tensor in given (human-readable) format to output file
* [using itensor::PrintData(t) format]
*
* TODO implement custom print fuction for tensor instead of
* redirecting stdout to file using C function
*
*/
void writeTensorF(string fname, itensor::ITensor t) {
ofstream outf;
outf.open(fname, ios::out);
// Print full information about tensor in following format
/*
* ITensor r=t.r() t.inds()
* (*,*,...) Re + Im
* ...
*
* where t.r() is the rank of the tensor, t.inds() is the IndexSet
* holding indices of tensor and each consecutive line holds
* single non-zero tensor element with values of indices in the
* same order as in t.inds() IndexSet
*
*/
// double threshold = 1.0e-14;
// Apply lambda expression to each tensor element
// t.apply([&threshold](itensor::Cplx val) {
// if(abs(val) <= threshold) val = 0.0;
// return val;
//});
// Save old settings
ios::fmtflags old_settings = cout.flags();
int old_precision = cout.precision();
cout.precision(numeric_limits<double>::max_digits10);
streambuf* coutbuf = cout.rdbuf(); // save old buf
cout.rdbuf(outf.rdbuf()); // redirect std::cout to out.txt!
switch (t.r()) {
case 2: {
// itensor::printfln("t=\n%s", t);
cout << "placeholder_for_name =" << endl << t;
auto inds = t.inds();
for (int i = 1; i <= inds[0].m(); i++) {
for (int j = 1; j <= inds[1].m(); j++) {
cout << noshowpos << "(" << i << "," << j << ") "
<< t.cplx(inds[0](i), inds[1](j)).real() << showpos
<< t.cplx(inds[0](i), inds[1](j)).imag() << "i" << endl;
}
}
break;
}
case 3: {
// itensor::printfln("t=\n%s", t);
cout << "placeholder_for_name =" << endl << t;
auto inds = t.inds();
for (int i = 1; i <= inds[0].m(); i++) {
for (int j = 1; j <= inds[1].m(); j++) {
for (int k = 1; k <= inds[2].m(); k++) {
cout << noshowpos << "(" << i << "," << j << "," << k << ") "
<< t.cplx(inds[0](i), inds[1](j), inds[2](k)).real() << showpos
<< t.cplx(inds[0](i), inds[1](j), inds[2](k)).imag() << "i"
<< endl;
}
}
}
break;
}
default: {
itensor::PrintData(t);
break;
}
}
cout.rdbuf(coutbuf); // reset to standard output again
cout.flags(old_settings);
cout.precision(old_precision);
outf.close();
}
/*
* Write out tensor in binary itensor format to output file
* (presents ITensor::Index ids)
*
*/
void writeTensorB(string const& fname, itensor::ITensor const& t) {
ofstream outf;
outf.open(fname, ios::out | ios::binary);
itensor::write(outf, t);
outf.close();
}
/*
* Read tensor in format given by PrintData of itensor into t
*
* TODO Implement read for general rank of tensor
*
*/
itensor::ITensor readTensorF(string const& fname) {
ifstream inf;
inf.open(fname, ios::in);
if (!inf.good()) {
cout << "Failed opening file: " << fname << endl;
exit(EXIT_FAILURE);
}
cout << "Reading: " << fname << endl;
// Read tensor (object) name
string nameLine;
getline(inf, nameLine);
string name = nameLine.substr(0, nameLine.find("=") - 1);
cout << name << " ";
// read in the line containing the rank of the tensor and IndexSet
string tDescLine;
getline(inf, tDescLine);
// Parse the rank
int rank;
string rankStr;
int rankBegin = tDescLine.find("r=") + 2;
int rankEnd = tDescLine.find_first_of(':');
rankStr = tDescLine.substr(rankBegin, rankEnd - rankBegin);
rank = stoi(rankStr);
cout << "RANK " << rank << endl;
// Parse indices
stringstream ssInds(tDescLine.substr(tDescLine.find_first_of('(')));
char delimI = ' '; // Delim between index entries
char delimIF = ','; // Delim for fields of single index entry
string indToken, indCore, indPrime;
vector<itensor::Index> inds = vector<itensor::Index>(rank);
string indFields[4];
int primeLvl;
for (int i = 0; i < rank; i++) {
getline(ssInds, indToken, delimI);
// Separate core index properties and prime level
indCore = indToken.substr(1, indToken.find_last_of(')') - 1);
indPrime = indToken.substr(indToken.find_last_of(')') + 1);
// Tokenize individual fields of the index
stringstream ss(indCore);
for (int j = 0; j < 4; j++) {
getline(ss, indFields[j], delimIF);
}
// Get the prime level
// TODO compares unsigned with signed
if (indPrime.size() == count(indPrime.begin(), indPrime.end(), '\'')) {
// prime level <= 3 is indicated by ' or '' or '''
primeLvl = indPrime.size();
} else {
// prime level > 3 is indicated as 'n where n is the prime level
primeLvl = stoi(indPrime.substr(1));
}
// TODO? convert to switch - requires enum and string to enum map
if (indFields[2] == TAG_IT_ULINK) {
inds[i] = itensor::Index(indFields[0], stoi(indFields[1]), ULINK);
} else if (indFields[2] == TAG_IT_RLINK) {
inds[i] = itensor::Index(indFields[0], stoi(indFields[1]), RLINK);
} else if (indFields[2] == TAG_IT_DLINK) {
inds[i] = itensor::Index(indFields[0], stoi(indFields[1]), DLINK);
} else if (indFields[2] == TAG_IT_LLINK) {
inds[i] = itensor::Index(indFields[0], stoi(indFields[1]), LLINK);
} else if (indFields[2] == TAG_IT_HSLINK) {
inds[i] = itensor::Index(indFields[0], stoi(indFields[1]), HSLINK);
} else if (indFields[2] == TAG_IT_VSLINK) {
inds[i] = itensor::Index(indFields[0], stoi(indFields[1]), VSLINK);
}
inds[i].prime(primeLvl);
}
cout << itensor::IndexSet(inds) << endl;
// Construct Tensor
auto t = itensor::ITensor(inds);
// Skip line with tensor "scale" and "norm" information
string metaLine;
getline(inf, metaLine);
// Get individual tensor elements
char delimIvs = ',';
string itElem, itIv;
int ivs[rank];
string valStr, valRe, valIm;
int cplxPos;
complex<double> itElemVal;
while (getline(inf, itElem) && (itElem.length() > 0)) {
// Parse indices value
stringstream itElemIvs(itElem.substr(1, itElem.find_first_of(')') - 1));
for (int i = 0; i < rank; i++) {
getline(itElemIvs, itIv, delimIvs);
ivs[i] = stoi(itIv);
}
// Parse tensor element value
valStr = itElem.substr(itElem.find_first_of(')') + 1);
cplxPos = valStr.find_last_of("+-");
valRe = valStr.substr(0, cplxPos);
valIm = valStr.substr(cplxPos, valStr.length() - cplxPos - 1);
itElemVal = complex<double>(stod(valRe), stod(valIm));
switch (rank) {
case 2: {
t.set(inds[0](ivs[0]), inds[1](ivs[1]), itElemVal);
break;
}
case 3: {
t.set(inds[0](ivs[0]), inds[1](ivs[1]), inds[2](ivs[2]), itElemVal);
break;
}
default: {
cout << "ERROR: Unsupported tensor rank" << endl;
exit(EXIT_FAILURE);
break;
}
}
}
inf.close();
return t;
}
/*
* Read in tensor in binary itensor format from input file
*
*/
itensor::ITensor readTensorB(string const& fname) {
ifstream inf;
inf.open(fname, ios::out | ios::binary);
if (!inf.good()) {
cout << "Failed opening file: " << fname << "\n";
exit(EXIT_FAILURE);
}
cout << "Reading: " << fname << "\n";
itensor::ITensor t;
itensor::read(inf, t);
inf.close();
return t;
} | 31.086726 | 80 | 0.584377 | jurajHasik |
9582a7a99cc88a427c7710ab064a6b9116c05ba3 | 428 | hpp | C++ | Source/Shader.hpp | claytonkanderson/Fractus | c4012cc40ee81ac042edcc5461c48e02456bcbd0 | [
"MIT"
] | null | null | null | Source/Shader.hpp | claytonkanderson/Fractus | c4012cc40ee81ac042edcc5461c48e02456bcbd0 | [
"MIT"
] | null | null | null | Source/Shader.hpp | claytonkanderson/Fractus | c4012cc40ee81ac042edcc5461c48e02456bcbd0 | [
"MIT"
] | null | null | null | //
// Shader.hpp
// Fracturing
//
// Created by Clayton Anderson on 4/16/17.
// Copyright © 2017 Clayton Anderson. All rights reserved.
//
#pragma once
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <glm/mat4x4.hpp>
#include <glm/gtc/matrix_transform.hpp>
GLuint LoadShaders(const char * vertex_file_path,const char * fragment_file_path);
| 20.380952 | 82 | 0.726636 | claytonkanderson |
9582df70e25512b93c6c1d0601032a3c4562f57f | 14,410 | cpp | C++ | tools/quantization/opttools/quantized_model_optimize.cpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | 2 | 2020-12-15T13:56:31.000Z | 2022-01-26T03:20:28.000Z | tools/quantization/opttools/quantized_model_optimize.cpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | null | null | null | tools/quantization/opttools/quantized_model_optimize.cpp | JujuDel/MNN | 8a82f5c5a7ae37192784c2dbd6dfc8ca8833565a | [
"Apache-2.0"
] | 1 | 2021-11-24T06:26:27.000Z | 2021-11-24T06:26:27.000Z | #include "MNN_generated.h"
#include <MNN/MNNDefine.h>
#include <fstream>
#include <sstream>
#include <memory>
#include <map>
#include <queue>
#include <set>
using namespace MNN;
//#define OPT_SHAPE_TRANSFORM
static bool reIndex(MNN::NetT* mNet) {
std::map<int, int> usefulTensorIndexMap;
std::vector<std::string> usefulTensorName;
std::vector<bool> tensorValid(mNet->tensorName.size(), false);
for (auto& op : mNet->oplists) {
for (auto index : op->inputIndexes) {
tensorValid[index] = true;
}
for (auto index : op->outputIndexes) {
tensorValid[index] = true;
}
}
for (int i = 0; i < tensorValid.size(); ++i) {
if (tensorValid[i]) {
usefulTensorIndexMap.insert(std::make_pair(i, usefulTensorName.size()));
usefulTensorName.push_back(mNet->tensorName[i]);
}
}
// Re index
for (auto& op : mNet->oplists) {
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->inputIndexes[i]);
op->inputIndexes[i] = iter->second;
}
for (int i = 0; i < op->outputIndexes.size(); ++i) {
auto iter = usefulTensorIndexMap.find(op->outputIndexes[i]);
op->outputIndexes[i] = iter->second;
}
}
mNet->tensorName = usefulTensorName;
for (auto iter = mNet->extraTensorDescribe.begin(); iter != mNet->extraTensorDescribe.end();) {
auto index = (*iter)->index;
if (usefulTensorIndexMap.find(index) == usefulTensorIndexMap.end()) {
iter = mNet->extraTensorDescribe.erase(iter);
continue;
}
(*iter)->index = usefulTensorIndexMap.find(index)->second;
iter++;
}
// Check dup name and modify
std::set<std::string> names;
std::set<std::string> tensorNames;
for (int i = 0; i < mNet->oplists.size(); ++i) {
auto& op = mNet->oplists[i];
auto opName = op->name;
if (opName.empty() || names.find(opName) != names.end()) {
std::ostringstream defaultName;
defaultName << EnumNameOpType(op->type);
defaultName << i;
op->name = defaultName.str();
MNN_PRINT("%d op name is empty or dup, set to %s\n", i, op->name.c_str());
opName = op->name;
}
names.insert(opName);
for (auto output : op->outputIndexes) {
auto origin = mNet->tensorName[output];
if (origin.empty() || tensorNames.find(origin) != tensorNames.end()) {
std::ostringstream defaultName;
defaultName << output;
origin = defaultName.str();
mNet->tensorName[output] = origin;
}
tensorNames.insert(origin);
}
}
return true;
}
static std::set<OpType> gShapeTransformType {
OpType_BatchToSpaceND,
OpType_Crop,
OpType_DepthToSpace,
OpType_ExpandDims,
OpType_Flatten,
OpType_Gather,
OpType_GatherV2,
OpType_GatherND,
OpType_Padding,
OpType_Permute,
OpType_Reshape,
OpType_Slice,
OpType_SliceTf,
OpType_StridedSlice,
OpType_Squeeze,
OpType_SpaceToDepth,
OpType_SpaceToBatchND,
OpType_Tile,
OpType_Unsqueeze,
OpType_ConvertTensor,
OpType_Broastcast,
};
static std::set<OpType> gInt8Ops {
OpType_ConvInt8,
OpType_DepthwiseConvInt8,
OpType_PoolInt8,
OpType_EltwiseInt8
};
static void onlyTurnScaleToSingle(const std::vector<std::unique_ptr<OpT>>& sourceOplists) {
for (int i=0; i<sourceOplists.size(); ++i) {
auto op = sourceOplists[i].get();
if (op->type == OpType_Int8ToFloat || op->type == OpType_FloatToInt8) {
auto quanParam = op->main.AsQuantizedFloatParam();
auto tensorScale = quanParam->tensorScale[0];
quanParam->tensorScale = {tensorScale};
}
}
}
int main(int argc, const char* argv[]) {
MNN_PRINT("Optimize quantize model for smaller and faster, only valid to run after MNN 1.1.2\n");
MNN_PRINT("The tool is just for temporary usage, in laster version may be depercerate\n");
if (argc < 3) {
MNN_ERROR("Usage: ./quantized_model_optimize.out origin_quan.mnn optimized_quan.mnn\n");
return 0;
}
auto srcFile = argv[1];
auto dstFile = argv[2];
FUNC_PRINT_ALL(srcFile, s);
FUNC_PRINT_ALL(dstFile, s);
std::unique_ptr<NetT> source;
{
std::ifstream sourceFile(srcFile);
if (sourceFile.fail()) {
MNN_ERROR("Can't open source file\n");
return 0;
}
std::ostringstream tempOs;
tempOs << sourceFile.rdbuf();
auto tempS = tempOs.str();
source = std::move(UnPackNet((void*)tempS.c_str()));
}
if (nullptr == source) {
MNN_ERROR("Source net invalid\n");
return 0;
}
#ifdef OPT_SHAPE_TRANSFORM
// Compute the quan info for model
struct ValueMapInfo {
float scale = 0.0f;
float bias = 0.0f;
float minValue = -128.0f;
float maxValue = 127.0f;
bool valid = false;
};
std::vector<ValueMapInfo> quanInfos(source->tensorName.size());
int beforeConvert = 0;
// First Load info from convert op
for (int i=0; i<source->oplists.size(); ++i) {
auto op = source->oplists[i].get();
if (op->type == OpType_Int8ToFloat || op->type == OpType_FloatToInt8) {
auto quanParam = op->main.AsQuantizedFloatParam();
auto tensorScale = quanParam->tensorScale[0];
beforeConvert++;
if (op->type == OpType_FloatToInt8) {
if (tensorScale > 0.000001f) {
tensorScale = 1.0f / tensorScale;
}
}
for (auto index : op->inputIndexes) {
auto& info = quanInfos[index];
info.valid = true;
info.scale = tensorScale;
}
for (auto index : op->outputIndexes) {
auto& info = quanInfos[index];
info.valid = true;
info.scale = tensorScale;
}
continue;
}
if (OpType_EltwiseInt8 == op->type) {
auto quanParameters = op->main.AsEltwiseInt8();
quanInfos[op->inputIndexes[0]].valid = true;
quanInfos[op->inputIndexes[0]].scale = quanParameters->inputQuan0->tensorScale[0];
quanInfos[op->inputIndexes[1]].valid = true;
quanInfos[op->inputIndexes[1]].scale = quanParameters->inputQuan1->tensorScale[0];
quanInfos[op->outputIndexes[0]].valid = true;
quanInfos[op->outputIndexes[0]].scale = 1.0f / quanParameters->outputQuan->tensorScale[0];
continue;
}
}
// Compute indirect quan infos by shape transform
std::vector<ValueMapInfo> quanInfoIndirects = quanInfos;
for (int i=0; i<source->oplists.size(); ++i) {
auto op = source->oplists[i].get();
if (op->type == OpType_Int8ToFloat || op->type == OpType_FloatToInt8) {
auto& info = quanInfoIndirects[op->inputIndexes[0]];
if (info.valid) {
for (auto index : op->outputIndexes) {
quanInfoIndirects[index] = info;
}
}
}
if (gShapeTransformType.find(op->type) != gShapeTransformType.end()) {
auto& info = quanInfoIndirects[op->inputIndexes[0]];
if (info.valid) {
for (auto index : op->outputIndexes) {
quanInfoIndirects[index] = info;
}
}
continue;
}
}
// Reset Quan op's parameter by new quanInfoIndirects info
for (int i=0; i<source->oplists.size(); ++i) {
auto op = source->oplists[i].get();
if (OpType_ConvInt8 == op->type || OpType_DepthwiseConvInt8 == op->type) {
auto quanParameters = op->main.AsConvolution2D()->symmetricQuan.get();
if (quanInfoIndirects[op->inputIndexes[0]].scale != quanInfos[op->inputIndexes[0]].scale) {
// s0 * A1 = F, s1 * A2 = F, C = f(A1) * p0 = f(A2) * s1 / s0 * p0
auto adjustScale = quanInfoIndirects[op->inputIndexes[0]].scale / quanInfos[op->inputIndexes[0]].scale;
for (auto& s : quanParameters->scale) {
s = s * adjustScale;
}
}
MNN_ASSERT(quanInfos[op->outputIndexes[0]].scale == quanInfoIndirects[op->outputIndexes[0]].scale);
continue;
}
if (OpType_EltwiseInt8 == op->type) {
auto quanParameters = op->main.AsEltwiseInt8();
for (auto& s : quanParameters->inputQuan0->scale) {
s = quanInfoIndirects[op->inputIndexes[0]].scale;
}
for (auto& s : quanParameters->inputQuan1->scale) {
s = quanInfoIndirects[op->inputIndexes[1]].scale;
}
for (auto& s : quanParameters->outputQuan->scale) {
s = 1.0f / quanInfoIndirects[op->outputIndexes[0]].scale;
}
}
}
quanInfos = std::move(quanInfoIndirects);
// Remove Int8ToFloat and Float2Int8
std::queue<int> unusedIndexes;
{
std::map<int, int> indexMap;
auto oplists = std::move(source->oplists);
for (int i=0; i<oplists.size(); ++i) {
auto op = oplists[i].get();
if (op->type == OpType_FloatToInt8 || op->type == OpType_Int8ToFloat) {
auto inputIndex = op->inputIndexes[0];
auto outputIndex = op->outputIndexes[0];
auto iter = indexMap.find(inputIndex);
if (iter == indexMap.end()) {
indexMap.insert(std::make_pair(outputIndex, inputIndex));
} else {
indexMap.insert(std::make_pair(outputIndex, iter->second));
}
continue;
}
for (int j=0; j<op->inputIndexes.size(); ++j) {
auto iter = indexMap.find(op->inputIndexes[j]);
if (iter != indexMap.end()) {
op->inputIndexes[j] = iter->second;
}
}
source->oplists.emplace_back(std::move(oplists[i]));
}
for (auto& iter : indexMap) {
unusedIndexes.push(iter.first);
}
}
// Add Float2Int8 and Int8ToFloat Back
int afterConvert = 0;
{
// 0: float, 1: int
enum DataType {
FLOAT = 0,
INT8 = 1
};
std::vector<DataType> tensorType(source->tensorName.size(), FLOAT);
std::map<int, int> indexMap;
auto oplists = std::move(source->oplists);
for (int opIndex = 0; opIndex < oplists.size(); ++opIndex) {
auto op = oplists[opIndex].get();
DataType dataType = FLOAT;
if (gInt8Ops.find(op->type) != gInt8Ops.end()) {
dataType = INT8;
} else if (gShapeTransformType.find(op->type) != gShapeTransformType.end()) {
dataType = tensorType[op->inputIndexes[0]];
}
for (int i = 0; i < op->outputIndexes.size(); ++i) {
tensorType[op->outputIndexes[i]] = dataType;
}
for (int i = 0; i < op->inputIndexes.size(); ++i) {
auto index = op->inputIndexes[i];
if (tensorType[index] != dataType) {
auto replaceIter = indexMap.find(index);
if (replaceIter != indexMap.end()) {
op->inputIndexes[i] = replaceIter->second;
} else if (quanInfos[index].valid) {
afterConvert++;
// Create Op
// construct new op
std::unique_ptr<OpT> convertType(new MNN::OpT);
convertType->main.type = MNN::OpParameter_QuantizedFloatParam;
std::ostringstream opName;
opName << "Convert_" << index << "_" << (int)dataType;
convertType->name = opName.str();
auto dequantizationParam = new MNN::QuantizedFloatParamT;
convertType->main.value = dequantizationParam;
if (dataType == FLOAT) {
convertType->type = MNN::OpType_Int8ToFloat;
dequantizationParam->tensorScale = {quanInfos[index].scale};
} else {
convertType->type = MNN::OpType_FloatToInt8;
if (quanInfos[index].scale > 0.0f) {
dequantizationParam->tensorScale = {1.0f / quanInfos[index].scale};
} else {
dequantizationParam->tensorScale = {0.0f};
}
}
convertType->inputIndexes = {index};
convertType->outputIndexes = {(int)source->tensorName.size()};
source->tensorName.push_back(convertType->name);
// reset current op's input index at i
op->inputIndexes[i] = convertType->outputIndexes[0];
indexMap[index] = convertType->outputIndexes[0];
source->oplists.emplace_back(std::move(convertType));
}
}
}
source->oplists.emplace_back(std::move(oplists[opIndex]));
}
}
MNN_PRINT("From %d Convert to %d Convert\n", beforeConvert, afterConvert);
reIndex(source.get());
#else
onlyTurnScaleToSingle(source->oplists);
for (auto& subGraph : source->subgraphs) {
onlyTurnScaleToSingle(subGraph->nodes);
}
#endif
{
flatbuffers::FlatBufferBuilder builderOutput(1024);
auto len = MNN::Net::Pack(builderOutput, source.get());
builderOutput.Finish(len);
int sizeOutput = builderOutput.GetSize();
auto bufferOutput = builderOutput.GetBufferPointer();
std::ofstream output(dstFile);
output.write((const char*)bufferOutput, sizeOutput);
}
return 0;
}
| 39.264305 | 119 | 0.540389 | JujuDel |
9585b39d1666335cf42c47767b455d9ffda41564 | 3,525 | cpp | C++ | DeferredShading/DeferredShading/Renderer.cpp | yanghyunchan/2014_OperationBluehole | 188b61dea134d4f8e37aff514cda3601f5f2a294 | [
"MIT"
] | null | null | null | DeferredShading/DeferredShading/Renderer.cpp | yanghyunchan/2014_OperationBluehole | 188b61dea134d4f8e37aff514cda3601f5f2a294 | [
"MIT"
] | null | null | null | DeferredShading/DeferredShading/Renderer.cpp | yanghyunchan/2014_OperationBluehole | 188b61dea134d4f8e37aff514cda3601f5f2a294 | [
"MIT"
] | null | null | null | #include "stdafx.h"
#include "Renderer.h"
#include "App.h"
#include "Logger.h"
#include "RSManager.h"
#include "LightManager.h"
Renderer::Renderer()
{
}
Renderer::~Renderer()
{
DestroyDevice();
}
BOOL Renderer::Init()
{
HWND hWnd = App::GetInstance()->GetHandleMainWindow();
if (!CreateDevice(hWnd))
{
MessageBox(hWnd, L"CreateDevice Error!", L"Error!", MB_ICONINFORMATION | MB_OK);
DestroyDevice();
return FALSE;
}
if (!mElin.Init())
{
MessageBox(hWnd, L"mElin Init Error!", L"Error!", MB_ICONINFORMATION | MB_OK);
DestroyDevice();
return FALSE;
}
if (!mRoom.Init())
{
MessageBox(hWnd, L"mRoom Init Error!", L"Error!", MB_ICONINFORMATION | MB_OK);
DestroyDevice();
return FALSE;
}
return TRUE;
}
void Renderer::Render()
{
// om - output merge
mD3DDeviceContext->OMSetDepthStencilState(RenderStateManager::GetInstance()->GetDepthState(), 0);
mElin.RenderAll();
mRoom.RenderAll(mD3DDeviceContext);
}
BOOL Renderer::CreateDevice(HWND hWnd)
{
UINT createDeviceFlags = 0;
#ifdef _DEBUG
createDeviceFlags |= D3D11_CREATE_DEVICE_DEBUG;
#endif
D3D_DRIVER_TYPE driverTypes[] =
{
D3D_DRIVER_TYPE_HARDWARE,
D3D_DRIVER_TYPE_WARP,
D3D_DRIVER_TYPE_REFERENCE,
};
UINT numDriverTypes = ARRAYSIZE(driverTypes);
D3D_FEATURE_LEVEL featureLevels[] =
{
D3D_FEATURE_LEVEL_11_0,
D3D_FEATURE_LEVEL_10_1,
D3D_FEATURE_LEVEL_10_0,
};
UINT numFeatureLevels = ARRAYSIZE(featureLevels);
DXGI_SWAP_CHAIN_DESC sd;
ZeroMemory(&sd, sizeof(sd));
sd.BufferCount = 1;
sd.BufferDesc.Width = App::GetInstance()->GetWindowWidth();
sd.BufferDesc.Height = App::GetInstance()->GetWindowHeight();
sd.BufferDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
sd.BufferDesc.RefreshRate.Numerator = 60;
sd.BufferDesc.RefreshRate.Denominator = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.OutputWindow = hWnd;
sd.SampleDesc.Count = 1;
sd.SampleDesc.Quality = 0;
sd.Windowed = TRUE;
for (UINT driverTypeIndex = 0; driverTypeIndex < numDriverTypes; driverTypeIndex++)
{
mDriverType = driverTypes[driverTypeIndex];
hr = D3D11CreateDeviceAndSwapChain(NULL, mDriverType, NULL, createDeviceFlags, featureLevels, numFeatureLevels,
D3D11_SDK_VERSION, &sd, &mSwapChain, &mD3DDevice, &mFeatureLevel, &mD3DDeviceContext);
if (SUCCEEDED(hr))
break;
}
if (FAILED(hr))
return FALSE;
// Create a render target view
ID3D11Texture2D* pBackBuffer = NULL;
hr = mSwapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)&pBackBuffer);
if (FAILED(hr))
return FALSE;
hr = mD3DDevice->CreateRenderTargetView(pBackBuffer, NULL, &mRenderTargetView);
pBackBuffer->Release();
if (FAILED(hr))
return FALSE;
return TRUE;
}
void Renderer::DestroyDevice()
{
if (mD3DDeviceContext)
mD3DDeviceContext->ClearState();
SafeRelease(mRenderTargetView);
SafeRelease(mSwapChain);
SafeRelease(mD3DDeviceContext);
SafeRelease(mD3DDevice);
}
void Renderer::SetupViewPort()
{
// Setup the viewport
D3D11_VIEWPORT vp;
vp.Width = (FLOAT)App::GetInstance()->GetWindowWidth();
vp.Height = (FLOAT)App::GetInstance()->GetWindowHeight();
vp.MinDepth = 0.0f;
vp.MaxDepth = 1.0f;
vp.TopLeftX = 0;
vp.TopLeftY = 0;
mD3DDeviceContext->RSSetViewports(1, &vp);
}
void Renderer::ClearBackBuff()
{
//clear
float ClearColor[4] = { 0.0f, 0.125f, 0.3f, 1.0f };
mD3DDeviceContext->ClearRenderTargetView(mRenderTargetView, ClearColor);
}
| 23.344371 | 114 | 0.704397 | yanghyunchan |
9587752c5a95185648b09b1a5feef0e5bc73ee54 | 8,501 | cpp | C++ | Chapter3/GL01_APIWrapping/src/GLAPITrace.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 399 | 2021-06-03T02:42:20.000Z | 2022-03-27T23:23:15.000Z | Chapter3/GL01_APIWrapping/src/GLAPITrace.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 7 | 2021-07-13T02:36:01.000Z | 2022-03-26T03:46:37.000Z | Chapter3/GL01_APIWrapping/src/GLAPITrace.cpp | adoug/3D-Graphics-Rendering-Cookbook | dabffed670b8be5a619f0f62b10e0cc8ccdd5a36 | [
"MIT"
] | 53 | 2021-06-02T20:02:24.000Z | 2022-03-29T15:36:30.000Z | #include <assert.h>
#include "GL.h"
#include "GLAPITrace.h"
#define W( en ) if ( e == en ) return #en;
std::string Enum2String(GLenum e)
{
/* BeginMode */
W(GL_POINTS);
W(GL_LINES);
W(GL_LINE_LOOP);
W(GL_LINE_STRIP);
W(GL_TRIANGLES);
W(GL_TRIANGLE_STRIP);
W(GL_TRIANGLE_FAN);
/* BlendingFactorDest */
W(GL_SRC_COLOR);
W(GL_ONE_MINUS_SRC_COLOR);
W(GL_SRC_ALPHA);
W(GL_ONE_MINUS_SRC_ALPHA);
W(GL_DST_ALPHA);
W(GL_ONE_MINUS_DST_ALPHA);
/* BlendingFactorSrc */
W(GL_DST_COLOR);
W(GL_ONE_MINUS_DST_COLOR);
W(GL_SRC_ALPHA_SATURATE);
/* BlendEquationSeparate */
W(GL_FUNC_ADD);
W(GL_BLEND_EQUATION);
W(GL_BLEND_EQUATION_RGB);
W(GL_BLEND_EQUATION_ALPHA);
/* BlendSubtract */
W(GL_FUNC_SUBTRACT);
W(GL_FUNC_REVERSE_SUBTRACT);
/* Separate Blend Functions */
W(GL_BLEND_DST_RGB);
W(GL_BLEND_SRC_RGB);
W(GL_BLEND_DST_ALPHA);
W(GL_BLEND_SRC_ALPHA);
W(GL_CONSTANT_COLOR);
W(GL_ONE_MINUS_CONSTANT_COLOR);
W(GL_CONSTANT_ALPHA);
W(GL_ONE_MINUS_CONSTANT_ALPHA);
W(GL_BLEND_COLOR);
/* Buffer Objects */
W(GL_ARRAY_BUFFER);
W(GL_ELEMENT_ARRAY_BUFFER);
W(GL_ARRAY_BUFFER_BINDING);
W(GL_ELEMENT_ARRAY_BUFFER_BINDING);
W(GL_STREAM_DRAW);
W(GL_STATIC_DRAW);
W(GL_DYNAMIC_DRAW);
W(GL_BUFFER_SIZE);
W(GL_BUFFER_USAGE);
W(GL_CURRENT_VERTEX_ATTRIB);
/* CullFaceMode */
W(GL_FRONT);
W(GL_BACK);
W(GL_FRONT_AND_BACK);
/* EnableCap */
W(GL_TEXTURE_2D);
W(GL_CULL_FACE);
W(GL_BLEND);
W(GL_DITHER);
W(GL_STENCIL_TEST);
W(GL_DEPTH_TEST);
W(GL_SCISSOR_TEST);
W(GL_POLYGON_OFFSET_FILL);
W(GL_SAMPLE_ALPHA_TO_COVERAGE);
W(GL_SAMPLE_COVERAGE);
/* ErrorCode */
W(GL_INVALID_ENUM);
W(GL_INVALID_VALUE);
W(GL_INVALID_OPERATION);
W(GL_OUT_OF_MEMORY);
/* FrontFaceDirection */
W(GL_CW);
W(GL_CCW);
/* GetPName */
W(GL_LINE_WIDTH);
W(GL_ALIASED_LINE_WIDTH_RANGE);
W(GL_CULL_FACE_MODE);
W(GL_FRONT_FACE);
W(GL_DEPTH_RANGE);
W(GL_DEPTH_WRITEMASK);
W(GL_DEPTH_CLEAR_VALUE);
W(GL_DEPTH_FUNC);
W(GL_STENCIL_CLEAR_VALUE);
W(GL_STENCIL_FUNC);
W(GL_STENCIL_FAIL);
W(GL_STENCIL_PASS_DEPTH_FAIL);
W(GL_STENCIL_PASS_DEPTH_PASS);
W(GL_STENCIL_REF);
W(GL_STENCIL_VALUE_MASK);
W(GL_STENCIL_WRITEMASK);
W(GL_STENCIL_BACK_FUNC);
W(GL_STENCIL_BACK_FAIL);
W(GL_STENCIL_BACK_PASS_DEPTH_FAIL);
W(GL_STENCIL_BACK_PASS_DEPTH_PASS);
W(GL_STENCIL_BACK_REF);
W(GL_STENCIL_BACK_VALUE_MASK);
W(GL_STENCIL_BACK_WRITEMASK);
W(GL_VIEWPORT);
W(GL_SCISSOR_BOX);
/* GL_SCISSOR_TEST */
W(GL_COLOR_CLEAR_VALUE);
W(GL_COLOR_WRITEMASK);
W(GL_UNPACK_ALIGNMENT);
W(GL_PACK_ALIGNMENT);
W(GL_MAX_TEXTURE_SIZE);
W(GL_MAX_VIEWPORT_DIMS);
W(GL_SUBPIXEL_BITS);
W(GL_POLYGON_OFFSET_UNITS);
/* GL_POLYGON_OFFSET_FILL */
W(GL_POLYGON_OFFSET_FACTOR);
W(GL_TEXTURE_BINDING_2D);
W(GL_SAMPLE_BUFFERS);
W(GL_SAMPLES);
W(GL_SAMPLE_COVERAGE_VALUE);
W(GL_SAMPLE_COVERAGE_INVERT);
W(GL_NUM_COMPRESSED_TEXTURE_FORMATS);
W(GL_COMPRESSED_TEXTURE_FORMATS);
/* HintMode */
W(GL_DONT_CARE);
W(GL_FASTEST);
W(GL_NICEST);
/* DataType */
W(GL_BYTE);
W(GL_UNSIGNED_BYTE);
W(GL_SHORT);
W(GL_UNSIGNED_SHORT);
W(GL_INT);
W(GL_UNSIGNED_INT);
W(GL_FLOAT);
W(GL_FIXED);
/* PixelFormat */
W(GL_DEPTH_COMPONENT);
W(GL_ALPHA);
W(GL_RGB);
W(GL_RGBA);
W(GL_COMPRESSED_RGB8_ETC2);
W(GL_COMPRESSED_RGBA8_ETC2_EAC);
/* PixelType */
W(GL_UNSIGNED_SHORT_4_4_4_4);
W(GL_UNSIGNED_SHORT_5_5_5_1);
W(GL_UNSIGNED_SHORT_5_6_5);
/* Shaders */
W(GL_FRAGMENT_SHADER);
W(GL_VERTEX_SHADER);
W(GL_MAX_VERTEX_ATTRIBS);
W(GL_MAX_VERTEX_UNIFORM_VECTORS);
W(GL_MAX_FRAGMENT_UNIFORM_VECTORS);
W(GL_MAX_VARYING_VECTORS);
W(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS);
W(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS);
W(GL_MAX_TEXTURE_IMAGE_UNITS);
W(GL_SHADER_TYPE);
W(GL_DELETE_STATUS);
W(GL_LINK_STATUS);
W(GL_VALIDATE_STATUS);
W(GL_ATTACHED_SHADERS);
W(GL_ACTIVE_UNIFORMS);
W(GL_ACTIVE_UNIFORM_MAX_LENGTH);
W(GL_ACTIVE_ATTRIBUTES);
W(GL_ACTIVE_ATTRIBUTE_MAX_LENGTH);
W(GL_SHADING_LANGUAGE_VERSION);
W(GL_CURRENT_PROGRAM);
/* StencilFunction */
W(GL_NEVER);
W(GL_LESS);
W(GL_EQUAL);
W(GL_LEQUAL);
W(GL_GREATER);
W(GL_NOTEQUAL);
W(GL_GEQUAL);
W(GL_ALWAYS);
/* StencilOp */
W(GL_KEEP);
W(GL_REPLACE);
W(GL_INCR);
W(GL_DECR);
W(GL_INVERT);
W(GL_INCR_WRAP);
W(GL_DECR_WRAP);
/* StringName */
W(GL_VENDOR);
W(GL_RENDERER);
W(GL_VERSION);
W(GL_EXTENSIONS);
/* TextureMagFilter */
W(GL_NEAREST);
W(GL_LINEAR);
/* TextureMinFilter */
W(GL_NEAREST_MIPMAP_NEAREST);
W(GL_LINEAR_MIPMAP_NEAREST);
W(GL_NEAREST_MIPMAP_LINEAR);
W(GL_LINEAR_MIPMAP_LINEAR);
/* TextureParameterName */
W(GL_TEXTURE_MAG_FILTER);
W(GL_TEXTURE_MIN_FILTER);
W(GL_TEXTURE_WRAP_S);
W(GL_TEXTURE_WRAP_T);
/* TextureTarget */
W(GL_TEXTURE);
W(GL_TEXTURE_CUBE_MAP);
W(GL_TEXTURE_BINDING_CUBE_MAP);
W(GL_TEXTURE_CUBE_MAP_POSITIVE_X);
W(GL_TEXTURE_CUBE_MAP_NEGATIVE_X);
W(GL_TEXTURE_CUBE_MAP_POSITIVE_Y);
W(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y);
W(GL_TEXTURE_CUBE_MAP_POSITIVE_Z);
W(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z);
W(GL_MAX_CUBE_MAP_TEXTURE_SIZE);
/* TextureUnit */
W(GL_TEXTURE0);
W(GL_TEXTURE1);
W(GL_TEXTURE2);
W(GL_TEXTURE3);
W(GL_TEXTURE4);
W(GL_TEXTURE5);
W(GL_TEXTURE6);
W(GL_TEXTURE7);
W(GL_TEXTURE8);
W(GL_TEXTURE9);
W(GL_TEXTURE10);
W(GL_TEXTURE11);
W(GL_TEXTURE12);
W(GL_TEXTURE13);
W(GL_TEXTURE14);
W(GL_TEXTURE15);
W(GL_TEXTURE16);
W(GL_TEXTURE17);
W(GL_TEXTURE18);
W(GL_TEXTURE19);
W(GL_TEXTURE20);
W(GL_TEXTURE21);
W(GL_TEXTURE22);
W(GL_TEXTURE23);
W(GL_TEXTURE24);
W(GL_TEXTURE25);
W(GL_TEXTURE26);
W(GL_TEXTURE27);
W(GL_TEXTURE28);
W(GL_TEXTURE29);
W(GL_TEXTURE30);
W(GL_TEXTURE31);
W(GL_ACTIVE_TEXTURE);
/* TextureWrapMode */
W(GL_REPEAT);
W(GL_CLAMP_TO_EDGE);
W(GL_MIRRORED_REPEAT);
/* Uniform Types */
W(GL_FLOAT_VEC2);
W(GL_FLOAT_VEC3);
W(GL_FLOAT_VEC4);
W(GL_INT_VEC2);
W(GL_INT_VEC3);
W(GL_INT_VEC4);
W(GL_BOOL);
W(GL_BOOL_VEC2);
W(GL_BOOL_VEC3);
W(GL_BOOL_VEC4);
W(GL_FLOAT_MAT2);
W(GL_FLOAT_MAT3);
W(GL_FLOAT_MAT4);
W(GL_SAMPLER_2D);
W(GL_SAMPLER_CUBE);
/* Vertex Arrays */
W(GL_VERTEX_ATTRIB_ARRAY_ENABLED);
W(GL_VERTEX_ATTRIB_ARRAY_SIZE);
W(GL_VERTEX_ATTRIB_ARRAY_STRIDE);
W(GL_VERTEX_ATTRIB_ARRAY_TYPE);
W(GL_VERTEX_ATTRIB_ARRAY_NORMALIZED);
W(GL_VERTEX_ATTRIB_ARRAY_POINTER);
W(GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING);
/* Read Format */
W(GL_IMPLEMENTATION_COLOR_READ_TYPE);
W(GL_IMPLEMENTATION_COLOR_READ_FORMAT);
/* Shader Source */
W(GL_COMPILE_STATUS);
W(GL_INFO_LOG_LENGTH);
W(GL_SHADER_SOURCE_LENGTH);
W(GL_SHADER_COMPILER);
/* Shader Binary */
W(GL_SHADER_BINARY_FORMATS);
W(GL_NUM_SHADER_BINARY_FORMATS);
/* Shader Precision-Specified Types */
W(GL_LOW_FLOAT);
W(GL_MEDIUM_FLOAT);
W(GL_HIGH_FLOAT);
W(GL_LOW_INT);
W(GL_MEDIUM_INT);
W(GL_HIGH_INT);
/* Framebuffer Object. */
W(GL_FRAMEBUFFER);
W(GL_RENDERBUFFER);
W(GL_RGBA4);
W(GL_RGB5_A1);
W(GL_RGB565);
W(GL_DEPTH_COMPONENT16);
W(GL_STENCIL_INDEX);
W(GL_STENCIL_INDEX8);
W(GL_RENDERBUFFER_WIDTH);
W(GL_RENDERBUFFER_HEIGHT);
W(GL_RENDERBUFFER_INTERNAL_FORMAT);
W(GL_RENDERBUFFER_RED_SIZE);
W(GL_RENDERBUFFER_GREEN_SIZE);
W(GL_RENDERBUFFER_BLUE_SIZE);
W(GL_RENDERBUFFER_ALPHA_SIZE);
W(GL_RENDERBUFFER_DEPTH_SIZE);
W(GL_RENDERBUFFER_STENCIL_SIZE);
W(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE);
W(GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME);
W(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL);
W(GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE);
W(GL_COLOR_ATTACHMENT0);
W(GL_DEPTH_ATTACHMENT);
W(GL_STENCIL_ATTACHMENT);
W(GL_FRAMEBUFFER_COMPLETE);
W(GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT);
W(GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT);
W(GL_FRAMEBUFFER_UNSUPPORTED);
W(GL_FRAMEBUFFER_BINDING);
W(GL_RENDERBUFFER_BINDING);
W(GL_MAX_RENDERBUFFER_SIZE);
W(GL_INVALID_FRAMEBUFFER_OPERATION);
W(GL_TEXTURE_WIDTH);
W(GL_TEXTURE_HEIGHT);
W(GL_TEXTURE_INTERNAL_FORMAT);
W(GL_LINE);
W(GL_FILL);
W(GL_UNIFORM_BUFFER);
W(GL_RGBA32F);
W(GL_RGB32F);
W(GL_RGBA16F);
W(GL_COMPRESSED_RED);
W(GL_COMPRESSED_RGB);
W(GL_COMPRESSED_RGBA);
W(GL_RED);
W(GL_R16);
W(GL_R32F);
W(GL_RGB16F);
W(GL_TEXTURE_3D);
W(GL_DEPTH_COMPONENT24);
W(GL_BGR);
W(GL_BGRA);
W(GL_TEXTURE_COMPRESSED_IMAGE_SIZE);
W(GL_TEXTURE_COMPRESSED);
W(GL_TIME_ELAPSED);
W(GL_TIMESTAMP);
W(GL_QUERY_RESULT);
W(GL_QUERY_RESULT_AVAILABLE);
W(GL_PROGRAM_BINARY_LENGTH);
W(GL_PROGRAM_BINARY_RETRIEVABLE_HINT);
W(GL_UNIFORM_BLOCK_DATA_SIZE);
W(GL_GEOMETRY_SHADER);
W(GL_PATCHES);
W(GL_PATCH_VERTICES);
W(GL_TESS_EVALUATION_SHADER);
W(GL_TESS_CONTROL_SHADER);
return std::to_string(e);
}
| 20.683698 | 52 | 0.764616 | adoug |
958aee21e7c750b5ee959a618c4143e6e3de7e78 | 1,005 | cpp | C++ | CPP/Hash&String/322/CoinChange.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Hash&String/322/CoinChange.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | CPP/Hash&String/322/CoinChange.cpp | Insofan/LeetCode | d6722601886e181745a2e9c31cb146bc0826c906 | [
"Apache-2.0"
] | null | null | null | //
// Created by Insomnia on 2018/8/2.
//
#include <iostream>
#include <vector>
using namespace std;
class Solution {
public:
int coinChange(vector<int> &coins, int amount) {
vector<int> dp;
for (int i = 0; i <= amount; i++) {
dp.push_back(-1);
}
dp[0] = 0;
for (int i = 1; i <= amount; i++) {
for (int j = 0; j < coins.size(); j++) {
if (i - coins[j] >= 0 && (dp[i - coins[j]] != -1)) {
if (dp[i] == -1 || dp[i] > dp[i - coins[j]] + 1) {
dp[i] = dp[i - coins[j]] + 1;
}
}
}
}
return dp[amount];
}
};
int main() {
Solution solve;
vector<int> coins;
coins.push_back(1);
coins.push_back(2);
coins.push_back(5);
coins.push_back(7);
coins.push_back(10);
for (int i = 1; i <= 14; ++i) {
printf("dp[%d] = %d \n", i, solve.coinChange(coins, i));
}
return 0;
}
| 20.510204 | 70 | 0.428856 | Insofan |
9590f35960698ec5baec6d3f40b7936858cd28b8 | 1,683 | cpp | C++ | enshellcode.cpp | 3gstudent/Shellcode-Generater | ca992ef1a5493e908bce18327c3efc1aeeb4c5f4 | [
"BSD-3-Clause"
] | 61 | 2017-01-19T07:40:24.000Z | 2022-03-14T18:56:27.000Z | enshellcode.cpp | 3gstudent/Shellcode-Generater | ca992ef1a5493e908bce18327c3efc1aeeb4c5f4 | [
"BSD-3-Clause"
] | null | null | null | enshellcode.cpp | 3gstudent/Shellcode-Generater | ca992ef1a5493e908bce18327c3efc1aeeb4c5f4 | [
"BSD-3-Clause"
] | 35 | 2017-01-19T07:40:30.000Z | 2022-03-14T18:56:30.000Z | #include <windows.h>
size_t GetSize(char * szFilePath)
{
size_t size;
FILE* f = fopen(szFilePath, "rb");
fseek(f, 0, SEEK_END);
size = ftell(f);
rewind(f);
fclose(f);
return size;
}
unsigned char* ReadBinaryFile(char *szFilePath, size_t *size)
{
unsigned char *p = NULL;
FILE* f = NULL;
size_t res = 0;
*size = GetSize(szFilePath);
if (*size == 0) return NULL;
f = fopen(szFilePath, "rb");
if (f == NULL)
{
printf("Binary file does not exists!\n");
return 0;
}
p = new unsigned char[*size];
rewind(f);
res = fread(p, sizeof(unsigned char), *size, f);
fclose(f);
if (res == 0)
{
delete[] p;
return NULL;
}
return p;
}
int main(int argc, char* argv[])
{
char *szFilePath="c:\\test\\shellcode.bin";
char *szFilePath2="c:\\test\\shellcode2.bin";
unsigned char *BinData = NULL;
size_t size = 0;
BinData = ReadBinaryFile(szFilePath, &size);
for(int i=0;i<size;i++)
{
BinData[i]=BinData[i]^0x44;
}
FILE* f = NULL;
f = fopen(szFilePath2, "wb");
if (f == NULL)
{
printf("Create error\n");
return 0;
}
char decode[]="\x83\xC0\x14\x33\xC9\x8A\x1C\x08\x80\xF3\x44\x88\x1C\x08\x41\x80\xFB\x91\x75\xF1";
char end[]="\xD5";
fwrite(decode,20,1,f);
fwrite(BinData,size,1,f);
fwrite(end,1,1,f);
fclose(f);
f = fopen(szFilePath2, "rb");
if (f == NULL)
{
printf("Create error\n");
return 0;
}
unsigned char *BinData2 = NULL;
size_t size2 = 0;
BinData2 = ReadBinaryFile(szFilePath2, &size2);
printf("\"");
for (int j=0;j<size2;j++)
{
printf("\\x%02x",BinData2[j]);
if((j+1)%16==0)
printf("\"\n\"");
}
printf("\"");
fclose(f);
return 0;
}
| 21.0375 | 99 | 0.586453 | 3gstudent |
9592d02e563645c92c3a5e5d1d2d1f8f557d9e2a | 479 | cpp | C++ | CodeForces/Complete/700-799/706B-InterestingDrink.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 36 | 2019-12-27T08:23:08.000Z | 2022-01-24T20:35:47.000Z | CodeForces/Complete/700-799/706B-InterestingDrink.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 10 | 2019-11-13T02:55:18.000Z | 2021-10-13T23:28:09.000Z | CodeForces/Complete/700-799/706B-InterestingDrink.cpp | Ashwanigupta9125/code-DS-ALGO | 49f6cf7d0c682da669db23619aef3f80697b352b | [
"MIT"
] | 53 | 2020-08-15T11:08:40.000Z | 2021-10-09T15:51:38.000Z | #include <cstdio>
#include <vector>
int main(){
const int N = 100100;
long n; scanf("%ld\n", &n);
std::vector<long> cumPrices(N + 1, 0);
for(long p = 0; p < n; p++){
long x; scanf("%ld", &x);
++cumPrices[x];
}
for(long p = 1; p <= N; p++){cumPrices[p] += cumPrices[p - 1];}
long q; scanf("%ld\n", &q);
while(q--){
long a; scanf("%ld\n", &a);
printf("%ld\n", cumPrices[(a <= N) ? a : N]);
}
return 0;
}
| 19.958333 | 67 | 0.455115 | Ashwanigupta9125 |
959409ba62cd1e8917e85c78b22c441123c6ecd0 | 4,793 | cc | C++ | 080-badterm/window.cc | gynvael/stream | 2d1a3f25b2f83241b39dab931d9ff03fca81d26e | [
"MIT"
] | 152 | 2016-02-04T10:40:46.000Z | 2022-03-03T18:25:54.000Z | 080-badterm/window.cc | gynvael/stream | 2d1a3f25b2f83241b39dab931d9ff03fca81d26e | [
"MIT"
] | 4 | 2016-03-11T23:49:46.000Z | 2017-06-16T18:58:53.000Z | 080-badterm/window.cc | gynvael/stream | 2d1a3f25b2f83241b39dab931d9ff03fca81d26e | [
"MIT"
] | 48 | 2016-01-31T19:13:36.000Z | 2021-09-03T19:50:17.000Z | #include "window.h"
#include "context.h"
bool TermWindow::InitX11() {
static bool X11_initialized; // Not multi-threading safe.
if (X11_initialized) {
return true;
}
XInitThreads();
display_ = XOpenDisplay(NULL);
if (display_ == nullptr) {
fprintf(stderr, "XOpenDisplay: error\n");
return false;
}
WM_DELETE_WINDOW = XInternAtom(display_, "WM_DELETE_WINDOW", false);
WM_SIZE_HINTS = XInternAtom(display_, "WM_SIZE_HINTS", false);
WM_NORMAL_HINTS = XInternAtom(display_, "WM_NORMAL_HINTS", false);
_NET_WM_ALLOWED_ACTIONS = XInternAtom(
display_, "_NET_WM_ALLOWED_ACTIONS", False);
_NET_WM_ACTION_CLOSE = XInternAtom(display_, "_NET_WM_ACTION_CLOSE", False);
_NET_WM_ACTION_MINIMIZE = XInternAtom(
display_, "_NET_WM_ACTION_MINIMIZE", False);
_NET_WM_ACTION_MOVE = XInternAtom(display_, "_NET_WM_ACTION_MOVE", False);
screen_ = DefaultScreen(display_);
visual_ = DefaultVisual(display_, screen_);
X11_initialized = true;
return true;
}
TermWindow::~TermWindow() {
Destroy();
}
void TermWindow::Destroy() {
//TODO: if (window_ != nullptr) {
XDestroyWindow(display_, window_);
//}
}
void TermWindow::QuitX11() {
XCloseDisplay(display_);
}
void TermWindow::ResizeConsoles() {
uint32_t w = (uint32_t)surface_->width;
uint32_t h = (uint32_t)surface_->height;
for (auto& console : ctx_->consoles) {
console->ResizeTextBuffer(w, h);
// TODO(gynvael):
console->HandleSurfaceChange(surface_);
}
}
bool TermWindow::Create() {
// TODO: SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,
window_ = XCreateSimpleWindow(
display_,
RootWindow(display_, screen_),
/*x=*/10, /*y=*/10, kDefaultWidth, kDefaultHeight,
/*border_width=*/1,
/*border=*/BlackPixel(display_, screen_),
/*background=*/BlackPixel(display_, screen_));
/*
TODO: window_ isn't a pointer, figure out how to get info about an erro
if (window_ == nullptr) {
fprintf(stderr, "XCreateSimpleWindow: error\n");
return false;
}*/
XStoreName(display_, window_, "badterm");
XSetWMProtocols(display_, window_, &WM_DELETE_WINDOW, 1);
XSelectInput(display_, window_, KeyPressMask | ExposureMask);
XSizeHints xsh;
xsh.flags = PMinSize | PMaxSize;
xsh.min_width = xsh.max_width = kDefaultWidth;
xsh.min_height = xsh.max_height = kDefaultHeight;
XSetWMSizeHints(display_, window_, &xsh, WM_SIZE_HINTS);
XSetWMNormalHints(display_, window_, &xsh);
const Atom allowed[] = {
_NET_WM_ACTION_CLOSE,
_NET_WM_ACTION_MINIMIZE,
_NET_WM_ACTION_MOVE
};
XChangeProperty(display_, window_, _NET_WM_ALLOWED_ACTIONS, XA_ATOM, 32,
PropertyNewValue, (unsigned char*)&allowed, 3);
XMapWindow(display_, window_);
XFlush(display_);
frame_ = new uint32_t[kDefaultWidth * kDefaultHeight];
//
surface_ = XCreateImage(
display_, visual_, /*depth=*/24,
ZPixmap, /*offset=*/0, (char*)frame_, kDefaultWidth, kDefaultHeight,
/*bitmap_pad=*/32, /*bytes_per_line*/0
);
if (surface_ == nullptr) {
fprintf(stderr, "XCreateImage: error\n");
return false;
}
ResizeConsoles();
return true;
}
bool TermWindow::HandleEvents() {
while (XPending(display_)) {
XEvent ev;
XNextEvent(display_, &ev);
if (ev.type == ClientMessage &&
(Atom)ev.xclient.data.l[0] == WM_DELETE_WINDOW) {
return false;
}
if (ev.type == Expose) {
RedrawWindowIfConsoleActive(nullptr);
continue;
}
/*if (ev.type == SDL_WINDOWEVENT) {
if (ev.window.event == SDL_WINDOWEVENT_SIZE_CHANGED) {
surface_ = SDL_GetWindowSurface(window_);
if (surface_ == nullptr) {
fprintf(stderr, "SDL_GetWindowSurface: error\n");
return false;
}
ResizeConsoles();
//SDL_UpdateWindowSurface(window_);
continue;
}
if (ev.window.event == SDL_WINDOWEVENT_CLOSE) {
SDL_Event quit_ev;
quit_ev.type = SDL_QUIT;
SDL_PushEvent(&quit_ev);
continue;
}
if (ev.window.event == SDL_WINDOWEVENT_MOVED ||
ev.window.event == SDL_WINDOWEVENT_SHOWN ||
ev.window.event == SDL_WINDOWEVENT_EXPOSED ||
ev.window.event == SDL_WINDOWEVENT_RESIZED ||
ev.window.event == SDL_WINDOWEVENT_MAXIMIZED ||
ev.window.event == SDL_WINDOWEVENT_RESTORED) {
printf("%p\n", window_);
SDL_UpdateWindowSurface(window_);
continue;
}
}*/
}
return true;
}
void TermWindow::RedrawWindowIfConsoleActive(Console */*console*/) {
GC ctx;
ctx = DefaultGC(display_, screen_);
XPutImage(
display_, window_, ctx, surface_,
/*src_x=*/0, /*src_y=*/0, /*dst_x=*/0, /*dst_y=*/0,
surface_->width, surface_->height);
XFlush(display_);
}
| 26.335165 | 78 | 0.665554 | gynvael |
d2e60056a68e23bf365edb4411447e7794d5552f | 6,434 | cpp | C++ | tests/test_vec3.cpp | stephen-sorley/obvi | ead96e23dfd9ffba35590b3a035556eeb093d9a8 | [
"MIT"
] | null | null | null | tests/test_vec3.cpp | stephen-sorley/obvi | ead96e23dfd9ffba35590b3a035556eeb093d9a8 | [
"MIT"
] | null | null | null | tests/test_vec3.cpp | stephen-sorley/obvi | ead96e23dfd9ffba35590b3a035556eeb093d9a8 | [
"MIT"
] | null | null | null | /* Unit tests for vec3 (util library).
*
* * * * * * * * * * * *
* The MIT License (MIT)
*
* Copyright (c) 2019 Stephen Sorley
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
* * * * * * * * * * * *
*/
#include <catch2/catch.hpp>
#include <obvi/util/vec3.hpp>
using obvi::vec3;
using namespace Catch::literals; // To get "_a" UDL for approximate floating-point values.
#define VEC3_EQUAL(v, v0, v1, v2) \
REQUIRE( v.pt[0] == v0 ); \
REQUIRE( v.pt[1] == v1 ); \
REQUIRE( v.pt[2] == v2 );
TEMPLATE_TEST_CASE("vec3 set and get", "[vec3]", float, double) {
vec3<TestType> v;
VEC3_EQUAL(v, 0, 0, 0);
SECTION( "array and named element access are the same" ) {
v.pt[0] = TestType(1.1);
v.pt[1] = TestType(2.2);
v.pt[2] = TestType(3.3);
VEC3_EQUAL(v, v.x(), v.y(), v.z());
}
SECTION( "array and index element access are the same" ) {
v.pt[0] = TestType(1.1);
v.pt[1] = TestType(2.2);
v.pt[2] = TestType(3.3);
VEC3_EQUAL(v, v[0], v[1], v[2]);
const vec3<TestType> &vref = v;
VEC3_EQUAL(v, vref[0], vref[1], vref[2]);
}
SECTION( "set method works" ) {
v.set(TestType(4.4), TestType(5.5), TestType(6.6));
VEC3_EQUAL(v, TestType(4.4), TestType(5.5), TestType(6.6));
}
SECTION( "initialization from different type works" ) {
vec3<long double> w(1.0L,2.0L,3.6L);
v = vec3<TestType>(w);
VEC3_EQUAL(v, TestType(w.x()), TestType(w.y()), TestType(w.z()))
}
}
TEMPLATE_TEST_CASE("vec3 math", "[vec3]", float, double) {
vec3<TestType> v(1,2,3);
vec3<TestType> w(4,5,6);
TestType s = 2.5;
SECTION( "negate" ) {
w = -v;
VEC3_EQUAL(w, -1.0_a, -2.0_a, -3.0_a);
}
SECTION( "add" ) {
SECTION( "vector in-place" ) {
v += w;
VEC3_EQUAL(v, 5.0_a, 7.0_a, 9.0_a);
}
SECTION( "vector separate" ) {
v = v + w;
VEC3_EQUAL(v, 5.0_a, 7.0_a, 9.0_a);
}
SECTION( "scalar in-place" ) {
v += s;
VEC3_EQUAL(v, 3.5_a, 4.5_a, 5.5_a);
}
SECTION( "scalar separate right" ) {
v = v + s;
VEC3_EQUAL(v, 3.5_a, 4.5_a, 5.5_a);
}
SECTION( "scalar separate left" ) {
v = s + v;
VEC3_EQUAL(v, 3.5_a, 4.5_a, 5.5_a);
}
}
SECTION( "subtract" ) {
SECTION( "vector in-place" ) {
v -= w;
VEC3_EQUAL(v, -3.0_a, -3.0_a, -3.0_a);
}
SECTION( "vector separate" ) {
v = v - w;
VEC3_EQUAL(v, -3.0_a, -3.0_a, -3.0_a);
}
SECTION( "scalar in-place" ) {
v -= s;
VEC3_EQUAL(v, -1.5_a, -0.5_a, 0.5_a);
}
SECTION( "scalar separate" ) {
v = v - s;
VEC3_EQUAL(v, -1.5_a, -0.5_a, 0.5_a);
}
}
SECTION( "multiply" ) {
SECTION( "scalar in-place" ) {
v *= s;
VEC3_EQUAL(v, 2.5_a, 5.0_a, 7.5_a);
}
SECTION( "scalar separate right" ) {
v = v * s;
VEC3_EQUAL(v, 2.5_a, 5.0_a, 7.5_a);
}
SECTION( "scalar separate left" ) {
v = s * v;
VEC3_EQUAL(v, 2.5_a, 5.0_a, 7.5_a);
}
SECTION( "vector in-place" ) {
v *= w;
VEC3_EQUAL(v, 4.0_a, 10.0_a, 18.0_a);
}
SECTION( "vector separate" ) {
v = v * w;
VEC3_EQUAL(v, 4.0_a, 10.0_a, 18.0_a);
}
}
SECTION( "divide" ) {
SECTION( "scalar in-place" ) {
v /= s;
VEC3_EQUAL(v, 0.4_a, 0.8_a, 1.2_a);
}
SECTION( "scalar separate right" ) {
v = v / s;
VEC3_EQUAL(v, 0.4_a, 0.8_a, 1.2_a);
}
SECTION( "scalar separate left" ) {
v = s / v;
VEC3_EQUAL(v, 2.5_a, 1.25_a, 0.8333333333333333_a);
}
SECTION( "vector in-place" ) {
v /= w;
VEC3_EQUAL(v, 0.25_a, 0.4_a, 0.5_a);
}
SECTION( "vector separate" ) {
v = v / w;
VEC3_EQUAL(v, 0.25_a, 0.4_a, 0.5_a);
}
}
SECTION( "dot product" ) {
REQUIRE( v.dot(w) == 32.0_a );
REQUIRE( v.dot(w.x(), w.y(), w.z()) == 32.0_a );
}
SECTION( "cross product" ) {
v = v.cross(w);
VEC3_EQUAL(v, -3.0_a, 6.0_a, -3.0_a);
}
SECTION( "2-norm" ) {
REQUIRE( v.normsqd() == 14.0_a );
w = v.normalized();
VEC3_EQUAL(w, 0.2672612_a, 0.5345225_a, 0.8017837_a);
}
SECTION( "min/max" ) {
using vec3t = vec3<TestType>;
REQUIRE( vec3t(1,5,7).min_component() == 1 );
REQUIRE( vec3t(7,1,5).min_component() == 1 );
REQUIRE( vec3t(5,7,1).min_component() == 1 );
REQUIRE( vec3t(1,5,7).max_component() == 7 );
REQUIRE( vec3t(7,1,5).max_component() == 7 );
REQUIRE( vec3t(5,7,1).max_component() == 7 );
v.set(1,5,7);
w.set(2,3,6);
VEC3_EQUAL(std::min(v,w), 1, 3, 6);
VEC3_EQUAL(std::max(v,w), 2, 5, 7);
}
}
| 28.981982 | 91 | 0.494871 | stephen-sorley |
d2e7346e5842d06158d5b731f4695a17f846f84c | 1,080 | cc | C++ | src/commands/heapdump/heap_snapshot.cc | rickyes/xprofiler | 536160b955daa36b6953f3856e11149218ef1390 | [
"BSD-2-Clause"
] | 249 | 2020-05-22T14:25:36.000Z | 2022-03-29T02:30:18.000Z | src/commands/heapdump/heap_snapshot.cc | rickyes/xprofiler | 536160b955daa36b6953f3856e11149218ef1390 | [
"BSD-2-Clause"
] | 97 | 2020-05-29T06:10:04.000Z | 2022-03-31T10:14:59.000Z | src/commands/heapdump/heap_snapshot.cc | rickyes/xprofiler | 536160b955daa36b6953f3856e11149218ef1390 | [
"BSD-2-Clause"
] | 39 | 2020-06-11T08:45:35.000Z | 2022-03-15T07:29:53.000Z | #include "heap_snapshot.h"
#include "../../library/writer.h"
#include "../../logger.h"
namespace xprofiler {
using v8::OutputStream;
class FileOutputStream : public OutputStream {
public:
FileOutputStream(FILE *stream) : stream_(stream) {}
virtual int GetChunkSize() {
return 65536; // big chunks == faster
}
virtual void EndOfStream() {}
virtual WriteResult WriteAsciiChunk(char *data, int size) {
const size_t len = static_cast<size_t>(size);
size_t off = 0;
while (off < len && !feof(stream_) && !ferror(stream_))
off += fwrite(data + off, 1, len - off, stream_);
return off == len ? kContinue : kAbort;
}
private:
FILE *stream_;
};
void Snapshot::Serialize(const HeapSnapshot *profile, string filename) {
FILE *fp = fopen(filename.c_str(), "w");
if (fp == NULL) {
Error("heapdump", "open file %s failed.", filename.c_str());
return;
}
FileOutputStream stream(fp);
profile->Serialize(&stream, HeapSnapshot::kJSON);
fclose(fp);
const_cast<HeapSnapshot *>(profile)->Delete();
}
} // namespace xprofiler
| 24 | 72 | 0.660185 | rickyes |
d2e7839d96e9324465863c5e0aeebbe4e48d3442 | 9,579 | cpp | C++ | build/moc/moc_VideoReceiver.cpp | UNIST-ESCL/UNIST_GCS | f61f0c12bbb028869e4494f507ea8ab52c8c79c2 | [
"Apache-2.0"
] | 1 | 2018-11-07T06:10:53.000Z | 2018-11-07T06:10:53.000Z | build/moc/moc_VideoReceiver.cpp | UNIST-ESCL/UNIST_GCS | f61f0c12bbb028869e4494f507ea8ab52c8c79c2 | [
"Apache-2.0"
] | null | null | null | build/moc/moc_VideoReceiver.cpp | UNIST-ESCL/UNIST_GCS | f61f0c12bbb028869e4494f507ea8ab52c8c79c2 | [
"Apache-2.0"
] | 1 | 2018-11-07T06:10:47.000Z | 2018-11-07T06:10:47.000Z | /****************************************************************************
** Meta object code from reading C++ file 'VideoReceiver.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.9.3)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../../src/VideoStreaming/VideoReceiver.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'VideoReceiver.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.9.3. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
QT_WARNING_PUSH
QT_WARNING_DISABLE_DEPRECATED
struct qt_meta_stringdata_VideoReceiver_t {
QByteArrayData data[19];
char stringdata0[230];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_VideoReceiver_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_VideoReceiver_t qt_meta_stringdata_VideoReceiver = {
{
QT_MOC_LITERAL(0, 0, 13), // "VideoReceiver"
QT_MOC_LITERAL(1, 14, 19), // "videoRunningChanged"
QT_MOC_LITERAL(2, 34, 0), // ""
QT_MOC_LITERAL(3, 35, 16), // "imageFileChanged"
QT_MOC_LITERAL(4, 52, 16), // "videoFileChanged"
QT_MOC_LITERAL(5, 69, 21), // "showFullScreenChanged"
QT_MOC_LITERAL(6, 91, 5), // "start"
QT_MOC_LITERAL(7, 97, 4), // "stop"
QT_MOC_LITERAL(8, 102, 6), // "setUri"
QT_MOC_LITERAL(9, 109, 3), // "uri"
QT_MOC_LITERAL(10, 113, 13), // "stopRecording"
QT_MOC_LITERAL(11, 127, 14), // "startRecording"
QT_MOC_LITERAL(12, 142, 9), // "videoFile"
QT_MOC_LITERAL(13, 152, 12), // "_updateTimer"
QT_MOC_LITERAL(14, 165, 12), // "videoSurface"
QT_MOC_LITERAL(15, 178, 13), // "VideoSurface*"
QT_MOC_LITERAL(16, 192, 12), // "videoRunning"
QT_MOC_LITERAL(17, 205, 9), // "imageFile"
QT_MOC_LITERAL(18, 215, 14) // "showFullScreen"
},
"VideoReceiver\0videoRunningChanged\0\0"
"imageFileChanged\0videoFileChanged\0"
"showFullScreenChanged\0start\0stop\0"
"setUri\0uri\0stopRecording\0startRecording\0"
"videoFile\0_updateTimer\0videoSurface\0"
"VideoSurface*\0videoRunning\0imageFile\0"
"showFullScreen"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_VideoReceiver[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
11, 14, // methods
5, 84, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
4, // signalCount
// signals: name, argc, parameters, tag, flags
1, 0, 69, 2, 0x06 /* Public */,
3, 0, 70, 2, 0x06 /* Public */,
4, 0, 71, 2, 0x06 /* Public */,
5, 0, 72, 2, 0x06 /* Public */,
// slots: name, argc, parameters, tag, flags
6, 0, 73, 2, 0x0a /* Public */,
7, 0, 74, 2, 0x0a /* Public */,
8, 1, 75, 2, 0x0a /* Public */,
10, 0, 78, 2, 0x0a /* Public */,
11, 1, 79, 2, 0x0a /* Public */,
11, 0, 82, 2, 0x2a /* Public | MethodCloned */,
13, 0, 83, 2, 0x08 /* Private */,
// signals: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
QMetaType::Void,
// slots: parameters
QMetaType::Void,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 9,
QMetaType::Void,
QMetaType::Void, QMetaType::QString, 12,
QMetaType::Void,
QMetaType::Void,
// properties: name, type, flags
14, 0x80000000 | 15, 0x00095409,
16, QMetaType::Bool, 0x00495001,
17, QMetaType::QString, 0x00495001,
12, QMetaType::QString, 0x00495001,
18, QMetaType::Bool, 0x00495103,
// properties: notify_signal_id
0,
0,
1,
2,
3,
0 // eod
};
void VideoReceiver::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
VideoReceiver *_t = static_cast<VideoReceiver *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->videoRunningChanged(); break;
case 1: _t->imageFileChanged(); break;
case 2: _t->videoFileChanged(); break;
case 3: _t->showFullScreenChanged(); break;
case 4: _t->start(); break;
case 5: _t->stop(); break;
case 6: _t->setUri((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 7: _t->stopRecording(); break;
case 8: _t->startRecording((*reinterpret_cast< const QString(*)>(_a[1]))); break;
case 9: _t->startRecording(); break;
case 10: _t->_updateTimer(); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::videoRunningChanged)) {
*result = 0;
return;
}
}
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::imageFileChanged)) {
*result = 1;
return;
}
}
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::videoFileChanged)) {
*result = 2;
return;
}
}
{
typedef void (VideoReceiver::*_t)();
if (*reinterpret_cast<_t *>(_a[1]) == static_cast<_t>(&VideoReceiver::showFullScreenChanged)) {
*result = 3;
return;
}
}
} else if (_c == QMetaObject::RegisterPropertyMetaType) {
switch (_id) {
default: *reinterpret_cast<int*>(_a[0]) = -1; break;
case 0:
*reinterpret_cast<int*>(_a[0]) = qRegisterMetaType< VideoSurface* >(); break;
}
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty) {
VideoReceiver *_t = static_cast<VideoReceiver *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 0: *reinterpret_cast< VideoSurface**>(_v) = _t->videoSurface(); break;
case 1: *reinterpret_cast< bool*>(_v) = _t->videoRunning(); break;
case 2: *reinterpret_cast< QString*>(_v) = _t->imageFile(); break;
case 3: *reinterpret_cast< QString*>(_v) = _t->videoFile(); break;
case 4: *reinterpret_cast< bool*>(_v) = _t->showFullScreen(); break;
default: break;
}
} else if (_c == QMetaObject::WriteProperty) {
VideoReceiver *_t = static_cast<VideoReceiver *>(_o);
Q_UNUSED(_t)
void *_v = _a[0];
switch (_id) {
case 4: _t->setShowFullScreen(*reinterpret_cast< bool*>(_v)); break;
default: break;
}
} else if (_c == QMetaObject::ResetProperty) {
}
#endif // QT_NO_PROPERTIES
}
const QMetaObject VideoReceiver::staticMetaObject = {
{ &QObject::staticMetaObject, qt_meta_stringdata_VideoReceiver.data,
qt_meta_data_VideoReceiver, qt_static_metacall, nullptr, nullptr}
};
const QMetaObject *VideoReceiver::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *VideoReceiver::qt_metacast(const char *_clname)
{
if (!_clname) return nullptr;
if (!strcmp(_clname, qt_meta_stringdata_VideoReceiver.stringdata0))
return static_cast<void*>(this);
return QObject::qt_metacast(_clname);
}
int VideoReceiver::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QObject::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 11)
qt_static_metacall(this, _c, _id, _a);
_id -= 11;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 11)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 11;
}
#ifndef QT_NO_PROPERTIES
else if (_c == QMetaObject::ReadProperty || _c == QMetaObject::WriteProperty
|| _c == QMetaObject::ResetProperty || _c == QMetaObject::RegisterPropertyMetaType) {
qt_static_metacall(this, _c, _id, _a);
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyDesignable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyScriptable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyStored) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyEditable) {
_id -= 5;
} else if (_c == QMetaObject::QueryPropertyUser) {
_id -= 5;
}
#endif // QT_NO_PROPERTIES
return _id;
}
// SIGNAL 0
void VideoReceiver::videoRunningChanged()
{
QMetaObject::activate(this, &staticMetaObject, 0, nullptr);
}
// SIGNAL 1
void VideoReceiver::imageFileChanged()
{
QMetaObject::activate(this, &staticMetaObject, 1, nullptr);
}
// SIGNAL 2
void VideoReceiver::videoFileChanged()
{
QMetaObject::activate(this, &staticMetaObject, 2, nullptr);
}
// SIGNAL 3
void VideoReceiver::showFullScreenChanged()
{
QMetaObject::activate(this, &staticMetaObject, 3, nullptr);
}
QT_WARNING_POP
QT_END_MOC_NAMESPACE
| 33.493007 | 107 | 0.598288 | UNIST-ESCL |
d2e91391e42c5312372509b2bb141c1a7d383ec3 | 4,090 | cpp | C++ | src/gdb_server.cpp | Cytosine2020/neutron | 1c3db597d8a4027a03f1201c0ffb255a831a246c | [
"MIT"
] | 2 | 2020-09-03T13:36:55.000Z | 2022-03-19T17:54:36.000Z | src/gdb_server.cpp | Cytosine2020/neutron | 1c3db597d8a4027a03f1201c0ffb255a831a246c | [
"MIT"
] | null | null | null | src/gdb_server.cpp | Cytosine2020/neutron | 1c3db597d8a4027a03f1201c0ffb255a831a246c | [
"MIT"
] | null | null | null | #include "gdb_server.hpp"
#include <unistd.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <ostream>
#include "neutron_utility.hpp"
namespace neutron {
bool GDBServer::Buffer::receive(int socket) {
if (begin_ < end_ && begin_ > 0) {
for (usize i = begin_; i < end_; ++i) {
array[i - begin_] = array[i];
}
}
usize remain = end_ - begin_;
isize ret = recv(socket, array.begin() + remain, array.size() - remain, 0);
begin_ = 0;
end_ = remain + ret;
if (debug) {
if (ret > 0) {
*debug_stream << "[receive] ";
(*debug_stream).write(reinterpret_cast<const char *>(array.begin() + remain), end_);
*debug_stream << std::endl;
} else {
*debug_stream << "recv failed!" << std::endl;
}
}
return ret > 0;
}
bool GDBServer::Buffer::receive_message(int socket, GDBServer::Buffer &buf) {
if (!seek_message(socket)) return false;
u8 sum = 0;
while (true) {
i32 a = pop_socket(socket), b;
switch (a) {
case -1:
goto error;
case '$':
if (debug) { *debug_stream << "unexpected character `$`!" << std::endl; }
goto error;
case '#':
if (sum != pop_hex_byte_socket(socket)) { goto error; }
return true;
case '}':
b = pop_socket(socket);
if (b == -1) { goto error; }
sum += a + b;
buf.push(static_cast<u8>(b) ^ ESCAPE);
break;
default:
sum += a;
buf.push(a);
}
}
error:
buf.clear();
clear();
return false;
}
bool GDBServer::gdb_connect(u32 port) {
int socket_fd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in local{};
struct sockaddr_in gdb_addr{};
local.sin_family = AF_INET;
local.sin_port = htons(port);
local.sin_addr = in_addr{.s_addr = INADDR_ANY};
socklen_t len = sizeof(gdb_addr);
if (socket_fd == -1) {
neutron_warn("socket creation failed!");
goto error;
}
if (bind(socket_fd, reinterpret_cast<struct sockaddr *>(&local), sizeof(local)) == -1) {
neutron_warn("socket bind failed!");
goto error;
}
if (listen(socket_fd, 1) == -1) {
neutron_warn("socket listen failed!");
goto error;
}
gdb = ::accept(socket_fd, reinterpret_cast<struct sockaddr *>(&gdb_addr), &len);
if (gdb == -1) {
neutron_warn("accept failed!");
goto error;
}
if (debug) {
char *in_addr = reinterpret_cast<char *>(&gdb_addr.sin_addr);
*debug_stream << static_cast<u32>(in_addr[0]) << '.'
<< static_cast<u32>(in_addr[1]) << '.'
<< static_cast<u32>(in_addr[2]) << '.'
<< static_cast<u32>(in_addr[3]) << ':'
<< gdb_addr.sin_port << std::endl;
}
close(socket_fd);
if (recv_buffer.pop_socket(gdb) != '+') {
if (debug) { *debug_stream << "the first character received is not `+`!" << std::endl; }
gdb_close();
}
send_buffer.push('$');
return true;
error:
if (socket_fd != -1) { close(socket_fd); }
return false;
}
bool GDBServer::send() {
u8 sum = 0;
for (auto *ptr = send_buffer.begin() + 1, *end = send_buffer.end(); ptr < end; ++ptr) {
sum += *ptr;
}
if (!send_buffer.push('#') || !send_buffer.push_hex_byte(sum)) return false;
for (usize retry = 0; retry < RETRY; ++retry) {
isize byte = send_message(reinterpret_cast<const char *>(send_buffer.begin()),
send_buffer.size());
if (static_cast<usize>(byte) == send_buffer.size()) {
recv_buffer.clear();
if (recv_buffer.pop_socket(gdb) == '+') {
send_buffer.clear();
send_buffer.push('$');
return true;
}
}
}
return false;
}
}
| 25.72327 | 96 | 0.51198 | Cytosine2020 |
d2ea4e3b00573bdd4382469a615e62247c72b75d | 645 | hpp | C++ | modules/procedural/source/blub/procedural/log/global.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 96 | 2015-02-02T20:01:24.000Z | 2021-11-14T20:33:29.000Z | modules/procedural/source/blub/procedural/log/global.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 12 | 2016-06-04T15:45:30.000Z | 2020-02-04T11:10:51.000Z | modules/procedural/source/blub/procedural/log/global.hpp | qwertzui11/voxelTerrain | 05038fb261893dd044ae82fab96b7708ea5ed623 | [
"MIT"
] | 19 | 2015-09-22T01:21:45.000Z | 2020-09-30T09:52:27.000Z | #ifndef BLUB_PROCEDURAL_LOG_GLOBAL_HPP
#define BLUB_PROCEDURAL_LOG_GLOBAL_HPP
#include "blub/log/global.hpp"
#include "blub/log/globalLogger.hpp"
#include "blub/log/logger.hpp"
#include "blub/log/predecl.hpp"
namespace blub
{
namespace procedural
{
namespace log
{
BLUB_LOG_GLOBAL_LOGGER(global, blub::log::logger)
}
}
}
#define BLUB_PROCEDURAL_LOG_OUT() BLUB_LOG_OUT_TO(blub::procedural::log::global::get())
#define BLUB_PROCEDURAL_LOG_WARNING() BLUB_LOG_WARNING_TO(blub::procedural::log::global::get())
#define BLUB_PROCEDURAL_LOG_ERROR() BLUB_LOG_ERROR_TO(blub::procedural::log::global::get())
#endif // BLUB_PROCEDURAL_LOG_GLOBAL_HPP
| 23.035714 | 95 | 0.795349 | qwertzui11 |
d2ee01391bcdf7ee82c7a630fc56fcefc34731e7 | 7,327 | cpp | C++ | tester/g_ult/unit_tests/cpu/test_cases/cpu_layer_softmax.cpp | davenso/idlf | df34a6b88c1ff1880fbb2b58caccd6075dd414a5 | [
"BSD-3-Clause"
] | 1 | 2015-12-04T21:01:27.000Z | 2015-12-04T21:01:27.000Z | tester/g_ult/unit_tests/cpu/test_cases/cpu_layer_softmax.cpp | davenso/idlf | df34a6b88c1ff1880fbb2b58caccd6075dd414a5 | [
"BSD-3-Clause"
] | null | null | null | tester/g_ult/unit_tests/cpu/test_cases/cpu_layer_softmax.cpp | davenso/idlf | df34a6b88c1ff1880fbb2b58caccd6075dd414a5 | [
"BSD-3-Clause"
] | null | null | null | /*
Copyright (c) 2014, Intel Corporation
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 Intel Corporation nor the names of its contributors
may be used to endorse or promote products derived from this software
without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <cfloat>
#include "tester/g_ult/unit_tests/cpu/naive_implementations.h"
namespace
{
///////////////////////////////////////////////////////////////////////////////////////////////////
// Helper classess and functions.
bool compare_work_items(
nn_workload_item* &work_item,
nn_workload_item* &work_item_ref)
{
for (uint32_t batch = 0; batch < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_n]; ++batch)
{
for (uint32_t output_element = 0; output_element < work_item->output[0]->parent->lengths.t[NN_DATA_COORD_x]; ++output_element)
{
float value = nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0);
float value_ref = nn_workload_data_get<float>(work_item_ref->output[0], batch, output_element, 0, 0, 0, 0);
float diff = fabs(value_ref - value);
if (value_ref == 0.0f || value == 0.0f || diff < FLT_MIN)
{
if (diff > FLT_MIN)
{
return false;
}
}
else
{
if (fabs(diff / value_ref) > 5.2e-05F)
{
return false;
}
}
}
}
return true;
}
bool run_work_item(
nn_workload_item* &work_item,
bool is_ref,
nn_device_t *device)
{
if (is_ref)
{
// Naive implementation.
cpu_layer_softmax( //definition in naive_implementations.cpp
work_item,
is_ref,
device);
}
else
{
// Use optimized routine.
work_item->primitive->forward({work_item->input[0].get_data_view()}, {}, work_item->output);
}
return true;
}
void destroy_work_item(
nn_workload_item* &work_item)
{
work_item->input.clear();
delete reinterpret_cast<nn::workload_data<float>*>(work_item->output[0]);
delete work_item;
work_item = nullptr;
}
void create_and_initialize_input_item(
nn_workload_item* &work_item,
uint32_t input_width,
uint32_t batch_size)
{
nn_workload_data_coords_t in_out_coords =
{
batch_size,
input_width,
1,
1,
1,
1
};
work_item = new nn_workload_item();
work_item->type = NN_WORK_ITEM_TYPE_INPUT;
work_item->arguments.input.index = 0;
nn_workload_data_layout_t inp_out_layout = nn::workload_data<float>::layout.nxyzpq;
work_item->output.push_back(new nn::workload_data<float>(in_out_coords, inp_out_layout));
for (uint32_t batch = 0; batch < batch_size; ++batch)
{
for (uint32_t input_element = 0; input_element < input_width; ++input_element)
{
float value = 0.03125f;
value *= pow(1.01f, input_element);
value *= pow(1.01f, batch);
if (input_element % 2) value *= -1.0f;
nn_workload_data_get<float>(work_item->output[0], batch, input_element, 0, 0, 0, 0) = value;
}
}
}
void create_and_initialize_work_item(
nn_workload_item* &work_item,
nn_workload_item* input_item,
uint32_t input_width,
uint32_t batch_size,
nn_device_t *device)
{
nn_workload_data_coords_t in_out_coords =
{
batch_size,
input_width,
1,
1,
1,
1
};
work_item = new nn_workload_item();
work_item->type = NN_WORK_ITEM_TYPE_SOFTMAX;
work_item->primitive =
new layer::softmax_f32(input_width, batch_size, reinterpret_cast<nn_device_internal *>(device));
work_item->input.push_back({ input_item, 0 });
nn_workload_data_layout_t inp_out_layout = nn::workload_data<float>::layout.nxyzpq;
work_item->output.push_back(new nn::workload_data<float>(in_out_coords, inp_out_layout));
for (uint32_t batch = 0; batch < batch_size; ++batch)
{
for (uint32_t output_element = 0; output_element < input_width; ++output_element)
{
nn_workload_data_get<float>(work_item->output[0], batch, output_element, 0, 0, 0, 0) = 0.0f;
}
}
}
bool ult_perform_test(
uint32_t input_width,
uint32_t batch_size)
{
bool return_value = true;
nn_device_description_t device_description;
nn_device_interface_0_t device_interface_0;
nn_device_load(&device_description);
nn_device_interface_open(0, &device_interface_0);
// Input item.
nn_workload_item* input_item = nullptr;
create_and_initialize_input_item(input_item, input_width, batch_size);
// Work item.
nn_workload_item* work_item = nullptr;
create_and_initialize_work_item(work_item, input_item, input_width, batch_size, device_interface_0.device);
// Reference workload item.
nn_workload_item* work_item_ref = nullptr;
create_and_initialize_work_item(work_item_ref, input_item, input_width, batch_size, nullptr);
// Run items.
return_value &= run_work_item(work_item, false, device_interface_0.device);
return_value &= run_work_item(work_item_ref, true, nullptr);
// Compare results.
return_value &= compare_work_items(work_item, work_item_ref);
// Cleanup.
destroy_work_item(work_item);
destroy_work_item(work_item_ref);
destroy_work_item(input_item);
nn_device_interface_close(&device_interface_0);
nn_device_unload();
return return_value;
}
}
///////////////////////////////////////////////////////////////////////////////////////////////////
// Tests.
TEST(cpu_softmax_artificial, cpu_softmax_base)
{
uint32_t batches[] = { 1, 8, 48 };
for (auto batch : batches)
for (uint32_t input_sizes = 1; input_sizes < 256; ++input_sizes)
EXPECT_EQ(true, ult_perform_test(
input_sizes, // input/output width
batch // batch size
));
} | 31.718615 | 134 | 0.653746 | davenso |
d2f1e8a9a135b0da04a661fa80c256bcac7c48c1 | 9,611 | cpp | C++ | src/main.cpp | csc-std/routine | 16e74628eb4815a816fb8eecbbe8e5fe2ad55daa | [
"MIT"
] | null | null | null | src/main.cpp | csc-std/routine | 16e74628eb4815a816fb8eecbbe8e5fe2ad55daa | [
"MIT"
] | null | null | null | src/main.cpp | csc-std/routine | 16e74628eb4815a816fb8eecbbe8e5fe2ad55daa | [
"MIT"
] | null | null | null | #include "util.h"
using namespace UNITTEST ;
namespace UNITTEST {
template <class U>
struct GN_sqrt_mFirstY {
DOUBLE mFirstY ;
Scope<GN_sqrt_mFirstY> mHandle ;
explicit GN_sqrt_mFirstY (VREF<SyntaxTree> me) {
me.mark_as_iteration () ;
me.then (Function<void> ([&] () {
mFirstY = me.later (TYPEAS<DOUBLE>::expr) ;
Singleton<Console>::instance ().print (slice ("mFirstY = ") ,mFirstY) ;
})) ;
mHandle = Scope<GN_sqrt_mFirstY> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFirstY[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFirstY[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrX {
DOUBLE mCurrX ;
Scope<GN_sqrt_mCurrX> mHandle ;
explicit GN_sqrt_mCurrX (VREF<SyntaxTree> me) {
me.mark_as_iteration () ;
me.then (Function<void> ([&] () {
mCurrX = me.later (TYPEAS<DOUBLE>::expr) ;
})) ;
mHandle = Scope<GN_sqrt_mCurrX> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrX[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrX[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrY {
DOUBLE mCurrY ;
Scope<GN_sqrt_mCurrY> mHandle ;
explicit GN_sqrt_mCurrY (VREF<SyntaxTree> me) {
auto &mFirstY = me.stack (TYPEAS<GN_sqrt_mFirstY<U>>::expr).mFirstY ;
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
me.then (Function<void> ([&] () {
mCurrY = MathProc::square (mCurrX) - mFirstY ;
Singleton<Console>::instance ().print (slice ("mCurrY = ") ,mCurrY) ;
})) ;
mHandle = Scope<GN_sqrt_mCurrY> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrY[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrY[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrZ {
DOUBLE mCurrZ ;
Scope<GN_sqrt_mCurrZ> mHandle ;
explicit GN_sqrt_mCurrZ (VREF<SyntaxTree> me) {
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
me.then (Function<void> ([&] () {
mCurrZ = 2 * mCurrX ;
})) ;
mHandle = Scope<GN_sqrt_mCurrZ> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrZ[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrZ[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mNextX {
DOUBLE mNextX ;
Scope<GN_sqrt_mNextX> mHandle ;
explicit GN_sqrt_mNextX (VREF<SyntaxTree> me) {
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
auto &mCurrY = me.stack (TYPEAS<GN_sqrt_mCurrY<U>>::expr).mCurrY ;
auto &mCurrZ = me.stack (TYPEAS<GN_sqrt_mCurrZ<U>>::expr).mCurrZ ;
me.then (Function<void> ([&] () {
mNextX = mCurrX - mCurrY * MathProc::inverse (mCurrZ) ;
})) ;
mHandle = Scope<GN_sqrt_mNextX> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mNextX[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mNextX[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mCurrTimes {
LENGTH mCurrTimes ;
Scope<GN_sqrt_mCurrTimes> mHandle ;
explicit GN_sqrt_mCurrTimes (VREF<SyntaxTree> me) {
me.mark_as_iteration () ;
me.then (Function<void> ([&] () {
mCurrTimes = me.later (TYPEAS<LENGTH>::expr) ;
})) ;
mHandle = Scope<GN_sqrt_mCurrTimes> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mCurrTimes[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mCurrTimes[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mNextTimes {
LENGTH mNextTimes ;
Scope<GN_sqrt_mNextTimes> mHandle ;
explicit GN_sqrt_mNextTimes (VREF<SyntaxTree> me) {
auto &mCurrTimes = me.stack (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr).mCurrTimes ;
me.then (Function<void> ([&] () {
mNextTimes = mCurrTimes + 1 ;
})) ;
mHandle = Scope<GN_sqrt_mNextTimes> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mNextTimes[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mNextTimes[") ,U::expr ,slice ("]")) ;
}
} ;
template <class U>
struct GN_sqrt_mFinalX {
DOUBLE mFinalX ;
LENGTH mFinalTimes ;
Scope<GN_sqrt_mFinalX> mHandle ;
explicit GN_sqrt_mFinalX (VREF<SyntaxTree> me) {
me.maybe (TYPEAS<GN_sqrt_mFirstY<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mCurrX<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mNextX<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mCurrY<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mNextTimes<U>>::expr) ;
me.once (Function<void> ([&] () {
auto &mFirstY = me.stack (TYPEAS<GN_sqrt_mFirstY<U>>::expr).mFirstY ;
auto &mCurrX = me.stack (TYPEAS<GN_sqrt_mCurrX<U>>::expr).mCurrX ;
auto &mNextX = me.stack (TYPEAS<GN_sqrt_mNextX<U>>::expr).mNextX ;
auto &mCurrY = me.stack (TYPEAS<GN_sqrt_mCurrY<U>>::expr).mCurrY ;
auto &mCurrTimes = me.stack (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr).mCurrTimes ;
auto &mNextTimes = me.stack (TYPEAS<GN_sqrt_mNextTimes<U>>::expr).mNextTimes ;
me.redo (TYPEAS<GN_sqrt_mCurrX<U>>::expr ,mFirstY) ;
me.redo (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr ,ZERO) ;
while (TRUE) {
me.play () ;
if (MathProc::abs (mCurrY) < DOUBLE (SINGLE_EPS))
break ;
if (mCurrTimes >= 100)
break ;
me.undo (TYPEAS<GN_sqrt_mCurrX<U>>::expr) ;
me.undo (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr) ;
me.redo (TYPEAS<GN_sqrt_mCurrX<U>>::expr ,mNextX) ;
me.redo (TYPEAS<GN_sqrt_mCurrTimes<U>>::expr ,mNextTimes) ;
}
me.then (Function<void> ([&] () {
mFinalX = mCurrX ;
mFinalTimes = mCurrTimes ;
Singleton<Console>::instance ().print (slice ("mFinalX = ") ,mFinalX) ;
Singleton<Console>::instance ().print (slice ("mFinalTimes = ") ,mFinalTimes) ;
})) ;
})) ;
mHandle = Scope<GN_sqrt_mFinalX> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFinalX[") ,U::expr ,slice ("]")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFinalX[") ,U::expr ,slice ("]")) ;
}
} ;
struct GN_sqrt_mFirstY_thread {
Array<DOUBLE> mFirstY ;
Scope<GN_sqrt_mFirstY_thread> mHandle ;
explicit GN_sqrt_mFirstY_thread (VREF<SyntaxTree> me) {
me.then (Function<void> ([&] () {
mFirstY = Array<DOUBLE> (10) ;
for (auto &&i : mFirstY) {
const auto r1x = Random::instance ().random_value (100 ,10000) ;
i = DOUBLE (r1x) ;
}
})) ;
mHandle = Scope<GN_sqrt_mFirstY_thread> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFirstY_thread")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFirstY_thread")) ;
}
} ;
struct GN_sqrt_mFinalX_thread {
Array<DOUBLE> mFinalX ;
Scope<GN_sqrt_mFinalX_thread> mHandle ;
explicit GN_sqrt_mFinalX_thread (VREF<SyntaxTree> me) {
auto &&mFirstY = me.stack (TYPEAS<GN_sqrt_mFirstY_thread>::expr).mFirstY ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK0>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK1>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK2>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK3>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK4>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK5>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK6>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK7>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK8>>::expr) ;
me.maybe (TYPEAS<GN_sqrt_mFinalX<RANK9>>::expr) ;
me.once (Function<void> ([&] () {
mFinalX = Array<DOUBLE> (mFirstY.length ()) ;
process<RANK0> (me ,mFirstY ,mFinalX) ;
process<RANK1> (me ,mFirstY ,mFinalX) ;
process<RANK2> (me ,mFirstY ,mFinalX) ;
process<RANK3> (me ,mFirstY ,mFinalX) ;
process<RANK4> (me ,mFirstY ,mFinalX) ;
process<RANK5> (me ,mFirstY ,mFinalX) ;
process<RANK6> (me ,mFirstY ,mFinalX) ;
process<RANK7> (me ,mFirstY ,mFinalX) ;
process<RANK8> (me ,mFirstY ,mFinalX) ;
process<RANK9> (me ,mFirstY ,mFinalX) ;
me.then (Function<void> ([&] () {
Singleton<Console>::instance ().print () ;
for (auto &&i : mFinalX.iter ()) {
Singleton<Console>::instance ().print (slice ("sqrt (") ,mFirstY[i] ,slice (") = ") ,mFinalX[i]) ;
}
Singleton<Console>::instance ().print () ;
})) ;
})) ;
mHandle = Scope<GN_sqrt_mFinalX_thread> (thiz) ;
}
void enter () {
Singleton<Console>::instance ().info (slice ("enter GN_sqrt_mFinalX_thread")) ;
}
void leave () {
Singleton<Console>::instance ().info (slice ("leave GN_sqrt_mFinalX_thread")) ;
}
template <class U>
imports void process (
VREF<SyntaxTree> me ,
CREF<Array<DOUBLE>> mFirstY_thread ,
VREF<Array<DOUBLE>> mFinalX_thread) {
auto &mFinalX = me.stack (TYPEAS<GN_sqrt_mFinalX<U>>::expr).mFinalX ;
me.redo (TYPEAS<GN_sqrt_mFirstY<U>>::expr ,mFirstY_thread[U::expr]) ;
me.play () ;
mFinalX_thread[U::expr] = mFinalX ;
}
} ;
} ;
exports void test_main () ;
#ifdef __CSC_TARGET_EXE__
exports int main () {
Singleton<Reporter>::instance ().detect_memory_leaks () ;
Singleton<Reporter>::instance ().detect_crash_signal () ;
Singleton<Console>::instance ().open () ;
Singleton<Console>::instance ().link (slice (".")) ;
test_main () ;
return 0 ;
}
#endif | 30.511111 | 103 | 0.655499 | csc-std |
d2f25c92265d7d680c5b5fb7187d406c4b75d3d4 | 3,451 | cpp | C++ | Sources/engine/engine/private/engine/Engine.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 20 | 2019-12-22T20:40:22.000Z | 2021-07-06T00:23:45.000Z | Sources/engine/engine/private/engine/Engine.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 32 | 2020-07-11T15:51:13.000Z | 2021-06-07T10:25:07.000Z | Sources/engine/engine/private/engine/Engine.cpp | Zino2201/ZinoEngine | 519d34a1d2b09412c8e2cba6b685b4556ec2c2ac | [
"MIT"
] | 3 | 2019-12-19T17:04:04.000Z | 2021-05-17T01:49:59.000Z | #include "engine/Engine.h"
#include "module/Module.h"
#include "module/ModuleManager.h"
#include "engine/TickSystem.h"
#include "profiling/Profiling.h"
#include "console/Console.h"
#include <SDL.h>
#include "engine/InputSystem.h"
#include "module/Module.h"
#include "assetdatabase/AssetDatabase.h"
namespace ze
{
static ConVarRef<int32_t> cvar_maxfps("r_maxfps", 300,
"Max FPS when focused. 0 to disable.",
0,
300);
static ConVarRef<int32_t> cvar_unfocus_fps("r_unfocusfps", 15,
"Max FPS when unfocused",
1,
1000);
static ConVarRef<int32_t> CVarSimFPS("sim_fixed_dt", 20,
"Fixed simulation/Physics delta time",
1,
60);
bool bRun = true;
ZE_DEFINE_MODULE(ze::module::DefaultModule, engine)
/**
* Try to load a required module
* Crash if it fails
*/
ze::module::Module* LoadRequiredModule(const std::string_view& InName)
{
ze::module::Module* Ptr = ze::module::load_module(InName);
if (!Ptr)
ze::logger::fatal("Failed to load required module {} ! Exiting", InName);
return Ptr;
}
EngineApp::EngineApp() : should_run(false), focused(true), frame_count(0), err_code(0)
{
/** Load asset related modules */
LoadRequiredModule("asset");
LoadRequiredModule("assetdatabase");
previous = std::chrono::high_resolution_clock::now();
}
void EngineApp::process_event(const SDL_Event& in_event, const float in_delta_time)
{
if (in_event.type == SDL_QUIT)
exit(0);
if (in_event.type == SDL_KEYDOWN)
ze::input::on_key_pressed(in_event);
if (in_event.type == SDL_KEYUP)
ze::input::on_key_released(in_event);
if (in_event.type == SDL_MOUSEMOTION)
ze::input::set_mouse_delta(maths::Vector2f(in_event.motion.xrel, in_event.motion.yrel));
/*
if (in_event.type == SDL_WINDOWEVENT)
{
switch(in_event.window.event)
{
case SDL_WINDOWEVENT_FOCUS_GAINED:
focused = true;
break;
case SDL_WINDOWEVENT_FOCUS_LOST:
focused = false;
break;
}
}
*/
}
int EngineApp::run()
{
should_run = true;
focused = true;
while(should_run)
{
loop();
}
return err_code;
}
void EngineApp::exit(int in_err_code)
{
should_run = false;
err_code = in_err_code;
}
double engine_elapsed_time = 0.0;
double engine_delta_time = 0.0;
void EngineApp::loop()
{
auto current = std::chrono::high_resolution_clock::now();
std::chrono::duration<double, std::milli> delta_time = current - previous;
previous = current;
engine_delta_time = delta_time.count();
float delta_time_as_secs = static_cast<float>(engine_delta_time) * 0.001f;
engine_elapsed_time += delta_time_as_secs;
ze::input::clear();
/** Process events */
{
SDL_Event event;
while (SDL_PollEvent(&event))
{
process_event(event, delta_time_as_secs);
}
}
ticksystem::tick(ticksystem::TickFlagBits::Variable, delta_time_as_secs);
ticksystem::tick(ticksystem::TickFlagBits::Late, delta_time_as_secs);
post_tick(delta_time_as_secs);
/** Fps limiter */
if(cvar_maxfps.get() != 0)
{
using namespace std::chrono_literals;
focused = true;
const std::chrono::duration<double, std::milli> min_ms(focused ? (1000.0 / cvar_maxfps.get()) : (1000.0 / cvar_unfocus_fps.get()));
const auto target_sleep_time = current + min_ms;
std::this_thread::sleep_until(target_sleep_time - 1ms);
while(std::chrono::high_resolution_clock::now() < target_sleep_time) {}
}
frame_count++;
}
double EngineApp::get_elapsed_time()
{
return engine_elapsed_time;
}
double EngineApp::get_delta_time()
{
return engine_delta_time;
}
} /* namespace ze */ | 22.121795 | 133 | 0.722689 | Zino2201 |
d2f2a2afd2e868f8c599c400ab9fbbe6f347e299 | 12,000 | hpp | C++ | src/utility.hpp | bkentel/boken-old | 8967856be5f283989d0c10843bcb739728423152 | [
"MIT"
] | null | null | null | src/utility.hpp | bkentel/boken-old | 8967856be5f283989d0c10843bcb739728423152 | [
"MIT"
] | null | null | null | src/utility.hpp | bkentel/boken-old | 8967856be5f283989d0c10843bcb739728423152 | [
"MIT"
] | 1 | 2020-04-11T12:20:00.000Z | 2020-04-11T12:20:00.000Z | #pragma once
#include "config.hpp" //string_view
#include <bkassert/assert.hpp>
#include <type_traits>
#include <algorithm>
#include <array>
#include <functional>
#include <utility>
#include <memory>
#include <cstddef>
#include <cstdint>
namespace boken {
namespace detail {
template <typename Container, typename Compare>
void sort_impl(Container&& c, Compare comp) {
using std::sort;
using std::begin;
using std::end;
sort(begin(c), end(c), comp);
}
} //namespace detail
namespace container_algorithms {
template <typename Container, typename Compare>
void sort(Container&& c, Compare comp) {
detail::sort_impl(std::forward<Container>(c), comp);
}
template <typename Container, typename Predicate>
auto find_if(Container&& c, Predicate pred) {
using std::begin;
using std::end;
return std::find_if(begin(c), end(c), pred);
}
template <typename Container, typename Predicate>
auto* find_ptr_if(Container&& c, Predicate pred) {
using std::begin;
using std::end;
using result_t = decltype(std::addressof(*begin(c)));
auto const it = find_if(std::forward<Container>(c), pred);
return (it == end(c))
? static_cast<result_t>(nullptr)
: std::addressof(*it);
}
} // container_algorithms
template <size_t N, typename Predicate = std::less<>>
auto sort_by_nth_element(Predicate pred = Predicate {}) noexcept {
return [pred](auto const& a, auto const& b) noexcept {
return pred(std::get<N>(a), std::get<N>(b));
};
}
enum class convertion_type {
unchecked, clamp, fail, modulo
};
template <convertion_type T>
using convertion_t = std::integral_constant<convertion_type, T>;
template <typename T>
constexpr auto as_unsigned(T const n, convertion_t<convertion_type::clamp>) noexcept {
return static_cast<std::make_unsigned_t<T>>(n < 0 ? 0 : n);
}
template <typename T>
constexpr auto as_unsigned(T const n, convertion_type const type = convertion_type::clamp) noexcept {
static_assert(std::is_arithmetic<T>::value, "");
using ct = convertion_type;
return type == ct::clamp ? as_unsigned(n, convertion_t<ct::clamp> {})
: as_unsigned(n, convertion_t<ct::clamp> {});
}
template <typename T, typename U>
inline constexpr ptrdiff_t check_offsetof() noexcept {
static_assert(std::is_standard_layout<T>::value
, "Must be standard layout");
static_assert(!std::is_function<U>::value
, "Must not be a function");
static_assert(!std::is_member_function_pointer<std::add_pointer_t<U>>::value
, "Must not be a member function");
return 0;
}
#define BK_OFFSETOF(s, m) (check_offsetof<s, decltype(s::m)>() + offsetof(s, m))
template <typename T>
inline constexpr std::add_const_t<T>& as_const(T& t) noexcept {
return t;
}
template <typename T>
void as_const(T const&&) = delete;
template <typename T>
inline constexpr std::add_const_t<T>* as_const(T* const t) noexcept {
return t;
}
template <typename T>
inline constexpr void call_destructor(T& t)
noexcept(std::is_nothrow_destructible<T>::value)
{
t.~T();
(void)t; // spurious unused warning
}
template <size_t StackSize>
class basic_buffer {
public:
explicit basic_buffer(size_t const size)
: data_ {}
, size_ {size <= StackSize ? StackSize : size}
, first_ {init_storage_(data_, size_)}
{
}
basic_buffer() noexcept
: basic_buffer {StackSize}
{
}
~basic_buffer() {
size_ <= StackSize ? call_destructor(data_.s_)
: call_destructor(data_.d_);
}
auto size() const noexcept { return size_; }
auto data() const noexcept { return as_const(first_); }
auto begin() const noexcept { return data(); }
auto end() const noexcept { return begin() + size(); }
auto data() noexcept { return first_; }
auto begin() noexcept { return data(); }
auto end() noexcept { return begin() + size(); }
char operator[](size_t const i) const noexcept {
return *(begin() + i);
}
char& operator[](size_t const i) noexcept {
return *(begin() + i);
}
private:
using static_t = std::array<char, StackSize + 1>;
using dynamic_t = std::unique_ptr<char[]>;
union storage_t {
storage_t() noexcept {}
~storage_t() {}
static_t s_;
dynamic_t d_;
} data_;
static char* init_storage_(storage_t& data, size_t const size) {
if (size && size <= StackSize) {
new (&data.s_) static_t;
return data.s_.data();
} else {
new (&data.d_) dynamic_t {new char[size]};
return data.d_.get();
}
}
size_t size_;
char* first_;
};
using dynamic_buffer = basic_buffer<0>;
template <size_t Size>
using static_buffer = basic_buffer<Size>;
template <typename T>
class sub_region_iterator : public std::iterator_traits<T*> {
using this_t = sub_region_iterator<T>;
template <typename U> friend class sub_region_iterator;
public:
using reference = typename std::iterator_traits<T*>::reference;
using pointer = typename std::iterator_traits<T*>::pointer;
sub_region_iterator(
T* const p
, ptrdiff_t const off_x, ptrdiff_t const off_y
, ptrdiff_t const width_outer, ptrdiff_t const height_outer
, ptrdiff_t const width_inner, ptrdiff_t const height_inner
, ptrdiff_t const x = 0, ptrdiff_t const y = 0
) noexcept
: p_ {p + (off_x + x) + (off_y + y) * width_outer}
, off_x_ {off_x}
, off_y_ {off_y}
, width_outer_ {width_outer}
, width_inner_ {width_inner}
, height_inner_ {height_inner}
, x_ {x}
, y_ {y}
{
BK_ASSERT(!!p);
BK_ASSERT(off_x >= 0 && off_y >= 0);
BK_ASSERT(width_inner >= 0 && width_outer >= width_inner + off_x);
BK_ASSERT(height_inner >= 0 && height_outer >= height_inner + off_y);
BK_ASSERT(x_ <= width_inner && y_ <= height_inner);
}
// create a new iterator with the same properties as other, but with a
// different base pointer.
template <typename U>
sub_region_iterator(sub_region_iterator<U> it, T* const p) noexcept
: p_ {p + (it.off_x_ + it.x_) + (it.off_y_ + it.y_) * it.width_outer_}
, off_x_ {it.off_x_}
, off_y_ {it.off_y_}
, width_outer_ {it.width_outer_}
, width_inner_ {it.width_inner_}
, height_inner_ {it.height_inner_}
, x_ {it.x_}
, y_ {it.y_}
{
}
reference operator*() const noexcept {
return *p_;
}
pointer operator->() const noexcept {
return &**this;
}
void operator++() noexcept {
++p_;
if (++x_ < width_inner_) {
return;
}
if (++y_ < height_inner_) {
x_ = 0;
p_ += (width_outer_ - width_inner_);
}
}
sub_region_iterator operator++(int) noexcept {
auto result = *this;
++(*this);
return result;
}
bool operator<(this_t const& other) const noexcept {
return p_ < other.p_;
}
bool operator==(this_t const& other) const noexcept {
return (p_ == other.p_);
}
bool operator!=(this_t const& other) const noexcept {
return !(*this == other);
}
ptrdiff_t operator-(this_t const& other) const noexcept {
BK_ASSERT(is_compatible_(other));
return (x_ + y_ * width_inner_)
- (other.x_ + other.y_ * other.width_inner_);
}
ptrdiff_t x() const noexcept { return x_; }
ptrdiff_t y() const noexcept { return y_; }
ptrdiff_t off_x() const noexcept { return off_x_; }
ptrdiff_t off_y() const noexcept { return off_y_; }
ptrdiff_t width() const noexcept { return width_inner_; }
ptrdiff_t height() const noexcept { return height_inner_; }
ptrdiff_t stride() const noexcept { return width_outer_; }
private:
template <typename U>
bool is_compatible_(sub_region_iterator<U> const& it) const noexcept {
return off_x_ == it.off_x_
&& off_y_ == it.off_y_
&& width_outer_ == it.width_outer_
&& width_inner_ == it.width_inner_
&& height_inner_ == it.height_inner_;
}
T* p_ {};
ptrdiff_t off_x_ {};
ptrdiff_t off_y_ {};
ptrdiff_t width_outer_ {};
ptrdiff_t width_inner_ {};
ptrdiff_t height_inner_ {};
ptrdiff_t x_ {};
ptrdiff_t y_ {};
};
template <typename T>
using const_sub_region_iterator = sub_region_iterator<std::add_const_t<std::decay_t<T>>>;
template <typename T>
using sub_region_range = std::pair<
sub_region_iterator<T>, sub_region_iterator<T>>;
template <typename T>
using const_sub_region_range = sub_region_range<std::add_const_t<std::decay_t<T>>>;
template <typename T>
sub_region_range<T> make_sub_region_range(
T* const p
, ptrdiff_t const off_x, ptrdiff_t const off_y
, ptrdiff_t const width_outer, ptrdiff_t const height_outer
, ptrdiff_t const width_inner, ptrdiff_t const height_inner
) noexcept {
return {
sub_region_iterator<T> {
p
, off_x, off_y
, width_outer, height_outer
, width_inner, height_inner
}
, sub_region_iterator<T> {
p
, off_x, off_y
, width_outer, height_outer
, width_inner, height_inner
, width_inner, height_inner - 1
}
};
}
namespace detail {
template <typename It>
size_t weight_list_size(std::random_access_iterator_tag, It const first, It const last) noexcept {
return static_cast<size_t>(std::distance(first, last));
}
template <typename Tag, typename It>
size_t weight_list_size(Tag, It, It) noexcept {
return 0u;
}
} // namespace detail
template <typename Weight, typename Result>
class weight_list {
static_assert(std::is_arithmetic<Weight>::value, "");
using pair_t = std::pair<Weight, Result>;
public:
weight_list() = default;
template <typename InputIt1, typename InputIt2>
weight_list(InputIt1 const first_weight, InputIt1 const last_weight
, InputIt2 const first_result, InputIt2 const last_result
) {
using tag1_t = typename std::iterator_traits<InputIt1>::iterator_category;
using tag2_t = typename std::iterator_traits<InputIt2>::iterator_category;
size_t const s1 =
detail::weight_list_size(tag1_t {}, first_weight, last_weight);
size_t const s2 =
detail::weight_list_size(tag2_t {}, first_result, last_result);
size_t const reserve_size =
((s1 > 0u) && (s2 > 0u)) ? std::min(s1, s2)
: (s1 > 0u) ? s1
: (s2 > 0u) ? s2
: 0u;
data_.reserve(reserve_size);
auto it1 = first_weight;
auto it2 = first_result;
for (; it1 != last_weight && it2 != last_result; ++it1, ++it2) {
BK_ASSERT(*it1 > Weight {});
data_.push_back({sum_ += *it1, *it2});
}
}
weight_list(std::initializer_list<pair_t> const data) {
data_.reserve(data.size());
for (auto const& p : data) {
BK_ASSERT(p.first > 0);
data_.push_back({sum_ += p.first, p.second});
}
}
Weight max() const noexcept { return sum_; }
Result const& operator[](Weight const n) const noexcept {
BK_ASSERT(!data_.empty() && n >= Weight {} && n < sum_);
auto const first = begin(data_);
auto const last = end(data_);
auto const it = std::lower_bound(first, last, n
, [](pair_t const& p, Weight const w) noexcept {
return p.first <= w;
});
return (it != last)
? it->second
: data_.back().second;
}
private:
std::vector<pair_t> data_ {};
Weight sum_ {};
};
} //namespace boken
| 28.436019 | 101 | 0.6165 | bkentel |
d2f4085b5e1c59ada5e4bcd5fb22e6789fc4ebf7 | 7,936 | cpp | C++ | lib/essex/server/daemon.cpp | holtzermann17/Noosphere | 7be63c122f778ef00e56ffe847a6d40d004527dd | [
"MIT"
] | 1 | 2018-05-31T06:29:48.000Z | 2018-05-31T06:29:48.000Z | lib/essex/server/daemon.cpp | holtzermann17/Noosphere | 7be63c122f778ef00e56ffe847a6d40d004527dd | [
"MIT"
] | null | null | null | lib/essex/server/daemon.cpp | holtzermann17/Noosphere | 7be63c122f778ef00e56ffe847a6d40d004527dd | [
"MIT"
] | 1 | 2021-05-02T15:14:36.000Z | 2021-05-02T15:14:36.000Z | #include <strstream>
#include <pthread.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <assert.h>
#include "daemon.h"
// forward decl
void* thread_handle (void *);
/* these must be global so the term handler can get them */
pid_t childunix, childinet;
vector<pid_t> children;
/* term for main searchd process */
void handler_term( int arg ) {
if( childunix ) kill( childunix, SIGTERM );
if( childinet ) kill( childinet, SIGTERM );
exit( 0 );
}
/* handle sigchld to clean up zombies */
void handler_child( int arg ) {
wait( NULL );
}
/* term for listeners */
void handler_term_listener( int arg ) {
/* kill all the children */
for( int i=0; i < children.size(); ++i ) {
if( children[i] )
kill( children[i], SIGTERM );
}
}
/* sigchld for listeners */
void handler_child_listener( int arg ) {
pid_t ch = wait( NULL );
for( int i=0; i < children.size(); ++i )
if( children[i]==ch ) children[i] = 0;
}
searchdaemon::searchdaemon( confhelper &options ) :
_options( options ),
_log( options.get_string( "LogFile" ), logger::DEBUG ) { }
void searchdaemon::listenloop( listener &l ) {
vector<pthread_t> threads;
pthread_t thread;
pthread_attr_t attr;
assert(pthread_attr_init (&attr) == 0);
engine.initmutex();
// do we need this?? it does'nt seem to help when a connection is aborted
//signal( SIGCHLD, handler_child );
while( true ) {
// pid_t ch;
next_conn = new connection( l.get_connection() );
// create a thread
assert(pthread_create(
&thread,
&attr,
//(void*)thread_handle,
(void*(*)(void*))thread_handle,
(void*)this
) == 0);
// start up the thread, stop it on a return of 0
pthread_join(thread, (void **)0);
// add thread to list
threads.push_back(thread);
// if( (ch=fork())==0 ) {
// _log.lprintf( logger::DEBUG, "Connection\n" );
// handle( c );
// } else children.push_back( ch );
}
}
// dummy function to receive thread handling
//
void* thread_handle(void *arg) {
searchdaemon *s = (searchdaemon *)arg;
// invoke handler for current connection
//
s->handle_current();
// APK - pthread-style exit
pthread_exit(0);
}
// public access to tell the searchdaemon to handle the incoming connection.
// needed for interface with pthreads.
//
void searchdaemon::handle_current( void ) {
// copy next connection into a local variable, since when the next one
// comes in, the value of next_conn will change.
//
connection* c;
c = next_conn;
// call the handler.
//
handle(*c);
delete c; // free mem
}
// main connection handler
//
void searchdaemon::handle( connection c ) {
c.send_message( connection::HELLO, string( "searchd" ) );
vector<string> t;
string cmd( "" );
do {
t = c.get_response();
// lost peer
if( t[0] == "DISCON") break;
if( t.size() < 1 ) {
c.send_message( connection::BADCMD, "Empty command" );
}
else {
cmd = t[0];
/* index a document chunk (corresponds to XML element) */
if (cmd == "index") {
#ifdef LOG_INDEXING
_log.lprintf( logger::DEBUG, "Got index command\n" );
#endif
c.send_message( connection::OK, "indexing; send IDs" );
//read in doc/tag IDs
vector<string> IDs = c.get_index_IDs();
assert(IDs.size()==2);
string docID=IDs[0];
string tagID=IDs[1];
#ifdef LOG_INDEXING
_log.lprintf( logger::DEBUG, "Got index IDs\n" );
#endif
c.send_message( connection::OK, "send words" );
//read in terms
vector<string> words = c.get_words();;
#ifdef LOG_INDEXING
_log.lprintf( logger::DEBUG, "Receiving indexing words\n" );
#endif
//add to inverted index
engine.add_element(words, docID, tagID);
//cout << "printing ii" << endl;
//engine.print();
//cout << "done printing ii" << endl;
}
/* unindex based on a document id */
else if (cmd == "unindex") {
#ifdef LOG_INDEXING
_log.lprintf( logger::DEBUG, "Got unindex command\n" );
#endif
c.send_message( connection::OK, "unindexing; send ID" );
string docID = c.get_unindex_ID();
#ifdef LOG_INDEXING
_log.lprintf( logger::DEBUG, "Unindexing\n" );
#endif
engine.remove_doc(docID);
}
/* execute a search */
else if (cmd == "search") {
_log.lprintf( logger::DEBUG, "Got search command\n" );
c.send_message( connection::OK, "send query" );
vector<query_node> query = c.get_query();
_log.lprintf( logger::DEBUG, "Searching\n" );
vector<query_result> results = engine.search(query);
if( results.size()>0 ) {
_log.lprintf( logger::DEBUG, "Sending some search results\n" );
c.send_message( connection::BEGINSEARCHRESULT, "here are some results");
for( int i=0; i < results.size(); i++ )
c.send_search_result(results[i]);
c.send_message( connection::ENDSEARCHRESULT, "that is all" );
}
else {
c.send_message( connection::NOSEARCHRESULT, "no results" );
}
}
/* execute a limited search */
else if (cmd == "limitsearch") {
_log.lprintf( logger::DEBUG, "Got search command\n" );
c.send_message( connection::OK, "send query" );
vector<query_node> query = c.get_query();
int limit = c.get_limit();
_log.lprintf( logger::DEBUG, "Limited Searching\n" );
// actual number of matches gets returned in nmatches
int nmatches = limit;
vector<query_result> results = engine.search(query, nmatches);
if( results.size() > 0 ) {
_log.lprintf( logger::DEBUG, "Sending search results number of matches\n" );
char buf[101];
ostrstream os(buf, 100);
os << nmatches << endl;
c.send_message( connection::NMATCHES, buf);
_log.lprintf( logger::DEBUG, "Sending some search results\n" );
c.send_message( connection::BEGINSEARCHRESULT, "here are some results");
for( int i=0; i < results.size() && i < results.size(); i++ )
c.send_search_result(results[i]);
c.send_message( connection::ENDSEARCHRESULT, "that is all" );
}
else {
c.send_message( connection::NOSEARCHRESULT, "no results" );
}
}
/* shut down daemon */
else if( cmd == "quit" ) {
_log.lprintf( logger::DEBUG, "Shutting down.\n" );
c.send_message( connection::BYE, "Thanks for playing" );
}
/* get statistics */
else if ( cmd == "stats" ) {
c.send_message( connection::OK, "printing statistics" );
engine.stats();
}
/* squeeze down data structures to conserve memory, do other
* maintenance */
else if ( cmd == "compactify" ) {
c.send_message( connection::OK, "compactifying data structures" );
engine.stats();
}
/*
else if ( cmd=="printindex" ) {
c.send_message( connection::OK, "printing inverted index" );
engine.print();
}
*/
/* say what? */
else c.send_message( connection::BADCMD, string( "Unknown command " ) + cmd );
}
} while( cmd != "quit" );
c.finish();
}
void searchdaemon::go() {
/* let search engine get at logger */
engine.setlogger(&_log);
/* fork off listeners */
_log.lprintf( logger::DEBUG, "Looks good: %d\n", getpid() );
childunix=0;
childinet=0;
/* fork off a unix listener .. */
if( _options.get_bool( "ListenUnix" ) ) {
_log.lprintf( logger::DEBUG, "Forking UNIX domain listener\n" );
if( (childunix=fork())==0 ) {
listener unix_listen( _log, _options.get_string( "UnixSocket" ) );
listenloop( unix_listen );
}
}
/* .. and an inet listeneer */
if( _options.get_bool( "ListenInet" ) ) {
_log.lprintf( logger::DEBUG, "Forking inet domain listener\n" );
if( (childinet=fork())==0 ) {
listener inet_listen( _log, _options.get_string( "BindAddress" ), _options.get_int( "ListenPort" ) );
listenloop( inet_listen );
}
}
signal( SIGTERM, handler_term );
/* now just chill for a bit */
while( childunix != 0 || childinet != 0 ) {
pid_t child = wait( NULL );
if( child==childunix ) childunix = 0;
if( child==childinet ) childinet = 0;
}
exit( 0 );
}
| 24.343558 | 104 | 0.635333 | holtzermann17 |
d2f79d0ccf37336b91b25491691596d601dca514 | 49 | cxx | C++ | libs/cg_nui/surfel_container.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 11 | 2017-09-30T12:21:55.000Z | 2021-04-29T21:31:57.000Z | libs/cg_nui/surfel_container.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 2 | 2017-07-11T11:20:08.000Z | 2018-03-27T12:09:02.000Z | libs/cg_nui/surfel_container.cxx | IXDdev/IXD_engine | 497c1fee90e486c19debc5347b740b56b1fef416 | [
"BSD-3-Clause"
] | 24 | 2018-03-27T11:46:16.000Z | 2021-05-01T20:28:34.000Z | #include "surfel_container.h"
// TODO: implement | 16.333333 | 29 | 0.755102 | IXDdev |
d2f9e5afc7cd122b4ed8de4a0ecd19ae123b127a | 1,416 | cpp | C++ | AlphaEngine/Source/Scripting/LuaVar.cpp | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | AlphaEngine/Source/Scripting/LuaVar.cpp | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | AlphaEngine/Source/Scripting/LuaVar.cpp | Sh1ft0/alpha | 6726d366f0c8d2e1434b87f815b2644ebf170adf | [
"Apache-2.0"
] | null | null | null | /**
Copyright 2014-2015 Jason R. Wendlandt
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 "Scripting/LuaVar.h"
namespace alpha
{
LuaTable::LuaTable(const std::string & name)
: LuaVar(name)
{ }
LuaTable::~LuaTable() { }
LUA_VARTYPE LuaTable::GetVarType() const { return VT_TABLE; }
void LuaTable::Push(std::string key, std::shared_ptr<LuaVar> value)
{
m_vars[key] = value;
}
/**
* Find the LuaVar with the given key, if it exists (shallow search)
*/
std::shared_ptr<LuaVar> LuaTable::Get(const std::string & key) const
{
auto search = m_vars.find(key);
if (search != m_vars.end())
{
return search->second;
}
return nullptr;
}
//! Get all variables that exist in this LUA table
const std::map<std::string, std::shared_ptr<LuaVar> > & LuaTable::GetAll() const
{
return m_vars;
}
}
| 27.230769 | 84 | 0.664548 | Sh1ft0 |
d2fb38a80612a4f2ad85fa926c0fe4112c7295b9 | 716 | hpp | C++ | include/molecular.hpp | grasingerm/port-authority | 51db6b09d6a1545eafeaf6be037a23d47313c490 | [
"MIT"
] | null | null | null | include/molecular.hpp | grasingerm/port-authority | 51db6b09d6a1545eafeaf6be037a23d47313c490 | [
"MIT"
] | null | null | null | include/molecular.hpp | grasingerm/port-authority | 51db6b09d6a1545eafeaf6be037a23d47313c490 | [
"MIT"
] | null | null | null | #ifndef __MOLECULAR_HPP__
#define __MOLECULAR_HPP__
#include "pauth_types.hpp"
#include "unordered_pair.hpp"
#include <unordered_map>
namespace pauth {
enum class molecular_id { Ar, Cu, H, O, C, Test, Test1, Test2 };
using molecular_name_map = std::unordered_map<std::string, molecular_id>;
extern const molecular_name_map molecular_names_to_ids;
struct molecular_pair_hash {
std::size_t operator()(const unordered_pair<molecular_id> &k) const {
return ((std::hash<int>()(static_cast<int>(k.first))) ^
(std::hash<int>()(static_cast<int>(k.second))));
}
};
using molecular_pair_interaction_map =
std::unordered_map<unordered_pair<molecular_id>, double, molecular_pair_hash>;
}
#endif
| 25.571429 | 82 | 0.74162 | grasingerm |
d2fc6694e806eff7cb75ec1ac0068ab50dac916f | 1,193 | cpp | C++ | datasets/github_cpp_10/3/129.cpp | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 1 | 2019-05-03T19:27:45.000Z | 2019-05-03T19:27:45.000Z | datasets/github_cpp_10/3/129.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | datasets/github_cpp_10/3/129.cpp | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | null | null | null | #include <iostream>
#include "tree_functions.cpp"
template <class T>
class avl_tree {
private:
tree_functions::node<T>* root;
public:
avl_tree();
avl_tree(T);
bool empty();
void clear();
void insert(T);
bool search(T);
void remove(T);
void print();
};
template <class T>
avl_tree<T>::avl_tree(){
root=NULL;
}
template <class T>
avl_tree<T>::avl_tree(T z){
root=new tree_functions::node<T>(z);
}
template <class T>
bool avl_tree<T>::empty(){
return root==NULL;
}
template <class T>
void avl_tree<T>::clear(){
root=NULL;
}
template <class T>
void avl_tree<T>::insert(T z) {
root=tree_functions::insert(root,z);
}
template <class T>
bool avl_tree<T>::search(T z) {
return tree_functions::search(root,z);
}
template <class T>
void avl_tree<T>::remove(T z) {
root=tree_functions::remove(root,z);
}
template <class T>
void avl_tree<T>::print() {
tree_functions::print(root);
std::cout<<std::endl;
}
int main() {
avl_tree<int> x;
x.insert(56);
x.insert(79);
x.insert(34);
x.insert(61);
x.insert(59);
x.insert(55);
x.insert(62);
x.insert(34);
x.insert(65);
x.print();
x.remove(34);
x.print();
} | 13.872093 | 40 | 0.626991 | yijunyu |
d2fdbae67a8cd06943148771f10792355ae5ab2c | 1,299 | cpp | C++ | TOI16/Camp-3/old toi test/toi8/toi8_maze.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Camp-3/old toi test/toi8/toi8_maze.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | TOI16/Camp-3/old toi test/toi8/toi8_maze.cpp | mrmuffinnxz/TOI-preparation | 85a7d5b70d7fc661950bbb5de66a6885a835e755 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define pi pair<int, int>
using namespace std;
int n, m, sx, sy, ex, ey;
pi maze[151][151];
main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
cin >> n >> m;
cin >> sx >> sy;
cin >> ex >> ey;
sx--, sy--, ex--, ey--;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
{
cin >> maze[i][j].first;
maze[i][j].second = 0;
}
queue<pair<pi, pi> > q;
q.push({{0, 2}, {sx, sy}});
q.push({{0, 3}, {ex, ey}});
maze[sx][sy].first = 2;
maze[ex][ey].first = 3;
int dir[4][2] = {{1,0}, {-1,0}, {0,1}, {0,-1}};
while(!q.empty())
{
int level = q.front().first.first, zone = q.front().first.second, x = q.front().second.first, y = q.front().second.second;
q.pop();
for(int i=0;i<4;i++)
{
int xx = x+dir[i][0], yy = y+dir[i][1];
if(xx < 0 || xx >= n || yy < 0 || yy >= m) continue;
if(maze[xx][yy].first == 1)
{
maze[xx][yy] = make_pair(zone, level+1);
q.push({{level+1, zone}, {xx, yy}});
}
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cout << maze[i][j].first;
cout << "\n";
}
cout << "\n";
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
cout << maze[i][j].second;
cout << "\n";
}
int bomb = 0, path = 0;
for(int i=0;i<n;i++)
for(int j=0;j<m;j++)
if(maze[i][j].first == 0)
{
}
}
| 17.32 | 124 | 0.474981 | mrmuffinnxz |
d2fe497101c59db89f5e757c5201f8312f339003 | 226 | cpp | C++ | acwing/0717.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | acwing/0717.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | null | null | null | acwing/0717.cpp | zyzisyz/OJ | 55221a55515231182b6bd133edbdb55501a565fc | [
"Apache-2.0"
] | 2 | 2020-01-01T13:49:08.000Z | 2021-03-06T06:54:26.000Z | #include<iostream>
using namespace std;
int f[50];
int main(void){
int n;
cin>>n;
f[0] = 0;
f[1] = 1;
for(int i=2; i<n; i++){
f[i] = f[i-1]+f[i-2];
}
for(int i=0; i<n; i++){
cout<<f[i]<<" ";
}
cout<<endl;
}
| 9.826087 | 24 | 0.473451 | zyzisyz |
960141367d4754b84040d706d9eaf80e5a2ed5c2 | 2,408 | cpp | C++ | mainapp/Classes/Games/SentenceMaker/GreenDashedRect.cpp | JaagaLabs/GLEXP-Team-KitkitSchool | f94ea3e53bd05fdeb2a9edcc574bc054e575ecc0 | [
"Apache-2.0"
] | 45 | 2019-05-16T20:49:31.000Z | 2021-11-05T21:40:54.000Z | mainapp/Classes/Games/SentenceMaker/GreenDashedRect.cpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 10 | 2019-05-17T13:38:22.000Z | 2021-07-31T19:38:27.000Z | mainapp/Classes/Games/SentenceMaker/GreenDashedRect.cpp | rdsmarketing/GLEXP-Team-KitkitSchool | 6ed6b76d17fd7560abc35dcdf7cf4a44ce70745e | [
"Apache-2.0"
] | 29 | 2019-05-16T17:49:26.000Z | 2021-12-30T16:36:24.000Z | //
// GreenDashedRect.cpp
// KitkitSchool-mobile
//
// Created by JungJaehun on 13/02/2018.
//
#include "GreenDashedRect.hpp"
#include "WordItem.hpp"
GreenDashedRect* GreenDashedRect::create() {
GreenDashedRect *popup = new (std::nothrow) GreenDashedRect();
if (popup && popup->init())
{
popup->autorelease();
return popup;
}
CC_SAFE_DELETE(popup);
return nullptr;
}
float GreenDashedRect::getBodyWidth(float width) {
return width-34*2;
}
bool GreenDashedRect::init() {
if (!Node::init()) {
return false;
}
_defaultWidth = 160;
_stretched = false;
_pair = nullptr;
_word = "";
auto bodyWidth = getBodyWidth(_defaultWidth);
_currentBodyWidth = bodyWidth;
setContentSize(Size(_defaultWidth, 128));
setAnchorPoint(Vec2::ANCHOR_MIDDLE);
_left = Sprite::create("SentenceMaker/Sentencemaker_image_block-guideline-left.png");
_left->setAnchorPoint(Vec2::ANCHOR_MIDDLE_RIGHT);
_left->setPosition(Vec2(bodyWidth/2*-1+getContentSize().width/2, getContentSize().height/2));
addChild(_left);
_right = Sprite::create("SentenceMaker/Sentencemaker_image_block-guideline-right.png");
_right->setAnchorPoint(Vec2::ANCHOR_MIDDLE_LEFT);
_right->setPosition(Vec2(bodyWidth/2+getContentSize().width/2,getContentSize().height/2));
addChild(_right);
Texture2D::TexParams params = { GL_LINEAR, GL_LINEAR, GL_REPEAT, GL_REPEAT };
_horiTex = Director::getInstance()->getTextureCache()->addImage("SentenceMaker/Sentencemaker_image_block-guideline-center.png");
_horiTex->setTexParameters(params);
_body = Sprite::createWithTexture(_horiTex, Rect(0, 0, bodyWidth, 128));
_body->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
_body->setPosition(getContentSize()/2);
addChild(_body);
return true;
}
void GreenDashedRect::initUI() {
}
void GreenDashedRect::setBodyWidth(float width) {
this->setContentSize(Size(width, this->getContentSize().height));
auto bodyWidth = getBodyWidth(width);
_left->setPosition(Vec2(bodyWidth/2*-1+getContentSize().width/2, getContentSize().height/2));
_right->setPosition(Vec2(bodyWidth/2+getContentSize().width/2,getContentSize().height/2));
_body->setTextureRect(Rect(0, 0, bodyWidth, 128));
_body->setPosition(getContentSize()/2);
_stretched = (width == _defaultWidth) ? false : true;
}
| 32.106667 | 132 | 0.697259 | JaagaLabs |