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
sequencelengths
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
sequencelengths
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
sequencelengths
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
c336ad5ddfea4ebd9a85a629cdf94c9c4a61e99b
421
hpp
C++
src/settingspage.hpp
Chepik/SpaceInvaders1
8547cfaaa33d7ccddd8c58391d92dd97864d9e5f
[ "MIT" ]
null
null
null
src/settingspage.hpp
Chepik/SpaceInvaders1
8547cfaaa33d7ccddd8c58391d92dd97864d9e5f
[ "MIT" ]
null
null
null
src/settingspage.hpp
Chepik/SpaceInvaders1
8547cfaaa33d7ccddd8c58391d92dd97864d9e5f
[ "MIT" ]
null
null
null
#pragma once #include <QWidget> #include <string> namespace Ui { class SettingsPage; } class SettingsPage : public QWidget { Q_OBJECT public: explicit SettingsPage(QWidget *parent = 0); ~SettingsPage(); private slots: void on_menuButton_clicked(); /// /// It stores setting data into a file. /// void on_saveButton_clicked(); signals: void moveToMenuPage(); private: Ui::SettingsPage *ui; };
12.757576
45
0.695962
Chepik
c337a0816a0f36567cbccc2405a833339cfd7830
11,150
cpp
C++
Enclave/src/enclave_forward.cpp
yy738686337/sgx_project_v2
20a8db8a2aecac0aead50e00d3f8515c46b9af9a
[ "Apache-2.0" ]
null
null
null
Enclave/src/enclave_forward.cpp
yy738686337/sgx_project_v2
20a8db8a2aecac0aead50e00d3f8515c46b9af9a
[ "Apache-2.0" ]
null
null
null
Enclave/src/enclave_forward.cpp
yy738686337/sgx_project_v2
20a8db8a2aecac0aead50e00d3f8515c46b9af9a
[ "Apache-2.0" ]
null
null
null
#include "enclave.h" extern "C" { #include "ecall_batchnorm_layer.h" } #include "types.h" // void ecall_gemm(int TA, int TB, int M, int N, int K, float ALPHA, // float *A, int lda, // float *B, int ldb, // float BETA, // float *C, int ldc, int a_size, int b_size, int c_size) { // crypt_aux((unsigned char*)pass, pass_len, (unsigned char*)B, 4, b_size); // //rc4_crypt("lizheng", 7, C, c_size); // gemm(TA, TB, M, N, K, ALPHA, A, lda, B, ldb, BETA, C, ldc); // crypt_aux((unsigned char*)pass, pass_len, (unsigned char*)C, 4, c_size); // } void ecall_avgpool_forward(int batch, int c, int fig_size, float *input, int input_len, float *output, int output_len) { crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float), input_len); int b, k, i; for (b = 0; b < batch; ++b) { for (k = 0; k < c; ++k) { int out_index = k + b * c; output[out_index] = 0; for (i = 0; i < fig_size; ++i) { int in_index = i + fig_size * (k + b * c); output[out_index] += input[in_index]; } output[out_index] /= fig_size; } } crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float), output_len); } void ecall_forward_connected_layer(int TA, int TB, int batch, int outputs, int inputs, int batch_normalize, int train, float *rolling_mean, float *rolling_variance, float *scales, float *x, float *x_norm, float *input, int lda, float *weights, int ldb, float *output, int ldc, long a_size, long b_size, long c_size, float *biases, float *mean, float *variance, ACTIVATION a) { int M = batch; int K = inputs; int N = outputs; crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * inputs, batch); #ifdef DNNL dnnl_transfer_layer_data data; data.batch = batch; data.input = input; data.ic = inputs; data.oc = outputs; data.output = output; data.biases = biases; data.weights = weights; run_dnnl_function(dnnl_connected_forward, &data); #else gemm(0, 1, M, N, K, 1, input, K, weights, K, 1, output, N); add_bias(output, biases, batch, outputs, 1); #endif if (batch_normalize) { forward_batchnorm_layer(CONNECTED, train, outputs, batch, outputs, 1, 1, output, input, mean, rolling_mean, variance, rolling_variance, x, x_norm, scales); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x, sizeof(float) * N, batch); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x_norm, sizeof(float) * N, batch); } // add_bias(output, biases, batch, outputs, 1); activate_array(output, c_size, a); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float) * N, batch); } void ecall_forward_maxpool_layer(int pad, int raw_h, int raw_w, int out_h, int out_w, int c, int batch, int size, int stride, float *input, int input_len, float *output, int out_len, int *indices) { crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * raw_h * raw_w * c, batch); int b, i, j, k, m, n; // 初始偏移设定为四周补0长度的负值 int w_offset = -pad; int h_offset = -pad; // 获取当前层的输出尺寸 int h = out_h; int w = out_w; // 获取当前层输入图像的通道数,为什么是输入通道数?不应该为输出通道数吗?实际二者没有区别,对于最大池化层来说,输入有多少通道,输出就有多少通道! // 遍历batch中每一张输入图片,计算得到与每一张输入图片具有相同通道数的输出图 for (b = 0; b < batch; ++b) { // 对于每张输入图片,将得到通道数一样的输出图,以输出图为基准,按输出图通道,行,列依次遍历 // (这对应图像在output的存储方式,每张图片按行铺排成一大行,然后图片与图片之间再并成一行)。 // 以输出图为基准进行遍历,最终循环的总次数刚好覆盖池化核在输入图片不同位置进行池化操作。 for (k = 0; k < c; ++k) { for (i = 0; i < h; ++i) { for (j = 0; j < w; ++j) { // out_index为输出图中的索引:out_index = b * c * w * h + k * w * h + h * w + w,展开写可能更为清晰些 int out_index = j + w * (i + h * (k + c * b)); float max = -FLT_MAX; // FLT_MAX为c语言中float.h定义的对大浮点数,此处初始化最大元素值为最小浮点数 int max_i = -1; // 最大元素值的索引初始化为-1 // 下面两个循环回到了输入图片,计算得到的cur_h以及cur_w都是在当前层所有输入元素的索引,内外循环的目的是找寻输入图像中, // 以(h_offset + i*l.stride, w_offset + j*l.stride)为左上起点,尺寸为l.size池化区域中的最大元素值max及其在所有输入元素中的索引max_i for (n = 0; n < size; ++n) { for (m = 0; m < size; ++m) { // cur_h,cur_w是在所有输入图像中第k通道中的cur_h行与cur_w列,index是在所有输入图像元素中的总索引。 // 为什么这里少一层对输入通道数的遍历循环呢?因为对于最大池化层来说输入与输出通道数是一样的,并在上面的通道数循环了! int cur_h = h_offset + i * stride + n; int cur_w = w_offset + j * stride + m; int index = raw_w * (cur_h + raw_h * (k + b * c)) + cur_w; // 边界检查:正常情况下,是不会越界的,但是如果有补0操作,就会越界了,这里的处理方式是直接让这些元素值为-FLT_MAX // (注意虽然称之为补0操作,但实际不是补0),总之,这些补的元素永远不会充当最大元素值。 int valid = (cur_h >= 0 && cur_h < raw_h && cur_w >= 0 && cur_w < raw_w); float val = (valid != 0) ? input[index] : -FLT_MAX; // 记录这个池化区域中的最大的元素值及其在所有输入元素中的总索引 max_i = (val > max) ? index : max_i; max = (val > max) ? val : max; } } // 由此得到最大池化层每一个输出元素值及其在所有输入元素中的总索引。 // 为什么需要记录每个输出元素值对应在输入元素中的总索引呢?因为在下面的反向过程中需要用到,在计算当前最大池化层上一层网络的敏感度时, // 需要该索引明确当前层的每个元素究竟是取上一层输出(也即上前层输入)的哪一个元素的值,具体见下面backward_maxpool_layer()函数的注释。 output[out_index] = max; indices[out_index] = max_i; } } } } crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float) * out_h * out_w * c, batch); } void ecall_forward_convolutional_layer(int batch, int ic, int h, int w, int size, int stride, int pad, int n_filters, int out_h, int out_w, float *weights, int weight_len, float *input, int in_len, float *output, int out_len, float *biases, int bias_len, int batch_normalize, int train, int outputs, float *rolling_mean, float *rolling_variance, float *scales, float *x, float *x_norm, float *mean, float *variance, ACTIVATION activation) { int i; int m = n_filters; // 该层卷积核个数 int k = size * size * ic; // 该层每个卷积核的参数元素个数 int n = out_h * out_w; // 该层每个特征图的尺寸(元素个数) int fig_size = h * ic * w; crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * fig_size, batch); #ifdef DNNL dnnl_transfer_layer_data data = {}; data.batch = batch; data.h = h; data.w = w; data.ic = ic; data.oc = m; data.out_h = out_h; data.out_w = out_w; data.pad = pad; data.stride = stride; data.size = size; data.input = input; data.weights = weights; data.biases = biases; data.output = output; run_dnnl_function(dnnl_conv_forward, &data); #else float *a = weights; // 所有卷积核(也即权重),元素个数为l.n*l.c*l.size*l.size,按行存储,共有l*n行,l.c*l.size*l.size列 float *b = (float *)calloc(out_h * out_w * size * size * ic, sizeof(float)); float *c = output; // 存储一张输入图片(多通道)所有的输出特征图(输入图片是多通道的,输出图片也是多通道的,有多少个卷积核就有多少个通道,每个卷积核得到一张特征图即为一个通道) for (i = 0; i < batch; ++i) { im2col_cpu(input, ic, h, w, size, stride, pad, b); gemm(0, 0, m, n, k, 1, a, k, b, n, 1, c, n); c += n * m; input += ic * h * w; } if (batch_normalize) { forward_batchnorm_layer(CONNECTED, train, outputs, batch, m, out_h, out_w, output, input, mean, rolling_mean, variance, rolling_variance, x, x_norm, scales); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x, sizeof(float) * outputs, batch); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)x_norm, sizeof(float) * outputs, batch); } add_bias(output, biases, batch, n_filters, out_h * out_w); #endif activate_array(output, m * n * batch, activation); crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)output, sizeof(float) * n * m, batch); } void ecall_forward_cost_layer(COST_TYPE cost_type, int batch, int in_len, float *input, size_t input_size, float *truth, float *delta, float *output, float *cost) { crypt_aux((uint8_t *)pass, pass_len, (uint8_t *)input, sizeof(float) * in_len, batch); crypt_aux((uint8_t *)pass, pass_len, (uint8_t *)truth, sizeof(float) * 1, batch); if (cost_type == SMOOTH) { smooth_l1_cpu(input_size, input, truth, delta, output); } else if (cost_type == L1) { l1_cpu(input_size, input, truth, delta, output); } else if (cost_type == CE) { ce_forward(batch, in_len, input, truth, delta, output); } else { l2_cpu(input_size, input, truth, delta, output); } cost[0] = sum_array(output, input_size); } void ecall_forward_dropout_layer(int train, size_t batch, size_t inputs, float probability, float scale, size_t, float *rand, float *input) { crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * inputs, batch); int i; // 如果当前网络不是处于训练阶段而处于测试阶段,则直接返回(使用inverted dropout带来的方便) if (!train) return; // 遍历dropout层的每一个输入元素(包含整个batch的),按照指定的概率l.probability置为0或者按l.scale缩放 for (i = 0; i < batch * inputs; ++i) { // 产生一个0~1之间均匀分布的随机数 float r = rand_uniform(0, 1); // 每个输入元素都对应一个随机数,保存在l.rand中 rand[i] = r; // 如果r小于l.probability(l.probability是舍弃概率),则舍弃该输入元素,注意,舍弃并不是删除, // 而是将其值置为0,所以输入元素个数总数没变(因故输出元素个数l.outputs等于l.inputs) if (r < probability) input[i] = 0; // 否则保留该输入元素,并乘以比例因子 else input[i] *= scale; } crypt_aux((unsigned char *)pass, pass_len, (unsigned char *)input, sizeof(float) * inputs, batch); }
39.964158
139
0.530314
yy738686337
c33aa15e40f13b90ecbc39f24e23d934fd8e17db
1,817
cpp
C++
Source code/Game/Source files/Graphics/Texture.cpp
Ansoulom/cat-rush
e99b18d7bf7b72f0e4918f0cc24a190dd55747e6
[ "MIT" ]
null
null
null
Source code/Game/Source files/Graphics/Texture.cpp
Ansoulom/cat-rush
e99b18d7bf7b72f0e4918f0cc24a190dd55747e6
[ "MIT" ]
null
null
null
Source code/Game/Source files/Graphics/Texture.cpp
Ansoulom/cat-rush
e99b18d7bf7b72f0e4918f0cc24a190dd55747e6
[ "MIT" ]
null
null
null
#include "Texture.h" #include "Game_core.h" #include <SDL_image.h> #include <SDL_ttf.h> #include "Colors.h" namespace Game { namespace Graphics { Texture::Texture(Renderer& renderer, const std::filesystem::path& file_path) : Texture{ std::unique_ptr<SDL_Surface, Sdl_deleter>{IMG_Load(file_path.string().c_str()), Sdl_deleter{}}, renderer } { } Texture::Texture(Renderer& renderer, const std::string& text, Color text_color, const Text::Font& font) : Texture{ std::unique_ptr<SDL_Surface, Sdl_deleter>{ TTF_RenderText_Blended( &Wrappers::Sdl_wrapper::get_font(font), text.c_str(), Wrappers::Sdl_wrapper::get_color(text_color)), Sdl_deleter{} }, renderer } { } Texture::Texture(Texture&& other) noexcept : texture_{move(other.texture_)}, width_{other.width_}, height_{other.height_} { } Texture& Texture::operator=(Texture&& other) noexcept { texture_ = move(other.texture_); width_ = other.width_; height_ = other.height_; return *this; } Texture::Texture(std::unique_ptr<SDL_Surface, Sdl_deleter> surface, Renderer& renderer) : texture_{}, width_{0}, height_{0} { if(!surface) { throw std::runtime_error{std::string{"Could not create surface: "} + SDL_GetError()}; } texture_ = std::unique_ptr<SDL_Texture, Sdl_deleter>{ SDL_CreateTextureFromSurface(renderer.sdl_renderer_.get(), surface.get()), Sdl_deleter{} }; if(!texture_) { throw std::runtime_error{std::string{"Could not create texture from surface: "} + SDL_GetError()}; } SDL_SetTextureBlendMode(texture_.get(), SDL_BLENDMODE_BLEND); width_ = surface->w; height_ = surface->h; } int Texture::width() const { return width_; } int Texture::height() const { return height_; } } }
23
105
0.672537
Ansoulom
c33da97875df8f8a499fb3c743b29be6118380bc
2,950
cpp
C++
lib/Error.cpp
OMAS-IIIF/cserve
8932ed36fa6f1935b3db97ed556f876e2e459c4b
[ "MIT" ]
1
2021-06-24T06:10:07.000Z
2021-06-24T06:10:07.000Z
lib/Error.cpp
OMAS-IIIF/cserve
8932ed36fa6f1935b3db97ed556f876e2e459c4b
[ "MIT" ]
null
null
null
lib/Error.cpp
OMAS-IIIF/cserve
8932ed36fa6f1935b3db97ed556f876e2e459c4b
[ "MIT" ]
null
null
null
/* * Copyright © 2016 Lukas Rosenthaler, Andrea Bianco, Benjamin Geer, * Ivan Subotic, Tobias Schweizer, André Kilchenmann, and André Fatton. * This file is part of Sipi. * Sipi is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as published * by the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * Sipi 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. * Additional permission under GNU AGPL version 3 section 7: * If you modify this Program, or any covered work, by linking or combining * it with Kakadu (or a modified version of that library) or Adobe ICC Color * Profiles (or a modified version of that library) or both, containing parts * covered by the terms of the Kakadu Software Licence or Adobe Software Licence, * or both, the licensors of this Program grant you additional permission * to convey the resulting work. * See the GNU Affero General Public License for more details. * You should have received a copy of the GNU Affero General Public * License along with Sipi. If not, see <http://www.gnu.org/licenses/>. */ #include <cstring> // std::strerror #include <sstream> // std::ostringstream #include "Error.h" namespace cserve { Error::Error(const char *file_p, const int line_p, const char *msg, int errno_p) : runtime_error( std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line(line_p), file(file_p), message(msg), sysErrno(errno_p) { } //============================================================================ Error::Error(const char *file_p, const int line_p, const std::string &msg, int errno_p) : runtime_error( std::string(msg) + "\nFile: " + std::string(file_p) + std::string(" Line: ") + std::to_string(line_p)), line(line_p), file(file_p), message(msg), sysErrno(errno_p) { } //============================================================================ std::string Error::to_string(void) const { std::ostringstream err_stream; err_stream << "Error at [" << file << ": " << line << "]"; if (sysErrno != 0) err_stream << " (system error: " << std::strerror(sysErrno) << ")"; err_stream << ": " << message; return err_stream.str(); } //============================================================================ std::ostream &operator<<(std::ostream &out_stream, const Error &rhs) { std::string errStr = rhs.to_string(); out_stream << errStr; return out_stream; } //============================================================================ }
42.753623
108
0.581695
OMAS-IIIF
c3400e35727d8d10b38cbfff47efe2051869ec33
22,148
cpp
C++
Engine/source/platformX86UNIX.alt/x86UNIXWindow.client.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
46
2015-01-05T17:34:43.000Z
2022-01-04T04:03:09.000Z
Engine/source/platformX86UNIX.alt/x86UNIXWindow.client.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
10
2015-01-20T23:14:46.000Z
2019-04-05T22:04:15.000Z
Engine/source/platformX86UNIX.alt/x86UNIXWindow.client.cpp
fr1tz/terminal-overload
85f0689a40022e5eb7e54dcb6ddfb5ddd82a0a60
[ "CC-BY-4.0" ]
9
2015-08-08T18:46:06.000Z
2021-02-01T13:53:20.000Z
// Copyright information can be found in the file named COPYING // located in the root directory of this distribution. #include "windowManager/x11/x11WindowMgr.h" #include "console/console.h" #include "core/stream/fileStream.h" //#include "game/resource.h" //#include "game/version.h" #include "math/mRandom.h" #include "platformX86UNIX/platformX86UNIX.h" #include "platformX86UNIX/x86UNIXStdConsole.h" #include "platform/input/event.h" //#include "platform/gameInterface.h" #include "platform/platform.h" //#include "platform/platformAL.h" #include "platform/platformInput.h" //#include "platform/platformVideo.h" #include "platform/profiler.h" //#include "platformX86UNIX/platformGL.h" //#include "platformX86UNIX/x86UNIXOGLVideo.h" #include "platformX86UNIX/x86UNIXState.h" #ifndef TORQUE_DEDICATED #include "platformX86UNIX/x86UNIXMessageBox.h" #include "platformX86UNIX/x86UNIXInputManager.h" #endif #include <errno.h> #include <signal.h> #include <stdlib.h> #include <unistd.h> // fork, execvp, chdir #include <time.h> // nanosleep #ifndef TORQUE_DEDICATED #include <X11/Xlib.h> #include <X11/Xos.h> #include <SDL/SDL.h> #include <SDL/SDL_syswm.h> #include <SDL/SDL_version.h> #endif static x86UNIXPlatformState _x86UNIXState_Obj; x86UNIXPlatformState *x86UNIXState = &_x86UNIXState_Obj; bool DisplayPtrManager::sgDisplayLocked = false; LockFunc_t DisplayPtrManager::sgLockFunc = NULL; LockFunc_t DisplayPtrManager::sgUnlockFunc = NULL; static U32 lastTimeTick; static MRandomLCG sgPlatRandom; #ifndef TORQUE_DEDICATED extern void InstallRedBookDevices(); extern void PollRedbookDevices(); extern bool InitOpenGL(); // This is called when some X client sends // a selection event (e.g. SelectionRequest) // to the window extern void NotifySelectionEvent(XEvent& event); #endif //------------------------------------------------------------------------------ static S32 ParseCommandLine(S32 argc, const char **argv, Vector<char*>& newCommandLine) { x86UNIXState->setExePathName(argv[0]); bool foundDedicated = false; for ( int i=0; i < argc; i++ ) { // look for platform specific args if (dStrcmp(argv[i], "-version") == 0) { dPrintf("%s (built on %s)\n", getVersionString(), getCompileTimeString()); dPrintf("gcc: %s\n", __VERSION__); return 1; } if (dStrcmp(argv[i], "-cdaudio") == 0) { x86UNIXState->setCDAudioEnabled(true); continue; } if (dStrcmp(argv[i], "-dedicated") == 0) { foundDedicated = true; // no continue because dedicated is also handled by script } if (dStrcmp(argv[i], "-dsleep") == 0) { x86UNIXState->setDSleep(true); continue; } if (dStrcmp(argv[i], "-nohomedir") == 0) { x86UNIXState->setUseRedirect(false); continue; } if (dStrcmp(argv[i], "-chdir") == 0) { if ( ++i >= argc ) { dPrintf("Follow -chdir option with the desired working directory.\n"); return 1; } if (chdir(argv[i]) == -1) { dPrintf("Unable to chdir to %s: %s\n", argv[i], strerror(errno)); return 1; } continue; } // copy the arg into newCommandLine int argLen = dStrlen(argv[i]) + 1; char* argBuf = new char[argLen]; // this memory is deleted in main() dStrncpy(argBuf, argv[i], argLen); newCommandLine.push_back(argBuf); } x86UNIXState->setDedicated(foundDedicated); #if defined(TORQUE_DEDICATED) && !defined(TORQUE_ENGINE) if (!foundDedicated) { dPrintf("This is a dedicated server build. You must supply the -dedicated command line parameter.\n"); return 1; } #endif return 0; } int XLocalErrorHandler(Display* display, XErrorEvent* error) { char errorBuffer[4096]; XGetErrorText(display, error->error_code, errorBuffer, sizeof(errorBuffer)); Con::printf(errorBuffer); AssertFatal(0, "X Error"); } void InitWindowingSystem() { #ifndef TORQUE_DEDICATED if( !x86UNIXState->isXWindowsRunning() ) { Display* dpy = XOpenDisplay(NULL); AssertFatal(dpy, "Failed to connect to X Server"); if (dpy != NULL) { x86UNIXState->setXWindowsRunning(true); x86UNIXState->setDisplayPointer(dpy); XSetErrorHandler(XLocalErrorHandler); } } #endif } //------------------------------------------------------------------------------ static void InitWindow(const Point2I &initialSize, const char *name) { x86UNIXState->setWindowSize(initialSize); x86UNIXState->setWindowName(name); } #ifndef TORQUE_DEDICATED /* //------------------------------------------------------------------------------ bool InitSDL() { if (SDL_Init(SDL_INIT_VIDEO) != 0) return false; atexit(SDL_Quit); SDL_SysWMinfo sysinfo; SDL_VERSION(&sysinfo.version); if (SDL_GetWMInfo(&sysinfo) == 0) return false; x86UNIXState->setDisplayPointer(sysinfo.info.x11.display); DisplayPtrManager::setDisplayLockFunction(sysinfo.info.x11.lock_func); DisplayPtrManager::setDisplayUnlockFunction(sysinfo.info.x11.unlock_func); DisplayPtrManager xdisplay; Display* display = xdisplay.getDisplayPointer(); x86UNIXState->setScreenNumber( DefaultScreen( display ) ); x86UNIXState->setScreenPointer( DefaultScreenOfDisplay( display ) ); x86UNIXState->setDesktopSize( (S32) DisplayWidth( display, x86UNIXState->getScreenNumber()), (S32) DisplayHeight( display, x86UNIXState->getScreenNumber()) ); x86UNIXState->setDesktopBpp( (S32) DefaultDepth( display, x86UNIXState->getScreenNumber())); // indicate that we want sys WM messages SDL_EventState(SDL_SYSWMEVENT, SDL_ENABLE); return true; } */ //------------------------------------------------------------------------------ static void ProcessSYSWMEvent(const SDL_Event& event) { XEvent& xevent = event.syswm.msg->event.xevent; //Con::printf("xevent : %d", xevent.type); switch (xevent.type) { case SelectionRequest: // somebody wants our clipboard NotifySelectionEvent(xevent); break; } } //------------------------------------------------------------------------------ static void SetAppState() { U8 state = SDL_GetAppState(); // if we're not active but we have appactive and inputfocus, set window // active and reactivate input if ((!x86UNIXState->windowActive() || !Input::isActive()) && state & SDL_APPACTIVE && state & SDL_APPINPUTFOCUS) { x86UNIXState->setWindowActive(true); Input::deactivate(); Input::activate(); } // if we are active, but we don't have appactive or input focus, // deactivate input (if window not locked) and clear windowActive else if (x86UNIXState->windowActive() && !(state & SDL_APPACTIVE && state & SDL_APPINPUTFOCUS)) { if (x86UNIXState->windowLocked()) Input::deactivate(); x86UNIXState->setWindowActive(false); } } //------------------------------------------------------------------------------ static S32 NumEventsPending() { static const int MaxEvents = 255; static SDL_Event events[MaxEvents]; SDL_PumpEvents(); return SDL_PeepEvents(events, MaxEvents, SDL_PEEKEVENT, SDL_ALLEVENTS); } //------------------------------------------------------------------------------ static void PrintSDLEventQueue() { static const int MaxEvents = 255; static SDL_Event events[MaxEvents]; SDL_PumpEvents(); S32 numEvents = SDL_PeepEvents( events, MaxEvents, SDL_PEEKEVENT, SDL_ALLEVENTS); if (numEvents <= 0) { dPrintf("SDL Event Queue is empty\n"); return; } dPrintf("SDL Event Queue:\n"); for (int i = 0; i < numEvents; ++i) { const char *eventType; switch (events[i].type) { case SDL_NOEVENT: eventType = "SDL_NOEVENT"; break; case SDL_ACTIVEEVENT: eventType = "SDL_ACTIVEEVENT"; break; case SDL_KEYDOWN: eventType = "SDL_KEYDOWN"; break; case SDL_KEYUP: eventType = "SDL_KEYUP"; break; case SDL_MOUSEMOTION: eventType = "SDL_MOUSEMOTION"; break; case SDL_MOUSEBUTTONDOWN: eventType = "SDL_MOUSEBUTTONDOWN"; break; case SDL_MOUSEBUTTONUP: eventType = "SDL_MOUSEBUTTONUP"; break; case SDL_JOYAXISMOTION: eventType = "SDL_JOYAXISMOTION"; break; case SDL_JOYBALLMOTION: eventType = "SDL_JOYBALLMOTION"; break; case SDL_JOYHATMOTION: eventType = "SDL_JOYHATMOTION"; break; case SDL_JOYBUTTONDOWN: eventType = "SDL_JOYBUTTONDOWN"; break; case SDL_JOYBUTTONUP: eventType = "SDL_JOYBUTTONUP"; break; case SDL_QUIT: eventType = "SDL_QUIT"; break; case SDL_SYSWMEVENT: eventType = "SDL_SYSWMEVENT"; break; case SDL_VIDEORESIZE: eventType = "SDL_VIDEORESIZE"; break; case SDL_VIDEOEXPOSE: eventType = "SDL_VIDEOEXPOSE"; break; /* Events SDL_USEREVENT through SDL_MAXEVENTS-1 are for your use */ case SDL_USEREVENT: eventType = "SDL_USEREVENT"; break; default: eventType = "UNKNOWN!"; break; } dPrintf("Event %d: %s\n", i, eventType); } } //------------------------------------------------------------------------------ static bool ProcessMessages() { static const int MaxEvents = 255; static const U32 Mask = SDL_QUITMASK | SDL_VIDEORESIZEMASK | SDL_VIDEOEXPOSEMASK | SDL_ACTIVEEVENTMASK | SDL_SYSWMEVENTMASK | SDL_EVENTMASK(SDL_USEREVENT); static SDL_Event events[MaxEvents]; SDL_PumpEvents(); S32 numEvents = SDL_PeepEvents(events, MaxEvents, SDL_GETEVENT, Mask); if (numEvents == 0) return true; for (int i = 0; i < numEvents; ++i) { SDL_Event& event = events[i]; switch (event.type) { case SDL_QUIT: return false; break; case SDL_VIDEORESIZE: case SDL_VIDEOEXPOSE: //Game->refreshWindow(); break; case SDL_USEREVENT: if (event.user.code == TORQUE_SETVIDEOMODE) { SetAppState(); // SDL will send a motion event to restore the mouse position // on the new window. Ignore that if the window is locked. if (x86UNIXState->windowLocked()) { SDL_Event tempEvent; SDL_PeepEvents(&tempEvent, 1, SDL_GETEVENT, SDL_MOUSEMOTIONMASK); } } break; case SDL_ACTIVEEVENT: SetAppState(); break; case SDL_SYSWMEVENT: ProcessSYSWMEvent(event); break; } } return true; } //------------------------------------------------------------------------------ // send a destroy window event to the window. assumes // window is created. void SendQuitEvent() { SDL_Event quitevent; quitevent.type = SDL_QUIT; SDL_PushEvent(&quitevent); } #endif // TORQUE_DEDICATED //------------------------------------------------------------------------------ static inline void Sleep(int secs, int nanoSecs) { timespec sleeptime; sleeptime.tv_sec = secs; sleeptime.tv_nsec = nanoSecs; nanosleep(&sleeptime, NULL); } #ifndef TORQUE_DEDICATED struct AlertWinState { bool fullScreen; bool cursorHidden; bool inputGrabbed; }; //------------------------------------------------------------------------------ void DisplayErrorAlert(const char* errMsg, bool showSDLError) { char fullErrMsg[2048]; dStrncpy(fullErrMsg, errMsg, sizeof(fullErrMsg)); if (showSDLError) { char* sdlerror = SDL_GetError(); if (sdlerror != NULL && dStrlen(sdlerror) > 0) { dStrcat(fullErrMsg, " (Error: "); dStrcat(fullErrMsg, sdlerror); dStrcat(fullErrMsg, ")"); } } Platform::AlertOK("Error", fullErrMsg); } //------------------------------------------------------------------------------ static inline void AlertDisableVideo(AlertWinState& state) { /* RKO-TODO: Possibly re-implement this functionality? state.fullScreen = Video::isFullScreen(); state.cursorHidden = (SDL_ShowCursor(SDL_QUERY) == SDL_DISABLE); state.inputGrabbed = (SDL_WM_GrabInput(SDL_GRAB_QUERY) == SDL_GRAB_ON); if (state.fullScreen) SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); if (state.cursorHidden) SDL_ShowCursor(SDL_ENABLE); if (state.inputGrabbed) SDL_WM_GrabInput(SDL_GRAB_OFF); */ } //------------------------------------------------------------------------------ static inline void AlertEnableVideo(AlertWinState& state) { /* RKO-TODO: Possibly re-implement this functionality? if (state.fullScreen) SDL_WM_ToggleFullScreen(SDL_GetVideoSurface()); if (state.cursorHidden) SDL_ShowCursor(SDL_DISABLE); if (state.inputGrabbed) SDL_WM_GrabInput(SDL_GRAB_ON); */ } #endif // TORQUE_DEDICATED //------------------------------------------------------------------------------ void Platform::AlertOK(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); mBox.alertOK(windowTitle, message); AlertEnableVideo(state); } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("Alert: %s %s", windowTitle, message); else dPrintf("Alert: %s %s\n", windowTitle, message); } } //------------------------------------------------------------------------------ bool Platform::AlertOKCancel(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); bool val = mBox.alertOKCancel(windowTitle, message) == XMessageBox::OK; AlertEnableVideo(state); return val; } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("Alert: %s %s", windowTitle, message); else dPrintf("Alert: %s %s\n", windowTitle, message); return false; } } //------------------------------------------------------------------------------ bool Platform::AlertRetry(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); bool val = mBox.alertRetryCancel(windowTitle, message) == XMessageBox::Retry; AlertEnableVideo(state); return val; } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("Alert: %s %s", windowTitle, message); else dPrintf("Alert: %s %s\n", windowTitle, message); return false; } } //------------------------------------------------------------------------------ Platform::ALERT_ASSERT_RESULT Platform::AlertAssert(const char *windowTitle, const char *message) { #ifndef TORQUE_DEDICATED if (x86UNIXState->isXWindowsRunning()) { AlertWinState state; AlertDisableVideo(state); DisplayPtrManager xdisplay; XMessageBox mBox(xdisplay.getDisplayPointer()); int val = mBox.alertAssert(windowTitle, message); ALERT_ASSERT_RESULT result = ALERT_ASSERT_IGNORE; switch( val ) { case XMessageBox::OK: result = ALERT_ASSERT_EXIT; break; default: case XMessageBox::Cancel: result = ALERT_ASSERT_IGNORE; break; case XMessageBox::Retry: result = ALERT_ASSERT_DEBUG; break; case XMessageBox::IgnoreAll: result = ALERT_ASSERT_IGNORE_ALL; break; } AlertEnableVideo(state); return result; } else #endif { if (Con::isActive() && StdConsole::isEnabled()) Con::printf("AlertAssert: %s %s", windowTitle, message); else dPrintf("AlertAssert: %s %s\n", windowTitle, message); return ALERT_ASSERT_DEBUG; } } //------------------------------------------------------------------------------ bool Platform::excludeOtherInstances(const char *mutexName) { AssertFatal(0, "Not Implemented"); return false; } //------------------------------------------------------------------------------ void Platform::process() { PROFILE_START(XUX_PlatformProcess); stdConsole->process(); if (x86UNIXState->windowCreated()) { #ifndef TORQUE_DEDICATED // process window events PROFILE_START(XUX_ProcessMessages); bool quit = !ProcessMessages(); PROFILE_END(); if(quit) { // generate a quit event Platform::postQuitMessage(0); } // process input events PROFILE_START(XUX_InputProcess); Input::process(); PROFILE_END(); // poll redbook state PROFILE_START(XUX_PollRedbookDevices); PollRedbookDevices(); PROFILE_END(); // if we're not the foreground window, sleep for 1 ms if (!x86UNIXState->windowActive()) Sleep(0, getBackgroundSleepTime() * 1000000); #endif } else { // no window // sleep for 1 ms // JMQ: since linux's minimum sleep latency seems to be 20ms, this can // increase player pings by 10-20ms in the dedicated server. So // you have to use -dsleep to enable it. the server sleeps anyway when // there are no players connected. // JMQ: recent kernels (such as RH 8.0 2.4.18) reduce the latency // to 2-4 ms on average. /*if (!Game->isJournalReading() && (x86UNIXState->getDSleep() || Con::getIntVariable("Server::PlayerCount") - Con::getIntVariable("Server::BotCount") <= 0)) { PROFILE_START(XUX_Sleep); Sleep(0, getBackgroundSleepTime() * 1000000); PROFILE_END(); }*/ } #ifndef TORQUE_DEDICATED #if 0 // JMQ: disabled this because it may fire mistakenly in some configurations. // sdl's default event handling scheme should be enough. // crude check to make sure that we're not loading up events. the sdl // event queue should never have more than (say) 25 events in it at this // point const int MaxEvents = 25; if (NumEventsPending() > MaxEvents) { PrintSDLEventQueue(); AssertFatal(false, "The SDL event queue has too many events!"); } #endif #endif PROFILE_END(); } //------------------------------------------------------------------------------ // Web browser function: //------------------------------------------------------------------------------ bool Platform::openWebBrowser( const char* webAddress ) { if (!webAddress || dStrlen(webAddress)==0) return false; // look for a browser preference variable // JMQTODO: be nice to implement some UI to customize this const char* webBrowser = Con::getVariable("Pref::Unix::WebBrowser"); if (dStrlen(webBrowser) == 0) webBrowser = NULL; pid_t pid = fork(); if (pid == -1) { Con::printf("WARNING: Platform::openWebBrowser failed to fork"); return false; } else if (pid != 0) { // parent //if (Video::isFullScreen()) // Video::toggleFullScreen(); return true; } else if (pid == 0) { // child // try to exec konqueror, then netscape char* argv[3]; argv[0] = const_cast<char*>(""); argv[1] = const_cast<char*>(webAddress); argv[2] = 0; int ok = -1; // if execvp returns, it means it couldn't execute the program if (webBrowser != NULL) ok = execvp(webBrowser, argv); ok = execvp("konqueror", argv); ok = execvp("mozilla", argv); ok = execvp("netscape", argv); // use dPrintf instead of Con here since we're now in another process, dPrintf("WARNING: Platform::openWebBrowser: couldn't launch a web browser\n"); _exit(-1); return false; } else { Con::printf("WARNING: Platform::openWebBrowser: forking problem"); return false; } } //------------------------------------------------------------------------------ // Login password routines: //------------------------------------------------------------------------------ const char* Platform::getLoginPassword() { Con::printf("WARNING: Platform::getLoginPassword() is unimplemented"); return ""; } //------------------------------------------------------------------------------ bool Platform::setLoginPassword( const char* password ) { Con::printf("WARNING: Platform::setLoginPassword is unimplemented"); return false; } //------------------------------------------------------------------------------ // Silly Korean registry key checker: //------------------------------------------------------------------------------ ConsoleFunction( isKoreanBuild, bool, 1, 1, "isKoreanBuild()" ) { Con::printf("WARNING: isKoreanBuild() is unimplemented"); return false; } bool Platform::displaySplashWindow(String path) { X11WindowManager* mgr = (X11WindowManager*)PlatformWindowManager::get(); return mgr->displaySplashWindow(); } void Platform::closeSplashWindow() { X11WindowManager* mgr = (X11WindowManager*)PlatformWindowManager::get(); return mgr->closeSplashWindow(); } void Platform::openFolder(const char* path ) { AssertFatal(0, "Not Implemented"); } void Platform::openFile(const char* path ) { AssertFatal(0, "Not Implemented"); }
29.530667
109
0.580865
fr1tz
c34cd3a6f09c34be5a627b7d7a66f5c422434241
3,044
hpp
C++
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/frame/frame_init.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
10
2021-03-29T13:52:06.000Z
2022-03-10T02:24:25.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/frame/frame_init.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
1
2019-07-19T02:40:32.000Z
2019-07-19T02:40:32.000Z
Pods/OpenVPNAdapter/Sources/OpenVPN3/openvpn/frame/frame_init.hpp
TiagoPedroByterev/openvpnclient-ios
a9dafb2a481cc72a3e408535fb7f0aba9f5cfa76
[ "MIT" ]
7
2018-07-11T10:37:02.000Z
2019-08-03T10:34:08.000Z
// OpenVPN -- An application to securely tunnel IP networks // over a single port, with support for SSL/TLS-based // session authentication and key exchange, // packet encryption, packet authentication, and // packet compression. // // Copyright (C) 2012-2017 OpenVPN Inc. // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU Affero General Public License Version 3 // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program in the COPYING file. // If not, see <http://www.gnu.org/licenses/>. // Method to generate a Frame object for typical OpenVPN usage #ifndef OPENVPN_FRAME_FRAME_INIT_H #define OPENVPN_FRAME_FRAME_INIT_H #include <algorithm> #include <openvpn/frame/frame.hpp> namespace openvpn { inline Frame::Ptr frame_init(const bool align_adjust_3_1, const size_t tun_mtu, const size_t control_channel_payload, const bool verbose) { const size_t payload = std::max(tun_mtu + 512, size_t(2048)); const size_t headroom = 512; const size_t tailroom = 512; const size_t align_block = 16; const unsigned int buffer_flags = 0; Frame::Ptr frame(new Frame(Frame::Context(headroom, payload, tailroom, 0, align_block, buffer_flags))); if (align_adjust_3_1) { (*frame)[Frame::READ_LINK_TCP] = Frame::Context(headroom, payload, tailroom, 3, align_block, buffer_flags); (*frame)[Frame::READ_LINK_UDP] = Frame::Context(headroom, payload, tailroom, 1, align_block, buffer_flags); } (*frame)[Frame::READ_BIO_MEMQ_STREAM] = Frame::Context(headroom, std::min(control_channel_payload, payload), tailroom, 0, align_block, buffer_flags); (*frame)[Frame::WRITE_SSL_CLEARTEXT] = Frame::Context(headroom, payload, tailroom, 0, align_block, BufferAllocated::GROW); frame->standardize_capacity(~0); if (verbose) OPENVPN_LOG("Frame=" << headroom << '/' << payload << '/' << tailroom << " mssfix-ctrl=" << (*frame)[Frame::READ_BIO_MEMQ_STREAM].payload()); return frame; } inline Frame::Context frame_init_context_simple(const size_t payload) { const size_t headroom = 512; const size_t tailroom = 512; const size_t align_block = 16; const unsigned int buffer_flags = 0; return Frame::Context(headroom, payload, tailroom, 0, align_block, buffer_flags); } inline Frame::Ptr frame_init_simple(const size_t payload) { Frame::Ptr frame = new Frame(frame_init_context_simple(payload)); frame->standardize_capacity(~0); return frame; } } // namespace openvpn #endif // OPENVPN_FRAME_FRAME_INIT_H
37.580247
126
0.698095
TiagoPedroByterev
c34db1d2b727bafb6be96b212497109fe9458ee2
280
cpp
C++
CodeForces/CF742-D2-A.cpp
amraboelkher/CompetitiveProgramming
624ca5c3e5044eae2800d14b3dbb961c85494b85
[ "MIT" ]
2
2017-12-06T01:17:21.000Z
2018-05-02T04:49:44.000Z
CodeForces/CF742-D2-A.cpp
amraboelkher/CompetitiveProgramming
624ca5c3e5044eae2800d14b3dbb961c85494b85
[ "MIT" ]
null
null
null
CodeForces/CF742-D2-A.cpp
amraboelkher/CompetitiveProgramming
624ca5c3e5044eae2800d14b3dbb961c85494b85
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int get(int a , int b){ if(b == 0) return 1; if(b == 1)return a % 10; int x = get(a , b / 2) % 10; x = x * x % 10; if(b & 1) x = (x * a) % 10; return x; } int main(){ int n ; cin >> n; cout << get(1378 , n) << endl; }
13.333333
32
0.482143
amraboelkher
c3531b198c7bb2f9265dae8567fa54f4391b28e7
2,296
cpp
C++
DEM/Game/src/AI/Memory/MemSystem.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
15
2019-05-07T11:26:13.000Z
2022-01-12T18:26:45.000Z
DEM/Game/src/AI/Memory/MemSystem.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
16
2021-10-04T17:15:31.000Z
2022-03-20T09:34:29.000Z
DEM/Game/src/AI/Memory/MemSystem.cpp
niello/deusexmachina
2f698054fe82d8b40a0a0e58b86d64ffed0de06c
[ "MIT" ]
2
2019-04-28T23:27:48.000Z
2019-05-07T11:26:18.000Z
#include "MemSystem.h" #include <AI/PropActorBrain.h> namespace AI { void CMemSystem::Update() { float Now = 0.f;//(float)GameSrv->GetTime(); CArray<CSensor*> ValidationSensors; // Here we validate facts that reside in memory but weren't updated by the last // sensor activity session. Facts will be accepted or rejected by sensors where // it is possible. Some sort of prediction can be applied to remaining facts. for (UPTR i = 0; i < Facts.GetListCount(); ++i) { //!!!can avoid second dictionary lookup, index will always be i! //???!!!cache sensor lists?! CArray<PSensor>::CIterator It = pActor->GetSensors().Begin(); for (; It != pActor->GetSensors().End(); ++It) if ((*It)->ValidatesFactType(*Facts.GetKeyAt(i))) ValidationSensors.Add((*It)); for (CMemFactNode ItCurr = Facts.GetHeadAt(i); ItCurr; /* empty */) { CMemFact* pFact = ItCurr->Get(); if (pFact->LastUpdateTime < Now) { UPTR Result = Running; CArray<CSensor*>::CIterator It = ValidationSensors.Begin(); for (; It != ValidationSensors.End(); ++It) { // Since we validate only facts not updated this frame, we definitely know here, // that sensor didn't sense stimulus that produced this fact Result = (*It)->ValidateFact(pActor, *pFact); if (Result != Running) break; } if (Result != Failure) pFact->Confidence -= (Now - pFact->LastUpdateTime) * pFact->ForgettingFactor; if (Result == Failure || pFact->Confidence <= 0.f) { CMemFactNode ItRemove = ItCurr; ++ItCurr; Facts.Remove(ItRemove); continue; } // update facts here (can predict positions etc) pFact->LastUpdateTime = Now; } ++ItCurr; } ValidationSensors.Clear(); //???sort by confidence? may be only some fact types } } //--------------------------------------------------------------------- CMemFact* CMemSystem::FindFact(const CMemFact& Pattern, Data::CFlags FieldMask) { CMemFactNode ItCurr = Facts.GetHead(Pattern.GetKey()); while (ItCurr) { // Can lookup pointer to virtual function Match() once since facts are grouped by the class if ((*ItCurr)->Match(Pattern, FieldMask)) return *ItCurr; ++ItCurr; } return nullptr; } //--------------------------------------------------------------------- }
26.697674
93
0.619338
niello
c354055e941357c284944c6b60ed479af608b87c
34,574
cpp
C++
src/QtPhonemes/Phonemes/nSpeechTune.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nSpeechTune.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
src/QtPhonemes/Phonemes/nSpeechTune.cpp
Vladimir-Lin/QtPhonemes
1c1b4f4aa99bbadab5ca25dce1fc64c8ee70202d
[ "MIT" ]
null
null
null
#include <qtphonemes.h> #define SYL_RISE 1 #define SYL_EMPHASIS 2 #define SYL_END_CLAUSE 4 #define PITCHfall 0 #define PITCHrise 2 #define PITCHfrise 4 // and 3 must be for the variant preceded by 'r' #define PITCHfrise2 6 // and 5 must be the 'r' variant #define PITCHrisefall 8 #define N_TONE_HEAD_TABLE 13 #define N_TONE_NUCLEUS_TABLE 13 #define SECONDARY 3 #define PRIMARY 4 #define PRIMARY_STRESSED 6 #define PRIMARY_LAST 7 #define T_EMPH 1 #define OPTION_EMPHASIZE_ALLCAPS 0x100 #define OPTION_EMPHASIZE_PENULTIMATE 0x200 typedef struct { char name [12] ; unsigned char flags [ 4] ; signed char head_extend [ 8] ; unsigned char prehead_start ; unsigned char prehead_end ; unsigned char stressed_env ; unsigned char stressed_drop ; unsigned char secondary_drop ; unsigned char unstressed_shape ; unsigned char onset ; unsigned char head_start ; unsigned char head_end ; unsigned char head_last ; unsigned char head_max_steps ; unsigned char n_head_extend ; signed char unstr_start [ 3] ; // for: onset, head, last signed char unstr_end [ 3] ; unsigned char nucleus0_env ; // pitch envelope, tonic syllable is at end, no tail unsigned char nucleus0_max ; unsigned char nucleus0_min ; unsigned char nucleus1_env ; // when followed by a tail unsigned char nucleus1_max ; unsigned char nucleus1_min ; unsigned char tail_start ; unsigned char tail_end ; unsigned char split_nucleus_env ; unsigned char split_nucleus_max ; unsigned char split_nucleus_min ; unsigned char split_tail_start ; unsigned char split_tail_end ; unsigned char split_tune ; unsigned char spare [ 8] ; int spare2 ; // the struct length should be a multiple of 4 bytes } TUNE ; typedef struct { unsigned char pre_start ; unsigned char pre_end ; unsigned char body_start ; unsigned char body_end ; int * body_drops ; unsigned char body_max_steps ; char body_lower_u ; unsigned char n_overflow ; signed char * overflow ; } TONE_HEAD ; typedef struct { unsigned char pitch_env0 ; /* pitch envelope, tonic syllable at end */ unsigned char tonic_max0 ; unsigned char tonic_min0 ; unsigned char pitch_env1 ; /* followed by unstressed */ unsigned char tonic_max1 ; unsigned char tonic_min1 ; short * backwards ; unsigned char tail_start ; unsigned char tail_end ; unsigned char flags ; } TONE_NUCLEUS ; /* indexed by stress */ static int min_drop[] = { 6, 7, 9, 9,20,20,20,25} ; // pitch change during the main part of the clause static int drops_0[8] = { 9, 9,16,16,16,23,55,32} ; // overflow table values are 64ths of the body pitch range (between body_start and body_end) static signed char oflow [] = { 0, 40, 24, 8, 0} ; static signed char oflow_emf [] = {10, 52, 32, 20, 10} ; static signed char oflow_less[] = { 6, 38, 24, 14, 4} ; static TONE_HEAD tone_head_table[N_TONE_HEAD_TABLE] = { { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 0 statement { 46, 57, 78, 46, drops_0, 3, 7, 5, oflow } , // 1 comma { 46, 57, 78, 46, drops_0, 3, 7, 5, oflow } , // 2 question { 46, 57, 90, 50, drops_0, 3, 9, 5, oflow_emf } , // 3 exclamation { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 4 statement, emphatic { 46, 57, 74, 55, drops_0, 4, 7, 5, oflow_less} , // 5 statement, less intonation { 46, 57, 74, 55, drops_0, 4, 7, 5, oflow_less} , // 6 comma, less intonation { 46, 57, 74, 55, drops_0, 4, 7, 5, oflow_less} , // 7 comma, less intonation, less rise { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 8 pitch raises at end of sentence { 46, 57, 78, 46, drops_0, 3, 7, 5, oflow } , // 9 comma { 46, 57, 78, 50, drops_0, 3, 7, 5, oflow } , // 10 question { 34, 41, 41, 32, drops_0, 3, 7, 5, oflow_less} , // 11 test { 46, 57, 55, 50, drops_0, 3, 7, 5, oflow_less} // 12 test }; static TONE_NUCLEUS tone_nucleus_table[N_TONE_NUCLEUS_TABLE] = { {PITCHfall, 64, 8, PITCHfall, 70,18, NULL, 24, 12, 0}, // 0 statement {PITCHfrise, 80,18, PITCHfrise2, 78,22, NULL, 34, 52, 0}, // 1 comma {PITCHfrise, 88,22, PITCHfrise2, 82,22, NULL, 34, 64, 0}, // 2 question {PITCHfall, 92, 8, PITCHfall, 92,80, NULL, 76, 8, T_EMPH}, // 3 exclamation {PITCHfall, 86, 4, PITCHfall, 94,66, NULL, 34, 10, 0}, // 4 statement, emphatic {PITCHfall, 62,10, PITCHfall, 62,20, NULL, 28, 16, 0}, // 5 statement, less intonation {PITCHfrise, 68,18, PITCHfrise2, 68,22, NULL, 30, 44, 0}, // 6 comma, less intonation {PITCHfrise2, 64,16, PITCHfall, 66,32, NULL, 32, 18, 0}, // 7 comma, less intonation, less rise {PITCHrise, 68,46, PITCHfall, 42,32, NULL, 46, 58, 0}, // 8 pitch raises at end of sentence {PITCHfrise, 78,24, PITCHfrise2, 72,22, NULL, 42, 52, 0}, // 9 comma {PITCHfrise, 88,34, PITCHfall, 64,32, NULL, 46, 82, 0}, // 10 question {PITCHfall, 56,12, PITCHfall, 56,20, NULL, 24, 12, 0}, // 11 test {PITCHfall, 70,18, PITCHfall, 70,24, NULL, 32, 20, 0}, // 12 test }; //////////////////////////////////////////////////////////////////////// int PitchSegment ( N::Syllables & syllables , int start , int end , TONE_HEAD * th , TONE_NUCLEUS * tn , int MinStress , int Continuing ) /* Calculate pitches until next RESET or tonic syllable, or end. Increment pitch if stress is >= min_stress. Used for tonic segment */ { int stress ; int pitch = 0 ; int increment = 0 ; int n_primary = 0 ; int n_steps = 0 ; int initial ; int overflow = 0 ; int n_overflow ; int pitch_range ; int pitch_range_abs ; int * drops = th->body_drops ; signed char * overflow_tab ; static signed char continue_tab[5] = {-26, 32, 20, 8, 0} ; /////////////////////////////////////////////////////////////////////// pitch_range = (th->body_end - th->body_start) << 8 ; pitch_range_abs = abs(pitch_range) ; /////////////////////////////////////////////////////////////////////// if ( Continuing ) { initial = 0 ; overflow = 0 ; n_overflow = 5 ; overflow_tab = continue_tab ; increment = pitch_range / ( th->body_max_steps -1 ) ; } else { n_overflow = th->n_overflow ; overflow_tab = th->overflow ; initial = 1 ; } ; /////////////////////////////////////////////////////////////////////// while ( start < end ) { stress = syllables[start]->Stress ; if ( initial || (stress >= MinStress)) { // a primary stress if ( ( initial ) || ( stress == 5 ) ) { initial = 0 ; overflow = 0 ; n_steps = n_primary = syllables.Increments(start,end,MinStress) ; if ( n_steps > th->body_max_steps ) { n_steps = th->body_max_steps ; } ; if ( n_steps > 1 ) increment = pitch_range / (n_steps -1) ; else increment = 0 ; pitch = th->body_start << 8 ; } else { if ( n_steps > 0 ) pitch += increment ; else { pitch = (th->body_end << 8) + (pitch_range_abs * overflow_tab[overflow++]) /64 ; if ( overflow >= n_overflow ) { overflow = 0 ; overflow_tab = th->overflow ; } ; } ; } ; n_steps -- ; n_primary -- ; if ( ( tn->backwards ) && ( n_primary < 2 ) ) { pitch = tn->backwards[n_primary] << 8 ; } ; } ; ///////////////////////////////////////////////////////////////////// if ( stress >= PRIMARY ) { syllables[start]->Stress = PRIMARY_STRESSED ; syllables[start]->setPitch((pitch >> 8),drops[stress]) ; } else if ( stress >= SECONDARY ) { syllables[start]->setPitch((pitch >> 8),drops[stress]); } else { /* unstressed, drop pitch if preceded by PRIMARY */ if ( (syllables[start-1]->Stress & 0x3f) >= SECONDARY) { syllables[start]->setPitch ( (pitch >> 8) - th->body_lower_u , drops[stress] ) ; } else { syllables[start]->setPitch((pitch >> 8),drops[stress]) ; } ; } ; start++ ; } ; return start ; } //////////////////////////////////////////////////////////////////////// N::SpeechTune:: SpeechTune (void) : prehead_start (0 ) , prehead_end (0 ) , stressed_env (0 ) , stressed_drop (0 ) , secondary_drop (0 ) , unstressed_shape (0 ) , onset (0 ) , head_start (0 ) , head_end (0 ) , head_last (0 ) , head_max_steps (0 ) , n_head_extend (0 ) , nucleus0_env (0 ) , nucleus0_max (0 ) , nucleus0_min (0 ) , nucleus1_env (0 ) , nucleus1_max (0 ) , nucleus1_min (0 ) , tail_start (0 ) , tail_end (0 ) , split_nucleus_env (0 ) , split_nucleus_max (0 ) , split_nucleus_min (0 ) , split_tail_start (0 ) , split_tail_end (0 ) , split_tune (0 ) , spare2 (0 ) { memset(name ,0,sizeof(char)*12) ; memset(flags ,0,sizeof(char)* 4) ; memset(head_extend,0,sizeof(char)* 8) ; memset(unstr_start,0,sizeof(char)* 3) ; memset(unstr_end ,0,sizeof(char)* 3) ; memset(spare ,0,sizeof(char)* 8) ; } N::SpeechTune:: SpeechTune(const SpeechTune & tune) { assign ( tune ) ; } N::SpeechTune::~SpeechTune(void) { } N::SpeechTune & N::SpeechTune::operator = (const SpeechTune & tune) { return assign(tune) ; } N::SpeechTune & N::SpeechTune::assign(const SpeechTune & tune) { nMemberCopy ( tune , prehead_start ) ; nMemberCopy ( tune , prehead_end ) ; nMemberCopy ( tune , stressed_env ) ; nMemberCopy ( tune , stressed_drop ) ; nMemberCopy ( tune , secondary_drop ) ; nMemberCopy ( tune , unstressed_shape ) ; nMemberCopy ( tune , onset ) ; nMemberCopy ( tune , head_start ) ; nMemberCopy ( tune , head_end ) ; nMemberCopy ( tune , head_last ) ; nMemberCopy ( tune , head_max_steps ) ; nMemberCopy ( tune , n_head_extend ) ; nMemberCopy ( tune , nucleus0_env ) ; nMemberCopy ( tune , nucleus0_max ) ; nMemberCopy ( tune , nucleus0_min ) ; nMemberCopy ( tune , nucleus1_env ) ; nMemberCopy ( tune , nucleus1_max ) ; nMemberCopy ( tune , nucleus1_min ) ; nMemberCopy ( tune , tail_start ) ; nMemberCopy ( tune , tail_end ) ; nMemberCopy ( tune , split_nucleus_env ) ; nMemberCopy ( tune , split_nucleus_max ) ; nMemberCopy ( tune , split_nucleus_min ) ; nMemberCopy ( tune , split_tail_start ) ; nMemberCopy ( tune , split_tail_end ) ; nMemberCopy ( tune , split_tune ) ; nMemberCopy ( tune , spare2 ) ; ::memcpy(name ,tune.name ,sizeof(char)*12) ; ::memcpy(flags ,tune.flags ,sizeof(char)* 4) ; ::memcpy(head_extend,tune.head_extend,sizeof(char)* 8) ; ::memcpy(unstr_start,tune.unstr_start,sizeof(char)* 3) ; ::memcpy(unstr_end ,tune.unstr_end ,sizeof(char)* 3) ; ::memcpy(spare ,tune.spare ,sizeof(char)* 8) ; return ME ; } int N::SpeechTune::packetSize(void) { return sizeof(TUNE) ; } void N::SpeechTune::set(int index,QByteArray & data) { TUNE * tune = NULL ; char * d = (char *)data.data() ; tune = (TUNE *) ( d + index ) ; #define MemberCopy(o,m) m = o->m MemberCopy ( tune , prehead_start ) ; MemberCopy ( tune , prehead_end ) ; MemberCopy ( tune , stressed_env ) ; MemberCopy ( tune , stressed_drop ) ; MemberCopy ( tune , secondary_drop ) ; MemberCopy ( tune , unstressed_shape ) ; MemberCopy ( tune , onset ) ; MemberCopy ( tune , head_start ) ; MemberCopy ( tune , head_end ) ; MemberCopy ( tune , head_last ) ; MemberCopy ( tune , head_max_steps ) ; MemberCopy ( tune , n_head_extend ) ; MemberCopy ( tune , nucleus0_env ) ; MemberCopy ( tune , nucleus0_max ) ; MemberCopy ( tune , nucleus0_min ) ; MemberCopy ( tune , nucleus1_env ) ; MemberCopy ( tune , nucleus1_max ) ; MemberCopy ( tune , nucleus1_min ) ; MemberCopy ( tune , tail_start ) ; MemberCopy ( tune , tail_end ) ; MemberCopy ( tune , split_nucleus_env ) ; MemberCopy ( tune , split_nucleus_max ) ; MemberCopy ( tune , split_nucleus_min ) ; MemberCopy ( tune , split_tail_start ) ; MemberCopy ( tune , split_tail_end ) ; MemberCopy ( tune , split_tune ) ; MemberCopy ( tune , spare2 ) ; #undef MemberCopy ::memcpy(name ,tune->name ,sizeof(char)*12) ; ::memcpy(flags ,tune->flags ,sizeof(char)* 4) ; ::memcpy(head_extend,tune->head_extend,sizeof(char)* 8) ; ::memcpy(unstr_start,tune->unstr_start,sizeof(char)* 3) ; ::memcpy(unstr_end ,tune->unstr_end ,sizeof(char)* 3) ; ::memcpy(spare ,tune->spare ,sizeof(char)* 8) ; } int N::SpeechTune::Packet(QByteArray & data) { TUNE tune ; char * d = (char *)&tune ; #define MemberCopy(o,m) o.m = m MemberCopy ( tune , prehead_start ) ; MemberCopy ( tune , prehead_end ) ; MemberCopy ( tune , stressed_env ) ; MemberCopy ( tune , stressed_drop ) ; MemberCopy ( tune , secondary_drop ) ; MemberCopy ( tune , unstressed_shape ) ; MemberCopy ( tune , onset ) ; MemberCopy ( tune , head_start ) ; MemberCopy ( tune , head_end ) ; MemberCopy ( tune , head_last ) ; MemberCopy ( tune , head_max_steps ) ; MemberCopy ( tune , n_head_extend ) ; MemberCopy ( tune , nucleus0_env ) ; MemberCopy ( tune , nucleus0_max ) ; MemberCopy ( tune , nucleus0_min ) ; MemberCopy ( tune , nucleus1_env ) ; MemberCopy ( tune , nucleus1_max ) ; MemberCopy ( tune , nucleus1_min ) ; MemberCopy ( tune , tail_start ) ; MemberCopy ( tune , tail_end ) ; MemberCopy ( tune , split_nucleus_env ) ; MemberCopy ( tune , split_nucleus_max ) ; MemberCopy ( tune , split_nucleus_min ) ; MemberCopy ( tune , split_tail_start ) ; MemberCopy ( tune , split_tail_end ) ; MemberCopy ( tune , split_tune ) ; MemberCopy ( tune , spare2 ) ; #undef MemberCopy ::memcpy(tune.name ,name ,sizeof(char)*12) ; ::memcpy(tune.flags ,flags ,sizeof(char)* 4) ; ::memcpy(tune.head_extend,head_extend,sizeof(char)* 8) ; ::memcpy(tune.unstr_start,unstr_start,sizeof(char)* 3) ; ::memcpy(tune.unstr_end ,unstr_end ,sizeof(char)* 3) ; ::memcpy(tune.spare ,spare ,sizeof(char)* 8) ; data.append((const char *)d,sizeof(TUNE)) ; return sizeof(TUNE) ; } int N::SpeechTune::setHeadIntonation ( Syllables & syllables , int start , int end ) { int stress ; int ix ; int pitch = 0 ; int increment = 0 ; int n_steps = 0 ; int stage = 0 ; // onset, head, last int initial = 1 ; int overflow_ix = 0 ; int pitch_range = ( head_end - head_start ) << 8 ; int pitch_range_abs = ::abs ( pitch_range ) ; int * drops = drops_0 ; // this should be controled by tune->head_drops int n_unstressed = 0 ; int unstressed_ix = 0 ; int unstressed_inc ; int used_onset = 0 ; int head_final = end ; int secondary = 2 ; // 2 //////////////////////////////////////////////////////////////////////// if ( onset == 255 ) stage = 1 ; // no onset specified if ( head_last != 255 ) { // find the last primary stress in the body for ( ix = end - 1 ; ix >= start ; ix-- ) { if ( syllables[ix]->Stress >= 4 ) { head_final = ix ; break ; } ; } ; } ; //////////////////////////////////////////////////////////////////////// while ( start < end ) { stress = syllables[start]->Stress ; if ( initial || ( stress >= 4 ) ) { // a primary stress if ( ( initial ) || ( stress == 5 ) ) { initial = 0 ; overflow_ix = 0 ; if ( onset == 255 ) { n_steps = syllables.Increments(start,head_final,4) ; pitch = head_start << 8 ; } else { // a pitch has been specified for the onset syllable, don't include it in the pitch incrementing n_steps = syllables.Increments(start+1,head_final,4) ; pitch = onset << 8 ; used_onset = 1 ; } ; if ( n_steps > head_max_steps) n_steps = head_max_steps ; if ( n_steps > 1 ) { increment = pitch_range / ( n_steps - 1 ) ; } else increment = 0 ; } else if ( start == head_final ) { // a pitch has been specified for the last primary stress before the nucleus pitch = head_last << 8 ; stage = 2 ; } else { if ( used_onset ) { stage = 1 ; used_onset = 0 ; pitch = head_start << 8 ; n_steps++ ; } else if ( n_steps > 0 ) pitch += increment ; else { pitch = (head_end << 8) + (pitch_range_abs * head_extend[overflow_ix++]) / 64 ; if ( overflow_ix >= n_head_extend ) overflow_ix = 0 ; } ; } ; n_steps-- ; } ; if ( stress >= PRIMARY ) { n_unstressed = syllables.Unstressed(start+1,end,secondary) ; unstressed_ix = 0 ; syllables[start]->Stress = PRIMARY_STRESSED ; syllables[start]->Envelope = stressed_env ; syllables[start]->setPitch ( ( pitch >> 8 ) , stressed_drop ) ; } else if ( stress >= secondary ) { n_unstressed = syllables.Unstressed(start,end,secondary) ; unstressed_ix = 0 ; syllables[start]->setPitch( (pitch >> 8) , drops[stress] ) ; } else { if(n_unstressed > 1) { unstressed_inc = ( unstr_end[stage] - unstr_start[stage]) / ( n_unstressed - 1 ) ; } else unstressed_inc = 0 ; syllables[start]->setPitch ( (pitch >> 8) + unstr_start[stage] + (unstressed_inc * unstressed_ix) , drops[stress] ) ; unstressed_ix++ ; } ; start++ ; } ; return start ; } int N::SpeechTune::Pitches(Syllables & syllables,int start,int end,int toneflags) // Calculate pitch values for the vowels in this tone group { int ix = start ; int prev = syllables.Previous ; int drop ; /* vowels before the first primary stress */ syllables.setPitchGradient(ix,ix+prev,prehead_start,prehead_end) ; ix += prev ; /* body of tonic segment */ if ( toneflags & OPTION_EMPHASIZE_PENULTIMATE ) { syllables.TonePosition = syllables.TonePosition2 ; // put tone on the penultimate stressed word } ; ix = setHeadIntonation(syllables,ix,syllables.TonePosition) ; if (syllables.NoTonic) return 0 ; if (syllables.Tail == 0) { syllables.PitchEnvelope = nucleus0_env ; drop = nucleus0_max - nucleus0_min ; syllables[ix++]->setPitch(nucleus0_min,drop) ; } else { syllables.PitchEnvelope = nucleus1_env ; drop = nucleus1_max - nucleus1_min ; syllables[ix++]->setPitch(nucleus1_min,drop) ; } ; syllables[syllables.TonePosition]->Envelope = syllables.PitchEnvelope ; if (syllables[syllables.TonePosition]->Stress == PRIMARY) { syllables[syllables.TonePosition]->Stress = PRIMARY_STRESSED ; } ; /* tail, after the tonic syllable */ syllables.setPitchGradient(ix,end,tail_start,tail_end) ; return syllables.PitchEnvelope ; } int N::SpeechTune::Pitches(Syllables & syllables,int start,int end,int control,int index,int toneflags) { int ix ; TONE_HEAD * th ; TONE_NUCLEUS * tn ; int drop ; int continuing = 0 ; ////////////////////////////////////////////////////////////////////// if ( control == 0 ) return Pitches (syllables,start,end,toneflags) ; if ( start > 0 ) continuing = 1 ; th = &tone_head_table [ index ] ; tn = &tone_nucleus_table [ index ] ; ix = start ; /* vowels before the first primary stress */ syllables.setPitchGradient(ix ,ix+syllables.Previous , th->pre_start,th->pre_end ) ; ix += syllables.Previous ; /* body of tonic segment */ if ( toneflags & OPTION_EMPHASIZE_PENULTIMATE ) { // put tone on the penultimate stressed word syllables.TonePosition = syllables.TonePosition2 ; } ; ix = PitchSegment ( syllables , ix , syllables.TonePosition , th , tn , PRIMARY , continuing ) ; if (syllables.NoTonic) return 0 ; /* tonic syllable */ if ( tn->flags & T_EMPH ) { syllables[ix]->Flags |= SYL_EMPHASIS ; } ; if ( syllables.Tail == 0 ) { syllables.PitchEnvelope = tn->pitch_env0 ; drop = tn->tonic_max0 - tn->tonic_min0 ; syllables[ix]->setPitch(tn->tonic_min0,drop) ; ix++ ; } else { syllables.PitchEnvelope = tn->pitch_env1 ; drop = tn->tonic_max1 - tn->tonic_min1 ; syllables[ix]->setPitch(tn->tonic_min1,drop) ; ix++ ; } ; ////////////////////////////////////////////////////////////////////// syllables[syllables.TonePosition]->Envelope = syllables.PitchEnvelope ; if (syllables[syllables.TonePosition]->Stress == PRIMARY) { syllables[syllables.TonePosition]->Stress = PRIMARY_STRESSED ; } ; /* tail, after the tonic syllable */ syllables.setPitchGradient(ix,end,tn->tail_start,tn->tail_end) ; return syllables.PitchEnvelope ; } void N::SpeechTune::report(void) { printf("Name = %s\n",name) ; #define R(item) printf(#item " = %d\n",item) R ( prehead_start ) ; R ( prehead_end ) ; R ( stressed_env ) ; R ( stressed_drop ) ; R ( secondary_drop ) ; R ( unstressed_shape ) ; R ( onset ) ; R ( head_start ) ; R ( head_end ) ; R ( head_last ) ; R ( head_max_steps ) ; R ( n_head_extend ) ; R ( nucleus0_env ) ; R ( nucleus0_max ) ; R ( nucleus0_min ) ; R ( nucleus1_env ) ; R ( nucleus1_max ) ; R ( nucleus1_min ) ; R ( tail_start ) ; R ( tail_end ) ; R ( split_nucleus_env ) ; R ( split_nucleus_max ) ; R ( split_nucleus_min ) ; R ( split_tail_start ) ; R ( split_tail_end ) ; R ( split_tune ) ; R ( spare2 ) ; #undef R #define R(item,total) \ printf(#item " = ") ; \ for (int i=0;i<total;i++) { \ printf("[%d]",item[i]) ; \ } ; \ printf("\n") R(flags ,4) ; R(head_extend,8) ; R(unstr_start,3) ; R(unstr_end ,3) ; R(spare ,8) ; #undef R }
53.853583
122
0.37398
Vladimir-Lin
c357b32535eb58b0741bde301a38f6e29ed2125f
405
hpp
C++
include/Nen/Component/CircleComponent.hpp
Astomih/NenEngine
669fcbaa7a26cbdeb764315d8c9c17370075611e
[ "MIT" ]
2
2021-03-16T15:59:41.000Z
2021-12-01T12:30:30.000Z
include/Nen/Component/CircleComponent.hpp
Astomih/NenEngine
669fcbaa7a26cbdeb764315d8c9c17370075611e
[ "MIT" ]
1
2021-09-05T05:08:48.000Z
2021-09-05T05:08:48.000Z
include/Nen/Component/CircleComponent.hpp
Astomih/NenEngine
669fcbaa7a26cbdeb764315d8c9c17370075611e
[ "MIT" ]
null
null
null
#pragma once #include "Component.hpp" namespace nen { class circle_component : public base_component { public: circle_component(class base_actor &owner); void SetRadius(float radius) noexcept { mRadius = radius; } vector3 GetRadius() const; const vector3 &GetCenter() const; bool Intersect(const circle_component &a, const circle_component &b); private: float mRadius; }; } // namespace nen
23.823529
71
0.750617
Astomih
c35a7d175749453b2ba1a1d63890b00162cd038e
628
hpp
C++
src/gameworld/gameworld/scene/speciallogic/personspecial/specialfbguide.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/scene/speciallogic/personspecial/specialfbguide.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/scene/speciallogic/personspecial/specialfbguide.hpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#ifndef __SPECIAL_FB_GUIDE_H__ #define __SPECIAL_FB_GUIDE_H__ #include "scene/speciallogic/speciallogic.hpp" #include "other/fb/fbguideconfig.hpp" #include "protocal/msgfb.h" class SpecialFbGuide: public SpecialLogic { public: SpecialFbGuide(Scene *scene); virtual ~SpecialFbGuide(); virtual void OnRoleLeaveScene(Role *role, bool is_logout); void OnFinish(Role *role, int monster_x, int monster_y, int monster_id); void OnCreateGather(Role *role, int gather_x, int gather_y, int gather_id, int gather_time); void SetObjPos(Role * role, Protocol::CSFunOpenSetObjToPos *cmd); protected: bool m_is_finish; }; #endif
25.12
93
0.786624
mage-game
c365a0cc958dc5ad3e5a502c3ac833300430ba49
760
cpp
C++
src/Event.cpp
zetef/calviewer
d08654051b5b6de214bf6cfc3b39afac2ab752c6
[ "MIT" ]
null
null
null
src/Event.cpp
zetef/calviewer
d08654051b5b6de214bf6cfc3b39afac2ab752c6
[ "MIT" ]
1
2019-04-21T22:31:24.000Z
2019-04-22T09:01:01.000Z
src/Event.cpp
zetef/kalendar
d08654051b5b6de214bf6cfc3b39afac2ab752c6
[ "MIT" ]
null
null
null
#include "../include/Event.h" //////////////////////////////// /// Public Member Functions //// //////////////////////////////// Event::Event() { init(); } void Event::init(){ m_exist = false; m_title = "No Event"; m_day = 1; m_month = 1; m_year = 1900; } void Event::set_title(std::string t_title) { m_title = t_title; } void Event::set_day(int t_day) { m_day = t_day; } int Event::get_day(){ return m_day; } void Event::set_month(int t_month) { m_month = t_month; } int Event::get_month(){ return m_month; } void Event::set_year(int t_year) { m_year = t_year; } int Event::get_year(){ return m_year; } // void Event::check() { // if(){ // set_title(); // } // } void Event::free(){ init(); } ////////////////////////////////
12.881356
44
0.534211
zetef
c379a50ee71309d9e765e9d9241fcac798ad588c
3,201
cpp
C++
src/Source Code/Mesh.cpp
MayKoder/Advanced-GL-Shader
3a73c5c112f9cc245b6353734eed572b96f95af2
[ "MIT" ]
null
null
null
src/Source Code/Mesh.cpp
MayKoder/Advanced-GL-Shader
3a73c5c112f9cc245b6353734eed572b96f95af2
[ "MIT" ]
null
null
null
src/Source Code/Mesh.cpp
MayKoder/Advanced-GL-Shader
3a73c5c112f9cc245b6353734eed572b96f95af2
[ "MIT" ]
null
null
null
#include "Mesh.h" #include <vector> void Mesh::init(Vertex* vertices, unsigned int numVertices, unsigned int* indices, unsigned int numIndices) { IndexedModel model; for (unsigned int i = 0; i < numVertices; i++) { model.positions.push_back(*vertices[i].GetPos()); model.texCoords.push_back(*vertices[i].GetTexCoord()); model.normals.push_back(*vertices[i].GetNormal()); } for (unsigned int i = 0; i < numIndices; i++) model.indices.push_back(indices[i]); initModel(model); } void Mesh::initModel(const IndexedModel& model) { drawCount = model.indices.size(); glGenVertexArrays(1, &vertexArrayObject); //generate a vertex array and store it in the VAO glBindVertexArray(vertexArrayObject); //bind the VAO (any operation that works on a VAO will work on our bound VAO - binding) glGenBuffers(4, vertexArrayBuffers); //generate our buffers based of our array of data/buffers - GLuint vertexArrayBuffers[NUM_BUFFERS]; glBindBuffer(GL_ARRAY_BUFFER, vertexArrayBuffers[POSITION_VERTEXBUFFER]); //tell opengl what type of data the buffer is (GL_ARRAY_BUFFER), and pass the data glBufferData(GL_ARRAY_BUFFER, model.positions.size() * sizeof(model.positions[0]), &model.positions[0], GL_STATIC_DRAW); //move the data to the GPU - type of data, size of data, starting address (pointer) of data, where do we store the data on the GPU (determined by type) glEnableVertexAttribArray(0); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, vertexArrayBuffers[TEXCOORD_VB]); //tell opengl what type of data the buffer is (GL_ARRAY_BUFFER), and pass the data glBufferData(GL_ARRAY_BUFFER, model.texCoords.size() * sizeof(model.texCoords[0]), &model.texCoords[0], GL_STATIC_DRAW); //move the data to the GPU - type of data, size of data, starting address (pointer) of data, where do we store the data on the GPU glEnableVertexAttribArray(1); glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ARRAY_BUFFER, vertexArrayBuffers[NORMAL_VB]); glBufferData(GL_ARRAY_BUFFER, sizeof(model.normals[0]) * model.normals.size(), &model.normals[0], GL_STATIC_DRAW); glEnableVertexAttribArray(2); glVertexAttribPointer(2, 3, GL_FLOAT, GL_FALSE, 0, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexArrayBuffers[INDEX_VB]); //tell opengl what type of data the buffer is (GL_ARRAY_BUFFER), and pass the data glBufferData(GL_ELEMENT_ARRAY_BUFFER, model.indices.size() * sizeof(model.indices[0]), &model.indices[0], GL_STATIC_DRAW); //move the data to the GPU - type of data, size of data, starting address (pointer) of data, where do we store the data on the GPU glBindVertexArray(0); // unbind our VAO } Mesh::Mesh() : vertexArrayObject(0) { drawCount = NULL; memset(vertexArrayBuffers, 0, sizeof(vertexArrayBuffers)); } void Mesh::loadModel(const std::string& filename) { IndexedModel model = OBJModel(filename).ToIndexedModel(); initModel(model); } Mesh::~Mesh() { glDeleteVertexArrays(1, &vertexArrayObject); // delete arrays } void Mesh::draw() { glBindVertexArray(vertexArrayObject); glDrawElements(GL_TRIANGLES, drawCount, GL_UNSIGNED_INT, 0); //glDrawArrays(GL_TRIANGLES, 0, drawCount); glBindVertexArray(0); }
40.0125
273
0.759763
MayKoder
c37bee8a2868aaf01d2cbab804d52a1d98a34b1f
2,287
cpp
C++
src/main.cpp
horvatm/misaligned_roche_critical
8e302b468c8b23ce012407250292e5fdf806ef4f
[ "MIT" ]
null
null
null
src/main.cpp
horvatm/misaligned_roche_critical
8e302b468c8b23ce012407250292e5fdf806ef4f
[ "MIT" ]
null
null
null
src/main.cpp
horvatm/misaligned_roche_critical
8e302b468c8b23ce012407250292e5fdf806ef4f
[ "MIT" ]
null
null
null
/* Searching for critical points of the Kopal potential Omega of the misaligned binary star: Omega(x,y,z,params) = 1/r1 + q(1/r2 - x/delta^2) + 1/2 (1 + q) F^2 [(x cos theta' - z sin theta')^2 + y^2] r1 = sqrt(x^2 + y^2 + z^2) r2 = sqrt((x-delta)^2 + y^2 + z^2) The critical point r is defined as Nabla Omega(r) = 0; Note: * Sometimes we referee to theta as beta. Author: Martin Horvat, Jan 2018 */ #include <iostream> #include <cmath> #include <fstream> #include "main.h" int main(){ std::cout.precision(16); std::cout << std::scientific; std::ofstream fl("res1.dat"); fl.precision(16); fl << std::scientific; double X0 = -10000, // limits of the bounding box [X0,Y0] , [X1,Y1] Y0 = -10000, X1 = +10000, Y1 = +10000, Nx = 1000000, // maximal number of steps in X direction Ny = 1000000, // maximal number of steps in Y direction Nl = 50, // maximal number of recursions Nth = 400, // steps in theta, theta in [th_min, th_max] th, th_min = -M_PI/2, th_max = +M_PI/2, dth = (th_max - th_min)/(Nth-1), Nq = 50, // steps in q, q in [q_min, q_max] q, q_min = 0.1, q_max = 10, dq = (q_max - q_min)/(Nq-1), NF = 50, // steps in F, F in [F_min, F_max] F, F_min = 0.1, F_max = 10, dF = (F_max - F_min)/(NF-1), p[4], H[2][2]; for (int i = 0; i < Nq; ++i) { p[0] = q = q_min + dq*i; for (int j = 0; j < NF; ++j) { F = F_min + dF*j; p[1] = (1 + q)*F*F; for (int k = 0; k < Nth; ++k) { th = th_min + k*dth; sincos(th, p+2, p+3); Troots <double> roots; //scan_with_lines<double>(X0, Y0, X1, Y1, p, roots, Nx, Ny, Nl); scan_with_image<double>(X0, Y0, X1, Y1, p, roots, Nx, Ny, Nl); for (auto && x: roots) if (!(x[0] == 0 && x[1] == 0) && !(x[0] == 1 && x[1] == 0)) { Dfun(x.ptr(), H, p); fl << q << ' ' << F << ' ' << th << ' ' << x[0] << ' ' << x[1] << ' ' << extreme_type(H) << '\n'; } } fl.flush(); } } return 0; }
23.336735
109
0.452995
horvatm
c39615e0b35dee60bd22cf92c60d9aeeffaabf7c
839
cpp
C++
프로그래머스/동적계획법/정수삼각형.cpp
woorimlee/cpp_CTCI_6E_APSS
ff1d42e871ba853ac3de726df0c609885ba07573
[ "MIT" ]
2
2020-12-30T03:35:51.000Z
2021-02-28T20:39:09.000Z
프로그래머스/동적계획법/정수삼각형.cpp
woorimlee/cpp_CTCI_6E_APSS
ff1d42e871ba853ac3de726df0c609885ba07573
[ "MIT" ]
1
2020-12-08T08:48:40.000Z
2021-04-09T04:58:57.000Z
프로그래머스/동적계획법/정수삼각형.cpp
woorimlee/Algorithm-Repository
ff1d42e871ba853ac3de726df0c609885ba07573
[ "MIT" ]
null
null
null
#include <string> #include <vector> #include <algorithm> #include <iostream> using namespace std; int cache[501][501]; int search_path(vector<vector<int>>& tri, int y, int x) { if (y == tri.size()) return 0; int& ret = cache[y][x]; if (ret != -1) return ret; ret = 0; ret = max(ret, search_path(tri, y + 1, x) + tri[y][x]); ret = max(ret, search_path(tri, y + 1, x + 1) + tri[y][x]); return ret; } int solution(vector<vector<int>> triangle) { int answer = 0; fill(&cache[0][0], &cache[500][501], -1); answer = search_path(triangle, 0, 0); cout << answer; return answer; } int main() { //[[7], [3, 8], [8, 1, 0], [2, 7, 4, 4], [4, 5, 2, 6, 5]] vector<vector <int> > t = { {7}, {3, 8}, {8, 1, 0}, {2, 7, 4, 4}, {4, 5, 2, 6, 5} }; solution(t); return 0; }
23.305556
88
0.517282
woorimlee
c3a838b1b9a20f49df4a644f22c3613dd2e42bcb
158
cpp
C++
testcase/while_loop.cpp
ryanorz/srun
00080749fc7c1bff9c2ebb506bbbda23a893bf7c
[ "Apache-2.0" ]
7
2017-01-17T07:21:24.000Z
2017-02-26T17:24:02.000Z
testcase/while_loop.cpp
ryanorz/srun
00080749fc7c1bff9c2ebb506bbbda23a893bf7c
[ "Apache-2.0" ]
null
null
null
testcase/while_loop.cpp
ryanorz/srun
00080749fc7c1bff9c2ebb506bbbda23a893bf7c
[ "Apache-2.0" ]
null
null
null
#include <unistd.h> #include <stdio.h> int main() { int n = 0; while (1) { sleep(1); printf("while_loop %d\n", ++n); fflush(stdout); } return 0; }
11.285714
33
0.563291
ryanorz
c3ac79593d612a9c9e6ad4eb3e97686fe7dce256
17,552
hpp
C++
filter/cuckoo_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
33
2021-08-29T00:19:14.000Z
2022-03-30T02:40:36.000Z
filter/cuckoo_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
null
null
null
filter/cuckoo_filter.hpp
yuchen1024/Kunlun
f1a4a6a1efcb81905df4f0c3ffe5e863fa0dfacf
[ "MIT" ]
3
2021-09-09T11:34:35.000Z
2022-01-12T11:10:05.000Z
/* ** Modified from https://github.com/efficient/cuckoofilter ** (1) simplify the design ** (2) add serialize/deserialize interfaces ** Thanks discussions with Minglang Dong */ #ifndef KUNLUN_CUCKOO_FILTER_HPP #define KUNLUN_CUCKOO_FILTER_HPP #include "../include/std.inc" #include "../utility/murmurhash3.hpp" #include "../utility/bit_operation.hpp" #include "../crypto/ec_point.hpp" #include "../utility/print.hpp" // selection of keyed hash for cuckoo filter #define FastHash LiteMurmurHash enum InsertToBucketStatus { SuccessAndNoKick = 0, FreshInsertFailure = 1, SuccessButKick = 2, }; struct VictimCache{ uint32_t bucket_index; uint32_t tag; uint32_t used; // false or true }; // Cuckoo filter interfaces: Insert, Delete, Contain. class CuckooFilter{ public: // Storage of items std::vector<uint8_t> bucket_table; // number of inserted elements size_t inserted_element_num; size_t max_kick_count = 500; // maximum number of cuckoo kicks before claiming failure size_t slot_num = 4; // the slot num of each bucket size_t tag_bit_size = 16; size_t bucket_byte_size; size_t bucket_num; VictimCache victim; CuckooFilter() {}; CuckooFilter(size_t projected_element_num, double desired_false_positive_probability){ max_kick_count = 500; slot_num = 4; tag_bit_size = 16; bucket_byte_size = slot_num * tag_bit_size / 8; // bucket_num must be always a power of two bucket_num = upperpower2(std::max<uint32_t>(1, projected_element_num /slot_num)); double load_factor = (double)projected_element_num / (bucket_num * slot_num); if (load_factor > 0.96) { bucket_num = bucket_num * 2; } bucket_table.resize(bucket_num * slot_num * tag_bit_size / 8); memset(bucket_table.data(), 0, bucket_table.size()); inserted_element_num = 0; victim.used = 0; } ~CuckooFilter() {} size_t ObjectSize() { // hash_num + random_seed + table_size + table_content return 6 * 8 + bucket_table.size() + 4 * 3; } // index_1 = LEFT(Hash(x)) mod bucket_num serve as the first choice inline uint32_t ComputeBucketIndex(uint32_t hash_value) { // since bucket_num = 2^n, the following is equivalent to hash_value mod 2^n return hash_value & (bucket_num - 1); // fetch left 32 bit } inline uint32_t ComputeTag(uint32_t hash_value) { uint32_t tag; // set tag as the leftmost "tag_bit_size" part tag = hash_value >> (32 - tag_bit_size); tag += (tag == 0); // ensure tag is not zero return tag; } inline uint32_t ComputeAnotherBucketIndex(const uint32_t bucket_index, const uint32_t tag) { // index_2 = (index_1 XOR tag) mod bucket_num return (bucket_index ^ (tag * 0x5bd1e995)) & (bucket_num - 1); //return (bucket_index ^ FastHash(&tag, 4)) & (bucket_num - 1); } // Insert an item to the filter. // To make this procedure efficient, we omit the repetetion check // so, we need to ensure the inserted element // We also omit extra check when victim is being used // simply presume in that case the filter will be very dense bool PlainInsert(const void* input, size_t LEN){ if (victim.used){ std::cerr << "there is not enough space" << std::endl; return false; } uint32_t hash_value = FastHash(input, LEN); uint32_t current_bucket_index = ComputeBucketIndex(hash_value); uint32_t current_tag = ComputeTag(hash_value); // std::cout << "bucket index = " << std::hex << current_bucket_index << std::endl; // std::cout << "tag = " << std::hex << current_tag << std::endl; uint32_t kickout_tag = 0; bool licence_to_kickout = false; size_t kick_count = 0; int insert_to_bucket_status; while (kick_count < max_kick_count) { insert_to_bucket_status = InsertTagToBucket(current_bucket_index, current_tag, licence_to_kickout, kickout_tag); switch(insert_to_bucket_status){ case SuccessAndNoKick: inserted_element_num++; return true; case FreshInsertFailure: licence_to_kickout = true; break; case SuccessButKick: kick_count++; current_tag = kickout_tag; break; } current_bucket_index = ComputeAnotherBucketIndex(current_bucket_index, current_tag); } // if there is still kickout tag after MaxKickCount times kick, save it to victim cache victim.bucket_index = current_bucket_index; victim.tag = current_tag; victim.used = 1; return true; } template <typename ElementType> // Note: T must be a C++ POD type. inline bool Insert(const ElementType& element) { return PlainInsert(&element, sizeof(ElementType)); } inline bool Insert(const std::string& str) { return PlainInsert(str.data(), str.size()); } // You can insert any custom-type data you like as below inline bool Insert(const ECPoint &A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainInsert(buffer, POINT_BYTE_LEN); } inline bool Insert(const std::vector<ECPoint> &vec_A) { bool insert_status = true; size_t num = vec_A.size(); unsigned char *buffer = new unsigned char[num*POINT_BYTE_LEN]; for(auto i = 0; i < num; i++){ EC_POINT_point2oct(group, vec_A[i].point_ptr, POINT_CONVERSION_COMPRESSED, buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN, nullptr); if(PlainInsert(buffer+i*POINT_BYTE_LEN, POINT_BYTE_LEN) == false){ insert_status = false; break; } } delete[] buffer; return insert_status; } template <typename InputIterator> inline bool Insert(const InputIterator begin, const InputIterator end) { bool insert_status = true; InputIterator itr = begin; while (end != itr){ if(Insert(*(itr++)) == false){ insert_status = false; break; } } return insert_status; } template <class T, class Allocator, template <class,class> class Container> inline bool Insert(Container<T, Allocator>& container) { bool insert_status = true; for(auto i = 0; i < container.size(); i++){ if(Insert(container[i]) == false){ insert_status = false; std::cout << "insert the " << i << "-th element fails" << std::endl; break; } } return insert_status; } // Report if the item is inserted, with false positive rate. bool PlainContain(const void* input, size_t LEN) { uint32_t hash_value = FastHash(input, LEN); uint32_t index1 = ComputeBucketIndex(hash_value); uint32_t tag = ComputeTag(hash_value); uint32_t index2 = ComputeAnotherBucketIndex(index1, tag); // check if find in buckets if (FindTagInBucket(index1, tag)) return true; if (FindTagInBucket(index2, tag)) return true; // check if in victim.cache if (victim.used && (tag == victim.tag) && (index1 == victim.bucket_index || index2 == victim.bucket_index)) return true; return false; } template <typename ElementType> inline bool Contain(const ElementType& element) { return PlainContain(&element, sizeof(ElementType)); } inline bool Contain(const std::string& str) { return PlainContain(str.data(), str.size()); } inline bool Contain(const ECPoint& A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainContain(buffer, POINT_BYTE_LEN); } bool TrySaveVictim(uint32_t bucket_index, uint32_t slot_index, uint32_t tag) { if (victim.used && (victim.bucket_index == bucket_index) && (victim.tag == tag)) { victim.used = 0; WriteTag(bucket_index, slot_index, tag); return true; } return false; } // Delete an key from the filter bool PlainDelete(const void* input, size_t LEN) { bool delete_status = false; uint32_t hash_value = FastHash(input, LEN); uint32_t index1 = ComputeBucketIndex(hash_value); uint32_t tag = ComputeTag(hash_value); uint32_t index2 = ComputeAnotherBucketIndex(index1, tag); uint32_t delete_slot_index; if (DeleteTagFromBucket(index1, tag, delete_slot_index)) { inserted_element_num--; delete_status = true; TrySaveVictim(index1, delete_slot_index, tag); } if (DeleteTagFromBucket(index2, tag, delete_slot_index)) { inserted_element_num--; delete_status = true; TrySaveVictim(index2, delete_slot_index, tag); } if (victim.used && tag == victim.tag && (index1 == victim.bucket_index || index2 == victim.bucket_index)) { victim.used = 0; delete_status = true; } return delete_status; } template <typename ElementType> inline bool Delete(const ElementType& element) { return PlainDelete(&element, sizeof(ElementType)); } inline bool Delete(const std::string& str) { return PlainDelete(str.data(), str.size()); } inline bool Delete(const ECPoint& A) { unsigned char buffer[POINT_BYTE_LEN]; EC_POINT_point2oct(group, A.point_ptr, POINT_CONVERSION_COMPRESSED, buffer, POINT_BYTE_LEN, nullptr); return PlainDelete(buffer, POINT_BYTE_LEN); } // read tag from i-th bucket j-th slot inline uint32_t ReadTag(const size_t bucket_index, const size_t slot_index) { const uint8_t* ptr = bucket_table.data() + bucket_index * bucket_byte_size; uint32_t tag; /* following code only works for little-endian */ switch(tag_bit_size){ case 8: tag = ptr[slot_index]; break; case 16: ptr += (slot_index << 1); tag = *((uint16_t*)ptr); break; case 32: tag = ((uint32_t*)ptr)[slot_index]; break; } return tag; } // write tag to pos(i,j) inline void WriteTag(const size_t bucket_index, const size_t slot_index, const uint32_t tag) { const uint8_t *ptr = bucket_table.data() + bucket_index * bucket_byte_size; /* following code only works for little-endian */ switch(tag_bit_size){ case 8: ((uint8_t *)ptr)[slot_index] = tag; break; case 16: ((uint16_t *)ptr)[slot_index] = tag; break; case 32: ((uint32_t *)ptr)[slot_index] = tag; break; } } inline bool FindTagInBucket(const size_t bucket_index, const uint32_t tag) { // caution: unaligned access & assuming little endian const uint8_t *ptr = bucket_table.data() + bucket_index * bucket_byte_size; uint64_t v; switch(tag_bit_size){ case 8: v = *(uint32_t*)ptr; return hasvalue8(v, tag); case 16: v = *(uint64_t*)ptr; return hasvalue16(v, tag); default: for (auto slot_index = 0; slot_index < slot_num; slot_index++) { if (ReadTag(bucket_index, slot_index) == tag) return true; } } return false; } inline bool DeleteTagFromBucket(const size_t bucket_index, const uint32_t tag, uint32_t &delete_slot_index) { for (auto slot_index = 0; slot_index < slot_num; slot_index++) { if (ReadTag(bucket_index, slot_index) == tag) { WriteTag(bucket_index, slot_index, 0); delete_slot_index = slot_index; return true; } } return false; } inline InsertToBucketStatus InsertTagToBucket(const size_t bucket_index, const uint32_t tag, const bool licence_to_kickout, uint32_t &kickout_tag) { for (auto slot_index = 0; slot_index < slot_num; slot_index++) { if (ReadTag(bucket_index, slot_index) == 0) { WriteTag(bucket_index, slot_index, tag); return SuccessAndNoKick; } } // licence_to_kickout = true indicates the element must be add to this bucket // licence_to_kickout = false indicates this is a new element, and can be add to the alternative bucket if (licence_to_kickout == true) { size_t r = rand() % slot_num; kickout_tag = ReadTag(bucket_index, r); WriteTag(bucket_index, r, tag); return SuccessButKick; } // here, we must have licence_to_kickout == false return FreshInsertFailure; } inline bool WriteObject(std::string file_name){ std::ofstream fout; fout.open(file_name, std::ios::binary); if(!fout){ std::cerr << file_name << " open error" << std::endl; return false; } fout.write(reinterpret_cast<char *>(&inserted_element_num), 8); fout.write(reinterpret_cast<char *>(&max_kick_count), 8); fout.write(reinterpret_cast<char *>(&slot_num), 8); fout.write(reinterpret_cast<char *>(&tag_bit_size), 8); fout.write(reinterpret_cast<char *>(&bucket_byte_size), 8); fout.write(reinterpret_cast<char *>(&bucket_num), 8); fout.write(reinterpret_cast<char *>(&victim.bucket_index), 4); fout.write(reinterpret_cast<char *>(&victim.tag), 4); fout.write(reinterpret_cast<char *>(&victim.used), 4); fout.write(reinterpret_cast<char *>(bucket_table.data()), bucket_table.size()); fout.close(); #ifdef DEBUG std::cout << "'" <<file_name << "' size = " << ObjectSize() << " bytes" << std::endl; #endif return true; } inline bool ReadObject(std::string file_name){ std::ifstream fin; fin.open(file_name, std::ios::binary); if(!fin){ std::cerr << file_name << " open error" << std::endl; return false; } fin.read(reinterpret_cast<char *>(&inserted_element_num), 8); fin.read(reinterpret_cast<char *>(&max_kick_count), 8); fin.read(reinterpret_cast<char *>(&slot_num), 8); fin.read(reinterpret_cast<char *>(&tag_bit_size), 8); fin.read(reinterpret_cast<char *>(&bucket_byte_size), 8); fin.read(reinterpret_cast<char *>(&bucket_num), 8); fin.read(reinterpret_cast<char *>(&victim.bucket_index), 4); fin.read(reinterpret_cast<char *>(&victim.tag), 4); fin.read(reinterpret_cast<char *>(&victim.used), 4); bucket_table.resize(bucket_byte_size * bucket_num, static_cast<uint8_t>(0x00)); fin.read(reinterpret_cast<char *>(bucket_table.data()), bucket_table.size()); return true; } inline bool WriteObject(char* buffer){ if(buffer == nullptr){ std::cerr << "allocate memory for cuckoo filter fails" << std::endl; return false; } memcpy(buffer, &inserted_element_num, 8); memcpy(buffer+8, &max_kick_count, 8); memcpy(buffer+16, &slot_num, 8); memcpy(buffer+24, &tag_bit_size, 8); memcpy(buffer+32, &bucket_byte_size, 8); memcpy(buffer+40, &bucket_num, 8); memcpy(buffer+48, &victim.bucket_index, 4); memcpy(buffer+52, &victim.tag, 4); memcpy(buffer+66, &victim.used, 4); memcpy(buffer+60, bucket_table.data(), bucket_table.size()); return true; } inline bool ReadObject(char* buffer){ if(buffer == nullptr){ std::cerr << "allocate memory for cuckoo filter fails" << std::endl; return false; } memcpy(&inserted_element_num, buffer, 8); memcpy(&max_kick_count, buffer+8, 8); memcpy(&slot_num, buffer+16, 8); memcpy(&tag_bit_size, buffer+24, 8); memcpy(&bucket_byte_size, buffer+32, 8); memcpy(&bucket_num, buffer+40, 8); memcpy(&victim.bucket_index, buffer+48, 4); memcpy(&victim.tag, buffer+52, 4); memcpy(&victim.used, buffer+56, 4); bucket_table.resize(bucket_byte_size * bucket_num, static_cast<uint8_t>(0x00)); memcpy(bucket_table.data(), buffer+60, bucket_table.size()); return true; } /* methods for providing stats */ void PrintInfo() { PrintSplitLine('-'); std::cout << "CuckooFilter Status:" << std::endl; std::cout << "inserted element num = " << inserted_element_num << std::endl; std::cout << "load factor = " << 1.0 * inserted_element_num / (bucket_num * slot_num) << std::endl; std::cout << "bucket num = " << bucket_num << std::endl; std::cout << "hashtable size = " << (bucket_table.size() >> 10) << " KB" << std::endl; std::cout << "bits per element = " << double(bucket_table.size()) * 8 / inserted_element_num << std::endl; PrintSplitLine('-'); } }; #endif
35.387097
129
0.610529
yuchen1024
ce82ed132259bd302bb4bbcde281dff59033a932
1,230
cpp
C++
URI Online Judge/1367 - Ajude!/uri-1367.cpp
MarcoRhayden/Uri-Online-Judge
92bed9fd0e5455686d54500f8e36588d6518f1b3
[ "MIT" ]
1
2019-03-29T11:52:44.000Z
2019-03-29T11:52:44.000Z
URI Online Judge/1367 - Ajude!/uri-1367.cpp
MarcoRhayden/Uri-Online-Judge
92bed9fd0e5455686d54500f8e36588d6518f1b3
[ "MIT" ]
null
null
null
URI Online Judge/1367 - Ajude!/uri-1367.cpp
MarcoRhayden/Uri-Online-Judge
92bed9fd0e5455686d54500f8e36588d6518f1b3
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; void resultData(vector<string> identifier, vector<int> timeSbm, vector<string> result, int sbm) { vector<string> crt, inctr; int s = 0; int p = 0; for (int i = 0; i < sbm; ++i) { if (result[i].compare("correct") == 0) { s++; p += timeSbm[i]; crt.push_back(identifier[i]); } else { inctr.push_back(identifier[i]); } } for (int j = 0; j < inctr.size(); ++j) { if (find(crt.begin(), crt.end(), inctr[j]) != crt.end()) { p += 20; } } cout << s << " " << p << endl; } int main(int argc, char *argv[]) { int sbm, t; string str; vector<string> identifier; vector<int> timeSbm; vector<string> result; while ( (cin >> sbm) && (sbm != 0) ) { identifier.clear(); timeSbm.clear(); result.clear(); for (int x = 0; x < sbm; ++x) { cin >> str; identifier.push_back(str); cin >> t; timeSbm.push_back(t); cin >> str; result.push_back(str); } resultData(identifier, timeSbm, result, sbm); } return(0); }
24.117647
66
0.469919
MarcoRhayden
ce91ae694d0a886127026a86bae29615f735482a
3,447
inl
C++
20191112/perm_gen/perm_gen_base.inl
Goreli/DKMCPPM
a12401f6df8e3c0281d2efec18dcf4e330712023
[ "MIT" ]
3
2019-11-12T01:55:33.000Z
2021-05-07T14:58:22.000Z
20191112/perm_gen/perm_gen_base.inl
Goreli/DKMCPPM
a12401f6df8e3c0281d2efec18dcf4e330712023
[ "MIT" ]
null
null
null
20191112/perm_gen/perm_gen_base.inl
Goreli/DKMCPPM
a12401f6df8e3c0281d2efec18dcf4e330712023
[ "MIT" ]
null
null
null
/* perm_gen_base.inl This header file defines the PermutationGeneratorBase template class. Copyright(c) 2019 David Krikheli Modification history: 14/Nov/2019 - David Krikheli created the module. */ #include <algorithm> namespace dk { template <class T> PermutationGeneratorBase<T>::PermutationGeneratorBase() : bExcludeDups_{ false }, bRandom_{ false } { try { auto iSeed = std::random_device{}(); _randNumGen.seed(iSeed); } catch (...) { auto iSeed = std::chrono::system_clock::now().time_since_epoch().count(); _randNumGen.seed(iSeed); } } template <class T> PermutationGeneratorBase<T>::~PermutationGeneratorBase() { } template <class T> void PermutationGeneratorBase<T>::generate(const std::vector<T>& symbolPool, bool bExcludeDups, size_t iRandPermAlgId) { permutation_.resize(symbolPool.size()); symbolPool_ = symbolPool; switch (iRandPermAlgId) { case 0: bExcludeDups_ = bExcludeDups; bRandom_ = false; generate_(0); break; case 1: bExcludeDups_ = bExcludeDups; bRandom_ = true; generate_(0); break; case 2: // bExcludeDups_ and bRandom_ have no effect on generate_R2_R3_(....). generate_R2_R3_(0); break; case 3: // bExcludeDups_ and bRandom_ have no effect on generate_R2_R3_(....). generate_R2_R3_(1); break; } } template <class T> void PermutationGeneratorBase<T>::generate_(size_t iPos) { size_t vocSize = symbolPool_.size(); std::uniform_int_distribution<size_t> dist(0, vocSize-1); size_t inx{ 0 }; for (size_t _inx_ = 0; _inx_ < symbolPool_.size(); _inx_++) { if(bRandom_) inx = dist(_randNumGen); else { inx = _inx_; if (bExcludeDups_) { auto it = symbolPool_.begin() + inx; auto findIt = std::find(symbolPool_.begin(), it, *it); if (findIt != it) continue; } } permutation_[iPos] = symbolPool_[inx]; // If the call stack has hit the bottom of recursion tree then // process the permutation and move on to the next recursion cycle. // Otherwise just keep drilling down. if (vocSize == 1) process_(permutation_); else { symbolPool_.erase(symbolPool_.begin() + inx); generate_(iPos + 1); symbolPool_.insert(symbolPool_.begin() + inx, permutation_[iPos]); // The following piece of code ran perfectly ok when compiled with clang++ // on the Ubuntu subsystem of Windows 10. It crashed when compiled with // VS 2019 on Windows 10. /* it = symbolPool_.erase(it); generate_nodups_(iPos + 1); symbolPool_.insert(it, permutation_[iPos]); */ } } } template <class T> void PermutationGeneratorBase<T>::generate_l(const std::vector<T>& symbolPool, bool bAscending) { permutation_ = symbolPool; if (bAscending) do process_(permutation_); while (std::next_permutation(permutation_.begin(), permutation_.end())); else do process_(permutation_); while (std::prev_permutation(permutation_.begin(), permutation_.end())); } template <class T> void PermutationGeneratorBase<T>::generate_R2_R3_(size_t iOffset) { size_t vocSize = symbolPool_.size(); permutation_ = symbolPool_; size_t j{ 0 }; while (true) { for (size_t i = 0; i < vocSize - 1; i++) { std::uniform_int_distribution<size_t> dist(i + iOffset, vocSize - 1); j = dist(_randNumGen); iter_swap(permutation_.begin() + i, permutation_.begin() + j); } process_(permutation_); } } }; // namespace dk
27.576
121
0.680012
Goreli
ce91e6b161b565ceae74631230feb116cb1681a1
3,515
cpp
C++
src/libsocket/event.cpp
publiqnet/belt.pp
837112652885284cd0f8245b1c9cf31dcfad17e1
[ "MIT" ]
4
2017-11-24T09:47:18.000Z
2019-02-18T14:43:05.000Z
src/libsocket/event.cpp
publiqnet/belt.pp
837112652885284cd0f8245b1c9cf31dcfad17e1
[ "MIT" ]
1
2018-04-11T12:42:25.000Z
2018-04-11T12:42:25.000Z
src/libsocket/event.cpp
publiqnet/belt.pp
837112652885284cd0f8245b1c9cf31dcfad17e1
[ "MIT" ]
2
2019-01-10T14:11:28.000Z
2021-05-31T11:14:46.000Z
#include "event.hpp" #include <mutex> #include <unordered_set> namespace beltpp_socket_impl { using namespace beltpp; using std::unordered_set; event_handler_ex::event_handler_ex() : m_impl() { } event_handler_ex::~event_handler_ex() = default; event_handler_ex::wait_result event_handler_ex::wait(std::unordered_set<event_item const*>& set_items) { set_items.clear(); m_impl.m_event_item_ids.clear(); for (auto& event_item_in_set : m_impl.m_event_items) { event_item_in_set->prepare_wait(); } if (m_impl.m_timer_helper.expired()) { m_impl.m_timer_helper.update(); return event_handler_ex::timer_out; } std::unordered_set<uint64_t> set_ids; { std::lock_guard<std::mutex> lock(m_impl.m_mutex); auto it = m_impl.sync_eh_ids.begin(); if (it != m_impl.sync_eh_ids.end()) { set_ids.insert(*it); m_impl.sync_eh_ids.erase(it); } } bool on_demand = false; if (set_ids.empty()) set_ids = m_impl.m_poll_master.wait(m_impl.m_timer_helper, on_demand); std::lock_guard<std::mutex> lock(m_impl.m_mutex); auto it = set_ids.begin(); while (it != set_ids.end()) { auto id = *it; bool found = false; for (auto const& ids_item : m_impl.m_ids) { if (ids_item.valid_index(id)) { auto& ref_item = ids_item[id]; event_item* pitem = ref_item.m_pitem; set_items.insert(pitem); found = true; auto& item = m_impl.m_event_item_ids[pitem]; item.insert(ref_item.m_item_id); break; } } if (false == found) it = set_ids.erase(it); else ++it; } bool on_timer = m_impl.m_timer_helper.expired(); bool on_event = (false == set_ids.empty()); if (on_timer) m_impl.m_timer_helper.update(); if (false == on_demand && false == on_timer && false == on_event) return event_handler_ex::nothing; if (on_demand && false == on_timer && false == on_event) return event_handler_ex::on_demand; if (false == on_demand && on_timer && false == on_event) return event_handler_ex::timer_out; if (false == on_demand && false == on_timer && on_event) return event_handler_ex::event; if (on_demand && on_timer && false == on_event) return event_handler_ex::on_demand_and_timer_out; if (on_demand && false == on_timer && on_event) return event_handler_ex::on_demand_and_event; if (false == on_demand && on_timer && on_event) return event_handler_ex::timer_out_and_event; /*if (on_demand && on_timer && on_event)*/ return event_handler_ex::on_demand_and_timer_out_and_event; } std::unordered_set<uint64_t> event_handler_ex::waited(event_item& ev_it) const { return m_impl.m_event_item_ids.at(&ev_it); } void event_handler_ex::wake() { m_impl.m_poll_master.wake(); } void event_handler_ex::set_timer(std::chrono::steady_clock::duration const& period) { m_impl.m_timer_helper.set(period); } void event_handler_ex::add(event_item& ev_it) { m_impl.m_event_items.insert(&ev_it); } void event_handler_ex::remove(event_item& ev_it) { m_impl.m_event_items.erase(&ev_it); } }// beltpp_socket_impl
23.75
102
0.609388
publiqnet
ce955d4bcc6bd15db19b0f8269338eda4c626d55
2,310
cpp
C++
src/iksdl/Renderer.cpp
InternationalKoder/iksdl
066a60b405bab5310a500132b0bd4d82c6476f24
[ "Zlib" ]
null
null
null
src/iksdl/Renderer.cpp
InternationalKoder/iksdl
066a60b405bab5310a500132b0bd4d82c6476f24
[ "Zlib" ]
null
null
null
src/iksdl/Renderer.cpp
InternationalKoder/iksdl
066a60b405bab5310a500132b0bd4d82c6476f24
[ "Zlib" ]
null
null
null
/* * IKSDL - C++ wrapper for SDL * Copyright (C) 2021 InternationalKoder * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. * */ #include "iksdl/Renderer.hpp" #include "iksdl/SdlException.hpp" #include <SDL.h> #include <string> namespace iksdl { Renderer::Renderer(SDL_Window& window, const RendererOptions& options) : m_renderer(nullptr) { m_renderer = SDL_CreateRenderer(&window, -1, options.m_sdlFlags); if(m_renderer == nullptr) throw SdlException(std::string(CREATE_RENDERER_ERROR) + SDL_GetError()); } Renderer::Renderer(Renderer&& other) : m_renderer(std::exchange(other.m_renderer, nullptr)), m_viewport(std::move(other.m_viewport)) {} Renderer::~Renderer() { SDL_DestroyRenderer(m_renderer); } Renderer& Renderer::operator=(Renderer&& other) { if(this == &other) return *this; SDL_DestroyRenderer(m_renderer); m_renderer = std::exchange(other.m_renderer, nullptr); m_viewport = std::move(other.m_viewport); return *this; } void Renderer::clear(const Color& clearColor) const { SDL_SetRenderDrawColor(m_renderer, clearColor.getRed(), clearColor.getGreen(), clearColor.getBlue(), clearColor.getAlpha()); SDL_RenderClear(m_renderer); } void Renderer::setViewport(const Recti& viewport) { m_viewport = { .x = viewport.getX(), .y = viewport.getY(), .w = viewport.getWidth(), .h = viewport.getHeight() }; SDL_RenderSetViewport(m_renderer, &m_viewport); } }
30.8
82
0.709524
InternationalKoder
ce957028c1714864476a0912d2af3718adf7e764
1,203
cpp
C++
src/phase_cong/ipermute.cpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
1
2020-06-12T13:30:56.000Z
2020-06-12T13:30:56.000Z
src/phase_cong/ipermute.cpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
src/phase_cong/ipermute.cpp
waterben/LineExtraction
d247de45417a1512a3bf5d0ffcd630d40ffb8798
[ "MIT" ]
null
null
null
// // Academic License - for use in teaching, academic research, and meeting // course requirements at degree granting institutions only. Not for // government, commercial, or other organizational use. // File: ipermute.cpp // // MATLAB Coder version : 3.0 // C/C++ source code generated on : 27-Jan-2016 06:44:05 // // Include Files #include "rt_nonfinite.h" #include "logGaborFilter.h" #include "phasecong.h" #include "ipermute.h" #include "logGaborFilter_emxutil.h" // Function Definitions // // Arguments : const emxArray_creal_T *b // emxArray_creal_T *a // Return Type : void // void ipermute(const emxArray_creal_T *b, emxArray_creal_T *a) { int i6; int loop_ub; int b_loop_ub; int i7; i6 = a->size[0] * a->size[1]; a->size[0] = b->size[1]; a->size[1] = b->size[0]; emxEnsureCapacity((emxArray__common *)a, i6, (int)sizeof(creal_T)); loop_ub = b->size[0]; for (i6 = 0; i6 < loop_ub; i6++) { b_loop_ub = b->size[1]; for (i7 = 0; i7 < b_loop_ub; i7++) { a->data[i7 + a->size[0] * i6] = b->data[i6 + b->size[0] * i7]; } } } // // File trailer for ipermute.cpp // // [EOF] //
24.55102
74
0.600998
waterben
ce95ef89b50c5889cf42c95d259cca39f19c101a
1,394
cpp
C++
platform-io/lib/zeromq/src/zeromq/ZeroMQWriter.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
2
2020-01-13T07:32:50.000Z
2020-03-03T14:32:25.000Z
platform-io/lib/zeromq/src/zeromq/ZeroMQWriter.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
16
2019-06-16T05:51:02.000Z
2020-02-03T01:59:23.000Z
platform-io/lib/zeromq/src/zeromq/ZeroMQWriter.cpp
darvik80/rover-cpp
8da7b7f07efe7096843ae17536603277f55debea
[ "Apache-2.0" ]
1
2020-03-03T14:32:27.000Z
2020-03-03T14:32:27.000Z
// // Created by Ivan Kishchenko on 05.09.2021. // #include "ZeroMQWriter.h" #include "ZeroMQFlag.h" std::error_code ZeroMQWriter::writeData(const void *data, std::size_t size) { write((const char*)data, size); if (!(*this)) { return std::make_error_code(std::errc::message_size); } return {}; } std::error_code ZeroMQWriter::writeFlag(uint8_t flag) { return writeData(&flag, sizeof(uint8_t)); } std::error_code ZeroMQWriter::writeFlagAndSize(uint8_t flags, uint64_t size) { if (size > UINT8_MAX) { flags |= flag_long; } if (auto err = writeFlag(flags)) { return err; } if (size > UINT8_MAX) { if (auto err = writeSize((uint64_t) size)) { return err; } } else { if (auto err = writeSize((uint8_t) size)) { return err; } } return {}; } std::error_code ZeroMQWriter::writeSize(uint8_t size) { return writeData(&size, sizeof(uint8_t)); } std::error_code ZeroMQWriter::writeSize(uint32_t size) { size = ZeroMQUtils::swapEndian(size); return writeData(&size, sizeof(uint32_t)); } std::error_code ZeroMQWriter::writeSize(uint64_t size) { size = ZeroMQUtils::swapEndian(size); return writeData(&size, sizeof(uint64_t)); } std::error_code ZeroMQWriter::writeString(const std::string& str) { return writeData(str.data(), str.size()); }
23.627119
78
0.637016
darvik80
ce96d8634af00facb457d9d8755a1fd50f15cb05
2,575
cpp
C++
aws-cpp-sdk-awstransfer/source/model/WorkflowStep.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-awstransfer/source/model/WorkflowStep.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-awstransfer/source/model/WorkflowStep.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/awstransfer/model/WorkflowStep.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace Transfer { namespace Model { WorkflowStep::WorkflowStep() : m_type(WorkflowStepType::NOT_SET), m_typeHasBeenSet(false), m_copyStepDetailsHasBeenSet(false), m_customStepDetailsHasBeenSet(false), m_deleteStepDetailsHasBeenSet(false), m_tagStepDetailsHasBeenSet(false) { } WorkflowStep::WorkflowStep(JsonView jsonValue) : m_type(WorkflowStepType::NOT_SET), m_typeHasBeenSet(false), m_copyStepDetailsHasBeenSet(false), m_customStepDetailsHasBeenSet(false), m_deleteStepDetailsHasBeenSet(false), m_tagStepDetailsHasBeenSet(false) { *this = jsonValue; } WorkflowStep& WorkflowStep::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Type")) { m_type = WorkflowStepTypeMapper::GetWorkflowStepTypeForName(jsonValue.GetString("Type")); m_typeHasBeenSet = true; } if(jsonValue.ValueExists("CopyStepDetails")) { m_copyStepDetails = jsonValue.GetObject("CopyStepDetails"); m_copyStepDetailsHasBeenSet = true; } if(jsonValue.ValueExists("CustomStepDetails")) { m_customStepDetails = jsonValue.GetObject("CustomStepDetails"); m_customStepDetailsHasBeenSet = true; } if(jsonValue.ValueExists("DeleteStepDetails")) { m_deleteStepDetails = jsonValue.GetObject("DeleteStepDetails"); m_deleteStepDetailsHasBeenSet = true; } if(jsonValue.ValueExists("TagStepDetails")) { m_tagStepDetails = jsonValue.GetObject("TagStepDetails"); m_tagStepDetailsHasBeenSet = true; } return *this; } JsonValue WorkflowStep::Jsonize() const { JsonValue payload; if(m_typeHasBeenSet) { payload.WithString("Type", WorkflowStepTypeMapper::GetNameForWorkflowStepType(m_type)); } if(m_copyStepDetailsHasBeenSet) { payload.WithObject("CopyStepDetails", m_copyStepDetails.Jsonize()); } if(m_customStepDetailsHasBeenSet) { payload.WithObject("CustomStepDetails", m_customStepDetails.Jsonize()); } if(m_deleteStepDetailsHasBeenSet) { payload.WithObject("DeleteStepDetails", m_deleteStepDetails.Jsonize()); } if(m_tagStepDetailsHasBeenSet) { payload.WithObject("TagStepDetails", m_tagStepDetails.Jsonize()); } return payload; } } // namespace Model } // namespace Transfer } // namespace Aws
21.280992
93
0.744078
perfectrecall
ce97384dc5744247b8b1dab531cfa7e46c727497
1,079
cc
C++
mime1836_sigmaic256_bg00/species_advance/advance_p_efield.cc
laofei177/vpic_reconnection_tutorial
7ba13578fe34615a118f3d98446ea94ad2b3d188
[ "MIT" ]
1
2021-03-31T11:44:29.000Z
2021-03-31T11:44:29.000Z
mime1836_sigmaic256_bg00/species_advance/advance_p_efield.cc
xiaocanli/vpic_reconnection_tutorial
05ff2372404717a548066f4a5fd8bbeb1407b30a
[ "MIT" ]
null
null
null
mime1836_sigmaic256_bg00/species_advance/advance_p_efield.cc
xiaocanli/vpic_reconnection_tutorial
05ff2372404717a548066f4a5fd8bbeb1407b30a
[ "MIT" ]
1
2021-03-31T11:48:43.000Z
2021-03-31T11:48:43.000Z
/* #define IN_spa */ #include "species_advance_efield.h" //----------------------------------------------------------------------------// // Top level function to select and call particle advance function using the // desired particle advance abstraction. Currently, the only abstraction // available is the pipeline abstraction. Particles advanced by this function // experience only part of electric field and have no feedback to the fields. // efield_type=0: without parallel electric field // efield_type=1: without the y-component of parallel electric field // efield_type=2: without electric field in regions where |E|>|B| //----------------------------------------------------------------------------// void advance_p_efield( species_t * RESTRICT sp, accumulator_array_t * RESTRICT aa, const interpolator_array_t * RESTRICT ia, const int efield_type ) { // Once more options are available, this should be conditionally executed // based on user choice. advance_p_efield_pipeline( sp, aa, ia, efield_type ); }
43.16
80
0.623726
laofei177
ce9965984c806989b9fa18c73cf2a5cdaf84e800
2,297
cpp
C++
demo/saxpy/scalar/saxpy_scalar.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
34
2017-05-19T18:10:17.000Z
2022-01-04T02:18:13.000Z
demo/saxpy/scalar/saxpy_scalar.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
null
null
null
demo/saxpy/scalar/saxpy_scalar.cpp
psiha/nt2
5e829807f6b57b339ca1be918a6b60a2507c54d0
[ "BSL-1.0" ]
7
2017-12-02T12:59:17.000Z
2021-07-31T12:46:14.000Z
//============================================================================== // Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II // Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI // Copyright 2012 - 2014 MetaScale SAS // // Distributed under the Boost Software License, Version 1.0. // See accompanying file LICENSE.txt or copy at // http://www.boost.org/LICENSE_1_0.txt //============================================================================== #include <boost/fusion/include/at.hpp> #include <vector> #include <nt2/sdk/bench/benchmark.hpp> #include <nt2/sdk/bench/metric/gflops.hpp> #include <nt2/sdk/bench/protocol/max_duration.hpp> #include <nt2/sdk/bench/setup/geometric.hpp> #include <nt2/sdk/bench/setup/constant.hpp> #include <nt2/sdk/bench/setup/combination.hpp> #include <nt2/sdk/bench/stats/median.hpp> using namespace nt2::bench; using namespace nt2; template<typename T> struct axpy_scalar { typedef void experiment_is_immutable; template<typename Setup> axpy_scalar(Setup const& s) : size_(boost::fusion::at_c<0>(s)) , alpha(boost::fusion::at_c<1>(s)) { X.resize(size_); Y.resize(size_); for(std::size_t i = 0; i<size_; ++i) X[i] = Y[i] = T(i); } void operator()() { for(std::size_t i = 0; i<size_; i++) Y[i] = Y[i] + alpha*(X[i]); } friend std::ostream& operator<<(std::ostream& os, axpy_scalar<T> const& p) { return os << "(" << p.size() << ")"; } std::size_t size() const { return size_; } double flops() const { return 2.*size_; } private: std::size_t size_; T alpha; std::vector<T> X, Y; }; NT2_REGISTER_BENCHMARK_TPL( axpy_scalar, NT2_SIMD_REAL_TYPES ) { std::size_t size_min = args("size_min", 16); std::size_t size_max = args("size_max", 4096); std::size_t size_step = args("size_step", 2); T alpha = args("alpha", 1.); run_during_with< axpy_scalar<T> > ( 1. , and_( geometric(size_min,size_max,size_step) , constant(alpha) ) , gflops<stats::median_>() ); }
31.902778
82
0.538964
psiha
ce9bc8e8548eae2f6a3c556434c93481db45e62e
15,716
cpp
C++
src/hash.cpp
eval-apply/digamma
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
[ "BSD-2-Clause" ]
null
null
null
src/hash.cpp
eval-apply/digamma
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
[ "BSD-2-Clause" ]
null
null
null
src/hash.cpp
eval-apply/digamma
fbab05bdcb7019ff005ee84ed8f737ff3d44b38e
[ "BSD-2-Clause" ]
null
null
null
// Copyright (c) 2004-2022 Yoshikatsu Fujita / LittleWing Company Limited. // See LICENSE file for terms and conditions of use. #include "core.h" #include "hash.h" #include "arith.h" #include "equiv.h" #include "utf8.h" #define EQUAL_HASH_DEPTH_LIMIT 100 uint32_t address_hash1(void* adrs, uint32_t bound) { return (((uintptr_t)adrs >> 3) * 2654435761U + ((uintptr_t)adrs & 7)) % bound; } uint32_t address_hash2(void* adrs, uint32_t bound) { uint32_t hash = (((uintptr_t)adrs >> 3) * 13845163U) % bound; return hash + (hash == 0); } uint32_t string_hash1(const char* str, uint32_t bound) { int hash = 107; while (*str) hash = hash * 32 - hash + (*str++); return hash % bound; } uint32_t string_hash2(const char* str, uint32_t bound) { int hash = 131; while (*str) hash = hash * 4 + hash + (*str++); hash = hash % bound; return hash + (hash == 0); } static uint32_t eqv_hash1(scm_obj_t obj, uint32_t bound) { if (CELLP(obj)) { if (FLONUMP(obj)) { scm_flonum_t flonum = (scm_flonum_t)obj; assert(sizeof(flonum->value) == 8); uint32_t* datum = (uint32_t*)(&flonum->value); return (datum[0] + datum[1] * 5) % bound; } if (BIGNUMP(obj)) { scm_bignum_t bignum = (scm_bignum_t)obj; int count = bn_get_count(bignum); uint32_t hash = bn_get_sign(bignum) + count * 5; if (sizeof(digit_t) == sizeof(uint32_t)) { for (int i = 0; i < count; i++) hash = hash * 5 + bignum->elts[i]; } else { for (int i = 0; i < count; i++) { hash = hash * 5 + (bignum->elts[i] & 0xffffffff) + ((uint64_t)bignum->elts[i] >> 32); } } return hash % bound; } if (RATIONALP(obj)) { scm_rational_t rational = (scm_rational_t)obj; uint32_t hash; hash = eqv_hash(rational->nume, INT32_MAX) * 5 - eqv_hash(rational->deno, INT32_MAX); return hash % bound; } if (COMPLEXP(obj)) { scm_complex_t complex = (scm_complex_t)obj; uint32_t hash; hash = eqv_hash(complex->real, INT32_MAX) * 5 + eqv_hash(complex->imag, INT32_MAX); return hash % bound; } } return address_hash1(obj, bound); } static uint32_t eqv_hash2(scm_obj_t obj, uint32_t bound) { if (CELLP(obj)) { if (FLONUMP(obj)) { scm_flonum_t flonum = (scm_flonum_t)obj; assert(sizeof(flonum->value) == 8); uint32_t* datum = (uint32_t*)(&flonum->value); uint32_t hash = (datum[0] + datum[1] * 3) % bound; return hash + (hash == 0); } if (BIGNUMP(obj)) { scm_bignum_t bignum = (scm_bignum_t)obj; int count = bn_get_count(bignum); uint32_t hash = bn_get_sign(bignum) + count * 3; if (sizeof(digit_t) == sizeof(uint32_t)) { for (int i = 0; i < count; i++) hash = hash * 3 + bignum->elts[i]; } else { for (int i = 0; i < count; i++) { hash = hash * 3 + (bignum->elts[i] & 0xffffffff) + ((uint64_t)bignum->elts[i] >> 32); } } hash = hash % bound; return hash + (hash == 0); } if (RATIONALP(obj)) { scm_rational_t rational = (scm_rational_t)obj; uint32_t hash = eqv_hash2(rational->nume, INT32_MAX) * 3 - eqv_hash2(rational->deno, INT32_MAX); hash = hash % bound; return hash + (hash == 0); } if (COMPLEXP(obj)) { scm_complex_t complex = (scm_complex_t)obj; uint32_t hash = eqv_hash2(complex->real, INT32_MAX) * 3 + eqv_hash2(complex->imag, INT32_MAX); hash = hash % bound; return hash + (hash == 0); } } return address_hash2(obj, bound); } static uint32_t obj_hash(scm_obj_t obj, int depth) { if (depth > EQUAL_HASH_DEPTH_LIMIT) return 1; if (CELLP(obj)) { if (PAIRP(obj)) { uint32_t hash1 = obj_hash(CAR(obj), depth + 1); uint32_t hash2 = obj_hash(CDR(obj), depth + 1); return (hash1 + hash2 * 64 - hash2); } if (VECTORP(obj)) { scm_vector_t vector = (scm_vector_t)obj; int n = vector->count; scm_obj_t* elts = vector->elts; uint32_t hash = 1; for (int i = 0; i < n; i++) { hash = hash * 32 - hash + obj_hash(elts[i], depth + 1); } return hash; } if (SYMBOLP(obj)) return symbol_hash((scm_symbol_t)obj, INT32_MAX); if (STRINGP(obj)) return string_hash((scm_string_t)obj, INT32_MAX); if (number_pred(obj)) return eqv_hash(obj, INT32_MAX); return HDR_TC(HDR(obj)); } return address_hash1(obj, INT32_MAX); } uint32_t eqv_hash(scm_obj_t obj, uint32_t bound) { return eqv_hash1(obj, bound); } uint32_t equal_hash(scm_obj_t obj, uint32_t bound) { return obj_hash(obj, 0) % bound; } uint32_t string_hash(scm_obj_t obj, uint32_t bound) { assert(STRINGP(obj)); scm_string_t string = (scm_string_t)obj; return string_hash1(string->name, bound); } uint32_t symbol_hash(scm_obj_t obj, uint32_t bound) { assert(SYMBOLP(obj)); scm_symbol_t symbol = (scm_symbol_t)obj; return string_hash2(symbol->name, bound); } bool eqv_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return eqv_pred(obj1, obj2); } bool equal_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return r5rs_equal_pred(obj1, obj2); } bool string_hash_equiv(scm_obj_t obj1, scm_obj_t obj2) { return string_eq_pred(obj1, obj2); } int lookup_mutable_hashtable_size(int n) { static const int primes[] = {7, 13, 29, 59, 113, 223, 431, 821, 1567, 2999, 5701, 10837, 20593, 39133, 74353, 141277, 268439, 510047, 969097, 1841291, 3498457, 5247701, 7871573, 11807381, 17711087, 26566649, 39849977, 59774983, 89662483, 134493731, 201740597, 302610937, 453916423, 680874641, 1021311983, 1531968019, 2147483647}; for (int i = 0; i < array_sizeof(primes); i++) { if (primes[i] > n) return primes[i]; } fatal("%s:%u internal error: hashtable too big", __FILE__, __LINE__); } int lookup_immutable_hashtable_size(int n) { static const int primes[] = { 7, 11, 13, 17, 23, 29, 37, 47, 59, 71, 89, 107, 131, 157, 191, 229, 277, 337, 409, 491, 593, 719, 863, 1039, 1249, 1499, 1801, 2161, 2593, 3119, 3761, 4513, 5417, 6521, 7829, 9397, 11279, 13537, 16249, 19501, 23417, 28109, 33739, 40487, 48589, 58309, 69991, 84011, 100823, 120997, 145207, 174257, 209123, 250949, 301141, 361373, 433651, 520381, 624467, 749383, 899263, 1079123, 1294957, 1553971, 1864769, 2237743, 2685301, 3222379, 3866857, 4640231, 5568287, 6681947, 8018347, 9622021, 11546449, 13855747, 16626941, 19952329, 23942797, 28731359, 34477637, 41373173, 49647809, 59577379, 71492873, 85791451, 102949741, 123539747, 148247713, 177897311, 213476789, 256172149, 307406587, 368887919, 442665511, 531198691, 637438433, 764926171, 917911471, 1101493807, 1321792573, 1586151131, 1903381357, 2147483647}; for (int i = 0; i < array_sizeof(primes); i++) { if (primes[i] > n) return primes[i]; } fatal("%s:%u internal error: hashtable too big", __FILE__, __LINE__); } static int put_eq_hashtable(scm_hashtable_t ht, scm_obj_t key, scm_obj_t value) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (tag == scm_hash_deleted) { ht_datum->live++; goto found; } if (tag == key) goto found; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = key; ht_datum->elts[index + nsize] = value; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } static scm_obj_t get_eq_hashtable(scm_hashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key) return ht_datum->elts[index + nsize]; if (tag == scm_hash_free) return scm_undef; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } static int remove_eq_hashtable(scm_hashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->elts[index + nsize] = scm_unspecified; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } if (tag == scm_hash_free) return 0; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } scm_obj_t lookup_weakhashtable(scm_weakhashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) return scm_undef; if (entry != scm_hash_deleted) { assert(WEAKMAPPINGP(entry)); scm_weakmapping_t wmap = (scm_weakmapping_t)entry; if (wmap->key == scm_false) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; } else { if (wmap->key == key) return wmap; } } index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int remove_weakhashtable(scm_weakhashtable_t ht, scm_obj_t key) { ht->lock.verify_locked(); weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) return 0; if (entry != scm_hash_deleted) { assert(WEAKMAPPINGP(entry)); scm_weakmapping_t wmap = (scm_weakmapping_t)entry; if (wmap->key == scm_false) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; } else if (wmap->key == key) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } } index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int put_weakhashtable(scm_weakhashtable_t ht, scm_weakmapping_t wmap) { ht->lock.verify_locked(); scm_obj_t key = wmap->key; weakhashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = address_hash1(key, nsize); int hash2 = address_hash2(key, nsize); int index = hash1; do { scm_obj_t entry = ht_datum->elts[index]; if (entry == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (entry == scm_hash_deleted) { ht_datum->live++; goto found; } assert(WEAKMAPPINGP(entry)); assert(((scm_weakmapping_t)entry)->key != key); // verify no duplicate entry index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = wmap; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_SPARSE_THRESHOLD(nsize)) return lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)); if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } static uint32_t simple_hash2(uint32_t hash, int nsize) { int dist = nsize >> 6; dist = (dist < 8) ? ((nsize > 8) ? 8 : 1) : dist; int hash2 = dist - (hash % dist); assert(hash2 && hash2 < nsize); return hash2; } int put_hashtable(scm_hashtable_t ht, scm_obj_t key, scm_obj_t value) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return put_eq_hashtable(ht, key, value); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == scm_hash_free) { ht_datum->live++; ht_datum->used++; goto found; } if (tag == scm_hash_deleted) { ht_datum->live++; goto found; } if (tag == key || (*ht->equiv)(tag, key)) goto found; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); found: ht_datum->elts[index] = key; ht_datum->elts[index + nsize] = value; if (ht_datum->used < HASH_BUSY_THRESHOLD(nsize)) return 0; if (ht_datum->live < HASH_DENSE_THRESHOLD(nsize)) return nsize; return lookup_mutable_hashtable_size(nsize); } scm_obj_t get_hashtable(scm_hashtable_t ht, scm_obj_t key) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return get_eq_hashtable(ht, key); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key || (*ht->equiv)(tag, key)) return ht_datum->elts[index + nsize]; if (tag == scm_hash_free) return scm_undef; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); } int remove_hashtable(scm_hashtable_t ht, scm_obj_t key) { if (ht->type == SCM_HASHTABLE_TYPE_EQ) return remove_eq_hashtable(ht, key); ht->lock.verify_locked(); hashtable_rec_t* ht_datum = ht->datum; assert(ht_datum); int nsize = ht_datum->capacity; int hash1 = (*ht->hash)(key, nsize); int hash2 = simple_hash2(hash1, nsize); int index = hash1; do { scm_obj_t tag = ht_datum->elts[index]; if (tag == key || (*ht->equiv)(tag, key)) { ht_datum->elts[index] = scm_hash_deleted; ht_datum->elts[index + nsize] = scm_unspecified; ht_datum->live--; return ht_datum->live < HASH_SPARSE_THRESHOLD(nsize) ? lookup_mutable_hashtable_size(HASH_MUTABLE_SIZE(ht_datum->live)) : 0; } if (tag == scm_hash_free) return 0; index += hash2; if (index >= nsize) index -= nsize; } while (index != hash1); fatal("%s:%u hash table full.", __FILE__, __LINE__); }
36.548837
141
0.627704
eval-apply
ce9f8023b431fcf053b7b590b0c8ea901848a5dd
30,969
cpp
C++
examples/test/main.cpp
pkholland/anon
c9fbe49e505eb4d100da58058e9f51508b06635d
[ "MIT" ]
1
2015-03-12T01:05:52.000Z
2015-03-12T01:05:52.000Z
examples/test/main.cpp
pkholland/anon
c9fbe49e505eb4d100da58058e9f51508b06635d
[ "MIT" ]
null
null
null
examples/test/main.cpp
pkholland/anon
c9fbe49e505eb4d100da58058e9f51508b06635d
[ "MIT" ]
null
null
null
/* Copyright (c) 2015 Anon authors, see AUTHORS file. 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 <stdio.h> #include <thread> #include <arpa/inet.h> #include <netdb.h> #include "log.h" #include "udp_dispatch.h" #include "big_id_serial.h" #include "big_id_crypto.h" #include "fiber.h" #include "tcp_server.h" #include "tcp_client.h" #include "dns_cache.h" #include "lock_checker.h" #include "time_utils.h" #include "dns_lookup.h" #include "http_server.h" #include "tls_pipe.h" #include "epc_test.h" #include "mcdc.h" //#include "http2_handler.h" //#include "http2_test.h" class my_udp : public udp_dispatch { public: my_udp(int port) : udp_dispatch(port, false, true) { } virtual void recv_msg(const unsigned char *msg, ssize_t len, const struct sockaddr_storage *sockaddr, socklen_t sockaddr_len) { anon_log("received msg of: \"" << (char *)msg << "\""); //std::this_thread::sleep_for(std::chrono::milliseconds( 0 )); } }; extern "C" int main(int argc, char **argv) { anon_log("application start"); if (!init_big_id_crypto()) { anon_log_error("init_big_id_crypto failed"); return 1; } uint8_t big_id_data[32] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31}; big_id id(big_id_data); anon_log("big id: (short) " << id); anon_log("big id: (long) " << ldisp(id)); anon_log("random big id: " << ldisp(big_rand_id())); anon_log("sha256 id: " << ldisp(sha256_id("hello world\n", strlen("hello world\n")))); uint8_t small_id_data[20] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19}; small_id sid(small_id_data); anon_log("small id: (short) " << sid); anon_log("small id: (long) " << ldisp(sid)); anon_log("small random id: " << ldisp(small_rand_id())); anon_log("sha1 id: " << ldisp(sha1_id("hello world\n", strlen("hello world\n")))); { int udp_port = 8617; int tcp_port = 8618; int http_port = 8619; io_dispatch::start(std::thread::hardware_concurrency(), false); dns_cache::initialize(); dns_lookup::start_service(); fiber::initialize(); epc_test_init(); auto m_udp = std::make_shared<my_udp>(udp_port); http_server my_http; #if 0 http2_handler my_http2(my_http,[](std::unique_ptr<fiber_pipe>&& read_pipe, http_server::pipe_t& write_pipe, uint32_t stream_id){ anon_log("started new stream " << stream_id << ", should be reading from fd " << read_pipe->get_fd() << ", but am closing it!"); }); #endif my_http.start(http_port, [](http_server::pipe_t &pipe, const http_request &request) { http_response response; response.add_header("content-type", "text/plain"); response << "hello browser!\n\n"; response << "src addr: " << *request.src_addr << "\n"; response << "http version major: " << request.http_major << "\n"; response << "http version minor: " << request.http_minor << "\n"; response << "method: " << request.method_str() << "\n\n"; response << "-- headers --\n"; for (auto it = request.headers.headers.begin(); it != request.headers.headers.end(); it++) response << " " << it->first << ": " << it->second << "\n"; response << "\n"; response << "url path: " << request.get_url_field(UF_PATH) << "\n"; response << "url query: " << request.get_url_field(UF_QUERY) << "\n"; pipe.respond(response); }); int num_pipe_pairs = 400; int num_read_writes = 10000; while (true) { // read a command from stdin char msgBuff[256]; auto bytes_read = read(0 /*stdin*/, &msgBuff[0], sizeof(msgBuff)); if (bytes_read > 1) { // truncate the return char to a 0 so we can compare to strings msgBuff[bytes_read - 1] = 0; if (!strcmp(&msgBuff[0], "q")) { anon_log("quitting"); break; } else if (!strcmp(&msgBuff[0], "h")) { anon_log("available commands:"); anon_log(" q - quit"); anon_log(" p - pause all io threads, print while paused, then resume"); anon_log(" s - send some udp packets to the udp handler"); anon_log(" h - display this menu"); anon_log(" t - install a one second timer, which when it expires prints a message"); anon_log(" tt - schedule, and then delete a timer before it has a chance to expire"); anon_log(" fs - run a fiber which executes the fiber sleep function for 1000 milliseconds"); anon_log(" e - execute a print statement once on each io thread"); anon_log(" o - execute a print statement once on a single io thread"); anon_log(" f - execute a print statement on a fiber"); anon_log(" ft - test how long it takes to fiber/context switch " << num_pipe_pairs * num_read_writes << " times"); anon_log(" ot - similar test to 'ft', except run in os threads to test thread dispatch speed"); anon_log(" fi - run a fiber that creates additional fibers using \"in-fiber\" start mechanism"); anon_log(" fr - run a fiber that creates additional fibers using \"run\" start mechanism"); anon_log(" or - similar to 'fr', except using threads instead of fibers"); anon_log(" d - dns cache lookup of \"www.google.com\", port 80 with \"lookup_and_run\""); anon_log(" df - same as 'd', except \"lookup_and_run\" is called from a fiber"); anon_log(" id - same as 'df', except calling the fiber-blocking \"get_addrinfo\""); anon_log(" c - tcp connect to \"www.google.com\", port 80 and print a message"); anon_log(" ic - same as 'c', except calling the fiber-blocking connect"); anon_log(" cp - tcp connect to \"www.google.com\", port 79 and print a message - fails slowly"); anon_log(" ch - tcp connect to \"nota.yyrealhostzz.com\", port 80 and print a message - fails quickly"); anon_log(" h2 - connect to localhost:" << http_port << " and send an HTTP/1.1 with Upgrade to HTTP/2 message"); anon_log(" dl - dns_lookup \"www.google.com\", port 80 and print all addresses"); anon_log(" ss - send a simple command to adobe's renga server"); anon_log(" et - execute the endpoint_cluster tests"); anon_log(" mc - execute the memcached tests"); } else if (!strcmp(&msgBuff[0], "p")) { anon_log("pausing io threads"); io_dispatch::while_paused([] { anon_log("all io threads now paused"); }); anon_log("resuming io threads"); } else if (!strcmp(&msgBuff[0], "s")) { int num_messages = 20; anon_log("sending " << num_messages << " udp packet" << (num_messages == 1 ? "" : "s") << " to my_udp on loopback addr"); struct sockaddr_in6 addr = {0}; addr.sin6_family = AF_INET6; addr.sin6_port = htons(udp_port); addr.sin6_addr = in6addr_loopback; for (int i = 0; i < num_messages; i++) { std::ostringstream msg; msg << "hello world (" << std::to_string(i) << ")" /*<< rand_id()*/; if (sendto(m_udp->get_sock(), msg.str().c_str(), strlen(msg.str().c_str()) + 1, 0, (struct sockaddr *)&addr, sizeof(addr)) == -1) anon_log_error("sendto failed with errno: " << errno_string()); } } else if (!strcmp(&msgBuff[0], "t")) { anon_log("queueing one second delayed task"); io_dispatch::schedule_task([] { anon_log("task completed"); }, cur_time() + 1); } else if (!strcmp(&msgBuff[0], "tt")) { anon_log("queueing one second delayed task and deleting it before it expires"); auto t = io_dispatch::schedule_task([] { anon_log("oops, task completed!"); }, cur_time() + 1); if (io_dispatch::remove_task(t)) { anon_log("removed the task " << t); } else anon_log("failed to remove the task " << t); } else if (!strcmp(&msgBuff[0], "fs")) { anon_log("run a fiber which executes the fiber sleep function for 1000 milliseconds"); fiber::run_in_fiber([] { anon_log("in fiber, calling msleep(1000)"); fiber::msleep(1000); anon_log("back from calling msleep(1000)"); }); } else if (!strcmp(&msgBuff[0], "e")) { anon_log("executing print statement on each io thread"); io_dispatch::on_each([] { anon_log("hello from io thread " << syscall(SYS_gettid)); }); } else if (!strcmp(&msgBuff[0], "o")) { anon_log("executing print statement on one io thread"); io_dispatch::on_one([] { anon_log("hello from io thread " << syscall(SYS_gettid)); }); } else if (!strcmp(&msgBuff[0], "f")) { anon_log("executing print statement from a fiber"); fiber::run_in_fiber([] { anon_log("hello from fiber " << get_current_fiber_id()); }); } else if (!strcmp(&msgBuff[0], "ft")) { anon_log("executing fiber dispatch timing test"); auto start_time = cur_time(); std::vector<int> fds(num_pipe_pairs * 2); for (int i = 0; i < num_pipe_pairs; i++) { if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, &fds[i * 2]) != 0) do_error("socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, sv)"); } for (int i = 0; i < num_pipe_pairs; i++) { fiber::run_in_fiber([fds, i, num_read_writes] { fiber_pipe pipe(fds[i * 2], fiber_pipe::unix_domain); for (int rc = 0; rc < num_read_writes; rc++) { int v; pipe.read(&v, sizeof(v)); if (v != rc) anon_log("fiber read " << v << " instead of " << rc); } }); } fiber::run_in_fiber([fds, num_pipe_pairs, num_read_writes] { std::vector<std::unique_ptr<fiber_pipe>> pipes; for (int pc = 0; pc < num_pipe_pairs; pc++) pipes.push_back(std::move(std::unique_ptr<fiber_pipe>(new fiber_pipe(fds[pc * 2 + 1], fiber_pipe::unix_domain)))); for (int wc = 0; wc < num_read_writes; wc++) { for (int pc = 0; pc < num_pipe_pairs; pc++) pipes[pc]->write(&wc, sizeof(wc)); } }); fiber::wait_for_zero_fibers(); anon_log("fiber test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "ot")) { anon_log("executing thread dispatch timing test"); auto start_time = cur_time(); std::vector<int> fds(num_pipe_pairs * 2); std::vector<std::thread> threads; for (int i = 0; i < num_pipe_pairs; i++) { if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, &fds[i * 2]) != 0) anon_log_error("socketpair(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0, sv) failed with errno: " << errno_string()); } for (int i = 0; i < num_pipe_pairs; i++) { threads.push_back(std::thread([fds, i, num_read_writes] { try { for (int rc = 0; rc < num_read_writes; rc++) { int v; auto bytes_read = read(fds[i * 2], &v, sizeof(v)); if (bytes_read != sizeof(v)) anon_log_error("read(" << fds[i * 2] << ",...) returned " << bytes_read << ", errno: " << errno_string()); else if (v != rc) anon_log_error("thread read " << v << " instead of " << rc); } close(fds[i * 2]); } catch (const std::exception &err) { anon_log_error("exception caught, what = " << err.what()); } catch (...) { anon_log_error("unknown exception caught"); } })); } threads.push_back(std::thread([fds, num_pipe_pairs, num_read_writes] { try { for (int wc = 0; wc < num_read_writes; wc++) { for (int pc = 0; pc < num_pipe_pairs; pc++) { if (write(fds[pc * 2 + 1], &wc, sizeof(wc)) != sizeof(wc)) anon_log_error("(write(fds[pc*2+1],&wc,sizeof(wc)) failed with errno: " << errno_string()); } } for (int pc = 0; pc < num_pipe_pairs; pc++) close(fds[pc * 2 + 1]); } catch (const std::exception &err) { anon_log_error("exception caught, what = " << err.what()); } catch (...) { anon_log_error("unknown exception caught"); } })); for (auto thread = threads.begin(); thread != threads.end(); ++thread) thread->join(); anon_log("thread test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "fi")) { anon_log("starting fiber which starts other fibers using \"in-fiber\" mechanism"); fiber::run_in_fiber([] { fiber_mutex mutex; mutex.lock(); anon_log("start, mutex " << &mutex << " is locked"); // "in-fiber" start sf1 fiber sf1([&mutex] { anon_log("locking mutex " << &mutex); fiber_lock lock(mutex); anon_log("locked mutex, now unlocking and exiting"); }, fiber::k_default_stack_size, false, "sf1"); // "in-fiber" start sf2 fiber sf2([&mutex] { anon_log("locking mutex " << &mutex); fiber_lock lock(mutex); anon_log("locked mutex, now unlocking and exiting"); }, fiber::k_default_stack_size, false, "sf2"); anon_log("fibers " << sf1.get_fiber_id() << " and " << sf2.get_fiber_id() << " both running, now unlocking mutex " << &mutex); mutex.unlock(); // wait for sf1 and sf2 to exit sf1.join(); sf2.join(); anon_log("fibers " << sf1.get_fiber_id() << " and " << sf2.get_fiber_id() << " have exited"); }); fiber::wait_for_zero_fibers(); anon_log("all fibers done"); } else if (!strcmp(&msgBuff[0], "fr")) { anon_log("starting fiber which starts 10000 sub fibers using \"run\" mechanism"); auto start_time = cur_time(); fiber::run_in_fiber([] { fiber_mutex mutex; fiber_cond cond; int num_fibers = 10000; int started = 0; // "run" start for (int fc = 0; fc < num_fibers; fc++) { fiber::run_in_fiber([&mutex, &cond, &started, num_fibers] { fiber_lock lock(mutex); if (++started == num_fibers) { anon_log("last sub fiber, now notifying"); cond.notify_all(); } }); } fiber_lock lock(mutex); while (started != num_fibers) cond.wait(lock); }); fiber::wait_for_zero_fibers(); anon_log("fiber test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "or")) { anon_log("starting thread which starts 10000 sub threads"); auto start_time = cur_time(); std::thread([] { std::mutex mutex; std::condition_variable cond; int num_threads = 10000; int started = 0; for (int tc = 0; tc < num_threads; tc++) { std::thread([&mutex, &cond, &started, num_threads] { anon::unique_lock<std::mutex> lock(mutex); if (++started == num_threads) { anon_log("last sub thread, now notifying"); cond.notify_all(); } }) .detach(); } anon::unique_lock<std::mutex> lock(mutex); while (started != num_threads) cond.wait(lock); }) .join(); anon_log("thread test done, total time: " << cur_time() - start_time << " seconds"); } else if (!strcmp(&msgBuff[0], "c")) { const char *host = "www.google.com"; int port = 80; anon_log("tcp connecting to \"" << host << "\", port " << port); tcp_client::connect_and_run(host, port, [host, port](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else if (err_code > 0) anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << error_string(err_code)); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << gai_strerror(err_code)); }); } else if (!strcmp(&msgBuff[0], "ic")) { const char *host = "www.google.com"; int port = 80; anon_log("tcp connecting to \"" << host << "\", port " << port << ", with tcp_client::connect"); fiber::run_in_fiber([host, port] { auto c = tcp_client::connect(host, port); if (c.first == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << (c.first > 0 ? error_string(c.first) : gai_strerror(c.first))); }); } else if (!strcmp(&msgBuff[0], "cp")) { const char *host = "www.google.com"; int port = 79; anon_log("trying to tcp connect to \"" << host << "\", port " << port); tcp_client::connect_and_run(host, port, [host, port](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); } else if (!strcmp(&msgBuff[0], "ch")) { const char *host = "nota.yyrealhostzz.com"; int port = 80; anon_log("trying to tcp connect to \"" << host << "\", port " << port); tcp_client::connect_and_run(host, port, [host, port](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) anon_log("connected to \"" << host << "\", port " << port << ", now disconnecting"); else anon_log("connection to \"" << host << "\", port " << port << " failed with error: (" << err_code << ") " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); } else if (!strcmp(&msgBuff[0], "d")) { const char *host = "www.google.com"; int port = 80; anon_log("looking up \"" << host << "\", port " << port << " (twice)"); for (int i = 0; i < 2; i++) dns_cache::lookup_and_run(host, port, [host, port](int err_code, const struct sockaddr *addr, socklen_t addrlen) { if (err_code == 0) anon_log("dns lookup for \"" << host << "\", port " << port << " found: " << *addr); else anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); } else if (!strcmp(&msgBuff[0], "df")) { const char *host = "www.google.com"; int port = 80; anon_log("running a fiber which looks up \"" << host << "\", port " << port << " (twice)"); fiber::run_in_fiber([host, port] { for (int i = 0; i < 2; i++) dns_cache::lookup_and_run(host, port, [host, port](int err_code, const struct sockaddr *addr, socklen_t addrlen) { if (err_code == 0) anon_log("dns lookup for \"" << host << "\", port " << port << " found: " << *addr); else anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); }); }); } else if (!strcmp(&msgBuff[0], "id")) { const char *host = "www.google.com"; int port = 80; anon_log("running a fiber which calls get_addrinfo on \"" << host << "\", port " << port << " (twice)"); fiber::run_in_fiber([host, port] { for (int i = 0; i < 2; i++) { struct sockaddr_in6 addr; socklen_t addrlen; int ret = dns_cache::get_addrinfo(host, port, &addr, &addrlen); if (ret == 0) anon_log("dns lookup for \"" << host << "\", port " << port << " found: " << addr); else anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (ret > 0 ? error_string(ret) : gai_strerror(ret))); } }); } else if (!strcmp(&msgBuff[0], "h2")) { #if 0 run_http2_test(http_port); #endif } else if (!strcmp(&msgBuff[0], "dl")) { const char *host = "www.google.com"; int port = 80; anon_log("looking up \"" << host << "\", port " << port << ", and printing all ip addresses"); fiber::run_in_fiber([host, port] { auto addrs = dns_lookup::get_addrinfo(host, port); if (addrs.first != 0) anon_log("dns lookup for \"" << host << "\", port " << port << " failed with error: " << (addrs.first > 0 ? error_string(addrs.first) : gai_strerror(addrs.first))); else { anon_log("dns lookup for \"" << host << "\", port " << port << " found " << addrs.second.size() << " addresses"); for (auto addr : addrs.second) anon_log(" " << addr); } }); } else if (!strcmp(&msgBuff[0], "et")) { epc_test(); } else if (!strncmp(&msgBuff[0], "ss", 2)) { int total = 4; if (strlen(&msgBuff[0]) > 2) total = atoi(&msgBuff[2]); const char *host = "na1r-dev1.services.adobe.com"; int port = 443; std::atomic_int num_succeeded(0); std::atomic_int num_failed(0); std::atomic_int num_tls(0); std::atomic_int num_connected(0); std::atomic_int num_calls(0); anon_log("making " << total << " api calls to \"" << host << "\", port " << port); for (int i = 0; i < total; i++) { tcp_client::connect_and_run(host, port, [host, port, total, &num_succeeded, &num_failed, &num_tls, &num_connected, &num_calls](int err_code, std::unique_ptr<fiber_pipe> &&pipe) { if (err_code == 0) { if (++num_connected == 1) anon_log("tcp connected..."); pipe->limit_io_block_time(120); try { const char *user_name = "user@domain.com"; const char *password = "password"; tls_context ctx(true /*client*/, 0 /*verify_cert*/, "/etc/ssl/certs" /*verify_loc*/, 0, 0, 5); //anon_log("connected to \"" << host << "\", port " << port << ", (fd: " << fd << ") now starting tls handshake"); tls_pipe p(std::move(pipe), true /*client*/, true /*verify_peer*/, false /* doSNI */, host, ctx); ++num_tls; std::ostringstream body; body << "<ReqBody version=\"1.5\" clientId=\"anon_client\">\n"; body << " <req dest=\"UserManagement\" api=\"authUserWithCredentials\">\n"; body << " <string>" << user_name << "</string>\n"; body << " <string>" << password << "</string>\n"; body << " <AuthRequest/>\n"; body << " </req>\n"; body << "</ReqBody>\n"; std::string body_st = body.str(); std::ostringstream oss; oss << "POST /account/amfgateway2 HTTP/1.1\r\n"; oss << "host: " << host << "\r\n"; oss << "content-length: " << body_st.length() << "\r\n"; oss << "user-agent: anon_agent\r\n"; oss << "content-type: text/xml;charset=utf-8\r\n"; oss << "accept: text/xml;charset=utf-8\r\n"; oss << "\r\n"; oss << body_st.c_str(); std::string st = oss.str(); const char *buf = st.c_str(); size_t len = st.length(); #if 0 anon_log("tls handshake completed, certificates accepted, now sending (encrypted):\n\n" << buf); #endif p.write(st.c_str(), len); //anon_log("tls send completed, now reading"); char ret_buf[10250]; auto ret_len = p.read(&ret_buf[0], sizeof(ret_buf) - 1); //ret_buf[ret_len] = 0; //anon_log("server return starts with (encrypted):\n\n" << &ret_buf[0] << "\n"); //anon_log("closing connection to \"" << host << "\" (fd: " << fd << ")"); p.shutdown(); ++num_succeeded; } catch (...) { //anon_log("caught exception"); } } else { //anon_log("connection to \"" << host << "\", port " << port << " failed with error: " << (err_code > 0 ? error_string(err_code) : gai_strerror(err_code))); ++num_failed; } if (++num_calls == total) anon_log("finished " << total << " api calls:\n " << num_succeeded << " succeeded\n " << num_failed << " failed to connect\n " << num_connected - num_tls << " failed during tls handshake\n " << num_tls - num_succeeded << " failed after tls handshake"); }); } } else if (!strncmp(&msgBuff[0], "pp ", 3)) { auto sock = atoi(&msgBuff[3]); struct sockaddr_in6 addr6; socklen_t addr_len = sizeof(addr6); if (getpeername(sock, (struct sockaddr *)&addr6, &addr_len) != 0) anon_log("getpeername(" << sock << "...) failed with error " << errno_string()); else anon_log("getpeername(" << sock << ", ...) reported peer as " << &addr6); } else if (!strcmp(&msgBuff[0], "mc")) { std::condition_variable cond; std::mutex mtx; bool running = true; fiber::run_in_fiber([&cond, &mtx, &running] { struct unlocker { unlocker(std::condition_variable &cond, std::mutex &mtx, bool &running) : cond(cond), mtx(mtx), running(running) { } ~unlocker() { std::unique_lock<std::mutex> l(mtx); running = false; cond.notify_all(); } std::condition_variable &cond; std::mutex &mtx; bool &running; }; unlocker unl(cond, mtx, running); const char *host = "127.0.0.1"; int port = 11211; anon_log("memcached test to host: \"" << host << "\", port: " << port); const char *key = "key1"; const char *val = "this is the value for key1"; mcd_cluster c(host, port); anon_log(" setting value for \"" << key << "\" to: \"" << val << "\""); c.set(key, val, 1); anon_log(" fetching value for \"" << key << "\", got \"" << c.get(key) << "\""); }); std::unique_lock<std::mutex> l(mtx); while (running) cond.wait(l); } else anon_log("unknown command - \"" << &msgBuff[0] << "\", type \"h <return>\" for help"); } } } epc_test_term(); dns_lookup::end_service(); dns_cache::terminate(); io_dispatch::join(); fiber::terminate(); term_big_id_crypto(); anon_log("application exit"); return 0; }
39.908505
272
0.502406
pkholland
ce9fb266d61bf3c485015eabe0377a3c85b44d2d
37,377
cpp
C++
vnext/Desktop.IntegrationTests/HttpOriginPolicyIntegrationTest.cpp
iahmadwaqar/react-native-windows
2d128d8d3e51e4cba8f94965053c6b679602c87d
[ "MIT" ]
4,873
2017-03-09T22:58:40.000Z
2019-05-06T21:03:20.000Z
vnext/Desktop.IntegrationTests/HttpOriginPolicyIntegrationTest.cpp
iahmadwaqar/react-native-windows
2d128d8d3e51e4cba8f94965053c6b679602c87d
[ "MIT" ]
1,293
2017-03-09T15:57:29.000Z
2019-05-06T20:35:22.000Z
vnext/Desktop.IntegrationTests/HttpOriginPolicyIntegrationTest.cpp
iahmadwaqar/react-native-windows
2d128d8d3e51e4cba8f94965053c6b679602c87d
[ "MIT" ]
477
2017-03-10T06:39:32.000Z
2019-05-06T20:33:00.000Z
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include <CppUnitTest.h> #include <CppRuntimeOptions.h> #include <Networking/IHttpResource.h> #include <Networking/OriginPolicy.h> #include <Test/HttpServer.h> // Standard Library #include <future> using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace http = boost::beast::http; using Microsoft::React::Networking::IHttpResource; using Microsoft::React::Networking::OriginPolicy; using std::make_shared; using std::promise; using std::string; namespace { constexpr char s_serverHost[]{"http://localhost"}; constexpr char s_crossOriginUrl[]{"http://example.rnw"}; } // namespace // clang-format off namespace Microsoft::React::Test { TEST_CLASS(HttpOriginPolicyIntegrationTest) { static constexpr bool s_shouldSucceed{true}; static constexpr bool s_shouldFail{false}; static uint16_t s_port; struct ServerParams { uint16_t Port; string Url; EmptyResponse Preflight; StringResponse Response; ServerParams( uint16_t port) noexcept : Port{port} , Url{s_serverHost + string{":"} + std::to_string(port)} { Preflight.set(http::field::access_control_allow_methods, "GET, POST, DELETE, PATCH"); Response.result(http::status::unknown); Response.body() = "RESPONSE_CONTENT"; } }; struct ClientParams { promise<void> ContentPromise; string ErrorMessage; IHttpResource::Response Response; string ResponseContent; http::verb Method; IHttpResource::Headers RequestHeaders; bool WithCredentials{false}; ClientParams(http::verb method, IHttpResource::Headers&& headers) : Method{ method } , RequestHeaders{ std::move(headers) } { } }; std::shared_ptr<HttpServer> CreateServer(ServerParams& serverArgs, ClientParams& clientArgs) noexcept { auto server = make_shared<HttpServer>(serverArgs.Port); server->Callbacks().OnOptions = [&serverArgs](const DynamicRequest& request) -> ResponseWrapper { return { std::move(serverArgs.Preflight) }; }; auto reqHandler = [&serverArgs](const DynamicRequest& request) -> ResponseWrapper { return { std::move(serverArgs.Response) }; }; switch (clientArgs.Method) { case http::verb::get: server->Callbacks().OnGet = reqHandler; break; case http::verb::post: server->Callbacks().OnPost = reqHandler; break; case http::verb::patch: server->Callbacks().OnPatch = reqHandler; break; case http::verb::trace: server->Callbacks().OnTrace = reqHandler; break; case http::verb::connect: server->Callbacks().OnConnect = reqHandler; break; case http::verb::options: default: Assert::Fail(L"Unsupported request method"); } return server; } void TestOriginPolicyWithRedirect(ServerParams& server1Args, ServerParams& server2Args, ClientParams& clientArgs, bool shouldSucceed) { auto server1 = CreateServer(server1Args, clientArgs); auto server2 = CreateServer(server2Args, clientArgs); server1->Start(); server2->Start(); auto resource = IHttpResource::Make(); resource->SetOnResponse([&clientArgs](int64_t, IHttpResource::Response&& response) { clientArgs.Response = std::move(response); }); resource->SetOnData([&clientArgs](int64_t, string&& content) { clientArgs.ResponseContent = std::move(content); clientArgs.ContentPromise.set_value(); }); resource->SetOnError([&clientArgs](int64_t, string&& message) { clientArgs.ErrorMessage = std::move(message); clientArgs.ContentPromise.set_value(); }); resource->SendRequest( string{http::to_string(clientArgs.Method).data()}, string{server1Args.Url}, std::move(clientArgs.RequestHeaders), { IHttpResource::BodyData::Type::String, "REQUEST_CONTENT" }, "text", false, /*useIncrementalUpdates*/ 1000, /*timeout*/ clientArgs.WithCredentials, /*withCredentials*/ [](int64_t){} /*reactCallback*/ ); clientArgs.ContentPromise.get_future().wait(); server2->Stop(); server1->Stop(); if (shouldSucceed) { Assert::AreEqual({}, clientArgs.ErrorMessage); //TODO: chose server? // We assume 2-server tests will always redirect so the final response will come from server 2. Assert::AreEqual(server2Args.Response.result_int(), static_cast<unsigned int>(clientArgs.Response.StatusCode)); Assert::AreEqual({"RESPONSE_CONTENT"}, clientArgs.ResponseContent); } else { Assert::AreNotEqual({}, clientArgs.ErrorMessage); } } void TestOriginPolicy(ServerParams& serverArgs, ClientParams& clientArgs, bool shouldSucceed) { auto server = CreateServer(serverArgs, clientArgs); server->Start(); auto resource = IHttpResource::Make(); resource->SetOnResponse([&clientArgs](int64_t, IHttpResource::Response&& res) { clientArgs.Response = std::move(res); }); resource->SetOnData([&clientArgs](int64_t, string&& content) { clientArgs.ResponseContent = std::move(content); clientArgs.ContentPromise.set_value(); }); resource->SetOnError([&clientArgs](int64_t, string&& message) { clientArgs.ErrorMessage = std::move(message); clientArgs.ContentPromise.set_value(); }); resource->SendRequest( string{http::to_string(clientArgs.Method).data()}, string{serverArgs.Url}, std::move(clientArgs.RequestHeaders), { IHttpResource::BodyData::Type::String, "REQUEST_CONTENT" }, "text", false, /*useIncrementalUpdates*/ 1000, /*timeout*/ clientArgs.WithCredentials, /*withCredentials*/ [](int64_t) {} /*reactCallback*/ ); clientArgs.ContentPromise.get_future().wait(); server->Stop(); if (shouldSucceed) { Assert::AreEqual({}, clientArgs.ErrorMessage); Assert::AreEqual(serverArgs.Response.result_int(), static_cast<unsigned int>(clientArgs.Response.StatusCode)); Assert::AreEqual({"RESPONSE_CONTENT"}, clientArgs.ResponseContent); } else { Assert::AreNotEqual({}, clientArgs.ErrorMessage); } } TEST_METHOD_CLEANUP(MethodCleanup) { SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); SetRuntimeOptionString("Http.GlobalOrigin", {}); // Bug in HttpServer does not correctly release TCP port between test methods. // Using a different por per test for now. s_port++; } //TODO: NoCors_InvalidMethod_Failed? BEGIN_TEST_METHOD_ATTRIBUTE(NoCorsForbiddenMethodSucceeds) // CONNECT, TRACE, and TRACK methods not supported by Windows.Web.Http // https://docs.microsoft.com/en-us/uwp/api/windows.web.http.httpmethod?view=winrt-19041#properties TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(NoCorsForbiddenMethodSucceeds) { SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); constexpr uint16_t port{ 5556 }; constexpr char url[]{ "http://localhost:5556" }; string error; string getContent; IHttpResource::Response getResponse; promise<void> getDataPromise; auto server = make_shared<HttpServer>(port); server->Callbacks().OnOptions = [&url](const DynamicRequest& request) -> ResponseWrapper { EmptyResponse response; response.result(http::status::accepted); response.set(http::field::access_control_allow_credentials, "false"); response.set(http::field::access_control_allow_headers, "ValidHeader"); response.set(http::field::access_control_allow_methods, "GET, POST, DELETE, PATCH"); response.set(http::field::access_control_allow_origin, url); return { std::move(response) }; }; server->Callbacks().OnTrace = [](const DynamicRequest& request) -> ResponseWrapper { StringResponse response; response.result(http::status::ok); response.body() = "GET_CONTENT"; return { std::move(response) }; }; server->Start(); auto resource = IHttpResource::Make(); resource->SetOnResponse([&getResponse](int64_t, IHttpResource::Response&& res) { getResponse = std::move(res); }); resource->SetOnData([&getDataPromise, &getContent](int64_t, string&& content) { getContent = std::move(content); getDataPromise.set_value(); }); resource->SetOnError([&server, &error, &getDataPromise](int64_t, string&& message) { error = std::move(message); getDataPromise.set_value(); }); resource->SendRequest( "TRACE", url, { {"ValidHeader", "AnyValue"} }, {} /*bodyData*/, "text", false /*useIncrementalUpdates*/, 1000 /*timeout*/, false /*withCredentials*/, [](int64_t) {} /*callback*/ ); getDataPromise.get_future().wait(); server->Stop(); Assert::AreEqual({}, error); Assert::AreEqual(200, static_cast<int>(getResponse.StatusCode)); Assert::AreEqual({ "GET_CONTENT" }, getContent); }// NoCorsForbiddenMethodSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(SimpleCorsForbiddenMethodFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(SimpleCorsForbiddenMethodFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, serverArgs.Url); ClientParams clientArgs(http::verb::connect, {{"Content-Type", "text/plain"}}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::SimpleCrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// SimpleCorsForbiddenMethodFails //NoCors_ForbiddenMethodConnect_Failed BEGIN_TEST_METHOD_ATTRIBUTE(NoCorsCrossOriginFetchRequestSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(NoCorsCrossOriginFetchRequestSucceeds) { SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// NoCorsCrossOriginFetchRequestSucceeds //NoCors_CrossOriginFetchRequestWithTimeout_Succeeded //TODO: Implement timeout BEGIN_TEST_METHOD_ATTRIBUTE(NoCorsCrossOriginPatchSucceededs) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(NoCorsCrossOriginPatchSucceededs) { SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::None)); ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// NoCorsCrossOriginPatchSucceededs // Simple-Cors — Prevents the method from being anything other than HEAD, GET or POST, // and the headers from being anything other than simple headers (CORS safe listed headers). // If any ServiceWorkers intercept these requests, they may not add or override any headers except for those that are simple headers. // In addition, JavaScript may not access any properties of the resulting Response. // This ensures that ServiceWorkers do not affect the semantics of the Web and prevents security and privacy issues arising from leaking data across domains. BEGIN_TEST_METHOD_ATTRIBUTE(SimpleCorsSameOriginSucceededs) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(SimpleCorsSameOriginSucceededs) { ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::SimpleCrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// SimpleCorsSameOriginSucceededs BEGIN_TEST_METHOD_ATTRIBUTE(SimpleCorsCrossOriginFetchFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(SimpleCorsCrossOriginFetchFails) { ServerParams serverArgs(s_port); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/html" }}); // text/html is a non-simple value SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::SimpleCrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// SimpleCorsCrossOriginFetchFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsSameOriginRequestSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsSameOriginRequestSucceeds) { ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::ok); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); // text/plain is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// FullCorsSameOriginRequestSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginAllowOriginWildcardSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginAllowOriginWildcardSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, "*"); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, "*"); serverArgs.Response.set(http::field::access_control_allow_credentials, "true"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); // text/plain is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// FullCorsCrossOriginAllowOriginWildcardSucceeds // With CORS, Cross-Origin Resource Sharing, the server can decide what origins are permitted to read information from the client. // Additionally, for non-simple requests, client should preflight the request through the HTTP Options request, and only send the // actual request after the server has responded that the desired headers are supported. BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginMatchingOriginSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginMatchingOriginSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.set(http::field::access_control_allow_credentials, "true"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); // text/plain is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, true /*shouldSucceed*/); }// FullCorsCrossOriginMatchingOriginSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginWithCredentialsFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginWithCredentialsFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::access_control_allow_credentials, "true"); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header clientArgs.WithCredentials = true; SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); SetRuntimeOptionBool("Http.OmitCredentials", true); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginWithCredentialsFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginMissingCorsHeadersFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginMissingCorsHeadersFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.erase(http::field::access_control_allow_methods); serverArgs.Preflight.result(http::status::not_implemented); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginMissingCorsHeadersFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginMismatchedCorsHeaderFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginMismatchedCorsHeaderFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, "http://other.example.rnw"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginMismatchedCorsHeaderFails // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSExternalRedirectNotAllowed BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginCheckFailsOnPreflightRedirectFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginCheckFailsOnPreflightRedirectFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::location, "http://any-host.extension"); serverArgs.Preflight.result(http::status::moved_permanently); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// FullCorsCrossOriginCheckFailsOnPreflightRedirectFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCorsCheckFailsOnResponseRedirectFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCorsCheckFailsOnResponseRedirectFails) { ServerParams serverArgs(s_port); // server1 allowed origin header includes http://example.com serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); // This is a CORS request to server1, but server1 redirects the request to server2 serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // Redir server's URL serverArgs.Response.set(http::field::location, "http://localhost:6666"); serverArgs.Response.set(http::field::server, "BaseServer"); // Server2 does not set Access-Control-Allow-Origin for GET requests ServerParams redirServerArgs(++s_port); redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::server, "RedirectServer"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldFail); }// FullCorsCorsCheckFailsOnResponseRedirectFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsSameOriginToSameOriginRedirectSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsSameOriginToSameOriginRedirectSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::location, serverArgs.Url); serverArgs.Response.result(http::status::accepted); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldSucceed); } // FullCorsSameOriginToSameOriginRedirectSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsSameOriginToCrossOriginRedirectSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsSameOriginToCrossOriginRedirectSucceeds) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, serverArgs.Url); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, serverArgs.Url); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldSucceed); } // FullCorsSameOriginToCrossOriginRedirectSucceeds //TODO: Seems to redirect to exact same resource. Implement second resource in same server. // Redirects a cross origin request to cross origin request on the same server BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToCrossOriginRedirectSucceeds) TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToCrossOriginRedirectSucceeds) { ServerParams serverArgs(s_port); //ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_allow_origin, serverArgs.Url); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, serverArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); //redirServerArgs.Response.result(http::status::accepted); //redirServerArgs.Response.set(http::field::access_control_allow_origin, serverArgs.Url); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, /*redirServerArgs, */clientArgs, s_shouldSucceed); } // FullCorsCrossOriginToCrossOriginRedirectSucceeds // The initial request gets redirected back to the original origin, // but it will lack the Access-Control-Allow-Origin header. BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToOriginalOriginRedirectFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToOriginalOriginRedirectFails) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, redirServerArgs.Url); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", redirServerArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldFail); } // FullCorsCrossOriginToOriginalOriginRedirectFails // Redirects cross origin request to server1 to cross origin request to server2 BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToAnotherCrossOriginRedirectSucceeds) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToAnotherCrossOriginRedirectSucceeds) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, "*"); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldSucceed); } // FullCorsCrossOriginToAnotherCrossOriginRedirectSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightSucceeds) // [0x80072f88] The HTTP redirect request must be confirmed by the user //TODO: Figure out manual redirection. TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightSucceeds) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); // server1 redirects the GET request to server2 serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // Since redirect tainted the origin, the server has to allow all origins for CORS to succeed redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, "*"); // PATCH is not a simple method, so preflight is required for server1 ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldSucceed); } // FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightSucceeds BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightFails) { ServerParams serverArgs(s_port); ServerParams redirServerArgs(++s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); // server1 redirects the GET request to server2 serverArgs.Response.result(http::status::moved_permanently); serverArgs.Response.set(http::field::location, redirServerArgs.Url); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // Since redirect tainted the origin, the server does not know what origin to allow through a single value. // Even if server successfully guessed the single value, it will still fail on the client side. redirServerArgs.Response.result(http::status::accepted); redirServerArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); // PATCH is not a simple method, so preflight is required for server1 ClientParams clientArgs(http::verb::patch, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicyWithRedirect(serverArgs, redirServerArgs, clientArgs, s_shouldFail); } // FullCorsCrossOriginToAnotherCrossOriginRedirectWithPreflightFails BEGIN_TEST_METHOD_ATTRIBUTE(FullCors304ForSimpleGetFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCors304ForSimpleGetFails) { ServerParams serverArgs(s_port); serverArgs.Response.result(http::status::not_modified); // PATCH is not a simple method, so preflight is required for server1 ClientParams clientArgs(http::verb::get, {{ "Content-Type", "text/plain" }}); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); } // FullCors304ForSimpleGetFails TEST_METHOD(FullCorsPreflightSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "ArbitraryHeader"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "ArbitraryHeader"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Response.result(http::status::ok); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); ClientParams clientArgs(http::verb::get, { {"Content-Type", "text/plain"}, {"ArbitraryHeader", "AnyValue"} }); SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldSucceed); }// FullCorsPreflightSucceeds // The current implementation omits withCredentials flag from request and always sets it to false // Configure the responses for CORS request BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsCrossOriginWithCredentialsSucceeds) //TODO: Fails if run after FullCorsCrossOriginWithCredentialsFails TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsCrossOriginWithCredentialsSucceeds) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_origin, s_crossOriginUrl); serverArgs.Preflight.set(http::field::access_control_allow_credentials, "true"); serverArgs.Response.result(http::status::accepted); serverArgs.Response.set(http::field::access_control_allow_origin, s_crossOriginUrl); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }}); // application/text is a non-simple header clientArgs.WithCredentials = true; SetRuntimeOptionString("Http.GlobalOrigin", s_crossOriginUrl); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldSucceed); }// FullCorsCrossOriginWithCredentialsSucceeds // "Host" is one of the forbidden headers for fetch BEGIN_TEST_METHOD_ATTRIBUTE(FullCorsRequestWithHostHeaderFails) // "Host" is not an accepted request header in WinRT. TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(FullCorsRequestWithHostHeaderFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }, { "Host", "http://sub.example.rnw" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); Assert::Fail(L"FIX!!! Passes for the worng reason. Error: 0x80070057 : 'Invalid HTTP headers.'"); }// FullCorsRequestWithHostHeaderFails BEGIN_TEST_METHOD_ATTRIBUTE(RequestWithProxyAuthorizationHeaderFails) END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(RequestWithProxyAuthorizationHeaderFails) { ServerParams serverArgs(s_port); serverArgs.Preflight.set(http::field::access_control_request_headers, "Content-Type"); serverArgs.Preflight.set(http::field::access_control_allow_headers, "Content-Type"); serverArgs.Response.result(http::status::accepted); ClientParams clientArgs(http::verb::get, {{ "Content-Type", "application/text" }, { "Proxy-Authorization", "Basic Zm9vOmJhcg==" }}); SetRuntimeOptionString("Http.GlobalOrigin", serverArgs.Url.c_str()); SetRuntimeOptionInt("Http.OriginPolicy", static_cast<int32_t>(OriginPolicy::CrossOriginResourceSharing)); TestOriginPolicy(serverArgs, clientArgs, s_shouldFail); }// RequestWithProxyAuthorizationHeaderFails BEGIN_TEST_METHOD_ATTRIBUTE(ExceedingRedirectLimitFails) TEST_IGNORE() END_TEST_METHOD_ATTRIBUTE() TEST_METHOD(ExceedingRedirectLimitFails) { Assert::Fail(L"NOT IMPLEMENTED"); }// ExceedingRedirectLimitFails }; uint16_t HttpOriginPolicyIntegrationTest::s_port = 7777; }//namespace Microsoft::React::Test // clang-format on
44.655914
160
0.731439
iahmadwaqar
cea8b31c3435b2438bb81c8fba50ef1024968b54
753
cpp
C++
src/ECS/Detail/SystemHolder.cpp
Ethan13310/ECS
63aae52624b6468a7db078fdf7c32dd4caecaa70
[ "MIT" ]
12
2018-12-06T12:51:57.000Z
2022-03-20T14:31:28.000Z
src/ECS/Detail/SystemHolder.cpp
Ethan13310/ECS
63aae52624b6468a7db078fdf7c32dd4caecaa70
[ "MIT" ]
1
2021-07-15T08:33:16.000Z
2021-07-15T08:33:16.000Z
src/ECS/Detail/SystemHolder.cpp
Ethan13310/ECS
63aae52624b6468a7db078fdf7c32dd4caecaa70
[ "MIT" ]
3
2019-08-10T22:34:28.000Z
2021-07-14T09:19:36.000Z
// Copyright (c) 2021 Ethan Margaillan <contact@ethan.jp>. // Licensed under the MIT License - https://raw.githubusercontent.com/Ethan13310/ECS/master/LICENSE #include <ECS/Detail/SystemHolder.hpp> ecs::detail::SystemHolder::~SystemHolder() { removeAllSystems(); } void ecs::detail::SystemHolder::removeAllSystems() { for (auto &system : m_systems) { if (system.second != nullptr) { system.second->shutdownEvent(); system.second->detachAll(); } } m_systems.clear(); m_priorities.clear(); } void ecs::detail::SystemHolder::removeSystemPriority(detail::TypeId id) { for (auto it{ m_priorities.begin() }; it != m_priorities.end();) { if (it->second == id) { it = m_priorities.erase(it); } else { ++it; } } }
18.825
99
0.670651
Ethan13310
ceb30aa972be3cfb975cfbeb5fb41bbebe710e08
337
hpp
C++
Vesper/Vesper/Textures/UVTexture.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
6
2017-09-14T03:26:49.000Z
2021-09-18T05:40:59.000Z
Vesper/Vesper/Textures/UVTexture.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
Vesper/Vesper/Textures/UVTexture.hpp
FallenShard/Crisp
d4cf22c0f9af73a6c4ba2b7d67696f1a188fd423
[ "MIT" ]
null
null
null
#pragma once #include <memory> #include <string> #include <functional> #include <cmath> #include "Texture.hpp" namespace crisp { class UVTexture : public Texture<Spectrum> { public: UVTexture(const VariantMap& variantMap = VariantMap()); virtual Spectrum eval(const glm::vec2& uv) const override; }; }
17.736842
66
0.673591
FallenShard
cebefcfa86ed528de60b9fc78e36968ef9615386
8,855
cpp
C++
tests/is_base_of/overview.cpp
connojd/bsl
9adebf89bf34ac14d92b26007cb19d5508de54ac
[ "MIT" ]
null
null
null
tests/is_base_of/overview.cpp
connojd/bsl
9adebf89bf34ac14d92b26007cb19d5508de54ac
[ "MIT" ]
null
null
null
tests/is_base_of/overview.cpp
connojd/bsl
9adebf89bf34ac14d92b26007cb19d5508de54ac
[ "MIT" ]
null
null
null
/// @copyright /// Copyright (C) 2020 Assured Information Security, Inc. /// /// @copyright /// 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: /// /// @copyright /// The above copyright notice and this permission notice shall be included in /// all copies or substantial portions of the Software. /// /// @copyright /// 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 <bsl/is_base_of.hpp> #include <bsl/ut.hpp> namespace { class myclass final {}; struct mystruct final {}; union myunion final {}; enum class myenum : bsl::int32 { }; class myclass_abstract // NOLINT { public: virtual ~myclass_abstract() noexcept = default; virtual void foo() noexcept = 0; }; class myclass_base {}; class myclass_subclass : public myclass_base {}; } /// <!-- description --> /// @brief Main function for this unit test. If a call to ut_check() fails /// the application will fast fail. If all calls to ut_check() pass, this /// function will successfully return with bsl::exit_success. /// /// <!-- inputs/outputs --> /// @return Always returns bsl::exit_success. /// bsl::exit_code main() noexcept { using namespace bsl; static_assert(is_base_of<myclass_base, myclass_subclass>::value); static_assert(is_base_of<myclass_base const, myclass_subclass>::value); static_assert(is_base_of<myclass_subclass, myclass_subclass>::value); static_assert(is_base_of<myclass_subclass const, myclass_subclass>::value); static_assert(!is_base_of<bool, myclass_subclass>::value); static_assert(!is_base_of<bool const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int8, myclass_subclass>::value); static_assert(!is_base_of<bsl::int8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int16, myclass_subclass>::value); static_assert(!is_base_of<bsl::int16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int32, myclass_subclass>::value); static_assert(!is_base_of<bsl::int32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int64, myclass_subclass>::value); static_assert(!is_base_of<bsl::int64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least8, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least16, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least32, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least64, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_least64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast8, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast16, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast32, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast64, myclass_subclass>::value); static_assert(!is_base_of<bsl::int_fast64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::intptr, myclass_subclass>::value); static_assert(!is_base_of<bsl::intptr const, myclass_subclass>::value); static_assert(!is_base_of<bsl::intmax, myclass_subclass>::value); static_assert(!is_base_of<bsl::intmax const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint8, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint16, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint32, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint64, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least8, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least16, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least32, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least64, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_least64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast8, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast8 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast16, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast16 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast32, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast32 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast64, myclass_subclass>::value); static_assert(!is_base_of<bsl::uint_fast64 const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintptr, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintptr const, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintmax, myclass_subclass>::value); static_assert(!is_base_of<bsl::uintmax const, myclass_subclass>::value); static_assert(!is_base_of<myclass, myclass_subclass>::value); static_assert(!is_base_of<myclass const, myclass_subclass>::value); static_assert(!is_base_of<mystruct, myclass_subclass>::value); static_assert(!is_base_of<mystruct const, myclass_subclass>::value); static_assert(!is_base_of<myunion, myclass_subclass>::value); static_assert(!is_base_of<myunion const, myclass_subclass>::value); static_assert(!is_base_of<myenum, myclass_subclass>::value); static_assert(!is_base_of<myenum const, myclass_subclass>::value); static_assert(!is_base_of<bool[], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool[1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool[][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool[1][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<bool const[1][1], myclass_subclass>::value); // NOLINT static_assert(!is_base_of<void, myclass_subclass>::value); static_assert(!is_base_of<void const, myclass_subclass>::value); static_assert(!is_base_of<void *, myclass_subclass>::value); static_assert(!is_base_of<void const *, myclass_subclass>::value); static_assert(!is_base_of<void *const, myclass_subclass>::value); static_assert(!is_base_of<void const *const, myclass_subclass>::value); static_assert(!is_base_of<bool &, myclass_subclass>::value); static_assert(!is_base_of<bool &&, myclass_subclass>::value); static_assert(!is_base_of<bool const &, myclass_subclass>::value); static_assert(!is_base_of<bool const &&, myclass_subclass>::value); static_assert(!is_base_of<bool(bool), myclass_subclass>::value); static_assert(!is_base_of<bool (*)(bool), myclass_subclass>::value); return bsl::ut_success(); }
53.993902
87
0.74026
connojd
cebf3cf1108f22fd2fd3cb3140f720d05ef77d67
974
hpp
C++
include/Vnavbar.hpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
2
2020-12-10T20:22:17.000Z
2020-12-10T20:23:35.000Z
include/Vnavbar.hpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
null
null
null
include/Vnavbar.hpp
LeandreBl/sfml-scene
3fb0d1167f1585c0c82775a23b44df46ec7378d5
[ "Apache-2.0" ]
null
null
null
#pragma once #include "UI.hpp" #include "BasicShape.hpp" namespace sfs { class Vnavbar : public UI { public: Vnavbar(Scene &scene, const sf::Vector2f &position = sf::Vector2f(0, 0), const sf::Vector2f &size = sf::Vector2f(30, 100), const sf::Color &color = sf::Color::White) noexcept; Vnavbar(const Vnavbar &) noexcept = default; Vnavbar &operator=(Vnavbar &) noexcept = default; void start() noexcept; void update() noexcept; void onDestroy() noexcept; void onEvent(const sf::Event &event) noexcept; float getValue() const noexcept; sf::FloatRect getGlobalBounds() const noexcept; void setCursorTexture(const sf::Texture &texture) noexcept; void setTexture(const sf::Texture &texture) noexcept; protected: float maxOffset() const noexcept; float minOffset() const noexcept; void setCursorColor(int x, int y) noexcept; Rectangle &_background; Rectangle &_cursor; sf::Color _color; float _clickPosY; bool _clicked; }; } // namespace sfs
28.647059
73
0.726899
LeandreBl
cec715d578e6c654d9056e2632f77b75d882218c
2,932
cpp
C++
quicksort_vs_insertion_sort/main.cpp
saarioka/CPP-snippets
e8f07d76ee0b532f2c90b7360d666342ab7c8291
[ "Apache-2.0" ]
null
null
null
quicksort_vs_insertion_sort/main.cpp
saarioka/CPP-snippets
e8f07d76ee0b532f2c90b7360d666342ab7c8291
[ "Apache-2.0" ]
null
null
null
quicksort_vs_insertion_sort/main.cpp
saarioka/CPP-snippets
e8f07d76ee0b532f2c90b7360d666342ab7c8291
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <ctime> #include <algorithm> // random_shuffle #include <vector> #include <ctime> #include <stdio.h> #include <chrono> using namespace std; // quicksort template <class T> void quicksort(T &A, int a1, int y1){ if(a1 >= y1) return; int x = A[(a1+y1)/2]; int a = a1-1; int y = y1 + 1; int apu; while(a < y){ a++; y--; while(A[a] < x) a++; while(A[y] > x) y--; if(a < y){ apu = A[a]; A[a] = A[y]; A[y] = apu; } } if(a == a1) a++; quicksort(A,a1,a-1); quicksort(A,a,y1); } // insertion sort template <class T> void insertionsort(T &A, unsigned koko){ int apu, j; for(unsigned i = 1; i<koko; i++){ apu = A[i]; j = i-1; while(j >= 0 && (A[j] > apu)){ A[j+1] = A[j]; j--; } A[j+1] = apu; } } // tulosta sailio template <class T> void tulosta(T &A, unsigned koko){ for(unsigned i=0; i < koko; i++) cout << A[i] << " "; cout << "\n"; } int main() { const unsigned koko = 19; vector <int> A(koko); // sailion taytto srand (time(NULL)); for(unsigned i = 0; i<koko; i++){ A[i] = i+1; } random_shuffle(&A[0], &A[koko-1]); tulosta(A,20); cout << "\n"; // quicksort auto alku = chrono::high_resolution_clock::now(); for(unsigned i = 0; i<1000; i++){ srand (time(NULL)); random_shuffle(&A[0], &A[koko-1]); quicksort(A,0,koko-1); } auto loppu = chrono::high_resolution_clock::now(); auto kesto = chrono::duration_cast<std::chrono::nanoseconds>(loppu - alku).count(); tulosta(A,20); cout <<"Quick sort: koko " << koko << " ,kesto " << kesto << "ns.\n\n"; // sailion sekoitus random_shuffle(&A[0], &A[koko-1]); tulosta(A,20); cout << "\n"; // insertion sort alku = chrono::high_resolution_clock::now(); for(unsigned i = 0; i<1000; i++){ srand (time(NULL)); random_shuffle(&A[0], &A[koko-1]); insertionsort(A,koko); } loppu = chrono::high_resolution_clock::now(); kesto = chrono::duration_cast<std::chrono::nanoseconds>(loppu - alku).count(); tulosta(A, 20); cout <<"Insertion sort: koko " << koko << " ,kesto " << kesto << "ns.\n\n"; return 0; } /* * T. 59 * a) n^2 on pienillä n arvoilla pienempi, kuin 10*n*log n + 2*n * * * b) matemaattisesti: n on väh. 62 * ks. kuva * * kokeellisesti: n on n. 20 * ks. T. 60 * * * * T. 60 * * 4 2 16 17 11 10 13 1 5 6 15 3 14 12 19 8 7 9 18 20 * * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * Quick sort: koko 20 ,kesto 12000700ns. * * 12 4 10 19 17 6 7 5 16 11 1 14 3 9 2 18 15 8 13 20 * * 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 * Insertion sort: koko 20 ,kesto 12000100ns. * * Press <RETURN> to close this window... * * */
22.212121
87
0.518076
saarioka
cecbf5d970405fb691fc28bfc30c0d42b0211690
13,051
hpp
C++
src/centurion/opengl.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
14
2020-05-17T21:38:03.000Z
2020-11-21T00:16:25.000Z
src/centurion/opengl.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
70
2020-04-26T17:08:52.000Z
2020-11-21T17:34:03.000Z
src/centurion/opengl.hpp
Creeperface01/centurion
e3b674c11849367a18c2d976ce94071108e1590d
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2019-2022 Albin Johansson * * 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. */ #ifndef CENTURION_OPENGL_HPP_ #define CENTURION_OPENGL_HPP_ #ifndef CENTURION_NO_OPENGL #include <SDL.h> #include <cassert> // assert #include <memory> // unique_ptr #include <optional> // optional #include <ostream> // ostream #include <string> // string #include <string_view> // string_view #include "common.hpp" #include "detail/owner_handle_api.hpp" #include "features.hpp" #include "math.hpp" #include "texture.hpp" #include "window.hpp" namespace cen { /// \addtogroup video /// \{ /** * \defgroup opengl OpenGL * * \brief Provides utilities related to OpenGL. */ /// \addtogroup opengl /// \{ /** * \brief Represents different OpenGL attributes. */ enum class gl_attribute { red_size = SDL_GL_RED_SIZE, green_size = SDL_GL_GREEN_SIZE, blue_size = SDL_GL_BLUE_SIZE, alpha_size = SDL_GL_ALPHA_SIZE, buffer_size = SDL_GL_BUFFER_SIZE, depth_size = SDL_GL_DEPTH_SIZE, stencil_size = SDL_GL_STENCIL_SIZE, accum_red_size = SDL_GL_ACCUM_RED_SIZE, accum_green_size = SDL_GL_ACCUM_GREEN_SIZE, accum_blue_size = SDL_GL_ACCUM_BLUE_SIZE, accum_alpha_size = SDL_GL_ACCUM_ALPHA_SIZE, stereo = SDL_GL_STEREO, double_buffer = SDL_GL_DOUBLEBUFFER, accelerated_visual = SDL_GL_ACCELERATED_VISUAL, retained_backing = SDL_GL_RETAINED_BACKING, share_with_current_context = SDL_GL_SHARE_WITH_CURRENT_CONTEXT, framebuffer_srgb_capable = SDL_GL_FRAMEBUFFER_SRGB_CAPABLE, multisample_buffers = SDL_GL_MULTISAMPLEBUFFERS, multisample_samples = SDL_GL_MULTISAMPLESAMPLES, egl = SDL_GL_CONTEXT_EGL, context_flags = SDL_GL_CONTEXT_FLAGS, context_major_version = SDL_GL_CONTEXT_MAJOR_VERSION, context_minor_version = SDL_GL_CONTEXT_MINOR_VERSION, context_profile_mask = SDL_GL_CONTEXT_PROFILE_MASK, context_release_behavior = SDL_GL_CONTEXT_RELEASE_BEHAVIOR, context_reset_notification = SDL_GL_CONTEXT_RESET_NOTIFICATION, context_no_error = SDL_GL_CONTEXT_NO_ERROR }; /// \name OpenGL attribute functions /// \{ [[nodiscard]] constexpr auto to_string(const gl_attribute attr) -> std::string_view { switch (attr) { case gl_attribute::red_size: return "red_size"; case gl_attribute::green_size: return "green_size"; case gl_attribute::blue_size: return "blue_size"; case gl_attribute::alpha_size: return "alpha_size"; case gl_attribute::buffer_size: return "buffer_size"; case gl_attribute::depth_size: return "depth_size"; case gl_attribute::stencil_size: return "stencil_size"; case gl_attribute::accum_red_size: return "accum_red_size"; case gl_attribute::accum_green_size: return "accum_green_size"; case gl_attribute::accum_blue_size: return "accum_blue_size"; case gl_attribute::accum_alpha_size: return "accum_alpha_size"; case gl_attribute::stereo: return "stereo"; case gl_attribute::egl: return "egl"; case gl_attribute::context_flags: return "context_flags"; case gl_attribute::double_buffer: return "double_buffer"; case gl_attribute::accelerated_visual: return "accelerated_visual"; case gl_attribute::retained_backing: return "retained_backing"; case gl_attribute::share_with_current_context: return "share_with_current_context"; case gl_attribute::framebuffer_srgb_capable: return "framebuffer_srgb_capable"; case gl_attribute::multisample_buffers: return "multisample_buffers"; case gl_attribute::multisample_samples: return "multisample_samples"; case gl_attribute::context_major_version: return "context_major_version"; case gl_attribute::context_minor_version: return "context_minor_version"; case gl_attribute::context_profile_mask: return "context_profile_mask"; case gl_attribute::context_release_behavior: return "context_release_behavior"; case gl_attribute::context_reset_notification: return "context_reset_notification"; case gl_attribute::context_no_error: return "context_no_error"; default: throw exception{"Did not recognize OpenGL attribute!"}; } } inline auto operator<<(std::ostream& stream, const gl_attribute attr) -> std::ostream& { return stream << to_string(attr); } /// \} End of OpenGL attribute functions /** * \brief Represents different swap interval modes. */ enum class gl_swap_interval { late_immediate = -1, immediate = 0, synchronized = 1, }; /// \name OpenGL swap interval functions /// \{ [[nodiscard]] constexpr auto to_string(const gl_swap_interval interval) -> std::string_view { switch (interval) { case gl_swap_interval::immediate: return "immediate"; case gl_swap_interval::synchronized: return "synchronized"; case gl_swap_interval::late_immediate: return "late_immediate"; default: throw exception{"Did not recognize swap interval!"}; } } inline auto operator<<(std::ostream& stream, const gl_swap_interval interval) -> std::ostream& { return stream << to_string(interval); } /// \} End of OpenGL swap interva functions /** * \brief Manages the initialization and de-initialization of an OpenGL library. */ class gl_library final { public: CENTURION_DISABLE_COPY(gl_library) CENTURION_DISABLE_MOVE(gl_library) CENTURION_NODISCARD_CTOR explicit gl_library(const char* path = nullptr) { if (SDL_GL_LoadLibrary(path) == -1) { throw sdl_error{}; } } ~gl_library() noexcept { SDL_GL_UnloadLibrary(); } [[nodiscard]] auto address_of(const char* function) const noexcept // NOLINT -> void* { assert(function); return SDL_GL_GetProcAddress(function); } }; template <typename T> class basic_gl_context; using gl_context = basic_gl_context<detail::owner_tag>; ///< An owning context. using gl_context_handle = basic_gl_context<detail::handle_tag>; ///< A non-owning context. /** * \brief Represents an OpenGL context. * * \ownerhandle `gl_context`/`gl_context_handle` * * \see `gl_context` * \see `gl_context_handle` */ template <typename T> class basic_gl_context final { public: explicit basic_gl_context(maybe_owner<SDL_GLContext> context) noexcept(detail::is_handle<T>) : mContext{context} { if constexpr (detail::is_owner<T>) { if (!mContext) { throw exception{"Can't create OpenGL context from null pointer!"}; } } } template <typename U> explicit basic_gl_context(basic_window<U>& window) noexcept(detail::is_handle<T>) : mContext{SDL_GL_CreateContext(window.get())} { if constexpr (detail::is_owner<T>) { if (!mContext) { throw sdl_error{}; } } } template <typename U> auto make_current(basic_window<U>& window) -> result { assert(window.is_opengl()); return SDL_GL_MakeCurrent(window.get(), mContext.get()) == 0; } [[nodiscard]] auto get() const noexcept -> SDL_GLContext { return mContext.get(); } private: struct Deleter final { void operator()(SDL_GLContext context) noexcept { SDL_GL_DeleteContext(context); } }; std::unique_ptr<void, Deleter> mContext; }; /// \} End of group opengl /// \} End of group video /// \ingroup opengl namespace gl { /// \addtogroup video /// \{ /// \addtogroup opengl OpenGL /// \{ /** * \brief Swaps the buffers for an OpenGL window. * * \pre The window must be usable within an OpenGL context. * * \note This requires that double-buffering is supported. * * \param window the OpenGL window to swap the buffers for. */ template <typename T> void swap(basic_window<T>& window) noexcept { assert(window.is_opengl()); SDL_GL_SwapWindow(window.get()); } /** * \brief Returns the drawable size of an OpenGL window. * * \pre `window` must be an OpenGL window. * * \param window the OpenGL window that will be queried. * * \return the drawable size of the window. */ template <typename T> [[nodiscard]] auto drawable_size(const basic_window<T>& window) noexcept -> iarea { assert(window.is_opengl()); int width{}; int height{}; SDL_GL_GetDrawableSize(window.get(), &width, &height); return {width, height}; } /** * \brief Resets all OpenGL context attributes to their default values. */ inline void reset_attributes() noexcept { SDL_GL_ResetAttributes(); } /** * \brief Sets the value of an OpenGL context attribute. * * \param attr the attribute that will be set. * \param value the new value of the attribute. * * \return `success` if the attribute was set; `failure` otherwise. */ inline auto set(const gl_attribute attr, const int value) noexcept -> result { return SDL_GL_SetAttribute(static_cast<SDL_GLattr>(attr), value) == 0; } /** * \brief Returns the current value of an OpenGL context attribute. * * \param attr the attribute to query. * * \return the value of the specified attribute; an empty optional is returned if the value * could not be obtained. */ inline auto get(const gl_attribute attr) noexcept -> std::optional<int> { int value{}; if (SDL_GL_GetAttribute(static_cast<SDL_GLattr>(attr), &value) == 0) { return value; } else { return std::nullopt; } } /** * \brief Sets the swap interval strategy that will be used. * * \param interval the swap interval that will be used. * * \return `success` if the swap interval set; `failure` if it isn't supported. */ inline auto set_swap_interval(const gl_swap_interval interval) noexcept -> result { return SDL_GL_SetSwapInterval(to_underlying(interval)) == 0; } /** * \brief Returns the swap interval used by the current OpenGL context. * * \note `immediate` is returned if the swap interval cannot be determined. * * \return the current swap interval. */ [[nodiscard]] inline auto swap_interval() noexcept -> gl_swap_interval { return gl_swap_interval{SDL_GL_GetSwapInterval()}; } /** * \brief Returns a handle to the currently active OpenGL window. * * \return a potentially empty window handle. */ [[nodiscard]] inline auto get_window() noexcept -> window_handle { return window_handle{SDL_GL_GetCurrentWindow()}; } /** * \brief Returns a handle to the currently active OpenGL context. * * \return a potentially empty OpenGL context handle. */ [[nodiscard]] inline auto get_context() noexcept -> gl_context_handle { return gl_context_handle{SDL_GL_GetCurrentContext()}; } /** * \brief Indicates whether a specific extension is supported. * * \param extension the extension that will be checked. * * \return `true` if the extension is supported; `false` otherwise. */ [[nodiscard]] inline auto is_extension_supported(const char* extension) noexcept -> bool { assert(extension); return SDL_GL_ExtensionSupported(extension) == SDL_TRUE; } /// \copydoc is_extension_supported() [[nodiscard]] inline auto is_extension_supported(const std::string& extension) noexcept -> bool { return is_extension_supported(extension.c_str()); } /** * \brief Binds a texture to the current OpenGL context. * * \param texture the texture to bind. * * \return the size of the bound texture; an empty optional is returned if something goes * wrong. */ template <typename T> auto bind(basic_texture<T>& texture) noexcept -> std::optional<farea> { float width{}; float height{}; if (SDL_GL_BindTexture(texture.get(), &width, &height) == 0) { return farea{width, height}; } else { return std::nullopt; } } /** * \brief Unbinds a texture from the OpenGL context. * * \param texture the texture to unbind. * * \return `success` if the texture was unbound; `failure` otherwise. */ template <typename T> auto unbind(basic_texture<T>& texture) noexcept -> result { return SDL_GL_UnbindTexture(texture.get()) == 0; } /// \} End of group opengl /// \} End of group video } // namespace gl } // namespace cen #endif // CENTURION_NO_OPENGL #endif // CENTURION_OPENGL_HPP_
25.391051
95
0.718489
Creeperface01
ced556d24274a10ce37286ca3de032c6b4258690
1,432
cpp
C++
src/ParamsLog.cpp
quekyuyang/stitch-cpp
9158d03d4fe2b09d4672b38d0762426178cb646c
[ "MIT" ]
null
null
null
src/ParamsLog.cpp
quekyuyang/stitch-cpp
9158d03d4fe2b09d4672b38d0762426178cb646c
[ "MIT" ]
null
null
null
src/ParamsLog.cpp
quekyuyang/stitch-cpp
9158d03d4fe2b09d4672b38d0762426178cb646c
[ "MIT" ]
null
null
null
#include <vector> #include <fstream> #include "ParamsLog.hpp" #include <nlohmann/json.hpp> using json = nlohmann::json; void ParamsLogManager::addNodeData(std::vector<Node> &nodes) { for (const auto &node : nodes) { std::string ID_pair(node.getID() + "-" + node.getBestLink().getTargetID()); const cv::Mat &homo_mat = node.getBestLink().getHomoMat(); if (homo_mat.empty()) continue; std::vector<double> homo_params; if (homo_mat.isContinuous()) homo_params.assign(homo_mat.begin<double>(),homo_mat.end<double>()); else throw std::runtime_error("Homography matrix not continuous"); _params_logs[ID_pair].addHomoParams(homo_params); _params_logs[ID_pair].addNInliers(node.getBestLink().getNInliers()); } } void ParamsLogManager::saveJson(std::string filepath) { json jdata; for (const auto &entry : _params_logs) { jdata[entry.first]["params"] = entry.second.getHomoParams(); jdata[entry.first]["n_inliers"] = entry.second.getNInliers(); } std::ofstream file(filepath); file << jdata; } void ParamsLog::addHomoParams(std::vector<double> homo_params) { _homo_params_log.push_back(homo_params); } void ParamsLog::addNInliers(int n_inliers) { _n_inliers_log.push_back(n_inliers); } std::vector<std::vector<double>> ParamsLog::getHomoParams() const {return _homo_params_log;} std::vector<int> ParamsLog::getNInliers() const {return _n_inliers_log;}
27.018868
92
0.713687
quekyuyang
ced7b79c6ed690d3423fe8550ea3e244b6efa1de
1,084
cpp
C++
BZOJ/3261/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3261/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
BZOJ/3261/code.cpp
sjj118/OI-Code
964ea6e799d14010f305c7e4aee269d860a781f7
[ "MIT" ]
null
null
null
#include<iostream> #include<cstdio> #define rg register #define rep(i,x,y) for(rg int i=(x);i<=(y);++i) #define per(i,x,y) for(rg int i=(x);i>=(y);--i) using namespace std; const int maxn=6e5+10,maxp=3e7; int root[maxn],n,m,xn; struct Trie{ int tot,son[maxp][2],val[maxp]; int modify(int v,int&k,int d){ int t=++tot;val[t]=val[k]+1; if(d==-1)return t; if((v>>d)&1)son[t][0]=son[k][0],son[t][1]=modify(v,son[k][1],d-1); else son[t][0]=modify(v,son[k][0],d-1),son[t][1]=son[k][1]; return t; } int query(int v,int&l,int&r,int d){ if(d==-1)return 0; int t=!((v>>d)&1); if(val[son[r][t]]-val[son[l][t]])return query(v,son[l][t],son[r][t],d-1)+(1<<d); else return query(v,son[l][!t],son[r][!t],d-1); } }T; int main(){ scanf("%d%d",&n,&m); rep(i,1,n){int x;scanf("%d",&x);root[i]=T.modify(xn,root[i-1],30);xn^=x;} rep(i,1,m){ char op;scanf("\n%c",&op); if(op=='A'){ int x;scanf("%d",&x); ++n;root[n]=T.modify(xn,root[n-1],30);xn^=x; }else{ int l,r,x;scanf("%d%d%d",&l,&r,&x); printf("%d\n",T.query(x^xn,root[l-1],root[r],30)); } } return 0; }
27.1
82
0.550738
sjj118
cedf1d3f2815230f1c11aa68733ec3f2f0a2643b
2,098
cc
C++
core/network/PiiMimeTypeMap.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-19T22:14:18.000Z
2020-04-13T23:27:20.000Z
core/network/PiiMimeTypeMap.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
null
null
null
core/network/PiiMimeTypeMap.cc
topiolli/into
f0a47736f5c93dd32e89e7aad34152ae1afc5583
[ "BSD-3-Clause" ]
14
2015-01-16T05:43:15.000Z
2019-01-29T07:57:11.000Z
/* This file is part of Into. * Copyright (C) Intopii 2013. * All rights reserved. * * Licensees holding a commercial Into license may use this file in * accordance with the commercial license agreement. Please see * LICENSE.commercial for commercial licensing terms. * * Alternatively, this file may be used under the terms of the GNU * Affero General Public License version 3 as published by the Free * Software Foundation. In addition, Intopii gives you special rights * to use Into as a part of open source software projects. Please * refer to LICENSE.AGPL3 for details. */ #include "PiiMimeTypeMap.h" #include <QFile> #include <QRegExp> PiiMimeTypeMap::PiiMimeTypeMap() : d(new Data) { d->mapTypes.insert("html", "text/html"); d->mapTypes.insert("css", "text/css"); d->mapTypes.insert("js", "application/javascript"); d->mapTypes.insert("txt", "text/plain"); d->mapTypes.insert("png", "image/png"); d->mapTypes.insert("jpg", "image/jpeg"); d->mapTypes.insert("pdf", "application/pdf"); } PiiMimeTypeMap::PiiMimeTypeMap(const QString& mimeTypeFile) : d(new Data) { readMimeTypes(mimeTypeFile); } PiiMimeTypeMap::~PiiMimeTypeMap() { delete d; } void PiiMimeTypeMap::readMimeTypes(const QString& fileName) { QFile file(fileName); if (!file.open(QIODevice::ReadOnly)) return; char buffer[1024]; QRegExp reSpace("[\t \n]+"); while (file.readLine(buffer, 1024) > 0) { if (buffer[0] == '#') continue; QStringList lstParts(QString(buffer).split(reSpace, QString::SkipEmptyParts)); if (lstParts.size() < 2) continue; for (int i=1; i<lstParts.size(); ++i) d->mapTypes.insert(lstParts[i], lstParts[0]); } } QString PiiMimeTypeMap::typeForExtension(const QString& extension) const { return d->mapTypes[extension]; } QStringList PiiMimeTypeMap::extensionsForType(const QString& mimeType) const { QStringList lstResult; for (QMap<QString,QString>::const_iterator i=d->mapTypes.begin(); i != d->mapTypes.end(); ++i) if (i.value() == mimeType) lstResult << i.key(); return lstResult; }
27.605263
84
0.693518
topiolli
cee247b8ed4ea3a5e334a00a920cc167c35f4971
1,626
cpp
C++
src/knapsack/dynamic.cpp
ThermalSpan/cpp-knapsack
dcc577a3ef9f9da1f2a85400465f488d91fdd8cf
[ "MIT" ]
null
null
null
src/knapsack/dynamic.cpp
ThermalSpan/cpp-knapsack
dcc577a3ef9f9da1f2a85400465f488d91fdd8cf
[ "MIT" ]
null
null
null
src/knapsack/dynamic.cpp
ThermalSpan/cpp-knapsack
dcc577a3ef9f9da1f2a85400465f488d91fdd8cf
[ "MIT" ]
null
null
null
// // dynamic.cpp // knapsack // // Created by Russell Wilhelm Bentley on 1/26/16. // Copyright (c) 2015 Russell Wilhelm Bentley. // Distributed under the MIT license // #include <iostream> #include "dynamic.h" using namespace std; void dynamicSolve (ItemVec &vec, int capacity) { int x, y, index, doNotTake, doTake; int rowSize = capacity + 1; int columnSize = vec.size () + 1; int arraySize = columnSize * rowSize; int *sumArray = new int[arraySize]; // Here, x refers to [0, capacity] // y refers to [0, n] for (x = 0; x < rowSize; x++) { sumArray[x] = 0; } for (y = 1; y < columnSize; y++) { for (x = 0; x < rowSize; x++) { index = y * rowSize + x; if (vec[y-1].s_weight <= x) { doNotTake = sumArray[ (y-1) * rowSize + x]; doTake = sumArray[ (y-1) * rowSize + (x - vec[y-1].s_weight)] + vec[y-1].s_value; sumArray[index] = max (doNotTake, doTake); } else { sumArray[index] = sumArray[ (y-1) * rowSize + x]; } } } cout << sumArray[arraySize - 1] << endl; char *decision = (char *) malloc (vec.size () * sizeof (char) + 1); decision[vec.size ()] = '\0'; x = capacity; for (y = vec.size (); y > 0; y--) { if (sumArray[y * rowSize + x] == sumArray[ (y-1) * rowSize + x]) { decision[y-1] = '0'; } else { decision[y-1] = '1'; x -= vec[y-1].s_weight; } } string d (decision); cout << d << endl; delete (sumArray); free (decision); }
26.655738
97
0.50123
ThermalSpan
cee4def62b0375fe1890a48a8be5ce80e75f12e7
2,636
cpp
C++
lib/thornhill/src/kernel.cpp
andr3h3nriqu3s11/thornhill
ec31eb06dd914bcb7fd22ff31386b40996656d94
[ "MIT" ]
6
2021-11-06T08:42:41.000Z
2022-01-06T11:42:18.000Z
lib/thornhill/src/kernel.cpp
andr3h3nriqu3s11/thornhill
ec31eb06dd914bcb7fd22ff31386b40996656d94
[ "MIT" ]
1
2022-01-09T18:09:57.000Z
2022-01-09T18:09:57.000Z
lib/thornhill/src/kernel.cpp
andr3h3nriqu3s11/thornhill
ec31eb06dd914bcb7fd22ff31386b40996656d94
[ "MIT" ]
1
2022-01-09T18:07:42.000Z
2022-01-09T18:07:42.000Z
#include <cstring> #include <thornhill> #include "drivers/hardware/serial.hpp" using namespace std; using namespace Thornhill; namespace Thornhill::Kernel { void printChar(char c) { ThornhillSerial::writeCharacter(c); } void print(const char* message, bool appendNewline) { ThornhillSerial::write(message, appendNewline); } int vprintf(const char* fmt, va_list arg) { int length = 0; char* strPtr; char buffer[32]; char c; while ((c = *fmt++)) { if ('%' == c) { switch ((c = *fmt++)) { /* %% => print a single % symbol (escape) */ case '%': printChar('%'); length++; break; /* %c => print a character */ case 'c': printChar((char) va_arg(arg, int)); length++; break; /* %s => print a string */ case 's': strPtr = va_arg(arg, char*); print(strPtr, false); length += strlen(strPtr); break; /* %d => print number as decimal */ case 'd': itoa(buffer, va_arg(arg, int64_t), 10, 32); print(buffer, false); length += strlen(buffer); break; /* %u => print unsigned number as integer */ case 'u': uitoa(buffer, va_arg(arg, uint64_t), 10, 32); print(buffer, false); length += strlen(buffer); break; /* %x => print number as hexadecimal */ case 'x': uitoa(buffer, va_arg(arg, uint64_t), 16, 32); print(buffer, false); length += strlen(buffer); break; /* %n => print newline */ case 'n': printChar('\r'); printChar('\n'); length += 2; break; } } else { printChar(c); length++; } } return length; } void printf(const char* fmt...) { va_list arg; va_start(arg, fmt); vprintf(fmt, arg); va_end(arg); } }
28.344086
69
0.371017
andr3h3nriqu3s11
ceef16b8847785459e6d10d1411ba662812cfd15
3,488
hpp
C++
src/assembler/LinearElasticity.hpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
228
2018-11-23T19:32:42.000Z
2022-03-25T10:30:51.000Z
src/assembler/LinearElasticity.hpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
14
2019-03-11T22:44:14.000Z
2022-03-16T14:50:35.000Z
src/assembler/LinearElasticity.hpp
danielepanozzo/polyfem
34a7719c2a3874b7ecc865c28d8b3d9bbdf7d0ba
[ "MIT" ]
45
2018-12-31T02:04:57.000Z
2022-03-08T02:42:01.000Z
#pragma once #include <polyfem/Common.hpp> #include <polyfem/ElementAssemblyValues.hpp> #include <polyfem/ElementBases.hpp> #include <polyfem/ElasticityUtils.hpp> #include <polyfem/AutodiffTypes.hpp> #include <Eigen/Dense> #include <functional> //local assembler for linear elasticity namespace polyfem { class LinearElasticity { public: ///computes local stiffness matrix is R^{dim²} for bases i,j //vals stores the evaluation for that element //da contains both the quadrature weight and the change of metric in the integral Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 9, 1> assemble(const ElementAssemblyValues &vals, const int i, const int j, const QuadratureVector &da) const; //neccessary for mixing linear model with non-linear collision response Eigen::MatrixXd assemble_hessian(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; //compute gradient of elastic energy, as assembler Eigen::VectorXd assemble_grad(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; //compute elastic energy double compute_energy(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; //kernel of the pde, used in kernel problem Eigen::Matrix<AutodiffScalarGrad, Eigen::Dynamic, 1, 0, 3, 1> kernel(const int dim, const AutodiffGradPt &r) const; //uses autodiff to compute the rhs for a fabbricated solution //uses autogenerated code to compute div(sigma) //pt is the evaluation of the solution at a point Eigen::Matrix<double, Eigen::Dynamic, 1, 0, 3, 1> compute_rhs(const AutodiffHessianPt &pt) const; //compute von mises stress for an element at the local points void compute_von_mises_stresses(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &stresses) const; //compute stress tensor for an element at the local points void compute_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, Eigen::MatrixXd &tensor) const; //size of the problem, this is a tensor problem so the size is the size of the mesh inline int &size() { return size_; } inline int size() const { return size_; } //inialize material parameter void set_parameters(const json &params); //initialize material param per element void init_multimaterial(const bool is_volume, const Eigen::MatrixXd &Es, const Eigen::MatrixXd &nus); //class that stores and compute lame parameters per point const LameParameters &lame_params() const { return params_; } private: int size_ = 2; //class that stores and compute lame parameters per point LameParameters params_; void assign_stress_tensor(const int el_id, const ElementBases &bs, const ElementBases &gbs, const Eigen::MatrixXd &local_pts, const Eigen::MatrixXd &displacement, const int all_size, Eigen::MatrixXd &all, const std::function<Eigen::MatrixXd(const Eigen::MatrixXd &)> &fun) const; //aux function that computes energy //double compute_energy is the same with T=double //assemble_grad is the same with T=DScalar1 and return .getGradient() template <typename T> T compute_energy_aux(const ElementAssemblyValues &vals, const Eigen::MatrixXd &displacement, const QuadratureVector &da) const; }; } // namespace polyfem
47.780822
281
0.770069
danielepanozzo
cef7d285a9c0e707d21f972b609644e5a3683a3b
66,737
cpp
C++
test/examples/conc_queue_examples.cpp
giucamp/density
b6a9653b36ec0c37c26f879574295a56e6345a7b
[ "BSL-1.0" ]
18
2016-05-24T11:46:43.000Z
2020-11-03T17:11:27.000Z
test/examples/conc_queue_examples.cpp
giucamp/density
b6a9653b36ec0c37c26f879574295a56e6345a7b
[ "BSL-1.0" ]
13
2017-11-04T17:41:30.000Z
2018-09-05T11:32:22.000Z
test/examples/conc_queue_examples.cpp
giucamp/density
b6a9653b36ec0c37c26f879574295a56e6345a7b
[ "BSL-1.0" ]
1
2018-09-27T21:00:20.000Z
2018-09-27T21:00:20.000Z
// Copyright Giuseppe Campana (giu.campana@gmail.com) 2016-2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #include "../test_framework/density_test_common.h" // #include "test_framework/progress.h" #include <assert.h> #include <chrono> #include <complex> #include <density/conc_heter_queue.h> #include <density/io_runtimetype_features.h> #include <iostream> #include <iterator> #include <string> // if assert expands to nothing, some local variable becomes unused #if defined(_MSC_VER) && defined(NDEBUG) #pragma warning(push) #pragma warning(disable : 4189) // local variable is initialized but not referenced #endif namespace density_tests { uint32_t compute_checksum(const void * i_data, size_t i_lenght); void conc_heterogeneous_queue_put_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue push example 1] queue.push(12); queue.push(std::string("Hello world!!")); //! [conc_heter_queue push example 1] //! [conc_heter_queue emplace example 1] queue.emplace<int>(); queue.emplace<std::string>(12, '-'); //! [conc_heter_queue emplace example 1] { //! [conc_heter_queue start_push example 1] auto put = queue.start_push(12); put.element() += 2; put.commit(); // commits a 14 //! [conc_heter_queue start_push example 1] } { //! [conc_heter_queue start_emplace example 1] auto put = queue.start_emplace<std::string>(4, '*'); put.element() += "****"; put.commit(); // commits a "********" //! [conc_heter_queue start_emplace example 1] } } { //! [conc_heter_queue dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); queue.dyn_push(type); // appends 0 //! [conc_heter_queue dyn_push example 1] } { //! [conc_heter_queue dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.dyn_push_copy(type, &source); //! [conc_heter_queue dyn_push_copy example 1] } { //! [conc_heter_queue dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.dyn_push_move(type, &source); //! [conc_heter_queue dyn_push_move example 1] } { //! [conc_heter_queue start_dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); auto put = queue.start_dyn_push(type); put.commit(); //! [conc_heter_queue start_dyn_push example 1] } { //! [conc_heter_queue start_dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_dyn_push_copy(type, &source); put.commit(); //! [conc_heter_queue start_dyn_push_copy example 1] } { //! [conc_heter_queue start_dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_dyn_push_move(type, &source); put.commit(); //! [conc_heter_queue start_dyn_push_move example 1] } } void conc_heterogeneous_queue_put_transaction_samples() { using namespace density; { //! [conc_heter_queue put_transaction default_construct example 1] conc_heter_queue<>::put_transaction<> transaction; assert(transaction.empty()); //! [conc_heter_queue put_transaction default_construct example 1] } { //! [conc_heter_queue put_transaction copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::put_transaction<>>::value, ""); static_assert( !std::is_copy_constructible<conc_heter_queue<int>::put_transaction<>>::value, ""); //! [conc_heter_queue put_transaction copy_construct example 1] } { //! [conc_heter_queue put_transaction copy_assign example 1] static_assert( !std::is_copy_assignable<conc_heter_queue<>::put_transaction<>>::value, ""); static_assert( !std::is_copy_assignable<conc_heter_queue<int>::put_transaction<>>::value, ""); //! [conc_heter_queue put_transaction copy_assign example 1] } { //! [conc_heter_queue put_transaction move_construct example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_push(1); // move from transaction1 to transaction2 auto transaction2(std::move(transaction1)); assert(transaction1.empty()); assert(transaction2.element() == 1); // commit transaction2 transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue put_transaction move_construct example 1] //! [conc_heter_queue put_transaction move_construct example 2] // put_transaction<void> can be move constructed from any put_transaction<T> static_assert( std::is_constructible< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); // put_transaction<T> can be move constructed only from put_transaction<T> static_assert( !std::is_constructible< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( !std::is_constructible< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<float> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); //! [conc_heter_queue put_transaction move_construct example 2] } { //! [conc_heter_queue put_transaction move_assign example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_push(1); conc_heter_queue<>::put_transaction<> transaction2; transaction2 = std::move(transaction1); assert(transaction1.empty()); transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue put_transaction move_assign example 1] //! [conc_heter_queue put_transaction move_assign example 2] // put_transaction<void> can be move assigned from any put_transaction<T> static_assert( std::is_assignable< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::put_transaction<void>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); // put_transaction<T> can be move assigned only from put_transaction<T> static_assert( !std::is_assignable< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<void> &&>::value, ""); static_assert( !std::is_assignable< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<float> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::put_transaction<int>, conc_heter_queue<>::put_transaction<int> &&>::value, ""); //! [conc_heter_queue put_transaction move_assign example 2] } { //! [conc_heter_queue put_transaction raw_allocate example 1] conc_heter_queue<> queue; struct Msg { std::chrono::high_resolution_clock::time_point m_time = std::chrono::high_resolution_clock::now(); size_t m_len = 0; void * m_data = nullptr; }; auto post_message = [&queue](const void * i_data, size_t i_len) { auto transaction = queue.start_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_data = transaction.raw_allocate(i_len, 1); memcpy(transaction.element().m_data, i_data, i_len); assert( !transaction .empty()); // a put transaction is not empty if it's bound to an element being put transaction.commit(); assert(transaction.empty()); // the commit makes the transaction empty }; auto const start_time = std::chrono::high_resolution_clock::now(); auto consume_all_msgs = [&queue, &start_time] { while (auto consume = queue.try_start_consume()) { auto const checksum = compute_checksum(consume.element<Msg>().m_data, consume.element<Msg>().m_len); std::cout << "Message with checksum " << checksum << " at "; std::cout << (consume.element<Msg>().m_time - start_time).count() << std::endl; consume.commit(); } }; int msg_1 = 42, msg_2 = 567; post_message(&msg_1, sizeof(msg_1)); post_message(&msg_2, sizeof(msg_2)); consume_all_msgs(); //! [conc_heter_queue put_transaction raw_allocate example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction raw_allocate_copy example 1] struct Msg { size_t m_len = 0; char * m_chars = nullptr; }; auto post_message = [&queue](const char * i_data, size_t i_len) { auto transaction = queue.start_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_chars = transaction.raw_allocate_copy(i_data, i_data + i_len); memcpy(transaction.element().m_chars, i_data, i_len); transaction.commit(); }; //! [conc_heter_queue put_transaction raw_allocate_copy example 1] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction raw_allocate_copy example 2] struct Msg { char * m_chars = nullptr; }; auto post_message = [&queue](const std::string & i_string) { auto transaction = queue.start_emplace<Msg>(); transaction.element().m_chars = transaction.raw_allocate_copy(i_string); transaction.commit(); }; //! [conc_heter_queue put_transaction raw_allocate_copy example 2] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction empty example 1] conc_heter_queue<>::put_transaction<> transaction; assert(transaction.empty()); transaction = queue.start_push(1); assert(!transaction.empty()); //! [conc_heter_queue put_transaction empty example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction operator_bool example 1] conc_heter_queue<>::put_transaction<> transaction; assert(!transaction); transaction = queue.start_push(1); assert(transaction); //! [conc_heter_queue put_transaction operator_bool example 1] } { //! [conc_heter_queue put_transaction cancel example 1] conc_heter_queue<> queue; // start and cancel a put assert(queue.empty()); auto put = queue.start_push(42); /* assert(queue.empty()); <- this assert would trigger an undefined behavior, because it would access the queue during a non-reentrant put transaction. */ assert(!put.empty()); put.cancel(); assert(queue.empty() && put.empty()); // start and commit a put put = queue.start_push(42); put.commit(); assert(queue.try_start_consume().element<int>() == 42); //! [conc_heter_queue put_transaction cancel example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction element_ptr example 1] int value = 42; auto put = queue.start_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(*static_cast<int *>(put.element_ptr()) == 42); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; put.commit(); //! [conc_heter_queue put_transaction element_ptr example 1] //! [conc_heter_queue put_transaction element_ptr example 2] auto put_1 = queue.start_push(1); assert(*static_cast<int *>(put_1.element_ptr()) == 1); // this is fine assert(put_1.element() == 1); // this is better put_1.commit(); //! [conc_heter_queue put_transaction element_ptr example 2] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction complete_type example 1] int value = 42; auto put = queue.start_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(put.complete_type().is<int>()); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; //! [conc_heter_queue put_transaction complete_type example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue put_transaction destroy example 1] queue.start_push(42); /* this transaction is destroyed without being committed, so it gets canceled automatically. */ //! [conc_heter_queue put_transaction destroy example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue typed_put_transaction element example 1] int value = 42; auto untyped_put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); auto typed_put = queue.start_reentrant_push(42.); /* typed_put = std::move(untyped_put); <- this would not compile: can't assign an untyped transaction to a typed transaction */ assert(typed_put.element() == 42.); //! [conc_heter_queue typed_put_transaction element example 1] } } void conc_heterogeneous_queue_consume_operation_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue consume_operation default_construct example 1] conc_heter_queue<>::consume_operation consume; assert(consume.empty()); //! [conc_heter_queue consume_operation default_construct example 1] } //! [conc_heter_queue consume_operation copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::consume_operation>::value, ""); //! [conc_heter_queue consume_operation copy_construct example 1] //! [conc_heter_queue consume_operation copy_assign example 1] static_assert(!std::is_copy_assignable<conc_heter_queue<>::consume_operation>::value, ""); //! [conc_heter_queue consume_operation copy_assign example 1] { //! [conc_heter_queue consume_operation move_construct example 1] conc_heter_queue<> queue; queue.push(42); auto consume = queue.try_start_consume(); auto consume_1 = std::move(consume); assert(consume.empty() && !consume_1.empty()); consume_1.commit(); //! [conc_heter_queue consume_operation move_construct example 1] } { //! [conc_heter_queue consume_operation move_assign example 1] conc_heter_queue<> queue; queue.push(42); queue.push(43); auto consume = queue.try_start_consume(); conc_heter_queue<>::consume_operation consume_1; consume_1 = std::move(consume); assert(consume.empty() && !consume_1.empty()); consume_1.commit(); //! [conc_heter_queue consume_operation move_assign example 1] } { //! [conc_heter_queue consume_operation destroy example 1] conc_heter_queue<> queue; queue.push(42); // this consumed is started and destroyed before being committed, so it has no observable effects queue.try_start_consume(); //! [conc_heter_queue consume_operation destroy example 1] } { //! [conc_heter_queue consume_operation empty example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume; assert(consume.empty()); consume = queue.try_start_consume(); assert(!consume.empty()); //! [conc_heter_queue consume_operation empty example 1] } { //! [conc_heter_queue consume_operation operator_bool example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume; assert(consume.empty() == !consume); consume = queue.try_start_consume(); assert(consume.empty() == !consume); //! [conc_heter_queue consume_operation operator_bool example 1] } { //! [conc_heter_queue consume_operation commit_nodestroy example 1] conc_heter_queue<> queue; queue.emplace<std::string>("abc"); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); consume.complete_type().destroy(consume.element_ptr()); // the string has already been destroyed. Calling commit would trigger an undefined behavior consume.commit_nodestroy(); //! [conc_heter_queue consume_operation commit_nodestroy example 1] } { //! [conc_heter_queue consume_operation cancel example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); consume.cancel(); // there is still a 42 in the queue assert(queue.try_start_consume().element<int>() == 42); //! [conc_heter_queue consume_operation cancel example 1] } { //! [conc_heter_queue consume_operation complete_type example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); assert(consume.complete_type().is<int>()); assert( consume.complete_type() == runtime_type<>::make<int>()); // same to the previous assert assert(consume.element<int>() == 42); consume.commit(); //! [conc_heter_queue consume_operation complete_type example 1] } { //! [conc_heter_queue consume_operation element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); ++*static_cast<int *>(consume.element_ptr()); assert(consume.element<int>() == 43); consume.commit(); //! [conc_heter_queue consume_operation element_ptr example 1] } { //! [conc_heter_queue consume_operation swap example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume_1 = queue.try_start_consume(); conc_heter_queue<>::consume_operation consume_2; { using namespace std; swap(consume_1, consume_2); } assert(consume_2.complete_type().is<int>()); assert( consume_2.complete_type() == runtime_type<>::make<int>()); // same to the previous assert assert(consume_2.element<int>() == 42); consume_2.commit(); assert(queue.empty()); //! [conc_heter_queue consume_operation swap example 1] } { //! [conc_heter_queue consume_operation unaligned_element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); bool const is_overaligned = alignof(int) > conc_heter_queue<>::min_alignment; void * const unaligned_ptr = consume.unaligned_element_ptr(); int * element_ptr; if (is_overaligned) { element_ptr = static_cast<int *>(address_upper_align(unaligned_ptr, alignof(int))); } else { assert(unaligned_ptr == consume.element_ptr()); element_ptr = static_cast<int *>(unaligned_ptr); } assert(address_is_aligned(element_ptr, alignof(int))); std::cout << "An int: " << *element_ptr << std::endl; consume.commit(); //! [conc_heter_queue consume_operation unaligned_element_ptr example 1] } { //! [conc_heter_queue consume_operation element example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::consume_operation consume = queue.try_start_consume(); assert(consume.complete_type().is<int>()); std::cout << "An int: " << consume.element<int>() << std::endl; /* std::cout << "An float: " << consume.element<float>() << std::endl; this would trigger an undefined behavior, because the element is not a float */ consume.commit(); //! [conc_heter_queue consume_operation element example 1] } } void conc_heterogeneous_queue_reentrant_put_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_push example 1] queue.reentrant_push(12); queue.reentrant_push(std::string("Hello world!!")); //! [conc_heter_queue reentrant_push example 1] //! [conc_heter_queue reentrant_emplace example 1] queue.reentrant_emplace<int>(); queue.reentrant_emplace<std::string>(12, '-'); //! [conc_heter_queue reentrant_emplace example 1] { //! [conc_heter_queue start_reentrant_push example 1] auto put = queue.start_reentrant_push(12); put.element() += 2; put.commit(); // commits a 14 //! [conc_heter_queue start_reentrant_push example 1] } { //! [conc_heter_queue start_reentrant_emplace example 1] auto put = queue.start_reentrant_emplace<std::string>(4, '*'); put.element() += "****"; put.commit(); // commits a "********" //! [conc_heter_queue start_reentrant_emplace example 1] } } { //! [conc_heter_queue reentrant_dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); queue.reentrant_dyn_push(type); // appends 0 //! [conc_heter_queue reentrant_dyn_push example 1] } { //! [conc_heter_queue reentrant_dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.reentrant_dyn_push_copy(type, &source); //! [conc_heter_queue reentrant_dyn_push_copy example 1] } { //! [conc_heter_queue reentrant_dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); queue.reentrant_dyn_push_move(type, &source); //! [conc_heter_queue reentrant_dyn_push_move example 1] } { //! [conc_heter_queue start_reentrant_dyn_push example 1] using MyRunTimeType = runtime_type<f_default_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; auto const type = MyRunTimeType::make<int>(); auto put = queue.start_reentrant_dyn_push(type); put.commit(); //! [conc_heter_queue start_reentrant_dyn_push example 1] } { //! [conc_heter_queue start_reentrant_dyn_push_copy example 1] using MyRunTimeType = runtime_type<f_copy_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string const source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_reentrant_dyn_push_copy(type, &source); put.commit(); //! [conc_heter_queue start_reentrant_dyn_push_copy example 1] } { //! [conc_heter_queue start_reentrant_dyn_push_move example 1] using MyRunTimeType = runtime_type<f_move_construct, f_destroy, f_size, f_alignment>; conc_heter_queue<MyRunTimeType> queue; std::string source("Hello world!!"); auto const type = MyRunTimeType::make<decltype(source)>(); auto put = queue.start_reentrant_dyn_push_move(type, &source); put.commit(); //! [conc_heter_queue start_reentrant_dyn_push_move example 1] } } void conc_heterogeneous_queue_reentrant_put_transaction_samples() { using namespace density; { //! [conc_heter_queue reentrant_put_transaction default_construct example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(transaction.empty()); //! [conc_heter_queue reentrant_put_transaction default_construct example 1] } { //! [conc_heter_queue reentrant_put_transaction copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::reentrant_put_transaction<>>::value, ""); static_assert( !std::is_copy_constructible< conc_heter_queue<int>::reentrant_put_transaction<>>::value, ""); //! [conc_heter_queue reentrant_put_transaction copy_construct example 1] } { //! [conc_heter_queue reentrant_put_transaction copy_assign example 1] static_assert( !std::is_copy_assignable<conc_heter_queue<>::reentrant_put_transaction<>>::value, ""); static_assert( !std::is_copy_assignable<conc_heter_queue<int>::reentrant_put_transaction<>>::value, ""); //! [conc_heter_queue reentrant_put_transaction copy_assign example 1] } { //! [conc_heter_queue reentrant_put_transaction move_construct example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_reentrant_push(1); // move from transaction1 to transaction2 auto transaction2(std::move(transaction1)); assert(transaction1.empty()); assert(transaction2.element() == 1); // commit transaction2 transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue reentrant_put_transaction move_construct example 1] //! [conc_heter_queue reentrant_put_transaction move_construct example 2] // reentrant_put_transaction<void> can be move constructed from any reentrant_put_transaction<T> static_assert( std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); // reentrant_put_transaction<T> can be move constructed only from reentrant_put_transaction<T> static_assert( !std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( !std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<float> &&>::value, ""); static_assert( std::is_constructible< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); //! [conc_heter_queue reentrant_put_transaction move_construct example 2] } { //! [conc_heter_queue reentrant_put_transaction move_assign example 1] conc_heter_queue<> queue; auto transaction1 = queue.start_reentrant_push(1); conc_heter_queue<>::reentrant_put_transaction<> transaction2; transaction2 = queue.start_reentrant_push(1); transaction2 = std::move(transaction1); assert(transaction1.empty()); transaction2.commit(); assert(transaction2.empty()); //! [conc_heter_queue reentrant_put_transaction move_assign example 1] //! [conc_heter_queue reentrant_put_transaction move_assign example 2] // reentrant_put_transaction<void> can be move assigned from any reentrant_put_transaction<T> static_assert( std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<void>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); // reentrant_put_transaction<T> can be move assigned only from reentrant_put_transaction<T> static_assert( !std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<void> &&>::value, ""); static_assert( !std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<float> &&>::value, ""); static_assert( std::is_assignable< conc_heter_queue<>::reentrant_put_transaction<int>, conc_heter_queue<>::reentrant_put_transaction<int> &&>::value, ""); //! [conc_heter_queue reentrant_put_transaction move_assign example 2] } { //! [conc_heter_queue reentrant_put_transaction raw_allocate example 1] conc_heter_queue<> queue; struct Msg { std::chrono::high_resolution_clock::time_point m_time = std::chrono::high_resolution_clock::now(); size_t m_len = 0; void * m_data = nullptr; }; auto post_message = [&queue](const void * i_data, size_t i_len) { auto transaction = queue.start_reentrant_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_data = transaction.raw_allocate(i_len, 1); memcpy(transaction.element().m_data, i_data, i_len); assert( !transaction .empty()); // a put transaction is not empty if it's bound to an element being put transaction.commit(); assert(transaction.empty()); // the commit makes the transaction empty }; auto const start_time = std::chrono::high_resolution_clock::now(); auto consume_all_msgs = [&queue, &start_time] { while (auto consume = queue.try_start_reentrant_consume()) { auto const checksum = compute_checksum(consume.element<Msg>().m_data, consume.element<Msg>().m_len); std::cout << "Message with checksum " << checksum << " at "; std::cout << (consume.element<Msg>().m_time - start_time).count() << std::endl; consume.commit(); } }; int msg_1 = 42, msg_2 = 567; post_message(&msg_1, sizeof(msg_1)); post_message(&msg_2, sizeof(msg_2)); consume_all_msgs(); //! [conc_heter_queue reentrant_put_transaction raw_allocate example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 1] struct Msg { size_t m_len = 0; char * m_chars = nullptr; }; auto post_message = [&queue](const char * i_data, size_t i_len) { auto transaction = queue.start_reentrant_emplace<Msg>(); transaction.element().m_len = i_len; transaction.element().m_chars = transaction.raw_allocate_copy(i_data, i_data + i_len); memcpy(transaction.element().m_chars, i_data, i_len); transaction.commit(); }; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 1] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 2] struct Msg { char * m_chars = nullptr; }; auto post_message = [&queue](const std::string & i_string) { auto transaction = queue.start_reentrant_emplace<Msg>(); transaction.element().m_chars = transaction.raw_allocate_copy(i_string); transaction.commit(); }; //! [conc_heter_queue reentrant_put_transaction raw_allocate_copy example 2] (void)post_message; } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction empty example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(transaction.empty()); transaction = queue.start_reentrant_push(1); assert(!transaction.empty()); //! [conc_heter_queue reentrant_put_transaction empty example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction operator_bool example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(!transaction); transaction = queue.start_reentrant_push(1); assert(transaction); //! [conc_heter_queue reentrant_put_transaction operator_bool example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction queue example 1] conc_heter_queue<>::reentrant_put_transaction<> transaction; assert(transaction.queue() == nullptr); transaction = queue.start_reentrant_push(1); assert(transaction.queue() == &queue); //! [conc_heter_queue reentrant_put_transaction queue example 1] } { //! [conc_heter_queue reentrant_put_transaction cancel example 1] conc_heter_queue<> queue; // start and cancel a put assert(queue.empty()); auto put = queue.start_reentrant_push(42); /* assert(queue.empty()); <- this assert would trigger an undefined behavior, because it would access the queue during a non-reentrant put transaction. */ assert(!put.empty()); put.cancel(); assert(queue.empty() && put.empty()); // start and commit a put put = queue.start_reentrant_push(42); put.commit(); assert(queue.try_start_reentrant_consume().element<int>() == 42); //! [conc_heter_queue reentrant_put_transaction cancel example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction element_ptr example 1] int value = 42; auto put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(*static_cast<int *>(put.element_ptr()) == 42); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; put.commit(); //! [conc_heter_queue reentrant_put_transaction element_ptr example 1] //! [conc_heter_queue reentrant_put_transaction element_ptr example 2] auto put_1 = queue.start_reentrant_push(1); assert(*static_cast<int *>(put_1.element_ptr()) == 1); // this is fine assert(put_1.element() == 1); // this is better put_1.commit(); //! [conc_heter_queue reentrant_put_transaction element_ptr example 2] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction complete_type example 1] int value = 42; auto put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); assert(put.complete_type().is<int>()); std::cout << "Putting an " << put.complete_type().type_info().name() << "..." << std::endl; //! [conc_heter_queue reentrant_put_transaction complete_type example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_put_transaction destroy example 1] queue.start_reentrant_push( 42); /* this transaction is destroyed without being committed, so it gets canceled automatically. */ //! [conc_heter_queue reentrant_put_transaction destroy example 1] } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_typed_put_transaction element example 1] int value = 42; auto untyped_put = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<decltype(value)>(), &value); auto typed_put = queue.start_reentrant_push(42.); /* typed_put = std::move(untyped_put); <- this would not compile: can't assign an untyped transaction to a typed transaction */ assert(typed_put.element() == 42.); //! [conc_heter_queue reentrant_typed_put_transaction element example 1] } } void conc_heterogeneous_queue_reentrant_consume_operation_samples() { using namespace density; { conc_heter_queue<> queue; //! [conc_heter_queue reentrant_consume_operation default_construct example 1] conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty()); //! [conc_heter_queue reentrant_consume_operation default_construct example 1] } //! [conc_heter_queue reentrant_consume_operation copy_construct example 1] static_assert( !std::is_copy_constructible<conc_heter_queue<>::reentrant_consume_operation>::value, ""); //! [conc_heter_queue reentrant_consume_operation copy_construct example 1] //! [conc_heter_queue reentrant_consume_operation copy_assign example 1] static_assert( !std::is_copy_assignable<conc_heter_queue<>::reentrant_consume_operation>::value, ""); //! [conc_heter_queue reentrant_consume_operation copy_assign example 1] { //! [conc_heter_queue reentrant_consume_operation move_construct example 1] conc_heter_queue<> queue; queue.push(42); auto consume = queue.try_start_reentrant_consume(); auto consume_1 = std::move(consume); assert(consume.empty() && !consume_1.empty()); consume_1.commit(); //! [conc_heter_queue reentrant_consume_operation move_construct example 1] } { //! [conc_heter_queue reentrant_consume_operation move_assign example 1] conc_heter_queue<> queue; queue.push(42); queue.push(43); auto consume = queue.try_start_reentrant_consume(); consume.cancel(); conc_heter_queue<>::reentrant_consume_operation consume_1; consume = queue.try_start_reentrant_consume(); consume_1 = std::move(consume); assert(consume.empty()); assert(!consume_1.empty()); consume_1.commit(); //! [conc_heter_queue reentrant_consume_operation move_assign example 1] } { //! [conc_heter_queue reentrant_consume_operation destroy example 1] conc_heter_queue<> queue; queue.push(42); // this consumed is started and destroyed before being committed, so it has no observable effects queue.try_start_reentrant_consume(); //! [conc_heter_queue reentrant_consume_operation destroy example 1] } { //! [conc_heter_queue reentrant_consume_operation empty example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty()); consume = queue.try_start_reentrant_consume(); assert(!consume.empty()); //! [conc_heter_queue reentrant_consume_operation empty example 1] } { //! [conc_heter_queue reentrant_consume_operation operator_bool example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty() == !consume); consume = queue.try_start_reentrant_consume(); assert(consume.empty() == !consume); //! [conc_heter_queue reentrant_consume_operation operator_bool example 1] } { //! [conc_heter_queue reentrant_consume_operation queue example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume; assert(consume.empty() && !consume && consume.queue() == nullptr); consume = queue.try_start_reentrant_consume(); assert(!consume.empty() && !!consume && consume.queue() == &queue); //! [conc_heter_queue reentrant_consume_operation queue example 1] } { //! [conc_heter_queue reentrant_consume_operation commit_nodestroy example 1] conc_heter_queue<> queue; queue.emplace<std::string>("abc"); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); consume.complete_type().destroy(consume.element_ptr()); // the string has already been destroyed. Calling commit would trigger an undefined behavior consume.commit_nodestroy(); //! [conc_heter_queue reentrant_consume_operation commit_nodestroy example 1] } { //! [conc_heter_queue reentrant_consume_operation swap example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume_1 = queue.try_start_reentrant_consume(); conc_heter_queue<>::reentrant_consume_operation consume_2; { using namespace std; swap(consume_1, consume_2); } assert(consume_2.complete_type().is<int>()); assert( consume_2.complete_type() == runtime_type<>::make<int>()); // same to the previous assert assert(consume_2.element<int>() == 42); consume_2.commit(); assert(queue.empty()); //! [conc_heter_queue reentrant_consume_operation swap example 1] } { //! [conc_heter_queue reentrant_consume_operation cancel example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); consume.cancel(); // there is still a 42 in the queue assert(queue.try_start_reentrant_consume().element<int>() == 42); //! [conc_heter_queue reentrant_consume_operation cancel example 1] } { //! [conc_heter_queue reentrant_consume_operation complete_type example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); assert(consume.complete_type().is<int>()); assert( consume.complete_type() == runtime_type<>::make<int>()); // same to the previous assert consume.commit(); assert(queue.empty()); //! [conc_heter_queue reentrant_consume_operation complete_type example 1] } { //! [conc_heter_queue reentrant_consume_operation element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); ++*static_cast<int *>(consume.element_ptr()); assert(consume.element<int>() == 43); consume.commit(); //! [conc_heter_queue reentrant_consume_operation element_ptr example 1] } { //! [conc_heter_queue reentrant_consume_operation unaligned_element_ptr example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); bool const is_overaligned = alignof(int) > conc_heter_queue<>::min_alignment; void * const unaligned_ptr = consume.unaligned_element_ptr(); int * element_ptr; if (is_overaligned) { element_ptr = static_cast<int *>(address_upper_align(unaligned_ptr, alignof(int))); } else { assert(unaligned_ptr == consume.element_ptr()); element_ptr = static_cast<int *>(unaligned_ptr); } assert(address_is_aligned(element_ptr, alignof(int))); std::cout << "An int: " << *element_ptr << std::endl; consume.commit(); //! [conc_heter_queue reentrant_consume_operation unaligned_element_ptr example 1] } { //! [conc_heter_queue reentrant_consume_operation element example 1] conc_heter_queue<> queue; queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume = queue.try_start_reentrant_consume(); assert(consume.complete_type().is<int>()); std::cout << "An int: " << consume.element<int>() << std::endl; /* std::cout << "An float: " << consume.element<float>() << std::endl; this would trigger an undefined behavior, because the element is not a float */ consume.commit(); //! [conc_heter_queue reentrant_consume_operation element example 1] } } void conc_heterogeneous_queue_samples_1() { //! [conc_heter_queue example 3] using namespace density; /* a runtime_type is internally like a pointer to a v-table, but it can contain functions or data (like in the case of f_size and f_alignment). */ using MyRunTimeType = runtime_type< f_default_construct, f_copy_construct, f_destroy, f_size, f_alignment, f_ostream, f_istream, f_rtti>; conc_heter_queue<MyRunTimeType> queue; queue.push(4); queue.push(std::complex<double>(1., 4.)); queue.emplace<std::string>("Hello!!"); // queue.emplace<std::thread>(); - This would not compile because std::thread does not have a << operator for streams // consume all the elements while (auto consume = queue.try_start_consume()) { /* this is like: give me the function at the 6-th row in the v-table. The type f_ostream is converted to an index at compile time. */ auto const ostream_feature = consume.complete_type().get_feature<f_ostream>(); ostream_feature(std::cout, consume.element_ptr()); // this invokes the feature std::cout << "\n"; consume .commit(); // don't forget the commit, otherwise the element will remain in the queue } //! [conc_heter_queue example 3] //! [conc_heter_queue example 4] // this local function reads from std::cin an object of a given type and puts it in the queue auto ask_and_put = [&](const MyRunTimeType & i_type) { // for this we exploit the feature f_rtti that we have included in MyRunTimeType std::cout << "Enter a " << i_type.type_info().name() << std::endl; auto const istream_feature = i_type.get_feature<f_istream>(); auto put = queue.start_dyn_push(i_type); istream_feature(std::cin, put.element_ptr()); /* if an exception is thrown before the commit, the put is canceled without ever having observable side effects. */ put.commit(); }; ask_and_put(MyRunTimeType::make<int>()); ask_and_put(MyRunTimeType::make<std::string>()); //! [conc_heter_queue example 4] } void conc_heterogeneous_queue_samples(std::ostream & i_ostream) { PrintScopeDuration dur(i_ostream, "concurrent heterogeneous queue samples"); using namespace density; { //! [conc_heter_queue put example 1] conc_heter_queue<> queue; queue.push(19); // the parameter can be an l-value or an r-value queue.emplace<std::string>(8, '*'); // pushes "********" //! [conc_heter_queue put example 1] //! [conc_heter_queue example 2] auto consume = queue.try_start_consume(); int my_int = consume.element<int>(); consume.commit(); consume = queue.try_start_consume(); std::string my_string = consume.element<std::string>(); consume.commit(); //! [conc_heter_queue example 3 (void)my_int; (void)my_string; } { //! [conc_heter_queue put example 2] conc_heter_queue<> queue; struct MessageInABottle { const char * m_text = nullptr; }; auto transaction = queue.start_emplace<MessageInABottle>(); transaction.element().m_text = transaction.raw_allocate_copy("Hello world!"); transaction.commit(); //! [conc_heter_queue put example 2] //! [conc_heter_queue consume example 1] auto consume = queue.try_start_consume(); if (consume.complete_type().is<std::string>()) { std::cout << consume.element<std::string>() << std::endl; } else if (consume.complete_type().is<MessageInABottle>()) { std::cout << consume.element<MessageInABottle>().m_text << std::endl; } consume.commit(); //! [conc_heter_queue consume example 1] } { //! [conc_heter_queue default_construct example 1] conc_heter_queue<> queue; assert(queue.empty()); //! [conc_heter_queue default_construct example 1] } { //! [conc_heter_queue move_construct example 1] using MyRunTimeType = runtime_type< f_default_construct, f_copy_construct, f_destroy, f_size, f_alignment, f_equal>; conc_heter_queue<MyRunTimeType> queue; queue.push(std::string()); queue.push(std::make_pair(4., 1)); conc_heter_queue<MyRunTimeType> queue_1(std::move(queue)); assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue move_construct example 1] } { //! [conc_heter_queue construct_copy_alloc example 1] default_allocator allocator; conc_heter_queue<> queue(allocator); assert(queue.empty()); //! [conc_heter_queue construct_copy_alloc example 1] } { //! [conc_heter_queue construct_move_alloc example 1] default_allocator allocator; conc_heter_queue<> queue(std::move(allocator)); assert(queue.empty()); //! [conc_heter_queue construct_move_alloc example 1] } { //! [conc_heter_queue move_assign example 1] using MyRunTimeType = runtime_type< f_default_construct, f_copy_construct, f_destroy, f_size, f_alignment, f_equal>; conc_heter_queue<MyRunTimeType> queue; queue.push(std::string()); queue.push(std::make_pair(4., 1)); conc_heter_queue<MyRunTimeType> queue_1; queue_1 = std::move(queue); assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue move_assign example 1] } { //! [conc_heter_queue get_allocator example 1] conc_heter_queue<> queue; assert(queue.get_allocator() == default_allocator()); //! [conc_heter_queue get_allocator example 1] } { //! [conc_heter_queue get_allocator_ref example 1] conc_heter_queue<> queue; assert(queue.get_allocator_ref() == default_allocator()); //! [conc_heter_queue get_allocator_ref example 1] } { //! [conc_heter_queue get_allocator_ref example 2] conc_heter_queue<> queue; auto const & queue_ref = queue; assert(queue_ref.get_allocator_ref() == default_allocator()); //! [conc_heter_queue get_allocator_ref example 2] (void)queue_ref; } { //! [conc_heter_queue swap example 1] conc_heter_queue<> queue, queue_1; queue.push(1); swap(queue, queue_1); assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue swap example 1] } { //! [conc_heter_queue swap example 2] conc_heter_queue<> queue, queue_1; queue.push(1); { using namespace std; swap(queue, queue_1); } assert(queue.empty()); assert(!queue_1.empty()); //! [conc_heter_queue swap example 2] } { //! [conc_heter_queue empty example 1] conc_heter_queue<> queue; assert(queue.empty()); queue.push(1); assert(!queue.empty()); //! [conc_heter_queue empty example 1] } { //! [conc_heter_queue clear example 1] conc_heter_queue<> queue; queue.push(1); queue.clear(); assert(queue.empty()); //! [conc_heter_queue clear example 1] } { //! [conc_heter_queue pop example 1] conc_heter_queue<> queue; queue.push(1); queue.push(2); queue.pop(); auto consume = queue.try_start_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue pop example 1] } { //! [conc_heter_queue try_pop example 1] conc_heter_queue<> queue; bool pop_result = queue.try_pop(); assert(pop_result == false); queue.push(1); queue.push(2); pop_result = queue.try_pop(); assert(pop_result == true); auto consume = queue.try_start_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue try_pop example 1] (void)pop_result; } { //! [conc_heter_queue try_start_consume example 1] conc_heter_queue<> queue; auto consume_1 = queue.try_start_consume(); assert(!consume_1); queue.push(42); auto consume_2 = queue.try_start_consume(); assert(consume_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_consume example 1] } { //! [conc_heter_queue try_start_consume_ example 1] conc_heter_queue<> queue; conc_heter_queue<>::consume_operation consume_1; bool const bool_1 = queue.try_start_consume(consume_1); assert(!bool_1 && !consume_1); queue.push(42); conc_heter_queue<>::consume_operation consume_2; auto bool_2 = queue.try_start_consume(consume_2); assert(consume_2 && bool_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_consume_ example 1] (void)bool_1; (void)bool_2; } { conc_heter_queue<> queue; //! [conc_heter_queue reentrant example 1] // start 3 reentrant put transactions auto put_1 = queue.start_reentrant_push(1); auto put_2 = queue.start_reentrant_emplace<std::string>("Hello world!"); double pi = 3.14; auto put_3 = queue.start_reentrant_dyn_push_copy(runtime_type<>::make<double>(), &pi); assert( queue.empty()); // the queue is still empty, because no transaction has been committed // commit and start consuming "Hello world!" put_2.commit(); auto consume2 = queue.try_start_reentrant_consume(); assert(!consume2.empty() && consume2.complete_type().is<std::string>()); // commit and start consuming 1 put_1.commit(); auto consume1 = queue.try_start_reentrant_consume(); assert(!consume1.empty() && consume1.complete_type().is<int>()); // cancel 3.14, and commit the consumes put_3.cancel(); consume1.commit(); consume2.commit(); assert(queue.empty()); //! [conc_heter_queue reentrant example 1] } { //! [conc_heter_queue reentrant_pop example 1] conc_heter_queue<> queue; queue.push(1); queue.push(2); queue.reentrant_pop(); auto consume = queue.try_start_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue reentrant_pop example 1] } { //! [conc_heter_queue try_reentrant_pop example 1] conc_heter_queue<> queue; bool pop_result = queue.try_reentrant_pop(); assert(pop_result == false); queue.push(1); queue.push(2); pop_result = queue.try_reentrant_pop(); assert(pop_result == true); auto consume = queue.try_start_reentrant_consume(); assert(consume.element<int>() == 2); consume.commit(); //! [conc_heter_queue try_reentrant_pop example 1] (void)pop_result; } { //! [conc_heter_queue try_start_reentrant_consume example 1] conc_heter_queue<> queue; auto consume_1 = queue.try_start_reentrant_consume(); assert(!consume_1); queue.push(42); auto consume_2 = queue.try_start_reentrant_consume(); assert(consume_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_reentrant_consume example 1] } { //! [conc_heter_queue try_start_reentrant_consume_ example 1] conc_heter_queue<> queue; conc_heter_queue<>::reentrant_consume_operation consume_1; bool const bool_1 = queue.try_start_reentrant_consume(consume_1); assert(!bool_1 && !consume_1); queue.push(42); conc_heter_queue<>::reentrant_consume_operation consume_2; auto bool_2 = queue.try_start_reentrant_consume(consume_2); assert(consume_2 && bool_2); assert(consume_2.element<int>() == 42); consume_2.commit(); //! [conc_heter_queue try_start_reentrant_consume_ example 1] (void)bool_1; (void)bool_2; } // this samples uses std::cout and std::cin // conc_heterogeneous_queue_samples_1(); conc_heterogeneous_queue_put_samples(); conc_heterogeneous_queue_put_transaction_samples(); conc_heterogeneous_queue_consume_operation_samples(); conc_heterogeneous_queue_reentrant_put_samples(); conc_heterogeneous_queue_reentrant_put_transaction_samples(); conc_heterogeneous_queue_reentrant_consume_operation_samples(); } } // namespace density_tests #if defined(_MSC_VER) && defined(NDEBUG) #pragma warning(pop) #endif
41.272109
125
0.574943
giucamp
300045ee0e2efaeecde3a8fb9d02197701b34471
2,962
cpp
C++
leveldb_rest.cpp
nucleati/leveldb_rest
921116a58bfed934d25b06675ed51c98fa3ea903
[ "MIT" ]
null
null
null
leveldb_rest.cpp
nucleati/leveldb_rest
921116a58bfed934d25b06675ed51c98fa3ea903
[ "MIT" ]
null
null
null
leveldb_rest.cpp
nucleati/leveldb_rest
921116a58bfed934d25b06675ed51c98fa3ea903
[ "MIT" ]
null
null
null
#include </Simple-Web-Server/client_http.hpp> #include </Simple-Web-Server/server_http.hpp> #include <future> // Added for the json-example #define BOOST_SPIRIT_THREADSAFE #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <algorithm> #include <boost/filesystem.hpp> #include <fstream> #include <vector> #include <map> #ifdef HAVE_OPENSSL #include "crypto.hpp" #endif #include "config/config.hpp" #include "set_endpoints.hpp" #include "leveldb/db.h" #include "leveldb/write_batch.h" #include "leveldb/filter_policy.h" using namespace std; // Added for the json-example: using namespace boost::property_tree; using HttpServer = SimpleWeb::Server<SimpleWeb::HTTP>; using HttpClient = SimpleWeb::Client<SimpleWeb::HTTP>; int main(int argc, char** argv) { Config config; if(argc != 2) { std::cerr << "Can't start server without configuration file: " << std::endl; std::cerr << "Correct use: " << argv[0] << " configuration.json" << endl; return(-1); } else { try{ char* filename = argv[1]; config.readJson(filename); } catch(...){ throw("Something went wrong while reading configuration file."); } } HttpServer server; server.config.port = std::stoi(config.getValue("port")); std::map<std::string, leveldb::DB*> ldbs; leveldb::Options options; options.create_if_missing = true; // User/Project database for(unsigned i = 0 ; i < config.config_tree->get_child("dbs").size() ; i++){ std::string db_name = "dbs.[" + std::to_string(i) + "].db"; std::string db_mount = "dbs.[" + std::to_string(i) + "].mp"; std::string db_path = "dbs.[" + std::to_string(i) + "].path"; std::string db_name_and_path = config.getValue(db_path) + config.getValue(db_name) ; leveldb::DB* db; leveldb::Status status = leveldb::DB::Open(options, db_name_and_path, &db) ; std::cout << "Received handle from database : " << db_name_and_path << std::endl; if (false == status.ok()){ cout << "Unable to open database " << db_name_and_path << " ." << endl; cout << status.ToString() << endl; return -1; } // Set up paths for requests std::string dbm = config.getValue(db_mount); set_endpoints(server, db, dbm); } server.on_error = [](shared_ptr<HttpServer::Request> /*request*/, const SimpleWeb::error_code & /*ec*/) { // Handle errors here // Note that connection timeouts will also call this handle with ec set to SimpleWeb::errc::operation_canceled }; // Start server and receive assigned port when server is listening for requests promise<unsigned short> server_port; thread server_thread([&server, &server_port]() { // Start server server.start([&server_port](unsigned short port) { server_port.set_value(port); }); }); cout << "Server listening on port " << server_port.get_future().get() << endl << endl; server_thread.join(); }
29.62
114
0.664416
nucleati
30066a5ff92dc6432fa71d3d12d9d629e0e896bc
3,912
cpp
C++
src/cpp/server.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
14
2019-11-15T18:19:35.000Z
2022-02-03T12:09:14.000Z
src/cpp/server.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
null
null
null
src/cpp/server.cpp
MayaPosch/NymphMQTT
10707ba763606424ab2b81e310cb53a38fa66687
[ "BSD-3-Clause" ]
1
2020-03-20T22:45:14.000Z
2020-03-20T22:45:14.000Z
/* server.cpp - Definition of the NymphMQTT server class. Revision 0. Features: - Provides public API for NymphMQTT server. Notes: - 2021/01/03, Maya Posch */ #include "server.h" #include "dispatcher.h" #include "nymph_logger.h" #include "session.h" #include "server_connections.h" #include <Poco/Net/NetException.h> #include <Poco/NumberFormatter.h> // Static initialisations. long NmqttServer::timeout = 3000; string NmqttServer::loggerName = "NmqttServer"; Poco::Net::ServerSocket NmqttServer::ss; Poco::Net::TCPServer* NmqttServer::server; // --- CONSTRUCTOR --- NmqttServer::NmqttServer() { // } // --- DECONSTRUCTOR --- NmqttServer::~NmqttServer() { // } // --- INIT --- // Initialise the runtime. bool NmqttServer::init(std::function<void(int, std::string)> logger, int level, long timeout) { NmqttServer::timeout = timeout; setLogger(logger, level); // Set the function pointers for the command handlers. NmqttClientSocket ns; //using namespace std::placeholders; ns.connectHandler = &NmqttServer::connectHandler; //std::bind(&NmqttServer::connectHandler, this, _1); ns.pingreqHandler = &NmqttServer::pingreqHandler; //std::bind(&NmqttServer::pingreqHandler, this, _1); NmqttClientConnections::setCoreParameters(ns); // Start the dispatcher runtime. // Get the number of concurrent threads supported by the system we are running on. int numThreads = std::thread::hardware_concurrency(); // Initialise the Dispatcher with the maximum number of threads as worker count. Dispatcher::init(numThreads); return true; } // --- SET LOGGER --- // Sets the logger function to be used by the Nymph Logger class, along with the // desired maximum log level: // NYMPH_LOG_LEVEL_FATAL = 1, // NYMPH_LOG_LEVEL_CRITICAL, // NYMPH_LOG_LEVEL_ERROR, // NYMPH_LOG_LEVEL_WARNING, // NYMPH_LOG_LEVEL_NOTICE, // NYMPH_LOG_LEVEL_INFO, // NYMPH_LOG_LEVEL_DEBUG, // NYMPH_LOG_LEVEL_TRACE void NmqttServer::setLogger(std::function<void(int, std::string)> logger, int level) { NymphLogger::setLoggerFunction(logger); NymphLogger::setLogLevel((Poco::Message::Priority) level); } // --- START --- bool NmqttServer::start(int port) { try { // Create a server socket that listens on all interfaces, IPv4 and IPv6. // Assign it to the new TCPServer. ss.bind6(port, true, false); // Port, SO_REUSEADDR, IPv6-only. ss.listen(); server = new Poco::Net::TCPServer( new Poco::Net::TCPServerConnectionFactoryImpl<NmqttSession>(), ss); server->start(); } catch (Poco::Net::NetException& e) { NYMPH_LOG_ERROR("Error starting TCP server: " + e.message()); return false; } //running = true; return true; } // --- SEND MESSAGE --- // Private method for sending data to a remote broker. bool NmqttServer::sendMessage(uint64_t handle, std::string binMsg) { NmqttClientSocket* clientSocket = NmqttClientConnections::getSocket(handle); try { int ret = clientSocket->socket->sendBytes(((const void*) binMsg.c_str()), binMsg.length()); if (ret != binMsg.length()) { // Handle error. NYMPH_LOG_ERROR("Failed to send message. Not all bytes sent."); return false; } NYMPH_LOG_DEBUG("Sent " + Poco::NumberFormatter::format(ret) + " bytes."); } catch (Poco::Exception &e) { NYMPH_LOG_ERROR("Failed to send message: " + e.message()); return false; } return true; } // --- CONNECT HANDLER --- // Process connection. Return CONNACK response. void NmqttServer::connectHandler(uint64_t handle) { NmqttMessage msg(MQTT_CONNACK); sendMessage(handle, msg.serialize()); } // --- PINGREQ HANDLER --- // Reply to ping response from a client. void NmqttServer::pingreqHandler(uint64_t handle) { NmqttMessage msg(MQTT_PINGRESP); sendMessage(handle, msg.serialize()); } // --- SHUTDOWN --- // Shutdown the runtime. Close any open connections and clean up resources. bool NmqttServer::shutdown() { server->stop(); return true; }
25.23871
103
0.712168
MayaPosch
30086c6c23c601d124f5c797085d4214e774e3a8
921
cpp
C++
A_Little_Elephant_and_Rozdil.cpp
ar1936/CPP
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
1
2021-04-20T13:49:56.000Z
2021-04-20T13:49:56.000Z
A_Little_Elephant_and_Rozdil.cpp
ar1936/cpp
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
null
null
null
A_Little_Elephant_and_Rozdil.cpp
ar1936/cpp
4c76c2bf5308d8d3b6e295482e3ce4284fbeaf13
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> #include <iomanip> using namespace std; typedef long long ll; typedef double db; #define pb push_back #define ppb pop_back #define mpll map<ll, ll> #define vll vector<ll> #define str string #define si size() #define vs vector<string> #define vc vector<char> #define sll set<ll> #define pi 3.14159265358979323846264338327 #define nope string::npos void fast(){ ios_base::sync_with_stdio(false); cin.tie(NULL); } int main() { fast(); ll n, min_time(1000000001),min_index(0),time,count(1); cin>>n; for(int i=1;i<=n;i++) { cin>>time; if(time<min_time) { min_time=time; min_index=i; count=1; } else if(min_time==time) count++; } if(count==1) cout<<min_index; else { cout<<"Still Rozdil"; } return 0; }
19.595745
59
0.560261
ar1936
30151745d9266c4dc1312469e78003bc6e110386
1,989
cpp
C++
libstarlight/source/starlight/ui/Button.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
36
2017-01-17T22:58:08.000Z
2021-12-28T00:04:52.000Z
libstarlight/source/starlight/ui/Button.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
3
2017-03-26T20:47:25.000Z
2019-12-12T01:50:02.000Z
libstarlight/source/starlight/ui/Button.cpp
mothie/libstarlight
91bd6892ccc95ccf255cad73ef659b6cf37ab4a9
[ "MIT" ]
9
2017-04-17T19:01:24.000Z
2021-12-01T18:26:01.000Z
#include "Button.h" #include "starlight/_incLib/json.hpp" #include "starlight/InputManager.h" #include "starlight/GFXManager.h" #include "starlight/ThemeManager.h" using starlight::Vector2; using starlight::Color; using starlight::gfx::Font; using starlight::InputManager; using starlight::GFXManager; using starlight::ThemeManager; using starlight::TextConfig; using starlight::ui::Button; std::function<TextConfig&()> Button::defCfg = []() -> TextConfig& { static TextConfig _tc = ThemeManager::GetMetric("/controls/button/text", TextConfig()); return _tc; }; void Button::SetText(const std::string& text) { label = text; MarkForRedraw(); } void Button::Draw() { //static auto font = ThemeManager::GetFont("default.12"); static auto idle = ThemeManager::GetAsset("controls/button.idle"); static auto press = ThemeManager::GetAsset("controls/button.press"); TextConfig& tc = style.textConfig.ROGet(); auto rect = (this->rect + GFXManager::GetOffset()).IntSnap(); if (InputManager::GetDragHandle() == this) { (style.press ? style.press : press)->Draw(rect); } else { (style.idle ? style.idle : idle)->Draw(rect); } tc.Print(rect, label); if (style.glyph) style.glyph->Draw(rect.Center(), Vector2::half, nullptr, tc.textColor); } void Button::OnTouchOn() { if (InputManager::Pressed(Keys::Touch)) { InputManager::GetDragHandle().Grab(this); MarkForRedraw(); } } void Button::OnTouchOff() { auto& drag = InputManager::GetDragHandle(); if (drag == this) drag.Release(); } void Button::OnDragStart() { // do we need to do anything here? } void Button::OnDragHold() { if (InputManager::TouchDragDist().Length() > InputManager::dragThreshold) { InputManager::GetDragHandle().PassUp(); } } void Button::OnDragRelease() { if (InputManager::Released(Keys::Touch)) { if (eOnTap) eOnTap(*this); } MarkForRedraw(); }
24.8625
92
0.659628
mothie
30188d28702d70d3aaf829bc7ee178ce28093cc4
641
cpp
C++
03-Making Decisions/Program_4-23.cpp
ringosimonchen0820/How-to-C--
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
[ "MIT" ]
null
null
null
03-Making Decisions/Program_4-23.cpp
ringosimonchen0820/How-to-C--
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
[ "MIT" ]
1
2020-10-11T18:39:08.000Z
2020-10-11T18:39:17.000Z
03-Making Decisions/Program_4-23.cpp
ringosimonchen0820/How-to-C--
69b0310e6aeab25a7e2eed41e4d6cff85a034e00
[ "MIT" ]
2
2020-10-12T20:33:32.000Z
2020-10-12T20:34:00.000Z
// The switch statement in this program tells the user something // he or she already knows: the data just entered! #include <iostream> using namespace std; int main() { char choice; cout << "Enter A, B, or C: "; cin >> choice; switch (choice) { case 'A' : cout << "You entered A.\n"; break; case 'B' : cout << "You entered B.\n"; break; case 'C' : cout << "You entered C.\n"; break; default : cout << "You did not enter A, B, or C!\n"; //? The default section does not need a break statement } return 0; }
22.892857
65
0.517941
ringosimonchen0820
6f72df799e5a12e1e05ecad1356ee41387923580
1,327
cpp
C++
src/population/reproducer/PassionateReproducer.cpp
jansvoboda11/gram
62e5b525ea648b4d452cb2153bcca90dfbee9de5
[ "MIT" ]
7
2017-05-03T11:47:42.000Z
2021-10-12T02:46:16.000Z
src/population/reproducer/PassionateReproducer.cpp
jansvoboda11/gram
62e5b525ea648b4d452cb2153bcca90dfbee9de5
[ "MIT" ]
3
2021-02-22T19:14:05.000Z
2021-06-14T20:36:47.000Z
src/population/reproducer/PassionateReproducer.cpp
jansvoboda11/gram
62e5b525ea648b4d452cb2153bcca90dfbee9de5
[ "MIT" ]
2
2020-01-29T05:37:00.000Z
2022-01-17T06:03:48.000Z
#include "gram/population/reproducer/PassionateReproducer.h" #include <algorithm> #include <memory> #include "gram/individual/Individual.h" #include "gram/operator/crossover/Crossover.h" #include "gram/operator/mutation/Mutation.h" #include "gram/operator/selector/IndividualSelector.h" #include "gram/population/Individuals.h" #include "gram/population/reproducer/Reproducer.h" using namespace gram; using namespace std; PassionateReproducer::PassionateReproducer(unique_ptr<IndividualSelector> selector, unique_ptr<Crossover> crossover, unique_ptr<Mutation> mutation) : selector(move(selector)), crossover(move(crossover)), mutation(move(mutation)) { // } Individuals PassionateReproducer::reproduce(Individuals& individuals) { unsigned long size = individuals.size(); Individuals children; children.reserve(size); for (unsigned long i = 0; i < size; i++) { Individual child = createChild(individuals); children.addIndividual(child); } return children; } Individual PassionateReproducer::createChild(Individuals& individuals) { Individual& parent1 = selector->select(individuals); Individual& parent2 = selector->select(individuals); Individual child = parent1.mateWith(parent2, *crossover); child.mutate(*mutation); return child; }
28.234043
116
0.74529
jansvoboda11
6f807d0caccd5ee9fa9f6be4d17bcabca111da1b
15,170
cpp
C++
demos/fractal/fractal_demo.cpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
284
2017-11-07T10:06:48.000Z
2021-01-12T15:32:51.000Z
demos/fractal/fractal_demo.cpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
38
2018-01-14T12:34:54.000Z
2020-09-26T15:32:43.000Z
demos/fractal/fractal_demo.cpp
a-n-t-h-o-n-y/MCurses
c9184a0fefbdc4eb9a044f815ee2270e6b8f202c
[ "MIT" ]
31
2017-11-30T11:22:21.000Z
2020-11-03T05:27:47.000Z
#include "fractal_demo.hpp" #include <cassert> #include <cmath> #include <future> #include <thread> #include <utility> #include <vector> #include <termox/termox.hpp> #include "float_t.hpp" #include "julia.hpp" #include "mandelbrot.hpp" namespace { using fractal::Float_t; auto constexpr zoom_scale = 0.05; auto constexpr default_boundary = ox::Boundary<Float_t>{-2, 2, 2, -2}; using ox::Color; using ox::RGB; /// Fractal colors start at color 16. auto const custom_palette = ox::Palette{ {Color::Background, RGB{000000}}, {Color::Foreground, RGB{0xFFFFFF}}, {Color{16}, RGB{0x02044e}}, {Color{17}, RGB{0x180450}}, {Color{18}, RGB{0x270252}}, {Color{19}, RGB{0x330154}}, {Color{20}, RGB{0x3e0055}}, {Color{21}, RGB{0x480056}}, {Color{22}, RGB{0x520057}}, {Color{23}, RGB{0x5c0058}}, {Color{24}, RGB{0x650058}}, {Color{25}, RGB{0x6e0058}}, {Color{26}, RGB{0x770058}}, {Color{27}, RGB{0x800058}}, {Color{28}, RGB{0x880057}}, {Color{29}, RGB{0x900056}}, {Color{30}, RGB{0x980455}}, {Color{31}, RGB{0x9f0d54}}, {Color{32}, RGB{0xa71553}}, {Color{33}, RGB{0xad1c52}}, {Color{34}, RGB{0xb42350}}, {Color{35}, RGB{0xba2b4e}}, {Color{36}, RGB{0xc0324d}}, {Color{37}, RGB{0xc6394b}}, {Color{38}, RGB{0xcb4049}}, {Color{39}, RGB{0xd04847}}, {Color{40}, RGB{0xd54f45}}, {Color{41}, RGB{0xd95644}}, {Color{42}, RGB{0xdd5e42}}, {Color{43}, RGB{0xe06640}}, {Color{44}, RGB{0xe36d3e}}, {Color{45}, RGB{0xe6753d}}, {Color{46}, RGB{0xe87d3b}}, {Color{47}, RGB{0xea853a}}, {Color{48}, RGB{0xec8d39}}, {Color{49}, RGB{0xed9438}}, {Color{50}, RGB{0xee9c38}}, {Color{51}, RGB{0xefa439}}, {Color{52}, RGB{0xefac3a}}, {Color{53}, RGB{0xefb43b}}, {Color{54}, RGB{0xefbc3e}}, {Color{55}, RGB{0xeec441}}, {Color{56}, RGB{0xefbc3e}}, {Color{57}, RGB{0xefb43b}}, {Color{58}, RGB{0xefac3a}}, {Color{59}, RGB{0xefa439}}, {Color{60}, RGB{0xee9c38}}, {Color{61}, RGB{0xed9438}}, {Color{62}, RGB{0xec8d39}}, {Color{63}, RGB{0xea853a}}, {Color{64}, RGB{0xe87d3b}}, {Color{65}, RGB{0xe6753d}}, {Color{66}, RGB{0xe36d3e}}, {Color{67}, RGB{0xe06640}}, {Color{68}, RGB{0xdd5e42}}, {Color{69}, RGB{0xd95644}}, {Color{70}, RGB{0xd54f45}}, {Color{71}, RGB{0xd04847}}, {Color{72}, RGB{0xcb4049}}, {Color{73}, RGB{0xc6394b}}, {Color{74}, RGB{0xc0324d}}, {Color{75}, RGB{0xba2b4e}}, {Color{76}, RGB{0xb42350}}, {Color{77}, RGB{0xad1c52}}, {Color{78}, RGB{0xa71553}}, {Color{79}, RGB{0x9f0d54}}, {Color{80}, RGB{0x980455}}, {Color{81}, RGB{0x900056}}, {Color{82}, RGB{0x880057}}, {Color{83}, RGB{0x800058}}, {Color{84}, RGB{0x770058}}, {Color{85}, RGB{0x6e0058}}, {Color{86}, RGB{0x650058}}, {Color{87}, RGB{0x5c0058}}, {Color{88}, RGB{0x520057}}, {Color{89}, RGB{0x480056}}, {Color{90}, RGB{0x3e0055}}, {Color{91}, RGB{0x330154}}, {Color{92}, RGB{0x270252}}, {Color{93}, RGB{0x180450}}}; /// Adds the given offset in each direction to the given boundary. [[nodiscard]] auto apply_offsets(ox::Boundary<Float_t> boundary, ox::Boundary<Float_t> const& offsets) -> ox::Boundary<Float_t> { boundary.west += offsets.west; boundary.east += offsets.east; boundary.north += offsets.north; boundary.south += offsets.south; return boundary; } /// Given a fractal function for a single point, will generate a field of points template <typename Fn> [[nodiscard]] auto generate_points(ox::Boundary<Float_t> boundary, Float_t x_step, Float_t y_step, unsigned int resolution, Fn&& generator) -> std::vector<std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>> { auto result = std::vector< std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>>{}; auto const count = ((boundary.east - boundary.west) / x_step) * ((boundary.north - boundary.south) / y_step); result.reserve(count); for (auto x = boundary.west; x <= boundary.east; x += x_step) { for (auto y = boundary.south; y <= boundary.north; y += y_step) { result.push_back( {{x, y}, ox::Color( ((std::forward<Fn>(generator)(x, y, resolution) - 1) % (custom_palette.size() - 2)) + 16)}); } } return result; } /// Generates a field of fractal values in parallel, depending on hardward cores template <typename Fn> [[nodiscard]] auto par_generate_points(ox::Boundary<Float_t> boundary, Float_t x_step, Float_t y_step, unsigned int resolution, Fn&& generator) -> std::vector<std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>> { auto result = std::vector< std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>>{}; auto const count = ((boundary.east - boundary.west) / x_step) * ((boundary.north - boundary.south) / y_step); result.reserve(count); // Break Into Chunks auto const thread_count = std::thread::hardware_concurrency(); auto const chunk_distance = (boundary.east - boundary.west) / (double)thread_count; auto boundaries = std::vector<ox::Boundary<Float_t>>{}; boundaries.reserve(thread_count); for (auto i = 0uL; i < thread_count; ++i) { auto b = boundary; b.west = b.west + (i * chunk_distance); b.east = b.west + chunk_distance; boundaries.push_back(b); } // Launch Threads auto futs = std::vector<std::future<std::vector< std::pair<ox::Color_graph<Float_t>::Coordinate, ox::Color>>>>{}; futs.reserve(thread_count); for (auto const& b : boundaries) { futs.push_back(std::async(std::launch::async, [=] { return generate_points(b, x_step, y_step, resolution, generator); })); } // Wait and Concat Results for (auto& f : futs) { auto points = f.get(); result.insert(std::end(result), std::begin(points), std::end(points)); } return result; } [[nodiscard]] auto make_instructions() -> ox::Glyph_string { using ox::Trait; auto x = ox::Glyph_string{}; x.append(U"Instructions" | Trait::Bold); x.append(U"\n\n"); x.append(U"Switch between "); x.append(U"fractal types" | Trait::Bold); x.append(U" with top bar selector."); x.append(U"\n\n"); x.append(U"Zoom" | Trait::Bold); x.append(U'\n'); x.append( U" [Scroll Mouse Wheel] - Zoom in/out on point over mouse cursor.\n" U" [CTRL + Up Arrow] - Zoom in on center point.\n [CTRL + " U"Down Arrow] - Zoom out on center point."); x.append(U"\n\n"); x.append(U"Move" | Trait::Bold); x.append(U" around with the arrow keys."); x.append(U"\n\n"); x.append(U"The "); x.append(U"Julia Set" | Trait::Bold); x.append( U" can have its constant `C` modified by left mouse clicking and " U"dragging on the fractal surface."); x.append(U"\n\n"); x.append(U"Decrease terminal font size to increase fractal "); x.append(U"resolution" | Trait::Bold); x.append(U"."); x.append(U"\n\n"); x.append( U"If you zoom in far enough it will bottom out on `long double` " U"floating point resolution and will freeze with black lines across " U"the image."); return x; } } // namespace namespace fractal { Float_edit::Float_edit() { using namespace ox; *this | pipe::fixed_height(1); this->second | bg(Color::White) | fg(Color::Black); } Top_bar::Top_bar() : ox::HPair<ox::Cycle_box, ox::Toggle_button>{ {ox::Align::Center, 0, 14}, {U"Instructions", U"Fractal View"}} { using namespace ox::pipe; *this | fixed_height(1); buttons | fixed_width(14) | children() | bg(ox::Color::White) | fg(ox::Color::Black); selector.add_option(U"< Mandelbrot >").connect([this] { fractal_changed.emit(Fractal::Mandelbrot); }); selector.add_option(U"< Julia >").connect([this] { fractal_changed.emit(Fractal::Julia); }); } Instructions::Instructions() : ox::Text_view{make_instructions()} { *this | bg(ox::Color{16}) | fg(ox::Color{45}); } Fractal_demo::Fractal_demo() : ox::VPair<Top_bar, ox::SPair<ox::Color_graph<Float_t>, Instructions>>{ {}, {{{-2, 2, 2, -2}}, {}}} { using namespace ox::pipe; auto const pal = custom_palette; *this | direct_focus() | on_focus_in([=] { ox::Terminal::set_palette(pal); }) | forward_focus(graph); auto& stack = this->second; stack | active_page(0); graph | strong_focus(); top_bar.instructions_request.connect([this] { this->show_instructions(); }); top_bar.fractal_view_request.connect([this] { this->show_fractals(); }); top_bar.fractal_changed.connect([this](auto type) { fractal_type_ = type; this->reset(); }); graph.mouse_moved.connect([this](auto const& m) { if (fractal_type_ != Fractal::Julia) return; auto const b = graph.boundary(); auto const hr = ((b.east - b.west) / (double)graph.area().width); auto const vr = ((b.north - b.south) / (double)graph.area().height); julia_c_.real(b.west + (m.at.x * hr)); julia_c_.imag(b.south + (m.at.y * vr)); this->reset(); }); graph.key_pressed.connect([this](auto k) { switch (k) { case ox::Key::Arrow_right: this->increment_h_offset(+1); this->reset(); break; case ox::Key::Arrow_left: this->increment_h_offset(-1); this->reset(); break; case ox::Key::Arrow_up: this->increment_v_offset(+1); this->reset(); break; case ox::Key::Arrow_down: this->increment_v_offset(-1); this->reset(); break; default: break; } // If statements to get around switch warning, not in enum. if (k == (ox::Mod::Ctrl | ox::Key::Arrow_up)) this->zoom_in(); else if (k == (ox::Mod::Ctrl | ox::Key::Arrow_down)) this->zoom_out(); }); graph.mouse_wheel_scrolled.connect([this](auto m) { switch (m.button) { case ox::Mouse::Button::ScrollUp: this->zoom_in_at(m.at); break; case ox::Mouse::Button::ScrollDown: this->zoom_out_at(m.at); break; default: break; } }); graph | on_resize([this](auto, auto) { this->reset(); }); graph | on_enable([this] { this->reset(); }); this->reset(default_boundary); } void Fractal_demo::reset(ox::Boundary<Float_t> b) { if (graph.area().height == 0 || graph.area().width == 0) return; graph.set_boundary(b); auto const x_interval = Float_t(b.east - b.west) / (graph.area().width * 1.001); auto const y_interval = Float_t(b.north - b.south) / (graph.area().height * 2.001); auto const distance = b.east - b.west; auto const resolution = std::clamp((int)std::log(1. / distance), 1, 8) * (custom_palette.size() - 2); switch (fractal_type_) { case Fractal::Mandelbrot: graph.reset(par_generate_points(b, x_interval, y_interval, resolution, mandelbrot)); break; case Fractal::Julia: graph.reset( par_generate_points(b, x_interval, y_interval, resolution, [&](auto x, auto y, auto mi) { return julia(x, y, julia_c_, mi); })); break; } } void Fractal_demo::reset() { this->reset(apply_offsets(default_boundary, offsets_)); } void Fractal_demo::increment_h_offset(int direction) { assert(direction == 1 || direction == -1); auto constexpr fraction = (Float_t)1. / (Float_t)25.; auto const b = graph.boundary(); auto const amount = direction * (b.east - b.west) * fraction; offsets_.west += amount; offsets_.east += amount; } void Fractal_demo::increment_v_offset(int direction) { assert(direction == 1 || direction == -1); auto constexpr fraction = (Float_t)1. / (Float_t)25.; auto const b = graph.boundary(); auto const amount = direction * (b.north - b.south) * fraction; offsets_.north += amount; offsets_.south += amount; } void Fractal_demo::zoom_in() { auto const b = graph.boundary(); auto const h_distance = (b.east - b.west); auto const v_distance = (b.north - b.south); offsets_.west += h_distance * zoom_scale; offsets_.east -= h_distance * zoom_scale; offsets_.north -= v_distance * zoom_scale; offsets_.south += v_distance * zoom_scale; this->reset(); } void Fractal_demo::zoom_in_at(ox::Point p) { auto const b = graph.boundary(); // Horizontal auto const h_distance = b.east - b.west; auto const h_ratio = h_distance / graph.area().width; auto const h_coord = h_ratio * p.x; offsets_.west += h_coord * zoom_scale; offsets_.east -= (h_distance - h_coord) * zoom_scale; // Vertical auto const v_distance = b.north - b.south; auto const v_ratio = v_distance / graph.area().height; auto const v_coord = v_ratio * (graph.area().height - p.y); offsets_.south += v_coord * zoom_scale; offsets_.north -= (v_distance - v_coord) * zoom_scale; this->reset(); } void Fractal_demo::zoom_out() { auto const b = graph.boundary(); auto const h_distance = (b.east - b.west); auto const v_distance = (b.north - b.south); offsets_.west -= h_distance * zoom_scale; offsets_.east += h_distance * zoom_scale; offsets_.north += v_distance * zoom_scale; offsets_.south -= v_distance * zoom_scale; this->reset(); } void Fractal_demo::zoom_out_at(ox::Point p) { auto const b = graph.boundary(); // Horizontal auto const h_distance = b.east - b.west; auto const h_ratio = h_distance / graph.area().width; auto const h_coord = h_ratio * p.x; offsets_.west -= h_coord * zoom_scale; offsets_.east += (h_distance - h_coord) * zoom_scale; // Vertical auto const v_distance = b.north - b.south; auto const v_ratio = v_distance / graph.area().height; auto const v_coord = v_ratio * (graph.area().height - p.y); offsets_.south -= v_coord * zoom_scale; offsets_.north += (v_distance - v_coord) * zoom_scale; this->reset(); } } // namespace fractal
34.873563
80
0.572841
a-n-t-h-o-n-y
6f86e37e18f7a6957282ae6811afe60b5ced4665
7,071
cpp
C++
billing/src/v20180709/model/PayModeSummaryOverviewItem.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
billing/src/v20180709/model/PayModeSummaryOverviewItem.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
billing/src/v20180709/model/PayModeSummaryOverviewItem.cpp
datalliance88/tencentcloud-sdk-cpp
fbb8ea8e385620ac41b0a9ceb5abf1405b8aac8c
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <tencentcloud/billing/v20180709/model/PayModeSummaryOverviewItem.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Billing::V20180709::Model; using namespace rapidjson; using namespace std; PayModeSummaryOverviewItem::PayModeSummaryOverviewItem() : m_payModeHasBeenSet(false), m_payModeNameHasBeenSet(false), m_realTotalCostHasBeenSet(false), m_realTotalCostRatioHasBeenSet(false), m_detailHasBeenSet(false) { } CoreInternalOutcome PayModeSummaryOverviewItem::Deserialize(const Value &value) { string requestId = ""; if (value.HasMember("PayMode") && !value["PayMode"].IsNull()) { if (!value["PayMode"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.PayMode` IsString=false incorrectly").SetRequestId(requestId)); } m_payMode = string(value["PayMode"].GetString()); m_payModeHasBeenSet = true; } if (value.HasMember("PayModeName") && !value["PayModeName"].IsNull()) { if (!value["PayModeName"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.PayModeName` IsString=false incorrectly").SetRequestId(requestId)); } m_payModeName = string(value["PayModeName"].GetString()); m_payModeNameHasBeenSet = true; } if (value.HasMember("RealTotalCost") && !value["RealTotalCost"].IsNull()) { if (!value["RealTotalCost"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.RealTotalCost` IsString=false incorrectly").SetRequestId(requestId)); } m_realTotalCost = string(value["RealTotalCost"].GetString()); m_realTotalCostHasBeenSet = true; } if (value.HasMember("RealTotalCostRatio") && !value["RealTotalCostRatio"].IsNull()) { if (!value["RealTotalCostRatio"].IsString()) { return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.RealTotalCostRatio` IsString=false incorrectly").SetRequestId(requestId)); } m_realTotalCostRatio = string(value["RealTotalCostRatio"].GetString()); m_realTotalCostRatioHasBeenSet = true; } if (value.HasMember("Detail") && !value["Detail"].IsNull()) { if (!value["Detail"].IsArray()) return CoreInternalOutcome(Error("response `PayModeSummaryOverviewItem.Detail` is not array type")); const Value &tmpValue = value["Detail"]; for (Value::ConstValueIterator itr = tmpValue.Begin(); itr != tmpValue.End(); ++itr) { ActionSummaryOverviewItem item; CoreInternalOutcome outcome = item.Deserialize(*itr); if (!outcome.IsSuccess()) { outcome.GetError().SetRequestId(requestId); return outcome; } m_detail.push_back(item); } m_detailHasBeenSet = true; } return CoreInternalOutcome(true); } void PayModeSummaryOverviewItem::ToJsonObject(Value &value, Document::AllocatorType& allocator) const { if (m_payModeHasBeenSet) { Value iKey(kStringType); string key = "PayMode"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_payMode.c_str(), allocator).Move(), allocator); } if (m_payModeNameHasBeenSet) { Value iKey(kStringType); string key = "PayModeName"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_payModeName.c_str(), allocator).Move(), allocator); } if (m_realTotalCostHasBeenSet) { Value iKey(kStringType); string key = "RealTotalCost"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_realTotalCost.c_str(), allocator).Move(), allocator); } if (m_realTotalCostRatioHasBeenSet) { Value iKey(kStringType); string key = "RealTotalCostRatio"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(m_realTotalCostRatio.c_str(), allocator).Move(), allocator); } if (m_detailHasBeenSet) { Value iKey(kStringType); string key = "Detail"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, Value(kArrayType).Move(), allocator); int i=0; for (auto itr = m_detail.begin(); itr != m_detail.end(); ++itr, ++i) { value[key.c_str()].PushBack(Value(kObjectType).Move(), allocator); (*itr).ToJsonObject(value[key.c_str()][i], allocator); } } } string PayModeSummaryOverviewItem::GetPayMode() const { return m_payMode; } void PayModeSummaryOverviewItem::SetPayMode(const string& _payMode) { m_payMode = _payMode; m_payModeHasBeenSet = true; } bool PayModeSummaryOverviewItem::PayModeHasBeenSet() const { return m_payModeHasBeenSet; } string PayModeSummaryOverviewItem::GetPayModeName() const { return m_payModeName; } void PayModeSummaryOverviewItem::SetPayModeName(const string& _payModeName) { m_payModeName = _payModeName; m_payModeNameHasBeenSet = true; } bool PayModeSummaryOverviewItem::PayModeNameHasBeenSet() const { return m_payModeNameHasBeenSet; } string PayModeSummaryOverviewItem::GetRealTotalCost() const { return m_realTotalCost; } void PayModeSummaryOverviewItem::SetRealTotalCost(const string& _realTotalCost) { m_realTotalCost = _realTotalCost; m_realTotalCostHasBeenSet = true; } bool PayModeSummaryOverviewItem::RealTotalCostHasBeenSet() const { return m_realTotalCostHasBeenSet; } string PayModeSummaryOverviewItem::GetRealTotalCostRatio() const { return m_realTotalCostRatio; } void PayModeSummaryOverviewItem::SetRealTotalCostRatio(const string& _realTotalCostRatio) { m_realTotalCostRatio = _realTotalCostRatio; m_realTotalCostRatioHasBeenSet = true; } bool PayModeSummaryOverviewItem::RealTotalCostRatioHasBeenSet() const { return m_realTotalCostRatioHasBeenSet; } vector<ActionSummaryOverviewItem> PayModeSummaryOverviewItem::GetDetail() const { return m_detail; } void PayModeSummaryOverviewItem::SetDetail(const vector<ActionSummaryOverviewItem>& _detail) { m_detail = _detail; m_detailHasBeenSet = true; } bool PayModeSummaryOverviewItem::DetailHasBeenSet() const { return m_detailHasBeenSet; }
30.089362
157
0.694103
datalliance88
6f890288d684594be9ab41a64e1ea24be9669ee1
1,681
cpp
C++
src/SLEngine.Shared/graphics/texture2D.cpp
SergioMasson/SimpleLittleEngine
10a0a43d7f4abae3574e902505b457455f0cb61b
[ "MIT" ]
null
null
null
src/SLEngine.Shared/graphics/texture2D.cpp
SergioMasson/SimpleLittleEngine
10a0a43d7f4abae3574e902505b457455f0cb61b
[ "MIT" ]
null
null
null
src/SLEngine.Shared/graphics/texture2D.cpp
SergioMasson/SimpleLittleEngine
10a0a43d7f4abae3574e902505b457455f0cb61b
[ "MIT" ]
null
null
null
#include "pch.h" #include "coreGraphics.h" #include <fstream> #include <iterator> #include <vector> #include "texture2D.h" #include "dds.h" using namespace sle; graphics::Texture2D::Texture2D(const wchar_t* filePath) { std::ifstream input(filePath, std::ios::binary); std::vector<char> bytes( (std::istreambuf_iterator<char>(input)), (std::istreambuf_iterator<char>())); input.close(); CreateDDSTextureFromMemory(graphics::g_d3dDevice.Get(), (byte*)bytes.data(), bytes.size(), m_resource.GetAddressOf(), m_resourceView.GetAddressOf()); // Once the texture view is created, create a sampler. This defines how the color // for a particular texture coordinate is determined using the relevant texture data. D3D11_SAMPLER_DESC samplerDesc; ZeroMemory(&samplerDesc, sizeof(samplerDesc)); samplerDesc.Filter = D3D11_FILTER_MIN_MAG_MIP_LINEAR;; samplerDesc.MaxAnisotropy = 0; // Specify how texture coordinates outside of the range 0..1 are resolved. samplerDesc.AddressU = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressV = D3D11_TEXTURE_ADDRESS_WRAP; samplerDesc.AddressW = D3D11_TEXTURE_ADDRESS_WRAP; // Use no special MIP clamping or bias. samplerDesc.MipLODBias = 0.0f; samplerDesc.MinLOD = 0; samplerDesc.MaxLOD = D3D11_FLOAT32_MAX; // Don't use a comparison function. samplerDesc.ComparisonFunc = D3D11_COMPARISON_NEVER; // Border address mode is not used, so this parameter is ignored. samplerDesc.BorderColor[0] = 0.0f; samplerDesc.BorderColor[1] = 0.0f; samplerDesc.BorderColor[2] = 0.0f; samplerDesc.BorderColor[3] = 0.0f; ASSERT_SUCCEEDED(graphics::g_d3dDevice->CreateSamplerState(&samplerDesc, m_samplerState.GetAddressOf())); }
32.326923
106
0.767995
SergioMasson
6f8cd43d044cfbac72e83f9a89554c2eea13fff7
2,409
hpp
C++
libs/core/include/fcppt/math/matrix/detail/determinant.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/math/matrix/detail/determinant.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
libs/core/include/fcppt/math/matrix/detail/determinant.hpp
pmiddend/fcppt
9f437acbb10258e6df6982a550213a05815eb2be
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2018. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef FCPPT_MATH_MATRIX_DETAIL_DETERMINANT_HPP_INCLUDED #define FCPPT_MATH_MATRIX_DETAIL_DETERMINANT_HPP_INCLUDED #include <fcppt/literal.hpp> #include <fcppt/tag_type.hpp> #include <fcppt/use.hpp> #include <fcppt/algorithm/fold.hpp> #include <fcppt/math/int_range_count.hpp> #include <fcppt/math/size_type.hpp> #include <fcppt/math/matrix/at_r_c.hpp> #include <fcppt/math/matrix/delete_row_and_column.hpp> #include <fcppt/math/matrix/has_dim.hpp> #include <fcppt/math/matrix/index.hpp> #include <fcppt/math/matrix/object_impl.hpp> #include <fcppt/math/matrix/static.hpp> namespace fcppt { namespace math { namespace matrix { namespace detail { template< typename T, typename S > T determinant( fcppt::math::matrix::object< T, 1, 1, S > const &_matrix ) { return fcppt::math::matrix::at_r_c< 0, 0 >( _matrix ); } template< typename T, fcppt::math::size_type N, typename S > std::enable_if_t< !fcppt::math::matrix::has_dim< fcppt::math::matrix::object< T, N, N, S >, 1, 1 >::value, T > determinant( fcppt::math::matrix::object< T, N, N, S > const &_matrix ) { return fcppt::algorithm::fold( fcppt::math::int_range_count< N >{}, fcppt::literal< T >( 0 ), [ &_matrix ]( auto const _row, T const _sum ) { FCPPT_USE( _row ); typedef fcppt::tag_type< decltype( _row ) > row; T const coeff{ row::value % fcppt::literal< fcppt::math::size_type >( 2 ) == fcppt::literal< fcppt::math::size_type >( 0 ) ? fcppt::literal< T >( 1 ) : fcppt::literal< T >( -1 ) }; constexpr fcppt::math::size_type const column{ 0u }; return _sum + coeff * fcppt::math::matrix::at_r_c< row::value, column >( _matrix ) * fcppt::math::matrix::detail::determinant( fcppt::math::matrix::delete_row_and_column< row::value, column >( _matrix ) ); } ); } } } } } #endif
13.844828
61
0.576588
pmiddend
6f8d7eae3e515934fa4bd754d6f749babaaa2380
46
hpp
C++
src/boost_log_utility_manipulators.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_log_utility_manipulators.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_log_utility_manipulators.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/log/utility/manipulators.hpp>
23
45
0.804348
miathedev
6f8ecb75e93f4737e55b506c0d42046a0034f092
13,172
cpp
C++
src/core/type/typemanager.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/type/typemanager.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
src/core/type/typemanager.cpp
eXl-Nic/eXl
a5a0f77f47db3179365c107a184bb38b80280279
[ "MIT" ]
null
null
null
/* Copyright 2009-2021 Nicolas Colombe 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 <core/type/typemanager.hpp> #include <core/type/tupletypestruct.hpp> #include <core/type/enumtype.hpp> #include <core/type/arraytype.hpp> #include <core/type/objectptrtype.hpp> #include <core/type/classtyperttiobject.hpp> #include <boost/lexical_cast.hpp> #include <boost/multi_index_container.hpp> #include <boost/multi_index/ordered_index.hpp> #include <boost/multi_index/member.hpp> #include <boost/multi_index/identity.hpp> #include <core/log.hpp> namespace eXl { namespace TypeManager { namespace detail { struct TypeCmpName { typedef TypeName const result_type; const TypeName operator()(const Type* iType) const { return iType->GetName(); } }; struct TypeCmpID { typedef size_t result_type; size_t operator()(TupleType* iType) const { return iType->GetTypeId(); } }; typedef boost::multi_index::multi_index_container<Type*, boost::multi_index::indexed_by< //boost::multi_index::ordered_unique<TypeCmpID>, boost::multi_index::ordered_unique<TypeCmpName>, boost::multi_index::ordered_unique<boost::multi_index::identity<Type*> > > >TypeMap; //typedef TypeMap::nth_index<0>::type TypeMap_by_ID; typedef TypeMap::nth_index<0>::type TypeMap_by_Name; typedef TypeMap::nth_index<1>::type TypeMap_by_Type; //typedef std::pair<const TupleType*,const TupleType*> ViewKey; typedef UnorderedMap<Type const*, ArrayType const*> ArrayCacheMap; typedef UnorderedMap<std::pair<Type const*, uint32_t>, ArrayType const*> SmallArrayCacheMap; struct ClassTypeEntry { Rtti const* rtti; ClassType const* classType; void SetPtrType(ObjectPtrType const* iType) { classPtrType = iType; } ObjectPtrType const* GetPtrType() const { return ((flags & 1) == 0) ? classPtrType : nullptr; } void SetHandleType(ResourceHandleType const* iType) { resHandleType = iType; flags |= 1; } ResourceHandleType const* GetHandleType() const { return ((flags & 1) == 1) ? (ResourceHandleType const*)(*((size_t*)&resHandleType) & ~1) : nullptr; } union { unsigned int flags; ObjectPtrType const* classPtrType; ResourceHandleType const* resHandleType; }; }; struct ClassCmpRtti { typedef Rtti const* result_type; result_type operator()(ClassTypeEntry const& iEntry) const { return iEntry.rtti; } }; struct ClassCmpParentRtti { typedef Rtti const* result_type; result_type operator()(ClassTypeEntry const& iEntry) const { return iEntry.rtti->GetFather(); } }; struct ClassCmpName { typedef KString const& result_type; result_type operator()(ClassTypeEntry const& iEntry) const { return iEntry.rtti->GetName(); } }; typedef boost::multi_index::multi_index_container<ClassTypeEntry, boost::multi_index::indexed_by< boost::multi_index::ordered_unique<ClassCmpRtti> ,boost::multi_index::ordered_non_unique<ClassCmpParentRtti> ,boost::multi_index::ordered_unique<ClassCmpName> > > ClassMap; typedef ClassMap::nth_index<0>::type ClassMap_by_Rtti; typedef ClassMap::nth_index<1>::type ClassMap_by_ParentRtti; typedef ClassMap::nth_index<2>::type ClassMap_by_Name; static const size_t UsrTypeFlag = size_t(1)<<(sizeof(size_t)*8-1); } struct TMData { detail::TypeMap m_TypeMap; detail::ArrayCacheMap m_ArrayMap; detail::SmallArrayCacheMap m_SmallArrayMap; detail::ClassMap m_ClassMap; void Clear() { m_TypeMap.clear(); for (auto Type : m_ArrayMap) { eXl_DELETE Type.second; } m_ArrayMap.clear(); m_ClassMap.clear(); } static TMData& Get() { static TMData s_Data; return s_Data; } }; UsrTypeReg BeginTypeRegistration(TypeName iName) { return UsrTypeReg(iName); } UsrTypeReg::UsrTypeReg(TypeName iName) : m_Name(iName) , m_Offset(0) { } UsrTypeReg& UsrTypeReg::AddField(TypeFieldName iName,Type const* iType) { if(iType!=nullptr) { List<FieldDesc>::iterator iter = m_Fields.begin(); List<FieldDesc>::iterator iterEnd = m_Fields.end(); for(;iter!=iterEnd;iter++) { if(iName==iter->GetName()) { eXl_ASSERT_MSG(iType == iter->GetType(),"Inconsistant"); return *this; } } m_Fields.push_back(FieldDesc(iName,m_Offset,iType)); m_Offset+=iType->GetSize(); } return *this; } UsrTypeReg& UsrTypeReg::AddFieldsFrom(const TupleType* iType) { if(iType==nullptr) return *this; unsigned int numFields = iType->GetNumField(); for(unsigned int i=0;i<numFields;i++) { bool nextField = false; TypeFieldName name; const Type* type = iType->GetFieldDetails(i,name); List<FieldDesc>::iterator iter = m_Fields.begin(); List<FieldDesc>::iterator iterEnd = m_Fields.end(); for(;iter!=iterEnd;iter++) { if(name==iter->GetName()) { nextField=true; break; } } if(nextField) continue; m_Fields.push_back(FieldDesc(name,m_Offset,type)); m_Offset+=iType->GetSize(); } return *this; } const TupleType* UsrTypeReg::EndRegistration() { return MakeTuple(m_Name,m_Fields,nullptr); } const TupleType* MakeTuple(TypeName iName,const List<FieldDesc>& iList,size_t* iId) { if(!iList.empty()) { size_t newId = iId==nullptr ? detail::UsrTypeFlag : *iId; TupleType* newType = TupleTypeStruct::MakeTuple(iName,iList,newId); List<FieldDesc>::const_iterator iter = iList.begin(); List<FieldDesc>::const_iterator iterEnd = iList.end(); return newType; } return nullptr; } const Type* RegisterType(Type const* iType) { if(iType == nullptr) return nullptr; eXl_ASSERT_REPAIR_RET(iType->IsCoreType() || iType->IsEnum(), nullptr); detail::TypeMap_by_Type::iterator iter = TMData::Get().m_TypeMap.get<1>().find(const_cast<Type*>(iType)); eXl_ASSERT_MSG(iter == TMData::Get().m_TypeMap.get<1>().end(),"Already registered"); if(iter!=TMData::Get().m_TypeMap.get<1>().end()) { LOG_WARNING<<"Type "<<iType->GetName()<<"already registered"<<"\n"; return *iter; } TMData::Get().m_TypeMap.insert(const_cast<Type*>(iType)); return iType; } const Type* GetCoreTypeFromName(TypeName iName) { auto const& typeMapByName = TMData::Get().m_TypeMap.get<0>(); auto iter = typeMapByName.find(iName); if (iter != typeMapByName.end()) { return *iter; } return nullptr; } Vector<Type const*> GetCoreTypes() { Vector<Type const*> coreTypes; for (auto const& entry : TMData::Get().m_TypeMap) { if (entry->IsCoreType()) { coreTypes.push_back(entry); } } return coreTypes; } TypeManager::EnumTypeReg::EnumTypeReg(TypeName iName) : m_Name(iName) { } TypeManager::EnumTypeReg& TypeManager::EnumTypeReg::AddValue(TypeEnumName iName) { for(unsigned int i = 0;i<m_Enums.size();++i) { if(m_Enums[i] == iName) { LOG_WARNING<<"Enum "<<iName<<" already exists"<<"\n"; return *this; } } m_Enums.push_back(iName); return *this; } namespace detail { EnumType const* _MakeEnumType(TypeName iName, Vector<TypeEnumName> & iVal) { //size_t newId = ++TMData::Get().m_IDGen; EnumType* newType = eXl_NEW EnumType(iName,0); newType->m_Enums.swap(iVal); Type const* res = TypeManager::RegisterType(newType); if(res == nullptr) { //TMData::Get().m_IDGen--; eXl_DELETE newType; return nullptr; } return newType; } } Type const* EnumTypeReg::EndRegistration() { if(m_Name != "" && m_Enums.size() > 0) { return detail::_MakeEnumType(m_Name,m_Enums); }else { LOG_WARNING<<"Invalid Enum definition"<<"\n"; return nullptr; } } EnumTypeReg BeginEnumTypeRegistration(TypeName iName) { return EnumTypeReg(iName); } ArrayType const* GetArrayType(Type const* iType) { if(iType != nullptr) { detail::ArrayCacheMap::iterator iter = TMData::Get().m_ArrayMap.find(iType); if(iter == TMData::Get().m_ArrayMap.end()) { return nullptr; } else { return iter->second; } } return nullptr; } void RegisterArrayType(ArrayType const* iType) { if (iType != nullptr) { eXl_ASSERT_REPAIR_RET(iType->IsCoreType(), ); detail::ArrayCacheMap::iterator iter = TMData::Get().m_ArrayMap.find(iType); if (iter == TMData::Get().m_ArrayMap.end()) { TMData::Get().m_ArrayMap.insert(std::make_pair(iType->GetElementType(), iType)); } } } ArrayType const* GetSmallArrayType(Type const* iType, uint32_t iBufferSize) { if (iType != nullptr) { detail::SmallArrayCacheMap::iterator iter = TMData::Get().m_SmallArrayMap.find(std::make_pair(iType, iBufferSize)); if (iter == TMData::Get().m_SmallArrayMap.end()) { return nullptr; } else { return iter->second; } } return nullptr; } void RegisterSmallArrayType(ArrayType const* iType, uint32_t iBufferSize) { if (iType != nullptr) { eXl_ASSERT_REPAIR_RET(iType->IsCoreType(), ); auto key = std::make_pair(iType->GetElementType(), iBufferSize); detail::SmallArrayCacheMap::iterator iter = TMData::Get().m_SmallArrayMap.find(key); if (iter == TMData::Get().m_SmallArrayMap.end()) { TMData::Get().m_SmallArrayMap.insert(std::make_pair(key, iType)); } } } Err ListDerivedClassesForRtti(Rtti const& iRtti, List<Rtti const*>& oList) { oList.clear(); List<Rtti const*> tempList; List<Rtti const*> tempList2; tempList.push_back(&iRtti); while(!tempList.empty()) { List<Rtti const*>::iterator iter = tempList.begin(); List<Rtti const*>::iterator iterEnd = tempList.end(); for(; iter != iterEnd; ++iter) { std::pair<detail::ClassMap_by_ParentRtti::iterator, detail::ClassMap_by_ParentRtti::iterator> iterRange = TMData::Get().m_ClassMap.get<1>().equal_range(*iter); detail::ClassMap_by_ParentRtti::iterator iterEntry = iterRange.first; for(; iterEntry != iterRange.second; ++iterEntry) { tempList2.push_back(iterEntry->rtti); oList.push_back(iterEntry->rtti); } } tempList.clear(); tempList.swap(tempList2); } RETURN_SUCCESS; } ResourceHandleType const* GetResourceHandleForRtti(Rtti const& iRtti) { detail::ClassMap_by_Rtti::iterator iter = TMData::Get().m_ClassMap.get<0>().find(&iRtti); if(iter != TMData::Get().m_ClassMap.get<0>().end()) { return iter->GetHandleType(); } return nullptr; } namespace detail { void _TMClear() { TMData::Get().Clear(); } } } }
29.077263
460
0.601124
eXl-Nic
6f91fe545d655a91ce5e6bbcaaff9de6252f4ed0
9,157
hpp
C++
tau/TauUtils/include/TUMaths.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
1
2020-04-22T04:07:01.000Z
2020-04-22T04:07:01.000Z
tau/TauUtils/include/TUMaths.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
tau/TauUtils/include/TUMaths.hpp
hyfloac/TauEngine
1559b2a6e6d1887b8ee02932fe0aa6e5b9d5652c
[ "MIT" ]
null
null
null
// ReSharper disable CppClangTidyClangDiagnosticSignCompare #pragma once #include "NumTypes.hpp" /** * Equal to pi/180. */ #define RADIANS_TO_DEGREES_CONVERTER_VAL 57.29577951308232087679815481410517 /** * Equal to 180/pi */ #define DEGREES_TO_RADIANS_CONVERTER_VAL 0.017453292519943295769236907684886 /** * Converts radians to degrees (single precision). */ #define RAD_2_DEG_F(__F) (float) ((__F) * RADIANS_TO_DEGREES_CONVERTER_VAL) /** * Converts degrees to radians (single precision). */ #define DEG_2_RAD_F(__F) (float) ((__F) * DEGREES_TO_RADIANS_CONVERTER_VAL) /** * Converts radians to degrees (double precision). */ #define RAD_2_DEG_D(__D) (double) ((__D) * RADIANS_TO_DEGREES_CONVERTER_VAL) /** * Converts degrees to radians (double precision). */ #define DEG_2_RAD_D(__D) (double) ((__D) * DEGREES_TO_RADIANS_CONVERTER_VAL) #define RAD_2_DEG(__F) RAD_2_DEG_F(__F) #define DEG_2_RAD(__F) DEG_2_RAD_F(__F) template<typename _T> [[nodiscard]] inline constexpr _T minT(const _T a, const _T b) noexcept { return a < b ? a : b; } template<typename _T> [[nodiscard]] inline constexpr _T minT(const _T a, const _T b, const _T c) noexcept { return minT(minT(a, b), c); } template<typename _T> [[nodiscard]] inline constexpr _T minT(const _T a, const _T b, const _T c, const _T d) noexcept { return minT(minT(a, b), minT(c, d)); } template<typename _T> [[nodiscard]] inline constexpr _T maxT(const _T a, const _T b) noexcept { return a > b ? a : b; } template<typename _T> [[nodiscard]] inline constexpr _T maxT(const _T a, const _T b, const _T c) noexcept { return maxT(maxT(a, b), c); } template<typename _T> [[nodiscard]] inline constexpr _T maxT(const _T a, const _T b, const _T c, const _T d) noexcept { return maxT(maxT(a, b), maxT(c, d)); } template<typename _T0, typename _T1> [[nodiscard]] inline constexpr _T0 minT(const _T0 a, const _T1 b) noexcept { return a < b ? a : b; } template<typename _T0, typename _T1, typename _T2> [[nodiscard]] inline constexpr _T0 minT(const _T0 a, const _T1 b, const _T2 c) noexcept { return minT(minT(a, b), c); } template<typename _T0, typename _T1, typename _T2, typename _T3> [[nodiscard]] inline constexpr _T0 minT(const _T0 a, const _T1 b, const _T2 c, const _T3 d) noexcept { return minT(minT(a, b), minT(c, d)); } template<typename _T0, typename _T1> [[nodiscard]] inline constexpr _T0 maxT(const _T0 a, const _T1 b) noexcept { return a > b ? a : b; } template<typename _T0, typename _T1, typename _T2> [[nodiscard]] inline constexpr _T0 maxT(const _T0 a, const _T1 b, const _T2 c) noexcept { return maxT(maxT(a, b), c); } template<typename _T0, typename _T1, typename _T2, typename _T3> [[nodiscard]] inline constexpr _T0 maxT(const _T0 a, const _T1 b, const _T2 c, const _T3 d) noexcept { return maxT(maxT(a, b), maxT(c, d)); } /** * Relative epsilon equals function. */ template<typename _T> static inline bool rEpsilonEquals(const _T x, const _T y, const _T epsilon = 1E-5) { const _T epsilonRelative = maxT(fabs(x), fabs(y)) * epsilon; return fabs(x - y) <= epsilonRelative; } /** * Absolute epsilon equals function. */ template<typename _T> static inline bool aEpsilonEquals(const _T x, const _T y, const _T epsilon = 1E-5) { return fabs(x - y) <= epsilon; } const u32 clzTab32[32] = { 0, 9, 1, 10, 13, 21, 2, 29, 11, 14, 16, 18, 22, 25, 3, 30, 8, 12, 20, 28, 15, 17, 24, 7, 19, 27, 23, 6, 26, 5, 4, 31 }; const u32 clzTab64[64] = { 63, 0, 58, 1, 59, 47, 53, 2, 60, 39, 48, 27, 54, 33, 42, 3, 61, 51, 37, 40, 49, 18, 28, 20, 55, 30, 34, 11, 43, 14, 22, 4, 62, 57, 46, 52, 38, 26, 32, 41, 50, 36, 17, 19, 29, 10, 13, 21, 56, 45, 25, 31, 35, 16, 9, 12, 44, 24, 15, 8, 23, 7, 6, 5 }; const u32 ctzTab32[32] = { 0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8, 31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9 }; const u32 ctzTab64[64] = { 0, 47, 1, 56, 48, 27, 2, 60, 57, 49, 41, 37, 28, 16, 3, 61, 54, 58, 35, 52, 50, 42, 21, 44, 38, 32, 29, 23, 17, 11, 4, 62, 46, 55, 26, 59, 40, 36, 15, 53, 34, 51, 20, 43, 31, 22, 10, 45, 25, 39, 14, 33, 19, 30, 9, 24, 13, 18, 8, 12, 7, 6, 5, 63 }; template<typename _T> [[nodiscard]] constexpr inline _T _alignTo(const _T val, const _T alignment) noexcept { if(alignment == 1) { return val; } return (val + alignment) & ~(alignment - 1); } template<typename _Tv, typename _Ta> [[nodiscard]] constexpr inline _Tv _alignTo(const _Tv val, const _Ta _alignment) noexcept { const _Tv alignment = static_cast<_Tv>(_alignment); if(alignment == 1) { return val; } return (val + alignment) & ~(alignment - 1); } template<typename _T, _T _Alignment> [[nodiscard]] constexpr inline _T _alignTo(const _T val) noexcept { if(_Alignment == 1) { return val; } return (val + _Alignment) & ~(_Alignment - 1); } template<typename _Tv, typename _Ta, _Ta _Alignment> [[nodiscard]] constexpr inline _Tv _alignTo(const _Tv val) noexcept { constexpr _Tv alignment = static_cast<_Tv>(_Alignment); if(alignment == 1) { return val; } return (val + alignment) & ~(alignment - 1); } #ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #define NOMINMAX #include <Windows.h> [[nodiscard]] inline u32 _ctz(const u32 v) noexcept { unsigned long trailingZero = 0; _BitScanForward(&trailingZero, v); return trailingZero; } [[nodiscard]] inline u32 _clz(const u32 v) noexcept { unsigned long leadingZero = 0; _BitScanReverse(&leadingZero, v); return 31 - leadingZero; } [[nodiscard]] inline u64 _ctz(const u64 v) noexcept { unsigned long trailingZero = 0; _BitScanForward64(&trailingZero, v); return trailingZero; } [[nodiscard]] inline u64 _clz(const u64 v) noexcept { unsigned long leadingZero = 0; _BitScanReverse64(&leadingZero, v); return 63 - leadingZero; } [[nodiscard]] constexpr inline u32 _ctzC(const u32 v) noexcept { return ctzTab32[((v ^ (v - 1)) * 0x077CB531u) >> 27]; } [[nodiscard]] constexpr inline u32 _clzC(u32 v) noexcept { v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return 63 - clzTab32[((v * 0x07C4ACDDu)) >> 27]; } [[nodiscard]] constexpr inline u32 _ctzC(const u64 v) noexcept { return ctzTab64[((v ^ (v - 1)) * 0x03F79D71B4CB0A89u) >> 58]; } [[nodiscard]] constexpr inline u32 _clzC(u64 v) noexcept { v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; return 63 - clzTab64[((v - (v >> 1)) * 0x07EDD5E59A4E28C2ull) >> 58]; } #else [[nodiscard]] inline u32 _ctz(const u32 v) noexcept { return __builtin_ctz(v); } [[nodiscard]] inline u32 _clz(const u32 v) noexcept { return __builtin_clz(v); } [[nodiscard]] inline u32 _ctz(const u64 v) noexcept { return __builtin_ctzll(v); } [[nodiscard]] inline u32 _clz(const u64 v) noexcept { return __builtin_clzll(v); } [[nodiscard]] constexpr inline u32 _ctzC(const u32 v) noexcept { return __builtin_ctz(v); } [[nodiscard]] constexpr inline u32 _clzC(const u32 v) noexcept { return __builtin_clz(v); } [[nodiscard]] constexpr inline u32 _ctzC(const u64 v) noexcept { return __builtin_ctzll(v); } [[nodiscard]] constexpr inline u32 _clzC(const u64 v) noexcept { return __builtin_clzll(v); } #endif #if defined(TAU_CROSS_PLATFORM) [[nodiscard]] constexpr inline u32 nextPowerOf2(u32 v) noexcept { --v; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; return v + 1; } [[nodiscard]] constexpr inline u64 nextPowerOf2(u64 v) noexcept { --v; v |= v >> 1; v |= v >> 2; v |= v >> 4; v |= v >> 8; v |= v >> 16; v |= v >> 32; return v + 1; } [[nodiscard]] constexpr inline u32 log2i(u32 value) noexcept { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; return clzTab32[((value * 0x07C4ACDDu)) >> 27]; } [[nodiscard]] constexpr inline u32 log2i(u64 value) noexcept { value |= value >> 1; value |= value >> 2; value |= value >> 4; value |= value >> 8; value |= value >> 16; value |= value >> 32; return clzTab64[((value - (value >> 1)) * 0x07EDD5E59A4E28C2ull) >> 58]; } #else [[nodiscard]] constexpr inline u32 nextPowerOf2(const u32 v) noexcept { if(v == 1) { return 1; } return 1u << (32u - _clzC(v - 1u)); } [[nodiscard]] constexpr inline u64 nextPowerOf2(const u64 v) noexcept { if(v == 1) { return 1; } return 1ull << (64ull - _clzC(v - 1ull)); } [[nodiscard]] constexpr inline u32 log2i(const u32 v) noexcept { return 63 - _clzC(v); } [[nodiscard]] constexpr inline u32 log2i(const u64 v) noexcept { return 63 - _clzC(v); } #endif
28.262346
101
0.611663
hyfloac
6f934bf0f862e239e196e4ed20105ed5bcadbaf7
4,638
cpp
C++
paxos++/detail/tcp_connection.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
54
2015-02-09T11:46:30.000Z
2021-08-13T14:08:52.000Z
paxos++/detail/tcp_connection.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
null
null
null
paxos++/detail/tcp_connection.cpp
armos-db/libpaxos-cpp
31e8a3f9664e3e6563d26dbc1323457f596b8eef
[ "BSD-3-Clause" ]
17
2015-01-13T03:18:49.000Z
2022-03-23T02:20:57.000Z
#include <iostream> #include <functional> #include <assert.h> #include <boost/asio/write.hpp> #include <boost/asio/placeholders.hpp> #include "util/debug.hpp" #include "parser.hpp" #include "command_dispatcher.hpp" #include "tcp_connection.hpp" namespace paxos { namespace detail { tcp_connection::tcp_connection ( boost::asio::io_service & io_service) : socket_ (io_service) { } tcp_connection::~tcp_connection () { PAXOS_DEBUG ("destructing connection " << this); } /*! static */ tcp_connection_ptr tcp_connection::create ( boost::asio::io_service & io_service) { return tcp_connection_ptr ( new tcp_connection (io_service)); } void tcp_connection::close () { socket_.close (); } bool tcp_connection::is_open () const { return socket_.is_open (); } boost::asio::ip::tcp::socket & tcp_connection::socket () { return socket_; } void tcp_connection::write_command ( detail::command const & command) { parser::write_command (shared_from_this (), command); } void tcp_connection::read_command ( read_callback callback) { parser::read_command (shared_from_this (), callback); } void tcp_connection::read_command_loop ( read_callback callback) { read_command ( [this, callback] (boost::optional <enum error_code> error, command const & command) { callback (error, command); if (!error) { this->read_command_loop (callback); } }); } void tcp_connection::write ( std::string const & message) { boost::mutex::scoped_lock lock (mutex_); write_locked (message); } void tcp_connection::write_locked ( std::string const & message) { /*! The problem with Boost.Asio is that it assumes that the buffer we send to async_write () must stay alive until the callback to handle_write () has been called. Since there is no way we can guarantee that if we use the message object we get as a reference to this function, we have no alternative but to copy the data into our local buffer. But wait! What happends when write() is called when we are not yet done writing another block? In that case, we will just append that data onto the queue. The handle_write () function checks whether any data is still pending on the queue, and if so, ensures another async_write () is called. */ if (write_buffer_.empty () == true) { write_buffer_ = message; start_write_locked (); } else { write_buffer_ += message; } } void tcp_connection::start_write_locked () { PAXOS_ASSERT (write_buffer_.empty () == false); boost::asio::async_write (socket_, boost::asio::buffer (write_buffer_), std::bind (&tcp_connection::handle_write, /*! Using shared_from_this here instead of this ensures that we obtain a shared pointer to ourselves, and so when our object would go out of scope normally, it at least stays alive until this callback is called. */ shared_from_this(), std::placeholders::_1, std::placeholders::_2)); } void tcp_connection::handle_write ( boost::system::error_code const & error, size_t bytes_transferred) { if (error) { PAXOS_WARN ("an error occured while writing data: " << error.message ()); return; } boost::mutex::scoped_lock lock (mutex_); handle_write_locked (bytes_transferred); } void tcp_connection::handle_write_locked ( size_t bytes_transferred) { PAXOS_ASSERT (write_buffer_.size () >= bytes_transferred); write_buffer_ = write_buffer_.substr (bytes_transferred); /*! As discussed in the write () function, if we still have data on the buffer, ensure that data is also written. */ if (write_buffer_.empty () == false) { start_write_locked (); } } }; };
24.670213
102
0.55994
armos-db
6f958355910429a3c5ab6590c7d0f0d3ba96cfa4
276
hpp
C++
src/color.hpp
adamhutchings/chirpc
70d190fa79fa9f968b8de14ca41a8f50bae0019b
[ "MIT" ]
1
2021-06-02T13:24:13.000Z
2021-06-02T13:24:13.000Z
src/color.hpp
dekrain/chirpc
93a6230da746d1e6e16230d79b151dee0d3f4a09
[ "MIT" ]
null
null
null
src/color.hpp
dekrain/chirpc
93a6230da746d1e6e16230d79b151dee0d3f4a09
[ "MIT" ]
null
null
null
/* Command-Line coloring, currently works only on linux VT100-based terminals.. This should be overhaul, rn this is very hacky. */ #pragma once #include <iostream> enum class color { red, blue, green, yellow, }; std::string write_color(std::string, color);
16.235294
77
0.692029
adamhutchings
6f9821aac5c9809f3b37c5ad13ae5ed5bacf5b2d
529
cpp
C++
C++/product-of-the-last-k-numbers.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/product-of-the-last-k-numbers.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/product-of-the-last-k-numbers.cpp
jaiskid/LeetCode-Solutions
a8075fd69087c5463f02d74e6cea2488fdd4efd1
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: ctor: O(1) // add : O(1) // get : O(1) // Space: O(n) class ProductOfNumbers { public: ProductOfNumbers() : accu_(1, 1) { } void add(int num) { if (!num) { accu_ = {1}; return; } accu_.emplace_back(accu_.back() * num); } int getProduct(int k) { if (accu_.size() <= k) { return 0; } return accu_.back() / accu_[accu_.size() - 1 - k]; } private: vector<int> accu_; };
17.064516
58
0.42344
jaiskid
6fa2d4f12b5516aaec0d7d3d08a9842cd5423925
1,309
hpp
C++
includes/Transaction.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
includes/Transaction.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
includes/Transaction.hpp
moguchev/Wallet
ddc38f49b3f563e9a68b784bf315206d21631116
[ "MIT" ]
null
null
null
#ifndef TRANSACTION_HPP #define TRANSACTION_HPP #include <algorithm> #include <fstream> #include <includes/Script.hpp> #include <includes/TxIn.hpp> #include <includes/TxOut.hpp> #include <string> using outputs = std::vector<TxOut>; using inputs = std::vector<TxIn>; class Transaction { public: Transaction() = default; ~Transaction() = default; Transaction(const std::string& file_name); Transaction(int32_t version, const inputs& input, const outputs& output, uint32_t lock_time); Transaction(Transaction&& other); Transaction(const Transaction& other); Transaction& operator=(Transaction&& other); Transaction& operator=(const Transaction& other); std::string get_hex_tx() const; std::vector<byte> get_byte_tx() const; void sign(const std::string& private_key_wif); bool is_signed() const; static Transaction parse(const std::string& file_name); std::vector<TxIn> get_inputs() const; std::vector<TxOut> get_outputs() const; int32_t get_version() const; uint32_t get_locktime() const; byte get_in_count() const; byte get_out_count() const; private: int32_t version_; byte tx_in_count_; inputs tx_in_; byte tx_out_count_; outputs tx_out_; uint32_t locktime_; }; #endif // TRANSACTION_HPP
18.7
57
0.70741
moguchev
6fa73f82aaf4c72123eb26e2a0d5365e0d31cd44
1,764
cpp
C++
src/mixer/mixer.editableObject_PolygonDuplicate.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
src/mixer/mixer.editableObject_PolygonDuplicate.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
src/mixer/mixer.editableObject_PolygonDuplicate.cpp
3dhater/mixer
52dca419de53abf3b61acd020c2fc9a52bce2255
[ "libpng-2.0" ]
null
null
null
#include "mixer.sdkImpl.h" #include "mixer.application.h" #include "mixer.viewportCamera.h" #include "mixer.pluginGUIImpl.h" #include "mixer.editableObject.h" #include "containers/mixer.BST.h" #include <set> extern miApplication * g_app; void miEditableObject::PolygonDuplicate() { miArray<miPolygon*> newPolygons; newPolygons.reserve(0x1000); { miBinarySearchTree<miVertex*> newVerts; auto c = m_mesh->m_first_polygon; auto l = c->m_left; while (true) { if (c->m_flags & miPolygon::flag_isSelected) { miPolygon* newPolygon = m_allocatorPolygon->Allocate(); newPolygons.push_back(newPolygon); auto cv = c->m_verts.m_head; auto lv = cv->m_left; while (true) { miVertex* newVertex = 0; if (!newVerts.Get((uint64_t)cv->m_data.m_vertex, newVertex)) { newVertex = m_allocatorVertex->Allocate(); newVertex->m_position = cv->m_data.m_vertex->m_position; m_mesh->_add_vertex_to_list(newVertex); newVerts.Add((uint64_t)cv->m_data.m_vertex, newVertex); } newVertex->m_polygons.push_back(newPolygon); newPolygon->m_verts.push_back(miPolygon::_vertex_data(newVertex, cv->m_data.m_uv, cv->m_data.m_normal, 0)); if (cv == lv) break; cv = cv->m_right; } } if (c == l) break; c = c->m_right; } } if (!newPolygons.m_size) return; this->DeselectAll(g_app->m_editMode); for (u32 i = 0; i < newPolygons.m_size; ++i) { m_mesh->_add_polygon_to_list(newPolygons.m_data[i]); newPolygons.m_data[i]->m_flags |= miPolygon::flag_isSelected; } m_mesh->UpdateCounts(); _rebuildEdges(); this->OnSelect(g_app->m_editMode); this->UpdateAabb(); g_app->UpdateSelectionAabb(); /// g_app->_callVisualObjectOnSelect(); _rebuildEdges(); }
23.52
112
0.681406
3dhater
6fa958e87f8361094f5b5fadb9ad561a6ae1039e
1,954
hpp
C++
boiled-plates/bop-utility/Benchmark.hpp
Lokidottir/boiled-plates
2ada3a86f5ea9a12a3244f9f6de54ce8329dbe38
[ "MIT" ]
null
null
null
boiled-plates/bop-utility/Benchmark.hpp
Lokidottir/boiled-plates
2ada3a86f5ea9a12a3244f9f6de54ce8329dbe38
[ "MIT" ]
null
null
null
boiled-plates/bop-utility/Benchmark.hpp
Lokidottir/boiled-plates
2ada3a86f5ea9a12a3244f9f6de54ce8329dbe38
[ "MIT" ]
null
null
null
#ifndef BOP_BENCHMARK_HPP #define BOP_BENCHMARK_HPP #include <chrono> namespace bop { namespace util { #ifndef BOP_UTIL_DEFAULT_TYPES #define BOP_UTIL_DEFAULT_TYPES typedef double prec_type; typedef uint64_t uint_type; #endif template<typename ...params> void nothing(params&&... args) { /* Used to gauge function call time. */ } template<class T = uint_type,typename F, typename ...params> T benchmark(uint_type test_count, F function, params&&... P) { /* Returns nanoseconds taken to perform a function given the parameters. The time taken to call the function is subtracted from the result. */ //Get the time before empty function calling auto empty_funct_b = std::chrono::high_resolution_clock::now(); #ifdef BOP_BENCHMARK_KEEP_CALLTIME for (unsigned int i = 0; i < test_count; i++) { /* Call the empty function as many times as the function being benchmarked to eliminate function call time as a factor. */ nothing(P...); } #endif //Get the time after the function calling auto empty_funct_a = std::chrono::high_resolution_clock::now(); //Get the time before benchmarked function is called auto before = std::chrono::high_resolution_clock::now(); for (unsigned int i = 0; i < test_count; i++) { function(P...); } //Get the time after auto after = std::chrono::high_resolution_clock::now(); return (std::chrono::duration_cast<std::chrono::nanoseconds>((after - before) - (empty_funct_b - empty_funct_a)).count()/static_cast<T>(test_count)); } } } #endif
36.867925
161
0.562948
Lokidottir
6faa0e34657af00fdaf827230b44506650038fa7
1,767
cpp
C++
C++/form-largest-integer-with-digits-that-add-up-to-target.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
3,269
2018-10-12T01:29:40.000Z
2022-03-31T17:58:41.000Z
C++/form-largest-integer-with-digits-that-add-up-to-target.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
53
2018-12-16T22:54:20.000Z
2022-02-25T08:31:20.000Z
C++/form-largest-integer-with-digits-that-add-up-to-target.cpp
Akhil-Kashyap/LeetCode-Solutions
c671a588f96f4e4bbde4512727322ff9b1c8ae6a
[ "MIT" ]
1,236
2018-10-12T02:51:40.000Z
2022-03-30T13:30:37.000Z
// Time: O(t) // Space: O(t) class Solution { public: string largestNumber(vector<int>& cost, int target) { vector<int> dp(1); dp[0] = 0; for (int t = 1; t <= target; ++t) { dp.emplace_back(-1); for (int i = 0; i < 9; ++i) { if (t < cost[i] || dp[t - cost[i]] < 0) { continue; } dp[t] = max(dp[t], dp[t - cost[i]] + 1); } } if (dp[target] < 0) { return "0"; } string result; for (int i = 8; i >= 0; --i) { while (target >= cost[i] && dp[target] == dp[target - cost[i]] + 1) { target -= cost[i]; result.push_back('1' + i); } } return result; } }; // Time: O(t) // Space: O(t) class Solution2 { public: string largestNumber(vector<int>& cost, int target) { const auto& key = [](const auto& a) { return pair{accumulate(cbegin(a), cend(a), 0), a}; }; vector<vector<int>> dp = {vector<int>(9)}; for (int t = 1; t <= target; ++t) { dp.emplace_back(); for (int i = 0; i < 9; ++i) { if (t < cost[i] || dp[t - cost[i]].empty()) { continue; } auto curr = dp[t - cost[i]]; ++curr[8 - i]; if (key(curr) > key(dp[t])) { dp[t] = move(curr); } } } if (dp.back().empty()) { return "0"; } string result; for (int i = 0; i < dp.back().size(); ++i) { result += string(dp.back()[i], '1' + 8 - i); } return result; } };
27.609375
81
0.370119
Akhil-Kashyap
6fabb7217734c99c79c1b9c076e29efd63650c74
1,865
cpp
C++
Fudl/easy/solved/Equivalent Resistance, Circuit Building.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
1
2022-03-16T08:56:31.000Z
2022-03-16T08:56:31.000Z
Fudl/easy/solved/Equivalent Resistance, Circuit Building.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
2
2022-03-17T11:27:14.000Z
2022-03-18T07:41:00.000Z
Fudl/easy/solved/Equivalent Resistance, Circuit Building.cpp
AhmedMostafa7474/Codingame-Solutions
da696a095c143c5d216bc06f6689ad1c0e25d0e0
[ "MIT" ]
6
2022-03-13T19:56:11.000Z
2022-03-17T12:08:22.000Z
#include <ctype.h> #include <iomanip> #include <cstdio> #include <ios> #include <iostream> #include <string> #include <vector> #include <algorithm> #include <map> #include <stack> using namespace std; /** * Auto-generated code below aims at helping you parse * the standard input according to the problem statement. **/ int main() { int n; cin >> n; cin.ignore(); map<string,double> var; for (int i = 0; i < n; i++) { string name; double r; cin >> name >> r; cin.ignore(); var[name] = r; } stack<string> ch; stack<double> val; char temp = '1'; string circuit; getline(cin, circuit); for (int i = 0; i < circuit.size(); i++) { if (circuit[i] == '[' || circuit[i] == '(') ch.push(circuit.substr(i,1)); else if (isalpha(circuit[i])) { string temp = ""; while (i < circuit.size()) { temp += circuit.substr(i,1); i++; if (!isalpha(circuit[i])) { val.push(var[temp]); ch.push(temp); i--; break; } } } else if (circuit[i] == ')') { double value = 0; while (!ch.empty()) { if (ch.top() == "(") { val.push(value); ch.pop(); ch.push("a"); break; } // value += top value += val.top(); val.pop(); ch.pop(); } } else if (circuit[i] == ']') { double value = 0; while (!ch.empty()) { if (ch.top() == "[") { val.push(1/value); ch.pop(); ch.push("a"); break; } // value += 1/top value += 1/val.top(); val.pop(); ch.pop(); } } } // Write an answer using cout. DON'T FORGET THE "<< endl" // To debug: cerr << "Debug messages..." << endl; cout << fixed << setprecision(1) << val.top() << endl; }
21.193182
59
0.472386
AhmedMostafa7474
6faef9985d7c2a365462673f37a33686614a73a8
258
cpp
C++
classes/RandomUtility.cpp
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
classes/RandomUtility.cpp
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
classes/RandomUtility.cpp
dstratossong/CC3K
026c2de810a7174a001427e2b9c3499b5ef1444f
[ "Apache-2.0" ]
null
null
null
// // Created by glados on 4/11/15. // #include <stdlib.h> #include <iostream> #include "RandomUtility.h" int RandomUtility::get_random_integer(int range) { return rand() % range; } void RandomUtility::seed() { srand((unsigned int) time(NULL)); }
16.125
50
0.674419
dstratossong
6fb11542c6ea9c59dd65ca5c48c30dee2c65cb43
1,215
cpp
C++
KTLT_doan1/file.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
KTLT_doan1/file.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
KTLT_doan1/file.cpp
ipupro2/KTLTr-Project-1
1ee29823a75b9518d6cc4d0b94edebc2a46ec63c
[ "MIT" ]
null
null
null
#include "file.h" void LoadScore(saveData data[]) { ifstream inNameScore; inNameScore.open("save.sav"); if (!inNameScore) { inNameScore.close(); ofstream outNameScore; outNameScore.open("save.sav"); for (int i = 0; i < 10; i++) outNameScore << "Noname 0" << endl; outNameScore.close(); inNameScore.open("save.sav"); } for (int i = 0; i < 10; i++) { inNameScore >> data[i].name; inNameScore >> data[i].score; } inNameScore.close(); } void SaveScore(saveData data) { ifstream inNameScore; inNameScore.open("save.sav"); saveData a[10]; string t1; unsigned long t2; int i = 0; LoadScore(a); for (i = 0; i < 10; i++) if (a[i].score < data.score) { t1 = a[i].name; t2 = a[i].score; a[i].name = data.name; a[i].score = data.score; for (int j = 9; j > i + 1; j--) { a[j].name = a[j - 1].name; a[j].score = a[j - 1].score; } a[i + 1].name = t1; a[i + 1].score = t2; break; } cout << endl; inNameScore.close(); ofstream outNameScore; outNameScore.open("save.sav"); for (i = 0; i < 10; i++) { outNameScore << a[i].name << " " << a[i].score << endl; } outNameScore.close(); }
20.25
58
0.548971
ipupro2
6fb33bf4fabc61bc75f4dd6f0059b84b3f4cc796
4,765
cpp
C++
src/render/Shader.cpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
1
2021-08-07T13:02:01.000Z
2021-08-07T13:02:01.000Z
src/render/Shader.cpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
src/render/Shader.cpp
Yousazoe/Solar
349c75f7a61b1727aa0c6d581cf75124b2502a57
[ "Apache-2.0" ]
null
null
null
#include<render/Shader.hpp> #include<render/ShaderInstanceLoader.hpp> #include<fs/Path.hpp> #include<fs/FileSystem.hpp> #include<sstream> namespace tutorial::graphics { bool Shader::_has_shader_cachae = true; using ShaderCompiler = std::string; struct CompileStrategy { std::string version; std::string shader_type; std::string suffix; }; std::string _shader_res_path = "../../data/shaders/"; CompileStrategy vs_5_0 = { "vs_5_0", "VERTEX_SHADER", "_vs" }; CompileStrategy gs_5_0 = { "gs_5_0", "GEOMETRY_SHADER", "_gs" }; CompileStrategy ps_5_0 = { "ps_5_0", "PIXEL_SHADER", "_ps" }; CompileStrategy cs_5_0 = { "cs_5_0", "COMPUTE_SHADER", "_cs" }; inline void compile_shader( const ShaderCompiler& compiler, const fs::Path& path, const fs::Path& output_path, const CompileStrategy& strategy, const std::string& entry, const std::vector<std::string>& defines ) { static std::stringstream cmd; cmd.clear(); cmd << compiler; cmd << " /Od "; cmd << " /T " << strategy.version; cmd << " /E " << entry; // use main as default entry cmd << " /I ./ "; // pipeline closure cmd << " /I " << path.parent_path().string(); // include directory/ cmd << " /D " << strategy.shader_type; for (const auto& define : defines) { cmd << " /D " << define; } cmd << " /Fo " << output_path.string(); cmd << path.string(); system(cmd.str().c_str()); cmd.str(""); } inline auto get_output_path( const fs::Path& path, const CompileStrategy& strategy ) { auto output_directory = path.parent_path(); output_directory.concat("/fxbin/"); auto file_name = path.stem().string(); return output_directory.append( file_name + strategy.suffix + ".fxo " ); } Shader::Shader(std::string name, bool compute) noexcept : _name{ std::move(name) }, _compute{ compute } { } Shader::Shader(std::string name, std::string entry, bool compute) noexcept : _name{ std::move(name) }, _entry{ std::move(entry) }, _compute{ compute } { } void Shader::operator=(Shader&& rhs) noexcept { _name = std::move(rhs._name); _entry = std::move(rhs._entry); _option_count = rhs._option_count; _options = rhs._options; _blocks = rhs._blocks; _shader_instances = std::move(rhs._shader_instances); } auto Shader::add_block(const ShaderBlock& block) noexcept -> void { assert(block.index < 32u); _blocks[block.index].enable = true; _blocks[block.index].option_offset = _option_count; const auto& option_strings = block.option_strings; std::copy_n(option_strings.begin(), option_strings.size(), _options.begin() + _option_count); _option_count += uint8(block.option_strings.size()); } auto Shader::default() noexcept -> ShaderVersion { return ShaderVersion{ *this }; } auto Shader::fetch(uint64 version) noexcept -> const ShaderInstance& { if (_shader_instances.find(version) == _shader_instances.end()) { _shader_instances[version] = compile(version); } return _shader_instances[version]; } auto Shader::compile(uint64 version) const noexcept -> ShaderInstance { std::vector<std::string> defines = {}; for (uint32 opt = 0u; opt < 32u; ++opt) { if (version & (1 << opt)) { defines.push_back(_options[opt]); } } static std::string compiler = std::string("fxc "); //compiler += " /I " + std::string(compilerDirectory) + "FX"; auto path = _shader_res_path + _name + (_compute ? ".compute" : ".shader"); auto output_path_base = _shader_res_path + _name + "_" + std::to_string(version); if (_compute) { auto output_path_cs = get_output_path(output_path_base, cs_5_0); compile_shader(compiler, path, output_path_cs, cs_5_0, _entry, defines); return ShaderInstanceLoader::load_compute(output_path_cs); } else { auto output_path_vs = get_output_path(output_path_base, vs_5_0); auto output_path_gs = get_output_path(output_path_base, gs_5_0); auto output_path_ps = get_output_path(output_path_base, ps_5_0); if (!_has_shader_cachae || !fs::exists(fs::status(output_path_vs))) { compile_shader(compiler, path, output_path_vs, vs_5_0, _entry, defines); } if (!_has_shader_cachae || !fs::exists(fs::status(output_path_gs))) { compile_shader(compiler, path, output_path_gs, gs_5_0, _entry, defines); } if (!_has_shader_cachae || !fs::exists(fs::status(output_path_ps))) { compile_shader(compiler, path, output_path_ps, ps_5_0, _entry, defines); } return ShaderInstanceLoader::load(output_path_vs, output_path_gs, output_path_ps); } } auto ShaderVersion::set_option(uint8 block, uint8 option, bool enable) noexcept -> void { assert(block < 32u); uint8 local_option = _shader._blocks[block].option_offset + option; _options.set(local_option, enable); } }
28.878788
95
0.684995
Yousazoe
6fb57f0384bd58536feaec3aec330c5773f1e535
1,738
cpp
C++
engine/graphics/src/graphics_glfw_wrappers.cpp
hapass/defold
fd3602f27a2596a2ad62bf9a70ae9d7acda24ad8
[ "Apache-2.0" ]
1
2020-05-19T15:47:07.000Z
2020-05-19T15:47:07.000Z
engine/graphics/src/graphics_glfw_wrappers.cpp
CagdasErturk/defold
28e5eb635042d37e17cda4d33e47fce2b569cab8
[ "Apache-2.0" ]
null
null
null
engine/graphics/src/graphics_glfw_wrappers.cpp
CagdasErturk/defold
28e5eb635042d37e17cda4d33e47fce2b569cab8
[ "Apache-2.0" ]
null
null
null
// Copyright 2020 The Defold Foundation // Licensed under the Defold License version 1.0 (the "License"); you may not use // this file except in compliance with the License. // // You may obtain a copy of the License, together with FAQs at // https://www.defold.com/license // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. #include <graphics/glfw/glfw.h> #include <graphics/glfw/glfw_native.h> #include "graphics_native.h" namespace dmGraphics { #define WRAP_GLFW_NATIVE_HANDLE_CALL(return_type, func_name) return_type GetNative##func_name() { return glfwGet##func_name(); } WRAP_GLFW_NATIVE_HANDLE_CALL(id, iOSUIWindow); WRAP_GLFW_NATIVE_HANDLE_CALL(id, iOSUIView); WRAP_GLFW_NATIVE_HANDLE_CALL(id, iOSEAGLContext); WRAP_GLFW_NATIVE_HANDLE_CALL(id, OSXNSWindow); WRAP_GLFW_NATIVE_HANDLE_CALL(id, OSXNSView); WRAP_GLFW_NATIVE_HANDLE_CALL(id, OSXNSOpenGLContext); WRAP_GLFW_NATIVE_HANDLE_CALL(HWND, WindowsHWND); WRAP_GLFW_NATIVE_HANDLE_CALL(HGLRC, WindowsHGLRC); WRAP_GLFW_NATIVE_HANDLE_CALL(EGLContext, AndroidEGLContext); WRAP_GLFW_NATIVE_HANDLE_CALL(EGLSurface, AndroidEGLSurface); WRAP_GLFW_NATIVE_HANDLE_CALL(JavaVM*, AndroidJavaVM); WRAP_GLFW_NATIVE_HANDLE_CALL(jobject, AndroidActivity); WRAP_GLFW_NATIVE_HANDLE_CALL(android_app*, AndroidApp); WRAP_GLFW_NATIVE_HANDLE_CALL(Window, X11Window); WRAP_GLFW_NATIVE_HANDLE_CALL(GLXContext, X11GLXContext); #undef WRAP_GLFW_NATIVE_HANDLE_CALL }
44.564103
129
0.794016
hapass
6fb976ab82764e96e51eca155329457c4d7d3694
2,449
cpp
C++
src/edit-row/treeview_enable_edit_next_field.cpp
rasmusbonnedal/gtk-snippets
54bd00e295c5701002bd5c9b42383d584120def0
[ "MIT" ]
1
2019-11-25T03:11:45.000Z
2019-11-25T03:11:45.000Z
src/edit-row/treeview_enable_edit_next_field.cpp
rasmusbonnedal/gtk-snippets
54bd00e295c5701002bd5c9b42383d584120def0
[ "MIT" ]
null
null
null
src/edit-row/treeview_enable_edit_next_field.cpp
rasmusbonnedal/gtk-snippets
54bd00e295c5701002bd5c9b42383d584120def0
[ "MIT" ]
1
2020-06-19T18:32:04.000Z
2020-06-19T18:32:04.000Z
// // Copyright (C) 2019 Rasmus Bonnedal // #include "treeview_enable_edit_next_field.h" namespace { void setCursorNextFieldHandler(const Glib::ustring& path_string, const Glib::ustring& new_text, Gtk::TreeViewColumn* column, Gtk::TreeViewColumn* colNext, bool nextRow) { Gtk::TreeView* treeView = column->get_tree_view(); Gtk::TreePath currpath(path_string); Gtk::TreePath nextpath(currpath); if (nextRow) { nextpath.next(); Glib::RefPtr<Gtk::ListStore> model = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(treeView->get_model()); // If path.next() is not a valid row, append new row for editing if (!model->get_iter(nextpath)) { model->append(); } } // Hack to work around problem setting cursor // See: // https://github.com/bbuhler/HostsManager/commit/bfa95e32dce484b79d4dc023cb48f3249dc3ff7a // https://gitlab.com/inkscape/inkscape/merge_requests/801/diffs?commit_id=40b6f70127755d2b44597e56f5bd965083eda3f2 Glib::signal_timeout().connect_once( [treeView, currpath, column, nextpath, colNext]() { Gtk::TreePath focusPath; Gtk::TreeViewColumn* focusColumn; treeView->get_cursor(focusPath, focusColumn); if (focusPath == currpath && focusColumn == column) { treeView->set_cursor(nextpath, *colNext, true); } }, 1); } void setCursorNextField(Gtk::TreeViewColumn* column, Gtk::TreeViewColumn* colNext, bool nextRow) { Gtk::CellRendererText* crt = dynamic_cast<Gtk::CellRendererText*>(column->get_first_cell()); g_return_if_fail(crt != nullptr); crt->signal_edited().connect( sigc::bind(&setCursorNextFieldHandler, column, colNext, nextRow)); } } // namespace void enableEditNextField(const std::vector<Gtk::TreeViewColumn*>& columns) { size_t nColumn = columns.size(); g_return_if_fail(nColumn >= 2); Gtk::TreeView* treeView = columns[0]->get_tree_view(); Glib::RefPtr<Gtk::ListStore> model = Glib::RefPtr<Gtk::ListStore>::cast_dynamic(treeView->get_model()); g_return_if_fail(model); for (size_t i = 0; i < nColumn - 1; ++i) { setCursorNextField(columns[i], columns[i + 1], false); } setCursorNextField(columns[nColumn - 1], columns[0], true); }
38.265625
119
0.633728
rasmusbonnedal
6fc1200e6c8493970730ac8160e71cfede239788
1,592
cpp
C++
sem_2/course_algorithms/contest_5/B.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_algorithms/contest_5/B.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
sem_2/course_algorithms/contest_5/B.cpp
KingCakeTheFruity/mipt
e32cfe5e53236cdd2933d8b666ca995508300f0f
[ "MIT" ]
null
null
null
/* Пишем Крускалу, делая вид, что что-то может быть приятнее dsu */ #include <cstdio> #include <cstdlib> #include <vector> #include <algorithm> #include <set> using std::vector; using std::reverse; using std::find; using std::set; using std::min; vector<long long> dsu; vector<long long> dsu_size; struct Pair { long long x; long long y; long long w; Pair() {} Pair(long long a, long long b, long long c): x(a), y(b), w(c) {} }; bool operator<(const Pair &a, const Pair &b) { if (a.w < b.w) { return true; } else if (a.w > b.w) { return false; } else { return a.y < b.y && a.x < b.x; } } void dsu_init(int n) { dsu.resize(n); dsu_size.resize(n); for (int i = 0; i < n; ++i) { dsu[i] = i; dsu_size[i] = 1; } } long long dsu_get(long long v) { if (dsu[v] == v) { return v; } else { return dsu[v] = dsu_get(dsu[v]); } } void dsu_unite(long long first, long long second) { first = dsu_get(first); second = dsu_get(second); if (dsu_size[first] > dsu_size[second]) { dsu[second] = first; dsu_size[first] += dsu_size[second]; } else { dsu[first] = second; dsu_size[second] += dsu_size[first]; } } int main() { long long n, m; scanf("%lld %lld", &n, &m); dsu_init(n); vector<Pair> g; for (long long i = 0; i < m; ++i) { long long a, b, x; scanf("%lld %lld %lld", &a, &b, &x); --a; --b; g.push_back({a, b, x}); } sort(g.begin(), g.end()); long long ans = 0; for (auto e : g) { if (dsu_get(e.x) != dsu_get(e.y)) { dsu_unite(e.x, e.y); ans += e.w; } } printf("%lld\n", ans); return 0; }
15.607843
61
0.568467
KingCakeTheFruity
6fc5a3f2f96a6118da72cb714d115c6548375138
3,929
hpp
C++
snmp_fetch/api/types.hpp
higherorderfunctor/snmp-fetch
c95e9f60d38901c500456dc6f07af343b36b4938
[ "CC0-1.0" ]
null
null
null
snmp_fetch/api/types.hpp
higherorderfunctor/snmp-fetch
c95e9f60d38901c500456dc6f07af343b36b4938
[ "CC0-1.0" ]
32
2019-09-19T05:25:07.000Z
2019-12-05T20:28:17.000Z
snmp_fetch/api/types.hpp
higherorderfunctor/snmp-fetch
c95e9f60d38901c500456dc6f07af343b36b4938
[ "CC0-1.0" ]
null
null
null
/** * type.hpp - Common type definitions. */ #ifndef SNMP_FETCH__TYPES_H #define SNMP_FETCH__TYPES_H #include <iostream> #include <boost/format.hpp> extern "C" { #include <net-snmp/net-snmp-config.h> #include <net-snmp/net-snmp-includes.h> } #include "utils.hpp" namespace snmp_fetch { // default values #define SNMP_FETCH__DEFAULT_RETRIES 3 #define SNMP_FETCH__DEFAULT_TIMEOUT 3 #define SNMP_FETCH__DEFAULT_MAX_ACTIVE_SESSIONS 10 #define SNMP_FETCH__DEFAULT_MAX_VAR_BINDS_PER_PDU 10 #define SNMP_FETCH__DEFAULT_MAX_BULK_REPETITIONS 10 // type aliases using host_t = std::tuple<uint64_t, std::string, std::string>; using oid_t = std::vector<uint64_t>; using oid_size_t = uint64_t; using value_size_t = uint64_t; using var_bind_size_t = std::tuple<oid_size_t, value_size_t>; using var_bind_t = std::tuple<oid_t, var_bind_size_t>; /** * async_status_t - Different statuses of an async session. */ enum async_status_t { ASYNC_IDLE = 0, ASYNC_WAITING, ASYNC_RETRY }; /** * PDU_TYPE - Constants exposed to python. */ enum PDU_TYPE { GET = SNMP_MSG_GET, NEXT= SNMP_MSG_GETNEXT, BULKGET = SNMP_MSG_GETBULK, }; /** * SnmpConfig - Pure C++ config type exposed through the to python module. */ struct SnmpConfig { ssize_t retries; ssize_t timeout; size_t max_active_sessions; size_t max_var_binds_per_pdu; size_t max_bulk_repetitions; /** * SnmpConfig - Constructor with default values. */ SnmpConfig( ssize_t retries = SNMP_FETCH__DEFAULT_RETRIES, ssize_t timeout = SNMP_FETCH__DEFAULT_TIMEOUT, size_t max_active_sessions = SNMP_FETCH__DEFAULT_MAX_ACTIVE_SESSIONS, size_t max_var_binds_per_pdu = SNMP_FETCH__DEFAULT_MAX_VAR_BINDS_PER_PDU, size_t max_bulk_repetitions = SNMP_FETCH__DEFAULT_MAX_BULK_REPETITIONS ); /** * SnmpConfig::operator== */ bool operator==(const SnmpConfig &a); /** * to_string - String method used for __str__ and __repr__ which mimics attrs. * * @return String representation of a SnmpConfig. */ std::string to_string(); }; /** * ERROR_TYPE - Constants exposed to python for identifying where an error happened. */ enum SNMP_ERROR_TYPE { SESSION_ERROR = 0, CREATE_REQUEST_PDU_ERROR, SEND_ERROR, BAD_RESPONSE_PDU_ERROR, TIMEOUT_ERROR, ASYNC_PROBE_ERROR, TRANSPORT_DISCONNECT_ERROR, CREATE_RESPONSE_PDU_ERROR, VALUE_WARNING }; /** * SnmpError - Pure C++ container for various error types exposed to python. */ struct SnmpError { SNMP_ERROR_TYPE type; host_t host; std::optional<int64_t> sys_errno; std::optional<int64_t> snmp_errno; std::optional<int64_t> err_stat; std::optional<int64_t> err_index; std::optional<oid_t> err_oid; std::optional<std::string> message; /** * SnmpError - Constructor method with default values. */ SnmpError( SNMP_ERROR_TYPE type, host_t host, std::optional<int64_t> sys_errno = {}, std::optional<int64_t> snmp_errno = {}, std::optional<int64_t> err_stat = {}, std::optional<int64_t> err_index = {}, std::optional<oid_t> err_oid = {}, std::optional<std::string> message = {} ); /** * SnmpError::operator== */ bool operator==(const SnmpError &a); /** * to_string - String method used for __str__ and __repr__ which mimics attrs. * * @return String representation of an SnmpError. */ std::string to_string(); }; /** * async_state - State wrapper for net-snmp sessions. * * Host should be left as copy as the underlying pending host list destroys the elements that * were used to build this structure. */ struct async_state { async_status_t async_status; void *session; int pdu_type; host_t host; std::vector<var_bind_t> *var_binds; std::vector<std::vector<oid_t>> next_var_binds; std::vector<std::vector<uint8_t>> *results; std::vector<SnmpError> *errors; SnmpConfig *config; }; } #endif
22.58046
94
0.71494
higherorderfunctor
6fc610be415c6d6c19d1b53b773bdf0b10c1ac3c
2,513
cpp
C++
Test/Math/Test_MathCore.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
1
2018-01-29T02:49:05.000Z
2018-01-29T02:49:05.000Z
Test/Math/Test_MathCore.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
26
2017-05-08T22:57:14.000Z
2018-05-15T20:55:26.000Z
Test/Math/Test_MathCore.cpp
XenonicDev/Red
fcd12416bdf7fe4d2372161e67edc585f75887e4
[ "MIT" ]
null
null
null
/* Copyright (c) 2017-2018 Andrew Depke */ #include "gtest/gtest.h" #include "../../Red/Math/MathCore.h" using namespace Red; TEST(MathCoreSuite, AbsGeneralInt) { EXPECT_EQ(3, Abs(3)); EXPECT_EQ(3, Abs(-3)); EXPECT_EQ(0, Abs(0)); } TEST(MathCoreSuite, AbsGeneralFloat) { EXPECT_FLOAT_EQ(3.0f, Abs(3.0f)); EXPECT_FLOAT_EQ(3.0f, Abs(-3.0f)); EXPECT_FLOAT_EQ(0.0f, Abs(0.0f)); } TEST(MathCoreSuite, AbsGeneralDouble) { EXPECT_EQ(3.0, Abs(3.0)); EXPECT_EQ(3.0, Abs(-3.0)); EXPECT_EQ(0.0, Abs(0.0)); } TEST(MathCoreSuite, AbsGeneralLongDouble) { EXPECT_EQ((long double)3.0, Abs((long double)3.0)); EXPECT_EQ((long double)3.0, Abs((long double)-3.0)); EXPECT_EQ((long double)0.0, Abs((long double)0.0)); } TEST(MathCoreSuite, MinGeneral) { EXPECT_EQ(3, Min(3, 3)); EXPECT_EQ(-3, Min(-3, -3)); EXPECT_EQ(-3, Min(3, -3)); EXPECT_EQ(-3, Min(-3, 3)); EXPECT_EQ(0, Min(0, 0)); } TEST(MathCoreSuite, MaxGeneral) { EXPECT_EQ(3, Max(3, 3)); EXPECT_EQ(-3, Max(-3, -3)); EXPECT_EQ(3, Max(3, -3)); EXPECT_EQ(3, Max(-3, 3)); EXPECT_EQ(0, Max(0, 0)); } TEST(MathCoreSuite, PowerGeneral) { EXPECT_EQ(64.0f, Power(4.0f, 3.0f)); EXPECT_NEAR(104.47f, Power(7.23f, 2.35f), 0.01f); EXPECT_NEAR(80890.20, Power(26.21, 3.46), 0.01); EXPECT_NEAR((long double)340439729893056.21, Power((long double)53.45, (long double)8.41), 0.4); } TEST(MathCoreSuite, PowerSpecialCases) { EXPECT_FLOAT_EQ(1.0f, Power(1.0f, 0.0f)); EXPECT_FLOAT_EQ(0.0f, Power(0.0f, 1.0f)); EXPECT_FLOAT_EQ(1.0f, Power(0.0f, 0.0f)); } TEST(MathCoreSuite, SquareRootGeneral) { EXPECT_EQ(0.0f, SquareRoot(0.0f)); EXPECT_FLOAT_EQ(3.0f, SquareRoot(9.0f)); EXPECT_NEAR(2.28, SquareRoot(5.20), 0.01); EXPECT_NEAR((long double)773.11, SquareRoot((long double)597695.0), 0.01); } TEST(MathCoreSuite, SquareRootNegative) { EXPECT_NO_THROW(SquareRoot(-1.0f)); EXPECT_NO_THROW(SquareRoot(-0.01f)); } TEST(MathCoreSuite, ModulusGeneral) { EXPECT_EQ(-5, Modulus(-5, 9)); EXPECT_FLOAT_EQ(1.8f, Modulus(9.0f, 2.4f)); EXPECT_NEAR(0.1, Modulus(5.20, 1.02), 0.01); EXPECT_NEAR((long double)170.84, Modulus((long double)597695.0, (long double)214.32), 0.01); } TEST(MathCoreSuite, ModulusSpecialCases) { EXPECT_NO_THROW(Modulus(1, 0)); EXPECT_EQ(0, Modulus(0, 1)); EXPECT_NO_THROW(Modulus(0, 0)); } TEST(MathCoreSuite, FactorialGeneral) { EXPECT_EQ(1, Factorial(0)); EXPECT_EQ(1, Factorial(1)); EXPECT_EQ(24, Factorial(4)); EXPECT_EQ(479001600, Factorial(12)); //EXPECT_EQ(243902008176640000, Factorial(20)); // Overflow Issues }
23.485981
97
0.68842
XenonicDev
6fc6e4cfb9f36f5eb8fa56104d1872f9014380dd
8,655
cpp
C++
src/server/safs/filtersafs.cpp
jvirkki/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
13
2015-10-09T05:59:20.000Z
2021-11-12T10:38:51.000Z
src/server/safs/filtersafs.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
null
null
null
src/server/safs/filtersafs.cpp
JamesLinus/heliod
efdf2d105e342317bd092bab2d727713da546174
[ "BSD-3-Clause" ]
6
2016-05-23T10:53:29.000Z
2019-12-13T17:57:32.000Z
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER. * * Copyright 2008 Sun Microsystems, Inc. All rights reserved. * * THE BSD LICENSE * * 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 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. */ /* * filtersafs.cpp: SAFs related to NSAPI filters * * Chris Elving */ #include "base/util.h" #include "base/vs.h" #include "frame/log.h" #include "frame/object.h" #include "frame/filter.h" #include "safs/dbtsafs.h" #include "safs/filtersafs.h" // Names of the SAFs as they should appear in log messages #define INSERT_FILTER "insert-filter" #define REMOVE_FILTER "remove-filter" #define INIT_FILTER_ORDER "init-filter-order" /* ------------------------ filter_init_directive ------------------------- */ static int filter_init_directive(const directive *dir, VirtualServer *incoming, const VirtualServer *current) { // Cache a const Filter * in the pblock if possible const char *name = pblock_findkeyval(pb_key_filter, dir->param.pb); if (name) { const Filter *filter = filter_find(name); if (filter) pblock_kvinsert(pb_key_magnus_internal, (const char *)&filter, sizeof(filter), dir->param.pb); } return REQ_PROCEED; } /* ----------------------------- find_filter ------------------------------ */ static inline const Filter *find_filter(pblock *pb, Session *sn, Request *rq) { const Filter *filter; // Look for a cached const Filter * const Filter **pfilter = (const Filter **)pblock_findkeyval(pb_key_magnus_internal, pb); if (pfilter) { filter = *pfilter; PR_ASSERT(filter != NULL); return filter; } // No cached const Filter *, find the filter name const char *name = pblock_findkeyval(pb_key_filter, pb); if (!name) { log_error(LOG_MISCONFIG, pblock_findkeyval(pb_key_fn, pb), sn, rq, XP_GetAdminStr(DBT_NeedFilter)); return NULL; } // Find the const Filter * with the specified name (this is slow) filter = filter_find(name); if (!filter) { log_error(LOG_MISCONFIG, pblock_findkeyval(pb_key_fn, pb), sn, rq, XP_GetAdminStr(DBT_CantFindFilterX), name); return NULL; } return filter; } /* ---------------------------- insert_filter ----------------------------- */ int insert_filter(pblock *pb, Session *sn, Request *rq) { const Filter *filter = find_filter(pb, sn, rq); if (!filter) return REQ_ABORTED; int rv = filter_insert(sn->csd, pb, sn, rq, NULL, filter); if (rv == REQ_PROCEED) { ereport(LOG_VERBOSE, "inserted filter %s", filter_name(filter)); } else if (rv == REQ_NOACTION) { ereport(LOG_VERBOSE, "did not insert filter %s", filter_name(filter)); } else { log_error(LOG_WARN, INSERT_FILTER, sn, rq, XP_GetAdminStr(DBT_ErrorInsertingFilterX), filter_name(filter)); } return rv; } /* ---------------------------- remove_filter ----------------------------- */ int remove_filter(pblock *pb, Session *sn, Request *rq) { const Filter *filter = find_filter(pb, sn, rq); if (!filter) return REQ_ABORTED; int rv = REQ_NOACTION; if (sn->csd && sn->csd_open == 1) rv = filter_remove(sn->csd, filter); return rv; } /* ------------------------ validate_filter_order ------------------------- */ static void validate_filter_order(const Filter *filter, int order) { if (FILTER_ORDER_CLASS(filter->order) != FILTER_ORDER_CLASS(order)) { log_error(LOG_WARN, INIT_FILTER_ORDER, NULL, NULL, XP_GetAdminStr(DBT_InvalidOrderForX), filter->name); } } /* -------------------------- init_filter_order --------------------------- */ int init_filter_order(pblock *pb, Session *sn, Request *rq) { // Get the list of filters to define the filter order for char *filters = pblock_findval("filters", pb); if (!filters) { pblock_nvinsert("error", XP_GetAdminStr(DBT_NeedFilters), pb); return REQ_ABORTED; } // Parse the list of filters int order = FILTER_TOPMOST; char *lasts; char *name = util_strtok(filters, ", \t", &lasts); while (name) { Filter *filter; if (*name == '(') { // Handle filter group. The relative order of filters within the // '('- and ')'-delimited filter group doesn't matter. // Skip past the opening '(' name++; // Handle all the filters in the group int group_order = order; while (name) { if (*name) { // Remove any closing ')' from the filter name char *paren = NULL; if (name[strlen(name) - 1] == ')') { paren = &name[strlen(name) - 1]; *paren = '\0'; } // Handle a filter within the group filter = (Filter *)filter_find(name); if (filter) { if (filter->order >= order) { validate_filter_order(filter, order - 1); filter->order = order - 1; } if (filter->order < group_order) group_order = filter->order; } else { log_error(LOG_MISCONFIG, INIT_FILTER_ORDER, sn, rq, XP_GetAdminStr(DBT_CannotOrderNonexistentFilterX), name); } // Check for end of filter group if (paren) { *paren = ')'; break; } } name = util_strtok(NULL, ", \t", &lasts); } if (!name) { log_error(LOG_MISCONFIG, INIT_FILTER_ORDER, sn, rq, XP_GetAdminStr(DBT_FiltersMissingClosingParen)); } order = group_order; } else { // Handle individual filter filter = (Filter *)filter_find(name); if (filter) { if (filter->order >= order) { validate_filter_order(filter, order - 1); filter->order = order - 1; } if (filter->order < order) order = filter->order; } else { log_error(LOG_MISCONFIG, INIT_FILTER_ORDER, sn, rq, XP_GetAdminStr(DBT_CannotOrderNonexistentFilterX), name); } } // Next filter name = util_strtok(NULL, ", \t", &lasts); } return REQ_PROCEED; } /* --------------------------- filtersafs_init ---------------------------- */ PRStatus filtersafs_init(void) { // Call filter_init_vs_directive() to cache the const Filter * for each // insert-filter and remove-filter directive vs_directive_register_cb(insert_filter, filter_init_directive, 0); vs_directive_register_cb(remove_filter, filter_init_directive, 0); return PR_SUCCESS; }
33.677043
109
0.570422
jvirkki
6fd4f9df67eaaae02c4bad0b328741e36348eb7c
291
cpp
C++
src/agent.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
null
null
null
src/agent.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
8
2018-11-13T14:33:26.000Z
2018-11-23T18:01:38.000Z
src/agent.cpp
kaidokert/MosquitoBorneDisease
b3584f12a9c3be2907360152c04032b213f19cd1
[ "BSD-3-Clause" ]
2
2019-08-05T07:21:28.000Z
2019-08-23T06:24:23.000Z
/* # Sub-module containing agent functions # # This file is part of SMosMod. # Copyright (c) 2017-2018, Imperial College London # For licensing information, see the LICENSE file distributed with the SMosMod # software package. */ #include "agent.hpp" Agent::Agent(double a) : age(a) {}
22.384615
79
0.725086
kaidokert
6fd6ece4a9cbb2847937978c423e9211904afbd8
2,976
hpp
C++
apps/openmw/mwgui/inventorywindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/inventorywindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
apps/openmw/mwgui/inventorywindow.hpp
Bodillium/openmw
5fdd264d0704e33b44b1ccf17ab4fb721f362e34
[ "Unlicense" ]
null
null
null
#ifndef MGUI_Inventory_H #define MGUI_Inventory_H #include "../mwrender/characterpreview.hpp" #include "windowpinnablebase.hpp" #include "widgets.hpp" #include "mode.hpp" namespace MWGui { class ItemView; class SortFilterItemModel; class TradeItemModel; class DragAndDrop; class ItemModel; class InventoryWindow : public WindowPinnableBase { public: InventoryWindow(DragAndDrop* dragAndDrop); virtual void open(); void doRenderUpdate(); /// start trading, disables item drag&drop void setTrading(bool trading); void onFrame(); void pickUpObject (MWWorld::Ptr object); MWWorld::Ptr getAvatarSelectedItem(int x, int y); void rebuildAvatar() { mPreview->rebuild(); } SortFilterItemModel* getSortFilterModel(); TradeItemModel* getTradeModel(); ItemModel* getModel(); void updateItemView(); void updatePlayer(); void useItem(const MWWorld::Ptr& ptr); void setGuiMode(GuiMode mode); private: DragAndDrop* mDragAndDrop; bool mPreviewDirty; bool mPreviewResize; int mSelectedItem; MWWorld::Ptr mPtr; MWGui::ItemView* mItemView; SortFilterItemModel* mSortModel; TradeItemModel* mTradeModel; MyGUI::Widget* mAvatar; MyGUI::ImageBox* mAvatarImage; MyGUI::TextBox* mArmorRating; Widgets::MWDynamicStat* mEncumbranceBar; MyGUI::Widget* mLeftPane; MyGUI::Widget* mRightPane; MyGUI::Button* mFilterAll; MyGUI::Button* mFilterWeapon; MyGUI::Button* mFilterApparel; MyGUI::Button* mFilterMagic; MyGUI::Button* mFilterMisc; MWWorld::Ptr mSkippedToEquip; GuiMode mGuiMode; int mLastXSize; int mLastYSize; std::auto_ptr<MWRender::InventoryPreview> mPreview; bool mTrading; void onItemSelected(int index); void onItemSelectedFromSourceModel(int index); void onBackgroundSelected(); void sellItem(MyGUI::Widget* sender, int count); void dragItem(MyGUI::Widget* sender, int count); void onWindowResize(MyGUI::Window* _sender); void onFilterChanged(MyGUI::Widget* _sender); void onAvatarClicked(MyGUI::Widget* _sender); void onPinToggled(); void onTitleDoubleClicked(); void updateEncumbranceBar(); void notifyContentChanged(); void adjustPanes(); /// Unequips mSelectedItem, if it is equipped, and then updates mSelectedItem in case it was re-stacked void ensureSelectedItemUnequipped(); }; } #endif // Inventory_H
25.878261
115
0.589718
Bodillium
6fdc5403627b016de97575f7b628f60fa2c16412
1,486
cpp
C++
src/ImageWriter.cpp
iaddis/milkdrop2020
9354242ccf17909be7e9ab2f140d8508030bc3b1
[ "MIT" ]
13
2021-03-07T01:57:37.000Z
2022-03-08T05:45:06.000Z
src/ImageWriter.cpp
iaddis/milkdrop2020
9354242ccf17909be7e9ab2f140d8508030bc3b1
[ "MIT" ]
1
2021-02-13T20:16:06.000Z
2021-03-22T18:42:58.000Z
src/ImageWriter.cpp
iaddis/milkdrop2020
9354242ccf17909be7e9ab2f140d8508030bc3b1
[ "MIT" ]
4
2021-03-27T03:23:31.000Z
2022-01-24T00:38:07.000Z
//#define STB_IMAGE_WRITE_STATIC #define STB_IMAGE_WRITE_IMPLEMENTATION #include "../external/stb/stb_image_write.h" #include "ImageWriter.h" #include <string> #include "path.h" bool ImageWriteToPNG(const std::string &path, const uint32_t *data, int width, int height) { int pitch = width * sizeof(data[0]); // stbi_write_force_png_filter = 0; // stbi_write_png_compression_level = 1; return stbi_write_png( path.c_str(), width, height, 4, data, pitch ) != 0; } bool ImageWriteToBMP(const std::string &path, const uint32_t *data, int width, int height) { // int pitch = width * sizeof(data[0]); return stbi_write_bmp( path.c_str(), width, height, 4, data ) != 0; } bool ImageWriteToTGA(const std::string &path, const uint32_t *data, int width, int height) { return stbi_write_tga( path.c_str(), width, height, 4, data ) != 0; } bool ImageWriteToHDR(const std::string &path, const float *data, int width, int height) { return stbi_write_hdr( path.c_str(), width, height, 4, data ) != 0; } bool ImageWriteToFile(const std::string &path, const uint32_t *data, int width, int height) { std::string ext = PathGetExtensionLower(path); if (ext == ".tga") { return ImageWriteToTGA(path, data, width, height); } if (ext == ".png") { return ImageWriteToPNG(path, data, width, height); } if (ext == ".bmp") { return ImageWriteToBMP(path, data, width, height); } return false; }
24.766667
91
0.662853
iaddis
6fe23e0207021da283b5b2934bcc1f0f5b52de59
988
cpp
C++
src/vnx_keyvalue_server.cpp
madMAx43v3r/vnx-keyvalue
dbb28a2494c12741ba6ce14c579bc5973981d5ac
[ "MIT" ]
1
2021-09-11T04:07:29.000Z
2021-09-11T04:07:29.000Z
src/vnx_keyvalue_server.cpp
vashil211/vnx-keyvalue
dbb28a2494c12741ba6ce14c579bc5973981d5ac
[ "MIT" ]
1
2021-06-13T16:13:54.000Z
2021-06-13T16:13:54.000Z
src/vnx_keyvalue_server.cpp
madMAx43v3r/vnx-keyvalue
dbb28a2494c12741ba6ce14c579bc5973981d5ac
[ "MIT" ]
2
2021-06-10T18:10:03.000Z
2021-06-12T05:46:00.000Z
/* * vnx_keyvalue_server.cpp * * Created on: Mar 22, 2020 * Author: mad */ #include <vnx/keyvalue/Server.h> #include <vnx/vnx.h> #include <vnx/Terminal.h> #include <vnx/Server.h> int main(int argc, char** argv) { std::map<std::string, std::string> options; options["s"] = "server"; options["server"] = "server name"; options["n"] = "name"; options["name"] = "collection name"; vnx::init("vnx_keyvalue_server", argc, argv, options); std::string server_name = "StorageServer"; vnx::read_config("server", server_name); { vnx::Handle<vnx::Terminal> terminal = new vnx::Terminal("Terminal"); terminal.start_detached(); } { vnx::Handle<vnx::Server> server = new vnx::Server("Server", vnx::Endpoint::from_url(".vnx_keyvalue_server.sock")); server.start_detached(); } { vnx::Handle<vnx::keyvalue::Server> module = new vnx::keyvalue::Server(server_name); vnx::read_config("name", module->collection); module.start_detached(); } vnx::wait(); }
21.478261
116
0.663968
madMAx43v3r
6fe36be835bebb48bbae0b9c8e24bf76d2cdca23
1,177
cpp
C++
9.File Handling/i-Design/2/User.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
26
2021-03-17T03:15:22.000Z
2021-06-09T13:29:41.000Z
9.File Handling/i-Design/2/User.cpp
Servatom/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
6
2021-03-16T19:04:05.000Z
2021-06-03T13:41:04.000Z
9.File Handling/i-Design/2/User.cpp
Concept-Team/e-box-UTA018
a6caf487c9f27a5ca30a00847ed49a163049f67e
[ "MIT" ]
42
2021-03-17T03:16:22.000Z
2021-06-14T21:11:20.000Z
#include<iostream> #include<string> #include<stdio.h> #include<fstream> #include<list> #include<iterator> #include<sstream> using namespace std; class User{ private: string name; string username; string password; string contactnumber; public: User(){} User(string name, string username, string password, string contactnumber){ this->name = name; this->username = username; this->password = password; this->contactnumber = contactnumber; } void setName(string name){ this->name = name; } void setUsername(string uname){ this->username = uname; } void setPassword(string pass){ this->password = pass; } void setContactNumber(string connum){ this->contactnumber = connum; } string getName(){ return name; } string getUsername(){ return username; } string getPassword(){ return password; } string getContactNumber(){ return contactnumber; } };
24.520833
82
0.540357
Concept-Team
6fe38eaf77b861677540d0680f3905e2307a1ef7
801
cpp
C++
src/index/ranker/ranker_factory.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
null
null
null
src/index/ranker/ranker_factory.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
null
null
null
src/index/ranker/ranker_factory.cpp
saq7/MeTA
0392964c1cdc073ae5123f7d64affdc4105acc4f
[ "MIT" ]
1
2021-09-06T06:08:38.000Z
2021-09-06T06:08:38.000Z
/** * @file ranker_factory.cpp * @author Chase Geigle */ #include "cpptoml.h" #include "index/ranker/all.h" #include "index/ranker/ranker_factory.h" namespace meta { namespace index { template <class Ranker> void ranker_factory::reg() { add(Ranker::id, make_ranker<Ranker>); } ranker_factory::ranker_factory() { // built-in rankers reg<absolute_discount>(); reg<dirichlet_prior>(); reg<jelinek_mercer>(); reg<okapi_bm25>(); reg<pivoted_length>(); } std::unique_ptr<ranker> make_ranker(const cpptoml::table& config) { auto function = config.get_as<std::string>("method"); if (!function) throw ranker_factory::exception{ "ranking-function required to construct a ranker"}; return ranker_factory::get().create(*function, config); } } }
19.536585
65
0.679151
saq7
6fe831bce94053dac21d5d4c5d9aaa44fd35b756
278
cpp
C++
Programmers/MidWord.cpp
YEAjiJUNG/AlgorithmPractice
720abd9bb3bf1eeadf57402379fdf30921f7c333
[ "Apache-2.0" ]
1
2021-05-21T02:23:38.000Z
2021-05-21T02:23:38.000Z
Programmers/MidWord.cpp
YEAjiJUNG/AlgorithmPractice
720abd9bb3bf1eeadf57402379fdf30921f7c333
[ "Apache-2.0" ]
null
null
null
Programmers/MidWord.cpp
YEAjiJUNG/AlgorithmPractice
720abd9bb3bf1eeadf57402379fdf30921f7c333
[ "Apache-2.0" ]
null
null
null
#include <string> #include <vector> using namespace std; string solution(string s) { string answer = ""; if(s.size() % 2 == 0){ answer += s[s.size()/2 -1]; answer += s[s.size()/2]; } else{ answer = s[s.size()/2]; } return answer; }
16.352941
35
0.507194
YEAjiJUNG
6fec4faf907996fac4d71b4ecf1a61147969ef04
4,863
cpp
C++
osal/mpp_platform.cpp
Fruit-Pi/mpp
dd7097fbab86eeed807e177620212847a9bc8f70
[ "Apache-2.0" ]
312
2016-12-26T12:32:03.000Z
2022-03-29T13:37:59.000Z
osal/mpp_platform.cpp
Fruit-Pi/mpp
dd7097fbab86eeed807e177620212847a9bc8f70
[ "Apache-2.0" ]
271
2017-01-12T03:59:31.000Z
2022-03-31T02:26:45.000Z
osal/mpp_platform.cpp
Fruit-Pi/mpp
dd7097fbab86eeed807e177620212847a9bc8f70
[ "Apache-2.0" ]
195
2016-12-01T07:22:01.000Z
2022-03-30T23:09:00.000Z
/* * Copyright 2015 Rockchip Electronics Co. LTD * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define MODULE_TAG "mpp_platform" #include <string.h> #include "mpp_env.h" #include "mpp_log.h" #include "mpp_common.h" #include "mpp_platform.h" #include "mpp_service.h" static MppKernelVersion check_kernel_version(void) { static const char *kernel_version_path = "/proc/version"; MppKernelVersion version = KERNEL_UNKNOWN; FILE *fp = NULL; char buf[32]; if (access(kernel_version_path, F_OK | R_OK)) return version; fp = fopen(kernel_version_path, "rb"); if (fp) { size_t len = fread(buf, 1, sizeof(buf) - 1, fp); char *pos = NULL; buf[len] = '\0'; pos = strstr(buf, "Linux version "); if (pos) { RK_S32 major = 0; RK_S32 minor = 0; RK_S32 last = 0; RK_S32 count = 0; pos += 14; count = sscanf(pos, "%d.%d.%d ", &major, &minor, &last); if (count >= 2 && major > 0 && minor > 0) { if (major == 3) version = KERNEL_3_10; else if (major == 4) { version = KERNEL_4_4; if (minor >= 19) version = KERNEL_4_19; } } } fclose(fp); } return version; } class MppPlatformService { private: // avoid any unwanted function MppPlatformService(); ~MppPlatformService() {}; MppPlatformService(const MppPlatformService &); MppPlatformService &operator=(const MppPlatformService &); MppIoctlVersion ioctl_version; MppKernelVersion kernel_version; RK_U32 vcodec_type; RK_U32 hw_ids[32]; MppServiceCmdCap mpp_service_cmd_cap; const MppSocInfo *soc_info; const char *soc_name; public: static MppPlatformService *get_instance() { static MppPlatformService instance; return &instance; } MppIoctlVersion get_ioctl_version(void) { return ioctl_version; }; MppKernelVersion get_kernel_version(void) { return kernel_version; }; const char *get_soc_name() { return soc_name; }; MppServiceCmdCap *get_mpp_service_cmd_cap() { return &mpp_service_cmd_cap; }; RK_U32 get_hw_id(RK_S32 client_type); }; MppPlatformService::MppPlatformService() : ioctl_version(IOCTL_MPP_SERVICE_V1), kernel_version(KERNEL_UNKNOWN), vcodec_type(0), soc_info(NULL), soc_name(NULL) { /* judge vdpu support version */ MppServiceCmdCap *cap = &mpp_service_cmd_cap; /* default value */ cap->support_cmd = 0; cap->query_cmd = MPP_CMD_QUERY_BASE + 1; cap->init_cmd = MPP_CMD_INIT_BASE + 1; cap->send_cmd = MPP_CMD_SEND_BASE + 1; cap->poll_cmd = MPP_CMD_POLL_BASE + 1; cap->ctrl_cmd = MPP_CMD_CONTROL_BASE + 0; mpp_env_get_u32("mpp_debug", &mpp_debug, 0); /* read soc name */ soc_name = mpp_get_soc_name(); soc_info = mpp_get_soc_info(); if (soc_info->soc_type == ROCKCHIP_SOC_AUTO) mpp_log("can not found match soc name: %s\n", soc_name); ioctl_version = IOCTL_VCODEC_SERVICE; if (mpp_get_mpp_service_name()) { ioctl_version = IOCTL_MPP_SERVICE_V1; check_mpp_service_cap(&vcodec_type, hw_ids, cap); } kernel_version = check_kernel_version(); vcodec_type = soc_info->vcodec_type; } RK_U32 MppPlatformService::get_hw_id(RK_S32 client_type) { RK_U32 hw_id = 0; if (vcodec_type & (1 << client_type)) hw_id = hw_ids[client_type]; return hw_id; } MppIoctlVersion mpp_get_ioctl_version(void) { return MppPlatformService::get_instance()->get_ioctl_version(); } MppKernelVersion mpp_get_kernel_version(void) { return MppPlatformService::get_instance()->get_kernel_version(); } RK_U32 mpp_get_2d_hw_flag(void) { RK_U32 flag = 0; if (!access("/dev/rga", F_OK)) flag |= HAVE_RGA; if (!access("/dev/iep", F_OK)) flag |= HAVE_IEP; return flag; } const MppServiceCmdCap *mpp_get_mpp_service_cmd_cap(void) { return MppPlatformService::get_instance()->get_mpp_service_cmd_cap(); } RK_U32 mpp_get_client_hw_id(RK_S32 client_type) { return MppPlatformService::get_instance()->get_hw_id(client_type); }
27.788571
84
0.644047
Fruit-Pi
6ff5413513d9f236e76309c83167a7ae1242665a
1,503
hpp
C++
HW05/hw05.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
HW05/hw05.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
HW05/hw05.hpp
MetalheadKen/NTUST-Parallel-Course
4a4e726a5220eaf7403375b61cf6ce8a7cd9cbb9
[ "MIT" ]
null
null
null
#pragma once #include <cstring> #include <cmath> #include "YoUtil.hpp" struct mygpu { YoUtil::GPU *gpu; cl::CommandQueue cmdQueue; cl::Device device; cl::Context context; cl::Program *program; cl::Buffer point_buf; cl::Buffer accum_buf; }; void prepareGPU(mygpu& gpu); void releaseGPU(mygpu& gpu); struct mydata { size_t size; cl_double *point; }; bool readPointCloud(const char *filename, mydata& data, mygpu& gpu); double centerPointCloudToOrigin(mydata &data, mygpu &gpu); struct accumulator { size_t *accum; size_t n_theta; size_t n_phi; size_t n_rho; cl_double rho_max; cl_double d_theta; cl_double d_phi; cl_double d_rho; }; void prepareAccumulator(accumulator& votes, const double rho_max, const size_t n_theta, const size_t n_phi, const size_t n_rho, mygpu& gpu); void releaseAccumulator(accumulator& votes); void houghTransform(const mydata &data, accumulator &votes, mygpu& gpu); // This struct should store resultant plane parameters in descending order struct houghPlanes { size_t votes; double theta; double phi; double rho; }; void identifyPlaneParameters(const accumulator &votes, houghPlanes &planes, mygpu& gpu); void releaseHoughPlanes(houghPlanes &planes); bool outputPtxFile(const mydata& data, const houghPlanes &results, const accumulator &votes, const char *outputCloudData, mygpu &gpu); void release(mydata& data);
24.241935
141
0.698603
MetalheadKen
b5008194f9a06527ecf6fe1cf98b96de0345d8a6
2,782
cpp
C++
app/src/main/jni/jniCalls/gestureClass.cpp
smkang99/openGL
321edc6b473cfdb33ad448fdf83fabb35707858f
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/jniCalls/gestureClass.cpp
smkang99/openGL
321edc6b473cfdb33ad448fdf83fabb35707858f
[ "Apache-2.0" ]
null
null
null
app/src/main/jni/jniCalls/gestureClass.cpp
smkang99/openGL
321edc6b473cfdb33ad448fdf83fabb35707858f
[ "Apache-2.0" ]
null
null
null
// // Created by 15102 on 3/9/2020. // #include <jni.h> //#include "modelAssimp.h" #include <myJNIHelper.h> #include <modelAssimp.h> #ifdef __cplusplus extern "C" { #endif extern ModelAssimp *gAssimpObject; JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_DoubleTapNative(JNIEnv *env, jobject instance) { if (gAssimpObject == NULL) { return; } gAssimpObject->DoubleTapAction(); } /** * one finger drag - compute normalized current position and normalized displacement * from previous position */ JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_ScrollNative(JNIEnv *env, jobject instance, jfloat distanceX, jfloat distanceY, jfloat positionX, jfloat positionY) { if (gAssimpObject == NULL) { return; } // normalize movements on the screen wrt GL surface dimensions // invert dY to be consistent with GLES conventions float dX = (float) distanceX / gAssimpObject->GetScreenWidth(); float dY = -(float) distanceY / gAssimpObject->GetScreenHeight(); float posX = 2*positionX/ gAssimpObject->GetScreenWidth() - 1.; float posY = -2*positionY / gAssimpObject->GetScreenHeight() + 1.; posX = fmax(-1., fmin(1., posX)); posY = fmax(-1., fmin(1., posY)); gAssimpObject->ScrollAction(dX, dY, posX, posY); } /** * Pinch-and-zoom gesture: pass the change in scale to class' method */ JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_ScaleNative(JNIEnv *env, jobject instance, jfloat scaleFactor) { if (gAssimpObject == NULL) { return; } gAssimpObject->ScaleAction((float) scaleFactor); } /** * Two-finger drag - normalize the distance moved wrt GLES surface size */ JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_MoveNative(JNIEnv *env, jobject instance, jfloat distanceX, jfloat distanceY) { if (gAssimpObject == NULL) { return; } // normalize movements on the screen wrt GL surface dimensions // invert dY to be consistent with GLES conventions float dX = distanceX / gAssimpObject->GetScreenWidth(); float dY = -distanceY / gAssimpObject->GetScreenHeight(); gAssimpObject->MoveAction(dX, dY); } JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_turnOffLight(JNIEnv *env, jobject thiz) { gAssimpObject->TurnOffLight(); // TODO: implement turnOffLight() } JNIEXPORT void JNICALL Java_com_example_hellojni_GestureClass_turnOnLight(JNIEnv *env, jobject thiz) { gAssimpObject->TurnOnLight(); // TODO: implement turnOnLight() } #ifdef __cplusplus } #endif
28.387755
89
0.670022
smkang99
b501c34433a2e60198711749c6b60b82f2520efc
471
cpp
C++
lintcode/besttimetobuyandsellstock.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2016-01-20T08:26:34.000Z
2016-01-20T08:26:34.000Z
lintcode/besttimetobuyandsellstock.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
1
2015-10-21T05:38:17.000Z
2015-11-02T07:42:55.000Z
lintcode/besttimetobuyandsellstock.cpp
WIZARD-CXY/pl
22b7f5d81804f4e333d3cff6433364ba1a0ac7ef
[ "Apache-2.0" ]
null
null
null
class Solution { public: /** * @param prices: Given an integer array * @return: Maximum profit */ int maxProfit(vector<int> &prices) { // write your code here int minprice=INT_MAX; int res=0; for(auto price : prices){ minprice=min(minprice,price); int profit=price-minprice; res=max(profit,res); } return res; } };
19.625
44
0.477707
WIZARD-CXY
b504a01594dae37b8379ab8d0546b9ba5b066487
2,858
hh
C++
src/ggl/MR_ApplyRule.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
20
2017-05-09T15:37:04.000Z
2021-11-24T10:51:02.000Z
src/ggl/MR_ApplyRule.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
2
2017-05-24T08:00:25.000Z
2017-05-24T08:01:01.000Z
src/ggl/MR_ApplyRule.hh
michaelapeterka/GGL
99e585b773ad8f33e39160d2cbd71c00e036fa37
[ "MIT" ]
7
2017-05-29T10:55:18.000Z
2020-12-04T14:24:51.000Z
#ifndef GGL_MR_APPLYRULE_HH_ #define GGL_MR_APPLYRULE_HH_ #include "sgm/Match_Reporter.hh" #include "ggl/Graph_Storage.hh" #include "ggl/Graph.hh" #include "ggl/RuleGraph.hh" #include <climits> namespace ggl { /*! @brief Graph Grammar Rule application for each reported match * * A sgm::Match_Reporter implementation that applies a graph grammar ggl::Rule * to a graph and generates the resulting graph. The new graph is added * to a specified container for further handling like storage or output. * The pattern graph has to be an instance of ggl::LeftSidePattern. * * @author Martin Mann (c) 2008 http://www.bioinf.uni-freiburg.de/~mmann/ * */ class MR_ApplyRule : public sgm::Match_Reporter { protected: //! the storage to that "reportHit(..)" adds the resulting graphs //! after the application of a rule to a matched target graph. Graph_Storage & storage; //! we apply undirected rules or not const bool undirectedRule; /*! if set to true, than all components of the Rules LeftSidePattern * are matched to an own target graph copy if two components map to * the same target graph. */ const bool addEachComponent; public: /*! Construction of a MR_ApplyRule object that adds the resulting * graphs to the given Graph_Storage object. * @param storage the Graph_Storage object to add the results to * @param addEachComponent if set to true, than all components of the * Rules LeftSidePattern are matched to an own target graph * copy if two components map to the same target graph. * NOTE: only important for rules with multi-component * LeftSidePattern! */ MR_ApplyRule( Graph_Storage & storage , const bool addEachComponent = false ); virtual ~MR_ApplyRule(); //! Applies the Rule represented by the pattern onto the matched //! subgraph of target and adds the resulting graph to the internal //! Graph_Storage object. //! NOTE: It is assumed that pattern is an instance of //! ggl::LeftSidePattern! //! @param pattern the pattern graph that was searched for //! @param target the graph the pattern was found within //! @param match contains the indices of the matched pattern nodes in //! the target graph. match[i] corresponds to the mapping of the i-th //! vertex in the pattern graph. virtual void reportHit ( const sgm::Pattern_Interface & pattern, const sgm::Graph_Interface & target, const sgm::Match & match ); }; //////////////////////////////////////////////////////////////////////////////// } // namespace ggl #include "ggl/MR_ApplyRule.icc" #endif /*MR_APPLYRULE_HH_*/
32.11236
83
0.644507
michaelapeterka
b505660d07d2b5c52b2dc66d597edda14aa7df49
842
cpp
C++
main.cpp
MCLEANS/STM32F4_FreeRTOS_TEMPLATE
b7ca381938baed6eb3295d7ec3511e15a9c06706
[ "MIT" ]
1
2021-08-21T03:48:09.000Z
2021-08-21T03:48:09.000Z
main.cpp
MCLEANS/STM32F4_FreeRTOS_TEMPLATE
b7ca381938baed6eb3295d7ec3511e15a9c06706
[ "MIT" ]
null
null
null
main.cpp
MCLEANS/STM32F4_FreeRTOS_TEMPLATE
b7ca381938baed6eb3295d7ec3511e15a9c06706
[ "MIT" ]
null
null
null
#include "stm32f4xx.h" #include "clockconfig.h" #include <FreeRTOS.h> #include <task.h> #include <portmacro.h> custom_libraries::clock_config system_clock; extern "C" void led1_task(void* pvParameter){ while(1){ for(volatile int i = 0; i < 2000000; i++){} GPIOD->ODR ^= (1<<12); } } extern "C" void led2_task(void* pvParameter){ while(1){ for(volatile int i = 0; i < 2000000; i++){} GPIOD->ODR ^= (1<<13); } } int main(void) { system_clock.initialize(); RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN; GPIOD->MODER |= GPIO_MODER_MODER12_0; GPIOD->ODR |= GPIO_ODR_ODR_12; GPIOD->MODER |= GPIO_MODER_MODER13_0; GPIOD->ODR |= GPIO_ODR_ODR_13; xTaskCreate(led1_task,"led 1 controller",100,NULL,1,NULL); xTaskCreate(led2_task,"led 2 controller",100,NULL,1,NULL); vTaskStartScheduler(); while(1){ } }
21.05
60
0.665083
MCLEANS
b508fbfdd518f36bd26fcf04dcd37df520ef145f
3,829
cpp
C++
src/model/io/yuv420rgbbuffer.cpp
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
null
null
null
src/model/io/yuv420rgbbuffer.cpp
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
null
null
null
src/model/io/yuv420rgbbuffer.cpp
fanghaocong/GitlHEVCAnalyzer
1dbf3adca4822b0a55af03c7a7f49c92798c91d6
[ "Apache-2.0" ]
null
null
null
#include "yuv420rgbbuffer.h" #include <QFile> #include <QDebug> extern "C" { #include "libswscale/swscale.h" #include "libavutil/imgutils.h" #include "libavutil/frame.h" } static enum AVPixelFormat bitDepth2PixelFormat( int iBitDepth ) { enum AVPixelFormat pixelFormat; if ( iBitDepth == 8 ) { pixelFormat = AV_PIX_FMT_YUV420P; } else if ( iBitDepth == 10 ) { pixelFormat = AV_PIX_FMT_YUV420P10LE; } else if ( iBitDepth == 16 ) { pixelFormat = AV_PIX_FMT_YUV420P16LE; } return pixelFormat; } YUV420RGBBuffer::YUV420RGBBuffer() { m_iBufferWidth = 0; m_iBufferHeight = 0; m_iFrameCount = -1; m_iBitDepth = -1; m_puhYUVBuffer = NULL; m_puhRGBBuffer = NULL; m_pFrameYUV = av_frame_alloc(); m_pFrameRGB = av_frame_alloc(); m_pConvertCxt = NULL; } YUV420RGBBuffer::~YUV420RGBBuffer() { av_free(m_puhYUVBuffer); m_puhYUVBuffer = NULL; av_free(m_puhRGBBuffer); m_puhRGBBuffer = NULL; av_frame_free(&m_pFrameYUV); av_frame_free(&m_pFrameRGB); sws_freeContext(m_pConvertCxt); } bool YUV420RGBBuffer::openYUVFile( const QString& strYUVPath, int iWidth, int iHeight, int iBitDepth ) { /// if new size dosen't match current size, delete old one and create new one if( iWidth != m_iBufferWidth || iHeight != m_iBufferHeight || iBitDepth != m_iBitDepth ) { enum AVPixelFormat pixelFormat = bitDepth2PixelFormat(iBitDepth); av_free(m_puhYUVBuffer); m_puhYUVBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(pixelFormat, iWidth, iHeight, 1) * sizeof(uint8_t)); av_free(m_puhRGBBuffer); m_puhRGBBuffer = (uint8_t *)av_malloc(av_image_get_buffer_size(AV_PIX_FMT_RGB32, iWidth, iHeight, 1) * sizeof(uint8_t)); av_image_fill_arrays(m_pFrameYUV->data, m_pFrameYUV->linesize, m_puhYUVBuffer, pixelFormat, iWidth, iHeight, 1); av_image_fill_arrays(m_pFrameRGB->data, m_pFrameRGB->linesize, m_puhRGBBuffer, AV_PIX_FMT_RGB32, iWidth, iHeight, 1); sws_freeContext(m_pConvertCxt); m_pConvertCxt = sws_getContext(iWidth, iHeight, pixelFormat, iWidth, iHeight, AV_PIX_FMT_RGB32, SWS_BICUBIC, NULL, NULL, NULL); } m_iBufferWidth = iWidth; m_iBufferHeight = iHeight; m_iBitDepth = iBitDepth; /// set YUV file reader if( !m_cIOYUV.openYUVFilePath(strYUVPath) ) { qCritical() << "YUV Buffer Initialization Fail"; return false; } return true; } QPixmap* YUV420RGBBuffer::getFrame(int iFrameCount) { QPixmap* pcFramePixmap = NULL; if( xReadFrame(iFrameCount) ) { QImage cFrameImg(m_puhRGBBuffer, m_iBufferWidth, m_iBufferHeight, QImage::Format_RGB32 ); m_cFramePixmap = QPixmap::fromImage(cFrameImg); pcFramePixmap = &m_cFramePixmap; } else { qCritical() << "Read YUV File Failure."; } return pcFramePixmap; } bool YUV420RGBBuffer::xReadFrame(int iFrameCount) { if( iFrameCount < 0 ) return false; m_iFrameCount = iFrameCount; enum AVPixelFormat pixelFormat = bitDepth2PixelFormat(m_iBitDepth); int iFrameSizeInByte = av_image_get_buffer_size(pixelFormat, m_iBufferWidth, m_iBufferHeight, 1); if( m_cIOYUV.seekTo(iFrameCount*iFrameSizeInByte) == false ) return false; int iReadBytes = 0; ///read iReadBytes = m_cIOYUV.readOneFrame(m_puhYUVBuffer, (uint)iFrameSizeInByte); if( iReadBytes != iFrameSizeInByte ) { qCritical() << "Read YUV Frame Error"; return false; } else { /// YUV to RGB conversion sws_scale(m_pConvertCxt, (const uint8_t *const *) m_pFrameYUV->data, m_pFrameYUV->linesize, 0, m_iBufferHeight, m_pFrameRGB->data, m_pFrameRGB->linesize); return true; } }
26.776224
135
0.680595
fanghaocong
b517ad009d89ba9a9df95013f0dab81716a2a52f
1,077
cpp
C++
code/clock_real/mts_clock_real.cpp
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
8
2019-03-28T04:15:59.000Z
2021-03-23T14:29:43.000Z
code/clock_real/mts_clock_real.cpp
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
null
null
null
code/clock_real/mts_clock_real.cpp
mtsquant/MTS
ab7ecab0f88c844289b5c81e5627326fe36e682f
[ "Apache-2.0" ]
5
2019-11-06T12:39:21.000Z
2021-01-28T19:14:14.000Z
/***************************************************************************** * Copyright [2017-2019] [MTSQuant] * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ #include "clock_real_api.h" #include "ClockReal.h" #include "mts_core/enums.h" extern "C" { MTS_CLOCK_REAL_API mts::Clock* createClock(mts::EnvironmentMode mode) { if (mode != mts::ENVIR_REAL) { return nullptr; } return new mts::ClockReal(); } MTS_CLOCK_REAL_API void releaseClock(mts::Clock* clock) { delete clock; } }
34.741935
78
0.629526
mtsquant
b518e4b42c4ca9a8a5577f4ff97282c4bdab6f52
13,542
cpp
C++
main.cpp
Joel714/GameProject
417b0f65d2f2c9dde2d2bf68f6ac092501dfcabc
[ "MIT" ]
null
null
null
main.cpp
Joel714/GameProject
417b0f65d2f2c9dde2d2bf68f6ac092501dfcabc
[ "MIT" ]
null
null
null
main.cpp
Joel714/GameProject
417b0f65d2f2c9dde2d2bf68f6ac092501dfcabc
[ "MIT" ]
null
null
null
#include <cstdlib> #include <cstdio> #include <cassert> #include <GL/gl.h> #include <GL/glut.h> #ifdef FREEGLUT #include <GL/freeglut_ext.h> #endif #ifndef NDEBUG #define msglError( ) _msglError( stderr, __FILE__, __LINE__ ) #else #define msglError( ) #endif #include <FreeImage.h> #include "keys.h" #include "player.h" #include "enemy.h" #include "mapfileReader.h" #include "camera.h" #include "states.h" Keys keys; Player player; GLuint playerTextureId; float playerTexCoords[33][8] = { { 0.0, 1.0, 0.0625, 1.0, 0.0625, 0.90625, 0.0, 0.90625},//0 stand still :Right {0.125, 1.0, 0.1875, 1.0, 0.1875, 0.90625, 0.125, 0.90625}, {0.5, 0.90625, 0.5625, 0.90625, 0.5625, 0.8125, 0.5, 0.8125},//2 jump/fall :Right {0.5, 0.8125, 0.5625, 0.8125, 0.5625, 0.71875, 0.5, 0.71875}, {0.0, 0.90625, 0.0625, 0.90625, 0.0625, 0.8125, 0.0, 0.8125},//4 walking 1 :Right {0.0, 0.8125, 0.0625, 0.8125, 0.0625, 0.71875, 0.0, 0.71875}, {0.0625, 0.90625, 0.125, 0.90625, 0.125, 0.8125, 0.0625, 0.8125},//6 walking 2 :Right {0.0625, 0.8125, 0.125, 0.8125, 0.125, 0.71875, 0.0625, 0.71875}, {0.125, 0.90625, 0.1875, 0.90625, 0.1875, 0.8125, 0.125, 0.8125},//8 walking 3 :Right {0.125, 0.8125, 0.1875, 0.8125, 0.1875, 0.71875, 0.125, 0.71875}, {0.1875, 0.90625, 0.25, 0.90625, 0.25, 0.8125, 0.1875, 0.8125},//10 walking 4 :Right {0.1875, 0.8125, 0.25, 0.8125, 0.25, 0.71875, 0.1875, 0.71875}, {0.25, 1.0, 0.3125, 1.0, 0.3125, 0.90625, 0.25, 0.90625},//12 hit :Right {0.0625, 1.0, 0.125, 1.0, 0.125, 0.90625, 0.0625, 0.90625},//13 stand still :Left {0.1875, 1.0, 0.25, 1.0, 0.25, 0.90625, 0.1875, 0.90625}, { 0.5625, 0.90625, 0.625, 0.90625, 0.625, 0.8125, 0.5625, 0.8125},//15 jump/fall :Left {0.5625, 0.8125, 0.625, 0.8125, 0.625, 0.71875, 0.5625, 0.71875}, {0.25, 0.90625, 0.3125, 0.90625, 0.3125, 0.8125, 0.25, 0.8125},//17 walking 1 :Left {0.25, 0.8125, 0.3125, 0.8125, 0.3125, 0.71875, 0.25, 0.71875}, {0.3125, 0.90625, 0.375, 0.90625, 0.375, 0.8125, 0.3125, 0.8125},//19 walking 2 :Left {0.3125, 0.8125, 0.375, 0.8125, 0.375, 0.71875, 0.3125, 0.71875}, {0.375, 0.90625, 0.4375, 0.90625, 0.4375, 0.8125, 0.375, 0.8125},//21 walking 3 :Left {0.375, 0.8125, 0.4375, 0.8125, 0.4375, 0.71875, 0.375, 0.71875}, {0.4375, 0.90625, 0.5, 0.90625, 0.5, 0.8125, 0.4375, 0.8125},//23 walking 4 :Left {0.4375, 0.8125, 0.5, 0.8125, 0.5, 0.71875, 0.4375, 0.71875}, {0.3125, 1.0, 0.375, 1.0, 0.375, 0.90625, 0.3125, 0.90625},//25 hit :Left {0.375, 1.0, 0.4375, 1.0, 0.4375, 0.90625, 0.375, 0.90625},//26 chunk 1 {0.4375, 1.0, 0.5, 1.0, 0.5, 0.90625, 0.4375, 0.90625},//27 chunk 2 {0.5, 1.0, 0.5625, 1.0, 0.5625, 0.90625, 0.5, 0.90625},//28 chunk 3 {0.90625, 1.0, 1.0, 1.0, 1.0, 0.96875, 0.90625, 0.96875},//29 bar {0.9375, 0.96875, 0.96875, 0.96875, 0.96875, 0.9375, 0.9375, 0.9375},//30 red {0.96875, 0.96875, 1.0, 0.96875, 1.0, 0.9375, 0.96875, 0.9375},//31 bullet {0.5625 , 1.0, 0.625, 1.0, 0.625, 0.90625, 0.5625, 0.90625}//32 invisible }; int mapWidth = 0; int mapHeight = 0; int *mapData; GLuint mapTexureId; float mapTexCoords[4][8] = { {0.0, 1.0, 0.5, 1.0, 0.5, 0.5, 0.0, 0.5}, {0.5, 1.0, 1.0, 1.0, 1.0, 0.5, 0.5, 0.5}, {0.0, 0.5, 0.5, 0.5, 0.5, 0.0, 0.0, 0.0}, {0.5, 0.5, 1.0, 0.5, 1.0, 0.0, 0.5, 0.0} }; const int enemyArraySize = 3; Enemy enemyArray[enemyArraySize]; GLuint enemyTextureId; float etexCoords[16][8] = { {0.0, 1.0, 0.25, 1.0, 0.25, 0.5, 0.0, 0.5},//0 Looking/standing stil : Left {0.25, 1.0, 0.5, 1.0, 0.5, 0.5, 0.25, 0.5},//1 arm half way up : Left {0.5, 1.0, 0.75, 1.0, 0.75, 0.5, 0.5, 0.5},//2 arm up/firing : Left {0.75, 1.0, 0.875, 1.0, 0.875, 0.875, 0.75, 0.875},//3 bullet {0.0, 0.5, 0.25, 0.5, 0.25, 0.0, 0.0, 0.0},//4 dying animation 1 : Left {0.25, 0.5, 0.5, 0.5, 0.5, 0.0, 0.25, 0.0},//5 dying animation 2 : Left {0.5, 0.5, 0.75, 0.5, 0.75, 0.0, 0.5, 0.0},//6 dying animation 3 : Left {0.75, 0.5, 1.0, 0.5, 1.0, 0.0, 0.75, 0.0},//7 dead : Left {0.25, 1.0, 0.0, 1.0, 0.0, 0.5, 0.25, 0.5},//8 Looking/standing stil : Right {0.5, 1.0, 0.25, 1.0, 0.25, 0.5, 0.5, 0.5},//9 arm half way up : Right {0.75, 1.0, 0.5, 1.0, 0.5, 0.5, 0.75, 0.5},//10 arm up/firing : Right {0.875, 1.0, 0.75, 1.0, 0.75, 0.875, 0.875, 0.875},//bullet {0.25, 0.5, 0.0, 0.5, 0.0, 0.0, 0.25, 0.0},//12 dying animation 1 : Right {0.5, 0.5, 0.25, 0.5, 0.25, 0.0, 0.5, 0.0},//13 dying animation 2 : Right {0.75, 0.5, 0.5, 0.5, 0.5, 0.0, 0.75, 0.0},//14 dying animation 3 : Right {1.0, 0.5, 0.75, 0.5, 0.75, 0.0, 1.0, 0.0}//15 dead : Right }; bool gameStarted = false; bool gameEnded = false; Camera myCamera; bool _msglError( FILE *out, const char *filename, int line ){ bool ret = false; GLenum err = glGetError( ); while( err != GL_NO_ERROR ) { ret = true; fprintf( out, "GL ERROR:%s:%d: %s\n", filename, line, (char*)gluErrorString( err ) ); err = glGetError( ); } return( ret ); } void initOpenGL( ){ glClearColor( 0.5f, 0.5f, 0.5f, 1.0f ); glEnable( GL_DEPTH_TEST ); glDepthRange(0.0, 1.0); glDepthFunc(GL_LEQUAL); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); msglError( ); } void initKeys(){ keys.a_isDown = false; keys.d_isDown = false; keys.w_isDown = false; keys.f_isDown = false; } //uses FreeImage to load a texture void textureLoader(const char *filename, GLuint *textureid){ FIBITMAP* bitmap = NULL; FREE_IMAGE_FORMAT fif = FreeImage_GetFileType(filename, 0); if( fif == FIF_UNKNOWN ){ fif = FreeImage_GetFIFFromFilename(filename); } if( (fif != FIF_UNKNOWN) && FreeImage_FIFSupportsReading(fif)){ bitmap = FreeImage_Load(fif, filename, 0); assert(bitmap); } assert(bitmap); FREE_IMAGE_COLOR_TYPE fic = FreeImage_GetColorType(bitmap); assert( fic == FIC_RGB || fic == FIC_RGBALPHA ); unsigned int bpp = FreeImage_GetBPP(bitmap); assert(bpp == 24 || bpp == 32); GLenum pixelFormat; if(bpp == 24){ pixelFormat = GL_BGR; }else{ pixelFormat = GL_BGRA; } int width = FreeImage_GetWidth(bitmap); int height = FreeImage_GetHeight(bitmap); glGenTextures(1, textureid); glBindTexture(GL_TEXTURE_2D, *textureid); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, pixelFormat, GL_UNSIGNED_BYTE, (void*)FreeImage_GetBits(bitmap)); } void resetLevel(){ player.currentState = Still; player.previousState = Still; player.frameCount = 0; player.texIndex = 0; player.xVelocity = 0; player.yVelocity = 0; player.facingLeft = false; player.bulletLifeTime = 0; player.bulletIsFired = false; player.health = 3; player.isHit = false; player.invulnerableTime = 0; player.invulnerableTimeLimit = 180; player.isDead = false; player.x = 64; player.y = 240; for(int i = 0; i < enemyArraySize; i++){ enemyArray[i].currentState = Looking; enemyArray[i].frameCount = 0; enemyArray[i].texIndex = 0; enemyArray[i].facingRight = false; enemyArray[i].bulletLifeTime = 0; enemyArray[i].bulletIsFired = false; } } void keyboardDown( unsigned char key, int x, int y ){ switch( key ){ case 27: // The 'esc' key case 'q': delete [] mapData; #ifdef FREEGLUT glutLeaveMainLoop( ); #else exit( 0 ); #endif break; case 'a': keys.a_isDown = true; break; case 'd': keys.d_isDown = true; break; case 'w': keys.w_isDown = true; break; case 'f': keys.f_isDown = true; break; case 's': gameStarted = true; break; case 'r': if(gameEnded){ gameEnded = false; resetLevel(); } break; default: break; } } void keyboardUp( unsigned char key, int x, int y ){ switch( key ){ case 'a': keys.a_isDown = false; break; case 'd': keys.d_isDown = false; break; case 'w': keys.w_isDown = false; break; case 'f': keys.f_isDown = false; break; default: break; } } void display( ){ msglError( ); glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT ); glEnable(GL_TEXTURE_2D); glBindTexture(GL_TEXTURE_2D, mapTexureId); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); if(gameEnded){ //show ending menu glBindTexture(GL_TEXTURE_2D, playerTextureId); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.4375); glVertex3f(-1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.4375); glVertex3f(1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.15625); glVertex3f(1.0, -1.0, 0.0); glTexCoord2f(0.0, 0.15625); glVertex3f(-1.0, -1.0, 0.0); glEnd(); }else if(gameStarted){ //the maximum and minumum amount of //tiles that are viewed on screen int minXview = 0; int maxXview = 0; int minYview = 0; int maxYview = 0; //get max and min of viewable tiles if(myCamera.x % 32 == 0){ minXview = myCamera.x/32 - 5; maxXview = myCamera.x/32 + 4; }else{ minXview = myCamera.x/32 - 5; maxXview = myCamera.x/32 + 5; } if(myCamera.y % 32 == 0){ minYview = myCamera.y/32 - 5; maxYview = myCamera.y/32 + 4; }else{ minYview = myCamera.y/32 - 5; maxYview = myCamera.y/32 + 5; } //check if it's within possible values if(minXview < 0 || minXview > (mapWidth - 1)){ minXview = 0; } if(maxXview > (mapWidth - 1) || maxXview < 0 ){ maxXview = 0; } if(minYview < 0 || minYview > (mapHeight - 1)){ minYview = 0; } if(maxYview > (mapHeight - 1) || maxYview < 0 ){ maxYview = 0; } //loop through map data and draw the tiles for(int i = minYview; i <= maxYview; i++){ for(int j = minXview; j <= maxXview; j++){ if(mapData[(i * mapWidth) + j] == 0){ }else if(mapData[(i * mapWidth) + j] == 1){ myCamera.drawSprite(j * 32, i * 32, 32, 32, mapTexCoords, 1); } } } glBindTexture(GL_TEXTURE_2D, playerTextureId); //draw player sprite myCamera.drawSprite(player.x, player.y, 48, 32, playerTexCoords, player.texIndex); //draw red healthbar myCamera.drawSprite(myCamera.x - 160, myCamera.y - 160, 16, 16 * player.health, playerTexCoords, 30); //draw healthbar outline myCamera.drawSprite(myCamera.x - 160, myCamera.y - 160, 16, 48, playerTexCoords, 29); //draw player bullet if it's fired if(player.bulletIsFired){ myCamera.drawSprite(player.bulletX, player.bulletY, 16, 16, playerTexCoords, 31); } //loop through enemy array and draw //enemy sprite and bullet glBindTexture(GL_TEXTURE_2D, enemyTextureId); for(int eIndex = 0; eIndex < enemyArraySize; eIndex++){ myCamera.drawSprite(enemyArray[eIndex].x, enemyArray[eIndex].y, 64, 32, etexCoords, enemyArray[eIndex].texIndex); if(enemyArray[eIndex].bulletIsFired){ myCamera.drawSprite(enemyArray[eIndex].bulletX, enemyArray[eIndex].bulletY, 16, 16, etexCoords, 3); } } }else if(!gameStarted){ //show strating menu glBindTexture(GL_TEXTURE_2D, playerTextureId); glBegin(GL_QUADS); glTexCoord2f(0.0, 0.71875); glVertex3f(-1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.71875); glVertex3f(1.0, 1.0, 0.0); glTexCoord2f(0.25, 0.4375); glVertex3f(1.0, -1.0, 0.0); glTexCoord2f(0.0, 0.4375); glVertex3f(-1.0, -1.0, 0.0); glEnd(); } glDisable(GL_TEXTURE_2D); glutSwapBuffers( ); msglError( ); } void reshape( int width, int height ){ if (height == 0){ height = 1; } glViewport( 0, 0, (GLsizei)width, (GLsizei)height ); glMatrixMode( GL_PROJECTION ); glLoadIdentity( ); glMatrixMode( GL_MODELVIEW ); glLoadIdentity( ); } void update(int x){ //end game when player reaches //the end of the map if(player.x >= (mapWidth - 2) * 32){ gameEnded = true; } //reset level if player dies if(player.isDead || player.y > (mapHeight * 32)){ resetLevel(); } //if the game has started then //go through the player and enemy fsm if(gameStarted && !gameEnded){ player.FSM(mapData, mapWidth, mapHeight, &keys); myCamera.updatePosition(player.x, player.y, mapHeight, mapWidth); for(int i = 0; i < enemyArraySize; i++){ enemyArray[i].FSM(&player); } } glutTimerFunc(16, update, 0); glutPostRedisplay(); } int main(int argc, const char* argv[]){ glutInit( &argc, (char**)argv ); glutInitDisplayMode( GLUT_RGBA | GLUT_DOUBLE | GLUT_DEPTH ); glutInitWindowSize( 640, 640); glutCreateWindow( "Demo" ); initOpenGL( ); initKeys(); getMapData(&mapWidth, &mapHeight, mapData); player.x = 64; player.y = 240; enemyArray[0].x = 640; enemyArray[0].y = 224; enemyArray[1].x = 1120; enemyArray[1].y = 160; enemyArray[2].x = 1600; enemyArray[2].y = 224; textureLoader("data/playerSprites.png", &playerTextureId); textureLoader("data/enemySprites.png", &enemyTextureId); textureLoader("data/tileSprites.png", &mapTexureId); glutKeyboardFunc( keyboardDown ); glutKeyboardUpFunc( keyboardUp ); glutDisplayFunc( display ); glutReshapeFunc( reshape ); glutTimerFunc(16, update, 0); glutMainLoop( ); return(0); }
28.812766
127
0.603604
Joel714
b519402bd985faa4b8e0961fa74cd224cdcf84ff
555
cpp
C++
cpp/evenOddQuery.cpp
Rohit-RA-2020/hackerrank-math
466a9b25311c8ba9d457720d618d8930667e498f
[ "MIT" ]
null
null
null
cpp/evenOddQuery.cpp
Rohit-RA-2020/hackerrank-math
466a9b25311c8ba9d457720d618d8930667e498f
[ "MIT" ]
null
null
null
cpp/evenOddQuery.cpp
Rohit-RA-2020/hackerrank-math
466a9b25311c8ba9d457720d618d8930667e498f
[ "MIT" ]
null
null
null
// https://www.hackerrank.com/challenges/even-odd-query #include <iostream> using namespace std; int A[100008], N; int find(int x, int y) { if (A[x] % 2) return 1; if (x == y) return 0; if (A[x + 1] == 0) return 1; return 0; } int main() { int x, y, Q; cin >> N; for (int i = 1; i <= N; i++) cin >> A[i]; cin >> Q; while (Q--) { cin >> x >> y; if (find(x, y)) cout << "Odd" << endl; else cout << "Even" << endl; } return 0; }
16.323529
55
0.421622
Rohit-RA-2020
b51c26cf9fa26a79b625b701c31623f4b175f203
16,938
cpp
C++
franka_polishing/src/nodes/nflat_surfaces_node.cpp
amaroUC/TOOLING4G
d25d43c0e14798617b7c4be60fd9eed2df25aa17
[ "Apache-2.0" ]
2
2020-11-18T09:01:49.000Z
2021-09-24T10:31:14.000Z
franka_polishing/src/nodes/nflat_surfaces_node.cpp
amaroUC/TOOLING4G
d25d43c0e14798617b7c4be60fd9eed2df25aa17
[ "Apache-2.0" ]
1
2021-11-12T12:19:15.000Z
2021-11-16T12:17:01.000Z
franka_polishing/src/nodes/nflat_surfaces_node.cpp
amaroUC/TOOLING4G
d25d43c0e14798617b7c4be60fd9eed2df25aa17
[ "Apache-2.0" ]
2
2020-07-25T07:38:20.000Z
2021-11-08T15:19:08.000Z
// ============================================================================= // Name : nflat_surfaces_node.cpp // Author : Hélio Ochoa // Description : // ============================================================================= #include <franka_polishing/spacenav.h> #include <visualization_msgs/Marker.h> #include <tf/transform_broadcaster.h> geometry_msgs::PoseStamped marker_pose; // STATE MACHINE -------------------------------------------------------------- #define MOVE2POINT 0 #define PATTERN 1 #define MOVEUP 2 #define CHOOSEPLANE 3 #define INTERRUPT 4 // ----------------------------------------------------------------------------- int main(int argc, char** argv) { ros::init(argc, argv, "nflat_surfaces_node"); ros::NodeHandle nh; franka_polishing::Spacenav panda(nh); // --------------------------------------------------------------------------- // VIZUALIZATIONS MARKERS INITIALIZATION // --------------------------------------------------------------------------- ros::Publisher marker_pub = nh.advertise<visualization_msgs::Marker>("visualization_marker", 20); visualization_msgs::Marker points, line_strip; points.header.frame_id = line_strip.header.frame_id = "/panda_link0"; points.header.stamp = line_strip.header.stamp = ros::Time::now(); points.ns = "points"; line_strip.ns = "lines"; points.id = 0; line_strip.id = 1; points.action = line_strip.action = visualization_msgs::Marker::ADD; points.type = visualization_msgs::Marker::POINTS; line_strip.type = visualization_msgs::Marker::LINE_STRIP; points.pose.orientation.w = line_strip.pose.orientation.w = 1.0; // POINTS markers use x and y scale for width/height respectively points.scale.x = 0.01; points.scale.y = 0.01; // Set the color -- be sure to set alpha to something non-zero! points.color.a = 1.0; points.color.r = 1.0; points.color.g = 0.0; points.color.b = 0.0; // LINE_STRIP/LINE_LIST markers use only the x component of scale, for the line width line_strip.scale.x = 0.01; // Line strip is green line_strip.color.a = 1.0; line_strip.color.g = 1.0; // --------------------------------------------------------------------------- // TF BROADCASTER // --------------------------------------------------------------------------- tf::TransformBroadcaster br, br_d; tf::Transform transform, transform_d; // --------------------------------------------------------------------------- // GET THE CO-MANIPULATION PATTERN FROM A FILE // --------------------------------------------------------------------------- Eigen::MatrixXd position; // matrix to save the robot positions in Base-frame Eigen::MatrixXd orientation; // matrix to save the robot orientations in Base-frame std::ifstream pattern_file; std::string pattern_path; pattern_path = "/home/panda/catkin_ws/src/TOOLING4G/franka_polishing/co_manipulation_data/pattern"; pattern_file.open(pattern_path); double time, px, py, pz, qx, qy, qz, qw; std::string line; getline(pattern_file, line); // first line getline(pattern_file, line); // second line int column = 0; position.resize(3, column + 1); orientation.resize(4, column + 1); if(pattern_file.is_open()){ while(pattern_file >> time >> px >> py >> pz >> qx >> qy >> qz >> qw){ // save the values in the matrix position.conservativeResize(3, column + 1); orientation.conservativeResize(4, column + 1); position(0, column) = px; position(1, column) = py; position(2, column) = pz; orientation(0, column) = qx; orientation(1, column) = qy; orientation(2, column) = qz; orientation(3, column) = qw; column++; } } else{ std::cout << "\nError open the file!" << std::endl; return(0); } pattern_file.close(); //std::cout << position.transpose() << std::endl; //std::cout << orientation.transpose() << std::endl; Eigen::Quaterniond Qpattern; Qpattern.coeffs() = orientation.col(0); Eigen::Matrix3d Rpattern(Qpattern); // --------------------------------------------------------------------------- // COMPUTE OFFSETS BETWEEN POSITIONS // --------------------------------------------------------------------------- Eigen::MatrixXd OFFSET; OFFSET.resize(3, column-1); for(int i = 0; i < column-1; i++){ OFFSET(0, i) = position(0, i+1) - position(0, i); OFFSET(1, i) = position(1, i+1) - position(1, i); OFFSET(2, i) = position(2, i+1) - position(2, i); } //std::cout << OFFSET.transpose() << std::endl; // --------------------------------------------------------------------------- // GET MOULD POINTS FROM A FILE // --------------------------------------------------------------------------- std::ifstream file_plane; std::string path_plane; double x, y, z; Eigen::MatrixXd P; path_plane = "/home/panda/catkin_ws/src/TOOLING4G/franka_polishing/co_manipulation_data/mold_workspace"; file_plane.open(path_plane); int n_points = 0; P.resize(3, n_points + 1); if(file_plane.is_open()){ while(file_plane >> x >> y >> z){ // save the values in the matrix P.conservativeResize(3, n_points + 1); P(0, n_points) = x; P(1, n_points) = y; P(2, n_points) = z; n_points++; } } else{ std::cout << "Error open the file!" << std::endl; return(0); } file_plane.close(); // std::cout << P << std::endl; int n_planes = n_points/4; int n = 0; Eigen::Vector3d P1(P.col(n)); Eigen::Vector3d P2(P.col(n+1)); Eigen::Vector3d P3(P.col(n+2)); Eigen::Vector3d P4(P.col(n+3)); Eigen::Matrix3d Rmould; Rmould = panda.points2Rotation(P1, P2, P4); //std::cout << Rmould << std::endl; // mould orientation in Quaternion unit Eigen::Quaterniond Qmould(Rmould); // compute the desired rotation in all points of plane Eigen::Matrix3d Rpoints(Rmould * Rpattern); Eigen::Quaterniond Qpoints(Rpoints); // build a vector with all points of the mould work space int Nx = 5; int Ny = 5; Eigen::Vector3d delta_synthetic; delta_synthetic << 0.0, 0.0, 0.0; Eigen::MatrixXd Xd; Xd = panda.moldWorkSpace(P1, P2, P4, delta_synthetic, Nx, Ny); // std::cout << Xd.transpose() << std::endl; geometry_msgs::Point p, l; // points and lines int n_columns = 0; while(n_columns < (Nx+1)*(Ny+1)){ p.x = Xd(0, n_columns); p.y = Xd(1, n_columns); p.z = Xd(2, n_columns); points.points.push_back(p); n_columns++; } // --------------------------------------------------------------------------- // GET INITIAL POSE // --------------------------------------------------------------------------- Eigen::Matrix4d O_T_EE_i; Eigen::VectorXd pose_i(7,1); O_T_EE_i = panda.O_T_EE; pose_i = panda.robot_pose(O_T_EE_i); // --------------------------------------------------------------------------- // TRAJECTORY TO FIRST POINT // --------------------------------------------------------------------------- Eigen::Vector3d pi, pf; int num_cols = n_columns-1; pi << pose_i[0], pose_i[1], pose_i[2]; pf << Xd(0, num_cols), Xd(1, num_cols), Xd(2, num_cols); double ti = 1.0; double tf = 6.0; double t = 0.0; double delta_t = 0.001; // orientation Eigen::Quaterniond oi, of; oi.coeffs() << pose_i[3], pose_i[4], pose_i[5], pose_i[6]; of.coeffs() << Qpoints.vec()[0], Qpoints.vec()[1], Qpoints.vec()[2], Qpoints.w(); double t1 = 0.0; double delta_t1 = delta_t/(tf-ti); // --------------------------------------------------------------------------- // TRAJECTORY MOVE UP CONDITIONS // --------------------------------------------------------------------------- Eigen::Vector3d delta_up; delta_up << 0.0, 0.0, 0.1; // --------------------------------------------------------------------------- // DEFINE WORK-SPACE LIMITS // --------------------------------------------------------------------------- // distances between the 4 points that delimit the plane Eigen::Vector3d l12(P2 - P1); Eigen::Vector3d l23(P3 - P2); Eigen::Vector3d l34(P4 - P3); Eigen::Vector3d l41(P1 - P4); // --------------------------------------------------------------------------- // MAIN LOOP // --------------------------------------------------------------------------- Eigen::Vector3d position_d(pi); Eigen::Quaterniond orientation_d(oi); Eigen::Vector3d new_position_d(position_d); Eigen::Vector3d mould_offset; mould_offset.setZero(); Eigen::Vector3d l1P, l2P, l3P, l4P; l1P.setZero(); l2P.setZero(); l3P.setZero(); l4P.setZero(); double signal1 = 0.0; double signal2 = 0.0; double signal3 = 0.0; double signal4 = 0.0; int flag_pattern = 0; int flag_print = 0; int flag_interrupt = 0; int count = 0; int k = 0; ros::Rate loop_rate(1000); while (ros::ok()){ switch (flag_pattern) { //////////////////////////////////////////////////// // ----------------------------------------------------------------------- case MOVE2POINT: if(flag_print == 0){ std::cout << CLEANWINDOW << "ROBOT IS MOVING TO A MOLD POINT..." << std::endl; flag_print = 1; } // --> MOVE TO MOULD POINT <-- if( (t >= ti) && (t <= tf) ){ position_d = panda.polynomial3_trajectory(pi, pf, ti, tf, t); if ( t1 <= 1.0 ){ orientation_d = oi.slerp(t1, of); orientation_d.normalize(); } t1 = t1 + delta_t1; } else if(t > tf){ flag_pattern = PATTERN; count = 0; } t = t + delta_t; new_position_d = position_d; // INTERRUPT if(panda.spacenav_button_2 == 1){ flag_pattern = INTERRUPT; } break; // ----------------------------------------------------------------------- case PATTERN: if(flag_print == 1){ std::cout << CLEANWINDOW << "PATTERN IS EXECUTING, IF YOU WOULD LIKE TO STOP PRESS SPACENAV BUTTON <2>..." << std::endl; flag_print = 2; } // PATTERN if (count < column-1){ mould_offset << OFFSET(0, count), OFFSET(1, count), OFFSET(2, count); new_position_d = new_position_d + Rmould * mould_offset; // distances between the pattern points and the 4 points that delimit the plane l1P = (new_position_d - P1); l2P = (new_position_d - P2); l3P = (new_position_d - P3); l4P = (new_position_d - P4); // signal between the 2 vectors signal1 = l1P.dot(l12); signal2 = l2P.dot(l23); signal3 = l3P.dot(l34); signal4 = l4P.dot(l41); if( (signal1 >= 0.0) && (signal2 >= 0.0) && (signal3 >= 0.0) && (signal4 >= 0.0) ){ position_d = new_position_d; } }// -------------------------------------------------------------------- else{ flag_pattern = MOVEUP; O_T_EE_i = panda.O_T_EE; pose_i = panda.robot_pose(O_T_EE_i); // get current pose pi << pose_i[0], pose_i[1], pose_i[2]; pf << pi + delta_up; t = 0; // reset the time } count++; // draw the lines of the polished area if(count % 100 == 0){ l.x = position_d[0]; l.y = position_d[1]; l.z = position_d[2]; line_strip.points.push_back(l); marker_pub.publish(line_strip); } // INTERRUPT if(panda.spacenav_button_2 == 1){ flag_pattern = INTERRUPT; } break; // ----------------------------------------------------------------------- case MOVEUP: if(flag_print == 2){ std::cout << CLEANWINDOW << "PATTERN WAS EXECUTED AND THE ROBOT IS MOVING UP!" << std::endl; flag_print = 0; } // --> MOVE UP <-- ti = 0.0; tf = 3.0; if((t >= ti) && (t <= tf)){ position_d = panda.polynomial3_trajectory(pi, pf, ti, tf, t); } else if(t > tf){ if(num_cols > 0){ num_cols--; flag_pattern = MOVE2POINT; O_T_EE_i = panda.O_T_EE; // get current pose pose_i = panda.robot_pose(O_T_EE_i); pi << pose_i[0], pose_i[1], pose_i[2]; pf << Xd(0, num_cols), Xd(1, num_cols), Xd(2, num_cols); t = 0.0; ti = 0.0; tf = 3.0; } else{ if(flag_print == 0){ std::cout << CLEANWINDOW << "MOLD AREA POLISHED!" << std::endl; flag_print = 3; } if(k < n_planes){ k = k + 1; // next plane n = n + 4; // next 4 points flag_pattern = CHOOSEPLANE; } } } t = t + delta_t; // INTERRUPT if(panda.spacenav_button_2 == 1){ flag_pattern = INTERRUPT; } break; // ----------------------------------------------------------------------- case CHOOSEPLANE: if(flag_print == 3){ std::cout << CLEANWINDOW << "WAIT UNTIL NEW PLANE IS BUILT..." << std::endl; flag_print = 0; } if(k >= n_planes) { std::cout << CLEANWINDOW << "ALL MOLD AREAS POLISHED!" << std::endl; return 0; } else{ P1 = P.col(n); P2 = P.col(n+1); P3 = P.col(n+2); P4 = P.col(n+3); Rmould = panda.points2Rotation(P1, P2, P4); Qmould = Rmould; // compute the desired rotation in all points of plane Rpoints = Rmould * Rpattern; Qpoints = Rpoints; // build a matrix with all points of the mould work space Xd = panda.moldWorkSpace(P1, P2, P4, delta_synthetic, Nx, Ny); n_columns = 0; while(n_columns < (Nx+1)*(Ny+1)){ p.x = Xd(0, n_columns); p.y = Xd(1, n_columns); p.z = Xd(2, n_columns); points.points.push_back(p); n_columns++; } l12 = (P2 - P1); l23 = (P3 - P2); l34 = (P4 - P3); l41 = (P1 - P4); flag_pattern = MOVE2POINT; O_T_EE_i = panda.O_T_EE; // get current pose pose_i = panda.robot_pose(O_T_EE_i); num_cols = n_columns-1; pi << pose_i[0], pose_i[1], pose_i[2]; pf << Xd(0, num_cols), Xd(1, num_cols), Xd(2, num_cols); t = 0.0; ti = 0.0; tf = 3.0; oi.coeffs() << pose_i[3], pose_i[4], pose_i[5], pose_i[6]; of.coeffs() << Qpoints.vec()[0], Qpoints.vec()[1], Qpoints.vec()[2], Qpoints.w(); t1 = 0.0; delta_t1 = delta_t/(tf-ti); } break; // ----------------------------------------------------------------------- case INTERRUPT: if(flag_interrupt == 0){ std::cout << CLEANWINDOW << "PROGRAM INTERRUPTED! IF YOU WOULD LIKE TO CONTINUE, PLEASE PRESS SPACENAV BUTTON <1>..." << std::endl; flag_interrupt = 1; } if(panda.spacenav_button_1 == 1){ flag_print = 2; flag_interrupt = 0; flag_pattern = MOVEUP; O_T_EE_i = panda.O_T_EE; pose_i = panda.robot_pose(O_T_EE_i); // get current pose pi << pose_i[0], pose_i[1], pose_i[2]; pf << pi + delta_up; t = 0; } break; }////////////////////////////////////////////////////////////////////////// // std::cout << CLEANWINDOW << position_d << std::endl; // std::cout << CLEANWINDOW << orientation_d.coeffs() << std::endl; panda.posePublisherCallback(marker_pose, position_d, orientation_d); // ------------------------------------------------------------------------- // TF AND VISUALIZATION MARKERS // ------------------------------------------------------------------------- marker_pub.publish(points); // draw the points of the mould work-space // Draw the mould transform transform.setOrigin( tf::Vector3(P1(0), P1(1), P1(2)) ); transform.setRotation( tf::Quaternion(Qmould.vec()[0], Qmould.vec()[1], Qmould.vec()[2], Qmould.w()) ); br.sendTransform(tf::StampedTransform(transform, ros::Time::now(), "/panda_link0", "/mould")); // Draw the desired EE transform transform_d.setOrigin( tf::Vector3(position_d(0), position_d(1), position_d(2)) ); transform_d.setRotation( tf::Quaternion(orientation_d.vec()[0], orientation_d.vec()[1], orientation_d.vec()[2], orientation_d.w()) ); br_d.sendTransform(tf::StampedTransform(transform_d, ros::Time::now(), "/panda_link0", "/panda_EE_d")); // ------------------------------------------------------------------------- if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)) break; ros::spinOnce(); loop_rate.sleep(); } return 0; }
33.146771
141
0.483115
amaroUC
b52316be55163b26ceef1181b10414f4fa4b8a9f
400
cpp
C++
Codeforces 915B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 915B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
Codeforces 915B.cpp
Jvillegasd/Codeforces
ffdd2d5db1dabc7ff76f8f92270c79233a77b933
[ "MIT" ]
null
null
null
#include <stdio.h> #include <math.h> #include <algorithm> using namespace std; int main(){ int n, p, l, r; scanf("%d %d %d %d", &n, &p, &l, &r); if(l == 1 && r == n) printf("0\n"); else if(l == 1 && r != n) printf("%d\n", abs(p - r) + 1); else if(r == n && l != 1) printf("%d\n", abs(p - l) + 1); else printf("%d\n", min(abs(p - l), abs(p - r)) + 2 + r - l); return 0; }
26.666667
65
0.455
Jvillegasd
dde249bfdafe6afef31f10f3bf6464b7719a2bcf
40,247
cpp
C++
export/windows/obj/src/lime/text/Font.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/text/Font.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
null
null
null
export/windows/obj/src/lime/text/Font.cpp
arturspon/zombie-killer
07848c5006916e9079537a3d703ffe3740afaa5a
[ "MIT" ]
1
2021-07-16T22:57:01.000Z
2021-07-16T22:57:01.000Z
// Generated by Haxe 4.0.0-rc.2+77068e10c #include <hxcpp.h> #ifndef INCLUDED_Std #include <Std.h> #endif #ifndef INCLUDED_haxe_IMap #include <haxe/IMap.h> #endif #ifndef INCLUDED_haxe_ds_IntMap #include <haxe/ds/IntMap.h> #endif #ifndef INCLUDED_haxe_io_Bytes #include <haxe/io/Bytes.h> #endif #ifndef INCLUDED_haxe_io_Path #include <haxe/io/Path.h> #endif #ifndef INCLUDED_lime__internal_backend_native_NativeCFFI #include <lime/_internal/backend/native/NativeCFFI.h> #endif #ifndef INCLUDED_lime_app_Future #include <lime/app/Future.h> #endif #ifndef INCLUDED_lime_app_Promise_lime_text_Font #include <lime/app/Promise_lime_text_Font.h> #endif #ifndef INCLUDED_lime_graphics_Image #include <lime/graphics/Image.h> #endif #ifndef INCLUDED_lime_graphics_ImageBuffer #include <lime/graphics/ImageBuffer.h> #endif #ifndef INCLUDED_lime_graphics_ImageType #include <lime/graphics/ImageType.h> #endif #ifndef INCLUDED_lime_math_Vector2 #include <lime/math/Vector2.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_AbstractHTTPRequest #include <lime/net/_HTTPRequest/AbstractHTTPRequest.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_Bytes #include <lime/net/_HTTPRequest_Bytes.h> #endif #ifndef INCLUDED_lime_net__HTTPRequest_lime_text_Font #include <lime/net/_HTTPRequest_lime_text_Font.h> #endif #ifndef INCLUDED_lime_net__IHTTPRequest #include <lime/net/_IHTTPRequest.h> #endif #ifndef INCLUDED_lime_text_Font #include <lime/text/Font.h> #endif #ifndef INCLUDED_lime_text_GlyphMetrics #include <lime/text/GlyphMetrics.h> #endif #ifndef INCLUDED_lime_utils_ArrayBufferView #include <lime/utils/ArrayBufferView.h> #endif #ifndef INCLUDED_lime_utils_Assets #include <lime/utils/Assets.h> #endif #ifndef INCLUDED_lime_utils_TAError #include <lime/utils/TAError.h> #endif HX_DEFINE_STACK_FRAME(_hx_pos_51012fd6257f8a4a_54_new,"lime.text.Font","new",0x97494f29,"lime.text.Font.new","lime/text/Font.hx",54,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_103_decompose,"lime.text.Font","decompose",0x6e29ff3a,"lime.text.Font.decompose","lime/text/Font.hx",103,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_181_getGlyph,"lime.text.Font","getGlyph",0x5bf955cd,"lime.text.Font.getGlyph","lime/text/Font.hx",181,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_188_getGlyphs,"lime.text.Font","getGlyphs",0x1e31be06,"lime.text.Font.getGlyphs","lime/text/Font.hx",188,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_198_getGlyphMetrics,"lime.text.Font","getGlyphMetrics",0x8c9677f6,"lime.text.Font.getGlyphMetrics","lime/text/Font.hx",198,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_215_renderGlyph,"lime.text.Font","renderGlyph",0xe6e51a3f,"lime.text.Font.renderGlyph","lime/text/Font.hx",215,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_254_renderGlyphs,"lime.text.Font","renderGlyphs",0x2191dd54,"lime.text.Font.renderGlyphs","lime/text/Font.hx",254,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_418___copyFrom,"lime.text.Font","__copyFrom",0x8a0b5b36,"lime.text.Font.__copyFrom","lime/text/Font.hx",418,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_442___fromBytes,"lime.text.Font","__fromBytes",0x257c2b4a,"lime.text.Font.__fromBytes","lime/text/Font.hx",442,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_455___fromFile,"lime.text.Font","__fromFile",0x6331ec7d,"lime.text.Font.__fromFile","lime/text/Font.hx",455,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_468___initializeSource,"lime.text.Font","__initializeSource",0xb57a50c2,"lime.text.Font.__initializeSource","lime/text/Font.hx",468,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_495___loadFromName,"lime.text.Font","__loadFromName",0x6b610412,"lime.text.Font.__loadFromName","lime/text/Font.hx",495,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_592___setSize,"lime.text.Font","__setSize",0x86a86dec,"lime.text.Font.__setSize","lime/text/Font.hx",592,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_120_fromBytes,"lime.text.Font","fromBytes",0x65a32e2a,"lime.text.Font.fromBytes","lime/text/Font.hx",120,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_134_fromFile,"lime.text.Font","fromFile",0x07a4e59d,"lime.text.Font.fromFile","lime/text/Font.hx",134,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_149_loadFromBytes,"lime.text.Font","loadFromBytes",0x5727f7a4,"lime.text.Font.loadFromBytes","lime/text/Font.hx",149,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_157_loadFromFile,"lime.text.Font","loadFromFile",0x5ed36963,"lime.text.Font.loadFromFile","lime/text/Font.hx",157,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_153_loadFromFile,"lime.text.Font","loadFromFile",0x5ed36963,"lime.text.Font.loadFromFile","lime/text/Font.hx",153,0x3be57807) HX_LOCAL_STACK_FRAME(_hx_pos_51012fd6257f8a4a_174_loadFromName,"lime.text.Font","loadFromName",0x64170d32,"lime.text.Font.loadFromName","lime/text/Font.hx",174,0x3be57807) namespace lime{ namespace text{ void Font_obj::__construct(::String name){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_54_new) HXLINE( 55) if (hx::IsNotNull( name )) { HXLINE( 57) this->name = name; } HXLINE( 60) if (!(this->_hx___init)) { HXLINE( 62) this->ascender = 0; HXLINE( 66) this->descender = 0; HXLINE( 70) this->height = 0; HXLINE( 74) this->numGlyphs = 0; HXLINE( 78) this->underlinePosition = 0; HXLINE( 82) this->underlineThickness = 0; HXLINE( 86) this->unitsPerEM = 0; HXLINE( 88) if (hx::IsNotNull( this->_hx___fontID )) { HXLINE( 90) if (::lime::utils::Assets_obj::isLocal(this->_hx___fontID,null(),null())) { HXLINE( 92) this->_hx___fromBytes(::lime::utils::Assets_obj::getBytes(this->_hx___fontID)); } } else { HXLINE( 95) if (hx::IsNotNull( this->_hx___fontPath )) { HXLINE( 97) this->_hx___fromFile(this->_hx___fontPath); } } } } Dynamic Font_obj::__CreateEmpty() { return new Font_obj; } void *Font_obj::_hx_vtable = 0; Dynamic Font_obj::__Create(hx::DynamicArray inArgs) { hx::ObjectPtr< Font_obj > _hx_result = new Font_obj(); _hx_result->__construct(inArgs[0]); return _hx_result; } bool Font_obj::_hx_isInstanceOf(int inClassId) { return inClassId==(int)0x00000001 || inClassId==(int)0x6aed2e71; } ::Dynamic Font_obj::decompose(){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_103_decompose) HXLINE( 105) if (hx::IsNull( this->src )) { HXLINE( 105) HX_STACK_DO_THROW(HX_("Uninitialized font handle.",3a,84,ab,29)); } HXLINE( 106) ::Dynamic data = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_outline_decompose(hx::DynamicPtr(this->src),20480)) ); HXLINE( 113) return data; } HX_DEFINE_DYNAMIC_FUNC0(Font_obj,decompose,return ) int Font_obj::getGlyph(::String character){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_181_getGlyph) HXDLIN( 181) return ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_glyph_index(hx::DynamicPtr(this->src),character); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,getGlyph,return ) ::Array< int > Font_obj::getGlyphs(::String __o_characters){ ::String characters = __o_characters; if (hx::IsNull(__o_characters)) characters = HX_("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^`'\"/\\&*()[]{}<>|:;_-+=?,. ",c1,f6,34,50); HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_188_getGlyphs) HXLINE( 190) ::Dynamic glyphs = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_glyph_indices(hx::DynamicPtr(this->src),characters)) ); HXLINE( 191) return ( (::Array< int >)(glyphs) ); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,getGlyphs,return ) ::lime::text::GlyphMetrics Font_obj::getGlyphMetrics(int glyph){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_198_getGlyphMetrics) HXLINE( 200) ::Dynamic value = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_glyph_metrics(hx::DynamicPtr(this->src),glyph)) ); HXLINE( 201) ::lime::text::GlyphMetrics metrics = ::lime::text::GlyphMetrics_obj::__alloc( HX_CTX ); HXLINE( 203) metrics->advance = ::lime::math::Vector2_obj::__alloc( HX_CTX ,value->__Field(HX_("horizontalAdvance",fe,57,3e,ce),hx::paccDynamic),value->__Field(HX_("verticalAdvance",ac,8e,f7,57),hx::paccDynamic)); HXLINE( 204) metrics->height = ( (int)(value->__Field(HX_("height",e7,07,4c,02),hx::paccDynamic)) ); HXLINE( 205) metrics->horizontalBearing = ::lime::math::Vector2_obj::__alloc( HX_CTX ,value->__Field(HX_("horizontalBearingX",ae,21,22,6c),hx::paccDynamic),value->__Field(HX_("horizontalBearingY",af,21,22,6c),hx::paccDynamic)); HXLINE( 206) metrics->verticalBearing = ::lime::math::Vector2_obj::__alloc( HX_CTX ,value->__Field(HX_("verticalBearingX",40,c3,78,64),hx::paccDynamic),value->__Field(HX_("verticalBearingY",41,c3,78,64),hx::paccDynamic)); HXLINE( 208) return metrics; } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,getGlyphMetrics,return ) ::lime::graphics::Image Font_obj::renderGlyph(int glyph,int fontSize){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_215_renderGlyph) HXLINE( 217) this->_hx___setSize(fontSize); HXLINE( 219) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(0); HXLINE( 222) int dataPosition = 0; HXLINE( 223) bytes = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_render_glyph(hx::DynamicPtr(this->src),glyph,hx::DynamicPtr(bytes))) ); HXLINE( 225) bool _hx_tmp; HXDLIN( 225) if (hx::IsNotNull( bytes )) { HXLINE( 225) _hx_tmp = (bytes->length > 0); } else { HXLINE( 225) _hx_tmp = false; } HXDLIN( 225) if (_hx_tmp) { HXLINE( 227) int index = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 228) dataPosition = (dataPosition + 4); HXLINE( 229) int width = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 230) dataPosition = (dataPosition + 4); HXLINE( 231) int height = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 232) dataPosition = (dataPosition + 4); HXLINE( 233) int x = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 234) dataPosition = (dataPosition + 4); HXLINE( 235) int y = (((( (int)(bytes->b->__get(dataPosition)) ) | (( (int)(bytes->b->__get((dataPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((dataPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((dataPosition + 3))) ) << 24)); HXLINE( 236) dataPosition = (dataPosition + 4); HXLINE( 238) ::haxe::io::Bytes data = bytes->sub(dataPosition,(width * height)); HXLINE( 239) dataPosition = (dataPosition + (width * height)); HXLINE( 241) ::lime::utils::ArrayBufferView this1; HXDLIN( 241) if (hx::IsNotNull( data )) { HXLINE( 241) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 241) int in_byteOffset = 0; HXDLIN( 241) if ((in_byteOffset < 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 241) if ((hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 241) int bufferByteLength = data->length; HXDLIN( 241) int elementSize = _this->bytesPerElement; HXDLIN( 241) int newByteLength = bufferByteLength; HXDLIN( 241) { HXLINE( 241) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 241) if ((hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 241) if ((newByteLength < 0)) { HXLINE( 241) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } } HXDLIN( 241) _this->buffer = data; HXDLIN( 241) _this->byteOffset = in_byteOffset; HXDLIN( 241) _this->byteLength = newByteLength; HXDLIN( 241) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 241) this1 = _this; } else { HXLINE( 241) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85)); } HXDLIN( 241) ::lime::graphics::ImageBuffer buffer = ::lime::graphics::ImageBuffer_obj::__alloc( HX_CTX ,this1,width,height,8,null()); HXLINE( 242) ::lime::graphics::Image image = ::lime::graphics::Image_obj::__alloc( HX_CTX ,buffer,0,0,width,height,null(),null()); HXLINE( 243) image->x = ( (Float)(x) ); HXLINE( 244) image->y = ( (Float)(y) ); HXLINE( 246) return image; } HXLINE( 250) return null(); } HX_DEFINE_DYNAMIC_FUNC2(Font_obj,renderGlyph,return ) ::haxe::ds::IntMap Font_obj::renderGlyphs(::Array< int > glyphs,int fontSize){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_254_renderGlyphs) HXLINE( 256) ::haxe::ds::IntMap uniqueGlyphs = ::haxe::ds::IntMap_obj::__alloc( HX_CTX ); HXLINE( 258) { HXLINE( 258) int _g = 0; HXDLIN( 258) while((_g < glyphs->length)){ HXLINE( 258) int glyph = glyphs->__get(_g); HXDLIN( 258) _g = (_g + 1); HXLINE( 260) uniqueGlyphs->set(glyph,true); } } HXLINE( 263) ::Array< int > glyphList = ::Array_obj< int >::__new(0); HXLINE( 265) { HXLINE( 265) ::Dynamic key = uniqueGlyphs->keys(); HXDLIN( 265) while(( (bool)(key->__Field(HX_("hasNext",6d,a5,46,18),hx::paccDynamic)()) )){ HXLINE( 265) int key1 = ( (int)(key->__Field(HX_("next",f3,84,02,49),hx::paccDynamic)()) ); HXLINE( 267) glyphList->push(key1); } } HXLINE( 281) ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_set_size(hx::DynamicPtr(this->src),fontSize); HXLINE( 283) ::haxe::io::Bytes bytes = ::haxe::io::Bytes_obj::alloc(0); HXLINE( 284) bytes = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_render_glyphs(hx::DynamicPtr(this->src),hx::DynamicPtr(glyphList),hx::DynamicPtr(bytes))) ); HXLINE( 286) bool _hx_tmp; HXDLIN( 286) if (hx::IsNotNull( bytes )) { HXLINE( 286) _hx_tmp = (bytes->length > 0); } else { HXLINE( 286) _hx_tmp = false; } HXDLIN( 286) if (_hx_tmp) { HXLINE( 288) int bytesPosition = 0; HXLINE( 289) int count = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 290) bytesPosition = (bytesPosition + 4); HXLINE( 292) int bufferWidth = 128; HXLINE( 293) int bufferHeight = 128; HXLINE( 294) int offsetX = 0; HXLINE( 295) int offsetY = 0; HXLINE( 296) int maxRows = 0; HXLINE( 298) int width; HXDLIN( 298) int height; HXLINE( 299) int i = 0; HXLINE( 301) while((i < count)){ HXLINE( 303) bytesPosition = (bytesPosition + 4); HXLINE( 304) width = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 305) bytesPosition = (bytesPosition + 4); HXLINE( 306) height = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 307) bytesPosition = (bytesPosition + 4); HXLINE( 309) bytesPosition = (bytesPosition + (8 + (width * height))); HXLINE( 311) if (((offsetX + width) > bufferWidth)) { HXLINE( 313) offsetY = (offsetY + (maxRows + 1)); HXLINE( 314) offsetX = 0; HXLINE( 315) maxRows = 0; } HXLINE( 318) if (((offsetY + height) > bufferHeight)) { HXLINE( 320) if ((bufferWidth < bufferHeight)) { HXLINE( 322) bufferWidth = (bufferWidth * 2); } else { HXLINE( 326) bufferHeight = (bufferHeight * 2); } HXLINE( 329) offsetX = 0; HXLINE( 330) offsetY = 0; HXLINE( 331) maxRows = 0; HXLINE( 335) bytesPosition = 4; HXLINE( 336) i = 0; HXLINE( 337) continue; } HXLINE( 340) offsetX = (offsetX + (width + 1)); HXLINE( 342) if ((height > maxRows)) { HXLINE( 344) maxRows = height; } HXLINE( 347) i = (i + 1); } HXLINE( 350) ::haxe::ds::IntMap map = ::haxe::ds::IntMap_obj::__alloc( HX_CTX ); HXLINE( 351) ::lime::graphics::ImageBuffer buffer = ::lime::graphics::ImageBuffer_obj::__alloc( HX_CTX ,null(),bufferWidth,bufferHeight,8,null()); HXLINE( 352) int dataPosition = 0; HXLINE( 353) ::haxe::io::Bytes data = ::haxe::io::Bytes_obj::alloc((bufferWidth * bufferHeight)); HXLINE( 355) bytesPosition = 4; HXLINE( 356) offsetX = 0; HXLINE( 357) offsetY = 0; HXLINE( 358) maxRows = 0; HXLINE( 360) int index; HXDLIN( 360) int x; HXDLIN( 360) int y; HXDLIN( 360) ::lime::graphics::Image image; HXLINE( 362) { HXLINE( 362) int _g1 = 0; HXDLIN( 362) int _g2 = count; HXDLIN( 362) while((_g1 < _g2)){ HXLINE( 362) _g1 = (_g1 + 1); HXDLIN( 362) int i1 = (_g1 - 1); HXLINE( 364) index = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 365) bytesPosition = (bytesPosition + 4); HXLINE( 366) width = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 367) bytesPosition = (bytesPosition + 4); HXLINE( 368) height = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 369) bytesPosition = (bytesPosition + 4); HXLINE( 370) x = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 371) bytesPosition = (bytesPosition + 4); HXLINE( 372) y = (((( (int)(bytes->b->__get(bytesPosition)) ) | (( (int)(bytes->b->__get((bytesPosition + 1))) ) << 8)) | (( (int)(bytes->b->__get((bytesPosition + 2))) ) << 16)) | (( (int)(bytes->b->__get((bytesPosition + 3))) ) << 24)); HXLINE( 373) bytesPosition = (bytesPosition + 4); HXLINE( 375) if (((offsetX + width) > bufferWidth)) { HXLINE( 377) offsetY = (offsetY + (maxRows + 1)); HXLINE( 378) offsetX = 0; HXLINE( 379) maxRows = 0; } HXLINE( 382) { HXLINE( 382) int _g11 = 0; HXDLIN( 382) int _g21 = height; HXDLIN( 382) while((_g11 < _g21)){ HXLINE( 382) _g11 = (_g11 + 1); HXDLIN( 382) int i2 = (_g11 - 1); HXLINE( 384) dataPosition = (((i2 + offsetY) * bufferWidth) + offsetX); HXLINE( 385) data->blit(dataPosition,bytes,bytesPosition,width); HXLINE( 386) bytesPosition = (bytesPosition + width); } } HXLINE( 389) image = ::lime::graphics::Image_obj::__alloc( HX_CTX ,buffer,offsetX,offsetY,width,height,null(),null()); HXLINE( 390) image->x = ( (Float)(x) ); HXLINE( 391) image->y = ( (Float)(y) ); HXLINE( 393) map->set(index,image); HXLINE( 395) offsetX = (offsetX + (width + 1)); HXLINE( 397) if ((height > maxRows)) { HXLINE( 399) maxRows = height; } } } HXLINE( 406) ::lime::utils::ArrayBufferView this1; HXDLIN( 406) if (hx::IsNotNull( data )) { HXLINE( 406) ::lime::utils::ArrayBufferView _this = ::lime::utils::ArrayBufferView_obj::__alloc( HX_CTX ,0,4); HXDLIN( 406) int in_byteOffset = 0; HXDLIN( 406) if ((in_byteOffset < 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 406) if ((hx::Mod(in_byteOffset,_this->bytesPerElement) != 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 406) int bufferByteLength = data->length; HXDLIN( 406) int elementSize = _this->bytesPerElement; HXDLIN( 406) int newByteLength = bufferByteLength; HXDLIN( 406) { HXLINE( 406) newByteLength = (bufferByteLength - in_byteOffset); HXDLIN( 406) if ((hx::Mod(bufferByteLength,_this->bytesPerElement) != 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } HXDLIN( 406) if ((newByteLength < 0)) { HXLINE( 406) HX_STACK_DO_THROW(::lime::utils::TAError_obj::RangeError_dyn()); } } HXDLIN( 406) _this->buffer = data; HXDLIN( 406) _this->byteOffset = in_byteOffset; HXDLIN( 406) _this->byteLength = newByteLength; HXDLIN( 406) _this->length = ::Std_obj::_hx_int((( (Float)(newByteLength) ) / ( (Float)(_this->bytesPerElement) ))); HXDLIN( 406) this1 = _this; } else { HXLINE( 406) HX_STACK_DO_THROW(HX_("Invalid constructor arguments for UInt8Array",6b,44,d5,85)); } HXDLIN( 406) buffer->data = this1; HXLINE( 409) return map; } HXLINE( 413) return null(); } HX_DEFINE_DYNAMIC_FUNC2(Font_obj,renderGlyphs,return ) void Font_obj::_hx___copyFrom( ::lime::text::Font other){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_418___copyFrom) HXDLIN( 418) if (hx::IsNotNull( other )) { HXLINE( 420) this->ascender = other->ascender; HXLINE( 421) this->descender = other->descender; HXLINE( 422) this->height = other->height; HXLINE( 423) this->name = other->name; HXLINE( 424) this->numGlyphs = other->numGlyphs; HXLINE( 425) this->src = other->src; HXLINE( 426) this->underlinePosition = other->underlinePosition; HXLINE( 427) this->underlineThickness = other->underlineThickness; HXLINE( 428) this->unitsPerEM = other->unitsPerEM; HXLINE( 430) this->_hx___fontID = other->_hx___fontID; HXLINE( 431) this->_hx___fontPath = other->_hx___fontPath; HXLINE( 434) this->_hx___fontPathWithoutDirectory = other->_hx___fontPathWithoutDirectory; HXLINE( 437) this->_hx___init = true; } } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___copyFrom,(void)) void Font_obj::_hx___fromBytes( ::haxe::io::Bytes bytes){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_442___fromBytes) HXLINE( 443) this->_hx___fontPath = null(); HXLINE( 446) this->_hx___fontPathWithoutDirectory = null(); HXLINE( 448) this->src = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_load_bytes(hx::DynamicPtr(bytes))) ); HXLINE( 450) this->_hx___initializeSource(); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___fromBytes,(void)) void Font_obj::_hx___fromFile(::String path){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_455___fromFile) HXLINE( 456) this->_hx___fontPath = path; HXLINE( 459) this->_hx___fontPathWithoutDirectory = ::haxe::io::Path_obj::withoutDirectory(this->_hx___fontPath); HXLINE( 461) this->src = ( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_load_file(hx::DynamicPtr(this->_hx___fontPath))) ); HXLINE( 463) this->_hx___initializeSource(); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___fromFile,(void)) void Font_obj::_hx___initializeSource(){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_468___initializeSource) HXLINE( 470) if (hx::IsNotNull( this->src )) { HXLINE( 472) if (hx::IsNull( this->name )) { HXLINE( 477) this->name = ( (::String)(( ( ::Dynamic)(::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_family_name(hx::DynamicPtr(this->src))) )) ); } HXLINE( 481) this->ascender = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_ascender(hx::DynamicPtr(this->src)); HXLINE( 482) this->descender = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_descender(hx::DynamicPtr(this->src)); HXLINE( 483) this->height = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_height(hx::DynamicPtr(this->src)); HXLINE( 484) this->numGlyphs = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_num_glyphs(hx::DynamicPtr(this->src)); HXLINE( 485) this->underlinePosition = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_underline_position(hx::DynamicPtr(this->src)); HXLINE( 486) this->underlineThickness = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_underline_thickness(hx::DynamicPtr(this->src)); HXLINE( 487) this->unitsPerEM = ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_get_units_per_em(hx::DynamicPtr(this->src)); } HXLINE( 491) this->_hx___init = true; } HX_DEFINE_DYNAMIC_FUNC0(Font_obj,_hx___initializeSource,(void)) ::lime::app::Future Font_obj::_hx___loadFromName(::String name){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_495___loadFromName) HXLINE( 496) ::lime::app::Promise_lime_text_Font promise = ::lime::app::Promise_lime_text_Font_obj::__alloc( HX_CTX ); HXLINE( 557) promise->error(HX_("",00,00,00,00)); HXLINE( 560) return promise->future; } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___loadFromName,return ) void Font_obj::_hx___setSize(int size){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_592___setSize) HXDLIN( 592) ::lime::_internal::backend::native::NativeCFFI_obj::lime_font_set_size(hx::DynamicPtr(this->src),size); } HX_DEFINE_DYNAMIC_FUNC1(Font_obj,_hx___setSize,(void)) ::lime::text::Font Font_obj::fromBytes( ::haxe::io::Bytes bytes){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_120_fromBytes) HXLINE( 121) if (hx::IsNull( bytes )) { HXLINE( 121) return null(); } HXLINE( 123) ::lime::text::Font font = ::lime::text::Font_obj::__alloc( HX_CTX ,null()); HXLINE( 124) font->_hx___fromBytes(bytes); HXLINE( 127) if (hx::IsNotNull( font->src )) { HXLINE( 127) return font; } else { HXLINE( 127) return null(); } HXDLIN( 127) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,fromBytes,return ) ::lime::text::Font Font_obj::fromFile(::String path){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_134_fromFile) HXLINE( 135) if (hx::IsNull( path )) { HXLINE( 135) return null(); } HXLINE( 137) ::lime::text::Font font = ::lime::text::Font_obj::__alloc( HX_CTX ,null()); HXLINE( 138) font->_hx___fromFile(path); HXLINE( 141) if (hx::IsNotNull( font->src )) { HXLINE( 141) return font; } else { HXLINE( 141) return null(); } HXDLIN( 141) return null(); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,fromFile,return ) ::lime::app::Future Font_obj::loadFromBytes( ::haxe::io::Bytes bytes){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_149_loadFromBytes) HXDLIN( 149) return ::lime::app::Future_obj::withValue(::lime::text::Font_obj::fromBytes(bytes)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,loadFromBytes,return ) ::lime::app::Future Font_obj::loadFromFile(::String path){ HX_BEGIN_LOCAL_FUNC_S0(hx::LocalFunc,_hx_Closure_0) HXARGC(1) ::lime::app::Future _hx_run( ::lime::text::Font font){ HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_157_loadFromFile) HXLINE( 157) if (hx::IsNotNull( font )) { HXLINE( 159) return ::lime::app::Future_obj::withValue(font); } else { HXLINE( 163) return ::lime::app::Future_obj::withError(HX_("",00,00,00,00)); } HXLINE( 157) return null(); } HX_END_LOCAL_FUNC1(return) HX_GC_STACKFRAME(&_hx_pos_51012fd6257f8a4a_153_loadFromFile) HXLINE( 154) ::lime::net::_HTTPRequest_lime_text_Font request = ::lime::net::_HTTPRequest_lime_text_Font_obj::__alloc( HX_CTX ,null()); HXLINE( 155) return request->load(path)->then( ::Dynamic(new _hx_Closure_0())); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,loadFromFile,return ) ::lime::app::Future Font_obj::loadFromName(::String path){ HX_STACKFRAME(&_hx_pos_51012fd6257f8a4a_174_loadFromName) HXDLIN( 174) return ::lime::app::Future_obj::withError(HX_("",00,00,00,00)); } STATIC_HX_DEFINE_DYNAMIC_FUNC1(Font_obj,loadFromName,return ) hx::ObjectPtr< Font_obj > Font_obj::__new(::String name) { hx::ObjectPtr< Font_obj > __this = new Font_obj(); __this->__construct(name); return __this; } hx::ObjectPtr< Font_obj > Font_obj::__alloc(hx::Ctx *_hx_ctx,::String name) { Font_obj *__this = (Font_obj*)(hx::Ctx::alloc(_hx_ctx, sizeof(Font_obj), true, "lime.text.Font")); *(void **)__this = Font_obj::_hx_vtable; __this->__construct(name); return __this; } Font_obj::Font_obj() { } void Font_obj::__Mark(HX_MARK_PARAMS) { HX_MARK_BEGIN_CLASS(Font); HX_MARK_MEMBER_NAME(ascender,"ascender"); HX_MARK_MEMBER_NAME(descender,"descender"); HX_MARK_MEMBER_NAME(height,"height"); HX_MARK_MEMBER_NAME(name,"name"); HX_MARK_MEMBER_NAME(numGlyphs,"numGlyphs"); HX_MARK_MEMBER_NAME(src,"src"); HX_MARK_MEMBER_NAME(underlinePosition,"underlinePosition"); HX_MARK_MEMBER_NAME(underlineThickness,"underlineThickness"); HX_MARK_MEMBER_NAME(unitsPerEM,"unitsPerEM"); HX_MARK_MEMBER_NAME(_hx___fontID,"__fontID"); HX_MARK_MEMBER_NAME(_hx___fontPath,"__fontPath"); HX_MARK_MEMBER_NAME(_hx___fontPathWithoutDirectory,"__fontPathWithoutDirectory"); HX_MARK_MEMBER_NAME(_hx___init,"__init"); HX_MARK_END_CLASS(); } void Font_obj::__Visit(HX_VISIT_PARAMS) { HX_VISIT_MEMBER_NAME(ascender,"ascender"); HX_VISIT_MEMBER_NAME(descender,"descender"); HX_VISIT_MEMBER_NAME(height,"height"); HX_VISIT_MEMBER_NAME(name,"name"); HX_VISIT_MEMBER_NAME(numGlyphs,"numGlyphs"); HX_VISIT_MEMBER_NAME(src,"src"); HX_VISIT_MEMBER_NAME(underlinePosition,"underlinePosition"); HX_VISIT_MEMBER_NAME(underlineThickness,"underlineThickness"); HX_VISIT_MEMBER_NAME(unitsPerEM,"unitsPerEM"); HX_VISIT_MEMBER_NAME(_hx___fontID,"__fontID"); HX_VISIT_MEMBER_NAME(_hx___fontPath,"__fontPath"); HX_VISIT_MEMBER_NAME(_hx___fontPathWithoutDirectory,"__fontPathWithoutDirectory"); HX_VISIT_MEMBER_NAME(_hx___init,"__init"); } hx::Val Font_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"src") ) { return hx::Val( src ); } break; case 4: if (HX_FIELD_EQ(inName,"name") ) { return hx::Val( name ); } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { return hx::Val( height ); } if (HX_FIELD_EQ(inName,"__init") ) { return hx::Val( _hx___init ); } break; case 8: if (HX_FIELD_EQ(inName,"ascender") ) { return hx::Val( ascender ); } if (HX_FIELD_EQ(inName,"__fontID") ) { return hx::Val( _hx___fontID ); } if (HX_FIELD_EQ(inName,"getGlyph") ) { return hx::Val( getGlyph_dyn() ); } break; case 9: if (HX_FIELD_EQ(inName,"descender") ) { return hx::Val( descender ); } if (HX_FIELD_EQ(inName,"numGlyphs") ) { return hx::Val( numGlyphs ); } if (HX_FIELD_EQ(inName,"decompose") ) { return hx::Val( decompose_dyn() ); } if (HX_FIELD_EQ(inName,"getGlyphs") ) { return hx::Val( getGlyphs_dyn() ); } if (HX_FIELD_EQ(inName,"__setSize") ) { return hx::Val( _hx___setSize_dyn() ); } break; case 10: if (HX_FIELD_EQ(inName,"unitsPerEM") ) { return hx::Val( unitsPerEM ); } if (HX_FIELD_EQ(inName,"__fontPath") ) { return hx::Val( _hx___fontPath ); } if (HX_FIELD_EQ(inName,"__copyFrom") ) { return hx::Val( _hx___copyFrom_dyn() ); } if (HX_FIELD_EQ(inName,"__fromFile") ) { return hx::Val( _hx___fromFile_dyn() ); } break; case 11: if (HX_FIELD_EQ(inName,"renderGlyph") ) { return hx::Val( renderGlyph_dyn() ); } if (HX_FIELD_EQ(inName,"__fromBytes") ) { return hx::Val( _hx___fromBytes_dyn() ); } break; case 12: if (HX_FIELD_EQ(inName,"renderGlyphs") ) { return hx::Val( renderGlyphs_dyn() ); } break; case 14: if (HX_FIELD_EQ(inName,"__loadFromName") ) { return hx::Val( _hx___loadFromName_dyn() ); } break; case 15: if (HX_FIELD_EQ(inName,"getGlyphMetrics") ) { return hx::Val( getGlyphMetrics_dyn() ); } break; case 17: if (HX_FIELD_EQ(inName,"underlinePosition") ) { return hx::Val( underlinePosition ); } break; case 18: if (HX_FIELD_EQ(inName,"underlineThickness") ) { return hx::Val( underlineThickness ); } if (HX_FIELD_EQ(inName,"__initializeSource") ) { return hx::Val( _hx___initializeSource_dyn() ); } break; case 26: if (HX_FIELD_EQ(inName,"__fontPathWithoutDirectory") ) { return hx::Val( _hx___fontPathWithoutDirectory ); } } return super::__Field(inName,inCallProp); } bool Font_obj::__GetStatic(const ::String &inName, Dynamic &outValue, hx::PropertyAccess inCallProp) { switch(inName.length) { case 8: if (HX_FIELD_EQ(inName,"fromFile") ) { outValue = fromFile_dyn(); return true; } break; case 9: if (HX_FIELD_EQ(inName,"fromBytes") ) { outValue = fromBytes_dyn(); return true; } break; case 12: if (HX_FIELD_EQ(inName,"loadFromFile") ) { outValue = loadFromFile_dyn(); return true; } if (HX_FIELD_EQ(inName,"loadFromName") ) { outValue = loadFromName_dyn(); return true; } break; case 13: if (HX_FIELD_EQ(inName,"loadFromBytes") ) { outValue = loadFromBytes_dyn(); return true; } } return false; } hx::Val Font_obj::__SetField(const ::String &inName,const hx::Val &inValue,hx::PropertyAccess inCallProp) { switch(inName.length) { case 3: if (HX_FIELD_EQ(inName,"src") ) { src=inValue.Cast< ::Dynamic >(); return inValue; } break; case 4: if (HX_FIELD_EQ(inName,"name") ) { name=inValue.Cast< ::String >(); return inValue; } break; case 6: if (HX_FIELD_EQ(inName,"height") ) { height=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"__init") ) { _hx___init=inValue.Cast< bool >(); return inValue; } break; case 8: if (HX_FIELD_EQ(inName,"ascender") ) { ascender=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"__fontID") ) { _hx___fontID=inValue.Cast< ::String >(); return inValue; } break; case 9: if (HX_FIELD_EQ(inName,"descender") ) { descender=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"numGlyphs") ) { numGlyphs=inValue.Cast< int >(); return inValue; } break; case 10: if (HX_FIELD_EQ(inName,"unitsPerEM") ) { unitsPerEM=inValue.Cast< int >(); return inValue; } if (HX_FIELD_EQ(inName,"__fontPath") ) { _hx___fontPath=inValue.Cast< ::String >(); return inValue; } break; case 17: if (HX_FIELD_EQ(inName,"underlinePosition") ) { underlinePosition=inValue.Cast< int >(); return inValue; } break; case 18: if (HX_FIELD_EQ(inName,"underlineThickness") ) { underlineThickness=inValue.Cast< int >(); return inValue; } break; case 26: if (HX_FIELD_EQ(inName,"__fontPathWithoutDirectory") ) { _hx___fontPathWithoutDirectory=inValue.Cast< ::String >(); return inValue; } } return super::__SetField(inName,inValue,inCallProp); } void Font_obj::__GetFields(Array< ::String> &outFields) { outFields->push(HX_("ascender",37,98,10,60)); outFields->push(HX_("descender",17,65,27,ab)); outFields->push(HX_("height",e7,07,4c,02)); outFields->push(HX_("name",4b,72,ff,48)); outFields->push(HX_("numGlyphs",2d,44,5a,5f)); outFields->push(HX_("src",e4,a6,57,00)); outFields->push(HX_("underlinePosition",d5,5d,6b,96)); outFields->push(HX_("underlineThickness",c8,ba,9b,91)); outFields->push(HX_("unitsPerEM",96,b6,60,21)); outFields->push(HX_("__fontID",8a,5a,1e,a3)); outFields->push(HX_("__fontPath",34,76,08,70)); outFields->push(HX_("__fontPathWithoutDirectory",59,11,28,91)); outFields->push(HX_("__init",30,9e,b3,f4)); super::__GetFields(outFields); }; #ifdef HXCPP_SCRIPTABLE static hx::StorageInfo Font_obj_sMemberStorageInfo[] = { {hx::fsInt,(int)offsetof(Font_obj,ascender),HX_("ascender",37,98,10,60)}, {hx::fsInt,(int)offsetof(Font_obj,descender),HX_("descender",17,65,27,ab)}, {hx::fsInt,(int)offsetof(Font_obj,height),HX_("height",e7,07,4c,02)}, {hx::fsString,(int)offsetof(Font_obj,name),HX_("name",4b,72,ff,48)}, {hx::fsInt,(int)offsetof(Font_obj,numGlyphs),HX_("numGlyphs",2d,44,5a,5f)}, {hx::fsObject /* ::Dynamic */ ,(int)offsetof(Font_obj,src),HX_("src",e4,a6,57,00)}, {hx::fsInt,(int)offsetof(Font_obj,underlinePosition),HX_("underlinePosition",d5,5d,6b,96)}, {hx::fsInt,(int)offsetof(Font_obj,underlineThickness),HX_("underlineThickness",c8,ba,9b,91)}, {hx::fsInt,(int)offsetof(Font_obj,unitsPerEM),HX_("unitsPerEM",96,b6,60,21)}, {hx::fsString,(int)offsetof(Font_obj,_hx___fontID),HX_("__fontID",8a,5a,1e,a3)}, {hx::fsString,(int)offsetof(Font_obj,_hx___fontPath),HX_("__fontPath",34,76,08,70)}, {hx::fsString,(int)offsetof(Font_obj,_hx___fontPathWithoutDirectory),HX_("__fontPathWithoutDirectory",59,11,28,91)}, {hx::fsBool,(int)offsetof(Font_obj,_hx___init),HX_("__init",30,9e,b3,f4)}, { hx::fsUnknown, 0, null()} }; static hx::StaticInfo *Font_obj_sStaticStorageInfo = 0; #endif static ::String Font_obj_sMemberFields[] = { HX_("ascender",37,98,10,60), HX_("descender",17,65,27,ab), HX_("height",e7,07,4c,02), HX_("name",4b,72,ff,48), HX_("numGlyphs",2d,44,5a,5f), HX_("src",e4,a6,57,00), HX_("underlinePosition",d5,5d,6b,96), HX_("underlineThickness",c8,ba,9b,91), HX_("unitsPerEM",96,b6,60,21), HX_("__fontID",8a,5a,1e,a3), HX_("__fontPath",34,76,08,70), HX_("__fontPathWithoutDirectory",59,11,28,91), HX_("__init",30,9e,b3,f4), HX_("decompose",b1,c3,a7,7a), HX_("getGlyph",36,0d,dc,f5), HX_("getGlyphs",7d,82,af,2a), HX_("getGlyphMetrics",ad,6f,39,58), HX_("renderGlyph",76,2a,b6,61), HX_("renderGlyphs",3d,fd,ae,1d), HX_("__copyFrom",df,7e,99,6b), HX_("__fromBytes",81,3b,4d,a0), HX_("__fromFile",26,10,c0,44), HX_("__initializeSource",6b,c5,c1,17), HX_("__loadFromName",3b,b0,f4,80), HX_("__setSize",63,32,26,93), ::String(null()) }; hx::Class Font_obj::__mClass; static ::String Font_obj_sStaticFields[] = { HX_("fromBytes",a1,f2,20,72), HX_("fromFile",06,9d,87,a1), HX_("loadFromBytes",9b,c3,86,f4), HX_("loadFromFile",4c,89,f0,5a), HX_("loadFromName",1b,2d,34,60), ::String(null()) }; void Font_obj::__register() { Font_obj _hx_dummy; Font_obj::_hx_vtable = *(void **)&_hx_dummy; hx::Static(__mClass) = new hx::Class_obj(); __mClass->mName = HX_("lime.text.Font",b7,86,7e,d1); __mClass->mSuper = &super::__SGetClass(); __mClass->mConstructEmpty = &__CreateEmpty; __mClass->mConstructArgs = &__Create; __mClass->mGetStaticField = &Font_obj::__GetStatic; __mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField; __mClass->mStatics = hx::Class_obj::dupFunctions(Font_obj_sStaticFields); __mClass->mMembers = hx::Class_obj::dupFunctions(Font_obj_sMemberFields); __mClass->mCanCast = hx::TCanCast< Font_obj >; #ifdef HXCPP_SCRIPTABLE __mClass->mMemberStorageInfo = Font_obj_sMemberStorageInfo; #endif #ifdef HXCPP_SCRIPTABLE __mClass->mStaticStorageInfo = Font_obj_sStaticStorageInfo; #endif hx::_hx_RegisterClass(__mClass->mName, __mClass); } } // end namespace lime } // end namespace text
47.970203
248
0.682014
arturspon
dde40449f8455a3781147ccc19987bfef51bcdaf
73
cpp
C++
LearningOpenGL/Source/Core/Material/Material.cpp
zhengweifu/LearningOpenGL
0d73b035ffa11112d62f0af974f4a8622eef6598
[ "MIT" ]
null
null
null
LearningOpenGL/Source/Core/Material/Material.cpp
zhengweifu/LearningOpenGL
0d73b035ffa11112d62f0af974f4a8622eef6598
[ "MIT" ]
null
null
null
LearningOpenGL/Source/Core/Material/Material.cpp
zhengweifu/LearningOpenGL
0d73b035ffa11112d62f0af974f4a8622eef6598
[ "MIT" ]
null
null
null
#include "Core/Material/Material.h" LEARN_OPENGL_BEGIN LEARN_OPENGL_END
14.6
35
0.849315
zhengweifu
ddeb3b3e963ca7fc1ade5249914d8461ee1b7e69
5,219
cpp
C++
hyperUI/source/StandardUI/UIRoundProgressElement.cpp
sadcatsoft/hyperui
f26242a9034ad1e0abf54bd7691fe48809262f5b
[ "MIT" ]
2
2019-05-17T16:16:21.000Z
2019-08-21T20:18:22.000Z
hyperUI/source/StandardUI/UIRoundProgressElement.cpp
sadcatsoft/hyperui
f26242a9034ad1e0abf54bd7691fe48809262f5b
[ "MIT" ]
1
2018-10-18T22:05:12.000Z
2018-10-18T22:05:12.000Z
hyperUI/source/StandardUI/UIRoundProgressElement.cpp
sadcatsoft/hyperui
f26242a9034ad1e0abf54bd7691fe48809262f5b
[ "MIT" ]
null
null
null
/***************************************************************************** Disclaimer: This software is supplied to you by Sad Cat Software ("Sad Cat") in consideration of your agreement to the following terms, and your use, installation, modification or redistribution of this Sad Cat software constitutes acceptance of these terms. If you do not agree with these terms, please do not use, install, modify or redistribute this Sad Cat software. This software is provided "as is". Sad Cat Software makes no warranties, express or implied, including without limitation the implied warranties of non-infringement, merchantability and fitness for a particular purpose, regarding Sad Cat's software or its use and operation alone or in combination with other hardware or software products. In no event shall Sad Cat Software be liable for any special, indirect, incidental, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) arising in any way out of the use, reproduction, modification and/or distribution of Sad Cat's software however caused and whether under theory of contract, tort (including negligence), strict liability or otherwise, even if Sad Cat Software has been advised of the possibility of such damage. Copyright (C) 2012, Sad Cat Software. All Rights Reserved. *****************************************************************************/ #include "stdafx.h" #define VALUE_ANIM_TIME 0.35 #define VALUE_ANIM_OFFSET_TIME 0.25 namespace HyperUI { /*****************************************************************************/ UIRoundProgressElement::UIRoundProgressElement(UIPlane* pParentPlane) : UIElement(pParentPlane) { onAllocated(pParentPlane); } /*****************************************************************************/ void UIRoundProgressElement::onAllocated(IBaseObject* pData) { UIElement::onAllocated(pData); myMinProgress = 0.0; myMaxProgress = 1.0; myCurrProgress = 0.0; myAnim.setNonAnimValue(0); } /*****************************************************************************/ void UIRoundProgressElement::stopCurrProgAnim() { GTIME lTime = Application::getInstance()->getGlobalTime(getClockType()); myAnim.setNonAnimValue(myAnim.getValue()); } /*****************************************************************************/ void UIRoundProgressElement::setProgress(FLOAT_TYPE fValue, bool bAnimated, FLOAT_TYPE fOverrideTime, bool bContinueFromCurrentAnim, FLOAT_TYPE fOffsetTime) { myCurrProgress = fValue; if(bAnimated) { if(bContinueFromCurrentAnim) { GTIME lTime = Application::getInstance()->getGlobalTime(getClockType()); FLOAT_TYPE fCurrVal = myAnim.getValue(); FLOAT_TYPE fFullTime = fOverrideTime > 0 ? fOverrideTime : VALUE_ANIM_TIME; FLOAT_TYPE fRemTime = fFullTime*(1.0 - fCurrVal); myAnim.setAnimation(fCurrVal, 1, fRemTime, getClockType()); //myAnim.setAnimation(fCurrVal, 1, fRemTime, getClockType(), AnimOverActionNone, NULL, fOffsetTime < 0 ? VALUE_ANIM_OFFSET_TIME : fOffsetTime); } else myAnim.setAnimation(0, 1, fOverrideTime > 0 ? fOverrideTime : VALUE_ANIM_TIME, getClockType()); //myAnim.setAnimation(0, 1, fOverrideTime > 0 ? fOverrideTime : VALUE_ANIM_TIME, getClockType(), AnimOverActionNone, NULL, fOffsetTime < 0 ? VALUE_ANIM_OFFSET_TIME : fOffsetTime); } else { myAnim.setNonAnimValue(1.0); } } /*****************************************************************************/ void UIRoundProgressElement::onPreRenderChildren(const SVector2D& svScroll, FLOAT_TYPE fOpacity, FLOAT_TYPE fScale) { UIElement::onPreRenderChildren(svScroll, fOpacity, fScale); SVector2D svPos; FLOAT_TYPE fFinalOpac, fLocScale; this->getLocalPosition(svPos, &fFinalOpac, &fLocScale); // , &fLocRotAngle); fFinalOpac *= fOpacity; svPos += svScroll; getDrawingCache()->flush(); // Render our actual progress GTIME lTime = Application::getInstance()->getGlobalTime(getClockType()); FLOAT_TYPE fAnim = myAnim.getValue(); renderProgressAnimInternal(svPos, fAnim, fFinalOpac, fScale); // Now render our top cap anim, if applicable: if(this->doesPropertyExist(PropertyCapImage)) { theCommonString = this->getStringProp(PropertyCapImage); getDrawingCache()->addSprite(theCommonString.c_str(), svPos.x, svPos.y, fFinalOpac, 0, fScale, 1.0, true); } } /*****************************************************************************/ void UIRoundProgressElement::renderProgressAnimInternal(SVector2D& svCenter, FLOAT_TYPE fAnimValue, FLOAT_TYPE fFinalOpacity, FLOAT_TYPE fScale) { FLOAT_TYPE fProgress = (myCurrProgress - myMinProgress)/(myMaxProgress - myMinProgress); fProgress *= fAnimValue; theCommonString = this->getStringProp(PropertyObjThirdAnim); FLOAT_TYPE fRadius = getTextureManager()->getFileWidth(theCommonString.c_str())*fScale*0.5; RenderUtils::renderCircularProgress(getParentWindow(), fProgress, theCommonString.c_str(), svCenter.x, svCenter.y, fRadius, fFinalOpacity); } /*****************************************************************************/ };
45.780702
183
0.659513
sadcatsoft
ddebca10b021a7199efef6f9a0c6c75f07d7e582
1,201
hpp
C++
gui/myscene.hpp
mguludag/QTextRecognizer
29dd7b746be831c01b6260ab20ca926f7ff835ca
[ "MIT" ]
25
2020-05-01T01:20:03.000Z
2022-01-19T02:48:12.000Z
gui/myscene.hpp
mguludag/QTextRecognizer
29dd7b746be831c01b6260ab20ca926f7ff835ca
[ "MIT" ]
null
null
null
gui/myscene.hpp
mguludag/QTextRecognizer
29dd7b746be831c01b6260ab20ca926f7ff835ca
[ "MIT" ]
7
2020-07-20T12:02:34.000Z
2022-01-06T03:09:31.000Z
#ifndef MYSCENE_HPP #define MYSCENE_HPP #include <QGraphicsScene> #include <QGraphicsSceneMouseEvent> #include <QMimeData> #include <QObject> #include <QUrl> #include <QWidget> class MyScene : public QGraphicsScene { Q_OBJECT struct Props { QPointF m_pos, m_topleft, m_bottomright; } Props; public: QString filename; explicit MyScene(QWidget *parent = nullptr); void mouseMoveEvent(QGraphicsSceneMouseEvent *event); void mousePressEvent(QGraphicsSceneMouseEvent *event); void mouseReleaseEvent(QGraphicsSceneMouseEvent *event); struct Props getProps() { return Props; } signals: void moveSignal(); void pressSignal(); void releaseSignal(); void drop(); public slots: protected: void dragEnterEvent(QGraphicsSceneDragDropEvent *event) { if (event->mimeData()->hasUrls()) { event->acceptProposedAction(); } } void dragMoveEvent(QGraphicsSceneDragDropEvent *) {} void dropEvent(QGraphicsSceneDragDropEvent *event) { filename = event->mimeData()->urls()[0].toLocalFile(); event->acceptProposedAction(); emit drop(); } private: }; #endif // MYSCENE_HPP
21.836364
62
0.68443
mguludag
ddf16c028182f525afa574368bb95a15376b0483
2,551
cpp
C++
Data Structures/Arrays/Dynamic Array.cpp
VaibhavDS19/Hackerrankchallenges
5207c4145547ad6707bb86f71c692be23445b56a
[ "MIT" ]
null
null
null
Data Structures/Arrays/Dynamic Array.cpp
VaibhavDS19/Hackerrankchallenges
5207c4145547ad6707bb86f71c692be23445b56a
[ "MIT" ]
null
null
null
Data Structures/Arrays/Dynamic Array.cpp
VaibhavDS19/Hackerrankchallenges
5207c4145547ad6707bb86f71c692be23445b56a
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; string ltrim(const string &); string rtrim(const string &); vector<string> split(const string &); /* * Complete the 'dynamicArray' function below. * * The function is expected to return an INTEGER_ARRAY. * The function accepts following parameters: * 1. INTEGER n * 2. 2D_INTEGER_ARRAY queries */ vector<int> dynamicArray(int n, vector<vector<int>> queries) { vector<vector<int>> seqlist(n); vector<int> sol; int lastAnswer=0, seq, size; for(vector<int> i:queries) { seq = (i[1]^lastAnswer)%n; if(i[0]==1) { seqlist[seq].push_back(i[2]); } else { size=seqlist[seq].size(); lastAnswer=seqlist[seq][i[2]%size]; sol.push_back(lastAnswer); } } return sol; } int main() { ofstream fout(getenv("OUTPUT_PATH")); string first_multiple_input_temp; getline(cin, first_multiple_input_temp); vector<string> first_multiple_input = split(rtrim(first_multiple_input_temp)); int n = stoi(first_multiple_input[0]); int q = stoi(first_multiple_input[1]); vector<vector<int>> queries(q); for (int i = 0; i < q; i++) { queries[i].resize(3); string queries_row_temp_temp; getline(cin, queries_row_temp_temp); vector<string> queries_row_temp = split(rtrim(queries_row_temp_temp)); for (int j = 0; j < 3; j++) { int queries_row_item = stoi(queries_row_temp[j]); queries[i][j] = queries_row_item; } } vector<int> result = dynamicArray(n, queries); for (int i = 0; i < result.size(); i++) { fout << result[i]; if (i != result.size() - 1) { fout << "\n"; } } fout << "\n"; fout.close(); return 0; } string ltrim(const string &str) { string s(str); s.erase( s.begin(), find_if(s.begin(), s.end(), not1(ptr_fun<int, int>(isspace))) ); return s; } string rtrim(const string &str) { string s(str); s.erase( find_if(s.rbegin(), s.rend(), not1(ptr_fun<int, int>(isspace))).base(), s.end() ); return s; } vector<string> split(const string &str) { vector<string> tokens; string::size_type start = 0; string::size_type end = 0; while ((end = str.find(" ", start)) != string::npos) { tokens.push_back(str.substr(start, end - start)); start = end + 1; } tokens.push_back(str.substr(start)); return tokens; }
20.909836
82
0.577813
VaibhavDS19
ddf38c23944d3160b61f3fbc21fc437d746fc983
6,836
cpp
C++
src/CoreGenPortal/PortalCore/CoreRegClassInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2019-06-25T13:06:14.000Z
2019-06-25T13:06:14.000Z
src/CoreGenPortal/PortalCore/CoreRegClassInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
128
2018-10-23T12:45:15.000Z
2021-12-28T13:09:39.000Z
src/CoreGenPortal/PortalCore/CoreRegClassInfoWin.cpp
opensocsysarch/CoreGenPortal
b6c8c9ca13fa8add969511f153331cad83953799
[ "Apache-2.0" ]
1
2021-01-20T23:17:34.000Z
2021-01-20T23:17:34.000Z
// // _COREREGCLASSINFOWIN_CPP_ // // Copyright (C) 2017-2020 Tactical Computing Laboratories, LLC // All Rights Reserved // contact@tactcomplabs.com // // See LICENSE in the top level directory for licensing details // #include "CoreGenPortal/PortalCore/CoreRegClassInfoWin.h" // Event Table wxBEGIN_EVENT_TABLE(CoreRegClassInfoWin, wxDialog) EVT_BUTTON(wxID_OK, CoreRegClassInfoWin::OnPressOk) EVT_BUTTON(wxID_SAVE, CoreRegClassInfoWin::OnSave) wxEND_EVENT_TABLE() CoreRegClassInfoWin::CoreRegClassInfoWin( wxWindow* parent, wxWindowID id, const wxString& title, CoreGenRegClass *RegClass ) : wxDialog( parent, id, title, wxDefaultPosition, wxSize(500,320), wxDEFAULT_DIALOG_STYLE|wxVSCROLL ){ RegClassNode = RegClass; // init the internals this->SetLayoutAdaptationMode(wxDIALOG_ADAPTATION_MODE_ENABLED); this->SetSizeHints( wxDefaultSize, wxDefaultSize ); // create the outer box sizer OuterSizer = new wxBoxSizer( wxVERTICAL ); // create the scrolled window Wnd = new wxScrolledWindow(this, wxID_ANY, wxDefaultPosition, wxDefaultSize, 0, wxT("Scroll")); // create the inner sizer InnerSizer = new wxBoxSizer( wxVERTICAL ); // add all the interior data // -- reg class RegClassNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegClassNameText = new wxStaticText( Wnd, 2, wxT("Register Class Name"), wxDefaultPosition, wxSize(160, -1), 0 ); RegClassNameText->Wrap(-1); RegClassNameSizer->Add( RegClassNameText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); RegClassNameCtrl = new wxTextCtrl( Wnd, 0, RegClass ? wxString(RegClass->GetName()) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Reg Class Name") ); RegClassNameSizer->Add( RegClassNameCtrl, 0, wxALL, 0 ); InnerSizer->Add( RegClassNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // -- Write ports ReadPortsSizer = new wxBoxSizer( wxHORIZONTAL ); ReadPortsText = new wxStaticText( Wnd, 4, wxT("Read Ports"), wxDefaultPosition, wxSize(160, -1), 0 ); ReadPortsText->Wrap(-1); ReadPortsSizer->Add( ReadPortsText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); ReadPortsCtrl = new wxTextCtrl( Wnd, 5, RegClass ? wxString(std::to_string(RegClass->GetReadPorts())) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Read Ports") ); ReadPortsSizer->Add( ReadPortsCtrl, 0, wxALL, 0 ); InnerSizer->Add( ReadPortsSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // -- write ports WritePortsSizer = new wxBoxSizer( wxHORIZONTAL ); WritePortsText = new wxStaticText( Wnd, 6, wxT("Write Ports"), wxDefaultPosition, wxSize(160, -1), 0 ); WritePortsText->Wrap(-1); WritePortsSizer->Add( WritePortsText, 0, wxALIGN_CENTER_VERTICAL|wxALL, 0 ); WritePortsCtrl = new wxTextCtrl( Wnd, 7, RegClass ? wxString(std::to_string(RegClass->GetWritePorts())) : "", wxDefaultPosition, wxSize(320,25), 0, wxDefaultValidator, wxT("Write Ports") ); WritePortsSizer->Add( WritePortsCtrl, 0, wxALL, 0 ); InnerSizer->Add( WritePortsSizer, 0, wxALIGN_CENTER|wxALL, 5 ); //-- registers RegNameSizer = new wxBoxSizer( wxHORIZONTAL ); RegNameText = new wxStaticText( Wnd, 3, wxT("Registers"), wxDefaultPosition, wxSize(160,-1), 0 ); RegNameText->Wrap(-1); RegNameSizer->Add( RegNameText, 0, wxALIGN_CENTER|wxALL, 0 ); RegNameCtrl = new wxTextCtrl( Wnd, 1, wxEmptyString, wxDefaultPosition, wxSize(320,100), wxTE_MULTILINE|wxHSCROLL, wxDefaultValidator, wxT("registers") ); if(RegClass){ for( unsigned i=0; i<RegClass->GetNumReg(); i++ ){ RegNameCtrl->AppendText(wxString(RegClass->GetReg(i)->GetName())+wxT("\n") ); } } RegNameSizer->Add( RegNameCtrl, 0, wxALL, 0 ); InnerSizer->Add( RegNameSizer, 0, wxALIGN_CENTER|wxALL, 5 ); // add the static line FinalStaticLine = new wxStaticLine( Wnd, wxID_ANY, wxDefaultPosition, wxDefaultSize, wxLI_HORIZONTAL ); InnerSizer->Add( FinalStaticLine, 1, wxEXPAND | wxALL, 5 ); // setup all the buttons m_socbuttonsizer = new wxStdDialogButtonSizer(); m_userOK = new wxButton( Wnd, wxID_CANCEL ); m_userSAVE = new wxButton( Wnd, wxID_SAVE); m_socbuttonsizer->SetAffirmativeButton( m_userOK ); m_socbuttonsizer->SetCancelButton( m_userSAVE ); m_socbuttonsizer->Realize(); InnerSizer->Add( m_socbuttonsizer, 0, wxALL, 5 ); Wnd->SetScrollbars(20,20,50,50); Wnd->SetSizer( InnerSizer ); Wnd->SetAutoLayout(true); Wnd->Layout(); // draw the dialog box until we get more info OuterSizer->Add(Wnd, 1, wxEXPAND | wxALL, 5 ); this->SetSizer( OuterSizer ); this->SetAutoLayout( true ); this->Layout(); } void CoreRegClassInfoWin::OnPressOk(wxCommandEvent& ok){ this->EndModal(wxID_OK); } void CoreRegClassInfoWin::OnSave(wxCommandEvent& save){ PortalMainFrame *PMF = (PortalMainFrame*)this->GetParent(); if(PMF->OnSave(this, this->RegClassNode, CGRegC)) this->EndModal(wxID_SAVE); } CoreRegClassInfoWin::~CoreRegClassInfoWin(){ } // EOF
37.355191
101
0.521065
opensocsysarch
fb04460a52eaf8025e256f7b7a5bdc70ab6f86ef
7,202
cpp
C++
SDK/PUBG_Niagara_functions.cpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
7
2019-03-06T11:04:52.000Z
2019-07-10T20:00:51.000Z
SDK/PUBG_Niagara_functions.cpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
null
null
null
SDK/PUBG_Niagara_functions.cpp
realrespecter/PUBG-FULL-SDK
5e2b0f103c74c95d2329c4c9dfbfab48aa0da737
[ "MIT" ]
10
2019-03-06T11:53:46.000Z
2021-02-18T14:01:11.000Z
// PUBG FULL SDK - Generated By Respecter (5.3.4.11 [06/03/2019]) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "PUBG_Niagara_parameters.hpp" namespace SDK { //--------------------------------------------------------------------------- //Functions //--------------------------------------------------------------------------- // Function Niagara.NiagaraComponent.SetRenderingEnabled // (Final, Native) // Parameters: // bool bInRenderingEnabled (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetRenderingEnabled(bool bInRenderingEnabled) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetRenderingEnabled"); UNiagaraComponent_SetRenderingEnabled_Params params; params.bInRenderingEnabled = bInRenderingEnabled; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec4 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector4* InValue (ConstParm, Parm, OutParm, ReferenceParm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec4(class FString* InVariableName, struct FVector4* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec4"); UNiagaraComponent_SetNiagaraVariableVec4_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec3 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector* InValue (Parm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec3(class FString* InVariableName, struct FVector* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec3"); UNiagaraComponent_SetNiagaraVariableVec3_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableVec2 // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // struct FVector2D* InValue (Parm, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableVec2(class FString* InVariableName, struct FVector2D* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableVec2"); UNiagaraComponent_SetNiagaraVariableVec2_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableFloat // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // float* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableFloat(class FString* InVariableName, float* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableFloat"); UNiagaraComponent_SetNiagaraVariableFloat_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraVariableBool // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // bool* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraVariableBool(class FString* InVariableName, bool* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraVariableBool"); UNiagaraComponent_SetNiagaraVariableBool_Params params; params.InVariableName = InVariableName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraStaticMeshDataInterfaceActor // (Final, Native) // Parameters: // class FString* InVariableName (Parm, ZeroConstructor) // class AActor** InSource (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraStaticMeshDataInterfaceActor(class FString* InVariableName, class AActor** InSource) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraStaticMeshDataInterfaceActor"); UNiagaraComponent_SetNiagaraStaticMeshDataInterfaceActor_Params params; params.InVariableName = InVariableName; params.InSource = InSource; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.SetNiagaraEmitterSpawnRate // (Final, Native) // Parameters: // class FString* InEmitterName (Parm, ZeroConstructor) // float* InValue (Parm, ZeroConstructor, IsPlainOldData) void UNiagaraComponent::SetNiagaraEmitterSpawnRate(class FString* InEmitterName, float* InValue) { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.SetNiagaraEmitterSpawnRate"); UNiagaraComponent_SetNiagaraEmitterSpawnRate_Params params; params.InEmitterName = InEmitterName; params.InValue = InValue; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.ResetEffect // (Final, Native) void UNiagaraComponent::ResetEffect() { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.ResetEffect"); UNiagaraComponent_ResetEffect_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } // Function Niagara.NiagaraComponent.ReinitializeEffect // (Final, Native) void UNiagaraComponent::ReinitializeEffect() { static auto fn = UObject::FindObject<UFunction>("Function Niagara.NiagaraComponent.ReinitializeEffect"); UNiagaraComponent_ReinitializeEffect_Params params; auto flags = fn->FunctionFlags; fn->FunctionFlags |= 0x400; UObject::ProcessEvent(fn, &params); fn->FunctionFlags = flags; } } #ifdef _MSC_VER #pragma pack(pop) #endif
30.260504
125
0.711469
realrespecter
fb063781520cb0a4cca149aafebc08d9057c0538
2,161
cpp
C++
src/vkex/QueryPool.cpp
apazylbe/PorQue4K
209ba90a35f05df0be68df586c9e184183ed8263
[ "Apache-2.0" ]
15
2020-06-12T01:40:34.000Z
2022-03-16T21:52:46.000Z
src/vkex/QueryPool.cpp
apazylbe/PorQue4K
209ba90a35f05df0be68df586c9e184183ed8263
[ "Apache-2.0" ]
4
2020-06-12T23:57:52.000Z
2020-06-24T19:19:16.000Z
src/vkex/QueryPool.cpp
apazylbe/PorQue4K
209ba90a35f05df0be68df586c9e184183ed8263
[ "Apache-2.0" ]
3
2020-06-12T15:02:13.000Z
2020-07-05T17:34:20.000Z
/* Copyright 2018-2019 Google Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #include "vkex/QueryPool.h" #include "vkex/Device.h" #include "vkex/ToString.h" namespace vkex { // ================================================================================================= // QueryPool // ================================================================================================= CQueryPool::CQueryPool() { } CQueryPool::~CQueryPool() { } vkex::Result CQueryPool::InternalCreate( const vkex::QueryPoolCreateInfo& create_info, const VkAllocationCallbacks* p_allocator ) { // Copy create info m_create_info = create_info; // Create Vulkan sampler { // Create info m_vk_create_info = { VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO }; m_vk_create_info.queryType = m_create_info.query_type; m_vk_create_info.queryCount = m_create_info.query_count; m_vk_create_info.pipelineStatistics = m_create_info.pipeline_statistics.flags; // Create Vulkan sampler VkResult vk_result = InvalidValue<VkResult>::Value; VKEX_VULKAN_RESULT_CALL( vk_result, vkex::CreateQueryPool( *m_device, &m_vk_create_info, p_allocator, &m_vk_object) ); if (vk_result != VK_SUCCESS) { return vkex::Result(vk_result); } } return vkex::Result::Success; } vkex::Result CQueryPool::InternalDestroy(const VkAllocationCallbacks* p_allocator) { if (m_vk_object != VK_NULL_HANDLE) { vkex::DestroyQueryPool( *m_device, m_vk_object, p_allocator); m_vk_object = VK_NULL_HANDLE; } return vkex::Result::Success; } } // namespace vkex
27.0125
100
0.648774
apazylbe
fb0918f6b14b61ff1c285851a2d06dc0989cd7fc
5,709
cpp
C++
engine/Ecs/Systems/CheckCollisionsSystem.cpp
ledocool/snail_engine
0114a62dbecbbe58348fbe7083d9182bc1bd8c3c
[ "Apache-2.0" ]
null
null
null
engine/Ecs/Systems/CheckCollisionsSystem.cpp
ledocool/snail_engine
0114a62dbecbbe58348fbe7083d9182bc1bd8c3c
[ "Apache-2.0" ]
null
null
null
engine/Ecs/Systems/CheckCollisionsSystem.cpp
ledocool/snail_engine
0114a62dbecbbe58348fbe7083d9182bc1bd8c3c
[ "Apache-2.0" ]
1
2018-08-11T14:31:27.000Z
2018-08-11T14:31:27.000Z
/* * Copyright 2018 LedoCool. * * 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. */ /* * File: CheckCollisions.cpp * Author: LedoCool * * Created on December 24, 2018, 8:35 PM */ #include "CheckCollisionsSystem.h" #include "engine/Etc/Rect.h" #include "engine/Etc/Vector2.h" #include "engine/Game/Camera.h" #include "engine/Ecs/Components/IncludeComponents.h" CheckCollisionsSystem::CheckCollisionsSystem() { } CheckCollisionsSystem::~ CheckCollisionsSystem() { } void CheckCollisionsSystem::Execute(Uint32 dt, std::shared_ptr<GameState>& gameState) { gameState->collidingEntitites.clear(); BuildBinaryTree(gameState); for(auto entity : gameState->map->GetEntities()) { auto position = std::dynamic_pointer_cast<Position>(entity->GetComponent(ComponentTypes::POSITION).lock()); auto velocity = std::dynamic_pointer_cast<Velocity>(entity->GetComponent(ComponentTypes::VELOCITY).lock()); auto acceleration = std::dynamic_pointer_cast<Acceleration>(entity->GetComponent(ComponentTypes::ACCELERATION).lock()); auto size = std::dynamic_pointer_cast<Size>(entity->GetComponent(ComponentTypes::SIZE).lock()); if(!acceleration) { acceleration = std::make_shared<Acceleration>(Vector2<float>(0.f, 0.f), 0.f); } if(!velocity) { velocity = std::make_shared<Velocity>(Vector2<float>(0.f, 0.f), 0.f); } if(!(position && size)) { continue; } float halfSize = size->size() / 2.f; Rect<float> boundingRect( - halfSize, halfSize, - halfSize, halfSize ); for(auto weakPossiblyCollidingEntity : gameState->collisionTree->GetObjects(boundingRect)) { auto collider = weakPossiblyCollidingEntity.lock(); if(!collider || collider == entity) { continue; } auto colliderPosition = std::dynamic_pointer_cast<Position>(collider->GetComponent(ComponentTypes::POSITION).lock()); auto colliderVelocity = std::dynamic_pointer_cast<Velocity>(collider->GetComponent(ComponentTypes::VELOCITY).lock()); auto coliderAcceleration = std::dynamic_pointer_cast<Acceleration>(collider->GetComponent(ComponentTypes::ACCELERATION).lock()); auto colliderSize = std::dynamic_pointer_cast<Size>(collider->GetComponent(ComponentTypes::SIZE).lock()); if(!coliderAcceleration) { coliderAcceleration = std::make_shared<Acceleration>(Vector2<float>(0.f, 0.f), 0.f); } if(!colliderVelocity) { colliderVelocity = std::make_shared<Velocity>(Vector2<float>(0.f, 0.f), 0.f); } if(!(colliderPosition && colliderSize)) { continue; } float colliderHalfSize = colliderSize->size() / 2.f; Rect<float> colliderBoundingRect( - colliderHalfSize, colliderHalfSize, - colliderHalfSize, colliderHalfSize ); for(Uint32 iTime = 0; iTime < dt; iTime++) { Vector2<float> entity1_position = position->coords(); entity1_position += velocity->velocity() * iTime; entity1_position += acceleration->vector() * iTime * iTime / 2.f; Vector2<float> entity2_position = colliderPosition->coords(); entity2_position += colliderVelocity->velocity() * iTime; entity2_position += coliderAcceleration->vector() * iTime * iTime / 2.f; if(boundingRect.addPosition(entity1_position.x(), entity1_position.y()).CollidesWith( colliderBoundingRect.addPosition(entity2_position.x(), entity2_position.y()))) { Vector2<float> diff = entity1_position - entity2_position; if(diff.Magnitude() <= colliderSize->size() + size->size()) { std::weak_ptr<Entity> leftEntity(entity); std::pair<std::weak_ptr<Entity>, std::weak_ptr<Entity> > collidingPair(leftEntity, weakPossiblyCollidingEntity); gameState->collidingEntitites.push_back(collidingPair); } } } } } } void CheckCollisionsSystem::BuildBinaryTree(std::shared_ptr<GameState>& gameState) { auto cameraCoordinates = gameState->camera->GetCoordinates(); auto screenSize = gameState->camera->GetScreenProportions(); Rect<float> chunk( cameraCoordinates.x() - screenSize.x(), cameraCoordinates.x() + screenSize.x(), cameraCoordinates.y() - screenSize.y(), cameraCoordinates.y() + screenSize.y() ); gameState->collisionTree = std::make_shared<TreeRoot>(); gameState->collisionTree->BuildTree(chunk, gameState->map->GetEntities()); }
39.372414
140
0.600981
ledocool