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
float64
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
float64
1
77k
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
float64
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
653k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
1
1a05fd4f32bf7ac9e3f364b003d152b41f41516b
2,184
cpp
C++
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std ; int main() { stack <char> data; char input[500005]; int n ; scanf("%d", &n); map <int , int> marking ; int balanced= 0 ; long long int ans = 0 ; for(int i = 0 ; i < n ; i++) { scanf("%s", input); int k = 0 ; int score = 0 ; stack <char> store ; //cout <<"HE" << endl ; while(input[k] != '\0') { //cout << input[k] << endl ; if(input[k] == '(') { store.push(input[k]); //cout << "1" << endl ; } else { if(!store.empty() && store.top() == '(') { store.pop(); //cout << "2" << endl; } else { store.push(input[k]); //cout << "3" << endl ; } } //cout << k << endl ; k++; } if(store.size() == 0) { balanced++; } else { bool possible = true; char init = store.top() ; store.pop(); if(init == '(') { score++; } else score--; //cout << "HERE" << endl ; while(!store.empty()) { if(store.top() != init) { possible = false ; break; } else if(store.top() == '(') { score++; } else score--; store.pop(); } if(!possible) continue; else if(marking[score * -1] > 0) { marking[score * -1] = marking[score * -1] - 1 ; ans++ ; } else { marking[score] = marking[score] + 1 ; } } } ans += balanced/2; printf("%lld\n", ans); return 0 ; }
24
64
0.287088
1a0823730e616552e21f820c37d0889c43151bc6
1,769
cpp
C++
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define lson(x) ((x)<<1) #define rson(x) (((x)<<1)+1) const int maxn = 100005; typedef long long ll; struct Node { int l, r; ll sum, add; void set (int l, int r, ll sum, ll add) { this->l = l; this->r = r; this->sum = sum; this->add = add; } void maintain (ll v) { sum += (r - l + 1) * v; add += v; } }nd[maxn * 4]; int N, Q, A[maxn]; void pushup (int u) { nd[u].sum = nd[lson(u)].sum + nd[rson(u)].sum; } void pushdown(int u) { if (nd[u].add) { nd[lson(u)].maintain(nd[u].add); nd[rson(u)].maintain(nd[u].add); nd[u].add = 0; } } void build (int u, int l, int r) { nd[u].l = l; nd[u].r = r; nd[u].add = 0; if (l == r) { nd[u].sum = A[l]; return; } int mid = (l + r) / 2; build(lson(u), l, mid); build(rson(u), mid + 1, r); pushup(u); } ll query(int u, int l, int r) { if (l <= nd[u].l && nd[u].r <= r) return nd[u].sum; pushdown(u); ll ret = 0; int mid = (nd[u].l + nd[u].r) / 2; if (l <= mid) ret += query(lson(u), l, r); if (r > mid) ret += query(rson(u), l, r); pushup(u); return ret; } void modify (int u, int l, int r, int v) { if (l <= nd[u].l && nd[u].r <= r) { nd[u].maintain(v); return; } pushdown(u); int mid = (nd[u].l + nd[u].r) / 2; if (l <= mid) modify(lson(u), l, r, v); if (r > mid) modify(rson(u), l, r, v); pushup(u); } int main () { while (scanf("%d%d", &N, &Q) == 2) { for (int i = 1; i <= N; i++) scanf("%d", &A[i]); build(1, 1, N); int l, r, v; char order[5]; for (int i = 0; i < Q; i++) { scanf("%s%d%d", order, &l, &r); if (order[0] == 'Q') printf("%lld\n", query(1, l, r)); else { scanf("%d", &v); modify(1, l, r, v); } } } return 0; }
16.229358
47
0.487846
1a0ed3e7186d638471d1b6fd0a646abe72bf17ce
871
cpp
C++
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Print all the ancestors of a given node #include<iostream> using namespace std; struct Node { int data; Node *left; Node *right; }; //creates a node Node* create(int data) { try { Node *node=new Node; node->data=data; node->left=NULL; node->right=NULL; return node; } catch(bad_alloc xa) { cout<<"Memory overflow!!"; return NULL; } } //prints all the ancestors of a gievn key node bool printAncestors(Node *root,int key) { if(root==NULL) return false; if(root->data==key) return true; if(printAncestors(root->left,key)||printAncestors(root->right,key)) { cout<<root->data<<" "; return true; } else false; } int main() { Node *root=create(1); root->left=create(2); root->right=create(3); root->left->left=create(4); root->right->right=create(6); root->left->right=create(5); if(printAncestors(root,4)); return 0; }
14.278689
68
0.657865
1a0ff312380fc1200503bb7f17cbbec9408ee287
404
hpp
C++
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.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_RUCKSACK_TESTBED_OBJECT_IMPL_FWD_HPP_INCLUDED #define SGE_RUCKSACK_TESTBED_OBJECT_IMPL_FWD_HPP_INCLUDED namespace sge::rucksack::testbed { class object_impl; } #endif
23.764706
61
0.759901
1a10a79e16490f9837cc80b4d97b6cc4c35fa011
835
cpp
C++
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
// // Created by manuelrenz on 12.04.18. // #include "WinKeyReducerEval.h" /* ----------------------------------------- * specialized for yahoo -- using normal hashtable * NB: we have to do full specialization per C++ * ----------------------------------------- */ // using MyWinKeyReduerEval = WinKeyReducerEval<std::pair<uint64_t, long>, /* kv in */ // WinKeyFragLocal_Std, WinKeyFrag_Std, /* internal map format */ // std::pair<uint64_t, long>, /* kvout */ // WindowsBundle /* output bundle */ // >; using MyWinKeyReduerEval = WinKeyReducerEval<std::pair<uint64_t, uint64_t>, /* kv in */ WinKeyFragLocal_Std, WinKeyFrag_Std, /* internal map format */ std::pair<uint64_t, uint64_t>, /* kvout */ WindowsBundle /* output bundle */ >; #include "WinKeyReducerEval-yahoo-common.h"
32.115385
87
0.590419
1a12a65e5e6b8c99169fb89dd6614e4378e58de6
3,113
hpp
C++
ThreadPool.hpp
ConfuseL/SampleHttpProxy
ab17f925068f3fee3f93c909ab643fe375273ac1
[ "MIT" ]
null
null
null
ThreadPool.hpp
ConfuseL/SampleHttpProxy
ab17f925068f3fee3f93c909ab643fe375273ac1
[ "MIT" ]
null
null
null
ThreadPool.hpp
ConfuseL/SampleHttpProxy
ab17f925068f3fee3f93c909ab643fe375273ac1
[ "MIT" ]
1
2020-04-10T05:47:32.000Z
2020-04-10T05:47:32.000Z
#ifndef THREADPOOL_HPP_INCLUDED #define THREADPOOL_HPP_INCLUDED #include"Condition.hpp" #include<queue> #include<iostream> //参考他人博客,仅再度抽象封装 //原地址 https://www.cnblogs.com/yangang92/p/5485868.html typedef struct task { void *(*job)(void *args); void *arg; }Task; void * ThreadManager(void *arg); class ThreadPool { public: Condition status; std::queue<Task* > taskQueue; int total; int idleNum; int maxNum; bool quit; ThreadPool(int threads):total(0),idleNum(0),maxNum(threads),quit(false) { status.Init(); } ~ThreadPool() { if(!quit) { status.Lock(); quit=true; if(total>0) { status.WakeUpAll(); } while(total) { status.Wait(); } } status.UnLock(); status.Destroy(); } void Add( void *(*job)(void *args),void *arg) { Task *newTask= (Task *)malloc(sizeof(Task)); newTask->job=job; newTask->arg=arg; status.Lock(); taskQueue.push(newTask); if(idleNum>0) { status.WakeUp(); } else if(total<maxNum) { pthread_t newId; pthread_create(&newId,NULL,ThreadManager,this); total++; } status.UnLock(); } }; void * ThreadManager(void *arg) { struct timespec _time; bool timeout; // std::cout<<(int)pthread_self()<<"线程开始"<<std::endl; ThreadPool *pool=(ThreadPool *)arg; while(1) { timeout=false; pool->status.Lock(); pool->idleNum++; while(pool->taskQueue.empty()&&!pool->quit) { // std::cout<<(int)pthread_self()<<"线程正在等待任务分配"<<std::endl; clock_gettime(CLOCK_REALTIME,&_time); _time.tv_sec+=2; int status=pool->status.WaitSomeTime(&_time); if(status==ETIMEDOUT) { //std:: cout<<(int)pthread_self()<<"线程等待超时"<<std::endl; timeout=true; break; } } pool->idleNum--; if(!pool->taskQueue.empty()) { Task *t=pool->taskQueue.front(); pool->taskQueue.pop(); pool->status.UnLock(); t->job(t->arg); free(t); pool->status.Lock(); } if(pool->taskQueue.empty()&&pool->quit) { if((--(pool->total))==0) { pool->status.WakeUp(); } pool->status.UnLock(); break; } if(timeout) { pool->total--; pool->status.UnLock(); break; } pool->status.UnLock(); } // std::cout<<(int)pthread_self()<<"线程结束工作"<<std::endl; return NULL; } #endif // THREADPOOL_HPP_INCLUDED
25.941667
75
0.451333
1a143a76a1c87083c7987e104a76b6db72592a9f
554
cpp
C++
Codechef - Contests/JULY16/POLYEVAL.cpp
Gurupradeep/Codes
5595f2e0f867a2a21d050379ead18bd6ef563978
[ "MIT" ]
null
null
null
Codechef - Contests/JULY16/POLYEVAL.cpp
Gurupradeep/Codes
5595f2e0f867a2a21d050379ead18bd6ef563978
[ "MIT" ]
null
null
null
Codechef - Contests/JULY16/POLYEVAL.cpp
Gurupradeep/Codes
5595f2e0f867a2a21d050379ead18bd6ef563978
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define MOD 786433 int main() { long long n; long long a[10002]; scanf("%lld",&n); for(int i=0;i<=n;i++) scanf("%lld",&a[i]); long long q; scanf("%lld",&q); while(q--) { long long x; scanf("%lld",&x); long long ans = a[0]; long long temp = 1; for(int i=1;i<=n;i++) { temp = (temp*x)%MOD; ans = (ans + (temp*a[i])%MOD)%MOD; } printf("%lld\n",ans); } }
20.518519
47
0.415162
1a150466293290bde2678ab09e37514c5e673198
594
cpp
C++
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
1
2017-12-24T07:51:07.000Z
2017-12-24T07:51:07.000Z
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
null
null
null
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
null
null
null
#include <unordered_map> #include <iostream> #include <string> int lengthOfLongestSubstring(std::string s){ std::unordered_map<char, int> smap; int n = s.length(); int max_length = 0; if(n<2){ return n; } for(int i=0,j=0;j<n;++j){ char c = s.at(j); if(smap.count(c)){ i=smap[c]>i?smap[c]:i; } smap[c]=j+1; max_length = max_length<(j-i+1)?(j-i+1):max_length; } return max_length; }; int main(int argc, char **argv){ std::string test_s = "pwwerkw"; std::cout<< test_s<<"\n"; std::cout<<lengthOfLongestSubstring(test_s)<<"\n"; return 0; };
20.482759
54
0.60101
1a188685b8533ef9c29a86aa81c89e2f18be079a
794
cpp
C++
tests/test/main.cpp
n-krueger/faabric
c95c3baf9406613629e5f382efc0fc8366b22752
[ "Apache-2.0" ]
null
null
null
tests/test/main.cpp
n-krueger/faabric
c95c3baf9406613629e5f382efc0fc8366b22752
[ "Apache-2.0" ]
null
null
null
tests/test/main.cpp
n-krueger/faabric
c95c3baf9406613629e5f382efc0fc8366b22752
[ "Apache-2.0" ]
null
null
null
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "faabric_utils.h" #include <faabric/util/logging.h> #include <faabric/util/testing.h> struct LogListener : Catch::TestEventListenerBase { using TestEventListenerBase::TestEventListenerBase; void testCaseStarting(Catch::TestCaseInfo const& testInfo) override { auto logger = faabric::util::getLogger(); logger->debug("---------------------------------------------"); logger->debug("TEST: {}", testInfo.name); logger->debug("---------------------------------------------"); } }; CATCH_REGISTER_LISTENER(LogListener) int main(int argc, char* argv[]) { faabric::util::setTestMode(true); int result = Catch::Session().run(argc, argv); fflush(stdout); return result; }
23.352941
71
0.602015
1a19c14e380f519b3eedb83c76f7ee7dcd473c07
57
hpp
C++
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/view/filter_view/filter_view.hpp>
28.5
56
0.824561
1a1b0f533febd3eea6b49484a2587e41d528f5e9
1,938
cpp
C++
uva/nonstop.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
uva/nonstop.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
uva/nonstop.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int ni, ncase = 1; while(cin >> ni && ni) { map<int, vector<pair<int, int> > > graph; // from -> [to, cost] for(int i = 1; i <= ni; i++) { int roads; cin >> roads; while (roads > 0) { int outroad, cost; cin >> outroad >> cost; graph[i].push_back({outroad, cost}); roads--; } } int s, t; cin >> s >> t; priority_queue< pair<int, int>, vector< pair<int, int> >, greater< pair<int, int> > > que; vector<bool> vis; vector<int> dist; vector<int> pred; dist.resize(ni + 1, INT_MAX); pred.resize(ni + 1, INT_MAX); vis.resize(ni + 1, false); que.push({0, s}); dist[s] = 0; pred[s] = -1; while(!que.empty()) { int atual = que.top().second; que.pop(); if(vis[atual]) continue; for(int i = 0; i < graph[atual].size(); i++) { int vizinho = graph[atual].at(i).first; int cost = graph[atual].at(i).second; if(dist[vizinho] > dist[atual] + cost) { dist[vizinho] = dist[atual] + cost; pred[vizinho] = atual; que.push({dist[vizinho], vizinho}); } } vis[atual] = true; } vector<int> path; int atual = t; do { path.insert(path.begin(), atual); atual = pred[atual]; } while(atual > -1); cout << "Case " << ncase << ": Path ="; for(int i = 0; i < path.size(); i++) cout << " " << path[i]; cout << "; " << dist[t] << " second delay" << endl; ncase++; } return 0; }
26.547945
99
0.400413
1a1bf305dff57f8ef966632556b29af27fdd2b66
1,162
cpp
C++
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
#include "gesture-sensor.h" #include "Gesture_PAJ7620/paj7620.h" /** Initialiazes gesture sensor **/ unsigned int gestureInit() { paj7620Init(); } /** Reads gesture sensor and returns value of gesture (or 0 if no gesture detected) For more info see: http://wiki.seeedstudio.com/Grove-Gesture_v1.0/ @returns data = 0 if no gesture detected, otherwise the value of one of the constants below Up Gesture, data = GES_UP_FLAG Down Gesture, data = GES_DOWN_FLAG Left Gesture, data = GES_LEFT_FLAG Right Gesture, data = GES_RIGHT_FLAG Forward Gesture, data = GES_FORWARD_FLAG Backward Gesture, data = GES_BACKWARD_FLAG Clockwise Gesture, data = GES_CLOCKWISE_FLAG Count Clockwise Gesture, data = GES_COUNT_CLOCKWISE_FLAG Wave Gesture, data = GES_WAVE_FLAG */ unsigned int gestureRead() { unsigned char gestureData = 0; // Read Bank_0_Reg_0x43/0x44 for gesture result. paj7620ReadReg(0x43, 1, &gestureData); // When different gestures be detected, the variable 'data' will be set to different values by paj7620ReadReg(0x43, 1, &data). if (gestureData == 0) //check for wave paj7620ReadReg(0x44, 1, &gestureData); return gestureData; }
29.05
170
0.754733
1a1e6d1996dd998faef62fad2eac4b71a73a209c
3,009
cc
C++
src/sys/fuzzing/framework/engine/adapter-client-unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-12-29T10:11:08.000Z
2022-01-04T15:37:09.000Z
src/sys/fuzzing/framework/engine/adapter-client-unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/sys/fuzzing/framework/engine/adapter-client-unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia 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 "src/sys/fuzzing/framework/engine/adapter-client.h" #include <fuchsia/fuzzer/cpp/fidl.h> #include <string> #include <vector> #include <gtest/gtest.h> #include "src/lib/files/directory.h" #include "src/lib/files/file.h" #include "src/lib/files/path.h" #include "src/sys/fuzzing/common/input.h" #include "src/sys/fuzzing/common/options.h" #include "src/sys/fuzzing/common/signal-coordinator.h" #include "src/sys/fuzzing/framework/engine/corpus.h" #include "src/sys/fuzzing/framework/testing/adapter.h" using fuchsia::fuzzer::TargetAdapterSyncPtr; namespace fuzzing { // Test fixtures class TargetAdapterClientTest : public ::testing::Test { protected: std::shared_ptr<Options> DefaultOptions() { auto options = std::make_shared<Options>(); TargetAdapterClient::AddDefaults(options.get()); return options; } void Configure(const std::shared_ptr<Options>& options) { adapter_ = std::make_unique<FakeTargetAdapter>(); client_ = std::make_unique<TargetAdapterClient>(adapter_->GetHandler()); client_->Configure(options); } std::unique_ptr<FakeTargetAdapter> TakeAdapter() { return std::move(adapter_); } std::unique_ptr<TargetAdapterClient> TakeClient() { return std::move(client_); } private: std::unique_ptr<FakeTargetAdapter> adapter_; std::unique_ptr<TargetAdapterClient> client_; }; // Unit tests TEST_F(TargetAdapterClientTest, AddDefaults) { Options options; TargetAdapterClient::AddDefaults(&options); EXPECT_EQ(options.max_input_size(), kDefaultMaxInputSize); } TEST_F(TargetAdapterClientTest, StartAndFinish) { Configure(DefaultOptions()); auto adapter = TakeAdapter(); auto client = TakeClient(); Input sent("foo"); client->Start(&sent); EXPECT_EQ(adapter->AwaitSignal(), kStart); EXPECT_EQ(adapter->test_input(), sent); adapter->SignalPeer(kFinish); client->AwaitFinish(); } TEST_F(TargetAdapterClientTest, StartAndError) { Configure(DefaultOptions()); auto adapter = TakeAdapter(); auto client = TakeClient(); Input sent1("foo"); client->Start(&sent1); EXPECT_EQ(adapter->AwaitSignal(), kStart); EXPECT_EQ(adapter->test_input(), sent1); client->SetError(); client->AwaitFinish(); // |Start| after |SetError| is a no-op... Input sent2("bar"); client->Start(&sent2); client->AwaitFinish(); // ...until |ClearError|. client->ClearError(); client->Start(&sent2); EXPECT_EQ(adapter->AwaitSignal(), kStart); EXPECT_EQ(adapter->test_input(), sent2); adapter->SignalPeer(kFinish); client->AwaitFinish(); } TEST_F(TargetAdapterClientTest, StartAndClose) { Configure(DefaultOptions()); auto adapter = TakeAdapter(); auto client = TakeClient(); Input sent("foo"); client->Start(&sent); EXPECT_EQ(adapter->AwaitSignal(), kStart); client->Close(); client->AwaitFinish(); } } // namespace fuzzing
27.108108
82
0.724826
1a21833b125a42eaea4adc2df9fbb966b754a605
2,744
cpp
C++
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
#include <cstring> #include <ctime> #include <fstream> #include <iostream> using namespace std; void usage() { cout << "para is error." << endl; cout << "example: a.out in out pwd" << endl; } std::chrono::steady_clock::time_point now() { return std::chrono::steady_clock::now(); } long long subSecond(std::chrono::steady_clock::time_point before) { return std::chrono::duration_cast<std::chrono::seconds>(now() - before).count(); } int main(int argc, char **argv) { if (argc != 4) { usage(); return -1; } string file = argv[1]; long long totalSize = 0; ifstream in(file, ios::in | ios::in | ios::binary); if (in.is_open() == false) { cout << file << " is can not open.[read]" << endl; return -1; } else { in.seekg(0, ios_base::end); totalSize = in.tellg(); in.seekg(0, ios_base::beg); } string outFile = argv[2]; ofstream out(outFile, ios::out | ios::binary | ios::ate); if (out.is_open() == false) { cout << outFile << " is can not open.[write]" << endl; return -1; } long long pw; if (strlen(argv[3]) > 0) { pw = std::atoll(argv[3]); } else { usage(); return -1; } bool encode = true; unsigned long long curSize = 0; const int size = 4096; char buffer[size]; string head = "lahFv9y&RCluQl%r8bNzh#FiCml7!%tq"; auto count = in.read(buffer, head.size()).gcount(); if (count == head.size() && memcmp(buffer, head.c_str(), head.size()) != 0) { for (size_t i = 0; i < count; i++) { if (((curSize + i) % pw) != 0) { buffer[i] = ~buffer[i]; } } curSize += count; out.write(head.c_str(), head.size()); out.write(buffer, count); cout << "file is will encode" << endl; } else { cout << "file is will decode" << endl; encode = false; } auto curTime = now(); while (true) { if (in.good() == false) { break; } auto count = in.read(buffer, size).gcount(); for (size_t i = 0; i < count; i++) { if (((curSize + i) % pw) != 0) { buffer[i] = ~buffer[i]; } } curSize += count; if (count > 0) { out.write(buffer, count); } if (subSecond(curTime) >= 10) { curTime = now(); cout << "process is " << (double)curSize / totalSize << endl; } } if (in.eof() && out.good()) { cout << "process ok" << endl; return -1; } else { cout << "process fail" << endl; return -1; } in.close(); out.close(); return 0; }
25.64486
84
0.492347
1a21cb2d3ab3b4f974a0062f92d74b4be234f1e9
1,560
cpp
C++
example_contests/fk_2014_beta/problems/rod/submissions/accepted/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
6
2016-03-28T13:57:54.000Z
2017-07-25T06:04:05.000Z
example_contests/fk_2014_delta/problems/rod/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
25
2015-01-23T18:02:35.000Z
2015-03-17T01:40:27.000Z
example_contests/fk_2014_delta/problems/rod/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
3
2016-06-28T00:48:38.000Z
2017-05-25T05:29:25.000Z
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iomanip> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; #define all(o) (o).begin(), (o).end() #define allr(o) (o).rbegin(), (o).rend() const int INF = 2147483647; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef vector<vii> vvii; template <class T> int size(T &x) { return x.size(); } // assert or gtfo int main() { int n, m; scanf("%d %d\n", &n, &m); int **step = new int*[m]; for (int i = 0; i < m; i++) { step[i] = new int[n]; memset(step[i], 0, n << 2); } for (int i = 0; i < m; i++) { string line; getline(cin, line); for (int j = 0; j < n; j++) { if (2*j-1 >= 0 && line[2*j-1] == '-') assert(step[i][j] == 0), step[i][j] = -1; if (2*j+1 < size(line) && line[2*j+1] == '-') assert(step[i][j] == 0), step[i][j] = 1; } } char *res = new char[n]; for (int i = 0; i < n; i++) { int at = i; for (int r = 0; r < m; r++) { at += step[r][at]; } res[at] = 'A' + i; } for (int i = 0; i < n; i++) printf("%c", res[i]); printf("\n"); return 0; }
19.5
98
0.502564
1a23311b821d1bb428105d6656d6357ef83fc1b0
732
cpp
C++
TAO/tao/Strategies/OC_Endpoint_Selector_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Strategies/OC_Endpoint_Selector_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Strategies/OC_Endpoint_Selector_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// ================================================================= /** * @file OC_Endpoint_Selector_Loader.cpp * * $Id: OC_Endpoint_Selector_Loader.cpp 91628 2010-09-07 11:11:12Z johnnyw $ * * @author Phil Mesnier <mesnier_p@ociweb.com> * */ // ================================================================= // $Id: OC_Endpoint_Selector_Loader.cpp 91628 2010-09-07 11:11:12Z johnnyw $ #include "tao/Strategies/OC_Endpoint_Selector_Loader.h" #include "tao/Strategies/OC_Endpoint_Selector_Factory.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL int TAO_OC_Endpoint_Selector_Loader::init (void) { return ACE_Service_Config::process_directive (ace_svc_desc_TAO_OC_Endpoint_Selector_Factory); } TAO_END_VERSIONED_NAMESPACE_DECL
29.28
96
0.653005
1a2d220b03104c81c8e904a466f499037ba4da15
398
cpp
C++
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_9/Lesson 9.6 Default Constructor That Accepts Parameters with Default Values to Set Members Using Initialization Lists.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_9/Lesson 9.6 Default Constructor That Accepts Parameters with Default Values to Set Members Using Initialization Lists.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_9/Lesson 9.6 Default Constructor That Accepts Parameters with Default Values to Set Members Using Initialization Lists.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Human { private: string Name; int Age; public: Human(string InputName = "Adam", int InputAge = 22) :Name(InputName), Age(InputAge) { cout << "Constructed a Human called " << Name; cout << ", " << Age << " years old" << endl; } }; int main() { Human FirstMan; Human FirstWoman("Alice", 21); return 0; }
14.214286
53
0.613065
1a2ef9f4e0f1a167b3ccd77dfee875e7e2e5f181
375
cpp
C++
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
39
2015-01-22T08:13:28.000Z
2021-02-03T07:29:56.000Z
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
20
2015-04-27T02:35:31.000Z
2021-01-20T16:47:23.000Z
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
30
2015-01-29T21:23:57.000Z
2021-01-11T14:19:47.000Z
//--------------------------------------------------------------------- // <copyright file="e2e_test_case.cpp" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- #include "e2e_test_case.h"
53.571429
126
0.458667
1a2f2aff78994a592508932704d8b48c8e74ec75
2,505
cpp
C++
books/C++_advanced_programming/code/Chapter23/Logger.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
C++11/C++11_1/Logger.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
C++11/C++11_1/Logger.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include <iostream> #include "Logger.h" #include <fstream> using std::thread; using std::cout; using std::endl; using std::cerr; using std::unique_lock; using std::mutex; using std::ofstream; //Logger::Logger() //{ // // Start background thread // mThread = thread{ &Logger::processEntries, this }; //} //void Logger::log(const std::string& entry) //{ // // Lock mutex and entry to the queue // unique_lock<mutex> lock(mMutex); // mQueue.push(entry); // // Notify condition variable to wake up thread // mCondVar.notify_all(); //} //void Logger::processEntries() //{ // // Open log file. // ofstream ofs("log.txt"); // if (ofs.fail()) // { // cerr << "Failed to open logfile." << endl; // return; // } // // // Start processing loop. // unique_lock<mutex> lock(mMutex); // while (true) // { // // Wait for a notification // mCondVar.wait(lock); // // Condition variable is notified, so something might be in the queue. // lock.unlock(); // while (true) // { // lock.lock(); // if (mQueue.empty()) // break; // else // { // ofs << mQueue.front() << endl; // mQueue.pop(); // } // lock.unlock(); // } // } //} Logger::Logger() : mExit(false) { // Start background thread mThread = thread{ &Logger::processEntries, this }; } Logger::~Logger() { { unique_lock<mutex> lock(mMutex); // Gracefully shut down the thread by setting mExit. // to true and notifying the thread. mExit = true; // Notify condition variable to wake up thread mCondVar.notify_all(); } // Wait unitl thread is shut down. This should be outside the above code // block because the lock on mMutex must be released before calling join() mThread.join(); } void Logger::log(const std::string& entry) { // Lock mutex and entry to the queue unique_lock<mutex> lock(mMutex); mQueue.push(entry); // Notify condition variable to wake up thread mCondVar.notify_all(); } void Logger::processEntries() { // Open log file. ofstream ofs("log.txt"); if (ofs.fail()) { cerr << "Failed to open logfile." << endl; return; } // Start processing loop. unique_lock<mutex> lock(mMutex); while (true) { if (!mExit) mCondVar.wait(lock); // Wait for a notification // mCondVar.wait(lock); // Condition variable is notified, so something might be in the queue. lock.unlock(); while (true) { lock.lock(); if (mQueue.empty()) break; else { ofs << mQueue.front() << endl; mQueue.pop(); } lock.unlock(); } if (mExit) break; } }
18.284672
75
0.631138
1a31cdf344682d4a296557effad4459f6f2376ff
17,601
cpp
C++
src/UnitTest.cpp
ibest/seqyclean
45d6d52ffc62078c91588ef3c10f28ff8e1dca13
[ "MIT" ]
22
2015-08-25T16:39:55.000Z
2022-03-10T12:37:45.000Z
src/UnitTest.cpp
ibest/seqyclean
45d6d52ffc62078c91588ef3c10f28ff8e1dca13
[ "MIT" ]
4
2015-06-22T18:56:01.000Z
2020-05-19T06:57:13.000Z
src/UnitTest.cpp
ibest/seqyclean
45d6d52ffc62078c91588ef3c10f28ff8e1dca13
[ "MIT" ]
4
2015-11-02T18:43:01.000Z
2017-12-13T15:29:11.000Z
/* * File: UnitTest.cpp * Author: kwt * * Created on July 28, 2013, 11:18 AM */ #include "UnitTest.h" UnitTest::UnitTest() { //Test Illumina PE //Test Illumina SE //Test overlap Illumins } UnitTest::UnitTest(const UnitTest& orig) { } UnitTest::~UnitTest() { } void UnitTest::Test454() { //Test 454 roche_names.push_back("test_data/in.sff"); trim_adapters_flag = true; qual_trim_flag = true; output_prefix = "UnitTest454"; sum_stat_tsv << "Version\tFiles\tNUM_THREADS\tAdaptersTrimming\tVectorTrimming\tkmer_size\tDistance\tContamScr\tkmer_contam_size\tQualTrim\tQual_max_avg_error\tQual_max_err_at_ends\tOutputPrefix\tRepFilename\tOutputFilename\tMax_align_mismatches\tMinReadLen\tReadsAnalyzed\tBases\tleft_mid_tags_found\tpercentage_left_mid_tags_found\tright_mid_tags_found\tpercentage_right_mid_tags_found\tReadsWithVector_found\tpercentage_ReadsWithVector_found\tReadsWithContam_found\tpercentage_ReadsWithContam_found\tLeftTrimmedByAdapter\tLeftTrimmedByQual\tLeftTrimmedByVector\tAvgLeftTrimLen\tRightTrimmedByAdapter\tRightTrimmedByQual\tRightTrimmedByVector\tAvgRightTrimLen\tDiscardedTotal\tDiscByContam\tDiscByLength\tReadsKept\tPercentageKept\tAvgTrimmedLen\n"; cout << "Unit test 454..." << endl; cout << "--------------------Basic parameters--------------------\n"; sum_stat << "--------------------Basic parameters--------------------\n"; cout << "Provided data file(s) : \n" ; sum_stat << "Provided data file(s) : \n" ; for(int i=0; i<(int)roche_names.size(); ++i) { cout << roche_names[i] << "\n"; sum_stat << roche_names[i] << "\n"; } cout << string("Adapters trimming: ") + ( trim_adapters_flag ? "YES. Custom RLMIDS: " + ( custom_rlmids_flag ? "YES, file_of_RL_MIDS: " + string(rlmids_file) : "NO. Default RL MIDs will be used." ) : " ") << endl; sum_stat << string("Adapters trimming: ") + ( trim_adapters_flag ? "YES. Custom RLMIDS: " + ( custom_rlmids_flag ? "YES, file_of_RL_MIDS: " + string(rlmids_file) : "NO. Default RL MIDs will be used." ) : " " ) << endl; if(vector_flag) { cout << "Vector screening: YES. Vector_file provided: " << vector_file << endl; sum_stat << "Vector screening: YES. Vector_file provided: " << vector_file << endl; cout << "K-mer_size for for vector trimming: " << KMER_SIZE << " bp\n"; sum_stat << "K-mer_size for vector trimming: " << KMER_SIZE << " bp\n"; cout << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; sum_stat << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; } else { cout << "Vector screening: NO" << endl; sum_stat << "Vector screening: NO" << endl; } if(contaminants_flag) { cout << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; sum_stat << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; cout << "K-mer size for contaminants: " << KMER_SIZE_CONT << " bp\n"; sum_stat << "K-mer size for contaminants: " << KMER_SIZE_CONT << " bp\n"; } else { cout << "Contaminants screening: NO" << endl; sum_stat << "Contaminants screening: NO" << endl; } if(qual_trim_flag) { cout << "Quality trimming: YES" << endl; sum_stat << "Quality trimming: YES" << endl; cout << "Maximim error: " << -10*log10(max_a_error) << endl; sum_stat << "Maximim error: " << -10*log10(max_a_error) << endl; cout << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; sum_stat << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; } else { cout << "Quality trimming: NO" << endl; sum_stat << "Quality trimming: NO" << endl; } cout << "--------------------Output files--------------------\n"; sum_stat << "--------------------Output files--------------------\n"; cout << "Output prefix: " << output_prefix << endl; sum_stat << "Output prefix: " << output_prefix << endl; roche_output_file_name = output_prefix + ".sff";// + (output_fastqfile_flag ? ", " + output_prefix + ".fastq" : "" ); roche_rep_file_name = output_prefix + "_Report.tsv" ; cout << "Report file: " << roche_rep_file_name << "\n"; sum_stat << "Report file: " << roche_rep_file_name << "\n"; cout << "Roche output file(s): " << ( roche_output_file_name + (output_fastqfile_flag ? ", " + output_prefix + ".fastq" : "" ) ) << "\n"; sum_stat << "Roche output file(s): " << ( roche_output_file_name + (output_fastqfile_flag ? ", " + output_prefix + ".fastq" : "" ) ) << "\n"; cout << "--------------------Other parameters--------------------\n"; sum_stat << "--------------------Other parameters--------------------\n"; cout << "k-mer_size: " << KMER_SIZE << " bp\n"; sum_stat << "k-mer_size: " << KMER_SIZE << " bp\n"; cout << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; sum_stat << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; cout << "Minimum read length to accept: " << minimum_read_length << " bp\n"; sum_stat << "Minimum read length to accept: " << minimum_read_length << " bp\n"; cout << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; sum_stat << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; cout << "number_of_threads: " << NUM_THREADS << endl; sum_stat << "number_of_threads: " << NUM_THREADS << endl; if(vector_flag ) { BuildVectorDictionary(vector_file); } if(contaminants_flag ) { /*Building dictionary for contaminants :*/ BuildContDictionary(cont_file); } RocheRoutine(); } void UnitTest::TestIlluminaPE() { cout << "--------------------Basic parameters--------------------\n"; sum_stat << "--------------------Basic parameters--------------------\n"; //Sum stat TSV header sum_stat_tsv << "Version\tPE1PE2\tAdapters_trim\tVectorTrim\tK_mer_size\tDistance\tContamScr\tkc_size\tQualTrim\tQual_max_avg_error\tQual_max_err_at_ends\tOutputPrefix\tRepFilename1\tRepFilename2\tPE1OutputFilename\tPE2OutputFilename\tShuffledFilename\tSEFilename\tMax_align_mismatches\tMinReadLen\tnew2old_illumina\tPE1ReadsAn\tPE1Bases\tPE1TruSeqAdap_found\tPerc_PE1TruSeq\tPE1ReadsWVector_found\tPerc_PE1ReadsWVector\tPE1ReadsWContam_found\tPerc_PE1ReadsWContam\tPE1LeftTrimmedQual\tPE1LeftTrimmedVector\tPE1AvgLeftTrimLen\tPE1RightTrimmedAdap\tPE1RightTrimmedQual\tPE1RightTrimmedVector\tPE1AvgRightTrimLen\tPE1DiscardedTotal\tPE1DiscByContam\tPE1DiscByLength\tPE2ReadsAn\tPE2Bases\tPE2TruSeqAdap_found\tPerc_PE2TruSeq\tPE2ReadsWVector_found\tPerc_PE2ReadsWVector\tPE2ReadsWContam_found\tPerc_PE2ReadsWContam\tPE2LeftTrimmedQual\tPE2LeftTrimmedVector\tPE2AvgLeftTrimLen\tPE2RightTrimmedAdap\tPE2RightTrimmedQual\tPE2RightTrimmedVector\tPE2AvgRightTrimLen\tPE2DiscardedTotal\tPE2DiscByContam\tPE2DiscByLength\tPairsKept\tPerc_Kept\tBases\tPerc_Bases\tPairsDiscarded\tPerc_Discarded\tBases\tPerc_Bases\tSE_PE1_Kept\tSE_PE1_Bases\tSE_PE2_Kept\tSE_PE2_Bases\tAvgTrimmedLenPE1\tAvgTrimmedLenPE2\tAvgLenPE1\tAvgLenPE2\tperfect_ov\tpartial_ov\n"; cout << "Provided data files : " << endl; sum_stat << "Provided data files : " << endl; string filename_str = ""; for(int i=0; i<(int)pe1_names.size(); ++i) { cout << "PE1: " << pe1_names[i] << ", PE2: " << pe2_names[i] << endl; sum_stat << "PE1: " << pe1_names[i] << ", PE2: " << pe2_names[i] << endl; filename_str += "\t" + string(pe1_names[i]) + "\t" + string(pe2_names[i]); } cout << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; sum_stat << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; if(vector_flag) { cout << "Vector screening: YES. Vector_file provided: " << vector_file << endl; sum_stat << "Vector screening: YES. Vector_file provided: " << vector_file << endl; cout << "K-mer_size for for vector trimming: " << KMER_SIZE << endl; sum_stat << "K-mer_size for vector trimming: " << KMER_SIZE << endl; cout << "Distance between the first bases of two consecutive kmers: " << DISTANCE << endl; sum_stat << "Distance between the first bases of two consecutive kmers: " << DISTANCE << endl; } else { cout << "Vector screening: NO" << endl; sum_stat << "Vector screening: NO" << endl; } if(contaminants_flag) { cout << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; sum_stat << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; cout << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; sum_stat << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; } else { cout << "Contaminants screening: NO" << endl; sum_stat << "Contaminants screening: NO" << endl; } if(qual_trim_flag) { cout << "Quality trimming: YES" << endl; sum_stat << "Quality trimming: YES" << endl; cout << "Maximum error: " << -10*log10(max_a_error) << endl; sum_stat << "Maximum error: " << -10*log10(max_a_error) << endl; cout << "Maximum error at ends: " << -10*log10(max_e_at_ends) << endl; sum_stat << "Maximum error at ends: " << -10*log10(max_e_at_ends) << endl; } else { cout << "Quality trimming: NO" << endl; sum_stat << "Quality trimming: NO" << endl; } cout << "--------------------Output files--------------------\n"; sum_stat << "--------------------Output files--------------------\n"; cout << "Output prefix: " << output_prefix << endl; sum_stat << "Output prefix: " << output_prefix << endl; rep_file_name1 = output_prefix + "_PE1_Report.tsv"; rep_file_name2 = output_prefix + "_PE2_Report.tsv"; pe_output_filename1 = output_prefix + "_PE1.fastq" ; pe_output_filename2 = output_prefix + "_PE2.fastq" ; shuffle_filename = output_prefix + "_shuffled.fastq"; se_filename = output_prefix + "_SE.fastq"; cout << "Report files: " << rep_file_name1 << ", " << rep_file_name2 << endl; sum_stat << "Report files: " << rep_file_name1 << ", " << rep_file_name2 << endl; if (!shuffle_flag) { cout << "PE1 file: " << pe_output_filename1 << endl; sum_stat << "PE1 file: " << pe_output_filename1 << endl; cout << "PE2 file: " << pe_output_filename2 << endl; sum_stat << "PE2 file: " << pe_output_filename2 << endl; } else { cout << "Shuffled file: " << shuffle_filename << endl; sum_stat << "Shuffled file: " << shuffle_filename << endl; } cout << "Single-end reads: "<< se_filename << endl; sum_stat << "Single-end reads: "<< se_filename << endl; if(overlap_flag) { overlap_file_name = output_prefix + "_SEOLP.fastq"; sum_stat << "Single-end overlapped reads: "<< overlap_file_name << endl; } cout << "--------------------Other parameters--------------------\n"; sum_stat << "--------------------Other parameters--------------------\n"; cout << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; sum_stat << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; cout << "Minimum read length to accept: " << minimum_read_length << endl; sum_stat << "Minimum read length to accept: " << minimum_read_length << endl; cout << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; sum_stat << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; cout << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; sum_stat << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; cout << "Q-value: " << phred_coeff_illumina << endl; sum_stat << "Q-value: " << phred_coeff_illumina << endl; } void UnitTest::TestIlluminaSE() { sum_stat_tsv << "Version\tSE\tAdapters_trim\tVectorTrim\tK_mer_size\tDistance\tContamScr\tkc_size\tQualTrim\tQual_max_avg_error\tQual_max_err_at_ends\tOutputPrefix\tRepFilename\ttSEOutputFilename\tMax_align_mismatches\tMinReadLen\tnew2old_illumina\tSEReadsAn\tSEBases\tSETruSeqAdap_found\tPerc_SETruSeq\tSEReadsWVector_found\tPerc_SEReadsWVector\tSEReadsWContam_found\tPerc_SEReadsWContam\tSELeftTrimmedQual\tSELeftTrimmedVector\tSEAvgLeftTrimLen\tSERightTrimmedAdap\tSERightTrimmedQual\tSERightTrimmedVector\tSEAvgRightTrimLen\tSEDiscardedTotal\tSEDiscByContam\tSEDiscByLength\tSEReadsKept\tPerc_Kept\tBases\tPerc_Bases\tAvgTrimmedLenSE\n"; cout << "Provided data file(s) : " << endl; sum_stat << "Provided data file(s) : " << endl; for(int i=0; i<(int)se_names.size(); ++i) { cout << "SE: " << se_names[i] << endl; sum_stat << "SE: " << se_names[i] << endl; } cout << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; sum_stat << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; if(vector_flag) { cout << "Vector screening: YES. Vector_file provided: " << vector_file << endl; sum_stat << "Vector screening: YES. Vector_file provided: " << vector_file << endl; cout << "K-mer_size for for vector trimming: " << KMER_SIZE << endl; sum_stat << "K-mer_size for vector trimming: " << KMER_SIZE << endl; cout << "Distance between the first bases of two consequitve kmers: " << DISTANCE << endl; sum_stat << "Distance between the first bases of two consequitve kmers: " << DISTANCE << endl; } else { cout << "Vector screening: NO" << endl; sum_stat << "Vector screening: NO" << endl; } if(contaminants_flag) { cout << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; sum_stat << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; cout << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; sum_stat << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; } else { cout << "Contaminants screening: NO" << endl; sum_stat << "Contaminants screening: NO" << endl; } if(qual_trim_flag) { cout << "Quality trimming: YES" << endl; sum_stat << "Quality trimming: YES" << endl; cout << "Maximim error: " << -10*log10(max_a_error) << endl; sum_stat << "Maximim error: " << -10*log10(max_a_error) << endl; cout << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; sum_stat << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; } else { cout << "Quality trimming: NO" << endl; sum_stat << "Quality trimming: NO" << endl; } cout << "--------------------Output files--------------------\n"; sum_stat << "--------------------Output files--------------------\n"; cout << "Output prefix: " << output_prefix << endl; sum_stat << "Output prefix: " << output_prefix << endl; rep_file_name1 = output_prefix + "_SE_Report.tsv"; se_output_filename = output_prefix + "_SE.fastq" ; cout << "Report file: " << rep_file_name1 << endl; sum_stat << "Report file: " << rep_file_name1<< endl; cout << "SE file: " << se_output_filename << endl; sum_stat << "SE file: " << se_output_filename << endl; cout << "Single-end reads: "<< se_filename << endl; sum_stat << "Single-end reads: "<< se_filename << endl; cout << "--------------------Other parameters--------------------\n"; sum_stat << "--------------------Other parameters--------------------\n"; cout <//Test is the files provided are old-style illumina< "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; sum_stat << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; cout << "Minimum read length to accept: " << minimum_read_length << endl; sum_stat << "Minimum read length to accept: " << minimum_read_length << endl; cout << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; sum_stat << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; cout << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; sum_stat << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; cout << "Q-value: " << phred_coeff_illumina << endl; sum_stat << "Q-value: " << phred_coeff_illumina << endl; }
49.720339
1,247
0.600932
1a31d7d4b5ea19d59daef6364171585a63d77769
13,752
cpp
C++
common/operations/BatchMatmul.cpp
riscv-android-src/platform-packages-modules-NeuralNetworks
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
[ "Apache-2.0" ]
null
null
null
common/operations/BatchMatmul.cpp
riscv-android-src/platform-packages-modules-NeuralNetworks
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
[ "Apache-2.0" ]
null
null
null
common/operations/BatchMatmul.cpp
riscv-android-src/platform-packages-modules-NeuralNetworks
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021 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 LOG_TAG "Operations" #ifdef NN_INCLUDE_CPU_IMPLEMENTATION #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #pragma clang diagnostic ignored "-Wsign-compare" #pragma clang diagnostic ignored "-Winvalid-partial-specialization" #include <tensorflow/lite/kernels/internal/reference/reference_ops.h> #include <tensorflow/lite/kernels/internal/runtime_shape.h> #pragma clang diagnostic pop #include <limits> #include <memory> #include <vector> #include "CpuOperationUtils.h" #endif // NN_INCLUDE_CPU_IMPLEMENTATION #include "BatchMatmul.h" #include "OperationResolver.h" #include "OperationsUtils.h" #include "Tracing.h" namespace android { namespace nn { namespace batch_matmul_op { #ifdef NN_INCLUDE_CPU_IMPLEMENTATION namespace { // Checks if two matrices can be multiplied. bool canMatrixMul(uint32_t LHSRow, uint32_t LHSCol, uint32_t RHSRow, uint32_t RHSCol, bool adjX, bool adjY) { if (LHSRow == 0 || LHSCol == 0 || RHSRow == 0 || RHSCol == 0) { return false; } if (adjX) { LHSCol = LHSRow; } if (adjY) { RHSRow = RHSCol; } return LHSCol == RHSRow; } // Computes the dimensions of output tensor. std::vector<uint32_t> computeOutputDimensions(const Shape& LHSTensorShape, const Shape& RHSTensorShape, bool adjX, bool adjY) { uint32_t numDims = getNumberOfDimensions(LHSTensorShape); auto outputTensorDimensions = LHSTensorShape.dimensions; outputTensorDimensions[numDims - 2] = adjX ? LHSTensorShape.dimensions[numDims - 1] : LHSTensorShape.dimensions[numDims - 2]; outputTensorDimensions[numDims - 1] = adjY ? RHSTensorShape.dimensions[numDims - 2] : RHSTensorShape.dimensions[numDims - 1]; return outputTensorDimensions; } // Swaps row and column dimensions for a shape. Shape swapRowColumnDims(const Shape& shape) { Shape swappedShape = shape; uint32_t numDims = getNumberOfDimensions(shape); swappedShape.dimensions[numDims - 2] = shape.dimensions[numDims - 1]; swappedShape.dimensions[numDims - 1] = shape.dimensions[numDims - 2]; return swappedShape; } // Transposes a matrix. template <typename T> void transposeRowsColumns(const T* inputData, const Shape& inputShape, T* outputData) { Shape transposedShape = swapRowColumnDims(inputShape); tflite::TransposeParams params; int rank = getNumberOfDimensions(inputShape); params.perm_count = rank; for (int i = 0; i < rank - 2; ++i) { params.perm[i] = i; } params.perm[rank - 2] = rank - 1; params.perm[rank - 1] = rank - 2; tflite::reference_ops::Transpose(params, convertShapeToTflshape(inputShape), inputData, convertShapeToTflshape(transposedShape), outputData); } // Creates a temporary space in heap. // Note that it is caller's responsibility to free the memory. template <typename T> std::unique_ptr<T> getTempData(uint32_t numElems) { return std::unique_ptr<T>(new (std::nothrow) T[numElems]); } // Performs batch matmul. // LHS <..., A, B> X RHS<..., B, C> // We assume that LHS and RHS are both row oriented (adjacent values in memory // are in the same row) and will output in the same memory layout. However, // TFLite's fast GEMM libraries assume RCC layout (LHS row oriented, // RHS column oriented, output column oriented). Therefore, we perform // RHS <..., C, B> X LHS <..., B, A> // where output is a C X A column-oriented, which is equivalent to // A X C row-oriented. template <typename T> bool batchMatMulGeneric(const T* inputLHSData, const Shape& inputLHSShape, const T* inputRHSData, const Shape& inputRHSShape, const bool adjX, const bool adjY, T* outputData, const Shape& outputShape) { NNTRACE_TRANS("batchMatMulGeneric"); // Only performs transpose without conjugation for adjoint since complex number is not // supported. NNTRACE_COMP_SWITCH("reference_ops::Transpose"); const T* realInputLHSData = inputLHSData; const T* realInputRHSData = inputRHSData; auto tempInputLHSData = getTempData<T>(getNumberOfElements(inputLHSShape)); auto tempInputRHSData = getTempData<T>(getNumberOfElements(inputRHSShape)); // For LHS, it's passed as RHS and column-oriented. // If adjX is false, needs to swap shape but no need to do data transpose. // If adjX is true, no need to swap shape but needs to do data transpose. // For RHS, it's passed as LHS and row-oriented. // If adjY is false, needs to swap shape also needs to do data transpose. // If adjY is true, no need to swap shape also no need to do data transpose. if (adjX) { transposeRowsColumns(inputLHSData, inputLHSShape, tempInputLHSData.get()); realInputLHSData = tempInputLHSData.get(); } if (!adjY) { transposeRowsColumns(inputRHSData, inputRHSShape, tempInputRHSData.get()); realInputRHSData = tempInputRHSData.get(); } Shape realInputLHSShape = adjX ? inputLHSShape : swapRowColumnDims(inputLHSShape); Shape realInputRHSShape = adjY ? inputRHSShape : swapRowColumnDims(inputRHSShape); NNTRACE_COMP_SWITCH("reference_ops::BatchMatMul"); tflite::reference_ops::BatchMatMul(convertShapeToTflshape(realInputRHSShape), realInputRHSData, convertShapeToTflshape(realInputLHSShape), realInputLHSData, convertShapeToTflshape(outputShape), outputData); return true; } // Performs batch matmul for quantized types. template <typename T> bool batchMatMulQuantized(const T* inputLHSData, const Shape& inputLHSShape, const T* inputRHSData, const Shape& inputRHSShape, const bool adjX, const bool adjY, T* outputData, const Shape& outputShape) { NNTRACE_TRANS("batchMatMulQuantized"); NNTRACE_COMP_SWITCH("reference_ops::Transpose"); const T* realInputLHSData = inputLHSData; const T* realInputRHSData = inputRHSData; auto tempInputLHSData = getTempData<T>(getNumberOfElements(inputLHSShape)); auto tempInputRHSData = getTempData<T>(getNumberOfElements(inputRHSShape)); if (adjX) { transposeRowsColumns(inputLHSData, inputLHSShape, tempInputLHSData.get()); realInputLHSData = tempInputLHSData.get(); } if (!adjY) { transposeRowsColumns(inputRHSData, inputRHSShape, tempInputRHSData.get()); realInputRHSData = tempInputRHSData.get(); } Shape realInputLHSShape = adjX ? inputLHSShape : swapRowColumnDims(inputLHSShape); Shape realInputRHSShape = adjY ? inputRHSShape : swapRowColumnDims(inputRHSShape); NNTRACE_COMP_SWITCH("reference_ops::BatchMatMul"); double realMultiplier = 0.0; int32_t outputMultiplier = 0; int32_t outputShift = 0; NN_RET_CHECK(GetQuantizedConvolutionMultiplier(realInputLHSShape, realInputRHSShape, outputShape, &realMultiplier)); NN_RET_CHECK(QuantizeMultiplier(realMultiplier, &outputMultiplier, &outputShift)); tflite::FullyConnectedParams params; params.input_offset = -realInputLHSShape.offset; params.weights_offset = -realInputRHSShape.offset; params.output_offset = outputShape.offset; params.output_multiplier = outputMultiplier; params.output_shift = outputShift; // BatchMatMul has no fused activation functions. Therefore, sets // output activation min and max to min and max of int8_t. params.quantized_activation_min = std::numeric_limits<int8_t>::min(); params.quantized_activation_max = std::numeric_limits<int8_t>::max(); params.lhs_cacheable = false; params.rhs_cacheable = false; tflite::reference_ops::BatchMatMul<T, int32_t>( params, convertShapeToTflshape(realInputRHSShape), realInputRHSData, convertShapeToTflshape(realInputLHSShape), realInputLHSData, convertShapeToTflshape(outputShape), outputData); return true; } } // namespace bool prepare(IOperationExecutionContext* context) { Shape inputLHSTensorShape = context->getInputShape(kInputLHSTensor); Shape inputRHSTensorShape = context->getInputShape(kInputRHSTensor); // Checks two input tensors have same number of dimensions. NN_RET_CHECK_EQ(getNumberOfDimensions(inputLHSTensorShape), getNumberOfDimensions(inputRHSTensorShape)) << "Input tensor ranks do not match with each other."; NN_RET_CHECK_GE(getNumberOfDimensions(inputLHSTensorShape), 2u) << "Input tensor rank should be at least 2."; NN_RET_CHECK_LE(getNumberOfDimensions(inputLHSTensorShape), 4u) << "Input tensor rank should be at most 4."; uint32_t numDims = getNumberOfDimensions(inputLHSTensorShape); const bool adjX = context->getInputValue<bool>(kInputLHSAdj); const bool adjY = context->getInputValue<bool>(kInputRHSAdj); // Checks dimensions work for matrix multiplication. NN_RET_CHECK(canMatrixMul(getSizeOfDimension(inputLHSTensorShape, numDims - 2), getSizeOfDimension(inputLHSTensorShape, numDims - 1), getSizeOfDimension(inputRHSTensorShape, numDims - 2), getSizeOfDimension(inputRHSTensorShape, numDims - 1), adjX, adjY)) << "Input tensors are not able to perform matrix multiplication."; Shape outputTensorShape = context->getOutputShape(kOutputTensor); outputTensorShape.dimensions = computeOutputDimensions(inputLHSTensorShape, inputRHSTensorShape, adjX, adjY); return context->setOutputShape(kOutputTensor, outputTensorShape); } bool execute(IOperationExecutionContext* context) { switch (context->getInputType(kInputLHSTensor)) { case OperandType::TENSOR_FLOAT32: return batchMatMulGeneric(context->getInputBuffer<float>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<float>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<float>(kOutputTensor), context->getOutputShape(kOutputTensor)); case OperandType::TENSOR_FLOAT16: return batchMatMulGeneric(context->getInputBuffer<_Float16>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<_Float16>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<_Float16>(kOutputTensor), context->getOutputShape(kOutputTensor)); case OperandType::TENSOR_INT32: return batchMatMulGeneric(context->getInputBuffer<int32_t>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<int32_t>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<int32_t>(kOutputTensor), context->getOutputShape(kOutputTensor)); case OperandType::TENSOR_QUANT8_ASYMM_SIGNED: return batchMatMulQuantized(context->getInputBuffer<int8_t>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<int8_t>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<int8_t>(kOutputTensor), context->getOutputShape(kOutputTensor)); default: NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName; } return true; } #endif // NN_INCLUDE_CPU_IMPLEMENTATION } // namespace batch_matmul_op NN_REGISTER_OPERATION(BATCH_MATMUL, batch_matmul_op::kOperationName, batch_matmul_op::validate, batch_matmul_op::prepare, batch_matmul_op::execute); } // namespace nn } // namespace android
48.939502
100
0.666885
1a345ae3458244a74c91c876824819c90e3a90b0
2,662
cc
C++
zircon/system/ulib/fbl/test/algorithm_tests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
zircon/system/ulib/fbl/test/algorithm_tests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
zircon/system/ulib/fbl/test/algorithm_tests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2016 The Fuchsia 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 <algorithm> #include <limits> #include <fbl/algorithm.h> #include <zxtest/zxtest.h> namespace { TEST(AlgorithmTest, RoundUp) { EXPECT_EQ(fbl::round_up(0u, 1u), 0u); EXPECT_EQ(fbl::round_up(0u, 5u), 0u); EXPECT_EQ(fbl::round_up(5u, 5u), 5u); EXPECT_EQ(fbl::round_up(1u, 6u), 6u); EXPECT_EQ(fbl::round_up(6u, 1u), 6u); EXPECT_EQ(fbl::round_up(6u, 3u), 6u); EXPECT_EQ(fbl::round_up(6u, 4u), 8u); EXPECT_EQ(fbl::round_up(15u, 8u), 16u); EXPECT_EQ(fbl::round_up(16u, 8u), 16u); EXPECT_EQ(fbl::round_up(17u, 8u), 24u); EXPECT_EQ(fbl::round_up(123u, 100u), 200u); EXPECT_EQ(fbl::round_up(123456u, 1000u), 124000u); uint64_t large_int = std::numeric_limits<uint32_t>::max() + 1LLU; EXPECT_EQ(fbl::round_up(large_int, 64U), large_int); EXPECT_EQ(fbl::round_up(large_int, 64LLU), large_int); EXPECT_EQ(fbl::round_up(large_int + 63LLU, 64U), large_int + 64LLU); EXPECT_EQ(fbl::round_up(large_int + 63LLU, 64LLU), large_int + 64LLU); EXPECT_EQ(fbl::round_up(large_int, 3U), large_int + 2LLU); EXPECT_EQ(fbl::round_up(large_int, 3LLU), large_int + 2LLU); EXPECT_EQ(fbl::round_up(2U, large_int), large_int); EXPECT_EQ(fbl::round_up(2LLU, large_int), large_int); } TEST(AlgorithmTest, RoundDown) { EXPECT_EQ(fbl::round_down(0u, 1u), 0u); EXPECT_EQ(fbl::round_down(0u, 5u), 0u); EXPECT_EQ(fbl::round_down(5u, 5u), 5u); EXPECT_EQ(fbl::round_down(1u, 6u), 0u); EXPECT_EQ(fbl::round_down(6u, 1u), 6u); EXPECT_EQ(fbl::round_down(6u, 3u), 6u); EXPECT_EQ(fbl::round_down(6u, 4u), 4u); EXPECT_EQ(fbl::round_down(15u, 8u), 8u); EXPECT_EQ(fbl::round_down(16u, 8u), 16u); EXPECT_EQ(fbl::round_down(17u, 8u), 16u); EXPECT_EQ(fbl::round_down(123u, 100u), 100u); EXPECT_EQ(fbl::round_down(123456u, 1000u), 123000u); uint64_t large_int = std::numeric_limits<uint32_t>::max() + 1LLU; EXPECT_EQ(fbl::round_down(large_int, 64U), large_int); EXPECT_EQ(fbl::round_down(large_int, 64LLU), large_int); EXPECT_EQ(fbl::round_down(large_int + 63LLU, 64U), large_int); EXPECT_EQ(fbl::round_down(large_int + 63LLU, 64LLU), large_int); EXPECT_EQ(fbl::round_down(large_int + 65LLU, 64U), large_int + 64LLU); EXPECT_EQ(fbl::round_down(large_int + 65LLU, 64LLU), large_int + 64LLU); EXPECT_EQ(fbl::round_down(large_int + 2LLU, 3U), large_int + 2LLU); EXPECT_EQ(fbl::round_down(large_int + 2LLU, 3LLU), large_int + 2LLU); EXPECT_EQ(fbl::round_down(2U, large_int), 0); EXPECT_EQ(fbl::round_down(2LLU, large_int), 0); } } // namespace
36.972222
74
0.706987
1a3481fd62fddf822dd050eb0f24ebee0a0dfd13
2,375
cpp
C++
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/priority-booster
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
3
2020-09-19T07:27:34.000Z
2022-01-02T21:10:38.000Z
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/windows-kernel-programming
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
null
null
null
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/windows-kernel-programming
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
null
null
null
// DelProtect2Config.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "stdafx.h" #include "..\DelProtect2\DelProtectCommon.h" #include <iostream> int Error(const char* text) { printf("%s (%d)\n", text, ::GetLastError()); return 1; } int PrintUsage() { printf("Usage: DelProtect2Config <option> [exename]\n"); printf("\tOption: add, remove or clear\n"); return 0; } int wmain(int argc, const wchar_t* argv[]) { if (argc < 2) { return PrintUsage(); } HANDLE hDevice = ::CreateFileW(USER_FILE_NAME, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (hDevice == INVALID_HANDLE_VALUE) return Error("Failed to open handle to device"); DWORD returned{ 0 }; BOOL success { FALSE }; bool badOption = false; if (::_wcsicmp(argv[1], L"add") == 0) { if (argc < 3) { return PrintUsage(); } success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_ADD_EXE, (PVOID)argv[2], ((DWORD)::wcslen(argv[2]) + 1) * sizeof(WCHAR), nullptr, 0, &returned, nullptr); } else if (::_wcsicmp(argv[1], L"remove") == 0) { if (argc < 3) { return PrintUsage(); } success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_REMOVE_EXE, (PVOID)argv[2], ((DWORD)::wcslen(argv[2]) + 1) * sizeof(WCHAR), nullptr, 0, &returned, nullptr); } else if (::_wcsicmp(argv[1], L"clear") == 0) { success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_CLEAR, nullptr, 0, nullptr, 0, &returned, nullptr); } else { badOption = true; printf("Unknown option.\n"); PrintUsage(); } if (!badOption) { if (!success) { Error("Failed in operation"); } else { printf("Success.\n"); } } ::CloseHandle(hDevice); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
26.988636
135
0.671579
1a3e64646759c6e42fb554b1722fb23abd9fac41
907
hpp
C++
output/include/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
1
2019-07-31T06:44:46.000Z
2019-07-31T06:44:46.000Z
src/pilo/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
src/pilo/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
#pragma once #include "core/coredefs.hpp" namespace pilo { namespace core { namespace threading { class read_write_lock { public: #ifdef WINDOWS read_write_lock() { ::InitializeSRWLock(&m_lock); } #else read_write_lock() { ::pthread_rwlock_init(&m_lock, NULL); } ~read_write_lock(); #endif void lock_read(); void lock_write(); bool try_lock_read(); bool try_lock_write(); void unlock_read(); void unlock_write(); protected: #ifdef WINDOWS SRWLOCK m_lock; #else pthread_rwlock_t m_lock; #endif }; } } }
18.895833
57
0.416759
1a40c72b20b9825a1fb3a4c6019aa141d52ec6d0
1,256
cc
C++
caffe2/contrib/prof/profiling_annotations_test.cc
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
1
2019-07-21T02:13:22.000Z
2019-07-21T02:13:22.000Z
caffe2/contrib/prof/profiling_annotations_test.cc
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
caffe2/contrib/prof/profiling_annotations_test.cc
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
// Unit tests for profiling_annotations.h. #include "caffe2/contrib/prof/profiling_annotations.h" #include <gtest/gtest.h> namespace caffe2 { namespace contrib { namespace prof { namespace { TEST(TwoNumberStatsTest, ComputeAndGetOpStatsSummary) { // e.g., 2 and 3 TwoNumberStats stats; stats.addPoint(2); stats.addPoint(3); EXPECT_FLOAT_EQ(2.5, stats.getMean()); // Population standard deviation. EXPECT_FLOAT_EQ(0.5, stats.getStddev()); } TEST(TwoNumberStatsTest, TestRestore) { // Expect that restore&recompute is still the same. // E.g., 2 and 3 (above). TwoNumberStats stats(2.5, 0.5, 2); // Expect that restore&recompute is still the same. EXPECT_FLOAT_EQ(2.5, stats.getMean()); // Population standard deviation. EXPECT_FLOAT_EQ(0.5, stats.getStddev()); } TEST(ProfilingAnnotationsTest, BasicAccessToActiveData) { ProfilingOperatorAnnotation op_annotation; op_annotation.getMutableExecutionTimeMs()->addPoint(5); EXPECT_EQ(5, op_annotation.getExecutionTimeMs().getMean()); ProfilingDataAnnotation data_annotation; data_annotation.getMutableUsedBytes()->addPoint(7); EXPECT_EQ(7, data_annotation.getUsedBytes().getMean()); } } // namespace } // namespace prof } // namespace contrib } // namespace caffe2
27.911111
61
0.749204
1a412569050244cbdd0b2b246b2ecbf4c5c37b3a
164
hpp
C++
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
#pragma once #include "proxy.hpp" #include "topology.hpp" namespace face_vertex { inline bool is_valid(VertexProxy vp) { return is_valid(topology(vp)); } }
11.714286
34
0.719512
1a43b6233a940ecb5091f95246199e1d08b44a81
1,461
cpp
C++
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Buddy Strings https://leetcode.com/problems/buddy-strings/ Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: A = "ab", B = "ba" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B. Example 2: Input: A = "ab", B = "ab" Output: false Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B. Example 3: Input: A = "aa", B = "aa" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B. Example 4: Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true Example 5: Input: A = "", B = "aa" Output: false Constraints: 0 <= A.length <= 20000 0 <= B.length <= 20000 A and B consist of lowercase letters. */ class Solution { public: bool buddyStrings(string A, string B) { // aaa aaa 1 < 3 // abc abc 3 < 3 int n = A.size(); if(A==B) return (set<char>(A.begin(), A.end()).size() < n); int l = 0, r = n - 1; while(l < n && A[l] == B[l]) l++; while(r >= 0 && A[r] == B[r]) r--; if(l < r) swap(A[l], A[r]); return A == B; } };
26.089286
202
0.590691
1a44e14db33b2f2ab59aecad07e52ca9a292ea61
2,159
cpp
C++
Development/Editor/Core/LuaEngine/logging_backend.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
2
2016-05-30T11:42:33.000Z
2017-10-31T11:53:42.000Z
Development/Editor/Core/LuaEngine/logging_backend.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
null
null
null
Development/Editor/Core/LuaEngine/logging_backend.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
null
null
null
#include "logging_backend.h" #include <boost/filesystem/fstream.hpp> #include <base/util/format.h> #include <base/exception/exception.h> namespace logging { struct logging_backend::implementation { boost::filesystem::path root_path_; boost::filesystem::ofstream file_; uintmax_t written_; implementation(const boost::filesystem::path& root_path) : root_path_(root_path) , file_() , written_(0) { } }; logging_backend::logging_backend(const boost::filesystem::path& root_path) : impl_(new implementation(root_path)) { } logging_backend::~logging_backend() { delete impl_; } void logging_backend::consume(record_view const& rec, string_type const& formatted_message) { if((impl_->file_.is_open() && (impl_->written_ + formatted_message.size() >= 512*1024) ) || !impl_->file_.good() ) { rotate_file(); } if (!impl_->file_.is_open()) { boost::filesystem::create_directories(impl_->root_path_); impl_->file_.open(impl_->root_path_ / L"ydwe.log", std::ios_base::app | std::ios_base::out); if (!impl_->file_.is_open()) { throw base::exception("Failed to open file '%s' for writing.", (impl_->root_path_ / L"ydwe.log").string().c_str()); } impl_->written_ = static_cast<std::streamoff>(impl_->file_.tellp()); } impl_->file_.write(formatted_message.data(), static_cast<std::streamsize>(formatted_message.size())); impl_->file_.put(static_cast<string_type::value_type>('\n')); impl_->written_ += formatted_message.size() + 1; } void logging_backend::flush() { if (impl_->file_.is_open()) impl_->file_.flush(); } void logging_backend::rotate_file() { impl_->file_.close(); impl_->file_.clear(); impl_->written_ = 0; size_t i = 1; for (; i < 10; ++i) { boost::filesystem::path p = impl_->root_path_ / base::format(L"ydwe%03d.log", i); if (!boost::filesystem::exists(p)) { break; } } if (i == 10) i = 1; boost::filesystem::rename(impl_->root_path_ / L"ydwe.log", impl_->root_path_ / base::format(L"ydwe%03d.log", i)); ++i; if (i == 10) i = 1; boost::filesystem::remove(impl_->root_path_ / base::format(L"ydwe%03d.log", i)); } }
25.702381
119
0.666975
1a46c9989a42f40ab255fa8cb9678bb0c9116371
24,249
cpp
C++
mtoa/gpuCacheTranslator/gpuCacheTranslator.cpp
compso/bb_alembic
71512e88374f801aa9b54404923ad764a4db9c96
[ "MIT" ]
2
2015-11-16T03:25:20.000Z
2017-08-28T02:54:53.000Z
mtoa/gpuCacheTranslator/gpuCacheTranslator.cpp
compso/bb_alembic
71512e88374f801aa9b54404923ad764a4db9c96
[ "MIT" ]
null
null
null
mtoa/gpuCacheTranslator/gpuCacheTranslator.cpp
compso/bb_alembic
71512e88374f801aa9b54404923ad764a4db9c96
[ "MIT" ]
null
null
null
/* (c)2012 BlueBolt Ltd. All rights reserved. * * GpuCacheTranslator.cpp * * Created on: 20 Jul 2012 * Author: ashley-r */ #include <maya/MFnDagNode.h> #include <maya/MBoundingBox.h> #include <maya/MPlugArray.h> #include <maya/MTypes.h> #include "gpuCacheTranslator.h" /* * Return a new string with all occurrences of 'from' replaced with 'to' */ std::string replace_all(const MString &str, const char *from, const char *to) { std::string result(str.asChar()); std::string::size_type index = 0, from_len = strlen(from), to_len = strlen(to); while ((index = result.find(from, index)) != std::string::npos) { result.replace(index, from_len, to); index += to_len; } return result; } union DJB2HashUnion{ unsigned int hash; int hashInt; }; int DJB2Hash(unsigned char *str) { DJB2HashUnion hashUnion; hashUnion.hash = 5381; int c; while ((c = *str++)) hashUnion.hash = ((hashUnion.hash << 5) + hashUnion.hash) + c; /* hash * 33 + c */ return hashUnion.hashInt; } AtNode* GpuCacheTranslator::CreateArnoldNodes() { AiMsgDebug("[GpuCacheTranslator] CreateArnoldNodes()"); m_isMasterDag = IsMasterInstance(); m_masterDag = GetMasterInstance(); if (m_isMasterDag) { return AddArnoldNode( "alembic_loader" ); } else { return AddArnoldNode( "ginstance" ); } } void GpuCacheTranslator::Delete() { // If the procedural has been expanded at export, // we need to delete all the created nodes here AiMsgDebug("[GpuCacheTranslator] Delete()"); CShapeTranslator::Delete(); } void GpuCacheTranslator::RequestUpdate() { SetUpdateMode(AI_RECREATE_NODE); CShapeTranslator::RequestUpdate(); } void GpuCacheTranslator::Export( AtNode* instance ) { if (IsExported()) { // Since we always use AI_RECREATE_NODE during IPR (see RequestUpdate) // we should never get here. Early out for safety return; } AiMsgDebug("[GpuCacheTranslator] Export()"); const char* nodeType = AiNodeEntryGetName(AiNodeGetNodeEntry(instance)); if (strcmp(nodeType, "ginstance") == 0) { ExportInstance(instance, m_masterDag, false); } else { ExportProcedural(instance, false); } } AtNode* GpuCacheTranslator::ExportInstance(AtNode *instance, const MDagPath& masterInstance, bool update) { AtNode* masterNode = AiNodeLookUpByName(masterInstance.partialPathName().asChar()); int instanceNum = m_dagPath.instanceNumber(); if ( instanceNum > 0 ) { std::cout << "ExportInstance::instanceNum :: " << instanceNum << std::endl; AiNodeSetStr(instance, "name", m_dagPath.partialPathName().asChar()); ExportMatrix(instance); AiNodeSetPtr(instance, "node", masterNode); AiNodeSetBool(instance, "inherit_xform", false); int visibility = AiNodeGetInt(masterNode, "visibility"); AiNodeSetInt(instance, "visibility", visibility); AiNodeSetPtr( instance, "shader", arnoldShader(instance) ); // Export light linking per instance ExportLightLinking(instance); } return instance; } void GpuCacheTranslator::ExportProcedural( AtNode *node, bool update) { AiMsgDebug("[GpuCacheTranslator] ExportProcedural()"); // do basic node export ExportMatrix( node ); // AiNodeSetPtr( node, "shader", arnoldShader(node) ); AiNodeSetInt( node, "visibility", ComputeVisibility() ); MPlug plug = FindMayaPlug( "receiveShadows" ); if( !plug.isNull() ) { AiNodeSetBool( node, "receive_shadows", plug.asBool() ); } plug = FindMayaPlug( "aiSelfShadows" ); if( !plug.isNull() ) { AiNodeSetBool( node, "self_shadows", plug.asBool() ); } plug = FindMayaPlug( "aiOpaque" ); if( !plug.isNull() ) { AiNodeSetBool( node, "opaque", plug.asBool() ); } MStatus status; MFnDependencyNode dnode(m_dagPath.node(), &status); if (status) AiNodeSetInt(node, "id", DJB2Hash((unsigned char*)dnode.name().asChar())); // now set the procedural-specific parameters if (!update){ MFnDagNode fnDagNode( m_dagPath ); MBoundingBox bound = fnDagNode.boundingBox(); AiNodeSetVec( node, "min", bound.min().x-m_dispPadding, bound.min().y-m_dispPadding, bound.min().z-m_dispPadding ); AiNodeSetVec( node, "max", bound.max().x+m_dispPadding, bound.max().y, bound.max().z+m_dispPadding ); // const char *dsoPath = getenv( "ALEMBIC_ARNOLD_PROCEDURAL_PATH" ); // AiNodeSetStr( node, "filename", dsoPath ? dsoPath : "bb_AlembicArnoldProcedural.so" ); // Set the parameters for the procedural //abcFile path MString abcFile = fnDagNode.findPlug("cacheFileName").asString().expandEnvironmentVariablesAndTilde(); //object path MString objectPath = fnDagNode.findPlug("cacheGeomPath").asString(); //object pattern MString objectPattern = "*"; plug = FindMayaPlug( "objectPattern" ); if (!plug.isNull() ) { if (plug.asString() != "") { objectPattern = plug.asString(); } } //object pattern MString excludePattern = ""; plug = FindMayaPlug( "excludePattern" ); if (!plug.isNull() ) { if (plug.asString() != "") { excludePattern = plug.asString(); } } float shutterOpen = 0.0; plug = FindMayaPlug( "shutterOpen" ); if (!plug.isNull() ) { shutterOpen = plug.asFloat(); } float shutterClose = 0.0; plug = FindMayaPlug( "shutterClose" ); if (!plug.isNull() ) { shutterClose = plug.asFloat(); } float timeOffset = 0.0; plug = FindMayaPlug( "timeOffset" ); if (!plug.isNull() ) { timeOffset = plug.asFloat(); } float frame = 0.0; plug = FindMayaPlug( "frame" ); if (!plug.isNull() ) { frame = plug.asFloat(); } int subDIterations = 0; plug = FindMayaPlug( "ai_subDIterations" ); if (!plug.isNull() ) { subDIterations = plug.asInt(); } MString nameprefix = ""; plug = FindMayaPlug( "namePrefix" ); if (!plug.isNull() ) { nameprefix = plug.asString(); } // bool exportFaceIds = fnDagNode.findPlug("exportFaceIds").asBool(); bool makeInstance = false; plug = FindMayaPlug( "makeInstance" ); if (!plug.isNull() ) { makeInstance = plug.asBool(); } // bool loadAtInit = true; // plug = FindMayaPlug( "loadAtInit" ); // if (!plug.isNull() ) // { // loadAtInit = plug.asBool(); // } bool flipv = false; plug = FindMayaPlug( "flipv" ); if (!plug.isNull() ) { flipv = plug.asBool(); } bool invertNormals = false; plug = FindMayaPlug( "invertNormals" ); if (!plug.isNull() ) { invertNormals = plug.asBool(); } short i_subDUVSmoothing = 1; plug = FindMayaPlug( "ai_subDUVSmoothing" ); if (!plug.isNull() ) { i_subDUVSmoothing = plug.asShort(); } MString subDUVSmoothing; switch (i_subDUVSmoothing) { case 0: subDUVSmoothing = "pin_corners"; break; case 1: subDUVSmoothing = "pin_borders"; break; case 2: subDUVSmoothing = "linear"; break; case 3: subDUVSmoothing = "smooth"; break; default : subDUVSmoothing = "pin_corners"; break; } // MTime curTime = MAnimControl::currentTime(); // fnDagNode.findPlug("time").getValue( frame ); // MTime frameOffset; // fnDagNode.findPlug("timeOffset").getValue( frameOffset ); // float time = curTime.as(MTime::kFilm)+timeOffset; float time = frame+timeOffset; MString argsString; if (objectPath != "|"){ argsString += " -objectpath "; // convert "|" to "/" argsString += MString(replace_all(objectPath,"|","/").c_str()); } if (objectPattern != "*"){ argsString += " -pattern "; argsString += objectPattern; } if (excludePattern != ""){ argsString += " -excludepattern "; argsString += excludePattern; } if (shutterOpen != 0.0){ argsString += " -shutteropen "; argsString += shutterOpen; } if (shutterClose != 0.0){ argsString += " -shutterclose "; argsString += shutterClose; } if (subDIterations != 0){ argsString += " -subditerations "; argsString += subDIterations; argsString += " -subduvsmoothing "; argsString += subDUVSmoothing; } if (makeInstance){ argsString += " -makeinstance "; } if (nameprefix != ""){ argsString += " -nameprefix "; argsString += nameprefix; } if (flipv){ argsString += " -flipv "; } if (invertNormals){ argsString += " -invertNormals "; } argsString += " -filename "; argsString += abcFile; argsString += " -frame "; argsString += time; if (m_displaced){ argsString += " -disp_map "; argsString += AiNodeGetName(m_dispNode); } AiNodeSetStr(node, "data", argsString.asChar()); // AiNodeSetBool( node, "load_at_init", loadAtInit ); ExportUserAttrs(node); // export curve attributes ExportCurveAttrs(node); // Export light linking per instance ExportLightLinking(node); } } void GpuCacheTranslator::ExportUserAttrs( AtNode *node ) { // Get the optional attributes and export them as user vars MPlug plug = FindMayaPlug( "shaderAssignation" ); if( !plug.isNull() ) { AiNodeDeclare( node, "shaderAssignation", "constant STRING" ); AiNodeSetStr( node, "shaderAssignation", plug.asString().asChar() ); } plug = FindMayaPlug( "displacementAssignation" ); if( !plug.isNull() ) { AiNodeDeclare( node, "displacementAssignation", "constant STRING" ); AiNodeSetStr( node, "displacementAssignation", plug.asString().asChar() ); } plug = FindMayaPlug( "shaderAssignmentfile" ); if( !plug.isNull() ) { AiNodeDeclare( node, "shaderAssignmentfile", "constant STRING" ); AiNodeSetStr( node, "shaderAssignmentfile", plug.asString().asChar() ); } plug = FindMayaPlug( "overrides" ); if( !plug.isNull() ) { AiNodeDeclare( node, "overrides", "constant STRING" ); AiNodeSetStr( node, "overrides", plug.asString().asChar() ); } plug = FindMayaPlug( "overridefile" ); if( !plug.isNull() ) { AiNodeDeclare( node, "overridefile", "constant STRING" ); AiNodeSetStr( node, "overridefile", plug.asString().asChar() ); } plug = FindMayaPlug( "userAttributes" ); if( !plug.isNull() ) { AiNodeDeclare( node, "userAttributes", "constant STRING" ); AiNodeSetStr( node, "userAttributes", plug.asString().asChar() ); } plug = FindMayaPlug( "userAttributesfile" ); if( !plug.isNull() ) { AiNodeDeclare( node, "userAttributesfile", "constant STRING" ); AiNodeSetStr( node, "userAttributesfile", plug.asString().asChar() ); } plug = FindMayaPlug( "skipJson" ); if( !plug.isNull() ) { AiNodeDeclare( node, "skipJson", "constant BOOL" ); AiNodeSetBool( node, "skipJson", plug.asBool() ); } plug = FindMayaPlug( "skipShaders" ); if( !plug.isNull() ) { AiNodeDeclare( node, "skipShaders", "constant BOOL" ); AiNodeSetBool( node, "skipShaders", plug.asBool() ); } plug = FindMayaPlug( "skipOverrides" ); if( !plug.isNull() ) { AiNodeDeclare( node, "skipOverrides", "constant BOOL" ); AiNodeSetBool( node, "skipOverrides", plug.asBool() ); } plug = FindMayaPlug( "skipUserAttributes" ); if( !plug.isNull() ) { AiNodeDeclare( node, "skipUserAttributes", "constant BOOL" ); AiNodeSetBool( node, "skipUserAttributes", plug.asBool() ); } plug = FindMayaPlug( "skipDisplacements" ); if( !plug.isNull() ) { AiNodeDeclare( node, "skipDisplacements", "constant BOOL" ); AiNodeSetBool( node, "skipDisplacements", plug.asBool() ); } plug = FindMayaPlug( "objectPattern" ); if( !plug.isNull() ) { AiNodeDeclare( node, "objectPattern", "constant STRING" ); AiNodeSetStr( node, "objectPattern", plug.asString().asChar() ); } plug = FindMayaPlug( "assShaders" ); if( !plug.isNull() ) { AiNodeDeclare( node, "assShaders", "constant STRING" ); AiNodeSetStr( node, "assShaders", plug.asString().asChar() ); } plug = FindMayaPlug( "radiusPoint" ); if( !plug.isNull() ) { AiNodeDeclare( node, "radiusPoint", "constant FLOAT" ); AiNodeSetFlt( node, "radiusPoint", plug.asFloat() ); } plug = FindMayaPlug( "scaleVelocity" ); if( !plug.isNull() ) { AiNodeDeclare( node, "scaleVelocity", "constant FLOAT" ); AiNodeSetFlt( node, "scaleVelocity", plug.asFloat() ); } } void GpuCacheTranslator::ExportCurveAttrs( AtNode *node ) { MPlug plug = FindMayaPlug( "radiusCurve" ); if( !plug.isNull() ) { AiNodeDeclare( node, "radiusCurve", "constant FLOAT" ); AiNodeSetFlt( node, "radiusCurve", plug.asFloat() ); } plug = FindMayaPlug( "modeCurve" ); if( !plug.isNull() ) { AiNodeDeclare( node, "modeCurve", "constant STRING" ); int modeCurveInt = plug.asInt(); if (modeCurveInt == 1) AiNodeSetStr(node, "modeCurve", "thick"); else if (modeCurveInt == 2) AiNodeSetStr(node, "modeCurve", "oriented"); else AiNodeSetStr(node, "modeCurve", "ribbon"); } } bool GpuCacheTranslator::RequiresMotionData() { return IsMotionBlurEnabled( MTOA_MBLUR_OBJECT ) && IsLocalMotionBlurEnabled(); } void GpuCacheTranslator::ExportMotion( AtNode *node ) { if( !IsMotionBlurEnabled() ) { return; } ExportMatrix( node ); } void GpuCacheTranslator::nodeInitialiser( CAbTranslator context ) { CExtensionAttrHelper helper( context.maya, "procedural" ); CShapeTranslator::MakeCommonAttributes(helper); CShapeTranslator::MakeMayaVisibilityFlags(helper); CAttrData data; // make the attributes data.defaultValue.STR() = AtString(""); data.name = "aiTraceSets"; data.shortName = "trace_sets"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "aiSssSetname"; data.shortName = "ai_sss_setname"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "objectPattern"; data.shortName = "object_pattern"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "excludePattern"; data.shortName = "exclude_pattern"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "namePrefix"; data.shortName = "name_prefix"; helper.MakeInputString ( data ); data.defaultValue.BOOL() = false; data.name = "makeInstance"; data.shortName = "make_instance"; helper.MakeInputBoolean(data); data.defaultValue.BOOL() = false; data.name = "flipv"; data.shortName = "flip_v"; helper.MakeInputBoolean(data); data.defaultValue.BOOL() = false; data.name = "invertNormals"; data.shortName = "invert_normals"; helper.MakeInputBoolean(data); data.defaultValue.STR() = AtString(""); data.name = "shaderAssignation"; data.shortName = "shader_assignation"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "displacementAssignation"; data.shortName = "displacement_assignation"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "shaderAssignmentfile"; data.shortName = "shader_assignment_file"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "overrides"; data.shortName = "overrides"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "overridefile"; data.shortName = "override_file"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "userAttributes"; data.shortName = "user_attributes"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "userAttributesfile"; data.shortName = "user_attributes_file"; helper.MakeInputString ( data ); data.defaultValue.BOOL() = false; data.name = "skipJson"; data.shortName = "skip_json"; helper.MakeInputBoolean(data); data.defaultValue.BOOL() = false; data.name = "skipShaders"; data.shortName = "skip_shaders"; helper.MakeInputBoolean(data); data.defaultValue.BOOL() = false; data.name = "skipOverrides"; data.shortName = "skip_overrides"; helper.MakeInputBoolean(data); data.defaultValue.BOOL() = false; data.name = "skipUserAttributes"; data.shortName = "skip_user_attributes"; helper.MakeInputBoolean(data); data.defaultValue.BOOL() = false; data.name = "skipDisplacements"; data.shortName = "skip_displacements"; helper.MakeInputBoolean(data); data.defaultValue.STR() = AtString(""); data.name = "objectPattern"; data.shortName = "object_pattern"; helper.MakeInputString ( data ); data.defaultValue.STR() = AtString(""); data.name = "assShaders"; data.shortName = "ass_shaders"; helper.MakeInputString ( data ); data.defaultValue.FLT() = 0.1f; data.name = "radiusPoint"; data.shortName = "radius_point"; helper.MakeInputFloat(data); data.defaultValue.FLT() = 0.0f; data.name = "timeOffset"; data.shortName = "time_offset"; helper.MakeInputFloat(data); data.defaultValue.FLT() = 0.0f; data.name = "frame"; data.shortName = "frame"; helper.MakeInputFloat(data); // radiusCurve, this can be textured to give varying width along the curve data.defaultValue.FLT() = 0.01f; data.name = "radiusCurve"; data.shortName = "radius_curve"; data.hasMin = true; data.min.FLT() = 0.0f; data.hasSoftMax = true; data.softMax.FLT() = 1.0f; helper.MakeInputFloat(data); MStringArray curveTypeEnum; curveTypeEnum.append ( "ribbon" ); curveTypeEnum.append ( "thick" ); data.defaultValue.INT() = 0; data.name = "modeCurve"; data.shortName = "mode_curve"; data.enums = curveTypeEnum; helper.MakeInputEnum(data); data.defaultValue.FLT() = 1.0f; data.name = "scaleVelocity"; data.shortName = "scale_velocity"; helper.MakeInputFloat(data); data.defaultValue.BOOL() = true; data.name = "loadAtInit"; data.shortName = "load_at_init"; helper.MakeInputBoolean(data); } void GpuCacheTranslator::GetDisplacement( MObject& obj, float& dispPadding, bool& enableAutoBump) { MFnDependencyNode dNode(obj); MPlug plug = dNode.findPlug("aiDisplacementPadding"); if (!plug.isNull()) dispPadding = AiMax(dispPadding, plug.asFloat()); if (!enableAutoBump) { plug = dNode.findPlug("aiDisplacementAutoBump"); if (!plug.isNull()) enableAutoBump = enableAutoBump || plug.asBool(); } } AtNode* GpuCacheTranslator::arnoldShader(AtNode* node) { m_displaced = false; float maximumDisplacementPadding = -AI_BIG; bool enableAutoBump = false; unsigned instNumber = m_dagPath.isInstanced() ? m_dagPath.instanceNumber() : 0; MPlug shadingGroupPlug = GetNodeShadingGroup(m_dagPath.node(), instNumber); //find and export any displacment shaders attached // DISPLACEMENT MATERIAL EXPORT MPlugArray connections; MFnDependencyNode fnDGShadingGroup(shadingGroupPlug.node()); MPlug shaderPlug = fnDGShadingGroup.findPlug("displacementShader"); shaderPlug.connectedTo(connections, true, false); // are there any connections to displacementShader? if (connections.length() > 0) { m_displaced = true; MObject dispNode = connections[0].node(); GetDisplacement(dispNode, maximumDisplacementPadding, enableAutoBump); m_dispPadding = maximumDisplacementPadding; AtNode* dispImage(ExportConnectedNode(connections[0])); m_dispNode = dispImage; } // Only export displacement attributes if a displacement is applied if (m_displaced) { std::cout << "arnoldShader::m_displaced :: " << m_displaced << std::endl; // Note that disp_height has no actual influence on the scale of the displacement if it is vector based // it only influences the computation of the displacement bounds // AiNodeSetFlt(node, "disp_padding", maximumDisplacementPadding); } // return the exported surface shader return ExportConnectedNode( shadingGroupPlug ); }
31.656658
127
0.545507
1a46daba1ed7553485e49f5066597902ebe065d4
3,415
cpp
C++
recast_ros/src/nodes/test_planning_service_interactive.cpp
ori-drs/recast_ros
f1516d43578aa7550fbb3ee6d91bf4fe8eb773f8
[ "Zlib" ]
8
2020-04-13T16:34:35.000Z
2021-12-21T14:24:31.000Z
recast_ros/src/nodes/test_planning_service_interactive.cpp
ori-drs/recast_ros
f1516d43578aa7550fbb3ee6d91bf4fe8eb773f8
[ "Zlib" ]
3
2020-06-24T16:05:02.000Z
2022-01-18T08:15:20.000Z
recast_ros/src/nodes/test_planning_service_interactive.cpp
ori-drs/recast_ros
f1516d43578aa7550fbb3ee6d91bf4fe8eb773f8
[ "Zlib" ]
2
2021-02-20T08:39:36.000Z
2021-02-22T09:48:22.000Z
// // Copyright (c) 2019 Martim Brandão martim@robots.ox.ac.uk, Omer Burak Aladag aladagomer@sabanciuniv.edu, Ioannis Havoutis ioannis@robots.ox.ac.uk // As a part of Dynamic Robot Systems Group, Oxford Robotics Institute, University of Oxford // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #include "recast_ros/RecastPathSrv.h" #include <geometry_msgs/PoseStamped.h> #include <ros/ros.h> class TestPlanningServiceInteractive { public: TestPlanningServiceInteractive(ros::NodeHandle &node_handle) : node_handle_(node_handle) { // ros params node_handle_.param("target_topic", target_topic_, std::string("/move_base_simple/goal")); node_handle_.param("path_service", path_service_, std::string("/recast_node/plan_path")); node_handle_.param("loop_rate", loop_rate_, 1.0); // subscribe target subscriber_ = node_handle_.subscribe(target_topic_, 1, &TestPlanningServiceInteractive::callback, this); } void callback(const geometry_msgs::PoseStamped &msg) { ROS_INFO("Received point: %f %f %f", msg.pose.position.x, msg.pose.position.y, msg.pose.position.z); target_ = msg.pose.position; } void run() { // ros ros::ServiceClient client_recast = node_handle_.serviceClient<recast_ros::RecastPathSrv>(path_service_); // wait until the client exists... ROS_INFO("Waiting for Recast path planning service to become available..."); client_recast.waitForExistence(); ROS_INFO("Recast planning service active!"); // loop ros::Rate loop_rate(loop_rate_); while (ros::ok()) { // get current state. TODO: take as param? geometry_msgs::Point current; current.x = 0; current.y = 0; current.z = 0; // recast plan to goal recast_ros::RecastPathSrv srv; srv.request.startXYZ = current; srv.request.goalXYZ = target_; if (!client_recast.call(srv)) { ROS_ERROR("Failed to call recast query service"); // continue; } if (srv.response.path.size() < 2) { ROS_ERROR("Could not find a path"); // continue; } ros::spinOnce(); loop_rate.sleep(); } } protected: ros::NodeHandle node_handle_; ros::Subscriber subscriber_; std::string target_topic_; std::string path_service_; double loop_rate_; geometry_msgs::Point target_; }; int main(int argc, char *argv[]) { ros::init(argc, argv, "high_level_planner_node"); ros::NodeHandle node_handle("~"); TestPlanningServiceInteractive test_planning_service_interactive(node_handle); test_planning_service_interactive.run(); return 0; }
34.846939
147
0.70981
1a49226dab9c37637f639d113eaa776ed9b030cf
1,352
hpp
C++
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
38
2016-01-14T13:51:13.000Z
2021-12-29T01:49:30.000Z
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
null
null
null
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
16
2016-01-15T11:07:51.000Z
2021-12-29T01:49:37.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Texture.hpp" namespace s3d { class RenderTexture : public Texture { protected: struct _swapChain {}; RenderTexture(const _swapChain&); public: RenderTexture(); RenderTexture(uint32 width, uint32 height, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); explicit RenderTexture(const Size& size, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); RenderTexture(uint32 width, uint32 height, const ColorF& color, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); RenderTexture(const Size& size, const ColorF& color, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); void clear(const ColorF& color); void beginReset(); bool endReset(const Size& size, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); bool saveDDS(const FilePath& path) const; }; }
30.044444
178
0.699704
1a495c21c102171ec676f78c94de7d3c26d81452
2,096
cc
C++
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
null
null
null
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia 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 "src/graphics/bin/vulkan_loader/loader.h" #include <lib/fdio/directory.h> #include <lib/fdio/io.h> LoaderImpl::~LoaderImpl() { app_->RemoveObserver(this); } // static void LoaderImpl::Add(LoaderApp* app, const std::shared_ptr<sys::OutgoingDirectory>& outgoing) { outgoing->AddPublicService(fidl::InterfaceRequestHandler<fuchsia::vulkan::loader::Loader>( [app](fidl::InterfaceRequest<fuchsia::vulkan::loader::Loader> request) { auto impl = std::make_unique<LoaderImpl>(app); LoaderImpl* impl_ptr = impl.get(); impl_ptr->bindings_.AddBinding(std::move(impl), std::move(request), nullptr); })); } // LoaderApp::Observer implementation. void LoaderImpl::OnIcdListChanged(LoaderApp* app) { auto it = callbacks_.begin(); while (it != callbacks_.end()) { std::optional<zx::vmo> vmo = app->GetMatchingIcd(it->first); if (!vmo) { ++it; } else { it->second(*std::move(vmo)); it = callbacks_.erase(it); } } if (callbacks_.empty()) { app_->RemoveObserver(this); } } // fuchsia::vulkan::loader::Loader impl void LoaderImpl::Get(std::string name, GetCallback callback) { AddCallback(std::move(name), std::move(callback)); } void LoaderImpl::ConnectToDeviceFs(zx::channel channel) { app_->ServeDeviceFs(std::move(channel)); } void LoaderImpl::GetSupportedFeatures(GetSupportedFeaturesCallback callback) { fuchsia::vulkan::loader::Features features = fuchsia::vulkan::loader::Features::CONNECT_TO_DEVICE_FS | fuchsia::vulkan::loader::Features::GET; callback(features); } void LoaderImpl::AddCallback(std::string name, fit::function<void(zx::vmo)> callback) { std::optional<zx::vmo> vmo = app_->GetMatchingIcd(name); if (vmo) { callback(*std::move(vmo)); return; } callbacks_.emplace_back(std::make_pair(std::move(name), std::move(callback))); if (callbacks_.size() == 1) { app_->AddObserver(this); } }
32.75
100
0.689885
1a5413d982d8ec4139e18bfbc2ad0598067a66cb
1,803
hpp
C++
external/bayesopt/include/criteria/criteria_a_opt.hpp
pchrapka/brain-modelling
f232b5a858e45f10b0b0735269010454129ab017
[ "MIT" ]
1
2017-10-13T19:37:52.000Z
2017-10-13T19:37:52.000Z
external/bayesopt/include/criteria/criteria_a_opt.hpp
pchrapka/brain-modelling
f232b5a858e45f10b0b0735269010454129ab017
[ "MIT" ]
null
null
null
external/bayesopt/include/criteria/criteria_a_opt.hpp
pchrapka/brain-modelling
f232b5a858e45f10b0b0735269010454129ab017
[ "MIT" ]
1
2019-11-25T12:22:05.000Z
2019-11-25T12:22:05.000Z
/** \file criteria_a_opt.hpp \brief A-optimality (uncertainty) based criteria */ /* ------------------------------------------------------------------------- This file is part of BayesOpt, an efficient C++ library for Bayesian optimization. Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es> BayesOpt is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BayesOpt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with BayesOpt. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------ */ #ifndef _CRITERIA_A_OPT_HPP_ #define _CRITERIA_A_OPT_HPP_ #include "criteria_functors.hpp" namespace bayesopt { /**\addtogroup CriteriaFunctions */ //@{ /** * \brief Greedy A-Optimality criterion. * Used for learning the function, not to minimize. Some authors * name it I-optimality because it minimizes the error on the * prediction, not on the parameters. */ class GreedyAOptimality: public Criteria { public: virtual ~GreedyAOptimality(){}; void setParameters(const vectord &params) {}; size_t nParameters() {return 0;}; double operator() (const vectord &x) { return -mProc->prediction(x)->getStd(); }; std::string name() {return "cAopt";}; }; //@} } //namespace bayesopt #endif
31.086207
81
0.655019
1a55fef6e547e747fbd7704e3b90f38d875e7382
1,831
cc
C++
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
#include "selfdrive/common/params.h" #include <cstring> static const char* const kUsage = "%s: read|write|read_block params_path key [value]\n"; int main(int argc, const char* argv[]) { if (argc < 4) { printf(kUsage, argv[0]); return 0; } Params params(argv[2]); const char* key = argv[3]; if (strcmp(argv[1], "read") == 0) { char* value; size_t value_size; int result = params.read_db_value(key, &value, &value_size); if (result >= 0) { fprintf(stdout, "Read %zu bytes: ", value_size); fwrite(value, 1, value_size, stdout); fprintf(stdout, "\n"); free(value); } else { fprintf(stderr, "Error reading: %d\n", result); return -1; } } else if (strcmp(argv[1], "write") == 0) { if (argc < 5) { fprintf(stderr, "Error: write value required\n"); return 1; } const char* value = argv[4]; const size_t value_size = strlen(value); int result = params.write_db_value(key, value, value_size); if (result >= 0) { fprintf(stdout, "Wrote %s to %s\n", value, key); } else { fprintf(stderr, "Error writing: %d\n", result); return -1; } } else if (strcmp(argv[1], "read_block") == 0) { char* value; size_t value_size; params.read_db_value_blocking(key, &value, &value_size); fprintf(stdout, "Read %zu bytes: ", value_size); fwrite(value, 1, value_size, stdout); fprintf(stdout, "\n"); free(value); } else { printf(kUsage, argv[0]); return 1; } return 0; } // BUILD: // $ gcc -I$HOME/one selfdrive/common/test_params.c selfdrive/common/params.c selfdrive/common/util.c -o ./test_params // $ seq 0 100000 | xargs -P20 -I{} ./test_params write /data/params DongleId {} && sleep 0.1 & // $ while ./test_params read /data/params DongleId; do sleep 0.05; done
29.063492
118
0.607318
1a5b1fb2d6c86019f43255d5c217e30395d9c968
7,517
cpp
C++
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
/* * MPAOFactory.cpp * * Created on: 21 March 2015 * Author: cyosp */ #include <com/cyosp/mpa/api/rest/v1/MPAOFactory.hpp> namespace mpa_api_rest_v1 { // Initialize static member MPAOFactory * MPAOFactory::mpaofactory = NULL; MPAOFactory * MPAOFactory::getInstance() { if( mpaofactory == NULL ) mpaofactory = new MPAOFactory(); return mpaofactory; } MPAOFactory::MPAOFactory() { //tokenList = new map<string, Token>(); } // Return NULL if URL is bad // GET // /mpa/res/logout // /mpa/res/accounts // /mpa/res/accounts/10 // /mpa/res/accounts/10/categories // /mpa/res/infos // /mpa/res/locales // POST // /mpa/res/users/login // /mpa/res/users/logout // /mpa/res/users/add // /mpa/res/users/0/del?version=0 // /mpa/res/users/10/upd?version=1 // /mpa/res/accounts/add // /mpa/res/accounts/20/del?version=1 // /mpa/res/accounts/20/upd?version=1 // /mpa/res/categories/add // /mpa/res/categories/30/del?version=1 mpa_api_rest_v1::MPAO * MPAOFactory::getMPAO(HttpRequestType requestType, const string& url, const map<string, string>& argvals) { mpa_api_rest_v1::MPAO * ret = NULL; // // Decode URL // ActionType actionType = NONE; vector<std::pair<string, int> > urlPairs; boost::smatch matches; const boost::regex startUrl("^/api/rest/v1(/.*)$"); if( boost::regex_match(url, matches, startUrl) ) { MPA_LOG_TRIVIAL(trace, "Match with start URL"); // Remove start of URL string urlToAnalyse = matches[1]; if( requestType == POST ) { const boost::regex actionTypeRegex("(.*)/([a-z]+)$"); if( boost::regex_match(urlToAnalyse, matches, actionTypeRegex) ) { MPA_LOG_TRIVIAL(trace, "Action type: " + matches[2]); // Remove URL action type urlToAnalyse = matches[1]; if( matches[2] == "login" ) { actionType = LOGIN; // Update URL in order to be compliant to the standard others urlToAnalyse = "/login/0"; } else if( matches[2] == "add" ) { actionType = ADD; // Update URL in order to be compliant to the standard others urlToAnalyse += "/0"; } else if( matches[2] == "del" ) actionType = DELETE; else if( matches[2] == "upd" ) actionType = UPDATE; const boost::regex urlPairRegex("^/([a-z]+)/([0-9]+)(.*)$"); // Fill vector starting by the beginning of URL while( boost::regex_match(urlToAnalyse, matches, urlPairRegex) ) { // Update URL string name = matches[1]; string idString = matches[2]; int id = atoi(idString); urlToAnalyse = matches[3]; MPA_LOG_TRIVIAL(trace, "Name: " + name + ", id: " + idString); urlPairs.push_back(std::pair<string, int>(name, id)); } MPA_LOG_TRIVIAL(trace, "End URL analyze"); } else MPA_LOG_TRIVIAL(trace, "URL doesn't match action type"); } else { MPA_LOG_TRIVIAL(trace, "URL to analyze: " + urlToAnalyse); // Manage URL like: GET /mpa/res/accounts const boost::regex urlStartRegex("^/([a-z]+)(.*)$"); while( boost::regex_match(urlToAnalyse, matches, urlStartRegex) ) { MPA_LOG_TRIVIAL(trace, "URL start match"); // Set values string name = matches[1]; string idString = ""; int id = 0; urlToAnalyse = matches[2]; MPA_LOG_TRIVIAL(trace, "New URL to analyze: " + urlToAnalyse); // Manage URL like: GET /mpa/res/accounts/10 const boost::regex urlIdRegex("^/([0-9]+)(.*)$"); // Fill vector starting by beginning of URL if( boost::regex_match(urlToAnalyse, matches, urlIdRegex) ) { MPA_LOG_TRIVIAL(trace, "URL ID match"); idString = matches[1]; id = atoi(idString); urlToAnalyse = matches[2]; } MPA_LOG_TRIVIAL(trace, "Name: " + name + ", id: " + idString); urlPairs.push_back(std::pair<string, int>(name, id)); } } // Manage case where URL doesn't match with an expected one if( urlPairs.size() > 0 ) { int lastPosition = urlPairs.size() - 1; string lastIdentifier = urlPairs[lastPosition].first; MPA_LOG_TRIVIAL(trace, "Last identifier: " + lastIdentifier); if( lastIdentifier == mpa_api_rest_v1::Login::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Login(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Logout::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Logout(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Account::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Account(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::User::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::User(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Info::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Info(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Locale::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Locale(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Category::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Category(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Provider::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Provider(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Operation::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Operation(requestType, actionType, argvals, urlPairs); } else MPA_LOG_TRIVIAL(info, "Bad URL"); } else MPA_LOG_TRIVIAL(trace, "Doesn't match with POST start URL"); return ret; } map<string, string> & MPAOFactory::getTokenList() { return tokenList; } }
37.585
101
0.518159
1a5cad6550b20dbdefcd13178dd1e94768258ae2
3,141
cc
C++
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
67
2018-03-01T06:56:49.000Z
2022-03-08T18:44:47.000Z
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
93
2018-12-07T17:38:04.000Z
2022-03-31T10:04:51.000Z
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
33
2018-02-28T17:06:19.000Z
2022-01-20T12:12:27.000Z
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include <algorithm> #include <array> #include <string> #include <vector> #include "atlas/functionspace/EdgeColumns.h" #include "atlas/functionspace/NodeColumns.h" #include "atlas/grid/StructuredGrid.h" #include "atlas/mesh/HybridElements.h" #include "atlas/mesh/Mesh.h" #include "atlas/mesh/Nodes.h" #include "atlas/meshgenerator.h" #include "atlas/parallel/mpi/mpi.h" #include "tests/AtlasTestEnvironment.h" using namespace atlas::functionspace; using namespace atlas::grid; using namespace atlas::meshgenerator; namespace atlas { namespace test { template <typename Container> Container reversed(const Container& a) { Container a_reversed = a; std::reverse(a_reversed.begin(), a_reversed.end()); return a_reversed; } static std::array<bool, 2> false_true{false, true}; //----------------------------------------------------------------------------- CASE("halo nodes") { Grid grid("O8"); std::vector<int> halos{0, 1, 2, 3, 4}; std::vector<int> nodes{560, 592, 624, 656, 688}; for (bool reduce : false_true) { SECTION(std::string(reduce ? "reduced" : "increased")) { Mesh mesh = StructuredMeshGenerator().generate(grid); EXPECT(mesh.nodes().size() == nodes[0]); for (int h : (reduce ? reversed(halos) : halos)) { NodeColumns fs(mesh, option::halo(h)); if (mpi::comm().size() == 1) { EXPECT(fs.nb_nodes() == nodes[h]); } } } } } //----------------------------------------------------------------------------- CASE("halo edges") { Grid grid("O8"); std::vector<int> halos{0, 1, 2, 3, 4}; std::vector<int> edges{1559, 1649, 1739, 1829, 1919}; for (bool reduce : false_true) { for (bool with_pole_edges : false_true) { int pole_edges = with_pole_edges ? StructuredGrid(grid).nx().front() : 0; SECTION(std::string(reduce ? "reduced " : "increased ") + std::string(with_pole_edges ? "with_pole_edges" : "without_pole_edges")) { Mesh mesh = StructuredMeshGenerator().generate(grid); EXPECT(mesh.edges().size() == 0); for (int h : (reduce ? reversed(halos) : halos)) { EdgeColumns fs(mesh, option::halo(h) | option::pole_edges(with_pole_edges)); if (mpi::comm().size() == 1) { EXPECT(fs.nb_edges() == edges[h] + pole_edges); } } } } } } //----------------------------------------------------------------------------- } // namespace test } // namespace atlas int main(int argc, char** argv) { return atlas::test::run(argc, argv); }
32.05102
96
0.559058
1a61d1a6a96afadc80416f46aaf1e217616dc71f
4,176
cpp
C++
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: SPK_PLLineRenderer.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLMath/Math.h> // On Mac OS X I'am getting the compiler error "error: ‘isfinite’ was not declared in this scope" when not including this header, first... I'am not sure what SPARK is changing in order to cause this error... #include <PLCore/PLCore.h> PL_WARNING_PUSH PL_WARNING_DISABLE(4530) // "warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc" // [HACK] There are missing forward declarations within the SPARK headers... namespace SPK { class Group; } #include <Core/SPK_Group.h> PL_WARNING_POP #include "SPARK_PL/RenderingAPIs/PixelLight/SPK_PLBuffer.h" #include "SPARK_PL/RenderingAPIs/PixelLight/SPK_PLLineRenderer.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace SPARK_PL { //[-------------------------------------------------------] //[ Protected definitions ] //[-------------------------------------------------------] const std::string SPK_PLLineRenderer::PLBufferName("SPK_PLLineRenderer_Buffer"); //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Destructor of SPK_PLLineRenderer */ SPK_PLLineRenderer::~SPK_PLLineRenderer() { } //[-------------------------------------------------------] //[ Public virtual SPK::BufferHandler functions ] //[-------------------------------------------------------] void SPK_PLLineRenderer::createBuffers(const SPK::Group &group) { // Create the SPK_PLBuffer instance m_pSPK_PLBuffer = static_cast<SPK_PLBuffer*>(group.createBuffer(PLBufferName, PLBufferCreator(GetPLRenderer(), 14, 0, SPK::TEXTURE_NONE), 0U, false)); } void SPK_PLLineRenderer::destroyBuffers(const SPK::Group &group) { group.destroyBuffer(PLBufferName); } //[-------------------------------------------------------] //[ Protected functions ] //[-------------------------------------------------------] /** * @brief * Constructor of SPK_PLLineRenderer */ SPK_PLLineRenderer::SPK_PLLineRenderer(PLRenderer::Renderer &cRenderer, float fLength, float fWidth) : SPK_PLRenderer(cRenderer), SPK::LineRendererInterface(fLength, fWidth), m_pSPK_PLBuffer(nullptr) { } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // SPARK_PL
42.612245
232
0.534722
1a680e179daa526101317eb8f2d21d4435439a12
1,803
cpp
C++
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
1
2020-07-11T12:39:03.000Z
2020-07-11T12:39:03.000Z
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
null
null
null
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
null
null
null
#include "include/fbr.h" #include "Player.h" using namespace std; using namespace fbr; int main(){ Player *p = new Player(); BaseTask *printHP = new TaskArgs<>(&Player::printHp, p); TaskArgs<int> *taskArg = new TaskArgs<int>(&Player::addHp, p); int a = 20; taskArg->setArgs(a); TaskArgs<int, bool> *test = new TaskArgs<int, bool>(&Player::damage, p); int b = 5; bool isMagic=false; test->setArgs(b, isMagic); TaskArgsCopy<int, int, int> *move = new TaskArgsCopy<int, int, int>(&Player::move, p); int c = 0; move->setArgs(54, c, std::thread::hardware_concurrency()); Task *inputtask = new Task(&Player::taskInput, p); inputtask->setReuseable(true); Scheduler *scheduler = new Scheduler(0,4, taskArg,true,true); if (scheduler->getIsConstructed() == false){ return 0; } fbr::con_cout << "All workers ready! " << fbr::endl; Task *update = new Task(&Player::update, p); //wake up main thread Task *endTask = new Task(&Scheduler::wakeUpMain); Task *longTask = new Task(&Player::longTask, p); //run all task unsyncronized //example with vector //vector<BaseTask*> allTasks = { printHP, move, update,longTask }; //scheduler->runTasks(allTasks, priority::low); //example with variadic function Scheduler::runTasks(priority::low, 4, printHP, move, update, longTask); //scheduler->waitAllFibersFree(); //Scheduler::waitForCounter(0, inputtask); //Scheduler::waitForCounter(0, inputtask); //puts main thread to wait and doesn't cunsume cpu time //wakes up when endTask is run Scheduler::waitMain(); scheduler->close(); //system("pause"); //delete scheduler and display msg delete scheduler; //fbr::log << "here" << Log::endl; fbr::con_cout << "Scheduler deleted" << fbr::endl; SpinUntil *timer = new SpinUntil(); timer->wait(2); delete timer; }
25.757143
87
0.684415
1a6885151eed7a9c4445dd976ea5a82ec986cb63
898
cpp
C++
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include <utility> #include "continued_fraction.h" #include "largeint.h" using uInt = std::uint_fast32_t; using LInt = Euler::LargeInt<uInt>; using Fraction = std::pair<LInt, LInt>; // first: 分子, second: 分母 using namespace Euler::ContinuedFraction; int main(void) { constexpr uInt DEPTH_BOUND = 100; // 項目は1始まりで数える(1項目, 2項目, ...) Fraction frac = std::make_pair(1, 1); if (DEPTH_BOUND <= 1) { frac.first = napiers_term_at(0); } else { frac.second = napiers_term_at(DEPTH_BOUND - 1); } // 地道に分数計算 for (uInt i = 2; i <= DEPTH_BOUND; i++) { const uInt a = napiers_term_at(DEPTH_BOUND - i); frac.first += frac.second * a; if (i == DEPTH_BOUND) { continue; } // 1/(fr.f/fr.s) => fr.s/fr.f std::swap(frac.first, frac.second); } std::cout << "Euler065: " << frac.first.digits_sum() << std::endl; return 0; }
23.631579
68
0.635857
1a69b234e05419fabf8a71196bb209069b6d6387
3,385
cpp
C++
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
/***************************************************************************** XFadeShape.cpp Author: Laurent de Soras, 2017 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Approx.h" #include "fstb/fnc.h" #include "fstb/ToolsSimd.h" #include "mfx/dsp/wnd/XFadeShape.h" #include <cassert> namespace mfx { namespace dsp { namespace wnd { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void XFadeShape::set_duration (double duration, float fade_ratio) { assert (duration > 0); assert (fade_ratio > 0); assert (fade_ratio <= 1); if (duration != _duration || fade_ratio != _fade_ratio) { _duration = duration; _fade_ratio = fade_ratio; if (is_ready ()) { make_shape (); } } } void XFadeShape::set_sample_freq (double sample_freq) { assert (sample_freq > 0); _sample_freq = sample_freq; make_shape (); } bool XFadeShape::is_ready () const { return (_sample_freq > 0); } int XFadeShape::get_len () const { assert (_len > 0); return _len; } const float * XFadeShape::use_shape () const { assert (_len > 0); return (&_shape [0]); } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void XFadeShape::make_shape () { const int len = fstb::round_int (_sample_freq * _duration); if (len != _len) { _len = len; // +3 because we could read (or write) a full vector from the last // position const int len_margin = len + 3; _shape.resize (len_margin); #if 1 const float p = 0.25f / _fade_ratio; fstb::ToolsSimd::VectF32 x; fstb::ToolsSimd::VectF32 step; fstb::ToolsSimd::start_lerp (x, step, -p, p, len); const auto half = fstb::ToolsSimd::set1_f32 ( 0.5f ); const auto mi = fstb::ToolsSimd::set1_f32 (-0.25f); const auto ma = fstb::ToolsSimd::set1_f32 (+0.25f); for (int pos = 0; pos < len; pos += 4) { auto xx = x; xx = fstb::ToolsSimd::min_f32 (xx, ma); xx = fstb::ToolsSimd::max_f32 (xx, mi); auto v = fstb::Approx::sin_nick_2pi (xx); v *= half; v += half; fstb::ToolsSimd::store_f32 (&_shape [pos], v); x += step; } #else // Reference implementation const float p = 0.25f / _fade_ratio; const float dif = p * 2; const float step = dif * fstb::rcp_uint <float> (len); const float x = -p; for (int pos = 0; pos < len; ++pos) { const float xx = fstb::limit (x, -0.25f, +0.25f); const float v = fstb::Approx::sin_nick_2pi (xx) * 0.5f + 0.5f; _shape [pos] = v; x += step; } #endif } } } // namespace wnd } // namespace dsp } // namespace mfx /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
19.454023
78
0.534417
1a6e268dde28804830c7cc3dcdd417023249b707
93
cpp
C++
Source/Nova/Game/NovaDestination.cpp
Sabrave/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
17
2022-02-19T05:39:33.000Z
2022-03-01T01:56:19.000Z
Source/Nova/Game/NovaDestination.cpp
Frank1eJohnson/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
null
null
null
Source/Nova/Game/NovaDestination.cpp
Frank1eJohnson/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
null
null
null
// Nova project - Gwennaël Arbona #include "NovaDestination.h" #include "Nova/Nova.h"
15.5
34
0.688172
1a6f4a155ba3def3a2ad336ba461a65aed37ae45
5,536
cpp
C++
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
#include"core.h" Collision::Collision() {} void Collision::init(std::string filename) { std::ifstream inFile; this->center_point = glm::vec2(22.5, 31.0); this->player_position.push_back(glm::vec4(0, 0, 0, 0)); this->player_position.push_back(glm::vec4(0, 0, 0, 0)); std::vector<unsigned int> vertex_indices, normal_indices; std::vector<glm::vec3> temp_v; std::vector<glm::vec3> temp_vn; bool read = true; inFile.open(filename); if(!inFile) { std::cout << "Can't open collision file " << filename << std::endl; exit(1); } // Read floor std::string ch; while(inFile >> ch && read) { if(ch == "v") { glm::vec3 vertex; inFile >> vertex.x; inFile >> vertex.y; inFile >> vertex.z; temp_v.push_back(vertex); } else if (ch == "o") { inFile >> ch; int s1 = ch.find("_"); if(ch.substr(0, s1) != "floor") { read = false; } } else if (ch == "vn") { glm::vec3 normal; inFile >> normal.x; inFile >> normal.y; inFile >> normal.z; temp_vn.push_back(normal); } else if (ch == "f") { unsigned int vertex_index[3], normal_index[3]; //unsigned int uv_index[3] for(int i = 0; i < 3; i++) { inFile >> ch; int s1 = ch.find("/"); vertex_index[i] = std::stoi(ch.substr(0, s1)); std::string ch2 = ch.substr(s1+1, ch.length()); int s2 = ch2.find("/"); /*if(s2 > 0) { uv_index[i] = std::stoi(ch.substr(s1, s2)); }*/ normal_index[i] = std::stoi(ch2.substr(s2+1, ch.length())); } vertex_indices.push_back(vertex_index[0]); vertex_indices.push_back(vertex_index[1]); vertex_indices.push_back(vertex_index[2]); normal_indices.push_back(normal_index[0]); normal_indices.push_back(normal_index[1]); normal_indices.push_back(normal_index[2]); } } // Done reading floor // Now processing floor indices for(unsigned int i=0; i < vertex_indices.size(); i++) { unsigned int vertex_index = vertex_indices[i]; unsigned int normal_index = normal_indices[i]; glm::vec3 v = temp_v[vertex_index-1]; this->floor_verts.push_back(v); glm::vec3 normal = temp_vn[normal_index-1]; this->floor_norms.push_back(normal); } inFile.close(); std::cout << "Collision map intialized" << std::endl; } bool Collision::on_floor(float x, float y) { for(unsigned int i = 0; i < this->floor_verts.size(); i+=3) { glm::vec2 p1, p2, p3; p1.x = this->floor_verts[i].x; p1.y = this->floor_verts[i].z; p2.x = this->floor_verts[i+1].x; p2.y = this->floor_verts[i+1].z; p3.x = this->floor_verts[i+2].x; p3.y = this->floor_verts[i+2].z; // Barycentric coordinates float alpha = ((p2.y - p3.y) * (x - p3.x) + (p3.x - p2.x) * (y - p3.y)) / ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y)); float beta = ((p3.y - p1.y) * (x - p3.x) + (p1.x - p3.x) * (y - p3.y)) / ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y)); float gamma = 1.0f - alpha - beta; if(alpha > 0.0 && beta > 0.0 && gamma > 0.0) { return true; } } return false; } bool Collision::wall_hit_x(float x, float y) { if(x > 10 && x < 34 && y > 18 && y < 45) { return false; } return !this->on_floor(x, y); } bool Collision::wall_hit_y(float x, float y) { if(x > 10 && x < 34 && y > 18 && y < 45) { return false; } return !this->on_floor(x, y); } float Collision::distance(glm::vec2 p1, glm::vec2 p2) { float distance = sqrt( pow(p1.x-p2.x, 2) + pow(p1.y-p2.y, 2) ); return distance; } float Collision::player_distance(unsigned int id) { glm::vec4 player = this->player_position[id]; glm::vec4 enemy = this->get_enemy_pos(id); // Calculate enemy ray float ray_x = enemy.x + (sin(enemy.w*PI/180) * CHAR_MOVE_SPEED); float ray_y = enemy.y + (cos(enemy.w*PI/180) * CHAR_MOVE_SPEED); float distance = sqrt( pow(player.x-ray_x, 2) + pow(player.y-ray_y, 2) + pow(player.z-enemy.z, 2) ); return distance; } bool Collision::player_collision(unsigned int player) { // Set to true if the player collided with enemy // Used to set velocities on knock-back for character if(this->player_distance(player) < 1.0) { return true; } return false; } // Method for players to report their position void Collision::report(unsigned int id, float x, float y, float z, float angle) { this->player_position[id].x = x; this->player_position[id].y = y; this->player_position[id].z = z; this->player_position[id].w = angle; } glm::vec4 Collision::get_enemy_pos(unsigned int player) { unsigned int enemy; if(player == 0) { enemy = 1; } else { enemy = 0; } return this->player_position[enemy]; } bool Collision::in_center(unsigned int id) { float distance = this->distance(glm::vec2(this->player_position[id].x, this->player_position[id].y), this->center_point); if(distance < 8.5) { return true; } return false; }
28.536082
144
0.53974
2b2dd61a9b564be843b5a4a768fe43e64162ec90
6,944
hpp
C++
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
1
2021-03-29T06:09:19.000Z
2021-03-29T06:09:19.000Z
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
null
null
null
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
null
null
null
/* ** Author: Samuel R. Blackburn ** Internet: wfc@pobox.com ** ** Copyright, 1995-2019, Samuel R. Blackburn ** ** "You can get credit for something or get it done, but not both." ** Dr. Richard Garwin ** ** BSD License follows. ** ** 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 WFC 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. ** ** $Workfile: ServiceConfiguration.hpp $ ** $Revision: 12 $ ** $Modtime: 6/26/01 11:07a $ */ /* SPDX-License-Identifier: BSD-2-Clause */ #if ! defined( SERVICE_CONFIGURATION_CLASS_HEADER ) #define SERVICE_CONFIGURATION_CLASS_HEADER class CServiceConfigurationA { protected: DWORD m_TypeOfService{ 0 }; DWORD m_WhenToStart{ 0 }; DWORD m_ErrorControl{ 0 }; DWORD m_Tag{ 0 }; std::string m_NameOfExecutableFile; std::string m_LoadOrderGroup; std::string m_StartName; std::string m_DisplayName; std::vector<std::string> m_Dependencies; public: CServiceConfigurationA() noexcept; explicit CServiceConfigurationA( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; explicit CServiceConfigurationA( _In_ _QUERY_SERVICE_CONFIGA const * source ) noexcept; explicit CServiceConfigurationA( _In_ CServiceConfigurationA const& source ) noexcept; explicit CServiceConfigurationA( _In_ CServiceConfigurationA const * source ) noexcept; virtual ~CServiceConfigurationA() = default; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGA const * source ) noexcept; virtual void Copy( _In_ CServiceConfigurationA const& source ) noexcept; virtual void Copy( _In_ CServiceConfigurationA const * source ) noexcept; virtual void Empty( void ) noexcept; virtual void GetDependencies( _Out_ std::vector<std::string>& dependencies ) const noexcept; virtual void GetDisplayName( _Out_ std::string& display_name ) const noexcept; virtual _Check_return_ DWORD GetErrorControl( void ) const noexcept; virtual void GetLoadOrderGroup( _Out_ std::string& load_order_group ) const noexcept; virtual void GetNameOfExecutableFile( _Out_ std::string& name_of_executable ) const noexcept; virtual void GetStartName( _Out_ std::string& start_name ) const noexcept; virtual _Check_return_ DWORD GetTag( void ) const noexcept; virtual _Check_return_ DWORD GetTypeOfService( void ) const noexcept; virtual _Check_return_ DWORD GetWhenToStart( void ) const noexcept; virtual _Check_return_ CServiceConfigurationA& operator=( _In_ CServiceConfigurationA const& source ) noexcept; virtual _Check_return_ CServiceConfigurationA& operator=( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; #if defined( _DEBUG ) && ! defined( WFC_NO_DUMPING ) virtual void Dump( CDumpContext& dump_context ) const; #endif // _DEBUG }; class CServiceConfigurationW { protected: DWORD m_TypeOfService{0}; DWORD m_WhenToStart{0}; DWORD m_ErrorControl{0}; DWORD m_Tag{0}; std::wstring m_NameOfExecutableFile; std::wstring m_LoadOrderGroup; std::wstring m_StartName; std::wstring m_DisplayName; std::vector<std::wstring> m_Dependencies; public: CServiceConfigurationW() noexcept; explicit CServiceConfigurationW( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; explicit CServiceConfigurationW( _In_ _QUERY_SERVICE_CONFIGW const * source ) noexcept; explicit CServiceConfigurationW( _In_ CServiceConfigurationW const& source ) noexcept; explicit CServiceConfigurationW( _In_ CServiceConfigurationW const * source ) noexcept; virtual ~CServiceConfigurationW(); virtual void Copy( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGW const * source ) noexcept; virtual void Copy( _In_ CServiceConfigurationW const& source ) noexcept; virtual void Copy( _In_ CServiceConfigurationW const * source ) noexcept; virtual void Empty( void ) noexcept; virtual void GetDependencies( _Out_ std::vector<std::wstring>& dependencies ) const noexcept; virtual void GetDisplayName( _Out_ std::wstring& display_name ) const noexcept; inline constexpr _Check_return_ DWORD GetErrorControl(void) const noexcept { return(m_ErrorControl); } virtual void GetLoadOrderGroup( _Out_ std::wstring& load_order_group ) const noexcept; virtual void GetNameOfExecutableFile( _Out_ std::wstring& name_of_executable ) const noexcept; virtual void GetStartName( _Out_ std::wstring& start_name ) const noexcept; inline constexpr _Check_return_ DWORD GetTag(void) const noexcept { return(m_Tag); } inline constexpr _Check_return_ DWORD GetTypeOfService(void) const noexcept { return(m_TypeOfService); } inline constexpr _Check_return_ DWORD GetWhenToStart(void) const noexcept { return(m_WhenToStart); } virtual _Check_return_ CServiceConfigurationW& operator=( _In_ CServiceConfigurationW const& source ) noexcept; virtual _Check_return_ CServiceConfigurationW& operator=( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; #if defined( _DEBUG ) && ! defined( WFC_NO_DUMPING ) virtual void Dump( CDumpContext& dump_context ) const; #endif // _DEBUG }; #if defined( UNICODE ) #define CServiceConfiguration CServiceConfigurationW #else #define CServiceConfiguration CServiceConfigurationA #endif // UNICODE #endif // SERVICE_CONFIGURATION_CLASS_HEADER
45.986755
117
0.751296
2b303ea879083312a7aa10e39830d4871b6b87d2
14,571
cpp
C++
lib/sram/src/sram.cpp
sinanislekdemir/MedlarII
ca5923c7408aae6f71b8e9b79a569e4a8b9da5e8
[ "MIT" ]
2
2021-03-14T07:29:22.000Z
2021-03-15T16:02:14.000Z
lib/sram/src/sram.cpp
sinanislekdemir/MedlarII
ca5923c7408aae6f71b8e9b79a569e4a8b9da5e8
[ "MIT" ]
null
null
null
lib/sram/src/sram.cpp
sinanislekdemir/MedlarII
ca5923c7408aae6f71b8e9b79a569e4a8b9da5e8
[ "MIT" ]
null
null
null
#include "sram.h" #include <Arduino.h> #include <freemem.h> #include <mdisplay.h> #include <stdint.h> SRam::SRam() { } SRam::~SRam() { this->close(); } char *dtoc(double d) { char *value = reinterpret_cast<char *>(&d); return value; } double ctod(char *data) { double resp = *reinterpret_cast<double *const>(data); return resp; } uint8_t argc(char *text, char delimiter) { // return argument count given in a text bool string_literal = false; uint8_t count = 1; for (uint8_t i = 0; i < strlen(text); i++) { if (text[i] == '"') { string_literal = !string_literal; } if (!string_literal && text[i] == '#') { break; } if (!string_literal && text[i] == delimiter) { count += 1; } } return count; } int extract_size(char *text, char delimiter, uint8_t part) { int result = 0; int n = strlen(text); int counter = 0; bool ignore = false; for (uint8_t i = 0; i < n; i++) { if (text[i] == '"') { ignore = !ignore; } if (text[i] != delimiter) { if (counter == part) { result++; } } else { if (ignore && counter == part) { result++; } } if (text[i] == delimiter && !ignore) { counter++; } } return result; } // strtok should do fine but I need to keep "..." intact int extract(char *text, char delimiter, uint8_t part, char *back) { int n = strlen(text); int j; j = 0; int counter = 0; bool ignore = false; for (uint8_t i = 0; i < n; i++) { if (text[i] == '"') { ignore = !ignore; } if (text[i] != delimiter) { if (counter == part) { back[j++] = text[i]; } } else { if (ignore && counter == part) { back[j++] = text[i]; } } if (text[i] == delimiter && !ignore) { counter++; } } back[j] = '\0'; return 0; } int rest(char *text, uint8_t pos, char *back) { if (pos >= strlen(text)) { return 0; } uint8_t j = 0; for (uint8_t i = pos; i < strlen(text); i++) { back[j++] = text[i]; } back[j] = '\0'; return j; } void SRam::open(const char *filename) { if (SD.exists(filename)) { bool d = SD.remove(filename); if (!d) { Serial.println("Failed to delete"); } } // FILE_WRITE != O_RDWR this->ram = SD.open(filename, FILE_WRITE); this->ram.close(); this->ram = SD.open(filename, O_RDWR); this->filename = (char *)malloc(strlen(filename) + 1); memcpy(this->filename, filename, strlen(filename)); this->filename[strlen(filename)] = '\0'; if (!this->ram) { return; } this->isOpen = true; } void SRam::close() { if (this->isOpen) { free(this->filename); this->ram.flush(); this->ram.close(); } } int SRam::ensureOpen() { if (this->filename == NULL || strlen(this->filename) == 0) { return -1; } if (!this->ram) { this->ram = SD.open(this->filename, O_RDWR); if (!this->ram) { return -1; } } return 0; } File SRam::get_file(memoryBlockHeader *m) { File r; if (!m || m->type != TYPE_FILE) { return r; } char *fname = (char *)malloc(MAX_FILE_PATH); memset(fname, '\0', MAX_FILE_PATH); this->read_all(m->varname, m->pid, fname, true); if (!SD.exists(fname)) { r = SD.open(fname, FILE_WRITE); r.close(); } r = SD.open(fname, O_RDWR); r.seek(0); free(fname); return r; } memoryBlockHeader *SRam::find_variable(char *name, uint16_t pid) { // Idea! // PID | VARNAME | USED | POSITION | SIZE | VARIABLE-DATA | PID | VARNAME | // USED... Header followed by the value. then the next variable header. memoryBlockHeader *variable = (memoryBlockHeader *)malloc(HeaderSize); if (name[0] == '$') { variable->exists = true; variable->pid = pid; variable->position = 0; variable->size = sizeof(double); variable->type = TYPE_DOUBLE; return variable; } uint32_t pos = 0; variable->exists = 0; this->ensureOpen(); this->ram.seek(0); while (this->ram.available()) { this->ram.readBytes((char *)(variable), HeaderSize); if (!variable->exists || variable->pid != pid || strcmp(variable->varname, name) != 0) { pos += HeaderSize + variable->size; // fast forward to the next variable position bool seek = this->ram.seek(pos); if (!seek) { break; } continue; } variable->position = pos + HeaderSize; return variable; } free(variable); return NULL; } void SRam::allocate_variable(char *name, uint16_t pid, uint16_t variableSize, uint8_t variable_type) { memoryBlockHeader variable; if (this->ensureOpen() == -1) { Serial.println("File not open"); return; } this->ram.seek(this->ram.size()); strcpy(variable.varname, name); variable.exists = 1; if (variable_type == TYPE_FILE) { variable.size = MAX_FILE_PATH; } else { variable.size = variableSize; } variable.pid = pid; variable.type = variable_type; this->ram.write((char *)(&variable), HeaderSize); this->ram.flush(); // allocate extra space for the variable for (uint16_t i = 0; i < variable.size; i++) { this->ram.write("\0", 1); if (i % 128 == 0) { this->ram.flush(); } } this->ram.flush(); } void SRam::delete_variable(char *name, uint16_t pid) { memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return; } uint32_t location = variable->position - HeaderSize + 1; variable->exists = 0; this->ram.seek(location); this->ram.write((char *)(variable), HeaderSize); this->ram.flush(); free(variable); } uint16_t SRam::read(char *name, uint16_t pid, uint32_t pos, char *buffer, uint16_t size, bool raw) { memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return 0; } if (variable->type == TYPE_FILE && !raw) { File f = this->get_file(variable); if (!f) { free(variable); return 0; } if (pos > f.size()) { free(variable); return 0; } f.seek(pos); if (f.available() == 0) { free(variable); return 0; } uint16_t size_read = f.readBytes(buffer, size); f.close(); free(variable); return size_read; } if (pos > variable->size) { free(variable); return 0; } if (pos + size > variable->size) { size = variable->size - pos; } bool seek_check = this->ram.seek(variable->position + pos); if (!seek_check) { free(variable); return 0; } free(variable); return this->ram.readBytes(buffer, size); } uint16_t SRam::read_all(char *name, uint16_t pid, char *buffer, bool raw) { memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return 0; } uint16_t r = this->read(name, pid, 0, buffer, variable->size, raw); free(variable); return r; } uint16_t SRam::write(char *name, uint16_t pid, uint32_t pos, char *data, uint16_t size, bool raw) { if (name[0] == '$') { char rest[2] = "\0"; strcpy(rest, name + 1); int index = atoi(rest); this->registers[index] = ctod(data); return sizeof(double); } memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return -1; } if (variable->type == TYPE_FILE && !raw) { File f = this->get_file(variable); if (!f) { free(variable); return 0; } if (pos > f.size()) { pos = f.size(); } f.seek(pos); uint16_t size_write = f.write(data); f.close(); free(variable); return size_write; } if (size + pos > variable->size) { free(variable); return -2; } bool seek_check = this->ram.seek(variable->position + pos); if (!seek_check) { free(variable); return -3; } free(variable); uint16_t size_w = this->ram.write(data, size); this->ram.flush(); return size_w; } // sinan int SRam::get_var_size(char *text, uint16_t pid) { if (text[0] == '"' && text[strlen(text) - 1] == '"') { return strlen(text); } if (strlen(text) > 0 && isdigit(text[0])) { return sizeof(double); } if (text[0] == '$') { return sizeof(double); } memoryBlockHeader *m; char *shortened = (char *)malloc(strlen(text)); if (strstr(text, "[") != NULL && strstr(text, "]") != NULL) { memset(shortened, '\0', strlen(text)); extract(text, '[', 0, shortened); m = this->find_variable(shortened, pid); } else { m = this->find_variable(text, pid); } if (m == NULL) { free(shortened); return -1; } if (m->type == TYPE_NUM) { free(m); free(shortened); return sizeof(double); } uint16_t read_size = m->size; if (strstr(text, "[") != NULL && strstr(text, "]") != NULL) { uint32_t end = this->get_end(text, pid); free(shortened); free(m); return end; } if (m->type == TYPE_FILE) { File f = this->get_file(m); if (!f) { return -1; } uint32_t s = f.size(); f.close(); free(shortened); free(m); return s; } free(shortened); free(m); return read_size; } uint32_t SRam::get_start(char *text, uint16_t pid) { char temp[16]; char back[4]; int state = 0; int p = 0; for (uint8_t i = 0; i < strlen(text); i++) { if (text[i] == ':' || text[i] == ']') { break; } if (state == 1) { temp[p++] = text[i]; temp[p] = '\0'; } if (text[i] == '[') { state = 1; } } memset(back, 0, 4); this->get_var(temp, pid, back); return ctod(back); } uint32_t SRam::get_end(char *text, uint16_t pid) { char temp[16]; char back[4]; int state = 0; int p = 0; for (uint8_t i = 0; i < strlen(text); i++) { if (text[i] == ']') { break; } if (state == 1) { temp[p++] = text[i]; temp[p] = '\0'; } if (text[i] == ':') { state = 1; } } memset(back, 0, 4); this->get_var(temp, pid, back); return ctod(back); } /** * @brief Get variable from memory file * * @param text - variable name * @param pid - process id * @param back - back buffer * @return int - return 0 for text, 1 for number, -1 for no match */ int SRam::get_var(char *text, uint16_t pid, char *back) { if (back == NULL) { return 0; } if (text[0] == '$') { char rest[2] = "\0"; strcpy(rest, text + 1); int index = atoi(rest); memcpy(back, dtoc(this->registers[index]), sizeof(double)); return TYPE_NUM; } if (text[0] == '"' && text[strlen(text) - 1] == '"') { uint8_t p = 0; for (unsigned int i = 1; i < strlen(text) - 1; i++) { back[p++] = text[i]; } return TYPE_BYTE; } if (strlen(text) > 0 && isdigit(text[0])) { double x = atof(text); memcpy(back, dtoc(x), sizeof(double)); return TYPE_NUM; } if (strcmp(text, "millis") == 0) { double x = millis(); memset(back, 0, 4); memcpy(back, dtoc(x), sizeof(double)); return TYPE_NUM; } char *shortened = (char *)malloc(strlen(text)); bool partial = false; memset(shortened, 0, strlen(text)); memoryBlockHeader *m; if (strstr(text, "[") != NULL && strstr(text, "]") != NULL) { extract(text, '[', 0, shortened); partial = true; m = this->find_variable(shortened, pid); } else { m = this->find_variable(text, pid); } if (m == NULL) { free(shortened); return -1; } uint16_t from = 0; uint16_t read_size = m->size; if (partial) { from = uint16_t(this->get_start(text, pid)); read_size = uint16_t(this->get_end(text, pid)); this->read(shortened, pid, from, back, read_size, false); } else { this->read(text, pid, from, back, read_size, false); } free(shortened); int ret = m->type; free(m); return ret; } void SRam::dump() { // Idea! // PID | VARNAME | USED | POSITION | SIZE | VARIABLE-DATA | PID | VARNAME | // USED... Header followed by the value. then the next variable header. memoryBlockHeader variable; this->ram.seek(0); if (this->ensureOpen() == -1) { Serial.println("Memory is not accessable"); } Serial.print("Filename: "); Serial.println(this->filename); Serial.print("Memory size:"); Serial.print(this->ram.size()); Serial.println(" bytes"); while (this->ram.readBytes((char *)(&variable), HeaderSize) > 0) { Serial.print("Variable name: "); Serial.println(variable.varname); Serial.print("Variable exists: "); Serial.println(variable.exists); Serial.print("Variable size: "); Serial.println(variable.size); Serial.print("Variable type: "); Serial.println(variable.type); this->ram.seek(this->ram.position() + variable.size); } }
21.747761
100
0.49372
2b3437df2442f79b844247273b091143e02b3108
3,341
cpp
C++
Game.cpp
JankoDedic/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
1
2018-02-28T14:21:14.000Z
2018-02-28T14:21:14.000Z
Game.cpp
djanko1337/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
null
null
null
Game.cpp
djanko1337/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
1
2020-07-13T08:56:55.000Z
2020-07-13T08:56:55.000Z
#include "Game.hpp" #include "RectangleFunctions.hpp" #include "Renderer.hpp" namespace TappyPlane { using namespace SDLW::Video; using namespace SDLW::Events; constexpr auto backgroundSpritesheetHandle = "background"; constexpr auto backgroundBounds = canvasBounds; constexpr auto backgroundScrollSpeed = 0.5f; constexpr auto groundSpritesheetHandle = "ground"; constexpr Rectangle groundBounds{0, canvasBounds.height() - 270, canvasBounds.width(), 270}; constexpr auto groundScrollSpeed = 2.0f; constexpr int spikePairDistance{420}; constexpr int spikesScrollSpeed{5}; constexpr auto getReadySpritesheetHandle = "getReady"; constexpr Rectangle getReadyBounds{canvasBounds.width() / 2 - 907 / 2, canvasBounds.height() / 2 - 163 / 2, 907, 163}; constexpr auto gameOverSpritesheetHandle = "gameOver"; constexpr Rectangle gameOverBounds{canvasBounds.width() / 2 - 934 / 2, canvasBounds.height() / 2 - 176 / 2, 934, 176}; Game::Game() : mGameState(State::GetReady) , mBackground(backgroundSpritesheetHandle, backgroundBounds, backgroundScrollSpeed) , mGround(groundSpritesheetHandle, groundBounds, groundScrollSpeed) , mSpikes(spikePairDistance, spikesScrollSpeed) , mGetReadySprite(getReadySpritesheetHandle, getReadyBounds) , mGameOverSprite(gameOverSpritesheetHandle, gameOverBounds) { } void Game::handleEvent(const Event& event) noexcept { if (event.type() == Event::Type::MouseButtonDown) { switch (mGameState) { case State::GetReady: start(); break; case State::InProgress: mPlane.jump(); break; case State::GameOver: reset(); break; default: break; } } } void Game::update() noexcept { if (mGameState != State::InProgress) { return; } mBackground.update(); mGround.update(); mSpikes.update(); mPlane.update(); if (hasPlaneCrashed()) { mBackground.pause(); mGround.pause(); mSpikes.pause(); mPlane.pause(); mGameState = State::GameOver; } } void Game::draw() const { mBackground.draw(); mPlane.draw(); mSpikes.draw(); mGround.draw(); if (mGameState == State::GetReady) { mGetReadySprite.draw(); } else if (mGameState == State::GameOver) { mGameOverSprite.draw(); } } void Game::start() { mBackground.play(); mSpikes.play(); mGround.play(); mPlane.play(); mGameState = State::InProgress; } void Game::reset() { mPlane.reset(); mSpikes.reset(); mGameState = State::GetReady; } static bool areColliding(const Plane& plane, const Spikes& spikes) { for (auto[first, last] = spikes.bounds(); first < last; ++first) { if (areIntersecting(plane.bounds(), first->topSpikeBounds) || areIntersecting(plane.bounds(), first->bottomSpikeBounds)) { return true; } } return false; } bool Game::hasPlaneCrashed() { return areColliding(mPlane, mSpikes) || didPlaneHitTheGround() || didPlaneHitTheCeiling(); } bool Game::didPlaneHitTheGround() { return areIntersecting(mPlane.bounds(), mGround.bounds()); } bool Game::didPlaneHitTheCeiling() { return topOf(mPlane.bounds()) < topOf(canvasBounds); } } // namespace TappyPlane
24.566176
75
0.657887
2b3c6494fcf05fd98c75d47ed901c2fa1affe08f
24,449
cpp
C++
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: article.cpp,v $ /* Revision 1.1 2010/07/21 17:14:56 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.3 2009/08/25 20:04:25 richard_wood /* Updates for 2.9.9 /* /* Revision 1.2 2009/08/16 21:05:38 richard_wood /* Changes for V2.9.7 /* /* Revision 1.1 2009/06/09 13:21:28 richard_wood /* *** empty log message *** /* /* Revision 1.7 2008/09/19 14:51:10 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ /////////////////////////////////////////////////////////////////////////// // article.cpp - The outer object relays requests to the // inner object. This module is mostly fluff. // #include "stdafx.h" #include "afxmt.h" #include "article.h" #include "utilstr.h" #include "codepg.h" #include "tglobopt.h" #include "rgcomp.h" #include "8859x.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif // live and die at global scope TMemShack TArticleHeader::m_gsMemShack(sizeof(TArticleHeader), "Hdr"); static CCriticalSection sArtCritical; extern ULONG String_base64_decode (LPTSTR pInBuf, int nInSz, LPTSTR pOutBuf, int nOutSz); extern ULONG String_QP_decode (LPCTSTR pInBuf, int nInSz, LPTSTR pOutBuf, int nOutSz); int magic_isohdr_translate (LPCTSTR text, CString & strOut); // Used for RFC 2047 decoding in headers class TAnsiCodePage { public: TAnsiCodePage() { // Old Wisdom // ISO-8859-1 == LATIN 1 == CP 1252 // ISO-8859-2 == LATIN 2 == CP 1250 } // this is used strictly for SUBJECT and FROM lines BOOL CanTranslate(LPCTSTR pszText, int & iType, GravCharset * & rpCharset) { int unusedLen = 0; int ret = this->FindISOString ( pszText, unusedLen, rpCharset ); if (0==ret) return FALSE; else { iType = ret; return TRUE; } } // =========================================================== // return 1 for QP, 2 for B64, 0 for 'can not handle it' // // update ln - offset to start of good data (after 8859-15?Q?) // // example: // =?iso-8859-1?q?this=20is=20some=20text?= BOOL FindISOString (LPCTSTR cpIn, int & ln, GravCharset * & rpCharset) { CString strcp = cpIn; strcp.MakeLower(); LPCTSTR cp = strcp; LPTSTR pRes = 0; pRes = (LPSTR)strstr (cp, "=?"); if (NULL == pRes) return FALSE; if (NULL == *(pRes+2)) return FALSE; else { CString charsetName; LPTSTR pTravel = pRes + 2; int n=0; LPTSTR pTxt = charsetName.GetBuffer(strcp.GetLength()); while (*pTravel && ('?' != *pTravel)) { *pTxt++ = *pTravel++; n++; } charsetName.ReleaseBuffer(n); // use the map for a fast lookup rpCharset = gsCharMaster.findByName( charsetName ); if (NULL == rpCharset) return FALSE; if (NULL == *pTravel) // pTravel should point to the ?q? or ?b? return FALSE; ASSERT('?' == *pTravel); ++pTravel; TCHAR cEncoding = *pTravel; int ret = 0; if (NULL == cEncoding) return 0; if ('q' == cEncoding) ret = 1; else if ('b' == cEncoding) ret = 2; else return ret; ++pTravel; // point to 2nd ? if ((NULL == *pTravel) || ('?' != *pTravel)) return 0; ++pTravel; // point to start of data ln = pTravel - cp; return ret; } } }; static TAnsiCodePage gsCodePage; /////////////////////////////////////////////////////////////////////////// // TPersist822Header // #if defined(_DEBUG) void TPersist822Header::Dump(CDumpContext& dc) const { TBase822Header::Dump( dc ); m_pRep->Dump (dc); dc << "TPersist822Hdr\n" ; } #endif /////////////////////////////////////////////////////////////////////////// // Destructor TPersist822Header::TPersist822Header() { m_pRep = 0; // the derived classes must instantiate the Inner representation } /////////////////////////////////////////////////////////////////////////// // copy-constructor TPersist822Header::TPersist822Header(const TPersist822Header& src) { m_pRep = src.m_pRep; m_pRep->AddRef (); } /////////////////////////////////////////////////////////////////////////// // Destructor TPersist822Header::~TPersist822Header() { try { ASSERT(m_pRep); m_pRep->DeleteRef (); } catch(...) { // catch everything - no exceptions can leave a destructor } } void TPersist822Header::copy_on_write() { if (m_pRep->iGetRefCount() == 1) return; // call virt function to make the right kind of object TPersist822HeaderInner * pCpyInner = m_pRep->duplicate(); TPersist822HeaderInner * pOriginal = m_pRep; m_pRep = pCpyInner; // I now have a fresh copy all to myself pOriginal->DeleteRef(); // you have 1 less client } /////////////////////////////////////////////////////////////////////////// // NOTE: ask Al before using this function // // 5-01-96 amc Created void TPersist822Header::PrestoChangeo_AddReferenceCount() { ASSERT(m_pRep); m_pRep->AddRef (); // you have 1 more client } void TPersist822Header::PrestoChangeo_DelReferenceCount() { ASSERT(m_pRep); m_pRep->DeleteRef (); // you have 1 less client } void TPersist822Header::SetNumber(LONG n) { copy_on_write(); m_pRep->SetNumber(n); } void TPersist822Header::SetLines (int lines) { copy_on_write(); m_pRep->SetLines ( lines ); } void TPersist822Header::SetLines (const CString& body) { copy_on_write(); m_pRep->SetLines ( body ); } void TPersist822Header::StampCurrentTime() { copy_on_write(); m_pRep->StampCurrentTime(); } void TPersist822Header::SetMimeLines(LPCTSTR ver, LPCTSTR type, LPCTSTR encode, LPCTSTR desc) { copy_on_write(); // the inner function is virtual m_pRep->SetMimeLines (ver, type, encode, desc); } void TPersist822Header::GetMimeLines(CString* pVer, CString* pType, CString* pCode, CString* pDesc) { // the inner function is virtual m_pRep->GetMimeLines (pVer, pType, pCode, pDesc); } void TPersist822Header::Serialize(CArchive & archive) { // the inner function is virtual m_pRep->Serialize ( archive ); } TPersist822Header & TPersist822Header::operator=(const TPersist822Header &rhs) { if (&rhs == this) return *this; m_pRep->DeleteRef(); // he has one less client m_pRep = rhs.m_pRep; // copy ptr m_pRep->AddRef (); // you have 1 more client return *this; } ///// end TPersist822Header /////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // TArticleHeader // TArticleHeader::TArticleHeader() { // set object version m_pRep = new TArticleHeaderInner(TArticleHeaderInner::kVersion); } // Destructor TArticleHeader::~TArticleHeader() { /* empty */ } TArticleHeader& TArticleHeader::operator=(const TArticleHeader &rhs) { if (&rhs == this) return *this; TPersist822Header::operator=(rhs); return *this; } /////////////////////////////////////////////////////////////////////////// ULONG TArticleHeader::ShrinkMemPool() { if (true) { CSingleLock sLock(&sArtCritical, TRUE); ULONG u1 = TArticleHeader::m_gsMemShack.Shrink (); } ULONG u2 = TArticleHeaderInner::ShrinkMemPool(); return u2; } #if defined(_DEBUG) void TArticleHeader::Dump(CDumpContext& dc) const { // base class version TPersist822Header::Dump(dc); dc << "ArtHdr\n" ; } #endif ///// member functions void TArticleHeader::FormatExt(const CString& control, CString& strLine) { GetPA()->FormatExt (control, strLine); } void TArticleHeader::SetArticleNumber (LONG artInt) { copy_on_write(); m_pRep->SetNumber(artInt); } void TArticleHeader::SetDate(LPCTSTR date_line) { copy_on_write(); GetPA()->SetDate ( date_line ); } LPCTSTR TArticleHeader::GetDate(void) { return GetPA()->GetDate (); } void TArticleHeader::AddNewsGroup (LPCTSTR ngroup) { copy_on_write(); GetPA()->AddNewsGroup ( ngroup ); } void TArticleHeader::GetNewsGroups (CStringList* pList) const { GetPA()->GetNewsGroups ( pList ); } int TArticleHeader::GetNumOfNewsGroups () const { return GetPA()->GetNumOfNewsGroups (); } void TArticleHeader::ClearNewsGroups () { copy_on_write(); GetPA()->ClearNewsGroups (); } BOOL TArticleHeader::operator<= (const TArticleHeader & rhs) { return (*GetPA()) <= ( *(rhs.GetPA()) ); } void TArticleHeader::SetControl (LPCTSTR control) { copy_on_write(); GetPA()->SetControl ( control ); } LPCTSTR TArticleHeader::GetControl () { return GetPA()->GetControl (); } void TArticleHeader::SetDistribution(LPCTSTR dist) { copy_on_write(); GetPA()->SetDistribution (dist); } LPCTSTR TArticleHeader::GetDistribution() { return GetPA()->GetDistribution(); } void TArticleHeader::SetExpires(LPCTSTR dist) { copy_on_write(); GetPA()->SetExpires (dist); } LPCTSTR TArticleHeader::GetExpires() { return GetPA()->GetExpires(); } // user sets what groups to Followup-To void TArticleHeader::SetFollowup(LPCTSTR follow) { copy_on_write(); GetPA()->SetFollowup(follow); } LPCTSTR TArticleHeader::GetFollowup(void) const { return GetPA()->GetFollowup(); } void TArticleHeader::SetOrganization(LPCTSTR org) { copy_on_write(); GetPA()->SetOrganization(org); } LPCTSTR TArticleHeader::GetOrganization() { return GetPA()->GetOrganization(); } void TArticleHeader::SetKeywords(LPCTSTR keywords) { copy_on_write(); GetPA()->SetKeywords(keywords); } LPCTSTR TArticleHeader::GetKeywords(void) { return GetPA()->GetKeywords(); } void TArticleHeader::SetSender(LPCTSTR sndr) { copy_on_write(); GetPA()->SetSender(sndr); } LPCTSTR TArticleHeader::GetSender(void) { return GetPA()->GetSender(); } void TArticleHeader::SetReplyTo(LPCTSTR replyto) { copy_on_write(); GetPA()->SetReplyTo(replyto); } LPCTSTR TArticleHeader::GetReplyTo() { return GetPA()->GetReplyTo(); } void TArticleHeader::SetSummary(LPCTSTR sum) { copy_on_write(); GetPA()->SetSummary (sum); } LPCTSTR TArticleHeader::GetSummary(void) { return GetPA()->GetSummary(); } void TArticleHeader::SetXRef(LPCTSTR xref) { copy_on_write(); GetPA()->SetXRef(xref); } LPCTSTR TArticleHeader::GetXRef(void) { return GetPA()->GetXRef(); } // ------------------------------------------------------------------ // // void TArticleHeader::SetQPFrom (const CString & from) { copy_on_write(); // put it in GetPA()->SetFrom (from); } void TArticleHeader::SetFrom (const CString & from) { GetPA()->SetFrom (from); } CString TArticleHeader::GetFrom () { return GetPA()->GetFrom (); } const CString & TArticleHeader::GetOrigFrom(void) { return GetPA()->GetOrigFrom (); } void TArticleHeader::SetOrigFrom(const CString & f) { GetPA()->SetOrigFrom(f); } const CString & TArticleHeader::GetPhrase(void) { return GetPA()->GetPhrase(); } void TArticleHeader::SetMessageID (LPCTSTR msgid) { copy_on_write(); GetPA()->SetMessageID(msgid); } LPCTSTR TArticleHeader::GetMessageID(void) { return GetPA()->GetMessageID(); } int handle_2hex_digits (LPCTSTR cp, TCHAR & cOut) { BYTE e; TCHAR c, c2; if ((NULL == (c = cp[1])) || (NULL == (c2 = cp[2]))) return 1; if (!isxdigit (c)) /* must be hex! */ return 1; if (isdigit (c)) e = c - '0'; else e = c - (isupper (c) ? 'A' - 10 : 'a' - 10); c = c2; /* snarf next character */ if (!isxdigit (c)) /* must be hex! */ return 1; if (isdigit (c)) c -= '0'; else c -= (isupper (c) ? 'A' - 10 : 'a' - 10); cOut = TCHAR( BYTE( (e << 4) + c) ); /* merge the two hex digits */ return 0; } // ---------------------------------------------------------- // handle 2047 translation // struct T2047Segment { T2047Segment(LPCTSTR txt, bool fWS0) : fWS(fWS0), text(txt) { iEncodingType = 0; len = 0; } bool fWS; CString text; int iEncodingType; int len; }; typedef T2047Segment* P2047Segment; inline bool is_lwsp(TCHAR c) { if (' ' == c || '\t' == c) return true; else return false; } LPCTSTR read_ws_token (LPCTSTR pTrav, LPTSTR pToken) { while (*pTrav && is_lwsp(*pTrav)) *pToken++ = *pTrav++; *pToken = 0; return pTrav; } LPCTSTR read_black_token (LPCTSTR pTrav, LPTSTR pToken) { while (*pTrav && !is_lwsp(*pTrav)) *pToken++ = *pTrav++; *pToken = 0; return pTrav; } // ---------------------------------------------------------- int magic_hdr2047_segmentize ( LPCSTR subject, CTypedPtrArray<CPtrArray, P2047Segment> & listSegments, LPTSTR rcToken) { LPCTSTR pTrav = subject; while (*pTrav) { if (is_lwsp(*pTrav)) { pTrav = read_ws_token (pTrav, rcToken); listSegments.Add ( new T2047Segment(rcToken, true) ); } else { pTrav = read_black_token (pTrav, rcToken); listSegments.Add ( new T2047Segment(rcToken, false) ); } } return 0; } // ---------------------------------------------------------- // Example 1: // Subject: Hobbits v Sm=?ISO-8859-1?B?6Q==?=agol // This is incorrectly encoded // // Subject: =?Windows-1252?Q?Re:_Hobbits_v_Sm=E9agol?= // // this is better, since the encoded word is 1 ATOM (see rfc2047 section 5) // // HOWEVER, to be generous, I handle the top case now // int segment_2047_translate (T2047Segment * pS1, LPTSTR rcToken) { LPCTSTR cp = pS1->text; TCHAR c; int ret = 0; std::istrstream in_stream(const_cast<LPTSTR>(cp)); std::ostrstream out_stream(rcToken, 4096 * 4); std::vector<BYTE> vEncodedBytes; bool insideEncodedWord = false; int questionCount; while (in_stream.get(c)) { if (!insideEncodedWord) { if ('=' == c && '?' == TCHAR(in_stream.peek())) { insideEncodedWord = true; questionCount = 0; ret = 1; // set return to error } else { out_stream.put( c ); } } else { if (questionCount < 3) { if (c == '?') { questionCount++; } } else { if (c == '?' && TCHAR(in_stream.peek()) == '=') { in_stream.get(c); //eat = TCHAR rcDecoded[4024]; ULONG uLen; vEncodedBytes.push_back(0); LPTSTR psz=reinterpret_cast<LPTSTR>(&vEncodedBytes[0]); if (2 == pS1->iEncodingType) uLen = String_base64_decode (psz, vEncodedBytes.size()-1, rcDecoded, sizeof(rcDecoded)); else uLen = String_QP_decode (psz, vEncodedBytes.size()-1, rcDecoded, sizeof(rcDecoded)); for (int n = 0; n < uLen; ++n) out_stream.put (rcDecoded[n]); insideEncodedWord = false; vEncodedBytes.clear(); ret = 0; } else { vEncodedBytes.push_back((1 == pS1->iEncodingType && '_' == c) ? ' ' : c); } } } // end insideEW } // while // final cleanup if (0 == ret) { out_stream.put(0); pS1->text = rcToken; } return ret; } // ---------------------------------------------------------- int magic_hdr2047_translate (LPCSTR subject, CString & strOut) { TCHAR rcToken[4096 * 4]; CTypedPtrArray<CPtrArray, P2047Segment> listSegments; int iStat=0; magic_hdr2047_segmentize (subject, listSegments, rcToken); int sz = listSegments.GetSize(); int i; for (i = 0; i < sz; i++) { T2047Segment * pSeg = listSegments[i]; GravCharset * pCharsetDummy = 0; int encType = gsCodePage.FindISOString (pSeg->text, pSeg->len, pCharsetDummy); pSeg->iEncodingType = encType; } // drop LWSP segments in between encoded words for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if ((i+2) < listSegments.GetSize()) { T2047Segment* pS2 = listSegments[i+1]; T2047Segment* pS3 = listSegments[i+2]; if (pS1->iEncodingType && !pS1->text.IsEmpty() && pS2->fWS && pS3->iEncodingType && !pS3->text.IsEmpty()) { delete pS2; listSegments.RemoveAt (i+1); } } } // per segment translate for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if (pS1->iEncodingType) { iStat = segment_2047_translate (pS1, rcToken); if (iStat) break; } } // cleanup and build final string for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if (0 == iStat) strOut += pS1->text; delete pS1; } return iStat; } // ---------------------------------------------------------- int magic_isohdr_translate (LPCSTR subject, CString & strOut) { // do QP translation here // ex: // =?iso-8859-1?q?this=20is=20some=20text?= int iType = 0; GravCharset * pCharset = 0; if (FALSE == gsCodePage.CanTranslate(subject, iType, pCharset)) { // this may be untagged eight bit if ( using_hibit(subject) ) { int iSendCharset = gpGlobalOptions->GetRegCompose()->GetSendCharset(); GravCharset* pCharsetUser = gsCharMaster.findById( iSendCharset ); return CP_Util_Inbound (pCharsetUser, subject, lstrlen(subject), strOut); } else return 1; } CString strBytes; int stat = magic_hdr2047_translate (subject, strBytes); if (stat) return stat; // go from bytes to chars return CP_Util_Inbound ( pCharset, strBytes, strBytes.GetLength(), strOut); } // ---------------------------------------------------------- void TArticleHeader::SetQPSubject(LPCTSTR subject, LPCTSTR pszFrom) { copy_on_write(); CString strOut; // do QP translation here if (0 == magic_isohdr_translate (subject, strOut)) GetPA()->SetSubject(strOut); else GetPA()->SetSubject(subject); } void TArticleHeader::SetSubject(LPCTSTR subject) { copy_on_write(); GetPA()->SetSubject(subject); } LPCTSTR TArticleHeader::GetSubject (void) { return GetPA()->GetSubject(); } void TArticleHeader::GetDestList(TStringList* pList) const { GetPA()->GetDestList (pList); } void TArticleHeader::Format (CString& strLine) { GetPA()->Format(strLine); } int TArticleHeader::ParseFrom (CString& phrase, CString& address) { return GetPA()->ParseFrom(phrase, address); } void TArticleHeader::SetReferences (const CString& refs) { copy_on_write(); GetPA()->SetReferences (refs); } void TArticleHeader::SetCustomHeaders (const CStringList &sCustomHeaders) { copy_on_write(); GetPA()->SetCustomHeaders (sCustomHeaders); } const CStringList &TArticleHeader::GetCustomHeaders () const { return GetPA()->GetCustomHeaders(); } BOOL TArticleHeader::AtRoot(void) { return GetPA()->AtRoot(); } BOOL TArticleHeader::FindInReferences(const CString& msgID) { return GetPA()->FindInReferences(msgID); } int TArticleHeader::GetReferencesCount() { return GetPA()->GetReferencesCount(); } void TArticleHeader::CopyReferences(const TArticleHeader & src) { copy_on_write(); GetPA()->CopyReferences( *(src.GetPA()) ); } void TArticleHeader::ConstructReferences(const TArticleHeader & src, const CString& msgid) { GetPA()->ConstructReferences(*(src.GetPA()), msgid); } void TArticleHeader::GetDadRef(CString& str) { GetPA()->GetDadRef (str); } void TArticleHeader::GetFirstRef(CString& str) { GetPA()->GetFirstRef(str); } void TArticleHeader::GetReferencesWSList(CString& line) { GetPA()->GetReferencesWSList(line); } void TArticleHeader::GetReferencesStringList(CStringList* pList) { GetPA()->GetReferencesStringList(pList); } const TFlatStringArray &TArticleHeader::GetReferences () { return GetPA()->GetReferences(); } // end of TArticle Implementation /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // TEmailHeader // TEmailHeader::TEmailHeader() { m_pRep = new TEmailHeaderInner(TEmailHeaderInner::kVersion); // object version is 1 } // Empty destructor TEmailHeader::~TEmailHeader() { /* empty */ } TEmailHeader& TEmailHeader::operator=(const TEmailHeader &rhs) { if (&rhs == this) return *this; TPersist822Header::operator=(rhs); // do normal stuff return *this; } void TEmailHeader::Set_InReplyTo (LPCTSTR irt) { copy_on_write(); GetPE()->Set_InReplyTo(irt); } LPCTSTR TEmailHeader::Get_InReplyTo () { return GetPE()->Get_InReplyTo(); } int TEmailHeader::GetDestinationCount(TBase822Header::EAddrType eAddr) { return GetPE()->GetDestinationCount(eAddr); } void TEmailHeader::ParseTo(const CString & to, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseTo (to, pOutList, pErrList); } void TEmailHeader::GetToText(CString& txt) { GetPE()->GetToText (txt); } // CC - store the comma separated list of addresses void TEmailHeader::ParseCC(const CString& comma_sep_CC_list, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseCC (comma_sep_CC_list, pOutList, pErrList); } // CC - get the displayable text, separated by commas void TEmailHeader::GetCCText(CString& txt) { GetPE()->GetCCText ( txt ); } // BCC - store the comma separated list of addresses void TEmailHeader::ParseBCC(const CString& comma_sep_BCC_list, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseBCC ( comma_sep_BCC_list, pOutList, pErrList ); } // BCC - get the displayable text, separated by commas void TEmailHeader::GetBCCText(CString& txt) { GetPE()->GetBCCText ( txt ); } void TEmailHeader::GetDestinationList (TBase822Header::EAddrType eAddr, TStringList * pstrList) const { GetPE()->GetDestinationList(eAddr, pstrList); } // end of file
24.4002
95
0.598961
2b3f56c43262005553a7666cdfa8b342238ac1bd
3,199
hpp
C++
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
#pragma once #include "generic_attribute.hpp" #include "../util/observer.hpp" #include <emscripten/val.h> #include <functional> #include <iostream> namespace CppDom::Attributes { template <typename ValueT> class Attribute : public GenericAttribute { public: Attribute(std::string name, ValueT value) : name_{std::move(name)} , value_{std::move(value)} { } void setOn(emscripten::val& node) override { using emscripten::val; node.call<val>("setAttribute", val(name_), val(value_)); } Attribute* clone() const override { return new Attribute(name_, value_); } Attribute(Attribute const&) = default; Attribute(Attribute&&) = default; private: std::string name_; ValueT value_; }; class ComplexAttribute : public GenericAttribute { public: ComplexAttribute(std::function <void(emscripten::val&)> setOn) : GenericAttribute{} , setOn_{setOn} { } void setOn(emscripten::val& node) override { setOn_(node); } ComplexAttribute* clone() const override { return new ComplexAttribute(setOn_); } private: std::function <void(emscripten::val&)> setOn_; }; template <typename ValueT> class ReactiveAttribute : public GenericAttribute { public: ReactiveAttribute(std::string name, SharedObserver<ValueT> value) : name_{std::move(name)} , value_{std::move(value)} { value_.subscribe(this); } ~ReactiveAttribute() { value_.unsubscribe(this); } operator=(ReactiveAttribute const&) = delete; ReactiveAttribute(ReactiveAttribute const&) = delete; void setOn(emscripten::val& node) override { using emscripten::val; node.call<val>("setAttribute", val(name_), val(static_cast <ValueT&>(value_))); parent_ = &node; } void update() override { std::cout << "update reactive\n"; using emscripten::val; if (parent_ != nullptr) parent_->call<val>("setAttribute", val(name_), val(static_cast <ValueT&>(value_))); } ReactiveAttribute* clone() const override { return new ReactiveAttribute(name_, value_); } private: emscripten::val* parent_; std::string name_; SharedObserver<ValueT> value_; }; } #define MAKE_HTML_STRING_ATTRIBUTE(NAME) \ namespace CppDom::Attributes \ { \ struct NAME ## _ { \ Attribute <char const*> operator=(char const* val) \ { \ return {#NAME, std::move(val)}; \ } \ template <typename T> \ ReactiveAttribute <T> operator=(SharedObserver<T> observed) \ { \ return {#NAME, std::move(observed)}; \ } \ } NAME; \ }
26.438017
100
0.530166
2b422105b1d620f109831fd004da587a0acba6f1
3,431
cpp
C++
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
5
2019-12-20T05:48:26.000Z
2021-10-13T12:32:50.000Z
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
null
null
null
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
2
2020-03-07T11:40:38.000Z
2022-01-24T22:37:40.000Z
#include "msgpack_server.hpp" #include <msgpack.hpp> typedef long ssize_t; typedef std::basic_string<TCHAR> tstring; inline void operator<<(tstring &t, const std::string &s) { #ifdef _UNICODE if (s.size() > 0) { t.resize(s.size() + 1); size_t length = 0; mbstowcs_s(&length, &t[0], t.size(), s.c_str(), _TRUNCATE); t.resize(length); } else { t.clear(); } #else t = s; #endif } class Reply : public ReplyInterface { public: Reply(HANDLE pipe, uint32_t id); bool write(const char *data, std::size_t length); uint32_t id() const; private: HANDLE hPipe; uint32_t callid; }; Reply::Reply(HANDLE pipe, uint32_t id) : hPipe(pipe), callid(id) { } bool Reply::write(const char *data, std::size_t len) { DWORD length = 0; WriteFile(hPipe, data, len, &length, NULL); return length > 0; } uint32_t Reply::id() const { return callid; } class MsgpackServer::Private { public: Private(); ~Private(); public: tstring path; std::unordered_map<std::string, MsgpackCallback> handlers; HANDLE hPipe; bool active; }; MsgpackServer::Private::Private() : active(false) { } MsgpackServer::Private::~Private() { } MsgpackServer::MsgpackServer(const std::string &path) : d(new Private()) { d->path << path; } MsgpackServer::~MsgpackServer() { delete d; } void MsgpackServer::handle(const std::string &command, const MsgpackCallback &func) { if (func) { d->handlers[command] = func; } else { d->handlers.erase(command); } } bool MsgpackServer::start() { auto spd = spdlog::get("console"); size_t const try_read_size = 256; d->hPipe = CreateNamedPipe(d->path.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, 1, try_read_size, try_read_size, 1000, NULL); if (d->hPipe == INVALID_HANDLE_VALUE) { spd->error("CreateNamedPipe() failed"); return false; } if (!ConnectNamedPipe(d->hPipe, NULL)) { spd->error("ConnectNamedPipe() failed"); return false; } msgpack::unpacker unp; d->active = true; while (d->active) { unp.reserve_buffer(try_read_size); DWORD actual_read_size = 0; if (!ReadFile(d->hPipe, unp.buffer(), try_read_size, &actual_read_size, NULL)) { spd->error("ReadFile() failed"); break; } unp.buffer_consumed(actual_read_size); msgpack::object_handle result; while (unp.next(result)) { msgpack::object obj(result.get()); spd->debug("recv: {}", obj); try { const auto &tuple = obj.as<std::tuple<std::string, uint32_t, msgpack::object>>(); const auto &it = d->handlers.find(std::get<0>(tuple)); if (it != d->handlers.end()) { Reply reply(d->hPipe, std::get<1>(tuple)); (it->second)(std::get<2>(tuple), reply); } } catch (const std::bad_cast &err) { spd->error("msgpack decoding error: {}", err.what()); } if (!d->active) break; } } CloseHandle(d->hPipe); return true; } bool MsgpackServer::stop() { if (d->active) { d->active = false; return true; } return false; }
21.179012
97
0.558146
2b423a2bbdd5dc4457462f2f23e00bd3dc3cf5b4
190
cpp
C++
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
14
2019-04-29T15:17:24.000Z
2020-12-30T12:51:05.000Z
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
null
null
null
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
6
2019-04-29T15:17:25.000Z
2021-11-16T03:20:59.000Z
#include "flare_skia/skr_actor_star.hpp" using namespace flare; SkrActorStar::SkrActorStar() : SkrActorBasePath(this) {} void SkrActorStar::invalidateDrawable() { m_IsPathValid = false; }
27.142857
66
0.784211
2b47e6487736be4f7af55e23d51fc838ea6e9d7f
4,965
cc
C++
content/renderer/pepper/ppb_tcp_socket_private_impl.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2017-03-21T23:19:25.000Z
2019-02-03T05:32:47.000Z
content/renderer/pepper/ppb_tcp_socket_private_impl.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/pepper/ppb_tcp_socket_private_impl.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2012 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 "content/renderer/pepper/ppb_tcp_socket_private_impl.h" #include "content/common/pepper_messages.h" #include "content/renderer/pepper/host_globals.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_thread_impl.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/socket_option_data.h" namespace content { PPB_TCPSocket_Private_Impl::PPB_TCPSocket_Private_Impl( PP_Instance instance, uint32 socket_id, int routing_id) : ppapi::TCPSocketPrivateImpl(instance, socket_id), routing_id_(routing_id) { ChildThread::current()->AddRoute(routing_id, this); } PPB_TCPSocket_Private_Impl::~PPB_TCPSocket_Private_Impl() { ChildThread::current()->RemoveRoute(routing_id_); Disconnect(); } PP_Resource PPB_TCPSocket_Private_Impl::CreateResource(PP_Instance instance) { int routing_id = RenderThreadImpl::current()->GenerateRoutingID(); uint32 socket_id = 0; RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_CreatePrivate( routing_id, 0, &socket_id)); if (!socket_id) return 0; return (new PPB_TCPSocket_Private_Impl( instance, socket_id, routing_id))->GetReference(); } void PPB_TCPSocket_Private_Impl::SendConnect(const std::string& host, uint16_t port) { RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_Connect( routing_id_, socket_id_, host, port)); } void PPB_TCPSocket_Private_Impl::SendConnectWithNetAddress( const PP_NetAddress_Private& addr) { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_ConnectWithNetAddress( routing_id_, socket_id_, addr)); } void PPB_TCPSocket_Private_Impl::SendSSLHandshake( const std::string& server_name, uint16_t server_port, const std::vector<std::vector<char> >& trusted_certs, const std::vector<std::vector<char> >& untrusted_certs) { RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_SSLHandshake( socket_id_, server_name, server_port, trusted_certs, untrusted_certs)); } void PPB_TCPSocket_Private_Impl::SendRead(int32_t bytes_to_read) { RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_Read( socket_id_, bytes_to_read)); } void PPB_TCPSocket_Private_Impl::SendWrite(const std::string& buffer) { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_Write(socket_id_, buffer)); } void PPB_TCPSocket_Private_Impl::SendDisconnect() { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_Disconnect(socket_id_)); } void PPB_TCPSocket_Private_Impl::SendSetOption( PP_TCPSocket_Option name, const ppapi::SocketOptionData& value) { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_SetOption(socket_id_, name, value)); } bool PPB_TCPSocket_Private_Impl::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PPB_TCPSocket_Private_Impl, message) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_ConnectACK, OnTCPSocketConnectACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_SSLHandshakeACK, OnTCPSocketSSLHandshakeACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_ReadACK, OnTCPSocketReadACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_WriteACK, OnTCPSocketWriteACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_SetOptionACK, OnTCPSocketSetOptionACK) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PPB_TCPSocket_Private_Impl::OnTCPSocketConnectACK( uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result, const PP_NetAddress_Private& local_addr, const PP_NetAddress_Private& remote_addr) { OnConnectCompleted(result, local_addr, remote_addr); } void PPB_TCPSocket_Private_Impl::OnTCPSocketSSLHandshakeACK( uint32 plugin_dispatcher_id, uint32 socket_id, bool succeeded, const ppapi::PPB_X509Certificate_Fields& certificate_fields) { OnSSLHandshakeCompleted(succeeded, certificate_fields); } void PPB_TCPSocket_Private_Impl::OnTCPSocketReadACK(uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result, const std::string& data) { OnReadCompleted(result, data); } void PPB_TCPSocket_Private_Impl::OnTCPSocketWriteACK( uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result) { OnWriteCompleted(result); } void PPB_TCPSocket_Private_Impl::OnTCPSocketSetOptionACK( uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result) { OnSetOptionCompleted(result); } } // namespace content
34.964789
80
0.749446
2b4859e0cf3cce1bcdb6792c1ddba2420c735dfa
11,602
cpp
C++
hi_modules/nodes/FXNodes.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_modules/nodes/FXNodes.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_modules/nodes/FXNodes.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ namespace scriptnode { using namespace juce; using namespace hise; namespace fx { template <int V> sampleandhold_impl<V>::sampleandhold_impl() { } template <int V> void sampleandhold_impl<V>::setFactor(double value) { auto factor = jlimit(1, 44100, roundToInt(value)); if (data.isMonophonicOrInsideVoiceRendering()) data.get().factor = factor; else data.forEachVoice([factor](Data& d_) {d_.factor = factor; }); } template <int V> void sampleandhold_impl<V>::createParameters(Array<ParameterData>& d) { { ParameterData p("Counter"); p.range = { 1, 64, 1.0 }; p.db = BIND_MEMBER_FUNCTION_1(sampleandhold_impl::setFactor); d.add(std::move(p)); } } template <int V> void sampleandhold_impl<V>::processSingle(float* numFrames, int numChannels) { auto& v = data.get(); if (v.counter == 0) { FloatVectorOperations::copy(v.currentValues, numFrames, numChannels); v.counter = v.factor; } else { FloatVectorOperations::copy(numFrames, v.currentValues, numChannels); v.counter--; } } template <int V> void sampleandhold_impl<V>::reset() noexcept { if (data.isMonophonicOrInsideVoiceRendering()) data.get().clear(lastChannelAmount); else data.forEachVoice([this](Data& d_) {d_.clear(lastChannelAmount); }); } template <int V> void sampleandhold_impl<V>::process(ProcessData& d) { Data& v = data.get(); if (v.counter > d.size) { for (int i = 0; i < d.numChannels; i++) FloatVectorOperations::fill(d.data[i], v.currentValues[i], d.size); v.counter -= d.size; } else { for (int i = 0; i < d.size; i++) { if (v.counter == 0) { for (int c = 0; c < d.numChannels; c++) { v.currentValues[c] = d.data[c][i]; v.counter = v.factor + 1; } } for (int c = 0; c < d.numChannels; c++) d.data[c][i] = v.currentValues[c]; v.counter--; } } } template <int V> void sampleandhold_impl<V>::prepare(PrepareSpecs ps) { data.prepare(ps); lastChannelAmount = ps.numChannels; } template <int V> void sampleandhold_impl<V>::initialise(NodeBase* ) { } DEFINE_EXTERN_NODE_TEMPIMPL(sampleandhold_impl); template <int V> bitcrush_impl<V>::bitcrush_impl() { bitDepth.setAll(16.0f); } template <int V> void bitcrush_impl<V>::setBitDepth(double newBitDepth) { auto v = jlimit(1.0f, 16.0f, (float)newBitDepth); if (bitDepth.isMonophonicOrInsideVoiceRendering()) bitDepth.get() = v; else bitDepth.setAll(v); } template <int V> void bitcrush_impl<V>::createParameters(Array<ParameterData>& data) { { ParameterData p("Bit Depth"); p.range = { 4.0, 16.0, 0.1 }; p.defaultValue = 16.0; p.db = BIND_MEMBER_FUNCTION_1(bitcrush_impl::setBitDepth); data.add(std::move(p)); } } template <int V> bool bitcrush_impl<V>::handleModulation(double&) noexcept { return false; } template <int V> void bitcrush_impl<V>::reset() noexcept { } // ====================================================================================================== void getBitcrushedValue(float* data, int numSamples, float bitDepth) { const float invStepSize = pow(2.0f, bitDepth); const float stepSize = 1.0f / invStepSize; for (int i = 0; i < numSamples; i++) data[i] = (stepSize * ceil(data[i] * invStepSize) - 0.5f * stepSize); } // ====================================================================================================== template <int V> void bitcrush_impl<V>::process(ProcessData& d) { for (auto ch : d) getBitcrushedValue(ch, d.size, bitDepth.get()); } template <int V> void bitcrush_impl<V>::processSingle(float* numFrames, int numChannels) { getBitcrushedValue(numFrames, numChannels, bitDepth.get()); } template <int V> void bitcrush_impl<V>::prepare(PrepareSpecs ps) { bitDepth.prepare(ps); } template <int V> void bitcrush_impl<V>::initialise(NodeBase* ) { } DEFINE_EXTERN_NODE_TEMPIMPL(bitcrush_impl) template <int V> phase_delay_impl<V>::phase_delay_impl() { } template <int V> void phase_delay_impl<V>::initialise(NodeBase* ) { } template <int V> void phase_delay_impl<V>::prepare(PrepareSpecs ps) { sr = ps.sampleRate * 0.5; delays[0].prepare(ps); delays[1].prepare(ps); } template <int V> void phase_delay_impl<V>::process(ProcessData& d) { int numChannels = jmin(2, d.numChannels); for (int c = 0; c < numChannels; c++) { auto ptr = d.data[c]; auto& dl = delays[c].get(); for (int i = 0; i < d.size; i++) { auto v = *ptr; *ptr++ = dl.getNextSample(v); } } } template <int V> void scriptnode::fx::phase_delay_impl<V>::reset() noexcept { if (delays[0].isMonophonicOrInsideVoiceRendering()) { delays[0].get().reset(); delays[1].get().reset(); } else { auto f = [](AllpassDelay& d) { d.reset(); }; delays[0].forEachVoice(f); delays[1].forEachVoice(f); } } template <int V> void phase_delay_impl<V>::processSingle(float* numFrames, int numChannels) { numChannels = jmin(2, numChannels); for (int i = 0; i < numChannels; i++) numFrames[i] = delays[i].get().getNextSample(numFrames[i]); } template <int V> bool phase_delay_impl<V>::handleModulation(double&) noexcept { return false; } template <int V> void phase_delay_impl<V>::createParameters(Array<ParameterData>& data) { { ParameterData p("Frequency"); p.range = { 20.0, 20000.0, 0.1 }; p.range.setSkewForCentre(1000.0); p.defaultValue = 400.0; p.db = BIND_MEMBER_FUNCTION_1(phase_delay_impl::setFrequency); data.add(std::move(p)); } } template <int V> void phase_delay_impl<V>::setFrequency(double newFrequency) { newFrequency /= sr; auto coefficient = AllpassDelay::getDelayCoefficient((float)newFrequency); if (delays[0].isMonophonicOrInsideVoiceRendering()) { delays[0].get().setDelay(coefficient); delays[1].get().setDelay(coefficient); } else { auto f = [coefficient](AllpassDelay& d) {d.setDelay(coefficient); }; delays[0].forEachVoice(f); delays[1].forEachVoice(f); } } DEFINE_EXTERN_NODE_TEMPIMPL(phase_delay_impl); template <int V> void haas_impl<V>::setPosition(double newValue) { position = newValue; auto d = std::abs(position) * 0.02; if (delayL.isMonophonicOrInsideVoiceRendering()) { if (position == 0.0) { delayL.get().setDelayTimeSamples(0); delayR.get().setDelayTimeSamples(0); } else if (position > 0.0) { delayL.get().setDelayTimeSeconds(d); delayR.get().setDelayTimeSamples(0); } else if (position < 0.0) { delayL.get().setDelayTimeSamples(0); delayR.get().setDelayTimeSeconds(d); } } else { // We don't allow fade times in polyphonic effects because there is no constant flow of signal that // causes issues with the fade time logic... int fadeTime = NumVoices == 1 ? 2048 : 0; auto setZero = [fadeTime](DelayType& t) { t.setFadeTimeSamples(fadeTime); t.setDelayTimeSamples(0); }; auto setSeconds = [fadeTime, d](DelayType& t) { t.setFadeTimeSamples(fadeTime); t.setDelayTimeSeconds(d); }; if (position == 0.0) { delayL.forEachVoice(setZero); delayR.forEachVoice(setZero); } else if (position > 0.0) { delayL.forEachVoice(setSeconds); delayR.forEachVoice(setZero); } else if (position < 0.0) { delayL.forEachVoice(setZero); delayR.forEachVoice(setSeconds); } } } template <int V> bool haas_impl<V>::handleModulation(double&) { return false; } template <int V> void haas_impl<V>::process(ProcessData& d) { if (d.numChannels == 2) { delayL.get().processBlock(d.data[0], d.size); delayR.get().processBlock(d.data[1], d.size); } } template <int V> void haas_impl<V>::processSingle(float* data, int numChannels) { if (numChannels == 2) { data[0] = delayL.get().getDelayedValue(data[0]); data[1] = delayR.get().getDelayedValue(data[1]); } } template <int V> void haas_impl<V>::reset() { if (delayL.isMonophonicOrInsideVoiceRendering()) { jassert(delayR.isMonophonicOrInsideVoiceRendering()); delayL.get().setFadeTimeSamples(0); delayR.get().setFadeTimeSamples(0); delayL.get().clear(); delayR.get().clear(); } else { auto f = [](DelayType& d) {d.clear(); }; delayL.forEachVoice(f); delayR.forEachVoice(f); } } template <int V> void haas_impl<V>::prepare(PrepareSpecs ps) { delayL.prepare(ps); delayR.prepare(ps); auto sr = ps.sampleRate; auto f = [sr](DelayType& d) { d.prepareToPlay(sr); d.setFadeTimeSamples(0); }; delayL.forEachVoice(f); delayR.forEachVoice(f); setPosition(position); } template <int V> void haas_impl<V>::createParameters(Array<ParameterData>& data) { { ParameterData p("Position"); p.range = { -1.0, 1.0, 0.1 }; p.defaultValue = 0.0; p.db = BIND_MEMBER_FUNCTION_1(haas_impl::setPosition); data.add(std::move(p)); } } DEFINE_EXTERN_NODE_TEMPIMPL(haas_impl); reverb::reverb() { auto p = r.getParameters(); p.dryLevel = 0.0f; r.setParameters(p); } void reverb::initialise(NodeBase* ) { } void reverb::prepare(PrepareSpecs ps) { r.setSampleRate(ps.sampleRate); } void reverb::process(ProcessData& d) { if (d.numChannels == 2) r.processStereo(d.data[0], d.data[1], d.size); else if (d.numChannels == 1) r.processMono(d.data[0], d.size); } void reverb::reset() noexcept { r.reset(); } void reverb::processSingle(float* numFrames, int numChannels) { if (numChannels == 2) r.processStereo(numFrames, numFrames + 1, 1); else if (numChannels == 1) r.processMono(numFrames, 1); } bool reverb::handleModulation(double&) noexcept { return false; } void reverb::createParameters(Array<ParameterData>& data) { { ParameterData p("Size"); p.range = { 0.0, 1.0, 0.01 }; p.defaultValue = 0.5f; p.db = BIND_MEMBER_FUNCTION_1(reverb::setSize); data.add(std::move(p)); } { ParameterData p("Damping"); p.range = { 0.0, 1.0, 0.01 }; p.defaultValue = 0.5f; p.db = BIND_MEMBER_FUNCTION_1(reverb::setDamping); data.add(std::move(p)); } { ParameterData p("Width"); p.range = { 0.0, 1.0, 0.01 }; p.defaultValue = 0.5f; p.db = BIND_MEMBER_FUNCTION_1(reverb::setWidth); data.add(std::move(p)); } } void reverb::setDamping(double newDamping) { auto p = r.getParameters(); p.damping = jlimit(0.0f, 1.0f, (float)newDamping); r.setParameters(p); } void reverb::setWidth(double width) { auto p = r.getParameters(); p.damping = jlimit(0.0f, 1.0f, (float)width); r.setParameters(p); } void reverb::setSize(double size) { auto p = r.getParameters(); p.roomSize = jlimit(0.0f, 1.0f, (float)size); r.setParameters(p); } } }
20.390158
110
0.658593
2b4df60058134010d44cb4d759db34fe24b65a3b
7,330
cpp
C++
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "rolestoryfb.hpp" #include "obj/character/role.h" #include "config/logicconfigmanager.hpp" #include "other/vip/vipconfig.hpp" #include "other/fb/storyfbconfig.hpp" #include "servercommon/errornum.h" #include "protocal/msgfb.h" #include "other/event/eventhandler.hpp" #include "monster/monsterpool.h" #include "gameworld/world.h" #include "servercommon/string/gameworldstr.h" #include "scene/scene.h" #include "item/itempool.h" #include "item/knapsack.h" #include "other/route/mailroute.hpp" #include "global/worldstatus/worldstatus.hpp" #include "global/usercache/usercache.hpp" #include "other/vip/vip.hpp" #include "other/daycounter/daycounter.hpp" RoleStoryFB::RoleStoryFB() : m_role(NULL) { } RoleStoryFB::~RoleStoryFB() { } void RoleStoryFB::Init(Role *role, const StoryFBParam &param) { m_role = role; m_param = param; } void RoleStoryFB::GetInitParam(StoryFBParam *param) { *param = m_param; } void RoleStoryFB::OnDayChange(unsigned int old_dayid, unsigned int now_dayid) { for (int i = 0; i < FB_STORY_MAX_COUNT; i++) { m_param.fb_list[i].today_times = 0; } this->SendInfo(); } bool RoleStoryFB::CanEnter(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return false; } if (fb_index > 0 && !this->IsPassLevel(fb_index - 1) && 0 == m_param.fb_list[fb_index - 1].today_times) { m_role->NoticeNum(errornum::EN_PRVE_FB_NOT_COMPLETED); return false; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return false; } if (m_role->GetLevel() < level_cfg->role_level) { m_role->NoticeNum(errornum::EN_STORY_FB_FUN_OPEN_LEVEL_LIMIT); return false; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times) { m_role->NoticeNum(errornum::EN_STORY_FB_TIMES_LIMIT); return false; } return true; } void RoleStoryFB::OnEnterFB(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } m_param.curr_fb_index = fb_index; m_param.fb_list[fb_index].today_times++; m_role->GetDayCounter()->DayCountSet(DayCounter::DAYCOUNT_ID_FB_STORY, 1); this->SendInfo(); } void RoleStoryFB::AutoFBReqOne(int fb_index) { Scene *scene = m_role->GetScene(); if (NULL == scene) { return; } if (Scene::SCENE_TYPE_STORY_FB == scene->GetSceneType()) { m_role->NoticeNum(errornum::EN_FB_OPERATE_LIMIT); return; } if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return; } if (0 == m_param.fb_list[fb_index].is_pass) { m_role->NoticeNum(errornum::EN_STORY_FB_NO_PASS); return; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times) { const int vip_buy_times = LOGIC_CONFIG->GetVipConfig().GetAuthParam(m_role->GetVip()->GetVipLevel(), VAT_FB_STROY_COUNT); if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times + vip_buy_times) { m_role->NoticeNum(errornum::EN_BUY_STROY_FB_TIME_LIMIT); return; } if (level_cfg->reset_gold > 0 && !m_role->GetKnapsack()->GetMoney()->AllGoldMoreThan(level_cfg->reset_gold)) { m_role->NoticeNum(errornum::EN_GOLD_NOT_ENOUGH); return; } } ItemConfigData reward_item_list[MonsterInitParam::MAX_DROP_ITEM_COUNT]; int index_count = MonsterInitParam::MAX_DROP_ITEM_COUNT; long long reward_exp = 0; for(int i = 0; i < level_cfg->monster_count && i < StoryFBLevelCfg::MONSTER_COUNT_MAX; i++) { if (0 != level_cfg->monster_id_list[i]) { MONSTERPOOL->GetMonsterDrop(level_cfg->monster_id_list[i], reward_item_list, &index_count, &reward_exp, NULL, NULL); } } short item_count = 0; for (int j = 0; j < index_count && j < MonsterInitParam::MAX_DROP_ITEM_COUNT; j++) { if (0 == reward_item_list[j].item_id) { break; } item_count++; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times && !m_role->GetKnapsack()->GetMoney()->UseAllGold(level_cfg->reset_gold, "StoryFBAuto")) { m_role->NoticeNum(errornum::EN_GOLD_NOT_ENOUGH); return; } m_param.fb_list[fb_index].today_times++; EventHandler::Instance().OnAutoFbStory(m_role); m_role->AddExp(reward_exp, "StoryFBAuto", Role::EXP_ADD_REASON_DEFAULT); if (item_count > 0) { m_role->GetKnapsack()->PutList(item_count, reward_item_list, PUT_REASON_STORY_FB); } this->SendInfo(); } void RoleStoryFB::AutoFBReqAll() { Scene *scene = m_role->GetScene(); if (NULL == scene) { return; } if (Scene::SCENE_TYPE_STORY_FB == scene->GetSceneType()) { m_role->NoticeNum(errornum::EN_FB_OPERATE_LIMIT); return; } bool is_auto_succ = false; for(int i = 0; i < FB_STORY_MAX_COUNT; i ++) { const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(i); if (NULL == level_cfg) { break; } if (0 == m_param.fb_list[i].is_pass) { continue; } if (m_param.fb_list[i].today_times >= level_cfg->free_times) { continue; } ItemConfigData reward_item_list[MonsterInitParam::MAX_DROP_ITEM_COUNT]; int index_count = MonsterInitParam::MAX_DROP_ITEM_COUNT; long long reward_exp = 0; for(int j = 0; j < level_cfg->monster_count && j < StoryFBLevelCfg::MONSTER_COUNT_MAX; j++) { if (0 != level_cfg->monster_id_list[j]) { MONSTERPOOL->GetMonsterDrop(level_cfg->monster_id_list[j], reward_item_list, &index_count, &reward_exp, NULL, NULL); } } short item_count = 0; for(int k = 0; k < index_count && k < MonsterInitParam::MAX_DROP_ITEM_COUNT; k++) { if (0 == reward_item_list[i].item_id) { break; } item_count++; } is_auto_succ = true; m_param.fb_list[i].today_times++; m_role->AddExp(reward_exp, "StoryFBAuto", Role::EXP_ADD_REASON_DEFAULT); if (index_count > 0) { m_role->GetKnapsack()->PutList(item_count, reward_item_list , PUT_REASON_STORY_FB); } EventHandler::Instance().OnAutoFbStory(m_role); } if (is_auto_succ) { m_role->GetDayCounter()->DayCountSet(DayCounter::DAYCOUNT_ID_FB_STORY, 1); this->SendInfo(); } else { m_role->NoticeNum(errornum::EN_STORY_FB_NOT_LEVEL); } } void RoleStoryFB::SendInfo() { static Protocol::SCStoryFBInfo cmd; for (int i = 0; i < FB_STORY_MAX_COUNT; i++) { cmd.info_list[i].is_pass = m_param.fb_list[i].is_pass; cmd.info_list[i].today_times = m_param.fb_list[i].today_times; } EngineAdapter::Instance().NetSend(m_role->GetNetId(), (const char*)&cmd, sizeof(cmd)); } void RoleStoryFB::OnPassLevel(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return; } if (0 == m_param.fb_list[fb_index].is_pass) { m_param.fb_list[fb_index].is_pass = 1; m_role->GetKnapsack()->PutListOrMail(level_cfg->first_reward_list, PUT_REASON_STORY_FB); } else { m_role->GetKnapsack()->PutListOrMail(level_cfg->normal_reward_list, PUT_REASON_STORY_FB); } m_role->AddExp(level_cfg->reward_exp, "StoryFBPass", Role::EXP_ADD_REASON_DEFAULT); this->SendInfo(); } bool RoleStoryFB::IsPassLevel(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return false; } return 0 != m_param.fb_list[fb_index].is_pass; }
22.978056
156
0.715825
2b4e6076e6ed4c30ab1de9d92ebdfbe43d6fc701
4,120
cpp
C++
src/parsing.cpp
MicroTransactionsMatterToo/midiparser-cpp
1e95cc445dc4a0411c2ba0bbfd1814dffa368c47
[ "MIT" ]
null
null
null
src/parsing.cpp
MicroTransactionsMatterToo/midiparser-cpp
1e95cc445dc4a0411c2ba0bbfd1814dffa368c47
[ "MIT" ]
null
null
null
src/parsing.cpp
MicroTransactionsMatterToo/midiparser-cpp
1e95cc445dc4a0411c2ba0bbfd1814dffa368c47
[ "MIT" ]
null
null
null
// Copyright Ennis Massey 18/12/16 // // Created by Ennis Massey on 18/12/16. // #include "parsing.h" uint32_t midiparser::ParseUint32(std::ifstream &input_file) { // If the file isn't open, return 0 if (!input_file.is_open()) { return (uint32_t) 0; } // Create buffer char buffer[4]; // Read from stream input_file.read(buffer, 4); // If we couldn't read 4 bytes, we just return 0 if (input_file.eof()) { return (uint32_t) 0; } uint32_t value = (uint32_t) 0x00; value |= (uint32_t) buffer[3] << 0; value |= (uint32_t) buffer[2] << 8; value |= (uint32_t) buffer[1] << 16; value |= (uint32_t) buffer[0] << 24; return value; } uint32_t midiparser::ParseUint24(std::ifstream &input_file) { // If the file isn't open, return 0 if (!input_file.is_open()) { return (uint32_t) 0; } // Create buffer char buffer[3]; // Read from stream input_file.read(buffer, 3); // If we couldn't read 3 bytes, return 0 if (input_file.eof()) { return (uint32_t) 0; } uint32_t value = 0x00; value |= (uint32_t) buffer[2] << 0; value |= (uint32_t) buffer[1] << 8; value |= (uint32_t) buffer[0] << 16; return value; } uint16_t midiparser::ParseUint16(std::ifstream &input_file) { // If the file isn't open, return 0 if (!input_file.is_open()) { return (uint16_t) 0; } // Create buffer char buffer[2]; // Read from stream input_file.read(buffer, 2); if (input_file.eof()) { return (uint16_t) 0; } uint16_t value = 0x00; value |= (uint16_t) buffer[1] << 0; value |= (uint16_t) buffer[0] << 8; return value; } uint8_t midiparser::ParseUint7(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint8_t) 0; } char buffer[1]; input_file.read(buffer, 1); if (input_file.eof()) { return (uint8_t) 0; } uint8_t value = 0x00; value = (uint8_t) (buffer[0] & 0x7F); return value; } std::tuple<uint8_t, uint8_t> midiparser::ParseTwoUint7(std::ifstream &input_file) { if (!input_file.is_open()) { return std::make_tuple((uint8_t) 0, (uint8_t) 0); } char buffer[2]; input_file.read(buffer, 2); if (input_file.eof()) { return std::make_tuple((uint8_t) 0, (uint8_t) 0); } uint8_t value_one = (uint8_t) (buffer[0] & 0x7F); uint8_t value_two = (uint8_t) (buffer[1] & 0x7F); std::tuple<uint8_t, uint8_t> value = std::make_tuple(value_one, value_two); return value; } uint8_t midiparser::ParseUint8(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint8_t) 0; } char buffer[1]; input_file.read(buffer, 1); if (input_file.eof()) { return (uint8_t) 0; } return (uint8_t) buffer[0]; } int8_t midiparser::ParseInt8(std::ifstream &input_file) { if (!input_file.is_open()) { return (int8_t) 0; } char buffer[1]; input_file.read(buffer, 1); if (input_file.eof()) { return (int8_t) 0; } return (int8_t) buffer[0]; } uint16_t midiparser::ParsePitchWheelValue(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint16_t) 0; } char buffer[2]; input_file.read(buffer, 2); if (input_file.eof()) { return (uint16_t) 0; } uint16_t value = 0x00; value = (uint16_t) (buffer[1] & 0x7F); value <<= 7; value |= (uint16_t) (buffer[0] & 0x7F); return value; } uint32_t midiparser::ParseVariableLengthValue(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint32_t) 0; } char buffer[1]; bool did_return = false; uint32_t value = 0x00; bool first = true; while (first || (((buffer[0] & 0x80) == 0x80) && (did_return))) { value <<= 7; input_file.read(buffer, 1); if (input_file.eof()) { did_return = false; break; } did_return = true; value |= (uint32_t) buffer[0] & 0x7F; first = false; } return value; }
24.819277
83
0.583252
2b4fd467987270f15e141aee6f8c40202a83aa58
1,165
cpp
C++
protocol/src/protocol.cpp
danielmiester/OpenSlider
a374db0fe4b2f9b9e397b9052f0af5fbe8369211
[ "MIT" ]
null
null
null
protocol/src/protocol.cpp
danielmiester/OpenSlider
a374db0fe4b2f9b9e397b9052f0af5fbe8369211
[ "MIT" ]
null
null
null
protocol/src/protocol.cpp
danielmiester/OpenSlider
a374db0fe4b2f9b9e397b9052f0af5fbe8369211
[ "MIT" ]
null
null
null
#include "protocol.h" //#123:123,123; Protocol::Protocol(address_t addr){ _buf = malloc(PROTOCOL_BUF_SIZE); _address = addr; _command = Protocol::VERB::IDLE; } Protocol::inputData(size_t len, char* data){ } Protocol::setAddress(address_t addr){ _address = addr; } Protocol::stateMachine(char data){ switch(state){ case Protocol::STATE::IDLE: if(_prev_char != '\\'){ switch(data){ case Protocol::VERB::QUERY: case Protocol::VERB::SET: case Protocol::VERB::ANNC: case Protocol::VERB::SYS: _state = Protocol::STATE::FOUND_VERB; _command = (Protocol::VERB)data; _error = 0; break; default: _state = Protocol::STATE::IDLE; _command = Protocol::VERB::IDLE; _error = -1; break; } } break; case Protocol::STATE::FOUND_VERB: switch(data){ case '0' ... '9': _buf[_buf_pointer++] = data; case ':': _state = Protocol::STATE::FOUND_ADDR_DELIM; _command = } } } Protocol::processData(char data){ this->stateMachine(data); switch(state){ case } }
21.981132
55
0.569099
2b531c733edd0986429110aec5a426add9e73335
354
hpp
C++
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
292
2020-03-19T22:38:52.000Z
2022-03-05T22:49:34.000Z
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
#pragma once #include <natus/memory/allocator.hpp> #include <vector> namespace natus { namespace ntd { //template< typename T > //using vector = ::std::vector< T, natus::memory::allocator<T> > ; // for now, we use the default allocator template< typename T > using vector = ::std::vector< T > ; } }
19.666667
74
0.581921
2b5441573aab4a4ad911786a7ae38e80d31a1a94
2,276
cpp
C++
src/camera.cpp
LesleyLai/GLGrassRenderer
34c9a4822f1908e35620f10298839c96ab830958
[ "Apache-2.0" ]
57
2019-02-24T00:54:07.000Z
2022-03-09T22:08:59.000Z
src/camera.cpp
LesleyLai/GLGrassRenderer
34c9a4822f1908e35620f10298839c96ab830958
[ "Apache-2.0" ]
null
null
null
src/camera.cpp
LesleyLai/GLGrassRenderer
34c9a4822f1908e35620f10298839c96ab830958
[ "Apache-2.0" ]
11
2019-08-30T13:04:10.000Z
2021-12-25T04:03:49.000Z
#include "camera.hpp" Camera::Camera(glm::vec3 position, glm::vec3 up, float yaw, float pitch) : front_(glm::vec3(0.0f, 0.0f, -1.0f)), speed_(initial_speed), mouse_sensitivity_(init_sensitivity), zoom_(init_zoom) { position_ = position; world_up_ = up; yam_ = yaw; pitch_ = pitch; update_camera_vectors(); } void Camera::move(Camera::Movement direction, std::chrono::duration<float, std::milli> delta_time) { float dx = speed_ * delta_time.count() / 1000; switch (direction) { case Camera::Movement::forward: position_ += front_ * dx; break; case Camera::Movement::backward: position_ -= front_ * dx; break; case Camera::Movement::left: position_ -= right_ * dx; break; case Camera::Movement::right: position_ += right_ * dx; break; } } void Camera::mouse_movement(float xoffset, float yoffset, GLboolean constrainPitch) { xoffset *= mouse_sensitivity_; yoffset *= mouse_sensitivity_; yam_ += xoffset; pitch_ += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (pitch_ > 89.0f) { pitch_ = 89.0f; } if (pitch_ < -89.0f) { pitch_ = -89.0f; } } // Update Front, Right and Up Vectors using the updated Euler angles update_camera_vectors(); } void Camera::mouse_scroll(float yoffset) { if (zoom_ >= 1.0f && zoom_ <= 45.0f) { zoom_ -= yoffset; } if (zoom_ <= 1.0f) { zoom_ = 1.0f; } if (zoom_ >= 45.0f) { zoom_ = 45.0f; } } void Camera::update_camera_vectors() { // Calculate the new Front vector glm::vec3 front; front.x = std::cos(glm::radians(yam_)) * std::cos(glm::radians(pitch_)); front.y = std::sin(glm::radians(pitch_)); front.z = std::sin(glm::radians(yam_)) * std::cos(glm::radians(pitch_)); front_ = glm::normalize(front); // Also re-calculate the Right and Up vector right_ = glm::normalize(glm::cross( front_, world_up_)); // Normalize the vectors, because their length gets // closer to 0 the more you look up or down which // results in slower movement. up_ = glm::normalize(glm::cross(right_, front_)); }
26.776471
79
0.614675
2b5c0973d77dc6cbcd0829a6c30084dc53a6eb39
112
cc
C++
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
17
2016-11-27T13:13:40.000Z
2021-09-07T06:42:25.000Z
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
22
2017-01-18T06:10:18.000Z
2019-05-15T03:49:19.000Z
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
5
2017-07-24T15:19:32.000Z
2022-02-19T09:11:01.000Z
#include "reply.hh" using namespace eclipse::messages; std::string Reply::get_type() const { return "Reply"; }
22.4
55
0.723214
2b605c0a5c1cfdd09444dd5187f3d3a7193f9301
1,994
hpp
C++
include/Zelta/Core/RenderLayer.hpp
RafaelGC/ese
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
1
2018-01-28T21:35:14.000Z
2018-01-28T21:35:14.000Z
include/Zelta/Core/RenderLayer.hpp
RafaelGC/ese
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
1
2018-01-23T02:03:45.000Z
2018-01-23T02:03:45.000Z
include/Zelta/Core/RenderLayer.hpp
rafaelgc/ESE
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
null
null
null
#ifndef ZELTALIB_LAYER_HPP #define ZELTALIB_LAYER_HPP #include <vector> #include <SFML/Graphics/Drawable.hpp> // Base class: sf::Drawable #include <SFML/Graphics/RenderTarget.hpp> namespace zt { /** * @brief Container for drawable objects. * This class allows you to group sf::Drawable elements such as sf::Sprite. * The container keeps pointers to the objects, so your drawable objects * should be kept alive while using the render layer. * */ class RenderLayer : public sf::Drawable { protected: /** * @brief If it's false the contained objects won't be drawn. * */ bool visible; /** * @brief Vector que contiene un puntero a los dibujables de esta capa. * */ std::vector<sf::Drawable*>drawableItems; public: /** * @brief Constructs an empty layer. * */ RenderLayer(bool visible = true); virtual ~RenderLayer(); /** * @brief Draws all contained objects if the layer is visible. * */ virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; /** * @brief Adds a drawable. * */ void addDrawable(sf::Drawable &item); /** * @brief Removes a drawable if it exists. * @param item Drawable you cant to remove. * @return True if it was removed. */ bool removeDrawable(sf::Drawable & item); /** * @brief Sets the visibility. * */ void setVisible(bool visible); bool isVisible() const; int getZ() const; void setZ(int z); unsigned int count() const; bool isEmpty() const; /** * Compares the depth of the layer. * @param other * @return */ bool operator<(zt::RenderLayer & other) const; }; } #endif // LAYER_HPP
26.236842
83
0.549147
2b6481839159df93be542ffbc8d7757e642639bd
1,127
cpp
C++
src/gpu_monitor_hip.cpp
enp1s0/gpu_monitor
3d1ebb39803861e57670d08ead883d1208d6e35b
[ "MIT" ]
null
null
null
src/gpu_monitor_hip.cpp
enp1s0/gpu_monitor
3d1ebb39803861e57670d08ead883d1208d6e35b
[ "MIT" ]
null
null
null
src/gpu_monitor_hip.cpp
enp1s0/gpu_monitor
3d1ebb39803861e57670d08ead883d1208d6e35b
[ "MIT" ]
null
null
null
#include <hiptf/device.hpp> #include <hiptf/rsmi.hpp> #include "gpu_monitor_hip.hpp" void mtk::gpu_monitor::gpu_monitor_hip::init() { HIPTF_CHECK_ERROR(rsmi_init(0)); } void mtk::gpu_monitor::gpu_monitor_hip::shutdown() { } std::size_t mtk::gpu_monitor::gpu_monitor_hip::get_num_devices() const { return hiptf::device::get_num_devices(); } std::size_t mtk::gpu_monitor::gpu_monitor_hip::get_current_device() const { return hiptf::device::get_device_id(); } double mtk::gpu_monitor::gpu_monitor_hip::get_current_temperature(const unsigned gpu_id) const { int64_t temperature; HIPTF_CHECK_ERROR(rsmi_dev_temp_metric_get(gpu_id, 0, RSMI_TEMP_CURRENT, &temperature)); return temperature / 1000.0; } double mtk::gpu_monitor::gpu_monitor_hip::get_current_power(const unsigned gpu_id) const { uint64_t power; HIPTF_CHECK_ERROR(rsmi_dev_power_cap_get(gpu_id, 0, &power)); return power / 1000000.0; } std::size_t mtk::gpu_monitor::gpu_monitor_hip::get_current_used_memory(const unsigned gpu_id) const { uint64_t used; HIPTF_CHECK_ERROR(rsmi_dev_memory_usage_get(gpu_id, RSMI_MEM_TYPE_VRAM, &used)); return used; }
28.175
101
0.785271
2b6a60525f50008936b2c335749c76337bbd685d
935
cpp
C++
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
106
2021-07-04T01:10:18.000Z
2022-03-21T00:58:27.000Z
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
119
2021-07-10T14:26:24.000Z
2022-03-22T22:48:18.000Z
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
7
2021-07-23T11:23:04.000Z
2021-11-13T20:22:56.000Z
/** * \example strand.cpp * Simple \ref Strand examples */ #include <yaclib/executor/strand.hpp> #include <yaclib/executor/thread_pool.hpp> #include <iostream> #include <gtest/gtest.h> using namespace yaclib; TEST(Example, Strand) { std::cout << "Strand" << std::endl; auto tp = MakeThreadPool(4); auto strand = MakeStrand(tp); size_t counter = 0; static constexpr size_t kThreads = 5; static constexpr size_t kIncrementsPerThread = 12345; std::vector<std::thread> threads; for (size_t i = 0; i < kThreads; ++i) { threads.emplace_back([&]() { for (size_t j = 0; j < kIncrementsPerThread; ++j) { strand->Execute([&] { ++counter; }); } }); } for (auto& t : threads) { t.join(); } tp->Stop(); tp->Wait(); std::cout << "Counter value = " << counter << ", expected " << kThreads * kIncrementsPerThread << std::endl; std::cout << std::endl; }
18.7
110
0.59893
2b6d76ef984531a8a4aa2be05d6e7ede8a9f96a9
12,142
cpp
C++
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
28
2015-05-22T16:03:29.000Z
2022-01-15T12:12:46.000Z
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
15
2015-10-21T11:19:09.000Z
2020-07-15T05:01:12.000Z
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
8
2017-01-21T00:31:17.000Z
2018-08-12T13:28:57.000Z
/** ** Copyright (c) 2014 Illumina, Inc. ** ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE), ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** \description Generation of random/uniform intervals with precise boundaries ** Based on: ** [1] Jon Louis Bentley and James B. Saxe. 1980. Generating Sorted Lists of Random Numbers. ** ACM Trans. Math. Softw. 6, 3 (September 1980), 359-364. ** DOI=10.1145/355900.355907 http://doi.acm.org/10.1145/355900.355907 ** ** \author Lilian Janin **/ #include <numeric> #include <boost/foreach.hpp> #include <boost/format.hpp> #include "common/Exceptions.hh" #include "model/IntervalGenerator.hh" using namespace std; namespace eagle { namespace model { // Class RandomSequenceGenerator unsigned long RandomSequenceGenerator::getNext() { return static_cast<unsigned long>( floor(getNextAsDouble()) ); } bool RandomSequenceGenerator::hasFinished() { return (remainingSampleCount_ <= 0); } double RandomSequenceGenerator::getNextAsDouble() { if (remainingSampleCount_ <= 0) { BOOST_THROW_EXCEPTION( eagle::common::EagleException( 0, "RandomSequenceGenerator: all samples have already been generated") ); } double rand0to1 = (1.0+rand())/(1.0+RAND_MAX); curMax_ *= exp(log(rand0to1)/remainingSampleCount_); remainingSampleCount_--; return (1-curMax_)*intervalSize_; } // Class RandomIntervalGenerator pair< unsigned long, unsigned int > RandomIntervalGenerator::getNext( const signed long testValue ) { unsigned long intervalNum = (testValue<0)?randomSeq_.getNext():testValue; // Convert intervalNum to interval while ( intervalNum > currentContigIntervalInfo_->lastInterval || currentContigIntervalInfo_->lastInterval == 0xFFFFFFFFFFFFFFFF ) { ++currentContigIntervalInfo_; if (verbose_) { clog << "Generating fragments for chromosome starting at global pos " << currentContigIntervalInfo_->firstIntervalGlobalPos << endl; } } assert( intervalNum >= currentContigIntervalInfo_->firstInterval ); pair< unsigned long, unsigned int > p; if ( intervalNum < currentContigIntervalInfo_->firstSmallerInterval ) { unsigned long localIntervalNum = intervalNum - currentContigIntervalInfo_->firstInterval; p.first = currentContigIntervalInfo_->firstIntervalGlobalPos + localIntervalNum / intervalsPerNormalPosition_; p.second = minFragmentLength_ + localIntervalNum % intervalsPerNormalPosition_; } else { // static unsigned long lastSmallerIntervalNum = -1; // if ( currentContigIntervalInfo_->firstSmallerInterval != lastSmallerIntervalNum ) { unsigned long localIntervalNum = intervalNum - currentContigIntervalInfo_->firstSmallerInterval; unsigned int intervalCountForThisPos = maxFragmentLength_ - minFragmentLength_; unsigned long currentPos = currentContigIntervalInfo_->firstSmallerIntervalGlobalPos; while (intervalCountForThisPos > 0) { if ( localIntervalNum < intervalCountForThisPos ) { p.first = currentPos; p.second = localIntervalNum + minFragmentLength_; break; } localIntervalNum -= intervalCountForThisPos; --intervalCountForThisPos; ++currentPos; } assert( intervalCountForThisPos>0 && "should never happen" ); } } return p; } unsigned long RandomIntervalGenerator::getIntervalCount() { unsigned long intervalCount = 0; unsigned long globalPos = 0; BOOST_FOREACH( const unsigned long l, contigLengths_ ) { struct ContigIntervalInfo intervalInfo; intervalInfo.firstInterval = intervalCount; intervalInfo.firstIntervalGlobalPos = globalPos; if ( l+1 >= maxFragmentLength_ ) { unsigned long normalPositionCount = l - maxFragmentLength_ + 1; intervalCount += intervalsPerNormalPosition_ * normalPositionCount; intervalInfo.firstSmallerInterval = intervalCount; intervalCount += intervalsPerNormalPosition_ * (intervalsPerNormalPosition_-1) / 2; intervalInfo.firstSmallerIntervalGlobalPos = globalPos + normalPositionCount; } else { intervalInfo.firstSmallerIntervalGlobalPos = 0; EAGLE_WARNING( "Chromosome shorter than insert length" ); } intervalInfo.lastInterval = intervalCount - 1; if (verbose_) { clog << "Chromosome at global pos " << globalPos << " has " << (intervalInfo.lastInterval-intervalInfo.firstInterval+1) << " intervals" << endl; } globalPos += l; contigIntervalInfo_.push_back( intervalInfo ); } return intervalCount; } // Class RandomIntervalGeneratorUsingIntervalLengthDistribution pair< unsigned long, unsigned int > RandomIntervalGeneratorUsingIntervalLengthDistribution::getNext( const signed long testValue ) { assert( testValue < 0 ); // positive test case not implemented if (randomSeq_.hasFinished()) { return make_pair(0,0); } double randomPos = randomSeq_.getNextAsDouble(); // randomPos => currentPos double probaOfCurrentPos = getIntervalsProbaAtPos( currentPos_ ); while (randomPos >= accumulatedProbasUntilCurrentPos_ + probaOfCurrentPos) { accumulatedProbasUntilCurrentPos_ += probaOfCurrentPos; ++currentPos_; probaOfCurrentPos = getIntervalsProbaAtPos( currentPos_ ); } // randomPos(-currentPos) => fragmentLength unsigned int fragmentLength = fragmentLengthDist_.min(); double probaDiff = randomPos - accumulatedProbasUntilCurrentPos_; while (probaDiff > fragmentLengthDist_[fragmentLength]) { probaDiff -= fragmentLengthDist_[fragmentLength++]; } return make_pair( currentPos_, fragmentLength ); } double RandomIntervalGeneratorUsingIntervalLengthDistribution::getIntervalsProbaAtPos( unsigned long globalPos ) { assert( contigLengths_.size() == 1 ); // We restrict the current implementation to one contig at a time const unsigned long contigLength = contigLengths_[0]; if (globalPos + fragmentLengthDist_.max() < contigLength) { return 1.0; } else { unsigned int distanceToContigEnd = contigLength - globalPos; unsigned int index = fragmentLengthDist_.max() - distanceToContigEnd; if (index >= probas_.size()) { // We expect to build the index 1 entry at a time( index == probas_.size() most of the time), but we need to skip some initial entries for chromosomes smaller than the max template length if (index > probas_.size()) { probas_.resize( index, 0 ); } double p = 0; for (unsigned int i=fragmentLengthDist_.min(); i<=distanceToContigEnd; ++i) { p += fragmentLengthDist_[i]; } probas_.push_back( p ); // clog << (boost::format("Adding proba %f at index %d (for globalPos %d)") % p % index % globalPos).str() << endl; } return probas_[index]; } } double RandomIntervalGeneratorUsingIntervalLengthDistribution::getTotalIntervalsProba() { assert( contigLengths_.size() == 1 ); // We restrict the current implementation to one contig at a time const unsigned long contigLength = contigLengths_[0]; double intervalCount = 0; for (unsigned long globalPos=0; globalPos<contigLength; ++globalPos) { intervalCount += getIntervalsProbaAtPos( globalPos ); } if (verbose_) { EAGLE_DEBUG( 0, "Contig's total intervals probability: " << intervalCount ); } return intervalCount; } // Class UniformIntervalGenerator UniformIntervalGenerator::UniformIntervalGenerator( const vector<unsigned long>& contigLengths, const unsigned int medianFragmentLength, const double step, unsigned long& readCount, bool verbose) : IntervalGenerator( contigLengths, readCount, medianFragmentLength, medianFragmentLength, medianFragmentLength, verbose) , step_( step ) { unsigned long intervalCount = 0; unsigned long globalPos = 0; BOOST_FOREACH( const unsigned long l, contigLengths_ ) { struct ContigIntervalInfo intervalInfo; intervalInfo.firstGlobalPos = globalPos; unsigned long contigValidPosCount = l - medianFragmentLength + 1; intervalCount += contigValidPosCount; intervalInfo.lastGlobalPos = globalPos + contigValidPosCount - 1; globalPos += l; contigIntervalInfo_.push_back( intervalInfo ); } currentContigIntervalInfo_ = contigIntervalInfo_.begin(); currentGlobalPos_ = 0 - step_; unsigned long newReadCount = static_cast<unsigned long>( (double)intervalCount / step_ ); if (verbose_) { clog << (boost::format("Uniform coverage attempts to achieve the specified coverage depth for all the chromosome positions, which is impossible to achieve at the chromosome extremities => the average coverage depth will be lower than specified. Changing read count from %d to %d, for a step of %d") % readCount % newReadCount % step_).str() << endl; } readCount = newReadCount; } pair< unsigned long, unsigned int > UniformIntervalGenerator::getNext( const signed long testValue ) { currentGlobalPos_ += step_; // Convert intervalNum to interval while ( floor(currentGlobalPos_) > currentContigIntervalInfo_->lastGlobalPos ) { if ( currentContigIntervalInfo_+1 != contigIntervalInfo_.end() ) { ++currentContigIntervalInfo_; currentGlobalPos_ = currentContigIntervalInfo_->firstGlobalPos; if (verbose_) { clog << "Generating fragments for chromosome starting at global pos " << currentContigIntervalInfo_->firstGlobalPos << endl; } } else { return make_pair( 0, 0 ); //EAGLE_WARNING( "Too many reads generated at the end!" ); } } assert( floor(currentGlobalPos_) >= currentContigIntervalInfo_->firstGlobalPos ); return std::make_pair( (unsigned long)floor(currentGlobalPos_), medianFragmentLength_ ); } pair< unsigned long, unsigned int > RandomIntervalGeneratorFromProbabilityMatrix::getNext( const signed long testValue ) { if (remainingSampleCount_ > 0) { double rand0to1 = (1.0+rand())/(1.0+RAND_MAX); curMax_ *= exp(log(rand0to1)/remainingSampleCount_); remainingSampleCount_--; double choice = (1-curMax_) * intervalSize_; lastChoiceRemainder += choice - lastChoice; while (lastChoiceRemainder >= fragmentLengthProbabilityMatrix_.getProbabilities()[ lastChoiceIndex ]) { lastChoiceRemainder -= fragmentLengthProbabilityMatrix_.getProbabilities()[ lastChoiceIndex ]; if (lastChoiceIndex < fragmentLengthProbabilityMatrix_.getProbabilities().size()) { ++lastChoiceIndex; } else { // Avoid going past the end of the array because of rounding errors break; } } lastChoice = choice; unsigned long pickedGlobalPos = lastChoiceIndex / fragmentLengthDist_size; unsigned long pickedFragmentLength = lastChoiceIndex % fragmentLengthDist_size + fragmentLengthDist_min; cout << (boost::format("remainingSampleCount_=%d, choice=%f, choiceIndex=%d, pickedGlobalPos=%d, pickedFragmentLength=%d") % remainingSampleCount_ % choice % lastChoiceIndex % pickedGlobalPos % pickedFragmentLength).str() << endl; return make_pair( pickedGlobalPos, pickedFragmentLength ); } else { EAGLE_WARNING( "Too many reads generated at the end!" ); return make_pair( 0, 0 ); } } } // namespace model } // namespace eagle
37.36
357
0.674848
2b6edefa630bd18dcd564cccb200219b6dcbb4d4
4,791
cpp
C++
src/web/downloadthread.cpp
quizzmaster/chemkit
803e4688b514008c605cb5c7790f7b36e67b68fc
[ "BSD-3-Clause" ]
34
2015-01-24T23:59:41.000Z
2020-11-12T13:48:01.000Z
src/web/downloadthread.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
4
2015-12-28T20:29:16.000Z
2016-01-26T06:48:19.000Z
src/web/downloadthread.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
17
2015-01-23T14:50:24.000Z
2021-06-10T15:43:50.000Z
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project 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 "downloadthread.h" namespace chemkit { // === DownloadThread ====================================================== // /// \class DownloadThread downloadthread.h /// \ingroup chemkit-web /// \internal /// \brief The DownloadThread class provides an interface for /// downloading data from the web. // --- Construction and Destruction ---------------------------------------- // /// Creates a new download thread object. DownloadThread::DownloadThread(const QUrl &url) : QThread(), m_url(url) { m_manager = 0; m_ftp = 0; m_reply = 0; } /// Destroys the download thread object. DownloadThread::~DownloadThread() { delete m_ftp; delete m_manager; } // --- Properties ---------------------------------------------------------- // /// Returns the downloaded data. QByteArray DownloadThread::data() const { return m_data; } // --- Thread -------------------------------------------------------------- // /// Starts the download. /// /// This method should not be called directly. Use QThread::start(). void DownloadThread::run() { if(m_url.scheme() == "ftp"){ m_dataBuffer.open(QBuffer::ReadWrite); m_ftp = new QFtp; connect(m_ftp, SIGNAL(done(bool)), SLOT(ftpDone(bool)), Qt::DirectConnection); m_ftp->connectToHost(m_url.host()); m_ftp->login("anonymous", "chemkit"); QFileInfo fileInfo(m_url.path()); m_ftp->cd(fileInfo.path() + "/"); m_ftp->get(fileInfo.fileName(), &m_dataBuffer); m_ftp->close(); } else{ m_manager = new QNetworkAccessManager; connect(m_manager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*)), Qt::DirectConnection); m_reply = m_manager->get(QNetworkRequest(m_url)); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)), Qt::DirectConnection); } exec(); } // --- Static Methods ------------------------------------------------------ // /// Downloads and returns the data from \p url. QByteArray DownloadThread::download(const QUrl &url) { DownloadThread thread(url); thread.start(); thread.wait(); return thread.data(); } // --- Slots --------------------------------------------------------------- // void DownloadThread::replyFinished(QNetworkReply *reply) { m_data = reply->readAll(); reply->deleteLater(); m_manager->deleteLater(); exit(0); } void DownloadThread::replyError(QNetworkReply::NetworkError error) { Q_UNUSED(error); qDebug() << "chemkit-web: DownloadThread Error: " << m_reply->errorString(); } void DownloadThread::ftpDone(bool error) { if(error){ qDebug() << "chemkit-web: DownloadThread Ftp Error:" << m_ftp->errorString(); exit(-1); } m_data = m_dataBuffer.data(); exit(0); } } // end chemkit namespace
33.041379
86
0.615947
2b6feb5740721ab22d1b8a61391e5f5f9cb7af52
60
cpp
C++
common/UIOverlay.cpp
daozhangXDZ/OpenGLES_Examples
9266842fbd0ae899446b6ccda9cd63eeeaf1451f
[ "MIT" ]
248
2019-06-04T16:46:24.000Z
2022-02-13T11:21:14.000Z
common/UIOverlay.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
null
null
null
common/UIOverlay.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
40
2019-07-18T09:59:22.000Z
2021-09-17T13:00:05.000Z
// Implementation of Common library #include "UIOverlay.h"
20
36
0.766667
2b763a401e508f70e6f79004fda13fa62b744358
10,614
cpp
C++
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
1
2020-06-16T11:45:26.000Z
2020-06-16T11:45:26.000Z
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
null
null
null
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
null
null
null
#include "mpegts_muxer.h" #include "simple_buffer.h" #include "ts_packet.h" #include "crc.h" #include <string.h> #include "common.h" static const uint16_t MPEGTS_NULL_PACKET_PID = 0x1FFF; static const uint16_t MPEGTS_PAT_PID = 0x00; static const uint16_t MPEGTS_PMT_PID = 0x100; static const uint16_t MPEGTS_PCR_PID = 0x110; class MpegTsAdaptationFieldType { public: // Reserved for future use by ISO/IEC static const uint8_t mReserved = 0x00; // No adaptation_field, payload only static const uint8_t mPayloadOnly = 0x01; // Adaptation_field only, no payload static const uint8_t mAdaptionOnly = 0x02; // Adaptation_field followed by payload static const uint8_t mPayloadAdaptionBoth = 0x03; }; MpegTsMuxer::MpegTsMuxer() { } MpegTsMuxer::~MpegTsMuxer() { } void MpegTsMuxer::createPat(SimpleBuffer *pSb, uint16_t lPmtPid, uint8_t lCc) { int lPos = pSb->pos(); TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 1; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_PAT_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = lCc; AdaptationFieldHeader lAdaptField; PATHeader lPatHeader; lPatHeader.mTableId = 0x00; lPatHeader.mSectionSyntaxIndicator = 1; lPatHeader.mB0 = 0; lPatHeader.mReserved0 = 0x3; lPatHeader.mTransportStreamId = 0; lPatHeader.mReserved1 = 0x3; lPatHeader.mVersionNumber = 0; lPatHeader.mCurrentNextIndicator = 1; lPatHeader.mSectionNumber = 0x0; lPatHeader.mLastSectionNumber = 0x0; //program_number uint16_t lProgramNumber = 0x0001; //program_map_PID uint16_t lProgramMapPid = 0xe000 | (lPmtPid & 0x1fff); unsigned int lSectionLength = 4 + 4 + 5; lPatHeader.mSectionLength = lSectionLength & 0x3ff; lTsHeader.encode(pSb); lAdaptField.encode(pSb); lPatHeader.encode(pSb); pSb->write_2bytes(lProgramNumber); pSb->write_2bytes(lProgramMapPid); // crc32 uint32_t lCrc32 = crc32((uint8_t *) pSb->data() + 5, pSb->pos() - 5); pSb->write_4bytes(lCrc32); std::string lStuff(188 - (pSb->pos() - lPos), 0xff); pSb->write_string(lStuff); } void MpegTsMuxer::createPmt(SimpleBuffer *pSb, std::map<uint8_t, int> lStreamPidMap, uint16_t lPmtPid, uint8_t lCc) { int lPos = pSb->pos(); TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 1; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = lPmtPid; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = lCc; AdaptationFieldHeader lAdaptField; PMTHeader lPmtHeader; lPmtHeader.mTableId = 0x02; lPmtHeader.mSectionSyntaxIndicator = 1; lPmtHeader.mB0 = 0; lPmtHeader.mReserved0 = 0x3; lPmtHeader.mSectionLength = 0; lPmtHeader.mProgramNumber = 0x0001; lPmtHeader.mReserved1 = 0x3; lPmtHeader.mVersionNumber = 0; lPmtHeader.mCurrentNextIndicator = 1; lPmtHeader.mSectionNumber = 0x00; lPmtHeader.mLastSectionNumber = 0x00; lPmtHeader.mReserved2 = 0x7; lPmtHeader.mReserved3 = 0xf; lPmtHeader.mProgramInfoLength = 0; for (auto lIt = lStreamPidMap.begin(); lIt != lStreamPidMap.end(); lIt++) { lPmtHeader.mInfos.push_back(std::shared_ptr<PMTElementInfo>(new PMTElementInfo(lIt->first, lIt->second))); if (lIt->first == MpegTsStream::AVC) { lPmtHeader.mPcrPid = lIt->second; } } uint16_t lSectionLength = lPmtHeader.size() - 3 + 4; lPmtHeader.mSectionLength = lSectionLength & 0x3ff; lTsHeader.encode(pSb); lAdaptField.encode(pSb); lPmtHeader.encode(pSb); // crc32 uint32_t lCrc32 = crc32((uint8_t *) pSb->data() + lPos + 5, pSb->pos() - lPos - 5); pSb->write_4bytes(lCrc32); std::string lStuff(188 - (pSb->pos() - lPos), 0xff); pSb->write_string(lStuff); } void MpegTsMuxer::createPes(TsFrame *pFrame, SimpleBuffer *pSb) { bool lFirst = true; while (!pFrame->mData->empty()) { SimpleBuffer lPacket(188); TsHeader lTsHeader; lTsHeader.mPid = pFrame->mPid; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = getCc(pFrame->mStreamType); if (lFirst) { lTsHeader.mPayloadUnitStartIndicator = 0x01; if (pFrame->mStreamType == MpegTsStream::AVC) { lTsHeader.mAdaptationFieldControl |= 0x02; AdaptationFieldHeader adapt_field_header; adapt_field_header.mAdaptationFieldLength = 0x07; adapt_field_header.mRandomAccessIndicator = 0x01; adapt_field_header.mPcrFlag = 0x01; lTsHeader.encode(&lPacket); adapt_field_header.encode(&lPacket); writePcr(&lPacket, pFrame->mDts); } else { lTsHeader.encode(&lPacket); } PESHeader lPesHeader; lPesHeader.mPacketStartCode = 0x000001; lPesHeader.mStreamId = pFrame->mStreamId; lPesHeader.mMarkerBits = 0x02; lPesHeader.mOriginalOrCopy = 0x01; if (pFrame->mPts != pFrame->mDts) { lPesHeader.mPtsDtsFlags = 0x03; lPesHeader.mHeaderDataLength = 0x0A; } else { lPesHeader.mPtsDtsFlags = 0x2; lPesHeader.mHeaderDataLength = 0x05; } uint32_t lPesSize = (lPesHeader.mHeaderDataLength + pFrame->mData->size() + 3); lPesHeader.mPesPacketLength = lPesSize > 0xffff ? 0 : lPesSize; lPesHeader.encode(&lPacket); if (lPesHeader.mPtsDtsFlags == 0x03) { writePts(&lPacket, 3, pFrame->mPts); writePts(&lPacket, 1, pFrame->mDts); } else { writePts(&lPacket, 2, pFrame->mPts); } lFirst = false; } else { lTsHeader.encode(&lPacket); } uint32_t lBodySize = lPacket.size() - lPacket.pos(); uint32_t lInSize = pFrame->mData->size() - pFrame->mData->pos(); if (lBodySize <= lInSize) { // MpegTsAdaptationFieldType::payload_only or MpegTsAdaptationFieldType::payload_adaption_both for AVC lPacket.write_string(pFrame->mData->read_string(lBodySize)); } else { uint16_t lStuffSize = lBodySize - lInSize; if (lTsHeader.mAdaptationFieldControl == MpegTsAdaptationFieldType::mAdaptionOnly || lTsHeader.mAdaptationFieldControl == MpegTsAdaptationFieldType::mPayloadAdaptionBoth) { char *lpBase = lPacket.data() + 5 + lPacket.data()[4]; lPacket.setData(lpBase - lPacket.data() + lStuffSize, lpBase, lPacket.data() + lPacket.pos() - lpBase); memset(lpBase, 0xff, lStuffSize); lPacket.skip(lStuffSize); lPacket.data()[4] += lStuffSize; } else { // adaptationFieldControl |= 0x20 == MpegTsAdaptationFieldType::payload_adaption_both lPacket.data()[3] |= 0x20; lPacket.setData(188 - 4 - lStuffSize, lPacket.data() + 4, lPacket.pos() - 4); lPacket.skip(lStuffSize); lPacket.data()[4] = lStuffSize - 1; if (lStuffSize >= 2) { lPacket.data()[5] = 0; memset(&(lPacket.data()[6]), 0xff, lStuffSize - 2); } } lPacket.write_string(pFrame->mData->read_string(lInSize)); } pSb->append(lPacket.data(), lPacket.size()); } } void MpegTsMuxer::createPcr(SimpleBuffer *pSb) { uint64_t lPcr = 0; TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 0; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_PCR_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mAdaptionOnly; lTsHeader.mContinuityCounter = 0; AdaptationFieldHeader lAdaptField; lAdaptField.mAdaptationFieldLength = 188 - 4 - 1; lAdaptField.mSiscontinuityIndicator = 0; lAdaptField.mRandomAccessIndicator = 0; lAdaptField.mElementaryStreamPriorityIndicator = 0; lAdaptField.mPcrFlag = 1; lAdaptField.mOpcrFlag = 0; lAdaptField.mSplicingPointFlag = 0; lAdaptField.mTransportPrivateDataFlag = 0; lAdaptField.mAdaptationFieldExtensionFlag = 0; char *p = pSb->data(); lTsHeader.encode(pSb); lAdaptField.encode(pSb); writePcr(pSb, lPcr); } void MpegTsMuxer::createNull(SimpleBuffer *pSb) { TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 0; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_NULL_PACKET_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = 0; lTsHeader.encode(pSb); } void MpegTsMuxer::encode(TsFrame *pFrame, std::map<uint8_t, int> lStreamPidMap, uint16_t lPmtPid, SimpleBuffer *pSb) { if (shouldCreatePat()) { uint8_t lPatPmtCc = getCc(0); createPat(pSb, lPmtPid, lPatPmtCc); createPmt(pSb, lStreamPidMap, lPmtPid, lPatPmtCc); } createPes(pFrame, pSb); } uint8_t MpegTsMuxer::getCc(uint32_t lWithPid) { if (mPidCcMap.find(lWithPid) != mPidCcMap.end()) { mPidCcMap[lWithPid] = (mPidCcMap[lWithPid] + 1) & 0x0F; return mPidCcMap[lWithPid]; } mPidCcMap[lWithPid] = 0; return 0; } bool MpegTsMuxer::shouldCreatePat() { bool lRet = false; static const int lPatInterval = 20; static int lCurrentIndex = 0; if (lCurrentIndex % lPatInterval == 0) { if (lCurrentIndex > 0) { lCurrentIndex = 0; } lRet = true; } lCurrentIndex++; return lRet; }
36.102041
129
0.63746
2b7686c4291f08c186373e586ed0a4847757da18
632
hpp
C++
include/DynamicBitset.hpp
GiugnoLab/GRASS
2b65b37b03988a842318256e9b364d91221adabd
[ "Intel", "MIT" ]
1
2022-03-03T03:32:45.000Z
2022-03-03T03:32:45.000Z
include/DynamicBitset.hpp
GiugnoLab/GRASS
2b65b37b03988a842318256e9b364d91221adabd
[ "Intel", "MIT" ]
null
null
null
include/DynamicBitset.hpp
GiugnoLab/GRASS
2b65b37b03988a842318256e9b364d91221adabd
[ "Intel", "MIT" ]
null
null
null
/* * Dynamic Bitset Class powered by Mingz & Frank * Version 1.0 */ #ifndef DYNAMICBITSET_H #define DYNAMICBITSET_H #include <iostream> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; #define BIT_PER_DATASET_TYPE 8 typedef unsigned char dataset_t; class DynamicBitset { public: DynamicBitset(unsigned int size); ~DynamicBitset(); void reset(); void allset(); void set(unsigned int pos, bool value); bool get(unsigned int pos); unsigned int onset(unsigned int length); //debug print void print(); //private: unsigned int size; unsigned int words; dataset_t *dataset; }; #endif
15.414634
48
0.72943
2b795362dfcbc6fe454f61ae890685908c7f1d6f
694
cpp
C++
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
#include "log.hpp" namespace FE { std::shared_ptr<spdlog::logger> Log::s_core_logger; std::shared_ptr<spdlog::logger> Log::s_client_logger; void Log::init() { // See spdlog [wiki](https://github.com/gabime/spdlog/wiki) for more pattern settings // ^ - start color range // T - ISO 8601 time format // n - logger's name // v - actual text to log // $ - end color range spdlog::set_pattern("%^[%T] %n: %v%$"); // Create color multi threaded logger s_core_logger = spdlog::stdout_color_mt("FE"); s_core_logger->set_level(spdlog::level::trace); s_client_logger = spdlog::stdout_color_mt("APP"); s_client_logger->set_level(spdlog::level::trace); } } // namespace FE
26.692308
87
0.680115
2b7dfcb07b052af8e1404f5f78aab97ae12524d8
1,842
cc
C++
src/attributes/Akima474MethodWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/Akima474MethodWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/Akima474MethodWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file Akima474MethodAttributes.h \\brief Definition of Akima474Method Attributes class. This file is automatically generated. Do Not Edit! */ #include "MagRequest.h" #include "Akima474MethodWrapper.h" #include "MagicsParameter.h" #include "Factory.h" #include "MagTranslator.h" #include "MagicsGlobal.h" using namespace magics; Akima474MethodWrapper::Akima474MethodWrapper(): akima474method_(new Akima474Method()) { ContourMethodWrapper::object(akima474method_); } Akima474MethodWrapper::Akima474MethodWrapper(Akima474Method* akima474method): akima474method_(akima474method) { ContourMethodWrapper::object(akima474method_); } Akima474MethodWrapper::~Akima474MethodWrapper() { } void Akima474MethodWrapper::set(const MagRequest& request) { ContourMethodWrapper::set(request); if (request.countValues("CONTOUR_AKIMA_X_RESOLUTION") ) { double resolutionX_value = request("CONTOUR_AKIMA_X_RESOLUTION"); akima474method_->resolutionX_ = resolutionX_value; } if (request.countValues("CONTOUR_AKIMA_Y_RESOLUTION") ) { double resolutionY_value = request("CONTOUR_AKIMA_Y_RESOLUTION"); akima474method_->resolutionY_ = resolutionY_value; } } void Akima474MethodWrapper::print(ostream& out) const { out << "Akima474MethodWrapper[]"; }
22.192771
109
0.711726
2b88daacbff2a89f428e813af6cdbe47db5703b9
8,677
hxx
C++
com/ole32/olethunk/h/interop.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/olethunk/h/interop.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/olethunk/h/interop.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1994. // // File: interop.hxx // // Contents: Common definitions for the interop project // // History: 18-Feb-94 DrewB Created // //-------------------------------------------------------------------------- #ifndef __INTEROP_HXX__ #define __INTEROP_HXX__ //+--------------------------------------------------------------------------- // // Purpose: Standard debugging support // // History: 18-Feb-94 DrewB Created // //---------------------------------------------------------------------------- #include <debnot.h> // // The rest of the OACF flags are defined in thunkapi.hxx. This one is here // because it is shared between ole2.dll and olethk32.dll. The 16-bit binaries // do not include thunkapi.hxx at the moment. KevinRo promises to fix this someday // Feel free to fix this if you wish. // #define OACF_CORELTRASHMEM 0x10000000 // CorelDraw relies on the fact that // OLE16 trashed memory during paste- // link. Therefore, we'll go ahead // and trash it for them if this // flag is on. #define OACF_CRLPNTPERSIST 0x01000000 // CorelPaint IPersistStg used in their // OleSave screws up in QI #define OACF_WORKSCLIPOBJ 0x00100000 // Works 3.0b creates a clipboard // data object with a zero ref count // Word 6 does this too. Same flag used. // Also Paradox5, Novel/Corel WrdPft. // They all call OleIsCurrentClipboard // with a 0-refcount 16-bit IDataObject ptr. #define OACF_TEXTARTDOBJ 0x00010000 // TextArt IDataAdvHolder::DAdvise has // data object with a zero ref count #if DBG == 1 #ifdef WIN32 DECLARE_DEBUG(thk); #else DECLARE_DEBUG(thk1); #endif #define DEB_DLL 0x0008 #define DEB_THOPS DEB_USER1 #define DEB_INVOKES DEB_USER2 #define DEB_ARGS DEB_USER3 #define DEB_NESTING DEB_USER4 #define DEB_CALLTRACE DEB_USER5 #define DEB_THUNKMGR DEB_USER6 #define DEB_MEMORY DEB_USER7 #define DEB_TLSTHK DEB_USER8 #define DEB_UNKNOWN DEB_USER9 #define DEB_FAILURES DEB_USER10 #define DEB_DLLS16 DEB_USER11 #define DEB_APIS16 DEB_USER12 // api calls to 16 bit entry point #define DEB_DBGFAIL DEB_USER13 // Pop up dialog to allow debugging #endif #if DBG == 1 #ifdef WIN32 #define thkDebugOut(x) thkInlineDebugOut x #else #define thkDebugOut(x) thk1InlineDebugOut x #endif #define thkAssert(e) Win4Assert(e) #define thkVerify(e) Win4Assert(e) #else #define thkDebugOut(x) #define thkAssert(e) #define thkVerify(e) (e) #endif #define OLETHUNK_DLL16NOTFOUND 0x88880002 //+--------------------------------------------------------------------------- // // Purpose: Declarations and definitions shared across everything // // History: 18-Feb-94 DrewB Created // //---------------------------------------------------------------------------- // An IID pointer or an index into the list of known interfaces // If the high word is zero, it's an index, otherwise it's a pointer typedef DWORD IIDIDX; #define IIDIDX_IS_INDEX(ii) (HIWORD(ii) == 0) #define IIDIDX_IS_IID(ii) (!IIDIDX_IS_INDEX(ii)) #define IIDIDX_INVALID ((IIDIDX)0xffff) #define INDEX_IIDIDX(idx) ((IIDIDX)(idx)) #define IID_IIDIDX(piid) ((IIDIDX)(piid)) #define IIDIDX_INDEX(ii) ((int)(ii)) #define IIDIDX_IID(ii) ((IID const *)(ii)) // Methods are treated as if they all existed on a single interface // Their method numbers are biased to distinguish them from real methods #define THK_API_BASE 0xf0000000 #define THK_API_METHOD(method) (THK_API_BASE+(method)) // Standard method indices in the vtable #define SMI_QUERYINTERFACE 0 #define SMI_ADDREF 1 #define SMI_RELEASE 2 #define SMI_COUNT 3 #ifndef WIN32 #define UNALIGNED #endif //+--------------------------------------------------------------------------- // // Struct: CALLDATA // // Purpose: Data describing a 16-bit call to be made on behalf of // the 32-bit code, used since Callback16 can only pass // one parameter // // History: 18-Feb-94 JohannP Created // //---------------------------------------------------------------------------- typedef struct tagCallData { DWORD vpfn; DWORD vpvStack16; DWORD cbStack; } CALLDATA; typedef CALLDATA UNALIGNED FAR *LPCALLDATA; //+--------------------------------------------------------------------------- // // Struct: DATA16 // // Purpose: Data describing things in the 16-bit world that need to be // known to the 32-bit world. // // History: 3-Mar-94 BobDay Created // //---------------------------------------------------------------------------- typedef struct tagDATA16 { DWORD atfnProxy1632Vtbl; DWORD fnCallbackHandler; DWORD fnTaskAlloc; DWORD fnTaskFree; DWORD fnLoadProcDll; DWORD fnUnloadProcDll; DWORD fnCallGetClassObject; DWORD fnCallCanUnloadNow; DWORD fnQueryInterface16; DWORD fnAddRef16; DWORD fnRelease16; DWORD fnReleaseStgMedium16; DWORD avpfnSm16ReleaseHandlerVtbl; DWORD fnTouchPointer16; DWORD fnStgMediumStreamHandler16; DWORD fnCallStub16; DWORD fnSetOwnerPublic16; DWORD fnWinExec16; } DATA16; typedef DATA16 UNALIGNED FAR * LPDATA16; //+--------------------------------------------------------------------------- // // Struct: LOADPROCDLLSTRUCT // // Purpose: Data passed to the LoadProcDll function that is called from // the 32-bit function of similar name. // // History: 11-Mar-94 BobDay Created // //---------------------------------------------------------------------------- typedef struct tagLOADPROCDLLSTRUCT { DWORD vpDllName; DWORD vpfnGetClassObject; DWORD vpfnCanUnloadNow; DWORD vhmodule; } LOADPROCDLLSTRUCT; typedef LOADPROCDLLSTRUCT UNALIGNED FAR * LPLOADPROCDLLSTRUCT; //+--------------------------------------------------------------------------- // // Struct: CALLGETCLASSOBJECTSTRUCT // // Purpose: Data passed to the CallGetClassObject function that is called // from the 32-bit function of similar name. // // History: 11-Mar-94 BobDay Created // //---------------------------------------------------------------------------- typedef struct tagCALLGETCLASSOBJECTSTRUCT { DWORD vpfnGetClassObject; CLSID clsid; IID iid; DWORD iface; } CALLGETCLASSOBJECTSTRUCT; typedef CALLGETCLASSOBJECTSTRUCT UNALIGNED FAR * LPCALLGETCLASSOBJECTSTRUCT; //+--------------------------------------------------------------------------- // // Struct: WINEXEC16STRUCT // // Purpose: Data passed to the WinExec16 function that is called from // the 32-bit function of similar name. // // History: 27-Jul-94 AlexT Created // //---------------------------------------------------------------------------- typedef struct tagWINEXEC16STRUCT { DWORD vpCommandLine; unsigned short vusShow; } WINEXEC16STRUCT; typedef WINEXEC16STRUCT UNALIGNED FAR * LPWINEXEC16STRUCT; //+--------------------------------------------------------------------------- // // Class: CSm16ReleaseHandler (srh) // // Purpose: Provides punkForRelease for 32->16 STGMEDIUM conversion // // Interface: IUnknown // // History: 24-Apr-94 DrewB Created // //---------------------------------------------------------------------------- #ifdef __cplusplus class CSm16ReleaseHandler { public: void Init(IUnknown *pUnk, STGMEDIUM *psm32, STGMEDIUM UNALIGNED *psm16, IUnknown *punkForRelease, CLIPFORMAT cfFormat); void CallFailed() { _punkForRelease = NULL; } DWORD _avpfnVtbl; STGMEDIUM _sm32; STGMEDIUM _sm16; IUnknown *_punkForRelease; LONG _cReferences; CLIPFORMAT _cfFormat; IUnknown *_pUnkThkMgr; }; #endif #endif // __INTEROP_HXX__
30.660777
85
0.530483
2b8b20fd3f2f2b67388e511070ed3135875ff451
1,362
cpp
C++
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/cloudtrail/model/ListEventDataStoresResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CloudTrail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListEventDataStoresResult::ListEventDataStoresResult() { } ListEventDataStoresResult::ListEventDataStoresResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListEventDataStoresResult& ListEventDataStoresResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("EventDataStores")) { Array<JsonView> eventDataStoresJsonList = jsonValue.GetArray("EventDataStores"); for(unsigned eventDataStoresIndex = 0; eventDataStoresIndex < eventDataStoresJsonList.GetLength(); ++eventDataStoresIndex) { m_eventDataStores.push_back(eventDataStoresJsonList[eventDataStoresIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
27.24
126
0.768722
2b957045c492074cd0090fa7e5a5a8b75985c999
2,954
cpp
C++
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
#include "ns/RegistCallback.h" #include "ns/CompSerializer.h" #include "ns/CompNoSerialize.h" #include "ns/N0CompComplex.h" #include <node0/CompComplex.h> #include "ns/N2CompAnim.h" #include <node2/CompAnim.h> #include "ns/N2CompColorCommon.h" #include <node2/CompColorCommon.h> #include "ns/N2CompColorMap.h" #include <node2/CompColorMap.h> #include "ns/N2CompTransform.h" #include <node2/CompTransform.h> #include <node2/CompBoundingBox.h> #include "ns/N2CompUniquePatch.h" #include <node2/CompUniquePatch.h> #include "ns/N2CompSharedPatch.h" #include <node2/CompSharedPatch.h> #include "ns/N2CompScissor.h" #include <node2/CompScissor.h> #include "ns/N2CompScript.h" #include <node2/CompScript.h> #include "ns/N2CompScript.h" // todo #include <node2/EditOp.h> #include "ns/N0CompIdentity.h" #include <node0/CompIdentity.h> #include "ns/N0CompComplex.h" #include <node0/CompComplex.h> #include "ns/N2CompImage.h" #include <node2/CompImage.h> #include "ns/N2CompMask.h" #include <node2/CompMask.h> #include "ns/N2CompText.h" #include <node2/CompText.h> #include "ns/N2CompScale9.h" #include <node2/CompScale9.h> #include "ns/N2CompShape.h" #include <node2/CompShape.h> #include "ns/N3CompAABB.h" #include <node3/CompAABB.h> #include "ns/N3CompTransform.h" #include <node3/CompTransform.h> #include "ns/N3CompModel.h" #include <node3/CompModel.h> #include "ns/N3CompModelInst.h" #include <node3/CompModelInst.h> #include "ns/N3CompShape.h" #include <node3/CompShape.h> #include "ns/N0CompFlags.h" #include <node0/CompFlags.h> #include <node0/SceneNode.h> #include <memmgr/LinearAllocator.h> #include <anim/Layer.h> #include <anim/KeyFrame.h> namespace ns { void RegistCallback::Init() { AddUniqueCB<n0::CompIdentity, N0CompIdentity>(); AddUniqueCB<n2::CompColorCommon, N2CompColorCommon>(); AddUniqueCB<n2::CompColorMap, N2CompColorMap>(); AddUniqueCB<n2::CompTransform, N2CompTransform>(); AddUniqueNullCB<n2::CompBoundingBox, CompNoSerialize>(); AddUniqueCB<n2::CompUniquePatch, N2CompUniquePatch>(); AddUniqueCB<n2::CompSharedPatch, N2CompSharedPatch>(); AddUniqueCB<n2::CompScissor, N2CompScissor>(); AddUniqueCB<n2::CompScript, N2CompScript>(); AddSharedCB<n0::CompComplex, N0CompComplex>(); AddSharedCB<n2::CompAnim, N2CompAnim>(); AddSharedCB<n2::CompImage, N2CompImage>(); AddSharedCB<n2::CompMask, N2CompMask>(); AddSharedCB<n2::CompText, N2CompText>(); AddSharedCB<n2::CompScale9, N2CompScale9>(); //AddSharedCB<n2::CompShape, N2CompShape>(); AddUniqueCB<n3::CompAABB, N3CompAABB>(); AddUniqueCB<n3::CompTransform, N3CompTransform>(); AddSharedCB<n3::CompModel, N3CompModel>(); AddUniqueCB<n3::CompModelInst, N3CompModelInst>(); AddUniqueCB<n3::CompShape, N3CompShape>(); AddUniqueCB<n0::CompFlags, N0CompFlags>(); AddAssetCB<n0::CompComplex>(); AddAssetCB<n2::CompAnim>(); AddAssetCB<n2::CompImage>(); AddAssetCB<n2::CompMask>(); AddAssetCB<n2::CompText>(); AddAssetCB<n2::CompScale9>(); } }
27.607477
57
0.756601
2b9629798298c6704a0c43083e35af2d7e4529af
145
inl
C++
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2019-04-23T05:24:16.000Z
2019-04-23T05:24:16.000Z
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2016-08-16T13:05:39.000Z
2016-08-16T13:05:39.000Z
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2018-06-24T14:51:20.000Z
2018-06-24T14:51:20.000Z
0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x02, 0x0A, 0x03, 0x00, 0x02, 0x0A, 0x05, 0x00, 0x02, 0x03, 0x07, 0x00, 0x02, 0x0A, 0x09, 0x00, 0x02, 0x03
48.333333
96
0.662069
2b9cbd43fc10d98d1346ed20f4b7af95539df4fb
12,800
cpp
C++
src/providers/postgres/qgspostgresprojectstorage.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/providers/postgres/qgspostgresprojectstorage.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/providers/postgres/qgspostgresprojectstorage.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgspostgresprojectstorage.cpp --------------------- begin : April 2018 copyright : (C) 2018 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgspostgresprojectstorage.h" #include "qgspostgresconn.h" #include "qgspostgresconnpool.h" #include "qgsreadwritecontext.h" #include <QIODevice> #include <QJsonDocument> #include <QJsonObject> #include <QUrl> static bool _parseMetadataDocument( const QJsonDocument &doc, QgsProjectStorage::Metadata &metadata ) { if ( !doc.isObject() ) return false; QJsonObject docObj = doc.object(); metadata.lastModified = QDateTime(); if ( docObj.contains( "last_modified_time" ) ) { QString lastModifiedTimeStr = docObj["last_modified_time"].toString(); if ( !lastModifiedTimeStr.isEmpty() ) { QDateTime lastModifiedUtc = QDateTime::fromString( lastModifiedTimeStr, Qt::ISODate ); lastModifiedUtc.setTimeSpec( Qt::UTC ); metadata.lastModified = lastModifiedUtc.toLocalTime(); } } return true; } static bool _projectsTableExists( QgsPostgresConn &conn, const QString &schemaName ) { QString tableName( "qgis_projects" ); QString sql( QStringLiteral( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name=%1 and table_schema=%2" ) .arg( QgsPostgresConn::quotedValue( tableName ), QgsPostgresConn::quotedValue( schemaName ) ) ); QgsPostgresResult res( conn.PQexec( sql ) ); return res.PQgetvalue( 0, 0 ).toInt() > 0; } QStringList QgsPostgresProjectStorage::listProjects( const QString &uri ) { QStringList lst; QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) return lst; QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) return lst; if ( _projectsTableExists( *conn, projectUri.schemaName ) ) { QString sql( QStringLiteral( "SELECT name FROM %1.qgis_projects" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ) ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { int count = result.PQntuples(); for ( int i = 0; i < count; ++i ) { QString name = result.PQgetvalue( i, 0 ); lst << name; } } } QgsPostgresConnPool::instance()->releaseConnection( conn ); return lst; } bool QgsPostgresProjectStorage::readProject( const QString &uri, QIODevice *device, QgsReadWriteContext &context ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) { context.pushMessage( QObject::tr( "Invalid URI for PostgreSQL provider: " ) + uri, Qgis::Critical ); return false; } QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) { context.pushMessage( QObject::tr( "Could not connect to the database: " ) + projectUri.connInfo.connectionInfo( false ), Qgis::Critical ); return false; } if ( !_projectsTableExists( *conn, projectUri.schemaName ) ) { context.pushMessage( QObject::tr( "Table qgis_projects does not exist or it is not accessible." ), Qgis::Critical ); QgsPostgresConnPool::instance()->releaseConnection( conn ); return false; } bool ok = false; QString sql( QStringLiteral( "SELECT content FROM %1.qgis_projects WHERE name = %2" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ) ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { if ( result.PQntuples() == 1 ) { // TODO: would be useful to have QByteArray version of PQgetvalue to avoid bytearray -> string -> bytearray conversion QString hexEncodedContent( result.PQgetvalue( 0, 0 ) ); QByteArray binaryContent( QByteArray::fromHex( hexEncodedContent.toUtf8() ) ); device->write( binaryContent ); device->seek( 0 ); ok = true; } else { context.pushMessage( QObject::tr( "The project '%1' does not exist in schema '%2'." ).arg( projectUri.projectName, projectUri.schemaName ), Qgis::Critical ); } } QgsPostgresConnPool::instance()->releaseConnection( conn ); return ok; } bool QgsPostgresProjectStorage::writeProject( const QString &uri, QIODevice *device, QgsReadWriteContext &context ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) { context.pushMessage( QObject::tr( "Invalid URI for PostgreSQL provider: " ) + uri, Qgis::Critical ); return false; } QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) { context.pushMessage( QObject::tr( "Could not connect to the database: " ) + projectUri.connInfo.connectionInfo( false ), Qgis::Critical ); return false; } if ( !_projectsTableExists( *conn, projectUri.schemaName ) ) { // try to create projects table QString sql = QStringLiteral( "CREATE TABLE %1.qgis_projects(name TEXT PRIMARY KEY, metadata JSONB, content BYTEA)" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ) ); QgsPostgresResult res( conn->PQexec( sql ) ); if ( res.PQresultStatus() != PGRES_COMMAND_OK ) { QString errCause = QObject::tr( "Unable to save project. It's not possible to create the destination table on the database. Maybe this is due to database permissions (user=%1). Please contact your database admin." ).arg( projectUri.connInfo.username() ); context.pushMessage( errCause, Qgis::Critical ); QgsPostgresConnPool::instance()->releaseConnection( conn ); return false; } } // read from device and write to the table QByteArray content = device->readAll(); QString metadataExpr = QStringLiteral( "(%1 || (now() at time zone 'utc')::text || %2 || current_user || %3)::jsonb" ).arg( QgsPostgresConn::quotedValue( "{ \"last_modified_time\": \"" ), QgsPostgresConn::quotedValue( "\", \"last_modified_user\": \"" ), QgsPostgresConn::quotedValue( "\" }" ) ); // TODO: would be useful to have QByteArray version of PQexec() to avoid bytearray -> string -> bytearray conversion QString sql( "INSERT INTO %1.qgis_projects VALUES (%2, %3, E'\\\\x" ); sql = sql.arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ), metadataExpr // no need to quote: already quoted ); sql += QString::fromAscii( content.toHex() ); sql += "') ON CONFLICT (name) DO UPDATE SET content = EXCLUDED.content, metadata = EXCLUDED.metadata;"; QgsPostgresResult res( conn->PQexec( sql ) ); if ( res.PQresultStatus() != PGRES_COMMAND_OK ) { QString errCause = QObject::tr( "Unable to insert or update project (project=%1) in the destination table on the database. Maybe this is due to table permissions (user=%2). Please contact your database admin." ).arg( projectUri.projectName, projectUri.connInfo.username() ); context.pushMessage( errCause, Qgis::Critical ); QgsPostgresConnPool::instance()->releaseConnection( conn ); return false; } QgsPostgresConnPool::instance()->releaseConnection( conn ); return true; } bool QgsPostgresProjectStorage::removeProject( const QString &uri ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) return false; QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) return false; bool removed = false; if ( _projectsTableExists( *conn, projectUri.schemaName ) ) { QString sql( QStringLiteral( "DELETE FROM %1.qgis_projects WHERE name = %2" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ) ) ); QgsPostgresResult res( conn->PQexec( sql ) ); removed = res.PQresultStatus() == PGRES_COMMAND_OK; } QgsPostgresConnPool::instance()->releaseConnection( conn ); return removed; } bool QgsPostgresProjectStorage::readProjectStorageMetadata( const QString &uri, QgsProjectStorage::Metadata &metadata ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) return false; QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) return false; bool ok = false; QString sql( QStringLiteral( "SELECT metadata FROM %1.qgis_projects WHERE name = %2" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ) ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { if ( result.PQntuples() == 1 ) { metadata.name = projectUri.projectName; QString metadataStr = result.PQgetvalue( 0, 0 ); QJsonDocument doc( QJsonDocument::fromJson( metadataStr.toUtf8() ) ); ok = _parseMetadataDocument( doc, metadata ); } } QgsPostgresConnPool::instance()->releaseConnection( conn ); return ok; } #ifdef HAVE_GUI #include "qgspostgresprojectstoragedialog.h" QString QgsPostgresProjectStorage::visibleName() { return QObject::tr( "PostgreSQL" ); } QString QgsPostgresProjectStorage::showLoadGui() { QgsPostgresProjectStorageDialog dlg( false ); if ( !dlg.exec() ) return QString(); return dlg.currentProjectUri(); } QString QgsPostgresProjectStorage::showSaveGui() { QgsPostgresProjectStorageDialog dlg( true ); if ( !dlg.exec() ) return QString(); return dlg.currentProjectUri(); } #endif QString QgsPostgresProjectStorage::encodeUri( const QgsPostgresProjectUri &postUri ) { QUrl u; QUrlQuery urlQuery; u.setScheme( "postgresql" ); u.setHost( postUri.connInfo.host() ); if ( !postUri.connInfo.port().isEmpty() ) u.setPort( postUri.connInfo.port().toInt() ); u.setUserName( postUri.connInfo.username() ); u.setPassword( postUri.connInfo.password() ); if ( !postUri.connInfo.service().isEmpty() ) urlQuery.addQueryItem( "service", postUri.connInfo.service() ); if ( !postUri.connInfo.authConfigId().isEmpty() ) urlQuery.addQueryItem( "authcfg", postUri.connInfo.authConfigId() ); if ( postUri.connInfo.sslMode() != QgsDataSourceUri::SslPrefer ) urlQuery.addQueryItem( "sslmode", QgsDataSourceUri::encodeSslMode( postUri.connInfo.sslMode() ) ); urlQuery.addQueryItem( "dbname", postUri.connInfo.database() ); urlQuery.addQueryItem( "schema", postUri.schemaName ); if ( !postUri.projectName.isEmpty() ) urlQuery.addQueryItem( "project", postUri.projectName ); u.setQuery( urlQuery ); return QString::fromUtf8( u.toEncoded() ); } QgsPostgresProjectUri QgsPostgresProjectStorage::decodeUri( const QString &uri ) { QUrl u = QUrl::fromEncoded( uri.toUtf8() ); QUrlQuery urlQuery( u.query() ); QgsPostgresProjectUri postUri; postUri.valid = u.isValid(); QString host = u.host(); QString port = u.port() != -1 ? QString::number( u.port() ) : QString(); QString username = u.userName(); QString password = u.password(); QgsDataSourceUri::SslMode sslMode = QgsDataSourceUri::decodeSslMode( urlQuery.queryItemValue( "sslmode" ) ); QString authConfigId = urlQuery.queryItemValue( "authcfg" ); QString dbName = urlQuery.queryItemValue( "dbname" ); QString service = urlQuery.queryItemValue( "service" ); if ( !service.isEmpty() ) postUri.connInfo.setConnection( service, dbName, username, password, sslMode, authConfigId ); else postUri.connInfo.setConnection( host, port, dbName, username, password, sslMode, authConfigId ); postUri.schemaName = urlQuery.queryItemValue( "schema" ); postUri.projectName = urlQuery.queryItemValue( "project" ); return postUri; }
37.317784
278
0.672969
2b9d7e925eb9565282276d2ef7e186d71bfa2bba
16,851
cc
C++
tests/ut/cpp/dataset/c_api_audio_a_to_q_test.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
null
null
null
tests/ut/cpp/dataset/c_api_audio_a_to_q_test.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
null
null
null
tests/ut/cpp/dataset/c_api_audio_a_to_q_test.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * 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 "common/common.h" #include "include/api/types.h" #include "utils/log_adapter.h" #include "minddata/dataset/include/dataset/audio.h" #include "minddata/dataset/include/dataset/datasets.h" #include "minddata/dataset/include/dataset/execute.h" #include "minddata/dataset/include/dataset/transforms.h" using namespace mindspore::dataset; using mindspore::LogStream; using mindspore::ExceptionType::NoExceptionType; using mindspore::MsLogLevel::INFO; using namespace std; class MindDataTestPipeline : public UT::DatasetOpTesting { protected: }; TEST_F(MindDataTestPipeline, TestAmplitudeToDBPipeline) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto amplitude_to_db_op = audio::AmplitudeToDB(); ds = ds->Map({amplitude_to_db_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, TestAmplitudeToDBWrongArgs) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto amplitude_to_db_op = audio::AmplitudeToDB(ScaleType::kPower, 1.0, -1e-10, 80.0); ds = ds->Map({amplitude_to_db_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); // Expect failure EXPECT_EQ(iter, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBandBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BandBiquadOp = audio::BandBiquad(44100, 200.0); ds = ds->Map({BandBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBandBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto band_biquad_op_01 = audio::BandBiquad(0, 200); ds01 = ds->Map({band_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto band_biquad_op_02 = audio::BandBiquad(44100, 200, 0); ds02 = ds->Map({band_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestAllpassBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto AllpassBiquadOp = audio::AllpassBiquad(44100, 200.0); ds = ds->Map({AllpassBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by allpassbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestAllpassBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "Sample_rate_ is zero."; auto allpass_biquad_op_01 = audio::AllpassBiquad(0, 200.0, 0.707); ds01 = ds->Map({allpass_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto allpass_biquad_op_02 = audio::AllpassBiquad(44100, 200, 0); ds02 = ds->Map({allpass_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBandpassBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BandpassBiquadOp = audio::BandpassBiquad(44100, 200.0); ds = ds->Map({BandpassBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandpassbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBandpassBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto bandpass_biquad_op_01 = audio::BandpassBiquad(0, 200); ds01 = ds->Map({bandpass_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto bandpass_biquad_op_02 = audio::BandpassBiquad(44100, 200, 0); ds02 = ds->Map({bandpass_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBandrejectBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BandrejectBiquadOp = audio::BandrejectBiquad(44100, 200.0); ds = ds->Map({BandrejectBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandrejectbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBandrejectBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto bandreject_biquad_op_01 = audio::BandrejectBiquad(0, 200); ds01 = ds->Map({bandreject_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto bandreject_biquad_op_02 = audio::BandrejectBiquad(44100, 200, 0); ds02 = ds->Map({bandreject_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBassBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BassBiquadOp = audio::BassBiquad(44100, 50, 200.0); ds = ds->Map({BassBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bassbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBassBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto bass_biquad_op_01 = audio::BassBiquad(0, 50, 200.0); ds01 = ds->Map({bass_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto bass_biquad_op_02 = audio::BassBiquad(44100, 50, 200.0, 0); ds02 = ds->Map({bass_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, TestAnglePipeline) { MS_LOG(INFO) << "Doing MindDataTestPipeline-TestAnglePipeline"; std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("complex", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto angle_op = audio::Angle(); ds = ds->Map({angle_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2}; int i = 0; while (row.size() != 0) { auto col = row["complex"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 1); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, TestAnglePipelineError) { MS_LOG(INFO) << "Doing MindDataTestPipeline-TestAnglePipelineError"; std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("complex", mindspore::DataType::kNumberTypeFloat32, {3, 2, 1})); std::shared_ptr<Dataset> ds = RandomData(4, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto angle_op = audio::Angle(); ds = ds->Map({angle_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); std::unordered_map<std::string, mindspore::MSTensor> row; EXPECT_ERROR(iter->GetNextRow(&row)); } TEST_F(MindDataTestPipeline, TestFrequencyMaskingPipeline) { MS_LOG(INFO) << "Doing TestFrequencyMasking Pipeline."; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {200, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto frequencymasking = audio::FrequencyMasking(true, 6); ds = ds->Map({frequencymasking}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {200, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, TestFrequencyMaskingWrongArgs) { MS_LOG(INFO) << "Doing TestFrequencyMasking with wrong args."; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {20, 20})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto frequencymasking = audio::FrequencyMasking(true, -100); ds = ds->Map({frequencymasking}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); // Expect failure EXPECT_EQ(iter, nullptr); }
30.471971
98
0.699958
2b9e3b7072aa6eac36c65a288f0b47b2c92fdab0
2,406
cpp
C++
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
2
2018-01-02T14:07:54.000Z
2021-07-05T08:05:21.000Z
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
null
null
null
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
null
null
null
#include "chess-application.h" #include <GLFW/glfw3.h> #include <chrono> #include <iostream> #include <random> #include "selection-rendering-stage.h" using namespace bembel; ChessApplication::ChessApplication() : kernel::Application() { this->graphic_system = this->kernel->addSystem<graphics::GraphicSystem>(); this->graphic_system->getRendertingStageFactory() .registerDefaultObjectGenerator<SelectionRenderingStage>("SelectionRenderingStage"); auto& event_mgr = this->kernel->getEventManager(); event_mgr.addHandler<kernel::WindowShouldCloseEvent>(this); event_mgr.addHandler<kernel::FrameBufferResizeEvent>(this); } ChessApplication::~ChessApplication() { } bool ChessApplication::init() { BEMBEL_LOG_INFO() << "Loading Application Settings"; if(!this->kernel->loadSetting("chess/config.xml")) return false; auto pipline = this->graphic_system->getRenderingPipelines()[0].get(); this->camera = std::make_shared<CameraControle>(this->kernel->getEventManager(), pipline->getCamera()); BEMBEL_LOG_INFO() << "Initalizing Game"; this->chess_game = std::make_unique<ChessGame>( this->kernel->getAssetManager(), this->kernel->getEventManager(), *(this->graphic_system)); this->chess_game->resetChessBoard(); this->chess_game->resetChessBoard(); BEMBEL_LOG_INFO() << "Initalizing Camera"; pipline->setScene(this->chess_game->getScene()); this->camera->setCameraOffset(glm::vec3(8, 0.5f, 8)); this->camera->enableManualControle(true); BEMBEL_LOG_INFO() << "Initalizing Systems"; this->kernel->initSystems(); return true; } void ChessApplication::cleanup() { this->chess_game.reset(); this->kernel->shutdownSystems(); this->kernel->getAssetManager().deleteUnusedAssets(); this->kernel->getDisplayManager().closeOpenWindows(); } void ChessApplication::update(double time) { this->camera->update(time); this->chess_game->update(time); } void ChessApplication::handleEvent(const kernel::WindowShouldCloseEvent& event) { this->quit(); } void ChessApplication::handleEvent(const kernel::FrameBufferResizeEvent& event) { auto pipline = this->graphic_system->getRenderingPipelines()[0].get(); pipline->setResulution(event.size); pipline->getCamera()->setUpProjection( 60.0f * 3.14159265359f / 180.0f, event.size.x / event.size.y, 0.1f, 1000.0f); }
32.08
99
0.715711
2ba7bcde3e5dfc15bf94af1a4d55546f3cfbba51
14,693
cpp
C++
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
#include <iostream> #include "init_6he_ds.hpp" #include "TChain.h" void hdraw(TTree& tree, TString name, TString draw_cmd, TString binning, TCut cuts = "", TString title = "", TString xaxis_title = "", TString yaxis_title = "", TString draw_opts = "colz") { TString hstr = TString::Format("%s >>%s%s", draw_cmd.Data(), name.Data(), binning.Data()); tree.Draw(hstr, cuts, draw_opts); TH1 *hist = static_cast<TH1*>(gPad->GetPrimitive(name)); if (yaxis_title != "") { hist->GetYaxis()->SetTitle(yaxis_title); } if (xaxis_title != "") { hist->GetXaxis()->SetTitle(xaxis_title); } if (title != "") { hist->SetTitle(title); } } void phi_correlation_he6_carbon_compare() { init_dataset(); init_carbon_dataset(); std::cout << "Total number of events for he6: " << g_chain_total.GetEntries() << std::endl; std::cout << "Total number of events for carbon: " << g_c_chain.GetEntries() << std::endl; TCut p_angle_sn_cut = "p_theta*57.3>65 && p_theta*57.3<68"; TCut p_angle_acceptance_cut = "p_theta*57.3>55 && p_theta*57.3<70"; TCut phi_corr_cut_1d = "abs(abs(p_phi*57.3-s1dc_phi*57.3) - 180) < 8"; TCut target_cut{"tgt_up_xpos*tgt_up_xpos + tgt_up_ypos*tgt_up_ypos < 81"}; TCut vertex_zpos_cut{"es_vertex_zpos > -30 && es_vertex_zpos < 30"}; // distribution on HODF plastics // pla IDs [7,9]: beam / beam stopper // pla ID [0,4]: left scattering 6He // pla ID [11,14]: right scattering 6He // pla ID [17,23]: 4He (from inelastic shannel) std::string hodf_cut_str = ""; for (int i = 0; i < 5; i++) { hodf_cut_str += TString::Format("(hodf_q[%i]>14 && hodf_q[%i]<17) ", i, i); if (i != 4) hodf_cut_str += "|| "; } hodf_cut_str += "|| "; for (int i = 11; i < 15; i++) { hodf_cut_str += TString::Format("(hodf_q[%i]>14 && hodf_q[%i]<17) ", i, i); if (i != 14) hodf_cut_str += "|| "; } cout << "HODF cut:\n" << hodf_cut_str << std::endl; TCut hodf_cut{hodf_cut_str.c_str()}; TFile hist_out("out/phi_correlation_he6_carbon_compare.root", "RECREATE"); TCanvas c1("c1"); gStyle->SetOptStat(1111111); // // proton phi // c1.Clear(); // c1.Divide(2); // c1.cd(1); // hdraw(g_chain_total, "esl_p_phi", "esl_p_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left, proton phi angle", // "Proton #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "esr_p_phi", "esr_p_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right, proton phi angle", // "Proton #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // He phi // c1.Clear(); // c1.Divide(1); // c1.cd(1); // hdraw(g_chain_total, "fragment_phi_s1dc", "s1dc_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "Fragment azimuthal angle", // "Fragment #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // phi 2d corr ESPRI L&R // c1.Clear(); // c1.Divide(2); // c1.cd(1); // hdraw(g_chain_total, "esl_phi_corr", "esl_p_phi*57.3:s1dc_phi*57.3", // "(100,60,120,100,-120,-60)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left, phi correlation", // "Fragment #phi angle [lab. deg.]", // "Proton #phi angle [lab. deg.]"); // c1.cd(2); // hdraw(g_chain_total, "esr_phi_corr", "esr_p_phi*57.3:s1dc_phi*57.3", // "(100,-120,-60,100,60,120)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right, phi correlation", // "Fragment #phi angle [lab. deg.]", // "Proton #phi angle [lab. deg.]"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // ESPRI L&R phi corr 1d // c1.Clear(); // c1.Divide(1,2); // c1.cd(1); // hdraw(g_chain_total, "esl_phi_corr_1d", "esl_p_phi*57.3-s1dc_phi*57.3", // "(300,-350,-10)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left: P_{#phi} - He_{#phi}", // "P_{#phi} - He_{#phi} [deg]", // "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "esr_phi_corr_1d", "esr_p_phi*57.3-s1dc_phi*57.3", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right: P_{#phi} - He_{#phi}", // "P_{#phi} - He_{#phi} [deg]", // "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // ESPRI total - phi, hodf cuts // c1.Clear(); // c1.Divide(1,2); // c1.cd(1); // hdraw(g_chain_total, "tot_phi_corr_1d", "abs(p_phi*57.3-s1dc_phi*57.3)", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left & right: P_{#phi} - He_{#phi} (no #phi cut)", // "P_{#phi} - He_{#phi} [deg.]", // "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "tot_phi_corr_1d_cut", "abs(p_phi*57.3-s1dc_phi*57.3)", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut && // phi_corr_cut_1d, // "ESPRI left & right: P_{#phi} - He_{#phi} (#phi cut)", // "P_{#phi} - He_{#phi} [deg.]", // "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // polar corr with diff. cuts // // HODF cut - He6 vs. carbon // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_phi_hodf", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && hodf_cut, // "#theta angle correlation for 6he-p (tgt, hodf cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_phi_hodf2", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && hodf_cut, // "#theta angle correlation for 6he-C (tgt, hodf cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // tgt,phi,hodf cut - He6 vs. carbon // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_tgt_phi1d_hodf", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && // phi_corr_cut_1d && hodf_cut, // "#theta angle corr.: 6he-p (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_tgt_phi1d_hodf2", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && // phi_corr_cut_1d && hodf_cut, // "#theta angle corr.: 6he-C (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // 1d hist theta corr S/N // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_tgt_phi1d_hodf_1d", "s1dc_theta*57.3", // "(200,0,10)", // "triggers[5]==1" && target_cut && // hodf_cut && phi_corr_cut_1d && p_angle_sn_cut, // "#theta angle corr.: 6he-p (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Counts", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_tgt_phi1d_hodf_1d2", "s1dc_theta*57.3", // "(200,0,10)", // "triggers[5]==1" && target_cut && // hodf_cut && phi_corr_cut_1d && p_angle_sn_cut, // "#theta angle corr.: 6he-C (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Counts", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // theta exp - theta_theor 2d corr c1.Clear(); c1.Divide(2,1); c1.cd(1); hdraw(g_chain_total, "polar_t_tgt_hodf_phi", "p_theta*57.3:s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8,200,50,75)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Proton #theta angle [lab. deg.]", "colz"); c1.cd(2); hdraw(g_c_chain, "polar_t_tgt_hodf_phi2", "p_theta*57.3:s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8,200,50,75)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Proton #theta angle [lab. deg.]", "colz"); c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // theta exp - theta_theor 1d corr // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_t_1d", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "colz"); // gPad->SetLogy(); // c1.cd(2); // hdraw(g_c_chain, "polar_t_1d2", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "colz"); // gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // theta exp - theta_theor 1d corr + carbon BG // c1.Clear(); // c1.Divide(1); // c1.cd(1); // g_chain_total.SetLineColor(kBlue); // hdraw(g_chain_total, "polar_t_1d_hc1", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts"); // g_c_chain.SetLineColor(kRed); // hdraw(g_c_chain, "polar_t_1d_hc2", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "SAME"); // gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr + phi cut c1.Clear(); c1.Divide(2,1); c1.cd(1); hdraw(g_chain_total, "polar_t_1d_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "colz"); gPad->SetLogy(); c1.cd(2); g_c_chain.SetLineColor(kBlue); hdraw(g_c_chain, "polar_t_1d2_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "colz"); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr + phi cut + carbon BG c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); hdraw(g_chain_total, "polar_t_1d_hc1_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts"); g_c_chain.SetLineColor(kRed); hdraw(g_c_chain, "polar_t_1d_hc2_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "SAME"); TH1* he6_polar = static_cast<TH1*>(gPad->GetPrimitive("polar_t_1d_hc1_phi")); TH1* carbon_polar = static_cast<TH1*>(gPad->GetPrimitive("polar_t_1d_hc2_phi")); carbon_polar->Scale(3); he6_polar->Draw(); carbon_polar->SetLineColor(kRed); carbon_polar->Draw("SAME"); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr - carbon BG c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); g_c_chain.SetLineColor(kBlue); TH1* he6_polar_min_bg = (TH1*)he6_polar->Clone(); he6_polar_min_bg->Add(carbon_polar, -1); he6_polar_min_bg->SetTitle("#theta angle corr.: #theta_{exp}-#theta_{theor} for " "6he-p - 6he-C (tgt, hodf, phi cuts)"); he6_polar_min_bg->Draw(); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); c1.Clear(); c1.Divide(1); c1.cd(1); he6_polar->Draw(); carbon_polar->SetLineColor(kRed); carbon_polar->Draw("SAME"); //gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); g_c_chain.SetLineColor(kBlue); he6_polar_min_bg->Draw(); //gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf)", "pdf"); hist_out.Write(); hist_out.Close(); }
38.064767
100
0.574355
2ba8b7704ef008a72827b0bfff98fe3808468963
10,557
cpp
C++
src/drivers/milliped.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-01-25T20:16:33.000Z
2021-01-25T20:16:33.000Z
src/drivers/milliped.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-05-24T20:28:35.000Z
2021-05-25T14:44:54.000Z
src/drivers/milliped.cpp
PSP-Archive/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
null
null
null
/*************************************************************************** Millipede memory map (preliminary) 0400-040F POKEY 1 0800-080F POKEY 2 1000-13BF SCREEN RAM (8x8 TILES, 32x30 SCREEN) 13C0-13CF SPRITE IMAGE OFFSETS 13D0-13DF SPRITE HORIZONTAL OFFSETS 13E0-13EF SPRITE VERTICAL OFFSETS 13F0-13FF SPRITE COLOR OFFSETS 2000 BIT 1-4 trackball BIT 5 IS P1 FIRE BIT 6 IS P1 START BIT 7 IS VBLANK 2001 BIT 1-4 trackball BIT 5 IS P2 FIRE BIT 6 IS P2 START BIT 7,8 (?) 2010 BIT 1 IS P1 RIGHT BIT 2 IS P1 LEFT BIT 3 IS P1 DOWN BIT 4 IS P1 UP BIT 5 IS SLAM, LEFT COIN, AND UTIL COIN BIT 6,7 (?) BIT 8 IS RIGHT COIN 2030 earom read 2480-249F COLOR RAM 2500-2502 Coin counters 2503-2504 LEDs 2505-2507 Coin door lights ?? 2600 INTERRUPT ACKNOWLEDGE 2680 CLEAR WATCHDOG 2700 earom control 2780 earom write 4000-7FFF GAME CODE Known issues: * The dipswitches under $2000 aren't fully emulated. There must be some sort of trick to reading them properly. *************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "machine/atari_vg.h" void milliped_paletteram_w(int offset,int data); void milliped_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); int milliped_IN0_r(int offset); /* JB 971220 */ int milliped_IN1_r(int offset); /* JB 971220 */ void milliped_input_select_w(int offset, int data); void milliped_led_w (int offset, int data) { osd_led_w (offset, ~(data >> 7)); } static struct MemoryReadAddress readmem[] = { { 0x0000, 0x03ff, MRA_RAM }, { 0x0400, 0x040f, pokey1_r }, { 0x0800, 0x080f, pokey2_r }, { 0x1000, 0x13ff, MRA_RAM }, { 0x2000, 0x2000, milliped_IN0_r }, /* JB 971220 */ { 0x2001, 0x2001, milliped_IN1_r }, /* JB 971220 */ { 0x2010, 0x2010, input_port_2_r }, { 0x2011, 0x2011, input_port_3_r }, { 0x2030, 0x2030, atari_vg_earom_r }, { 0x4000, 0x7fff, MRA_ROM }, { 0xf000, 0xffff, MRA_ROM }, /* for the reset / interrupt vectors */ { -1 } /* end of table */ }; static struct MemoryWriteAddress writemem[] = { { 0x0000, 0x03ff, MWA_RAM }, { 0x0400, 0x040f, pokey1_w }, { 0x0800, 0x080f, pokey2_w }, { 0x1000, 0x13ff, videoram_w, &videoram, &videoram_size }, { 0x13c0, 0x13ff, MWA_RAM, &spriteram }, { 0x2480, 0x249f, milliped_paletteram_w, &paletteram }, { 0x2680, 0x2680, watchdog_reset_w }, { 0x2600, 0x2600, MWA_NOP }, /* IRQ ack */ { 0x2500, 0x2502, coin_counter_w }, { 0x2503, 0x2504, milliped_led_w }, { 0x2505, 0x2505, milliped_input_select_w }, { 0x2780, 0x27bf, atari_vg_earom_w }, { 0x2700, 0x2700, atari_vg_earom_ctrl }, { 0x2505, 0x2507, MWA_NOP }, /* coin door lights? */ { 0x4000, 0x73ff, MWA_ROM }, { -1 } /* end of table */ }; INPUT_PORTS_START( input_ports ) PORT_START /* IN0 $2000 */ /* see port 6 for x trackball */ PORT_DIPNAME (0x03, 0x00, "Language", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "English" ) PORT_DIPSETTING ( 0x01, "German" ) PORT_DIPSETTING ( 0x02, "French" ) PORT_DIPSETTING ( 0x03, "Spanish" ) PORT_DIPNAME (0x0c, 0x04, "Bonus", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "0" ) PORT_DIPSETTING ( 0x04, "0 1x" ) PORT_DIPSETTING ( 0x08, "0 1x 2x" ) PORT_DIPSETTING ( 0x0c, "0 1x 2x 3x" ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT ( 0x40, IP_ACTIVE_HIGH, IPT_VBLANK ) PORT_BIT ( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START /* IN1 $2001 */ /* see port 7 for y trackball */ PORT_BIT ( 0x03, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* JB 971220 */ PORT_DIPNAME (0x04, 0x00, "Credit Minimum", IP_KEY_NONE ) /* JB 971220 */ PORT_DIPSETTING ( 0x00, "1" ) PORT_DIPSETTING ( 0x04, "2" ) PORT_DIPNAME (0x08, 0x00, "Coin Counters", IP_KEY_NONE ) /* JB 971220 */ PORT_DIPSETTING ( 0x00, "1" ) PORT_DIPSETTING ( 0x08, "2" ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START /* IN2 $2010 */ PORT_BIT ( 0x01, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_TILT ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_START /* IN3 $2011 */ PORT_BIT ( 0x01, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 ) PORT_DIPSETTING( 0x80, "Off" ) PORT_DIPSETTING( 0x00, "On" ) PORT_START /* 4 */ /* DSW1 $0408 */ PORT_DIPNAME (0x01, 0x00, "Millipede Head", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x01, "Hard" ) PORT_DIPNAME (0x02, 0x00, "Beetle", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x02, "Hard" ) PORT_DIPNAME (0x0c, 0x04, "Lives", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "2" ) PORT_DIPSETTING ( 0x04, "3" ) PORT_DIPSETTING ( 0x08, "4" ) PORT_DIPSETTING ( 0x0c, "5" ) PORT_DIPNAME (0x30, 0x10, "Bonus Life", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "12000" ) PORT_DIPSETTING ( 0x10, "15000" ) PORT_DIPSETTING ( 0x20, "20000" ) PORT_DIPSETTING ( 0x30, "None" ) PORT_DIPNAME (0x40, 0x00, "Spider", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x40, "Hard" ) PORT_DIPNAME (0x80, 0x00, "Starting Score Select", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "On" ) PORT_DIPSETTING ( 0x80, "Off" ) PORT_START /* 5 */ /* DSW2 $0808 */ PORT_DIPNAME (0x03, 0x02, "Coinage", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Free Play" ) PORT_DIPSETTING ( 0x01, "1 Coin/2 Credits" ) PORT_DIPSETTING ( 0x02, "1 Coin/1 Credit" ) PORT_DIPSETTING ( 0x03, "2 Coins/1 Credit" ) PORT_DIPNAME (0x0c, 0x00, "Right Coin", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "*1" ) PORT_DIPSETTING ( 0x04, "*4" ) PORT_DIPSETTING ( 0x08, "*5" ) PORT_DIPSETTING ( 0x0c, "*6" ) PORT_DIPNAME (0x10, 0x00, "Left Coin", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "*1" ) PORT_DIPSETTING ( 0x10, "*2" ) PORT_DIPNAME (0xe0, 0x00, "Bonus Coins", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "None" ) PORT_DIPSETTING ( 0x20, "3 credits/2 coins" ) PORT_DIPSETTING ( 0x40, "5 credits/4 coins" ) PORT_DIPSETTING ( 0x60, "6 credits/4 coins" ) PORT_DIPSETTING ( 0x80, "6 credits/5 coins" ) PORT_DIPSETTING ( 0xa0, "4 credits/3 coins" ) PORT_DIPSETTING ( 0xc0, "Demo mode" ) PORT_START /* IN6: FAKE - used for trackball-x at $2000 */ PORT_ANALOGX( 0xff, 0x00, IPT_TRACKBALL_X | IPF_REVERSE, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE, 4 ) PORT_START /* IN7: FAKE - used for trackball-y at $2001 */ PORT_ANALOGX( 0xff, 0x00, IPT_TRACKBALL_Y | IPF_REVERSE, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE, 4 ) INPUT_PORTS_END static struct GfxLayout charlayout = { 8,8, /* 8*8 characters */ 256, /* 256 characters */ 2, /* 2 bits per pixel */ { 0, 256*8*8 }, /* the two bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 /* every char takes 8 consecutive bytes */ }; static struct GfxLayout spritelayout = { 8,16, /* 16*8 sprites */ 128, /* 64 sprites */ 2, /* 2 bits per pixel */ { 0, 128*16*8 }, /* the two bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 16*8 /* every sprite takes 16 consecutive bytes */ }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { 1, 0x0000, &charlayout, 0, 4 }, /* use colors 0-15 */ { 1, 0x0000, &spritelayout, 16, 1 }, /* use colors 16-19 */ { -1 } /* end of array */ }; static struct POKEYinterface pokey_interface = { 2, /* 2 chips */ 1500000, /* 1.5 MHz??? */ 50, POKEY_DEFAULT_GAIN, NO_CLIP, /* The 8 pot handlers */ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* The allpot handler */ { input_port_4_r, input_port_5_r }, }; static struct MachineDriver machine_driver = { /* basic machine hardware */ { { CPU_M6502, 1500000, /* 1.5 Mhz ???? */ 0, readmem,writemem,0,0, interrupt,4 } }, 60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 10, 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 0*8, 30*8-1 }, gfxdecodeinfo, 32, 32, 0, VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE, 0, generic_vh_start, generic_vh_stop, milliped_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_POKEY, &pokey_interface } } }; /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( milliped_rom ) ROM_REGION(0x10000) /* 64k for code */ ROM_LOAD( "milliped.104", 0x4000, 0x1000, 0x40711675 ) ROM_LOAD( "milliped.103", 0x5000, 0x1000, 0xfb01baf2 ) ROM_LOAD( "milliped.102", 0x6000, 0x1000, 0x62e137e0 ) ROM_LOAD( "milliped.101", 0x7000, 0x1000, 0x46752c7d ) ROM_RELOAD( 0xf000, 0x1000 ) /* for the reset and interrupt vectors */ ROM_REGION_DISPOSE(0x1000) /* temporary space for graphics (disposed after conversion) */ ROM_LOAD( "milliped.106", 0x0000, 0x0800, 0xf4468045 ) ROM_LOAD( "milliped.107", 0x0800, 0x0800, 0x68c3437a ) ROM_END struct GameDriver milliped_driver = { __FILE__, 0, "milliped", "Millipede", "1982", "Atari", "Ivan Mackintosh\nNicola Salmoria\nJohn Butler\nAaron Giles\nBernd Wiebelt\nBrad Oliver", 0, &machine_driver, 0, milliped_rom, 0, 0, 0, 0, /* sound_prom */ input_ports, 0, 0, 0, ORIENTATION_ROTATE_270, atari_vg_earom_load, atari_vg_earom_save };
29.822034
134
0.637586
ad9601f7ae49dc17671c16c6096ce479c6bbd639
9,600
cpp
C++
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
4
2018-07-03T14:21:39.000Z
2021-06-01T06:12:14.000Z
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_move.c -- monster movement #include "icommon.h" #define STEPSIZE 18 /* ============= SV_CheckBottom Returns false if any part of the bottom of the entity is off an edge that is not a staircase. ============= */ int c_yes, c_no; qboolean SV_CheckBottom (edict_t *ent) { vec3_t mins, maxs, start, stop; trace_t trace; int x, y; float mid, bottom; VectorAdd (ent->v.origin, ent->v.mins, mins); VectorAdd (ent->v.origin, ent->v.maxs, maxs); // if all of the points under the corners are solid world, don't bother // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; if (SV_PointContents (start) != CONTENTS_SOLID) goto realcheck; } c_yes++; return true; // we got out easy realcheck: c_no++; // // check it for real... // start[2] = mins[2]; // the midpoint must be within 16 of the bottom start[0] = stop[0] = (mins[0] + maxs[0])*0.5f; start[1] = stop[1] = (mins[1] + maxs[1])*0.5f; stop[2] = start[2] - 2*STEPSIZE; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; // the corners must be within 16 of the midpoint for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) return false; } c_yes++; return true; } /* ============= SV_movestep Called by monster program code. The move will be adjusted for slopes and stairs, but if the move isn't possible, no move is done, false is returned, and vm.pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) { float dz; vec3_t oldorg, neworg, end; trace_t trace; int i; edict_t *enemy; // try the move VectorCopy (ent->v.origin, oldorg); VectorAdd (ent->v.origin, move, neworg); // flying monsters don't step up if ( (int)ent->v.flags & (FL_SWIM | FL_FLY) ) { // try one move with vertical motion, then one without for (i=0 ; i<2 ; i++) { VectorAdd (ent->v.origin, move, neworg); enemy = ent->v.enemy; if (i == 0 && enemy != sv.worldedict) { dz = ent->v.origin[2] - ent->v.enemy->v.origin[2]; if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, ent); if (trace.fraction == 1) { if ( ((int)ent->v.flags & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY ) return false; // swim monster left water VectorCopy (trace.endpos, ent->v.origin); if (relink) SV_LinkEdict (ent, true); return true; } if (enemy == nullptr) break; } return false; } // push down from a step height above the wished position neworg[2] += STEPSIZE; VectorCopy (neworg, end); end[2] -= STEPSIZE*2; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid) return false; if (trace.startsolid) { neworg[2] -= STEPSIZE; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid || trace.startsolid) return false; } if (trace.fraction == 1) { // if monster had the ground pulled out, go ahead and fall if ( (int)ent->v.flags & FL_PARTIALGROUND ) { VectorAdd (ent->v.origin, move, ent->v.origin); if (relink) SV_LinkEdict (ent, true); ent->v.flags = static_cast<float>((int)ent->v.flags & ~FL_ONGROUND); // Con_Printf ("fall down\n"); return true; } return false; // walked off an edge } // check point traces down for dangling corners VectorCopy (trace.endpos, ent->v.origin); if (!SV_CheckBottom (ent)) { if ( (int)ent->v.flags & FL_PARTIALGROUND ) { // entity had floor mostly pulled out from underneath it // and is trying to correct if (relink) SV_LinkEdict (ent, true); return true; } VectorCopy (oldorg, ent->v.origin); return false; } if ( (int)ent->v.flags & FL_PARTIALGROUND ) { // Con_Printf ("back on ground\n"); ent->v.flags = static_cast<float>(static_cast<int>(ent->v.flags) & ~FL_PARTIALGROUND); } ent->v.groundentity = vm.EDICT_TO_PROG(trace.ent); // the move is ok if (relink) SV_LinkEdict (ent, true); return true; } //============================================================================ /* ====================== SV_StepDirection Turns to the movement direction, and walks the current distance if facing it. ====================== */ void PF_changeyaw (void); qboolean SV_StepDirection (edict_t *ent, float yaw, float dist) { vec3_t move, oldorigin; float delta; ent->v.ideal_yaw = yaw; PF_changeyaw(); static constexpr float yaw_constant= static_cast<float>(M_PI*2.0 / 360.0); yaw = yaw* yaw_constant; move[0] = cos(yaw)*dist; move[1] = sin(yaw)*dist; move[2] = 0; VectorCopy (ent->v.origin, oldorigin); if (SV_movestep (ent, move, false)) { delta = ent->v.angles[YAW] - ent->v.ideal_yaw; if (delta > 45.0f && delta < 315.0f) { // not turned far enough, so don't take the step VectorCopy (oldorigin, ent->v.origin); } SV_LinkEdict (ent, true); return true; } SV_LinkEdict (ent, true); return false; } /* ====================== SV_FixCheckBottom ====================== */ void SV_FixCheckBottom (edict_t *ent) { // Con_Printf ("SV_FixCheckBottom\n"); ent->v.flags = static_cast<float>(static_cast<int>(ent->v.flags) | FL_PARTIALGROUND); } /* ================ SV_NewChaseDir ================ */ #define DI_NODIR -1 void SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist) { float deltax,deltay; float d[3]; float tdir, olddir, turnaround; olddir = anglemod( (int)(actor->v.ideal_yaw/45.0f)*45.0f ); turnaround = anglemod(olddir - 180); deltax = enemy->v.origin[0] - actor->v.origin[0]; deltay = enemy->v.origin[1] - actor->v.origin[1]; if (deltax>10) d[1]= 0; else if (deltax<-10) d[1]= 180; else d[1]= DI_NODIR; if (deltay<-10) d[2]= 270; else if (deltay>10) d[2]= 90; else d[2]= DI_NODIR; // try direct route if (d[1] != DI_NODIR && d[2] != DI_NODIR) { if (d[1] == 0) tdir = d[2] == 90.0f ? 45.0f : 315.0f; else tdir = d[2] == 90.0f ? 135.0f : 215.0f; if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } // try other directions if ( ((rand()&3) & 1) || std::abs(deltay)>abs(deltax)) { tdir=d[1]; d[1]=d[2]; d[2]=tdir; } if (d[1]!=DI_NODIR && d[1]!=turnaround && SV_StepDirection(actor, d[1], dist)) return; if (d[2]!=DI_NODIR && d[2]!=turnaround && SV_StepDirection(actor, d[2], dist)) return; /* there is no direct path to the player, so pick another direction */ if (olddir!=DI_NODIR && SV_StepDirection(actor, olddir, dist)) return; if (rand()&1) /*randomly determine direction of search*/ { for (tdir=0 ; tdir<=315 ; tdir += 45) if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) return; } else { for (tdir=315 ; tdir >=0 ; tdir -= 45) if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) return; } if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist) ) return; actor->v.ideal_yaw = olddir; // can't move // if a bridge was pulled out from underneath a monster, it may not have // a valid standing position at all if (!SV_CheckBottom (actor)) SV_FixCheckBottom (actor); } /* ====================== SV_CloseEnough ====================== */ qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) { int i; for (i=0 ; i<3 ; i++) { if (goal->v.absmin[i] > ent->v.absmax[i] + dist) return false; if (goal->v.absmax[i] < ent->v.absmin[i] - dist) return false; } return true; } /* ====================== SV_MoveToGoal ====================== */ void SV_MoveToGoal (void) { #ifdef QUAKE2 edict_t *enemy; #endif auto ent = vm.pr_global_struct->self; auto goal = ent->v.goalentity; float dist = vm.G_FLOAT(OFS_PARM0); if ( !( (int)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) { vm.G_FLOAT(OFS_RETURN) = 0; return; } // if the next step hits the enemy, return immediately #ifdef QUAKE2 enemy = vm.PROG_TO_EDICT(ent->v.enemy); if (enemy != sv.edicts && SV_CloseEnough (ent, enemy, dist) ) #else if (ent->v.enemy != nullptr && SV_CloseEnough (ent, goal, dist) ) #endif return; // bump around... if ( (rand()&3)==1 || !SV_StepDirection (ent, ent->v.ideal_yaw, dist)) { SV_NewChaseDir (ent, goal, dist); } }
22.535211
92
0.621354
ad9c6825a96c1b09f45c58d1bd81ce77443d5dae
196
cpp
C++
tests/test_model.cpp
shakfu/prolog
9d6621e3e723b0bd899bd963fe4a4125cf57671c
[ "Unlicense" ]
null
null
null
tests/test_model.cpp
shakfu/prolog
9d6621e3e723b0bd899bd963fe4a4125cf57671c
[ "Unlicense" ]
null
null
null
tests/test_model.cpp
shakfu/prolog
9d6621e3e723b0bd899bd963fe4a4125cf57671c
[ "Unlicense" ]
null
null
null
#include "doctest.h" #include "model/vehicle.hpp" TEST_CASE("testing vehicle") { model::Vehicle v; v.brand = "x"; v.cost = 10.0; v.weight = 5.0; CHECK(v.cost_per_kg() == 2.0); }
14
34
0.591837
ad9db69271a9151979b183ac511aa504315c42c6
1,106
cpp
C++
c++/dp/MiniSqaureCut.cpp
Nk095291/pepcoding
fb57f8fa58c155d38bdbc47824f547e24c0804b6
[ "MIT" ]
1
2020-04-24T05:45:44.000Z
2020-04-24T05:45:44.000Z
c++/dp/MiniSqaureCut.cpp
Nk095291/pepcoding
fb57f8fa58c155d38bdbc47824f547e24c0804b6
[ "MIT" ]
null
null
null
c++/dp/MiniSqaureCut.cpp
Nk095291/pepcoding
fb57f8fa58c155d38bdbc47824f547e24c0804b6
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<climits> using namespace std; int solve(vector<vector<int>>&res, int b,int l){ if(l<=0||b<=0) return 0; if(l==b) return 0; if(res[b][l]!=INT_MAX) return res[b][l]; for(int i =1;i<=min(b,l);i++){ int p1v=solve(res,b-i,i); int p2v=solve(res,b,l-i); int p1h=solve(res,i,l-i); int p2h=solve(res,b-i,l); res[b][l]=min((p1h+p2h+1),(p1v+p2v+1)); } return res[b][l]; } int solve2(vector<vector<int>>&res, int b,int l){ if(l==0||b==0) return 0; if(l==b) return 1; if(res[b][l]!=0) return res[b][l]; int mymin=INT_MAX; for(int i =1;i<=min(b,l);i++){ int p1v=solve(res,b-i,i); int p2v=solve(res,b,l-i); int c1=p1v+p2v+1; int p1h=solve(res,i,l-i); int p2h=solve(res,b-i,l); int c2 =p1h+p2h+1; mymin=min(mymin,min(c1,c2)); } res[b][l]=mymin; return mymin; } int main(){ vector<vector<int>>res(31,vector<int>(36+1,INT_MAX)); cout<<solve(res,30,36); }
21.269231
57
0.507233
ada146d03ec82a7927462795c75ab534000fad54
451
cpp
C++
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
CHList/CS-305
731a192fb8ef38bde2e845733d43fd63e4129695
[ "MIT" ]
null
null
null
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
CHList/CS-305
731a192fb8ef38bde2e845733d43fd63e4129695
[ "MIT" ]
null
null
null
Arrays - Reverse array/Arrays - Reverse array/Source.cpp
CHList/CS-305
731a192fb8ef38bde2e845733d43fd63e4129695
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; void reverseArray(int [], int); int main() { const int size = 6; int list[size] = { 1,6,7,9,2,5 }; reverseArray(list, size); cout << list[0]; for (int i = 1; i < size; i++) { cout << "," << list[i]; } cout << endl; return 0; } void reverseArray(int list[], int size) { int temp = 0; for (int i = 1; i <= size/2; i++) { temp = list[size-i]; list[size - i] = list[i-1]; list[i-1] = temp; } }
18.791667
41
0.552106
ada2e2c33c4a1f6ea0a55e19426f4182afc20be6
1,115
cpp
C++
03-composition-references/1-reference/assign_a_reference.cpp
nofar88/cpp-5782
473c68627fc0908fdef8956caf1e1d2267c9417b
[ "MIT" ]
14
2021-01-30T16:36:18.000Z
2022-03-30T17:24:44.000Z
03-composition-references/1-reference/assign_a_reference.cpp
dimastar2310/cpp-5781
615ba07e0841522df74384f380172557f5e305a7
[ "MIT" ]
1
2022-03-02T20:55:14.000Z
2022-03-02T20:55:14.000Z
03-composition-references/1-reference/assign_a_reference.cpp
dimastar2310/cpp-5781
615ba07e0841522df74384f380172557f5e305a7
[ "MIT" ]
16
2021-03-02T11:13:41.000Z
2021-07-09T14:18:15.000Z
/** * Demonstrates assigning values to references in C++. * * @author Erel Segal-Halevi * @since 2018-02 */ #include <iostream> using namespace std; int main() { int* p1; //int& r1; // compile error int num = 1, num2 = 999; cout << "Pointer:" << endl; int* pnum = &num; cout << "pnum = " << pnum << " " << *pnum << " " << num << endl; (*pnum) = 2; cout << "pnum = " << pnum << " " << *pnum << " " << num << endl; pnum = &num2; cout << "pnum = " << pnum << " " << *pnum << " " << num << endl; pnum += 4; // unsafe cout << "pnum = " << pnum << " " << *pnum << " " << num << endl << endl; cout << "Reference:" << endl; int& rnum = num; cout << "rnum = " << &rnum << " " << rnum << " " << num << endl; rnum = 3; // Here a reference is like a pointer cout << "rnum = " << &rnum << " " << rnum << " " << num << endl; rnum = num2; // Here a reference is unlike a pointer cout << "rnum = " << &rnum << " " << rnum << " " << num << endl; rnum += 4; cout << "rnum = " << &rnum << " " << rnum << " " << num << endl << endl; }
30.135135
76
0.442152
ada55c5ef838ebe62e9bdce02ea66a59bd917970
2,347
cc
C++
chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
chrome/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.cc
sarang-apps/darshan_browser
173649bb8a7c656dc60784d19e7bb73e07c20daa
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
// Copyright 2018 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/chrome_cleaner/mojom/typemaps/string16_embedded_nulls_mojom_traits.h" namespace mojo { using chrome_cleaner::mojom::NullValueDataView; using chrome_cleaner::mojom::String16EmbeddedNullsDataView; using chrome_cleaner::String16EmbeddedNulls; // static bool StructTraits<NullValueDataView, nullptr_t>::Read(NullValueDataView data, nullptr_t* value) { *value = nullptr; return true; } // static base::span<const uint16_t> UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::value( const String16EmbeddedNulls& str) { DCHECK_EQ(String16EmbeddedNullsDataView::Tag::VALUE, GetTag(str)); // This should only be called by Mojo to get the data to be send through the // pipe. When called by Mojo in this case, str will outlive the returned span. return base::make_span(str.CastAsUInt16Array(), str.size()); } // static nullptr_t UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::null_value( const chrome_cleaner::String16EmbeddedNulls& str) { DCHECK_EQ(String16EmbeddedNullsDataView::Tag::NULL_VALUE, GetTag(str)); return nullptr; } // static chrome_cleaner::mojom::String16EmbeddedNullsDataView::Tag UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::GetTag( const chrome_cleaner::String16EmbeddedNulls& str) { return str.size() == 0 ? String16EmbeddedNullsDataView::Tag::NULL_VALUE : String16EmbeddedNullsDataView::Tag::VALUE; } // static bool UnionTraits<String16EmbeddedNullsDataView, String16EmbeddedNulls>::Read( String16EmbeddedNullsDataView str_view, String16EmbeddedNulls* out) { if (str_view.is_null_value()) { *out = String16EmbeddedNulls(); return true; } ArrayDataView<uint16_t> view; str_view.GetValueDataView(&view); // Note: Casting is intentional, since the data view represents the string as // a uint16_t array, whereas String16EmbeddedNulls's constructor expects // a wchar_t array. *out = String16EmbeddedNulls(reinterpret_cast<const wchar_t*>(view.data()), view.size()); return true; } } // namespace mojo
34.514706
86
0.737963
ada5da0873736248a9ef99e8067522d738188fd2
838
cpp
C++
UbiGame_Blank/Source/Game/Util/WallManager.cpp
AdrienPringle/HTN-team-brain-damage
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
[ "MIT" ]
null
null
null
UbiGame_Blank/Source/Game/Util/WallManager.cpp
AdrienPringle/HTN-team-brain-damage
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
[ "MIT" ]
null
null
null
UbiGame_Blank/Source/Game/Util/WallManager.cpp
AdrienPringle/HTN-team-brain-damage
f234bd1e46bd83f5c2a8af5535d3e795e0b8d985
[ "MIT" ]
null
null
null
#include "WallManager.h" #include "GameEngine/GameEngineMain.h" #include "Game/GameEntities/WallEntity.h" using namespace Game; WallManager* WallManager::sm_instance = nullptr; WallManager::WallManager(){ wasMouseDown = true; } WallManager::~WallManager(){ } void WallManager::Update(){ //spawn wall on mouse down if(!sf::Mouse::isButtonPressed(sf::Mouse::Left)){ wasMouseDown = false; } else if (!wasMouseDown) { wasMouseDown = true; SpawnWall(); } } void WallManager::SpawnWall(){ sf::RenderWindow *window = GameEngine::GameEngineMain::GetInstance()->GetRenderWindow(); sf::Vector2f mousePos = sf::Vector2f(sf::Mouse::getPosition(*window)); WallEntity* wall = new WallEntity(); wall->SetPos(mousePos); GameEngine::GameEngineMain::GetInstance()->AddEntity(wall); }
23.942857
92
0.689737
adad1ee2fe75ed250ac64d745fa10f209da9c2a0
735
cpp
C++
ESOData/Filesystem/DataFileHeader.cpp
FloorBelow/ESOData
eb35a95ec64d56c5842c4df85bc844e06fc72582
[ "MIT" ]
1
2021-12-20T02:46:34.000Z
2021-12-20T02:46:34.000Z
ESOData/Filesystem/DataFileHeader.cpp
rekiofoldhome/ESOData
3c176110e7fa37fcff0b74b0bf0649f7251e59ed
[ "MIT" ]
null
null
null
ESOData/Filesystem/DataFileHeader.cpp
rekiofoldhome/ESOData
3c176110e7fa37fcff0b74b0bf0649f7251e59ed
[ "MIT" ]
1
2021-06-10T03:00:46.000Z
2021-06-10T03:00:46.000Z
#include <ESOData/Filesystem/DataFileHeader.h> #include <ESOData/Serialization/SerializationStream.h> #include <stdexcept> namespace esodata { SerializationStream &operator <<(SerializationStream &stream, const DataFileHeader &header) { stream << DataFileHeader::Signature; stream << header.version; stream << header.unknown; stream << header.headerSize; return stream; } SerializationStream &operator >>(SerializationStream &stream, DataFileHeader &header) { uint32_t signature; stream >> signature; if (signature != DataFileHeader::Signature) throw std::runtime_error("Bad DAT file signature"); stream >> header.version; stream >> header.unknown; stream >> header.headerSize; return stream; } }
24.5
94
0.742857
adb86ae40f02307ae6ef47ba88df07ccb71ad290
3,225
hpp
C++
src/xml/Xml.hpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
1
2021-08-07T13:02:01.000Z
2021-08-07T13:02:01.000Z
src/xml/Xml.hpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
src/xml/Xml.hpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
#pragma once #include<../thirdparty/tinyxml/tinyxml.h> #include<memory> #include<fstream> namespace tutorial { class XMLAttribute { public: XMLAttribute() : _attrib(nullptr) {} XMLAttribute(TiXmlAttribute *attrib) : _attrib(attrib) {} bool is_empty() const { return _attrib == nullptr; } const char* name() const { return _attrib->Name(); } const char* value() const { return _attrib->Value(); } XMLAttribute next_attrib() { return XMLAttribute(_attrib->Next()); } protected: TiXmlAttribute* _attrib; }; class XMLNode { public: XMLNode() = default; XMLNode(TiXmlElement* node) : _node(node) {} public: TiXmlElement* get_xml_node() { return _node; } bool is_empty() const { return _node == nullptr; } const char* name() const { return _node->Value(); } XMLNode first_child() const { return XMLNode(_node->FirstChildElement()); } XMLNode next_sibling() const { return XMLNode(_node->NextSiblingElement()); } XMLNode first_child(const char* name) const { return XMLNode(_node->FirstChildElement(name)); } XMLNode next_sibling(const char* name) const { return XMLNode(_node->NextSiblingElement(name)); } XMLAttribute first_attrib() { return XMLAttribute(_node->FirstAttribute()); } const char* attribute(const char* name, const char* defValue = "") const { const char *attrib = _node->Attribute(name); return attrib != nullptr ? attrib : defValue; } void attribute(const char* name, float* value, const float& default) const { double v = default; _node->Attribute(name, &v); *value = (float)v; } void attribute(const char* name, int* value, const int& default) const { _node->Attribute(name, value); } size_t child_node_count(const char *name = nullptr) const { size_t numNodes = 0u; TiXmlElement *node1 = _node->FirstChildElement(name); while (node1) { ++numNodes; node1 = node1->NextSiblingElement(name); } return numNodes; } operator bool() const { return !is_empty(); } protected: TiXmlElement* _node = nullptr; }; class XMLDoc { public: XMLDoc() { } ~XMLDoc() { _doc.Clear(); } public: bool has_error() const; XMLNode get_root_node(); void parse_string(const char* text); void parse_buffer(const char* charbuf, size_t size); bool parse_file(const char* file_name); private: TiXmlDocument _doc; std::unique_ptr<char[]> buf; }; inline bool XMLDoc::has_error() const { return _doc.RootElement() == nullptr; } inline XMLNode XMLDoc::get_root_node() { return XMLNode(_doc.RootElement()); } inline void XMLDoc::parse_string(const char* text) { _doc.Parse(text); } inline void XMLDoc::parse_buffer(const char* charbuf, size_t size) { buf.reset(new char[size + 1]); memcpy(buf.get(), charbuf, size); buf[size] = '\0'; parse_string(buf.get()); } inline bool XMLDoc::parse_file(const char* file_name) { std::fstream f(file_name, std::ios::in | std::ios::binary); if (!f.is_open()) return false; f.seekg(0, std::ios::end); auto size = (size_t)f.tellg(); f.seekg(0, std::ios::beg); buf.reset(new char[size + 1]); f.read(buf.get(), size); buf[size] = '\0'; f.close(); parse_string(buf.get()); return true; } }
23.201439
99
0.671628
adb8aa8e189ae91a5b8983a0055f5d806bda8ccf
14,417
cpp
C++
aeron-driver/src/test/c/aeron_errors_test.cpp
dao-hackathon-dwtl-term/aeron
349fa0820e4c88fe38f1b1252508430c241a268c
[ "Apache-2.0" ]
1
2020-02-17T20:03:48.000Z
2020-02-17T20:03:48.000Z
aeron-driver/src/test/c/aeron_errors_test.cpp
dao-hackathon-dwtl-term/aeron
349fa0820e4c88fe38f1b1252508430c241a268c
[ "Apache-2.0" ]
null
null
null
aeron-driver/src/test/c/aeron_errors_test.cpp
dao-hackathon-dwtl-term/aeron
349fa0820e4c88fe38f1b1252508430c241a268c
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2014-2020 Real Logic Limited. * * 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 <functional> #include <utility> #include <gtest/gtest.h> #include <gmock/gmock.h> #include "aeron_test_base.h" extern "C" { #include "concurrent/aeron_thread.h" #include "aeron_system_counters.h" #include "command/aeron_control_protocol.h" } #define PUB_URI "aeron:udp?endpoint=localhost:24325" #define STREAM_ID (117) class ErrorCallbackValidation { public: explicit ErrorCallbackValidation(std::vector<std::string> expectedSubstrings) : m_expectedSubstrings(std::move(expectedSubstrings)) {} void reset() { m_observations.clear(); } void validate(std::string &errorStr) { m_observations.push_back(errorStr); for (auto &subString : m_expectedSubstrings) { if (std::string::npos == errorStr.find(subString)) { return; } } m_validated = true; } bool validated() const { return m_validated; } friend std::ostream& operator<<(std::ostream& os, const ErrorCallbackValidation& bar) { os << "Unable to find: "; os << "{ "; for (auto &subString : bar.m_expectedSubstrings) { os << subString << "; "; } os << "} in:"; os << std::endl; for (auto &subString : bar.m_observations) { os << subString; } return os; } private: std::vector<std::string> m_expectedSubstrings; std::vector<std::string> m_observations{}; bool m_validated = false; }; const char *CSV_NAME_CONFIG_WITH_UNRESOLVABLE_ADDRESS = "server0,endpoint,foo.example.com:24326,localhost:24326|"; class CErrorsTest : public CSystemTestBase, public testing::Test { public: CErrorsTest() : CSystemTestBase( std::vector<std::pair<std::string, std::string>>{ { "AERON_COUNTERS_BUFFER_LENGTH", "32768" }, { "AERON_NAME_RESOLVER_SUPPLIER", "csv_table" }, { "AERON_NAME_RESOLVER_INIT_ARGS", CSV_NAME_CONFIG_WITH_UNRESOLVABLE_ADDRESS } }) { } protected: std::int64_t *m_errorCounter = NULL; std::int64_t m_initialErrorCount = 0; aeron_counters_reader_t *m_countersReader = NULL; aeron_t *connect() override { aeron_t *aeron = CSystemTestBase::connect(); m_countersReader = aeron_counters_reader(aeron); m_errorCounter = aeron_counters_reader_addr(m_countersReader, AERON_SYSTEM_COUNTER_ERRORS); AERON_GET_VOLATILE(m_initialErrorCount, *m_errorCounter); return aeron; } void waitForErrorCounterIncrease() { int64_t currentErrorCount; do { proc_yield(); AERON_GET_VOLATILE(currentErrorCount, *m_errorCounter); } while (currentErrorCount <= m_initialErrorCount); } void verifyDistinctErrorLogContains(const char *text, std::int64_t timeoutMs = 0) { aeron_cnc_t *aeronCnc; int result = aeron_cnc_init(&aeronCnc, aeron_context_get_dir(m_context), 100); EXPECT_EQ(0, result); if (result < 0) { aeron_cnc_close(aeronCnc); return; } ErrorCallbackValidation errorCallbackValidation { std::vector<std::string>{ text } }; std::int64_t deadlineMs = aeron_epoch_clock() + timeoutMs; do { std::this_thread::yield(); errorCallbackValidation.reset(); aeron_cnc_error_log_read(aeronCnc, errorCallback, &errorCallbackValidation, 0); } while (!errorCallbackValidation.validated() && aeron_epoch_clock() <= deadlineMs); EXPECT_TRUE(errorCallbackValidation.validated()) << errorCallbackValidation; aeron_cnc_close(aeronCnc); } static void errorCallback( int32_t observation_count, int64_t first_observation_timestamp, int64_t last_observation_timestamp, const char *error, size_t error_length, void *clientd) { auto *callbackValidation = reinterpret_cast<ErrorCallbackValidation *>(clientd); std::string errorStr = std::string(error, error_length); callbackValidation->validate(errorStr); } }; TEST_F(CErrorsTest, shouldErrorOnAddCounterPoll) { ASSERT_EQ(-1, aeron_async_add_counter_poll(NULL, NULL)); std::string errorMessage = std::string(aeron_errmsg()); ASSERT_THAT(errorMessage, testing::HasSubstr("Invalid argument")); ASSERT_THAT(errorMessage, testing::HasSubstr("Parameters must not be null")); } TEST_F(CErrorsTest, shouldValidatePollType) { aeron_t *aeron = connect(); aeron_async_add_publication_t *pub_async; aeron_publication_t *pub; aeron_counter_t *counter; ASSERT_EQ(0, aeron_async_add_publication(&pub_async, aeron, "aeron:ipc", 1001)); ASSERT_EQ(-1, aeron_async_add_counter_poll(&counter, (aeron_async_add_counter_t *)pub_async)) << aeron_errmsg(); std::string errorMessage = std::string(aeron_errmsg()); ASSERT_THAT(errorMessage, testing::HasSubstr("Invalid argument")); ASSERT_THAT(errorMessage, testing::HasSubstr("Parameters must be valid, async->type")); while (1 != aeron_async_add_publication_poll(&pub, pub_async)) { proc_yield(); } aeron_publication_close(pub, NULL, NULL); } TEST_F(CErrorsTest, publicationErrorIncludesClientAndDriverErrorAndReportsInDistinctLog) { aeron_t *aeron = connect(); aeron_async_add_publication_t *pub_async; aeron_publication_t *pub; ASSERT_EQ(0, aeron_async_add_publication(&pub_async, aeron, "aeron:tcp?endpoint=localhost:21345", 1001)); int result; while (0 == (result = aeron_async_add_publication_poll(&pub, pub_async))) { proc_yield(); } ASSERT_EQ(-1, result); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "invalid URI scheme or transport: aeron:tcp?endpoint=localhost:21345"; ASSERT_THAT(-AERON_ERROR_CODE_INVALID_CHANNEL, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_publication registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, exclusivePublicationErrorIncludesClientAndDriverErrorAndReportsInDistinctLog) { aeron_t *aeron = connect(); aeron_async_add_exclusive_publication_t *pub_async; aeron_exclusive_publication_t *pub; ASSERT_EQ(0, aeron_async_add_exclusive_publication(&pub_async, aeron, "aeron:tcp?endpoint=localhost:21345", 1001)); int result; while (0 == (result = aeron_async_add_exclusive_publication_poll(&pub, pub_async))) { proc_yield(); } ASSERT_EQ(-1, result); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "invalid URI scheme or transport: aeron:tcp?endpoint=localhost:21345"; ASSERT_THAT(-AERON_ERROR_CODE_INVALID_CHANNEL, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_exclusive_publication registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, subscriptionErrorIncludesClientAndDriverErrorAndReportsInDistinctLog) { aeron_t *aeron = connect(); aeron_async_add_subscription_t *sub_async; aeron_subscription_t *sub; ASSERT_EQ(0, aeron_async_add_subscription( &sub_async, aeron, "aeron:tcp?endpoint=localhost:21345", 1001, NULL, NULL, NULL, NULL)); int result; while (0 == (result = aeron_async_add_subscription_poll(&sub, sub_async))) { proc_yield(); } ASSERT_EQ(-1, result) << aeron_errmsg(); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "invalid URI scheme or transport: aeron:tcp?endpoint=localhost:21345"; ASSERT_THAT(-AERON_ERROR_CODE_INVALID_CHANNEL, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_subscription registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, counterErrorIncludesClientAndDriverErrorAndReportsInDistinctLog) { aeron_t *aeron = connect(); aeron_async_add_counter_t *counter_async; aeron_counter_t *counter; int32_t key = 1000000; int result; do { ASSERT_EQ(0, aeron_async_add_counter(&counter_async, aeron, 2002, (const uint8_t *)&key, sizeof(key), "label", 5)); while (0 == (result = aeron_async_add_counter_poll(&counter, counter_async))) { proc_yield(); } if (result < 0) { break; } key++; } while (true); ASSERT_EQ(-1, result); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "Unable to allocate counter: type: 2002, label: label"; ASSERT_THAT(-AERON_ERROR_CODE_GENERIC_ERROR, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_counter registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, destinationErrorIncludesClientAndDriverErrorAndReportsInDistinctLog) { aeron_t *aeron = connect(); aeron_async_add_exclusive_publication_t *pub_async; aeron_async_destination_t *dest_async; aeron_exclusive_publication_t *pub; ASSERT_EQ(0, aeron_async_add_exclusive_publication(&pub_async, aeron, "aeron:udp?control-mode=manual", 1001)); int result; while (0 == (result = aeron_async_add_exclusive_publication_poll(&pub, pub_async))) { proc_yield(); } ASSERT_EQ(1, result) << aeron_errmsg(); ASSERT_EQ(0, aeron_exclusive_publication_async_add_destination( &dest_async, aeron, pub, "aeron:tcp?endpoint=localhost:21345")); while (0 == (result = aeron_exclusive_publication_async_destination_poll(dest_async))) { proc_yield(); } ASSERT_EQ(-1, result); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "invalid URI scheme or transport: aeron:tcp?endpoint=localhost:21345"; ASSERT_THAT(-AERON_ERROR_CODE_INVALID_CHANNEL, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_destination registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, shouldFailToResovleNameOnPublication) { aeron_t *aeron = connect(); aeron_async_add_publication_t *pub_async; aeron_publication_t *pub; ASSERT_EQ(0, aeron_async_add_publication(&pub_async, aeron, "aeron:udp?endpoint=foo.example.com:20202", 1001)); int result; while (0 == (result = aeron_async_add_publication_poll(&pub, pub_async))) { proc_yield(); } ASSERT_EQ(-1, result); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "Unable to resolve host"; ASSERT_THAT(-AERON_ERROR_CODE_UNKNOWN_HOST, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_publication registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, shouldFailToResovleNameOnDestination) { aeron_t *aeron = connect(); aeron_async_add_exclusive_publication_t *pub_async; aeron_async_destination_t *dest_async; aeron_exclusive_publication_t *pub; ASSERT_EQ(0, aeron_async_add_exclusive_publication(&pub_async, aeron, "aeron:udp?control-mode=manual", 1001)); int result; while (0 == (result = aeron_async_add_exclusive_publication_poll(&pub, pub_async))) { proc_yield(); } ASSERT_EQ(1, result) << aeron_errmsg(); ASSERT_EQ(0, aeron_exclusive_publication_async_add_destination( &dest_async, aeron, pub, "aeron:udp?endpoint=foo.example.com:21345")); while (0 == (result = aeron_exclusive_publication_async_destination_poll(dest_async))) { proc_yield(); } ASSERT_EQ(-1, result); std::string errorMessage = std::string(aeron_errmsg()); const char *expectedDriverMessage = "Unable to resolve host"; ASSERT_THAT(-AERON_ERROR_CODE_UNKNOWN_HOST, aeron_errcode()); ASSERT_THAT( errorMessage, testing::HasSubstr("async_add_destination registration")); ASSERT_THAT( errorMessage, testing::HasSubstr(expectedDriverMessage)); waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage); } TEST_F(CErrorsTest, shouldRecordDistinctErrorCorrectlyOnReresolve) { aeron_t *aeron = connect(); aeron_async_add_publication_t *pub_async; aeron_publication_t *pub; ASSERT_EQ(0, aeron_async_add_publication(&pub_async, aeron, "aeron:udp?endpoint=server0", 1001)); int result; while (0 == (result = aeron_async_add_publication_poll(&pub, pub_async))) { proc_yield(); } ASSERT_EQ(1, result); const char *expectedDriverMessage = "Unable to resolve host"; waitForErrorCounterIncrease(); verifyDistinctErrorLogContains(expectedDriverMessage, 10000); }
31.273319
119
0.697371
adbc18e69243df5c6ea4b52bfeae1e38d8b83f58
6,237
cpp
C++
levelManager.cpp
LEpigeon888/IndevBuggedGame
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
[ "Zlib" ]
null
null
null
levelManager.cpp
LEpigeon888/IndevBuggedGame
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
[ "Zlib" ]
null
null
null
levelManager.cpp
LEpigeon888/IndevBuggedGame
c99f9bc64d3b52fca830be4a79fb81dbdb8f97d7
[ "Zlib" ]
null
null
null
#include <fstream> #include <utility> #include "blockManager.hpp" #include "eventManager.hpp" #include "global.hpp" #include "levelManager.hpp" #include "utilities.hpp" void LevelManager::setBlockHere(std::map<Point, std::unique_ptr<Block>>& currentMap, BlockId idOfBlock, int xBlock, int yBlock) { auto block = BlockManager::createBlock(idOfBlock); block->setPosition({xBlock * SIZE_BLOCK, yBlock * SIZE_BLOCK}); currentMap[Point(xBlock, yBlock)] = std::move(block); } void LevelManager::loadLevelFromFile(LevelInfo& currentLevel, std::string filePath) { size_t spacePos; std::string currentLine; std::string currentType; std::string firstWordOfLine; std::ifstream file; file.open("resources/" + filePath); while (std::getline(file, currentLine)) { spacePos = currentLine.find(' '); firstWordOfLine = currentLine.substr(0, spacePos); if (spacePos == std::string::npos) { currentLine.clear(); } else { currentLine.erase(0, spacePos + 1); } if (firstWordOfLine == "GAME_VERSION") { currentLevel.initialGameVersion = VersionNumber(currentLine); } else if (firstWordOfLine == "NEXT_LEVEL") { currentLevel.nextLevelName = currentLine; } else if (firstWordOfLine == "SIZE_OF_LEVEL") { currentLevel.limitOfGame.top = 0; currentLevel.limitOfGame.left = 0; currentLevel.limitOfGame.width = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.limitOfGame.height = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "PLAYER_POSITION") { currentLevel.playerStartPosition.x = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.playerStartPosition.y = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "NEW_BLOCK") { BlockId idOfBlock = BlockManager::stringBlockId(Utilities::readFirstString(currentLine)); int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); setBlockHere(currentLevel.mapOfGame, idOfBlock, posX, posY); } else if (firstWordOfLine == "NEW_EVENT") { std::string nameOfEvent = Utilities::readFirstString(currentLine); int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int sizeX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int sizeY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.listOfEvent.emplace_back( EventManager::createEvent(nameOfEvent, sf::IntRect{posX, posY, sizeX, sizeY}, currentLine)); } } file.close(); } void LevelManager::loadBasicLevelFromFile(BasicLevelInfo& currentLevel, std::string filePath) { size_t spacePos; std::string currentLine; std::string currentType; std::string firstWordOfLine; std::ifstream file; file.open("resources/" + filePath); while (std::getline(file, currentLine)) { spacePos = currentLine.find(' '); firstWordOfLine = currentLine.substr(0, spacePos); if (spacePos == std::string::npos) { currentLine.clear(); } else { currentLine.erase(0, spacePos + 1); } if (firstWordOfLine == "SIZE_OF_LEVEL") { currentLevel.limitOfGame.top = 0; currentLevel.limitOfGame.left = 0; currentLevel.limitOfGame.width = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.limitOfGame.height = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "PLAYER_POSITION") { currentLevel.playerStartPosition.x = Utilities::stringToInt(Utilities::readFirstString(currentLine)); currentLevel.playerStartPosition.y = Utilities::stringToInt(Utilities::readFirstString(currentLine)); } else if (firstWordOfLine == "NEW_BLOCK") { BasicBlock newBlock; newBlock.id = BlockManager::stringBlockId(Utilities::readFirstString(currentLine)); int posX = Utilities::stringToInt(Utilities::readFirstString(currentLine)); int posY = Utilities::stringToInt(Utilities::readFirstString(currentLine)); newBlock.sprite.setSize(sf::Vector2f(SIZE_BLOCK, SIZE_BLOCK)); newBlock.sprite.setPosition(SIZE_BLOCK * posX, SIZE_BLOCK * posY); newBlock.sprite.setFillColor(BlockManager::getColorOfBlock(newBlock.id)); currentLevel.mapOfGame[Point(posX, posY)] = std::move(newBlock); } else { std::string newLine = firstWordOfLine; if (!currentLine.empty()) { newLine += " " + currentLine; } currentLevel.otherLines.push_back(newLine); } } file.close(); } void LevelManager::saveBasicLevel(BasicLevelInfo& currentLevel, std::string levelName) { std::ofstream file; file.open("resources/" + levelName); file << "SIZE_OF_LEVEL " << currentLevel.limitOfGame.width << " " << currentLevel.limitOfGame.height << std::endl; file << "PLAYER_POSITION " << currentLevel.playerStartPosition.x << " " << currentLevel.playerStartPosition.y << std::endl; for (auto& currentLevelIte : currentLevel.mapOfGame) { file << "NEW_BLOCK " << BlockManager::blockIdToString(currentLevelIte.second.id) << " " << currentLevelIte.first.first << " " << currentLevelIte.first.second << std::endl; } for (std::string& line : currentLevel.otherLines) { file << line << std::endl; } file.close(); }
36.473684
118
0.636364
adbecc30a0fe5a2dbe4ac91abdf0b678606a2c3f
955
cpp
C++
src/mxml/parsing/MordentHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
18
2016-05-22T00:55:28.000Z
2021-03-29T08:44:23.000Z
src/mxml/parsing/MordentHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
6
2017-05-17T13:20:09.000Z
2018-10-22T20:00:57.000Z
src/mxml/parsing/MordentHandler.cpp
dkun7944/mxml
6450e7cab88eb6ee0ac469f437047072e1868ea4
[ "MIT" ]
14
2016-05-12T22:54:34.000Z
2021-10-19T12:43:16.000Z
// Copyright © 2016 Venture Media Labs. // // This file is part of mxml. The full mxml copyright notice, including // terms governing use, modification, and redistribution, is contained in the // file LICENSE at the root of the source code distribution tree. #include "MordentHandler.h" #include "EmptyPlacementHandler.h" namespace mxml { using dom::Mordent; static const char* kPlacementAttribute = "placement"; static const char* kLongAttribute = "long"; void MordentHandler::startElement(const lxml::QName& qname, const AttributeMap& attributes) { _result.reset(new Mordent()); auto placement = attributes.find(kPlacementAttribute); if (placement != attributes.end()) _result->setPlacement(presentOptional(EmptyPlacementHandler::placementFromString(placement->second))); auto longv = attributes.find(kLongAttribute); if (longv != attributes.end()) _result->setLong(longv->second == "yes"); } } // namespace
30.806452
110
0.736126
adbfd05a98256bf85511a02bd842b3c4af93c5bb
2,714
cpp
C++
NES/Mapper/Mapper068.cpp
chittleskuny/virtuanes
f2528f24108ebde6c2e123920423d95e086d86bc
[ "MIT" ]
null
null
null
NES/Mapper/Mapper068.cpp
chittleskuny/virtuanes
f2528f24108ebde6c2e123920423d95e086d86bc
[ "MIT" ]
null
null
null
NES/Mapper/Mapper068.cpp
chittleskuny/virtuanes
f2528f24108ebde6c2e123920423d95e086d86bc
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////////// // Mapper068 SunSoft (After Burner II) // ////////////////////////////////////////////////////////////////////////// void Mapper068::Reset() { reg[0] = reg[1] = reg[2] = reg[3] = 0; coin = 0; SetPROM_32K_Bank( 0, 1, PROM_8K_SIZE-2, PROM_8K_SIZE-1 ); } #if 0 BYTE Mapper068::ExRead( WORD addr ) { if( addr == 0x4020 ) { DEBUGOUT( "RD $4020:%02X\n", coin ); return coin; } return addr>>8; } void Mapper068::ExWrite( WORD addr, BYTE data ) { if( addr == 0x4020 ) { DEBUGOUT( "WR $4020:%02X\n", data ); coin = data; } } #endif void Mapper068::Write( WORD addr, BYTE data ) { switch( addr & 0xF000 ) { case 0x8000: SetVROM_2K_Bank( 0, data ); break; case 0x9000: SetVROM_2K_Bank( 2, data ); break; case 0xA000: SetVROM_2K_Bank( 4, data ); break; case 0xB000: SetVROM_2K_Bank( 6, data ); break; case 0xC000: reg[2] = data; SetBank(); break; case 0xD000: reg[3] = data; SetBank(); break; case 0xE000: reg[0] = (data & 0x10)>>4; reg[1] = data & 0x03; SetBank(); break; case 0xF000: SetPROM_16K_Bank( 4, data ); break; } } void Mapper068::SetBank() { if( reg[0] ) { switch( reg[1] ) { case 0: SetVROM_1K_Bank( 8, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 9, (INT)reg[3]+0x80 ); SetVROM_1K_Bank( 10, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 11, (INT)reg[3]+0x80 ); break; case 1: SetVROM_1K_Bank( 8, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 9, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 10, (INT)reg[3]+0x80 ); SetVROM_1K_Bank( 11, (INT)reg[3]+0x80 ); break; case 2: SetVROM_1K_Bank( 8, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 9, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 10, (INT)reg[2]+0x80 ); SetVROM_1K_Bank( 11, (INT)reg[2]+0x80 ); break; case 3: SetVROM_1K_Bank( 8, (INT)reg[3]+0x80 ); SetVROM_1K_Bank( 9, (INT)reg[3]+0x80 ); SetVROM_1K_Bank( 10, (INT)reg[3]+0x80 ); SetVROM_1K_Bank( 11, (INT)reg[3]+0x80 ); break; } } else { switch( reg[1] ) { case 0: SetVRAM_Mirror( VRAM_VMIRROR ); break; case 1: SetVRAM_Mirror( VRAM_HMIRROR ); break; case 2: SetVRAM_Mirror( VRAM_MIRROR4L ); break; case 3: SetVRAM_Mirror( VRAM_MIRROR4H ); break; } } } void Mapper068::SaveState( LPBYTE p ) { p[0] = reg[0]; p[1] = reg[1]; p[2] = reg[2]; p[3] = reg[3]; } void Mapper068::LoadState( LPBYTE p ) { reg[0] = p[0]; reg[1] = p[1]; reg[2] = p[2]; reg[3] = p[3]; }
20.876923
75
0.51437
adc1c288c47b2f985cdf0a31fa43588ec7f4688d
3,976
cpp
C++
cabal_ep8_costumeext/src/main.cpp
Michael-Kelley/CABAL-Online-EP8-Costume-Limit-Extender
245001bafbd62db929f9ba2ae0282b2920239ba7
[ "MIT" ]
6
2019-06-15T14:50:30.000Z
2021-01-01T15:51:38.000Z
cabal_ep8_costumeext/src/main.cpp
Michael-Kelley/CABAL-Online-EP8-Costume-Limit-Extender
245001bafbd62db929f9ba2ae0282b2920239ba7
[ "MIT" ]
null
null
null
cabal_ep8_costumeext/src/main.cpp
Michael-Kelley/CABAL-Online-EP8-Costume-Limit-Extender
245001bafbd62db929f9ba2ae0282b2920239ba7
[ "MIT" ]
2
2019-06-29T12:09:33.000Z
2021-01-01T15:51:39.000Z
#define WIN32_LEAN_AND_MEAN #define VC_EXTRALEAN #include <Windows.h> #include <cstdint> #include <string> #include <WinSock2.h> // DO NOT ENABLE THIS! THE CODE FOR THIS DOES NOT WORK YET. #define EXTENDED_HOOK 0 const std::uintptr_t find_costume_mesh_addr = 0xC8CC0U; const std::uintptr_t ech_read_meshes_addr = 0xDA190U; std::uintptr_t base_addr = 0; std::uintptr_t find_costume_mesh_jmp_addr = 0; #if EXTENDED_HOOK std::uintptr_t display_code_jmp_addr = 0; std::uintptr_t display_code_pt1 = 0; __declspec(naked) void display_code_switch() { __asm { movsx edx, [esp + 40] // displaycode_pt1 mov display_code_pt1, edx } switch (display_code_pt1) { case 'z': // Martial gear __asm { mov edx, [ebp + 232] // mesh->flags and edx, 0xFFFFF03F } break; case 'a': // Armour gear __asm { mov edx, [ebp + 232] and edx, 0xFFFFF0BF or edx, 0x80 } break; case 'm': // Battle gear __asm { mov edx, [ebp + 232] and edx, 0xFFFFF07F or edx, 0x40 } break; case 'b': // dafuq is this? __asm { mov edx, [ebp + 232] and edx, 0xFFFFF0FF or edx, 0xC0 } break; case 's': // Everything from here on is costumes case 't': case 'u': case 'v': case 'w': case 'x': case 'y': __asm { mov edx, [ebp + 232] and edx, 0xFFFFF0FF or edx, 0xC0 mov esi, display_code_pt1 sub esi, 115 shl esi, 4 } break; case 'A': // New costume codes! case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': __asm { mov edx, [ebp + 232] and edx, 0xFFFFF0FF or edx, 0xC0 mov esi, display_code_pt1 sub esi, 58 shl esi, 4 } break; default: __asm { mov edx, [ebp + 232] or edx, 0xFC0 } break; } __asm { mov[ebp + 232], edx jmp[display_code_jmp_addr] } } #endif __declspec(naked) void check_mesh_flag() { __asm { and eax, 0x1FF sub eax, 0xC0 cmp eax, edx jmp[find_costume_mesh_jmp_addr] } } void hook() { if (base_addr != 0) return; base_addr = reinterpret_cast<decltype(base_addr)>(GetModuleHandle(nullptr)); find_costume_mesh_jmp_addr = base_addr + find_costume_mesh_addr + 0x74U; auto old = 0UL; // ECH::ReadMeshes patches auto addr = reinterpret_cast<uint8_t*>(base_addr + ech_read_meshes_addr); VirtualProtect(addr, 8, PAGE_EXECUTE_READWRITE, &old); *reinterpret_cast<uint32_t*>(addr) = 0x90909090; // nop, nop, nop, nop *reinterpret_cast<uint16_t*>(addr + 4) = 0x9090; // nop, nop addr[6] = 0x90; // nop VirtualProtect(addr, 8, old, &old); #if EXTENDED_HOOK // ECH::ReadMeshes once more (switch-case replacement) addr = reinterpret_cast<uint8_t*>(base_addr + ech_read_meshes_addr - 0x1E4U); VirtualProtect(addr, 8, PAGE_EXECUTE_READWRITE, &old); addr[0] = 0xE9; // jmp *reinterpret_cast<uint32_t*>(addr + 1) = reinterpret_cast<uint32_t>(&display_code_switch) - (base_addr + ech_read_meshes_addr - 0x1DFU); // Address of display_code_switch VirtualProtect(addr, 8, old, &old); // Set the address for display_code_switch return jump (stupid msvc inline assembler bullshit...) display_code_jmp_addr = base_addr + ech_read_meshes_addr - 0xA9U; #endif // FindCostumeMesh patches addr = reinterpret_cast<uint8_t*>(base_addr + find_costume_mesh_addr + 3); VirtualProtect(addr, 48, PAGE_EXECUTE_READWRITE, &old); *reinterpret_cast<uint16_t*>(&addr[2]) = 0x01FF; addr[8] = 0xBF; addr[12] = 0x7E; // jle addr[24] = 0xE9; // jmp *reinterpret_cast<uintptr_t*>(&addr[25]) = reinterpret_cast<uintptr_t>(&check_mesh_flag) - (base_addr + find_costume_mesh_addr + 32U); // Address of check_mesh_flag VirtualProtect(addr, 48, old, &old); } extern "C" __declspec(dllexport) void blue() { hook(); } // Doesn't work when called from DllMain... /*BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { if (fdwReason == DLL_PROCESS_ATTACH) hook(); }*/
22.850575
131
0.669517
adccb5f1b156054bc25860aecc8c8c7d649bfd59
14,637
cpp
C++
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
21
2015-07-22T15:22:41.000Z
2021-03-23T05:40:44.000Z
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
11
2015-10-19T07:54:10.000Z
2021-09-01T08:47:56.000Z
Source/Client/IM-Client/IMClient/HttpDownloader.cpp
InstantBusinessNetwork/IBN
bbcf47de56bfc52049eeb2e46677642a28f38825
[ "MIT" ]
16
2015-07-22T15:23:09.000Z
2022-01-17T10:49:43.000Z
// HttpDownloader.cpp: implementation of the CHttpDownloader class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "HttpDownloader.h" #include "Resource.h" #include "GlobalFunction.h" #include "atlenc.h" #ifdef _DEBUG #undef THIS_FILE static char THIS_FILE[]=__FILE__; #define new DEBUG_NEW #endif ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// CHttpDownloader::CHttpDownloader() { m_hInternet = 0; m_hConnect = 0; m_hRequest = 0; m_longAbort = FALSE; m_pStream = NULL; m_hWnd = NULL; m_nMessage = 0; m_dwTotalSize = 0; m_dwDownloaded = 0; m_dwTimeout = 60000; m_dwConnectRetryCount = 3; m_ProxyType = GetOptionInt(IDS_NETOPTIONS, IDS_ACCESSTYPE, INTERNET_OPEN_TYPE_PRECONFIG); m_ProxyName.Format(_T("http=http://%s:%s"), GetOptionString(IDS_NETOPTIONS, IDS_PROXYNAME, _T("")), GetOptionString(IDS_NETOPTIONS, IDS_PROXYPORT, _T(""))); // m_UseFireWall = GetOptionInt(IDS_NETOPTIONS, IDS_USEFIREWALL, FALSE); // m_FireWallUser = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, ""); // m_FireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, ""); m_hEvent = ::CreateEvent(NULL, TRUE, TRUE, NULL); } CHttpDownloader::~CHttpDownloader() { Clear(); if(m_pStream) { m_pStream->Release(); m_pStream = NULL; } CloseHandle(m_hEvent); } HRESULT CHttpDownloader::ConnectToServer(_bstr_t &strBuffer) { BOOL bResult; DWORD dwStatus; DWORD nTimeoutCounter; _bstr_t strMethod; _bstr_t strUrl = m_request.url; LPCTSTR szProxyName = NULL; if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY) szProxyName = m_ProxyName; //// InternetOpen \\\\ if(!m_hInternet) m_hInternet = InternetOpen(_T("McHttpDownloader"), m_ProxyType, szProxyName, NULL, INTERNET_FLAG_ASYNC); if(!m_hInternet) { strBuffer = _T("InternetOpen failed"); return E_FAIL; } InternetSetStatusCallback(m_hInternet, (INTERNET_STATUS_CALLBACK)CallbackFunc); //// InternetOpen //// if(m_longAbort > 0) return E_ABORT; //// InternetConnect \\\\ if(!m_hConnect) { m_hConnect = InternetConnect(m_hInternet, m_request.server, (short)m_request.port, NULL, NULL, INTERNET_SERVICE_HTTP, NULL, (DWORD)&m_context); } if(m_hConnect == NULL) { strBuffer = _T("InternetConnect failed"); return INET_E_CANNOT_CONNECT; } //// InternetConnect //// nTimeoutCounter = 0; NewConnect: strMethod = _T("GET"); strBuffer = _T(""); //// OpenRequest \\\\ if(m_hRequest) { ::InternetCloseHandle(m_hRequest); m_hRequest = NULL; } if(m_longAbort > 0) return E_ABORT; DWORD dwFlags = INTERNET_FLAG_KEEP_CONNECTION | INTERNET_FLAG_NO_CACHE_WRITE | INTERNET_FLAG_RELOAD | INTERNET_FLAG_PRAGMA_NOCACHE | INTERNET_FLAG_NO_UI | INTERNET_FLAG_NO_COOKIES | INTERNET_FLAG_IGNORE_CERT_CN_INVALID | INTERNET_FLAG_NO_AUTO_REDIRECT | INTERNET_FLAG_HYPERLINK | (m_request.bUseSSL ? (INTERNET_FLAG_SECURE/*| INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTPS| INTERNET_FLAG_IGNORE_REDIRECT_TO_HTTP*/) : 0); m_context.op = HTTP_DOWNLOADER_OP_OPEN_REQUEST; m_hRequest = HttpOpenRequest(m_hConnect, strMethod, strUrl, _T("HTTP/1.1"), NULL, NULL, dwFlags, (DWORD)&m_context); if(m_hRequest == NULL) { strBuffer = _T("HttpOpenRequest failed"); return E_FAIL; } if(m_ProxyType == INTERNET_OPEN_TYPE_PROXY) { if(GetOptionInt(IDS_NETOPTIONS,IDS_USEFIREWALL,0)) { CString fireWallUser = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLUSER, _T("")); CString fireWallPass = GetOptionString(IDS_NETOPTIONS, IDS_FIREWALLPASS, _T("")); ////////////////////////////////////////////////////////////////////////// int HeaderLen = ATL::ProxyAuthorizationStringGetRequiredLength(fireWallUser, fireWallPass); LPTSTR strHeader = new TCHAR[HeaderLen+1]; ZeroMemory(strHeader,HeaderLen+1); HRESULT hr = ATL::ProxyAuthorizationString(fireWallUser, fireWallPass, strHeader, &HeaderLen); ASSERT(hr==S_OK); HttpAddRequestHeaders(m_hRequest, strHeader, HeaderLen, HTTP_ADDREQ_FLAG_ADD ); delete []strHeader; ////////////////////////////////////////////////////////////////////////// } } //// OpenRequest //// NewRequest: if(m_longAbort > 0) return E_ABORT; m_context.op = HTTP_DOWNLOADER_OP_SEND_REQUEST; bResult = HttpSendRequest(m_hRequest, NULL , 0, (LPVOID)(BYTE*)(LPCTSTR)strBuffer, lstrlen(strBuffer)); if(!bResult && 997 == GetLastError()) // Overlapped I/O operation is in progress. bResult = WaitForComplete(m_dwTimeout); // Resolve host name, connect, send request, receive response. if(!bResult) { DWORD dwErrCode = GetLastError(); // ATLTRACE("Send Request error = %d \r\n",dwErrCode); if(dwErrCode == 6) // The handle is invalid. goto NewConnect; if(dwErrCode == ERROR_INTERNET_TIMEOUT) // timeout { if(++nTimeoutCounter < m_dwConnectRetryCount) goto NewConnect; else { strBuffer = _T("Timeout"); return E_FAIL;//INET_E_CONNECTION_TIMEOUT; } } strBuffer = _T("SendRequest failed"); return E_FAIL; } dwStatus = GetHttpStatus(); if(dwStatus == 401 || dwStatus == 407) // Denied or Proxy asks password { if(ERROR_INTERNET_FORCE_RETRY == InternetErrorDlg(GetDesktopWindow(), m_hRequest, ERROR_INTERNET_INCORRECT_PASSWORD, FLAGS_ERROR_UI_FILTER_FOR_ERRORS | FLAGS_ERROR_UI_FLAGS_CHANGE_OPTIONS | FLAGS_ERROR_UI_FLAGS_GENERATE_DATA, NULL)) { goto NewRequest; } } if(dwStatus != 200) // Not OK { strBuffer = _T("SendRequest returned with error"); return INET_E_CANNOT_CONNECT; } return S_OK; } DWORD CHttpDownloader::GetHttpStatus() { LPVOID lpOutBuffer = new char[4]; DWORD dwSize = 4; DWORD Status = 0; DWORD err = 0; BOOL bResult; ret: m_context.op = HTTP_DOWNLOADER_OP_GET_STATUS; bResult = HttpQueryInfo(m_hRequest, HTTP_QUERY_STATUS_CODE, (LPVOID)lpOutBuffer, &dwSize, NULL); if(!bResult&&997 == GetLastError()) WaitForComplete(m_dwTimeout); if(!bResult) { err = GetLastError(); if(err == ERROR_HTTP_HEADER_NOT_FOUND) { return false; //throw(); } else { if (err == ERROR_INSUFFICIENT_BUFFER) { if(lpOutBuffer!=NULL) delete[] lpOutBuffer; lpOutBuffer = new char[dwSize]; goto ret; } else { return Status; //throw(); } } } else { // ATLTRACE("HTTP STATUS - %s \r\n", lpOutBuffer); Status = atol((char*)lpOutBuffer); delete[] lpOutBuffer; lpOutBuffer = NULL; return Status; } } HRESULT CHttpDownloader::WorkFunction() { HRESULT hr; _bstr_t strBuffer; strBuffer = _T(""); if(m_longAbort > 0) { hr = E_ABORT; goto EndWorkFunc; } if(m_request.pCritSect) EnterCriticalSection(m_request.pCritSect); if(m_longAbort > 0) { hr = E_ABORT; goto EndWorkFunc; } hr = ConnectToServer(strBuffer); if(FAILED(hr)) goto EndWorkFunc; hr = ReadData(strBuffer); if(FAILED(hr) || m_dwDownloaded < m_dwTotalSize) { strBuffer = _T("Cannot read data"); goto EndWorkFunc; } EndWorkFunc: // TRACE(_T("HTTP OPERATION = %d\n"), m_context.op); Clear(); if(m_pStream) { LARGE_INTEGER li = {0, 0}; hr = m_pStream->Seek(li, STREAM_SEEK_SET, NULL); } if(m_request.pCritSect) { try { LeaveCriticalSection(m_request.pCritSect); } catch(...) { // MCTRACE(0, _T("LeaveCriticalSection(%08x)"), m_request.pCritSect); } } return hr; } HRESULT CHttpDownloader::ReadData(_bstr_t &strBuffer) { HRESULT hr = E_FAIL; IStream *pStream = NULL; INTERNET_BUFFERS ib ={0}; ULONG ulWritten; BOOL bResult; DWORD dwErr; TCHAR buf[32]; DWORD dwBufferLength; TCHAR *szNULL = _T("\x0"); // Get file size dwBufferLength = 32*sizeof(TCHAR); if(::HttpQueryInfo(m_hRequest, HTTP_QUERY_CONTENT_LENGTH, buf, &dwBufferLength, NULL)) { m_dwTotalSize = _tcstoul(buf, &szNULL, 10); if(m_hWnd != NULL && m_nMessage != 0) ::PostMessage(m_hWnd, m_nMessage, m_dwDownloaded, m_dwTotalSize); } //Check MD5 hash if(m_request.md5 != NULL && _tcslen(m_request.md5) >= 22) { dwBufferLength = 32*sizeof(TCHAR); if(::HttpQueryInfo(m_hRequest, HTTP_QUERY_CONTENT_MD5, buf, &dwBufferLength, NULL)) { if(0 == _tcsnicmp(m_request.md5, buf, 22)) { if(m_hWnd != NULL && m_nMessage != 0) ::PostMessage(m_hWnd, m_nMessage, m_dwTotalSize, m_dwTotalSize); } return S_OK; } } hr = CreateStreamOnHGlobal(NULL, TRUE, &pStream); if(FAILED(hr)) { return hr; } ib.lpcszHeader = NULL; ib.dwHeadersLength = NULL; ib.lpvBuffer = new TCHAR[COMMAND_BUFF_SIZE_PART]; ib.dwBufferLength = COMMAND_BUFF_SIZE_PART; ib.dwStructSize = sizeof(ib); do { ib.dwBufferLength = COMMAND_BUFF_SIZE_PART; if(m_longAbort > 0) { hr = E_ABORT; break; } m_context.op = HTTP_DOWNLOADER_OP_READ_DATA; bResult = InternetReadFileEx(m_hRequest, &ib, IRF_ASYNC | IRF_USE_CONTEXT, (DWORD)&m_context); dwErr = GetLastError(); if(!bResult && dwErr == 997) // Overlapped I/O operation is in progress. { bResult = WaitForComplete(m_dwTimeout); if(bResult) continue; } if(bResult) { if(ib.dwBufferLength) { hr = pStream->Write(ib.lpvBuffer, ib.dwBufferLength, &ulWritten); if(FAILED(hr)) { strBuffer = _T("Cannot write to stream"); break; } m_dwDownloaded += ib.dwBufferLength; if(m_hWnd != NULL && m_nMessage != 0) ::PostMessage(m_hWnd, m_nMessage, m_dwDownloaded, m_dwTotalSize); } } else { hr = E_FAIL; break; } // Sleep(1); } while(ib.dwBufferLength); if(ib.lpvBuffer) { delete[] ib.lpvBuffer; ib.lpvBuffer = NULL; } if(SUCCEEDED(hr) && pStream) { m_pStream = pStream; return hr; } else { if(pStream) pStream->Release(); pStream = NULL; } return hr; } HRESULT CHttpDownloader::Load(LPCTSTR szUrl, IStream **ppStream, LPCTSTR szMD5) { HRESULT hr = E_FAIL; m_longAbort = 0; Clear(); *ppStream = NULL; m_dwDownloaded = 0; m_dwTotalSize = 0; m_request.md5 = szMD5; hr = ParseUrl(szUrl); if(SUCCEEDED(hr)) { if(m_pStream) { m_pStream->Release(); m_pStream = NULL; } m_context.op = HTTP_DOWNLOADER_OP_IDLE; m_context.hEvent = m_hEvent; SetEvent(m_hEvent); hr = WorkFunction(); if(SUCCEEDED(hr)) { m_pStream->AddRef(); *ppStream = m_pStream; } } return hr; } HRESULT CHttpDownloader::ParseUrl(LPCTSTR szUrlIn) { if(!lstrlen(szUrlIn)) return INET_E_INVALID_URL; URL_COMPONENTS uc; memset(&uc, 0, sizeof(uc)); uc.dwStructSize = sizeof(uc); TCHAR szServer[1024]; TCHAR szUrl[1024]; // TCHAR szScheme[1024]; uc.lpszHostName = szServer; uc.dwHostNameLength = sizeof(szServer); uc.lpszUrlPath = szUrl; uc.dwUrlPathLength = sizeof(szUrl); // uc.lpszScheme =szScheme; // uc.dwSchemeLength = sizeof(szScheme); if(!InternetCrackUrl(szUrlIn, lstrlen(szUrlIn), 0, &uc)) return INET_E_INVALID_URL; if(uc.nScheme==INTERNET_SCHEME_HTTPS) m_request.bUseSSL = TRUE; if(lstrlen(szServer)) m_request.server = szServer; if(uc.nPort != 0) m_request.port = uc.nPort; if(lstrlen(szUrl)) m_request.url = szUrl; return S_OK; } void CHttpDownloader::EnableProgress(HWND hWnd, UINT nMessage) { m_hWnd = hWnd; m_nMessage = nMessage; } void CHttpDownloader::Abort() { InterlockedExchange(&m_longAbort, 1); Clear(); SetEvent(m_hEvent); } void CHttpDownloader::Clear() { if(m_hRequest) { InternetCloseHandle(m_hRequest); m_hRequest = NULL; } if(m_hConnect) { InternetCloseHandle(m_hConnect); m_hConnect = NULL; } if(m_hInternet) { InternetCloseHandle(m_hInternet); m_hInternet = NULL; } } void __stdcall CHttpDownloader::CallbackFunc(HINTERNET hInternet, DWORD dwContext, DWORD dwInternetStatus, LPVOID lpvStatusInformation, DWORD dwStatusInformationLength) { // TRACE(_T("INTERNET CALLBACK %08x %08x %d\n"), hInternet, dwContext, dwInternetStatus); if(IsBadWritePtr((LPVOID)dwContext,sizeof(CHttpDownloader :: HttpDownloaderContext))) return; CHttpDownloader::HttpDownloaderContext *pContext = (CHttpDownloader::HttpDownloaderContext*)dwContext; INTERNET_ASYNC_RESULT* pINTERNET_ASYNC_RESULT = NULL; BOOL bRetVal = FALSE; switch (dwInternetStatus) { case INTERNET_STATUS_REQUEST_COMPLETE: pINTERNET_ASYNC_RESULT = (INTERNET_ASYNC_RESULT*)lpvStatusInformation; if(pINTERNET_ASYNC_RESULT->dwError!=ERROR_INTERNET_OPERATION_CANCELLED) { pContext->dwError = pINTERNET_ASYNC_RESULT->dwError; bRetVal = SetEvent(pContext->hEvent); } break; /* case INTERNET_STATUS_RESPONSE_RECEIVED: if(pContext) { if(pContext->op == HTTP_DOWNLOADER_OP_READ_DATA) SetEvent(pContext->hEvent); } break;*/ case INTERNET_STATUS_RESOLVING_NAME: case INTERNET_STATUS_NAME_RESOLVED: case INTERNET_STATUS_CONNECTING_TO_SERVER: case INTERNET_STATUS_CONNECTED_TO_SERVER: case INTERNET_STATUS_SENDING_REQUEST: case INTERNET_STATUS_REQUEST_SENT: case INTERNET_STATUS_RECEIVING_RESPONSE: case INTERNET_STATUS_CTL_RESPONSE_RECEIVED: case INTERNET_STATUS_PREFETCH: case INTERNET_STATUS_CLOSING_CONNECTION: case INTERNET_STATUS_CONNECTION_CLOSED: case INTERNET_STATUS_HANDLE_CREATED: case INTERNET_STATUS_HANDLE_CLOSING: case INTERNET_STATUS_REDIRECT: case INTERNET_STATUS_INTERMEDIATE_RESPONSE: case INTERNET_STATUS_STATE_CHANGE: default: break; } } BOOL CHttpDownloader::WaitForComplete(DWORD dwMilliseconds) { ResetEvent(m_hEvent); DWORD dw = WaitForSingleObject(m_hEvent, dwMilliseconds); //TRACE("\r\n == after WaitForSingleObject == \r\n"); if(m_longAbort > 0) { // TRACE(_T("WaitForComplete: ABORTED, OP = %d\n"), m_context.op); SetLastError(ERROR_INTERNET_CONNECTION_ABORTED); return FALSE; } if(dw == WAIT_TIMEOUT) { // TRACE(_T("WaitForComplete: TIMEOUT, OP = %d\n"), m_context.op); SetLastError(ERROR_INTERNET_TIMEOUT); return FALSE; } if(m_context.dwError != ERROR_SUCCESS) return FALSE; return (dw == WAIT_OBJECT_0); }
23.27027
169
0.662909
adccb8a5662a5de17434c419c0a66ffe388f5e52
1,012
cc
C++
stl/containers/map/unordered_map.cc
curoky/dumbo
d0aae7b239a552ff670795ae51c3452c9e28f63d
[ "Apache-2.0" ]
null
null
null
stl/containers/map/unordered_map.cc
curoky/dumbo
d0aae7b239a552ff670795ae51c3452c9e28f63d
[ "Apache-2.0" ]
null
null
null
stl/containers/map/unordered_map.cc
curoky/dumbo
d0aae7b239a552ff670795ae51c3452c9e28f63d
[ "Apache-2.0" ]
null
null
null
/* * Copyright 2019 curoky(cccuroky@gmail.com). * * 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 <catch2/catch.hpp> // for AssertionHandler, operator""_catch_sr, SourceLineInfo, StringRef, REQUIRE, TEST_CASE #include <algorithm> // for max #include <unordered_map> // for unordered_map, pair TEST_CASE("[UnorderedMap]: insert when exists") { std::unordered_map<int, int> mp = {{1, 1}}; REQUIRE(mp.emplace(1, 2).second == false); REQUIRE(mp.emplace(2, 2).second == true); }
37.481481
120
0.720356
add35b5bbe2b0962674ac0b421017a86f1f02314
8,813
cc
C++
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
swapnil119/chromeos_smart_card_connector
c01ec7e9aad61ede90f1eeaf8554540ede988d2d
[ "Apache-2.0" ]
1
2021-10-18T03:23:18.000Z
2021-10-18T03:23:18.000Z
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
AdrianaDJ/chromeos_smart_card_connector
63bcbc1ce293779efbe99a63edfbc824d96719fc
[ "Apache-2.0" ]
1
2021-02-23T22:37:22.000Z
2021-02-23T22:37:22.000Z
common/cpp/src/google_smart_card_common/pp_var_utils/extraction.cc
AdrianaDJ/chromeos_smart_card_connector
63bcbc1ce293779efbe99a63edfbc824d96719fc
[ "Apache-2.0" ]
1
2021-04-15T17:09:55.000Z
2021-04-15T17:09:55.000Z
// Copyright 2016 Google 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. #include <google_smart_card_common/pp_var_utils/extraction.h> #include <cstring> #include <google_smart_card_common/numeric_conversions.h> namespace google_smart_card { namespace { constexpr char kErrorWrongType[] = "Expected a value of type \"%s\", instead got: %s"; template <typename T> bool VarAsInteger(const pp::Var& var, const char* type_name, T* result, std::string* error_message) { int64_t integer; if (var.is_int()) { integer = var.AsInt(); } else if (var.is_double()) { if (!CastDoubleToInt64(var.AsDouble(), &integer, error_message)) return false; } else { *error_message = FormatPrintfTemplate(kErrorWrongType, kIntegerJsTypeTitle, DebugDumpVar(var).c_str()); return false; } return CastInteger(integer, type_name, result, error_message); } } // namespace bool VarAs(const pp::Var& var, int8_t* result, std::string* error_message) { return VarAsInteger(var, "int8_t", result, error_message); } bool VarAs(const pp::Var& var, uint8_t* result, std::string* error_message) { return VarAsInteger(var, "uint8_t", result, error_message); } bool VarAs(const pp::Var& var, int16_t* result, std::string* error_message) { return VarAsInteger(var, "int16_t", result, error_message); } bool VarAs(const pp::Var& var, uint16_t* result, std::string* error_message) { return VarAsInteger(var, "uint16_t", result, error_message); } bool VarAs(const pp::Var& var, int32_t* result, std::string* error_message) { return VarAsInteger(var, "int32_t", result, error_message); } bool VarAs(const pp::Var& var, uint32_t* result, std::string* error_message) { return VarAsInteger(var, "uint32_t", result, error_message); } bool VarAs(const pp::Var& var, int64_t* result, std::string* error_message) { return VarAsInteger(var, "int64_t", result, error_message); } bool VarAs(const pp::Var& var, uint64_t* result, std::string* error_message) { return VarAsInteger(var, "uint64_t", result, error_message); } bool VarAs(const pp::Var& var, long* result, std::string* error_message) { return VarAsInteger(var, "long", result, error_message); } bool VarAs(const pp::Var& var, unsigned long* result, std::string* error_message) { return VarAsInteger(var, "unsigned long", result, error_message); } bool VarAs(const pp::Var& var, float* result, std::string* error_message) { double double_value; if (!VarAs(var, &double_value, error_message)) return false; *result = static_cast<float>(double_value); return true; } bool VarAs(const pp::Var& var, double* result, std::string* error_message) { if (!var.is_number()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kIntegerJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = var.AsDouble(); return true; } bool VarAs(const pp::Var& var, bool* result, std::string* error_message) { if (!var.is_bool()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kBooleanJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = var.AsBool(); return true; } bool VarAs(const pp::Var& var, std::string* result, std::string* error_message) { if (!var.is_string()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kStringJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = var.AsString(); return true; } bool VarAs(const pp::Var& var, pp::Var* result, std::string* /*error_message*/) { *result = var; return true; } bool VarAs(const pp::Var& var, pp::VarArray* result, std::string* error_message) { if (!var.is_array()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kArrayJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = pp::VarArray(var); return true; } bool VarAs(const pp::Var& var, pp::VarArrayBuffer* result, std::string* error_message) { if (!var.is_array_buffer()) { *error_message = FormatPrintfTemplate( kErrorWrongType, kArrayBufferJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = pp::VarArrayBuffer(var); return true; } bool VarAs(const pp::Var& var, pp::VarDictionary* result, std::string* error_message) { if (!var.is_dictionary()) { *error_message = FormatPrintfTemplate( kErrorWrongType, kDictionaryJsTypeTitle, DebugDumpVar(var).c_str()); return false; } *result = pp::VarDictionary(var); return true; } bool VarAs(const pp::Var& var, pp::Var::Null* /*result*/, std::string* error_message) { if (!var.is_null()) { *error_message = FormatPrintfTemplate(kErrorWrongType, kNullJsTypeTitle, DebugDumpVar(var).c_str()); return false; } return true; } namespace internal { std::vector<uint8_t> GetVarArrayBufferData(pp::VarArrayBuffer var) { std::vector<uint8_t> result(var.ByteLength()); if (!result.empty()) { std::memcpy(&result[0], var.Map(), result.size()); var.Unmap(); } return result; } } // namespace internal int GetVarDictSize(const pp::VarDictionary& var) { return GetVarArraySize(var.GetKeys()); } int GetVarArraySize(const pp::VarArray& var) { return static_cast<int>(var.GetLength()); } bool GetVarDictValue(const pp::VarDictionary& var, const std::string& key, pp::Var* result, std::string* error_message) { if (!var.HasKey(key)) { *error_message = FormatPrintfTemplate("The dictionary has no key \"%s\"", key.c_str()); return false; } *result = var.Get(key); return true; } pp::Var GetVarDictValue(const pp::VarDictionary& var, const std::string& key) { pp::Var result; std::string error_message; if (!GetVarDictValue(var, key, &result, &error_message)) GOOGLE_SMART_CARD_LOG_FATAL << error_message; return result; } VarDictValuesExtractor::VarDictValuesExtractor(const pp::VarDictionary& var) : var_(var) { const std::vector<std::string> keys = VarAs<std::vector<std::string>>(var_.GetKeys()); not_requested_keys_.insert(keys.begin(), keys.end()); } bool VarDictValuesExtractor::GetSuccess(std::string* error_message) const { if (failed_) { *error_message = error_message_; return false; } return true; } bool VarDictValuesExtractor::GetSuccessWithNoExtraKeysAllowed( std::string* error_message) const { if (!GetSuccess(error_message)) return false; if (!not_requested_keys_.empty()) { std::string unexpected_keys_dump; for (const std::string& key : not_requested_keys_) { if (!unexpected_keys_dump.empty()) unexpected_keys_dump += ", "; unexpected_keys_dump += '"' + key + '"'; } *error_message = FormatPrintfTemplate("The dictionary contains unexpected keys: %s", unexpected_keys_dump.c_str()); return false; } return true; } void VarDictValuesExtractor::CheckSuccess() const { std::string error_message; if (!GetSuccess(&error_message)) GOOGLE_SMART_CARD_LOG_FATAL << error_message; } void VarDictValuesExtractor::CheckSuccessWithNoExtraKeysAllowed() const { std::string error_message; if (!GetSuccessWithNoExtraKeysAllowed(&error_message)) GOOGLE_SMART_CARD_LOG_FATAL << error_message; } void VarDictValuesExtractor::AddRequestedKey(const std::string& key) { not_requested_keys_.erase(key); } void VarDictValuesExtractor::ProcessFailedExtraction( const std::string& key, const std::string& extraction_error_message) { if (failed_) { // We could concatenate all occurred errors, but storing of the first error // only should be enough. return; } error_message_ = FormatPrintfTemplate( "Failed to extract the dictionary value with key \"%s\": %s", key.c_str(), extraction_error_message.c_str()); failed_ = true; } } // namespace google_smart_card
30.181507
80
0.666969
add80978f49c3218f7ec8dd60422cf62bb0cd10f
51,310
cpp
C++
source/TrickHLA/Interaction.cpp
jiajlin/TrickHLA
ae704b97049579e997593ae6d8dd016010b8fa1e
[ "NASA-1.3" ]
null
null
null
source/TrickHLA/Interaction.cpp
jiajlin/TrickHLA
ae704b97049579e997593ae6d8dd016010b8fa1e
[ "NASA-1.3" ]
null
null
null
source/TrickHLA/Interaction.cpp
jiajlin/TrickHLA
ae704b97049579e997593ae6d8dd016010b8fa1e
[ "NASA-1.3" ]
null
null
null
/*! @file TrickHLA/Interaction.cpp @ingroup TrickHLA @brief This class represents an HLA Interaction that is managed by Trick. @copyright Copyright 2019 United States Government as represented by the Administrator of the National Aeronautics and Space Administration. No copyright is claimed in the United States under Title 17, U.S. Code. All Other Rights Reserved. \par<b>Responsible Organization</b> Simulation and Graphics Branch, Mail Code ER7\n Software, Robotics & Simulation Division\n NASA, Johnson Space Center\n 2101 NASA Parkway, Houston, TX 77058 @tldh @trick_link_dependency{DebugHandler.cpp} @trick_link_dependency{Federate.cpp} @trick_link_dependency{Int64Interval.cpp} @trick_link_dependency{Int64Time.cpp} @trick_link_dependency{Interaction.cpp} @trick_link_dependency{InteractionHandler.cpp} @trick_link_dependency{InteractionItem.cpp} @trick_link_dependency{Manager.cpp} @trick_link_dependency{MutexLock.cpp} @trick_link_dependency{MutexProtection.cpp} @trick_link_dependency{Parameter.cpp} @trick_link_dependency{ParameterItem.cpp} @trick_link_dependency{Types.cpp} @revs_title @revs_begin @rev_entry{Dan Dexter, L3 Titan Group, DSES, Aug 2006, --, Initial implementation.} @rev_entry{Dan Dexter, NASA ER7, TrickHLA, March 2019, --, Version 2 origin.} @rev_entry{Edwin Z. Crues, NASA ER7, TrickHLA, March 2019, --, Version 3 rewrite.} @revs_end */ // System include files. #include <cstdlib> #include <iostream> #include <sstream> // Trick include files. #include "trick/exec_proto.h" #include "trick/message_proto.h" // TrickHLA include files. #include "TrickHLA/Constants.hh" #include "TrickHLA/DebugHandler.hh" #include "TrickHLA/Federate.hh" #include "TrickHLA/Int64Interval.hh" #include "TrickHLA/Int64Time.hh" #include "TrickHLA/Interaction.hh" #include "TrickHLA/InteractionHandler.hh" #include "TrickHLA/InteractionItem.hh" #include "TrickHLA/Manager.hh" #include "TrickHLA/MutexLock.hh" #include "TrickHLA/MutexProtection.hh" #include "TrickHLA/Parameter.hh" #include "TrickHLA/ParameterItem.hh" #include "TrickHLA/StringUtilities.hh" #include "TrickHLA/Types.hh" // C++11 deprecated dynamic exception specifications for a function so we need // to silence the warnings coming from the IEEE 1516 declared functions. // This should work for both GCC and Clang. #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdeprecated" // HLA include files. #include RTI1516_HEADER #pragma GCC diagnostic pop using namespace std; using namespace RTI1516_NAMESPACE; using namespace TrickHLA; /*! * @job_class{initialization} */ Interaction::Interaction() : FOM_name( NULL ), publish( false ), subscribe( false ), preferred_order( TRANSPORT_SPECIFIED_IN_FOM ), param_count( 0 ), parameters( NULL ), handler( NULL ), mutex(), changed( false ), received_as_TSO( false ), time( 0.0 ), manager( NULL ), user_supplied_tag_size( 0 ), user_supplied_tag_capacity( 0 ), user_supplied_tag( NULL ) { return; } /*! * @job_class{shutdown} */ Interaction::~Interaction() { // Remove this interaction from the federation execution. remove(); if ( user_supplied_tag != NULL ) { if ( TMM_is_alloced( (char *)user_supplied_tag ) ) { TMM_delete_var_a( user_supplied_tag ); } user_supplied_tag = NULL; user_supplied_tag_size = 0; } // Make sure we destroy the mutex. (void)mutex.unlock(); } /*! * @job_class{initialization} */ void Interaction::initialize( Manager *trickhla_mgr ) { TRICKHLA_VALIDATE_FPU_CONTROL_WORD; if ( trickhla_mgr == NULL ) { send_hs( stderr, "Interaction::initialize():%d Unexpected NULL Trick-HLA-Manager!%c", __LINE__, THLA_NEWLINE ); exec_terminate( __FILE__, "Interaction::initialize() Unexpected NULL Trick-HLA-Manager!" ); return; } this->manager = trickhla_mgr; // Make sure we have a valid object FOM name. if ( ( FOM_name == NULL ) || ( *FOM_name == '\0' ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " Missing Interaction FOM Name." << " Please check your input or modified-data files to make sure the" << " Interaction FOM name is correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // TODO: Get the preferred order by parsing the FOM. // // Do a quick bounds check on the 'preferred_order' value. if ( ( preferred_order < TRANSPORT_FIRST_VALUE ) || ( preferred_order > TRANSPORT_LAST_VALUE ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " For Interaction '" << FOM_name << "', the 'preferred_order' is not valid and must be one" << " of TRANSPORT_SPECIFIED_IN_FOM, TRANSPORT_TIMESTAMP_ORDER or" << " TRANSPORT_RECEIVE_ORDER. Please check your input or modified-data" << " files to make sure the 'preferred_order' is correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // If we have an parameter count but no parameters then let the user know. if ( ( param_count > 0 ) && ( parameters == NULL ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " For Interaction '" << FOM_name << "', the 'param_count' is " << param_count << " but no 'parameters' are specified. Please check your input or" << " modified-data files to make sure the Interaction Parameters are" << " correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // If we have parameters but the parameter-count is invalid then let // the user know. if ( ( param_count <= 0 ) && ( parameters != NULL ) ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " For Interaction '" << FOM_name << "', the 'param_count' is " << param_count << " but 'parameters' have been specified. Please check your input" << " or modified-data files to make sure the Interaction Parameters" << " are correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Reset the TrickHLA Parameters count if it is negative or if there // are no attributes. if ( ( param_count < 0 ) || ( parameters == NULL ) ) { param_count = 0; } // We must have an interaction handler specified, otherwise we can not // process the interaction. if ( handler == NULL ) { ostringstream errmsg; errmsg << "Interaction::initialize():" << __LINE__ << " An Interaction-Handler for" << " 'handler' was not specified for the '" << FOM_name << "'" << " interaction. Please check your input or modified-data files to" << " make sure an Interaction-Handler is correctly specified." << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Initialize the Interaction-Handler. handler->initialize_callback( this ); TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } void Interaction::set_user_supplied_tag( unsigned char *tag, size_t tag_size ) { if ( tag_size > user_supplied_tag_capacity ) { user_supplied_tag_capacity = tag_size; if ( user_supplied_tag == NULL ) { user_supplied_tag = (unsigned char *)TMM_declare_var_1d( "char", (int)user_supplied_tag_capacity ); } else { user_supplied_tag = (unsigned char *)TMM_resize_array_1d_a( user_supplied_tag, (int)user_supplied_tag_capacity ); } } user_supplied_tag_size = tag_size; if ( tag != NULL ) { memcpy( user_supplied_tag, tag, user_supplied_tag_size ); } else { memset( user_supplied_tag, 0, user_supplied_tag_size ); } } /*! * @details Called from the virtual destructor. * @job_class{shutdown} */ void Interaction::remove() // RETURN: -- None. { // Only remove the Interaction if the manager has not been shutdown. if ( is_shutdown_called() ) { // Get the RTI-Ambassador and check for NULL. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb != NULL ) { if ( is_publish() ) { // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Un-publish the Interaction. try { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::remove():%d Unpublish Interaction '%s'.%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } rti_amb->unpublishInteractionClass( get_class_handle() ); } catch ( RTI1516_EXCEPTION &e ) { string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); send_hs( stderr, "Interaction::remove():%d Unpublish Interaction '%s' exception '%s'%c", __LINE__, get_FOM_name(), rti_err_msg.c_str(), THLA_NEWLINE ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } // Un-subscribe from the Interaction unsubscribe_from_interaction(); } } } void Interaction::setup_preferred_order_with_RTI() { // Just return if the user wants to use the default preferred order // specified in the FOM. Return if the interaction is not published since // we can only change the preferred order for publish interactions. if ( ( preferred_order == TRANSPORT_SPECIFIED_IN_FOM ) || !is_publish() ) { return; } RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::setup_preferred_order_with_RTI():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::setup_preferred_order_with_RTI():%d \ Published Interaction '%s' Preferred-Order:%s%c", __LINE__, get_FOM_name(), ( preferred_order == TRANSPORT_TIMESTAMP_ORDER ? "TIMESTAMP" : "RECEIVE" ), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Change the preferred order. try { switch ( preferred_order ) { case TRANSPORT_RECEIVE_ORDER: { rti_amb->changeInteractionOrderType( this->class_handle, RTI1516_NAMESPACE::RECEIVE ); break; } case TRANSPORT_TIMESTAMP_ORDER: default: { rti_amb->changeInteractionOrderType( this->class_handle, RTI1516_NAMESPACE::TIMESTAMP ); break; } } } catch ( RTI1516_NAMESPACE::InteractionClassNotPublished &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: InteractionClassNotPublished for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::setup_preferred_order_with_RTI():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } void Interaction::publish_interaction() { // The RTI must be ready and the flag must be set to publish. if ( !is_publish() ) { return; } RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::publish_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::publish_interaction():%d Interaction '%s'.%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Publish the Interaction try { rti_amb->publishInteractionClass( this->class_handle ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::publish_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } void Interaction::unpublish_interaction() { RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::unpublish_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } // Subscribe to the interaction. if ( is_publish() ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::unpublish_interaction():%d Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; try { rti_amb->unpublishInteractionClass( this->class_handle ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::unpublish_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } } void Interaction::subscribe_to_interaction() { // Get the RTI-Ambassador. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::subscribe_to_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } // Subscribe to the interaction. if ( is_subscribe() ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::subscribe_to_interaction():%d Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; try { rti_amb->subscribeInteractionClass( this->class_handle, true ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateServiceInvocationsAreBeingReportedViaMOM &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: FederateServiceInvocationsAreBeingReportedViaMOM for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::subscribe_to_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } } void Interaction::unsubscribe_from_interaction() { // Get the RTI-Ambassador. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::unsubscribe_from_interaction():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return; } // Make sure we only unsubscribe an interaction that was subscribed to. if ( is_subscribe() ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::unsubscribe_from_interaction():%d Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; try { rti_amb->unsubscribeInteractionClass( this->class_handle ); } catch ( RTI1516_NAMESPACE::InteractionClassNotDefined &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: InteractionClassNotDefined for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::FederateNotExecutionMember &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: FederateNotExecutionMember for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::SaveInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: SaveInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RestoreInProgress &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: RestoreInProgress for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::NotConnected &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: NotConnected for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_NAMESPACE::RTIinternalError &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " EXCEPTION: RTIinternalError for Interaction '" << get_FOM_name() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::unsubscribe_from_interaction():" << __LINE__ << " RTI1516_EXCEPTION for Interaction '" << get_FOM_name() << "' with error '" << rti_err_msg << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); exec_terminate( __FILE__, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; } } bool Interaction::send( RTI1516_USERDATA const &the_user_supplied_tag ) { // RTI must be ready and the flag must be set to publish. if ( !is_publish() ) { return ( false ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; // Get the Trick-Federate. Federate *trick_fed = get_federate(); // Get the RTI-Ambassador. RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::send():%d As Receive-Order: Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return ( false ); } ParameterHandleValueMap param_values_map; // For thread safety, lock here to avoid corrupting the parameters and use // braces to create scope for the mutex-protection to auto unlock the mutex. { // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Add all the parameter values to the map. for ( int i = 0; i < param_count; i++ ) { param_values_map[parameters[i].get_parameter_handle()] = parameters[i].get_encoded_parameter_value(); } // Release mutex lock as auto_unlock_mutex goes out of scope } if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d As Receive-Order: Interaction '%s'%c", __LINE__, get_FOM_name(), THLA_NEWLINE ); } bool successfuly_sent = false; try { // RECEIVE_ORDER with no timestamp. // Do not send any interactions if federate save / restore has begun (see // IEEE-1516.1-2000 sections 4.12, 4.20) if ( trick_fed->should_publish_data() ) { // This call returns an event retraction handle but we // don't support event retraction so no need to store it. (void)rti_amb->sendInteraction( this->class_handle, param_values_map, the_user_supplied_tag ); successfuly_sent = true; } } catch ( RTI1516_EXCEPTION &e ) { string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); send_hs( stderr, "Interaction::send():%d As Receive-Order: Interaction '%s' with exception '%s'%c", __LINE__, get_FOM_name(), rti_err_msg.c_str(), THLA_NEWLINE ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; // Free the memory used in the parameter values map. param_values_map.clear(); return ( successfuly_sent ); } bool Interaction::send( double send_HLA_time, RTI1516_USERDATA const &the_user_supplied_tag ) { // RTI must be ready and the flag must be set to publish. if ( !is_publish() ) { return ( false ); } // Macro to save the FPU Control Word register value. TRICKHLA_SAVE_FPU_CONTROL_WORD; RTIambassador *rti_amb = get_RTI_ambassador(); if ( rti_amb == NULL ) { send_hs( stderr, "Interaction::send():%d Unexpected NULL RTIambassador.%c", __LINE__, THLA_NEWLINE ); return ( false ); } ParameterHandleValueMap param_values_map; // For thread safety, lock here to avoid corrupting the parameters and use // braces to create scope for the mutex-protection to auto unlock the mutex. { // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Add all the parameter values to the map. for ( int i = 0; i < param_count; i++ ) { if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d Adding '%s' to parameter map.%c", __LINE__, parameters[i].get_FOM_name(), THLA_NEWLINE ); } param_values_map[parameters[i].get_parameter_handle()] = parameters[i].get_encoded_parameter_value(); } // auto_unlock_mutex unlocks the mutex here as it goes out of scope. } // Update the timestamp. time.set( send_HLA_time ); // Get the Trick-Federate. Federate *trick_fed = get_federate(); // Determine if the interaction should be sent with a timestamp. // See IEEE 1516.1-2010 Section 6.12. bool send_with_timestamp = trick_fed->in_time_regulating_state() && ( preferred_order != TRANSPORT_RECEIVE_ORDER ); bool successfuly_sent = false; try { // Do not send any interactions if federate save or restore has begun (see // IEEE-1516.1-2000 sections 4.12, 4.20) if ( trick_fed->should_publish_data() ) { // The message will only be sent as TSO if our Federate is in the HLA Time // Regulating state and the interaction prefers timestamp order. // See IEEE-1516.1-2000, Sections 6.6 and 8.1.1. if ( send_with_timestamp ) { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d As Timestamp-Order: Interaction '%s' sent for time %lf seconds.%c", __LINE__, get_FOM_name(), time.get_time_in_seconds(), THLA_NEWLINE ); } // This call returns an event retraction handle but we // don't support event retraction so no need to store it. // Send in Timestamp Order. (void)rti_amb->sendInteraction( this->class_handle, param_values_map, the_user_supplied_tag, time.get() ); successfuly_sent = true; } else { if ( DebugHandler::show( DEBUG_LEVEL_2_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::send():%d As Receive-Order: \ Interaction '%s' is time-regulating:%s, preferred-order:%s.%c", __LINE__, get_FOM_name(), ( trick_fed->in_time_regulating_state() ? "Yes" : "No" ), ( ( preferred_order == TRANSPORT_RECEIVE_ORDER ) ? "receive" : "timestamp" ), THLA_NEWLINE ); } // Send in Receive Order (i.e. with no timestamp). (void)rti_amb->sendInteraction( this->class_handle, param_values_map, the_user_supplied_tag ); successfuly_sent = true; } } } catch ( RTI1516_NAMESPACE::InvalidLogicalTime &e ) { // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::send():" << __LINE__ << " As " << ( send_with_timestamp ? "Timestamp Order" : "Receive Order" ) << ", InvalidLogicalTime exception for " << get_FOM_name() << " time=" << time.get_time_in_seconds() << " (" << time.get_time_in_micros() << " microseconds)" << " error message:'" << rti_err_msg.c_str() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); } catch ( RTI1516_EXCEPTION &e ) { string rti_err_msg; StringUtilities::to_string( rti_err_msg, e.what() ); ostringstream errmsg; errmsg << "Interaction::send():" << __LINE__ << " As " << ( send_with_timestamp ? "Timestamp Order" : "Receive Order" ) << ", Interaction '" << get_FOM_name() << "' with exception '" << rti_err_msg.c_str() << "'" << THLA_ENDL; send_hs( stderr, (char *)errmsg.str().c_str() ); } // Macro to restore the saved FPU Control Word register value. TRICKHLA_RESTORE_FPU_CONTROL_WORD; TRICKHLA_VALIDATE_FPU_CONTROL_WORD; // Free the memory used in the parameter values map. param_values_map.clear(); return ( successfuly_sent ); } void Interaction::process_interaction() { // The Interaction data must have changed and the RTI must be ready. if ( !is_changed() ) { return; } // For thread safety, lock here to avoid corrupting the parameters and use // braces to create scope for the mutex-protection to auto unlock the mutex. { // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Check the change flag again now that we have the lock on the mutex. if ( !is_changed() ) { // cppcheck-suppress [identicalConditionAfterEarlyExit] return; } if ( DebugHandler::show( DEBUG_LEVEL_5_TRACE, DEBUG_SOURCE_INTERACTION ) ) { string handle_str; StringUtilities::to_string( handle_str, class_handle ); if ( received_as_TSO ) { send_hs( stdout, "Interaction::process_interaction():%d ID:%s, FOM_name:'%s', HLA time:%G, Timestamp-Order%c", __LINE__, handle_str.c_str(), get_FOM_name(), time.get_time_in_seconds(), THLA_NEWLINE ); } else { send_hs( stdout, "Interaction::process_interaction():%d ID:%s, FOM_name:'%s', Receive-Order%c", __LINE__, handle_str.c_str(), get_FOM_name(), THLA_NEWLINE ); } } // Unpack all the parameter data. for ( int i = 0; i < param_count; i++ ) { parameters[i].unpack_parameter_buffer(); } mark_unchanged(); // Unlock the mutex as the auto_unlock_mutex goes out of scope. } // Call the users interaction handler (callback) so that they can // continue processing the interaction. if ( handler != NULL ) { if ( user_supplied_tag_size > 0 ) { handler->receive_interaction( RTI1516_USERDATA( user_supplied_tag, user_supplied_tag_size ) ); } else { handler->receive_interaction( RTI1516_USERDATA( 0, 0 ) ); } } } void Interaction::extract_data( InteractionItem *interaction_item ) { // Must be set to subscribe to the interaction and the interaction item // is not null, otherwise just return. if ( !is_subscribe() || ( interaction_item == NULL ) ) { return; } if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) { string handle_str; StringUtilities::to_string( handle_str, class_handle ); send_hs( stdout, "Interaction::extract_data():%d ID:%s, FOM_name:'%s'%c", __LINE__, handle_str.c_str(), get_FOM_name(), THLA_NEWLINE ); } if ( interaction_item->is_timestamp_order() ) { // Update the timestamp. time.set( interaction_item->time ); // Received in Timestamp Order (TSO). received_as_TSO = true; } else { // Receive Order (RO), not Timestamp Order (TSO). received_as_TSO = false; } // For thread safety, lock here to avoid corrupting the parameters. // When auto_unlock_mutex goes out of scope it automatically unlocks the // mutex even if there is an exception. MutexProtection auto_unlock_mutex( &mutex ); // Extract the user supplied tag. if ( interaction_item->user_supplied_tag_size > 0 ) { set_user_supplied_tag( interaction_item->user_supplied_tag, interaction_item->user_supplied_tag_size ); mark_changed(); } else { set_user_supplied_tag( (unsigned char *)NULL, 0 ); } // Process all the parameter-items in the queue. while ( !interaction_item->parameter_queue.empty() ) { ParameterItem *param_item = static_cast< ParameterItem * >( interaction_item->parameter_queue.front() ); // Determine if we have a valid parameter-item. if ( ( param_item != NULL ) && ( param_item->index >= 0 ) && ( param_item->index < param_count ) ) { if ( DebugHandler::show( DEBUG_LEVEL_7_TRACE, DEBUG_SOURCE_INTERACTION ) ) { send_hs( stdout, "Interaction::extract_data():%d Decoding '%s' from parameter map.%c", __LINE__, parameters[param_item->index].get_FOM_name(), THLA_NEWLINE ); } // Extract the parameter data for the given parameter-item. parameters[param_item->index].extract_data( param_item->size, param_item->data ); // Mark the interaction as changed. mark_changed(); } // Now that we extracted the data from the parameter-item remove it // from the queue. interaction_item->parameter_queue.pop(); } // Unlock the mutex as auto_unlock_mutex goes out of scope. } void Interaction::mark_unchanged() { this->changed = false; // Clear the change flag for each of the attributes as well. for ( int i = 0; i < param_count; i++ ) { parameters[i].mark_unchanged(); } } /*! * @details If the manager does not exist, -1.0 seconds is assigned to the returned object. */ Int64Interval Interaction::get_fed_lookahead() const { Int64Interval i; if ( manager != NULL ) { i = manager->get_fed_lookahead(); } else { i = Int64Interval( -1.0 ); } return i; } /*! * @details If the manager does not exist, MAX_LOGICAL_TIME_SECONDS is assigned * to the returned object. */ Int64Time Interaction::get_granted_fed_time() const { Int64Time t; if ( manager != NULL ) { t = manager->get_granted_fed_time(); } else { t = Int64Time( MAX_LOGICAL_TIME_SECONDS ); } return t; } Federate *Interaction::get_federate() { return ( ( this->manager != NULL ) ? this->manager->get_federate() : NULL ); } RTIambassador *Interaction::get_RTI_ambassador() { return ( ( this->manager != NULL ) ? this->manager->get_RTI_ambassador() : static_cast< RTI1516_NAMESPACE::RTIambassador * >( NULL ) ); } bool Interaction::is_shutdown_called() const { return ( ( this->manager != NULL ) ? this->manager->is_shutdown_called() : false ); }
40.982428
123
0.638823
adda4a644ee7c2c8bbc263e13622a455a0d36f54
111
cpp
C++
dll/common/Engine/Math/Ray3D.cpp
kbinani/dxrip
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
[ "MIT" ]
4
2015-09-23T14:12:07.000Z
2021-10-04T21:03:32.000Z
dll/common/Engine/Math/Ray3D.cpp
kbinani/dxrip
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
[ "MIT" ]
null
null
null
dll/common/Engine/Math/Ray3D.cpp
kbinani/dxrip
ef170fd895c6d9bb6c05bc2026e9fa9bcd0b1908
[ "MIT" ]
2
2018-06-26T14:59:11.000Z
2021-09-01T01:50:20.000Z
/* Ray3D.cpp Written by Matthew Fisher a 3D ray represented by an origin point and a direction vector. */
18.5
64
0.72973
addab0877a5b8d2d066a2c5e438bfad57730c3d1
1,126
cpp
C++
examples/hello_world.cpp
jaredjxyz/borrowing
5ba3ec34f5fc4b56830b64087d5a00d04c9943c1
[ "MIT" ]
1
2020-09-18T20:21:26.000Z
2020-09-18T20:21:26.000Z
examples/hello_world.cpp
jaredjxyz/borrowing
5ba3ec34f5fc4b56830b64087d5a00d04c9943c1
[ "MIT" ]
null
null
null
examples/hello_world.cpp
jaredjxyz/borrowing
5ba3ec34f5fc4b56830b64087d5a00d04c9943c1
[ "MIT" ]
null
null
null
#include "borrowing/borrowing.h" #include <chrono> #include <iostream> #include <thread> int main() { using borrowing::Borrowable; using borrowing::Borrowed; // Turn the string into "Hello World" const std::string goal = "Hello world"; Borrowable<std::string> str_owner("Hi"); auto change_string = [&](const std::string& s){ auto init_time = std::chrono::steady_clock::now(); while (std::chrono::steady_clock::now() - init_time < std::chrono::seconds(1)) { Borrowed<std::string> str = str_owner.borrow(); *str = s; } str_owner.borrow()->clear(); }; auto print_string = [&](){ do { std::cout << *str_owner.cborrow() << std::endl; } while (!str_owner.cborrow()->empty()); }; // Should print "Hi", "Hello World", or "Hi mom", but not a jumbled mess // of characters that would happen in a non thread-safe environment std::thread t3(print_string); std::thread t2(change_string, "Hello World!"); std::thread t1(change_string, "Hi mom!"); t3.join(); t2.join(); t1.join(); // str_owner.try_borrow(); // Works in C++17 and higher return 0; }
23.957447
84
0.633215
addb6f1d810461d20306b4f65fed774fec2478a9
4,541
cpp
C++
src/qquicknativeview_android.cpp
KonstantinRitt/qquicknativeview
2b87d5f46bd435871167eeb6d5ed05a37c5da838
[ "MIT" ]
null
null
null
src/qquicknativeview_android.cpp
KonstantinRitt/qquicknativeview
2b87d5f46bd435871167eeb6d5ed05a37c5da838
[ "MIT" ]
null
null
null
src/qquicknativeview_android.cpp
KonstantinRitt/qquicknativeview
2b87d5f46bd435871167eeb6d5ed05a37c5da838
[ "MIT" ]
null
null
null
#include "qquicknativeview_p.h" #include <QtCore/qbasicatomic.h> #include <QtGui/private/qhighdpiscaling_p.h> #include <QtAndroidExtras/qandroidfunctions.h> #include <QtAndroidExtras/qandroidjnienvironment.h> #include <QtAndroidExtras/qandroidjniobject.h> QT_BEGIN_NAMESPACE static QBasicAtomicInteger<uint> s_id = Q_BASIC_ATOMIC_INITIALIZER(10000); void QQuickNativeViewPrivate::create() { Q_Q(QQuickNativeView); QtAndroid::runOnAndroidThreadSync([this]() { handle = q_func()->createNativeView(); Q_ASSERT(handle != 0); QAndroidJniObject *view = reinterpret_cast<QAndroidJniObject *>(handle); Q_ASSERT(view != nullptr && view->isValid()); nativeViewId = s_id.fetchAndAddOrdered(1); Q_ASSERT(nativeViewId != 0); QAndroidJniObject::callStaticMethod<void>("org/qtproject/qt5/android/QtNative", "insertNativeView", "(ILandroid/view/View;IIII)V", jint(nativeViewId), view->object(), 0, 0, 0, 0); }); q->afterNativeViewCreated(); } void QQuickNativeViewPrivate::destroy() { Q_Q(QQuickNativeView); q->beforeNativeViewDestroyed(); QtAndroid::runOnAndroidThreadSync([this]() { Q_ASSERT(nativeViewId != 0); // if it was the last view, it won't be released until replaced with another view // see QtNative.destroySurface for details QAndroidJniObject::callStaticMethod<void>("org/qtproject/qt5/android/QtNative", "destroySurface", "(I)V", jint(nativeViewId)); nativeViewId = 0; q_func()->destroyNativeView(handle); handle = 0; }); } void QQuickNativeViewPrivate::updateGeometry(const QRectF &geometry) { Q_Q(QQuickNativeView); if (Q_UNLIKELY(q->window() == nullptr)) return; const QRect screenRect = QHighDpi::toNativePixels(geometry, q->window()).toRect(); int viewId = nativeViewId; Q_ASSERT(viewId != 0); QtAndroid::runOnAndroidThread([viewId, screenRect]() { QAndroidJniObject::callStaticMethod<void>("org/qtproject/qt5/android/QtNative", "setSurfaceGeometry", "(IIIII)V", jint(viewId), jint(screenRect.x()), jint(screenRect.y()), jint(screenRect.width()), jint(screenRect.height())); }); } void QQuickNativeViewPrivate::updateRotation(qreal angle) { const QAndroidJniObject view = *reinterpret_cast<QAndroidJniObject *>(handle); Q_ASSERT(view.isValid()); QtAndroid::runOnAndroidThread([view, angle]() { view.callMethod<void>("setRotation", "(F)V", jfloat(angle)); }); } void QQuickNativeViewPrivate::updateVisibility(bool visible) { const QAndroidJniObject view = *reinterpret_cast<QAndroidJniObject *>(handle); Q_ASSERT(view.isValid()); QtAndroid::runOnAndroidThread([view, visible]() { QAndroidJniObject::callStaticMethod<void>("org/qtproject/qt5/android/QtNative", "setViewVisibility", "(Landroid/view/View;Z)V", view.object(), jboolean(visible)); }); } void QQuickNativeViewPrivate::updateOpacity(qreal opacity) { const QAndroidJniObject view = *reinterpret_cast<QAndroidJniObject *>(handle); Q_ASSERT(view.isValid()); QtAndroid::runOnAndroidThread([view, opacity]() { view.callMethod<void>("setAlpha", "(F)V", jfloat(opacity)); }); } void QQuickNativeViewPrivate::updateEnabled(bool enabled) { const QAndroidJniObject view = *reinterpret_cast<QAndroidJniObject *>(handle); Q_ASSERT(view.isValid()); QtAndroid::runOnAndroidThread([view, enabled]() { view.callMethod<void>("setEnabled", "(Z)V", jboolean(enabled)); }); } QT_END_NAMESPACE
33.88806
100
0.550099
addc2b8b55dc4dcf0b78935062600f696c73c88e
10,750
cpp
C++
Src/GUI/FrTabControl.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
Src/GUI/FrTabControl.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
Src/GUI/FrTabControl.cpp
VladGordienko28/FluorineEngine-I
31114c41884d41ec60d04dba7965bc83be47d229
[ "MIT" ]
null
null
null
/*============================================================================= FrTabControl.cpp: Tab control widget. Copyright Jul.2016 Vlad Gordienko. =============================================================================*/ #include "GUI.h" /*----------------------------------------------------------------------------- WTabPage implementation. -----------------------------------------------------------------------------*/ // Whether fade tab, if it not in focus. #define FADE_TAB 0 // // Tab page constructor. // WTabPage::WTabPage( WContainer* InOwner, WWindow* InRoot ) : WContainer( InOwner, InRoot ), Color( COLOR_SteelBlue ), TabWidth( 70 ), TabControl( nullptr ) { Align = AL_Client; Padding = TArea( 0, 0, 0, 0 ); } // // Tab page repaint. // void WTabPage::OnPaint( CGUIRenderBase* Render ) { WContainer::OnPaint( Render ); #if 0 // Debug draw. Render->DrawRegion ( ClientToWindow( TPoint( 0, 0 ) ), Size, Color * COLOR_CornflowerBlue, Color * COLOR_CornflowerBlue, BPAT_Diagonal ); #endif } // // Close the tab page. // void WTabPage::Close( Bool bForce ) { assert(TabControl != nullptr); TabControl->CloseTabPage( TabControl->Pages.FindItem(this), bForce ); } /*----------------------------------------------------------------------------- WTabControl implementation. -----------------------------------------------------------------------------*/ // // Tabs control constructor. // WTabControl::WTabControl( WContainer* InOwner, WWindow* InRoot ) : WContainer( InOwner, InRoot ), Pages(), iActive( -1 ), iHighlight( -1 ), iCross( -1 ), DragPage( nullptr ), bWasDrag( false ), bOverflow( false ) { // Grab some place for header. Padding = TArea( 21, 0, 0, 0 ); Align = AL_Client; // Overflow popup menu. Popup = new WPopupMenu( this, InRoot ); } // // Draw a tab control. // void WTabControl::OnPaint( CGUIRenderBase* Render ) { // Call parent. WContainer::OnPaint( Render ); // Precompute. TPoint Base = ClientToWindow(TPoint::Zero); Integer TextY = Base.Y + (19-Root->Font1->Height) / 2; Integer XWalk = Base.X; // Draw a master bar. Render->DrawRegion ( Base, TSize( Size.Width, 20 ), GUI_COLOR_PANEL, /*GUI_COLOR_PANEL_BORDER*/GUI_COLOR_PANEL, BPAT_Solid ); // Draw headers. TColor ActiveColor; Integer iPage; for( iPage=0; iPage<Pages.Num(); iPage++ ) { WTabPage* Page = Pages[iPage]; // Test, maybe list overflow. if( XWalk+Page->TabWidth >= Base.X+Size.Width-15 ) break; // Special highlight required? if( iPage == iActive || iPage == iHighlight ) { TColor DrawColor = iPage == iActive ? Page->Color : TColor( 0x1d, 0x1d, 0x1d, 0xff ) + Page->Color; TColor DarkColor = DrawColor * TColor( 0xdd, 0xdd, 0xdd, 0xff ); // Fade color, if not in focus. if( iPage == iActive ) { #if FADE_TAB if( !IsChildFocused() ) DrawColor = TColor( 0x50, 0x50, 0x50, 0xff )+DrawColor*0.35f; #endif ActiveColor = DrawColor; } Render->DrawRegion ( TPoint( XWalk, Base.Y ), TSize( Page->TabWidth, 19 ), DrawColor, DrawColor, BPAT_Solid ); // Highlight selected cross. if( iCross == iPage ) Render->DrawRegion ( TPoint( XWalk+Page->TabWidth - 21, Base.Y + 3 ), TSize( 13, 13 ), DarkColor, DarkColor, BPAT_Solid ); // Draw cross. Render->DrawPicture ( TPoint( XWalk+Page->TabWidth - 20, Base.Y + 4 ), TSize( 11, 11 ), TPoint( 0, 11 ), TSize( 11, 11 ), Root->Icons ); } // Draw tab title. Render->DrawText ( TPoint( XWalk + 5, TextY ), Page->Caption, GUI_COLOR_TEXT, //COLOR_White, Root->Font1 ); // To next. XWalk+= Page->TabWidth; } // Draw a little marker if list overflow. if( bOverflow = iPage < Pages.Num() ) { TPoint Cursor = Root->MousePos; TPoint Start = TPoint( Base.X+Size.Width-14, Base.Y+3 ); if( Cursor.X>=Start.X && Cursor.Y>=Start.Y && Cursor.X<=Start.X+14 && Cursor.Y<=Start.Y+14 ) Render->DrawRegion ( Start, TSize( 14, 14 ), GUI_COLOR_BUTTON_HIGHLIGHT, GUI_COLOR_BUTTON_HIGHLIGHT, BPAT_Solid ); Render->DrawPicture ( TPoint( Base.X+Size.Width-10, Base.Y+9 ), TSize( 7, 4 ), TPoint( 0, 32 ), TSize( 7, 4 ), Root->Icons ); } // Draw a tiny color bar according to active page. if( iActive != -1 ) { WTabPage* Active = Pages[iActive]; Render->DrawRegion ( TPoint( Base.X, Base.Y + 19 ), TSize( Size.Width, 2 ), ActiveColor, ActiveColor, BPAT_Solid ); } } // // Return the active page, if // no page active return nullptr. // WTabPage* WTabControl::GetActivePage() { return iActive!=-1 && iActive<Pages.Num() ? Pages[iActive] : nullptr; } // // Add a new tab and activate it. // Integer WTabControl::AddTabPage( WTabPage* Page ) { Integer iNew = Pages.Push(Page); Page->TabControl = this; ActivateTabPage( iNew ); return iNew; } // // Close tab by its index. // void WTabControl::CloseTabPage( Integer iPage, Bool bForce ) { assert(iPage>=0 && iPage<Pages.Num()); WTabPage* P = Pages[iPage]; // Is tab prepared for DIE? if( bForce || P->OnQueryClose() ) { Pages.RemoveShift(iPage); if( Pages.Num() ) { // Open new item or just close. if( iActive == iPage ) { // Open new one. ActivateTabPage( Pages.Num()-1 ); iHighlight = -1; } else { // Save selection. iActive = iActive > iPage ? iActive-1 : iActive; } } else { // Nothing to open, all tabs are closed. iHighlight = iActive = -1; } // Destroy widget. delete P; } } // // Mouse click on tabs bar. // void WTabControl::OnMouseUp( EMouseButton Button, Integer X, Integer Y ) { WContainer::OnMouseUp( Button, X, Y ); iCross = XYToCross( X, Y ); // Close tab if cross pressed. if( !bWasDrag && Button == MB_Left && iCross != -1 ) { CloseTabPage(iCross); } // Close tab via middle button. if( Button == MB_Middle ) { Integer iPage = XToIndex(X); if( iPage != -1 ) CloseTabPage(iPage); } // No more drag. DragPage = nullptr; bWasDrag = false; } // // When mouse hover tabs bar. // void WTabControl::OnMouseMove( EMouseButton Button, Integer X, Integer Y ) { WContainer::OnMouseMove( Button, X, Y ); if( !DragPage ) { // No drag, just highlight. iHighlight = XToIndex( X ); iCross = XYToCross( X, Y ); } else { // Process tab drag. Integer XWalk = 0; for( Integer i=0; i<Pages.Num(); i++ ) if( Pages[i] != DragPage ) XWalk += Pages[i]->TabWidth; else break; while( X < XWalk ) { Integer iDrag = Pages.FindItem( DragPage ); if( iDrag <= 0 ) break; XWalk -= Pages[iDrag-1]->TabWidth; Pages.Swap( iDrag, iDrag-1 ); } while( X > XWalk+DragPage->TabWidth ) { Integer iDrag = Pages.FindItem( DragPage ); if( iDrag >= Pages.Num()-1 ) break; XWalk += Pages[iDrag+1]->TabWidth; Pages.Swap( iDrag, iDrag+1 ); } // Refresh highlight. iActive = iHighlight = Pages.FindItem( DragPage ); bWasDrag = true; } } // // When mouse press tabs bar. // void WTabControl::OnMouseDown( EMouseButton Button, Integer X, Integer Y ) { WContainer::OnMouseDown( Button, X, Y ); // Test maybe clicked on little triangle. if( bOverflow && Button==MB_Left && X > Size.Width-14 ) { // Setup popup and show it. Popup->Items.Empty(); for( Integer i=0; i<Pages.Num(); i++ ) Popup->AddItem( Pages[i]->Caption, WIDGET_EVENT(WTabControl::PopupPageClick), true ); Popup->Show( TPoint( Size.Width, 20 ) ); return; } Integer iClicked = XToIndex(X); iCross = XYToCross( X, Y ); // Activate pressed. if( iCross == -1 && iClicked != -1 && iClicked != iActive && !DragPage && Button != MB_Middle ) { ActivateTabPage( iClicked ); } // Prepare to drag active page. bWasDrag = false; if( Button == MB_Left && iActive != -1 ) DragPage = Pages[iActive]; } // // Activate an iPage. // void WTabControl::ActivateTabPage( Integer iPage ) { assert(iPage>=0 && iPage<Pages.Num()); // Hide all. for( Integer i=0; i<Pages.Num(); i++ ) Pages[i]->bVisible = false; // Show and activate. Pages[iPage]->bVisible = true; Pages[iPage]->OnOpen(); iActive = iPage; // Realign. AlignChildren(); //Pages[iPage]->AlignChildren(); Pages[iPage]->WidgetProc( WPE_Resize, TWidProcParms() ); // Make it focused. Root->SetFocused( this ); } // // Activate an Page. // void WTabControl::ActivateTabPage( WTabPage* Page ) { Integer iPage = Pages.FindItem( Page ); assert(iPage != -1); ActivateTabPage( iPage ); } // // When mouse leave tabs. // void WTabControl::OnMouseLeave() { WContainer::OnMouseLeave(); // No highlight any more. iHighlight = -1; iCross = -1; } // // Convert mouse X to tab index, if mouse outside // any tabs return -1. // Integer WTabControl::XToIndex( Integer InX ) { Integer XWalk = 0; for( Integer i=0; i<Pages.Num(); i++ ) { WTabPage* Page = Pages[i]; if( XWalk+Page->TabWidth > Size.Width-15 ) break; if( ( InX >= XWalk ) && ( InX <= XWalk + Page->TabWidth ) ) return i; XWalk += Page->TabWidth; } return -1; } // // Figure out index of close cross on tab. // It no cross around - return -1. // Integer WTabControl::XYToCross( Integer InX, Integer InY ) { Integer XWalk = 0; for( Integer i=0; i<Pages.Num(); i++ ) { WTabPage* Page = Pages[i]; if( XWalk+Page->TabWidth > Size.Width-15 ) break; if( ( InX > XWalk+Page->TabWidth-20 ) && ( InX < XWalk+Page->TabWidth-5 ) && ( InY > 4 && InY < 15 ) ) return i; XWalk += Page->TabWidth; } return -1; } // // Page selected. // void WTabControl::PopupPageClick( WWidget* Sender ) { // Figure out chosen page. WTabPage* Chosen = nullptr; for( Integer i=0; i<Popup->Items.Num(); i++ ) if( Popup->Items[i].bChecked ) { Chosen = Pages[i]; break; } assert(Chosen); // Carousel pages, to make chosen first. while( Pages[0] != Chosen ) { WTabPage* First = Pages[0]; for( Integer i=0; i<Pages.Num()-1; i++ ) Pages[i] = Pages[i+1]; Pages[Pages.Num()-1] = First; } // Make first page active now. ActivateTabPage( 0 ); } // // Tab control has been activated. // void WTabControl::OnActivate() { WContainer::OnActivate(); // Pages switching failure :( #if 0 // Activate selected page. WTabPage* Page = GetActivePage(); if( Page ) Root->SetFocused( Page ); #endif } /*----------------------------------------------------------------------------- The End. -----------------------------------------------------------------------------*/
19.265233
102
0.574233
addceae60277af9d0efb17f388335e133ab6e685
880
cpp
C++
samples/sample37.cpp
AjayBrahmakshatriya/mirror-cpp
f19fdfbfdc3f333a5e20f88374b87a3509dd1af7
[ "MIT" ]
null
null
null
samples/sample37.cpp
AjayBrahmakshatriya/mirror-cpp
f19fdfbfdc3f333a5e20f88374b87a3509dd1af7
[ "MIT" ]
null
null
null
samples/sample37.cpp
AjayBrahmakshatriya/mirror-cpp
f19fdfbfdc3f333a5e20f88374b87a3509dd1af7
[ "MIT" ]
null
null
null
// Include the headers #include "blocks/c_code_generator.h" #include "builder/static_var.h" #include "builder/dyn_var.h" #include "blocks/extract_cuda.h" #include <iostream> // Include the BuildIt types using builder::dyn_var; using builder::static_var; static void bar(dyn_var<int*> buffer) { builder::annotate(CUDA_KERNEL); for (dyn_var<int> cta = 0; cta < 128; cta = cta + 1) { for (dyn_var<int> tid = 0; tid < 512; tid = tid + 1) { dyn_var<int> thread_id = cta * 512 + tid; buffer[thread_id] = 0; } } } int main(int argc, char* argv[]) { builder::builder_context context; auto ast = context.extract_function_ast(bar, "bar"); auto new_decls = block::extract_cuda_from(block::to<block::func_decl>(ast)->body); for (auto a: new_decls) block::c_code_generator::generate_code(a, std::cout, 0); block::c_code_generator::generate_code(ast, std::cout, 0); }
28.387097
83
0.7
adddaedc9a8c59629f3f2fd012503ac9d6c83d26
336
cpp
C++
net.ssa/Dima/bge.root/bge/bge/ui.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:19.000Z
2022-03-26T17:00:19.000Z
Dima/bge.root/bge/bge/ui.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
null
null
null
Dima/bge.root/bge/bge/ui.cpp
ixray-team/xray-vss-archive
b245c8601dcefb505b4b51f58142da6769d4dc92
[ "Linux-OpenIB" ]
1
2022-03-26T17:00:21.000Z
2022-03-26T17:00:21.000Z
//////////////////////////////////////////////////////////////////////////// // Module : ui.cpp // Created : 12.11.2004 // Modified : 12.11.2004 // Author : Dmitriy Iassenev // Description : User interface //////////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "ui.h"
30.545455
77
0.330357