blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
2
247
content_id
stringlengths
40
40
detected_licenses
listlengths
0
57
license_type
stringclasses
2 values
repo_name
stringlengths
4
111
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringlengths
4
58
visit_date
timestamp[ns]date
2015-07-25 18:16:41
2023-09-06 10:45:08
revision_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
committer_date
timestamp[ns]date
1970-01-14 14:03:36
2023-09-06 06:22:19
github_id
int64
3.89k
689M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
25 values
gha_event_created_at
timestamp[ns]date
2012-06-07 00:51:45
2023-09-14 21:58:52
gha_created_at
timestamp[ns]date
2008-03-27 23:40:48
2023-08-24 19:49:39
gha_language
stringclasses
159 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
7
10.5M
extension
stringclasses
111 values
filename
stringlengths
1
195
text
stringlengths
7
10.5M
82b6bb553e271a52c74e987cd44596be522a7feb
bdc441a0df7141991ff07cb4b938856ecf3b02b8
/task16.cpp
04c52fd6f1ba7380b9a7800f024e956fe4d733b0
[]
no_license
aaglakova/Alima
8f968d2d7040ec0dcde4523cba8ff04b4382e9ed
4197f9bd59cb7063656f1b230af20e2deada1483
refs/heads/master
2020-09-12T17:07:05.265521
2019-11-23T19:53:39
2019-11-23T19:53:39
222,488,253
0
1
null
null
null
null
UTF-8
C++
false
false
132
cpp
task16.cpp
#include<iostream> #include<cmath> using namespace std; int main(){ int a,b,c; cin>>a>>b>>c; cout<<(a*2)+(b-3)+(c*c); }
f6c48bc0e84483ceffc8f3d1a2e15da828c35663
5a7e278a539a99c6595564896910a24d59ccd5dd
/module04/ex02/Squad.cpp
d19b6b79b07d16271025cd141afe6e1a0d65670a
[ "MIT" ]
permissive
selysse/CPP-Piscine
9f51230d878b115bbcdbc1356ead4a0204fc5495
72884c60ac5007d34874b006e37dad7a04e846bb
refs/heads/main
2023-07-30T21:16:37.614213
2021-09-11T14:28:11
2021-09-11T14:28:11
405,367,386
1
0
null
null
null
null
UTF-8
C++
false
false
2,951
cpp
Squad.cpp
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* Squad.cpp :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: gselyse <gselyse@student.42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2021/03/05 12:28:33 by gselyse #+# #+# */ /* Updated: 2021/03/10 01:56:12 by gselyse ### ########.fr */ /* */ /* ************************************************************************** */ #include "Squad.hpp" #include <iostream> Squad::Squad():_army_size(0), _squad(NULL) { std::cout << "Squad created" << std::endl; } Squad::Squad(Squad const &copy) { *this = copy; } Squad &Squad::operator=(const Squad &copy) { if(this != &copy) { if (_army_size > 0) this->destroySquad(); _squad = new ISpaceMarine*[_army_size]; _army_size = copy._army_size; int i = 0; while (i < _army_size) { _squad[i] = copy.getUnit(i)->clone(); i++; } } return (*this); } Squad::~Squad() { if (_squad != NULL) destroySquad(); } void Squad::destroySquad() { if (_squad && _army_size) { int i = 0; while (i < _army_size) { delete _squad[i]; _squad[i] = NULL; i++; } delete [] _squad; _squad = NULL; _army_size = 0; } } int Squad::InSquad(ISpaceMarine *unit) const { int i = 0; while (_squad && i < _army_size) { if (_squad[i] == unit) return (1); i++; } return (0); } ISpaceMarine **Squad::squadCopy(ISpaceMarine **dst) const { int i = 0; while (i < _army_size) { dst[i] = _squad[i]; i++; } return (dst); } int Squad::push(ISpaceMarine *new_unit) { if (new_unit && !_squad) { _squad = new ISpaceMarine*[1]; _squad[0] = new_unit; _army_size++; } else if (new_unit && !this->InSquad(new_unit)) { ISpaceMarine **tmp = new ISpaceMarine*[_army_size + 1]; tmp = this->squadCopy(tmp); tmp[_army_size] = new_unit; delete [] _squad; _squad = tmp; _army_size++; } return (_army_size); } int Squad::get_armySize()const { return (_army_size); } int Squad::getCount()const { return (_army_size); } ISpaceMarine* Squad::getUnit(int i)const { if (i > _army_size || i < 0) return (NULL); return (_squad[i]); }
fdb5133778c81307f4558301e51a7d6398e5d6a7
0327ee82307542b781cf213e9b826aaf1e440e1c
/core/model/TextureLoader.cpp
d8094f3cd7b5af77526da0ae8a976e0587f76fb1
[]
no_license
hsaturn/Vrp
37cdb7d9fbc64b7a5e49572301da1c790c7255ae
d4cd1a0eec31d04c669df8cd4688ae2474d9927a
refs/heads/master
2023-06-22T21:18:12.510715
2023-06-15T00:44:50
2023-06-15T00:44:50
77,689,083
1
1
null
2019-08-17T08:08:06
2016-12-30T13:53:48
C++
UTF-8
C++
false
false
959
cpp
TextureLoader.cpp
#include <SFML/Graphics.hpp> #include "TextureLoader.hpp" #include <GL/glew.h> #include <iostream> using namespace std; bool TextureLoader::genGlTexture(std::string file) { sf::Image image; image.loadFromFile(file); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, image.getSize().x, image.getSize().y, 0, GL_RGBA, GL_UNSIGNED_BYTE, image.getPixelsPtr()); glGenerateMipmap(GL_TEXTURE_2D); //Generate mipmaps now!!! glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); return true; // TODO } bool TextureLoader::genGlCheckerBoard() { float pixels[] = { 0.0f, 0.0f, 0.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 0.0f, 0.0f, 0.0f }; glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, GL_RGB, GL_FLOAT, pixels); return true; }
468984c72383f183e8c482b22ce5ee22976d4fdc
93db926ca9a92af6f912c3285ca344a81c3163f0
/src/threadpool.h
73b67f46ebc97ea48163653f0aa00fb3b2638289
[]
no_license
sunchunqiang/udpserver
ed10c90888ccac139cce83b830ad50bd85e1973a
b5d7f4c3216b3c967e0b0f0a0043657862b18850
refs/heads/master
2021-05-09T12:06:25.662187
2018-11-27T23:15:16
2018-11-27T23:15:16
119,005,642
0
0
null
2018-11-27T23:13:16
2018-01-26T04:29:03
C++
UTF-8
C++
false
false
2,103
h
threadpool.h
/* * threadpool.h * * Created on: Jan 27, 2018 * Author: csun */ #ifndef THREADPOOL_H_ #define THREADPOOL_H_ #include <future> #include <atomic> #include <memory> #include <vector> #include "lockfreequeue.h" using namespace std; class taskwrapper { struct impl_base { virtual void call()=0; virtual ~impl_base() { } }; std::unique_ptr<impl_base> impl; template<typename Task> struct impl_type: impl_base { Task task; impl_type(Task&& task_) : task(std::move(task_)) { } void call() { task(); } }; public: template<typename F> taskwrapper(F&& f) : impl(new impl_type<F>(std::move(f))) { } void call() { impl->call(); } void operator()() { call(); } taskwrapper() = default; taskwrapper(taskwrapper&& other) : impl(std::move(other.impl)) { } taskwrapper& operator=(taskwrapper&& other) { impl = std::move(other.impl); return *this; } taskwrapper(const taskwrapper&) = delete; taskwrapper(taskwrapper&) = delete; taskwrapper& operator=(const taskwrapper&) = delete; }; class thread_pool { lockfreequeue<taskwrapper> work_queue; atomic<bool> done; std::vector<std::thread> threads; void worker_thread() { while (!done) { unique_ptr<taskwrapper> task = work_queue.pop(); if (task != nullptr) { (*task)(); } else { std::this_thread::yield(); } } } public: thread_pool() :done(false) { } ~thread_pool() { } void stop() { done = true; for(auto& th:threads) { th.join(); } } void start(unsigned int thread_count) { done = false; try { for (unsigned i = 0; i < thread_count; ++i) { threads.push_back( std::thread(&thread_pool::worker_thread, this)); } } catch (...) { done = true; throw; } } template<typename Task> std::future<typename std::result_of<Task()>::type> submit(Task& f) { typedef typename std::result_of<Task()>::type result_type; std::packaged_task<result_type()> task(std::move(f)); std::future<result_type> res(task.get_future()); work_queue.push(std::move(task)); return res; } }; #endif /* THREADPOOL_H_ */
5b3cceb18c51b213951830a6346913f7f86d1854
082cb1c8684125db213ee3d94ac74e946afffcd5
/main_p2.cpp
a54b007c70fb204e07c6bb6a787201cf41db5c4b
[]
no_license
EmiREstGon/P2-Algoritmos
96cb084c72d1bcd0b4bd5609b224e12f8bf0c39a
36b7c6bfdb92df4a98a0a759d2eefc30383e8dfa
refs/heads/main
2023-03-18T07:14:48.314834
2021-03-08T18:25:32
2021-03-08T18:25:32
344,250,096
1
0
null
null
null
null
UTF-8
C++
false
false
2,044
cpp
main_p2.cpp
// AUTOR: Emilio Rafael Estévez González // FECHA: 8/2/21 // EMAIL: alu0101389240 // VERSION: 1.0 // ASIGNATURA: Algoritmos y Estructuras de Datos // PRÁCTICA Nº: 2 // COMENTARIOS: se indican entre [] las pautas de estilo aplicadas de // "C++ Programming Style Guidelines" // https://geosoft.no/development/cppstyle.html // COMPILACIÓN: g++ -g rational_t.cpp main_p2.cpp -o main_p2 // pauta de estilo [92]: comentarios multilínea usando solo "//" #include <iostream> #include <cmath> // pauta de estilo [41]: ficheros de cabecera agrupados y separados #include "rational_t.hpp" #include "vector_t.hpp" #include "matrix_t.hpp" using namespace std; int main() { rational_t a(1, 2), b(3); // FASE I cout << "a + b: "; // suma (a+b).write(); cout << "b - a: "; // resta (b-a).write(); cout << "a * b: "; // multiplicación (a*b).write(); cout << "a / b: "; // división (a/b).write(); cout << endl; // fin de línea // FASE II vector_t<double> v, w; // vector_t de tipo double, con las variables "v" y "w" v.read(), v.write(); w.read(), w.write(); cout << "Producto escalar de vector_t<double>: " << scal_prod(v, w) << endl << endl; // escritura por pantalla del producto escalar: "scal_prod(v, w)" vector_t<rational_t> x, y; // vector_t en la clase "rational_t", con las variables "x" y "y" x.read(), x.write(); y.read(), y.write(); cout << "Producto escalar de vector_t<rational_t>: " << scal_prod(x, y) << endl << endl; // escritura por pantalla del producto escalar: "scal_prod(x, y)" // FASE III matrix_t<double> A, B, C; // matriz de tipo double, con las variables "A", "B", "C" A.read(), A.write(); B.read(), B.write(); C.multiply(A, B); cout << "Multiplicación de matrices A y B: " << endl; // escritura por pantalla de la multiplicación matricial: C.write(); return 0; } // Modificación vector_t<double> get_par_v, get_par_w; get_par_v.read(), get_par_v.write(); get_par_w.read(), get_par_w.write();
70ec4eff726ae90c11e90220e16ea56ec9c39603
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_6404600001200128_1/C++/Yithis/Mus.cpp
67be13017cda9107818518190dfd4ba356eea6d3
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
660
cpp
Mus.cpp
#include <iostream> using namespace std; int main() { int powtorzenia; cin >> powtorzenia; for(int x=1; x<=powtorzenia; x++) { int n; cin >> n; int wynik1, wynik2, roznica1, roznica2; int tab [2005]; tab[0]=0; wynik1=wynik2=roznica1=roznica2=0; for (int i=1; i<=n; i++) { cin >> tab[i]; if (tab[i-1] > tab[i]) { roznica1=tab[i-1]-tab[i]; wynik1+=roznica1; roznica2=max(roznica1, roznica2); } } for (int i=1; i<n; i++) { if (tab[i]<roznica2) { wynik2+=tab[i]; } else { wynik2+=roznica2; } } cout << "Case #" << x << ": " << wynik1 << " " << wynik2 << endl; } }
ddfde4ba1ddad17e015f85943fe734ac02ce0fd2
5989b2788ee1f7d6aacfa164398c78fb3dea7101
/midterm/q09.cpp
802fbc20c7c1888e0108b09b80c9f7d0ee0954d1
[]
no_license
TechSolomon/cs201
636d73aae18857bdceb3e307caf1f747ca0b4820
91f50bf07d9961f965503b807eab79c30af400e0
refs/heads/master
2023-01-25T02:47:22.089327
2020-12-10T06:57:48
2020-12-10T06:57:48
290,005,361
0
0
null
null
null
null
UTF-8
C++
false
false
776
cpp
q09.cpp
// q09.cpp // Solomon Himelbloom // 18 October 2020 // CS 201 Midterm Exam #include <iostream> #include <stdio.h> #include <string> #include <vector> using std::cin; using std::cout; using std::endl; using std::string; using std::vector; void PrintSubStrings(std::string input, int permutations) { for (int i = 0; i < permutations; i++) { for (int length = 1; length <= permutations - i; length++) { cout << input.substr(i, length) << " "; } } } // Question #9: Write a C++ function PrintSubStrings that take a string // and prints all substrings in that string. // E.g. PrintSubStrings(“abc”) would output a b c ab bc abc. int main() { std::string output = "abc"; PrintSubStrings(output, output.length()); return 0; }
520695e4d1ea873b4294e84c59fa4c00e37a9e99
548193730ee9272ac8b852694bda6d8b22a81fc5
/201410/QSTRING.cpp
fcc8387e12eefae4ffdbf42e0ef030af14ad493c
[]
no_license
iSeaSoul/codechef
465662e3ea5a1c940b1890593b34527d1dff21fa
5aa5bdba6f49999b35dd6e26f0f6ac92feb54c47
refs/heads/master
2021-01-19T05:00:20.235655
2014-10-26T06:58:07
2014-10-26T06:58:07
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,179
cpp
QSTRING.cpp
/* * Not the fish. * iSea @ 2014-10-04 17:20 */ #include <cmath> #include <ctime> #include <cstdio> #include <cstring> #include <iostream> #include <algorithm> #include <fstream> #include <sstream> #include <vector> #include <string> #include <bitset> #include <queue> #include <map> #include <set> using namespace std; // Self Template Code BGEIN #define sz(x) ((int)((x).size())) #define out(x) printf(#x" %d\n", x) #define rep(i,n) for (int i = 0; i < (n); ++i) #define repf(i,a,b) for (int i = (a); i <= (b); ++i) #define repd(i,a,b) for (int i = (a); i >= (b); --i) #define repcase int t, Case = 1; for (scanf ("%d", &t); t; --t) #define repeach(i,x) for (__typeof((x).begin()) i = (x).begin(); i != (x).end(); ++i) typedef long long int64; typedef pair<int, int> pii; int sgn(double x) { return (x > 1e-8) - (x < -1e-8); } int count_bit(int x) { return x == 0? 0 : count_bit(x >> 1) + (x & 1); } template<class T> inline void ckmin(T &a, const T b) { if (b < a) a = b; } template<class T> inline void ckmax(T &a, const T b) { if (b > a) a = b; } // Self Template Code END const int MAXN = 1000000 + 10; struct suffix_array { int wa[MAXN], wb[MAXN], wv[MAXN], wc[MAXN]; int sa[MAXN], sr[MAXN], height[MAXN]; // sa : [1, n] sa[i] - the suffix from sa[i] rank i // sr : [0, n) sr[i] - the suffix from i rank sc[i] // height : [2, n] lcp length of sa[i - 1] and sa[i] int cmp(int *r, int a, int b, int l) { return r[a] == r[b] && r[a + l] == r[b + l]; } // m indicate the size of characters // adjust if it's a number string void da(char *r, int n, int m = 28) { int i, j, p, *x = wa, *y = wb, *t; for (i = 0; i < m; i++) wc[i] = 0; for (i = 0; i < n; i++) wc[x[i] = r[i]]++; for (i = 1; i < m; i++) wc[i] += wc[i - 1]; for (i = n - 1; i >= 0; i--) sa[--wc[x[i]]] = i; for (j = 1, p = 1; p < n; j *= 2, m = p) { for (p = 0, i = n - j; i < n; i++) y[p++]=i; for (i = 0; i < n; i++) if(sa[i] >= j) y[p++] = sa[i] - j; for (i = 0; i < n; i++) wv[i] = x[y[i]]; for (i = 0; i < m; i++) wc[i] = 0; for (i = 0; i < n; i++) wc[wv[i]] ++; for (i = 1; i < m; i++) wc[i] += wc[i-1]; for (i = n - 1; i >= 0; i--) sa[--wc[wv[i]]] = y[i]; for (t = x, x = y, y = t, p = 1, x[sa[0]] = 0, i = 1; i < n; i++){ x[sa[i]] = cmp(y, sa[i - 1], sa[i], j) ? p - 1 : p++; } } } void cal_height(char *r, int n) { int i, j, k = 0; for (i = 1; i <= n; i++) sr[sa[i]] = i; for (i = 0; i < n; height[sr[i++]] = k) { for (k ? k-- : 0, j = sa[sr[i] - 1]; r[i + k] == r[j + k]; k++); } } // complexity O(n * logn) void process(char *r, int n) { da(r, n + 1); cal_height(r, n); } }; struct persist_st { struct node { int l, r, val; }; node n[MAXN * 40]; int r_cnt, N; void init(int _n) { r_cnt = 0; N = _n; } int build(int l, int r) { int curR = r_cnt++; n[curR].val = 0; if (l != r) { n[curR].l = build (l, (l + r) >> 1); n[curR].r = build (((l + r) >> 1) + 1, r); } return curR; } void update_dif(int cur_root, int root) { n[cur_root].val = n[root].val + 1; } int update(int root, int pos) { // printf ("update %d %d\n", root, pos); int nextR = r_cnt++; int resR = nextR; update_dif (nextR, root); int l = 1, r = N; while (l != r) { int mid = (l + r) >> 1; if (pos <= mid) { n[nextR].l = r_cnt++; n[nextR].r = n[root].r; nextR = n[nextR].l; root = n[root].l; r = mid; } else { n[nextR].r = r_cnt++; n[nextR].l = n[root].l; nextR = n[nextR].r; root = n[root].r; l = mid + 1; } update_dif (nextR, root); } // printf ("update root %d\n", resR); return resR; } int get_kth_num_pos(int l_root, int r_root, int cnt) { // printf ("query pos %d %d %d\n", l_root, r_root, cnt); if (n[r_root].val - n[l_root].val < cnt) { return -1; } int l = 1, r = N; while (l != r) { // printf ("go %d %d\n", l, r); int mid = (l + r) >> 1; if (n[n[r_root].l].val - n[n[l_root].l].val >= cnt) { l_root = n[l_root].l; r_root = n[r_root].l; r = mid; } else { cnt -= n[n[r_root].l].val - n[n[l_root].l].val; l_root = n[l_root].r; r_root = n[r_root].r; l = mid + 1; } } // printf ("query res %d\n", l); return l; } int get_index(int l_root, int r_root, int pos) { int cnt = 0; int l = 1, r = N; while (l != r) { int mid = (l + r) >> 1; if (pos <= mid) { l_root = n[l_root].l; r_root = n[r_root].l; r = mid; } else { cnt += (n[n[r_root].l].val - n[n[l_root].l].val); l_root = n[l_root].r; r_root = n[r_root].r; l = mid + 1; } } cnt += n[r_root].val - n[l_root].val; return cnt; } }; int plog2[MAXN]; struct RMQ { int dp[MAXN][20]; void init(int* val, int n) { for (int i = 1; i <= n; ++i) { dp[i][0] = val[i]; } int maxk = plog2[n]; for (int k = 1; k <= maxk; ++k) { for (int i = 1; i + (1 << (k - 1)) <= n; ++i) { dp[i][k] = min(dp[i][k - 1], dp[i + (1 << (k - 1))][k - 1]); } } } int query(int a, int b) { int k = plog2[b - a + 1]; return min(dp[a][k], dp[b - (1 << k) + 1][k]); } }; persist_st pst; suffix_array sa; RMQ rmq; char s[MAXN]; int root_id[MAXN]; long long psum[MAXN]; int main() { repf (i, 1, MAXN - 1) { plog2[i] = (int)(log((double)(i)) / log(2.0)); } while (scanf ("%s", s) != EOF) { // build sa int n = strlen(s); rep (i, n) { s[i] = (s[i] - 'a') + 2; } sa.process(s, n); // build pst pst.init(n); root_id[0] = pst.build(1, n); repf (i, 1, n) { root_id[i] = pst.update(root_id[i - 1], sa.sa[i] + 1); } // build lcp_rmq rmq.init(sa.height, n); // build partial sum repf (i, 1, n) { int num_distinct_substring = n - sa.sa[i] - sa.height[i]; psum[i] = psum[i - 1] + num_distinct_substring; // printf ("%I64d\n", psum[i]); } int cl = 0, cr = 0, M; scanf ("%d", &M); while (M--) { char op[10]; long long k; int l, r; scanf ("%s", op); if (strcmp(op, "Select") == 0) { scanf ("%lld%d", &k, &r); int pos = lower_bound(psum + 1, psum + n + 1, k) - psum; k -= psum[pos - 1]; int anslen = sa.height[pos] + k; int L = pos + 1, R = n; while (L <= R) { int mid = (L + R) >> 1; if (rmq.query(pos + 1, mid) >= anslen) { L = mid + 1; } else { R = mid - 1; } } // printf ("getmin %d %d\n", pos, L - 1); int cl = pst.get_kth_num_pos(root_id[pos - 1], root_id[L - 1], r); int cr = cl + anslen - 1; printf ("%d %d\n", cl, cr); } else { scanf ("%d%d", &l, &r); int pos = sa.sr[l - 1]; int anslen = r - l + 1; int L = pos + 1, R = n; while (L <= R) { int mid = (L + R) >> 1; if (rmq.query(pos + 1, mid) >= anslen) { L = mid + 1; } else { R = mid - 1; } } int curr = L - 1; L = 1, R = pos - 1; while (L <= R) { int mid = (L + R) >> 1; if (rmq.query(mid + 1, pos) >= anslen) { R = mid - 1; } else { L = mid + 1; } } int curl = R + 1; k = psum[curl - 1] + (anslen - sa.height[curl]); int rank = pst.get_index(root_id[curl - 1], root_id[curr], l); printf ("%lld %d\n", k, rank); } } } return 0; }
c18bd7057d842a7896c787303319ab6709611c9a
133ba09a1b53a4a0fc2d96a86c515d93926c1946
/backtracking/sudoku.cpp
deda1c47c4bdcee90fc6edf566660e73cfe0e4aa
[ "MIT" ]
permissive
archit-1997/InterviewBit
f13fa6ab1a063dae791198c18c8a6ad6a0aa7bdc
6f5655ce0c9c8dd1b2433588f47da5aa7f5860d7
refs/heads/main
2023-06-25T13:16:12.204385
2021-07-26T02:26:47
2021-07-26T02:26:47
329,556,348
1
0
MIT
2021-03-07T14:58:20
2021-01-14T08:44:10
C++
UTF-8
C++
false
false
1,534
cpp
sudoku.cpp
const int N = 9; bool isValid(vector<vector<char>> &A, int row, int col) { char elem = A[row][col]; // check range if (elem - '0' < 1 || elem - '0' > 9) return false; // check row and column for duplicates for (auto p = 0; p < N; ++p) { if (A[p][col] == elem && p != row) return false; if (A[row][p] == elem && p != col) return false; } // check 3x3 subgrid for duplicates int subRow = (row / 3) * 3; // Ex: row = 2 belongs to first subgrid, so to // bring back row to index 0 int subCol = (col / 3) * 3; // so as to start iterating first subgrid, we do 2/3 = 0 then 0*3 = 0. for (auto i = subRow; i < subRow + 3; ++i) { for (auto j = subCol; j < subCol + 3; ++j) { if (A[i][j] == elem && (i != row || j != col)) return false; } } return true; } bool sudoku(vector<vector<char>> &A, int row, int col) { if (row == 9) return true; int nextRow, nextCol; if (col == 8) { nextRow = row + 1; nextCol = 0; } else { nextRow = row; nextCol = col + 1; } if (A[row][col] != '.') { if (!isValid(A, row, col)) return false; return sudoku(A, nextRow, nextCol); } for (auto i = 1; i <= N; ++i) { A[row][col] = i + '0'; if (isValid(A, row, col) && sudoku(A, nextRow, nextCol)) return true; } A[row][col] = '.'; return false; } void Solution::solveSudoku(vector<vector<char>> &A) { if (A.size() != N || A[0].size() != N) return; sudoku(A, 0, 0); }
3df89b1450769837a52a440e75f0cd80b3d9b130
1af49694004c6fbc31deada5618dae37255ce978
/chrome/browser/video_tutorials/internal/tutorial_store_unittest.cc
4657d4b1711b706faa4bea394304477e2f426290
[ "BSD-3-Clause" ]
permissive
sadrulhc/chromium
59682b173a00269ed036eee5ebfa317ba3a770cc
a4b950c23db47a0fdd63549cccf9ac8acd8e2c41
refs/heads/master
2023-02-02T07:59:20.295144
2020-12-01T21:32:32
2020-12-01T21:32:32
317,678,056
3
0
BSD-3-Clause
2020-12-01T21:56:26
2020-12-01T21:56:25
null
UTF-8
C++
false
false
7,792
cc
tutorial_store_unittest.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/video_tutorials/internal/tutorial_store.h" #include <map> #include <memory> #include <string> #include <utility> #include "base/run_loop.h" #include "base/test/task_environment.h" #include "chrome/browser/video_tutorials/test/test_utils.h" #include "components/leveldb_proto/public/proto_database.h" #include "components/leveldb_proto/testing/fake_db.h" #include "testing/gtest/include/gtest/gtest.h" using leveldb_proto::test::FakeDB; using InitStatus = leveldb_proto::Enums::InitStatus; namespace video_tutorials { class TutorialStoreTest : public testing::Test { public: using TutorialGroupProto = video_tutorials::proto::VideoTutorialGroup; using EntriesMap = std::map<std::string, std::unique_ptr<TutorialGroup>>; using ProtoMap = std::map<std::string, TutorialGroupProto>; using KeysAndEntries = std::map<std::string, TutorialGroup>; TutorialStoreTest() : db_(nullptr) {} ~TutorialStoreTest() override = default; TutorialStoreTest(const TutorialStoreTest& other) = delete; TutorialStoreTest& operator=(const TutorialStoreTest& other) = delete; protected: void Init(std::vector<TutorialGroup> input, InitStatus status, bool expected_success) { CreateTestDbEntries(std::move(input)); auto db = std::make_unique<FakeDB<TutorialGroupProto, TutorialGroup>>( &db_entries_); db_ = db.get(); store_ = std::make_unique<TutorialStore>(std::move(db)); store_->Initialize(base::BindOnce(&TutorialStoreTest::OnInitCompleted, base::Unretained(this), expected_success)); db_->InitStatusCallback(status); } void OnInitCompleted(bool expected_success, bool success) { EXPECT_EQ(expected_success, success); } void CreateTestDbEntries(std::vector<TutorialGroup> input) { for (auto& entry : input) { TutorialGroupProto proto; TutorialGroupToProto(&entry, &proto); db_entries_.emplace(entry.language, proto); } } void LoadEntriesAndVerify(const std::vector<std::string>& keys, bool expected_success, std::vector<TutorialGroup> expected_entries) { store_->LoadEntries(keys, base::BindOnce(&TutorialStoreTest::OnEntriesLoaded, base::Unretained(this), expected_success, expected_entries)); db_->LoadCallback(true); } void OnEntriesLoaded( bool expected_success, std::vector<TutorialGroup> expected_entries, bool success, std::unique_ptr<std::vector<TutorialGroup>> loaded_entries) { EXPECT_EQ(expected_success, success); EXPECT_EQ(loaded_entries->size(), expected_entries.size()); std::vector<TutorialGroup> actual_loaded_entries; for (auto& loaded_entry : *loaded_entries.get()) { actual_loaded_entries.emplace_back(loaded_entry); } EXPECT_EQ(expected_entries, actual_loaded_entries); } // Verifies the entries in the db is |expected|. void VerifyDataInDb(std::unique_ptr<KeysAndEntries> expected) { db_->LoadKeysAndEntries(base::BindOnce(&TutorialStoreTest::OnVerifyDataInDb, base::Unretained(this), std::move(expected))); db_->LoadCallback(true); } void OnVerifyDataInDb(std::unique_ptr<KeysAndEntries> expected, bool success, std::unique_ptr<KeysAndEntries> loaded_entries) { EXPECT_TRUE(success); DCHECK(expected); DCHECK(loaded_entries); for (auto it = loaded_entries->begin(); it != loaded_entries->end(); it++) { EXPECT_NE(expected->count(it->first), 0u); auto& actual_loaded_group = it->second; auto& expected_group = expected->at(it->first); EXPECT_EQ(actual_loaded_group, expected_group); } } const EntriesMap& loaded_keys_and_entries() const { return loaded_keys_and_entries_; } FakeDB<TutorialGroupProto, TutorialGroup>* db() { return db_; } Store<TutorialGroup>* store() { return store_.get(); } private: base::test::TaskEnvironment task_environment_; EntriesMap loaded_keys_and_entries_; ProtoMap db_entries_; FakeDB<TutorialGroupProto, TutorialGroup>* db_{nullptr}; std::unique_ptr<Store<TutorialGroup>> store_; }; // Test loading keys from a non-empty database in initialization successfully. TEST_F(TutorialStoreTest, InitSuccess) { TutorialGroup test_group; test::BuildTestGroup(&test_group); std::vector<TutorialGroup> test_data; test_data.emplace_back(std::move(test_group)); Init(std::move(test_data), InitStatus::kOK, true /* expected */); } // Test loading all entries from a non-empty database in initialization // successfully. TEST_F(TutorialStoreTest, LoadAllEntries) { TutorialGroup test_group; test::BuildTestGroup(&test_group); std::vector<TutorialGroup> test_data; test_data.emplace_back(std::move(test_group)); auto expected_test_data = test_data; Init(std::move(test_data), InitStatus::kOK, true /* expected */); LoadEntriesAndVerify(std::vector<std::string>(), true, expected_test_data); } // Test loading keys from a non-empty database in initialization successfully. TEST_F(TutorialStoreTest, LoadSpecificEntries) { TutorialGroup test_group; test::BuildTestGroup(&test_group); std::vector<TutorialGroup> test_data; test_data.emplace_back(std::move(test_group)); auto expected_test_data = test_data; Init(std::move(test_data), InitStatus::kOK, true /* expected */); std::vector<std::string> keys; keys.emplace_back("en"); LoadEntriesAndVerify(keys, true, expected_test_data); } TEST_F(TutorialStoreTest, LoadEntryThatDoesntExist) { std::vector<TutorialGroup> test_data; auto expected_test_data = test_data; Init(std::move(test_data), InitStatus::kOK, true /* expected */); std::vector<std::string> keys; keys.emplace_back("en"); LoadEntriesAndVerify(keys, true, expected_test_data); } // Test adding and updating data successfully. TEST_F(TutorialStoreTest, AddAndUpdateDataSuccess) { std::vector<TutorialGroup> test_data; Init(std::move(test_data), InitStatus::kOK, true /* expected */); // Add a group successfully. TutorialGroup test_group; test::BuildTestGroup(&test_group); std::vector<std::pair<std::string, TutorialGroup>> entries_to_save; entries_to_save.emplace_back(std::make_pair(test_group.language, test_group)); std::vector<std::string> keys_to_delete; store()->UpdateAll( entries_to_save, keys_to_delete, base::BindOnce([](bool success) { EXPECT_TRUE(success); })); db()->UpdateCallback(true); auto expected = std::make_unique<KeysAndEntries>(); expected->emplace(test_group.language, std::move(test_group)); VerifyDataInDb(std::move(expected)); } // Test deleting entries with keys . TEST_F(TutorialStoreTest, Delete) { TutorialGroup test_group; test::BuildTestGroup(&test_group); std::string locale = test_group.language; std::vector<TutorialGroup> test_data; test_data.emplace_back(std::move(test_group)); Init(test_data, InitStatus::kOK, true /* expected */); std::vector<std::string> keys{locale}; std::vector<std::pair<std::string, TutorialGroup>> entries_to_save; store()->UpdateAll( entries_to_save, std::move(keys), base::BindOnce([](bool success) { EXPECT_TRUE(success); })); db()->UpdateCallback(true); // No entry is expected in db. auto expected = std::make_unique<KeysAndEntries>(); VerifyDataInDb(std::move(expected)); } } // namespace video_tutorials
0208891608ab9af242dd8e7ccc8246d2c306b19e
f75d23537ad491a0e5ea456cad2bf2f3df747381
/source/discord/message.hpp
b6b99ef2f33975b6425b6131d70e619139cb8174
[ "MIT" ]
permissive
kociap/Discordpp
ae37efd80ab85226910557f038adaac389f1e47d
fcbf30d199ec217e0e6289aee96e365de383dbda
refs/heads/master
2020-04-02T17:36:03.081975
2019-01-14T09:55:00
2019-01-14T09:55:00
154,663,948
0
1
MIT
2019-01-15T07:44:18
2018-10-25T12:04:47
C++
UTF-8
C++
false
false
534
hpp
message.hpp
#ifndef DISCORD_MESSAGE_HPP #define DISCORD_MESSAGE_HPP #include "nlohmann/json.hpp" #include "types.hpp" #include "user.hpp" namespace discord { struct Message { User author; Snowflake id; Snowflake channel_id; Snowflake guild_id; String content; String timestamp; static Message from_json(nlohmann::json const&); }; // nlohmann::json specific function void from_json(nlohmann::json const&, Message&); } // namespace discord #endif // !DISCORD_MESSAGE_HPP
8ccdf8d03b98456c6584ff2ca02b64620895ecad
c80e47505635b5d0b895518b5b311e3276f9ddd3
/COUNTING_ways.cpp
36b2a32d73bff44a3dc8aa58c51e782702884f7c
[]
no_license
dabbler011/codes
9389cd08270b249e0c1f1940cb34fcbc59d9ccf9
6570914383423edc8a3076b303eff1511fcf3983
refs/heads/master
2021-01-20T06:32:52.478702
2018-08-04T18:08:25
2018-08-04T18:08:25
101,504,543
2
0
null
null
null
null
UTF-8
C++
false
false
565
cpp
COUNTING_ways.cpp
#include <bits/stdc++.h> using namespace std; int dp[10001][101]; int compute (int dist,int k) { if (dist < 0) return 0; if (dist == 0) return 1; if(dp[dist][k]!=-1) return dp[dist][k]; int i,ans=0; for (i = 1;i <= k;i++) { ans+=compute(dist-i,k); ans%=1000000007; } return dp[dist][k]=ans; } int main () { memset(dp,-1,sizeof(dp)); int i; for (i=1;i<=100;i++) compute(10000,i); int t; cin>>t; while(t--) { int x,k; cin>>x>>k; cout<<dp[x][k]<<endl; } return 0; }
e19385500506abd73e012291835b5e290ad2b5a4
66dcd8757e7c865d1147978bbdb29ed8eeea0a7a
/game-specific/Shattered Memories/CommonQt/CsvReader.h
19ab908649f29d3abdca43d1ecdb7c36bf27edad
[]
no_license
YAGAMI55/consolgames-tools
9f03106c10161dad130cf0e6f47fa4871c2dfdec
9cb5b20e0411ef3708fc1f747823246e5bfcc40d
refs/heads/master
2022-04-12T11:50:58.730962
2019-03-13T21:14:54
2019-03-13T21:14:54
null
0
0
null
null
null
null
UTF-8
C++
false
false
357
h
CsvReader.h
#pragma once #include <QFile> #include <QTextStream> #include <QStringList> namespace ShatteredMemories { class CsvReader { public: CsvReader(const QString& filename); bool isOpen(); QMap<QString, QString> readLine(); const QStringList& header() const; private: QFile m_file; QTextStream m_stream; QStringList m_header; }; }
d312cfbe6279727d1183f29934a3a4f05dcb111d
5bfca148fb7d074a6a9486002c626926826875f8
/homework/4_02.cpp
bdf129074a349a7bfe230f2e9bc9dac6af6e5052
[]
no_license
djww/lab_work
b948cb7f4050b63b2262d832646691f040166832
223cf25573124cd5073459688736ab163cc03a4c
refs/heads/master
2020-03-30T06:03:03.458789
2018-11-21T09:52:21
2018-11-21T09:52:21
150,835,733
0
0
null
null
null
null
UTF-8
C++
false
false
1,081
cpp
4_02.cpp
 #include<iostream> using namespace std; class Student { private: int num; char name[20]; static int total;//静态变量,放在public下 public: static void print(); Student() { total++; } ~Student() { total--; } Student(int n, char *p = "wang"); void GetName(); int Getnum(); }; int Student::total = 0;//初始化total Student::Student(int n, char* p) { num = n; strcpy(name, p); total++; } void Student::GetName() { cout << "the name of Student is" << name << endl; } int Student::Getnum() { cout << " the num of student is" << num << endl; return num; } void Student::print() { cout << "the number of students:" << total << endl; } int main() { Student::print(); //用类名调用静态对象, 0 Student *p = new Student(13); //调用一次构造函数 total+1 Student::print(); //total=1 //p->print(); //利用对象的指针访问静态变量 1 delete p; //调用析构函数 total-1 Student::print(); //=0 p->print(); Student s[2]; Student::print(); //1 s[1].print();//2 system("pause"); return 0; }
4c119630a6eaefc4a75ffe38d3dabf118a8d9ab1
07c3e4c4f82056e76285c81f14ea0fbb263ed906
/Re-Abyss/app/components/Actor/Enemy/KingDux/Tentacle/Builder.hpp
2f8efb5c5b89db6f46865fd37371e568c9c2d90e
[]
no_license
tyanmahou/Re-Abyss
f030841ca395c6b7ca6f9debe4d0de8a8c0036b5
bd36687ddabad0627941dbe9b299b3c715114240
refs/heads/master
2023-08-02T22:23:43.867123
2023-08-02T14:20:26
2023-08-02T14:20:26
199,132,051
9
1
null
2021-11-22T20:46:39
2019-07-27T07:28:34
C++
UTF-8
C++
false
false
288
hpp
Builder.hpp
#pragma once #include <abyss/commons/Fwd.hpp> #include <abyss/components/Actor/Enemy/KingDux/Tentacle/BuildDesc.hpp> namespace abyss::Actor::Enemy::KingDux::Tentacle { struct Builder { static void Build(ActorObj* pActor, ActorObj* parent, const BuildDesc& desc); }; }
a7f1956317bde56e5e8621e2b271609c090c26f8
93deffee902a42052d9f5fb01e516becafe45b34
/cf-gym/UCUP-23/B.cpp
1a3c81c27186f8b1c087e5d68be70f9bb9655000
[]
no_license
kobortor/Competitive-Programming
1aca670bc37ea6254eeabbe33e1ee016174551cc
69197e664a71a492cb5b0311a9f7b00cf0b1ccba
refs/heads/master
2023-06-25T05:04:42.492243
2023-06-16T18:28:42
2023-06-16T18:28:42
95,998,328
10
0
null
null
null
null
UTF-8
C++
false
false
1,716
cpp
B.cpp
#include <bits/stdc++.h> using namespace std; #define allof(x) (x).begin(), (x).end() typedef long long ll; typedef pair<ll, ll> pll; pll operator-(pll p1, pll p2) { return {p1.first - p2.first, p1.second - p2.second}; } ll cross(pll p1, pll p2) { return p1.first * p2.second - p1.second * p2.first; } ll norm(pll p) { return p.first * p.first + p.second * p.second; } int main() { cin.tie(0); cin.sync_with_stdio(0); int z; cin >> z; while (z--) { int n; cin >> n; vector<pll> pts; pts.push_back({1, 0}); pts.push_back({n, 0}); for (int i = 1; i <= n; i++) { ll y; cin >> y; pts.push_back({i, y}); } iter_swap(pts.begin(), min_element(allof(pts))); pll p0 = pts[0]; sort(pts.begin() + 1, pts.end(), [=](pll p1, pll p2) { p1 = p1 - p0; p2 = p2 - p0; ll cx = cross(p1, p2); if (cx == 0) { // longest first return norm(p1) > norm(p2); } else { return cx < 0; } }); // for (pll p : pts) { // cout << p.first << " " << p.second << endl; // } vector<pll> hull; hull.push_back(pts[0]); for (int i = 1; i < (int)pts.size(); i++) { // ignore same directions if (i != 1 && cross(pts[i - 1] - pts[0], pts[i] - pts[0]) == 0) { continue; } while ((int)hull.size() >= 2) { int m = hull.size(); if (cross(hull[m - 2] - hull[m - 1], pts[i] - hull[m - 1]) < 0) { hull.pop_back(); } else { break; } } hull.push_back(pts[i]); } ll ans = 0; for (int i = 1; i + 2 < (int)hull.size(); i++) { ll x1 = hull[i].first; ll x2 = hull[i + 1].first; ll y1 = hull[i].second; ll y2 = hull[i + 1].second; ans += (x2 - x1) * (y1 + y2); } cout << ans << "\n"; } }
95212b1cd637e4cb9e0e62f7f29c2e82e1a8370b
6c2409604c8296fb442b34f0af88119a8c439085
/mednafen/src/wii/emulator/MenuManager.h
a278e63f5df35ea4df63491f8c68e1e97d1c6c14
[]
no_license
xjsxjs197/WiiEmuHanhua
19083fe1957d3052aec38c43c1bbd6f2f4ecc8e8
9ba1951f0a10058a91bbd1b7c9daee6dd0b474af
refs/heads/master
2023-01-25T00:53:07.750669
2022-07-02T02:54:54
2022-07-02T02:54:54
129,381,604
7
4
null
2023-01-11T11:27:08
2018-04-13T09:40:35
C
UTF-8
C++
false
false
602
h
MenuManager.h
#ifndef MENU_MANAGER_H #define MENU_MANAGER_H #include "Emulator.h" #include "BaseManager.h" #include "EmulatorMenuHelper.h" #include "CartridgeSettingsMenuHelper.h" #include "wii_main.h" class MenuManager : public BaseManager { protected: TREENODE* m_emulatorMenu; TREENODE* m_cartridgeSettingsMenu; public: MenuManager( Emulator& emulator ); TREENODE* getEmulatorMenu(); TREENODE* getCartridgeSettingsMenu(); virtual void getNodeName( TREENODE* node, char *buffer, char* value ); virtual void selectNode( TREENODE *node ); virtual bool isNodeVisible( TREENODE *node ); }; #endif
3a1c01149d84970b3fd27729fb367dbbf514f6d4
5deb8b306936767c6faff5c4b9b886f83635a863
/EasyNet/EasyServer/easy_server_message.cpp
feb2a8f82c0e3b74d94e7c8a6af39b40c7f9862e
[]
no_license
chenmaosheng/fantuantool
ac1573f54a48570ae6770b0b119415f18cdcef8a
fd43fa2edda174e3a03a549d57a2229f03b56cd1
refs/heads/master
2021-01-10T13:38:06.874445
2020-04-21T12:34:01
2020-04-21T12:34:01
48,181,785
0
1
null
2020-10-13T02:15:45
2015-12-17T15:19:09
C
UTF-8
C++
false
false
791
cpp
easy_server_message.cpp
#include "easy_server_message.h" #include "easy_packet.h" #include "easy_packethandler.h" #include "easy_session.h" bool CALLBACK PingReq_Callback(void* pClient, InputStream& stream) { EasySession* pSession = (EasySession*)pClient; uint32 iVersion; if (!stream.Serialize(iVersion)) return false; pSession->OnPingReq(iVersion); return true; } static PacketHandler::Func func[] = { PingReq_Callback, }; struct ClientDispatcher { ClientDispatcher() { PacketHandler::m_pFunc = func; } }; static ClientDispatcher clientDispatcher; int32 PingAck(void* pServer, uint32 iVersion) { OutputStream stream; if (!stream.Serialize(iVersion)) return -1; PacketHandler::SendPacket(pServer, 0, stream.GetDataLength(), stream.GetBuffer()); return 0; }
465679cb7587ae028bf912c41f3a7cfa5676aad0
95ae7dfa9ee578f1b24a65986ff78bf77ceca0c5
/Engine/source/console/telnetDebugger.cpp
cc810a8a15996f3a1f33b3c53f0ab974f92d35b5
[ "MIT", "LicenseRef-scancode-unknown" ]
permissive
TorqueGameEngines/Torque3D
4e1f6a05cc0928980c8c7c20bcdd680eaa6dcee8
a445a4364664e299196bd551d213844486080145
refs/heads/development
2023-09-03T12:40:40.658487
2023-08-24T14:44:43
2023-08-24T14:44:43
267,440,108
1,192
178
MIT
2023-09-13T14:28:16
2020-05-27T22:35:54
C++
UTF-8
C++
false
false
27,834
cpp
telnetDebugger.cpp
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "console/telnetDebugger.h" #include "core/frameAllocator.h" #include "console/console.h" #include "console/engineAPI.h" #include "core/stringTable.h" #include "console/consoleInternal.h" #include "console/ast.h" #include "console/compiler.h" #include "core/util/journal/process.h" #include "core/module.h" MODULE_BEGIN( TelnetDebugger ) MODULE_INIT { TelnetDebugger::create(); } MODULE_SHUTDOWN { TelnetDebugger::destroy(); } MODULE_END; // // Enhanced TelnetDebugger for Torsion // http://www.sickheadgames.com/torsion // // // Debugger commands: // // CEVAL console line - evaluate the console line // output: none // // BRKVARSET varName passct expr - NOT IMPLEMENTED! // output: none // // BRKVARCLR varName - NOT IMPLEMENTED! // output: none // // BRKSET file line clear passct expr - set a breakpoint on the file,line // it must pass passct times for it to break and if clear is true, it // clears when hit // output: // // BRKNEXT - stop execution at the next breakable line. // output: none // // BRKCLR file line - clear a breakpoint on the file,line // output: none // // BRKCLRALL - clear all breakpoints // output: none // // CONTINUE - continue execution // output: RUNNING // // STEPIN - run until next statement // output: RUNNING // // STEPOVER - run until next break <= current frame // output: RUNNING // // STEPOUT - run until next break <= current frame - 1 // output: RUNNING // // EVAL tag frame expr - evaluate the expr in the console, on the frame'th stack frame // output: EVALOUT tag exprResult // // FILELIST - list script files loaded // output: FILELISTOUT file1 file2 file3 file4 ... // // BREAKLIST file - get a list of breakpoint-able lines in the file // output: BREAKLISTOUT file skipBreakPairs skiplinecount breaklinecount skiplinecount breaklinecount ... // // // Other output: // // BREAK file1 line1 function1 file2 line2 function2 ... - Sent when the debugger hits a // breakpoint. It lists out one file/line/function triplet for each stack level. // The first one is the top of the stack. // // COUT console-output - echo of console output from engine // // BRKMOV file line newline - sent when a breakpoint is moved to a breakable line. // // BRKCLR file line - sent when a breakpoint cannot be moved to a breakable line on the client. // DefineEngineFunction( dbgSetParameters, void, (S32 port, const char * password, bool waitForClient ), (false), "( int port, string password, bool waitForClient )" "Open a debug server port on the specified port, requiring the specified password, " "and optionally waiting for the debug client to connect.\n" "@internal Primarily used for Torsion and other debugging tools") { if (TelDebugger) { TelDebugger->setDebugParameters(port, password, waitForClient ); } } DefineEngineFunction( dbgIsConnected, bool, (), , "()" "Returns true if a script debugging client is connected else return false.\n" "@internal Primarily used for Torsion and other debugging tools") { return TelDebugger && TelDebugger->isConnected(); } DefineEngineFunction( dbgDisconnect, void, (), , "()" "Forcibly disconnects any attached script debugging client.\n" "@internal Primarily used for Torsion and other debugging tools") { if (TelDebugger) TelDebugger->disconnect(); } static void debuggerConsumer(U32 level, const char *line) { TORQUE_UNUSED(level); if (TelDebugger) TelDebugger->processConsoleLine(line); } TelnetDebugger::TelnetDebugger() { Con::addConsumer(debuggerConsumer); mAcceptPort = -1; mAcceptSocket = NetSocket::INVALID; mDebugSocket = NetSocket::INVALID; mState = NotConnected; mCurPos = 0; mBreakpoints = NULL; mBreakOnNextStatement = false; mStackPopBreakIndex = -1; mProgramPaused = false; mWaitForClient = false; dStrncpy(mDebuggerPassword, "", PasswordMaxLength); dStrncpy(mLineBuffer, "", sizeof(mLineBuffer)); // Add the version number in a global so that // scripts can detect the presence of the // "enhanced" debugger features. Con::evaluatef( "$dbgVersion = %d;", Version ); } TelnetDebugger::Breakpoint **TelnetDebugger::findBreakpoint(StringTableEntry fileName, S32 lineNumber) { Breakpoint **walk = &mBreakpoints; Breakpoint *cur; while((cur = *walk) != NULL) { // TODO: This assumes that the OS file names are case // insensitive... Torque needs a dFilenameCmp() function. if( dStricmp( cur->fileName, fileName ) == 0 && cur->lineNumber == U32(lineNumber)) return walk; walk = &cur->next; } return NULL; } TelnetDebugger::~TelnetDebugger() { Con::removeConsumer(debuggerConsumer); if(mAcceptSocket != NetSocket::INVALID) Net::closeSocket(mAcceptSocket); if(mDebugSocket != NetSocket::INVALID) Net::closeSocket(mDebugSocket); } TelnetDebugger *TelDebugger = NULL; void TelnetDebugger::create() { TelDebugger = new TelnetDebugger; Process::notify(TelDebugger, &TelnetDebugger::process, PROCESS_FIRST_ORDER); } void TelnetDebugger::destroy() { Process::remove(TelDebugger, &TelnetDebugger::process); delete TelDebugger; TelDebugger = NULL; } void TelnetDebugger::send(const char *str) { Net::send(mDebugSocket, (const unsigned char*)str, dStrlen(str)); } void TelnetDebugger::disconnect() { if ( mDebugSocket != NetSocket::INVALID ) { Net::closeSocket(mDebugSocket); mDebugSocket = NetSocket::INVALID; } removeAllBreakpoints(); mState = NotConnected; mProgramPaused = false; } void TelnetDebugger::setDebugParameters(S32 port, const char *password, bool waitForClient) { // Don't bail if same port... we might just be wanting to change // the password. // if(port == mAcceptPort) // return; if(mAcceptSocket != NetSocket::INVALID) { Net::closeSocket(mAcceptSocket); mAcceptSocket = NetSocket::INVALID; } mAcceptPort = port; if(mAcceptPort != -1 && mAcceptPort != 0) { NetAddress address; Net::getIdealListenAddress(&address); address.port = mAcceptPort; mAcceptSocket = Net::openSocket(); Net::bindAddress(address, mAcceptSocket); Net::listen(mAcceptSocket, 4); Net::setBlocking(mAcceptSocket, false); } dStrncpy(mDebuggerPassword, password, PasswordMaxLength); mWaitForClient = waitForClient; if ( !mWaitForClient ) return; // Wait for the client to fully connect. while ( mState != Connected ) { Platform::sleep(10); process(); } } void TelnetDebugger::processConsoleLine(const char *consoleLine) { if(mState != NotConnected) { send("COUT "); send(consoleLine); send("\r\n"); } } void TelnetDebugger::process() { NetAddress address; if(mAcceptSocket != NetSocket::INVALID) { // ok, see if we have any new connections: NetSocket newConnection; newConnection = Net::accept(mAcceptSocket, &address); if(newConnection != NetSocket::INVALID && mDebugSocket == NetSocket::INVALID) { char buffer[256]; Net::addressToString(&address, buffer); Con::printf("Debugger connection from %s", buffer); mState = PasswordTry; mDebugSocket = newConnection; Net::setBlocking(newConnection, false); } else if(newConnection != NetSocket::INVALID) Net::closeSocket(newConnection); } // see if we have any input to process... if(mDebugSocket == NetSocket::INVALID) return; checkDebugRecv(); if(mDebugSocket == NetSocket::INVALID) removeAllBreakpoints(); } void TelnetDebugger::checkDebugRecv() { for (;;) { // Process all the complete commands in the buffer. while ( mCurPos > 0 ) { // Remove leading whitespace. while ( mCurPos > 0 && ( mLineBuffer[0] == 0 || mLineBuffer[0] == '\r' || mLineBuffer[0] == '\n' ) ) { mCurPos--; dMemmove(mLineBuffer, mLineBuffer + 1, mCurPos); } // Look for a complete command. bool gotCmd = false; for(S32 i = 0; i < mCurPos; i++) { if( mLineBuffer[i] == 0 ) mLineBuffer[i] = '_'; else if ( mLineBuffer[i] == '\r' || mLineBuffer[i] == '\n' ) { // Send this command to be processed. mLineBuffer[i] = '\n'; processLineBuffer(i+1); // Remove the command from the buffer. mCurPos -= i + 1; dMemmove(mLineBuffer, mLineBuffer + i + 1, mCurPos); gotCmd = true; break; } } // If we didn't find a command in this pass // then we have an incomplete buffer. if ( !gotCmd ) break; } // found no <CR> or <LF> if(mCurPos == MaxCommandSize) // this shouldn't happen { disconnect(); return; } S32 numBytes; Net::Error err = Net::recv(mDebugSocket, (unsigned char*)(mLineBuffer + mCurPos), MaxCommandSize - mCurPos, &numBytes); if((err != Net::NoError && err != Net::WouldBlock) || numBytes == 0) { disconnect(); return; } if(err == Net::WouldBlock) return; mCurPos += numBytes; } } void TelnetDebugger::executionStopped(CodeBlock *code, U32 lineNumber) { if(mProgramPaused) return; if(mBreakOnNextStatement) { setBreakOnNextStatement( false ); breakProcess(); return; } Breakpoint **bp = findBreakpoint(code->name, lineNumber); if(!bp) return; Breakpoint *brk = *bp; mProgramPaused = true; Con::evaluatef("$Debug::result = %s;", brk->testExpression); if(Con::getBoolVariable("$Debug::result")) { brk->curCount++; if(brk->curCount >= brk->passCount) { brk->curCount = 0; if(brk->clearOnHit) removeBreakpoint(code->name, lineNumber); breakProcess(); } } mProgramPaused = false; } void TelnetDebugger::pushStackFrame() { if(mState == NotConnected) return; if(mBreakOnNextStatement && mStackPopBreakIndex > -1 && gEvalState.getStackDepth() > mStackPopBreakIndex) setBreakOnNextStatement( false ); } void TelnetDebugger::popStackFrame() { if(mState == NotConnected) return; if(mStackPopBreakIndex > -1 && gEvalState.getStackDepth()-1 <= mStackPopBreakIndex) setBreakOnNextStatement( true ); } void TelnetDebugger::breakProcess() { // Send out a break with the full stack. sendBreak(); mProgramPaused = true; while(mProgramPaused) { Platform::sleep(10); checkDebugRecv(); if(mDebugSocket == NetSocket::INVALID) { mProgramPaused = false; removeAllBreakpoints(); debugContinue(); return; } } } void TelnetDebugger::sendBreak() { // echo out the break send("BREAK"); char buffer[MaxCommandSize]; char scope[MaxCommandSize]; S32 last = 0; for(S32 i = (S32) gEvalState.getStackDepth() - 1; i >= last; i--) { CodeBlock *code = gEvalState.stack[i]->code; const char *file = "<none>"; if (code && code->name && code->name[0]) file = code->name; Namespace *ns = gEvalState.stack[i]->scopeNamespace; scope[0] = 0; if ( ns ) { if ( ns->mParent && ns->mParent->mPackage && ns->mParent->mPackage[0] ) { dStrcat( scope, ns->mParent->mPackage, MaxCommandSize ); dStrcat( scope, "::", MaxCommandSize ); } if ( ns->mName && ns->mName[0] ) { dStrcat( scope, ns->mName, MaxCommandSize ); dStrcat( scope, "::", MaxCommandSize ); } } const char *function = gEvalState.stack[i]->scopeName; if ((!function) || (!function[0])) function = "<none>"; dStrcat( scope, function, MaxCommandSize ); U32 line=0, inst; U32 ip = gEvalState.stack[i]->ip; if (code) code->findBreakLine(ip, line, inst); dSprintf(buffer, MaxCommandSize, " %s %d %s", file, line, scope); send(buffer); } send("\r\n"); } void TelnetDebugger::processLineBuffer(S32 cmdLen) { if (mState == PasswordTry) { if(dStrncmp(mLineBuffer, mDebuggerPassword, cmdLen-1)) { // failed password: send("PASS WrongPassword.\r\n"); disconnect(); } else { send("PASS Connected.\r\n"); mState = mWaitForClient ? Initialize : Connected; } return; } else { char evalBuffer[MaxCommandSize]; char varBuffer[MaxCommandSize]; char fileBuffer[MaxCommandSize]; char clear[MaxCommandSize]; S32 passCount, line, frame; if(dSscanf(mLineBuffer, "CEVAL %[^\n]", evalBuffer) == 1) { RawData rd; rd.size = dStrlen(evalBuffer) + 1; rd.data = ( S8* ) evalBuffer; Con::smConsoleInput.trigger(rd); } else if(dSscanf(mLineBuffer, "BRKVARSET %s %d %[^\n]", varBuffer, &passCount, evalBuffer) == 3) addVariableBreakpoint(varBuffer, passCount, evalBuffer); else if(dSscanf(mLineBuffer, "BRKVARCLR %s", varBuffer) == 1) removeVariableBreakpoint(varBuffer); else if(dSscanf(mLineBuffer, "BRKSET %s %d %s %d %[^\n]", fileBuffer,&line,&clear,&passCount,evalBuffer) == 5) addBreakpoint(fileBuffer, line, dAtob(clear), passCount, evalBuffer); else if(dSscanf(mLineBuffer, "BRKCLR %s %d", fileBuffer, &line) == 2) removeBreakpoint(fileBuffer, line); else if(!dStrncmp(mLineBuffer, "BRKCLRALL\n", cmdLen)) removeAllBreakpoints(); else if(!dStrncmp(mLineBuffer, "BRKNEXT\n", cmdLen)) debugBreakNext(); else if(!dStrncmp(mLineBuffer, "CONTINUE\n", cmdLen)) debugContinue(); else if(!dStrncmp(mLineBuffer, "STEPIN\n", cmdLen)) debugStepIn(); else if(!dStrncmp(mLineBuffer, "STEPOVER\n", cmdLen)) debugStepOver(); else if(!dStrncmp(mLineBuffer, "STEPOUT\n", cmdLen)) debugStepOut(); else if(dSscanf(mLineBuffer, "EVAL %s %d %[^\n]", varBuffer, &frame, evalBuffer) == 3) evaluateExpression(varBuffer, frame, evalBuffer); else if(!dStrncmp(mLineBuffer, "FILELIST\n", cmdLen)) dumpFileList(); else if(dSscanf(mLineBuffer, "BREAKLIST %s", fileBuffer) == 1) dumpBreakableList(fileBuffer); else { S32 errorLen = dStrlen(mLineBuffer) + 32; // ~25 in error message, plus buffer FrameTemp<char> errorBuffer(errorLen); dSprintf( errorBuffer, errorLen, "DBGERR Invalid command(%s)!\r\n", mLineBuffer ); // invalid stuff. send( errorBuffer ); } } } void TelnetDebugger::addVariableBreakpoint(const char*, S32, const char*) { send("addVariableBreakpoint\r\n"); } void TelnetDebugger::removeVariableBreakpoint(const char*) { send("removeVariableBreakpoint\r\n"); } void TelnetDebugger::addAllBreakpoints(CodeBlock *code) { if(mState == NotConnected) return; // Find the breakpoints for this code block and attach them. Breakpoint *cur = mBreakpoints; while( cur != NULL ) { // TODO: This assumes that the OS file names are case // insensitive... Torque needs a dFilenameCmp() function. if( dStricmp( cur->fileName, code->name ) == 0 ) { cur->code = code; // Find the fist breakline starting from and // including the requested breakline. S32 newLine = code->findFirstBreakLine(cur->lineNumber); if (newLine <= 0) { char buffer[MaxCommandSize]; dSprintf(buffer, MaxCommandSize, "BRKCLR %s %d\r\n", cur->fileName, cur->lineNumber); send(buffer); Breakpoint *next = cur->next; removeBreakpoint(cur->fileName, cur->lineNumber); cur = next; continue; } // If the requested breakline does not match // the actual break line we need to inform // the client. if (newLine != cur->lineNumber) { char buffer[MaxCommandSize]; // If we already have a line at this breapoint then // tell the client to clear the breakpoint. if ( findBreakpoint(cur->fileName, newLine) ) { dSprintf(buffer, MaxCommandSize, "BRKCLR %s %d\r\n", cur->fileName, cur->lineNumber); send(buffer); Breakpoint *next = cur->next; removeBreakpoint(cur->fileName, cur->lineNumber); cur = next; continue; } // We're moving the breakpoint to new line... inform the // client so it can update it's view. dSprintf(buffer, MaxCommandSize, "BRKMOV %s %d %d\r\n", cur->fileName, cur->lineNumber, newLine); send(buffer); cur->lineNumber = newLine; } code->setBreakpoint(cur->lineNumber); } cur = cur->next; } // Enable all breaks if a break next was set. if (mBreakOnNextStatement) code->setAllBreaks(); } void TelnetDebugger::addBreakpoint(const char *fileName, S32 line, bool clear, S32 passCount, const char *evalString) { fileName = StringTable->insert(fileName); Breakpoint **bp = findBreakpoint(fileName, line); if(bp) { // trying to add the same breakpoint... Breakpoint *brk = *bp; dFree(brk->testExpression); brk->testExpression = dStrdup(evalString); brk->passCount = passCount; brk->clearOnHit = clear; brk->curCount = 0; } else { // Note that if the code block is not already // loaded it is handled by addAllBreakpoints. CodeBlock* code = CodeBlock::find(fileName); if (code) { // Find the fist breakline starting from and // including the requested breakline. S32 newLine = code->findFirstBreakLine(line); if (newLine <= 0) { char buffer[MaxCommandSize]; dSprintf(buffer, MaxCommandSize, "BRKCLR %s %d\r\n", fileName, line); send(buffer); return; } // If the requested breakline does not match // the actual break line we need to inform // the client. if (newLine != line) { char buffer[MaxCommandSize]; // If we already have a line at this breapoint then // tell the client to clear the breakpoint. if ( findBreakpoint(fileName, newLine) ) { dSprintf(buffer, MaxCommandSize, "BRKCLR %s %d\r\n", fileName, line); send(buffer); return; } // We're moving the breakpoint to new line... inform the client. dSprintf(buffer, MaxCommandSize, "BRKMOV %s %d %d\r\n", fileName, line, newLine); send(buffer); line = newLine; } code->setBreakpoint(line); } Breakpoint *brk = new Breakpoint; brk->code = code; brk->fileName = fileName; brk->lineNumber = line; brk->passCount = passCount; brk->clearOnHit = clear; brk->curCount = 0; brk->testExpression = dStrdup(evalString); brk->next = mBreakpoints; mBreakpoints = brk; } } void TelnetDebugger::removeBreakpointsFromCode(CodeBlock *code) { Breakpoint **walk = &mBreakpoints; Breakpoint *cur; while((cur = *walk) != NULL) { if(cur->code == code) { dFree(cur->testExpression); *walk = cur->next; delete walk; } else walk = &cur->next; } } void TelnetDebugger::removeBreakpoint(const char *fileName, S32 line) { fileName = StringTable->insert(fileName); Breakpoint **bp = findBreakpoint(fileName, line); if(bp) { Breakpoint *brk = *bp; *bp = brk->next; if ( brk->code ) brk->code->clearBreakpoint(brk->lineNumber); dFree(brk->testExpression); delete brk; } } void TelnetDebugger::removeAllBreakpoints() { Breakpoint *walk = mBreakpoints; while(walk) { Breakpoint *temp = walk->next; if ( walk->code ) walk->code->clearBreakpoint(walk->lineNumber); dFree(walk->testExpression); delete walk; walk = temp; } mBreakpoints = NULL; } void TelnetDebugger::debugContinue() { if (mState == Initialize) { mState = Connected; return; } setBreakOnNextStatement( false ); mStackPopBreakIndex = -1; mProgramPaused = false; send("RUNNING\r\n"); } void TelnetDebugger::setBreakOnNextStatement( bool enabled ) { if ( enabled ) { // Apply breaks on all the code blocks. for(CodeBlock *walk = CodeBlock::getCodeBlockList(); walk; walk = walk->nextFile) walk->setAllBreaks(); mBreakOnNextStatement = true; } else if ( !enabled ) { // Clear all the breaks on the codeblocks // then go reapply the breakpoints. for(CodeBlock *walk = CodeBlock::getCodeBlockList(); walk; walk = walk->nextFile) walk->clearAllBreaks(); for(Breakpoint *w = mBreakpoints; w; w = w->next) { if ( w->code ) w->code->setBreakpoint(w->lineNumber); } mBreakOnNextStatement = false; } } void TelnetDebugger::debugBreakNext() { if (mState != Connected) return; if ( !mProgramPaused ) setBreakOnNextStatement( true ); } void TelnetDebugger::debugStepIn() { // Note that step in is allowed during // the initialize state, so that we can // break on the first script line executed. setBreakOnNextStatement( true ); mStackPopBreakIndex = -1; mProgramPaused = false; // Don't bother sending this to the client // if it's in the initialize state. It will // just be ignored as the client knows it // is in a running state when it connects. if (mState != Initialize) send("RUNNING\r\n"); else mState = Connected; } void TelnetDebugger::debugStepOver() { if (mState != Connected) return; setBreakOnNextStatement( true ); mStackPopBreakIndex = gEvalState.getStackDepth(); mProgramPaused = false; send("RUNNING\r\n"); } void TelnetDebugger::debugStepOut() { if (mState != Connected) return; setBreakOnNextStatement( false ); mStackPopBreakIndex = gEvalState.getStackDepth() - 1; if ( mStackPopBreakIndex == 0 ) mStackPopBreakIndex = -1; mProgramPaused = false; send("RUNNING\r\n"); } void TelnetDebugger::evaluateExpression(const char *tag, S32 frame, const char *evalBuffer) { // Make sure we're passing a valid frame to the eval. if ( frame > gEvalState.getStackDepth() ) frame = gEvalState.getStackDepth() - 1; if ( frame < 0 ) frame = 0; // Local variables use their own memory management and can't be queried by just executing // TorqueScript, we have to go digging into the interpreter. S32 evalBufferLen = dStrlen(evalBuffer); bool isEvaluatingLocalVariable = evalBufferLen > 0 && evalBuffer[0] == '%'; if (isEvaluatingLocalVariable) { // See calculation of current frame in pushing a reference frame for console exec, we need access // to the proper scope. //frame = gEvalState.getTopOfStack() - frame - 1; S32 stackIndex = gEvalState.getTopOfStack() - frame - 1; const char* format = "EVALOUT %s %s\r\n"; gEvalState.pushDebugFrame(stackIndex); Dictionary& stackFrame = gEvalState.getCurrentFrame(); StringTableEntry functionName = stackFrame.scopeName; StringTableEntry namespaceName = stackFrame.scopeNamespace->mName; StringTableEntry varToLookup = StringTable->insert(evalBuffer); S32 registerId = stackFrame.code->variableRegisterTable.lookup(namespaceName, functionName, varToLookup); if (registerId == -1) { // ERROR, can't read the variable! send("EVALOUT \"\" \"\""); return; } const char* varResult = gEvalState.getLocalStringVariable(registerId); gEvalState.popFrame(); S32 len = dStrlen(format) + dStrlen(tag) + dStrlen(varResult); char* buffer = new char[len]; dSprintf(buffer, len, format, tag, varResult[0] ? varResult : "\"\""); send(buffer); delete[] buffer; return; } // Build a buffer just big enough for this eval. const char* format = "return %s;"; dsize_t len = dStrlen( format ) + dStrlen( evalBuffer ); char* buffer = new char[ len ]; dSprintf( buffer, len, format, evalBuffer ); // Execute the eval. CodeBlock *newCodeBlock = new CodeBlock(); ConsoleValue result = newCodeBlock->compileExec( NULL, buffer, false, frame ); delete [] buffer; // Create a new buffer that fits the result. format = "EVALOUT %s %s\r\n"; len = dStrlen( format ) + dStrlen( tag ) + dStrlen( result.getString() ); buffer = new char[ len ]; dSprintf( buffer, len, format, tag, result.getString()[0] ? result.getString() : "\"\"" ); send( buffer ); delete newCodeBlock; delete [] buffer; } void TelnetDebugger::dumpFileList() { send("FILELISTOUT "); for(CodeBlock *walk = CodeBlock::getCodeBlockList(); walk; walk = walk->nextFile) { send(walk->name); if(walk->nextFile) send(" "); } send("\r\n"); } void TelnetDebugger::dumpBreakableList(const char *fileName) { fileName = StringTable->insert(fileName); CodeBlock *file = CodeBlock::find(fileName); char buffer[MaxCommandSize]; if(file) { dSprintf(buffer, MaxCommandSize, "BREAKLISTOUT %s %d", fileName, file->breakListSize >> 1); send(buffer); for(U32 i = 0; i < file->breakListSize; i += 2) { dSprintf(buffer, MaxCommandSize, " %d %d", file->breakList[i], file->breakList[i+1]); send(buffer); } send("\r\n"); } else send("DBGERR No such file!\r\n"); } void TelnetDebugger::clearCodeBlockPointers(CodeBlock *code) { Breakpoint **walk = &mBreakpoints; Breakpoint *cur; while((cur = *walk) != NULL) { if(cur->code == code) cur->code = NULL; walk = &cur->next; } }
4025eee4a4d3d3e52d39ffb70b0a36e32f5bf596
e3ceca6a34bf3426b90b3952782d4fd94c54d08a
/b問題/b_template_matching.cpp
67deeb380e5cc00273e50fa58f3b5bd89c7dfee3
[]
no_license
THEosusi/atcoder
ede5bffb44d59e266c6c4763a64cddeed8d8101f
0e9a17a82562e469198a6cc81922db5ac13efa6d
refs/heads/master
2023-06-21T06:45:28.128553
2021-07-27T09:02:55
2021-07-27T09:02:55
336,729,745
0
0
null
null
null
null
UTF-8
C++
false
false
1,063
cpp
b_template_matching.cpp
#include <bits/stdc++.h> using namespace std; int main() { int N,M; cin>>N>>M; vector<vector<char>>vec1(N,vector<char>(N)); vector<vector<char>>vec2(M,vector<char>(M)); for(int i=0;i<N;i++){ for(int j=0;j<N;j++){ cin>>vec1.at(i).at(j); } } for(int i=0;i<M;i++){ for(int j=0;j<M;j++){ cin>>vec2.at(i).at(j); } } for(int i=0;i<=N-M;i++){ for(int j=0;j<=N-M;j++){ bool aiu=false; for(int k=0;k<M;k++){ for(int l=0;l<M;l++){ if(vec2.at(k).at(l)==vec1.at(k+i).at(l+j)){ if(k==M-1&&l==M-1){ cout<<"Yes"<<endl; return 0; } } else{ aiu=true; break; } } if(aiu){ break; } } } } cout<<"No"<<endl; }
a7e0db24d0f5ef5b014243487b68ab9f31d6c012
69e2ba977ee203ffeb14cf23d0cba9725bbf73a9
/Optimization_Interface/path_graphics_item.h
9090d075be1e86f6ce4779c103bffadb2a150b55
[]
no_license
mceowen/optgui
70599b8702b2c712a6807ec65ca465f287f38b78
73650c5427c5b3d0a1ffa5c62422c61a04a42be3
refs/heads/master
2020-07-08T13:02:21.359429
2019-09-11T17:40:42
2019-09-11T17:40:42
203,681,058
0
0
null
null
null
null
UTF-8
C++
false
false
1,066
h
path_graphics_item.h
// TITLE: Optimization_Interface/path_graphics_item.h // AUTHORS: Daniel Sullivan, Miki Szmuk // LAB: Autonomous Controls Lab (ACL) // LICENSE: Copyright 2018, All Rights Reserved // Graphical representation for current drone path #ifndef PATH_GRAPHICS_ITEM_H_ #define PATH_GRAPHICS_ITEM_H_ #include <QGraphicsItem> #include <QPainter> #include "path_model_item.h" namespace interface { class PathGraphicsItem : public QGraphicsItem { public: explicit PathGraphicsItem(PathModelItem *model, QGraphicsItem *parent = nullptr); QRectF boundingRect() const override; void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = nullptr) override; void expandScene(); protected: QPainterPath shape() const override; QVariant itemChange(GraphicsItemChange change, const QVariant &value) override; private: void initialize(); QPen pen_; PathModelItem *model_; }; } // namespace interface #endif // PATH_GRAPHICS_ITEM_H_
c2c84d756eb0a9d270c1000c061f345753ba9e88
59409fab0056c63eb8b43c6bebc46ad2320e5f3f
/MAX10/tsbs/common_sw_library/tsb/ip/software/descriptor_ram_encapsulator/descriptor_ram_encapsulator.h
0a593c1fa2e8e52735ae2bfd36dde482389e95fc
[]
no_license
thomaslindner/xu1-max10-testing
ce96004e9ee51c927ec64fdc8d2438bc95742a46
a44bdeff1bf533632bfaea5ab9c8cf22d0529e85
refs/heads/master
2022-12-22T20:14:30.665124
2020-05-19T22:53:52
2020-05-19T22:53:52
295,867,338
0
1
null
null
null
null
UTF-8
C++
false
false
2,881
h
descriptor_ram_encapsulator.h
/* * descriptor_ram_encapsulator.h * * Created on: May 28, 2015 * Author: yairlinn */ #ifndef DESCRIPTOR_RAM_ENCAPSULATOR_H_ #define DESCRIPTOR_RAM_ENCAPSULATOR_H_ #include "basedef.h" #include "altera_msgdma_descriptor_regs.h" #include "altera_msgdma_csr_regs.h" #include "altera_msgdma_response_regs.h" #include "io.h" #include "altera_msgdma.h" #include "priv/alt_busy_sleep.h" #include "sys/alt_errno.h" #include "sys/alt_irq.h" #include "sys/alt_stdio.h" #include <string> namespace descram { class descriptor_ram_encapsulator { protected: alt_msgdma_standard_descriptor work_descriptor; unsigned long base_address_for_relative_addresses; unsigned long base_addr, span, num_descriptors; unsigned long per_descriptor_length_in_bytes; unsigned long get_descriptor_base(unsigned long desc_num); void write_descriptor( unsigned long descriptor_num, alt_msgdma_standard_descriptor* descriptor ); void construct_descriptor( alt_u32 read_address, alt_u32 write_address, alt_u32 length_in_words, alt_u32 control, alt_msgdma_standard_descriptor* descriptor ); public: descriptor_ram_encapsulator(unsigned long base_addr, unsigned long span, unsigned long base_address_for_relative_addresses, unsigned long per_descriptor_length_in_bytes = 16); int construct_and_write_descriptor( unsigned long descriptor_num, alt_u32 read_address, alt_u32 write_address, alt_u32 length_in_words, alt_u32 control ); int relative_construct_and_write_descriptor( unsigned long descriptor_num, alt_u32 read_address, alt_u32 write_address, alt_u32 length_in_words, alt_u32 control ); virtual ~descriptor_ram_encapsulator(); unsigned long get_base_addr() const { return base_addr; } void set_base_addr(unsigned long baseAddr) { base_addr = baseAddr; } unsigned long get_num_descriptors() const { return num_descriptors; } void set_num_descriptors(unsigned long numDescriptors) { num_descriptors = numDescriptors; } unsigned long get_span() const { return span; } void set_span(unsigned long span) { this->span = span; } unsigned long get_per_descriptor_length_in_bytes() const { return per_descriptor_length_in_bytes; } void set_per_descriptor_length_in_bytes( unsigned long perDescriptorLengthInBytes) { per_descriptor_length_in_bytes = perDescriptorLengthInBytes; } unsigned long get_base_address_for_relative_addresses() const { return base_address_for_relative_addresses; } void set_base_address_for_relative_addresses( unsigned long baseAddressForRelativeAddresses) { base_address_for_relative_addresses = baseAddressForRelativeAddresses; } }; } /* namespace descram */ #endif /* DESCRIPTOR_RAM_ENCAPSULATOR_H_ */
edd152fe4311fbd43db6849486231c130b4e4398
696165d7df8d6866a7d8dbc84e4efb70d2c315c6
/HighestTidyNumber/HighestTidyNumber/HighestTidyNumber.cpp
8b6c8a5657ded0673e7ae96c2dfba98607c95cda
[]
no_license
yadav26/GoogleCodeJam
0ecea18c9885845eef4ce1588e11dcf5bb8ae923
138abfaffb79573775fdbc9e420c093089659060
refs/heads/master
2021-04-29T16:36:09.472302
2018-11-24T14:47:59
2018-11-24T14:47:59
121,653,086
0
0
null
null
null
null
UTF-8
C++
false
false
5,920
cpp
HighestTidyNumber.cpp
// HighestTidyNumber.cpp : Defines the entry point for the console application. // #include <iostream> #include <fstream> #include <string> #include <sstream> using namespace std; //TDD bool checkIfCorrect(string input, string result) { int rlen = result.length(); int ilen = input.length(); int index = 0; if (ilen - rlen > 1) { cout << "Failed ilen - rlen > 1 in=" << input << ", res="<<result <<endl; return false; } if (rlen > ilen ) { cout << "Failed rlen > ilen in=" << input << ", res="<<result <<endl; return false; } else if (rlen < ilen) { if (result[0] > input[0]) { //cout << "Failed rlen < ilen && result[0] > input[0] in=" << input << ", res="<<result <<endl; return true; //only exception... no way to prove if can be compared..ignore and rely on length } } else { while (rlen > index) { if (result[index] == input[index]) ++index; else if (result[index] > input[index]) { cout << "Failed ilen == rlen && result[index] > input[index] in=" << input << ", res="<<result <<endl; return false; } else { return true; } } } return true; } string outpath = ".\\..\\Debug\\"; bool readBigInputs(string fname) { string ifilepath = outpath + fname+ ".in"; string ofilepath = outpath + fname+ ".out"; std::ofstream ofs(ofilepath, std::ofstream::out); std::ifstream file(ifilepath); if (!file){ ofs.close(); cout << "Input file not found at input path.\n"; return false; } if (file.is_open()) { cout << "Input file opened successfully.\n"; std::string line; int testCaseId = 0; string str = ""; string::size_type sz; getline(file, str); int testcases = std::stoi(str, &sz); int caseid = 1; while (getline(file, line)) { //cout << line << endl; bool tidy = false; //while (false == tidy) { int sz = line.size(); int counter = 0; if (sz == 1) { tidy = true; //cout << "this is tidy " << line << endl; ofs << "Case #" << caseid++ << ": " << line << endl; continue; } string newline = ""; int totalappendcount = 0; while (newline.size() <= sz ) { if (counter == sz - 1) { newline += line[counter]; break; } if (line[counter] <= line[counter + 1]) { newline += line[counter]; ++counter; } else { //find the immediate smaller number char p = line.at(counter); int number = atoi(&p); --number; char buff [2]="\0"; itoa(number, buff, 10 ); //traverse backwards to find the smaller number then the new smaller number. int rcounter = 0; int newlinesz = newline.length() ; int lastval = 0; if (newlinesz > 0) { int lastNewlineIndex = newlinesz - 1; do{ p = newline.at(lastNewlineIndex - rcounter); lastval = atoi(&p); if (lastval <= number) break; ++rcounter; } while ( (lastNewlineIndex - rcounter) >= 0 ); if((newlinesz - rcounter)==0)//if 0 index to be updated, totalappendcount = sz - 1; else totalappendcount = sz - (newlinesz - rcounter); //append smaller number and fill with 9 if (newlinesz - rcounter > 0) { newline = newline.substr(0, newlinesz - rcounter); newline += buff; --totalappendcount; } else { newline = ""; if (number > 0) { newline = buff; //--totalappendcount; } } } else { if (number > 0) { newline = buff; totalappendcount = line.length() -1; } else { totalappendcount = line.length() - 1; } } for (int x = 0; x < totalappendcount;++x) { newline += "9"; } break; } } cout << "Case #" << caseid << ": "<< line <<"\n" << newline << endl<<endl; ofs << "Case #" << caseid++ << ": " << newline << endl; checkIfCorrect(line, newline); } } } ofs.close(); file.close(); return true; } bool readInputs(string fname) { string ifilepath = outpath + fname + ".in"; string ofilepath = outpath + fname + ".out"; std::ofstream ofs(ofilepath, std::ofstream::out); std::ifstream file(ifilepath); if (!file) return false; if (file.is_open()) { cout << "file opened successfully."; std::string line; int testCaseId = 0; string str = ""; string::size_type sz; getline(file, str); int testcases = std::stoi(str, &sz); int caseid =1; while (getline(file, line)) { cout << line << endl; //int sz = line.size(); //int counter = sz-1; bool tidy = false; while (false == tidy) { int sz = line.size(); int counter = sz - 1; if (sz == 1) { tidy = true; cout << "this is tidy " << line << endl; ofs << "Case #"<< caseid++ << ": " << line << endl; continue; } while (/*line.size() > sz - counter && */counter-1 >= 0) { if (line[counter] >= line[counter - 1]) { counter--; } else break; //counter -= 1; } if (counter == 0) { cout << "this is tidy " << line << endl; ofs << "Case #" << caseid++ << ": " << line << endl; tidy = true; } else { string::size_type sz; //uint64_t number = string_to_uint64(line); int number = std::stoi(line, &sz);; number--; line = std::to_string(number); } } } } ofs.close(); file.close(); } int main() { readBigInputs("BL"); readBigInputs("BS"); return 0; }
1387c11be80aad53374380eedda74ecd5b451956
77d0c34fab629098f5adbd0aa7a0bec4e22931de
/test/testCmdLineArgs.cxx
69e0605ea89d90f3119281d0e1b46d4c555e59bc
[]
no_license
anitaNeutrino/anitaAnalysisTools
ab2329f48ef6ccbfc886ba9dcddf1a678f0b3b21
87650ca307c12400269f99d07cb51d9f56c7b584
refs/heads/master
2023-04-17T18:18:49.656811
2020-08-12T15:55:34
2020-08-12T15:55:34
61,329,404
0
0
null
null
null
null
UTF-8
C++
false
false
118
cxx
testCmdLineArgs.cxx
#include "AcclaimCmdLineArgs.h" int main(int argc, char* argv[]){ Acclaim::CmdLineArgs(argc, argv); return 0; }
1e923678e42774b36a79ecaa41f189a54af9046f
4f9930aa654816f464ea73fce01a73a5a3977c96
/CGL-Project/Source.cpp
a09aac3c50e2625286b2921300dd13ae82b48232
[]
no_license
Eyad-Mohammed-Osama/CG-Project
770164a28bcec1b186406dc4f681e2ccf0f34897
0361b44b8bbadce1c62d74e7954c422f7fa12c29
refs/heads/master
2020-12-19T01:23:49.243495
2020-01-22T14:13:22
2020-01-22T14:13:22
235,577,409
0
0
null
null
null
null
UTF-8
C++
false
false
21,227
cpp
Source.cpp
/* * This Code Was Created By Jeff Molofee 2000 * A HUGE Thanks To Fredric Echols For Cleaning Up * And Optimizing This Code, Making It More Flexible! * If You've Found This Code Useful, Please Let Me Know. * Visit My Site At nehe.gamedev.net */ #include <windows.h> // Header File For Windows #include <gl\gl.h> // Header File For The OpenGL32 Library #include <gl\glu.h> // Header File For The GLu32 Library #include <GL\glut.h> #include <irrKlang\irrKlang.h> #include <stdio.h> // Header File For Standard Input/Output #include <stdarg.h> // Header File For Variable Argument Routines #include <string> #include <ctime> #include <cstdlib> #include <iostream> #include <queue> #include <thread> #define STB_IMAGE_IMPLEMENTATION #include "stb_image.h" #include "Textures.h" #include "Map.h" #include "ObjectsListIndices.h" #include "Snake.h" #define PI acos(-1) #define JUMP 2 #define TILESIZE 2 #define SKYHEIGHT 800 #define LENGTH 1600 #define FLOORSIZE 8 #pragma comment(lib,"opengl32.lib") #pragma comment(lib,"glu32.lib") unsigned int base; // Base Display List For The Font Set unsigned int Index; double Theta = 0; double CoinAngle = 0; int X = 1, Y = 1, Z = 1; Textures TexturesList = {}; int CameraPosition = 5; int RotationCoefficient = 0; int Score = 0; int CurrentLevel = 2; int RemainingLives = 4; int SnakeSpeed = 1000; Map WorldMap = NULL; irrklang::ISoundEngine *se = irrklang::createIrrKlangDevice(); ObjectsListIndices Objects; bool IsSoundEnabled = false; bool IsMipmap = true; bool IsRotating = false; bool IsMoving = false; bool GameStarted = false; bool Fullscreen = false; bool Debug = false; bool CoinEaten = true; bool GameOver = false; bool GamePaused = false; bool ShouldGenerateLevel = true; bool ShouldGenerateRandomVector = true; bool HasWonGame = false; bool StartFromTheBeginning = true; static std::vector<Point> ObstaclesRandomPoints; Point CoinCoordinates; Snake GameSnake; void GLPrint(const char *str, double x, double y, double z) { // Custom GL "Print" Routine int len = (int)strlen(str); glRasterPos3d(x, y, z); for (int i = 0; i < len; i++) { glutBitmapCharacter(GLUT_BITMAP_TIMES_ROMAN_24, (int)str[i]); } } void DrawFloor(int size = 1) { int step = 2; glBindTexture(GL_TEXTURE_2D, TexturesList.Grass); for (int i = 0; i < 2 * size; i += step) { for (int j = 0; j < 2 * size; j += step) { glPushMatrix(); glTranslated(i, 0, j); glCallList(Objects.Tile); glPopMatrix(); } } } unsigned int LoadTexture(const char imagename[], bool mipmap) { unsigned int textureID; glGenTextures(1, &textureID); glBindTexture(GL_TEXTURE_2D, textureID); // load and generate the texture int width, height, nrChannels; unsigned char *data = stbi_load(imagename, &width, &height, &nrChannels, 0); if (data) { if (mipmap) { gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGB, width, height, GL_RGB, GL_UNSIGNED_BYTE, data); } else { glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, width, height, 0, GL_RGB, GL_UNSIGNED_BYTE, data); } } else { MessageBox(NULL, "Failed to load texture", "SHUTDOWN ERROR", MB_OK | MB_ICONINFORMATION); } stbi_image_free(data); glTexEnvf(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE); //GL_ADD, GL_MODULATE, GL_DECAL, GL_BLEND, GL_REPLACE. // set the texture wrapping/filtering options (on the currently bound texture object) glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);//GL_CLAMP glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); if (mipmap) { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR_MIPMAP_LINEAR); } else { glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); } return textureID; } void DrawSkybox() { glPushMatrix(); // Bottom glBindTexture(GL_TEXTURE_2D, TexturesList.Water); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3d(-LENGTH, -SKYHEIGHT, LENGTH); glTexCoord2f(1, 0); glVertex3d(-LENGTH, -SKYHEIGHT, -LENGTH); glTexCoord2f(1, 1); glVertex3d(LENGTH, -SKYHEIGHT, -LENGTH); glTexCoord2f(0, 1); glVertex3d(LENGTH, -SKYHEIGHT, LENGTH); glEnd(); // Top glBindTexture(GL_TEXTURE_2D, TexturesList.Sky); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3d(-LENGTH, SKYHEIGHT, LENGTH); glTexCoord2f(1, 0); glVertex3d(-LENGTH, SKYHEIGHT, -LENGTH); glTexCoord2f(1, 1); glVertex3d(LENGTH, SKYHEIGHT, -LENGTH); glTexCoord2f(0, 1); glVertex3d(LENGTH, SKYHEIGHT, LENGTH); glEnd(); // Left glBindTexture(GL_TEXTURE_2D, TexturesList.Sky); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(-LENGTH, -LENGTH, LENGTH); glTexCoord2f(1, 1); glVertex3d(-LENGTH, -LENGTH, -LENGTH); glTexCoord2f(1, 0); glVertex3d(-LENGTH, LENGTH, -LENGTH); glTexCoord2f(0, 0); glVertex3d(-LENGTH, LENGTH, LENGTH); glEnd(); // Right glBindTexture(GL_TEXTURE_2D, TexturesList.Sky); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(LENGTH, -LENGTH, LENGTH); glTexCoord2f(1, 1); glVertex3d(LENGTH, -LENGTH, -LENGTH); glTexCoord2f(1, 0); glVertex3d(LENGTH, LENGTH, -LENGTH); glTexCoord2f(0, 0); glVertex3d(LENGTH, LENGTH, LENGTH); glEnd(); // Front glBindTexture(GL_TEXTURE_2D, TexturesList.Sky); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(-LENGTH, -LENGTH, LENGTH); glTexCoord2f(1, 1); glVertex3d(LENGTH, -LENGTH, LENGTH); glTexCoord2f(1, 0); glVertex3d(LENGTH, LENGTH, LENGTH); glTexCoord2f(0, 0); glVertex3d(-LENGTH, LENGTH, LENGTH); glEnd(); // Back glBindTexture(GL_TEXTURE_2D, TexturesList.Sky); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(-LENGTH, -LENGTH, -LENGTH); glTexCoord2f(1, 1); glVertex3d(LENGTH, -LENGTH, -LENGTH); glTexCoord2f(1, 0); glVertex3d(LENGTH, LENGTH, -LENGTH); glTexCoord2f(0, 0); glVertex3d(-LENGTH, LENGTH, -LENGTH); glEnd(); glPopMatrix(); } void GenerateObstacles(int count) { Point P; glPushMatrix(); for (int i = 0; i < count;) { P = ObstaclesRandomPoints[i]; if (WorldMap(P.X, P.Z) == Map::EMPTY) { WorldMap(P.X, P.Z) = Map::OBSTACLE; glPushMatrix(); glTranslated(P.X - 1, 0, P.Z - 1); glCallList(Objects.Obstacle); glPopMatrix(); i++; } else { continue; } } glPopMatrix(); } void GenerateCoin() { if (CoinEaten && GameStarted) { bool flag = false; Point Temp; while (!flag) { Temp.X = rand() % (CurrentLevel * FLOORSIZE * 2); if (Temp.X % 2 == 0) { continue; } Temp.Y = 1; Temp.Z = rand() % (CurrentLevel * FLOORSIZE * 2); if (Temp.Z % 2 == 0) { continue; } if (WorldMap(Temp.X, Temp.Z) == Map::OBSTACLE) { continue; } flag = true; } CoinEaten = false; CoinCoordinates = Temp; } glPushMatrix(); glTranslated(CoinCoordinates.X, 0.5, CoinCoordinates.Z); glRotated(CoinAngle, 0, 1, 0); glCallList(Objects.Coin); glPopMatrix(); WorldMap(CoinCoordinates.X, CoinCoordinates.Z) = Map::COIN; } bool GoingToCollide(int x, int z) { if (x > CurrentLevel * FLOORSIZE * 2 - 1 || x < 0 || z > CurrentLevel * FLOORSIZE * 2 - 1 || z < 0) { return true; } if (WorldMap(x, z) == Map::OBSTACLE) { return true; } return false; } bool GoingToCoin(int x, int z) { if (WorldMap(x, z) == Map::COIN) { return true; } return false; } void SetInside() { if (X >= 2 * CurrentLevel * FLOORSIZE - 1) { X = CurrentLevel * FLOORSIZE * 2 - 1; } if (Y >= 2 * CurrentLevel * FLOORSIZE - 1) { Y = CurrentLevel * FLOORSIZE * 2 - 1; } if (Z >= 2 * CurrentLevel * FLOORSIZE - 1) { Z = CurrentLevel * FLOORSIZE * 2 - 1; } if (X < 1) { X = 1; } if (Y < 1) { Y = 1; } if (Z < 1) { Z = 1; } } void UpdateSnake() { glPushMatrix(); GLUquadric *head = gluNewQuadric(); glTranslated(X, 0.25, Z); glBindTexture(GL_TEXTURE_2D, TexturesList.SnakeHead); gluQuadricTexture(head, true); gluSphere(head, 0.5, 100, 40); GLUquadric *body = gluNewQuadric(); for (int i = 0; i < Score; i++) { glTranslated(-round(cos(Theta)), 0.25, -round(sin(Theta))); glBindTexture(GL_TEXTURE_2D, TexturesList.SnakeBody); gluQuadricTexture(body, true); gluSphere(body, 0.5, 100, 40); } glPopMatrix(); } void Move(int useless) { if (GoingToCollide(X + JUMP * cos(Theta), Z + JUMP * sin(Theta)) && IsMoving) { se->play2D("Music/Solid.wav", false); GameOver = true; IsMoving = false; RemainingLives--; } else { if (IsMoving) { if (GoingToCoin(X, Z)) { Score++; WorldMap(X, Z) = Map::EMPTY; CoinEaten = true; GenerateCoin(); se->play2D("Music/Bleep.mp3"); WorldMap(CoinCoordinates.X, CoinCoordinates.Z) = Map::COIN; GameSnake.InsertBody(X, Z); } UpdateSnake(); //WorldMap(X, Z) = Map::EMPTY; X += JUMP * cos(Theta); //Y += SPEED * sin(angle); Z += JUMP * sin(Theta); //WorldMap(X, Z) = Map::SNAKE; } glutTimerFunc(SnakeSpeed, Move, 0); } glutPostRedisplay(); } void ChangeCameraAngle(int useless) { double value = RotationCoefficient * PI / 2; if (Theta < value) { if (Theta + 0.1 >= value) { Theta = RotationCoefficient * PI / 2; IsMoving = true; IsRotating = false; } else { IsMoving = false; IsRotating = true; Theta += 0.4; glutTimerFunc(10, ChangeCameraAngle, 0); } } else if (Theta > value) { if (Theta - 0.1 <= value) { Theta = RotationCoefficient * PI / 2; IsMoving = true; IsRotating = false; } else { IsMoving = false; IsRotating = true; Theta -= 0.4; glutTimerFunc(10, ChangeCameraAngle, 0); } } glutPostRedisplay(); } void RotateCoin(int useless) { CoinAngle += 1; glutTimerFunc(100, RotateCoin, 0); glutPostRedisplay(); } void GenerateRandomVector() { ObstaclesRandomPoints.clear(); srand(time(0)); int c = 0; while (c < pow(CurrentLevel * FLOORSIZE, 2)) { Point Temp; Temp.X = rand() % (CurrentLevel * FLOORSIZE + 1); if ((int)Temp.X % 2 == 0) { continue; } Temp.Y = 1; Temp.Z = rand() % (CurrentLevel * FLOORSIZE + 1); if ((int)Temp.Z % 2 == 0) { continue; } ObstaclesRandomPoints.push_back(Temp); c++; } } void GenerateLevel() { if (ShouldGenerateRandomVector) { GenerateRandomVector(); Score = 0; ShouldGenerateRandomVector = false; } GameSnake = Snake(1, 1); WorldMap = Map(CurrentLevel * FLOORSIZE); WorldMap(1, 1) = Map::SNAKE; DrawFloor(CurrentLevel * FLOORSIZE); GenerateObstacles(CurrentLevel * 4); } void ReSizeGLScene(int width, int height) // Resize And Initialize The GL Window { glViewport(0, 0, (GLsizei)width, (GLsizei)height); glMatrixMode(GL_PROJECTION); glLoadIdentity(); //gluOrtho2D(-10, 10, -10, 10); //2D prespective (for WEEK 2) gluPerspective(45.0f, (GLfloat)width / (GLfloat)height, 0.1f, 4000.0f); //3D prespective (since WEEK 3) glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // Reset The Modelview Matrix } void Keyboard(unsigned char key, int x, int y) { if (Debug) { char buffer[128]; sprintf(buffer, "Key '%c' was pressed", key); MessageBox(NULL, buffer, "Info", 0x00000000L); } if (key == VK_ESCAPE) { exit(EXIT_SUCCESS); } else if (key == 'q') { IsRotating = true; IsMoving = false; RotationCoefficient--; ChangeCameraAngle(0); } else if (key == 'e') { IsRotating = true; IsMoving = false; RotationCoefficient++; ChangeCameraAngle(0); } else if (key == 'w') { if (!GameStarted) { GameSnake = Snake(1, 1); WorldMap(1, 1) = Map::SNAKE; GameOver = false; GameStarted = true; IsRotating = false; IsMoving = true; CoinEaten = true; Move(0); } } else if (key == 'n') { CurrentLevel++; GenerateLevel(); GameStarted = false; HasWonGame = false; } else if (key == 'i') { char buffer[1024]; sprintf(buffer, "Current Coordinates:\nX: %f\nY: %f\nZ: %f\n\nLooking At:\nX: %f\nY: %f\nZ: %f\nTheta: %f", X, Y, Z, X + cos(Theta), Y, Z + sin(Theta), Theta); MessageBox(NULL, buffer, "Coordinates", 0x00000000L); } else if (key == '+') { CameraPosition++; CameraPosition = CameraPosition % 6; } else if (key == '-') { ShouldGenerateLevel = !ShouldGenerateLevel; ShouldGenerateRandomVector = true; } else if (key == 'p') { IsMoving = !IsMoving; GamePaused = !GamePaused; } else if (key == 'r' && GameOver && RemainingLives > 1) { ShouldGenerateRandomVector = true; GenerateLevel(); GameStarted = false; GameOver = false; if (StartFromTheBeginning) { CurrentLevel = 1; StartFromTheBeginning = false; } } } void SpecialKey(int key, int x, int y) { if (key == GLUT_KEY_F1) { if (Fullscreen) { glutReshapeWindow(1024, 768); } else { glutFullScreen(); } Fullscreen = !Fullscreen; } else if (key == GLUT_KEY_F2) { IsSoundEnabled = !IsSoundEnabled; if (!IsSoundEnabled) { se->stopAllSounds(); } else { se->play2D("Music/Gameplay.mp3", true); } } else if (key == GLUT_KEY_F3) { MessageBox(NULL, WorldMap.ToString().c_str(), "World Map", 0x00000000L); } else if (key == GLUT_KEY_F4) { Debug = !Debug; } else if (key == GLUT_KEY_F11) { ObstaclesRandomPoints.clear(); GenerateRandomVector(); CurrentLevel++; GenerateLevel(); } else if (key == GLUT_KEY_F12) { ObstaclesRandomPoints.clear(); GenerateRandomVector(); CurrentLevel--; GenerateLevel(); } } void Animate(void) { glutPostRedisplay(); } int InitGL(void) // All Setup For OpenGL Goes Here { if (IsSoundEnabled) { se->play2D("Music/Gameplay.mp3", true); } glEnable(GL_TEXTURE_2D); glShadeModel(GL_SMOOTH); // Enable Smooth Shading glClearColor(0.0f, 0.0f, 0.0f, 0.5f); // Black Background glClearDepth(1.0f); // Depth Buffer Setup glEnable(GL_DEPTH_TEST); // Enables Depth Testing glDepthFunc(GL_LEQUAL); // The Type Of Depth Testing To Do glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // Really Nice Perspective Calculations TexturesList.Sky = LoadTexture("Images/Sky-Seamless.jpg", IsMipmap); TexturesList.Grass = LoadTexture("Images/Grass.jpg", IsMipmap); TexturesList.Wood = LoadTexture("Images/Wood.jpg", IsMipmap); TexturesList.Coin = LoadTexture("Images/Coin.jpg", IsMipmap); TexturesList.SnakeHead = LoadTexture("Images/SnakeHead.jpg", IsMipmap); TexturesList.SnakeBody = LoadTexture("Images/SnakeBody.png", IsMipmap); TexturesList.Water = LoadTexture("Images/Water.jpg", IsMipmap); int index = glGenLists(3); Objects.Obstacle = index; Objects.Coin = index + 1; Objects.Tile = index + 2; #pragma region Obstacle glNewList(Objects.Obstacle, GL_COMPILE); glPushMatrix(); // Top glBindTexture(GL_TEXTURE_2D, TexturesList.Wood); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3d(0, TILESIZE, TILESIZE); glTexCoord2f(1, 0); glVertex3d(0, TILESIZE, 0); glTexCoord2f(1, 1); glVertex3d(TILESIZE, TILESIZE, 0); glTexCoord2f(0, 1); glVertex3d(TILESIZE, TILESIZE, TILESIZE); glEnd(); // Bottom glBindTexture(GL_TEXTURE_2D, TexturesList.Wood); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3d(0, 0, TILESIZE); glTexCoord2f(1, 0); glVertex3d(0, 0, 0); glTexCoord2f(1, 1); glVertex3d(TILESIZE, 0, 0); glTexCoord2f(0, 1); glVertex3d(TILESIZE, 0, TILESIZE); glEnd(); // Left glBindTexture(GL_TEXTURE_2D, TexturesList.Wood); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(0, 0, TILESIZE); glTexCoord2f(1, 1); glVertex3d(0, 0, 0); glTexCoord2f(1, 0); glVertex3d(0, TILESIZE, 0); glTexCoord2f(0, 0); glVertex3d(0, TILESIZE, TILESIZE); glEnd(); // Right glBindTexture(GL_TEXTURE_2D, TexturesList.Wood); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(TILESIZE, 0, TILESIZE); glTexCoord2f(1, 1); glVertex3d(TILESIZE, 0, 0); glTexCoord2f(1, 0); glVertex3d(TILESIZE, TILESIZE, 0); glTexCoord2f(0, 0); glVertex3d(TILESIZE, TILESIZE, TILESIZE); glEnd(); // Front glBindTexture(GL_TEXTURE_2D, TexturesList.Wood); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(0, 0, TILESIZE); glTexCoord2f(1, 1); glVertex3d(TILESIZE, 0, TILESIZE); glTexCoord2f(1, 0); glVertex3d(TILESIZE, TILESIZE, TILESIZE); glTexCoord2f(0, 0); glVertex3d(0, TILESIZE, TILESIZE); glEnd(); // Back glBindTexture(GL_TEXTURE_2D, TexturesList.Wood); glBegin(GL_QUADS); glTexCoord2f(0, 1); glVertex3d(0, 0, 0); glTexCoord2f(1, 1); glVertex3d(TILESIZE, 0, 0); glTexCoord2f(1, 0); glVertex3d(TILESIZE, TILESIZE, 0); glTexCoord2f(0, 0); glVertex3d(0, TILESIZE, 0); glEnd(); glPopMatrix(); glEndList(); #pragma endregion #pragma region Coin glNewList(Objects.Coin, GL_COMPILE); glPushMatrix(); glTranslated(0, 0, 0); glBindTexture(GL_TEXTURE_2D, TexturesList.Coin); GLUquadric *coin = gluNewQuadric(); gluQuadricTexture(coin, true); gluDisk(coin, 0, 0.5, 100, 32); glPopMatrix(); glEndList(); #pragma endregion #pragma region Tile glNewList(Objects.Tile, GL_COMPILE); int step = 2; glPushMatrix(); glBegin(GL_QUADS); glTexCoord2f(0, 0); glVertex3i(0, 0, 0); glTexCoord2f(1, 0); glVertex3i(step, 0, 0); glTexCoord2f(1, 1); glVertex3i(step, 0, step); glTexCoord2f(0, 1); glVertex3i(0, 0, step); glEnd(); glPopMatrix(); glEndList(); #pragma endregion RotateCoin(0); GenerateRandomVector(); return true; // Initialization Went OK } void DrawGLScene(void) // Here's Where We Do All The Drawing { glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // Clear Screen And Depth Buffer glLoadIdentity(); // Reset The Current Modelview Matrix if (GameOver) { glDisable(GL_TEXTURE_2D); glPushMatrix(); GLPrint("GAME OVER. HIT 'R' TO TRY AGAIN", 0, 0, -1); glPopMatrix(); glEnable(GL_TEXTURE_2D); } if (GamePaused) { glDisable(GL_TEXTURE_2D); glPushMatrix(); GLPrint("PAUSED. PRESS 'P' TO RESUME", 0, 0, -1); glPopMatrix(); glEnable(GL_TEXTURE_2D); } if (HasWonGame) { glDisable(GL_TEXTURE_2D); glPushMatrix(); GLPrint("YOU WON. PRESS 'N' TO GO TO NEXT STAGE", 0, 0, -1); glPopMatrix(); glEnable(GL_TEXTURE_2D); IsMoving = false; IsRotating = false; } if (RemainingLives == 0) { StartFromTheBeginning = true; } glDisable(GL_TEXTURE_2D); char buffer[1024]; sprintf(buffer, "X: %d", X); GLPrint(buffer, -0.5, 0.38, -1); sprintf(buffer, "Z: %d", Z); GLPrint(buffer, -0.5, 0.35, -1); sprintf(buffer, "Theta: %lf", Theta); GLPrint(buffer, -0.5, 0.32, -1); sprintf(buffer, "Rotation Coefficient: %d", RotationCoefficient); GLPrint(buffer, -0.5, 0.29, -1); sprintf(buffer, "Is Rotating: %d", IsRotating); GLPrint(buffer, -0.5, 0.26, -1); sprintf(buffer, "Is Moving: %d", IsMoving); GLPrint(buffer, -0.5, 0.23, -1); sprintf(buffer, "Coin coordinates: X: %d, Z: %d", CoinCoordinates.X, CoinCoordinates.Z); GLPrint(buffer, -0.5, 0.20, -1); sprintf(buffer, "Score: %d", Score); GLPrint(buffer, -0.5, 0.17, -1); sprintf(buffer, "Remaining lives: %d", RemainingLives); GLPrint(buffer, -0.5, 0.14, -1); glEnable(GL_TEXTURE_2D); glPushMatrix(); SetInside(); // The following line is causing camera speed issues if (CameraPosition == 0) { gluLookAt(X, Y, Z, X + JUMP * cos(Theta), Y/* + sin(angle)*/, Z + JUMP * sin(Theta), 0, 1, 0); } else if (CameraPosition == 1) { gluLookAt(CurrentLevel * FLOORSIZE * 2, CurrentLevel * FLOORSIZE * 2, CurrentLevel * FLOORSIZE * 2, 0, 0, 0, 0, 1, 0); } else if (CameraPosition == 2) { gluLookAt(CurrentLevel * FLOORSIZE * 2, CurrentLevel * FLOORSIZE * 2, 0, 0, 0, CurrentLevel * FLOORSIZE * 2, 0, 1, 0); } else if (CameraPosition == 3) { gluLookAt(0, CurrentLevel * FLOORSIZE * 2, CurrentLevel * FLOORSIZE * 2, CurrentLevel * FLOORSIZE * 2, 0, 0, 0, 1, 0); } else if (CameraPosition == 4) { gluLookAt(0, CurrentLevel * FLOORSIZE * 2, 0, CurrentLevel * FLOORSIZE * 2, 0, CurrentLevel * FLOORSIZE * 2, 0, 1, 0); } else if (CameraPosition == 5) { gluLookAt(CurrentLevel * FLOORSIZE * 2, 50, CurrentLevel * FLOORSIZE * 2, CurrentLevel * FLOORSIZE / 2, 0, CurrentLevel * FLOORSIZE / 2, 0, 1, 0); } DrawSkybox(); if (ShouldGenerateLevel) { GenerateLevel(); } if (Score == CurrentLevel * 2) { HasWonGame = true; } if (RemainingLives == -1) { GameOver = true; } GenerateCoin(); UpdateSnake(); glPopMatrix(); glutSwapBuffers(); } int main(int argc, char** argv) { glutInit(&argc, argv); glutInitDisplayMode(GLUT_DOUBLE); // Use single display buffer. glutInitWindowSize(1024, 768); glutInitWindowPosition(0, 0); glutCreateWindow("CGL Project"); InitGL(); glutKeyboardFunc(Keyboard); glutSpecialFunc(SpecialKey); glutReshapeFunc(ReSizeGLScene); glutDisplayFunc(DrawGLScene); glutIdleFunc(Animate); glutMainLoop(); return 0; }
170f8bdfdd1882849f23a393d1294d18be4bed35
6f42dc25b776f2aa086e9f4edb616404e71faf2c
/resolution/界面源代码/DancingGuiSys.cpp
e91730c5a16ed3152367ed4c6b405be0c77bc5f6
[]
no_license
xuyunhan/Dancing
309abc8b469829fd6fc6bf697fb7e1901550e0d7
bc7ca2bc7aa869b136fac14e2a7a8912135a99ce
refs/heads/master
2021-01-01T18:48:30.726060
2013-10-12T07:57:11
2013-10-12T07:57:11
26,994,390
0
1
null
null
null
null
GB18030
C++
false
false
31,631
cpp
DancingGuiSys.cpp
#include "DancingGuiSys.h" DancingGuiSys::DancingGuiSys(void) { } DancingGuiSys::~DancingGuiSys(void) { } //这里传了两个参数,第二个参数是为了控制游戏退出 DancingGuiSys::DancingGuiSys(OgreBites::SdkTrayManager *sdktraymanager,Ogre::Root *mRoot) { this->mTrayMgr = sdktraymanager; this->mRoot = mRoot; //默认单人模式 m_gameStyle = 1; //默认卡通形象 m_roleStyle = 1; //默认状态 mCurrentWidgetType = BaseState; // this->ConfigGuiInfo(); } void DancingGuiSys::setGameStart() { this->mCurrentWidgetType = GameStart; //删除以往界面中的控件 vector<OgreBites::Widget *>::iterator tempIte = this->mWidget_vec.begin(); for (; tempIte != this->mWidget_vec.end(); ++tempIte) { this->mTrayMgr->destroyWidget(*tempIte); } //清空界面控件列表 mWidget_vec.clear(); //初始化一下必须的控件 //退出按钮 Button *quitGame = mTrayMgr->createButton(OgreBites::TL_NONE,"Quit",Ogre::DisplayString(L"退出游戏"),100); quitGame->getOverlayElement()->setPosition(900,550); this->mWidget_vec.push_back(quitGame); //返回重新设置游戏界面(这个按钮只有是在单机模式中才有) if(this->m_gameStyle == 1) { Button *setGame= mTrayMgr->createButton(OgreBites::TL_NONE,"SetGame",Ogre::DisplayString(L"返回"),100); setGame->getOverlayElement()->setPosition(900,600); this->mWidget_vec.push_back(setGame); } //返回重新选择房间界面(这个按钮只有是在局域网中才有) if(this->m_gameStyle == 2) { Button *selectHouse = mTrayMgr->createButton(OgreBites::TL_NONE,"SelectHouse",Ogre::DisplayString(L"返回"),100); selectHouse->getOverlayElement()->setPosition(900,600); this->mWidget_vec.push_back(selectHouse); } //游戏中对人物的其他控制放在DancingHandleSys类中,创建DancingHandleSys的对象 //DancingHandleSys *temp = new DancingHandleSys(); //。。。 } void DancingGuiSys::setWidgetBaseState() { this->mCurrentWidgetType = BaseState; //删除以往界面中的控件 vector<OgreBites::Widget *>::iterator tempIte = this->mWidget_vec.begin(); for (; tempIte != this->mWidget_vec.end(); ++tempIte) { this->mTrayMgr->destroyWidget(*tempIte); } //清空界面控件列表 mWidget_vec.clear(); //开始游戏按钮 OgreBites::Button *startGame = mTrayMgr->createButton(OgreBites::TL_NONE,"StartGame",Ogre::DisplayString(L"开始游戏"),100); startGame->getOverlayElement()->setDimensions(120,50); startGame->getOverlayElement()->setPosition(450,350); this->mWidget_vec.push_back(startGame); //startGame->getOverlayElement()->setp //退出按钮 OgreBites::Button *quitGame = mTrayMgr->createButton(OgreBites::TL_NONE,"QuitGame",Ogre::DisplayString(L"退出"),100); quitGame->getOverlayElement()->setDimensions(120,50); quitGame->getOverlayElement()->setPosition(450,410); this->mWidget_vec.push_back(quitGame); //关于我们 按钮 OgreBites::Button *aboutUs = mTrayMgr->createButton(OgreBites::TL_NONE,"AboutUs",Ogre::DisplayString(L"关于我们"),100); aboutUs->getOverlayElement()->setDimensions(120,50); aboutUs->getOverlayElement()->setPosition(450,470); this->mWidget_vec.push_back(aboutUs); } void DancingGuiSys::setWidgetCreateRole() { //设置当前状态 this->mCurrentWidgetType = CreateRole; //删除以往界面中的控件 vector<OgreBites::Widget *>::iterator tempIte = this->mWidget_vec.begin(); for (; tempIte != this->mWidget_vec.end(); ++tempIte) { this->mTrayMgr->destroyWidget(*tempIte); } //清空界面控件列表 mWidget_vec.clear(); //控制位置的变量 Ogre::Real left = 200; Ogre::Real top = 100; //局域网/单机模式的选择 singleBox = mTrayMgr->createCheckBox(OgreBites::TL_NONE,"Box_Single",Ogre::DisplayString(L"单机模式")); singleBox->getOverlayElement()->setDimensions(100,30); singleBox->getOverlayElement()->setPosition(850,10); this->mWidget_vec.push_back(singleBox); if(this->m_gameStyle == 1) singleBox->setChecked(true,false); multiBox = mTrayMgr->createCheckBox(OgreBites::TL_NONE,"Box_Multi",Ogre::DisplayString(L"局域网模式")); multiBox->getOverlayElement()->setDimensions(100,30); multiBox->getOverlayElement()->setPosition(850,50); this->mWidget_vec.push_back(multiBox); if(this->m_gameStyle == 2) multiBox->setChecked(true,false); //昵称标签 OgreBites::Label *lname = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Name",Ogre::DisplayString(L"昵称"),50); lname->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(lname); left += 50; //250,90 //输入昵称文本框 //这里的文本框没有实现输入 OgreBites::TextBox *tname = mTrayMgr->createTextBox(OgreBites::TL_NONE,"T_Name",Ogre::DisplayString(L"请输入"),180,50); tname->getOverlayElement()->setPosition(left,top); tname->setText(Ogre::DisplayString(L"请输入你的昵称")); this->mWidget_vec.push_back(tname); left -= 50; top += 60;//200,150 //性别标签 OgreBites::Label *lsex = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Sex",Ogre::DisplayString(L"性别"),50); lsex->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(lsex); left += 50;//250,150 //性别checkbox maleBox = mTrayMgr->createCheckBox(OgreBites::TL_NONE,"C_SexM",Ogre::DisplayString(L"男"),60); maleBox->getOverlayElement()->setPosition(left,top); maleBox->setChecked(true,false); this->mWidget_vec.push_back(maleBox); left += 120;//370,150 femaleBox = mTrayMgr->createCheckBox(OgreBites::TL_NONE,"C_SexF",Ogre::DisplayString(L"女"),60); femaleBox->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(femaleBox); left -= 170; top += 60;//200,210 //发型标签 OgreBites::Label *lhair = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Hair",Ogre::DisplayString(L"发型"),50); lhair->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(lhair); left += 50;//250,210 //发型下拉框 Ogre::StringVector hairstyle; hairstyle.push_back(Ogre::DisplayString(L"短发")); hairstyle.push_back(Ogre::DisplayString(L"中分")); OgreBites::SelectMenu *shair = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_Hair",Ogre::DisplayString(L"请选择"),180,10,hairstyle); shair->getOverlayElement()->setHeight(50); shair->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(shair); left -= 50; top += 60;//200,270 //配饰 OgreBites::Label *lrings = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Rings",Ogre::DisplayString(L"配饰"),50); lrings->getOverlayElement()->setPosition(left,top); left += 50;//250,270 this->mWidget_vec.push_back(lrings); //配饰下拉框 Ogre::StringVector ringstyle; ringstyle.push_back(Ogre::DisplayString(L"耳环")); ringstyle.push_back(Ogre::DisplayString(L"耳钉")); OgreBites::SelectMenu *srings = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_Rings",Ogre::DisplayString(L"请选择"),180,10,ringstyle); srings->getOverlayElement()->setHeight(50); srings->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(srings); left -= 50; top += 60;//200,330 //上装 OgreBites::Label *lshangzhuang = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Shangzhuang",Ogre::DisplayString(L"上装"),50); lshangzhuang->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(lshangzhuang); left += 50;//250,330 //上装 Ogre::StringVector shangstyle; shangstyle.push_back(Ogre::DisplayString(L"衬衫")); shangstyle.push_back(Ogre::DisplayString(L"T恤")); OgreBites::SelectMenu *shangzhuang = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_Shangzhuang",Ogre::DisplayString(L"请选择"),180,10,shangstyle); shangzhuang->getOverlayElement()->setHeight(50); shangzhuang->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(shangzhuang); left -= 50; top += 60;//200,390 //从下面开始,下拉列表不能再显示中文了,我尝试在上装选项中多加几项,加多了显示中文的项也会报错,是不是内存不够? //下装 OgreBites::Label *lxiazhuang = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Xiazhuang",Ogre::DisplayString(L"下装"),50); lxiazhuang->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(lxiazhuang); left += 50;//250,330 //下装 Ogre::StringVector xiastyle; xiastyle.push_back(Ogre::DisplayString(L"mini-Skirt")); xiastyle.push_back(Ogre::DisplayString(L"Boshimiya-Skirt")); OgreBites::SelectMenu *xiazhuang = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_Xiazhuang",Ogre::DisplayString(L"请选择"),180,10,xiastyle); xiazhuang->getOverlayElement()->setHeight(50); xiazhuang->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(xiazhuang); left -= 50; top += 60;//200,390 //鞋子 Label *lshoes = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Shoes",Ogre::DisplayString(L"鞋子"),50); lshoes->getOverlayElement()->setPosition(left,top); left += 50;//250,450 this->mWidget_vec.push_back(lshoes); Ogre::StringVector shoestyle; shoestyle.push_back(Ogre::DisplayString(L"song")); shoestyle.push_back(Ogre::DisplayString(L"gao")); OgreBites::SelectMenu *sshoes = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_Shoes",Ogre::DisplayString(L"请选择"),180,10,shoestyle); sshoes->getOverlayElement()->setHeight(50); sshoes->getOverlayElement()->setPosition(left,top); left -= 50; top += 60;//200,510 this->mWidget_vec.push_back(sshoes); //显示当前形象标签 OgreBites::Label *showImage = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_ShowImage",Ogre::DisplayString(L"当前形象"),100); showImage->getOverlayElement()->setPosition(630,100); this->mWidget_vec.push_back(showImage); //显示形象空间 OgreBites::Label *image = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_Image",""); image->getOverlayElement()->setDimensions(210,350); image->getOverlayElement()->setPosition(580,130); this->mWidget_vec.push_back(image); //实时建模和卡通形象 role_cartoon = mTrayMgr->createCheckBox(OgreBites::TL_NONE,"Cartoon_Role",Ogre::DisplayString(L"卡通形象"),100); this->mWidget_vec.push_back(role_cartoon); role_cartoon->getOverlayElement()->setPosition(560,500); if(this->m_roleStyle == 1) role_cartoon->setChecked(true,false); role_real = mTrayMgr->createCheckBox(OgreBites::TL_NONE,"Real_Role",Ogre::DisplayString(L"实时建模"),100); this->mWidget_vec.push_back(role_real); role_real->getOverlayElement()->setPosition(700,500); if(this->m_roleStyle == 2) role_real->setChecked(true,false); //创建角色 按钮 OgreBites::Button *createRole = mTrayMgr->createButton(OgreBites::TL_NONE,"createRole",Ogre::DisplayString(L"创建角色"),100); createRole->getOverlayElement()->setDimensions(100,50); createRole->getOverlayElement()->setPosition(350,570); this->mWidget_vec.push_back(createRole); //直接开始游戏按钮 OgreBites::Button *startGame = mTrayMgr->createButton(OgreBites::TL_NONE,"StartGame_role",Ogre::DisplayString(L"开始游戏"),100); startGame->getOverlayElement()->setDimensions(100,50); startGame->getOverlayElement()->setPosition(470,570); this->mWidget_vec.push_back(startGame); //startGame->getOverlayElement()->setp //退出按钮 OgreBites::Button *quitGame = mTrayMgr->createButton(OgreBites::TL_NONE,"QuitGame_role",Ogre::DisplayString(L"退出"),100); quitGame->getOverlayElement()->setDimensions(100,50); quitGame->getOverlayElement()->setPosition(590,570); this->mWidget_vec.push_back(quitGame); //其他控件 }//startgame createhouse createrole gameset housed void DancingGuiSys::setWidgetGameSet() { this->mCurrentWidgetType = GameSet; //删除以往界面中的控件 vector<OgreBites::Widget *>::iterator tempIte = this->mWidget_vec.begin(); for (; tempIte != this->mWidget_vec.end(); ++tempIte) { this->mTrayMgr->destroyWidget(*tempIte); } //清空界面控件列表 mWidget_vec.clear(); //舞种 Label *l_danceStyle = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceStyle",Ogre::DisplayString(L"舞种")); l_danceStyle->getOverlayElement()->setDimensions(100,50); l_danceStyle->getOverlayElement()->setPosition(400,120); this->mWidget_vec.push_back(l_danceStyle); Ogre::StringVector danceStyle; danceStyle.push_back(Ogre::DisplayString(L"Latin")); danceStyle.push_back(Ogre::DisplayString(L"QiaQia")); SelectMenu *s_danceStyle = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_DanceStyle",Ogre::DisplayString(L"请选择"),180,10,danceStyle); s_danceStyle->getOverlayElement()->setDimensions(180,50); s_danceStyle->getOverlayElement()->setPosition(505,110); this->mWidget_vec.push_back(s_danceStyle); //从这开始,下面的下拉列表点击没反应了! //舞曲 Label *l_danceSong = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceSong",Ogre::DisplayString(L"舞曲")); l_danceSong->getOverlayElement()->setDimensions(100,50); l_danceSong->getOverlayElement()->setPosition(400,200); this->mWidget_vec.push_back(l_danceSong); Ogre::StringVector danceSong; danceStyle.push_back(Ogre::DisplayString("SanFrancisco")); danceStyle.push_back(Ogre::DisplayString("Young For You")); SelectMenu *s_danceSong = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_DanceSong",Ogre::DisplayString(L"请选择"),180,10,danceSong); s_danceSong->getOverlayElement()->setDimensions(180,50); s_danceSong->getOverlayElement()->setPosition(505,190); this->mWidget_vec.push_back(s_danceSong); //场景 Label *l_danceScence= mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceScence",Ogre::DisplayString(L"场景")); l_danceScence->getOverlayElement()->setDimensions(100,50); l_danceScence->getOverlayElement()->setPosition(400,280); this->mWidget_vec.push_back(l_danceScence); Ogre::StringVector danceScence; danceStyle.push_back(Ogre::DisplayString("Sea")); danceStyle.push_back(Ogre::DisplayString("Road")); SelectMenu *s_danceScence = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_DanceScence",Ogre::DisplayString(L"请选择"),180,10,danceScence); s_danceScence->getOverlayElement()->setDimensions(180,50); s_danceScence->getOverlayElement()->setPosition(505,270); this->mWidget_vec.push_back(s_danceScence); //场景预览 Label *l_danceView= mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceView",Ogre::DisplayString(L"场景预览")); l_danceView->getOverlayElement()->setDimensions(100,50); l_danceView->getOverlayElement()->setPosition(502,350); this->mWidget_vec.push_back(l_danceView); OgreBites::Label *l_danceimage = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceImage",""); l_danceimage->getOverlayElement()->setColour(Ogre::ColourValue(125,125,125)); l_danceimage->getOverlayElement()->setDimensions(200,200); l_danceimage->getOverlayElement()->setPosition(450,400); l_danceimage->show(); this->mWidget_vec.push_back(l_danceimage); //修改角色按钮 OgreBites::Button *corectRole = mTrayMgr->createButton(OgreBites::TL_NONE,"CorectRole_GameSet",Ogre::DisplayString(L"修改角色"),100); corectRole->getOverlayElement()->setDimensions(100,50); corectRole->getOverlayElement()->setPosition(370,620); this->mWidget_vec.push_back(corectRole); //直接开始游戏按钮 OgreBites::Button *startGame = mTrayMgr->createButton(OgreBites::TL_NONE,"StartGame_GameSet",Ogre::DisplayString(L"开始游戏"),100); startGame->getOverlayElement()->setDimensions(100,50); startGame->getOverlayElement()->setPosition(490,620); this->mWidget_vec.push_back(startGame); //startGame->getOverlayElement()->setp //退出按钮 OgreBites::Button *quitGame = mTrayMgr->createButton(OgreBites::TL_NONE,"QuitGame_GameSet",Ogre::DisplayString(L"退出"),100); quitGame->getOverlayElement()->setDimensions(100,50); quitGame->getOverlayElement()->setPosition(610,620); this->mWidget_vec.push_back(quitGame); } void DancingGuiSys::setWidgetCreateHouse() { this->mCurrentWidgetType = CreateHouse; vector<OgreBites::Widget *>::iterator tempIte = this->mWidget_vec.begin(); for (; tempIte != this->mWidget_vec.end(); ++tempIte) { this->mTrayMgr->destroyWidget(*tempIte); } mWidget_vec.clear(); //房间名 Label *houseName = mTrayMgr->createLabel(OgreBites::TL_NONE,"HouseName",Ogre::DisplayString(L"房间名称"),100); this->mWidget_vec.push_back(houseName); houseName->getOverlayElement()->setDimensions(120,30); houseName->getOverlayElement()->setPosition(90,140); //舞曲类型 Label *danceStyle = mTrayMgr->createLabel(OgreBites::TL_NONE,"DanceStyle",Ogre::DisplayString(L"游戏舞种"),100); this->mWidget_vec.push_back(danceStyle); danceStyle->getOverlayElement()->setDimensions(120,30); danceStyle->getOverlayElement()->setPosition(210,140); //剩余座位 Label *leftSeats = mTrayMgr->createLabel(OgreBites::TL_NONE,"LeftSeats",Ogre::DisplayString(L"剩余座位"),100); this->mWidget_vec.push_back(leftSeats); leftSeats->getOverlayElement()->setDimensions(120,30); leftSeats->getOverlayElement()->setPosition(330,140); //14个显示房间的标签的名称 Ogre::StringVector labelString; labelString.push_back("house_1"); labelString.push_back("house_2"); labelString.push_back("house_3"); labelString.push_back("house_4"); labelString.push_back("house_5"); labelString.push_back("house_6"); labelString.push_back("house_7"); labelString.push_back("house_8"); labelString.push_back("house_9"); labelString.push_back("house_10"); labelString.push_back("house_11"); labelString.push_back("house_12"); labelString.push_back("house_13"); labelString.push_back("house_14"); //临时的vector容器用来存储14个显示房间的标签 std::vector<OgreBites::Label *> mLabel_vec; Ogre::Real pTop = 170; for(int i = 0;i < 14;i++) { //把14个标签用来显示房间的信息 mLabel_vec.push_back(mTrayMgr->createLabel(OgreBites::TL_NONE,labelString[i],"",360)); mLabel_vec[i]->getOverlayElement()->setDimensions(360,30); mLabel_vec[i]->getOverlayElement()->setPosition(90,pTop); pTop += 30; this->mWidget_vec.push_back(mLabel_vec[i]); } //竖直线划分区域 OgreBites::Separator *cutSeparator = mTrayMgr->createSeparator(OgreBites::TL_NONE,"Se_Cut",3); cutSeparator->getOverlayElement()->setHeight(450); cutSeparator->getOverlayElement()->setPosition(500,140); this->mWidget_vec.push_back(cutSeparator); //创建新的房间 //标签 Label *creatNew = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_CreatNew",Ogre::DisplayString(L"创建新房间"),120); creatNew->getOverlayElement()->setDimensions(120,30); creatNew->getOverlayElement()->setPosition(550,140); this->mWidget_vec.push_back(creatNew); //用来记录位置的变量 Ogre::Real left,top; left = 600; top = 180; //房间名称标签 Label *l_roomName = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_RoomName",Ogre::DisplayString(L"房间名称"),120); l_roomName->getOverlayElement()->setDimensions(120,30); l_roomName->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(l_roomName); top -= 10; left += 120;//left 670,top 130 //房间名称输入框 OgreBites::TextBox *t_roomName = mTrayMgr->createTextBox(OgreBites::TL_NONE,"T_RoomName",Ogre::DisplayString(L"请输入房间名称"),200,50); t_roomName->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(t_roomName); left -= 120; top += 70;//left 550,top 180 //舞种 //标签 Label *l_danceStyle = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceStyle",Ogre::DisplayString(L"舞种选择"),120); l_danceStyle->getOverlayElement()->setDimensions(120,30); l_danceStyle->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(l_danceStyle); left += 120; top -= 10;//left 670,top 170 //下拉列表 Ogre::StringVector v_danceStyle; v_danceStyle.push_back("Latin"); v_danceStyle.push_back("QiaQia"); OgreBites::SelectMenu *s_danceStyle = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_DanceStyle",Ogre::DisplayString(L"舞种选择"),200,5,v_danceStyle); s_danceStyle->getOverlayElement()->setDimensions(200,50); s_danceStyle->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(s_danceStyle); left -= 120; top += 70;//left 550,top 220 //舞曲 //标签 Label *l_danceSong = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceSong",Ogre::DisplayString(L"舞曲选择"),120); l_danceSong->getOverlayElement()->setDimensions(120,30); l_danceSong->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(l_danceSong); left += 120; top -= 10;//left 670,top 210 //下拉列表 Ogre::StringVector v_danceSong; v_danceSong.push_back("pretty"); v_danceSong.push_back("lalala"); OgreBites::SelectMenu *s_danceSong = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_DanceSong",Ogre::DisplayString(L"舞曲选择"),200,5,v_danceSong); s_danceSong->getOverlayElement()->setDimensions(200,50); s_danceSong->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(s_danceSong); left -= 120; top += 70;//left 550,top 260 //场景 //标签 Label *l_danceScence = mTrayMgr->createLabel(OgreBites::TL_NONE,"L_DanceScence",Ogre::DisplayString(L"场景选择"),120); l_danceScence->getOverlayElement()->setDimensions(120,30); l_danceScence->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(l_danceScence); left += 120; top -= 10;//left 670,top 250 //下拉列表 Ogre::StringVector v_danceScence; v_danceScence.push_back("seaside"); v_danceScence.push_back("roadway"); OgreBites::SelectMenu *s_danceScence = mTrayMgr->createThickSelectMenu(OgreBites::TL_NONE,"S_DanceScence",Ogre::DisplayString(L"场景选择"),200,5,v_danceScence); s_danceScence->getOverlayElement()->setDimensions(200,50); s_danceScence->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(s_danceScence); top += 50;//left 670,top 300 //场景预览 OgreBites::Label *l_danceimage = mTrayMgr->createLabel(OgreBites::TL_NONE,"DanceImage",""); l_danceimage->getOverlayElement()->setColour(Ogre::ColourValue(125,125,125)); l_danceimage->getOverlayElement()->setDimensions(200,200); l_danceimage->getOverlayElement()->setPosition(left,top); this->mWidget_vec.push_back(l_danceimage); //修改角色按钮 OgreBites::Button *corectRole = mTrayMgr->createButton(OgreBites::TL_NONE,"CorectRole_CreateHouse",Ogre::DisplayString(L"修改角色"),100); corectRole->getOverlayElement()->setDimensions(100,50); corectRole->getOverlayElement()->setPosition(370,620); this->mWidget_vec.push_back(corectRole); //直接开始游戏按钮 OgreBites::Button *startGame = mTrayMgr->createButton(OgreBites::TL_NONE,"StartGame_CreateHouse",Ogre::DisplayString(L"开始游戏"),100); startGame->getOverlayElement()->setDimensions(100,50); startGame->getOverlayElement()->setPosition(490,620); this->mWidget_vec.push_back(startGame); //startGame->getOverlayElement()->setp //退出按钮 OgreBites::Button *quitGame = mTrayMgr->createButton(OgreBites::TL_NONE,"QuitGame_CreateHouse",Ogre::DisplayString(L"退出"),100); quitGame->getOverlayElement()->setDimensions(100,50); quitGame->getOverlayElement()->setPosition(610,620); quitGame->getOverlayElement()->setColour(Ogre::ColourValue(145,223,100)); this->mWidget_vec.push_back(quitGame); }//startgame createhouse createrole gameset housed //我把进入房间等待的那个界面删除了,用户建好房间或者设置好游戏选项后,应该直接进入跳舞的那个界面等待更好 /*void DancingGuiSys::setWidgetHoused() { this->mCurrentWidgetType = Housed; //删除以往界面中的控件 vector<OgreBites::Widget *>::iterator tempIte = this->mWidget_vec.begin(); for (; tempIte != this->mWidget_vec.end(); ++tempIte) { this->mTrayMgr->destroyWidget(*tempIte); } //清空界面控件列表 mWidget_vec.clear(); //8个座位标签 Ogre::StringVector seatName; seatName.push_back("seat_1"); seatName.push_back("seat_2"); seatName.push_back("seat_3"); seatName.push_back("seat_4"); seatName.push_back("seat_5"); seatName.push_back("seat_6"); seatName.push_back("seat_7"); seatName.push_back("seat_8"); //存储标签上显示的容器 Ogre::StringVector seatString; seatString.push_back("1"); seatString.push_back("2"); seatString.push_back("3"); seatString.push_back("4"); seatString.push_back("5"); seatString.push_back("6"); seatString.push_back("7"); seatString.push_back("8"); //临时的vector容器用来存储8个显示为座位的标签 std::vector<OgreBites::Label *> mLabel_vec; Ogre::Real pTop = 150; Ogre::Real pLeft = 80; for(int i = 0;i < 4;i++) { mLabel_vec.push_back(mTrayMgr->createLabel(OgreBites::TL_NONE,seatName[i],seatString[i],360)); mLabel_vec[i]->getOverlayElement()->setDimensions(120,170); mLabel_vec[i]->getOverlayElement()->setPosition(pLeft,pTop); pLeft += 150; this->mWidget_vec.push_back(mLabel_vec[i]); } pTop += 190; pLeft = 80; for(int i = 4;i < 8;i++) { mLabel_vec.push_back(mTrayMgr->createLabel(OgreBites::TL_NONE,seatString[i],seatString[i],360)); mLabel_vec[i]->getOverlayElement()->setDimensions(120,170); mLabel_vec[i]->getOverlayElement()->setPosition(pLeft,pTop); pLeft += 150; this->mWidget_vec.push_back(mLabel_vec[i]); } }*/ WidgetType DancingGuiSys::getCurrentWidgetType() { return this->mCurrentWidgetType; } void DancingGuiSys::setCurrentWidgetType() { } void DancingGuiSys::buttonHit(Button *button) { if(button == NULL) return; Ogre::String btnName = button->getName(); //对所有“退出”和“关于我们”的按钮进行特殊处理,其余利用map关联查找 if(btnName == Ogre::String("Quit") || btnName == Ogre::String("QuitGame_CreateHouse") || btnName == Ogre::String("QuitGame") || btnName == Ogre::String("QuitGame_role") ||btnName == Ogre::String("QuitGame_GameSet")) { mRoot->queueEndRendering(); } else if(btnName == Ogre::String("AboutUs")) { mTrayMgr->showOkDialog(Ogre::DisplayString(L"关于我们"),"Xi'an Universty of Science and Techonology 2013-3"); //TextBox *aboutBox = mTrayMgr->createTextBox(OgreBites::TL_CENTER,"Info_AboutUs",Ogre::DisplayString(L"关于我们"),300,300); //aboutBox->setText(Ogre::DisplayString(L"Xi'an University of Science and Techonology 2013-3")); } else { mMap.clear(); this->ConfigGuiInfo(); mPair.first = this->mCurrentWidgetType; mPair.second = btnName; functionPoint temp = this->mMap[mPair]; (this->*temp)(); } } void DancingGuiSys::itemSelected(SelectMenu *menu) { } void DancingGuiSys::labelHit(Label *label) { } void DancingGuiSys::sliderMoved(Slider *slider) { } void DancingGuiSys::checkBoxToggled(CheckBox *box) { if(box == NULL) return; Ogre::String boxName = box->getName(); //box->setChecked(true); //对checkbox进行判断,实现两者中只能点击一个 if(boxName == Ogre::String("Box_Single")) { //设置为单机模式 this->m_gameStyle = 1; if(box->isChecked()) this->multiBox->setChecked(false,false); } else if(boxName == Ogre::String("Box_Multi")) { //设置为局域网模式 this->m_gameStyle = 2; if(box->isChecked()) this->singleBox->setChecked(false,false); } else if(boxName == Ogre::String("C_SexM")) { //待处理 //处理显示男生形象,函数尚未添加 if(box->isChecked()) this->femaleBox->setChecked(false,false); } else if(boxName == Ogre::String("C_SexF")) { //待处理 //处理显示女生形象,函数尚未添加 if(box->isChecked()) this->maleBox->setChecked(false,false); } else if(boxName == Ogre::String("Cartoon_Role")) { this->m_roleStyle = 1; //处理卡通形象 if(box->isChecked()) { this->role_real->setChecked(false,false); //this->setWidgetCreateRole(); //对应的操作 } } else if(boxName == Ogre::String("Real_Role")) { this->m_roleStyle = 2; //处理实时建模 if(box->isChecked()) { //对应的操作 this->setRealRoleValue(); this->role_cartoon->setChecked(false,false); //this->setWidgetCreateRole(); } } } void DancingGuiSys::setRealRoleValue() { mTrayMgr->showOkDialog("Role_Build","Certain you camera is on And put your face right before your camera"); //改变现实的形象 //。。。 } void DancingGuiSys::okDialogClosed(const Ogre::DisplayString &message) { } void DancingGuiSys::yesNoDialogClosed(const Ogre::DisplayString &question, bool yesHit) { } void DancingGuiSys::ConfigGuiInfo() { //startgame createhouse createrole gameset housed //单机和局域网共有的 mPair.first = CreateRole; mPair.second = "StartGame_role"; this->mMap[mPair] = &DancingGuiSys::setGameStart; //单人模式下引导界面跳转 if(m_gameStyle == 1) { //最开始运行程序时的界面 mPair.first = BaseState; mPair.second = "StartGame"; //点击开始按钮后自动切换到创建角色界面 this->mMap[mPair] = &DancingGuiSys::setWidgetCreateRole; //角色创建完毕后,点击创建角色,跳转到游戏设定 mPair.first = CreateRole; mPair.second = "createRole"; this->mMap[mPair] = &DancingGuiSys::setWidgetGameSet; //游戏设定也结束后,这里还要添加返回上一步的判断切换 mPair.first = GameSet; mPair.second = "CorectRole_GameSet"; this->mMap[mPair] = &DancingGuiSys::setWidgetCreateRole; //设置游戏界面-->游戏开始界面 mPair.first = GameSet; mPair.second = "StartGame_GameSet"; this->mMap[mPair] = &DancingGuiSys::setGameStart; //游戏开始界面-->设置游戏界面 mPair.first = GameStart; mPair.second = "SetGame"; this->mMap[mPair] = &DancingGuiSys::setWidgetGameSet; } else if(m_gameStyle == 2) { //局域网时界面跳转 //创建角色跳转到创建房间和选择房间界面 mPair.first = CreateRole; mPair.second = "createRole"; this->mMap[mPair] = &DancingGuiSys::setWidgetCreateHouse; //由创建房间和选择房间的界面跳转回创建角色界面 mPair.first = CreateHouse; mPair.second = "CorectRole_CreateHouse"; this->mMap[mPair] = &DancingGuiSys::setWidgetCreateRole; //////////////////////////////////////////////////// //对应的真正进入游戏的界面 //在创建好房间后直接点击开始游戏进入的是游戏开始的界面中 mPair.first = CreateHouse; mPair.second = "StartGame_CreateHouse"; this->mMap[mPair] = &DancingGuiSys::setGameStart; //游戏开始界面-->选择或创建房间界面 mPair.first = GameStart; mPair.second = "SelectHouse"; this->mMap[mPair] = &DancingGuiSys::setWidgetCreateHouse; } }
03a6dcaadc2c3802785859da950bf8917b2f48a6
2a1e57d2f4588ab79e61dd9764175c1aefe09f63
/libraries/libsystem/io/FileWriter.cpp
b951cc866125f8d64c9afabb03ca4d86c3d8fd1e
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause", "MIT", "Zlib" ]
permissive
Rix565/skiftos-dailybuild
790157bfd9864d8ef5793ded2be5a5e4eb2ad8be
ef3abf0dda028b6d7b3e658946a031b1a1ba44c9
refs/heads/main
2023-04-09T01:08:19.999464
2021-03-22T18:30:53
2021-03-22T18:30:53
349,983,191
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
FileWriter.cpp
#include <libsystem/io/FileWriter.h> FileWriter::FileWriter(const char *path) : _handle{make<IO::Handle>(path, OPEN_WRITE | OPEN_CREATE | OPEN_STREAM)} { } FileWriter::FileWriter(Path &path) : _handle{make<IO::Handle>(path.string(), OPEN_WRITE | OPEN_CREATE | OPEN_STREAM)} { } FileWriter::FileWriter(RefPtr<IO::Handle> handle) : _handle{handle} { } void FileWriter::flush() {} size_t FileWriter::write(const void *buffer, size_t size) { return _handle->write(buffer, size).value_or_default(0); } size_t FileWriter::length() { auto result_or_stat = _handle->stat(); if (result_or_stat.success()) { return result_or_stat.value().size; } else { return 0; } } size_t FileWriter::position() { return _handle->tell().value_or_default(0); }
13e76c90e728b9a320c19d9e425f8a8c1a489f10
15443ae4d47b1433c7c2cfb610ea8b714bcbad01
/VstNoiseGate/AudioLib/Transfer.h
a948ce083e4d1e83ce4445fe238c1fdea906e0d6
[]
no_license
ValdemarOrn/NoiseInvaderVST
d0fc77cdc292c599ce4e0264bec536a9447c166e
0ec170a71a88e2ea3fa9e86b5e5623d4aa0839a7
refs/heads/master
2022-06-29T21:41:22.368301
2022-06-07T23:43:34
2022-06-07T23:43:34
49,460,806
21
6
null
null
null
null
UTF-8
C++
false
false
1,086
h
Transfer.h
#pragma once #include <vector> using namespace std; // UNTESTED BUT SHOULD WORK namespace AudioLib { class Transfer { private: vector<double> b; vector<double> a; double bufIn[64]; double bufOut[64]; double Gain; // buffer size int modulo = 64; int index = 0; public: Transfer() { SetB(vector<double> { 1.0 }); SetA(vector<double> { 1.0 }); } int GetOrder() { return (b.size() > a.size()) ? b.size() - 1 : a.size() - 1; } void SetB(vector<double> b) { this->b = b; } void SetA(vector<double> a) { this->a = a; if (a[0] == 0.0) Gain = 0.0; else Gain = 1 / a[0]; } double Process(double input) { index = (index + 1) % modulo; bufIn[index] = input; bufOut[index] = 0; for (int j = 0; j < b.size(); j++) bufOut[index] += (b[j] * bufIn[((index - j) + modulo) % modulo]); for (int j = 1; j < a.size(); j++) bufOut[index] -= (a[j] * bufOut[((index - j) + modulo) % modulo]); bufOut[index] = bufOut[index] * Gain; auto output = bufOut[index]; return output; } }; }
c7dfd358725d1a9c7eb7cbe349b78f7eb6ea62f0
9b7ec74c5a72a57fd08110e740f3d112b7daa91c
/test_ui/main.cpp
63e41569df4b46b1d035bf422febe880035bb966
[]
no_license
Splendor-Qian/Qt_Projects
3af0c629e2e57433265747030ae19db4cb2b1218
0137a9b29b10ff73101ec621b114580a485556f6
refs/heads/master
2021-01-10T15:43:07.013934
2016-03-28T03:28:55
2016-03-28T03:28:55
54,563,579
0
0
null
2016-03-25T08:35:39
2016-03-23T13:52:35
C++
UTF-8
C++
false
false
242
cpp
main.cpp
#include "test_ui.h" #include <QtWidgets/QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); test_ui w; w.show(); //测试更改,看是否能同步到服务器,文件版本修改为UTF-8 return a.exec(); }
63d1d9a00b739fb90e9ecf0d413c78075f0c9b93
553a95013775c188c42772fd1ddee80629570e09
/include/ast/ReferenceType.h
3e100b6c9230dd0e28466ed8b6070c9b8980276e
[ "MIT" ]
permissive
rdtscp/c-bootstrap
0f755ed8ccce7dc2a7bcc7748eaec63921fe1fe1
2ce2d46f00b76f76a4f53b19281095b39aa4706b
refs/heads/master
2021-06-27T07:33:07.849937
2020-11-15T14:39:36
2020-11-15T14:39:36
153,897,052
12
1
null
2023-08-31T00:48:02
2018-10-20T11:06:32
C++
UTF-8
C++
false
false
1,536
h
ReferenceType.h
#pragma once #include "PrimitiveType.h" #include "Type.h" namespace ACC { class ReferenceType : public Type, public atl::enable_shared_from_this<ReferenceType> { public: atl::shared_ptr<Type> referencedType; ReferenceType(const atl::shared_ptr<Type> &p_referencedType); bool canCastTo(Type &rhs) const override; unsigned int getBytes() const override; bool equivalentTo(Type &rhs) const override; atl::string mangle() const override; bool operator==(Type &rhs) const override; bool operator!=(Type &rhs) const override; bool operator==(const ReferenceType &rhs) const; bool operator!=(const ReferenceType &rhs) const; atl::shared_ptr<ReferenceType> getptr() { return shared_from_this(); } atl::string astClass() const override { return "ReferenceType"; } static atl::shared_ptr<Type> collapseReferenceTypes(atl::shared_ptr<Type> type) { if (type->astClass() == "ReferenceType") { type = atl::static_pointer_cast<ReferenceType>(type)->referencedType; if (type->astClass() == "ReferenceType") type = atl::static_pointer_cast<ReferenceType>(type)->referencedType; } return type; } static Type &collapseReferenceTypes(Type *type) { if (type->astClass() == "ReferenceType") { type = static_cast<ReferenceType *>(type)->referencedType.get(); if (type->astClass() == "ReferenceType") type = static_cast<ReferenceType *>(type)->referencedType.get(); } return *type; } VISITOR_ACCEPTORS }; } // namespace ACC
d8e9dcc797fbf8f881649fa3994afc8a5954d0d9
371a5d35aae103828fe0cca2adb501717e60d85f
/WiFiScanner/WiFiScanner.ino
f6664ff8ebb3799384ddcbeb23966f7fcb987f08
[]
no_license
skittleson/ArduinoProjects
8db3c87bc4ffde8aef58cffc867eabfea0316f00
14c672f6313db9d52d6571f29f3141b6c8c197bd
refs/heads/master
2021-03-22T17:23:24.632932
2020-06-10T00:15:29
2020-06-10T00:15:29
247,387,002
0
0
null
null
null
null
UTF-8
C++
false
false
3,308
ino
WiFiScanner.ino
/* * This sketch demonstrates how to scan WiFi networks. * The API is almost the same as with the WiFi Shield library, * the most obvious difference being the different file you need to include: */ #include <ESP8266WiFi.h> //https://github.com/esp8266/Arduino //#include <EEPROM.h> #include "FS.h" #include <ArduinoJson.h> const char *store = "/wifi.json"; void setup() { Serial.begin(115200); // Set WiFi to station mode and disconnect from an AP if it was previously connected WiFi.mode(WIFI_STA); WiFi.disconnect(); delay(100); Serial.println("Setup done"); // File f = SPIFFS.open("/file.txt", "w"); // f.println("This is the first line "); // f.println("This is the second line "); // f.close(); // delay(1000); } void loop() { /* FSInfo fs_info; SPIFFS.info(fs_info); */ SPIFFS.begin(); StaticJsonDocument<1024> doc; if (SPIFFS.exists(store)) { File file = SPIFFS.open(store, "r"); deserializeJson(doc, file); Serial.println("From memory"); serializeJson(doc, Serial); Serial.println(""); file.close(); } doc["1"] = 1; // write to file File fileWrite = SPIFFS.open(store, "w"); serializeJson(doc, fileWrite); fileWrite.close(); SPIFFS.end(); //doc["2"] = 2; //doc["1"]["test"] = 1; // Serial.println("Now: "); // serializeJson(doc, Serial); //delay(1000); // File fileWrite = SPIFFS.open(store, "w"); // serializeJson(doc, fileWrite); // fileWrite.close(); // File f = SPIFFS.open("/file.txt", "r"); // while (f.available()) // { // String line = f.readStringUntil('\n'); // Serial.println(line); // } // f.close(); // delay(10 * 1000); Serial.println("scan start"); delay(50); // WiFi.scanNetworks will return the number of networks found int n = WiFi.scanNetworks(); Serial.println("scan done"); if (n == 0) { Serial.println("no networks found"); } else { Serial.print(n); Serial.println(" networks found"); for (int i = 0; i < n; ++i) { // Print SSID and RSSI for each network found Serial.print(i + 1); Serial.print(": "); Serial.print(WiFi.SSID(i)); Serial.print(" ("); Serial.print(WiFi.RSSI(i)); Serial.print(") "); Serial.print(WiFi.BSSIDstr(i)); Serial.print(" "); Serial.println(WiFi.encryptionType(i)); //Serial.println((WiFi.encryptionType(i) == WIFI_AUTH_OPEN) ? " " : "*"); delay(10); } } Serial.println(""); // Wait a bit before scanning again delay(60 * 1000); } void StoreData() { } // void writeString(int address, String data) // { // EEPROM.begin(512); // int stringSize = data.length(); // for (int i = 0; i < stringSize; i++) // { // EEPROM.write(address + i, data[i]); // } // EEPROM.write(address + stringSize, '\0'); //Add termination null character // EEPROM.end(); // } // String readString(int address) // { // const int memSize = 512; // EEPROM.begin(memSize); // char data[100]; //Max 100 Bytes // int len = 0; // unsigned char k; // k = EEPROM.read(address); // while (k != '\0' && len < memSize) //Read until null character // { // k = EEPROM.read(address + len); // data[len] = k; // len++; // } // data[len] = '\0'; // EEPROM.end(); // return String(data); // }
91416abb2f3de4745080058d133544951392ed7d
0eff74b05b60098333ad66cf801bdd93becc9ea4
/second/download/xgboost/xgboost-old-new/xgboost-old-new/dmlc_xgboost_patch_426.cpp
ca9f4762cb39ea55f503c62cfdaf7707882b8b6f
[]
no_license
niuxu18/logTracker-old
97543445ea7e414ed40bdc681239365d33418975
f2b060f13a0295387fe02187543db124916eb446
refs/heads/master
2021-09-13T21:39:37.686481
2017-12-11T03:36:34
2017-12-11T03:36:34
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,113
cpp
dmlc_xgboost_patch_426.cpp
@@ -86,6 +86,7 @@ namespace xgboost{ if (!strcmp(name, "silent")) silent = atoi(val); if (!strcmp(name, "eval_metric")) evaluator_.AddEval(val); if (!strcmp(name, "objective") ) name_obj_ = val; + if (!strcmp(name, "num_class") ) base_gbm.SetParam("num_booster_group", val ); mparam.SetParam(name, val); base_gbm.SetParam(name, val); cfg_.push_back( std::make_pair( std::string(name), std::string(val) ) ); @@ -95,7 +96,13 @@ namespace xgboost{ * this function is reserved for solver to allocate necessary space and do other preparation */ inline void InitTrainer(void){ - base_gbm.InitTrainer(); + if( mparam.num_class != 0 ){ + if( name_obj_ != "softmax" ){ + name_obj_ = "softmax"; + printf("auto select objective=softmax to support multi-class classification\n" ); + } + } + base_gbm.InitTrainer(); obj_ = CreateObjFunction( name_obj_.c_str() ); for( size_t i = 0; i < cfg_.size(); ++ i ){ obj_->SetParam( cfg_[i].first.c_str(), cfg_[i].second.c_str() ); @@ -166,9 +173,18 @@ namespace xgboost{ inline void UpdateOneIter(const DMatrix &train){ this->PredictRaw(preds_, train); obj_->GetGradient(preds_, train.info, base_gbm.NumBoosters(), grad_, hess_); - // do boost - std::vector<unsigned> root_index; - base_gbm.DoBoost(grad_, hess_, train.data, root_index); + if( grad_.size() == train.Size() ){ + base_gbm.DoBoost(grad_, hess_, train.data, train.info.root_index); + }else{ + int ngroup = base_gbm.NumBoosterGroup(); + utils::Assert( grad_.size() == train.Size() * (size_t)ngroup, "BUG: UpdateOneIter: mclass" ); + std::vector<float> tgrad( train.Size() ), thess( train.Size() ); + for( int g = 0; g < ngroup; ++ g ){ + memcpy( &tgrad[0], &grad_[g*tgrad.size()], sizeof(float)*tgrad.size() ); + memcpy( &thess[0], &hess_[g*tgrad.size()], sizeof(float)*tgrad.size() ); + base_gbm.DoBoost(tgrad, thess, train.data, train.info.root_index, g ); + } + } } /*! * \brief evaluate the model for specific iteration @@ -190,9 +206,14 @@ namespace xgboost{ fprintf(fo, "\n"); fflush(fo); } - /*! \brief get prediction, without buffering */ - inline void Predict(std::vector<float> &preds, const DMatrix &data){ - this->PredictRaw(preds,data); + /*! + * \brief get prediction + * \param storage to store prediction + * \param data input data + * \param bst_group booster group we are in + */ + inline void Predict(std::vector<float> &preds, const DMatrix &data, int bst_group = -1){ + this->PredictRaw( preds, data, bst_group ); obj_->PredTransform( preds ); } public: @@ -241,24 +262,32 @@ namespace xgboost{ base_gbm.InteractRePredict(data.data, j, buffer_offset + j); } } - private: /*! \brief get un-transformed prediction*/ - inline void PredictRaw(std::vector<float> &preds, const DMatrix &data){ - this->PredictBuffer(preds, data, this->FindBufferOffset(data) ); + inline void PredictRaw(std::vector<float> &preds, const DMatrix &data, int bst_group = -1 ){ + int buffer_offset = this->FindBufferOffset(data); + if( bst_group < 0 ){ + int ngroup = base_gbm.NumBoosterGroup(); + preds.resize( data.Size() * ngroup ); + for( int g = 0; g < ngroup; ++ g ){ + this->PredictBuffer(&preds[ data.Size() * g ], data, buffer_offset, g ); + } + }else{ + preds.resize( data.Size() ); + this->PredictBuffer(&preds[0], data, buffer_offset, bst_group ); + } } /*! \brief get the un-transformed predictions, given data */ - inline void PredictBuffer(std::vector<float> &preds, const DMatrix &data, int buffer_offset){ - preds.resize(data.Size()); + inline void PredictBuffer(float *preds, const DMatrix &data, int buffer_offset, int bst_group ){ const unsigned ndata = static_cast<unsigned>(data.Size()); if( buffer_offset >= 0 ){ #pragma omp parallel for schedule( static ) for (unsigned j = 0; j < ndata; ++j){ - preds[j] = mparam.base_score + base_gbm.Predict(data.data, j, buffer_offset + j); + preds[j] = mparam.base_score + base_gbm.Predict(data.data, j, buffer_offset + j, data.info.GetRoot(j), bst_group ); } }else #pragma omp parallel for schedule( static ) for (unsigned j = 0; j < ndata; ++j){ - preds[j] = mparam.base_score + base_gbm.Predict(data.data, j, -1); + preds[j] = mparam.base_score + base_gbm.Predict(data.data, j, -1, data.info.GetRoot(j), bst_group ); }{ } } @@ -270,14 +299,17 @@ namespace xgboost{ /* \brief type of loss function */ int loss_type; /* \brief number of features */ - int num_feature; + int num_feature; + /* \brief number of class, if it is multi-class classification */ + int num_class; /*! \brief reserved field */ - int reserved[16]; + int reserved[15]; /*! \brief constructor */ ModelParam(void){ base_score = 0.5f; loss_type = 0; num_feature = 0; + num_class = 0; memset(reserved, 0, sizeof(reserved)); } /*! @@ -288,6 +320,7 @@ namespace xgboost{ inline void SetParam(const char *name, const char *val){ if (!strcmp("base_score", name)) base_score = (float)atof(val); if (!strcmp("loss_type", name)) loss_type = atoi(val); + if (!strcmp("num_class", name)) num_class = atoi(val); if (!strcmp("bst:num_feature", name)) num_feature = atoi(val); } /*!
412e259ba8227a9a81f332144e52946dea1bf5a9
5419ec31b9aec07477ac45cb97ee3074fc6fba4c
/Helloworld/Classes/Scenes/CcbLeaderSkillEffLayer.h
975fa0ec8cae241d07ab8642aa948e84d319e3d3
[]
no_license
Relvin/RelvinPetTwo
59ceded93181f2d301f6d33e70367fb45906c9ba
1b7bc4677c2a9620a2008e0fa9a925d4a5ca1af5
refs/heads/master
2020-03-30T06:39:00.198117
2015-01-07T09:55:49
2015-01-07T09:55:49
28,892,826
0
0
null
null
null
null
UTF-8
C++
false
false
2,738
h
CcbLeaderSkillEffLayer.h
/** * Create by GenerateCppCodeFromCCBFile.lua * All right received * Author: Junie Chu * Date: 2014-03-17 20:52:52 */ #ifndef __CCBLEADERSKILLEFFLAYER__H__ #define __CCBLEADERSKILLEFFLAYER__H__ //CcbLeaderSkillEffLayer.h come from ccb/pet_battle_ani.ccb #include "cocos2d.h" #include "cocos-ext.h" #include "Defines.h" class CcbLeaderSkillEffLayer: public cocos2d::CCLayer, public cocos2d::extension::CCBMemberVariableAssigner , public cocos2d::extension::CCBSelectorResolver , public cocos2d::extension::CCNodeLoaderListener { public: // Constructor CcbLeaderSkillEffLayer() { m_pSpritePet = NULL; m_pLabelTTFSkillName = NULL; m_pLabelTTFSkillDes = NULL; } ~CcbLeaderSkillEffLayer(); // Create Method CCB_STATIC_NEW_AUTORELEASE_OBJECT_WITH_INIT_METHOD(CcbLeaderSkillEffLayer, create); // Inhert MemberVariableAssigner virtual bool onAssignCCBMemberVariable( cocos2d::CCObject* pTarget, const char* pMemberVariableName, cocos2d::CCNode* pNode ); virtual bool onAssignCCBCustomProperty( CCObject* pTarget, const char* pMemberVariableName, cocos2d::extension::CCBValue* pCCBValue ); // Inhert CCBSelectorResolver virtual cocos2d::SEL_CallFuncN onResolveCCBCCCallFuncSelector( cocos2d::CCObject * pTarget, const char* pSelectorName ); virtual cocos2d::extension::SEL_CCControlHandler onResolveCCBCCControlSelector( cocos2d::CCObject * pTarget, const char* pSelectorName ); virtual cocos2d::SEL_MenuHandler onResolveCCBCCMenuItemSelector( cocos2d::CCObject * pTarget, const char* pSelectorName ); // Inhert CCNodeLoaderListener virtual void onNodeLoaded(cocos2d::CCNode * pNode, cocos2d::extension::CCNodeLoader * pNodeLoader); private: int mCustomPropertyInt; float mCustomPropertyFloat; bool mCustomPropertyBoolean; std::string mCustomPropertyString; // Attributes for CCB cocos2d::CCSprite* m_pSpritePet; cocos2d::CCLabelTTF* m_pLabelTTFSkillName; cocos2d::CCLabelTTF* m_pLabelTTFSkillDes; public: // Virtual Functions virtual bool init(); virtual void onEnter(); virtual void onEnterTransitionDidFinish(); virtual void onExit(); virtual void onExitTransitionDidStart(); public: // Funcitons void loadData(); private: void removeSelf(cocos2d::CCNode* pNode); void playVoice(cocos2d::CCNode* pNode); }; class CcbLeaderSkillEffLayerLoader : public cocos2d::extension::CCLayerLoader { public: // 用于创建一个自身的实例,保存为一个CCLayerLoader。} CCB_STATIC_NEW_AUTORELEASE_OBJECT_METHOD(CcbLeaderSkillEffLayerLoader, loader); protected: // 用于创建一个类型为HelloCocosBuilderLayer的CCNode。} CCB_VIRTUAL_NEW_AUTORELEASE_CREATECCNODE_METHOD(CcbLeaderSkillEffLayer); }; #endif // __CCBLEADERSKILLEFFLAYER__H__
fbd2c46777273119bbf980cb8ad8f950048fce7a
6b2a8dd202fdce77c971c412717e305e1caaac51
/solutions_5686275109552128_0/C++/tangyouze/b.cpp
0c80e6baca4758a1080f384c93ca63afff890bd7
[]
no_license
alexandraback/datacollection
0bc67a9ace00abbc843f4912562f3a064992e0e9
076a7bc7693f3abf07bfdbdac838cb4ef65ccfcf
refs/heads/master
2021-01-24T18:27:24.417992
2017-05-23T09:23:38
2017-05-23T09:23:38
84,313,442
2
4
null
null
null
null
UTF-8
C++
false
false
605
cpp
b.cpp
#include <iostream> #include <vector> using namespace std; vector<int> a; int solve2(int maxn){ int ans = 0; for(int i=0 ;i<(int)a.size(); i++){ ans += (a[i]-1) / maxn; } return ans + maxn; } void solve(int icase){ int n; cin >>n; a.clear(); for(int i=0; i<n; i++){ int q; cin >> q; a.push_back(q); } int ans = 10000; for(int i=1; i<=1000; i++){ ans = min(ans, solve2(i)); } printf("Case #%d: %d\n", icase, ans); } int main(){ int n; cin >> n; for(int i=0; i<n; i++){ solve(i+1); } }
637ccc82b2f78ce1bb118e9b9d4747615921e229
4ea8ead40f393581b2a85439df5a0f1e627858f1
/362Program2-1/TreeNode.h
8041d5f01e9fcfbecc4e4baf49cea71e72499ba1
[]
no_license
Crysta7049/DataStructuresProject2
7eae8069476b30d4a861c2bb7e502a858b98c1d5
421022ef69c46b86a560e22d8a4d9784de0283cb
refs/heads/main
2023-04-15T04:47:53.196925
2021-04-15T16:18:46
2021-04-15T16:18:46
358,321,523
0
0
null
null
null
null
UTF-8
C++
false
false
600
h
TreeNode.h
#ifndef TREENODE_H #define TREENODE_H #include <string> #include <vector> #include "LLNode.h" using namespace std; class TreeNode { private: //vector<int> nodeLineNums; public: string key_value_; TreeNode * left_; TreeNode * right_; TreeNode(string word); vector<int> nodeLineNums; TreeNode(string word, TreeNode* left, TreeNode* right); ~TreeNode(); void printLineNums(); /* member variables */ //TreeNode * listPoint_; }; #endif // TREENODE_H
8ca138c0053fe23aa76731c7a03401e8b4a59990
b0da51354ec662292efe2339988545f4737a9553
/code/render/graphics/handlers/billboardentityhandler.cc
816232feccd270efee02ea66038828184a1ebbb7
[ "LicenseRef-scancode-unknown-license-reference", "BSD-2-Clause" ]
permissive
Core-Game-Project-2016/nebula-trifid
9a49d7ae5d896a28e11805ba1404b743add2e9d6
2f1b1d6986a049b4d133d65bef6c0aeb674e1a94
refs/heads/master
2021-01-22T00:29:10.314856
2016-05-27T23:05:01
2016-05-27T23:05:01
55,078,691
0
1
null
2016-05-20T15:32:12
2016-03-30T16:23:52
C++
UTF-8
C++
false
false
1,944
cc
billboardentityhandler.cc
//------------------------------------------------------------------------------ // billboardentityhandler.cc // (C) 2009 Radon Labs GmbH // (C) 2013-2016 Individual contributors, see AUTHORS file //------------------------------------------------------------------------------ #include "stdneb.h" #include "graphics/graphicsprotocol.h" #include "messaging/staticmessagehandler.h" #include "graphics/billboardentity.h" #include "graphics/graphicsentity.h" using namespace Billboards; using namespace Graphics; using namespace Graphics; namespace Messaging { //------------------------------------------------------------------------------ /** */ __Handler(BillboardEntity, SetOverlayColor) { obj->SetColor(msg->GetColor()); } //------------------------------------------------------------------------------ /** */ __StaticHandler(CreateBillboardEntity) { // create a new billboard entity Ptr<BillboardEntity> billboardEntity = BillboardEntity::Create(); billboardEntity->SetTransform(msg->GetTransform()); billboardEntity->SetVisible(msg->GetVisible()); billboardEntity->SetTexture(msg->GetResourceId()); billboardEntity->SetViewAligned(msg->GetViewAligned()); billboardEntity->SetPickingId(msg->GetPickingId()); billboardEntity->SetColor(msg->GetColor()); // lookup stage and attach entity const Ptr<Stage>& stage = GraphicsServer::Instance()->GetStageByName(msg->GetStageName()); stage->AttachEntity(billboardEntity.cast<GraphicsEntity>()); // set return value msg->GetObjectRef()->Validate<BillboardEntity>(billboardEntity.get()); } //------------------------------------------------------------------------------ /** Dispatcher method (must be positioned after the handler methods to prevent automatic instantiation). */ __Dispatcher(BillboardEntity) { __Handle(BillboardEntity, SetOverlayColor); __HandleUnknown(GraphicsEntity); } } // namespace Messaging
57ac594a0714bfea04e641da312b33358a69283e
95e296d857f8a515f27138d8825e8295a381c4e7
/libpika/PNativeConstMethodDecls.h
9449b26201d27590289a7afea44e1030afc46d72
[ "Zlib" ]
permissive
tempbottle/pika
b5178c4e8c7e4575cb4d8f9f68aba1591d4ce4c7
58342ab8e8abb9c0d0d6af78579e25fb80a0b294
refs/heads/master
2020-12-25T04:10:38.860551
2015-01-01T03:28:56
2015-01-01T03:28:56
null
0
0
null
null
null
null
UTF-8
C++
false
false
39,714
h
PNativeConstMethodDecls.h
/* * PNativeConstMethodDecls.h * See Copyright Notice in Pika.h * * DO NOT INCLUDE DIRECTLY! */ // ConstMethod0 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet> struct ConstMethod0 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)() const; TMETHOD function; ConstMethod0(TMETHOD m) : function(m) { } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; RetType<TRet>(ctx, (ptr->*function)()); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 0; } }; template<typename TClass> struct ConstMethod0<TClass, void> : NativeMethodBase { typedef void(TClass::*TMETHOD)() const; TMETHOD function; ConstMethod0(TMETHOD m) : function(m) { } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; (ptr->*function)(); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 0; } }; // ConstMethod1 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0> struct ConstMethod1 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0) const; TMETHOD function; char signature[1]; ConstMethod1(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; VarType<TParam0> param0(ctx, (u2)0); TRet ret = (ptr->*function)(param0); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 1; } }; template<typename TClass, typename TParam0> struct ConstMethod1<TClass, void, TParam0> : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0) const; TMETHOD function; char signature[1]; ConstMethod1(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; VarType<TParam0> param0(ctx, (u2)0); (ptr->*function)(param0); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 1; } }; // ConstMethodVA //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet> struct ConstMethodVA : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(Context*) const; TMETHOD function; ConstMethodVA(TMETHOD m) : function(m) { } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; TRet ret = (ptr->*function)(ctx); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 1; } }; template<typename TClass> struct ConstMethodVA<TClass, void> : NativeMethodBase { typedef void(TClass::*TMETHOD)(Context*) const; TMETHOD function; ConstMethodVA(TMETHOD m) : function(m) { } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; (ptr->*function)(ctx); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 1; } }; // ConstMethod2 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1> struct ConstMethod2 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1) const; TMETHOD function; char signature[2]; ConstMethod2(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; VarType<TParam0> param0(ctx, (u2)0); VarType<TParam1> param1(ctx, (u2)1); TRet ret = (ptr->*function)(param0, param1); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 2; } }; template<typename TClass, typename TParam0, typename TParam1> struct ConstMethod2<TClass, void, TParam0, TParam1> : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1) const; TMETHOD function; char signature[2]; ConstMethod2(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; VarType<TParam0> param0(ctx, (u2)0); VarType<TParam1> param1(ctx, (u2)1); (ptr->*function)(param0, param1); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 2; } }; // ConstMethod3 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2> struct ConstMethod3 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2) const; TMETHOD function; char signature[3]; ConstMethod3(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; VarType<TParam0> param0(ctx, (u2)0); VarType<TParam1> param1(ctx, (u2)1); VarType<TParam2> param2(ctx, (u2)2); TRet ret = (ptr->*function)(param0, param1, param2); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 3; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2> struct ConstMethod3<TClass, void, TParam0, TParam1, TParam2> : NativeMethodBase { typedef void (TClass::*TMETHOD)(TParam0, TParam1, TParam2) const; TMETHOD function; char signature[3]; ConstMethod3(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; VarType<TParam0> param0(ctx, (u2)0); VarType<TParam1> param1(ctx, (u2)1); VarType<TParam2> param2(ctx, (u2)2); (ptr->*function)(param0, param1, param2); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 3; } }; // ConstMethod4 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3> struct ConstMethod4 : NativeMethodBase { typedef TRet (TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3) const; TMETHOD function; char signature[4]; ConstMethod4(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); TRet ret = (ptr->*function)(param0, param1, param2, param3); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 4; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3> struct ConstMethod4<TClass, void, TParam0, TParam1, TParam2, TParam3> : NativeMethodBase { typedef void (TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3) const; TMETHOD function; char signature[4]; ConstMethod4(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); (ptr->*function)(param0, param1, param2, param3); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 4; } }; // ConstMethod5 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4> struct ConstMethod5 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4) const; TMETHOD function; char signature[5]; ConstMethod5(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 5; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4> struct ConstMethod5<TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4> : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4) const; TMETHOD function; char signature[5]; ConstMethod5(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); (ptr->*function)(param0, param1, param2, param3, param4); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 5; } }; // ConstMethod6 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5> struct ConstMethod6 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5) const; TMETHOD function; char signature[6]; ConstMethod6(TMETHOD m): function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 6; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5> struct ConstMethod6 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5) const; TMETHOD function; char signature[6]; ConstMethod6(TMETHOD m): function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); (ptr->*function)(param0, param1, param2, param3, param4, param5); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 6; } }; // ConstMethod7 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6> struct ConstMethod7 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6) const; TMETHOD function; char signature[7]; ConstMethod7(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5, param6); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 7; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6> struct ConstMethod7 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6) const; TMETHOD function; char signature[7]; ConstMethod7(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); (ptr->*function)(param0, param1, param2, param3, param4, param5, param6); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 7; } }; // ConstMethod8 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7> struct ConstMethod8: NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7) const; TMETHOD function; char signature[8]; ConstMethod8(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 8; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7> struct ConstMethod8 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7) const; TMETHOD function; char signature[8]; ConstMethod8(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 8; } }; // ConstMethod9 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8> struct ConstMethod9 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8) const; TMETHOD function; char signature[9]; ConstMethod9(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 9; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8> struct ConstMethod9 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8) const; TMETHOD function; char signature[9]; ConstMethod9(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 9; } }; // ConstMethod10 //////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9> struct ConstMethod10 : NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9) const; TMETHOD function; char signature[10]; ConstMethod10(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; signature[9] = VarType<TParam9>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); VarType<TParam9> param9(args, (u2)9); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8, param9); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 10; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9> struct ConstMethod10 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9) const; TMETHOD function; char signature[10]; ConstMethod10(TMETHOD m) : function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; signature[9] = VarType<TParam9>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); VarType<TParam9> param9(args, (u2)9); (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8, param9); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 10; } }; // Method11 //////////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10> struct ConstMethod11: NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10) const; TMETHOD function; char signature[11]; ConstMethod11(TMETHOD m): function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; signature[9] = VarType<TParam9>::eSig; signature[10] = VarType<TParam10>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); VarType<TParam9> param9(args, (u2)9); VarType<TParam10> param10(args, (u2)10); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 11; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10> struct ConstMethod11 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10) const; TMETHOD function; char signature[11]; ConstMethod11(TMETHOD m): function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; signature[9] = VarType<TParam9>::eSig; signature[10] = VarType<TParam10>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); VarType<TParam9> param9(args, (u2)9); VarType<TParam10> param10(args, (u2)10); (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 11; } }; // ConstMethod12 //////////////////////////////////////////////////////////////////////////////////////// template<typename TClass, typename TRet, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10, typename TParam11> struct ConstMethod12: NativeMethodBase { typedef TRet(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TParam11) const; TMETHOD function; char signature[12]; ConstMethod12(TMETHOD m): function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; signature[9] = VarType<TParam9>::eSig; signature[10] = VarType<TParam10>::eSig; signature[11] = VarType<TParam11>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); VarType<TParam9> param9(args, (u2)9); VarType<TParam10> param10(args, (u2)10); VarType<TParam11> param11(args, (u2)11); TRet ret = (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11); RetType<TRet>(ctx, ret); } virtual int GetRetCount() const { return RetType<TRet>::ReturnCount; } virtual int GetArgCount() const { return 12; } }; template<typename TClass, typename TParam0, typename TParam1, typename TParam2, typename TParam3, typename TParam4, typename TParam5, typename TParam6, typename TParam7, typename TParam8, typename TParam9, typename TParam10, typename TParam11> struct ConstMethod12 < TClass, void, TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TParam11 > : NativeMethodBase { typedef void(TClass::*TMETHOD)(TParam0, TParam1, TParam2, TParam3, TParam4, TParam5, TParam6, TParam7, TParam8, TParam9, TParam10, TParam11) const; TMETHOD function; char signature[12]; ConstMethod12(TMETHOD m): function(m) { signature[0] = VarType<TParam0>::eSig; signature[1] = VarType<TParam1>::eSig; signature[2] = VarType<TParam2>::eSig; signature[3] = VarType<TParam3>::eSig; signature[4] = VarType<TParam4>::eSig; signature[5] = VarType<TParam5>::eSig; signature[6] = VarType<TParam6>::eSig; signature[7] = VarType<TParam7>::eSig; signature[8] = VarType<TParam8>::eSig; signature[9] = VarType<TParam9>::eSig; signature[10] = VarType<TParam10>::eSig; signature[11] = VarType<TParam11>::eSig; } virtual void Invoke(void* obj, Context* ctx) { TClass* ptr = (TClass*)obj; ctx->ParseArgsInPlace(&signature[0], GetArgCount()); Value* args = ctx->GetArgs(); VarType<TParam0> param0(args, (u2)0); VarType<TParam1> param1(args, (u2)1); VarType<TParam2> param2(args, (u2)2); VarType<TParam3> param3(args, (u2)3); VarType<TParam4> param4(args, (u2)4); VarType<TParam5> param5(args, (u2)5); VarType<TParam6> param6(args, (u2)6); VarType<TParam7> param7(args, (u2)7); VarType<TParam8> param8(args, (u2)8); VarType<TParam9> param9(args, (u2)9); VarType<TParam10> param10(args, (u2)10); VarType<TParam11> param11(args, (u2)11); (ptr->*function)(param0, param1, param2, param3, param4, param5, param6, param7, param8, param9, param10, param11); } virtual int GetRetCount() const { return 0; } virtual int GetArgCount() const { return 12; } };
40c74e691bb5c166ab9e6406c488eadbe0795951
30d9d86ecfa5327436d88e57d2ccce6f3ad954eb
/C++/day02/const.cpp
accb73bd79306bf81c31551dc970922b9f11208b
[]
no_license
taizilinger123/C
3eabdf04b192620263a3dc863eb4d4c30a94fffa
a77354dffc5a4f1c8445e65bbc5401b096aa9f27
refs/heads/master
2023-08-22T00:07:33.669500
2023-08-21T07:26:22
2023-08-21T07:26:22
215,798,200
0
0
null
null
null
null
UTF-8
C++
false
false
232
cpp
const.cpp
#include <iostream> using namespace std; int main(){ int a=100; const int *pa=&a; //*pa=101; int b=200; pa=&b; cout<<*pa<<endl; cout<<"-----------"<<endl; int* const ra=&a; //ra=&b; *ra=1000; cout<<a<<endl; }
fcc75253aeea4f1c632b25e762ba3bfd3abc85c0
1f8ce45e9693fd084de4c095daf476b8342e1333
/src/message_model/message/Load.h
188a62f9144e2d5a9a26d16f980a3dd06ed01e62
[]
no_license
jinshayumi/ubuntu_software_engineering_server
e5c48dcbbfe01039b05d067d26096bc71d91064e
275b802423578b3ec086eee581cbaecef41915d1
refs/heads/master
2020-04-03T16:01:29.097608
2018-10-25T17:05:30
2018-10-25T17:05:30
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,235
h
Load.h
// // Created by swchen on 18-10-24. // #ifndef SOFTWARE_ENGINEERING_LOAD_MSG_H #define SOFTWARE_ENGINEERING_LOAD_MSG_H #include <iostream> #include <string> #include <utility> #include "ArduinoJson/ArduinoJson.h" #include "MD5_coding/md5.h" #include "Define_Member.h" #include "Const_Values.h" using namespace std; using namespace SwChen::tools; #define Load_json_len 1000 namespace SwChen { namespace message { class Load { public: explicit Load(string acount = _STRING, string password = _STRING, string ip = _STRING, string port = _STRING, string device = _STRING) : acount(std::move(acount)), password(std::move(password)), ip(std::move(ip)), port(std::move(port)), device(std::move(device)) { cout << "Load_msg constructor" << endl; } DEFINE_SIMPLE_MEMBER(acount, string); DEFINE_SIMPLE_MEMBER(password, string); DEFINE_SIMPLE_MEMBER(ip, string); DEFINE_SIMPLE_MEMBER(port, string); DEFINE_SIMPLE_MEMBER(device, string); static void serialize(JsonObject &root, const void *load) { root["acount"] = ((Load *) load)->get_acount(); root["password"] = MD5(((Load *) load)->get_password()).toStr(); root["ip"] = ((Load *) load)->get_ip(); root["port"] = ((Load *) load)->get_port(); root["device"] = ((Load *) load)->get_device(); } static void deserialize(const string &json, void *&load) { if (!load) { load = new Load(); } StaticJsonBuffer<Load_json_len> jsonBuffer; JsonObject &root = jsonBuffer.parseObject(json); ((Load *) load)->set_acount(root["acount"]); ((Load *) load)->set_password(root["password"]); ((Load *) load)->set_ip(root["ip"]); ((Load *) load)->set_port(root["port"]); ((Load *) load)->set_device(root["device"]); } }; } } #endif //SOFTWARE_ENGINEERING_LOAD_MSG_H
45a72396b2d18f164dca5cd54a684786f9a888cb
3365fa45aad3565e232f75e7833daaac7fcc4739
/Game.h
f99a681d74cf354043ef8fd41b7d39075997ead8
[]
no_license
Sylvador/kind-of-a-space-shooter
5a11bd9eade5cdaba8465239fd2a632fba24b9a5
f8afa80a1bff27e2aa73048049f87611460b51aa
refs/heads/master
2023-04-17T21:10:28.843253
2021-05-12T19:34:24
2021-05-12T19:34:24
366,810,516
1
0
null
null
null
null
UTF-8
C++
false
false
1,013
h
Game.h
#pragma once #include "SFML/Graphics.hpp" #include "SFML/System.hpp" #include "SFML/Audio.hpp" #include "SFML/Window.hpp" #include "Player.h" #include "Bullet.h" #include "Enemy.h" #include <vector> #include <string> class Game { public: Game(); void run(); private: void processEvents(); void update(); void render(); void handlePlayerInput(sf::Keyboard::Key key, bool isPressed); sf::RenderWindow window; sf::Clock clock; sf::Time timeSinceLastUpdate; sf::Time TimePerFrame; sf::Vector2f currentVelocity; sf::Vector2f direction; float maxVelocity = 25.f; float acceleration = 1.f; float drag = 0.5f; sf::Font font; sf::Texture playerTex; sf::Texture enemyTex; sf::Texture bulletTex; Player* player; sf::Text hpText; bool pIsMovingUp; bool pIsMovingDown; bool pIsMovingRight; bool pIsMovingLeft; bool pIsShooting; int shootTimer; std::vector <Enemy> enemies; int spawnTimer; sf::Text EhpText; int score; sf::Text scoreText; sf::Text gameOverText; bool gameOver; };
03f25498360b34a2ff6f58f2901643f78840ee82
0c5a865ddf0490316a1ea1614a14a75c948cf594
/Seungjin-Lee/190709/190709질문.cpp
060342231b9460799126894b15b9490e5bd12774
[]
no_license
lsg1213/cpp_study
02f1722d475b4087621c2c89ecb68b88406b4152
d18bf44ed1212047ed3e631af99e4c8b063fa6e9
refs/heads/master
2020-06-10T11:44:45.781700
2019-08-31T02:37:15
2019-08-31T02:37:15
193,641,682
2
1
null
2019-07-05T05:26:51
2019-06-25T05:40:04
C++
UHC
C++
false
false
588
cpp
190709질문.cpp
#include <iostream> using namespace std; class Plus { int a, b, sum; public: //1. 생성자 채우기 Plus() : a(0), b(0), sum(0) { cout << "생성되었습니다" << endl; } Plus(int _a) : Plus() { a = _a; } Plus(int _a, int _b) : Plus(_a) { b = _b; } //2. 소멸자에서 sum 출력하고 "소멸되었습니다" 출력 ~Plus() { cout << sum << endl; cout << "소멸되었습니다" << endl; } }; int main() { int x, y; cin >> x >> y; //3. 같은 표현 생각해보기 Plus p1 = (x,y); Plus p2 = {x,y}; Plus p3{x,y}; Plus p4(x, y); return 0; }
5705e8ad2444981264d469e56a6f3150f0045d4a
c9822f8c49046088715ea96762dbffedd014a0b0
/hardwork/STL/list.hpp
88a173cb728a09fa21f984307b069e6c209c5918
[ "MIT" ]
permissive
jskyzero/Cplusplus.Playground
471d6b6068c5ad9119db86c346143e9f9103f5f8
b4a82bb32af04efcffb6e251ac8956a3cc316174
refs/heads/master
2023-01-07T00:23:48.900807
2020-11-12T04:49:21
2020-11-12T04:49:21
201,798,526
0
0
null
null
null
null
UTF-8
C++
false
false
1,886
hpp
list.hpp
/* List (abstract data type) In computer science, a list or sequence is an abstract data type that represents a countable number of ordered values, where the same value may occur more than once. An instance of a list is a computer representation of the mathematical concept of a finite sequence; the (potentially) infinite analog of a list is a stream.[1]:§3.5 Lists are a basic example of containers, as they contain other values. If the same value occurs multiple times, each occurrence is considered a distinct item. Constructor operations to construct Lists i. createList to create an empty List ii. add operation to add data to a List Selector operations to select items of a List i. get to return one item at a particular position. Predicate operations to test Lists i. isEmpty to test whether the List is empty ii. remove operation to delete a data item from a List */ #include <iostream> #include <list> #include <cassert> typedef std::list<int> List; void print_list(List initial_list) { List copied_list = initial_list; for (auto& num : copied_list) { std::cout << num << "-"; } std::cout << "end" << std::endl; } void practice_list(void) { std::cout << "practice_list" << std::endl; // i. createList to create an empty List List mylist; // ii. add operation to add data to a List mylist.push_back(123); mylist.push_back(456); print_list(mylist); // i. get to return one item at a particular position. auto mylist_it = mylist.begin(); assert(*(++mylist_it) == 456); // i. isEmpty to test whether the List is empty assert(!mylist.empty()); // ii. remove operation to delete a data item from a List mylist.erase(mylist_it); print_list(mylist); // test insert; mylist.insert(mylist.begin(), 1); print_list(mylist); mylist.insert(mylist.begin(), mylist.begin(), mylist.end()); print_list(mylist); mylist.clear(); }
2eb71c8e5b81a1d71ec9169c52a0762f75f8cc62
0f867ab0c8930e88e267dd637d48fdc6c422bed7
/Mercury2/src/InstanceCounter.h
e9e9ae83335cd0e657dffd864ba254a136edf7e8
[]
no_license
axlecrusher/hgengine
e15f29f955352da55776de45a21d60845491b91e
7e7e75c41a86d83acdcaab2b346a6b8c2f87da54
refs/heads/master
2021-01-20T05:43:26.316683
2013-01-31T05:42:34
2013-01-31T05:42:34
89,799,775
1
0
null
null
null
null
UTF-8
C++
false
false
718
h
InstanceCounter.h
#ifndef INSTANCECOUNTER_H #define INSTANCECOUNTER_H //This counter is used with singletons to //ensure proper destruction order of the //singleton template<typename T> class InstanceCounter { public: InstanceCounter(const MString & name) :m_name(name) { if (m_count == 0) { printf("Creating instance %s\n", m_name.c_str()); m_instance = &T::GetInstance(); } ++m_count; } ~InstanceCounter() { --m_count; if (m_count == 0) { printf("Destroying instance %s\n", m_name.c_str()); SAFE_DELETE(m_instance); } } private: static unsigned long m_count; MString m_name; T* m_instance; }; template<typename T> unsigned long InstanceCounter<T>::m_count = 0; #endif
ec1db1ea82dc093ac9a6f5489e9ebbe939254261
a28631dd1922231a94cca55fac4d18f8093bc04c
/amy_show/src/amy/show/modules/ShowSenser.h
237ef6944dae06e7217b4c1c97187214030e3194
[]
no_license
albarral/amy
47b23fa3569a4a263c2c5bef3e62860f5c7299c2
d1a7540c893cf4840f53fbd4f890aa086a986fe7
refs/heads/master
2020-04-10T21:02:25.048668
2018-09-28T12:20:03
2018-09-28T12:20:03
64,211,918
0
0
null
null
null
null
UTF-8
C++
false
false
1,548
h
ShowSenser.h
#ifndef __AMY_SHOW_SHOWSENSER_H #define __AMY_SHOW_SHOWSENSER_H /*************************************************************************** * Copyright (C) 2017 by Migtron Robotics * * albarral@migtron.com * ***************************************************************************/ #include <log4cxx/logger.h> #include "amy/show/ShowData.h" #include "amy/core/bus/ArmBus.h" #include "amy/core/bus/AxisBus.h" #include "amy/core/bus/JointBus.h" #include "tron/control/module3.h" namespace amy { // Module used to plot an arm's position (for debugging purpose). // It gets the info from the arm bus. class ShowSenser : public tron::Module3 { private: static log4cxx::LoggerPtr logger; // bus bool bconnected; // connected to bus JointBus* pHSBus; // access to arm's HS joint JointBus* pVSBus; // access to arm's VS joint JointBus* pELBus; // access to arm's ELB joint AxisBus* pPanBus; // access to pan bus AxisBus* pTiltBus; // access to tilt bus AxisBus* pRadialBus; // access to radial bus // logic bool benabled; ShowData* pShowData; // access to shared show data public: ShowSenser(); ~ShowSenser(); // bus connection void connect(ArmBus& oArmBus); bool isConnected() {return bconnected;}; void init(ShowData& oShowData); private: // first actions when the thread begins virtual void first(); // loop inside the module thread virtual void loop(); }; } #endif
54730f49648eba5ca54d31a622b1fe0faf95a5d9
0156169eba2b3bf660578f51f6ebcc231b7022b9
/Qix/Qix.h
ee267ae34267885f453f786ee261d12fbea130d6
[]
no_license
ckhamash/Qix
22c75d4ec88db9af660e9eb9728316e76938c0ac
03c5e95bd66a89e9ffb5fd6402f525452ab9ed00
refs/heads/master
2021-01-01T05:33:20.142960
2015-01-12T20:38:37
2015-01-12T20:38:37
28,829,654
0
0
null
null
null
null
UTF-8
C++
false
false
589
h
Qix.h
#pragma once #include "SFML\Graphics.hpp" class Game; class Qix { private: Game* pGame; std::vector<sf::Vector2f> positions; std::vector<sf::Vector2f> velocities; float speed; public: Qix(); Qix(Game* pGame); ~Qix(); void initQix(std::vector<sf::Vector2f> initPositions); std::vector<sf::Vector2f> getPositions(); bool isIntersecting(); bool isIntersecting(sf::Vector2f a, sf::Vector2f b, sf::Vector2f c, sf::Vector2f d); void randomizeVelocity(int index); void move(int index, float secondsSinceLastFrame); void update(float secondsSinceLastFrame); void draw(); };
b4da465d2f5d0abbe88886dff8a66a23f97cd88f
70a79d90a6a037071c41236ca0498f3e313ff1ce
/vpr/src/base/partition_region.h
eb89399191c6b9e7cc9e1b1ab73dc0f18f012660
[ "MIT", "MIT-Modern-Variant", "LicenseRef-scancode-unknown-license-reference" ]
permissive
verilog-to-routing/vtr-verilog-to-routing
7f327e74394fb35ca90d90c48e62df8db6080513
ef5f993959c6b6896f6821b14b361d581ebf46fe
refs/heads/master
2023-09-01T04:19:02.151710
2023-08-31T20:57:20
2023-08-31T20:57:20
38,118,370
898
403
NOASSERTION
2023-09-14T15:30:08
2015-06-26T15:24:42
C++
UTF-8
C++
false
false
2,473
h
partition_region.h
#ifndef PARTITION_REGIONS_H #define PARTITION_REGIONS_H #include "region.h" #include "atom_netlist_fwd.h" #include "vpr_types.h" /** * @file * @brief This file defines the PartitionRegion class. The PartitionRegion class is used to store the union * of regions that a partition can be placed in. * * For more details on what a region is, see vpr/src/base/region.h */ class PartitionRegion { public: /** * @brief Add a region to the union of regions belonging to the partition * * @param region The region to be added to the calling object */ void add_to_part_region(Region region); /** * @brief Return the union of regions */ std::vector<Region> get_partition_region(); std::vector<Region> get_partition_region() const; /** * @brief Set the union of regions */ void set_partition_region(std::vector<Region> pr); /** * @brief Check if the PartitionRegion is empty (meaning there is no constraint on the object the PartitionRegion belongs to) */ bool empty(); /** * @brief Check if the given location is within the legal bounds of the PartitionRegion. * The location provided is assumed to be valid. * * @param loc The location to be checked */ bool is_loc_in_part_reg(t_pl_loc loc); /** * @brief Global friend function that returns the intersection of two PartitionRegions * * @param cluster_pr One of the PartitionRegions to be intersected * @param new_pr One of the PartitionRegions to be intersected */ friend PartitionRegion intersection(const PartitionRegion& cluster_pr, const PartitionRegion& new_pr); /** * @brief Global friend function that updates the PartitionRegion of a cluster with the intersection * of the cluster PartitionRegion and a new PartitionRegion * * @param cluster_pr The cluster PartitionRegion that is to be updated * @param new_pr The new PartitionRegion that the cluster PartitionRegion will be intersected with */ friend void update_cluster_part_reg(PartitionRegion& cluster_pr, const PartitionRegion& new_pr); private: std::vector<Region> partition_region; ///< union of rectangular regions that a partition can be placed in }; ///@brief used to print data from a PartitionRegion void print_partition_region(FILE* fp, PartitionRegion pr); #endif /* PARTITION_REGIONS_H */
27cd6fbe6bd0ce5d3723b7a0c0156d53e3d63f2b
cbae1c6cc49485decf4692befa0cc2d1f94fcb5a
/Pong/header.h
d959b04488ae7ed042f6af430a1ecd5b5c2abc0b
[]
no_license
macairececile/Projets_DUT
4142ea9bb4cd1046dfb7d29878a0c15d04743423
dc672389fb9dd611dd3bbc3868a892a316da62a8
refs/heads/master
2022-12-08T20:59:28.537254
2020-09-09T12:35:32
2020-09-09T12:35:32
294,094,150
0
0
null
null
null
null
ISO-8859-1
C++
false
false
7,255
h
header.h
#ifndef HEADER_H_INCLUDED #define HEADER_H_INCLUDED #include <iostream> #include <cstdlib> #include <string> #include <SDL/SDL.h> #include <SDL/SDL_image.h> #include <SDL/SDL_ttf.h> #include <sstream> using namespace std; const int SCREEN_WIDTH=640; const int SCREEN_HEIGHT=480; const int SCREEN_BPP=32; const int TAILLE=20; // -- loadImage --------------------------------- // chargement d'une image // ---------------------------------------------- SDL_Surface *load_image( std::string filename ) { //Temporary storage for the image that's loaded SDL_Surface* loadedImage = NULL; //The optimized image that will be used SDL_Surface* optimizedImage = NULL; //Load the image loadedImage = SDL_LoadBMP( filename.c_str() ); //If nothing went wrong in loading the image if( loadedImage != NULL ) { //Create an optimized image optimizedImage = SDL_DisplayFormat( loadedImage ); //Free the old image SDL_FreeSurface( loadedImage ); } //Return the optimized image return optimizedImage; } // -- loadImageWithColorKey --------------------- // chargement d'une image // * paramètres entrées : // - "filename" : nom de l'image // - "r,g,b" : couleur de la ColorKey; cette // couleur devient transparente ! // * paramètre de sortie : SDL_Surface contenant // l'image. // ---------------------------------------------- SDL_Surface *loadImageWithColorKey(string filename, int r, int g, int b) { //The image that's loaded SDL_Surface* loadedImage = NULL; //The optimized image that will be used SDL_Surface* optimizedImage = NULL; //Load the image loadedImage = IMG_Load( filename.c_str() ); //If the image loaded if( loadedImage != NULL ) { //Create an optimized image optimizedImage = SDL_DisplayFormat( loadedImage ); //Free the old image SDL_FreeSurface( loadedImage ); //If the image was optimized just fine if( optimizedImage != NULL ) { //Map the color key Uint32 colorkey = SDL_MapRGB( optimizedImage->format, r, g, b ); //Set all pixels of color R 0, G 0xFF, B 0xFF to be transparent SDL_SetColorKey( optimizedImage, SDL_SRCCOLORKEY, colorkey ); } } //Return the optimized image return optimizedImage; } // -- applySurface ------------------------------ // cf atelier03 pour plus d'explication // ---------------------------------------------- void applySurface(int x, int y, SDL_Surface* source, SDL_Surface* destination, SDL_Rect* clip) { SDL_Rect offset; offset.x = x; offset.y = y; SDL_BlitSurface( source, clip, destination, &offset ); } struct ball { int x; // abscisse du centre de la balle int y; // ordonnée du centre de la balle int w; // largeur de la balle int h; // hauteur de la balle int mvt_x; // mouvement sur l'axe des abscisses int mvt_y; // mouvement sur l'axe des ordonnées }; struct Button { int x; int y; SDL_Rect but; }; void initPlay1(Button &p) { p.x = 100; p.y = 300; p.but.x = 0; p.but.y = 101; p.but.h = 59; p.but.w = 149; } void initPlay2(Button &p) { p.x = 100; p.y = 300; p.but.x = 200; p.but.y = 101; p.but.h = 59; p.but.w = 149; } void initQuit1(Button &p) { p.x = SCREEN_WIDTH-251; p.y = 300; p.but.x = 0; p.but.y = 0; p.but.h = 59; p.but.w = 149; } void initQuit2(Button &p) { p.x = SCREEN_WIDTH-251; p.y = 300; p.but.x = 200; p.but.y = 0; p.but.h = 59; p.but.w = 149; } void initBall(ball &b) { b.x = SCREEN_WIDTH/2; b.y = SCREEN_HEIGHT/2; b.w = TAILLE; b.h = TAILLE; b.mvt_x=2; // mouvement de la balle en abscisse b.mvt_y=2; // mouvement de la balle en ordonnée } bool collision(SDL_Rect a, SDL_Rect b) { int leftA, leftB; int rightA, rightB; int topA, topB; int bottomA, bottomB; leftA = a.x; rightA = a.x + a.w; topA = a.y; bottomA = a.y + a.h; leftB = b.x; rightB = b.x + b.w; topB = b.y; bottomB = b.y + b.h; if(bottomA <= topB) return false; if(topA >= bottomB) return false; if(rightA <= leftB) return false; if(leftA >= rightB) return false; return true; } void moveBall(ball &b, SDL_Rect player01, SDL_Rect player02) { SDL_Rect tmp; b.x+=b.mvt_x; b.y+=b.mvt_y; tmp.x=b.x-TAILLE/2; tmp.y=b.y-TAILLE/2; tmp.h=TAILLE; tmp.w=TAILLE; // Correction Mouvement Horizontal if ((b.x+TAILLE>SCREEN_WIDTH) || (b.x-TAILLE/2<0) || (collision(tmp, player01)) || (collision(tmp,player02))) { b.x=SCREEN_WIDTH-TAILLE; b.mvt_x*=-1; } // Correction Mouvement Vertical if ((b.y+TAILLE>SCREEN_HEIGHT) || (b.y-TAILLE/2<0)) { b.y=SCREEN_HEIGHT-TAILLE; b.mvt_y*=-1; } SDL_Delay(10); } void showBall(ball b, SDL_Surface*s) { SDL_Rect r; r.x=b.x-TAILLE/2; r.y=b.y-TAILLE/2; r.w=TAILLE; r.h=TAILLE; SDL_FillRect(s,&r, SDL_MapRGB(s->format,255,0,0)); } void moveplayer01(SDL_Rect & player01) { Uint8 *keystates = SDL_GetKeyState( NULL ); // Si la touche "a" est préssée if (keystates[SDLK_a]) player01.y+=2; // Si la touche "q" est préssée if (keystates[SDLK_q]) player01.y-=2; if (player01.y<0) { player01.y+=2; } if ((player01.y+player01.h)>SCREEN_HEIGHT) { player01.y-=2; } } void moveplayer02(SDL_Rect & player02) { Uint8 *keystates = SDL_GetKeyState( NULL ); // Si la touche du haut est préssée if (keystates[SDLK_UP]) player02.y+=2; // Si la touche du bas est préssée if (keystates[SDLK_DOWN]) player02.y-=2; if (player02.y<0) { player02.y+=2; } if ((player02.y+player02.h)>SCREEN_HEIGHT) { player02.y-=2; } } void ReInitball (ball & b, int & cpt1, int & cpt2, SDL_Rect & player01 , SDL_Rect & player02) { if (b.x <= player01.x) { cpt1++; initBall(b); } if (b.x + b.w >= player02.x + player02.w) { cpt2++; initBall(b); } } // Score void showMessageScreen(string message,int x,int y, TTF_Font *font,int fontSize,SDL_Color textColor,SDL_Surface* &screen) { string mot=""; string space=" "; int i=0,j; SDL_Surface *mes=NULL; j = message.find(space); while( j != string::npos ) { mot=message.substr(i,j-i); if(mot != "") { mes=TTF_RenderText_Solid(font,mot.c_str(),textColor); applySurface(x,y,mes,screen,NULL); x+=mes->w; SDL_FreeSurface(mes); } x+=fontSize; i=j+1; j = message.find(space,i); } mot=message.substr(i); mes=TTF_RenderText_Solid(font,mot.c_str(),textColor); applySurface(x,y,mes,screen,NULL); SDL_FreeSurface(mes); } #endif // HEADER_H_INCLUDED
9c5306ea369ed59cbbcb2c1b1580096626b2a511
1a2190b96ca17719d2b41a5fbcac6043cf9f08e4
/HackerRank/101 Hack 41/_arias-loops.cpp
7212abc0add1a1d121bc1391381a650166cc4d1d
[]
no_license
eliasm2/problem-solving
13c1abbf397bb41683fccb3490b0113c36ce9010
15becf49315b5defb8c1267e0c43ce1579dcae1a
refs/heads/master
2020-09-07T07:12:17.112311
2018-07-20T17:27:43
2018-07-20T17:27:43
null
0
0
null
null
null
null
UTF-8
C++
false
false
673
cpp
_arias-loops.cpp
#include <bits/stdc++.h> typedef long long int64; typedef unsigned long long uint64; using namespace std; const int64 MOD = 1e9 + 7; int main(int argc, char* argv[]) { ios::sync_with_stdio(false); int64 n, k; cin >> n >> k; if (k == 1LL) cout << n << "\n"; else { k--; int64 c = (k * (k + 1LL)) / 2LL; int64 mxi = n - c; int64 ans = 0LL; for (int64 i = 1LL; i <= mxi; ++i) { int64 cur = 1LL; for (int64 j = 1LL; j <= k; ++j) { int64 ths = n - ((j*(j+1LL))/2LL) - i + 1LL; cur *= (ths % MOD); cur %= MOD; } ans += cur; ans %= MOD; } cout << ans << "\n"; } return 0; }
070590fcbe07e79314091adaeb8d12b5555962c4
009f903779fdc3e8667915f40c51e48276fd996a
/selectionSort.cpp
56625da6215fbbdfc093bc160b1c52449c55c702
[]
no_license
MaryoriHilares/cc2
cab1e29e8133831667c283835d1bc67d14cf8c4a
c90dd03a277782f5ce3374290ef870372f0ae4cb
refs/heads/master
2022-11-18T04:27:06.491533
2020-07-20T04:00:54
2020-07-20T04:00:54
263,794,763
0
0
null
null
null
null
WINDOWS-1250
C++
false
false
913
cpp
selectionSort.cpp
#include <iostream> using namespace std; void swap(int *xp, int *yp) { int temp = *xp; *xp = *yp; *yp = temp; } void selectionSort(int arr[], int tam) { int i, j, min; for (i = 0; i < tam-1; i++) { // Encuentra el elemento mínimo en el arreglo desordenado min = i; for (j = i+1; j < tam; j++) if (arr[j] < arr[min]) min = j; //Intercambia el elemento mínimo encontrado con el primer elemento swap(&arr[min], &arr[i]); } } void mostrarArreglo(int arr[], int tam) { int i; for (i=0; i < tam; i++) cout << arr[i] << " "; cout << endl; } int main() { int arr[] = {64, 25, 12, 22, 11,16,0,9,3}; int tam=9; selectionSort(arr, tam); cout << "Arreglo ordenado: \n"; mostrarArreglo(arr, tam); return 0; }
7c2d75d38f30264e5db8408e9ef366778ad6bc96
39eac74fa6a244d15a01873623d05f480f45e079
/ApplyListDlg.h
efa597524047e0f417c353bec8462c0e75797b62
[]
no_license
15831944/Practice
a8ac8416b32df82395bb1a4b000b35a0326c0897
ae2cde9c8f2fb6ab63bd7d8cd58701bd3513ec94
refs/heads/master
2021-06-15T12:10:18.730367
2016-11-30T15:13:53
2016-11-30T15:13:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,721
h
ApplyListDlg.h
//{{AFX_INCLUDES() //}}AFX_INCLUDES #if !defined(AFX_APPLYLISTDLG_H__65102141_410A_11D2_AB75_00A0246CDDA1__INCLUDED_) #define AFX_APPLYLISTDLG_H__65102141_410A_11D2_AB75_00A0246CDDA1__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // ApplyListDlg.h : header file // #define APPLY_LIST_COMBO_SEL_EXISTING 0 #define APPLY_LIST_COMBO_SEL_AVAILABLE 1 ///////////////////////////////////////////////////////////////////////////// // CApplyListDlg dialog class CApplyListDlg : public CNxDialog { // Construction public: ~CApplyListDlg(); NXDATALISTLib::_DNxDataListPtr m_List; CApplyListDlg(CWnd* pParent); // standard constructor CString m_strClickedType; int m_iDestID; // Could be a bill or charge // Dialog Data //{{AFX_DATA(CApplyListDlg) enum { IDD = IDD_APPLY_LIST_DLG }; CNxIconButton m_btnOK; CNxIconButton m_btnNewPay; //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CApplyListDlg) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CApplyListDlg) afx_msg void OnShowWindow(BOOL bShow, UINT nStatus); afx_msg void OnLButtonDownList(long nRow, short nCol, long x, long y, long nFlags); afx_msg void OnAddPayment(); virtual BOOL OnInitDialog(); DECLARE_EVENTSINK_MAP() //}}AFX_MSG DECLARE_MESSAGE_MAP() private: void OnOK(); void FillAppliesList(); CBrush m_brush; }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_APPLYLISTDLG_H__65102141_410A_11D2_AB75_00A0246CDDA1__INCLUDED_)
49549513b54f309191d92d68951a6bc426cc5033
950dc03dea83292025ba6bbd47cec27b2008eba5
/src/tim/vx/ops/conv2d_test.cc
66a299c874ce4eba0a21fbbd57c975957933c867
[ "MIT" ]
permissive
Changerzz/TIM-VX
36d4a1d10bee3f1897c9e055508f938c56677998
a09ffe8b98283674fc343907b403632bcecf92bf
refs/heads/main
2023-06-19T09:21:29.432075
2021-07-21T07:52:19
2021-07-22T02:41:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
63,110
cc
conv2d_test.cc
#include "tim/vx/ops/conv2d.h" #include "gtest/gtest.h" #include "src/tim/vx/test_utils.h" #include "tim/vx/context.h" #include "tim/vx/graph.h" #include "tim/vx/types.h" TEST(Conv2d, shape_4_2_1_1_float32_PaddingTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 1, 1, 1, 1, // row = 1 2, 2, 3, 2 // row = 2 }; // weight data oihw std::vector<float> weight_data = { 1, 2, 3, 4, //first 2x2 filter -1, 1, -1, 1, // second 2x2 filter -1, -1, 1, 1, // third 2x2 filter }; // bias data std::vector<float> bias_data = {1, 2, 3}; // nchw std::vector<float> golden = {// first channel 18, 22, 21, 8, 7, 9, 8, 3, 2, 3, 1, -1, // second channel 2, 3, 1, 0, 5, 6, 6, 4, -1, -2, -2, 1}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_2_2_float32_PointwiseTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn tim::vx::ShapeType weight_shape({1, 1, 2, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2}; // weight data oihw std::vector<float> weight_data = { 1, 2 // first filter }; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3, 1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_float32_SimpleTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { // First batch 1, 1, 1, 1, // row = 1 2, 2, 2, 2, // row = 2 // Second batch 1, 2, 3, 4, // row = 1 1, 2, 3, 4, // row = 2 }; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {1, 2, 3}; // nchw std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_2_2_float32_SimpleChannelsTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 2, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data std::vector<float> input_data = { 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2}; // weight data std::vector<float> weight_data = {1, 2, 3, 4, 1, 2, 3, 4, -1, 1, -1, 1, -1, 1, -1, 1, -1, -1, 1, 1, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {1, 2, 3}; std::vector<float> golden = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_6_3_1_1_float32_SimpleAnisotropicStridesTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {3, 2, 1, -1, -2, -3, 4, 3, 2, -2, -3, -4, 5, 4, 3, -3, -4, -5}; // weight data oihw std::vector<float> weight_data = { 1, 2, // 3, 4, // }; // bias data std::vector<float> bias_data = {-1}; // nchw std::vector<float> golden = { 30, -24, // 40, -34, // }; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({3, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {105, 150, 183, 95, 235, 312, 357, 178, 187, 234, 261, 121}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedConstFilterTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {105, 150, 183, 95, 235, 312, 357, 178, 187, 234, 261, 121}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedBiasTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {10}; // nchw std::vector<float> golden = {115, 160, 193, 105, 245, 322, 367, 188, 197, 244, 271, 131}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::SAME; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_3_1_1_float32_HandCalculatedValidTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12}; // weight data oihw std::vector<float> weight_data = {1, 4, 7, 2, 5, 8, 3, 6, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {312, 357}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_2_2_float32_DisabledPointwiseMultifilterTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 2, 2}); //whcn tim::vx::ShapeType weight_shape({1, 1, 2, 2}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {4, 2, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 0.5, 0.5, 0.5, 1, 1, 1, 1, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2, 0.5, 1, 1.5, 2}; // weight data oihw std::vector<float> weight_data = {1, 2, 2, 3}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = { 1.5, 1.5, 1.5, 1.5, 3, 3, 3, 3, 2.5, 2.5, 2.5, 2.5, 5, 5, 5, 5, 1.5, 3, 4.5, 6, 1.5, 3, 4.5, 6, 2.5, 5, 7.5, 10, 2.5, 5, 7.5, 10}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_9_9_1_1_float32_SimpleDilationTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {3, 3, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {5, 5, 5, 5, 5, 5, 5, 5, 5}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({3, 3}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_float32_StrideTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {3, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 3, 2, 1, 2, 3, 4, 1, 2, 4, 4}; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {1, 2, 3}; // nchw std::vector<float> golden = {18, 22, 21, 2, 3, 1, 5, 6, 6, 17, 31, 40, 4, 5, 3, 3, 4, 4}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_float32_InputAndFilterSameWidthHeightTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({4, 2, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {1, 1, weight_shape[3], input_shape[3]}); //whcn tim::vx::TensorSpec input_spec(tim::vx::DataType::FLOAT32, input_shape, tim::vx::TensorAttribute::INPUT); tim::vx::TensorSpec weight_spec(tim::vx::DataType::FLOAT32, weight_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec bias_spec(tim::vx::DataType::FLOAT32, bias_shape, tim::vx::TensorAttribute::CONSTANT); tim::vx::TensorSpec output_spec(tim::vx::DataType::FLOAT32, output_shape, tim::vx::TensorAttribute::OUTPUT); // Input data nchw std::vector<float> input_data = {1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4}; // weight data oihw std::vector<float> weight_data = {1, 2, 3, 4, -1, -1, 1, 1}; // bias data std::vector<float> bias_data = {0}; // nchw std::vector<float> golden = {10, 34}; auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({0, 0}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<float> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest1) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float InputMin = -63.5, InputMax = 64, WeightMin = -63.5, WeightMax = 64, OutputMin = -127, OutputMax = 128; std::pair<float, int32_t> scalesAndZp; scalesAndZp = QuantizationParams<u_int8_t>(InputMin, InputMax); std::vector<float> scalesInput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsInput = {scalesAndZp.second}; scalesAndZp = QuantizationParams<u_int8_t>(WeightMin, WeightMax); std::vector<float> scalesWeight = {scalesAndZp.first}; std::vector<int32_t> zeroPointsWeight = {scalesAndZp.second}; std::vector<float> scalesBias = {scalesInput[0] * scalesWeight[0]}; std::vector<int32_t> zeroPointsBias = {0}; scalesAndZp = QuantizationParams<u_int8_t>(OutputMin, OutputMax); std::vector<float> scalesOutput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsOutput = {scalesAndZp.second}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::ASYMMETRIC, 2, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::ASYMMETRIC, 2, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4}; // weight data oihw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data // scale:0.25 Zp:0 std::vector<float> bias_data_float = {1, 2, 3}; // golden data //min:-127 max:128 scale:1 Zp:-1 std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scalesInput[0], zeroPointsInput[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scalesWeight[0], zeroPointsInput[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scalesBias[0], zeroPointsBias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_4_2_1_2_uint8_QuantizedTest2) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({4, 2, 1, 2}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 3}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float InputMin = -128.5, InputMax = 128, WeightMin = -128.5, WeightMax = 128, OutputMin = -127, OutputMax = 128; std::pair<float, int32_t> scalesAndZp; scalesAndZp = QuantizationParams<u_int8_t>(InputMin, InputMax); std::vector<float> scalesInput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsInput = {scalesAndZp.second}; scalesAndZp = QuantizationParams<u_int8_t>(WeightMin, WeightMax); std::vector<float> scalesWeight = {scalesAndZp.first}; std::vector<int32_t> zeroPointsWeight = {scalesAndZp.second}; std::vector<float> scalesBias = {scalesInput[0] * scalesWeight[0]}; std::vector<int32_t> zeroPointsBias = {0}; scalesAndZp = QuantizationParams<u_int8_t>(OutputMin, OutputMax); std::vector<float> scalesOutput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsOutput = {scalesAndZp.second}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::ASYMMETRIC, 2, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::ASYMMETRIC, 2, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); // Input data nchw // min:-128.5 max:128 scale:1.00588 Zp:0 std::vector<float> input_data_float = {1, 1, 1, 1, 2, 2, 2, 2, 1, 2, 3, 4, 1, 2, 3, 4}; // weight data oihw // min:-128.5 max:128 scale:1.00588 Zp:0 std::vector<float> weight_data_float = {1, 2, 3, 4, -1, 1, -1, 1, -1, -1, 1, 1}; // bias data // scale:1.0116 Zp:0 std::vector<float> bias_data_float = {1, 2, 3}; // golden data // min:-127 max:128 scale:1 Zp:-1 std::vector<float> golden_float = {18, 18, 2, 2, 5, 5, 17, 37, 4, 4, 3, 3}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scalesInput[0], zeroPointsInput[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scalesWeight[0], zeroPointsInput[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scalesBias[0], zeroPointsBias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_6_3_1_1_uint8_AnisotropicStridesQuantizedTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({6, 3, 1, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 2, weight_shape[3], input_shape[3]}); //whcn float InputMin = -63.5, InputMax = 64, WeightMin = -63.5, WeightMax = 64, OutputMin = -127, OutputMax = 128; std::pair<float, int32_t> scalesAndZp; scalesAndZp = QuantizationParams<u_int8_t>(InputMin, InputMax); std::vector<float> scalesInput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsInput = {scalesAndZp.second}; scalesAndZp = QuantizationParams<u_int8_t>(WeightMin, WeightMax); std::vector<float> scalesWeight = {scalesAndZp.first}; std::vector<int32_t> zeroPointsWeight = {scalesAndZp.second}; std::vector<float> scalesBias = {scalesInput[0] * scalesWeight[0]}; std::vector<int32_t> zeroPointsBias = {0}; scalesAndZp = QuantizationParams<u_int8_t>(OutputMin, OutputMax); std::vector<float> scalesOutput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsOutput = {scalesAndZp.second}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::ASYMMETRIC, 2, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::ASYMMETRIC, 2, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {3, 2, 1, -1, -2, -3, 4, 3, 2, -2, -3, -4, 5, 4, 3, -3, -4, -5}; // weight data oihw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> weight_data_float = {1, 2, 3, 4}; // bias data // scale:0.25 Zp:0 std::vector<float> bias_data_float = {-1}; // golden data //min:-127 max:128 scale:1 Zp:-1 std::vector<float> golden_float = {30, -24, 40, -34}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scalesInput[0], zeroPointsInput[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scalesWeight[0], zeroPointsInput[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scalesBias[0], zeroPointsBias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({3, 1}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_9_9_1_1_uint8_DilationQuantizedTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({9, 9, 1, 1}); //whcn tim::vx::ShapeType weight_shape({3, 3, 1, 1}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {3, 3, weight_shape[3], input_shape[3]}); //whcn float InputMin = -128, InputMax = 127, WeightMin = -128, WeightMax = 127, OutputMin = 0, OutputMax = 255; std::pair<float, int32_t> scalesAndZp; scalesAndZp = QuantizationParams<u_int8_t>(InputMin, InputMax); std::vector<float> scalesInput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsInput = {scalesAndZp.second}; scalesAndZp = QuantizationParams<u_int8_t>(WeightMin, WeightMax); std::vector<float> scalesWeight = {scalesAndZp.first}; std::vector<int32_t> zeroPointsWeight = {scalesAndZp.second}; std::vector<float> scalesBias = {scalesInput[0] * scalesWeight[0]}; std::vector<int32_t> zeroPointsBias = {0}; scalesAndZp = QuantizationParams<u_int8_t>(OutputMin, OutputMax); std::vector<float> scalesOutput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsOutput = {scalesAndZp.second}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::ASYMMETRIC, 2, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::ASYMMETRIC, 2, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); tim::vx::TensorSpec input_spec(tim::vx::DataType::UINT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::UINT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::UINT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); // Input data nchw // min:-128 max:127 scale:1 Zp:0 std::vector<float> input_data_float = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; // weight data oihw // min:-128 max:127 scale:1 Zp:0 std::vector<float> weight_data_float = {1, 2, 3, 4, 5, 6, 7, 8, 9}; // bias data // scale:1 Zp:0 std::vector<float> bias_data_float = {0}; // golden data // min:0 max:255 scale:1 Zp:-128 std::vector<float> golden_float = {5, 5, 5, 5, 5, 5, 5, 5, 5}; std::vector<u_int8_t> input_data = Quantize<uint8_t>(input_data_float, scalesInput[0], zeroPointsInput[0]); std::vector<u_int8_t> weight_data = Quantize<uint8_t>(weight_data_float, scalesWeight[0], zeroPointsInput[0]); std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scalesBias[0], zeroPointsBias[0]); std::vector<u_int8_t> golden = Quantize<uint8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({3, 3}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<u_int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerTensorTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float InputMin = -63.5, InputMax = 64, WeightMin = -63.5, WeightMax = 64, OutputMin = -63.5, OutputMax = 64; std::pair<float, int32_t> scalesAndZp; scalesAndZp = QuantizationParams<int8_t>(InputMin, InputMax); std::vector<float> scalesInput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsInput = {scalesAndZp.second}; scalesAndZp = QuantizationParams<int8_t>(WeightMin, WeightMax); std::vector<float> scalesWeight = {1}; std::vector<int32_t> zeroPointsWeight = {0}; std::vector<float> scalesBias = {scalesInput[0] * scalesWeight[0]}; std::vector<int32_t> zeroPointsBias = {0}; scalesAndZp = QuantizationParams<int8_t>(OutputMin, OutputMax); std::vector<float> scalesOutput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsOutput = {scalesAndZp.second}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::ASYMMETRIC, 2, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::ASYMMETRIC, 2, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3, 2, -1, -3, 3, -2, -4}; std::vector<int8_t> input_data = Quantize<int8_t>(input_data_float, scalesInput[0], zeroPointsInput[0]); // weight_float_data = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2}; std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2}; // bias data std::vector<float> bias_data_float = {3, -2}; std::vector<int32_t> bias_data = Quantize<int32_t>(bias_data_float, scalesBias[0], zeroPointsBias[0]); // golden_int8_data = {61, -115, 111, -89} // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> golden_float = {31, -57, 56, -44}; std::vector<int8_t> golden = Quantize<int8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_3_2_2_1_int8_QuantizedPerChannelTest) { auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); tim::vx::ShapeType input_shape({3, 2, 2, 1}); //whcn tim::vx::ShapeType weight_shape({2, 2, 2, 2}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {2, 1, weight_shape[3], input_shape[3]}); //whcn float InputMin = -63.5, InputMax = 64, WeightMin = 0, WeightMax = 0, OutputMin = -63.5, OutputMax = 64; std::pair<float, int32_t> scalesAndZp; scalesAndZp = QuantizationParams<int8_t>(InputMin, InputMax); std::vector<float> scalesInput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsInput = {scalesAndZp.second}; scalesAndZp = QuantizationParams<int8_t>(WeightMin, WeightMax); std::vector<float> scalesWeight = {1, 2}; std::vector<int32_t> zeroPointsWeight = {0, 0}; std::vector<float> scalesBias = {scalesInput[0] * scalesWeight[0], scalesInput[0] * scalesWeight[1]}; std::vector<int32_t> zeroPointsBias = {0, 0}; scalesAndZp = QuantizationParams<int8_t>(OutputMin, OutputMax); std::vector<float> scalesOutput = {scalesAndZp.first}; std::vector<int32_t> zeroPointsOutput = {scalesAndZp.second}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 3, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); // Input data nchw // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> input_data_float = {3, 1, -2, 4, 2, -3, 2, -1, -3, 3, -2, -4}; std::vector<int8_t> input_data = Quantize<int8_t>(input_data_float, scalesInput[0], zeroPointsInput[0]); // weight_data_float = {1, 3, 3, 5, 2, 4, 4, 6, 7, 5, 3, 1, 8, 6, 4, 2}; std::vector<int8_t> weight_data = {1, 3, 3, 5, 2, 4, 4, 6, 4, 3, 2, 1, 4, 3, 2, 1}; // bias_data_float ={3, -2}; std::vector<int32_t> bias_data = {6, -2}; // golden data // min:-63.5 max:64 scale:0.5 Zp:-1 std::vector<float> golden_float = {31, -57, 64, -46}; std::vector<int8_t> golden = Quantize<int8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({1, 1}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } TEST(Conv2d, shape_w_h_128_1_ksize_1_1_stride_2_int8_QuantizedPerChannel_customer_Test) { tim::vx::ShapeType input_shape({2, 2, 128, 1}); //whcn tim::vx::ShapeType weight_shape({1, 1, 128, 256}); //whio tim::vx::ShapeType bias_shape({weight_shape[3]}); tim::vx::ShapeType output_shape( {1, 1, weight_shape[3], input_shape[3]}); //whcn std::vector<float> scalesInput = {0.5}; std::vector<int32_t> zeroPointsInput = {-1}; std::vector<float> scalesWeight(weight_shape[3]); std::vector<int32_t> zeroPointsWeight(weight_shape[3]); for(unsigned int ii = 0; ii < weight_shape[3]; ii++){ scalesWeight[ii]=1; zeroPointsWeight[ii]=0; } int32_t sizeofweight = scalesWeight.size(); std::vector<float> scalesBias(sizeofweight); std::vector<int32_t> zeroPointsBias(sizeofweight); for (int i = 0; i < sizeofweight; i++) { scalesBias[i] = scalesInput[0] * scalesWeight[i]; zeroPointsBias[i] = 0; } std::vector<float> scalesOutput = {0.5}; std::vector<int32_t> zeroPointsOutput = {-1}; tim::vx::Quantization quantInput(tim::vx::QuantType::ASYMMETRIC, 2, scalesInput, zeroPointsInput); tim::vx::Quantization quantWeight(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 3, scalesWeight, zeroPointsWeight); tim::vx::Quantization quantBias(tim::vx::QuantType::SYMMETRIC_PER_CHANNEL, 0, scalesBias, zeroPointsBias); tim::vx::Quantization quantOutput(tim::vx::QuantType::ASYMMETRIC, 2, scalesOutput, zeroPointsOutput); uint32_t weightSize = weight_shape[0] * weight_shape[1] * weight_shape[2] * weight_shape[3]; std::vector<float> weight_data_float(weightSize); for (uint32_t ii = 0; ii < weightSize; ii++) { weight_data_float[ii] = 1; } std::vector<int8_t> weight_data = Quantize<int8_t>(weight_data_float, 1, 0); // bias_data std::vector<int32_t> bias_data(weight_shape[3]); for (uint32_t ii = 0; ii < weight_shape[3]; ii++) { bias_data[ii] = 2; } for (int ww = 32; ww < 97; ww++) { for (int hh = 16; hh < 65; hh++) { input_shape[0] = ww; input_shape[1] = hh; output_shape[0] = (ww + 1) / 2; output_shape[1] = (hh + 1) / 2; tim::vx::TensorSpec input_spec(tim::vx::DataType::INT8, input_shape, tim::vx::TensorAttribute::INPUT, quantInput); tim::vx::TensorSpec weight_spec(tim::vx::DataType::INT8, weight_shape, tim::vx::TensorAttribute::CONSTANT, quantWeight); tim::vx::TensorSpec bias_spec(tim::vx::DataType::INT32, bias_shape, tim::vx::TensorAttribute::CONSTANT, quantBias); tim::vx::TensorSpec output_spec(tim::vx::DataType::INT8, output_shape, tim::vx::TensorAttribute::OUTPUT, quantOutput); uint32_t inputSize = input_shape[0] * input_shape[1] * input_shape[2] * input_shape[3]; std::vector<float> input_data_float(inputSize); for (uint32_t ii = 0; ii < inputSize; ii++) { input_data_float[ii] = 1; } std::vector<int8_t> input_data = Quantize<int8_t>( input_data_float, scalesInput[0], zeroPointsInput[0]); uint32_t goldenSize = output_shape[0] * output_shape[1] * output_shape[2] * output_shape[3]; std::vector<float> golden_float(goldenSize); for (uint32_t ii = 0; ii < goldenSize; ii++) { golden_float[ii] = 128 + 1; } std::vector<int8_t> golden = Quantize<int8_t>(golden_float, scalesOutput[0], zeroPointsOutput[0]); auto ctx = tim::vx::Context::Create(); auto graph = ctx->CreateGraph(); auto input_tensor = graph->CreateTensor(input_spec); auto weight_tensor = graph->CreateTensor(weight_spec, weight_data.data()); auto bias_tensor = graph->CreateTensor(bias_spec, bias_data.data()); auto output_tensor = graph->CreateTensor(output_spec); auto padding = tim::vx::PadType::VALID; std::array<uint32_t, 2> stride({2, 2}); std::array<uint32_t, 2> dilation({1, 1}); auto conv2d = graph->CreateOperation<tim::vx::ops::Conv2d>( padding, stride, dilation); (*conv2d) .BindInput(input_tensor) .BindInput(weight_tensor) .BindInput(bias_tensor) .BindOutput(output_tensor); EXPECT_TRUE(graph->Compile()); input_tensor->CopyDataToTensor(input_data.data()); EXPECT_TRUE(graph->Run()); uint32_t output_size = 1; for (auto i : output_tensor->GetShape()) { output_size *= i; } std::vector<int8_t> output(output_size); EXPECT_TRUE(output_tensor->CopyDataFromTensor(output.data())); EXPECT_EQ(golden, output); } } }
501b0aeb745e1fdf27257938006866896a681886
58e65f021f19b09ce435e02f07085e956ec9d3d3
/psuedocode_section/primecheck.cpp
d1378240f71a074619a32b85e680b98cadc0fada
[]
no_license
sagarr70/coding-blocks-launchpad
58ecafad992d5a387fe60cff791a3b4335eeb9ad
0470c30e9c63f9df6606b3a18b34e9036e1b9281
refs/heads/master
2022-12-10T13:39:33.572265
2020-09-14T06:19:21
2020-09-14T06:19:21
268,731,038
1
0
null
null
null
null
UTF-8
C++
false
false
329
cpp
primecheck.cpp
#include<iostream> using namespace std; int main(){ int n; cin>>n; int flag=0; for (int i = 2; i <n; i++) { if (n%i==0) { flag =1; break; } } if (flag==0) { cout<<"prime no."; } else { cout<<"not a prime no."; } return 0; }
d63f24fa29d7be548cc026be18b405b45c26d4cb
87e70fb5fbf7248af832f5e5670da94b2383219b
/src/test/perf/memcpy/memcpy.cc
e3bee7d2c784911a8b232171ffeb2be7b822bafd
[ "LicenseRef-scancode-generic-cla", "MIT" ]
permissive
microsoft/snmalloc
2398796957201d105a4804f194d617b3b6e24e7c
7b597335aedc2c60b0174f6e67a7f7560f841760
refs/heads/main
2023-09-02T03:03:40.163801
2023-08-25T13:17:04
2023-08-25T13:17:04
164,874,285
1,195
100
MIT
2023-09-14T11:04:14
2019-01-09T14:05:53
C++
UTF-8
C++
false
false
4,275
cc
memcpy.cc
#include "snmalloc/global/memcpy.h" #include <test/measuretime.h> #include <test/opt.h> #include <vector> using namespace snmalloc; struct Shape { void* object; void* dst; }; size_t my_random() { return (size_t)rand(); } std::vector<Shape> allocs; void shape(size_t size) { for (size_t i = 0; i < 1000; i++) { auto rsize = size * 2; auto offset = 0; // Uncomment the next two lines to introduce some randomness to the start of // the memcpys. constexpr size_t alignment = 16; offset = (my_random() % // size / alignment) * alignment; Shape s; s.object = ThreadAlloc::get().alloc(rsize); s.dst = static_cast<unsigned char*>(s.object) + offset; // Bring into cache the destination of the copy. memset(s.dst, 0xFF, size); allocs.push_back(s); } } void unshape() { for (auto& s : allocs) { ThreadAlloc::get().dealloc(s.object); } allocs.clear(); } template<typename Memcpy> void test_memcpy(size_t size, void* src, Memcpy mc) { for (auto& s : allocs) { auto* dst = static_cast<unsigned char*>(s.dst); mc(dst, src, size); } } template<typename Memcpy> void test( size_t size, Memcpy mc, std::vector<std::pair<size_t, std::chrono::nanoseconds>>& stats) { auto src = ThreadAlloc::get().alloc(size); shape(size); for (size_t i = 0; i < 10; i++) { MeasureTime m(true); test_memcpy(size, src, mc); auto time = m.get_time(); stats.push_back({size, time}); } ThreadAlloc::get().dealloc(src); unshape(); } NOINLINE void memcpy_checked(void* dst, const void* src, size_t size) { memcpy<true>(dst, src, size); } NOINLINE void memcpy_unchecked(void* dst, const void* src, size_t size) { memcpy<false>(dst, src, size); } NOINLINE void memcpy_platform_checked(void* dst, const void* src, size_t size) { if (SNMALLOC_UNLIKELY(!check_bounds(dst, size))) { report_fatal_bounds_error(dst, size, ""); return; } memcpy(dst, src, size); } int main(int argc, char** argv) { opt::Opt opt(argc, argv); #ifndef SNMALLOC_PASS_THROUGH bool full_test = opt.has("--full_test"); // size_t size = 0; auto mc_platform_checked = [](void* dst, const void* src, size_t len) { memcpy_platform_checked(dst, src, len); }; auto mc_sn = [](void* dst, const void* src, size_t len) { memcpy_unchecked(dst, src, len); }; auto mc_platform = [](void* dst, const void* src, size_t len) { memcpy(dst, src, len); }; auto mc_sn_checked = [](void* dst, const void* src, size_t len) { memcpy_checked(dst, src, len); }; std::vector<size_t> sizes; for (size_t size = 0; size < 64; size++) { sizes.push_back(size); } for (size_t size = 64; size < 256; size += 16) { sizes.push_back(size); sizes.push_back(size + 5); } for (size_t size = 256; size < 1024; size += 64) { sizes.push_back(size); sizes.push_back(size + 5); } for (size_t size = 1024; size < 8192; size += 256) { sizes.push_back(size); sizes.push_back(size + 5); } for (size_t size = 8192; size < bits::one_at_bit(18); size <<= 1) { sizes.push_back(size); sizes.push_back(size + 5); } std::vector<std::pair<size_t, std::chrono::nanoseconds>> stats_sn, stats_sn_checked, stats_platform, stats_platform_checked; printf("size, sn, sn-checked, platform, platform-checked\n"); size_t repeats = full_test ? 80 : 1; for (auto repeat = repeats; 0 < repeat; repeat--) { for (auto copy_size : sizes) { test(copy_size, mc_platform_checked, stats_platform_checked); test(copy_size, mc_sn, stats_sn); test(copy_size, mc_platform, stats_platform); test(copy_size, mc_sn_checked, stats_sn_checked); } for (size_t i = 0; i < stats_sn.size(); i++) { auto& s1 = stats_sn[i]; auto& s2 = stats_sn_checked[i]; auto& s3 = stats_platform[i]; auto& s4 = stats_platform_checked[i]; std::cout << s1.first << ", " << s1.second.count() << ", " << s2.second.count() << ", " << s3.second.count() << ", " << s4.second.count() << std::endl; } stats_sn.clear(); stats_sn_checked.clear(); stats_platform.clear(); stats_platform_checked.clear(); } #else snmalloc::UNUSED(opt); #endif return 0; }
53199f1f5e766babd7f51d97539d304609242503
a608c63b46da16eb43599f4aa3476403ffbb2adb
/Tema1/Object.h
a3a376ee19a5df352b9b2a82e428201bc00a4318
[]
no_license
Vlad-Gabriel-Popa/Video-Games
5bad818099e0d1f4997dcc7a1d91c16545936d82
c18b6e870d2ac637b0f1c276a1590e198ed88f86
refs/heads/master
2021-01-03T11:12:05.290475
2020-02-12T17:47:11
2020-02-12T17:47:11
240,056,609
0
0
null
null
null
null
UTF-8
C++
false
false
256
h
Object.h
#pragma once class Object { public: Object() {} virtual ~Object() {} virtual std::vector<std::pair<std::string, glm::mat3>> update(glm::ivec2 resolution, float deltaTimeSeconds) = 0; virtual std::vector<glm::vec3> getBoundingBoxes() = 0; };
288aabd2c1c9acd5044b5e092460fe9769cad045
cec051c37e46b4134fa8834f559a70e4d103439b
/include/AnimatedObject.h
3593647f9042d1a71bb87a5ea886110d7135f04e
[]
no_license
HasanYousef/OOP-War-of-Empires
7b52441d6ffac2d8341ca12b7aca11be096fc316
84466cb47598ff9fa6bffb67ecf51aaa5e058f59
refs/heads/main
2023-06-03T04:09:22.897204
2021-06-24T22:15:54
2021-06-24T22:15:54
373,246,668
3
0
null
null
null
null
UTF-8
C++
false
false
349
h
AnimatedObject.h
#pragma once #include "WorldObject.h" #include "Animation.h" class AnimatedObject : public WorldObject { public: AnimatedObject(const sf::Vector2f&); AnimatedObject(const sf::Vector2f&, const bool&); //---build-body----------- virtual void draw(float delta) const { WorldObject::draw(delta); }; virtual sf::Sprite create(float) const = 0; };
40d14ce7b81e78b1d8df4735b98b56c4827179d6
d0c02a6e6355da82480891f7370db6b540301c40
/platform/store/common/frontend/client.h
7e6f67260649ce03fc12151784767844d208bcc7
[ "MIT" ]
permissive
UWSysLab/diamond
08a914c0366c05d02159a7ebc21ba006632b1b48
1beec323c084d9d477c770ca6b9625c8f5682a39
refs/heads/master
2022-07-25T01:32:06.827340
2020-06-11T21:16:06
2020-06-11T21:16:06
66,315,962
22
5
MIT
2022-07-07T20:58:24
2016-08-22T23:35:54
Java
UTF-8
C++
false
false
1,200
h
client.h
// -*- mode: c++; c-file-style: "k&r"; c-basic-offset: 4 -*- // vim: set ts=4 sw=4: /*********************************************************************** * * common/client.h: * Interface for a multiple shard transactional client. * **********************************************************************/ #ifndef _CLIENT_API_H_ #define _CLIENT_API_H_ #include "lib/assert.h" #include "lib/message.h" #include <string> #include <set> #include <map> class Client { public: Client() { }; virtual ~Client() { }; // Begin a transaction. virtual void Begin() = 0; virtual void BeginRO() = 0; // Get the value corresponding to key. virtual int Get(const std::string &key, std::string &value) = 0; // Get the value corresponding to key. virtual int MultiGet(const std::set<std::string> &keys, std::map<std::string, std::string> &value) = 0; // Set the value for the given key. virtual int Put(const std::string &key, const std::string &value) = 0; // Commit all Get(s) and Put(s) since Begin(). virtual bool Commit() = 0; // Abort all Get(s) and Put(s) since Begin(). virtual void Abort() = 0; }; #endif /* _CLIENT_API_H_ */
c11a5d6d462dba09b3ac8f602b843cc6ebefead2
0b92e1ec7fb877457e909de68b67b5c539f03985
/include/timeline.h
b9814531e08cb63ce504721de3e8dbcd925e99e0
[]
no_license
SystemicCypher/krono-engine
27abf1874211cacbca95a3f06a5b43dfb0e6ae64
5d3f490886ba9bfffb25aaeabf05731f12e45d02
refs/heads/master
2020-05-09T12:11:28.045275
2019-10-09T09:45:37
2019-10-09T09:45:37
181,104,812
0
0
null
null
null
null
UTF-8
C++
false
false
1,127
h
timeline.h
#include <string> #include <map> #include <utility> #include <vector> #include "timeperiod.h" class Timeline{ public: // The timeline constructor // It creates a timeline object // that has a Timeline(); // takes in an index to a byte - returns the byte's interpretation // basically returning the flag definition std::string flag_status(size_t byte_index); std::string flag_status(size_t byte_index, size_t bit_index); std::string flag_status(size_t byte_index, size_t bit_index_start, size_t bit_index_end); // The timeline is being changed in some capacity, this changes some flags bool timeline_change(size_t byte_index, size_t bit_index_start, size_t bit_index_end); private: // The linking of bits in the flag array to actual definitions // E.g bits 1 to 3 are std::map<std::pair<size_t, size_t>, std::string> flag_definitions; // An array of bits for flags // It's intended to have a few events that it encodes. // The structure is yet to be defined char* flags; // A vector of time period objects (Timeperiods) // This is what the present state of the timeline is std::vector<TimePeriod> time; };
7d2f79e4e6f5479d4880fcae3c12978ecdfc7aa1
9923a00a9afcd97c2fb02f6ed615adea3fc3fe1d
/Branch/Perception/LaneDetectionMT/armadillo/include/armadillo_bits/spop_sum_meat.hpp
ec72d8e5606990cc1e88b2ea70b194daae732c2f
[ "MIT" ]
permissive
Tsinghua-OpenICV/OpenICV
93df0e3dda406a5b8958f50ee763756a45182bf3
3bdb2ba744fabe934b31e36ba9c1e6ced2d5e6fc
refs/heads/master
2022-03-02T03:09:02.236509
2021-12-26T08:09:42
2021-12-26T08:09:42
225,785,128
13
9
null
2020-08-06T02:42:03
2019-12-04T05:17:57
C++
UTF-8
C++
false
false
1,778
hpp
spop_sum_meat.hpp
// Copyright (C) 2012 Ryan Curtin // Copyright (C) 2012 Conrad Sanderson // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0/. //! \addtogroup spop_sum //! @{ template<typename T1> arma_hot inline void spop_sum::apply(SpMat<typename T1::elem_type>& out, const SpOp<T1,spop_sum>& in) { arma_extra_debug_sigprint(); typedef typename T1::elem_type eT; const uword dim = in.aux_uword_a; arma_debug_check((dim > 1), "sum(): incorrect usage. dim must be 0 or 1"); const SpProxy<T1> p(in.m); if(p.is_alias(out) == false) { spop_sum::apply_noalias(out, p, dim); } else { SpMat<eT> tmp; spop_sum::apply_noalias(tmp, p, dim); out.steal_mem(tmp); } } template<typename T1> arma_hot inline void spop_sum::apply_noalias(SpMat<typename T1::elem_type>& out, const SpProxy<T1>& p, const uword dim) { arma_extra_debug_sigprint(); if(dim == 0) // find the sum in each column { out.zeros(1, p.get_n_cols()); typename SpProxy<T1>::const_iterator_type it = p.begin(); typename SpProxy<T1>::const_iterator_type it_end = p.end(); while(it != it_end) { out.at(0, it.col()) += (*it); ++it; } } else // find the sum in each row { out.zeros(p.get_n_rows(), 1); typename SpProxy<T1>::const_iterator_type it = p.begin(); typename SpProxy<T1>::const_iterator_type it_end = p.end(); while(it != it_end) { out.at(it.row(), 0) += (*it); ++it; } } } //! @}
aeab02d60a274219001c2537891023a3399739a4
f8f4aa67bac6feb1ecf5d5cc43cefde5722cd1e1
/gctest/src/weighted_action.h
4bcdd6f2df5e4620b473809217d4dcbd82d780f7
[]
no_license
SofiaCPP/IPL
a2ad968a09cae74dfb6cd57c067fa1a2e8d9c0c0
4efc456ff03850fa840bfbbc17f30f772562dcf2
refs/heads/master
2023-07-10T01:34:47.943866
2023-02-10T08:03:58
2023-02-10T08:03:58
146,637,650
25
52
null
2023-08-17T07:29:34
2018-08-29T17:51:02
C++
UTF-8
C++
false
false
871
h
weighted_action.h
#pragma once #include <functional> #include <random> #include <vector> template <typename Result, typename Generator> class WeightedActionTable { public: WeightedActionTable(Generator* generator) : m_Generator(generator) {} typedef std::function<Result()> ActionCallback; void AddAction(ActionCallback action, unsigned weight) { m_Actions.emplace_back(action); m_Weights.emplace_back(weight); m_Distribution = std::discrete_distribution(m_Weights.begin(), m_Weights.end()); } Result RunRandomAction() { auto random = m_Distribution(*m_Generator); return m_Actions[random](); } private: std::vector<ActionCallback> m_Actions; std::vector<unsigned> m_Weights; Generator* m_Generator; std::discrete_distribution<int> m_Distribution; };
ed61eb3fb15be1b921e0ce98cbd49fafc9c0f081
d468d856851990af88f1f80412d792e459af2b4f
/xml_parser.h
686ae77e798f52860d5fe38cf1bb1d036bdf0dd4
[]
no_license
jean-marc/objrdf
27ed47a2ff6ee84d65476d3b1c2f5e39a4d24d34
3c83c11a10e2d9697e48bb81dff5a449d6ffb7a8
refs/heads/master
2020-05-17T07:59:00.765844
2017-10-04T18:35:01
2017-10-04T18:35:01
2,861,108
0
0
null
null
null
null
UTF-8
C++
false
false
11,152
h
xml_parser.h
#ifndef XML_PARSER_H #define XML_PARSER_H #include "ebnf.h" #include <iostream> #include <string> #include <map> #include <sstream> #include <math.h> #include <vector> #include <list> #include <algorithm> #include "uri.h" //using namespace std; namespace objrdf{ typedef std::map<objrdf::uri,std::string> ATTRIBUTES; template<typename START,typename STOP> struct _range_:seq<START,kleene_p<not_p<STOP> >,STOP>{}; //CRTP curiously recursive template pattern template<typename SAX_HANDLER> struct xml_parser:char_iterator{ //<?xml version="1.0" encoding="UTF-8"?> typedef seq_c<'<','?'> start_xml_declaration; typedef seq_c<'?','>'> end_xml_declaration; typedef _range_<start_xml_declaration,end_xml_declaration> xml_declaration; typedef seq_c<'<','!','-','-'> start_comment; typedef seq_c<'-','-','>' > end_comment; typedef _range_<start_comment,end_comment> comment; /* <!DOCTYPE rdf:RDF [ <!ENTITY rdfns 'http://www.w3.org/1999/02/22-rdf-syntax-ns#'> <!ENTITY rdfsns 'http://www.w3.org/2000/01/rdf-schema#'> <!ENTITY skosns 'http://www.w3.org/2004/02/skos/core#'> ]> */ typedef seq_c<'<','!'> start_doctype; typedef seq_c<']','>'> end_doctype; typedef _range_<start_doctype,end_doctype> doctype; typedef choice<char_p<' '>,char_p<'\n'>,char_p<'\r'>,char_p<'\t'>> white_space; //namespace support //typedef event<plus_p<choice<range_p<'a','z'>,range_p<'A','Z'>,range_p<'0','9'>,char_p<'_'>,char_p<'-'> > > > nname; typedef plus_p<choice<range_p<'a','z'>,range_p<'A','Z'>,range_p<'0','9'>,char_p<'_'>,char_p<'-'>>> nname; //typedef event<char_p<':'> > colon; //typedef seq<nname,or_p<seq<colon,nname>,true_p> > name; typedef event<nname> prefix; typedef event<nname,int> suffix; typedef seq<prefix,or_p<seq<char_p<':'>,suffix>,true_p>> name; //typedef seq<nname,colon,nname> name; //typedef plus_p<choice<range_p<'a','z'>,range_p<'A','Z'>,range_p<'0','9'>,char_p<'_'>,char_p<'-'> > > name; //struct _prefix;typedef event<name,_prefix> prefix; //struct _suffix;typedef event<name,_suffix> suffix; //typedef name prefix; //typedef name suffix; //typedef seq<prefix,char_p<':'>,suffix> qname; //typedef plus_p<not_p<char_p<' '> > > name; //typedef choice<event<name>,event<qname> > element_name; typedef event<name> element_name; typedef event<name,int> attribute_name; //typedef cb<plus_p<not_p<char_p<'='> > > > attribute_name; typedef event<kleene_p<not_p<char_p<'\''>>>> attribute_value_0; typedef seq<char_p<'\''>,attribute_value_0,char_p<'\''>> attribute_0; typedef event<kleene_p<not_p<char_p<'\"'>>>> attribute_value_1; typedef seq<char_p<'"'>,attribute_value_1,char_p<'"'>> attribute_1; typedef kleene_p<seq<plus_p<white_space>,seq<attribute_name,char_p<'='>,or_p<attribute_0,attribute_1>>>> attributes; //typedef event<seq<char_p<'<'>,element_name,attributes,kleene_p<white_space>,char_p<'>'> > > start_tag; typedef event<seq<char_p<'<'>,element_name,attributes,kleene_p<white_space>>> start_tag; typedef event<seq<char_p<'<'>,char_p<'/'>,element_name,kleene_p<white_space>,char_p<'>'>>> end_tag; typedef event<seq_c<'/','>'>> empty_end_tag; //typedef event<seq<char_p<'<'>,element_name,attributes,kleene_p<white_space>,char_p<'/'>,char_p<'>'> > > empty_element; //will fill up the buffer quickly typedef event<plus_p<not_p<char_p<'<'>>>> text;//could add support for escaping struct element:choice< seq<start_tag,or_p< seq<char_p<'>'>,kleene_p<or_p<text,element> >,end_tag>, //<abc ...>...</abc> empty_end_tag> //<abc .../> >, comment, seq<white_space,element> >{}; typedef seq< kleene_p<white_space>, or_p<xml_declaration,true_p>, kleene_p<white_space>, or_p<doctype,true_p>, element > document; //struct element:or_p<empty_element,seq<start_tag,kleene_p<or_p<text,element> >,end_tag> >{}; /*struct element:choice< seq<start_tag,kleene_p<or_p<text,element> >,end_tag>, empty_element, comment, seq<white_space,element> >{};*/ bool go(){return document::go(*this);} string element_name_p,element_name_s,attribute_name_s,prefix_s,suffix_s; int depth; /* * an array of all the namespaces present in the document, the array can only * grow, replicate are not inserted, the index is used as a reference * */ vector<string> namespaces; struct ns{ string p; string s; int depth; ns(string p,string s,int d):p(p),s(s),depth(d){} }; list<ns> ns_v; xml_parser(istream& is):char_iterator(is){ depth=0; ns_v.push_front(ns("","",depth));//default namespace } //before put in the map struct att_stage{ string prefix; string name; string val; att_stage(string p,string n,string v):prefix(p),name(n),val(v){} }; vector<att_stage> att_v; ATTRIBUTES att_list; bool callback(prefix,string s){ //prefix_s=s; prefix_s.clear(); suffix_s=s; return true; } bool callback(suffix,string s){ prefix_s=suffix_s; suffix_s=s; return true; } bool callback(element_name,string s){ element_name_p=prefix_s; element_name_s=suffix_s; att_list.clear(); //suffix_s.clear(); return true; } bool callback(attribute_name,string s){ attribute_name_s=s; return true; } bool attribute_value(string s){ /* * xmlns='...' default namespace */ if(prefix_s=="xmlns") ns_v.push_front(ns(suffix_s,s,depth)); else if(suffix_s=="xmlns") //default namespace ns_v.push_front(ns("",s,depth)); else att_v.push_back(att_stage(prefix_s,suffix_s,s)); /* if(suffix_s.size()){ if(prefix_s=="xmlns") ns_v.push_back(ns(suffix_s,s,depth)); else att_v.push_back(att_stage(prefix_s,suffix_s,s)); }else att_list[attribute_name_s]=s;//duplicate attribute is an error per XML, here the last instance overrides previous ones */ //suffix_s.clear(); return true; } bool callback(attribute_value_0,string s){return attribute_value(s);} bool callback(attribute_value_1,string s){return attribute_value(s);} struct cmp{ const string prefix; cmp(const string _p):prefix(_p){/*prefix=_p;*/} bool operator()(ns& s) const{return prefix==s.p;} }; void print_ns(){ for(typename list<ns>::iterator i=ns_v.begin();i!=ns_v.end();++i) LOG_DEBUG<<"\t"<<i->p<<"\t"<<i->s<<"\t"<<i->depth<<endl; } bool callback(start_tag,string s){ //need to retrieve all the namespaces //print_ns(); for(typename vector<att_stage>::iterator i=att_v.begin();i<att_v.end();++i){ //LOG<<i->prefix<<" "<<i->name<<" "<<i->val<<endl; typename list<ns>::iterator j=find_if(ns_v.begin(),ns_v.end(),cmp(i->prefix)); if(j!=ns_v.end()){ att_list[objrdf::uri(j->s,i->name)]=i->val; }else{ LOG_ERROR<<"Namespace prefix:`"<<i->prefix<<"' no defined"<<endl; } } att_v.clear(); //if(element_name_s.size()){ typename list<ns>::iterator j=find_if(ns_v.begin(),ns_v.end(),cmp(element_name_p)); if(j!=ns_v.end()){ static_cast<SAX_HANDLER*>(this)->start_element(objrdf::uri(j->s,element_name_s),att_list); }else{ LOG_ERROR<<"Namespace prefix:`"<<element_name_p<<"' no defined"<<endl; } //}else // static_cast<SAX_HANDLER*>(this)->start_element(element_name_p,att_list); depth++; return true; } struct deeper{ const int d; deeper(int _d):d(_d){} bool operator()(ns& s) const{ //LOG<<"deeper? "<<d<<" "<<s.p<<" "<<s.s<<" "<<s.depth<<endl; return d<s.depth; } }; bool callback(end_tag,string s){ static_cast<SAX_HANDLER*>(this)->end_element(objrdf::uri(element_name_s)); //remove all namespaces deeper than current depth depth--; ns_v.remove_if(deeper(depth-1)); return true; } bool callback(empty_end_tag,string s){ static_cast<SAX_HANDLER*>(this)->end_element(objrdf::uri(element_name_s)); depth--; ns_v.remove_if(deeper(depth-1)); return true; } bool callback(text,string s){ static_cast<SAX_HANDLER*>(this)->characters(s); return true; } }; //why is it so convoluted? template<template<typename SAX_HANDLER> class PARSER> struct quiet:PARSER<quiet<PARSER> >{ quiet(istream& is):PARSER<quiet<PARSER> >(is){} bool start_element(objrdf::uri name,ATTRIBUTES att){return true;} bool end_element(objrdf::uri name){return true;} bool characters(string s){return true;} }; template<template<typename SAX_HANDLER> class PARSER> struct generic_xml_parser:PARSER<generic_xml_parser<PARSER> >{ typedef PARSER<generic_xml_parser<PARSER> > BASE; generic_xml_parser(istream& is):BASE(is){}; bool start_element(objrdf::uri name,ATTRIBUTES att){ cout<<"start element `"<<name<<"'\t"<<(char)BASE::is.peek()<<endl; for(ATTRIBUTES::iterator i=att.begin();i!=att.end();++i) cout<<"\t"<<i->first<<"->"<<i->second<<"\n"; return true; } bool end_element(objrdf::uri name){ cout<<"end element `"<<name<<"'"<<endl; return true; } bool characters(string s){ cout<<s.size()<<" character(s) "<<s<<endl; return true; } }; /* template<template<typename SAX_HANDLER> class PARSER> struct xml_xml:PARSER<xml_xml<PARSER> >{ typedef PARSER<xml_xml<PARSER> > BASE; //to be used in bash int depth; xml_xml(istream& is):BASE(is){ depth=0; } bool start_element(string name,ATTRIBUTES att){ if(name=="path"&&att["sodipodi:type"]=="arc"){ //att["jm"]="hello"; float cx=0,cy=0,rx=0,ry=0,start=0,end=0; {istringstream i(att["sodipodi:cx"]);i>>cx;} {istringstream i(att["sodipodi:cy"]);i>>cy;} {istringstream i(att["sodipodi:rx"]);i>>rx;} {istringstream i(att["sodipodi:ry"]);i>>ry;} {istringstream i(att["sodipodi:start"]);i>>start;} {istringstream i(att["sodipodi:end"]);i>>end;} LOG<<cx<<" "<<cy<<" "<<rx<<" "<<ry<<" "<<start<<" "<<end<<endl; ostringstream o; float x_axis_rotation=0; int large_arc_flag=0; int sweep_flag=(start<end); o<<"M "<<cx+rx*cos(start)<<" "<<cy+ry*sin(start)<<" A "<<rx<<" "<<ry<<" "<<x_axis_rotation<<" "<<large_arc_flag<<" "<<sweep_flag<<" "<<cx+rx*cos(end)<<" "<<cy+ry*sin(end); LOG<<o.str()<<endl; LOG<<att["d"]<<endl<<endl; att["d"]=o.str(); } cout<<"<"<<name; for(ATTRIBUTES::iterator i=att.begin();i!=att.end();++i) cout<<" "<<i->first<<"='"<<i->second<<"'"; cout<<">";//\n"; return true; } bool end_element(string name){ cout<<"</"<<name<<">";//\n"; return true; } bool characters(string s){ cout<<s; return true; } }; */ template<template<typename SAX_HANDLER> class PARSER> struct pretty_xml:PARSER<pretty_xml<PARSER> >{ typedef PARSER<pretty_xml<PARSER> > BASE; //to be used in bash int depth; pretty_xml(istream& is):BASE(is){ depth=0; } bool start_element(objrdf::uri name,ATTRIBUTES att){ cout<<"\033[36m<"<<name; for(ATTRIBUTES::iterator i=att.begin();i!=att.end();++i) cout<<" \033[32m"<<i->first<<"\033[m=\033[31m'"<<i->second<<"'"; cout<<"\033[36m>\033[m";//\n"; return true; } bool end_element(objrdf::uri name){ cout<<"\033[36m</"<<name<<">\033[m";//\n"; return true; } bool characters(string s){ cout<<s; return true; } }; } #endif
a27c1bbae17c33b9f7f38ce21e77f3efd8db1292
bc08fd1521dc811e1da1e6ff1edbcc4d8d531130
/main.cpp
15cdc0b3d5a7ad22af096e0c9ea6a739c9927dd8
[]
no_license
zlee-personal/gravity
dabb5c7372bfae9ddd89b4a711fdaeac44d6dae9
d38d3a55e78d23fc4ebcde713a4865d2cf92fde2
refs/heads/master
2022-07-04T00:16:25.201869
2020-05-20T20:53:35
2020-05-20T20:53:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
5,037
cpp
main.cpp
/* CSCI 261 Final Project: Zack and Kenny Go To Space * Author: Zachary Lee * Section B * Author: Kenny Pham * Section C */ #include <SFML/Graphics.hpp> #include <vector> #include <cstring> #include <thread> #include <iostream> #include <mutex> #include <windows.h> #include "Planet.h" #include "functions.h" #include "Entry.h" int main() { const unsigned int WIDTH = 1000; const unsigned int HEIGHT = 1000; std::vector<Planet> planets; // reserve space for 500 planets to avoid copying planets.reserve(500); planets.emplace_back(Planet(10000, Vector2D(500, 500), Vector2D(-1.5, 0))); planets.emplace_back(Planet(1000, Vector2D(500, 200), Vector2D(13, 0))); planets.emplace_back(Planet(10, Vector2D(500, 170), Vector2D(20, 0))); sf::RenderWindow window(sf::VideoMode(WIDTH, HEIGHT), "Gravity"); sf::View view(sf::FloatRect(0.f, 0.f, WIDTH, HEIGHT)); window.setView(view); // if simulation is paused bool paused = false; bool running = true; // if text is being entry bool entering = false; // load font and set it as the static Entry Font (dependency injection) sf::Font font; font.loadFromFile("data/arial.ttf"); Entry::setFont(font); Entry entry; sf::Clock clock; extern std::mutex planets_m; std::thread calculateThread(forwardAll, std::ref(planets), std::ref(paused), std::ref(running)); while (window.isOpen()) { // 60 fps if (clock.getElapsedTime().asMilliseconds() > 16) { clock.restart(); sf::Event event; while (window.pollEvent(event)) { if (event.type == sf::Event::Closed) { window.close(); } else if (event.type == sf::Event::MouseButtonReleased) { Vector2D position(event.mouseButton.x, event.mouseButton.y); entry = Entry(Vector2D(position)); entering = true; } else if (!entering) { if (event.type == sf::Event::KeyPressed) { if (event.key.code == sf::Keyboard::Space) { // check is space key is pressed and toggle paused paused = !paused; } else if (event.key.code == sf::Keyboard::Left) { planets_m.lock(); for (Planet &planet : planets) { // when gravity is all that acts on the planets, // *= -1 ing their velocity makes them seem to travel back in time planet.velocity *= -1; } planets_m.unlock(); } else if (event.key.code == sf::Keyboard::R) { // r clears all planets planets_m.lock(); planets.clear(); planets_m.unlock(); } } else if (event.type == sf::Event::MouseWheelMoved) { if (event.mouseWheel.delta < 0) { view.zoom(0.9 / (event.mouseWheel.delta * -1)); } else if (event.mouseWheel.delta > 0) { view.zoom(event.mouseWheel.delta * 1.1); } window.setView(view); } } else if (entering && event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Return) { // go to next field entry.next(); } else if (entering && event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Escape) { // exit entering entering = false; } else if (entering && event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::BackSpace) { // remove char from entering entry.removeChar(); } else if (entering && event.type == sf::Event::TextEntered && strchr("-1234567890.", event.text.unicode)) { // add char to entering entry.addChar(static_cast<char>(event.text.unicode)); } } if (entering && entry.done()) { if (entry.getMass() > 0) { planets_m.lock(); planets.emplace_back(entry.getMass(), entry.getPosition(), entry.getVelocity()); planets_m.unlock(); redraw(planets, window); } entering = false; } window.clear(); redraw(planets, window); if (entering) { entry.draw(window); } window.display(); } } running = false; calculateThread.join(); return 0; }
bad3ae2632bb60ccb6ed4018c577aedf77c58f7f
8b4c7652384e08b2ab0f41d4d0962c212a1e32aa
/static/integer/binary/logic/bit_manipulation.cpp
6f44cc43edbbf5789da7ada67bf27685fa896686
[ "MIT", "LicenseRef-scancode-free-unknown", "LGPL-3.0-only", "LicenseRef-scancode-public-domain" ]
permissive
stillwater-sc/universal
cd9e63d8672663de6716733c3a59c64f7a745e13
e0d76cdd1f901d3c779ef6c1e8adf8d323b4aa53
refs/heads/main
2023-08-21T14:53:02.747975
2023-08-08T16:14:14
2023-08-08T16:14:14
89,959,055
352
72
MIT
2023-09-07T21:23:58
2017-05-01T20:13:06
C++
UTF-8
C++
false
false
7,715
cpp
bit_manipulation.cpp
// bit_manipulation.cpp : test runner for bit manipulation of abitrary precision fixed-size integers // // Copyright (C) 2017-2022 Stillwater Supercomputing, Inc. // // This file is part of the universal numbers project, which is released under an MIT Open Source license. #include <universal/utility/directives.hpp> #include <iostream> #include <iomanip> #include <string> // configure the integer arithmetic class #define INTEGER_THROW_ARITHMETIC_EXCEPTION 0 #include <universal/number/integer/integer.hpp> #include <universal/number/integer/numeric_limits.hpp> // is representable #include <universal/functions/isrepresentable.hpp> #include <universal/verification/integer_test_suite.hpp> /* The goal of the arbitrary integers is to provide a constrained big integer type that enables fast computation with exceptions for overflow, so that the type can be used for forward error analysis studies. */ namespace sw { namespace universal { // TODO: we need to add a type_trait to integer<> so that we can SFINAE like this: // template<typename UnsignedInteger, // typename = typename std::enable_if< std::is_unsigned<UnsignedInteger>::value, UnsignedInteger >::type > // int VerifyNLZ(bool reportTestCases) { .. } template<unsigned nbits, typename BlockType> int VerifyFindMsb(bool reportTestCases) { using Integer = sw::universal::integer<nbits, BlockType>; int nrOfFailedTests = 0; Integer a(0); int msb = findMsb(a); if (reportTestCases) std::cout << to_binary(a, true) << " : msb at " << msb << '\n'; if (msb != -1) ++nrOfFailedTests; a.setbit(0u); for (unsigned i = 0; i < nbits; ++i) { msb = findMsb(a); if (reportTestCases) std::cout << to_binary(a, true) << " : msb at " << msb << '\n'; if (msb != static_cast<int>(i)) ++nrOfFailedTests; a <<= 1; } return nrOfFailedTests; } } } // namespace sw::universal // test the nlz method which returns the shift required to move the leading non-zero into the most significant bit position of the type void TestNLZ() { using namespace sw::universal; { uint8_t a = 0x1; for (uint32_t i = 0; i < 8; ++i) { int shift = nlz(a); std::cout << " shift = " << shift << " : " << to_binary(a, 8, true) << '\n'; a <<= 1; } } { uint16_t a = 0x1; for (uint32_t i = 0; i < 16; ++i) { int shift = nlz(a); std::cout << " shift = " << shift << " : " << to_binary(a, 16, true) << '\n'; a <<= 1; } } { uint32_t a = 0x1; for (uint32_t i = 0; i < 32; ++i) { int shift = nlz(a); std::cout << " shift = " << shift << " : " << to_binary(a, 32, true) << '\n'; a <<= 1; } } { uint64_t a = 0x1; for (uint32_t i = 0; i < 64; ++i) { int shift = nlz(a); std::cout << " shift = " << shift << " : " << to_binary(a, 64, true) << '\n'; a <<= 1; } } } template<size_t nbits, typename BlockType> void TestSignBitMask() { sw::universal::integer<nbits, BlockType> a{}; std::cout << std::right << std::setw(50) << type_tag(a) << '\n'; std::cout << "EXACT_FIT : " << (a.EXACT_FIT ? "yes\n" : "no\n"); std::cout << "bitsInBlock : " << a.bitsInBlock << '\n'; std::cout << "bitSurplus : " << a.bitSurplus << '\n'; std::cout << "bitsInMSU : " << a.bitsInMSU << '\n'; std::cout << "signBitShift : " << a.signBitShift << '\n'; std::cout << "SIGN_BIT_MASK : " << sw::universal::to_binary(a.SIGN_BIT_MASK, a.bitsInBlock) << '\n'; std::cout << "SIGN_EXTENTION_BITS : " << sw::universal::to_binary(a.SIGN_EXTENTION_BITS, a.bitsInBlock) << '\n'; std::cout << "MSU_MASK : " << sw::universal::to_binary(a.MSU_MASK, a.bitsInBlock) << '\n'; } void TestBitMasks() { TestSignBitMask<3, uint8_t>(); TestSignBitMask<4, uint8_t>(); TestSignBitMask<5, uint8_t>(); TestSignBitMask<6, uint8_t>(); TestSignBitMask<7, uint8_t>(); TestSignBitMask<8, uint8_t>(); TestSignBitMask<9, uint8_t>(); TestSignBitMask<10, uint8_t>(); TestSignBitMask<11, uint8_t>(); TestSignBitMask<12, uint8_t>(); TestSignBitMask<12, uint16_t>(); TestSignBitMask<16, uint16_t>(); TestSignBitMask<28, uint32_t>(); TestSignBitMask<32, uint32_t>(); TestSignBitMask<56, uint64_t>(); TestSignBitMask<60, uint64_t>(); TestSignBitMask<64, uint64_t>(); } // Regression testing guards: typically set by the cmake configuration, but MANUAL_TESTING is an override #define MANUAL_TESTING 1 // REGRESSION_LEVEL_OVERRIDE is set by the cmake file to drive a specific regression intensity // It is the responsibility of the regression test to organize the tests in a quartile progression. //#undef REGRESSION_LEVEL_OVERRIDE #ifndef REGRESSION_LEVEL_OVERRIDE #undef REGRESSION_LEVEL_1 #undef REGRESSION_LEVEL_2 #undef REGRESSION_LEVEL_3 #undef REGRESSION_LEVEL_4 #define REGRESSION_LEVEL_1 1 #define REGRESSION_LEVEL_2 1 #define REGRESSION_LEVEL_3 1 #define REGRESSION_LEVEL_4 1 #endif int main() try { using namespace sw::universal; std::string test_suite = "Integer bit manipulation verification"; std::string test_tag = "bit manipulators"; bool reportTestCases = false; int nrOfFailedTestCases = 0; ReportTestSuiteHeader(test_suite, reportTestCases); #if MANUAL_TESTING { using Integer = integer<16, uint16_t>; constexpr Integer a(SpecificValue::maxpos), b(SpecificValue::maxneg); int i = int(b); std::cout << i << '\n'; std::cout << b << '\n'; Integer c; c = a + b; std::cout << a << " + " << b << " = " << c << '\n'; std::cout << to_binary(a, true) << " + " << to_binary(b, true) << " = " << to_binary(c) << '\n'; } TestNLZ(); // TODO: we should have a native int TestBitMasks(); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 40, uint64_t>(reportTestCases), "integer< 40, uint64_t>", test_tag); ReportTestSuiteResults(test_suite, nrOfFailedTestCases); return EXIT_SUCCESS; // ignore failures #else #if REGRESSION_LEVEL_1 test_tag = "findMsb"; nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 4, uint8_t >(reportTestCases), "integer< 4, uint8_t >", test_tag); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 8, uint8_t >(reportTestCases), "integer< 8, uint8_t >", test_tag); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 12, uint8_t >(reportTestCases), "integer< 12, uint8_t >", test_tag); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 20, uint16_t>(reportTestCases), "integer< 20, uint16_t>", test_tag); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 40, uint16_t>(reportTestCases), "integer< 40, uint16_t>", test_tag); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 40, uint32_t>(reportTestCases), "integer< 40, uint32_t>", test_tag); nrOfFailedTestCases += ReportTestResult(VerifyFindMsb< 40, uint64_t>(reportTestCases), "integer< 40, uint64_t>", test_tag); #endif #if REGRESSION_LEVEL_2 #endif #if REGRESSION_LEVEL_3 #endif #if REGRESSION_LEVEL_4 #endif ReportTestSuiteResults(test_suite, nrOfFailedTestCases); return (nrOfFailedTestCases > 0 ? EXIT_FAILURE : EXIT_SUCCESS); #endif // MANUAL_TESTING } catch (char const* msg) { std::cerr << "Caught ad-hoc exception: " << msg << std::endl; return EXIT_FAILURE; } catch (const sw::universal::universal_arithmetic_exception& err) { std::cerr << "Caught unexpected universal arithmetic exception : " << err.what() << std::endl; return EXIT_FAILURE; } catch (const sw::universal::universal_internal_exception& err) { std::cerr << "Caught unexpected universal internal exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (const std::runtime_error& err) { std::cerr << "Caught runtime exception: " << err.what() << std::endl; return EXIT_FAILURE; } catch (...) { std::cerr << "Caught unknown exception" << '\n'; return EXIT_FAILURE; }
e9871bec3d4ae756bb9bc2b59651114ab438dabc
3efc50ba20499cc9948473ee9ed2ccfce257d79a
/data/code-jam/files/3224486_y0105w49_5632366324219904_0_extracted_D.cpp
1e80021f8cd33e84f557039a13db41402a29dab0
[]
no_license
arthurherbout/crypto_code_detection
7e10ed03238278690d2d9acaa90fab73e52bab86
3c9ff8a4b2e4d341a069956a6259bf9f731adfc0
refs/heads/master
2020-07-29T15:34:31.380731
2019-12-20T13:52:39
2019-12-20T13:52:39
209,857,592
9
4
null
2019-12-20T13:52:42
2019-09-20T18:35:35
C
UTF-8
C++
false
false
680
cpp
3224486_y0105w49_5632366324219904_0_extracted_D.cpp
#include <bits/stdc++.h> using namespace std; int N,L; string G[120],B; int main() { int t; cin>>t; for(int zz=1;zz<=t;zz++) { cin>>N>>L; for(int i=0;i<N;i++) cin>>G[i]; cin>>B; for(char c:B) assert(c=='1'); for(int i=0;i<N;i++) { for(char c:G[i]) if(c=='0') goto good; goto die; good:; } if(L==1) { printf("Case #%d: 1? 1\n",zz); continue; } printf("Case #%d: 1010101010101010101010101010101010101010101010101010101010101010?101010101010101010101010101010101010101010101010101010101010101 ",zz); L--; for(;L--;) cout<<'?'; cout<<endl; continue; die: printf("Case #%d: IMPOSSIBLE\n",zz); } }
5f260cced8e7ace620a246181d02534bf11b7eb1
d3567e3e6c23d662f84256298638e678ef6bd8ae
/string_sort.cpp
118e0588129f80cf16904b1c69e9f887e600f0c0
[]
no_license
andpar83/filesort
a4ff2823fc1e82111ce58f91a93eb8f0b32dc5da
6dae1bd9793d4a9823ae0c140cb85fbfa54583bf
refs/heads/master
2016-09-06T05:13:14.424242
2015-08-23T21:08:01
2015-08-23T21:08:01
41,266,975
0
0
null
null
null
null
UTF-8
C++
false
false
2,798
cpp
string_sort.cpp
#include "string_sort.h" #include <cstdint> #include <utility> #include <algorithm> #include <future> namespace fs { namespace utils { namespace impl { struct positional_less_comparator { positional_less_comparator(size_t p) : pos(p) { } bool operator()(const light_string& lhs, const light_string& rhs) { if (pos >= lhs.size() || pos >= rhs.size()) return lhs.size() < rhs.size(); auto r = memcmp(lhs.data() + pos, rhs.data() + pos, std::min(lhs.size() - pos, rhs.size() - pos)); if (r) return r < 0; return lhs.size() < rhs.size(); } size_t pos; }; std::pair<std::int64_t, std::int64_t> string_partition ( std::vector<light_string>& data, const size_t lo, const size_t hi, const size_t pos ) { assert(lo <= hi && hi < data.size()); auto lt = lo, gt = hi; const auto pivot = data[lo].get_char(pos); for (auto i = lo + 1; i <= gt;) { const auto cur = data[i].get_char(pos); if (cur < pivot) { std::swap(data[lt], data[i]); ++lt; ++i; } else if (cur > pivot) { std::swap(data[i], data[gt]); --gt; } else ++i; } return std::make_pair(static_cast<std::int64_t>(lt) - 1, gt + 1); } void string_sort(std::vector<light_string>& data, const std::int64_t lo, const std::int64_t hi, const size_t pos); std::future<void> run_async_sort(std::vector<light_string>& data, const std::int64_t lo, const std::int64_t hi, const size_t pos) { const size_t MIN_PARALLEL_SIZE = 50000; std::future<void> result; if (hi + 1 - lo >= MIN_PARALLEL_SIZE) result = std::async(&string_sort, std::ref(data), lo, hi, pos); return result; } void string_sort(std::vector<light_string>& data, const std::int64_t lo, const std::int64_t hi, const size_t pos) { if (hi <= lo) return; const auto part = string_partition(data, static_cast<size_t>(lo), static_cast<size_t>(hi), pos); const auto less_last_index = part.first; const auto greater_first_index = part.second; std::future<void> future_less = run_async_sort(data, lo, less_last_index, pos); std::future<void> futute_greater = run_async_sort(data, greater_first_index, hi, pos); if (!future_less.valid()) string_sort(data, lo, less_last_index, pos); if (!futute_greater.valid()) string_sort(data, greater_first_index, hi, pos); // This partition is not empty and if strings are not finished // (by length, which means that get_char returns -1) yet, continue sorting by next symbol if (data[static_cast<size_t>(less_last_index + 1)].get_char(pos) >= 0) string_sort(data, less_last_index + 1, greater_first_index - 1, pos + 1); if (future_less.valid()) future_less.wait(); if (futute_greater.valid()) futute_greater.wait(); } } void string_sort(std::vector<light_string>& data) { impl::string_sort(data, 0, static_cast<std::int64_t>(data.size()) - 1, 0); } }}
7a699b63ee58816243b67cd94a0d23aa23802e5a
5710362898c0e7e55cce568c01d508e1e298ee73
/linux/CThread.cpp
f0f1bae8a397039150da5eea3d23a886fd2c916a
[]
no_license
zhenyatnk/LockType
bb21e330fc118791df8f2dffda202c0c3a35c546
c2fc7c165605f286fba660382894430eadb463c5
refs/heads/master
2021-01-10T01:48:53.358441
2016-02-25T17:53:23
2016-02-25T17:53:23
36,813,285
1
0
null
null
null
null
UTF-8
C++
false
false
774
cpp
CThread.cpp
#include <pthread.h> #include "../intf/IThread.h" //---------------------------------------------------------- class CPosixRunnerThread : public IRunnerThread { public: virtual bool Start(IThread* aObj); virtual bool Wait(); virtual void Close(); private: pthread_t thread; }; //---------------------------------------------------------- bool CPosixRunnerThread::Start(IThread* aObj) { return 0 == pthread_create(&thread, NULL, IThread::thread_func, (void*)aObj); } bool CPosixRunnerThread::Wait() { return 0 == pthread_join(thread, NULL); } void CPosixRunnerThread::Close() { } //------------------------------------------------------------------------- IRunnerThread::Ptr IRunnerThread::Create() { return IRunnerThread::Ptr(new CPosixRunnerThread()); }
7986c940e963be1338c0defa162e8e06ad60c2ae
4954faea3f92757e1456cfd20da71e1aeb6005f0
/classe_aluno.cpp
e3941d9fe178c76bd8ae2c448861545079eddee2
[]
no_license
lucasbat/classe_aluno
65d53b62839e229a50afc1f1e2666aeba43cb4e7
d70b2e0a04ddeadba89f1337d3ed6fc70211ca65
refs/heads/master
2021-05-10T08:54:59.245775
2018-01-25T12:32:27
2018-01-25T12:32:27
118,910,110
0
0
null
null
null
null
UTF-8
C++
false
false
1,210
cpp
classe_aluno.cpp
/* Programa que implementa uma classe chamada aluno para calcular mensalidades de acordo situacao: sem bolsa, meio-bolsista ou bolsista. */ #include<iostream> #include<string> using namespace std; class Aluno{ private: string nome; int qtd; public: Aluno(){ qtd=0; } ~Aluno(){} void set_dados(){ cout<<"\nDigite o Nome: "; getline(cin,nome); cout<<"\nDigite qtd de disciplinas: "; cin>>qtd; cin.ignore(); } void print_dados(){ cout<<"\nNome: "<<nome; cout<<"\nQtd de Disciplinas: "<<qtd; } float mensalidade(){ float ma; ma=(200*qtd); return ma; } }; class Bolsista:public Aluno{ public: float mensalidade(){ float mb; mb=Aluno::mensalidade(); return mb*0.5; } }; class Meio_Bolsista:public Aluno{ public: float mensalidade(){ float mmb; mmb=Aluno::mensalidade(); return mmb*0.75; } }; int main(){ Aluno X; Bolsista Y; Meio_Bolsista Z; X.set_dados(); X.print_dados(); cout<<"\nSua mensalidade e de: "<<X.mensalidade(); Y.set_dados(); Y.print_dados(); cout<<"\nSua mensalidade e de: "<<Y.mensalidade(); Z.set_dados(); Z.print_dados(); cout<<"\nSua mensalidade e de: "<<Z.mensalidade(); cout<<"\n\n"; return 0; }
544886633bd4882f629833fe498fc24f9637e60c
89b935080c6eb26043cc82100729637c4b978073
/src/ssd1327.h
ba566e018c8a117d59b6059cf251104f7f3a178a
[ "Apache-2.0" ]
permissive
markbirss/ssd1327Grayscale
f8e14b3f1bc5edf998dc08c7034151c2dd6f5077
fb8622d5f45beaa68a50d85ba0ba58a512f9ed0b
refs/heads/master
2023-07-25T23:28:21.580576
2020-11-24T11:19:08
2020-11-24T11:19:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,225
h
ssd1327.h
/* * SSD1327 Grayscale driver library for SSD1327 over I2C. * */ #ifndef SSD1327_MAX_I2C_BUFFER #define SSD1327_MAX_I2C_BUFFER 32 #endif #ifndef SSD1327_MAX_SPI_BUFFER #define SSD1327_MAX_SPI_BUFFER 32 #endif #include <stdint.h> namespace Ssd1327 { class Interface { /** * Virtual methods to be implemented for writing data to the display over an. * interaface. E.g. I2C, SPI, 6800 or 8080. * */ public: static const int8_t NO_PIN = -1; virtual void begin(); /** * Try to reset the display module by reset pin, returns false if not * possible so the Ssd1327 instance can do a software reset. * * @return bool Reset succeeded or not. */ virtual bool hwReset(); /** * Do an initialisation before sending data, can be left emtpy if not * required. */ virtual void beginTransmission()=0; /** * Close a connection after sending data, can be left emtpy if not required. * @return Status of the transmission, 0 for success, other depending in the * platform. */ virtual uint8_t endTransmission()=0; /** * Write a byte. * @param byte to send to the display module. */ virtual void write(uint8_t byte)=0; /** * Send command to the display module. * @param command. */ virtual uint8_t sendCommand(uint8_t command)=0; /** * Send command args to the display module. * @param arg pointer to arg bytes to send to the module. * @param len Amount of bytes to send. */ virtual uint8_t sendCommand(uint8_t* command, uint8_t len)=0; /** * Write data to the display module. * @param data pointer to bytes to send to the module. * @param len Amount of bytes to send. */ virtual uint8_t sendData(uint8_t* data, uint16_t len)=0; enum class InterfaceType: uint8_t { Spi = 0, I2c = 1 } ; uint8_t type; }; class Implementation { public: /** * SSD1327 Commands. * * Enumeration of all SSD1327 commands, description in comments. If the * command needs arguments, it shows what arguments are expected too. E.g.: * * arg1 A[4:0], arg2 B[3:0] arg3 B[4:7] * * In the brackets is the valid range for the argument, interpret the numbers * as the starting bit from lowest order to highest, followed by the end bit. * Thus the example above shows arg1 a having a 5 bit value (0x00 - 0x1f), * arg2 is placed in the 4 lowest order nibble of the */ enum class Cmd: uint8_t { // Set column start and end addresses: start A[6:0], end B[5:0]. SetColumnRange = 0x15, // Set row start and end addresses: start A[5:0], end B[5:0]. SetRowRange = 0x75, // Set contrast: contrast A[7:0] SetContrastLevel = 0x81, /** Set remapping of GDDRAM: [ 0b A6 0b A4 0b A2 A1 A0 ] * A[0]: * 0b, Column address remap off * 1b, Column address remap on (swaps the rendering direction from right * to left, to left to right. Use with Nibble remapping to mirror * the image. * A[1]: Nibble remapping * 0b, Off * 1b, On (swaps first and last 4 bits of a byte, effectively swapping 2 * pixels). Use with column remapping to mirror the image. * A[2]: Address increment mode * 0b, Horizontal address increment, a.k.a. renders lines left to right, * top to bottom. * 1b, Vertical address increment, a.k.a. render lines top to bottom, * left to right. * A[4]: Com remapping * 0b, Off * 1b, On * A[6]: COM Split Odd Even, the controller is connected to the display * lines from the left and right and right side. The left and right * side coms alternate lines, the left side coms are connected to * uneven display rows, the right side coms are connected to the * even rows, but the numbering of the controller bus is sequential. * The controller com lines are though split through the middle, * The left side coms from left to right are 127 - 64, the right * side coms from left to right are 0 - 63. In the default mode (0b) * the lines are interleaved to match the com lines with the display * lines, when set to off (1b) your lines will be displayed in the * wrong order, in other words you will have to interleave the image * yourself. * 0b, On (default, good) * 1b, Off (bad) * Use these with the remapping enum and apply an OR operator to combine * them. */ SetRemapping = 0xa0, // Set display start line: start [6:0] (128 lines, 0 - 127). SetStartLine = 0xa1, /** * Set display offset, changes vertical memory (row) to display line (com) * mapping. E.g. set it to 40, row 0 in memory will be mapped to com39 on * the display shifting the image down and wrapping around to show the * bottom of the image at the top of the diplay, above display line 39. * All this assumes you have MUX set to the default of 128 and you didn't * use remap commands: offset [6:0]. */ SetDisplayOffset = 0xa2, // Normal diplay mode. SetDisplayNormal = 0xa4, // Power on all OLEDs, max power. SetDisplayAllOn = 0xa5, // Power off all OLEDs. SetDisplayAllOff = 0xa6, // Inverted display mode, considers grayscale. SetDisplayInverse = 0xa7, /** * Set multiplex ratio how many lines the display should multiplex. In * effect it controls how many rows are rendered. Combine with * SetDisplayOffset to render only part of the display: [ 0x10 - 0x80 ], * corrresponds to 16MUX-128MUX apply required mux ratio -1, e.g. send 127 * for 128MUX (default), values under 15 are invalid: ratio [6:0]. */ SetMuxRatio = 0xa8, /** * Enable/Disable the internal VDD regulator (for internal core logic * operation). This is required to match the wiring of the display. * enable A[0:0] */ EnableVddRegulator = 0xab, // Switch the display "off" (sleep mode). DisplayOff = 0xae, // Switch the display on. DisplayOn = 0xaf, /** * Set phase length of pre charging circuit for driving OLEDs: two nibbles * for setting the duration of resetting (phase 1) and pre charging * (phase 2) the OLED capacitor, in steps from 1 - 15 DCLK cycles. * 0 is not a valid reset / pre charge phase time. PWM set in GS15 should * be larger than the precharge cycles added up. The required phase length * depends on the capacity of the capacitor on the OLED, if it has higher * capacity, (dis)charging takes longer: * reset A[3:0], precharge a[7:4]. */ SetPhaseLength = 0xb1, // Send the GPU a NOP (no operation, do nothing instruction). SendNoOp = 0xb2, /** * Set display clock frequency (DCLK) and frequency divider. * Sets the frequency of rendering pixels, and the frequency divider. * The DCLK can be set between 535 and 655KHz, in 16 levels (4 bits). The * divide ratio can be set in 16 levels as well: divide A[3:0], * frequency A[7:4]. */ SetDisplayClock = 0xb3, // Set the GPIO to, low (00b), Hi-Z (01b) or high (11b).: gpio A[1:0]. SetGpio = 0xb5, /** * Set second pre-charge period, requires second pre-charge to be enabled * by the enable functionSelection command. Second pre charge time can be * set to 0 to 15 DCLKs: precharge A[3:0] * This is the third phase of driving pixels. */ SetSecondPrechargePeriod = 0xb6, /** * Set grayscale table, sets the brightness of each of the 16 selectable * levels of the grayscale. The brightness is set in pulse width of 6 bit * pulses of the DCLK, level zero is always zero, you can set the other * 15 levels per byte. This controls phase 4 of driving pixels: 15x A[5:0]. */ SetGrayscaleLevels = 0xb8, // Controls brightness /** * Reset grayscale levels to linear default (GS0: 0, GS1: 0, GS2: 2 - for * GS3 - GS14. Also resets phase 4 of pixel driving to default: * `(GS-1)*2`, GS15 28). */ resetGrayscale = 0xb9, // Default brightness // Send the GPU a NOP (no operation, do nothing instruction). // SendNoOp = 0xbb, /** * Set precharge voltage level relative to VCC, on a non-lineary scale * This is the voltage applied to OLED pixels.:level A[3:0], example * values: * 0x00: 0.2 * VCC * ... * 0x05: 0.5 * VCC (default) * ... * 0x07: 0.613 * VCC * 0x08: VCOMH * */ SetPreChargeVoltage = 0xbc, /** * Set COM deselect voltage level relative to VCC, on a non-lineary scale: * level A[2:0], example values: * 0x00: 0.72 * VCC * ... * 0x05: 0.82 * VCC (default) * ... * 0x07: 0.86 * VCC * This voltage should be sufficiently high such that the OLED bias is * reversed (in which state it can't emit light). This voltage supply is * used to reverse all OLEDs in a segment that is deselected. */ SetComDeselectVoltage = 0xbe, /** * Enable/Disable second pre-charge (phase 4) of the OLED driver. * Enable/Disable controls whether the low level voltage reference (Vsl) of * the driver should be regulated internally or externally: * disable A[0:0], vsl A[1:1] */ FunctionSelectionB = 0xd5, /** * Makes the display controller ignore any command expect for the unlock * command (same command with different argument). Use * `Implementation::Const::McuProtectEnable` to construct the argument, * OR is with 0x04 to enable the lock, or send it as is, to unlock it: * lock A[3:0] OR Implementation::Const::McuProtectEnable. */ McuProtectEnable = 0xfd, /** * Set the parameters for scrolling horizontally: pixel range and timing. * You can scroll any range on the display by specifying the start and end * rows and columns. You can set the scroll speed relative to the frame * rate: * dummy A[7:0]: mandatory empty byte, * rowStart B[6:0]: 0x00 - 0x7f (row 1 - 128) * interval C[2:0]: 3 bit interval according to a predefined table. * The interval is specified by an amount of frames, so * it depends on the framerate. You can use enum * ScrollSpeed to set the interval. * rowEnd D[6:0] 0x00 - 0x7f (row 1 - 128), > rowStart * columnStart E[5:0]: 0x00 - 0x3f (column 1 - 64) * * columnEnd F[5:0]: 0x00 - 0x3f (column 1 - 64) > columnStart */ SetHorizontalScrollRight= 0x26, // Same as SetHorizontalScrollRight, except it scrolls left. SetHorizontalScrollLeft = 0x27, ActivateScroll = 0x2f, DectivateScroll = 0x2e }; /** * SSD1327 constants. * * Enumeration of all SSD1327 constants, description in comments. */ enum class Const: uint8_t { // Protect command needs to be this value ORed with 0x04 to enable or as is // to disable protection. McuProtectEnableBase = 0b00010010, McuProtectLockMask = 0b00000100, ComSplitOddEvenOnMask = 0b01000000, ComRemappingOnMask = 0b00010000, HorizontalAddressIncrementMask = 0b01000100, NibbleRemappingOnMask = 0b00000010, GddrRemappingOnMask = 0b00000001, FunctionSelectionBBase = 0b01100000, }; /** * SSD1327 default values from the manual. */ enum class Default: uint8_t { ContrastLevel = 0xff, Remapping = (uint8_t)Const::ComSplitOddEvenOnMask, StartLine = 0x00, DisplayOffset = 0x00, PhaseLength = 0xf1, PixelResetPeriod = 0xf0, FirstPrechargePeriod = 0x01, SecondPrechargePeriod = 0x04, DisplayClockFrequency = 0x00, DisplayClockDivider = 0x00, PreChargeVoltage = 0x05, ComDeselectVoltage = 0x05, FunctionSelectionB = 0x62, }; /** * Horizontal Scrollspeed constants. */ enum class ScrollSpeed: uint8_t { Frames_2 = 0b111, Frames_3 = 0b100, Frames_4 = 0b101, Frames_5 = 0b110, Frames_6 = 0b000, Frames_32 = 0b001, Frames_64 = 0b010, Frames_256 = 0b011 }; enum class GpioMode: uint8_t { InputDisable = 0b00, InputEnable = 0b01, Output = 0b10 }; /** * Create an instance of the OLED driver. * * @param Ssd1327::Interface OLED interface struct. */ Implementation(uint8_t width, uint8_t height); uint8_t setColumnRange(uint8_t start, uint8_t end); uint8_t setRowRange(uint8_t start, uint8_t end); uint8_t resetRange(); uint8_t setDisplayOff(); uint8_t setDisplayOn(); uint8_t setDisplayOffset(uint8_t offset); uint8_t setDisplayNormal(); uint8_t setDisplayAllOn(); uint8_t setDisplayAllOff(); uint8_t setDisplayInverse(); uint8_t setContrastLevel(uint8_t level); uint8_t setRemapping( bool comSplitOddEven, bool comRemapping, bool horizontalAddressIncrement, bool nibbleRemapping, bool gddrRemapping ); uint8_t resetRemapping(); uint8_t setStartLine(uint8_t line); uint8_t setMuxRatio(uint8_t ratio); uint8_t resetMuxRatio(); uint8_t enableVddRegulator(bool state); uint8_t setPhaseLength(uint8_t phaseLen); /** * Set the time to discharge the OLED pixel capacitor. * * Note: this does not map to an exact command in the manual because this * setting is combined with the first pre-charge period in one byte and send * by the Cmd::SetPhaseLength command. If you need to set both these values * it's better to use the setPhaseLength function because it will send both * values to the module in 1 write action. * @param period for the OlED drivers first pre charge, only low 4 lowest * order bits are considered, minium value: 1. */ uint8_t setPixelResetPeriod(uint8_t period); /** * Set the time to pre charge the OLED pixel driver. * * Note: this does not map to an exact command in the manual because this * setting is combined with the pixel reset period in one byte and send by * the Cmd::SetPhaseLength command. If you need to set both these values it's * better to use the setPhaseLength function because it will send both values * to the module in 1 write action. * @param period for the OlED drivers first pre charge, only low 4 lowest * order bits are considered, minium value: 1. */ uint8_t setFirstPrechargePeriod(uint8_t period); uint8_t setSecondPrechargePeriod(uint8_t period); uint8_t sendNoOp(); uint8_t setDisplayClock(uint8_t clock, uint8_t divider); uint8_t setGpio(bool state); uint8_t setGpioMode(GpioMode mode); uint8_t setGrayscaleLevels(uint8_t* grayScaleMap); uint8_t resetGrayscale(); uint8_t setPreChargeVoltage(uint8_t voltage); uint8_t setComDeselectVoltage(uint8_t voltage); uint8_t functionSelectionB(uint8_t selection); uint8_t enableSecondPrecharge(bool state); uint8_t enableVslRegulator(bool state); uint8_t mcuProtectEnable(); uint8_t mcuProtectDisable(); // uint8_t setHorizontalScrollRight(); // uint8_t setHorizontalScrollLeft(); // uint8_t activateScroll(); // uint8_t dectivateScroll(); uint8_t clear(); uint8_t init(); uint8_t getHeight(); uint8_t getWidth(); uint8_t renderImageData( uint8_t x, uint8_t y, uint8_t width, uint8_t height, uint8_t *image, uint16_t len ); uint8_t reset(); Interface* interface; private: uint8_t _width; uint8_t _height; uint8_t _phaseLen = (uint8_t) Default::PhaseLength; uint8_t _functionSelB = (uint8_t) Default::FunctionSelectionB; GpioMode _gpioMode; /** * Platform independent wait function. * Apply a wait/delay/sleep/timer interrupt that suits your platform. * * @param ms to wait. */ virtual void _waitms(uint16_t ms)=0; }; };
8e64a5b0aa1fd95fcf6575538fd3ca2b732f7942
53fa6e3e8f305e131ff3d7731579715ecdbbff48
/Dynamic Programming/Unbounded Knapsack/Unbounded knapsack variation/3 Coin changed MIN no. of coins/MIn cions.cpp
5225e629769816e5fe224a5f85089515ff387f6a
[]
no_license
swapnilghule/dynamic-programming
2661a5bed733a54528f4aef2c935bb074478241e
e883f4a83dabf291b7dfa19e1591cb956a8f508e
refs/heads/main
2023-02-12T18:19:25.324736
2021-01-20T10:47:24
2021-01-20T10:47:24
331,276,255
0
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
MIn cions.cpp
#include<bits/stdc++.h> using namespace std; int t[200][2000]; int knapsack(int a[],int sum,int n) { for(int i=1;i<n+1;i++) { for(int j=1;j<sum+1;j++) { if(a[i-1]<=j) t[i][j]=min((t[i][j-a[i-1]]+1) , t[i-1][j]); else t[i][j]=t[i-1][j]; } } return t[n][sum]; } int main() { int n; cin>>n; int sum; int coins[n]; for(int i=0;i<n;i++) cin>>coins[i]; cin>>sum; for(int i=0;i<n+1;i++) { for(int j=0;j<sum+1;j++) { if(j==0) t[i][j]=0; if(i==0) t[i][j]=INT_MAX - 1; if(j%coins[0]==0) t[i][j]=j/coins[0]; else t[i][j]=INT_MAX - 1; } } int k=knapsack(coins,sum,n); cout<<k; return 0; }
223b90b783e60c7542eabcec42139fb6e0177aa5
99cc08be9f7cc2246218c2b1eaea785866094e64
/Lab9/menu.cpp
d3436be2d8b2e1cfcf635c1a26fcf58f7762526b
[]
no_license
EdgarH90/Lab9-Stack-Queue
46955ea38ad3f4e734e387d4aab52970db814875
b765ebdeeba6583811d343e250d6bdc3f1b40100
refs/heads/master
2022-05-06T20:56:20.057386
2019-12-07T03:14:18
2019-12-07T03:14:18
225,083,684
0
0
null
null
null
null
UTF-8
C++
false
false
2,634
cpp
menu.cpp
/******************************************************************************* ** Author: Edgar Hernandez ** Date: 11/30/2019 ** Description: This program contains the specification for the menu functions. ** It contains the main menu for stack palindrome and queue buffer functions and a ** submenu to display the options for each specific function. *******************************************************************************/ #include <string> #include <iostream> #include <sstream> #include <fstream> #include <iomanip> #include <climits> #include "menu.hpp" #include "inputValidation.hpp" // The function takes validates the user's choice and passes the value to the submenu void menu() { int status = 0; std::string errorMsg = "Please select a valid integer and press enter."; while (status != 3) { std::cout << "Please select the number for the function you would " << "like to run and press enter: " << std::endl; //User choices std::cout << "1. Create a palindrome." << std::endl; std::cout << "2. Test the buffer." << std::endl; std::cout << "3. Exit." << std::endl; inputValidation(status, errorMsg, 1, 3); if (status != 3) { subMenu(status, errorMsg); } } } //This function runs the Queue functions based on the user input void subMenu(int& userChoice, std::string& error) { if (userChoice == 1) { //Initialize the string for user input std::string userstrIn = ""; std::cout << "Please enter the string for the palindrome." << std::endl; std::getline(std::cin, userstrIn); //Run palindrome string function and reset to menu std::cout<< palindromeFunc(userstrIn) << std::endl; } else { ////Initialize the variables needed for the queue function int rounds = 0, addPercent = 0, removePercent = 0; std::cout << "How many rounds would you like to simulate? (max of 50) \n"; inputValidation(rounds, error, 1, 50); std::cout << "Enter the percentage chance to put a randomly generated number \n" << "at the end of the buffer. Use whole numbers from 1-100." << std::endl; inputValidation(addPercent, error, 1, 100); std::cout << "Enter the percentage chance to take out a randomly generated number \n" << "at the front of the buffer. Use whole numbers from 1-100." << std::endl; inputValidation(removePercent, error, 1, 100); buffer(rounds, addPercent, removePercent); } //Repeat options std::cout << "Would you like to run another function?" << std::endl; std::cout << std::setw(10) << "1. Yes " << "2. No " << std::endl; inputValidation(userChoice, error, 1, 2); if (userChoice == 2) { userChoice = 3; } }
74ac44a702984a7bb61e1ae08506f50ef9a7acb1
539fc5ad4ddcf095f51259aa2f5f8569029162be
/PT-CMPN103/Actions/BackAction.cpp
087e30cba7c093105c0119e979987c1047d90df5
[ "MIT" ]
permissive
ahmed-i-mokhtar/PT-CMPN103
89bbc039fe7036b9b788b693abe41445fc9db181
52893c2faf8c21aaeb0fbdb33556ba74d8bc6a7a
refs/heads/master
2021-06-17T17:42:19.379901
2017-05-24T13:06:50
2017-05-24T13:06:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
252
cpp
BackAction.cpp
#include "../Actions/BackAction.h" BackAction::BackAction(ApplicationManager*pApp) :Action(pApp) { } void BackAction::Execute() { pManager->GetOutput()->CreateMainToolBar(); } void BackAction::ReadActionParameters() { } BackAction::~BackAction() { }
18a9bd015c9b661ca9844b322f8c155515477dc1
7e089d39e23b1f55329e9661f3a4ba4c5a23afbd
/src/shared/engine/CreateTavernCommand.cpp
0448e5cc8b66aee2028c89c9630d90fb38666ae9
[]
no_license
Lastv25/rivieremonjoux
c2c6c4c40565b4fc43b2d2833349599ae82fcf66
01f71d12750761be050b506ba65d529ef54a9cde
refs/heads/master
2021-10-11T15:36:04.042571
2019-01-18T13:48:08
2019-01-18T13:48:08
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,046
cpp
CreateTavernCommand.cpp
#include "CreateTavernCommand.h" #include <iostream> using namespace std; using namespace engine; #include "../state/Tavern.h" #include "../state/Village.h" namespace state { class Village; class Tavern; } using namespace state; CreateTavernCommand::CreateTavernCommand ():Command(){ this->commandTypeId = CreateTavern; } CreateTavernCommand::~CreateTavernCommand (){ } CommandTypeId CreateTavernCommand::getCommandTypeId (){ return this->commandTypeId; } void CreateTavernCommand::execute (state::State* state){ state::Village* v =(state::Village*) state->getGrid()->get(0,0); cout << v->getTeam()->getTeam().size() <<endl; if(v->getTeam()->getTeam().size() == 0){ state->getChar()->add(state->getGrid()->get(0,0),"Village"); state->getGrid()->replaceElement(new state::Tavern(),"Tavern",0); } else { state->getChar()->add(state->getGrid()->get(0,0),"Village"); state->getGrid()->replaceElement(new state::Tavern(v->getTeam(),3),"Tavern",0); } } void CreateTavernCommand::executeInv (state::State* state){ }
bcedd2caa9e27ff62bcd8b85659c8dc5643c4168
8e00a94a33b21c4a37e7c736d6bc50fa1a1f8a53
/cli/notearray.cpp
2035c09cd338016b1b46e646a39a99ecb5801131
[]
no_license
craigsapp/humextra
cec67684cee40d190a692d58c3cb5c5c0f7f4c21
d2b87007c0d03c44a28c98c93690bcd97db2a243
refs/heads/master
2023-08-30T22:59:35.513514
2023-08-09T11:30:50
2023-08-09T11:30:50
9,120,415
17
7
null
2019-09-24T00:02:41
2013-03-30T18:56:05
C++
UTF-8
C++
false
false
43,739
cpp
notearray.cpp
// // Programmer: Craig Stuart Sapp <craig@ccrma.stanford.edu> // Creation Date: Tue Aug 30 10:51:26 PDT 2011 // Last Modified: Fri Sep 2 18:25:34 PDT 2011 // Last Modified: Tue Sep 13 13:33:52 PDT 2011 Added -k option // Last Modified: Thu Sep 15 01:36:49 PDT 2011 Added -D option // Last Modified: Thu Oct 20 22:23:27 PDT 2011 Fixed init bug // Last Modified: Sun Oct 20 17:41:10 PDT 2013 Fixed tie problem // Last Modified: Tue Nov 12 14:37:11 PST 2013 Added column for measure duration // Last Modified: Sat Mar 12 20:41:25 PST 2016 Switched to STL // Filename: ...sig/examples/all/notearray.cpp // Web Address: http://sig.sapp.org/examples/museinfo/humdrum/notearray.cpp // Syntax: C++; museinfo // // Description: Generate a two-dimensional numeric array containing // notes in the score in base-40, base-12, or base-7 // representation. Each data line represents a sonority // with attacked notes in that sonority being positive // numbers, and sustained notes from previous sonorities // being negative. // #include "humdrum.h" #include <iostream> #include <vector> #include <algorithm> using namespace std; #define STYLE_BASE40 40 #define STYLE_BASE12 12 #define STYLE_BASE7 7 #define TYPE_MIN 999 #define TYPE_NOTES 1000 #define TYPE_KERN 1000 #define TYPE_LINE (2000-1) /* +1 will be added later to make 2000 */ #define TYPE_MEASURE 3000 #define TYPE_BARDUR 3100 #define TYPE_BEATDUR 3200 #define TYPE_BEAT 4000 #define TYPE_ABSOLUTE 5000 #define TYPE_LINEDUR 6000 #define TYPE_ATTACK 7100 #define TYPE_LAST 7200 #define TYPE_NEXT 7300 // function declarations void getNoteArray (vector<vector<int> >& notes, vector<int>& measpos, vector<int>& linenum, HumdrumFile& infile, int base, int flags); void printNoteArray (vector<vector<int> >& notes, vector<int>& measpos, vector<int>& linenum, HumdrumFile& infile, vector<double>& bardur, vector<double>& beatdur); void printComments (HumdrumFile& infile, int startline, int stopline, int style); void printExclusiveInterpretations(int basecount); void printLine (vector<vector<int> >& notes, vector<vector<int> >& attacks, vector<vector<int> >& lasts, vector<vector<int> >& nexts, vector<int>& measpos, vector<int>& linenum, vector<double>& bardur, vector<double>& beatdur, HumdrumFile& infile, int index, int style); void usage (const char* command); void example (void); void checkOptions (Options& opts, int argc, char* argv[]); void getNoteAttackIndexes (vector<vector<int> >& attacks, vector<vector<int> >& notes, int offst); void getLastAttackIndexes (vector<vector<int> >& lasts, vector<vector<int> >& notes, int offset); void getNextAttackIndexes (vector<vector<int> >& lasts, vector<vector<int> >& notes, int offset); int noteStartMarker (vector<vector<int> >& notes, int line, int column); int noteEndMarker (vector<vector<int> >& notes, int line, int column); int noteContinueMarker (vector<vector<int> >& notes, int line, int column); int singleNote (vector<vector<int> >& notes, int line, int column); void getMeasureDurations (vector<double>& bardur, HumdrumFile& infile); void getBeatDurations (vector<double>& beatdur, HumdrumFile& infile); // global variables Options options; // database for command-line arguments int humdrumQ = 0; // used with -H option int base7Q = 0; // used with -d option int base12Q = 0; // used with -m option int base40Q = 1; // default output type int base = STYLE_BASE40; int measureQ = 1; // used with -M option int beatQ = 1; // used with -B option int commentQ = 1; // used with -C option int rationalQ = 0; // used with -r option int fractionQ = 0; // used with -f option int absoluteQ = 0; // used with -a option int linedurQ = 0; // used with -D option int measuredurQ = 1; // used with --no-measure-duration int beatdurQ = 1; // used with --no-beat-duration int doubleQ = 0; // used with --double option int lineQ = 0; // used with -l option int mathQ = 0; // used with --mathematica option int susxQ = 1; // used with -S option int bibQ = 0; // used with -b option int infoQ = 1; // used with -I option int octadj = 0; // used with -o option int endQ = 0; // used with -e option int typeQ = 0; // used with -c option int oneQ = 0; // used with -1 option int sepQ = 0; // used with --sep option int Offset = 0; // used with -1/--offset option int OffsetSum = 0; // used for multiple input files int attackQ = 0; // used with --attack option int nextQ = 0; // used with --last option int lastQ = 0; // used with --next option int indexQ = 0; // used with -i option int saQ = 0; // used with --sa option int quoteQ = 0; // used with --quote option int Count = 0; // count of how many input files int Current = 0; // used with --math option int moQ = 0; // used with --mo option int Measure = 0; // additive value for measure number int Mincrement= 0; // used to increment between pieces/movements int kernQ = 0; // used with -k option int kerntieQ = 1; // used with --no-tie option int doubletieQ= 0; // used with -T option int zeroQ = 1; // used with -Z option RationalNumber Absoffset; // used with --sa option const char* commentStart = "%"; const char* commentStop = ""; const char* mathvar = "data"; // used with --mathematica option const char* beatbase = ""; // used with -t option /////////////////////////////////////////////////////////////////////////// int main(int argc, char** argv) { vector<vector<int> > notelist; vector<double> bardur; vector<double> beatdur; vector<int> measpos; vector<int> linenum; HumdrumFile infile; // process the command-line options checkOptions(options, argc, argv); // figure out the number of input files to process int numinputs = options.getArgCount(); Count = numinputs; Absoffset = 0; for (int i=0; i<numinputs || i==0; i++) { Current = i; if (moQ) { Measure = (i+1) * Mincrement; } infile.clear(); // if no command-line arguments read data file from standard input if (numinputs < 1) { infile.read(cin); } else { infile.read(options.getArg(i+1)); } // analyze the input file according to command-line options infile.analyzeRhythm(beatbase); getMeasureDurations(bardur, infile); getBeatDurations(beatdur, infile); getNoteArray(notelist, measpos, linenum, infile, base, doubleQ); printNoteArray(notelist, measpos, linenum, infile, bardur, beatdur); OffsetSum += notelist.size(); if (!saQ) { Absoffset += infile.getTotalDurationR(); } if (sepQ && (Count > 1) && (Current < Count - 1)) { // add a separate between input file analyses: if (mathQ) { cout << "(* ********** *)\n"; } else if (humdrumQ) { cout << "!!!!!!!!!!\n"; } else { cout << "%%%%%%%%%%\n"; } } } return 0; } /////////////////////////////////////////////////////////////////////////// ////////////////////////////// // // getMeasureDurations -- Calculate the duration of a measure for each // line in the music. // void getMeasureDurations(vector<double>& bardur, HumdrumFile& infile) { int i; double value = infile.getPickupDuration(); bardur.resize(infile.getNumLines()); for (i=0; i<infile.getNumLines(); i++) { if (infile[i].isBarline()) { value = infile[i].getBeat(); } bardur[i] = value; } } ////////////////////////////// // // getBeatDurations -- Extract the duration of a beat for each // line in the music. // void getBeatDurations(vector<double>& bardur, HumdrumFile& infile) { int i; double value = 1.0; // quarter note bardur.resize(infile.getNumLines()); PerlRegularExpression pre; for (i=0; i<infile.getNumLines(); i++) { if (infile[i].isInterpretation()) { if (pre.search(infile[i][0], "^\\*M(\\d+)/(\\d+)%(\\d+)")) { value = 4.0 / atoi(pre.getSubmatch(2)) * atoi(pre.getSubmatch(3)); } else if (pre.search(infile[i][0], "^\\*M(\\d+)/(\\d+)")) { value = 4.0 / atoi(pre.getSubmatch(2)); } } bardur[i] = value; } } ////////////////////////////// // // getNoteArray -- // style: // STYLE_BASE40 40: print as base-40 pitches // STYLE_BASE12 12: print as base-12 pitches // STYLE_BASE7 7: print as base-7 pitches // // flags: // 0: all off: // 1: turn on double-barline rest markers. // void getNoteArray(vector<vector<int> >& notes, vector<int>& measpos, vector<int>& linenum, HumdrumFile& infile, int style, int flags) { notes.reserve(infile.getNumLines()); notes.resize(0); measpos.reserve(infile.getNumLines()); measpos.resize(0); linenum.reserve(infile.getNumLines()); linenum.resize(0); int measnum = 0; int rest = 0; int i, j, ii, jj; int negQ = 0; // prestorage for note lists so that --no-sustain option can be applied vector<int> templist; templist.reserve(1000); vector<int> templistI; templistI.reserve(1000); int value; int firstQ = 1; if (typeQ) { // store even if lineQ is zero! value = TYPE_LINE; linenum.push_back(value); } if (typeQ) { value = TYPE_MEASURE; measpos.push_back(value); } // increment measure number in case of pickups measnum = Measure; for (i=0; i<infile.getNumLines(); i++) { if (infile[i].isMeasure()) { if (doubleQ && (templist.size() == 0)) { if (strstr(infile[i][0], "||") != NULL) { // insert a rest sonority to break music // from previous measure notes.resize(notes.size() + 1); notes.back().reserve(infile[i].getFieldCount()); notes.back().resize(0); for (j=0; j<infile[i].getFieldCount(); j++) { if (!infile[i].isExInterp(j, "**kern")) { continue; } notes.back().push_back(rest); linenum.push_back(i); } measpos.push_back(measnum); } } // store new measure number (avoiding double code above) sscanf(infile[i][0], "=%d", &measnum); measnum += Measure; } if (!infile[i].isData()) { continue; } templist.resize(0); for (j=0; j<infile[i].getFieldCount(); j++) { if (!infile[i].isExInterp(j, "**kern")) { continue; } if (strchr(infile[i].getSpineInfo(j).c_str(), 'b') != NULL) { // ignore notes non-primary tracks continue; } int attack = 1; if (strcmp(infile[i][j],".")==0) { attack = -1; ii = infile[i].getDotLine(j); jj = infile[i].getDotSpine(j); } else { ii = i; jj = j; if (strchr(infile[ii][jj], '_') != NULL) { attack = -1; } if (strchr(infile[ii][jj], ']') != NULL) { attack = -1; } } int baseval = Convert::kernToBase40(infile[ii][jj]); baseval += 40 * octadj; if (strchr(infile[ii][jj], 'r') != NULL) { baseval = 0; } else { // now storing base-40, and converting to base-12/base-7 later // switch (style) { // case STYLE_BASE12: // baseval = Convert::base40ToMidiNoteNumber(baseval); // break; // case STYLE_BASE7: // baseval = Convert::base40ToDiatonic(baseval); // break; // } } if (style == STYLE_BASE7) { baseval = Convert::base40ToDiatonic(baseval); } else if (style == STYLE_BASE12) { baseval = Convert::base40ToMidiNoteNumber(baseval); } baseval = attack * baseval; templist.push_back(baseval); } negQ = 1; if (susxQ) { // if all notes are negative, then do not store the line for (int m=0; m<(int)templist.size(); m++) { if (templist[m] >= 0) { negQ = 0; break; } } if (negQ) { continue; } } if (firstQ && typeQ) { firstQ = 0; templistI.resize(templist.size()); int value = TYPE_NOTES; switch (style) { case STYLE_BASE40: value += 40; break; case STYLE_BASE12: value += 12; break; case STYLE_BASE7: value += 7; break; } fill(templistI.begin(), templistI.end(), value); notes.push_back(templistI); } notes.push_back(templist); measpos.push_back(measnum); linenum.push_back(i); } if (endQ) { notes.resize(notes.size()+1); notes.back().resize(notes[notes.size()-2].size()); fill(notes.back().begin(), notes.back().end(), 0); // sustains instead of rests (have to copy .last(-1): // for (i=0; i<(int)notes.last().size(); i++) { // if (notes.back()[i] > 0) { // notes.back()[i] *= -1; // } // } measpos.push_back(measpos.back()); linenum.push_back(linenum.back()); // store the data termination line as the line number of the sonority for (i=infile.getNumLines()-1; i>=0; i--) { if (infile[i].isInterpretation()) { linenum.back() = i; break; } } // increment the measure number if the beat of the end // is at 1. This will work unless the last sonority is a // grace note. if (infile[linenum.back()].getBeat() == 1.0) { measpos.back()++; } } } ////////////////////////////// // // printNoteArray -- // void printNoteArray(vector<vector<int> >& notes, vector<int>& measpos, vector<int>& linenum, HumdrumFile& infile, vector<double>& bardur, vector<double>& beatdur) { vector<vector<int> > attacks; vector<vector<int> > lasts; vector<vector<int> > nexts; if (attackQ) { getNoteAttackIndexes(attacks, notes, Offset + OffsetSum); } if (lastQ) { getLastAttackIndexes(lasts, notes, Offset + OffsetSum); } if (nextQ) { getNextAttackIndexes(nexts, notes, Offset + OffsetSum); } int i, j; for (i=0; i<(int)notes.size(); i++) { if (i == 0) { if (commentQ && !typeQ) { printComments(infile, 0, linenum[0], humdrumQ); } else if (commentQ && typeQ) { printComments(infile, 0, linenum[1], humdrumQ); } if (infoQ) { printExclusiveInterpretations(notes[0].size()); } else if (humdrumQ) { // always print exclusive interpretations if Humdrum output printExclusiveInterpretations(notes[0].size()); } if (mathQ) { if (Count <= 1) { cout << mathvar << " = {\n"; } else if (Current == 0) { cout << mathvar << " = {{\n"; } else { cout << "}, {\n"; } } } else if (commentQ) { printComments(infile, linenum[i-1]+1, linenum[i], humdrumQ); } if (typeQ && i == 0) { printLine(notes, attacks, lasts, nexts, measpos, linenum, bardur, beatdur, infile, i, 1); } else { printLine(notes, attacks, lasts, nexts, measpos, linenum, bardur, beatdur, infile, i, 0); } } if (humdrumQ) { int width = 1; if (attackQ) { width++; } if (lastQ) { width++; } if (nextQ) { width++; } if (kernQ) { width++; } int counter = notes[0].size(); counter *= width; counter += indexQ + lineQ + measureQ + beatQ + absoluteQ + linedurQ; // if (attackQ) { counter += notes[0].size(); } // if (lastQ) { counter += notes[0].size(); } // if (nextQ) { counter += notes[0].size(); } for (j=0; j<counter; j++) { cout << "*-"; if (j < counter-1) { cout << "\t"; } } cout << endl; } if (mathQ) { if (Count <= 1) { cout << "};\n"; } else if (Current <= Count - 2) { // cout << "}},\n"; } else if (Current == Count - 1) { cout << "}};\n"; } } if (commentQ) { printComments(infile, linenum.back(), infile.getNumLines()-1, humdrumQ); } } ////////////////////////////// // // getLastAttackIndexes -- return an index of the attack portion // of notes (or the first rest in a series of rests) in each voice. // void getLastAttackIndexes(vector<vector<int> >& lasts, vector<vector<int> >& notes, int offset) { int start = 0; lasts.resize(notes.size()); if (typeQ) { fill(lasts[0].begin(), lasts[0].end(), TYPE_LAST); start = 1; } int i, j; fill(lasts[start].begin(), lasts[start].end(), -1); if ((int)notes.size() == start+1) { return; } vector<int> states; states.resize(notes[0].size()); if (typeQ) { fill(states.begin(), states.end(), offset+1); } else { fill(states.begin(), states.end(), offset); } for (i=0; i<(int)notes.size(); i++) { lasts[i].resize(notes[i].size()); if (i <= start) { fill(lasts[i].begin(), lasts[i].end(), -1); if (typeQ && (i==0)) { fill(lasts[i].begin(), lasts[i].end(), TYPE_LAST); } continue; } for (j=0; j<(int)notes[i].size(); j++) { if (notes[i][j] > 0) { // a new note attack, store the note attack index in // the states array after recording the index of the previous note lasts[i][j] = states[j]; states[j] = i + offset; } else if (notes[i][j] < 0) { // note is sustaining, so copy the index of the last attack // from the previous line if (i > start) { lasts[i][j] = lasts[i-1][j]; } else { lasts[i][j] = -1; } } else { // rest: if last line was a rest then this is a rest sustain: if (i > start) { if (notes[i-1][j] == 0) { // rest sustain lasts[i][j] = lasts[i-1][j]; } else { // rest attack lasts[i][j] = states[j]; states[j] = i + offset; } } else { lasts[i][j] = -1; } } } } } ////////////////////////////// // // getNextAttackIndexes -- return an index of the attack portion // of notes (or the first rest in a series of rests) in each voice. // void getNextAttackIndexes(vector<vector<int> >& nexts, vector<vector<int> >& notes, int offset) { int start = 0; nexts.resize(notes.size()); if (typeQ) { nexts[0].resize(notes[0].size()); fill(nexts[0].begin(), nexts[0].end(), TYPE_NEXT); start = 1; } int i, j; nexts.back().resize(notes.back().size()); fill(nexts.back().begin(), nexts.back().end(), -1); if ((int)notes.size() == start+1) { return; } for (i=(int)notes.size()-2; i>=start; i--) { nexts[i].resize(notes[i].size()); for (j=0; j<(int)notes[i].size(); j++) { if ((notes[i][j] != 0) && (notes[i+1][j] == 0)) { // next note is a "rest attack" nexts[i][j] = i + 1 + offset; } else if (notes[i+1][j] > 0) { // a new note attack, store the note attack index in // the states array after recording the index of the previous note nexts[i][j] = i + 1 + offset; } else { nexts[i][j] = nexts[i+1][j]; } } } } ////////////////////////////// // // getNoteAttackIndexes -- return an index of the attack portion // of notes (or the first rest in a series of rests) in each voice. // void getNoteAttackIndexes(vector<vector<int> >& attacks, vector<vector<int> >& notes, int offset) { attacks.resize(notes.size()); int i, j; attacks[0].resize(notes[0].size()); fill (attacks[0].begin(), attacks[0].end(), offset); for (i=1; i<(int)attacks.size(); i++) { attacks[i].resize(notes[i].size()); for (j=0; j<(int)attacks[i].size(); j++) { if (notes[i][j] < 0) { // a sustained note, so store index of attack note attacks[i][j] = attacks[i-1][j]; } else if (notes[i][j] > 0) { // note being attacked, so store its index attacks[i][j] = i + offset; } else { // a rest: check to see if last position was a rest. // if so, then this is a "tied rest"; otherwise it is // a "attacked rest". if (notes[i-1][j] == 0) { attacks[i][j] = attacks[i-1][j]; } else { attacks[i][j] = i + offset; } } } } if (typeQ) { fill(attacks[0].begin(), attacks[0].end(), TYPE_ATTACK); } } ////////////////////////////// // // printLine -- print a line of the note array. // style == 0: regular line // style == 1: index line (don't extract beat or absbeat from infile) // void printLine(vector<vector<int> >& notes, vector<vector<int> >& attacks, vector<vector<int> >& lasts, vector<vector<int> >& nexts, vector<int>& measpos, vector<int>& linenum, vector<double>& bardur, vector<double>& beatdur, HumdrumFile& infile, int index, int style) { int& i = index; int j; if (mathQ) { cout << "{"; } if (indexQ) { cout << i + Offset + OffsetSum; } if (lineQ) { if (indexQ) { if (mathQ) { cout << ","; } cout << "\t"; } cout << linenum[i]+1; } if (measureQ) { if (indexQ || lineQ) { if (mathQ) { cout << ","; } cout << "\t"; } cout << measpos[i]; } if (measuredurQ) { if (indexQ || lineQ || measureQ) { if (mathQ) { cout << ","; } cout << "\t"; } if ((i == 0) && (linenum[i] == TYPE_LINE)) { cout << TYPE_BARDUR; } else { cout << bardur[linenum[i]]; } } if (beatdurQ) { if (indexQ || lineQ || measureQ || measuredurQ) { if (mathQ) { cout << ","; } cout << "\t"; } if ((i == 0) && (linenum[i] == TYPE_LINE)) { cout << TYPE_BEATDUR; } else { cout << beatdur[linenum[i]]; } } if (beatQ) { if (indexQ || lineQ || measuredurQ || measureQ || beatdurQ) { if (mathQ) { cout << ","; } cout << "\t"; } if (style == 1) { cout << TYPE_BEAT; } else if (rationalQ) { if (fractionQ) { cout << infile[linenum[i]].getBeatR() - 1; } else { // switched to 0-offset metrical position RationalNumber value = infile[linenum[i]].getBeatR(); value -= 1; value.printTwoPart(cout); } } else { // print beat position as a floating-point number: cout << infile[linenum[i]].getBeat() - 1; } } if (absoluteQ) { if (indexQ || lineQ || measuredurQ || measureQ || beatdurQ || beatQ) { if (mathQ) { cout << ","; } cout << "\t"; } if (style == 1) { cout << TYPE_ABSOLUTE; } else if (rationalQ) { if (fractionQ) { cout << (Absoffset + infile[linenum[i]].getAbsBeatR()); } else { RationalNumber sum = Absoffset + infile[linenum[i]].getAbsBeatR(); sum.printTwoPart(cout); } } else { // print beat position as a floating-point number: cout << infile[linenum[i]].getAbsBeat() + Absoffset.getFloat(); } } if (linedurQ) { if (indexQ || lineQ || measuredurQ || measureQ || beatdurQ || beatQ || absoluteQ) { if (mathQ) { cout << ","; } cout << "\t"; } if (style == 1) { cout << TYPE_LINEDUR; } else if (rationalQ) { if (fractionQ) { cout << (Absoffset + infile[linenum[i]].getDurationR()); } else { RationalNumber num = infile[linenum[i]].getDurationR(); num.printTwoPart(cout); } } else { // print beat position as a floating-point number: cout << infile[linenum[i]].getDuration(); } } if (indexQ || lineQ || measuredurQ || measureQ || beatdurQ || beatQ || absoluteQ || linedurQ) { if (mathQ) { cout << ","; } } vector<int> values; values.reserve(notes.size() * 10); int vv; int sign; for (j=0; j<(int)notes[i].size(); j++) { vv = notes[i][j]; //if (kernQ && (style == 1) && typeQ) { // int ww = TYPE_KERN; // values.push_back(ww); //} if (vv < TYPE_NOTES) { if (vv < 0) { sign = -1; vv = -vv; } else { sign = +1; } if (vv != 0) { switch (style) { case STYLE_BASE12: vv = Convert::base40ToMidiNoteNumber(vv); break; case STYLE_BASE7: vv = Convert::base40ToDiatonic(vv); break; } } vv *= sign; values.push_back(vv); } else { values.push_back(vv); } if (attackQ) { values.push_back(attacks[i][j]); } if (lastQ) { values.push_back(lasts[i][j]); } if (nextQ) { values.push_back(nexts[i][j]); } } int width = 1; // notes if (attackQ) { width++; } if (lastQ) { width++; } if (nextQ) { width++; } char buffer[1024] = {0}; for (j=0; j<(int)values.size(); j++) { if (kernQ && ((j % width) == 0)) { //if (mathQ) { // cout << ","; //} cout << "\t"; if ((style == 1) && (i == 0)) { cout << TYPE_KERN; } else { if (mathQ || quoteQ) { cout << "\""; } if (kerntieQ && noteStartMarker(notes, i, j / width)) { cout << "["; } if (doubletieQ && singleNote(notes, i, j / width)) { cout << "["; } if (values[j] == 0) { cout << "r"; } else { cout << Convert::base40ToKern(buffer, 1024, abs(values[j])); } if (kerntieQ && noteContinueMarker(notes, i, j / width)) { cout << "_"; } else if (kerntieQ && noteEndMarker(notes, i, j / width)) { cout << "]"; } if (doubletieQ && singleNote(notes, i, j / width)) { cout << "]"; } if (mathQ || quoteQ) { cout << "\""; } } if (mathQ) { cout << ","; } } cout << "\t" << values[j]; if (j < (int)values.size()-1) { if (mathQ) { cout << ","; } //cout << "\t"; } } if (mathQ) { cout << "}"; if (i < (int)linenum.size() - 1) { cout << ","; } } cout << endl; } ////////////////////////////// // // singleNote -- true if the note in the column/line is uniq // int singleNote(vector<vector<int> >& notes, int line, int column) { int start = 0; if (typeQ) { start = 1; } if (line < start) { return 0; } int pitch = notes[line][column]; int nextpitch = -1; int lastpitch = -1; if ((line > start) && ((int)notes.size() > 1+start)) { lastpitch = notes[line-1][column]; } if (((int)notes.size() > start+1) && (line < (int)notes.size() - 1)) { nextpitch = notes[line+1][column]; } if (pitch > TYPE_MIN) { return 0; } if (pitch < 0) { // note is a sustain, so not considered return 0; } else if (pitch == 0) { // if the rest is surrounded by non-rests, then mark if ((pitch != lastpitch) && (pitch != nextpitch)) { return 1; } else { return 0; } } else { if (pitch != -nextpitch) { // next sonority does not contain a sustain of the note return 1; } else { return 0; } } } ////////////////////////////// // // noteStartMarker -- // int noteStartMarker(vector<vector<int> >& notes, int line, int column) { int start = 0; if (typeQ) { start = 1; } if (line < start) { return 0; } int pitch = notes[line][column]; int nextpitch = -1; int lastpitch = -1; if ((line > start) && ((int)notes.size() > 1+start)) { lastpitch = notes[line-1][column]; } if (((int)notes.size() > start+1) && (line < (int)notes.size() - 1)) { nextpitch = notes[line+1][column]; } if (pitch == 0) { // if the first rest in a row then true if ((lastpitch != 0) && (nextpitch == 0)) { // don't include rests which start and stop on the same line return 1; } else { return 0; } } else if (pitch < 0) { return 0; } else { if ((nextpitch < 0) && (nextpitch != -1)) { return 1; } else { return 0; } } } ////////////////////////////// // // noteContinueMarker -- // int noteContinueMarker(vector<vector<int> >& notes, int line, int column) { int start = 0; if (typeQ) { start = 1; } if (line < start) { return 0; } int pitch = notes[line][column]; int nextpitch = -1; int lastpitch = -1; if ((line > start) && ((int)notes.size() > 1+start)) { lastpitch = notes[line-1][column]; } if (((int)notes.size() > start+1) && (line < (int)notes.size() - 1)) { nextpitch = notes[line+1][column]; } if (pitch == 0) { // if not the first or the last zero than a continue if ((lastpitch == 0) && (nextpitch == 0)) { return 1; } else { return 0; } } else if (pitch > 0) { return 0; } else { if (pitch == nextpitch ) { return 1; } else { return 0; } } } ////////////////////////////// // // noteEndMarker -- // int noteEndMarker(vector<vector<int> >& notes, int line, int column) { int start = 0; if (typeQ) { start = 1; } if (line < start) { return 0; } int pitch = notes[line][column]; int nextpitch = -1; // int lastpitch = -1; if ((line > start) && ((int)notes.size() > 1+start)) { // lastpitch = notes[line-1][column]; } if (((int)notes.size() > start+1) && (line < (int)notes.size() - 1)) { nextpitch = notes[line+1][column]; } if (pitch == 0) { // if not the first or the last zero than a continue if (nextpitch != 0) { return 1; } else { return 0; } } else if (pitch > 0) { return 0; } else { if (pitch != nextpitch ) { return 1; } else { return 0; } } } ////////////////////////////// // // printExclusiveInterpretations -- print ** markers at the start of // each column of data. // // Order of optional prefix columns: // lineQ // measureQ // beatQ // absoluteQ // linedurQ // void printExclusiveInterpretations(int basecount) { char basename[1024] = {0}; const char* prefix = "%%"; if (humdrumQ || mathQ) { prefix = "**"; } if (kernQ) { strcat(basename, "kern"); strcat(basename, "\t"); } if (base7Q) { // strcat(basename, prefix); strcat(basename, "b7"); } else if (base12Q) { // strcat(basename, prefix); strcat(basename, "b12"); } else { // strcat(basename, prefix); strcat(basename, "b40"); } if (attackQ) { strcat(basename, "\t"); strcat(basename, prefix); strcat(basename, "attk"); } if (lastQ) { strcat(basename, "\t"); strcat(basename, prefix); strcat(basename, "last"); } if (nextQ) { strcat(basename, "\t"); strcat(basename, prefix); strcat(basename, "next"); } int startmark = 0; if (indexQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "idx\t"; } if (lineQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "line\t"; } if (measureQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "bar\t"; } if (measuredurQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "mdur\t"; } if (beatdurQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "bdur\t"; } if (beatQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "beat\t"; } if (absoluteQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "abs\t"; } if (linedurQ) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << "ldur\t"; } int i; for (i=0; i<basecount; i++) { if ((startmark == 0) && mathQ) { cout << "(*"; startmark++; } else { cout << prefix; } cout << basename; if (i < basecount - 1) { cout << "\t"; } } if (mathQ) { cout << " *)"; } cout << "\n"; } ////////////////////////////// // // // printComments -- print any comments // void printComments(HumdrumFile& infile, int startline, int stopline, int style) { int i; for (i=startline; i<=stopline; i++) { if (!infile[i].isComment()) { continue; } if (bibQ && infile[i].isGlobalComment()) { continue; } if (infile[i].isLocalComment()) { // don't know how to store local comments, ignore for now. continue; } if (style) { // print in Humdrum format: cout << infile[i] << "\n"; } else { // print in Matlab format: cout << commentStart << infile[i] << commentStop << "\n"; } } } ////////////////////////////// // // checkOptions -- validate and process command-line options. // void checkOptions(Options& opts, int argc, char* argv[]) { opts.define("a|absolute=b", "print absolute beat numbers"); opts.define("b|bib|bibliographic|reference=b", "display only bib record"); opts.define("c|type=b", "add a numeric index at start of data array"); opts.define("d|diatonic=b", "print output in absolute diatonic"); opts.define("f|fraction=b", "display rational number as fraction"); opts.define("e|end|end-rest=b","store ending rest"); opts.define("i|index=b", "print a column with the index value"); opts.define("j|josquin=b", "default settings for josquin project"); opts.define("k|kern=b", "display kern spine"); opts.define("no-tie|no-ties=b", "don't display kern tie information"); opts.define("l|line=b", "print original line of sonority in data"); opts.define("m|midi=b", "print output as MIDI key numbers"); opts.define("o|octave=i:0", "octave adjustment value"); opts.define("r|rational=b", "display metric position as rational number"); opts.define("t|beat=s:", "metric base for constant beat analysis"); opts.define("1|one=b", "offset index values by one"); opts.define("M|no-measures=b", "don't print measure number column"); opts.define("B|no-beats=b", "don't print beat value column"); opts.define("C|no-comments=b", "don't print comments in file"); opts.define("D|linedur=b", "display duration of line"); opts.define("A|all=b", "display all options prefix columns"); opts.define("H|humdrum=b", "print output in Humdrum format"); opts.define("I|no-info=b", "do not display information header"); opts.define("S|no-sustain=b", "suppress sonorities that are only sustains"); opts.define("T|all-tie|all-ties=b", "start/stop tie marks on all notes"); opts.define("N|no-cols=b", "turn off all information columns"); opts.define("attack=b", "display note-attack index values"); opts.define("double=b", "add rests at double barlines"); opts.define("no-measure-duration=b", "don't display duration of measures"); opts.define("no-beat-duration=b", "don't display duration of beats"); opts.define("last=b", "display previous note-attack index values"); opts.define("math|mathematica=s:data", "print output data as Matlab array"); opts.define("mel|melodic=b", "display melodic note index columns"); opts.define("mo|measure-offset=i:0", "bar num increase per file"); opts.define("next=b", "display following note-attack index values"); opts.define("offset=i:0", "starting index for first row"); opts.define("sa|separate-absolute=b", "single absolute beat positions"); opts.define("sep|separator=b", "print a separator between input analyses"); opts.define("quote=b", "print quotes around kern names"); opts.define("Z|no-zero-beat=b", "start first beat of measure at 1 rather than 0"); opts.define("debug=b"); // determine bad input line num opts.define("author=b"); // author of program opts.define("version=b"); // compilation info opts.define("example=b"); // example usages opts.define("h|help=b"); // short description opts.process(argc, argv); // handle basic options: if (opts.getBoolean("author")) { cout << "Written by Craig Stuart Sapp, " << "craig@ccrma.stanford.edu, Aug 2011" << endl; exit(0); } else if (opts.getBoolean("version")) { cout << argv[0] << ", version: 30 August 2011" << endl; cout << "compiled: " << __DATE__ << endl; cout << MUSEINFO_VERSION << endl; exit(0); } else if (opts.getBoolean("help")) { usage(opts.getCommand().c_str()); exit(0); } else if (opts.getBoolean("example")) { example(); exit(0); } if (opts.getBoolean("josquin")) { // fix analysis, until then this is turned off: // beatbase = "1"; // beat is the whole note. doubleQ = 1; } else { beatbase = opts.getString("beat").c_str(); doubleQ = opts.getBoolean("double"); } humdrumQ = opts.getBoolean("humdrum"); base7Q = opts.getBoolean("diatonic"); base12Q = opts.getBoolean("midi"); if (base7Q) { base7Q = 1; base12Q = 0; base40Q = 0; } else if (base12Q) { base7Q = 0; base12Q = 1; base40Q = 0; } else { base7Q = 0; base12Q = 0; base40Q = 1; } if (base7Q) { base = STYLE_BASE7; } else if (base12Q) { base = STYLE_BASE12; } else { base = STYLE_BASE40; } mathQ = opts.getBoolean("mathematica"); mathvar = opts.getString("mathematica").c_str(); commentStart = "(* "; commentStop = " *)"; if (!mathQ) { commentStart = "% "; commentStop = ""; } lineQ = opts.getBoolean("line"); measureQ = !opts.getBoolean("no-measures"); beatQ = !opts.getBoolean("no-beats"); absoluteQ = opts.getBoolean("absolute"); linedurQ = opts.getBoolean("linedur"); commentQ = !opts.getBoolean("no-comments"); rationalQ = opts.getBoolean("rational"); fractionQ = opts.getBoolean("fraction"); susxQ = opts.getBoolean("no-sustain"); kernQ = opts.getBoolean("kern"); kerntieQ = !opts.getBoolean("no-tie"); bibQ = opts.getBoolean("bibliographic"); infoQ = !opts.getBoolean("no-info"); endQ = opts.getBoolean("end-rest"); octadj = opts.getInteger("octave"); typeQ = opts.getBoolean("type"); attackQ = opts.getBoolean("attack"); nextQ = opts.getBoolean("last"); measuredurQ = !opts.getBoolean("no-measure-duration"); beatdurQ = !opts.getBoolean("no-beat-duration"); lastQ = opts.getBoolean("next"); indexQ = opts.getBoolean("index"); sepQ = opts.getBoolean("sep"); saQ = opts.getBoolean("separate-absolute"); Mincrement= opts.getInteger("measure-offset"); moQ = opts.getBoolean("measure-offset"); Offset = opts.getInteger("offset"); zeroQ = !opts.getInteger("no-zero-beat"); quoteQ = opts.getBoolean("quote"); doubletieQ= opts.getBoolean("all-tie"); if (doubletieQ) { kerntieQ = 1; } if (Offset < 0) { Offset = 0; } if (opts.getBoolean("mel")) { attackQ = 1; nextQ = 1; lastQ = 1; } if (opts.getBoolean("1")) { Offset = 1; } if (fractionQ) { rationalQ = 1; } if (opts.getBoolean("no-cols")) { measureQ = 0; beatQ = 0; } if (opts.getBoolean("all")) { lineQ = measureQ = beatQ = absoluteQ = linedurQ = 1; } } ////////////////////////////// // // example -- example usage of the quality program // void example(void) { cout << " \n" << endl; } ////////////////////////////// // // usage -- gives the usage statement for the meter program // void usage(const char* command) { cout << " \n" << endl; }
ced610df676b7171802439e77c2beab4da2fba23
c202d50379bedd56ad716e27b0ee2c9a3ece508c
/onesolmain.cpp
c79ea988de62555ab04d169a3e6319667ce29472
[]
no_license
darryusa/QtProcess
668402fb346eced303005c1704e1d4308343c58e
578039859968a6ac2079aca38bc069558377c511
refs/heads/Production
2021-01-19T03:42:37.161376
2016-07-26T03:26:22
2016-07-26T03:26:22
63,032,141
0
0
null
2016-07-19T05:59:58
2016-07-11T03:01:39
Makefile
UTF-8
C++
false
false
4,049
cpp
onesolmain.cpp
#include "onesolmain.h" #include "staffwindow.h" #include "reportswindow.h" #include <QStackedWidget> #include <QDesktopWidget> #include <logindialog.h> OneSolMain::OneSolMain( QWidget *parent ) : QWidget( parent ) { //initialize variable menuWindow = new MainWindow(this); reportsWindow = new ReportsWindow(this); stackedWidget = new QStackedWidget; transactionWindow = new TransactionWindow(this); inventoryWindow = new InventoryWindow(this); staffWindow = new StaffWindow( this ); loginStaff = new LoginDialog(menuWindow,"staff"); loginReport = new LoginDialog(menuWindow,"report"); loginSale = new LoginDialog(menuWindow,"sale"); loginInventory = new LoginDialog(menuWindow,"inventory"); stackedWidget->addWidget(loginInventory); stackedWidget->addWidget(transactionWindow); stackedWidget->addWidget( staffWindow ); stackedWidget->addWidget(menuWindow); stackedWidget->addWidget(reportsWindow); stackedWidget->addWidget(inventoryWindow); stackedWidget->setCurrentWidget( menuWindow ); // connect SIGNAL and slots connect(loginReport, SIGNAL(reportLoggedin()), this, SLOT(reportSlotLoggedin())); connect(loginStaff, SIGNAL(staffLoggedin()), this, SLOT(staffSlotLoggedin())); connect(loginSale, SIGNAL(saleLoggin()), this, SLOT(saleLogginSlot())); connect(loginInventory,SIGNAL(inventoryLogin()),this, SLOT(inventoryLoggedin())); connect(menuWindow, SIGNAL(reportClicked()), this, SLOT(reportButtonClicked())); connect(menuWindow, SIGNAL(staffClicked()), this, SLOT(staffClick())); connect(menuWindow,SIGNAL(saleClicked()), this, SLOT(saleClicked())); connect(menuWindow,SIGNAL(inventoryClicked()), this, SLOT(inventoryClicked())); connect(staffWindow,SIGNAL(staffReturn()),this,SLOT(staffReturned())); connect(inventoryWindow,SIGNAL(inventoryReturn()),this,SLOT(staffReturned())); connect(this,SIGNAL(saleLogginSignal()),transactionWindow,SLOT(transactionLoggedin())); connect(transactionWindow,SIGNAL(returnToMain()),this,SLOT(returnFromTransactionSlot())); connect(reportsWindow,SIGNAL(returnFromReport()),this,SLOT(returnFromReportSlot())); QRect screenGeometry = QDesktopWidget().availableGeometry( this ); stackedWidget->resize( screenGeometry.size() ); stackedWidget->show(); } OneSolMain::~OneSolMain() { } void OneSolMain::reportButtonClicked() { loginReport->setModal(true); loginReport->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); loginReport->show(); } void OneSolMain::returnFromReportSlot() { stackedWidget->setCurrentWidget(menuWindow); } void OneSolMain::returnFromTransactionSlot() { stackedWidget->setCurrentWidget(menuWindow); } void OneSolMain::UserLoggedIn() { stackedWidget->setCurrentWidget( reportsWindow ); } void OneSolMain::staffSlotLoggedin() { stackedWidget->setCurrentWidget(staffWindow); loginStaff->hide(); } void OneSolMain::staffReturned() { stackedWidget->setCurrentWidget(menuWindow); } void OneSolMain::reportSlotLoggedin() { stackedWidget->setCurrentWidget(reportsWindow); loginReport->hide(); } void OneSolMain::staffClick() { loginStaff->setModal(true); loginStaff->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); loginStaff->show(); } void OneSolMain::saleClicked() { loginSale->setModal(true); loginSale->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); loginSale->open(); } void OneSolMain::saleLogginSlot() { loginSale->hide(); emit saleLogginSignal(); stackedWidget->setCurrentWidget(transactionWindow); } void OneSolMain::inventoryClicked() { loginInventory->setModal(true); loginInventory->setWindowFlags(Qt::Dialog | Qt::FramelessWindowHint); loginInventory->show(); } void OneSolMain::inventoryLoggedin() { loginInventory->hide(); stackedWidget->setCurrentWidget(inventoryWindow); }
0282310a9073d1d5c191f7e27faab16d8558159b
83ed3c66ce8971f02e31b1142bb30a387e8d8d64
/Hecsit.Graphics.EvA1/chiken.cpp
0aff1a6f9fdc28805ba123ff04af5c10c4aa3da1
[]
no_license
Huex/EvA
5ab9a9afcd41e9f8783b4874b57b57ab2782d2ac
7066eed85e41120a02741d7fbbb975889adec17c
refs/heads/master
2020-06-10T09:09:22.976677
2016-12-08T22:00:43
2016-12-08T22:00:43
75,976,035
1
1
null
null
null
null
UTF-8
C++
false
false
3,246
cpp
chiken.cpp
#include "stdafx.h" #include "chiken.h" void Chiken::Update() { extern float TIME_PER_FRAME; x += dx*0.005; y += dy*0.005; if (dx == 0 && dy == 0) { coord.s = float(2) / 7; } if (dy > 0) { orientation = Up; timerY += TIME_PER_FRAME; if (timerY >= 120) { coord.s -= scale.s; timerX = 0; timerY = 0; if (coord.s <= float(3) / 7) { coord.s = float(6) / 7; } } } if (dy < 0) { orientation = Down; timerY += TIME_PER_FRAME; if (timerY >= 120) { coord.s -= scale.s; timerX = 0; timerY = 0; if (coord.s <= float(3) / 7) { coord.s = float(6) / 7; } } } if (dx < 0) { orientation = Left; timerX += TIME_PER_FRAME; if (timerX >= 120) { coord.s -= scale.s; timerX = 0; timerY = 0; if (coord.s <= float(3) / 7) { coord.s = float(6) / 7; } } } if (dx > 0) { orientation = Right; timerX += TIME_PER_FRAME; if (timerX >= 120) { coord.s -= scale.s; timerX = 0; timerY = 0; if (coord.s <= float(3) / 7) { coord.s = float(6) / 7; } } } } Chiken::Chiken(TextureHelper * gTexture) { _textureHelper = gTexture; _textureHelper->Load("textures/chiken.png", &texture); x = 0; y = 0; dx = 0; dy = 0; timerX = 0; timerY = 0; orientation = Left; coord.s = float(6) / 7; coord.t = float(1) / 3; scale.s = float(1) / 7; scale.t = float(1) / 3; } Chiken::~Chiken() { } void Chiken::Draw() { extern float RATIO; Update(); _textureHelper->Activate(&texture); glEnable(GL_TEXTURE_2D); glBegin(GL_QUADS); if (orientation == Left) { coord.t = float(1) / 3; glTexCoord2f(coord.s, coord.t); glVertex3f(-0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t); glVertex3f(0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t - scale.t); glVertex3f(0.1 + x, (0.1 + y) * RATIO, 5); glTexCoord2f(coord.s, coord.t - scale.t); glVertex3f(-0.1 + x, (0.1 + y) * RATIO, 5); } if (orientation == Right) { coord.t = float(1) / 3; glTexCoord2f(coord.s + scale.s, coord.t); glVertex3f(-0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s, coord.t); glVertex3f(0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s, coord.t - scale.t); glVertex3f(0.1 + x, (0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t - scale.t); glVertex3f(-0.1 + x, (0.1 + y) * RATIO, 5); } if (orientation == Up) { coord.t = float(3) / 3; glTexCoord2f(coord.s, coord.t); glVertex3f(-0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t); glVertex3f(0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t - scale.t); glVertex3f(0.1 + x, (0.1 + y) * RATIO, 5); glTexCoord2f(coord.s, coord.t - scale.t); glVertex3f(-0.1 + x, (0.1 + y) * RATIO, 5); } if (orientation == Down) { coord.t = float(2) / 3; glTexCoord2f(coord.s, coord.t); glVertex3f(-0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t); glVertex3f(0.1 + x, (-0.1 + y) * RATIO, 5); glTexCoord2f(coord.s + scale.s, coord.t - scale.t); glVertex3f(0.1 + x, (0.1 + y) * RATIO, 5); glTexCoord2f(coord.s, coord.t - scale.t); glVertex3f(-0.1 + x, (0.1 + y) * RATIO, 5); } glEnd(); glDisable(GL_TEXTURE_2D); dx =0; dy =0; }
da594c70b971602d85edda577308de9a8660548f
b7f64aa094e720f296ec88d92bca04dd29728910
/DS&Algorithm-Models/数据结构/可并堆/棘手的操作_并查集+配对堆.cpp
8d35d3713b80c998acec10b4227e86af51026dc8
[]
no_license
AsterNighT/OI-Package
9d9a916ff6f90ceab1dfc78d4f37d650a192b241
4c83e7cc9134bfe608deb7aea4abb1d422ef223a
refs/heads/master
2021-06-22T17:07:52.753154
2017-07-15T14:05:59
2017-07-15T14:05:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,148
cpp
棘手的操作_并查集+配对堆.cpp
#include <iostream> #include <cstdlib> #include <cstdio> #include <algorithm> #include <string> #include <cstring> #include <cmath> #include <map> #include <stack> #include <set> #include <vector> #include <queue> #include <time.h> #define eps 1e-7 #define INF 0x3f3f3f3f #define MOD 1000000007 #define rep0(j,n) for(int j=0;j<n;++j) #define rep1(j,n) for(int j=1;j<=n;++j) #define pb push_back #define set0(n) memset(n,0,sizeof(n)) #define ll long long #define ull unsigned long long #define iter(i,v) for(edge *i=head[v];i;i=i->nxt) #define max(a,b) (a>b?a:b) #define min(a,b) (a<b?a:b) #define print_rumtime printf("Running time:%.3lfs\n",double(clock())/1000.0); #define TO(j) printf(#j": %d\n",j); //#define OJ using namespace std; const int MAXINT = 300010; const int MAXNODE = 100010; const int MAXEDGE = 2 * MAXNODE; char BUF, *buf; int read() { int c = getchar(); int f = 1, x = 0; while (!isdigit(c)) { if (c == '-') f = -1; if (c == -1) return -INF; c = getchar(); } while (isdigit(c)) { x = x * 10 + c - '0'; c = getchar(); } return f * x; } char get_ch() { char c = getchar(); while (!isalpha(c)) c = getchar(); return c; } int read_op() { int tp = 0, c = getchar(); while (!isalpha(c))c = getchar(); if (c == 'U') return 0; if (c == 'F') tp += 3; c = getchar(); tp += c - '0'; return tp; } //------------------- Head Files ----------------------// int cnt, h, t, n, a[MAXINT], m, fa[MAXINT], tag[MAXINT], add_tot = 0, sz[MAXINT]; struct node { node *f, *prv, *nxt, *c; int v; }*q[2 * MAXINT], *root[MAXINT], mp[MAXINT * 2]; int find_fa(int p) { return fa[p] == p ? p : find_fa(fa[p]); } int get_tag(int p) { int ans = tag[p]; while (p != fa[p]) { p = fa[p]; ans += tag[p]; } return ans; } node* combine(node *a, node *b) { if (a == b) abort(); if (!a) return b; if (!b) return a; if (a->v + get_tag(a - mp) < b->v + get_tag(b - mp)) swap(a, b); b->nxt = a->c; if (a->c) a->c->prv = b; a->c = b; b->f = a; return a; } node* pop(node *pt) { h = t = 0; node *p = pt->c; while (p) { q[t++] = p; p = p->nxt; } rep0(i, t) q[i]->f = q[i]->prv = q[i]->nxt = NULL; while (t - h > 1) q[t++] = combine(q[h], q[h + 1]), h += 2; pt->c = NULL; return (h != t ? q[h] : NULL); } void del(node *p) { if (p->prv) p->prv->nxt = p->nxt; if (p->nxt) p->nxt->prv = p->prv; if (p->f && p == p->f->c) p->f->c = p->nxt; p->f = p->prv = p->nxt = NULL; } struct pq { priority_queue<int> d, v; void push(int p) { v.push(p); } void del(int p) { d.push(p); } int top() { while (d.size() && v.top() == d.top()) d.pop(), v.pop(); return v.top(); } } ans; void get_input(); void work(); int main() { cnt = 0; get_input(); work(); return 0; } void work() { rep1(j, m) { int op = read_op(); if (op == 0) { int u = read(), v = read(); u = find_fa(u); v = find_fa(v); node* x = root[u], *y = root[v]; if (x == y) continue; ans.del(x->v + get_tag(x - mp)); ans.del(y->v + get_tag(y - mp)); if (sz[u] > sz[v]) swap(u, v); fa[u] = v; tag[u] -= tag[v]; sz[v] += sz[u]; x = combine(x, y); root[v] = x; ans.push(x->v + get_tag(x - mp)); } if (op == 1) { int u = read(), v = read(); int rt = find_fa(u); ans.del(root[rt]->v + get_tag(root[rt] - mp)); if (&mp[u] != root[rt]) del(&mp[u]); node *p = pop(&mp[u]); mp[u].v += v; p = combine(p, &mp[u]); if (&mp[u] != root[rt]) p = combine(p, root[rt]); root[rt] = p; ans.push(p->v + get_tag(p - mp)); } if (op == 2) { int u = read(), v = read(); u = find_fa(u); node *p = root[u]; ans.del(p->v + get_tag(p - mp)); tag[u] += v; ans.push(p->v + get_tag(p - mp)); } if (op == 3) add_tot += read(); if (op == 4) { int u = read(); printf("%d\n", mp[u].v + get_tag(u) + add_tot); } if (op == 5) { int u = read(); u = find_fa(u); node *p = root[u]; printf("%d\n", p->v + get_tag(p - mp) + add_tot); } if (op == 6) printf("%d\n", ans.top() + add_tot); } } void get_input() { n = read(); rep1(i, n) { mp[i].v = read(); ans.push(mp[i].v); mp[i].f = mp[i].nxt = mp[i].c = NULL; sz[i] = 1, fa[i] = i, root[i] = &mp[i]; } m = read(); }
56e9dc8b00476c5e6925b39272a77cf88c8d4fad
5c98e2e97e1546bea8c1b11212e0f227fab7bd9a
/KR1/Print.h
b6bf879d9cef7e1e3679da2499de111fe9bd8a71
[]
no_license
mariyaveleva16/OOP
076a845c00c7e023ccff023f2224bed63702dfff
a8cc27bb9f5d8a2e9623176fb31c73cd41ee6a65
refs/heads/main
2023-06-07T23:07:01.765217
2021-06-24T19:37:44
2021-06-24T19:37:44
379,961,093
0
0
null
null
null
null
UTF-8
C++
false
false
3,895
h
Print.h
#pragma once #include<iostream> class Date { private: int day; int mounth; int year; public: Date() { day = 0; mounth = 0; year = 0; }; Date(int d,int m , int y){ day = d; mounth = m; year = y; }; Date(const Date& other) { this->day = other.day; this->mounth= other.mounth; this->year = other.year; }; Date& operator=(const Date& other) { if (this != &other) { this->day = other.day; this->mounth = other.mounth; this->year = other.year; } return *this; }; ~Date() {}; void print() { std::cout << day << "." << mounth << "." << year; }; }; class PrintEdition:Date { private: char* name; int number_of_sheets; Date date; public: PrintEdition() { name = new char[1]; name[0] = '\0'; number_of_sheets= 0; }; PrintEdition(const char* _name, int _number_of_sheets, Date _date) { int len = strlen(_name); this->name = new char[len + 1]; strcpy_s(this->name, len + 1, _name); this->name[len] = '\0'; this->number_of_sheets = _number_of_sheets; date = _date; }; PrintEdition(const PrintEdition& other) { int len = strlen(other.name); this->name = new char[len + 1]; strcpy_s(this->name, len + 1, other.name); this->name[len] = '\0'; this->number_of_sheets = other.number_of_sheets; this->date = other.date; }; PrintEdition& operator=(const PrintEdition& other) { if (this != &other) { delete[] this->name; int len = strlen(other.name); this->name = new char[len + 1]; strcpy_s(this->name, len + 1, other.name); this->name[len] = '\0'; this->number_of_sheets = other.number_of_sheets; this->date = other.date; } return *this; }; ~PrintEdition() { delete[] this->name; }; void print() { std::cout << name << std::endl; std::cout << number_of_sheets << std::endl; date.print(); }; }; class Article { private: PrintEdition edition; char* name_author; public: Article() { name_author = new char[1]; name_author[0] = '\0'; }; Article(PrintEdition _edition,const char*_name ) { edition = _edition; int len = strlen(_name); this->name_author = new char[len + 1]; strcpy_s(this->name_author, len + 1, _name); this->name_author[len] = '\0'; }; Article(const Article& other) { this->edition = other.edition; int len = strlen(other.name_author); this->name_author = new char[len + 1]; strcpy_s(this->name_author, len + 1, other.name_author); this->name_author[len] = '\0'; }; Article& operator=(const Article& other) { if (this != &other) { delete[] this->name_author; this->edition = other.edition; int len = strlen(other.name_author); this->name_author = new char[len + 1]; strcpy_s(this->name_author, len + 1, other.name_author); this->name_author[len] = '\0'; } return *this; }; ~Article() { delete[] this->name_author; }; void print() { edition.print(); std::cout << name_author << std::endl; }; class Message { char* mess; char* sender; public: const char* getmess() const { return mess; } const char* getsender() const { return sender; } void print_sender() { std::cout << sender; } void print_mess() { std::cout << mess; } }; };
a360d2b60e6f5c8c5cbe844e8952e4092d3b6107
c9f0643360e17435db80298c4788f28dda695684
/UppgiftA/Source.cpp
4cc25d4e074e2ba373e63ad1ed53da1ea68df7e6
[]
no_license
Woebin/UppgiftA
67c715282fd11eb6a5f09cf62a35bab15ac62ea5
4650184e08e1a8b67a8e2a031f67978da4e37d0d
refs/heads/master
2021-01-19T02:09:31.814112
2016-11-10T13:37:08
2016-11-10T13:37:08
73,385,470
0
0
null
null
null
null
UTF-8
C++
false
false
342
cpp
Source.cpp
#include "Elephant.h" #include <string> #include <iostream> using namespace zoo; int main() { Elephant* elephants[3]; elephants[0] = new Elephant("Jumbo", 600, 170); elephants[1] = new Elephant("Mumbo", 500, 160); elephants[2] = new Elephant("Lillen", 800, 200); for (int i = 0; i < 3; ++i) printElephant(elephants[i]); return 0; }
d45efe89d62b30a35a56881c62e71e1b17748153
614f435c936612360cc0d5c2f6bfd0bfd531a3f0
/service/src/properties/source/PropertySource.h
4f0e38f3a1f9dcc9266d5bd0c5e0fe3157e57134
[ "Apache-2.0" ]
permissive
darvik80/rover-cpp
6a4db9140ca24f7a6eb0fcb1a1e26a609053a5b0
8da7b7f07efe7096843ae17536603277f55debea
refs/heads/master
2021-12-07T09:22:55.515589
2021-10-27T08:26:31
2021-10-27T08:26:31
192,087,118
2
1
Apache-2.0
2021-06-27T15:42:44
2019-06-15T14:20:28
C++
UTF-8
C++
false
false
960
h
PropertySource.h
// // Created by Ivan Kishchenko on 11.04.2021. // #pragma once #include <string> #include <string_view> #include <memory> #include "properties/NetworkProperties.h" #include "properties/LoggingProperties.h" #include "properties/HttpProperties.h" #include "properties/GrpcProperties.h" #include "properties/SerialProperties.h" #include "properties/MqttProperties.h" #include "properties/JoystickProperties.h" class PropertySource { public: typedef std::shared_ptr<PropertySource> Ptr; public: virtual void getProperties(NetworkProperties& props) = 0; virtual void getProperties(LoggingProperties& props) = 0; virtual void getProperties(HttpProperties& props) = 0; virtual void getProperties(GrpcProperties& props) = 0; virtual void getProperties(SerialProperties& props) = 0; virtual void getProperties(MqttProperties& props) = 0; virtual void getProperties(JoystickProperties& props) = 0; ~PropertySource() = default; };
a2143aaf377352da8004ae24e2945783911d7f46
bf8072d530549fb3972777ef8b8550883fba32f0
/Contest3/bai7/bai7.cpp
caadd1ec51427d8b5d618e5332c016e2c2e9bd83
[]
no_license
vhg-vip/DataStructure
42bb48b9cb7cd13518cfe38f6c4fca063a991b91
2e2aeeb566816dde6deb82a4b3b6b04081df2aac
refs/heads/master
2022-12-14T03:44:49.373943
2020-08-30T14:35:12
2020-08-30T14:35:12
268,308,448
0
0
null
null
null
null
UTF-8
C++
false
false
806
cpp
bai7.cpp
#include<iostream> #include<vector> #include<algorithm> using namespace std; typedef long long ll; ll mod=1e9+7; bool cmp(ll a, ll b){ if(a>b) return true; else return false; } int main(){ int t; cin >> t; while(t--){ int n; cin >> n; vector<ll> a; vector<ll> b; for(int i=0; i<n; i++){ int k; cin >> k; a.push_back(k); } for(int i=0; i<n; i++){ int k; cin >> k; b.push_back(k); } sort(a.begin(), a.end()); sort(b.begin(), b.end(), cmp); ll res=0; for(int i=0; i<n; i++) { a[i] = a[i]%mod; b[i] = b[i]%mod; res += (a[i]*b[i])%mod; } cout << res << endl; } }
31d5295534243f3955a0ba4067adc471239867fe
c0cc585bca2066cbf46f6b3e9f4936f478181e0c
/include/TCPServer.cpp
495acc5cb8d5d26738d75754962bf6699ef6038d
[]
no_license
fassad1001/QT_UniversalIOInterface
638a97814e56db35067f2ced0b14cc7b17f29a91
c77280d78b5a4857477fc5d411125290cb90dda9
refs/heads/master
2021-04-12T08:02:38.678477
2018-03-19T13:56:15
2018-03-19T13:56:22
125,846,996
0
0
null
null
null
null
UTF-8
C++
false
false
5,825
cpp
TCPServer.cpp
#include "TCPServer.h" TCPServer::TCPServer() { qRegisterMetaType<Client>("Client"); StartAcceptingptr = NULL; MaxNumberClient = 0; } TCPServer::TCPServer(unsigned int port) { qRegisterMetaType<Client>("Client"); Port = port; MaxNumberClient = 0; StartAcceptingptr = NULL; } TCPServer::~TCPServer() { Stop(); } bool TCPServer::setPort(unsigned int port) { if (StartAcceptingptr.isNull()) { // нельзя изменять порт при включенном сервере Port = port; return true; } return false; } unsigned int TCPServer::getPort() { return Port; } void TCPServer::InisializedServer() { if (Inisialized()) { // Setup the TCP listening socket int isResult = bind(Socket, resAddr->ai_addr, (int)resAddr->ai_addrlen); if (isResult == SOCKET_ERROR) { std::cout << "bind failed with error: " << WSAGetLastError() << std::endl; freeaddrinfo(resAddr); closesocket(Socket); if (!isWSACleanup) WSACleanup(); isWSACleanup = true; return; } freeaddrinfo(resAddr); isResult = listen(Socket, SOMAXCONN); if (isResult == SOCKET_ERROR) { std::cout << "listen failed with error: " << WSAGetLastError() << std::endl; closesocket(Socket); if (!isWSACleanup) WSACleanup(); isWSACleanup = true; return; } } } void TCPServer::Start() { if (!StartAcceptingptr.isNull()) return; InisializedServer(); // Запускаем поиск клиентов StartAcceptingptr = createPostFuncA(TCPServer, this, &TCPServer::StartAccepting); StartAcceptingptr->AddPostEvent(); } void TCPServer::Stop() { if (StartAcceptingptr.isNull()) return; // Отсанавливаем поиск клиентов StartAcceptingptr->getObj()->die(); StartAcceptingptr = NULL; MaxNumberClient = 0; // Отсоединяем всех клиентоа foreach (Client client, clients) { DisconnectClient(client); } shutdown(Socket, SD_BOTH); closesocket(Socket); if (!isWSACleanup) WSACleanup(); isWSACleanup = true; } void TCPServer::StartAccepting() { while (StartAcceptingptr->getObj()->GetLiveStatus()) { fd_set s_set; FD_ZERO(&s_set); FD_SET(Socket, &s_set); timeval timeout = {0, 0}; int select_res = select(1, &s_set, NULL, NULL, &timeout); // Проверяем наличие клиентов желающих подключиться if (select_res == SOCKET_ERROR) continue; if (select_res) { // Accept a client socket struct sockaddr_in client_info; int sizeAddr = sizeof(client_info); SOCKET socketClient = accept(Socket, (sockaddr*)&client_info, &sizeAddr); if (socketClient == INVALID_SOCKET) { qDebug() << "accept failed with error:" << WSAGetLastError(); closesocket(Socket); if (!isWSACleanup) WSACleanup(); isWSACleanup = true; return; } clients.push_back(Client(MaxNumberClient, QString("Client"), QString(inet_ntoa(client_info.sin_addr)), ntohs(client_info.sin_port), socketClient)); emit signalAcceptClient(clients.last()); SenderClientptr = createPostFunc(TCPServer, this, &TCPServer::SendToClient, Client, QByteArray); ReceiverClientptr = createPostFunc(TCPServer, this, &TCPServer::ReceiveFromClient, Client); ReceiverClientptr->AddPostEvent(clients.last()); Receivers.insert(MaxNumberClient, ReceiverClientptr); Senders.insert(MaxNumberClient, SenderClientptr); MaxNumberClient++; } } } void TCPServer::ReceiveFromClient(Client client) { int resultSelect = 0; unsigned long length; TReceiverClient receiver = Receivers[client.Number]; while (receiver->getObj()->GetLiveStatus()) { fd_set s_set; FD_ZERO(&s_set); FD_SET(client.Socket, &s_set); timeval timeout = {0, 0}; resultSelect = select(1, &s_set, NULL, NULL, &timeout); ioctlsocket(client.Socket, FIONREAD, &length); if (resultSelect == 1 && length == 0) break; // Если сокет мёртв Sleep(1); // В некоторых случаях не срабатывает проверка выше без переключения процессов QByteArray recvData; if (TCPSocket::ReadAll(client.Socket, recvData)) { if (recvData.size() != 0) { emit signalRecvData(client, recvData); } } } CloseSocketClient(client); } void TCPServer::slotSendData(Client client, QByteArray data) { if (Senders.contains(client.Number)) { Senders[client.Number]->AddPostEvent(client, data); } } void TCPServer::SendToClient(Client client, QByteArray data) { Write(client.Socket, data); } void TCPServer::CloseSocketClient(const Client &client) { if (clients.contains(client)) { SOCKET socketClient = client.Socket; shutdown(socketClient, SD_BOTH); closesocket(socketClient); emit signalDisconectClient(client); Receivers.remove(client.Number); Senders.remove(client.Number); clients.removeAll(client); } } void TCPServer::DisconnectClient(const Client &client) { if (clients.contains(client)) { TReceiverClient receiver = Receivers[client.Number]; receiver->getObj()->die(); } }
b114f7bacf99040625327bdaa92278335b3aa094
a799823d46e58f21c4eeed2a39a4be1bce36418f
/output.cpp
02ae990170b44dd90d14467f8ab24b6a0206d206
[]
no_license
jburkholder/io
79acf4f39e6fbd3a36b3c5e23479bda33c5bfbb8
1b5ce2a5458f7f2c1d9d56ce2c703bec3a993ddf
refs/heads/master
2021-01-10T08:58:36.074548
2015-11-15T00:21:43
2015-11-15T00:21:43
44,889,607
0
0
null
null
null
null
UTF-8
C++
false
false
318
cpp
output.cpp
#include <output.hpp> #include <mutex> // For: // std::mutex // std::lock_guard #include <temporary.hpp> static std::mutex output_main_mutex; void output_main() { std::lock_guard<std::mutex> output_main_lock( output_main_mutex ); try { debug_print( "Hello", ", ", "Output" ); } catch ( ... ) { throw; } }
6d137c11464f41e1ba9e2214d6bf996c861b388c
588c59ce0d31e9874dee2902e9f1cd87a909b74b
/Graph/Graph/graph.cpp
0e96df63ce7b0c4c7bae589956b5aed952148e9a
[]
no_license
MemoryOfStars/rehab
e56da637a6ec89bb283b45498aea301cd14d9fb0
d0eceaa3a48ee502268848d7c98c2d31e1aa5ed8
refs/heads/master
2020-08-29T00:24:37.635064
2019-12-01T07:17:29
2019-12-01T07:17:29
217,864,311
0
0
null
null
null
null
UTF-8
C++
false
false
462
cpp
graph.cpp
#include<iostream> #include<stdlib.h> #include<vector> #include"structure_define.h" using namespace std; int main() { Graph g = Graph(); g.addvertex("A"); g.addvertex("B"); g.addvertex("C"); g.addvertex("D"); g.addvertex("E"); g.addvertex("F"); g.addedge("A", "B", 4); g.addedge("A", "E", 7); g.addedge("A", "F", 3); g.addedge("B", "C", 20); g.addedge("B", "D", 10); g.addedge("C", "F", 6); g.addedge("D", "E", 11); g.Dijkstra("A"); return 0; }
af0a7333a675f8ab5d46a31571f993a9b3fe4343
89315bac44965dfb2ff149deda06ae6a069f3ece
/Source/main.cpp
50dad3b595379907bca4318d25ad1c478df2bd8b
[]
no_license
ulkumeteriz/Ray-Tracer
cf66884d3aaf7872b83b090c7856eb141b1d54bf
7831622239fc174ac7665697a2b43cbe8c3236a0
refs/heads/master
2020-04-03T22:11:19.113761
2018-10-31T16:57:22
2018-10-31T16:57:22
155,592,854
1
0
null
null
null
null
UTF-8
C++
false
false
12,250
cpp
main.cpp
#include <iostream> #include "parser.h" #include <GL/glew.h> #include <GLFW/glfw3.h> #include <math.h> #include "matrix4.hpp" #define PI 3.14159265359 using namespace parser; using namespace std; parser::Scene scene; static GLFWwindow* win = NULL; static const float CAMERA_TRANS_SPEED = 0.05f; // in radian static const float ROTATION_ANGLE = 0.5 * ( PI / 180 ); static bool lightState; static void errorCallback(int error, const char* description) { fprintf(stderr, "Error: %s\n", description); } void setCamera(); // turns on all the lights void turnOnLights(); // turns off all the lights void turnOffLights(); // 0-index void turnOnLight(int lightId); // 0-index void turnOffLight(int lightId); // 1-index void toggleLight(int lightId); Matrix4 createTransformationMatrixForRotation(Vector3 rotationAxis, float rotationAngle); static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { // if action is not press, do take no action if(action != GLFW_PRESS) return; switch(key) { case GLFW_KEY_ESCAPE: glfwSetWindowShouldClose(window, GLFW_TRUE); break; // keys that change the direction of the camera case GLFW_KEY_A: { // TODO look left, rotate gaze vector 0.5 degrees around up Matrix4 transformationMatrix = createTransformationMatrixForRotation(scene.camera.up, ROTATION_ANGLE); scene.camera.gaze = transformationMatrix * scene.camera.gaze; scene.camera.gaze.normalize(); break; } case GLFW_KEY_D: { // TODO look right, rotate gaze vector -0.5 degrees around up Matrix4 transformationMatrix = createTransformationMatrixForRotation(scene.camera.up, -1 * ROTATION_ANGLE); scene.camera.gaze = transformationMatrix * scene.camera.gaze; scene.camera.gaze.normalize(); break; } case GLFW_KEY_U: { // TODO look up, rotate gaze vector 0.5 degrees around left vector Vector3 leftVector = scene.camera.gaze * scene.camera.up; Matrix4 transformationMatrix = createTransformationMatrixForRotation(leftVector, ROTATION_ANGLE); scene.camera.gaze = transformationMatrix * scene.camera.gaze; scene.camera.gaze.normalize(); break; } case GLFW_KEY_J: { // TODO look down, rotate gaze vector -0.5 degrees around left vector Vector3 leftVector = scene.camera.gaze * scene.camera.up; Matrix4 transformationMatrix = createTransformationMatrixForRotation(leftVector, -1 * ROTATION_ANGLE); scene.camera.gaze = transformationMatrix * scene.camera.gaze; scene.camera.gaze.normalize(); break; } // keys that change the position of camera case GLFW_KEY_W: { scene.camera.position.x += scene.camera.gaze.x * CAMERA_TRANS_SPEED; scene.camera.position.y += scene.camera.gaze.y * CAMERA_TRANS_SPEED; scene.camera.position.z += scene.camera.gaze.z * CAMERA_TRANS_SPEED; break; } case GLFW_KEY_S: { scene.camera.position.x -= scene.camera.gaze.x * CAMERA_TRANS_SPEED; scene.camera.position.y -= scene.camera.gaze.y * CAMERA_TRANS_SPEED; scene.camera.position.z -= scene.camera.gaze.z * CAMERA_TRANS_SPEED; break; } // light case GLFW_KEY_0: if(lightState) { turnOffLights(); lightState = false; } else { turnOnLights(); lightState = true; } break; case GLFW_KEY_1: toggleLight(1); break; case GLFW_KEY_2: toggleLight(2); break; case GLFW_KEY_3: toggleLight(3); break; case GLFW_KEY_4: toggleLight(4); break; case GLFW_KEY_5: toggleLight(5); break; case GLFW_KEY_6: toggleLight(6); break; case GLFW_KEY_7: toggleLight(7); break; case GLFW_KEY_8: toggleLight(8); break; case GLFW_KEY_9: toggleLight(9); break; } // set camera again setCamera(); } Matrix4 createTransformationMatrixForRotation(Vector3 rotationAxis, float rotationAngle) { Vector3 & u = rotationAxis.normalize(); Vector3 v = u.generateDifferentlyDirectedVector(); v.normalize(); Vector3 w = u * v; w.normalize(); // then, correct v v = w * u; v.normalize(); float MArray[4][4] = { { u.getX(), u.getY(), u.getZ(), 0 }, { v.getX(), v.getY(), v.getZ(), 0 }, { w.getX(), w.getY(), w.getZ(), 0 }, { 0, 0, 0, 1 } }; float MInverseArray[4][4] = { { u.getX(), v.getX(), w.getX(), 0 }, { u.getY(), v.getY(), w.getY(), 0 }, { u.getZ(), v.getZ(), w.getZ(), 0 }, { 0, 0, 0, 1 } }; float cosine = cos(rotationAngle); float sine = sin(rotationAngle); float rotationArray[4][4] = { { 1, 0, 0, 0 }, { 0, cosine, -sine, 0 }, { 0, sine, cosine, 0 }, { 0, 0, 0, 1 } }; Matrix4 M(MArray); Matrix4 inverseM(MInverseArray); Matrix4 transformationMatrix = inverseM * Matrix4(rotationArray) * M; return transformationMatrix; } void loadTransformation(const Transformation & transformation) { switch(transformation.type) { case TRANSLATION: glTranslatef( scene.translations[transformation.id].x, scene.translations[transformation.id].y, scene.translations[transformation.id].z ); break; case ROTATION: glRotatef( scene.rotations[transformation.id].x, scene.rotations[transformation.id].y, scene.rotations[transformation.id].z, scene.rotations[transformation.id].w ); break; case SCALING: glScalef( scene.scalings[transformation.id].x, scene.scalings[transformation.id].y, scene.scalings[transformation.id].z ); break; } return; } void toggleLight(int lightId) { // 0-index lightId--; if(lightId >= (int)scene.point_lights.size()) return; PointLight & pLight = scene.point_lights[lightId]; if(pLight.status) turnOffLight(lightId); else turnOnLight(lightId); } // 0-index void turnOnLight(int lightId) { if(lightId >= (int)scene.point_lights.size()) return; PointLight & pLight = scene.point_lights[lightId]; pLight.status = true; GLfloat ambient[] = { scene.ambient_light.x, scene.ambient_light.y, scene.ambient_light.z }; glEnable(GL_LIGHT0 + lightId); GLfloat intensity[] = { pLight.intensity.x, pLight.intensity.y, pLight.intensity.z, 1.0f }; GLfloat position[] = { pLight.position.x, pLight.position.y, pLight.position.z, 1.0f }; glLightfv(GL_LIGHT0 + lightId, GL_POSITION, position); glLightfv(GL_LIGHT0 + lightId, GL_AMBIENT, ambient); glLightfv(GL_LIGHT0 + lightId, GL_DIFFUSE, intensity); glLightfv(GL_LIGHT0 + lightId, GL_SPECULAR, intensity); } // 0-index void turnOffLight(int lightId) { if(lightId >= (int)scene.point_lights.size()) return; PointLight & pLight = scene.point_lights[lightId]; pLight.status = false; glDisable(GL_LIGHT0 + lightId); } void turnOffLights() { lightState = false; for(int i = 0; i < (int)scene.point_lights.size(); i++) { turnOffLight(i); } } void turnOnLights() { lightState = true; for(int i = 0; i < (int)scene.point_lights.size(); i++) { turnOnLight(i); } } void loadVertex(int vertexId) { glNormal3f( scene.vertex_data[vertexId].normal.getX(), scene.vertex_data[vertexId].normal.getY(), scene.vertex_data[vertexId].normal.getZ() ); glVertex3f( scene.vertex_data[vertexId].position.getX(), scene.vertex_data[vertexId].position.getY(), scene.vertex_data[vertexId].position.getZ() ); } void render() { // clear color and buffer bits // clearColor indicates background color, initial paint glClearColor( scene.background_color.x / 255.0f, scene.background_color.y / 255.0f, scene.background_color.z / 255.0f, 1.0); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // for all meshes for(int meshInd = 0; meshInd < (int)scene.meshes.size(); meshInd++) { Mesh & mesh = scene.meshes[meshInd]; // load mesh type switch(mesh.type) { case SOLID: glPolygonMode(GL_FRONT_AND_BACK, GL_FILL); break; case WIREFRAME: glPolygonMode(GL_FRONT_AND_BACK, GL_LINE); break; } // load material Material & material = scene.materials[mesh.material_id]; GLfloat ambColor[4] = { material.ambient.x, material.ambient.y, material.ambient.z, 1.0}; GLfloat diffColor[4] = { material.diffuse.x, material.diffuse.y, material.diffuse.z, 1.0}; GLfloat specColor[4] = { material.specular.x, material.specular.y, material.specular.z, 1.0}; GLfloat specExp[1] = { material.phong_exponent }; glMaterialfv(GL_FRONT, GL_AMBIENT, ambColor); glMaterialfv(GL_FRONT, GL_DIFFUSE, diffColor); glMaterialfv(GL_FRONT, GL_SPECULAR, specColor); glMaterialfv(GL_FRONT, GL_SHININESS, specExp); // turn on lights // TODO: more work is going to be done on light on/off //turnOnLights(); // load transformations glMatrixMode(GL_MODELVIEW); // push the current MODELVIEW matrix to the stack // .. since it carries the view matrix glPushMatrix(); for(int transInd = (int)mesh.transformations.size() - 1; transInd >= 0 ; transInd--) { Transformation & transformation = mesh.transformations[transInd]; loadTransformation(transformation); } // add vertices glBegin(GL_TRIANGLES); for(int faceId = 0; faceId < (int)mesh.faces.size(); faceId++) { Face & face = mesh.faces[faceId]; loadVertex(face.v0_id); loadVertex(face.v1_id); loadVertex(face.v2_id); } glEnd(); // pop the saved MODELVIEW matrix, which carries the view matrix // .. regarding to the camera glPopMatrix(); } } void setCamera() { // viewport glViewport( 0, 0, scene.camera.image_width, scene.camera.image_height ); // modelview glMatrixMode(GL_MODELVIEW); glLoadIdentity(); // compute U, V, W Vector3 vecV(scene.camera.up.x, scene.camera.up.y, scene.camera.up.z); vecV.normalize(); Vector3 vecW = -Vector3(scene.camera.gaze.x, scene.camera.gaze.y, scene.camera.gaze.z); vecW.normalize(); vecW.normalize(); Vector3 vecU = vecV * vecW; // cross product vecU.normalize(); vecV = vecW * vecU; // in case, update the scene's gaze and up vector scene.camera.gaze.x = -vecW.getX(); scene.camera.gaze.y = -vecW.getY(); scene.camera.gaze.z = -vecW.getZ(); scene.camera.up.x = vecV.getX(); scene.camera.up.y = vecV.getY(); scene.camera.up.z = vecV.getZ(); gluLookAt( scene.camera.position.x, scene.camera.position.y, scene.camera.position.z, -vecW.getX() + scene.camera.position.x, -vecW.getY() + scene.camera.position.y, -vecW.getZ() + scene.camera.position.z, vecV.getX(), vecV.getY(), vecV.getZ() ); // projection glMatrixMode(GL_PROJECTION); glLoadIdentity(); glFrustum( scene.camera.near_plane.x, scene.camera.near_plane.y, scene.camera.near_plane.z, scene.camera.near_plane.w, scene.camera.near_distance, scene.camera.far_distance ); } int main(int argc, char* argv[]) { // load scene file scene.loadFromXml(argv[1]); // set error callback glfwSetErrorCallback(errorCallback); // initialize glfw if (!glfwInit()) { exit(EXIT_FAILURE); } // create window win = glfwCreateWindow(scene.camera.image_width, scene.camera.image_height, "CENG477 HW3: Speedy Gonzales", NULL, NULL); if (!win) { glfwTerminate(); exit(EXIT_FAILURE); } // select the windows that objects will be rendered to glfwMakeContextCurrent(win); // initialize glew GLenum err = glewInit(); if (err != GLEW_OK) { fprintf(stderr, "Error: %s\n", glewGetErrorString(err)); exit(EXIT_FAILURE); } // set key callback glfwSetKeyCallback(win, keyCallback); // set camera setCamera(); // shading mode: smooth glShadeModel(GL_SMOOTH); // enable depth_test and lighting glEnable(GL_DEPTH_TEST); glEnable(GL_LIGHTING); // initial case: light are turned on render(); turnOnLights(); while(!glfwWindowShouldClose(win)) { glfwWaitEvents(); render(); glfwSwapBuffers(win); } glfwDestroyWindow(win); glfwTerminate(); exit(EXIT_SUCCESS); return 0; }
998e9d5b5fa744dc7cfb9a2937bfd610965ab006
d93159d0784fc489a5066d3ee592e6c9563b228b
/Validation/DTRecHits/plugins/SealModule.cc
72272efd823e8e0e486737cec7aa3d86b5b48c73
[]
permissive
simonecid/cmssw
86396e31d41a003a179690f8c322e82e250e33b2
2559fdc9545b2c7e337f5113b231025106dd22ab
refs/heads/CAallInOne_81X
2021-08-15T23:25:02.901905
2016-09-13T08:10:20
2016-09-13T08:53:42
176,462,898
0
1
Apache-2.0
2019-03-19T08:30:28
2019-03-19T08:30:24
null
UTF-8
C++
false
false
755
cc
SealModule.cc
#include "FWCore/Framework/interface/MakerMacros.h" #include "Validation/DTRecHits/plugins/DTRecHitQuality.h" #include "Validation/DTRecHits/plugins/DTSegment2DQuality.h" #include "Validation/DTRecHits/plugins/DTSegment2DSLPhiQuality.h" #include "Validation/DTRecHits/plugins/DTSegment4DQuality.h" #include "Validation/DTRecHits/plugins/DTRecHitClients.h" #include "Validation/DTRecHits/plugins/DT2DSegmentClients.h" #include "Validation/DTRecHits/plugins/DT4DSegmentClients.h" DEFINE_FWK_MODULE(DTRecHitQuality); DEFINE_FWK_MODULE(DTSegment2DQuality); DEFINE_FWK_MODULE(DTSegment2DSLPhiQuality); DEFINE_FWK_MODULE(DTSegment4DQuality); DEFINE_FWK_MODULE(DTRecHitClients); DEFINE_FWK_MODULE(DT2DSegmentClients); DEFINE_FWK_MODULE(DT4DSegmentClients);
f2cda1a44d3f8a810f8c4a2b0b6356173bc84dc8
24e015bfc2883daf97c71a5c08cc3765d3678c74
/cpp/PageRef.h
2123e4a9c30c7ea015ce9cc3c9c47242ea1882c1
[]
no_license
herobd/crowdcat
4309a45fc9de0f42d7919d37af1034c78c392c67
67c24a18d5a6172b450bf4916557e10b3aebac43
refs/heads/master
2021-01-17T07:59:42.470951
2017-03-31T23:25:27
2017-03-31T23:25:27
83,824,594
1
0
null
null
null
null
UTF-8
C++
false
false
1,454
h
PageRef.h
#ifndef PAGE_REF #define PAGE_REF #include <map> #include "opencv2/core/core.hpp" #include "Location.h" using namespace std; //This object is purely to provide pointers when loading the systems state. //It is created by the Page and then passed to the MasterQueue //For debugging, it holds all word bounding boxes and can verify if a spotting object is valid class PageRef { public: PageRef() {} void addPage(int pageId, const cv::Mat* im) { pages[pageId]=im; } void addWord(const Location& loc) { words[loc.pageId].push_back(loc); } const cv::Mat* getPageImg(int pageId) const { return pages.at(pageId); } bool verify(int pageId, int tlx, int tly, int brx, int bry) const { if (pageId<0) return false; //check against words bool found=false; for (const Location& loc : words.at(pageId)) { if (loc.x1<=tlx && loc.y1<=tly && loc.x2>=brx && loc.y2>=bry) { if (pageId==0 && tlx==1574 && tly==2968 && brx==1664 && bry==3126) cout<<"[!] Matching word is at, page:"<<pageId<<" x1:"<<loc.x1<<" y1:"<<loc.y1<<" x2:"<<loc.x2<<" y2:"<<loc.y2<<endl; found=true; break; } } return found; } private: map<int, const cv::Mat*> pages; map<int, vector<Location> > words; }; #endif
2b8fba557c35264706b198812b2eb2cc28fec080
24cb0327427918882f25def47b4a16d7631cfa4b
/Library/patient_page.h
fbca6375e38317c97b33f69856b0ff6d65ab7d2a
[]
no_license
post-operative-care/GUI
c460c807285c18b70a936afdf4397cd7f04d89ac
e236799384ed0b0ef04821e2022d980ee02a0997
refs/heads/master
2021-05-19T11:31:21.280291
2020-04-15T06:31:05
2020-04-15T06:31:05
251,675,631
0
0
null
2020-04-14T15:09:02
2020-03-31T17:12:55
C++
UTF-8
C++
false
false
167
h
patient_page.h
#include<iostream> #include<fstream> #include<iomanip> #include<vector> #include<string> #include<cstdlib> #include<cstring> #include<windows.h> using namespace std;
33de3be4e88ceb86cd4dc8d3958741e71226e3bf
75ac581fff16bc6ec1f0a370a7c144e1826ed34c
/Modelo/Persona.cpp
59ef9f442961797e8f053ca1e19e2c12c3d5ee0f
[]
no_license
IsaacEscobar/POSGSOFT-IER-SHG
19a30ad81dc415c5f0425a2c5fa1331e99ad47c8
db73da77b57379ced51cfd89f6719ae55d99f077
refs/heads/main
2023-08-01T11:40:51.757930
2021-09-15T04:01:47
2021-09-15T04:01:47
405,523,367
0
0
null
null
null
null
UTF-8
C++
false
false
487
cpp
Persona.cpp
#include "Persona.h" // clase padre // constructor por defecto Persona::Persona() { } void Persona::mostrarInformacion(string nombre, int documento) { cout << "nombre" << nombre << "\n"; cout << documento << documento << "\n"; } void Persona::setNombre(string nombre) { this->nombre = nombre; } string Persona::getNombre() { return nombre; } void Persona::setDocumento(int documento) { this->documento = documento; } int Persona::getDocumento() { return documento; }
c59f14bf49b2645b3b621ccfe4c3c6e9b2466f40
5e5f82bd51f8025d95f55423506638308952ad31
/common/seda/Stage.h
c68a38cbf9934b77a5c11a91c91e8590ac239804
[]
no_license
fanjizhao/zonda
fbad2526135fbcb9bc3875175a206355799362f2
78b2941402e20c9ba31870ab43cc26134d2c05b3
refs/heads/master
2022-05-12T10:10:29.444731
2022-03-22T15:07:00
2022-03-22T15:07:00
8,473,194
5
7
null
null
null
null
UTF-8
C++
false
false
6,188
h
Stage.h
#ifndef ZONDA_COMMON_STAGE_H_ #define ZONDA_COMMON_STAGE_H_ #include <iostream> #include <vector> #include "IStage.h" #include "StageThread.h" #include "StageMgr.h" #include "log/Logger.h" #include "EventDispatcher.h" namespace zonda { namespace common { template <class TypeOfHandler, class TypeOfQueue = EventQueue> class Stage: public IStage { public: Stage(const char *name, size_t queue_capacity, int thread_count = 1, StageThreadMode thread_mode = EXLUSIVE); virtual int init(void *handler_param); virtual void set_event_dispatcher(EventDispatcher* dispatcher); virtual const char* get_name(); virtual IEventSink* get_sink(); virtual uint16_t get_id(); virtual int start(); virtual void stop(); virtual ~Stage(); virtual void enable_trace(); virtual void disable_trace(); private: std::string m_name; TypeOfQueue* m_event_queues; EventDispatcher* m_event_dispatcher; size_t m_queue_capacity; std::vector<TypeOfHandler*> m_handler_vector; int m_thread_count; StageThreadMode m_thread_mode; std::vector<StageThread*> m_thread_vector; uint16_t m_my_id; }; }//namespace common }//namespace zonda using namespace zonda::common; template <class TypeOfHandler, class TypeOfQueue> Stage<TypeOfHandler, TypeOfQueue>::Stage(const char *name, size_t queue_capacity, int thread_count , StageThreadMode thread_mode): m_name(name), //m_event_queue(), m_queue_capacity(queue_capacity), m_thread_count(thread_count), m_thread_mode(thread_mode) { m_event_queues = new TypeOfQueue[thread_count]; m_event_dispatcher = new EventDispatcher(); //Indicates this stage is not registered. m_my_id = -1; } template <class TypeOfHandler, class TypeOfQueue> Stage<TypeOfHandler, TypeOfQueue>::~Stage() { if (m_my_id != 0xFFFF) { StageMgr::instance()->dereg_stage(this); } //NOTE:It seems to free allocated thread objects and //event handler objects is uncessary since when we free the stage //object, that means we want to end the process. //On the other hand, if we want to free the thread objects and //event handler objects, we must free thread objects first because //the event handler objects are used by these thread objects. //To free thread objects, we need to ensure the real OS thread is alreay // stoped. That is too troublesome. } template <class TypeOfHandler, class TypeOfQueue> int Stage<TypeOfHandler, TypeOfQueue>::init(void* handler_param) { int r = 0; for (int i=0; i<m_thread_count; ++i) { r = m_event_queues[i].set_capacity(m_queue_capacity); if (r != 0) { LOG_FATAL("Failed to set_capacity of the queue"); return r; } //LOG_DEBUG("m_event_queues[" << i << "] size=" << (long)&m_event_queues[i]); } //Create the handlers if (m_thread_mode == SHARED) { TypeOfHandler* handler = new TypeOfHandler(); r = handler->init(this, handler_param); if (r != 0) { LOG_FATAL("Failed to init the handler"); return r; } m_handler_vector.push_back(handler); } else { for (int i=0; i<m_thread_count; ++i) { TypeOfHandler* handler = new TypeOfHandler(); int r = handler->init(this, handler_param); if (r) { LOG_FATAL("Failed to init the handler"); return -1; } m_handler_vector.push_back(handler); } } //Create the thread for (int i=0; i<m_thread_count; ++i) { StageThread* t = new StageThread(this); if (m_thread_mode == SHARED) { t->set_event_handler(m_handler_vector[0]); } else { t->set_event_handler(m_handler_vector[i]); } char thread_name[200]; sprintf(thread_name, "%s_%d", m_name.c_str(), i); t->set_thread_name(thread_name); t->set_event_source(&m_event_queues[i]); m_thread_vector.push_back(t); } IEventQueue* queues[m_thread_count]; for (int i=0; i<m_thread_count; ++i) { queues[i] = &m_event_queues[i]; } m_event_dispatcher->set_internal_queues(queues, m_thread_count); r = StageMgr::instance()->reg_stage(this, m_my_id); if ( r!= 0) { LOG_FATAL("Failed to reg_stage"); return r; } return 0; } template <class TypeOfHandler, class TypeOfQueue> void Stage<TypeOfHandler, TypeOfQueue>::set_event_dispatcher(EventDispatcher* dispatcher) { delete m_event_dispatcher; m_event_dispatcher = dispatcher; if (m_event_queues != NULL) { IEventQueue* queues[m_thread_count]; for (int i=0; i<m_thread_count; ++i) { queues[i] = &m_event_queues[i]; } m_event_dispatcher->set_internal_queues(queues, m_thread_count); } } template <class TypeOfHandler, class TypeOfQueue> const char* Stage<TypeOfHandler, TypeOfQueue>::get_name() { return m_name.c_str(); } template <class TypeOfHandler, class TypeOfQueue> IEventSink* Stage<TypeOfHandler, TypeOfQueue>::get_sink() { //return &m_event_queue; return m_event_dispatcher; } template <class TypeOfHandler, class TypeOfQueue> uint16_t Stage<TypeOfHandler, TypeOfQueue>::get_id() { return m_my_id; } template <class TypeOfHandler, class TypeOfQueue> int Stage<TypeOfHandler, TypeOfQueue>::start() { LOG_DEBUG("stage_name:" << m_name << ", thread count:" << m_thread_vector.size()); for (size_t i=0; i<m_thread_vector.size(); ++i) { int r = m_thread_vector[i]->start(); if (r != 0) { return -1; } } return 0; } template <class TypeOfHandler, class TypeOfQueue> void Stage<TypeOfHandler, TypeOfQueue>::stop() { for (size_t i=0; i<m_thread_vector.size(); ++i) { std::cout << "Stage::stop(), " << std::endl; m_thread_vector[i]->stop(); } } template <class TypeOfHandler, class TypeOfQueue> void Stage<TypeOfHandler, TypeOfQueue>::enable_trace() { for (size_t i=0; i<m_thread_vector.size(); ++i) { m_thread_vector[i]->enable_trace(); } } template <class TypeOfHandler, class TypeOfQueue> void Stage<TypeOfHandler, TypeOfQueue>::disable_trace() { for (size_t i=0; i<m_thread_vector.size(); ++i) { m_thread_vector[i]->disable_trace(); } } #endif //ZONDA_COMMON_STAGE_H_
bbcd556f0211a7cb09ea798d81ad8d71c053bdad
4096f25bf0a689eb6d648619415ab2f9a711501c
/2DLibV2/Texture/Texture.hpp
0d260104a09101003d2ea01bf1628e44ad1e5bf3
[]
no_license
semenovsergey0706/OpenGLBased2D
b27f53575a0c4750fa183c60514dde103776927b
5afa2b93419cde29b8bcd75ebdb698753998d01b
refs/heads/master
2023-01-05T22:20:19.212421
2020-11-07T12:37:34
2020-11-07T12:37:34
290,451,027
0
0
null
null
null
null
UTF-8
C++
false
false
552
hpp
Texture.hpp
#pragma once #include <string> #include <memory> #include "../../OpenGLWrappers/TextureObj.hpp" #include <glm/glm.hpp> #include <glm/gtc/matrix_transform.hpp> #include <glm/gtc/type_ptr.hpp> class Texture { private: int m_textureID; TextureObj<GL_TEXTURE_2D> m_textureObj; glm::vec2 m_size; public: Texture(); Texture(Texture&& texture) noexcept; void setID(int id); void loadFromFile(const char *path); const glm::vec2& getSize() const; const GLuint get() const; const int getID()const; void bind(); void unbind(); virtual ~Texture(); };
b34acae497c05b262b21ee87a36e7fa9e04fe9d0
c38d6e28655d1c51829c66912e47f1c5578acc73
/src/memo/filesystem/Unreachable.cc
85aa23fd36b9a6f2db85331094a2691111541894
[ "Apache-2.0" ]
permissive
TheodorKleynhans/memo
812dd573f574f69d6b3bd50ea9a3bf180de06eca
47095bf37a09258a957bf78efda3558762d41386
refs/heads/master
2021-01-15T22:10:14.453446
2017-07-24T16:21:49
2017-07-24T16:22:00
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,824
cc
Unreachable.cc
#include <memo/filesystem/Unreachable.hh> #include <elle/cast.hh> ELLE_LOG_COMPONENT("memo.filesystem.Unreachable"); namespace memo { namespace filesystem { /*-------------. | Construction | `-------------*/ Unreachable::Unreachable(FileSystem& owner, std::unique_ptr<model::blocks::Block> data, std::shared_ptr<DirectoryData> parent, std::string const& name, Address address, EntryType type) : Node(owner, address, parent, name) , _data(std::move(data)) , _type(type) {} Unreachable::~Unreachable() { ELLE_DEBUG("%s: destroyed", this); } /*-----. | Path | `-----*/ bool Unreachable::allow_cache() { return false; } void Unreachable::stat(struct stat* st) { memset(st, 0, sizeof(struct stat)); st->st_mode = this->_type == EntryType::file ? S_IFREG : S_IFDIR; } std::string Unreachable::getxattr(std::string const& key) { return umbrella( [this, &key] () -> std::string { if (auto special = xattr_special(key)) { if (*special == "auth") { return this->perms_to_json(dynamic_cast<ACLBlock&>(*this->_data)); } else if (this->_type == EntryType::directory && *special == "auth.inherit") { return "unknown"; } } return Node::getxattr(key); }); } /*----------. | Printable | `----------*/ void Unreachable::print(std::ostream& stream) const { elle::fprintf(stream, "Unreachable(\"%s\")", this->_name); } } }
d59cb4c7ea919380cb7a9690ec4cd48f27288f65
a67aff40080148e6ef791cae0a983d3dfc51a3e5
/LeetCode/tags/hash-table/count-good-meals.cpp
5e55033fb9c64016e5a0621a6b8cea7ed15fa918
[]
no_license
llenroc/CP
622b97676dafc80dbcb7054977fcb73702f370fe
fa4c5160f37b6cc550b062bf77b17b0484efc671
refs/heads/master
2023-03-28T17:25:28.548230
2021-04-06T11:09:14
2021-04-06T11:09:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
951
cpp
count-good-meals.cpp
#include<bits/stdc++.h> using namespace std; #define endl '\n' #define MOD 1000000007 typedef vector<int> vi; typedef vector<vector<int>> vii; class Solution { private: unordered_map<int, int> meals; long twoPointerSum(int target) { auto s=meals.begin(), e=rbegin(); long count=0; while(s!=e) { int x = (*s).first, c1=(*s).second, y = (*e).first, c2=(*e).second; if(x+y==target) { count = (count + (c1*c2) % MOD) % MOD; } else if(x+y > target) { --e; } else { s++; } } return count; } public: int countPairs(vector<int>& deliciousness) { for(int x:deliciousness) items[x]++; long counter = 0; for(int i=0;i<=21;i++) { long target = pow(2,i); counter = (counter + goodMeals(target) % MOD) % MOD; } return counter; } };
67104378abc804145aa080312553f55ea39fa8c2
7354562d87d43f4f7dc7787cb44c0db99be23f18
/40.cpp
097984591374badf20d3bd0983488557d4a3e530
[]
no_license
adityamangal1998/competitive-coding-questions
a9d428ecd2a542cd4bd68c8ed81306ce9e33e828
2be25c999f58ece19010811d9986ecd5e959aa86
refs/heads/master
2020-07-22T11:22:55.766438
2020-05-29T12:34:56
2020-05-29T12:34:56
207,182,041
3
0
null
null
null
null
UTF-8
C++
false
false
279
cpp
40.cpp
#include<bits/stdc++.h> using namespace std; int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); cin.tie(NULL); int n; cin>>n; int temp; int count = 0; while(n--) { cin>>temp; if(__builtin_popcount(n)==1) { count++; } } cout<<count; }
e53fc4872ee0846d6179c88421f62c807845833d
3d144a23e67c839a4df1c073c6a2c842508f16b2
/include/swift/AST/Module.h
aa1d88cb6388292b96c73596e99f4ca317c255f9
[ "Apache-2.0", "Swift-exception" ]
permissive
apple/swift
c2724e388959f6623cf6e4ad6dc1cdd875fd0592
98ada1b200a43d090311b72eb45fe8ecebc97f81
refs/heads/main
2023-08-16T10:48:25.985330
2023-08-16T09:00:42
2023-08-16T09:00:42
44,838,949
78,897
15,074
Apache-2.0
2023-09-14T21:19:23
2015-10-23T21:15:07
C++
UTF-8
C++
false
false
45,984
h
Module.h
//===--- Module.h - Swift Language Module ASTs ------------------*- C++ -*-===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// // // This file defines the Module class and its subclasses. // //===----------------------------------------------------------------------===// #ifndef SWIFT_MODULE_H #define SWIFT_MODULE_H #include "swift/AST/AccessNotes.h" #include "swift/AST/Decl.h" #include "swift/AST/DeclContext.h" #include "swift/AST/Identifier.h" #include "swift/AST/Import.h" #include "swift/AST/LookupKinds.h" #include "swift/AST/Type.h" #include "swift/Basic/BasicSourceInfo.h" #include "swift/Basic/Compiler.h" #include "swift/Basic/Debug.h" #include "swift/Basic/OptionSet.h" #include "swift/Basic/STLExtras.h" #include "swift/Basic/SourceLoc.h" #include "llvm/ADT/ArrayRef.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/SmallVector.h" #include "llvm/ADT/StringMap.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/MD5.h" #include <set> namespace clang { class Module; } namespace swift { enum class ArtificialMainKind : uint8_t; class ASTContext; class ASTWalker; class BraceStmt; class Decl; class DeclAttribute; class TypeDecl; enum class DeclKind : uint8_t; class ExtensionDecl; class DebuggerClient; class DeclName; class FileUnit; class FuncDecl; class InfixOperatorDecl; enum class LibraryLevel : uint8_t; class LinkLibrary; class ModuleLoader; class NominalTypeDecl; class EnumElementDecl; class OperatorDecl; class PostfixOperatorDecl; class PrefixOperatorDecl; class ProtocolConformance; class ProtocolDecl; struct PrintOptions; class Token; class TupleType; class Type; class TypeRefinementContext; class ValueDecl; class VarDecl; class VisibleDeclConsumer; class ASTScope; class SourceLookupCache; namespace ast_scope { class ASTSourceFileScope; } /// Discriminator for file-units. enum class FileUnitKind { /// For a .swift source file. Source, /// For the compiler Builtin module. Builtin, /// A serialized Swift AST. SerializedAST, /// A synthesized file. Synthesized, /// An imported Clang module. ClangModule, /// A Clang module imported from DWARF. DWARFModule }; enum class SourceFileKind { Library, ///< A normal .swift file. Main, ///< A .swift file that can have top-level code. SIL, ///< Came from a .sil file. Interface, ///< Came from a .swiftinterface file, representing another module. MacroExpansion, ///< Came from a macro expansion. }; /// Contains information about where a particular path is used in /// \c SourceFiles. struct SourceFilePathInfo { struct Comparator { bool operator () (SourceLoc lhs, SourceLoc rhs) const { return lhs.getOpaquePointerValue() < rhs.getOpaquePointerValue(); } }; SourceLoc physicalFileLoc{}; std::set<SourceLoc, Comparator> virtualFileLocs{}; // std::set for sorting SourceFilePathInfo() = default; void merge(const SourceFilePathInfo &other) { if (other.physicalFileLoc.isValid()) { assert(!physicalFileLoc.isValid()); physicalFileLoc = other.physicalFileLoc; } for (auto &elem : other.virtualFileLocs) { virtualFileLocs.insert(elem); } } bool operator == (const SourceFilePathInfo &other) const { return physicalFileLoc == other.physicalFileLoc && virtualFileLocs == other.virtualFileLocs; } }; /// Discriminator for resilience strategy. enum class ResilienceStrategy : unsigned { /// Public nominal types: fragile /// Non-inlinable function bodies: resilient /// /// This is the default behavior without any flags. Default, /// Public nominal types: resilient /// Non-inlinable function bodies: resilient /// /// This is the behavior with -enable-library-evolution. Resilient }; class OverlayFile; /// A mapping used to find the source file that contains a particular source /// location. class ModuleSourceFileLocationMap; /// A unit that allows grouping of modules by a package name. /// /// PackageUnit is treated as an enclosing scope of ModuleDecl. Unlike other /// DeclContext subclasses where a parent context is set in ctor, PackageUnit /// (parent context) is set as a field in ModuleDecl (child context). It also has a /// pointer back to the ModuleDecl, so that it can be used to return the module /// in the existing DeclContext lookup functions, which assume ModuleDecl as /// the top level context. Since both PackageUnit and ModuleDecl are created /// in the ASTContext memory arena, i.e. they will be destroyed when the /// ASTContext is destroyed, both pointng to each other is not considered risky. /// /// See \c ModuleDecl class PackageUnit: public DeclContext { /// Identifies this package and used for the equality check Identifier PackageName; /// Non-null reference to ModuleDecl that points to this package. /// Instead of having multiple ModuleDecls pointing to one PackageUnit, we /// create one PackageUnit per ModuleDecl, to make it easier to look up the /// module pointing to this package context, which is needed in the existing /// DeclContext look up functions. /// \see DeclContext::getModuleScopeContext /// \see DeclContext::getParentModule ModuleDecl &SourceModule; PackageUnit(Identifier name, ModuleDecl &src) : DeclContext(DeclContextKind::Package, nullptr), PackageName(name), SourceModule(src) {} public: static PackageUnit *create(Identifier name, ModuleDecl &src, ASTContext &ctx) { return new (ctx) PackageUnit(name, src); } static bool classof(const DeclContext *DC) { return DC->getContextKind() == DeclContextKind::Package; } static bool classof(const PackageUnit *PU) { return true; } Identifier getName() const { return PackageName; } ModuleDecl &getSourceModule() { return SourceModule; } /// Equality check via package name instead of pointer comparison. /// Returns false if the name is empty. bool isSamePackageAs(PackageUnit *other) { return !(getName().empty()) && getName() == other->getName(); } }; /// The minimum unit of compilation. /// /// A module is made up of several file-units, which are all part of the same /// output binary and logical module (such as a single library or executable). /// /// \sa FileUnit class ModuleDecl : public DeclContext, public TypeDecl, public ASTAllocated<ModuleDecl> { friend class DirectOperatorLookupRequest; friend class DirectPrecedenceGroupLookupRequest; /// The ABI name of the module, if it differs from the module name. mutable Identifier ModuleABIName; /// A package this module belongs to. It's set as a property instead of a /// parent decl context; otherwise it will break the existing decl context /// lookup functions that assume ModuleDecl as the top level context. PackageUnit *Package = nullptr; /// Module name to use when referenced in clients module interfaces. mutable Identifier ExportAsName; public: /// Produces the components of a given module's full name in reverse order. /// /// For a Swift module, this will only ever have one component, but an /// imported Clang module might actually be a submodule. /// /// *Note: see `StringRef operator*()` for details on the returned name for printing /// for a Swift module. class ReverseFullNameIterator { public: // Make this look like a valid STL iterator. using difference_type = int; using value_type = StringRef; using pointer = StringRef *; using reference = StringRef; using iterator_category = std::forward_iterator_tag; private: PointerUnion<const ModuleDecl *, const /* clang::Module */ void *> current; public: ReverseFullNameIterator() = default; explicit ReverseFullNameIterator(const ModuleDecl *M); explicit ReverseFullNameIterator(const clang::Module *clangModule) { current = clangModule; } /// Returns the name of the current module. /// Note that for a Swift module, it returns the current module's real (binary) name, /// which can be different from the name if module aliasing was used (see `-module-alias`). StringRef operator*() const; ReverseFullNameIterator &operator++(); friend bool operator==(ReverseFullNameIterator left, ReverseFullNameIterator right) { return left.current == right.current; } friend bool operator!=(ReverseFullNameIterator left, ReverseFullNameIterator right) { return !(left == right); } /// This is a convenience function that writes the entire name, in forward /// order, to \p out. /// /// It calls `StringRef operator*()` under the hood (see for more detail on the /// returned name for a Swift module). void printForward(raw_ostream &out, StringRef delim = ".") const; }; private: /// If non-NULL, a plug-in that should be used when performing external /// lookups. // FIXME: Do we really need to bloat all modules with this? DebuggerClient *DebugClient = nullptr; SmallVector<FileUnit *, 2> Files; /// Mapping used to find the source file associated with a given source /// location. ModuleSourceFileLocationMap *sourceFileLocationMap = nullptr; /// The set of auxiliary source files build as part of this module. SmallVector<SourceFile *, 2> AuxiliaryFiles; llvm::SmallDenseMap<Identifier, SmallVector<OverlayFile *, 1>> declaredCrossImports; llvm::DenseMap<Identifier, SmallVector<Decl *, 2>> ObjCNameLookupCache; /// A description of what should be implicitly imported by each file of this /// module. const ImplicitImportInfo ImportInfo; std::unique_ptr<SourceLookupCache> Cache; SourceLookupCache &getSourceLookupCache() const; /// Tracks the file that will generate the module's entry point, either /// because it contains a class marked with \@UIApplicationMain /// or \@NSApplicationMain, or because it is a script file. class EntryPointInfoTy { enum class Flags { DiagnosedMultipleMainClasses = 1 << 0, DiagnosedMainClassWithScript = 1 << 1 }; llvm::PointerIntPair<FileUnit *, 2, OptionSet<Flags>> storage; public: EntryPointInfoTy() = default; FileUnit *getEntryPointFile() const; void setEntryPointFile(FileUnit *file); bool hasEntryPoint() const; bool markDiagnosedMultipleMainClasses(); bool markDiagnosedMainClassWithScript(); }; /// Information about the file responsible for the module's entry point, /// if any. /// /// \see EntryPointInfoTy EntryPointInfoTy EntryPointInfo; AccessNotesFile accessNotes; /// Used by the debugger to bypass resilient access to fields. bool BypassResilience = false; ModuleDecl(Identifier name, ASTContext &ctx, ImplicitImportInfo importInfo); public: /// Creates a new module with a given \p name. /// /// \param importInfo Information about which modules should be implicitly /// imported by each file of this module. static ModuleDecl * create(Identifier name, ASTContext &ctx, ImplicitImportInfo importInfo = ImplicitImportInfo()) { return new (ctx) ModuleDecl(name, ctx, importInfo); } static ModuleDecl *createMainModule(ASTContext &ctx, Identifier name, ImplicitImportInfo iinfo) { auto *Mod = ModuleDecl::create(name, ctx, iinfo); Mod->Bits.ModuleDecl.IsMainModule = true; return Mod; } using Decl::getASTContext; /// Retrieves information about which modules are implicitly imported by /// each file of this module. const ImplicitImportInfo &getImplicitImportInfo() const { return ImportInfo; } /// Retrieve a list of modules that each file of this module implicitly /// imports. ImplicitImportList getImplicitImports() const; AccessNotesFile &getAccessNotes() { return accessNotes; } const AccessNotesFile &getAccessNotes() const { return accessNotes; } /// Return whether the module was imported with resilience disabled. The /// debugger does this to access private fields. bool getBypassResilience() const { return BypassResilience; } /// Only to be called by MemoryBufferSerializedModuleLoader. void setBypassResilience() { BypassResilience = true; } ArrayRef<FileUnit *> getFiles() { assert(!Files.empty() || failedToLoad()); return Files; } ArrayRef<const FileUnit *> getFiles() const { return { Files.begin(), Files.size() }; } /// Add the given file to this module. /// /// FIXME: Remove this function from public view. Modules never need to add /// files once they are created. /// /// \warning There are very few safe points to call this function once a /// \c ModuleDecl has been created. If you find yourself needing to insert /// a file in the middle of e.g. semantic analysis, use a \c /// SynthesizedFileUnit instead. void addFile(FileUnit &newFile); /// Add an auxiliary source file, introduced as part of the translation. void addAuxiliaryFile(SourceFile &sourceFile); /// Produces the source file that contains the given source location, or /// \c nullptr if the source location isn't in this module. SourceFile *getSourceFileContainingLocation(SourceLoc loc); // Retrieve the buffer ID and source location of the outermost location that // caused the generation of the buffer containing \p loc. \p loc and its // buffer if it isn't in a generated buffer or has no original location. std::pair<unsigned, SourceLoc> getOriginalLocation(SourceLoc loc) const; /// Creates a map from \c #filePath strings to corresponding \c #fileID /// strings, diagnosing any conflicts. /// /// A given \c #filePath string always maps to exactly one \c #fileID string, /// but it is possible for \c #sourceLocation directives to introduce /// duplicates in the opposite direction. If there are such conflicts, this /// method will diagnose the conflict and choose a "winner" among the paths /// in a reproducible way. The \c bool paired with the \c #fileID string is /// \c true for paths which did not have a conflict or won a conflict, and /// \c false for paths which lost a conflict. Thus, if you want to generate a /// reverse mapping, you should drop or special-case the \c #fileID strings /// that are paired with \c false. llvm::StringMap<std::pair<std::string, /*isWinner=*/bool>> computeFileIDMap(bool shouldDiagnose) const; /// Add a file declaring a cross-import overlay. void addCrossImportOverlayFile(StringRef file); /// Collect cross-import overlay names from a given YAML file path. static llvm::SmallSetVector<Identifier, 4> collectCrossImportOverlay(ASTContext &ctx, StringRef file, StringRef moduleName, StringRef& bystandingModule); /// If this method returns \c false, the module does not declare any /// cross-import overlays. /// /// This is a quick check you can use to bail out of expensive logic early; /// however, a \c true return doesn't guarantee that the module declares /// cross-import overlays--it only means that it \em might declare some. /// /// (Specifically, this method checks if the module loader found any /// swiftoverlay files, but does not load the files to see if they list any /// overlay modules.) bool mightDeclareCrossImportOverlays() const; /// Append to \p overlayNames the names of all modules that this module /// declares should be imported when \p bystanderName is imported. /// /// This operation is asymmetric: you will get different results if you /// reverse the positions of the two modules involved in the cross-import. void findDeclaredCrossImportOverlays( Identifier bystanderName, SmallVectorImpl<Identifier> &overlayNames, SourceLoc diagLoc) const; /// Get the list of all modules this module declares a cross-import with. void getDeclaredCrossImportBystanders( SmallVectorImpl<Identifier> &bystanderNames); /// Retrieve the ABI name of the module, which is used for metadata and /// mangling. Identifier getABIName() const; /// Set the ABI name of the module; void setABIName(Identifier name) { ModuleABIName = name; } /// Get the package name of this module /// FIXME: remove this and bump module version rdar://104723918 Identifier getPackageName() const { if (auto pkg = getPackage()) return pkg->getName(); return Identifier(); } /// Get the package associated with this module PackageUnit *getPackage() const { return Package; } /// Set the package this module is associated with /// FIXME: rename this with setPackage(name) rdar://104723918 void setPackageName(Identifier name); Identifier getExportAsName() const { return ExportAsName; } void setExportAsName(Identifier name) { ExportAsName = name; } /// Retrieve the actual module name of an alias used for this module (if any). /// /// For example, if '-module-alias Foo=Bar' is passed in when building the main module, /// and this module is (a) not the main module and (b) is named Foo, then it returns /// the real (physically on-disk) module name Bar. /// /// If no module aliasing is set, it will return getName(), i.e. Foo. Identifier getRealName() const; /// User-defined module version number. llvm::VersionTuple UserModuleVersion; void setUserModuleVersion(llvm::VersionTuple UserVer) { UserModuleVersion = UserVer; } llvm::VersionTuple getUserModuleVersion() const { return UserModuleVersion; } void addAllowableClientName(Identifier name) { allowableClientNames.push_back(name); } ArrayRef<Identifier> getAllowableClientNames() const { return allowableClientNames; } bool allowImportedBy(ModuleDecl *importer) const; private: /// An array of module names that are allowed to import this one. /// Any module can import this one if empty. std::vector<Identifier> allowableClientNames; /// A cache of this module's underlying module and required bystander if it's /// an underscored cross-import overlay. llvm::Optional<std::pair<ModuleDecl *, Identifier>> declaringModuleAndBystander; /// If this module is an underscored cross import overlay, gets the underlying /// module that declared it (which may itself be a cross-import overlay), /// along with the name of the required bystander module. Used by tooling to /// present overlays as if they were part of their underlying module. std::pair<ModuleDecl *, Identifier> getDeclaringModuleAndBystander(); /// Update the source-file location map to make it current. void updateSourceFileLocationMap(); public: /// If this is a traditional (non-cross-import) overlay, get its underlying /// module if one exists. ModuleDecl *getUnderlyingModuleIfOverlay() const; /// Returns true if this module is an underscored cross import overlay /// declared by \p other or its underlying clang module, either directly or /// transitively (via intermediate cross-import overlays - for cross-imports /// involving more than two modules). bool isCrossImportOverlayOf(ModuleDecl *other); /// If this module is an underscored cross-import overlay, returns the /// non-underscored underlying module that declares it as an overlay, either /// directly or transitively (via intermediate cross-import overlays - for /// cross-imports involving more than two modules). ModuleDecl *getDeclaringModuleIfCrossImportOverlay(); /// If this module is an underscored cross-import overlay of \p declaring or /// its underlying clang module, either directly or transitively, populates /// \p bystanderNames with the set of bystander modules that must be present /// alongside \p declaring for the overlay to be imported and returns true. /// Returns false otherwise. bool getRequiredBystandersIfCrossImportOverlay( ModuleDecl *declaring, SmallVectorImpl<Identifier> &bystanderNames); /// Walks and loads the declared, underscored cross-import overlays of this /// module and its underlying clang module, transitively, to find all cross /// import overlays this module underlies. /// /// This is used by tooling to present these overlays as part of this module. void findDeclaredCrossImportOverlaysTransitive( SmallVectorImpl<ModuleDecl *> &overlays); /// Convenience accessor for clients that know what kind of file they're /// dealing with. SourceFile &getMainSourceFile() const; /// Convenience accessor for clients that know what kind of file they're /// dealing with. FileUnit &getMainFile(FileUnitKind expectedKind) const; DebuggerClient *getDebugClient() const { return DebugClient; } void setDebugClient(DebuggerClient *R) { assert(!DebugClient && "Debugger client already set"); DebugClient = R; } /// Returns true if this module is compiled as static library. bool isStaticLibrary() const { return Bits.ModuleDecl.StaticLibrary; } void setStaticLibrary(bool isStatic = true) { Bits.ModuleDecl.StaticLibrary = isStatic; } /// Returns true if this module was or is being compiled for testing. bool isTestingEnabled() const { return Bits.ModuleDecl.TestingEnabled; } void setTestingEnabled(bool enabled = true) { Bits.ModuleDecl.TestingEnabled = enabled; } // Returns true if this module is compiled with implicit dynamic. bool isImplicitDynamicEnabled() const { return Bits.ModuleDecl.ImplicitDynamicEnabled; } void setImplicitDynamicEnabled(bool enabled = true) { Bits.ModuleDecl.ImplicitDynamicEnabled = enabled; } /// Returns true if this module was or is begin compile with /// `-enable-private-imports`. bool arePrivateImportsEnabled() const { return Bits.ModuleDecl.PrivateImportsEnabled; } void setPrivateImportsEnabled(bool enabled = true) { Bits.ModuleDecl.PrivateImportsEnabled = true; } /// Returns true if there was an error trying to load this module. bool failedToLoad() const { return Bits.ModuleDecl.FailedToLoad; } void setFailedToLoad(bool failed = true) { Bits.ModuleDecl.FailedToLoad = failed; } bool hasResolvedImports() const { return Bits.ModuleDecl.HasResolvedImports; } void setHasResolvedImports() { Bits.ModuleDecl.HasResolvedImports = true; } ResilienceStrategy getResilienceStrategy() const { return ResilienceStrategy(Bits.ModuleDecl.RawResilienceStrategy); } void setResilienceStrategy(ResilienceStrategy strategy) { Bits.ModuleDecl.RawResilienceStrategy = unsigned(strategy); } /// Distribution level of the module. LibraryLevel getLibraryLevel() const; /// Returns true if this module was or is being compiled for testing. bool hasIncrementalInfo() const { return Bits.ModuleDecl.HasIncrementalInfo; } void setHasIncrementalInfo(bool enabled = true) { Bits.ModuleDecl.HasIncrementalInfo = enabled; } /// Returns true if this module was built with /// -experimental-hermetic-seal-at-link. bool hasHermeticSealAtLink() const { return Bits.ModuleDecl.HasHermeticSealAtLink; } void setHasHermeticSealAtLink(bool enabled = true) { Bits.ModuleDecl.HasHermeticSealAtLink = enabled; } /// Returns true if this module was built with C++ interoperability enabled. bool hasCxxInteroperability() const { return Bits.ModuleDecl.HasCxxInteroperability; } void setHasCxxInteroperability(bool enabled = true) { Bits.ModuleDecl.HasCxxInteroperability = enabled; } /// \returns true if this module is a system module; note that the StdLib is /// considered a system module. bool isSystemModule() const { return Bits.ModuleDecl.IsSystemModule; } void setIsSystemModule(bool flag = true); /// \returns true if this module is part of the stdlib or contained within /// the SDK. If no SDK was specified, falls back to whether the module was /// specified as a system module (ie. it's on the system search path). bool isNonUserModule() const; public: /// Returns true if the module was rebuilt from a module interface instead /// of being built from the full source. bool isBuiltFromInterface() const { return Bits.ModuleDecl.IsBuiltFromInterface; } void setIsBuiltFromInterface(bool flag = true) { Bits.ModuleDecl.IsBuiltFromInterface = flag; } /// Returns true if this module is a non-Swift module that was imported into /// Swift. /// /// Right now that's just Clang modules. bool isNonSwiftModule() const { return Bits.ModuleDecl.IsNonSwiftModule; } /// \see #isNonSwiftModule void setIsNonSwiftModule(bool flag = true) { Bits.ModuleDecl.IsNonSwiftModule = flag; } bool isMainModule() const { return Bits.ModuleDecl.IsMainModule; } /// Whether this module has been compiled with comprehensive checking for /// concurrency, e.g., Sendable checking. bool isConcurrencyChecked() const { return Bits.ModuleDecl.IsConcurrencyChecked; } void setIsConcurrencyChecked(bool value = true) { Bits.ModuleDecl.IsConcurrencyChecked = value; } bool isObjCNameLookupCachePopulated() const { return Bits.ModuleDecl.ObjCNameLookupCachePopulated; } void setIsObjCNameLookupCachePopulated(bool value) { Bits.ModuleDecl.ObjCNameLookupCachePopulated = value; } /// For the main module, retrieves the list of primary source files being /// compiled, that is, the files we're generating code for. ArrayRef<SourceFile *> getPrimarySourceFiles() const; /// Retrieve the top-level module. If this module is already top-level, this /// returns itself. If this is a submodule such as \c Foo.Bar.Baz, this /// returns the module \c Foo. ModuleDecl *getTopLevelModule(bool overlay = false); bool isResilient() const { return getResilienceStrategy() != ResilienceStrategy::Default; } /// Look up a (possibly overloaded) value set at top-level scope /// (but with the specified access path, which may come from an import decl) /// within the current module. /// /// This does a simple local lookup, not recursively looking through imports. void lookupValue(DeclName Name, NLKind LookupKind, OptionSet<ModuleLookupFlags> Flags, SmallVectorImpl<ValueDecl*> &Result) const; /// Look up a (possibly overloaded) value set at top-level scope /// (but with the specified access path, which may come from an import decl) /// within the current module. /// /// This does a simple local lookup, not recursively looking through imports. void lookupValue(DeclName Name, NLKind LookupKind, SmallVectorImpl<ValueDecl*> &Result) const { lookupValue(Name, LookupKind, {}, Result); } /// Look up a local type declaration by its mangled name. /// /// This does a simple local lookup, not recursively looking through imports. TypeDecl *lookupLocalType(StringRef MangledName) const; /// Look up an opaque return type by the mangled name of the declaration /// that defines it. OpaqueTypeDecl *lookupOpaqueResultType(StringRef MangledName); /// Find ValueDecls in the module and pass them to the given consumer object. /// /// This does a simple local lookup, not recursively looking through imports. void lookupVisibleDecls(ImportPath::Access AccessPath, VisibleDeclConsumer &Consumer, NLKind LookupKind) const; private: void populateObjCNameLookupCache(); public: /// Finds top-levels decls of this module by @objc provided name. /// Decls that have no @objc attribute are not considered. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. /// /// \param Results Vector collecting the decls. /// /// \param name The @objc simple name to look for. Declarations with matching /// name and "anonymous" @objc attribute, as well a matching named @objc /// attribute will be added to Results. void lookupTopLevelDeclsByObjCName(SmallVectorImpl<Decl *> &Results, DeclName name); /// This is a hack for 'main' file parsing and the integrated REPL. /// /// FIXME: Refactor main file parsing to not pump the parser incrementally. /// FIXME: Remove the integrated REPL. void clearLookupCache(); /// Finds all class members defined in this module. /// /// This does a simple local lookup, not recursively looking through imports. void lookupClassMembers(ImportPath::Access accessPath, VisibleDeclConsumer &consumer) const; /// Finds class members defined in this module with the given name. /// /// This does a simple local lookup, not recursively looking through imports. void lookupClassMember(ImportPath::Access accessPath, DeclName name, SmallVectorImpl<ValueDecl*> &results) const; /// Look for the conformance of the given type to the given protocol. /// /// This routine determines whether the given \c type conforms to the given /// \c protocol. /// /// \param type The type for which we are computing conformance. /// /// \param protocol The protocol to which we are computing conformance. /// /// \param allowMissing When \c true, the resulting conformance reference /// might include "missing" conformances, which are synthesized for some /// protocols as an error recovery mechanism. /// /// \returns The result of the conformance search, which will be /// None if the type does not conform to the protocol or contain a /// ProtocolConformanceRef if it does conform. ProtocolConformanceRef lookupConformance(Type type, ProtocolDecl *protocol, bool allowMissing = false); /// Look for the conformance of the given existential type to the given /// protocol. ProtocolConformanceRef lookupExistentialConformance(Type type, ProtocolDecl *protocol); /// Exposes TypeChecker functionality for querying protocol conformance. /// Returns a valid ProtocolConformanceRef only if all conditional /// requirements are successfully resolved. ProtocolConformanceRef conformsToProtocol(Type sourceTy, ProtocolDecl *targetProtocol); /// Find a member named \p name in \p container that was declared in this /// module. /// /// \p container may be \c this for a top-level lookup. /// /// If \p privateDiscriminator is non-empty, only matching private decls are /// returned; otherwise, only non-private decls are returned. void lookupMember(SmallVectorImpl<ValueDecl*> &results, DeclContext *container, DeclName name, Identifier privateDiscriminator) const; /// Find all Objective-C methods with the given selector. void lookupObjCMethods( ObjCSelector selector, SmallVectorImpl<AbstractFunctionDecl *> &results) const; /// Find all SPI names imported from \p importedModule by this module, /// collecting the identifiers in \p spiGroups. void lookupImportedSPIGroups( const ModuleDecl *importedModule, llvm::SmallSetVector<Identifier, 4> &spiGroups) const; // Is \p attr accessible as an explicitly imported SPI from this module? bool isImportedAsSPI(const SpecializeAttr *attr, const ValueDecl *targetDecl) const; // Is \p spiGroup accessible as an explicitly imported SPI from this module? bool isImportedAsSPI(Identifier spiGroup, const ModuleDecl *fromModule) const; /// Is \p module imported as \c @_weakLinked from this module? bool isImportedAsWeakLinked(const ModuleDecl *module) const; /// \sa getImportedModules enum class ImportFilterKind { /// Include imports declared with `@_exported`. Exported = 1 << 0, /// Include "regular" imports with an access-level of `public`. Default = 1 << 1, /// Include imports declared with `@_implementationOnly`. ImplementationOnly = 1 << 2, /// Include imports declared with `package import`. PackageOnly = 1 << 3, /// Include imports marked `internal` or lower. These differs form /// implementation-only imports by stricter type-checking and loading /// policies. At this moment, we can group them under the same category /// as they have the same loading behavior. InternalOrBelow = 1 << 4, /// Include imports declared with `@_spiOnly`. SPIOnly = 1 << 5, /// Include imports shadowed by a cross-import overlay. Unshadowed imports /// are included whether or not this flag is specified. ShadowedByCrossImportOverlay = 1 << 6 }; /// \sa getImportedModules using ImportFilter = OptionSet<ImportFilterKind>; /// Returns an \c ImportFilter with all elements of \c ImportFilterKind. constexpr static ImportFilter getImportFilterAll() { return {ImportFilterKind::Exported, ImportFilterKind::Default, ImportFilterKind::ImplementationOnly, ImportFilterKind::PackageOnly, ImportFilterKind::InternalOrBelow, ImportFilterKind::SPIOnly, ImportFilterKind::ShadowedByCrossImportOverlay}; } /// Import kinds visible to the module declaring them. /// /// This leaves out \c ShadowedByCrossImportOverlay as even if present in /// the sources it's superseded by the cross-overlay as the local import. constexpr static ImportFilter getImportFilterLocal() { return {ImportFilterKind::Exported, ImportFilterKind::Default, ImportFilterKind::ImplementationOnly, ImportFilterKind::PackageOnly, ImportFilterKind::InternalOrBelow, ImportFilterKind::SPIOnly}; } /// Looks up which modules are imported by this module. /// /// \p filter controls whether public, private, or any imports are included /// in this list. void getImportedModules(SmallVectorImpl<ImportedModule> &imports, ImportFilter filter = ImportFilterKind::Exported) const; /// Lists modules that are not imported from a file and used in API. void getMissingImportedModules(SmallVectorImpl<ImportedModule> &imports) const; /// Looks up which modules are imported by this module, ignoring any that /// won't contain top-level decls. /// /// This is a performance hack. Do not use for anything but name lookup. /// May go away in the future. void getImportedModulesForLookup(SmallVectorImpl<ImportedModule> &imports) const; /// Has \p module been imported via an '@_implementationOnly' import /// instead of another kind of import? /// /// This assumes that \p module was imported. bool isImportedImplementationOnly(const ModuleDecl *module) const; /// Returns true if decl context or its content can be serialized by /// cross-module-optimization. /// The \p ctxt can e.g. be a NominalType or the context of a function. bool canBeUsedForCrossModuleOptimization(DeclContext *ctxt) const; /// Finds all top-level decls of this module. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. void getTopLevelDecls(SmallVectorImpl<Decl*> &Results) const; void getExportedPrespecializations(SmallVectorImpl<Decl *> &results) const; /// Finds top-level decls of this module filtered by their attributes. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. /// /// \param Results Vector collecting the decls. /// /// \param matchAttributes Check on the attributes of a decl to /// filter which decls to fully deserialize. Only decls with accepted /// attributes are deserialized and added to Results. void getTopLevelDeclsWhereAttributesMatch( SmallVectorImpl<Decl*> &Results, llvm::function_ref<bool(DeclAttributes)> matchAttributes) const; /// Finds all local type decls of this module. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. void getLocalTypeDecls(SmallVectorImpl<TypeDecl*> &Results) const; /// Finds all operator decls of this module. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. void getOperatorDecls(SmallVectorImpl<OperatorDecl *> &results) const; /// Finds all precedence group decls of this module. /// /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. void getPrecedenceGroups(SmallVectorImpl<PrecedenceGroupDecl*> &Results) const; /// Determines whether this module should be recursed into when calling /// \c getDisplayDecls. /// /// Some modules should not call \c getDisplayDecls, due to assertions /// in their implementation. These are usually implicit imports that would be /// recursed into for parsed modules. This function provides a guard against /// recusing into modules that should not have decls collected. bool shouldCollectDisplayDecls() const; /// Finds all top-level decls that should be displayed to a client of this /// module. /// /// This includes types, variables, functions, and extensions. /// This does a simple local lookup, not recursively looking through imports. /// The order of the results is not guaranteed to be meaningful. /// /// This can differ from \c getTopLevelDecls, e.g. it returns decls from a /// shadowed clang module. It does not force synthesized top-level decls that /// should be printed to be added; use \c swift::getTopLevelDeclsForDisplay() /// for that. void getDisplayDecls(SmallVectorImpl<Decl*> &results, bool recursive = false) const; using LinkLibraryCallback = llvm::function_ref<void(LinkLibrary)>; /// Generate the list of libraries needed to link this module, based on its /// imports. void collectLinkLibraries(LinkLibraryCallback callback) const; /// Get the path for the file that this module came from, or an empty /// string if this is not applicable. StringRef getModuleFilename() const; /// Get the path to the file defining this module, what we consider the /// source of truth about the module. Usually a swiftinterface file for a /// resilient module, a swiftmodule for a non-resilient module, or the /// modulemap for a clang module. Returns an empty string if not applicable. StringRef getModuleSourceFilename() const; /// Get the path to the file loaded by the compiler. Usually the binary /// swiftmodule file or a pcm in the cache. Returns an empty string if not /// applicable. StringRef getModuleLoadedFilename() const; /// \returns true if this module is the "swift" standard library module. bool isStdlibModule() const; /// \returns true if this module has standard substitutions for mangling. bool hasStandardSubstitutions() const; /// \returns true if this module is the "SwiftShims" module; bool isSwiftShimsModule() const; /// \returns true if this module is the "builtin" module. bool isBuiltinModule() const; /// \returns true if this module is the "SwiftOnoneSupport" module; bool isOnoneSupportModule() const; /// \returns true if this module is the "Foundation" module; bool isFoundationModule() const; /// \returns true if traversal was aborted, false otherwise. bool walk(ASTWalker &Walker); /// Register the file responsible for generating this module's entry point. /// /// \returns true if there was a problem adding this file. bool registerEntryPointFile(FileUnit *file, SourceLoc diagLoc, llvm::Optional<ArtificialMainKind> kind); /// \returns true if this module has a main entry point. bool hasEntryPoint() const { return EntryPointInfo.hasEntryPoint(); } NominalTypeDecl *getMainTypeDecl() const; /// Returns the associated clang module if one exists. const clang::Module *findUnderlyingClangModule() const; /// Does this module or the underlying clang module defines export_as with /// a value corresponding to the \p other module? bool isExportedAs(const ModuleDecl *other) const; /// Returns a generator with the components of this module's full, /// hierarchical name. /// /// For a Swift module, this will only ever have one component, but an /// imported Clang module might actually be a submodule. /// /// *Note: see `StringRef operator*()` for details on the returned name for printing /// for a Swift module. ReverseFullNameIterator getReverseFullModuleName() const { return ReverseFullNameIterator(this); } /// Calls \p callback for each source file of the module. void collectBasicSourceFileInfo( llvm::function_ref<void(const BasicSourceFileInfo &)> callback) const; void collectSerializedSearchPath( llvm::function_ref<void(StringRef)> callback) const; /// Retrieve a fingerprint value that summarizes the contents of this module. /// /// This interface hash a of a module is guaranteed to change if the interface /// hash of any of its (primary) source files changes. For example, when /// building incrementally, the interface hash of this module will change when /// the primaries contributing to its content changes. In contrast, when /// a module is deserialized, the hash of every source file contributes to /// the module's interface hash. It therefore serves as an effective, if /// coarse-grained, way of determining when top-level changes to a module's /// contents have been made. Fingerprint getFingerprint() const; /// Returns an approximation of whether the given module could be /// redistributed and consumed by external clients. /// /// FIXME: The scope of this computation should be limited entirely to /// RenamedDeclRequest. Unfortunately, it has been co-opted to support the /// \c SerializeOptionsForDebugging hack. Once this information can be /// transferred from module files to the dSYMs, remove this. bool isExternallyConsumed() const; SWIFT_DEBUG_DUMPER(dumpDisplayDecls()); SWIFT_DEBUG_DUMPER(dumpTopLevelDecls()); SourceRange getSourceRange() const { return SourceRange(); } static bool classof(const DeclContext *DC) { if (auto D = DC->getAsDecl()) return classof(D); return false; } static bool classof(const Decl *D) { return D->getKind() == DeclKind::Module; } using ASTAllocated<ModuleDecl>::operator new; using ASTAllocated<ModuleDecl>::operator delete; }; /// Wraps either a swift module or a clang one. /// FIXME: Should go away once swift modules can support submodules natively. class ModuleEntity { llvm::PointerUnion<const ModuleDecl *, const /* clang::Module */ void *> Mod; public: ModuleEntity() = default; ModuleEntity(const ModuleDecl *Mod) : Mod(Mod) {} ModuleEntity(const clang::Module *Mod) : Mod(static_cast<const void *>(Mod)){} /// @param useRealNameIfAliased Whether to use the module's real name in case /// module aliasing is used. For example, if a file /// has `import Foo` and `-module-alias Foo=Bar` is /// passed, treat Foo as an alias and Bar as the real /// module name as its dependency. This only applies /// to Swift modules. /// @return The module name; for Swift modules, the real module name could be /// different from the name if module aliasing is used. StringRef getName(bool useRealNameIfAliased = false) const; /// For Swift modules, it returns the same result as \c ModuleEntity::getName(bool). /// For Clang modules, it returns the result of \c clang::Module::getFullModuleName. std::string getFullName(bool useRealNameIfAliased = false) const; bool isSystemModule() const; bool isNonUserModule() const; bool isBuiltinModule() const; const ModuleDecl *getAsSwiftModule() const; const clang::Module *getAsClangModule() const; void *getOpaqueValue() const { assert(!Mod.isNull()); return Mod.getOpaqueValue(); } explicit operator bool() const { return !Mod.isNull(); } }; inline bool DeclContext::isModuleContext() const { if (auto D = getAsDecl()) return ModuleDecl::classof(D); return false; } inline bool DeclContext::isModuleScopeContext() const { if (ParentAndKind.getInt() == ASTHierarchy::FileUnit) return true; return isModuleContext(); } inline bool DeclContext::isPackageContext() const { return ParentAndKind.getInt() == ASTHierarchy::Package; } /// Extract the source location from the given module declaration. inline SourceLoc extractNearestSourceLoc(const ModuleDecl *mod) { return extractNearestSourceLoc(static_cast<const Decl *>(mod)); } /// Collects modules that this module imports via `@_exported import`. void collectParsedExportedImports(const ModuleDecl *M, SmallPtrSetImpl<ModuleDecl *> &Imports, llvm::SmallDenseMap<ModuleDecl *, SmallPtrSet<Decl *, 4>, 4> &QualifiedImports, llvm::function_ref<bool(AttributedImport<ImportedModule>)> includeImport = nullptr); } // end namespace swift #endif
ff04e22ba42aae20689efa5148dfc4fd7f1291a6
870dc87ffdfa7d939d760afb8eb4163fbc981525
/src/FrameBufferUserFrameHandler.cpp
e8afb8a4dd9c831e78c3bd072865576020adb625
[]
no_license
spierepf/HDLC
4abfbc89c8a1ae92ed6444c6fa9aab333fe4b45d
d52b3147ca9e01baee9fec2eaca4337480cc946a
refs/heads/master
2021-01-10T03:40:08.224102
2017-08-26T13:52:32
2017-08-26T13:52:32
52,214,747
2
0
null
null
null
null
UTF-8
C++
false
false
660
cpp
FrameBufferUserFrameHandler.cpp
/* * FrameBufferUserFrameHandler.cpp * * Created on: Sep 28, 2015 * Author: peter */ #include "FrameBufferUserFrameHandler.h" namespace hdlc { FrameBufferUserFrameHandler::FrameBufferUserFrameHandler(FrameBuffer& frameBuffer) : frameBuffer(frameBuffer) { // TODO Auto-generated constructor stub } FrameBufferUserFrameHandler::~FrameBufferUserFrameHandler() { // TODO Auto-generated destructor stub } void FrameBufferUserFrameHandler::handle(const uint8_t header, const uint8_t* payload, const uint8_t payloadSize) { for(int i = 0; i < payloadSize; i++) { frameBuffer.put(payload[i]); } frameBuffer.endFrame(); } } /* namespace hdlc */
40ebe9e2add01b3558de0c97080ff08b879e6fd7
ca312d55f55a07ace869fdec3508f440539109d5
/offline/packages/trackreco/ResidualOutlierFinder.h
bdfbd27a3d0e19503565c0f7261f97849e1398d4
[]
no_license
rccorliss/coresoftware
8d0cef3d2d0e9b4337e04ce992771ec60941eaab
79f380a1058390a7d353c034d326fa30d44ef892
refs/heads/master
2023-08-03T15:57:28.415262
2022-05-07T17:46:51
2022-05-07T17:46:51
149,708,452
0
1
null
2018-09-21T04:09:02
2018-09-21T04:09:02
null
UTF-8
C++
false
false
2,233
h
ResidualOutlierFinder.h
#include <Acts/Definitions/Units.hpp> #include <Acts/EventData/MultiTrajectory.hpp> #include <Acts/EventData/Measurement.hpp> #include <Acts/EventData/MeasurementHelpers.hpp> #include <trackbase/ActsTrackingGeometry.h> #include <trackbase/TrkrDefs.h> #include <trackbase/ActsSurfaceMaps.h> struct ResidualOutlierFinder { int verbosity = 0; std::map<long unsigned int, float> chi2Cuts; bool operator()(Acts::MultiTrajectory::ConstTrackStateProxy state) const { // can't determine an outlier w/o a measurement or predicted parameters if (!state.hasCalibrated() || !state.hasPredicted()) { return false; } const auto predicted = state.predicted(); const auto predictedCovariance = state.predictedCovariance(); double chi2 = std::numeric_limits<float>::max(); Acts::visit_measurement(state.calibrated(), state.calibratedCovariance(), state.calibratedSize(), [&](const auto calibrated, const auto calibratedCovariance) { constexpr size_t kMeasurementSize = decltype(calibrated)::RowsAtCompileTime; using ParametersVector = Acts::ActsVector<kMeasurementSize>; const auto H = state.projector().template topLeftCorner<kMeasurementSize, Acts::eBoundSize>().eval(); ParametersVector res; res = calibrated - H * predicted; chi2 = (res.transpose() * ((calibratedCovariance + H * predictedCovariance * H.transpose())).inverse() * res).eval()(0,0); }); /// end lambda and call to visit meas if(verbosity > 2) { const auto distance = (state.calibrated() - state.projector() * state.predicted()).norm(); std::cout << "Measurement has distance, chi2 " << distance << ", " << chi2 << std::endl; } auto volume = state.referenceSurface().geometryId().volume(); auto layer = state.referenceSurface().geometryId().layer(); bool outlier = false; float chi2cut = chi2Cuts.find(volume)->second; if(chi2 > chi2cut) { outlier = true; } if(verbosity > 2) { std::cout << "Meas vol id and layer " << volume << ", " << layer << " and chi2cut " << chi2cut << " so returning outlier : " << outlier << std::endl; } return outlier; } };
6c265128ef9ab2547f3ff0640aed3ccb53d3c2a5
d2924692c708bde0716dad0066ed7c93acb1f342
/branches/natan/brkga/genetic_algorithm.h
6e31876ab4000c40e183c208b29fadedb317a890
[]
no_license
jimmyliu86/pifro
119bdc8f4d61c65b0e5df73caf7fba422fecf1ed
7c723322dc0ee16a4836c501a49f3285acaf6436
refs/heads/master
2016-09-05T11:56:04.009643
2013-02-08T04:06:09
2013-02-08T04:06:09
33,106,602
0
0
null
null
null
null
ISO-8859-1
C++
false
false
1,410
h
genetic_algorithm.h
// Copyright 2011 Universidade Federal de Minas Gerais // Autor: Luiz Gustavo Sathler Dias // Projeto Orientado em Computação 2] // Definição da classe Algoritmo genético. #ifndef BRKGA_GENETICA_H_ #define BRKGA_GENETICA_H_ #include <vector> #include "./instance.h" typedef struct Chromosome { std::vector<Request> gen; double cost; }Chromosome; class GeneticAlgorithm { public: GeneticAlgorithm(int population_size, int size_of_setA, int size_of_setB, int size_of_setC, float prob_crossover, std::vector<Request>& request); ~GeneticAlgorithm(); void InitializePopulation(); void SortRequest(); void SortPopulation(); void UpdateCrossoverPopulation(); void Crossover(); void Crossover2(); void GenerateMutation(); void SaveBestIndividual(); void CalculateFitness(); void PrintToFile(float time); double Execute(); private: std::vector<Chromosome> population_; std::vector<Chromosome> cross_pop_; Chromosome best_individual_; int size_setA_; int size_setB_; int size_setC_; int population_size_; float prob_crossover_; std::vector<Request> original_; }; #endif // BRKGA_GENETICA_H_
c0b023ee79c2384580d5c6141fd0fd3762fd4f0d
9ddf037a658881221494c0278007e5e5ba8cf6e6
/RomanAddition/include/RomanAddition.hpp
a71707c27a47c1b4f25efa75603c1893a2a469ed
[]
no_license
boryssmejda/SPOJ
82d9a71ff81900e6234ec0584711384700887526
48b5be3e50327dc61a93a33a9a36ad3ac5934fad
refs/heads/master
2021-11-11T07:33:42.139837
2021-10-23T13:28:10
2021-10-23T13:28:10
178,557,461
0
0
null
null
null
null
UTF-8
C++
false
false
1,398
hpp
RomanAddition.hpp
#include <vector> #include <map> #include <iostream> #include <string> #include <utility> #include <array> #include <algorithm> class RomanNumber { private: struct number { std::string roman; int decimal; number(std::string s, int n): roman{s}, decimal{n}{} }; const std::array<number, 13> m_dictionary = { number(std::string("I") , 1), number(std::string("IV"), 4), number(std::string("V"), 5), number(std::string("IX"), 9), number(std::string("X"), 10), number(std::string("XL"), 40), number(std::string("L"), 50), number(std::string("XC"), 90), number(std::string("C"), 100), number(std::string("CD"), 400), number(std::string("D"), 500), number(std::string("CM"), 900), number(std::string("M"), 1000) }; int m_decimalForm; std::string m_romanNumber; std::string convertCurrentDigitToRoman(int num); std::pair<std::string, int> findRomanNumberNotBiggerThanCurrent(int number); protected: int toDecimal(); bool isCorrectRomanNumber(); std::string toRoman(); public: RomanNumber(std::string roman); RomanNumber(int decimal); RomanNumber() : m_decimalForm{ 0 }, m_romanNumber{ "" }{} RomanNumber& operator = (const RomanNumber& r); friend std::istream & operator >> (std::istream& in, RomanNumber& r); friend std::ostream& operator << (std::ostream& out, RomanNumber& r); friend RomanNumber operator + (RomanNumber l, RomanNumber r); };
e6b319a1fffff5bc929e8939d64f639cf6653324
094c3dfe368d9ea913391095aa5d2d8d55908162
/c++/qt/lines/lines.cpp
7c891681ccbe79c185787180ae312becd69852ce
[ "Apache-2.0" ]
permissive
tuxdna/sourcecode
443389f8b631c89d4f195ef1adc0c102f2054e2b
48001a01bb54db19a5bf170e887b7ce6b2d7019e
refs/heads/master
2021-01-01T18:37:26.731223
2014-02-12T15:52:40
2014-02-12T15:52:40
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,699
cpp
lines.cpp
#include "lines.h" #include <QApplication> #include <QPainter> Lines::Lines(QWidget *parent) : QWidget(parent) { } void Lines::paintEvent(QPaintEvent *event) { QPen pen(Qt::black, Qt::SolidLine); QPainter painter(this); painter.setPen(pen); painter.drawLine(20,40,250,40); pen.setStyle(Qt::DashLine); painter.setPen(pen); painter.drawLine(20,80,250,80); pen.setStyle(Qt::DashDotLine); painter.setPen(pen); painter.drawLine(20,120,250,120); pen.setStyle(Qt::DotLine); painter.setPen(pen); painter.drawLine(20,160,250,160); pen.setStyle(Qt::DashDotLine); painter.setPen(pen); painter.drawLine(20, 200, 250, 200); QVector<qreal> dashes; qreal space = 4; dashes << 1 << space << 5 << space; pen.setStyle(Qt::CustomDashLine); pen.setDashPattern(dashes); painter.setPen(pen); painter.drawLine(20, 240, 250, 240); painter.setPen(QColor("#d4d4d4")); painter.setBrush(QBrush("#c56c00")); painter.drawRect(10, 15, 90, 60); painter.setBrush(QBrush("#1ac500")); painter.drawRect(130, 15, 90, 60); painter.setBrush(QBrush("#539e47")); painter.drawRect(250, 15, 90, 60); painter.setBrush(QBrush("#004fc5")); painter.drawRect(10, 105, 90, 60); painter.setBrush(QBrush("#c50024")); painter.drawRect(130, 105, 90, 60); painter.setBrush(QBrush("#9e4757")); painter.drawRect(250, 105, 90, 60); painter.setBrush(QBrush("#5f3b00")); painter.drawRect(10, 195, 90, 60); painter.setBrush(QBrush("#4c4c4c")); painter.drawRect(130, 195, 90, 60); painter.setBrush(QBrush("#785f36")); painter.drawRect(250, 195, 90, 60); painter.setPen(Qt::NoPen); painter.setBrush(Qt::HorPattern); painter.drawRect(350+10, 15, 350+90, 60); painter.setBrush(Qt::VerPattern); painter.drawRect(350+130, 15, 350+90, 60); painter.setBrush(Qt::CrossPattern); painter.drawRect(350+250, 15, 350+90, 60); painter.setBrush(Qt::Dense7Pattern); painter.drawRect(350+10, 105, 350+90, 60); painter.setBrush(Qt::Dense6Pattern); painter.drawRect(350+130, 105, 350+90, 60); painter.setBrush(Qt::Dense5Pattern); painter.drawRect(350+250, 105, 350+90, 60); painter.setBrush(Qt::BDiagPattern); painter.drawRect(350+10, 195, 350+90, 60); painter.setBrush(Qt::FDiagPattern); painter.drawRect(350+130, 195, 350+90, 60); painter.setBrush(Qt::DiagCrossPattern); painter.drawRect(350+250, 195, 350+90, 60); painter.setPen(QPen(QBrush("#535353"), 0.5)); painter.setRenderHint(QPainter::Antialiasing); int h = height(); int w = width(); painter.translate(QPoint(w/2, h/2)); for (qreal rot=0; rot < 360.0; rot+=5.0 ) { painter.drawEllipse(-125, -40, 250, 80); painter.rotate(5.0); } }
91a07d271f045ad50db081c5d218e32def994685
e12264c9052df7d548300af5879e74939aaf834e
/map_gui/mainwindow.cpp
5b8ce4ad5b185b558ac4da0d7559ab6a19832ac1
[]
no_license
jevgienij/sim_map
df0c85c5f731f546c18b5ae3901bd115187f7e27
1cffc0e002394c88ced4b3b75abe0381fa8f62a3
refs/heads/master
2021-01-23T21:38:40.636460
2014-03-11T18:28:25
2014-03-11T18:28:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,587
cpp
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" #include <QInputDialog> #include <vlc-qt/Common.h> #include <vlc-qt/Instance.h> #include <vlc-qt/Media.h> #include <vlc-qt/MediaPlayer.h> SimMapWindow::SimMapWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::SimMapWindow), _media(0) { // setup GUI ui->setupUi(this); // setup video transmission _instance = new VlcInstance(VlcCommon::args(), this); _player = new VlcMediaPlayer(_instance); _player->setVideoWidget(ui->video); ui->video->setMediaPlayer(_player); connect(ui->setStreamUrl, SIGNAL(clicked()), this, SLOT(openMjpegUrl())); // setup data receive via ai_socket QObject::connect(&l, SIGNAL(dataAvailable(XXX_MAPGUI_STRUCT)), ui->mapWidget, SLOT(receiveData(XXX_MAPGUI_STRUCT))); } SimMapWindow::~SimMapWindow() { delete _player; delete _media; delete _instance; delete ui; } void SimMapWindow::openMjpegUrl() { QString url = QInputDialog::getText(this, tr("Set URL"), tr("Enter the stream URL you want to play"), QLineEdit::Normal, tr("http://127.0.0.1:8080")); if (url.isEmpty()) return; _media = new VlcMedia(url, _instance); _player->open(_media); } void SimMapWindow::resizeEvent(QResizeEvent *event) { QWidget::resizeEvent(event); adjustScrollBar(ui->scrollArea->verticalScrollBar()); adjustScrollBar(ui->scrollArea->horizontalScrollBar()); repaint(); } void SimMapWindow::adjustScrollBar(QScrollBar *scrollBar) { scrollBar->setValue((scrollBar->minimum() + scrollBar->maximum())/2); }
d816d985d21f618d2cc5d97b5891973e608ef097
76664ce6e64e7b79e1da0bc41bbb301505d992ef
/libraries/chain/apply_context.cpp
d1ccdbfc9d169d9dcf0bd6f32629a8ab0413d0be
[ "MIT", "BSL-1.0", "Apache-2.0", "BSD-2-Clause", "LLVM-exception", "BSD-3-Clause" ]
permissive
Laighno/evt
4b6fe18fdc4cc93b92b7bc4c27381a9ea5c784d7
90b94e831aebb62c6ad19ce59c9089e9f51cfd77
refs/heads/master
2021-06-02T07:47:34.222603
2019-05-18T07:11:16
2019-05-18T07:11:16
136,871,065
0
0
MIT
2018-06-11T03:41:41
2018-06-11T03:41:41
null
UTF-8
C++
false
false
3,275
cpp
apply_context.cpp
/** * @file * @copyright defined in evt/LICENSE.txt */ #include <evt/chain/apply_context.hpp> #include <algorithm> #include <evt/chain/controller.hpp> #include <evt/chain/execution_context_impl.hpp> #include <evt/chain/transaction_context.hpp> #include <evt/chain/global_property_object.hpp> #include <evt/chain/contracts/evt_contract.hpp> namespace evt { namespace chain { static inline void print_debug(const action_trace& ar) { if(!ar.console.empty()) { auto prefix = fc::format_string( "\n[${n}, ${d}-${k}]", fc::mutable_variant_object() ("n", ar.act.name) ("d", ar.act.domain) ("k", ar.act.key)); dlog(prefix + ": CONSOLE OUTPUT BEGIN =====================\n" + ar.console + prefix + ": CONSOLE OUTPUT END =====================" ); } } void apply_context::exec_one(action_trace& trace) { using namespace contracts; auto start = std::chrono::steady_clock::now(); auto r = action_receipt(); r.act_digest = digest_type::hash(act); r.global_sequence = next_global_sequence(); trace.trx_id = trx_context.trx_meta->id; trace.block_num = control.pending_block_state()->block_num; trace.block_time = control.pending_block_time(); trace.producer_block_id = control.pending_producer_block_id(); trace.act = act; try { try { if(act.index_ == -1) { act.index_ = exec_ctx.index_of(act.name); } if(act.index_ == exec_ctx.index_of<contracts::paybonus>()) { goto next; } exec_ctx.invoke<apply_action, void>(act.index_, *this); } FC_RETHROW_EXCEPTIONS(warn, "pending console output: ${console}", ("console", fmt::to_string(_pending_console_output))); } catch(fc::exception& e) { trace.receipt = r; // fill with known data trace.except = e; finalize_trace(trace, start); throw; } next: trace.receipt = r; trx_context.executed.emplace_back(move(r)); finalize_trace(trace, start); if(control.contracts_console()) { print_debug(trace); } } void apply_context::finalize_trace(action_trace& trace, const std::chrono::steady_clock::time_point& start) { using namespace std::chrono; trace.console = fmt::to_string(_pending_console_output); trace.elapsed = fc::microseconds(duration_cast<microseconds>(steady_clock::now() - start).count()); trace.generated_actions = std::move(_generated_actions); trace.new_ft_holders = std::move(_new_ft_holders); } void apply_context::exec(action_trace& trace) { exec_one(trace); } bool apply_context::has_authorized(const domain_name& domain, const domain_key& key) const { return act.domain == domain && act.key == key; } uint64_t apply_context::next_global_sequence() { const auto& p = control.get_dynamic_global_properties(); db.modify(p, [&](auto& dgp) { ++dgp.global_action_sequence; }); return p.global_action_sequence; } }} // namespace evt::chain