hexsha stringlengths 40 40 | size int64 7 1.05M | ext stringclasses 13 values | lang stringclasses 1 value | max_stars_repo_path stringlengths 4 269 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 9 | max_stars_count int64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 4 269 | max_issues_repo_name stringlengths 5 116 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 9 | max_issues_count int64 1 48.5k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 4 269 | max_forks_repo_name stringlengths 5 116 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 9 | max_forks_count int64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 7 1.05M | avg_line_length float64 1.21 330k | max_line_length int64 6 990k | alphanum_fraction float64 0.01 0.99 | author_id stringlengths 2 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c04859891a666e1816daf20afd5cbeedb16f3a5e | 1,780 | cpp | C++ | src/main/cpp/subsystems/subsystem_Arm.cpp | Robodox-599/2022_Ophthamologist | 2bb465e416389505afcd7d9cedc16ff868e5200a | [
"BSD-3-Clause"
] | 3 | 2022-03-03T03:36:45.000Z | 2022-03-04T03:45:18.000Z | src/main/cpp/subsystems/subsystem_Arm.cpp | Robodox-599/2022_Ophthamologist | 2bb465e416389505afcd7d9cedc16ff868e5200a | [
"BSD-3-Clause"
] | 1 | 2022-02-26T18:51:46.000Z | 2022-02-26T18:51:46.000Z | src/main/cpp/subsystems/subsystem_Arm.cpp | Robodox-599/2022_Ophthamologist | 2bb465e416389505afcd7d9cedc16ff868e5200a | [
"BSD-3-Clause"
] | null | null | null | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#include "subsystems/subsystem_Arm.h"
subsystem_Arm::subsystem_Arm() : m_ArmMotor{ArmConstants::ArmMotorPort, rev::CANSparkMax::MotorType::kBrushless}{
//arm motor set up
double kP = 1, kI = 0, kD = 0, kIz = 0, kFF = 0, kMaxOutput = .3, kMinOutput = -.3;
m_ArmPidController.SetP(kP);
m_ArmPidController.SetI(kI);
m_ArmPidController.SetD(kD);
m_ArmPidController.SetIZone(kIz);
m_ArmPidController.SetFF(kFF);
m_ArmPidController.SetOutputRange(kMinOutput, kMaxOutput);
m_ArmPidController.SetSmartMotionAccelStrategy(rev::CANPIDController::AccelStrategy::kTrapezoidal, 0);
m_ArmPidController.SetSmartMotionMaxAccel(ArmConstants::ArmAcceleration);
m_ArmPidController.SetSmartMotionMaxVelocity(ArmConstants::ArmVelocity);
m_ArmEncoder.SetPosition(0);
m_ArmMotor.SetInverted(true);
// m_ArmEncoder.SetInverted(true);
//built_different
//thing
}
/*moves the position of the arm by the inputed amount of ticks.
0 ticks is the arm in the horizontal position */
void subsystem_Arm::SetArmPosition(int ticks){
m_ArmPidController.SetReference(ticks, rev::ControlType::kPosition,0);
}
// This method will be called once per scheduler run
void subsystem_Arm::Periodic() {
frc::SmartDashboard::PutNumber("POSITION", m_ArmEncoder.GetPosition());
frc::SmartDashboard::PutNumber("CURRENT", m_ArmMotor.GetOutputCurrent());
//Stall prevention, checks the current of the motor to make sure that it isn't stuck
if(m_ArmMotor.GetOutputCurrent() > 100){
SetArmPosition(ArmConstants::ArmTicksUp);
}
}
| 39.555556 | 113 | 0.747753 | Robodox-599 |
c04d64e600dabcb8babaac093ec469ffa9698d27 | 2,459 | hpp | C++ | shared/imgui/imgui_impl_win32.hpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | shared/imgui/imgui_impl_win32.hpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | shared/imgui/imgui_impl_win32.hpp | jrnh/herby | bf0e90b850e2f81713e4dbc21c8d8b9af78ad203 | [
"MIT"
] | null | null | null | // dear imgui: Platform Backend for Windows (standard windows API for 32 and 64 bits applications)
// This needs to be used along with a Renderer (e.g. DirectX11, OpenGL3, Vulkan..)
// Implemented features:
// [X] Platform: Clipboard support (for Win32 this is actually part of core dear imgui)
// [X] Platform: Mouse cursor shape and visibility. Disable with 'io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange'.
// [X] Platform: Keyboard arrays indexed using VK_* Virtual Key Codes, e.g. ImGui::IsKeyPressed(VK_SPACE).
// [X] Platform: Gamepad support. Enabled with 'io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad'.
// You can copy and use unmodified imgui_impl_* files in your project. See examples/ folder for examples of using this.
// If you are new to Dear ImGui, read documentation from the docs/ folder + read the top of imgui.cpp.
// Read online: https://github.com/ocornut/imgui/tree/master/docs
#pragma once
#include <windows.h>
IMGUI_IMPL_API bool ImGui_ImplWin32_Init(void* hwnd);
IMGUI_IMPL_API void ImGui_ImplWin32_Shutdown();
IMGUI_IMPL_API void ImGui_ImplWin32_NewFrame();
// Configuration
// - Disable gamepad support or linking with xinput.lib
//#define IMGUI_IMPL_WIN32_DISABLE_GAMEPAD
//#define IMGUI_IMPL_WIN32_DISABLE_LINKING_XINPUT
// Win32 message handler
// - Intentionally commented out in a '#if 0' block to avoid dragging dependencies on <windows.h>
// - You can COPY this line into your .cpp code to forward declare the function.
IMGUI_IMPL_API LRESULT ImGui_ImplWin32_WndProcHandler(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam);
// DPI-related helpers (optional)
// - Use to enable DPI awareness without having to create an application manifest.
// - Your own app may already do this via a manifest or explicit calls. This is mostly useful for our examples/ apps.
// - In theory we could call simple functions from Windows SDK such as SetProcessDPIAware(), SetProcessDpiAwareness(), etc.
// but most of the functions provided by Microsoft require Windows 8.1/10+ SDK at compile time and Windows 8/10+ at runtime,
// neither we want to require the user to have. So we dynamically select and load those functions to avoid dependencies.
IMGUI_IMPL_API void ImGui_ImplWin32_EnableDpiAwareness();
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForHwnd(void* hwnd); // HWND hwnd
IMGUI_IMPL_API float ImGui_ImplWin32_GetDpiScaleForMonitor(void* monitor); // HMONITOR monitor
| 61.475 | 126 | 0.775519 | jrnh |
c04e6aae6af0b701a8a8b5931236b155562ee303 | 983 | inl | C++ | src/stk/filters/normalize.inl | simeks/stk | 21caff7d35d30f385928cd027243d8ac5d33a132 | [
"MIT"
] | 2 | 2018-08-15T10:52:34.000Z | 2018-09-26T13:05:57.000Z | src/stk/filters/normalize.inl | simeks/stk | 21caff7d35d30f385928cd027243d8ac5d33a132 | [
"MIT"
] | 19 | 2018-07-10T10:32:19.000Z | 2019-11-07T10:19:13.000Z | src/stk/filters/normalize.inl | simeks/stk | 21caff7d35d30f385928cd027243d8ac5d33a132 | [
"MIT"
] | 1 | 2018-06-27T17:28:20.000Z | 2018-06-27T17:28:20.000Z | namespace stk
{
template<typename T>
VolumeHelper<T> normalize(const VolumeHelper<T>& src,
T min,
T max,
VolumeHelper<T>* out)
{
T src_min, src_max;
find_min_max(src, src_min, src_max);
dim3 dims = src.size();
VolumeHelper<T> dest;
if (!out) {
dest.allocate(src.size());
out = &dest;
}
ASSERT(out->size() == dims);
out->copy_meta_from(src);
double range = double(max - min);
double src_range = double(src_max - src_min);
#pragma omp parallel for
for (int z = 0; z < int(dims.z); ++z) {
for (int y = 0; y < int(dims.y); ++y) {
for (int x = 0; x < int(dims.x); ++x) {
(*out)(x,y,z) = T(range * (src(x, y, z) - src_min) / src_range + min);
}
}
}
return *out;
}
}
| 26.567568 | 90 | 0.425229 | simeks |
c050e20a224e2e0c1b2f0153d3c38025d9a1d73b | 5,199 | cpp | C++ | src/util/codec_util_high_openssl.cpp | jackyding2679/cos-cpp-sdk-v5 | 037da66f54473ba9628b532df72759edb6ca7700 | [
"MIT"
] | 6 | 2018-11-17T01:34:02.000Z | 2020-04-21T14:18:44.000Z | src/util/codec_util_high_openssl.cpp | jackyding2679/cos-cpp-sdk-v5 | 037da66f54473ba9628b532df72759edb6ca7700 | [
"MIT"
] | null | null | null | src/util/codec_util_high_openssl.cpp | jackyding2679/cos-cpp-sdk-v5 | 037da66f54473ba9628b532df72759edb6ca7700 | [
"MIT"
] | 1 | 2018-11-19T08:12:13.000Z | 2018-11-19T08:12:13.000Z | #include "util/codec_util.h"
#include <cassert>
#include <string.h>
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <openssl/crypto.h>
#include <openssl/evp.h>
#include <openssl/hmac.h>
#include <openssl/md5.h>
#include "util/file_util.h"
#include "util/sha1.h"
#include <openssl/sha.h>
namespace qcloud_cos {
#define REVERSE_HEX(c) ( ((c) >= 'A') ? ((c) & 0xDF) - 'A' + 10 : (c) - '0' )
#define HMAC_LENGTH 20
unsigned char CodecUtil::ToHex(const unsigned char& x) {
return x > 9 ? (x - 10 + 'A') : x + '0';
}
void CodecUtil::BinToHex(const unsigned char *bin,unsigned int binLen, char *hex) {
for(unsigned int i = 0; i < binLen; ++i) {
hex[i<<1] = ToHex(bin[i] >> 4);
hex[(i<<1)+1] = ToHex(bin[i] & 15 );
}
}
std::string CodecUtil::EncodeKey(const std::string& key) {
std::string encodedKey = "";
std::size_t length = key.length();
for (size_t i = 0; i < length; ++i) {
if (isalnum((unsigned char)key[i]) ||
(key[i] == '-') ||
(key[i] == '_') ||
(key[i] == '.') ||
(key[i] == '~') ||
(key[i] == '/')) {
encodedKey += key[i];
} else {
encodedKey += '%';
encodedKey += ToHex((unsigned char)key[i] >> 4);
encodedKey += ToHex((unsigned char)key[i] % 16);
}
}
return encodedKey;
}
std::string CodecUtil::UrlEncode(const std::string& str) {
std::string encodedUrl = "";
std::size_t length = str.length();
for (size_t i = 0; i < length; ++i) {
if (isalnum((unsigned char)str[i]) ||
(str[i] == '-') ||
(str[i] == '_') ||
(str[i] == '.') ||
(str[i] == '~')) {
encodedUrl += str[i];
} else {
encodedUrl += '%';
encodedUrl += ToHex((unsigned char)str[i] >> 4);
encodedUrl += ToHex((unsigned char)str[i] % 16);
}
}
return encodedUrl;
}
std::string CodecUtil::Base64Encode(const std::string& plain_text) {
static const char b64_table[65] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const std::size_t plain_text_len = plain_text.size();
std::string retval((((plain_text_len + 2) / 3) * 4), '=');
std::size_t outpos = 0;
int bits_collected = 0;
unsigned int accumulator = 0;
const std::string::const_iterator plain_text_end = plain_text.end();
for (std::string::const_iterator i = plain_text.begin(); i != plain_text_end; ++i) {
accumulator = (accumulator << 8) | (*i & 0xffu);
bits_collected += 8;
while (bits_collected >= 6) {
bits_collected -= 6;
retval[outpos++] = b64_table[(accumulator >> bits_collected) & 0x3fu];
}
}
if (bits_collected > 0) {
assert(bits_collected < 6);
accumulator <<= 6 - bits_collected;
retval[outpos++] = b64_table[accumulator & 0x3fu];
}
assert(outpos >= (retval.size() - 2));
assert(outpos <= retval.size());
return retval;
}
std::string CodecUtil::HmacSha1(const std::string& plainText, const std::string& key) {
const EVP_MD *engine = EVP_sha1();
unsigned char *output = (unsigned char *)malloc(EVP_MAX_MD_SIZE);
unsigned int output_len = 0;
HMAC_CTX *ctx = HMAC_CTX_new();
HMAC_CTX_reset(ctx);
HMAC_Init_ex(ctx, (char *)key.c_str(), key.length(), engine, NULL);
HMAC_Update(ctx, (unsigned char*)plainText.c_str(), plainText.length());
HMAC_Final(ctx, output, &output_len);
HMAC_CTX_free(ctx);
std::string hmac_sha1_ret((char *)output, output_len);
free(output);
return hmac_sha1_ret;
}
std::string CodecUtil::HmacSha1Hex(const std::string& plain_text,const std::string& key) {
std::string encode_str = HmacSha1(plain_text, key);
char hex[(HMAC_LENGTH<<1)+1] = {0};
BinToHex((const unsigned char*)encode_str.c_str(), encode_str.size(), hex);
return std::string(hex, (HMAC_LENGTH << 1));
}
std::string CodecUtil::RawMd5(const std::string& plainText) {
const int md5_length = 16;
unsigned char md[md5_length];
MD5((const unsigned char*)plainText.data(), plainText.size(), md);
std::string tmp((const char *)md, md5_length);
return tmp;
}
// convert a hexadecimal string to binary value
std::string CodecUtil::HexToBin(const std::string &strHex) {
if (strHex.size() % 2 != 0) {
return "";
}
std::string strBin;
strBin.resize(strHex.size() / 2);
for (size_t i = 0; i < strBin.size(); i++) {
uint8_t cTmp = 0;
for (size_t j = 0; j < 2; j++) {
char cCur = strHex[2 * i + j];
if (cCur >= '0' && cCur <= '9') {
cTmp = (cTmp << 4) + (cCur - '0');
}
else if (cCur >= 'a' && cCur <= 'f') {
cTmp = (cTmp << 4) + (cCur - 'a' + 10);
}
else if (cCur >= 'A' && cCur <= 'F') {
cTmp = (cTmp << 4) + (cCur - 'A' + 10);
}
else {
return "";
}
}
strBin[i] = cTmp;
}
return strBin;
}// end of HexToBin
}// end of qcloud_cos namespace
| 30.946429 | 105 | 0.55126 | jackyding2679 |
c055064afd19bc84d0a88420d08f27ec9b0f5394 | 5,405 | cpp | C++ | src/test/graph5.cpp | jalilm/q-MAX | 3a4e7ca89a9d0096ce7366f9efcf4ba583a6aced | [
"MIT"
] | 2 | 2021-03-05T02:05:44.000Z | 2021-05-26T16:13:57.000Z | src/test/graph5.cpp | jalilm/q-MAX | 3a4e7ca89a9d0096ce7366f9efcf4ba583a6aced | [
"MIT"
] | null | null | null | src/test/graph5.cpp | jalilm/q-MAX | 3a4e7ca89a9d0096ce7366f9efcf4ba583a6aced | [
"MIT"
] | 2 | 2019-12-03T12:59:40.000Z | 2021-03-05T01:49:58.000Z | #include <cstdio>
#include <cstdlib>
#include <list>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstring>
#include <random>
#include <stdio.h>
#include <stdlib.h>
#include <sys/timeb.h>
#include "../QmaxKV.hpp"
#include "../HeapKV.hpp"
#include "../SkiplistKV.hpp"
#include "Utils.hpp"
#define CLK_PER_SEC CLOCKS_PER_SEC
#define CAIDA16_SIZE 152197437
#define CAIDA18_SIZE 175880808
#define UNIV1_SIZE 17323447
using namespace std;
void benchmark_psskiplist(int q, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) {
std::random_device _rd;
std::mt19937 _e2(_rd());
std::uniform_real_distribution<double> _dist(0,1);
key *elements = *keys;
val *weights = *vals;
struct timeb begintb, endtb;
clock_t begint, endt;
double time;
SkiplistKV sl(q);
begint = clock();
ftime(&begintb);
for (int i = 0; i < numKeys; i++) {
val priority = weights[i] / (1-_dist(_e2));
sl.add(pair<key, val>(elements[i], priority));
}
endt = clock();
ftime(&endtb);
time = ((double)(endt-begint))/CLK_PER_SEC;
ostream << dataset << ",SkipList," << numKeys << "," << q << ",," << time << endl;
}
void benchmark_psheap(int q, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) {
std::random_device _rd;
std::mt19937 _e2(_rd());
std::uniform_real_distribution<double> _dist(0,1);
key *elements = *keys;
val *weights = *vals;
struct timeb begintb, endtb;
clock_t begint, endt;
double time;
HeapKV heap(q);
begint = clock();
ftime(&begintb);
for (int i = 0; i < numKeys; i++) {
val priority = weights[i] / (1-_dist(_e2));
heap.add(pair<key,val>(elements[i], priority));
}
endt = clock();
ftime(&endtb);
time = ((double)(endt-begint))/CLK_PER_SEC;
ostream << dataset << ",Heap," << numKeys << "," << q << ",," << time << endl;
}
void benchmark_psqmax(int q, double gamma, key** keys, val** vals, ofstream &ostream, string dataset, int numKeys) {
std::random_device _rd;
std::mt19937 _e2(_rd());
std::uniform_real_distribution<double> _dist(0,1);
key *elements = *keys;
val *weights = *vals;
struct timeb begintb, endtb;
clock_t begint, endt;
double time;
QMaxKV qmax = QMaxKV(q, gamma);
begint = clock();
ftime(&begintb);
for (int i = 0; i < numKeys; i++) {
val priority = weights[i] / (1-_dist(_e2));
qmax.insert(elements[i], priority);
}
endt = clock();
ftime(&endtb);
time = ((double)(endt-begint))/CLK_PER_SEC;
ostream << dataset << ",AmortizedQMax," << numKeys << "," << q << "," << gamma << "," << time << endl;
}
void getKeysAndValsFromFile(string filename, vector<key*> &keys, vector<val*> &vals, int size) {
ifstream stream;
stream.open(filename, fstream::in | fstream::out | fstream::app);
if (!stream) {
throw invalid_argument("Could not open " + filename + " for reading.");
}
key* file_keys = (key*) malloc(sizeof(key) * size);
val* file_vals = (val*) malloc(sizeof(val) * size);
string line;
string len;
string id;
for (int i = 0; i < size; ++i){
getline(stream, line);
std::istringstream iss(line);
iss >> len;
iss >> id;
try {
file_keys[i] = stoull(id);
file_vals[i] = stoull(len);
} catch (const std::invalid_argument& ia) {
cerr << "Invalid argument: " << ia.what() << " at line " << i << endl;
cerr << len << " " << id << endl;;
--i;
exit(1);
}
}
keys.push_back(file_keys);
vals.push_back(file_vals);
stream.close();
}
int main() {
vector<ofstream*> streams;
vector<key*> keys;
vector<val*> vals;
vector<int> sizes;
vector<string> datasets;
ofstream univ1stream;
setupOutputFile("../results/ps_univ1.raw_res", univ1stream, false);
streams.push_back(&univ1stream);
getKeysAndValsFromFile("../datasets/UNIV1/mergedPktlen_Srcip", keys, vals, UNIV1_SIZE);
sizes.push_back(UNIV1_SIZE);
datasets.push_back("univ1");
ofstream caida16stream;
setupOutputFile("../results/ps_caida.raw_res", caida16stream, false);
streams.push_back(&caida16stream);
getKeysAndValsFromFile("../datasets/CAIDA16/mergedPktlen_Srcip", keys, vals, CAIDA16_SIZE);
sizes.push_back(CAIDA16_SIZE);
datasets.push_back("caida");
ofstream caida18stream;
setupOutputFile("../results/ps_caida18.raw_res", caida18stream, false);
streams.push_back(&caida18stream);
getKeysAndValsFromFile("../datasets/CAIDA18/mergedPktlen_Srcip", keys, vals, CAIDA18_SIZE);
sizes.push_back(CAIDA18_SIZE);
datasets.push_back("caida18");
list<unsigned int> qs = {10000000, 1000000, 100000, 10000};
for (int run = 0; run < 5; run++) {
for (unsigned q: qs) {
vector<key*>::iterator k_it = keys.begin();
vector<val*>::iterator v_it = vals.begin();
vector<int>::iterator s_it = sizes.begin();
vector<string>::iterator d_it = datasets.begin();
for (auto& stream : streams) {
key* k = *k_it;
val* v = *v_it;
int size = *s_it;
string dataset = *d_it;
benchmark_psheap(q, &k, &v, *stream, dataset, size);
benchmark_psskiplist(q, &k, &v, *stream, dataset, size);
list<double> gammas = {0.5, 0.25, 0.1, 0.05};
for (double g : gammas) {
benchmark_psqmax(q, g, &k, &v, *stream, dataset, size);
}
++k_it;
++v_it;
++s_it;
++d_it;
}
}
}
univ1stream.close();
caida16stream.close();
caida18stream.close();
return 0;
}
| 29.216216 | 116 | 0.639963 | jalilm |
c056cc860904fb1613e372c30ad3126ead651f41 | 7,118 | cpp | C++ | casablanca/Release/tests/Functional/uri/constructor_tests.cpp | fpelliccioni/Tao | d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9 | [
"BSL-1.0"
] | 1 | 2015-12-30T16:02:12.000Z | 2015-12-30T16:02:12.000Z | casablanca/Release/tests/Functional/uri/constructor_tests.cpp | fpelliccioni/Tao | d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9 | [
"BSL-1.0"
] | null | null | null | casablanca/Release/tests/Functional/uri/constructor_tests.cpp | fpelliccioni/Tao | d23655bdf1ff521dc0c7e3fb2f101d1156fea4d9 | [
"BSL-1.0"
] | null | null | null | /***
* ==++==
*
* Copyright (c) Microsoft Corporation. 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.
*
* ==--==
* =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+
*
* constructor_tests.cpp
*
* Tests for constructors of the uri class.
*
* =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-
****/
#include "stdafx.h"
using namespace web; using namespace utility;
using namespace http;
namespace tests { namespace functional { namespace uri_tests {
SUITE(constructor_tests)
{
TEST(parsing_constructor_char)
{
uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(U("qstring"), u.query());
VERIFY_ARE_EQUAL(U("goo"), u.fragment());
}
TEST(parsing_constructor_encoded_string)
{
uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(U("qstring"), u.query());
VERIFY_ARE_EQUAL(U("goo"), u.fragment());
}
TEST(parsing_constructor_string_string)
{
uri u(uri::encode_uri(U("net.tcp://testname.com:81/bleh%?qstring#goo")));
VERIFY_ARE_EQUAL(U("net.tcp"), u.scheme());
VERIFY_ARE_EQUAL(U("testname.com"), u.host());
VERIFY_ARE_EQUAL(81, u.port());
VERIFY_ARE_EQUAL(U("/bleh%25"), u.path());
VERIFY_ARE_EQUAL(U("qstring"), u.query());
VERIFY_ARE_EQUAL(U("goo"), u.fragment());
}
TEST(empty_strings)
{
VERIFY_IS_TRUE(uri(U("")).is_empty());
VERIFY_IS_TRUE(uri(U("")).is_empty());
VERIFY_IS_TRUE(uri(uri::encode_uri(U(""))).is_empty());
}
TEST(default_constructor)
{
VERIFY_IS_TRUE(uri().is_empty());
}
TEST(relative_ref_string)
{
uri u(uri::encode_uri(U("first/second#boff")));
VERIFY_ARE_EQUAL(U(""), u.scheme());
VERIFY_ARE_EQUAL(U(""), u.host());
VERIFY_ARE_EQUAL(0, u.port());
VERIFY_ARE_EQUAL(U("first/second"), u.path());
VERIFY_ARE_EQUAL(U(""), u.query());
VERIFY_ARE_EQUAL(U("boff"), u.fragment());
}
TEST(absolute_ref_string)
{
uri u(uri::encode_uri(U("/first/second#boff")));
VERIFY_ARE_EQUAL(U(""), u.scheme());
VERIFY_ARE_EQUAL(U(""), u.host());
VERIFY_ARE_EQUAL(0, u.port());
VERIFY_ARE_EQUAL(U("/first/second"), u.path());
VERIFY_ARE_EQUAL(U(""), u.query());
VERIFY_ARE_EQUAL(U("boff"), u.fragment());
}
TEST(copy_constructor)
{
uri original(U("http://localhost:456/path1?qstring#goo"));
uri new_uri(original);
VERIFY_ARE_EQUAL(original, new_uri);
}
TEST(move_constructor)
{
const utility::string_t uri_str(U("http://localhost:456/path1?qstring#goo"));
uri original(uri_str);
uri new_uri = std::move(original);
VERIFY_ARE_EQUAL(uri_str, new_uri.to_string());
VERIFY_ARE_EQUAL(uri(uri_str), new_uri);
}
TEST(assignment_operator)
{
uri original(U("http://localhost:456/path?qstring#goo"));
uri new_uri = original;
VERIFY_ARE_EQUAL(original, new_uri);
}
// Tests invalid URI being passed in constructor.
TEST(parsing_constructor_invalid)
{
VERIFY_THROWS(uri(U("123http://localhost:345/")), uri_exception);
VERIFY_THROWS(uri(U("h*ttp://localhost:345/")), uri_exception);
VERIFY_THROWS(uri(U("http://localhost:345/\"")), uri_exception);
VERIFY_THROWS(uri(U("http://localhost:345/path?\"")), uri_exception);
VERIFY_THROWS(uri(U("http://local\"host:345/")), uri_exception);
}
// Tests a variety of different URIs using the examples in RFC 3986.
TEST(RFC_3968_examples_string)
{
uri ftp(U("ftp://ftp.is.co.za/rfc/rfc1808.txt"));
VERIFY_ARE_EQUAL(U("ftp"), ftp.scheme());
VERIFY_ARE_EQUAL(U(""), ftp.user_info());
VERIFY_ARE_EQUAL(U("ftp.is.co.za"), ftp.host());
VERIFY_ARE_EQUAL(0, ftp.port());
VERIFY_ARE_EQUAL(U("/rfc/rfc1808.txt"), ftp.path());
VERIFY_ARE_EQUAL(U(""), ftp.query());
VERIFY_ARE_EQUAL(U(""), ftp.fragment());
// TFS #371892
//uri ldap(U("ldap://[2001:db8::7]/?c=GB#objectClass?one"));
//VERIFY_ARE_EQUAL(U("ldap"), ldap.scheme());
//VERIFY_ARE_EQUAL(U(""), ldap.user_info());
//VERIFY_ARE_EQUAL(U("2001:db8::7"), ldap.host());
//VERIFY_ARE_EQUAL(0, ldap.port());
//VERIFY_ARE_EQUAL(U("/"), ldap.path());
//VERIFY_ARE_EQUAL(U("c=GB"), ldap.query());
//VERIFY_ARE_EQUAL(U("objectClass?one"), ldap.fragment());
// We don't support anything scheme specific like in C# so
// these common ones don't have a great experience yet.
uri mailto(U("mailto:John.Doe@example.com"));
VERIFY_ARE_EQUAL(U("mailto"), mailto.scheme());
VERIFY_ARE_EQUAL(U(""), mailto.user_info());
VERIFY_ARE_EQUAL(U(""), mailto.host());
VERIFY_ARE_EQUAL(0, mailto.port());
VERIFY_ARE_EQUAL(U("John.Doe@example.com"), mailto.path());
VERIFY_ARE_EQUAL(U(""), mailto.query());
VERIFY_ARE_EQUAL(U(""), mailto.fragment());
uri tel(U("tel:+1-816-555-1212"));
VERIFY_ARE_EQUAL(U("tel"), tel.scheme());
VERIFY_ARE_EQUAL(U(""), tel.user_info());
VERIFY_ARE_EQUAL(U(""), tel.host());
VERIFY_ARE_EQUAL(0, tel.port());
VERIFY_ARE_EQUAL(U("+1-816-555-1212"), tel.path());
VERIFY_ARE_EQUAL(U(""), tel.query());
VERIFY_ARE_EQUAL(U(""), tel.fragment());
uri telnet(U("telnet://192.0.2.16:80/"));
VERIFY_ARE_EQUAL(U("telnet"), telnet.scheme());
VERIFY_ARE_EQUAL(U(""), telnet.user_info());
VERIFY_ARE_EQUAL(U("192.0.2.16"), telnet.host());
VERIFY_ARE_EQUAL(80, telnet.port());
VERIFY_ARE_EQUAL(U("/"), telnet.path());
VERIFY_ARE_EQUAL(U(""), telnet.query());
VERIFY_ARE_EQUAL(U(""), telnet.fragment());
}
TEST(user_info_string)
{
uri ftp(U("ftp://johndoe:testname@ftp.is.co.za/rfc/rfc1808.txt"));
VERIFY_ARE_EQUAL(U("ftp"), ftp.scheme());
VERIFY_ARE_EQUAL(U("johndoe:testname"), ftp.user_info());
VERIFY_ARE_EQUAL(U("ftp.is.co.za"), ftp.host());
VERIFY_ARE_EQUAL(0, ftp.port());
VERIFY_ARE_EQUAL(U("/rfc/rfc1808.txt"), ftp.path());
VERIFY_ARE_EQUAL(U(""), ftp.query());
VERIFY_ARE_EQUAL(U(""), ftp.fragment());
}
// Test query component can be seperated with '&' or ';'.
TEST(query_seperated_with_semi_colon)
{
uri u(U("http://localhost/path1?key1=val1;key2=val2"));
VERIFY_ARE_EQUAL(U("key1=val1;key2=val2"), u.query());
}
} // SUITE(constructor_tests)
}}}
| 32.651376 | 114 | 0.642737 | fpelliccioni |
c057107dfc15048f2e3953ddaad01a9aebe4120a | 766 | cpp | C++ | random_contest/Y2019/practice_for_preli/FLifeOfPhi/Solution.cpp | Reshad-Hasan/problem_solving | 1ef4c83fb329b5b51af9fa357db5bd39b537a9ea | [
"MIT"
] | 17 | 2019-09-23T04:09:13.000Z | 2020-07-27T02:51:51.000Z | random_contest/Y2019/practice_for_preli/FLifeOfPhi/Solution.cpp | Reshad-Hasan/problem_solving | 1ef4c83fb329b5b51af9fa357db5bd39b537a9ea | [
"MIT"
] | 15 | 2019-09-23T06:33:47.000Z | 2020-06-04T18:55:45.000Z | random_contest/Y2019/practice_for_preli/FLifeOfPhi/Solution.cpp | Reshad-Hasan/problem_solving | 1ef4c83fb329b5b51af9fa357db5bd39b537a9ea | [
"MIT"
] | 16 | 2019-09-21T23:19:58.000Z | 2020-06-18T07:26:39.000Z | // problem name: Life of Phi
// problem link: https://toph.co/p/life-of-phi
// contest link: https://toph.co/c/practice-icpc-2019-dhaka
// author: reyad
// time: (?)
#include <bits/stdc++.h>
using namespace std;
#define N 1000000
long long int phi[N + 10], sum[N + 10];
int mark[N + 10] = {0};
int main() {
sum[0] = 0; phi[0] = 0;
for(int i=1; i<=N; i++) {
phi[i] = i;
sum[i] = sum[i-1] + i;
}
phi[1] = 1;
mark[1] = 1;
for(int i=2; i<=N; i++) {
if(!mark[i]) {
for(int j=i; j<=N; j+=i) {
mark[j] = 1;
phi[j] = (i - 1) * phi[j] / i;
}
}
}
int tc;
scanf("%d", &tc);
for(int cc=0; cc<tc; cc++) {
int n;
scanf("%d", &n);
printf("%lld\n", sum[n-1] - n * phi[n] / 2);
}
return 0;
} | 17.409091 | 60 | 0.469974 | Reshad-Hasan |
c0599bf96e856e85af1d2b3bbbb0eb96ce47ee04 | 65 | cpp | C++ | VytUtils/InjectHook/InjectHook.cpp | Vyterm/VytHug | 22b4c6708a23898d41fc49d604c54790b4f8c965 | [
"MIT"
] | null | null | null | VytUtils/InjectHook/InjectHook.cpp | Vyterm/VytHug | 22b4c6708a23898d41fc49d604c54790b4f8c965 | [
"MIT"
] | null | null | null | VytUtils/InjectHook/InjectHook.cpp | Vyterm/VytHug | 22b4c6708a23898d41fc49d604c54790b4f8c965 | [
"MIT"
] | null | null | null | // InjectHook.cpp : 定义 DLL 应用程序的导出函数。
//
#include "stdafx.h"
| 9.285714 | 38 | 0.630769 | Vyterm |
c05d95a857f69853734f34c056ad5b995340d66b | 4,255 | hpp | C++ | teal/include/data/states.hpp | S6066/Teal | d2b4c4474be5caead2db956b3e11894472c8d465 | [
"X11"
] | 22 | 2016-07-12T14:17:21.000Z | 2019-02-16T19:05:32.000Z | teal/include/data/states.hpp | S6066/Teal | d2b4c4474be5caead2db956b3e11894472c8d465 | [
"X11"
] | null | null | null | teal/include/data/states.hpp | S6066/Teal | d2b4c4474be5caead2db956b3e11894472c8d465 | [
"X11"
] | 3 | 2016-12-02T06:38:04.000Z | 2018-11-25T05:59:46.000Z | // Copyright (C) 2019 Samy Bensaid
// This file is part of the Teal project.
// For conditions of distribution and use, see copyright notice in LICENSE
#pragma once
#ifndef TEAL_STATES_HPP
#define TEAL_STATES_HPP
#include <Nazara/Core/String.hpp>
#include <Nazara/Renderer/Texture.hpp>
#include <Nazara/Lua/LuaState.hpp>
#include <utility>
#include <unordered_map>
#include "data/elementdata.hpp"
#include "def/typedef.hpp"
#include "util/assert.hpp"
#include "util/util.hpp"
struct State
{
State() = default;
virtual ~State() = default;
virtual void serialize(const Nz::LuaState& state) = 0;
struct FightInfo
{
std::unordered_map<Element, int> maximumDamage; // positive: damage, negative: heal
std::unordered_map<Element, int> attackModifier; // positive: boost, negative: nerf
std::unordered_map<Element, int> resistanceModifier; // positive: boost, negative: nerf
int movementPointsDifference {};
int actionPointsDifference {};
enum StateFlag
{
None,
Paralyzed,
Sleeping,
Confused
} flags { None };
};
virtual FightInfo getFightInfo() = 0;
};
enum class StateType
{
PoisonnedState,
HealedState,
WeaknessState,
PowerState,
ParalyzedState,
SleepingState,
ConfusedState
};
inline Nz::String stateTypeToString(StateType stateType);
inline StateType stringToStateType(Nz::String string);
struct PoisonnedState : public State
{
inline PoisonnedState(const Nz::LuaState& state, int index = -1);
std::pair<Element, unsigned> damage;
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::PoisonnedState; }
};
struct HealedState : public State
{
inline HealedState(const Nz::LuaState& state, int index = -1);
std::pair<Element, unsigned> health;
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::HealedState; }
};
struct StatsModifierState : public State
{
inline StatsModifierState(const Nz::LuaState& state, int index = -1);
std::unordered_map<Element, int> attack;
std::unordered_map<Element, int> resistance;
int movementPoints {};
int actionPoints {};
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
};
struct WeaknessState : public StatsModifierState
{
inline WeaknessState(const Nz::LuaState& state, int index = -1) : StatsModifierState(state, index) {}
virtual inline void serialize(const Nz::LuaState& state) override;
static StateType getStateType() { return StateType::WeaknessState; }
};
struct PowerState : public StatsModifierState
{
inline PowerState(const Nz::LuaState& state, int index = -1) : StatsModifierState(state, index) {}
virtual inline void serialize(const Nz::LuaState& state) override;
static StateType getStateType() { return StateType::PowerState; }
};
struct ParalyzedState : public State
{
inline ParalyzedState(const Nz::LuaState& state, int index = -1) {}
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::ParalyzedState; }
};
struct SleepingState : public State // = paralyzed until attacked
{
inline SleepingState(const Nz::LuaState& state, int index = -1) {}
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::SleepingState; }
};
struct ConfusedState : public State // aka drunk
{
inline ConfusedState(const Nz::LuaState& state, int index = -1) {}
virtual inline void serialize(const Nz::LuaState& state) override;
virtual inline FightInfo getFightInfo() override;
static StateType getStateType() { return StateType::ConfusedState; }
};
#include "states.inl"
#endif // TEAL_STATES_HPP
| 29.344828 | 109 | 0.704113 | S6066 |
c06502bee9f477c1f768452c8e583ab0d9b47d8d | 5,814 | hpp | C++ | Nacro/SDK/FN_News_classes.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 11 | 2021-08-08T23:25:10.000Z | 2022-02-19T23:07:22.000Z | Nacro/SDK/FN_News_classes.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 1 | 2022-01-01T22:51:59.000Z | 2022-01-08T16:14:15.000Z | Nacro/SDK/FN_News_classes.hpp | Milxnor/Nacro | eebabf662bbce6d5af41820ea0342d3567a0aecc | [
"BSD-2-Clause"
] | 8 | 2021-08-09T13:51:54.000Z | 2022-01-26T20:33:37.000Z | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// WidgetBlueprintGeneratedClass News.News_C
// 0x0048 (0x0428 - 0x03E0)
class UNews_C : public UCommonActivatablePanel
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x03E0(0x0008) (Transient, DuplicateTransient)
class UIconTextButton_C* CloseButton; // 0x03E8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UScrollBox* DescriptionScroll; // 0x03F0(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class ULightbox_C* Lightbox; // 0x03F8(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UImage* MainIcon; // 0x0400(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UScrollBox* ScrollBoxEntries; // 0x0408(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonTextBlock* TextDescription; // 0x0410(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonTextBlock* Title; // 0x0418(0x0008) (BlueprintVisible, ExportObject, ZeroConstructor, InstancedReference, IsPlainOldData, RepSkip, RepNotify, Interp, NonTransactional, EditorOnly, NoDestructor, AutoWeak, ContainsInstancedReference, AssetRegistrySearchable, SimpleDisplay, AdvancedDisplay, Protected, BlueprintCallable, BlueprintAuthorityOnly, TextExportTransient, NonPIEDuplicateTransient, ExposeOnSpawn, PersistentInstance, UObjectWrapper, HasGetValueTypeHash, NativeAccessSpecifierPublic, NativeAccessSpecifierProtected, NativeAccessSpecifierPrivate)
class UCommonButtonGroup* ButtonGroup; // 0x0420(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("WidgetBlueprintGeneratedClass News.News_C");
return ptr;
}
void UpdateInfoPanel(const struct FText& BodyText);
void Init();
void PopulateEntries(bool* IsEmpty);
void AddEntry(const struct FText& inEntryText);
void BndEvt__CloseButton_K2Node_ComponentBoundEvent_21_CommonButtonClicked__DelegateSignature(class UCommonButton* Button);
void Construct();
void ExecuteUbergraph_News(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 111.807692 | 644 | 0.74011 | Milxnor |
c0665160623b93cb0f507861f30d7841f0bb0eb6 | 2,950 | hpp | C++ | include/veritacpp/dsl/math/variable.hpp | Nekrolm/veritacpp | 015c9dc2027154c8754a1b61040ce6d0bf807a47 | [
"MIT"
] | null | null | null | include/veritacpp/dsl/math/variable.hpp | Nekrolm/veritacpp | 015c9dc2027154c8754a1b61040ce6d0bf807a47 | [
"MIT"
] | null | null | null | include/veritacpp/dsl/math/variable.hpp | Nekrolm/veritacpp | 015c9dc2027154c8754a1b61040ce6d0bf807a47 | [
"MIT"
] | null | null | null | #pragma once
#include <algorithm>
#include <veritacpp/dsl/math/core_concepts.hpp>
#include <veritacpp/dsl/math/constants.hpp>
namespace veritacpp::dsl::math {
template <uint64_t N>
struct Variable;
template<uint64_t N, Functional F>
struct VariableBindingHolder {
F f;
static constexpr auto VariableID = N;
constexpr VariableBindingHolder(Variable<N>, F f) : f{f} {}
constexpr Functional auto operator()(Variable<N>) const {
return f;
}
};
template <uint64_t N, Functional F>
VariableBindingHolder(Variable<N>, F) -> VariableBindingHolder<N, F>;
template <class T>
struct IsVariableBinding : std::false_type {};
template <uint64_t N, Functional F>
struct IsVariableBinding<VariableBindingHolder<N, F>> : std::true_type {};
template <class T>
concept VariableBinding = IsVariableBinding<T>::value;
template <VariableBinding... Var>
struct VariableBindingGroup : Var... {
using Var::operator()...;
static constexpr auto MaxVariableID = std::max({ Var::VariableID... });
template<uint64_t N> requires ((N != Var::VariableID) && ...)
constexpr Functional auto operator () (Variable<N> x) const {
return x;
}
};
template <VariableBinding... Var>
VariableBindingGroup(Var...) -> VariableBindingGroup<Var...>;
template <uint64_t N>
struct Variable : BasicFunction {
static constexpr auto Id = N;
constexpr Arithmetic auto operator()(Arithmetic auto... args) const
requires (sizeof...(args) > N)
{
return std::get<N>(std::make_tuple(args...));
}
template <Functional F>
constexpr auto operator = (F f) const {
return VariableBindingGroup { VariableBindingHolder<N, F>(*this, f) };
}
};
template <uint64_t N, uint64_t M>
requires (N == M)
Functional auto operator - (Variable<N>, Variable<M>) {
return kZero;
}
template <uint64_t N, uint64_t M>
requires (N == M)
Functional auto operator / (Variable<N>, Variable<M>) {
return kOne;
}
// Veriable<N> requires at least N+1 arguments
static_assert(!(NVariablesFunctional<2, Variable<2>>));
template <VariableBinding... Var>
constexpr bool all_unique_variables = []<uint64_t... idx>(
std::integer_sequence<uint64_t, idx...>){
constexpr std::array arr { idx...};
return ((std::ranges::count(arr, idx) == 1) && ...);
}(std::integer_sequence<uint64_t, Var::VariableID...>{});
template <VariableBinding... Var>
consteval bool group_contains_binding(VariableBindingGroup<Var...>, VariableBinding auto v) {
return ((Var::VariableID == v.VariableID) || ...);
}
template<VariableBinding... V1, VariableBinding... V2>
constexpr auto operator , (VariableBindingGroup<V1...> v1, VariableBindingGroup<V2...> v2) {
static_assert(all_unique_variables<V1..., V2...>,
"rebinding same variable twice is not allowed");
return VariableBindingGroup {
static_cast<V1>(v1)...,
static_cast<V2>(v2)...
};
}
} | 25.652174 | 93 | 0.673898 | Nekrolm |
c06dd69760cadcf599751f81e1f4d434799bc534 | 1,224 | cpp | C++ | RLFPS/Source/RLFPS/Private/ReloadknockBackMod.cpp | Verb-Noun-Studios/Symbiotic | d037b3bbe4925f2d4c97d4c44e45ec0abe88c237 | [
"MIT"
] | 3 | 2022-01-11T03:29:03.000Z | 2022-02-03T03:46:44.000Z | RLFPS/Source/RLFPS/Private/ReloadknockBackMod.cpp | Verb-Noun-Studios/Symbiotic | d037b3bbe4925f2d4c97d4c44e45ec0abe88c237 | [
"MIT"
] | 27 | 2022-02-02T04:54:29.000Z | 2022-03-27T18:58:15.000Z | RLFPS/Source/RLFPS/Private/ReloadknockBackMod.cpp | Verb-Noun-Studios/Symbiotic | d037b3bbe4925f2d4c97d4c44e45ec0abe88c237 | [
"MIT"
] | null | null | null | // Fill out your copyright notice in the Description page of Project Settings.
#include "ReloadknockBackMod.h"
#include "GruntCharacter.h"
#include "Kismet/KismetMathLibrary.h"
#include "Kismet/GameplayStatics.h"
#include "GameFramework/PawnMovementComponent.h"
#include "GameFramework/CharacterMovementComponent.h"
UReloadKnockBackMod::UReloadKnockBackMod()
{
}
UReloadKnockBackMod::~UReloadKnockBackMod()
{
}
void UReloadKnockBackMod::OnReload_Implementation(AActor* player)
{
TArray<AActor*> enemies;
UGameplayStatics::GetAllActorsOfClass(GetWorld(), classToFind, enemies);
for (AActor* enemy : enemies)
{
FVector dir = enemy->GetActorLocation() - player->GetActorLocation();
float distance = dir.Size();
dir.Normalize();
UE_LOG(LogTemp, Warning, TEXT("Reload knockback: TestingDistance to Enemy, Distance: %f"), distance);
if (distance < range + additionalRangePerStack * stacks)
{
dir.Z = FMath::Clamp(dir.Z, 0.2f, 0.3f);
AGruntCharacter* character = Cast<AGruntCharacter>(enemy);
character->GetCharacterMovement()->MovementMode = EMovementMode::MOVE_Flying;
character->LaunchCharacter(dir * (strength + additionalStrengthPerStack * stacks + distance), true, true);
}
}
} | 25.5 | 109 | 0.753268 | Verb-Noun-Studios |
c06e568ee81ec53db067e0e956f0a9284c3ff952 | 5,267 | hpp | C++ | includes/Fox/Lexer/Lexer.hpp | Pierre-vh/Fox | ab3d9a5b3c409b5611840c477abef989830ea571 | [
"MIT"
] | 17 | 2019-01-17T22:41:11.000Z | 2020-08-27T03:39:07.000Z | includes/Fox/Lexer/Lexer.hpp | Pierre-vh/Moonshot | ab3d9a5b3c409b5611840c477abef989830ea571 | [
"MIT"
] | null | null | null | includes/Fox/Lexer/Lexer.hpp | Pierre-vh/Moonshot | ab3d9a5b3c409b5611840c477abef989830ea571 | [
"MIT"
] | 2 | 2019-06-30T19:07:10.000Z | 2019-12-26T17:30:17.000Z | //----------------------------------------------------------------------------//
// Part of the Fox project, licensed under the MIT license.
// See LICENSE.txt in the project root for license information.
// File : Lexer.hpp
// Author : Pierre van Houtryve
//----------------------------------------------------------------------------//
// This file declares the Fox Lexer.
//----------------------------------------------------------------------------//
#pragma once
#include "Token.hpp"
#include "Fox/Common/SourceLoc.hpp"
#include "Fox/Common/string_view.hpp"
namespace fox {
class DiagnosticEngine;
class SourceManager;
/// Lexer
/// The Fox Lexer. An instance of the lexer is tied to a SourceFile
/// (FileID). The lexing process can be initiated by calling lex(), and
/// the resulting tokens will be found in the token vector returned by
/// getTokens()
/// The Token Vector's last token will always be TokenKind::EndOfFile.
class Lexer {
public:
/// Constructor for the Lexer.
/// \param srcMgr The SourceManager instance to use
/// \param diags the DiagnosticEngine instance to use for diagnostics
/// \param file the File that's going to be lexed. It must be a file
/// owned by \p srcMgr.
Lexer(SourceManager& srcMgr, DiagnosticEngine& diags, FileID file);
/// Make this class non copyable, but movable
Lexer(const Lexer&) = delete;
Lexer& operator=(const Lexer&) = delete;
Lexer(Lexer&&) = default;
Lexer& operator=(Lexer&&) = default;
/// lex the full file. the tokens can be retrieved using getTokens()
void lex();
/// \returns the vector of tokens, can only be called if lex() has
/// been called. The token vector is guaranteed to have a EOF token
/// as the last token.
TokenVector& getTokens();
/// Returns a SourceLoc for the character (or codepoint beginning) at
/// \p ptr.
///
/// \p ptr cannot be null and must be contained in the buffer of
/// \ref theFile
SourceLoc getLocFromPtr(const char* ptr) const;
/// Returns a SourceRange for the range beginning at \p a and ending
/// at \p b (range [a, b])
///
/// Both pointers must satisfy the same constraint as the argument of
/// \ref getLocFromPtr
SourceRange getRangeFromPtrs(const char* a, const char* b) const;
/// \returns the number of tokens in the vector
std::size_t numTokens() const;
/// The DiagnosticEngine instance used by this Lexer
DiagnosticEngine& diagEngine;
/// The SourceManager instance used by this Lexer
SourceManager& sourceMgr;
/// The FileID of the file being lexed
const FileID theFile;
private:
// Pushes the current token with the kind "kind"
void pushTok(TokenKind kind);
// Pushes the current token character as a token with the kind "kind"
// (calls resetToken() + pushToken())
void beginAndPushToken(TokenKind kind);
// Calls advance(), then pushes the current token with the kind 'kind'
void advanceAndPushTok(TokenKind kind);
// Returns true if we reached EOF.
bool isEOF() const;
// Begins a new token
void resetToken();
// Entry point of the lexing process
void lexImpl();
// Lex an identifier or keyword
void lexIdentifierOrKeyword();
// Lex an int or double literal
void lexIntOrDoubleConstant();
/// Lex any number of text items (a string_item or char_item,
/// depending on \p delimiter)
/// \p delimiter The delimiter. Can only be ' or ".
/// \return true if the delimiter was found, false otherwise
bool lexTextItems(FoxChar delimiter);
// Lex a piece of text delimited by single quotes '
void lexCharLiteral();
// Lex a piece of text delimited by double quotes "
void lexStringLiteral();
// Lex an integer literal
void lexIntConstant();
// Handles a single-line comment
void skipLineComment();
// Handles a multi-line comment
void skipBlockComment();
// Returns true if 'ch' is a valid identifier head.
bool isValidIdentifierHead(FoxChar ch) const;
// Returns true if 'ch' is a valid identifier character.
bool isValidIdentifierChar(FoxChar ch) const;
// Returns the current character being considered
FoxChar getCurChar() const;
// Peeks the next character that will be considered
FoxChar peekNextChar() const;
// Advances to the next codepoint in the input.
// Returns false if we reached EOF.
bool advance();
SourceLoc getCurPtrLoc() const;
SourceLoc getCurtokBegLoc() const;
SourceRange getCurtokRange() const;
string_view getCurtokStringView() const;
const char* fileBeg_ = nullptr;
const char* fileEnd_ = nullptr;
// The pointer to the first byte of the token
const char* tokBegPtr_ = nullptr;
// The pointer to the current character being considered.
// (pointer to the first byte in the UTF8 codepoint)
const char* curPtr_ = nullptr;
TokenVector tokens_;
};
}
| 36.576389 | 80 | 0.617809 | Pierre-vh |
c0720c10013f99293aa1ab2ebc4d9bf3286bc964 | 8,572 | cpp | C++ | SampleMathematics/PointInPolyhedron/PointInPolyhedron.cpp | CRIMSONCardiovascularModelling/WildMagic5 | fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c | [
"BSL-1.0"
] | null | null | null | SampleMathematics/PointInPolyhedron/PointInPolyhedron.cpp | CRIMSONCardiovascularModelling/WildMagic5 | fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c | [
"BSL-1.0"
] | null | null | null | SampleMathematics/PointInPolyhedron/PointInPolyhedron.cpp | CRIMSONCardiovascularModelling/WildMagic5 | fcf549bfb99a5c4b3d6ffbff18aabdc1a4e9085c | [
"BSL-1.0"
] | null | null | null | // Geometric Tools, LLC
// Copyright (c) 1998-2014
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt
// http://www.geometrictools.com/License/Boost/LICENSE_1_0.txt
//
// File Version: 5.0.0 (2010/01/01)
#include "PointInPolyhedron.h"
WM5_WINDOW_APPLICATION(PointInPolyhedron);
// Enable only one at a time to test the algorithm.
//#define TRIFACES
//#define CVXFACES0
//#define CVXFACES1
//#define CVXFACES2
//#define SIMFACES0
#define SIMFACES1
//----------------------------------------------------------------------------
PointInPolyhedron::PointInPolyhedron ()
:
WindowApplication3("SampleMathematics/PointInPolyhedron", 0, 0, 1024,
768, Float4(0.75f, 0.75f, 0.75f, 1.0f)),
mTextColor(1.0f, 1.0f, 1.0f, 1.0f)
{
mQuery = 0;
mTFaces = 0;
mCFaces = 0;
mSFaces = 0;
mNumRays = 5;
mRayDirections = new1<Vector3f>(mNumRays);
for (int i = 0; i < mNumRays; ++i)
{
double point[3];
RandomPointOnHypersphere(3, point);
for (int j = 0; j < 3; ++j)
{
mRayDirections[i][j] = (float)point[j];
}
}
}
//----------------------------------------------------------------------------
bool PointInPolyhedron::OnInitialize ()
{
if (!WindowApplication3::OnInitialize())
{
return false;
}
// Set up the camera.
mCamera->SetFrustum(60.0f, GetAspectRatio(), 0.001f, 10.0f);
APoint camPosition(4.0f, 0.0f, 0.0f);
AVector camDVector(-1.0f, 0.0f, 0.0f);
AVector camUVector(0.0f, 0.0f, 1.0f);
AVector camRVector = camDVector.Cross(camUVector);
mCamera->SetFrame(camPosition, camDVector, camUVector, camRVector);
CreateScene();
// Initial update of objects.
mScene->Update();
// Initial culling of scene.
mCuller.SetCamera(mCamera);
mCuller.ComputeVisibleSet(mScene);
InitializeCameraMotion(0.01f, 0.01f);
InitializeObjectMotion(mScene);
return true;
}
//----------------------------------------------------------------------------
void PointInPolyhedron::OnTerminate ()
{
delete1(mRayDirections);
mScene = 0;
mWireState = 0;
mPoints = 0;
WindowApplication3::OnTerminate();
}
//----------------------------------------------------------------------------
void PointInPolyhedron::OnIdle ()
{
MeasureTime();
MoveCamera();
MoveObject();
mScene->Update(GetTimeInSeconds());
mCuller.ComputeVisibleSet(mScene);
if (mRenderer->PreDraw())
{
mRenderer->ClearBuffers();
mRenderer->Draw(mCuller.GetVisibleSet());
DrawFrameRate(8, GetHeight()-8, mTextColor);
mRenderer->PostDraw();
mRenderer->DisplayColorBuffer();
}
UpdateFrameCount();
}
//----------------------------------------------------------------------------
bool PointInPolyhedron::OnKeyDown (unsigned char key, int x, int y)
{
if (WindowApplication3::OnKeyDown(key, x, y))
{
return true;
}
switch (key)
{
case 'w':
case 'W':
mWireState->Enabled = !mWireState->Enabled;
break;
}
return false;
}
//----------------------------------------------------------------------------
void PointInPolyhedron::CreateScene ()
{
mScene = new0 Node();
mWireState = new0 WireState();
mRenderer->SetOverrideWireState(mWireState);
// Create a semitransparent sphere mesh.
VertexFormat* vformatMesh = VertexFormat::Create(1,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0);
TriMesh* mesh = StandardMesh(vformatMesh).Sphere(16, 16, 1.0f);
Material* material = new0 Material();
material->Diffuse = Float4(1.0f, 0.0f, 0.0f, 0.25f);
VisualEffectInstance* instance = MaterialEffect::CreateUniqueInstance(
material);
instance->GetEffect()->GetAlphaState(0, 0)->BlendEnabled = true;
mesh->SetEffectInstance(instance);
// Create the data structures for the polyhedron that represents the
// sphere mesh.
CreateQuery(mesh);
// Create a set of random points. Points inside the polyhedron are
// colored white. Points outside the polyhedron are colored blue.
VertexFormat* vformat = VertexFormat::Create(2,
VertexFormat::AU_POSITION, VertexFormat::AT_FLOAT3, 0,
VertexFormat::AU_COLOR, VertexFormat::AT_FLOAT3, 0);
int vstride = vformat->GetStride();
VertexBuffer* vbuffer = new0 VertexBuffer(1024, vstride);
VertexBufferAccessor vba(vformat, vbuffer);
Float3 white(1.0f, 1.0f, 1.0f);
Float3 blue(0.0f, 0.0f, 1.0f);
for (int i = 0; i < vba.GetNumVertices(); ++i)
{
Vector3f random(Mathf::SymmetricRandom(),
Mathf::SymmetricRandom(), Mathf::SymmetricRandom());
vba.Position<Vector3f>(i) = random;
if (mQuery->Contains(random))
{
vba.Color<Float3>(0, i) = white;
}
else
{
vba.Color<Float3>(0, i) = blue;
}
}
DeleteQuery();
mPoints = new0 Polypoint(vformat, vbuffer);
mPoints->SetEffectInstance(VertexColor3Effect::CreateUniqueInstance());
mScene->AttachChild(mPoints);
mScene->AttachChild(mesh);
}
//----------------------------------------------------------------------------
void PointInPolyhedron::CreateQuery (TriMesh* mesh)
{
const VertexBuffer* vbuffer = mesh->GetVertexBuffer();
const int numVertices = vbuffer->GetNumElements();
const Vector3f* vertices = (Vector3f*)vbuffer->GetData();
const IndexBuffer* ibuffer = mesh->GetIndexBuffer();
const int numIndices = ibuffer->GetNumElements();
const int numFaces = numIndices/3;
const int* indices = (int*)ibuffer->GetData();
const int* currentIndex = indices;
int i;
#ifdef TRIFACES
mTFaces = new1<PointInPolyhedron3f::TriangleFace>(numFaces);
for (i = 0; i < numFaces; ++i)
{
int v0 = *currentIndex++;
int v1 = *currentIndex++;
int v2 = *currentIndex++;
mTFaces[i].Indices[0] = v0;
mTFaces[i].Indices[1] = v1;
mTFaces[i].Indices[2] = v2;
mTFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]);
}
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mTFaces, mNumRays, mRayDirections);
#endif
#if defined(CVXFACES0) || defined(CVXFACES1) || defined(CVXFACES2)
mCFaces = new1<PointInPolyhedron3f::ConvexFace>(numFaces);
for (i = 0; i < numFaces; ++i)
{
int v0 = *currentIndex++;
int v1 = *currentIndex++;
int v2 = *currentIndex++;
mCFaces[i].Indices.resize(3);
mCFaces[i].Indices[0] = v0;
mCFaces[i].Indices[1] = v1;
mCFaces[i].Indices[2] = v2;
mCFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]);
}
#ifdef CVXFACES0
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mCFaces, mNumRays, mRayDirections, 0);
#else
#ifdef CVXFACES1
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mCFaces, mNumRays, mRayDirections, 1);
#else
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mCFaces, mNumRays, mRayDirections, 2);
#endif
#endif
#endif
#if defined (SIMFACES0) || defined (SIMFACES1)
mSFaces = new1<PointInPolyhedron3f::SimpleFace>(numFaces);
for (i = 0; i < numFaces; ++i)
{
int v0 = *currentIndex++;
int v1 = *currentIndex++;
int v2 = *currentIndex++;
mSFaces[i].Indices.resize(3);
mSFaces[i].Indices[0] = v0;
mSFaces[i].Indices[1] = v1;
mSFaces[i].Indices[2] = v2;
mSFaces[i].Plane = Plane3f(vertices[v0], vertices[v1], vertices[v2]);
mSFaces[i].Triangles.resize(3);
mSFaces[i].Triangles[0] = v0;
mSFaces[i].Triangles[1] = v1;
mSFaces[i].Triangles[2] = v2;
}
#ifdef SIMFACES0
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mSFaces, mNumRays, mRayDirections, 0);
#else
mQuery = new0 PointInPolyhedron3f(numVertices, vertices, numFaces,
mSFaces, mNumRays, mRayDirections, 1);
#endif
#endif
}
//----------------------------------------------------------------------------
void PointInPolyhedron::DeleteQuery ()
{
delete0(mQuery);
#ifdef TRIANGLE_FACES
delete1(mTFaces);
#endif
#if defined(CVXFACES0) || defined(CVXFACES1) || defined(CVXFACES2)
delete1(mCFaces);
#endif
#if defined (SIMFACES0) || defined (SIMFACES1)
delete1(mSFaces);
#endif
}
//----------------------------------------------------------------------------
| 29.457045 | 78 | 0.589011 | CRIMSONCardiovascularModelling |
c0746d375d5c43d68cfad1896e7a3ab6178e2c35 | 4,171 | cc | C++ | lite/kernels/cuda/sequence_arithmetic_compute_test.cc | peblue12345/Paddle-Lite | 3176ffcf9e0c9fec07f1a9d3f53efed5bb177696 | [
"Apache-2.0"
] | 1,799 | 2019-08-19T03:29:38.000Z | 2022-03-31T14:30:50.000Z | lite/kernels/cuda/sequence_arithmetic_compute_test.cc | peblue12345/Paddle-Lite | 3176ffcf9e0c9fec07f1a9d3f53efed5bb177696 | [
"Apache-2.0"
] | 3,767 | 2019-08-19T03:36:04.000Z | 2022-03-31T14:37:26.000Z | lite/kernels/cuda/sequence_arithmetic_compute_test.cc | yingshengBD/Paddle-Lite | eea59b66f61bb2acad471010c9526eeec43a15ca | [
"Apache-2.0"
] | 798 | 2019-08-19T02:28:23.000Z | 2022-03-31T08:31:54.000Z | // Copyright (c) 2019 PaddlePaddle Authors. 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 "lite/kernels/cuda/sequence_arithmetic_compute.h"
#include <gtest/gtest.h>
#include <algorithm>
#include <memory>
#include <utility>
#include <vector>
#include "lite/core/op_registry.h"
namespace paddle {
namespace lite {
namespace kernels {
namespace cuda {
void sequence_arithmetic_compute_ref(const Tensor& x,
const Tensor& y,
Tensor* out,
int op_type) {
auto x_data = x.data<float>();
auto y_data = y.data<float>();
out->Resize(x.dims());
out->set_lod(x.lod());
auto out_data = out->mutable_data<float>();
auto x_seq_offset = x.lod()[0];
auto y_seq_offset = y.lod()[0];
int seq_num = x_seq_offset.size() - 1;
int inner_size = x.numel() / x.dims()[0];
for (int i = 0; i < seq_num; i++) {
int len_x = (x_seq_offset[i + 1] - x_seq_offset[i]) * inner_size;
int len_y = (y_seq_offset[i + 1] - y_seq_offset[i]) * inner_size;
auto input_x = x_data + x_seq_offset[i] * inner_size;
auto input_y = y_data + y_seq_offset[i] * inner_size;
auto t_out = out_data + x_seq_offset[i] * inner_size;
int len = std::min(len_x, len_y);
for (int j = 0; j < len; j++) {
switch (op_type) {
case 1:
t_out[j] = input_x[j] + input_y[j];
break;
case 2:
t_out[j] = input_x[j] - input_y[j];
break;
case 3:
t_out[j] = input_x[j] * input_y[j];
break;
default:
break;
}
}
if (len_x > len) {
memcpy(t_out + len, input_x + len, sizeof(float) * (len_x - len));
}
}
}
void prepare_input(Tensor* x, const LoD& x_lod) {
x->Resize({static_cast<int64_t>(x_lod[0].back()), 3});
x->set_lod(x_lod);
auto x_data = x->mutable_data<float>();
for (int i = 0; i < x->numel(); i++) {
x_data[i] = (i - x->numel() / 2) * 1.1;
}
}
TEST(sequence_arithmetic_cuda, run_test) {
lite::Tensor x, y, x_cpu, y_cpu;
lite::Tensor out, out_cpu, out_ref;
lite::LoD x_lod{{0, 2, 5, 9}}, y_lod{{0, 2, 5, 9}};
prepare_input(&x_cpu, x_lod);
prepare_input(&y_cpu, y_lod);
x.Resize(x_cpu.dims());
x.set_lod(x_cpu.lod());
auto x_cpu_data = x_cpu.mutable_data<float>();
x.Assign<float, lite::DDim, TARGET(kCUDA)>(x_cpu_data, x_cpu.dims());
y.Resize(y_cpu.dims());
y.set_lod(y_cpu.lod());
auto y_cpu_data = y_cpu.mutable_data<float>();
y.Assign<float, lite::DDim, TARGET(kCUDA)>(y_cpu_data, y_cpu.dims());
operators::SequenceArithmeticParam param;
param.X = &x;
param.Y = &y;
param.Out = &out;
param.op_type = 1;
std::unique_ptr<KernelContext> ctx(new KernelContext);
auto& context = ctx->As<CUDAContext>();
cudaStream_t stream;
cudaStreamCreate(&stream);
context.SetExecStream(stream);
SequenceArithmeticCompute sequence_arithmetic;
sequence_arithmetic.SetContext(std::move(ctx));
sequence_arithmetic.SetParam(param);
sequence_arithmetic.Run();
cudaDeviceSynchronize();
auto out_data = out.mutable_data<float>(TARGET(kCUDA));
out_cpu.Resize(out.dims());
auto out_cpu_data = out_cpu.mutable_data<float>();
CopySync<TARGET(kCUDA)>(
out_cpu_data, out_data, sizeof(float) * out.numel(), IoDirection::DtoH);
sequence_arithmetic_compute_ref(x_cpu, y_cpu, &out_ref, param.op_type);
auto out_ref_data = out_ref.data<float>();
for (int i = 0; i < out.numel(); i++) {
EXPECT_NEAR(out_cpu_data[i], out_ref_data[i], 1e-3);
}
}
} // namespace cuda
} // namespace kernels
} // namespace lite
} // namespace paddle
| 31.598485 | 78 | 0.641333 | peblue12345 |
c07473128d2487829da72e764b45a69ee9d6ac17 | 4,564 | hpp | C++ | engine/include/ph/game_loop/DefaultGameUpdateable.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/game_loop/DefaultGameUpdateable.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | engine/include/ph/game_loop/DefaultGameUpdateable.hpp | PetorSFZ/PhantasyEngine | befe8e9499b7fd93d8765721b6841337a57b0dd6 | [
"Zlib"
] | null | null | null | // Copyright (c) Peter Hillerström (skipifzero.com, peter@hstroem.se)
// For other contributors see Contributors.txt
//
// 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.
#pragma once
#include <sfz/memory/Allocator.hpp>
#include <sfz/memory/SmartPointers.hpp>
#include "ph/game_loop/GameLoopUpdateable.hpp"
namespace ph {
using sfz::Allocator;
using sfz::UniquePtr;
using sfz::vec3;
using sfz::vec4;
// DefaultGameUpdateable logic
// ------------------------------------------------------------------------------------------------
struct ImguiControllers final {
bool useMouse = true;
bool useKeyboard = true;
int32_t controllerIndex = -1;
};
class GameLogic {
public:
virtual ~GameLogic() {}
virtual void initialize(Renderer& renderer) = 0;
// Returns the index of the controller to be used for Imgui. If -1 is returned no controller
// input will be provided to Imgui.
virtual ImguiControllers imguiController(const UserInput&) { return ImguiControllers(); }
virtual UpdateOp processInput(
const UserInput& input,
const UpdateInfo& updateInfo,
Renderer& renderer) = 0;
virtual UpdateOp updateTick(const UpdateInfo& updateInfo, Renderer& renderer) = 0;
virtual void render(const UpdateInfo& updateInfo, Renderer& renderer) = 0;
// Small hook that is called last in a frame, after rendering, regardless of whether the
// console is active or not.
//
// This is useful if you need to do some operations each frame when the renderer is not busy
// preparing commands to render a new frame (i.e., not between beginFrame() and finishFrame()).
//
// This is also the last thing that happens each frame, so it can also be a good place to put
// some per frame book keeping you are doing.
virtual void postRenderHook(ph::Renderer& renderer, bool consoleActive) {};
// Renders custom Imgui commands.
//
// This function and injectConsoleMenu() are the only places where Imgui commands can safely
// be called. BeginFrame() and EndFrame() are called before and after this function. Other
// Imgui commands from the DefaultGameUpdateable console itself may be sent within this same
// frame if they are set to be always shown. This function will not be called if the console
// is currently active.
virtual void renderCustomImgui() {}
// Call when console is active after all the built-in menus have been drawn. Can be used to
// inject game-specific custom menus into the console.
virtual void injectConsoleMenu() {}
// These two functions are used to dock injected console windows. The first one should return
// the number of windows you want to dock, the second one the name of each window given the
// index in the range you provided with the first function. These are typically only called
// during the first boot of the engine/game. You don't need to provide them even if you are
// injecting console windows;
virtual uint32_t injectConsoleMenuNumWindowsToDockInitially() { return 0; }
virtual const char* injectConsoleMenuNameOfWindowToDockInitially(uint32_t idx) { (void)idx; return nullptr; }
// Called when console is activated. The logic instance will not receive any additional calls
// until the console is closed, at which point onConsoleDeactivated() will be called. onQuit()
// may be called before the console is deactivated.
virtual void onConsoleActivated() {}
// Called when the console is deactivated.
virtual void onConsoleDeactivated() {}
virtual void onQuit() { }
};
// DefaultGameUpdateable creation function
// ------------------------------------------------------------------------------------------------
UniquePtr<GameLoopUpdateable> createDefaultGameUpdateable(
Allocator* allocator,
UniquePtr<GameLogic> logic) noexcept;
} // namespace ph
| 40.389381 | 110 | 0.724145 | PetorSFZ |
c07cae9204e813066bd15ab25d27470cdc4a1a8f | 14,576 | hpp | C++ | include/drone.hpp | KPO-2020-2021/zad5_1-kgliwinski | 0bd90e1e065f32363c77ad02e217406487850a99 | [
"Unlicense"
] | null | null | null | include/drone.hpp | KPO-2020-2021/zad5_1-kgliwinski | 0bd90e1e065f32363c77ad02e217406487850a99 | [
"Unlicense"
] | null | null | null | include/drone.hpp | KPO-2020-2021/zad5_1-kgliwinski | 0bd90e1e065f32363c77ad02e217406487850a99 | [
"Unlicense"
] | null | null | null | #pragma once
#include "prism.hpp"
#include "cuboid.hpp"
#include "lacze_do_gnuplota.hpp"
#include <unistd.h>
#include <vector>
/*!
* \file drone.hpp
*
* \brief Plik zawiera definicję klasy reprezentujacej drona,
* budowanie i przemieszczanie go
*/
/*!
* \class Drone
* \brief Opisuje drona o prostopadlosciennym korpusie i 4 rotorach
*/
class Drone
{
private:
/*!
* \brief Zmienna reprezentujaca polozenie drona (dokladnie
* polozenie punktu centralnego prostopadloscianu body)
*/
Vector3D drone_pos;
/*!
* \brief Zmienna reprezentujaca zwrot drona.
* Reprezentowana przez jednostkowy Vector,
* nie dopuszcza sie zwrotu pionowego.
*/
Vector3D drone_orient;
/*!
* \brief Zmienna reprezentujaca zwrot drona jako kat w stopniach.
*/
double drone_angle;
/*!
* \brief Tablica graniastoslupow szesciokatnych,
* reprezentujaca rotory drona
*/
Prism rotors[4];
/*!
* \brief Prostopadloscian reprezentujacy korpus drona
*/
Cuboid body;
public:
/*!
* \brief Konstruktor bezparametryczny klasy Drone.
* Powstaly dron jest skonstruowany z bezparametrycznych
* prostopadloscianu (body) oraz rotorow przeskalowanych
* 10-krotnie (aby sie poprawnie wyswietlal) w poziomie i
* 5-krotnie w pionie (aby zachowac pewna poprawna skale)
* \post Inicjalizuje podstawowego drona
*/
Drone();
/*!
* \brief Metoda uzywana przy konstruowania drona
* Ustawia rotory w ten sposob, ze srodek ich dolnej
* podstawy jest w tym samym punkcie co wierzcholki
* gornej podstawy body
* \post Zmienia pozycje rotorow = *this
*/
void set_rotors_in_place();
/*!
* \brief Przesuwa drona o zadany wektor w 3D
* \param[in] trans - Vector3D
* \param[out] translated - Dron po operacji przesuniecia
*/
Drone translation(Vector3D const &tran) const;
/*!
* \brief Metoda uzywana przy konstruowania drona
* przesuwa drona w ten sposob, ze Vector3D
* centre prostopadloscianu body pokrywa sie
* z Vector3D pos
* \returns translated - przesuniety dron
*/
Drone translation_to_pos() const;
/*!
* \brief Metoda obracajaca dron o zadany kat w 3D wokol srodka figury
* \param[in] mat - macierz obrotu
* \param[out] rotated - dron po przeprowadzonej rotacji
*/
Drone rotation_around_cen(const Matrix3D &mat) const;
/*!
* \brief Metoda skalujaca wszystkie elementy drona przez skale kazdego elementu
* \param[out] scaled - dron po operacji skalowania
*/
Drone scale_dro() const;
/*!
* \brief Przeciazenie operatora == dla klasy Drone
* \param[in] dro - porownywany dron
* \retval false - nie sa rowne,
* \retval true - sa rowne
*/
bool operator==(const Drone &dro) const;
/*!
* \brief Metoda ustawiajaca drone_pos
* \pre Pozycja drona musi znajdowac sie nad plaszcyzna.
* Punktem referencji jest srodek prostopadloscianu body, wiec
* aby dron nie zapadal sie w podloze, minimalna wspolrzedna z polozenia
* nie moze nigdy byc mniejsza od polowy wysokosci prostopadloscianu
* \param[in] pos - wektor pozycji
* \post Ustawia pozycje drona (zadana przez uzytkownika)
* \retval false - jesli wprowadzona pozycja jest bledna
* \retval true - jesli jest prawidlowa
*/
bool set_drone_pos(Vector3D const &pos);
/*!
* \brief Metoda wypisuje na standardowym wyjsciu pozycje drona (bez wysokosci)
*/
void print_drone_pos() const;
/*!
* \brief Metoda ustawiajaca skale wszystkich elementow drona
* \param[in] bod - skala korpusu
* \param[in] rot - skala rotorow
* \post Ustawia skale korpusa i rotorow
*/
void set_scale_all(Vector3D const &bod, Vector3D const &rot);
/*!
* \brief Metoda zwracajaca wszystkie elementy drona do odpowiednich zmiennych
* \param[in] b - tu zwrocone bedzie body
* \param[in] rot - tu zostana zwrocone odpowiednio rotory
* \param[in] p - wektor pozycji
* \post Zwraca odpowiednio pola klasy Drone
*/
void get_dro(Cuboid &b, Prism (&rot)[4], Vector3D &p) const;
/*!
* \brief Metoda sprawdzajaca budowe drona
* \retval true - dron odpowiednio zbudowany
* \retval false - dron blednie zbudowany
*/
bool check_dro() const;
/*!
* \brief Metoda zwracajaca orientacje drona
* \return res - Zwracana orientacja
*/
Vector3D get_orien() const;
/*!
* \brief Metoda sprawdzajaca orientacje drona
* Vector3D dron_orien musi byc jednostkowy, oraz miec skladowa z=0
* \retval true - odpowiednia orientacja
* \retval false - bledna orientacja
*/
bool check_orien() const;
/*!
* \brief Metoda ustawiajaca nazwy plikow do zapisu dla drona
* \param[in] bod - tablica nazw plikow odpowiednio 0-sample_name, 1-final_name;
* zawierajacych dane do korpusu drona
* \param[in] rots - analogiczna tablica co bod, dla rotorow drona
* \post Zmienia obiekt, przypisuje mu odpowiednie parametry
*/
void setup_filenames(std::string const (&bod)[2], std::string const (&rots)[4][2]);
/*!
* \brief Metoda ustawiajaca nazwy plikow w laczy do gnuplota (nazwy final!)
* \param[in] Lacze - lacze do ktorego wpisane zostana nazwy
* \pre Metoda wymaga zainicjowanych nazw elementow drona
* \post Zmienia lacze, przypisuje mu odpowiednie parametry
*/
bool set_filenames_gnuplot(PzG::LaczeDoGNUPlota &Lacze) const;
/*!
* \brief Metoda zwracajaca nazwy plikow do zapisu dla drona
* \param[in] bod - tablica nazw plikow odpowiednio 0-sample_name, 1-final_name;
* do ktorych zwracane sa nazwy
* \param[in] rots - analogiczna tablica co bod, dla rotorow drona
* \return przypisuje argumentom odpowiednie wartosci
*/
void get_filenames(std::string (&bod)[2], std::string (&rots)[4][2]) const;
/*!
* \brief Metoda rysujaca drona w gnuplocie. Przeznaczona do testow
* \post Wyswietla okienko gnuplota z wyrysowanym dronem
*/
void Print_to_gnuplot_drone() const;
/*!
* \brief Metoda zapisujaca parametry drona do plikow (do plikow final kazdego z elementow)
* \post Aktualizuje pliki z danymi
*/
void Print_to_files_drone() const;
/*!
* \brief Metoda animujaca obrot rotorow i zapisujaca to w plikach.
* Metoda sluzy jako metoda pomocnicza, przy kazdej animacji (translacji czy
* rotacji drona) rotory sie niezaleznie obracaja. Ta metoda to umozliwia.
* \pre Pliki musza byc odpowiednio skonfigurowane
* \post Rotory sa obracane o kat 1 stopnia, zmieniany jest obiekt drona
* efekt rotacji zapisywnay jest w plikach
*/
void Rotors_rotation_animation();
/*!
* \brief Metoda animujaca obrot drona i wyrysowujaca calosc w gnuplocie
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] Lacze - aktywne lacze do gnuplota
* \param[in] angle - kat obrotu w stopniach, obrot wykonuje sie wylacznie wokol osi z
* \post W oknie gnuplota wykonuje sie animacja obrotu drona
*/
void Drone_rotation_animation(PzG::LaczeDoGNUPlota Lacze, double const &angle);
/*!
* \brief Metoda przygotowujaca sciezke drona z uzyciem std::vector<>
* \pre Lacze musi byc odpowiednio skonfigurowane. Wektor translacji
* musi miec zerowa wpolrzedna z
* \param[in] tran - wektor translacji
* \param[in] path - std::vector<> do ktorego zapisywana jest sciezka
* \post W oknie gnuplota wyrysowuje sie sciezka drona
* \retval true - jesli jest odpowiednio skonfigurowane lacze
* \retval false - w przeciwnym wypadku
*/
bool Drone_make_path( Vector3D const &tran, std::vector<Vector3D> &path);
/*!
* \brief Metoda zapisujaca sciezke do pliku oraz do lacza
* \param[in] path - std::vector<> z ktorego wypisywana jest sciezka
* \param[in] name - nazwa pliku do zapisu
* \param[in] Lacze - lacze do gnuplota
* \post W podanym pliku zapisuje sie sciezka, jest rysowana w gnuplocie
* \retval true - jesli zapis sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_path_to_file(std::vector<Vector3D> &path, std::string const &name, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Oczyszcza plik ze sciezka
* \param[in] name - nazwa pliku ze sciezka
* \retval true - jesli operacja sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_path_clear(std::string const &name);
/*!
* \brief Metoda animujaca translacje drona i wyrysowujaca calosc w gnuplocie
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] Lacze - aktywne lacze do gnuplota
* \param[in] tran - wektor translacji
* \post W oknie gnuplota wykonuje sie animacja translacji drona
*/
void Drone_translation_animation(PzG::LaczeDoGNUPlota &Lacze, Vector3D const &tran);
/*!
* \brief Metoda zamieniajaca drona na tego z pliku sample
* \pre PLiki musza byc odpowiednio skonfigurowane
* \param[in] angle - jesli dron roboczy jest obrocony o pewien kat, nalezy
* podac ten kat w metodzie
* \post Zamienia drona na tego o wzorcowych wymiarach
*/
void Drone_change_to_sample(double const &angle);
/*!
* \brief Metoda wczytywania odpowiednich wierzcholkow z pliku wzorcowego
* zgodnie z zaproponowanym sposobem w zadaniu dron.
* Przypisuje wczytane wierzcholki do elementow drona.
* \param[out] dro - wczytwany dron
*/
Drone Drone_From_Sample() const;
/*!
* \brief Metoda obliczajaca i przeprowadzajaca caly ruch drona
* (obrot o kat i przelot z zadania 5.1)
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] angle - kat w stopniach
* \param[in] len - dlugosc przelotu
* \param[in] Lacze - aktywne lacze do gnuplota
* \post W oknie gnuplota wykonuje sie animacja ruchu drona
* \retval true - jesli operacja sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_basic_motion(double const &angle, double const &len, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Metoda robiaca "oblot" drona wokol punktu (z modyfikacji)
* \pre Lacze musi byc odpowiednio skonfigurowane
* \param[in] radius - promien okregu
* \param[in] Lacze - aktywne lacze do gnuplota
* \post W oknie gnuplota wykonuje sie animacja ruchu drona
* \retval true - jesli operacja sie powiedzie
* \retval false - w przeciwnym wypadku
*/
bool Drone_roundabout(double const &radius, PzG::LaczeDoGNUPlota &Lacze);
/*!
* \brief Metoda przygotowujaca sciezke drona z uzyciem std::vector<> do roundabout
* \pre Lacze musi byc odpowiednio skonfigurowane. Promien musi byc dodatni
* \param[in] radius - promien okregu
* \param[in] path - std::vector<> do ktorego zapisywana jest sciezka
* \post W oknie gnuplota wyrysowuje sie sciezka drona
* \retval true - jesli jest odpowiednio skonfigurowane lacze
* \retval false - w przeciwnym wypadku
*/
bool Drone_make_path_roundabout(double const &radius, std::vector<Vector3D> &path);
}; | 46.868167 | 176 | 0.525796 | KPO-2020-2021 |
c07cd1d2f1f988efc4c9d5488d644eba2c3ed223 | 908 | cpp | C++ | Spectro.Arduino/ColorAnimator.cpp | SKKbySSK/Spectro | 3f89838321b07e061575b995c46a154df3b50be3 | [
"MIT"
] | null | null | null | Spectro.Arduino/ColorAnimator.cpp | SKKbySSK/Spectro | 3f89838321b07e061575b995c46a154df3b50be3 | [
"MIT"
] | null | null | null | Spectro.Arduino/ColorAnimator.cpp | SKKbySSK/Spectro | 3f89838321b07e061575b995c46a154df3b50be3 | [
"MIT"
] | null | null | null | #include "Arduino.h"
#ifndef __COLOR__
#define __COLOR__
#include "Color.cpp"
#endif
extern unsigned long timer0_millis;
class ColorAnimator {
private:
int time;
float durationMs;
unsigned long offset, position;
int dr, dg, db, r, g, b;
Color color, from, to;
public:
float Progress;
ColorAnimator(Color from, Color to, float durationMs) {
this->from = from;
this->to = to;
this->durationMs = durationMs;
}
void Start() {
offset = millis();
position = 0;
Progress = 0;
color = from;
}
Color Update() {
position = millis() - offset;
Progress = position / durationMs;
Progress = min(1, Progress);
dr = to.r - from.r;
dg = to.g - from.g;
db = to.b - from.b;
r = from.r + (int)(dr * Progress);
g = from.g + (int)(dg * Progress);
b = from.b + (int)(db * Progress);
color = Color(r, g, b);
return color;
}
};
| 18.530612 | 57 | 0.594714 | SKKbySSK |
c07e0d23bcf83823c2e2554635644f1701758d8c | 2,325 | cpp | C++ | Hypodermic.Tests/RegistrationTests.cpp | KirillShirkunov/Hypodermic | 2c5466ae092dd16f3b55a385856a9ddf3215a5f6 | [
"MIT"
] | 419 | 2015-01-01T18:43:59.000Z | 2022-03-21T08:33:56.000Z | Hypodermic.Tests/RegistrationTests.cpp | KirillShirkunov/Hypodermic | 2c5466ae092dd16f3b55a385856a9ddf3215a5f6 | [
"MIT"
] | 39 | 2015-02-12T10:34:18.000Z | 2021-09-22T12:01:24.000Z | Hypodermic.Tests/RegistrationTests.cpp | KirillShirkunov/Hypodermic | 2c5466ae092dd16f3b55a385856a9ddf3215a5f6 | [
"MIT"
] | 91 | 2015-02-03T04:50:46.000Z | 2022-03-24T07:31:48.000Z | #include "stdafx.h"
#include "Hypodermic/ContainerBuilder.h"
#include "TestingTypes.h"
namespace Hypodermic
{
namespace Testing
{
BOOST_AUTO_TEST_SUITE(RegistrationTests)
BOOST_AUTO_TEST_CASE(should_call_activation_handler_everytime_an_instance_is_activated_through_resolution)
{
// Arrange
ContainerBuilder builder;
std::vector< std::shared_ptr< DefaultConstructible1 > > activatedInstances;
// Act
builder.registerType< DefaultConstructible1 >().onActivated([&activatedInstances](ComponentContext&, const std::shared_ptr< DefaultConstructible1 >& instance)
{
activatedInstances.push_back(instance);
});
auto container = builder.build();
// Assert
auto instance1 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance1 != nullptr);
auto instance2 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance2 != nullptr);
BOOST_CHECK(instance1 != instance2);
BOOST_REQUIRE_EQUAL(activatedInstances.size(), 2u);
BOOST_CHECK(instance1 == activatedInstances[0]);
BOOST_CHECK(instance2 == activatedInstances[1]);
}
BOOST_AUTO_TEST_CASE(should_call_activation_handler_only_once_for_single_instance_mode)
{
// Arrange
ContainerBuilder builder;
std::vector< std::shared_ptr< DefaultConstructible1 > > activatedInstances;
// Act
builder.registerType< DefaultConstructible1 >()
.singleInstance()
.onActivated([&activatedInstances](ComponentContext&, const std::shared_ptr< DefaultConstructible1 >& instance)
{
activatedInstances.push_back(instance);
});
auto container = builder.build();
// Assert
auto instance1 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance1 != nullptr);
auto instance2 = container->resolve< DefaultConstructible1 >();
BOOST_CHECK(instance2 != nullptr);
BOOST_CHECK(instance1 == instance2);
BOOST_REQUIRE_EQUAL(activatedInstances.size(), 1u);
BOOST_CHECK(instance1 == activatedInstances[0]);
}
BOOST_AUTO_TEST_SUITE_END()
} // namespace Testing
} // namespace Hypodermic | 30.194805 | 166 | 0.669677 | KirillShirkunov |
c07e324e1581990bbd78a66114c6b67e8f88d4ea | 2,096 | hpp | C++ | src/mpi/channel_base.hpp | angainor/oomph | 67a3a680cb3d68e4b7a71e6e1745e7a98076c44a | [
"BSD-3-Clause"
] | null | null | null | src/mpi/channel_base.hpp | angainor/oomph | 67a3a680cb3d68e4b7a71e6e1745e7a98076c44a | [
"BSD-3-Clause"
] | 6 | 2021-11-11T07:40:55.000Z | 2022-01-11T09:26:19.000Z | src/mpi/channel_base.hpp | angainor/oomph | 67a3a680cb3d68e4b7a71e6e1745e7a98076c44a | [
"BSD-3-Clause"
] | 2 | 2021-09-03T20:26:46.000Z | 2021-11-10T09:20:12.000Z | /*
* ghex-org
*
* Copyright (c) 2014-2021, ETH Zurich
* All rights reserved.
*
* Please, refer to the LICENSE file in the root directory.
* SPDX-License-Identifier: BSD-3-Clause
*/
#pragma once
#include <oomph/util/mpi_error.hpp>
#include "./context.hpp"
namespace oomph
{
class channel_base
{
protected:
using heap_type = context_impl::heap_type;
using pointer = heap_type::pointer;
using handle_type = typename pointer::handle_type;
using key_type = typename handle_type::key_type;
using flag_basic_type = key_type;
using flag_type = flag_basic_type volatile;
protected:
//heap_type& m_heap;
std::size_t m_size;
std::size_t m_T_size;
std::size_t m_levels;
std::size_t m_capacity;
communicator::rank_type m_remote_rank;
communicator::tag_type m_tag;
bool m_connected = false;
MPI_Request m_init_req;
public:
channel_base(/*heap_type& h,*/ std::size_t size, std::size_t T_size,
communicator::rank_type remote_rank, communicator::tag_type tag, std::size_t levels)
//: m_heap{h}
: m_size{size}
, m_T_size{T_size}
, m_levels{levels}
, m_capacity{levels}
, m_remote_rank{remote_rank}
, m_tag{tag}
{
}
void connect()
{
OOMPH_CHECK_MPI_RESULT(MPI_Wait(&m_init_req, MPI_STATUS_IGNORE));
m_connected = true;
}
protected:
// index of flag in buffer (in units of flag_basic_type)
std::size_t flag_offset() const noexcept
{
return (m_size * m_T_size + 2 * sizeof(flag_basic_type) - 1) / sizeof(flag_basic_type) - 1;
}
// number of elements of type T (including padding)
std::size_t buffer_size() const noexcept
{
return ((flag_offset() + 1) * sizeof(flag_basic_type) + m_T_size - 1) / m_T_size;
}
// pointer to flag location for a given buffer
void* flag_ptr(void* ptr) const noexcept
{
return (void*)((char*)ptr + flag_offset() * sizeof(flag_basic_type));
}
};
} // namespace oomph
| 27.578947 | 99 | 0.636927 | angainor |
c08386a52f78739a01a120394aa9317dae7e20ed | 37,370 | cpp | C++ | Plugins/agsblend/AGSBlend.cpp | rofl0r/ags | 23fcd2bef1c9b0ef61d849b0f78a2b4f5e9b712d | [
"Artistic-2.0"
] | 2 | 2020-06-26T11:40:27.000Z | 2021-06-14T15:58:09.000Z | Plugins/agsblend/AGSBlend.cpp | rofl0r/ags | 23fcd2bef1c9b0ef61d849b0f78a2b4f5e9b712d | [
"Artistic-2.0"
] | null | null | null | Plugins/agsblend/AGSBlend.cpp | rofl0r/ags | 23fcd2bef1c9b0ef61d849b0f78a2b4f5e9b712d | [
"Artistic-2.0"
] | null | null | null | /***********************************************************
* AGSBlend *
* *
* Author: Steven Poulton *
* *
* Date: 09/01/2011 *
* *
* Description: An AGS Plugin to allow true Alpha Blending *
* *
***********************************************************/
#pragma region Defines_and_Includes
#define MIN_EDITOR_VERSION 1
#define MIN_ENGINE_VERSION 3
#ifdef WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#if !defined(BUILTIN_PLUGINS)
#define THIS_IS_THE_PLUGIN
#endif
#include "../../Common/agsplugin.h"
#if defined(BUILTIN_PLUGINS)
namespace agsblend {
#endif
typedef unsigned char uint8;
#define DEFAULT_RGB_R_SHIFT_32 16
#define DEFAULT_RGB_G_SHIFT_32 8
#define DEFAULT_RGB_B_SHIFT_32 0
#define DEFAULT_RGB_A_SHIFT_32 24
#if !defined(WINDOWS_VERSION)
#define min(x,y) (((x) < (y)) ? (x) : (y))
#define max(x,y) (((x) > (y)) ? (x) : (y))
#endif
#define abs(a) ((a)<0 ? -(a) : (a))
#define ChannelBlend_Normal(B,L) ((uint8)(B))
#define ChannelBlend_Lighten(B,L) ((uint8)((L > B) ? L:B))
#define ChannelBlend_Darken(B,L) ((uint8)((L > B) ? B:L))
#define ChannelBlend_Multiply(B,L) ((uint8)((B * L) / 255))
#define ChannelBlend_Average(B,L) ((uint8)((B + L) / 2))
#define ChannelBlend_Add(B,L) ((uint8)(min(255, (B + L))))
#define ChannelBlend_Subtract(B,L) ((uint8)((B + L < 255) ? 0:(B + L - 255)))
#define ChannelBlend_Difference(B,L) ((uint8)(abs(B - L)))
#define ChannelBlend_Negation(B,L) ((uint8)(255 - abs(255 - B - L)))
#define ChannelBlend_Screen(B,L) ((uint8)(255 - (((255 - B) * (255 - L)) >> 8)))
#define ChannelBlend_Exclusion(B,L) ((uint8)(B + L - 2 * B * L / 255))
#define ChannelBlend_Overlay(B,L) ((uint8)((L < 128) ? (2 * B * L / 255):(255 - 2 * (255 - B) * (255 - L) / 255)))
#define ChannelBlend_SoftLight(B,L) ((uint8)((L < 128)?(2*((B>>1)+64))*((float)L/255):(255-(2*(255-((B>>1)+64))*(float)(255-L)/255))))
#define ChannelBlend_HardLight(B,L) (ChannelBlend_Overlay(L,B))
#define ChannelBlend_ColorDodge(B,L) ((uint8)((L == 255) ? L:min(255, ((B << 8 ) / (255 - L)))))
#define ChannelBlend_ColorBurn(B,L) ((uint8)((L == 0) ? L:max(0, (255 - ((255 - B) << 8 ) / L))))
#define ChannelBlend_LinearDodge(B,L)(ChannelBlend_Add(B,L))
#define ChannelBlend_LinearBurn(B,L) (ChannelBlend_Subtract(B,L))
#define ChannelBlend_LinearLight(B,L)((uint8)(L < 128)?ChannelBlend_LinearBurn(B,(2 * L)):ChannelBlend_LinearDodge(B,(2 * (L - 128))))
#define ChannelBlend_VividLight(B,L) ((uint8)(L < 128)?ChannelBlend_ColorBurn(B,(2 * L)):ChannelBlend_ColorDodge(B,(2 * (L - 128))))
#define ChannelBlend_PinLight(B,L) ((uint8)(L < 128)?ChannelBlend_Darken(B,(2 * L)):ChannelBlend_Lighten(B,(2 * (L - 128))))
#define ChannelBlend_HardMix(B,L) ((uint8)((ChannelBlend_VividLight(B,L) < 128) ? 0:255))
#define ChannelBlend_Reflect(B,L) ((uint8)((L == 255) ? L:min(255, (B * B / (255 - L)))))
#define ChannelBlend_Glow(B,L) (ChannelBlend_Reflect(L,B))
#define ChannelBlend_Phoenix(B,L) ((uint8)(min(B,L) - max(B,L) + 255))
#define ChannelBlend_Alpha(B,L,O) ((uint8)(O * B + (1 - O) * L))
#define ChannelBlend_AlphaF(B,L,F,O) (ChannelBlend_Alpha(F(B,L),B,O))
#pragma endregion
#if defined(WINDOWS_VERSION)
// The standard Windows DLL entry point
BOOL APIENTRY DllMain( HANDLE hModule,
DWORD ul_reason_for_call,
LPVOID lpReserved) {
switch (ul_reason_for_call) {
case DLL_PROCESS_ATTACH:
case DLL_THREAD_ATTACH:
case DLL_THREAD_DETACH:
case DLL_PROCESS_DETACH:
break;
}
return TRUE;
}
#endif
//define engine
IAGSEngine *engine;
#pragma region Color_Functions
int getr32(int c)
{
return ((c >> DEFAULT_RGB_R_SHIFT_32) & 0xFF);
}
int getg32 (int c)
{
return ((c >> DEFAULT_RGB_G_SHIFT_32) & 0xFF);
}
int getb32 (int c)
{
return ((c >> DEFAULT_RGB_B_SHIFT_32) & 0xFF);
}
int geta32 (int c)
{
return ((c >> DEFAULT_RGB_A_SHIFT_32) & 0xFF);
}
int makeacol32 (int r, int g, int b, int a)
{
return ((r << DEFAULT_RGB_R_SHIFT_32) |
(g << DEFAULT_RGB_G_SHIFT_32) |
(b << DEFAULT_RGB_B_SHIFT_32) |
(a << DEFAULT_RGB_A_SHIFT_32));
}
#pragma endregion
#pragma region Pixel32_Definition
struct Pixel32{
public:
Pixel32();
~Pixel32() {}
int GetColorAsInt();
int Red;
int Green;
int Blue;
int Alpha;
};
Pixel32::Pixel32() {
Red = 0;
Blue = 0;
Green = 0;
Alpha = 0;
}
int Pixel32::GetColorAsInt() {
return makeacol32(Red,Green,Blue,Alpha);
}
#pragma endregion
/// <summary>
/// Gets the alpha value at coords x,y
/// </summary>
int GetAlpha(int sprite, int x, int y){
BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
unsigned char **charbuffer = engine->GetRawBitmapSurface (engineSprite);
unsigned int **longbuffer = (unsigned int**)charbuffer;
int alpha = geta32(longbuffer[y][x]);
engine->ReleaseBitmapSurface (engineSprite);
return alpha;
}
/// <summary>
/// Sets the alpha value at coords x,y
/// </summary>
int PutAlpha(int sprite, int x, int y, int alpha){
BITMAP *engineSprite = engine->GetSpriteGraphic(sprite);
unsigned char **charbuffer = engine->GetRawBitmapSurface (engineSprite);
unsigned int **longbuffer = (unsigned int**)charbuffer;
int r = getr32(longbuffer[y][x]);
int g = getg32(longbuffer[y][x]);
int b = getb32(longbuffer[y][x]);
longbuffer[y][x] = makeacol32(r,g,b,alpha);
engine->ReleaseBitmapSurface (engineSprite);
return alpha;
}
/// <summary>
/// Translates index from a 2D array to a 1D array
/// </summary>
int xytolocale(int x, int y, int width){
return (y * width + x);
}
int HighPass(int sprite, int threshold){
BITMAP* src = engine->GetSpriteGraphic(sprite);
long srcWidth, srcHeight;
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
for (int y = 0; y<srcHeight; y++){
for (int x = 0; x<srcWidth; x++){
int srcr = getb32(srclongbuffer[y][x]);
int srcg = getg32(srclongbuffer[y][x]);
int srcb = getr32(srclongbuffer[y][x]);
int tempmaxim = max(srcr, srcg);
int maxim = max(tempmaxim, srcb);
int tempmin = min( srcr, srcg);
int minim = min( srcb, tempmin);
int light = (maxim + minim) /2 ;
if (light < threshold) srclongbuffer[y][x] = makeacol32(0,0,0,0);
}
}
return 0;
}
int Blur (int sprite, int radius) {
BITMAP* src = engine->GetSpriteGraphic(sprite);
long srcWidth, srcHeight;
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
int negrad = -1 * radius;
//use a 1Dimensional array since the array is on the free store, not the stack
Pixel32 * Pixels = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; // this defines a copy of the individual channels in class form.
Pixel32 * Dest = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))]; // this is the destination sprite. both have a border all the way round equal to the radius for the blurring.
Pixel32 * Temp = new Pixel32[(srcWidth + (radius * 2)) * (srcHeight + (radius * 2))];
int arraywidth = srcWidth + (radius * 2); //define the array width since its used many times in the algorithm
for (int y = 0; y<srcHeight; y++){ //copy the sprite to the Pixels class array
for (int x = 0; x<srcWidth; x++){
int locale = xytolocale(x + radius, y + radius, arraywidth);
Pixels[locale].Red = getr32(srclongbuffer[y][x]);
Pixels[locale].Green = getg32(srclongbuffer[y][x]);
Pixels[locale].Blue = getb32(srclongbuffer[y][x]);
Pixels[locale].Alpha = geta32(srclongbuffer[y][x]);
}
}
int numofpixels = (radius * 2 + 1);
for (int y = 0; y < srcHeight; y++) {
int totalr = 0;
int totalg = 0;
int totalb = 0;
int totala = 0;
// Process entire window for first pixel
for (int kx = negrad; kx <= radius; kx++){
int locale = xytolocale(kx + radius, y + radius, arraywidth);
totala += Pixels[locale].Alpha;
totalr += (Pixels[locale].Red * Pixels[locale].Alpha)/ 255;
totalg += (Pixels[locale].Green * Pixels[locale].Alpha)/ 255;
totalb += (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255;
}
int locale = xytolocale(radius, y + radius, arraywidth);
Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Temp[locale].Green = totalg / numofpixels;
Temp[locale].Blue = totalb / numofpixels;
Temp[locale].Alpha = totala / numofpixels;
// Subsequent pixels just update window total
for (int x = 1; x < srcWidth; x++) {
// Subtract pixel leaving window
int locale = xytolocale(x - 1, y + radius, arraywidth);
totala -= Pixels[locale].Alpha;
totalr -= (Pixels[locale].Red * Pixels[locale].Alpha)/ 255;
totalg -= (Pixels[locale].Green * Pixels[locale].Alpha)/ 255;
totalb -= (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255;
// Add pixel entering window
locale = xytolocale(x + radius + radius, y + radius, arraywidth);
totala += Pixels[locale].Alpha;
totalr += (Pixels[locale].Red * Pixels[locale].Alpha)/ 255;
totalg += (Pixels[locale].Green * Pixels[locale].Alpha)/ 255;
totalb += (Pixels[locale].Blue * Pixels[locale].Alpha)/ 255;
locale = xytolocale(x + radius, y + radius, arraywidth);
Temp[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Temp[locale].Green = totalg / numofpixels;
Temp[locale].Blue = totalb / numofpixels;
Temp[locale].Alpha = totala / numofpixels;
}
}
for (int x = 0; x < srcWidth; x++) {
int totalr = 0;
int totalg = 0;
int totalb = 0;
int totala = 0;
// Process entire window for first pixel
for (int ky = negrad; ky <= radius; ky++){
int locale = xytolocale(x + radius, ky + radius, arraywidth);
totala += Temp[locale].Alpha;
totalr += (Temp[locale].Red * Temp[locale].Alpha)/ 255;
totalg += (Temp[locale].Green * Temp[locale].Alpha)/ 255;
totalb += (Temp[locale].Blue * Temp[locale].Alpha)/ 255;
}
int locale = xytolocale(x + radius,radius, arraywidth);
Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Dest[locale].Green = totalg / numofpixels;
Dest[locale].Blue = totalb / numofpixels;
Dest[locale].Alpha = totala / numofpixels;
// Subsequent pixels just update window total
for (int y = 1; y < srcHeight; y++) {
// Subtract pixel leaving window
int locale = xytolocale(x + radius, y - 1, arraywidth);
totala -= Temp[locale].Alpha;
totalr -= (Temp[locale].Red * Temp[locale].Alpha)/ 255;
totalg -= (Temp[locale].Green * Temp[locale].Alpha)/ 255;
totalb -= (Temp[locale].Blue * Temp[locale].Alpha)/ 255;
// Add pixel entering window
locale = xytolocale(x + radius, y + radius + radius, arraywidth);
totala += Temp[locale].Alpha;
totalr += (Temp[locale].Red * Temp[locale].Alpha)/ 255;
totalg += (Temp[locale].Green * Temp[locale].Alpha)/ 255;
totalb += (Temp[locale].Blue * Temp[locale].Alpha)/ 255;
locale = xytolocale(x + radius, y + radius, arraywidth);
Dest[locale].Red = totalr / numofpixels; // take an average and assign it to the destination array
Dest[locale].Green = totalg / numofpixels;
Dest[locale].Blue = totalb / numofpixels;
Dest[locale].Alpha = totala / numofpixels;
}
}
for (int y = 0; y<srcHeight; y++){
for (int x = 0; x<srcWidth; x++){
int locale = xytolocale(x + radius, y + radius, arraywidth);
srclongbuffer[y][x] = Dest[locale].GetColorAsInt(); //write the destination array to the main buffer
}
}
delete [] Pixels;
delete [] Dest;
delete [] Temp;
engine->ReleaseBitmapSurface(src);
delete srclongbuffer;
delete srccharbuffer;
return 0;
}
int Clamp(int val, int min, int max){
if (val < min) return min;
else if (val > max) return max;
else return val;
}
int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans){
trans = 100 - trans;
long srcWidth, srcHeight, destWidth, destHeight;
BITMAP* src = engine->GetSpriteGraphic(sprite);
BITMAP* dest = engine->GetSpriteGraphic(destination);
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL);
if (x > destWidth || y > destHeight || x + srcWidth < 0 || y + srcHeight < 0) return 1; // offscreen
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest);
unsigned int **destlongbuffer = (unsigned int**)destcharbuffer;
if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
int destx, desty;
int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
unsigned int col;
int starty = 0;
int startx = 0;
if (x < 0) startx = -1 * x;
if (y < 0) starty = -1 * y;
int ycount = 0;
int xcount = 0;
for(ycount = starty; ycount<srcHeight; ycount ++){
for(xcount = startx; xcount<srcWidth; xcount ++){
destx = xcount + x;
desty = ycount + y;
srca = (geta32(srclongbuffer[ycount][xcount]));
if (srca != 0) {
srca = srca * trans / 100;
srcr = getr32(srclongbuffer[ycount][xcount]);
srcg = getg32(srclongbuffer[ycount][xcount]);
srcb = getb32(srclongbuffer[ycount][xcount]);
destr = getr32(destlongbuffer[desty][destx]);
destg = getg32(destlongbuffer[desty][destx]);
destb = getb32(destlongbuffer[desty][destx]);
desta = geta32(destlongbuffer[desty][destx]);
switch (DrawMode) {
case 0:
finalr = srcr;
finalg = srcg;
finalb = srcb;
break;
case 1:
finalr = ChannelBlend_Lighten(srcr,destr);
finalg = ChannelBlend_Lighten(srcg,destg);
finalb = ChannelBlend_Lighten(srcb,destb);
break;
case 2:
finalr = ChannelBlend_Darken(srcr,destr);
finalg = ChannelBlend_Darken(srcg,destg);
finalb = ChannelBlend_Darken(srcb,destb);
break;
case 3:
finalr = ChannelBlend_Multiply(srcr,destr);
finalg = ChannelBlend_Multiply(srcg,destg);
finalb = ChannelBlend_Multiply(srcb,destb);
break;
case 4:
finalr = ChannelBlend_Add(srcr,destr);
finalg = ChannelBlend_Add(srcg,destg);
finalb = ChannelBlend_Add(srcb,destb);
break;
case 5:
finalr = ChannelBlend_Subtract(srcr,destr);
finalg = ChannelBlend_Subtract(srcg,destg);
finalb = ChannelBlend_Subtract(srcb,destb);
break;
case 6:
finalr = ChannelBlend_Difference(srcr,destr);
finalg = ChannelBlend_Difference(srcg,destg);
finalb = ChannelBlend_Difference(srcb,destb);
break;
case 7:
finalr = ChannelBlend_Negation(srcr,destr);
finalg = ChannelBlend_Negation(srcg,destg);
finalb = ChannelBlend_Negation(srcb,destb);
break;
case 8:
finalr = ChannelBlend_Screen(srcr,destr);
finalg = ChannelBlend_Screen(srcg,destg);
finalb = ChannelBlend_Screen(srcb,destb);
break;
case 9:
finalr = ChannelBlend_Exclusion(srcr,destr);
finalg = ChannelBlend_Exclusion(srcg,destg);
finalb = ChannelBlend_Exclusion(srcb,destb);
break;
case 10:
finalr = ChannelBlend_Overlay(srcr,destr);
finalg = ChannelBlend_Overlay(srcg,destg);
finalb = ChannelBlend_Overlay(srcb,destb);
break;
case 11:
finalr = ChannelBlend_SoftLight(srcr,destr);
finalg = ChannelBlend_SoftLight(srcg,destg);
finalb = ChannelBlend_SoftLight(srcb,destb);
break;
case 12:
finalr = ChannelBlend_HardLight(srcr,destr);
finalg = ChannelBlend_HardLight(srcg,destg);
finalb = ChannelBlend_HardLight(srcb,destb);
break;
case 13:
finalr = ChannelBlend_ColorDodge(srcr,destr);
finalg = ChannelBlend_ColorDodge(srcg,destg);
finalb = ChannelBlend_ColorDodge(srcb,destb);
break;
case 14:
finalr = ChannelBlend_ColorBurn(srcr,destr);
finalg = ChannelBlend_ColorBurn(srcg,destg);
finalb = ChannelBlend_ColorBurn(srcb,destb);
break;
case 15:
finalr = ChannelBlend_LinearDodge(srcr,destr);
finalg = ChannelBlend_LinearDodge(srcg,destg);
finalb = ChannelBlend_LinearDodge(srcb,destb);
break;
case 16:
finalr = ChannelBlend_LinearBurn(srcr,destr);
finalg = ChannelBlend_LinearBurn(srcg,destg);
finalb = ChannelBlend_LinearBurn(srcb,destb);
break;
case 17:
finalr = ChannelBlend_LinearLight(srcr,destr);
finalg = ChannelBlend_LinearLight(srcg,destg);
finalb = ChannelBlend_LinearLight(srcb,destb);
break;
case 18:
finalr = ChannelBlend_VividLight(srcr,destr);
finalg = ChannelBlend_VividLight(srcg,destg);
finalb = ChannelBlend_VividLight(srcb,destb);
break;
case 19:
finalr = ChannelBlend_PinLight(srcr,destr);
finalg = ChannelBlend_PinLight(srcg,destg);
finalb = ChannelBlend_PinLight(srcb,destb);
break;
case 20:
finalr = ChannelBlend_HardMix(srcr,destr);
finalg = ChannelBlend_HardMix(srcg,destg);
finalb = ChannelBlend_HardMix(srcb,destb);
break;
case 21:
finalr = ChannelBlend_Reflect(srcr,destr);
finalg = ChannelBlend_Reflect(srcg,destg);
finalb = ChannelBlend_Reflect(srcb,destb);
break;
case 22:
finalr = ChannelBlend_Glow(srcr,destr);
finalg = ChannelBlend_Glow(srcg,destg);
finalb = ChannelBlend_Glow(srcb,destb);
break;
case 23:
finalr = ChannelBlend_Phoenix(srcr,destr);
finalg = ChannelBlend_Phoenix(srcg,destg);
finalb = ChannelBlend_Phoenix(srcb,destb);
break;
}
finala = 255-(255-srca)*(255-desta)/255;
finalr = srca*finalr/finala + desta*destr*(255-srca)/finala/255;
finalg = srca*finalg/finala + desta*destg*(255-srca)/finala/255;
finalb = srca*finalb/finala + desta*destb*(255-srca)/finala/255;
col = makeacol32(finalr, finalg, finalb, finala);
destlongbuffer[desty][destx] = col;
}
}
}
engine->ReleaseBitmapSurface(src);
engine->ReleaseBitmapSurface(dest);
engine->NotifySpriteUpdated(destination);
return 0;
}
int DrawAdd(int destination, int sprite, int x, int y, float scale){
long srcWidth, srcHeight, destWidth, destHeight;
BITMAP* src = engine->GetSpriteGraphic(sprite);
BITMAP* dest = engine->GetSpriteGraphic(destination);
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL);
if (x > destWidth || y > destHeight) return 1; // offscreen
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest);
unsigned int **destlongbuffer = (unsigned int**)destcharbuffer;
if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
int destx, desty;
int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
unsigned int col;
int ycount = 0;
int xcount = 0;
int starty = 0;
int startx = 0;
if (x < 0) startx = -1 * x;
if (y < 0) starty = -1 * y;
for(ycount = starty; ycount<srcHeight; ycount ++){
for(xcount = startx; xcount<srcWidth; xcount ++){
destx = xcount + x;
desty = ycount + y;
srca = (geta32(srclongbuffer[ycount][xcount]));
if (srca != 0) {
srcr = getr32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
srcg = getg32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
srcb = getb32(srclongbuffer[ycount][xcount]) * srca / 255 * scale;
desta = geta32(destlongbuffer[desty][destx]);
if (desta == 0){
destr = 0;
destg = 0;
destb = 0;
}
else {
destr = getr32(destlongbuffer[desty][destx]);
destg = getg32(destlongbuffer[desty][destx]);
destb = getb32(destlongbuffer[desty][destx]);
}
finala = 255-(255-srca)*(255-desta)/255;
finalr = Clamp(srcr + destr, 0, 255);
finalg = Clamp(srcg + destg, 0, 255);
finalb = Clamp(srcb + destb, 0, 255);
col = makeacol32(finalr, finalg, finalb, finala);
destlongbuffer[desty][destx] = col;
}
}
}
engine->ReleaseBitmapSurface(src);
engine->ReleaseBitmapSurface(dest);
engine->NotifySpriteUpdated(destination);
return 0;
}
int DrawAlpha(int destination, int sprite, int x, int y, int trans)
{
trans = 100 - trans;
long srcWidth, srcHeight, destWidth, destHeight;
BITMAP* src = engine->GetSpriteGraphic(sprite);
BITMAP* dest = engine->GetSpriteGraphic(destination);
engine->GetBitmapDimensions(src, &srcWidth, &srcHeight, NULL);
engine->GetBitmapDimensions(dest, &destWidth, &destHeight, NULL);
if (x > destWidth || y > destHeight) return 1; // offscreen
unsigned char **srccharbuffer = engine->GetRawBitmapSurface (src);
unsigned int **srclongbuffer = (unsigned int**)srccharbuffer;
unsigned char **destcharbuffer = engine->GetRawBitmapSurface (dest);
unsigned int **destlongbuffer = (unsigned int**)destcharbuffer;
if (srcWidth + x > destWidth) srcWidth = destWidth - x - 1;
if (srcHeight + y > destHeight) srcHeight = destHeight - y - 1;
int destx, desty;
int srcr, srcg, srcb, srca, destr, destg, destb, desta, finalr, finalg, finalb, finala;
int ycount = 0;
int xcount = 0;
int starty = 0;
int startx = 0;
if (x < 0) startx = -1 * x;
if (y < 0) starty = -1 * y;
for(ycount = starty; ycount<srcHeight; ycount ++){
for(xcount = startx; xcount<srcWidth; xcount ++){
destx = xcount + x;
desty = ycount + y;
srca = (geta32(srclongbuffer[ycount][xcount])) * trans / 100;
if (srca != 0) {
srcr = getr32(srclongbuffer[ycount][xcount]);
srcg = getg32(srclongbuffer[ycount][xcount]);
srcb = getb32(srclongbuffer[ycount][xcount]);
destr = getr32(destlongbuffer[desty][destx]);
destg = getg32(destlongbuffer[desty][destx]);
destb = getb32(destlongbuffer[desty][destx]);
desta = geta32(destlongbuffer[desty][destx]);
finala = 255-(255-srca)*(255-desta)/255;
finalr = srca*srcr/finala + desta*destr*(255-srca)/finala/255;
finalg = srca*srcg/finala + desta*destg*(255-srca)/finala/255;
finalb = srca*srcb/finala + desta*destb*(255-srca)/finala/255;
destlongbuffer[desty][destx] = makeacol32(finalr, finalg, finalb, finala);
}
}
}
engine->ReleaseBitmapSurface(src);
engine->ReleaseBitmapSurface(dest);
engine->NotifySpriteUpdated(destination);
return 0;
}
#if defined(WINDOWS_VERSION)
//==============================================================================
// ***** Design time *****
IAGSEditor *editor; // Editor interface
const char *ourScriptHeader =
"import int DrawAlpha(int destination, int sprite, int x, int y, int transparency);\r\n"
"import int GetAlpha(int sprite, int x, int y);\r\n"
"import int PutAlpha(int sprite, int x, int y, int alpha);\r\n"
"import int Blur(int sprite, int radius);\r\n"
"import int HighPass(int sprite, int threshold);\r\n"
"import int DrawAdd(int destination, int sprite, int x, int y, float scale);\r\n"
"import int DrawSprite(int destination, int sprite, int x, int y, int DrawMode, int trans);";
//------------------------------------------------------------------------------
LPCSTR AGS_GetPluginName()
{
return ("AGSBlend");
}
//------------------------------------------------------------------------------
int AGS_EditorStartup(IAGSEditor *lpEditor)
{
// User has checked the plugin to use it in their game
// If it's an earlier version than what we need, abort.
if (lpEditor->version < MIN_EDITOR_VERSION)
return (-1);
editor = lpEditor;
editor->RegisterScriptHeader(ourScriptHeader);
// Return 0 to indicate success
return (0);
}
//------------------------------------------------------------------------------
void AGS_EditorShutdown()
{
// User has un-checked the plugin from their game
editor->UnregisterScriptHeader(ourScriptHeader);
}
//------------------------------------------------------------------------------
void AGS_EditorProperties(HWND parent) //*** optional ***
{
// User has chosen to view the Properties of the plugin
// We could load up an options dialog or something here instead
/* MessageBox(parent,
L"AGSBlend v1.0 By Calin Leafshade",
L"About",
MB_OK | MB_ICONINFORMATION);
*/
}
//------------------------------------------------------------------------------
int AGS_EditorSaveGame(char *buffer, int bufsize) //*** optional ***
{
// Called by the editor when the current game is saved to disk.
// Plugin configuration can be stored in [buffer] (max [bufsize] bytes)
// Return the amount of bytes written in the buffer
return (0);
}
//------------------------------------------------------------------------------
void AGS_EditorLoadGame(char *buffer, int bufsize) //*** optional ***
{
// Called by the editor when a game is loaded from disk
// Previous written data can be read from [buffer] (size [bufsize]).
// Make a copy of the data, the buffer is freed after this function call.
}
//==============================================================================
#endif
// ***** Run time *****
// Engine interface
//------------------------------------------------------------------------------
#define REGISTER(x) engine->RegisterScriptFunction(#x, (void *) (x));
#define STRINGIFY(s) STRINGIFY_X(s)
#define STRINGIFY_X(s) #s
void AGS_EngineStartup(IAGSEngine *lpEngine)
{
engine = lpEngine;
// Make sure it's got the version with the features we need
if (engine->version < MIN_ENGINE_VERSION)
engine->AbortGame("Plugin needs engine version " STRINGIFY(MIN_ENGINE_VERSION) " or newer.");
//register functions
REGISTER(GetAlpha)
REGISTER(PutAlpha)
REGISTER(DrawAlpha)
REGISTER(Blur)
REGISTER(HighPass)
REGISTER(DrawAdd)
REGISTER(DrawSprite)
}
//------------------------------------------------------------------------------
void AGS_EngineShutdown()
{
// Called by the game engine just before it exits.
// This gives you a chance to free any memory and do any cleanup
// that you need to do before the engine shuts down.
}
//------------------------------------------------------------------------------
int AGS_EngineOnEvent(int event, int data) //*** optional ***
{
switch (event)
{
/*
case AGSE_KEYPRESS:
case AGSE_MOUSECLICK:
case AGSE_POSTSCREENDRAW:
case AGSE_PRESCREENDRAW:
case AGSE_SAVEGAME:
case AGSE_RESTOREGAME:
case AGSE_PREGUIDRAW:
case AGSE_LEAVEROOM:
case AGSE_ENTERROOM:
case AGSE_TRANSITIONIN:
case AGSE_TRANSITIONOUT:
case AGSE_FINALSCREENDRAW:
case AGSE_TRANSLATETEXT:
case AGSE_SCRIPTDEBUG:
case AGSE_SPRITELOAD:
case AGSE_PRERENDER:
case AGSE_PRESAVEGAME:
case AGSE_POSTRESTOREGAME:
*/
default:
break;
}
// Return 1 to stop event from processing further (when needed)
return (0);
}
//------------------------------------------------------------------------------
int AGS_EngineDebugHook(const char *scriptName,
int lineNum, int reserved) //*** optional ***
{
// Can be used to debug scripts, see documentation
return 0;
}
//------------------------------------------------------------------------------
void AGS_EngineInitGfx(const char *driverID, void *data) //*** optional ***
{
// This allows you to make changes to how the graphics driver starts up.
// See documentation
}
//..............................................................................
#if defined(BUILTIN_PLUGINS)
}
#endif | 35.288008 | 277 | 0.478245 | rofl0r |
c08409bca82ab6e9e3a44aa0af13ccc1e59356f1 | 1,468 | cpp | C++ | library/Components/Objects/Rulebase/src/Timebased_rules.cpp | NGliese/Embedded | 589f55858b1f8b994347df3c0a2b2fcd4f9bd14e | [
"MIT"
] | null | null | null | library/Components/Objects/Rulebase/src/Timebased_rules.cpp | NGliese/Embedded | 589f55858b1f8b994347df3c0a2b2fcd4f9bd14e | [
"MIT"
] | null | null | null | library/Components/Objects/Rulebase/src/Timebased_rules.cpp | NGliese/Embedded | 589f55858b1f8b994347df3c0a2b2fcd4f9bd14e | [
"MIT"
] | null | null | null | /*
* Timebased_rules.cpp
*
* Created on: Nov 16, 2021
* Author: nikolaj
*/
/***********************************************************************************************+
* \brief -- XX -- Library - CPP Source file
* \par
* \par @DETAILS
*
*
* \li LIMITATION-TO-CLASS
* \li LIMITATION-TO-CLASS
*
* \note ANY RELEVANT NOTES
*
* \file Timebased_rules.cpp
* \author N.G Pedersen <nikolajgliese@tutanota.com>
* \version 1.0
* \date 2021
* \copyright --
*
*
***********************************************************************************************/
#include "../include/Timebased_rules.hpp"
//#define DEBUG // default uncommeted
#ifdef DEBUG
static const char* LOG_TAG = "Timebased_rules";
#endif
constexpr int NIGHT_TIME_START = 20;
constexpr int NIGHT_TIME_END = 5;
constexpr int VACATION_START = 4;
constexpr int VACATION_END = 12;
bool Timebased_rules::isItNight(void)
{
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
if(tstruct.tm_hour >= NIGHT_TIME_START or tstruct.tm_hour <= NIGHT_TIME_END)
{
return true;
}
return false;
}
bool Timebased_rules::isItVacation(void)
{
time_t now = time(0);
struct tm tstruct;
tstruct = *localtime(&now);
std::cout << " current day is : " << (int)tstruct.tm_mday << "\n";
if(tstruct.tm_mday >= VACATION_START and tstruct.tm_mday <= VACATION_END)
{
return true;
}
return false;
}
| 21.275362 | 97 | 0.558583 | NGliese |
c0848274b608b3d75d61032d9eb6f302746143d7 | 1,576 | hpp | C++ | include/tensor_ops.hpp | jaistark/sp | 911933c65f950e6bc51451840068ca9249554846 | [
"BSD-2-Clause"
] | 28 | 2015-03-04T08:34:40.000Z | 2022-02-13T05:59:11.000Z | include/tensor_ops.hpp | jaistark/sp | 911933c65f950e6bc51451840068ca9249554846 | [
"BSD-2-Clause"
] | null | null | null | include/tensor_ops.hpp | jaistark/sp | 911933c65f950e6bc51451840068ca9249554846 | [
"BSD-2-Clause"
] | 14 | 2015-03-04T08:34:42.000Z | 2020-12-08T16:13:37.000Z | #ifndef _TENSOR_OPS_HPP_
#define _TENSOR_OPS_HPP_
#include "common.hpp"
#include "network.hpp"
#include "vector.hpp"
#include <vector>
// Routine to compute the second left eigenvector of the Markov Chain
// induced by the stationary distribution.
//
// triples is the list of third order moments (must be symmetric)
// counts is a counter such that counts[(u, v)] is the number of
// third-order moments containing u and v
// stationary_distrib is the multilinear PageRank vector
// alpha is the teleportation parameter
// max_iter is the maximum number of power iterations to run
// tol is the relative error tolerance for stopping
template <typename Scalar>
Vector<Scalar> SecondLeftEvec(std::vector<Tuple>& triples, Counts& counts,
Vector<Scalar>& stationary_distrib,
Scalar alpha, int max_iter,
double tol);
// Find the multilinear PageRank vector.
// We use the SS-HOPM by Kolda and Mayo to compute the vector.
//
// triples is the list of third order moments (must be symmetric)
// counts is a counter such that counts[(u, v)] is the number of
// third-order moments containing u and v
// alpha is the teleportation parameter
// gamma is the shift parameter for SS-HOPM
// num_nodes is the number of nodes
// max_iter is the maximum number of SS-HOPM iterations
// tol is the relative error tolerance for stopping
template <typename Scalar>
Vector<Scalar> MPRVec(std::vector<Tuple>& triples, Counts& counts,
Scalar alpha, Scalar gamma, int num_nodes, int max_iter,
double tol);
#endif // _TENSOR_OPS_HPP_
| 35.818182 | 74 | 0.738579 | jaistark |
6a51653fdedf9b0120d0cba5bb13202186eec594 | 333 | cpp | C++ | dialogs/dialog-about.cpp | Intueor/PPK | afd1ddcb6214352b87097b58de0b9555a8a3f1b2 | [
"Apache-2.0"
] | null | null | null | dialogs/dialog-about.cpp | Intueor/PPK | afd1ddcb6214352b87097b58de0b9555a8a3f1b2 | [
"Apache-2.0"
] | null | null | null | dialogs/dialog-about.cpp | Intueor/PPK | afd1ddcb6214352b87097b58de0b9555a8a3f1b2 | [
"Apache-2.0"
] | null | null | null | //== ВКЛЮЧЕНИЯ.
#include "dialog-about.h"
#include "ui_dialog-about.h"
//== ФУНКЦИИ КЛАССОВ.
//== Класс диалога "О программе".
// Конструктор.
DialogAbout::DialogAbout(QWidget *p_WidgetParent) : QDialog(p_WidgetParent), p_UI(new Ui::DialogAbout) { p_UI->setupUi(this); }
// Деструктор.
DialogAbout::~DialogAbout() { delete p_UI; }
| 27.75 | 127 | 0.714715 | Intueor |
6a55a46cc58954f0aa68d79792fa92fcbc3306ec | 4,356 | cxx | C++ | src/qds/DispatchIO.cxx | XFone/exapi | 05660e8b27dfa75aa0996342ee5b6b253b09c477 | [
"Apache-2.0"
] | 1 | 2020-04-11T06:06:40.000Z | 2020-04-11T06:06:40.000Z | src/qds/DispatchIO.cxx | XFone/exapi | 05660e8b27dfa75aa0996342ee5b6b253b09c477 | [
"Apache-2.0"
] | null | null | null | src/qds/DispatchIO.cxx | XFone/exapi | 05660e8b27dfa75aa0996342ee5b6b253b09c477 | [
"Apache-2.0"
] | null | null | null | /*
* $Id: $
*
* System I/O dispatching implementation
*
* Copyright (c) 2014-2015 Zerone.IO (Shanghai). All rights reserved.
*
* $Log: $
*
*/
#include "Base.h"
#include "Log.h"
#include "Trace.h"
#include "GlobalDefine.h"
#include "DispatchIO.h"
#include "algoapi/zmq/ZmqHelper.h"
#include <string>
using namespace std;
using namespace ATS;
#define USE_ZMQ_POLL 1
#define ZMQ_POLL_TIMEOUT 10 // 10ms
DispatchIO::DispatchIO(void) : n_mq(0)
{
m_zmqctx = zmq_ctx_new();
zmq_ctx_set(m_zmqctx, ZMQ_MAX_SOCKETS, 128);
}
DispatchIO::~DispatchIO(void)
{
for (int i = 0; i < n_mq; i++) {
delete a_mqs[i];
}
zmq_ctx_term(m_zmqctx);
// zmq_ctx_destroy(m_zmqctx); // deprecated
}
BaseZmqClient *DispatchIO::AssignSfHandler(SwordFishIntf *psf, BaseMsgDispatcher *dsp)
{
if (n_mq < (int)MAX_MQ_COUNT) {
psf->SetContext(m_zmqctx);
psf->SetUserParseFunc(dsp->GetMessageParser());
a_mqs[n_mq++] = new _MqDesc(psf, dsp, dsp);
}
return (BaseZmqClient *)psf;
}
BaseZmqClient *DispatchIO::AssignMqHandler(BaseZmqClient *pmq, IDispatcher *dsp)
{
if (n_mq < (int)MAX_MQ_COUNT) {
pmq->SetContext(m_zmqctx);
a_mqs[n_mq++] = new _MqDesc(pmq, dsp, NULL);
}
return pmq;
}
int DispatchIO::DispatchInfinitely(void *ctx, bool do_egress)
{
int i;
#if USE_ZMQ_POLL
int n_items = 0;
zmq_pollitem_t poll_items[MAX_MQ_COUNT];
for (i = 0; i < n_mq && i < (int)MAX_MQ_COUNT; i++) {
zmq_pollitem_t *pitem = &poll_items[i];
pitem->socket = a_mqs[i]->GetSocket();
pitem->fd = a_mqs[i]->GetFd();
pitem->events = ZMQ_POLLIN | ZMQ_POLLERR;
pitem->revents = 0;
n_items++;
TRACE_THREAD(7, "poll_item { socket: 0x%x, fd: %d }",
pitem->socket, pitem->fd);
}
LOGFILE(LOG_DEBUG, "ZMQ polling on %d items", n_items);
#endif /* USE_ZMQ_POLL */
do {
#if USE_ZMQ_POLL
int rc = zmq_poll(poll_items, n_items, ZMQ_POLL_TIMEOUT);
if (rc > 0) { // has events
i = 0;
TRACE_THREAD(8, "Got %d events", rc);
while (i < n_items && rc > 0) {
int revts = poll_items[i].revents;
if (revts) { // this item got an event
rc--;
TRACE_THREAD(8, "ZMQ#%d polled!", i);
if (revts & ZMQ_POLLIN) {
onDispatch(a_mqs[i]);
}
if (revts & ZMQ_POLLERR) {
LOGFILE(LOG_WARN, "socket %d has error", i);
// TODO
}
}
i++;
} // while (i && rc)
} else if (0 == rc) { // timeout
// TODO ---
// TRACE_THREAD(7, "timeout!");
} else { // -1 check errors
int err = zmq_errno();
switch (err) {
case EBADF: // fd or socket closed
// TODO: reopen or re-initialize MQ
LOGFILE(LOG_WARN, "zmq_poll got EBADF: %s", zmq_strerror(err));
break;
case EINTR:
// got SIGCHLD or SIGALRM
// assert(0);
LOGFILE(LOG_WARN, "got SIGCHLD or SIGALRM");
break;
default:
// what's up?
LOGFILE(LOG_WARN, "zmq_poll got error: %s", zmq_strerror(err));
// assert(0);
break;
}
} // if (rc)
#else /* !USE_ZMQ_POLL */
for (i = 0; i < n_mq; i++) {
onDispatch(&a_mqs[i]);
}
#endif /* USE_ZMQ_POLL */
if (do_egress) {
ProcessEgress();
}
} while (!g_is_exiting);
return 0;
}
TDispResult DispatchIO::onDispatch(Object desc)
{
_MqDesc *mqd = (_MqDesc *)desc;
TDispResult ret = DR_DROPPED;
Object obj;
if (NULL != (obj = mqd->doRecv())) {
ret = mqd->doDispatch(obj);
} else {
TRACE_THREAD(7, "DispatchIO::onDispatch: unknown message");
}
if (DR_SUCCESS != ret) {
// TODO: to check status
}
if (DR_CONTINUE == ret) {
// TODO: broadcast this message to all
}
return ret;
}
| 24.066298 | 87 | 0.506198 | XFone |
6a58d45a9c342cf63c598464f6ba5fdcb4928274 | 3,494 | cpp | C++ | Unix/samples/Providers/Demo-i2/X_Halves_Class_Provider.cpp | Beguiled/omi | 1c824681ee86f32314f430db972e5d3938f10fd4 | [
"MIT"
] | 165 | 2016-08-18T22:06:39.000Z | 2019-05-05T11:09:37.000Z | Unix/samples/Providers/Demo-i2/X_Halves_Class_Provider.cpp | snchennapragada/omi | 4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0 | [
"MIT"
] | 409 | 2016-08-18T20:52:56.000Z | 2019-05-06T10:03:11.000Z | Unix/samples/Providers/Demo-i2/X_Halves_Class_Provider.cpp | snchennapragada/omi | 4fa565207d3445d1f44bfc7b890f9ea5ea7b41d0 | [
"MIT"
] | 72 | 2016-08-23T02:30:08.000Z | 2019-04-30T22:57:03.000Z | /*
**==============================================================================
**
** Copyright (c) Microsoft Corporation. All rights reserved. See file LICENSE
** for license information.
**
**==============================================================================
*/
/* @migen@ */
#include <MI.h>
#include "X_Halves_Class_Provider.h"
MI_BEGIN_NAMESPACE
X_SmallNumber_Class FillNumberByKey(
Uint64 key);
X_Halves_Class_Provider::X_Halves_Class_Provider(
Module* module) :
m_Module(module)
{
}
X_Halves_Class_Provider::~X_Halves_Class_Provider()
{
}
void X_Halves_Class_Provider::EnumerateInstances(
Context& context,
const String& nameSpace,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::GetInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& instance_ref,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::CreateInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& new_instance)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::ModifyInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& new_instance,
const PropertySet& propertySet)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::DeleteInstance(
Context& context,
const String& nameSpace,
const X_Halves_Class& instance_ref)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
void X_Halves_Class_Provider::AssociatorInstances(
Context& context,
const String& nameSpace,
const MI_Instance* instanceName,
const String& resultClass,
const String& role,
const String& resultRole,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
if (!X_SmallNumber_IsA(instanceName))
{
context.Post(MI_RESULT_FAILED);
return ;
}
X_SmallNumber_Class number((const X_SmallNumber*)instanceName,true);
if (!number.Number().exists)
{ // key is missing
context.Post(MI_RESULT_FAILED);
return ;
}
Uint64 num = number.Number().value;
// check if we have smaller half
if (num % 2 == 0 &&
(role.GetSize() == 0 || role == MI_T("number")) && // check role
(resultRole.GetSize() == 0 || resultRole == MI_T("half")) // check result role
)
{
context.Post(FillNumberByKey(num / 2));
}
// check if we have bigger half
if (num * 2 < 10000 &&
(role.GetSize() == 0 || role == MI_T("half")) && // check role
(resultRole.GetSize() == 0 || resultRole == MI_T("number")) // check result role
)
{
context.Post(FillNumberByKey(num * 2));
}
context.Post(MI_RESULT_OK);
}
void X_Halves_Class_Provider::ReferenceInstances(
Context& context,
const String& nameSpace,
const MI_Instance* instanceName,
const String& role,
const PropertySet& propertySet,
bool keysOnly,
const MI_Filter* filter)
{
context.Post(MI_RESULT_NOT_SUPPORTED);
}
MI_END_NAMESPACE
MI_BEGIN_NAMESPACE
void X_Halves_Class_Provider::Load(
Context& context)
{
context.Post(MI_RESULT_OK);
}
void X_Halves_Class_Provider::Unload(
Context& context)
{
context.Post(MI_RESULT_OK);
}
MI_END_NAMESPACE
| 23.449664 | 90 | 0.644533 | Beguiled |
6a5bc50b3d3d4a4110129e869e023df358f61a0a | 3,545 | hpp | C++ | libcaf_core/caf/mixin/subscriber.hpp | mydatamodels/actor-framework | d8fe071c86137918dff57ea12fc7aa44e7f0190a | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/caf/mixin/subscriber.hpp | mydatamodels/actor-framework | d8fe071c86137918dff57ea12fc7aa44e7f0190a | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | libcaf_core/caf/mixin/subscriber.hpp | mydatamodels/actor-framework | d8fe071c86137918dff57ea12fc7aa44e7f0190a | [
"BSL-1.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* ____ _ _____ *
* / ___| / \ | ___| C++ *
* | | / _ \ | |_ Actor *
* | |___ / ___ \| _| Framework *
* \____/_/ \_|_| *
* *
* Copyright 2011-2018 Dominik Charousset *
* *
* Distributed under the terms and conditions of the BSD 3-Clause License or *
* (at your option) under the terms and conditions of the Boost Software *
* License 1.0. See accompanying files LICENSE and LICENSE_ALTERNATIVE. *
* *
* If you did not receive a copy of the license files, see *
* http://opensource.org/licenses/BSD-3-Clause and *
* http://www.boost.org/LICENSE_1_0.txt. *
******************************************************************************/
#pragma once
#include <unordered_set>
#include "caf/fwd.hpp"
#include "caf/group.hpp"
namespace caf::mixin {
/// Marker for `subscriber`.
struct subscriber_base {};
/// A `subscriber` is an actor that can subscribe
/// to a `group` via `self->join(...)`.
template <class Base, class Subtype>
class subscriber : public Base, public subscriber_base {
public:
// -- member types -----------------------------------------------------------
/// Allows subtypes to refer mixed types with a simple name.
using extended_base = subscriber;
/// A container for storing subscribed groups.
using subscriptions = std::unordered_set<group>;
// -- constructors, destructors, and assignment operators --------------------
template <class... Ts>
subscriber(actor_config& cfg, Ts&&... xs)
: Base(cfg, std::forward<Ts>(xs)...) {
if (cfg.groups != nullptr)
for (auto& grp : *cfg.groups)
join(grp);
}
// -- overridden functions of monitorable_actor ------------------------------
bool cleanup(error&& fail_state, execution_unit* ptr) override {
auto me = this->ctrl();
for (auto& subscription : subscriptions_)
subscription->unsubscribe(me);
subscriptions_.clear();
return Base::cleanup(std::move(fail_state), ptr);
}
// -- group management -------------------------------------------------------
/// Causes this actor to subscribe to the group `what`.
/// The group will be unsubscribed if the actor finishes execution.
void join(const group& what) {
CAF_LOG_TRACE(CAF_ARG(what));
if (what == invalid_group)
return;
if (what->subscribe(this->ctrl()))
subscriptions_.emplace(what);
}
/// Causes this actor to leave the group `what`.
void leave(const group& what) {
CAF_LOG_TRACE(CAF_ARG(what));
if (subscriptions_.erase(what) > 0)
what->unsubscribe(this->ctrl());
}
/// Returns all subscribed groups.
const subscriptions& joined_groups() const {
return subscriptions_;
}
private:
// -- data members -----------------------------------------------------------
/// Stores all subscribed groups.
subscriptions subscriptions_;
};
} // namespace caf
| 36.546392 | 80 | 0.472496 | mydatamodels |
6a5c9978d647b2abf2c1b08a4d22fca238db76dc | 6,228 | cpp | C++ | src/dis6/LinearSegmentParameter.cpp | AlphaPixel/open-dis-cpp | 90634cade32ac98e2108be8799bd2ec949c4337e | [
"BSD-2-Clause"
] | 42 | 2017-02-22T07:23:06.000Z | 2022-03-07T12:34:11.000Z | src/dis6/LinearSegmentParameter.cpp | AlphaPixel/open-dis-cpp | 90634cade32ac98e2108be8799bd2ec949c4337e | [
"BSD-2-Clause"
] | 62 | 2017-07-14T11:06:55.000Z | 2022-01-22T02:32:45.000Z | src/dis6/LinearSegmentParameter.cpp | AlphaPixel/open-dis-cpp | 90634cade32ac98e2108be8799bd2ec949c4337e | [
"BSD-2-Clause"
] | 51 | 2017-08-10T16:44:32.000Z | 2021-12-16T09:57:42.000Z | #include <dis6/LinearSegmentParameter.h>
using namespace DIS;
LinearSegmentParameter::LinearSegmentParameter():
_segmentNumber(0),
_segmentAppearance(),
_location(),
_orientation(),
_segmentLength(0),
_segmentWidth(0),
_segmentHeight(0),
_segmentDepth(0),
_pad1(0)
{
}
LinearSegmentParameter::~LinearSegmentParameter()
{
}
unsigned char LinearSegmentParameter::getSegmentNumber() const
{
return _segmentNumber;
}
void LinearSegmentParameter::setSegmentNumber(unsigned char pX)
{
_segmentNumber = pX;
}
SixByteChunk& LinearSegmentParameter::getSegmentAppearance()
{
return _segmentAppearance;
}
const SixByteChunk& LinearSegmentParameter::getSegmentAppearance() const
{
return _segmentAppearance;
}
void LinearSegmentParameter::setSegmentAppearance(const SixByteChunk &pX)
{
_segmentAppearance = pX;
}
Vector3Double& LinearSegmentParameter::getLocation()
{
return _location;
}
const Vector3Double& LinearSegmentParameter::getLocation() const
{
return _location;
}
void LinearSegmentParameter::setLocation(const Vector3Double &pX)
{
_location = pX;
}
Orientation& LinearSegmentParameter::getOrientation()
{
return _orientation;
}
const Orientation& LinearSegmentParameter::getOrientation() const
{
return _orientation;
}
void LinearSegmentParameter::setOrientation(const Orientation &pX)
{
_orientation = pX;
}
unsigned short LinearSegmentParameter::getSegmentLength() const
{
return _segmentLength;
}
void LinearSegmentParameter::setSegmentLength(unsigned short pX)
{
_segmentLength = pX;
}
unsigned short LinearSegmentParameter::getSegmentWidth() const
{
return _segmentWidth;
}
void LinearSegmentParameter::setSegmentWidth(unsigned short pX)
{
_segmentWidth = pX;
}
unsigned short LinearSegmentParameter::getSegmentHeight() const
{
return _segmentHeight;
}
void LinearSegmentParameter::setSegmentHeight(unsigned short pX)
{
_segmentHeight = pX;
}
unsigned short LinearSegmentParameter::getSegmentDepth() const
{
return _segmentDepth;
}
void LinearSegmentParameter::setSegmentDepth(unsigned short pX)
{
_segmentDepth = pX;
}
unsigned int LinearSegmentParameter::getPad1() const
{
return _pad1;
}
void LinearSegmentParameter::setPad1(unsigned int pX)
{
_pad1 = pX;
}
void LinearSegmentParameter::marshal(DataStream& dataStream) const
{
dataStream << _segmentNumber;
_segmentAppearance.marshal(dataStream);
_location.marshal(dataStream);
_orientation.marshal(dataStream);
dataStream << _segmentLength;
dataStream << _segmentWidth;
dataStream << _segmentHeight;
dataStream << _segmentDepth;
dataStream << _pad1;
}
void LinearSegmentParameter::unmarshal(DataStream& dataStream)
{
dataStream >> _segmentNumber;
_segmentAppearance.unmarshal(dataStream);
_location.unmarshal(dataStream);
_orientation.unmarshal(dataStream);
dataStream >> _segmentLength;
dataStream >> _segmentWidth;
dataStream >> _segmentHeight;
dataStream >> _segmentDepth;
dataStream >> _pad1;
}
bool LinearSegmentParameter::operator ==(const LinearSegmentParameter& rhs) const
{
bool ivarsEqual = true;
if( ! (_segmentNumber == rhs._segmentNumber) ) ivarsEqual = false;
if( ! (_segmentAppearance == rhs._segmentAppearance) ) ivarsEqual = false;
if( ! (_location == rhs._location) ) ivarsEqual = false;
if( ! (_orientation == rhs._orientation) ) ivarsEqual = false;
if( ! (_segmentLength == rhs._segmentLength) ) ivarsEqual = false;
if( ! (_segmentWidth == rhs._segmentWidth) ) ivarsEqual = false;
if( ! (_segmentHeight == rhs._segmentHeight) ) ivarsEqual = false;
if( ! (_segmentDepth == rhs._segmentDepth) ) ivarsEqual = false;
if( ! (_pad1 == rhs._pad1) ) ivarsEqual = false;
return ivarsEqual;
}
int LinearSegmentParameter::getMarshalledSize() const
{
int marshalSize = 0;
marshalSize = marshalSize + 1; // _segmentNumber
marshalSize = marshalSize + _segmentAppearance.getMarshalledSize(); // _segmentAppearance
marshalSize = marshalSize + _location.getMarshalledSize(); // _location
marshalSize = marshalSize + _orientation.getMarshalledSize(); // _orientation
marshalSize = marshalSize + 2; // _segmentLength
marshalSize = marshalSize + 2; // _segmentWidth
marshalSize = marshalSize + 2; // _segmentHeight
marshalSize = marshalSize + 2; // _segmentDepth
marshalSize = marshalSize + 4; // _pad1
return marshalSize;
}
// Copyright (c) 1995-2009 held by the author(s). All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer
// in the documentation and/or other materials provided with the
// distribution.
// * Neither the names of the Naval Postgraduate School (NPS)
// Modeling Virtual Environments and Simulation (MOVES) Institute
// (http://www.nps.edu and http://www.MovesInstitute.org)
// 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.
| 28.568807 | 93 | 0.745665 | AlphaPixel |
6a5ca6c9fede4f97106d6204d89b025f2bf8bb80 | 946 | hpp | C++ | src/recording/encoders/encoder.hpp | mightybruno/KShare | c1124354be9c8bb5c1931e37e19391f0b6c4389f | [
"MIT"
] | 213 | 2017-04-23T13:12:59.000Z | 2022-01-18T09:03:45.000Z | src/recording/encoders/encoder.hpp | mightybruno/KShare | c1124354be9c8bb5c1931e37e19391f0b6c4389f | [
"MIT"
] | 67 | 2017-04-29T21:49:36.000Z | 2018-06-09T21:30:04.000Z | src/recording/encoders/encoder.hpp | mightybruno/KShare | c1124354be9c8bb5c1931e37e19391f0b6c4389f | [
"MIT"
] | 38 | 2017-04-30T09:57:46.000Z | 2022-01-15T20:22:52.000Z | #ifndef ENCODER_HPP
#define ENCODER_HPP
#include <QImage>
#include <QSize>
extern "C" {
#include <libavcodec/avcodec.h>
#include <libavformat/avformat.h>
#include <libswscale/swscale.h>
}
struct OutputStream {
AVStream *st = NULL;
AVCodecContext *enc = NULL;
int64_t nextPts = 0;
AVFrame *frame = NULL;
SwsContext *sws = NULL;
};
struct CodecSettings {
int bitrate;
int gopSize;
int bFrames;
int mbDecisions;
QString h264Profile;
int h264Crf;
bool vp9Lossless;
};
class Encoder {
public:
Encoder(QString &targetFile, QSize res, CodecSettings *settings = NULL);
~Encoder();
bool addFrame(QImage frm);
bool isRunning();
bool end();
private:
AVCodec *codec = NULL;
OutputStream *out = new OutputStream;
AVFormatContext *fc = NULL;
bool success = false;
bool ended = false;
QSize size;
void setFrameRGB(QImage img);
};
#endif // ENCODER_HPP
| 16.892857 | 76 | 0.661734 | mightybruno |
6a6280e6a0a226f8f19c557fcabea131e16c7514 | 306 | cpp | C++ | atcoder/abc/20/a.cpp | utgw/programming-contest | eb7f28ae913296c6f4f9a8136dca8bd321e01e79 | [
"MIT"
] | null | null | null | atcoder/abc/20/a.cpp | utgw/programming-contest | eb7f28ae913296c6f4f9a8136dca8bd321e01e79 | [
"MIT"
] | null | null | null | atcoder/abc/20/a.cpp | utgw/programming-contest | eb7f28ae913296c6f4f9a8136dca8bd321e01e79 | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
#define FOR(i,m,n) for(int i=m;i<(n);i++)
#define REP(i,n) FOR(i,0,n)
#define ALL(x) (x).begin(),(x).end()
using namespace std;
typedef long long ll;
int main(void){
int q;
cin >> q;
if (q == 1)
cout << "ABC" << endl;
else
cout << "chokudai" << endl;
return 0;
}
| 18 | 41 | 0.558824 | utgw |
6a673688c8219042eb9dc1da3e7e81e903f7580d | 494 | hpp | C++ | Client/includes/states/PauseState.hpp | LiardeauxQ/r-type | 8a77164c276b2d5958cd3504a9ea34f1cf6823cf | [
"MIT"
] | 2 | 2020-02-12T12:02:00.000Z | 2020-12-23T15:31:59.000Z | Client/includes/states/PauseState.hpp | LiardeauxQ/r-type | 8a77164c276b2d5958cd3504a9ea34f1cf6823cf | [
"MIT"
] | null | null | null | Client/includes/states/PauseState.hpp | LiardeauxQ/r-type | 8a77164c276b2d5958cd3504a9ea34f1cf6823cf | [
"MIT"
] | 2 | 2020-02-12T12:02:03.000Z | 2020-12-23T15:32:55.000Z | /*
** EPITECH PROJECT, 2019
** PauseState.hpp
** File description:
** MenuState header
*/
#ifndef PAUSESTATE_HPP
#define PAUSESTATE_HPP
#include "State.hpp"
class PauseState : public State {
public:
PauseState(std::shared_ptr<GameData> gameData);
~PauseState();
void onStart();
void onStop();
void onPause();
void onResume();
Transition update();
Transition handleEvent(sf::Event &event);
};
#endif /* !PAUSESTATE_HPP */
| 19 | 55 | 0.625506 | LiardeauxQ |
6a696e2bf6e8f99049f29cd32c6e2e6e620d9d5e | 936 | cpp | C++ | source/loader/linux/driver_discovery_lin.cpp | bgoglin/level-zero | e36cbe25004642a0b0e8ed0670a03725caacd8ad | [
"MIT"
] | 3 | 2021-04-30T13:57:15.000Z | 2021-06-28T06:59:47.000Z | source/loader/linux/driver_discovery_lin.cpp | bgoglin/level-zero | e36cbe25004642a0b0e8ed0670a03725caacd8ad | [
"MIT"
] | null | null | null | source/loader/linux/driver_discovery_lin.cpp | bgoglin/level-zero | e36cbe25004642a0b0e8ed0670a03725caacd8ad | [
"MIT"
] | 1 | 2021-07-06T04:42:48.000Z | 2021-07-06T04:42:48.000Z | /*
*
* Copyright (C) 2020 Intel Corporation
*
* SPDX-License-Identifier: MIT
*
*/
#include "source/loader/driver_discovery.h"
#include "source/inc/ze_util.h"
#include <iostream>
#include <sstream>
#include <string>
namespace loader {
static const char *knownDriverNames[] = {
MAKE_LIBRARY_NAME("ze_intel_gpu", "1"),
};
std::vector<DriverLibraryPath> discoverEnabledDrivers() {
std::vector<DriverLibraryPath> enabledDrivers;
const char *altDrivers = nullptr;
// ZE_ENABLE_ALT_DRIVERS is for development/debug only
altDrivers = getenv("ZE_ENABLE_ALT_DRIVERS");
if (altDrivers == nullptr) {
for (auto path : knownDriverNames) {
enabledDrivers.emplace_back(path);
}
} else {
std::stringstream ss(altDrivers);
while (ss.good()) {
std::string substr;
getline(ss, substr, ',');
enabledDrivers.emplace_back(substr);
}
}
return enabledDrivers;
}
} // namespace loader
| 21.272727 | 57 | 0.688034 | bgoglin |
6a69d71eca6c7d026d5b3d43c05b8d46ca13d94a | 636 | hpp | C++ | include/Event.hpp | RPClab/Analysis | cca7d4d07ead111ac61caee31ebd3522c88bac96 | [
"MIT"
] | null | null | null | include/Event.hpp | RPClab/Analysis | cca7d4d07ead111ac61caee31ebd3522c88bac96 | [
"MIT"
] | 1 | 2021-08-04T08:20:00.000Z | 2021-08-04T08:20:00.000Z | include/Event.hpp | MaftyNaveyuErin/Analysis | 1d1870befde835baf6efb4fcaec292ee536d13f8 | [
"MIT"
] | 2 | 2021-07-29T06:47:38.000Z | 2021-08-04T09:17:02.000Z | #pragma once
#include "Channel.hpp"
#include "TObject.h"
#include <string>
#include <vector>
class Event: public TObject
{
public:
Event()=default;
void addChannel(const Channel& ch);
void clear();
double BoardID{0};
int EventNumber{0};
int Pattern{0};
int ChannelMask{0};
double EventSize{0};
double TriggerTimeTag{0};
double Period_ns{0.0};
std::string Model{""};
std::string FamilyCode{""};
std::vector<Channel> Channels;
ClassDef(Event, 2);
};
| 23.555556 | 53 | 0.512579 | RPClab |
6a6f09d56511d23170ba885239075452341f4c0f | 4,040 | cpp | C++ | src/cat_sorting.cpp | prescott66/poedit | f52d76beff00198686b27996d5a11fa24252a173 | [
"MIT"
] | null | null | null | src/cat_sorting.cpp | prescott66/poedit | f52d76beff00198686b27996d5a11fa24252a173 | [
"MIT"
] | null | null | null | src/cat_sorting.cpp | prescott66/poedit | f52d76beff00198686b27996d5a11fa24252a173 | [
"MIT"
] | null | null | null | /*
* This file is part of Poedit (http://www.poedit.net)
*
* Copyright (C) 1999-2012 Vaclav Slavik
* Copyright (C) 2005 Olivier Sannier
*
* 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 "cat_sorting.h"
#include <wx/config.h>
/*static*/ SortOrder SortOrder::Default()
{
SortOrder order;
wxString by = wxConfig::Get()->Read(_T("/sort_by"), _T("file-order"));
long untrans = wxConfig::Get()->Read(_T("/sort_untrans_first"), 1L);
if ( by == _T("source") )
order.by = By_Source;
else if ( by == _T("translation") )
order.by = By_Translation;
else
order.by = By_FileOrder;
order.untransFirst = (untrans != 0);
return order;
}
void SortOrder::Save()
{
wxString bystr;
switch ( by )
{
case By_FileOrder:
bystr = _T("file-order");
break;
case By_Source:
bystr = _T("source");
break;
case By_Translation:
bystr = _T("translation");
break;
}
wxConfig::Get()->Write(_T("/sort_by"), bystr);
wxConfig::Get()->Write(_T("/sort_untrans_first"), untransFirst);
}
bool CatalogItemsComparator::operator()(int i, int j) const
{
const CatalogItem& a = Item(i);
const CatalogItem& b = Item(j);
if ( m_order.untransFirst )
{
if ( a.GetValidity() == CatalogItem::Val_Invalid && b.GetValidity() != CatalogItem::Val_Invalid )
return true;
if ( a.GetValidity() != CatalogItem::Val_Invalid && b.GetValidity() == CatalogItem::Val_Invalid )
return false;
if ( !a.IsTranslated() && b.IsTranslated() )
return true;
if ( a.IsTranslated() && !b.IsTranslated() )
return false;
if ( a.IsFuzzy() && !b.IsFuzzy() )
return true;
if ( !a.IsFuzzy() && b.IsFuzzy() )
return false;
}
switch ( m_order.by )
{
case SortOrder::By_FileOrder:
{
return i < j;
}
case SortOrder::By_Source:
{
int r = CompareStrings(a.GetString(), b.GetString());
if ( r != 0 )
return r < 0;
break;
}
case SortOrder::By_Translation:
{
int r = CompareStrings(a.GetTranslation(), b.GetTranslation());
if ( r != 0 )
return r < 0;
break;
}
}
// As last resort, sort by position in file. Note that this means that
// no two items are considered equal w.r.t. sort order; this ensures stable
// ordering.
return i < j;
}
int CatalogItemsComparator::CompareStrings(wxString a, wxString b) const
{
// TODO: * use ICU for correct ordering
// * use natural sort (for numbers)
// * use ICU for correct case insensitivity
a.Replace(_T("&"), _T(""));
a.Replace(_T("_"), _T(""));
b.Replace(_T("&"), _T(""));
b.Replace(_T("_"), _T(""));
return a.CmpNoCase(b);
}
| 28.857143 | 105 | 0.597277 | prescott66 |
6a731d968ed5d8be887538dd0054220894a53008 | 2,354 | cpp | C++ | 101908/B.cpp | julianferres/Codeforces | ac80292a4d53b8078fc1a85e91db353c489555d9 | [
"MIT"
] | 4 | 2020-01-31T15:49:25.000Z | 2020-07-07T11:44:03.000Z | 101908/B.cpp | julianferres/CodeForces | 14e8369e82a2403094183d6f7824201f681c9f65 | [
"MIT"
] | null | null | null | 101908/B.cpp | julianferres/CodeForces | 14e8369e82a2403094183d6f7824201f681c9f65 | [
"MIT"
] | null | null | null | /* AUTHOR: julianferres */
#include <bits/stdc++.h>
using namespace std;
// neal Debugger
template<typename A, typename B> ostream& operator<<(ostream &os, const pair<A, B> &p) { return os << '(' << p.first << ", " << p.second << ')'; }
template<typename T_container, typename T = typename enable_if<!is_same<T_container, string>::value, typename T_container::value_type>::type> ostream& operator<<(ostream &os, const T_container &v) { os << '{'; string sep; for (const T &x : v) os << sep << x, sep = ", "; return os << '}'; }
void dbg_out() { cerr << endl; }
template<typename Head, typename... Tail> void dbg_out(Head H, Tail... T) { cerr << ' ' << H; dbg_out(T...); }
#ifdef LOCAL
#define dbg(...) cerr << "(" << #__VA_ARGS__ << "):", dbg_out(__VA_ARGS__)
#else
#define dbg(...)
#endif
typedef long long ll;
typedef vector<ll> vi; typedef pair<ll,ll> ii;
typedef vector<ii> vii; typedef vector<bool> vb;
#define FIN ios::sync_with_stdio(0);cin.tie(0);cout.tie(0)
#define forr(i, a, b) for(int i = (a); i < (int) (b); i++)
#define forn(i, n) forr(i, 0, n)
#define DBG(x) cerr << #x << " = " << (x) << endl
#define RAYA cerr << "===============================" << endl
#define pb push_back
#define mp make_pair
#define all(c) (c).begin(),(c).end()
#define esta(x,c) ((c).find(x) != (c).end())
const int MOD = 1e9+7; // 998244353
const int MAXN = 2e5+5;
const int GRUNDY_GRANDE = 1000;
vector<vector<int>> grundy(105, vector<int>(105));
int mex(int r, int c){
unordered_set<int> mex_set;
forn(i, r) mex_set.insert(grundy[i][c]);
forn(i, c) mex_set.insert(grundy[r][i]);
forr(i, 1, min(r, c)) //Diagonales
mex_set.insert(grundy[r-i][c-i]);
forn(i, GRUNDY_GRANDE + 1)
if(!esta(i, mex_set)) return i;
}
int main(){
FIN;
forn(i, 104){
grundy[i][0] = grundy[i][i] = grundy[0][i] = GRUNDY_GRANDE;
}
forr(i, 1, 101){
forr(j, 1, 101)
if(i != j) grundy[i][j] = mex(i, j);
}
int n; cin >> n;
int resultado_final = 0;
forn(i, n){
int ri, ci; cin >> ri >> ci;
if(grundy[ri][ci] == GRUNDY_GRANDE){
cout << "Y\n"; // YA directamente gana
return 0;
}
resultado_final ^= grundy[ri][ci]; // Cada ficha juega individualmente
}
cout << (resultado_final ? "Y" : "N") << "\n";
return 0;
}
| 30.973684 | 290 | 0.568819 | julianferres |
6a75d731e0a24deda022adeeec5ff7bb52df510e | 10,192 | cpp | C++ | benchmarks/linux-sgx/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp | vschiavoni/unine-twine | 312d770585ea88c13ef135ef467fee779494fd90 | [
"Apache-2.0"
] | 20 | 2021-04-05T20:05:57.000Z | 2022-02-19T18:48:52.000Z | benchmarks/linux-sgx/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp | vschiavoni/unine-twine | 312d770585ea88c13ef135ef467fee779494fd90 | [
"Apache-2.0"
] | null | null | null | benchmarks/linux-sgx/sdk/protected_fs/sgx_tprotected_fs/file_other.cpp | vschiavoni/unine-twine | 312d770585ea88c13ef135ef467fee779494fd90 | [
"Apache-2.0"
] | 4 | 2021-02-22T14:52:21.000Z | 2022-01-10T16:58:39.000Z | /*
* Copyright (C) 2011-2020 Intel Corporation. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Intel Corporation nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "sgx_tprotected_fs.h"
#include "sgx_tprotected_fs_t.h"
#include "protected_fs_file.h"
#include "benchmark_utils.h"
#include <sgx_utils.h>
//#include <sgx_trts.h>
#include <errno.h>
// this function returns 0 only if the specified file existed and it was actually deleted
// before we do that, we try to see if the file contained a monotonic counter, and if it did, we delete it from the system
int32_t protected_fs_file::remove(const char* filename)
{
sgx_status_t status;
int32_t result32 = 0;
/*
void* file = NULL;
int64_t real_file_size = 0;
if (filename == NULL)
return 1;
meta_data_node_t* file_meta_data = NULL;
meta_data_encrypted_t* encrypted_part_plain = NULL;
// if we have a problem in any of the stages, we simply jump to the end and try to remove the file...
do {
status = u_sgxprotectedfs_check_if_file_exists(&result, filename);
if (status != SGX_SUCCESS)
break;
if (result == 0)
{
errno = EINVAL;
return 1; // no such file, or file locked so we can't delete it anyways
}
try {
file_meta_data = new meta_data_node_t;
encrypted_part_plain = new meta_data_encrypted_t;
}
catch (std::bad_alloc e) {
break;
}
status = u_sgxprotectedfs_exclusive_file_open(&file, filename, 1, &real_file_size, &result32);
if (status != SGX_SUCCESS || file == NULL)
break;
if (real_file_size == 0 || real_file_size % NODE_SIZE != 0)
break; // empty file or not an SGX protected FS file
// might be an SGX protected FS file
status = u_sgxprotectedfs_fread_node(&result32, file, 0, (uint8_t*)file_meta_data, NODE_SIZE);
if (status != SGX_SUCCESS || result32 != 0)
break;
if (file_meta_data->plain_part.major_version != SGX_FILE_MAJOR_VERSION)
break;
sgx_aes_gcm_128bit_key_t zero_key_id = {0};
sgx_aes_gcm_128bit_key_t key = {0};
if (consttime_memequal(&file_meta_data->plain_part.key_id, &zero_key_id, sizeof(sgx_aes_gcm_128bit_key_t)) == 1)
break; // shared file - no monotonic counter
sgx_key_request_t key_request = {0};
key_request.key_name = SGX_KEYSELECT_SEAL;
key_request.key_policy = SGX_KEYPOLICY_MRENCLAVE;
memcpy(&key_request.key_id, &file_meta_data->plain_part.key_id, sizeof(sgx_key_id_t));
status = sgx_get_key(&key_request, &key);
if (status != SGX_SUCCESS)
break;
status = benchmark_sgx_rijndael128GCM_decrypt(&key,
file_meta_data->encrypted_part, sizeof(meta_data_encrypted_blob_t),
(uint8_t*)encrypted_part_plain,
file_meta_data->plain_part.meta_data_iv, SGX_AESGCM_IV_SIZE,
NULL, 0,
&file_meta_data->plain_part.meta_data_gmac);
if (status != SGX_SUCCESS)
break;
sgx_mc_uuid_t empty_mc_uuid = {0};
if (consttime_memequal(&empty_mc_uuid, &encrypted_part_plain->mc_uuid, sizeof(sgx_mc_uuid_t)) == 0)
{
status = sgx_destroy_monotonic_counter(&encrypted_part_plain->mc_uuid);
if (status != SGX_SUCCESS)
break;
// monotonic counter was deleted, mission accomplished!!
}
}
while (0);
// cleanup
if (file_meta_data != NULL)
delete file_meta_data;
if (encrypted_part_plain != NULL)
{
// scrub the encrypted part
memset_s(encrypted_part_plain, sizeof(meta_data_encrypted_t), 0, sizeof(meta_data_encrypted_t));
delete encrypted_part_plain;
}
if (file != NULL)
u_sgxprotectedfs_fclose(&result32, file);
*/
// do the actual file removal
status = u_sgxprotectedfs_remove(&result32, filename);
if (status != SGX_SUCCESS)
{
errno = status;
return 1;
}
if (result32 != 0)
{
if (result32 == -1) // no external errno value
errno = EPERM;
else
errno = result32;
return 1;
}
return 0;
}
int64_t protected_fs_file::tell()
{
int64_t result;
sgx_thread_mutex_lock(&mutex);
if (file_status != SGX_FILE_STATUS_OK)
{
errno = EPERM;
last_error = SGX_ERROR_FILE_BAD_STATUS;
sgx_thread_mutex_unlock(&mutex);
return -1;
}
result = offset;
sgx_thread_mutex_unlock(&mutex);
return result;
}
// we don't support sparse files, fseek beyond the current file size will fail
int protected_fs_file::seek(int64_t new_offset, int origin)
{
sgx_thread_mutex_lock(&mutex);
if (file_status != SGX_FILE_STATUS_OK)
{
last_error = SGX_ERROR_FILE_BAD_STATUS;
sgx_thread_mutex_unlock(&mutex);
return -1;
}
//if (open_mode.binary == 0 && origin != SEEK_SET && new_offset != 0)
//{
// last_error = EINVAL;
// sgx_thread_mutex_unlock(&mutex);
// return -1;
//}
int result = -1;
switch (origin)
{
case SEEK_SET:
if (new_offset >= 0 && new_offset <= encrypted_part_plain.size)
{
offset = new_offset;
result = 0;
}
break;
case SEEK_CUR:
if ((offset + new_offset) >= 0 && (offset + new_offset) <= encrypted_part_plain.size)
{
offset += new_offset;
result = 0;
}
break;
case SEEK_END:
if (new_offset <= 0 && new_offset >= (0 - encrypted_part_plain.size))
{
offset = encrypted_part_plain.size + new_offset;
result = 0;
}
break;
default:
break;
}
if (result == 0)
end_of_file = false;
else
last_error = EINVAL;
sgx_thread_mutex_unlock(&mutex);
return result;
}
uint32_t protected_fs_file::get_error()
{
uint32_t result = SGX_SUCCESS;
sgx_thread_mutex_lock(&mutex);
if (last_error != SGX_SUCCESS)
result = last_error;
else if (file_status != SGX_FILE_STATUS_OK)
result = SGX_ERROR_FILE_BAD_STATUS;
sgx_thread_mutex_unlock(&mutex);
return result;
}
bool protected_fs_file::get_eof()
{
return end_of_file;
}
void protected_fs_file::clear_error()
{
sgx_thread_mutex_lock(&mutex);
if (file_status == SGX_FILE_STATUS_NOT_INITIALIZED ||
file_status == SGX_FILE_STATUS_CLOSED ||
file_status == SGX_FILE_STATUS_CRYPTO_ERROR ||
file_status == SGX_FILE_STATUS_CORRUPTED ||
file_status == SGX_FILE_STATUS_MEMORY_CORRUPTED) // can't fix these...
{
sgx_thread_mutex_unlock(&mutex);
return;
}
if (file_status == SGX_FILE_STATUS_FLUSH_ERROR)
{
if (internal_flush(/*false,*/ true) == true)
file_status = SGX_FILE_STATUS_OK;
}
if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED)
{
if (write_all_changes_to_disk(true) == true)
{
need_writing = false;
file_status = SGX_FILE_STATUS_OK;
}
}
/*
if (file_status == SGX_FILE_STATUS_WRITE_TO_DISK_FAILED_NEED_MC)
{
if (write_all_changes_to_disk(true) == true)
{
need_writing = false;
file_status = SGX_FILE_STATUS_MC_NOT_INCREMENTED; // fall through...next 'if' should take care of this one
}
}
if ((file_status == SGX_FILE_STATUS_MC_NOT_INCREMENTED) &&
(encrypted_part_plain.mc_value <= (UINT_MAX-2)))
{
uint32_t mc_value;
sgx_status_t status = sgx_increment_monotonic_counter(&encrypted_part_plain.mc_uuid, &mc_value);
if (status == SGX_SUCCESS)
{
assert(mc_value == encrypted_part_plain.mc_value);
file_status = SGX_FILE_STATUS_OK;
}
else
{
last_error = status;
}
}
*/
if (file_status == SGX_FILE_STATUS_OK)
{
last_error = SGX_SUCCESS;
end_of_file = false;
}
sgx_thread_mutex_unlock(&mutex);
}
// clears the cache with all the plain data that was in it
// doesn't clear the meta-data and first node, which are part of the 'main' structure
int32_t protected_fs_file::clear_cache()
{
sgx_thread_mutex_lock(&mutex);
if (file_status != SGX_FILE_STATUS_OK)
{
sgx_thread_mutex_unlock(&mutex);
clear_error(); // attempt to fix the file, will also flush it
sgx_thread_mutex_lock(&mutex);
}
else // file_status == SGX_FILE_STATUS_OK
{
internal_flush(/*false,*/ true);
}
if (file_status != SGX_FILE_STATUS_OK) // clearing the cache might lead to losing un-saved data
{
sgx_thread_mutex_unlock(&mutex);
return 1;
}
while (cache.size() > 0)
{
void* data = cache.get_last();
assert(data != NULL);
assert(((file_data_node_t*)data)->need_writing == false); // need_writing is in the same offset in both node types
// for production -
if (data == NULL || ((file_data_node_t*)data)->need_writing == true)
{
sgx_thread_mutex_unlock(&mutex);
return 1;
}
cache.remove_last();
// before deleting the memory, need to scrub the plain secrets
if (((file_data_node_t*)data)->type == FILE_DATA_NODE_TYPE) // type is in the same offset in both node types
{
file_data_node_t* file_data_node = (file_data_node_t*)data;
memset_s(&file_data_node->plain, sizeof(data_node_t), 0, sizeof(data_node_t));
delete file_data_node;
}
else
{
file_mht_node_t* file_mht_node = (file_mht_node_t*)data;
memset_s(&file_mht_node->plain, sizeof(mht_node_t), 0, sizeof(mht_node_t));
delete file_mht_node;
}
}
sgx_thread_mutex_unlock(&mutex);
return 0;
}
| 25.672544 | 122 | 0.718407 | vschiavoni |
6a799b9f4c39aa781dfb7f22331f53657dfa4b64 | 5,442 | cc | C++ | INET_EC/visualizer/transportlayer/TransportConnectionOsgVisualizer.cc | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 12 | 2020-11-30T08:04:23.000Z | 2022-03-23T11:49:26.000Z | INET_EC/visualizer/transportlayer/TransportConnectionOsgVisualizer.cc | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 1 | 2021-01-26T10:49:56.000Z | 2021-01-31T16:58:52.000Z | INET_EC/visualizer/transportlayer/TransportConnectionOsgVisualizer.cc | LarryNguyen/ECSim- | 0d3f848642e49845ed7e4c7b97dd16bd3d65ede5 | [
"Apache-2.0"
] | 8 | 2021-03-15T02:05:51.000Z | 2022-03-21T13:14:02.000Z | //
// Copyright (C) OpenSim Ltd.
//
// This program is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with this program; if not, see <http://www.gnu.org/licenses/>.
//
#include "inet/common/ModuleAccess.h"
#include "inet/common/OSGUtils.h"
#include "inet/visualizer/transportlayer/TransportConnectionOsgVisualizer.h"
namespace inet {
namespace visualizer {
Define_Module(TransportConnectionOsgVisualizer);
#ifdef WITH_OSG
TransportConnectionOsgVisualizer::TransportConnectionOsgVisualization::TransportConnectionOsgVisualization(osg::Node *sourceNode, osg::Node *destinationNode, int sourceModuleId, int destinationModuleId, int count) :
TransportConnectionVisualization(sourceModuleId, destinationModuleId, count),
sourceNode(sourceNode),
destinationNode(destinationNode)
{
}
void TransportConnectionOsgVisualizer::initialize(int stage)
{
TransportConnectionVisualizerBase::initialize(stage);
if (!hasGUI()) return;
if (stage == INITSTAGE_LOCAL) {
networkNodeVisualizer = getModuleFromPar<NetworkNodeOsgVisualizer>(par("networkNodeVisualizerModule"), this);
}
}
osg::Node *TransportConnectionOsgVisualizer::createConnectionEndNode(tcp::TCPConnection *tcpConnection) const
{
auto path = resolveResourcePath((std::string(icon) + ".png").c_str());
auto image = inet::osg::createImage(path.c_str());
auto texture = new osg::Texture2D();
texture->setImage(image);
auto geometry = osg::createTexturedQuadGeometry(osg::Vec3(-image->s() / 2, 0.0, 0.0), osg::Vec3(image->s(), 0.0, 0.0), osg::Vec3(0.0, image->t(), 0.0), 0.0, 0.0, 1.0, 1.0);
auto stateSet = geometry->getOrCreateStateSet();
stateSet->setTextureAttributeAndModes(0, texture);
stateSet->setMode(GL_DEPTH_TEST, osg::StateAttribute::ON);
stateSet->setMode(GL_BLEND, osg::StateAttribute::ON);
stateSet->setMode(GL_LIGHTING, osg::StateAttribute::OFF);
stateSet->setRenderingHint(osg::StateSet::TRANSPARENT_BIN);
auto color = iconColorSet.getColor(connectionVisualizations.size());
auto colorArray = new osg::Vec4Array();
colorArray->push_back(osg::Vec4((double)color.red / 255.0, (double)color.green / 255.0, (double)color.blue / 255.0, 1));
geometry->setColorArray(colorArray, osg::Array::BIND_OVERALL);
auto geode = new osg::Geode();
geode->addDrawable(geometry);
return geode;
}
const TransportConnectionVisualizerBase::TransportConnectionVisualization *TransportConnectionOsgVisualizer::createConnectionVisualization(cModule *source, cModule *destination, tcp::TCPConnection *tcpConnection) const
{
auto sourceNode = createConnectionEndNode(tcpConnection);
auto destinationNode = createConnectionEndNode(tcpConnection);
return new TransportConnectionOsgVisualization(sourceNode, destinationNode, source->getId(), destination->getId(), 1);
}
void TransportConnectionOsgVisualizer::addConnectionVisualization(const TransportConnectionVisualization *connectionVisualization)
{
TransportConnectionVisualizerBase::addConnectionVisualization(connectionVisualization);
auto connectionOsgVisualization = static_cast<const TransportConnectionOsgVisualization *>(connectionVisualization);
auto sourceModule = getSimulation()->getModule(connectionVisualization->sourceModuleId);
auto sourceVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(sourceModule));
sourceVisualization->addAnnotation(connectionOsgVisualization->sourceNode, osg::Vec3d(0, 0, 32), 0); // TODO: size
auto destinationModule = getSimulation()->getModule(connectionVisualization->destinationModuleId);
auto destinationVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(destinationModule));
destinationVisualization->addAnnotation(connectionOsgVisualization->destinationNode, osg::Vec3d(0, 0, 32), 0); // TODO: size
}
void TransportConnectionOsgVisualizer::removeConnectionVisualization(const TransportConnectionVisualization *connectionVisualization)
{
TransportConnectionVisualizerBase::removeConnectionVisualization(connectionVisualization);
auto connectionOsgVisualization = static_cast<const TransportConnectionOsgVisualization *>(connectionVisualization);
auto sourceModule = getSimulation()->getModule(connectionVisualization->sourceModuleId);
auto sourceVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(sourceModule));
sourceVisualization->removeAnnotation(connectionOsgVisualization->sourceNode);
auto destinationModule = getSimulation()->getModule(connectionVisualization->destinationModuleId);
auto destinationVisualization = networkNodeVisualizer->getNetworkNodeVisualization(getContainingNode(destinationModule));
destinationVisualization->removeAnnotation(connectionOsgVisualization->destinationNode);
}
#endif // ifdef WITH_OSG
} // namespace visualizer
} // namespace inet
| 51.828571 | 218 | 0.789967 | LarryNguyen |
6a79ed6d1e35d244ed967fe0902d23a291ffafc7 | 3,909 | hpp | C++ | src/extra/imgui.hpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 12 | 2021-07-11T11:14:14.000Z | 2022-03-28T11:37:29.000Z | src/extra/imgui.hpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 103 | 2021-06-26T17:09:43.000Z | 2022-03-30T12:05:18.000Z | src/extra/imgui.hpp | fragcolor-xyz/chainblocks | bf83f8dc8f46637bc42713d1fa77e81228ddfccf | [
"BSD-3-Clause"
] | 8 | 2021-07-27T14:45:26.000Z | 2022-03-01T08:07:18.000Z | /* SPDX-License-Identifier: BSD-3-Clause */
/* Copyright © 2019 Fragcolor Pte. Ltd. */
#pragma once
#include "foundation.hpp"
#include "imgui.h"
#include "ImGuizmo.h"
namespace ImGuiExtra {
#include "imgui_memory_editor.h"
};
namespace chainblocks {
namespace ImGui {
constexpr uint32_t ImGuiContextCC = 'gui ';
struct Context {
static inline Type Info{
{CBType::Object,
{.object = {.vendorId = CoreCC, .typeId = ImGuiContextCC}}}};
// Useful to compare with with plugins, they might mismatch!
static inline const char *Version = ::ImGui::GetVersion();
// ImGuiContext *context = ::ImGui::CreateContext();
// ~Context() { ::ImGui::DestroyContext(context); }
// void Set() { ::ImGui::SetCurrentContext(context); }
// void Reset() {
// ::ImGui::DestroyContext(context);
// context = ::ImGui::CreateContext();
// }
};
struct Enums {
#define REGISTER_FLAGS_EX(_NAME_, _CC_) \
REGISTER_FLAGS(_NAME_, _CC_); \
static inline Type _NAME_##SeqType = Type::SeqOf(_NAME_##Type); \
static inline Type _NAME_##VarType = Type::VariableOf(_NAME_##Type); \
static inline Type _NAME_##VarSeqType = Type::VariableOf(_NAME_##SeqType)
enum class GuiButton {
Normal,
Small,
Invisible,
ArrowLeft,
ArrowRight,
ArrowUp,
ArrowDown
};
REGISTER_ENUM(GuiButton, 'guiB'); // FourCC = 0x67756942
enum class GuiTableFlags {
None = ::ImGuiTableFlags_None,
Resizable = ::ImGuiTableFlags_Resizable,
Reorderable = ::ImGuiTableFlags_Reorderable,
Hideable = ::ImGuiTableFlags_Hideable,
Sortable = ::ImGuiTableFlags_Sortable
};
REGISTER_FLAGS_EX(GuiTableFlags, 'guiT'); // FourCC = 0x67756954
enum class GuiTableColumnFlags {
None = ::ImGuiTableColumnFlags_None,
Disabled = ::ImGuiTableColumnFlags_Disabled,
DefaultHide = ::ImGuiTableColumnFlags_DefaultHide,
DefaultSort = ::ImGuiTableColumnFlags_DefaultSort
};
REGISTER_FLAGS_EX(GuiTableColumnFlags, 'guTC'); // FourCC = 0x67755443
enum class GuiTreeNodeFlags {
None = ::ImGuiTreeNodeFlags_None,
Selected = ::ImGuiTreeNodeFlags_Selected,
Framed = ::ImGuiTreeNodeFlags_Framed,
OpenOnDoubleClick = ::ImGuiTreeNodeFlags_OpenOnDoubleClick,
OpenOnArrow = ::ImGuiTreeNodeFlags_OpenOnArrow,
Leaf = ::ImGuiTreeNodeFlags_Leaf,
Bullet = ::ImGuiTreeNodeFlags_Bullet,
SpanAvailWidth = ::ImGuiTreeNodeFlags_SpanAvailWidth,
SpanFullWidth = ::ImGuiTreeNodeFlags_SpanFullWidth
};
REGISTER_FLAGS_EX(GuiTreeNodeFlags, 'guTN'); // FourCC = 0x6775544E
enum class GuiWindowFlags {
None = ::ImGuiWindowFlags_None,
NoTitleBar = ::ImGuiWindowFlags_NoTitleBar,
NoResize = ::ImGuiWindowFlags_NoResize,
NoMove = ::ImGuiWindowFlags_NoMove,
NoScrollbar = ::ImGuiWindowFlags_NoScrollbar,
NoScrollWithMouse = ::ImGuiWindowFlags_NoScrollWithMouse,
NoCollapse = ::ImGuiWindowFlags_NoCollapse,
AlwaysAutoResize = ::ImGuiWindowFlags_AlwaysAutoResize,
NoBackground = ::ImGuiWindowFlags_NoBackground,
NoSavedSettings = ::ImGuiWindowFlags_NoSavedSettings,
NoMouseInputs = ::ImGuiWindowFlags_NoMouseInputs,
MenuBar = ::ImGuiWindowFlags_MenuBar,
HorizontalScrollbar = ::ImGuiWindowFlags_HorizontalScrollbar,
NoFocusOnAppearing = ::ImGuiWindowFlags_NoFocusOnAppearing,
NoBringToFrontOnFocus = ::ImGuiWindowFlags_NoBringToFrontOnFocus,
AlwaysVerticalScrollbar = ::ImGuiWindowFlags_AlwaysVerticalScrollbar,
AlwaysHorizontalScrollbar = ::ImGuiWindowFlags_AlwaysHorizontalScrollbar,
AlwaysUseWindowPadding = ::ImGuiWindowFlags_AlwaysUseWindowPadding,
NoNavInputs = ::ImGuiWindowFlags_NoNavInputs,
NoNavFocus = ::ImGuiWindowFlags_NoNavFocus
};
REGISTER_FLAGS_EX(GuiWindowFlags, 'guiW'); // FourCC = 0x67756957
};
}; // namespace ImGui
}; // namespace chainblocks
| 34.59292 | 80 | 0.718086 | fragcolor-xyz |
6a803adcce9188677525ac3aca370c64bcdc4a90 | 849 | cpp | C++ | data/dailyCodingProblem189.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | 2 | 2020-09-04T20:56:23.000Z | 2021-06-11T07:42:26.000Z | data/dailyCodingProblem189.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | data/dailyCodingProblem189.cpp | vidit1999/daily_coding_problem | b90319cb4ddce11149f54010ba36c4bd6fa0a787 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
using namespace std;
/*
Given an array of elements, return the length of the longest
subarray where all its elements are distinct.
For example, given the array [5, 1, 3, 5, 2, 3, 4, 1],
return 5 as the longest subarray of distinct elements is [5, 2, 3, 4, 1].
*/
int longestSubarrayDistinct(int arr[], int n){
int start = 0, max_len = 0;
unordered_map<int, int> seen;
for(int i=0; i<n; i++){
if(seen.find(arr[i]) != seen.end()){
int last_seen = seen[arr[i]];
if(last_seen >= start){
int length = start - i;
max_len = max(max_len, length);
start = last_seen + 1;
}
}
else{
seen[arr[i]] = i;
}
}
return max_len;
}
// main function
int main(){
int arr[] = {5, 1, 3, 5, 2, 3, 4, 1};
int n = sizeof(arr)/sizeof(arr[0]);
cout << longestSubarrayDistinct(arr, n) << "\n";
return 0;
} | 21.769231 | 73 | 0.613663 | vidit1999 |
6a857de1c3a9b0b7e45629a7174adcf690b737ed | 2,056 | cpp | C++ | win9x/np2arg.cpp | Tatsuya79/NP2kai | ef8c450135f95bb71a463fe7284ce35107df38d7 | [
"MIT"
] | null | null | null | win9x/np2arg.cpp | Tatsuya79/NP2kai | ef8c450135f95bb71a463fe7284ce35107df38d7 | [
"MIT"
] | null | null | null | win9x/np2arg.cpp | Tatsuya79/NP2kai | ef8c450135f95bb71a463fe7284ce35107df38d7 | [
"MIT"
] | null | null | null | /**
* @file np2arg.cpp
* @brief 引数情報クラスの動作の定義を行います
*/
#include "compiler.h"
#include "np2arg.h"
#include "dosio.h"
#define MAXARG 32 //!< 最大引数エントリ数
#define ARG_BASE 1 //!< win32 の lpszCmdLine の場合の開始エントリ
//! 唯一のインスタンスです
Np2Arg Np2Arg::sm_instance;
/**
* コンストラクタ
*/
Np2Arg::Np2Arg()
{
ZeroMemory(this, sizeof(*this));
}
/**
* デストラクタ
*/
Np2Arg::~Np2Arg()
{
free(m_lpArg);
if(m_lpIniFile) free((TCHAR*)m_lpIniFile); // np21w ver0.86 rev8
}
/**
* パース
*/
void Np2Arg::Parse()
{
// 引数読み出し
free(m_lpArg);
m_lpArg = _tcsdup(::GetCommandLine());
LPTSTR argv[MAXARG];
const int argc = ::milstr_getarg(m_lpArg, argv, _countof(argv));
int nDrive = 0;
for (int i = ARG_BASE; i < argc; i++)
{
LPCTSTR lpArg = argv[i];
if ((lpArg[0] == TEXT('/')) || (lpArg[0] == TEXT('-')))
{
switch (_totlower(lpArg[1]))
{
case 'f':
m_fFullscreen = true;
break;
case 'i':
m_lpIniFile = &lpArg[2];
break;
}
}
else
{
LPCTSTR lpExt = ::file_getext(lpArg);
if (::file_cmpname(lpExt, TEXT("ini")) == 0 || ::file_cmpname(lpExt, TEXT("npc")) == 0 || ::file_cmpname(lpExt, TEXT("npcfg")) == 0 || ::file_cmpname(lpExt, TEXT("np2cfg")) == 0 || ::file_cmpname(lpExt, TEXT("np21cfg")) == 0 || ::file_cmpname(lpExt, TEXT("np21wcfg")) == 0)
{
m_lpIniFile = lpArg;
}
else if (nDrive < _countof(m_lpDisk))
{
m_lpDisk[nDrive++] = lpArg;
}
}
}
if(m_lpIniFile){ // np21w ver0.86 rev8
LPTSTR strbuf;
strbuf = (LPTSTR)calloc(500, sizeof(TCHAR));
if(!(_tcsstr(m_lpIniFile,_T(":"))!=NULL || (m_lpIniFile[0]=='\\'))){
// ファイル名のみの指定っぽかったら現在のディレクトリを結合
//getcwd(pathname, 300);
GetCurrentDirectory(500, strbuf);
if(strbuf[_tcslen(strbuf)-1]!='\\'){
_tcscat(strbuf, _T("\\")); // XXX: Linuxとかだったらスラッシュじゃないと駄目だよね?
}
}
_tcscat(strbuf, m_lpIniFile);
m_lpIniFile = strbuf;
}
}
/**
* ディスク情報をクリア
*/
void Np2Arg::ClearDisk()
{
ZeroMemory(m_lpDisk, sizeof(m_lpDisk));
}
| 20.767677 | 277 | 0.574903 | Tatsuya79 |
6a85da5fb4f57431ce5effe082ea022a6b6b5d64 | 192 | hpp | C++ | TeaGameLib/include/InternalGameLib/InternalGameLib.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 11 | 2020-03-08T03:12:38.000Z | 2020-10-30T14:35:39.000Z | TeaGameLib/include/InternalGameLib/InternalGameLib.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 3 | 2020-03-09T06:46:24.000Z | 2020-03-19T11:00:12.000Z | TeaGameLib/include/InternalGameLib/InternalGameLib.hpp | Perukii/TeaGameLibrary | ecf04ce3827cc125523774978a574a095d0ae5c5 | [
"MIT"
] | 1 | 2020-03-19T09:42:45.000Z | 2020-03-19T09:42:45.000Z | #pragma once
#include "../Input/KeyStates.hpp"
#include "../WindowEvent/EventStates.hpp"
namespace teaGameLib {
input::KeyStates GetKeyStates();
windowEvent::EventStates GetEventStates();
} | 24 | 43 | 0.765625 | Perukii |
6a893cfa08fecc79f54d50b783454a0ae24f444d | 5,127 | cpp | C++ | a3/map_metadata_f/Altis/config.cpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | a3/map_metadata_f/Altis/config.cpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | a3/map_metadata_f/Altis/config.cpp | tom4897/a3_map_metadata_f | bcb23baa3b1111629077e2d6b56faa5cd9ccd741 | [
"AAL"
] | null | null | null | #include "CfgPatches.hpp"
#include "..\CfgAreaCategories.inc"
class MAP_METADATA_ROOTCLASS
{
class Altis
{
class Fotia
{
#include "Fotia.hpp"
};
class KavalaPier
{
#include "KavalaPier.hpp"
};
class Kastro
{
#include "Kastro.hpp"
};
class Kavala
{
#include "Kavala.hpp"
};
class Athanos
{
#include "Athanos.hpp"
};
class Aggelochori
{
#include "Aggelochori.hpp"
};
class AgiosKonstantinos
{
#include "AgiosKonstantinos.hpp"
};
class Neri
{
#include "Neri.hpp"
};
class PowerPlant02
{
#include "PowerPlant02.hpp"
};
class quarry01
{
#include "quarry01.hpp"
};
class Oreokastro
{
#include "Oreokastro.hpp"
};
class Negades
{
#include "Negades.hpp"
};
class castle
{
#include "castle.hpp"
};
class Panochori
{
#include "Panochori.hpp"
};
class factory04
{
#include "factory04.hpp"
};
class Stadium
{
#include "Stadium.hpp"
};
class Gori
{
#include "Gori.hpp"
};
class factory03
{
#include "factory03.hpp"
};
class Faros
{
#include "Faros.hpp"
};
class Kore
{
#include "Kore.hpp"
};
class Edessa
{
#include "Edessa.hpp"
};
class Topolia
{
#include "Topolia.hpp"
};
class Aristi
{
#include "Aristi.hpp"
};
class Syrta
{
#include "Syrta.hpp"
};
class AgiosKosmas
{
#include "AgiosKosmas.hpp"
};
class Zaros
{
#include "Zaros.hpp"
};
class XirolimniDam
{
#include "XirolimniDam.hpp"
};
class AgiosDionysios
{
#include "AgiosDionysios.hpp"
};
class Abdera
{
#include "Abdera.hpp"
};
class KryaNera
{
#include "KryaNera.hpp"
};
class Galati
{
#include "Galati.hpp"
};
class Orino
{
#include "Orino.hpp"
};
class Therisa
{
#include "Therisa.hpp"
};
class Drimea
{
#include "Drimea.hpp"
};
class Poliakko
{
#include "Poliakko.hpp"
};
class Alikampos
{
#include "Alikampos.hpp"
};
class AACairfield
{
#include "AACairfield.hpp"
};
class Eginio
{
#include "Eginio.hpp"
};
class Vikos
{
#include "Vikos.hpp"
};
class Katalaki
{
#include "Katalaki.hpp"
};
class Lakka
{
#include "Lakka.hpp"
};
class Neochori
{
#include "Neochori.hpp"
};
class factory02
{
#include "factory02.hpp"
};
class Ifestiona
{
#include "Ifestiona.hpp"
};
class Stavros
{
#include "Stavros.hpp"
};
class Athira
{
#include "Athira.hpp"
};
class airbase01
{
#include "airbase01.hpp"
};
class Gravia
{
#include "Gravia.hpp"
};
class terminal01
{
#include "terminal01.hpp"
};
class Frini
{
#include "Frini.hpp"
};
class Faronaki
{
#include "Faronaki.hpp"
};
class military02
{
#include "military02.hpp"
};
class PowerPlant01
{
#include "PowerPlant01.hpp"
};
class military03
{
#include "military03.hpp"
};
class Telos
{
#include "Telos.hpp"
};
class Anthrakia
{
#include "Anthrakia.hpp"
};
class ChelonisiIsland
{
#include "ChelonisiIsland.hpp"
};
class AgiaTriada
{
#include "AgiaTriada.hpp"
};
class Pyrgos
{
#include "Pyrgos.hpp"
};
class Nychi
{
#include "Nychi.hpp"
};
class quarry02
{
#include "quarry02.hpp"
};
class Kalithea
{
#include "Kalithea.hpp"
};
class Charkia
{
#include "Charkia.hpp"
};
class storage01
{
#include "storage01.hpp"
};
class Livadi
{
#include "Livadi.hpp"
};
class Mine01
{
#include "Mine01.hpp"
};
class Rodopoli
{
#include "Rodopoli.hpp"
};
class Dorida
{
#include "Dorida.hpp"
};
class AgiosPetros
{
#include "AgiosPetros.hpp"
};
class Nifi
{
#include "Nifi.hpp"
};
class quarry03
{
#include "quarry03.hpp"
};
class Chalkeia
{
#include "Chalkeia.hpp"
};
class Panagia
{
#include "Panagia.hpp"
};
class Selakano
{
#include "Selakano.hpp"
};
class Paros
{
#include "Paros.hpp"
};
class SufrClub
{
#include "SufrClub.hpp"
};
class Kalochori
{
#include "Kalochori.hpp"
};
class Aktinarki
{
#include "Aktinarki.hpp"
};
class Iraklia
{
#include "Iraklia.hpp"
};
class Feres
{
#include "Feres.hpp"
};
class Trachia
{
#include "Trachia.hpp"
};
class AgiaPelagia
{
#include "AgiaPelagia.hpp"
};
class CapKategidis
{
#include "CapKategidis.hpp"
};
class Ioannina
{
#include "Ioannina.hpp"
};
class Sideras
{
#include "Sideras.hpp"
};
class Nidasos
{
#include "Nidasos.hpp"
};
class Delfinaki
{
#include "Delfinaki.hpp"
};
class CapThelos
{
#include "CapThelos.hpp"
};
class Sofia
{
#include "Sofia.hpp"
};
class Limnichori
{
#include "Limnichori.hpp"
};
class Gatolia
{
#include "Gatolia.hpp"
};
class MolosAirfield
{
#include "MolosAirfield.hpp"
};
class Molos
{
#include "Molos.hpp"
};
class Polemistia
{
#include "Polemistia.hpp"
};
class CapStrigla
{
#include "CapStrigla.hpp"
};
};
};
| 13.179949 | 35 | 0.586113 | tom4897 |
6a89b95f2bc2cb559c90d7f33a033c182a99d24e | 3,430 | cpp | C++ | leetcode/docu/522.cpp | sczzq/symmetrical-spoon | aa0c27bb40a482789c7c6a7088307320a007b49b | [
"Unlicense"
] | null | null | null | leetcode/docu/522.cpp | sczzq/symmetrical-spoon | aa0c27bb40a482789c7c6a7088307320a007b49b | [
"Unlicense"
] | null | null | null | leetcode/docu/522.cpp | sczzq/symmetrical-spoon | aa0c27bb40a482789c7c6a7088307320a007b49b | [
"Unlicense"
] | null | null | null | #include "cpp_header.h"
class Solution
{
struct customGreater1 {
bool operator()(const string & a, const string & b) const
{
return a.length() > b.length();
}
} ;
struct {
bool operator()(const string & a, const string & b) const
{
return a.length() > b.length();
}
} customGreater2;
public:
int findLUSlength(vector<string> strs)
{
int res = -1;
if(strs.size() > 0)
{
sort(strs.begin(), strs.end(), customGreater2); // nlgn
unordered_map<string, int> str_count;
for(auto & s : strs)
{
str_count[s]++;
}
auto last = unique(strs.begin(), strs.end()); // n
strs.erase(last, strs.end());
/*
cout << "--------------------------\n";
for(auto x : str_count)
{
cout << x.first << ", " << x.second << "\n";
}
cout << "--------------------------\n";
*/
for(auto it = strs.begin(); it != strs.end(); it++)
{
if(str_count[*it] == 1)
{
bool is_solo = true;
for(auto it2 = strs.begin(); it2 != it; it2++)
{
if(is_contained(*it, *it2))
{
is_solo = false;
break;
}
}
if(is_solo)
{
res = it->length();
break;
}
}
}
}
return res;
}
// time: O(n)
// memory: O(1)
bool is_contained(const string & s1, const string & s2)
{
int m = 0, n = 0;
bool res = false;
while( m < s1.length() && n < s2.length() )
{
if(s1[m] != s2[n])
{
n++;
}
else
{
m++;
n++;
}
}
if(m == s1.length())
{
res = true;
}
return res;
}
};
bool testcase(vector<string> strs, int res, int casenum)
{
Solution sol;
if( sol.findLUSlength(strs) == res )
{
cout << casenum << " pass\n";
}
else
{
cout << casenum << " no pass\n";
cout << "detail:\n";
for(auto & s : strs)
{
cout << s << "-- ";
}
cout << "\n";
}
cout << "-----------------------------------------\n";
}
int main()
{
vector<pair<vector<string>, int>> cases;
vector<string> strs;
strs = {"abc", "abd", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "ab", "bc", "abc", "b", "c", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "ab", "bc", "abc", "b", "c", "bcd", "abc", "bcd"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "bcd"};
cases.push_back(make_pair(strs, 3));
strs = {"a", "a", "a", "a", "a"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "a", "v", "v", "v"};
cases.push_back(make_pair(strs, -1));
strs = {"a", "a", "b", "v", "v"};
cases.push_back(make_pair(strs, 1));
strs = {"aaa", "aaa", "ba", "va", "vaaaaaaaaaaaaaaaaaaaa"};
cases.push_back(make_pair(strs, 21));
strs = {"aaa", "aaa", "ba", "va", "vaaaa", "vaaaa", "ab"};
cases.push_back(make_pair(strs, 2));
strs = {"", ""};
cases.push_back(make_pair(strs, -1));
strs = {"a", "", ""};
cases.push_back(make_pair(strs, 1));
strs = {"aa", "ab"};
cases.push_back(make_pair(strs, 2));
int num = 1;
for(auto & x : cases)
{
testcase(x.first, x.second, num);
num++;
}
/*
strs = {"a", "b", "c", "d", "e",
"ab", "ac", "ad", "ae", "bc", "bd", "be", "cd", "ce",
"ba", "ca", "da", "ea", "cb", "db", "eb", "dc", "ec",
"abc", "abd", "abe", "acd", "ace", "ade",
"acb", "adb", "aeb", "adc", "aec", "aed",
"bca", "bad", "bae", "cad", "cae", "dae",
"bac", "bda", "bea",
"cab", "dab", "eab",
"cba", "dba", "eba",
"abcd", "abce", "aced",
"abcde", "abcde"
};
testcase(strs, -1, 3);
*/
}
| 18.148148 | 64 | 0.481633 | sczzq |
6a90bf634e7d7df76f2056a146085b940571809b | 1,075 | hpp | C++ | include/das.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | 5 | 2021-01-02T19:06:37.000Z | 2022-03-11T23:56:03.000Z | include/das.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | null | null | null | include/das.hpp | rosskidson/nestris_x86 | ce5085436ff2c04f8f760c2d88469f77794dd6c3 | [
"MIT"
] | null | null | null | #pragma once
namespace nestris_x86 {
class Das {
public:
constexpr static int NTSC_FULL_CHARGE = 16;
constexpr static int NTSC_MIN_CHARGE = 10;
constexpr static int PAL_FULL_CHARGE = 12;
constexpr static int PAL_MIN_CHARGE = 8;
Das(const int das_full_charge, const int das_min_charge)
: das_full_charge_{das_full_charge}, das_min_charge_{das_min_charge} {}
inline void fullyChargeDas(int& das_counter) const { das_counter = das_full_charge_; }
inline void softResetDas(int& das_counter) const { das_counter = das_min_charge_; }
inline void hardResetDas(int& das_counter) const { das_counter = 0; }
inline bool dasFullyCharged(const int das_counter) const {
return das_counter >= das_full_charge_;
}
inline bool dasSoftlyCharged(const int das_counter) const {
return das_counter >= das_min_charge_;
}
inline int getFullDasChargeCount() const { return das_full_charge_; }
inline int getMinDasChargeCount() const { return das_min_charge_; }
private:
int das_full_charge_;
int das_min_charge_;
};
} // namespace nestris_x86
| 32.575758 | 88 | 0.763721 | rosskidson |
6a916445e96ae6271d525d688afe1d842b843903 | 893 | cpp | C++ | Sources/SolarTears/Core/Scene/SceneObjectLocation.cpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | 4 | 2021-06-30T16:00:20.000Z | 2021-10-13T06:17:56.000Z | Sources/SolarTears/Core/Scene/SceneObjectLocation.cpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | Sources/SolarTears/Core/Scene/SceneObjectLocation.cpp | Sixshaman/SolarTears | 97d07730f876508fce8bf93c9dc90f051c230580 | [
"BSD-3-Clause"
] | null | null | null | #include "SceneObjectLocation.hpp"
#include "../Math/QuaternionUtils.hpp"
void SceneObjectLocation::SetPrincipalRight(DirectX::XMVECTOR right)
{
DirectX::XMVECTOR defaultRight = DirectX::XMVectorSet(1.0f, 0.0f, 0.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultRight, right));
}
void SceneObjectLocation::SetPrincipalUp(DirectX::XMVECTOR newUpNrm)
{
DirectX::XMVECTOR defaultUp = DirectX::XMVectorSet(0.0f, 1.0f, 0.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultUp, newUpNrm));
}
void SceneObjectLocation::SetPrincipalForward(DirectX::XMVECTOR newForwardNrm)
{
DirectX::XMVECTOR defaultForward = DirectX::XMVectorSet(0.0f, 0.0f, 1.0f, 0.0f);
DirectX::XMStoreFloat4(&RotationQuaternion, Utils::QuaternionBetweenTwoVectorsNormalized(defaultForward, newForwardNrm));
} | 44.65 | 122 | 0.805151 | Sixshaman |
6a91d8d047e690a02d7a7a727a2b3bf6e57b9a49 | 6,581 | cpp | C++ | src/Win32ThreadSupport.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | src/Win32ThreadSupport.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | src/Win32ThreadSupport.cpp | yoshinoToylogic/bulletsharp | 79558f9e78b68f1d218d64234645848661a54e01 | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#ifndef DISABLE_MULTITHREADED
#include "StringConv.h"
#include "Win32ThreadSupport.h"
MultiThreaded::Win32ThreadConstructionInfo::~Win32ThreadConstructionInfo()
{
this->!Win32ThreadConstructionInfo();
}
MultiThreaded::Win32ThreadConstructionInfo::!Win32ThreadConstructionInfo()
{
if (_native) {
StringConv::FreeUnmanagedString(_uniqueName);
delete _native;
_native = NULL;
}
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc, int numThreads,
int threadStackSize)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc, numThreads, threadStackSize);
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc, int numThreads)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc, numThreads);
}
MultiThreaded::Win32ThreadConstructionInfo::Win32ThreadConstructionInfo(String^ uniqueName,
BulletSharp::Win32ThreadFunc userThreadFunc, BulletSharp::Win32LSMemorySetupFunc lsMemoryFunc)
{
_uniqueName = StringConv::ManagedToUnmanaged(uniqueName);
::Win32ThreadFunc threadFunc;
::Win32lsMemorySetupFunc memorySetupFunc;
if (userThreadFunc == Win32ThreadFunc::ProcessCollisionTask) {
threadFunc = processCollisionTask;
} else if (userThreadFunc == Win32ThreadFunc::SolverThreadFunc) {
threadFunc = SolverThreadFunc;
} else {
throw gcnew NotImplementedException();
}
if (lsMemoryFunc == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
memorySetupFunc = createCollisionLocalStoreMemory;
} else if (lsMemoryFunc == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
memorySetupFunc = SolverlsMemoryFunc;
} else {
throw gcnew NotImplementedException();
}
_native = new ::Win32ThreadSupport::Win32ThreadConstructionInfo((char*)_uniqueName,
threadFunc, memorySetupFunc);
}
BulletSharp::Win32LSMemorySetupFunc MultiThreaded::Win32ThreadConstructionInfo::LSMemorySetupFunc::get()
{
if (_native->m_lsMemoryFunc == createCollisionLocalStoreMemory) {
return Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory;
} else if (_native->m_lsMemoryFunc == SolverlsMemoryFunc) {
return Win32LSMemorySetupFunc::SolverLSMemoryFunc;
}
throw gcnew NotImplementedException();
}
void MultiThreaded::Win32ThreadConstructionInfo::LSMemorySetupFunc::set(BulletSharp::Win32LSMemorySetupFunc value)
{
if (value == Win32LSMemorySetupFunc::CreateCollisionLocalStoreMemory) {
_native->m_lsMemoryFunc = createCollisionLocalStoreMemory;
} else if (value == Win32LSMemorySetupFunc::SolverLSMemoryFunc) {
_native->m_lsMemoryFunc = SolverlsMemoryFunc;
}
}
int MultiThreaded::Win32ThreadConstructionInfo::NumThreads::get()
{
return _native->m_numThreads;
}
void MultiThreaded::Win32ThreadConstructionInfo::NumThreads::set(int value)
{
_native->m_numThreads = value;
}
int MultiThreaded::Win32ThreadConstructionInfo::ThreadStackSize::get()
{
return _native->m_threadStackSize;
}
void MultiThreaded::Win32ThreadConstructionInfo::ThreadStackSize::set(int value)
{
_native->m_threadStackSize = value;
}
String^ MultiThreaded::Win32ThreadConstructionInfo::UniqueName::get()
{
return StringConv::UnmanagedToManaged(_native->m_uniqueName);
}
void MultiThreaded::Win32ThreadConstructionInfo::UniqueName::set(String^ value)
{
StringConv::FreeUnmanagedString(_uniqueName);
_uniqueName = StringConv::ManagedToUnmanaged(value);
}
BulletSharp::Win32ThreadFunc MultiThreaded::Win32ThreadConstructionInfo::UserThreadFunc::get()
{
if (_native->m_userThreadFunc == processCollisionTask) {
return Win32ThreadFunc::ProcessCollisionTask;
} else if (_native->m_userThreadFunc == SolverThreadFunc) {
return Win32ThreadFunc::SolverThreadFunc;
}
throw gcnew NotImplementedException();
}
void MultiThreaded::Win32ThreadConstructionInfo::UserThreadFunc::set(BulletSharp::Win32ThreadFunc value)
{
if (value == Win32ThreadFunc::ProcessCollisionTask) {
_native->m_userThreadFunc = processCollisionTask;
} else if (value == Win32ThreadFunc::SolverThreadFunc) {
_native->m_userThreadFunc = SolverThreadFunc;
}
}
#define Native static_cast<::Win32ThreadSupport*>(_native)
MultiThreaded::Win32ThreadSupport::Win32ThreadSupport(Win32ThreadConstructionInfo^ threadConstructionInfo)
: ThreadSupportInterface(new ::Win32ThreadSupport(*threadConstructionInfo->_native))
{
}
/*
bool MultiThreaded::Win32ThreadSupport::IsTaskCompleted(unsigned int^ puiArgument0, unsigned int^ puiArgument1,
int timeOutInMilliseconds)
{
return Native->isTaskCompleted(puiArgument0->_native, puiArgument1->_native, timeOutInMilliseconds);
}
*/
void MultiThreaded::Win32ThreadSupport::StartThreads(Win32ThreadConstructionInfo^ threadInfo)
{
Native->startThreads(*threadInfo->_native);
}
#endif
| 35.005319 | 115 | 0.787114 | yoshinoToylogic |
6a93553c23bd705a101085f190f72efa0c6db371 | 7,143 | cpp | C++ | TabGraph/src/Light/SkyLight.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-08-28T09:35:18.000Z | 2020-08-28T09:35:18.000Z | TabGraph/src/Light/SkyLight.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | null | null | null | TabGraph/src/Light/SkyLight.cpp | Gpinchon/TabGraph | 29eae2d9982b6ce3e4ff43c707c87c2f57ab39bb | [
"Apache-2.0"
] | 1 | 2020-10-08T11:21:13.000Z | 2020-10-08T11:21:13.000Z | /*
* @Author: gpinchon
* @Date: 2021-03-12 16:08:58
* @Last Modified by: gpinchon
* @Last Modified time: 2021-05-18 18:26:25
*/
#include <Camera/Camera.hpp>
#include <Light/SkyLight.hpp>
#include <Renderer/Renderer.hpp>
#include <Renderer/Surface/GeometryRenderer.hpp>
#include <Scene/Scene.hpp>
#include <Shader/Program.hpp>
#include <SphericalHarmonics.hpp>
#include <Surface/CubeMesh.hpp>
#include <Surface/Geometry.hpp>
#include <Texture/Texture2D.hpp>
#include <Texture/TextureCubemap.hpp>
#if RENDERINGAPI == OpenGL
#include <Driver/OpenGL/Renderer/Light/SkyLightRenderer.hpp>
#endif
#define num_samples 16
#define num_samples_light 8
/// \private
struct ray_t {
glm::vec3 origin;
glm::vec3 direction;
};
/// \private
struct sphere_t {
glm::vec3 origin;
float radius;
};
bool isect_sphere(const ray_t ray, const sphere_t sphere, float& t0, float& t1)
{
glm::vec3 rc = sphere.origin - ray.origin;
float radius2 = sphere.radius * sphere.radius;
float tca = dot(rc, ray.direction);
float d2 = dot(rc, rc) - tca * tca;
if (d2 > radius2)
return false;
float thc = sqrt(radius2 - d2);
t0 = tca - thc;
t1 = tca + thc;
return true;
}
float rayleigh_phase_func(float mu)
{
return 3. * (1. + mu * mu)
/ //------------------------
(16. * M_PI);
}
float henyey_greenstein_phase_func(float mu)
{
const float g = 0.76;
return (1. - g * g)
/ //---------------------------------------------
((4. * M_PI) * pow(1. + g * g - 2. * g * mu, 1.5));
}
bool get_sun_light(const ray_t& ray, float& optical_depthR, float& optical_depthM, const SkyLight& sky)
{
float t0, t1;
const sphere_t atmosphere = sphere_t {
glm::vec3(0, 0, 0), sky.GetAtmosphereRadius()
};
isect_sphere(ray, atmosphere, t0, t1);
float march_pos = 0.;
float march_step = t1 / float(num_samples_light);
for (int i = 0; i < num_samples_light; i++) {
glm::vec3 s = ray.origin + ray.direction * float(march_pos + 0.5 * march_step);
float height = length(s) - sky.GetPlanetRadius();
if (height < 0.)
return false;
optical_depthR += exp(-height / sky.GetHRayleigh()) * march_step;
optical_depthM += exp(-height / sky.GetHMie()) * march_step;
march_pos += march_step;
}
return true;
}
static inline glm::vec3 GetIncidentLight(ray_t ray, const SkyLight& sky)
{
const sphere_t atmosphere = sphere_t {
glm::vec3(0, 0, 0), sky.GetAtmosphereRadius()
};
// "pierce" the atmosphere with the viewing ray
float t0, t1;
if (!isect_sphere(
ray, atmosphere, t0, t1)) {
return glm::vec3(0);
}
float march_step = t1 / float(num_samples);
// cosine of angle between view and light directions
float mu = glm::dot(ray.direction, sky.GetSunDirection());
// Rayleigh and Mie phase functions
// A black box indicating how light is interacting with the material
// Similar to BRDF except
// * it usually considers a single angle
// (the phase angle between 2 directions)
// * integrates to 1 over the entire sphere of directions
float phaseR = rayleigh_phase_func(mu);
float phaseM = henyey_greenstein_phase_func(mu);
// optical depth (or "average density")
// represents the accumulated extinction coefficients
// along the path, multiplied by the length of that path
float optical_depthR = 0.;
float optical_depthM = 0.;
glm::vec3 sumR = glm::vec3(0);
glm::vec3 sumM = glm::vec3(0);
float march_pos = 0.;
for (int i = 0; i < num_samples; i++) {
glm::vec3 s = ray.origin + ray.direction * float(march_pos + 0.5 * march_step);
float height = glm::length(s) - sky.GetPlanetRadius();
// integrate the height scale
float hr = exp(-height / sky.GetHRayleigh()) * march_step;
float hm = exp(-height / sky.GetHMie()) * march_step;
optical_depthR += hr;
optical_depthM += hm;
// gather the sunlight
ray_t light_ray {
s,
sky.GetSunDirection()
};
float optical_depth_lightR = 0.;
float optical_depth_lightM = 0.;
bool overground = get_sun_light(
light_ray,
optical_depth_lightR,
optical_depth_lightM,
sky);
if (overground) {
glm::vec3 tau = sky.GetBetaRayleigh() * (optical_depthR + optical_depth_lightR) + sky.GetBetaMie() * 1.1f * (optical_depthM + optical_depth_lightM);
glm::vec3 attenuation = exp(-tau);
sumR += hr * attenuation;
sumM += hm * attenuation;
}
march_pos += march_step;
}
return sky.GetSunPower() * (sumR * phaseR * sky.GetBetaRayleigh() + sumM * phaseM * sky.GetBetaMie());
}
SkyLight::SkyLight()
: DirectionalLight()
{
}
glm::vec3 SkyLight::GetSunDirection() const
{
return GetDirection();
}
void SkyLight::SetSunDirection(const glm::vec3& sunDir)
{
if (sunDir != GetSunDirection())
GetRenderer().FlagDirty();
SetDirection(sunDir);
}
float SkyLight::GetSunPower() const
{
return _sunPower;
}
void SkyLight::SetSunPower(const float sunPower)
{
if (sunPower != _sunPower)
GetRenderer().FlagDirty();
_sunPower = sunPower;
}
float SkyLight::GetPlanetRadius() const
{
return _planetRadius;
}
void SkyLight::SetPlanetRadius(float planetRadius)
{
if (planetRadius != _planetRadius)
GetRenderer().FlagDirty();
_planetRadius = planetRadius;
}
float SkyLight::GetAtmosphereRadius() const
{
return _atmosphereRadius;
}
void SkyLight::SetAtmosphereRadius(float atmosphereRadius)
{
if (atmosphereRadius != _atmosphereRadius)
GetRenderer().FlagDirty();
_atmosphereRadius = atmosphereRadius;
}
float SkyLight::GetHRayleigh() const
{
return _hRayleigh;
}
void SkyLight::SetHRayleigh(float hRayleigh)
{
if (hRayleigh != _hRayleigh)
GetRenderer().FlagDirty();
_hRayleigh = hRayleigh;
}
float SkyLight::GetHMie() const
{
return _hMie;
}
void SkyLight::SetHMie(float hMie)
{
if (hMie != _hMie)
GetRenderer().FlagDirty();
_hMie = hMie;
}
glm::vec3 SkyLight::GetBetaRayleigh() const
{
return _betaRayleigh;
}
void SkyLight::SetBetaRayleigh(glm::vec3 betaRayleigh)
{
if (betaRayleigh != _betaRayleigh)
GetRenderer().FlagDirty();
_betaRayleigh = betaRayleigh;
}
glm::vec3 SkyLight::GetBetaMie() const
{
return _betaMie;
}
void SkyLight::SetBetaMie(glm::vec3 betaMie)
{
if (betaMie != _betaMie)
GetRenderer().FlagDirty();
_betaMie = betaMie;
}
glm::vec3 SkyLight::GetIncidentLight(glm::vec3 direction) const
{
return ::GetIncidentLight({ glm::vec3(0, GetPlanetRadius() + 1, 0),
direction },
*this);
}
| 25.974545 | 161 | 0.607168 | Gpinchon |
6aa296e4271acaefa4e99d245bd535a646560041 | 435 | tpp | C++ | BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-016.tpp | hmarcuzzo/compiler_project | 2463d19c2b81ba28a943974828e8bb5954424cac | [
"Apache-2.0"
] | null | null | null | BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-016.tpp | hmarcuzzo/compiler_project | 2463d19c2b81ba28a943974828e8bb5954424cac | [
"Apache-2.0"
] | null | null | null | BCC__BCC36B__P[3]__HenriqueMarcuzzo_2046334/impl/semantica-testes/sema-016.tpp | hmarcuzzo/compiler_project | 2463d19c2b81ba28a943974828e8bb5954424cac | [
"Apache-2.0"
] | 4 | 2020-12-11T10:12:37.000Z | 2021-11-01T18:34:25.000Z | {Aviso: Coerção implícita do valor atribuído para 'a', variável a flutuante recebendo um inteiro}
{Erro: Função 'func' do tipo inteiro retornando flutuante}
{Aviso: Função 'func' declarada, mas não utilizada}
{Aviso: Chamada recursiva para a função 'principal'}
{Erro: Função 'principal' deveria retornar inteiro, mas retorna vazio}
flutuante: a
inteiro: b
inteiro func()
a := 10
retorna(a)
fim
inteiro principal()
b := 18
fim
| 24.166667 | 97 | 0.747126 | hmarcuzzo |
6aa4f512a2df7f5a1d78bc65cba5f0ef68794edc | 3,736 | cpp | C++ | modules/ocl/perf/perf_surf.cpp | emaknyus/OpenCV-2.4.3-custom | a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7 | [
"MIT"
] | null | null | null | modules/ocl/perf/perf_surf.cpp | emaknyus/OpenCV-2.4.3-custom | a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7 | [
"MIT"
] | null | null | null | modules/ocl/perf/perf_surf.cpp | emaknyus/OpenCV-2.4.3-custom | a0e0cd505560dcc0f13cb7ea4c5506e0251a21e7 | [
"MIT"
] | null | null | null | /*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2010-2012, Multicoreware, Inc., all rights reserved.
// Copyright (C) 2010-2012, Advanced Micro Devices, Inc., all rights reserved.
// Third party copyrights are property of their respective owners.
//
// @Authors
// Peng Xiao, pengxiao@multicorewareinc.com
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other oclMaterials provided with the distribution.
//
// * The name of the copyright holders may not 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 Intel Corporation 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.
//
//M*/
#include "precomp.hpp"
#include <iomanip>
#ifdef HAVE_OPENCL
using namespace cv;
using namespace cv::ocl;
using namespace cvtest;
using namespace testing;
using namespace std;
#define FILTER_IMAGE "../../../samples/gpu/road.png"
TEST(SURF, Performance)
{
cv::Mat img = readImage(FILTER_IMAGE, cv::IMREAD_GRAYSCALE);
ASSERT_FALSE(img.empty());
ocl::SURF_OCL d_surf;
ocl::oclMat d_keypoints;
ocl::oclMat d_descriptors;
double totalgputick = 0;
double totalgputick_kernel = 0;
double t1 = 0;
double t2 = 0;
for(int j = 0; j < LOOP_TIMES + 1; j ++)
{
t1 = (double)cvGetTickCount();//gpu start1
ocl::oclMat d_src(img);//upload
t2 = (double)cvGetTickCount(); //kernel
d_surf(d_src, ocl::oclMat(), d_keypoints, d_descriptors);
t2 = (double)cvGetTickCount() - t2;//kernel
cv::Mat cpu_kp, cpu_dp;
d_keypoints.download (cpu_kp);//download
d_descriptors.download (cpu_dp);//download
t1 = (double)cvGetTickCount() - t1;//gpu end1
if(j == 0)
continue;
totalgputick = t1 + totalgputick;
totalgputick_kernel = t2 + totalgputick_kernel;
}
cout << "average gpu runtime is " << totalgputick / ((double)cvGetTickFrequency()* LOOP_TIMES * 1000.) << "ms" << endl;
cout << "average gpu runtime without data transfer is " << totalgputick_kernel / ((double)cvGetTickFrequency()* LOOP_TIMES * 1000.) << "ms" << endl;
}
#endif //Have opencl | 36.271845 | 153 | 0.680139 | emaknyus |
6aa999e2ff00bd03bc8497fcf6b10f6459ac8c43 | 2,574 | cpp | C++ | src/prod/src/Management/ClusterManager/StoreDataComposeDeploymentInstanceCounter.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | 1 | 2018-03-15T02:09:21.000Z | 2018-03-15T02:09:21.000Z | src/prod/src/Management/ClusterManager/StoreDataComposeDeploymentInstanceCounter.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | src/prod/src/Management/ClusterManager/StoreDataComposeDeploymentInstanceCounter.cpp | AnthonyM/service-fabric | c396ea918714ea52eab9c94fd62e018cc2e09a68 | [
"MIT"
] | null | null | null | // ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
#include "stdafx.h"
using namespace Common;
using namespace Store;
using namespace std;
using namespace Management::ClusterManager;
StoreDataComposeDeploymentInstanceCounter::StoreDataComposeDeploymentInstanceCounter()
: StoreData()
, value_(0)
{
}
wstring const & StoreDataComposeDeploymentInstanceCounter::get_Type() const
{
return Constants::StoreType_ComposeDeploymentInstanceCounter;
}
wstring StoreDataComposeDeploymentInstanceCounter::ConstructKey() const
{
return Constants::StoreKey_ComposeDeploymentInstanceCounter;
}
void StoreDataComposeDeploymentInstanceCounter::WriteTo(Common::TextWriter & w, Common::FormatOptions const &) const
{
w.Write("ComposeDeploymentInstanceCounter[{0}]", value_);
}
ErrorCode StoreDataComposeDeploymentInstanceCounter::GetTypeNameAndVersion(
StoreTransaction const &storeTx,
__out ServiceModelTypeName &typeName,
__out ServiceModelVersion &version)
{
// refresh the latest version from store.
ErrorCode error = storeTx.ReadExact(*this);
if (error.IsSuccess())
{
++value_;
error = storeTx.Update(*this);
}
else if (error.IsError(ErrorCodeValue::NotFound))
{
value_ = 0;
error = storeTx.Insert(*this);
}
if (error.IsSuccess())
{
//
// Application type name is used as a part of the directory name for the package, so using a sequence number to limit the length of
// name.
//
typeName = ServiceModelTypeName(wformatString("{0}{1}", *Constants::ComposeDeploymentTypePrefix, this->Value));
version = StoreDataComposeDeploymentInstanceCounter::GenerateServiceModelVersion(this->Value);
}
return error;
}
ErrorCode StoreDataComposeDeploymentInstanceCounter::GetVersionNumber(ServiceModelVersion const &version, uint64 *versionNumber)
{
auto versionString = version.Value;
StringUtility::TrimLeading<wstring>(versionString, L"v");
if (!StringUtility::TryFromWString(versionString, *versionNumber))
{
return ErrorCodeValue::NotFound;
}
return ErrorCodeValue::Success;
}
ServiceModelVersion StoreDataComposeDeploymentInstanceCounter::GenerateServiceModelVersion(uint64 number)
{
return ServiceModelVersion(wformatString("v{0}", number));
}
| 29.930233 | 139 | 0.703186 | AnthonyM |
6aaa42ef431f5ec2d9fe5c251b78b3e27f40ee0d | 885 | hpp | C++ | presets/Particle/RectangularParticle.hpp | emirroner/MiniParticle | ece0c4d38f978530aba4a0eb382e0b8f07be4748 | [
"MIT"
] | null | null | null | presets/Particle/RectangularParticle.hpp | emirroner/MiniParticle | ece0c4d38f978530aba4a0eb382e0b8f07be4748 | [
"MIT"
] | null | null | null | presets/Particle/RectangularParticle.hpp | emirroner/MiniParticle | ece0c4d38f978530aba4a0eb382e0b8f07be4748 | [
"MIT"
] | 1 | 2021-01-05T14:02:56.000Z | 2021-01-05T14:02:56.000Z | #ifndef RECTANGULAR_PARTICLE_HPP
#define RECTANGULAR_PARTICLE_HPP
#include <SFML\Graphics.hpp>
#include "..\..\include\MiniParticle.hpp"
class RectangularParticle : public MiniParticle
{
public:
RectangularParticle();
RectangularParticle(sf::Vector2f pos,sf::Vector2f velocity,sf::Color color,sf::Vector2f size,float lifeTime,bool resize,float gravity,float rotationSpeed,unsigned short ID = 0);
void update(float elapsed,float deltaTime);
const sf::Vector2f& getSize() const;
sf::Color getColor() const;
const sf::Vector2f& getStartSize() const;
float getRotation() const;
float getStartLifeTime() const;
void setSize(sf::Vector2f size);
void setColor(sf::Color color);
private:
sf::Vector2f m_size, m_startSize;
float m_rotationSpeed, m_rotation;
float m_startLifeTime;
bool m_resize;
float m_gravity;
sf::Color m_color;
};
#endif // RECTANGULAR_PARTICLE_HPP
| 25.285714 | 178 | 0.776271 | emirroner |
6aaa4ed24b3a53cc7e35a954c2d5af11a60ca9fb | 308 | cpp | C++ | 03-SDU_Exam_Algorithm_Question/2006/2006-T01_Class_Declaration.cpp | ysl970629/kaoyan_data_structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | 2 | 2021-03-24T03:29:16.000Z | 2022-03-29T16:34:30.000Z | 03-SDU_Exam_Algorithm_Question/2006/2006-T01_Class_Declaration.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | 03-SDU_Exam_Algorithm_Question/2006/2006-T01_Class_Declaration.cpp | ysl2/kaoyan-data-structure | d0a469bf0e9e7040de21eca38dc19961aa7e9a53 | [
"MIT"
] | null | null | null | template <class T>
class BinaryTreeNode {
public:
BinaryTreeNode(const T &e, BinaryTreeNode *lchild, BinaryTreeNode *rchild) {
data = e;
BinaryTreeNode::lchild = lchild;
BinaryTreeNode::rchild = rchild;
}
private:
T data;
BinaryTreeNode<T> *lchild, *rchild;
};
| 22 | 80 | 0.636364 | ysl970629 |
6ab2c7e1f8b312f12e618cc550e47ffd48921505 | 6,504 | hpp | C++ | src/api/crypto.hpp | zengyuxing007/pipy | c60e08560b08728fa181940a4b9d67807a0ee625 | [
"BSL-1.0"
] | null | null | null | src/api/crypto.hpp | zengyuxing007/pipy | c60e08560b08728fa181940a4b9d67807a0ee625 | [
"BSL-1.0"
] | null | null | null | src/api/crypto.hpp | zengyuxing007/pipy | c60e08560b08728fa181940a4b9d67807a0ee625 | [
"BSL-1.0"
] | null | null | null | /*
* Copyright (c) 2019 by flomesh.io
*
* Unless prior written consent has been obtained from the copyright
* owner, the following shall not be allowed.
*
* 1. The distribution of any source codes, header files, make files,
* or libraries of the software.
*
* 2. Disclosure of any source codes pertaining to the software to any
* additional parties.
*
* 3. Alteration or removal of any notices in or on the software or
* within the documentation included within the software.
*
* ALL SOURCE CODE AS WELL AS ALL DOCUMENTATION INCLUDED WITH THIS
* SOFTWARE IS PROVIDED IN AN “AS IS” CONDITION, 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 CRYPTO_HPP
#define CRYPTO_HPP
#include "pjs/pjs.hpp"
#include "data.hpp"
#include <openssl/evp.h>
namespace pipy {
namespace crypto {
//
// AliasType
//
enum class AliasType {
sm2,
};
//
// PublicKey
//
class PublicKey : public pjs::ObjectTemplate<PublicKey> {
public:
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
PublicKey(Data *data, pjs::Object *options);
PublicKey(pjs::Str *data, pjs::Object *options);
~PublicKey();
EVP_PKEY* m_pkey = nullptr;
static auto read_pem(const void *data, size_t size) -> EVP_PKEY*;
friend class pjs::ObjectTemplate<PublicKey>;
};
//
// PrivateKey
//
class PrivateKey : public pjs::ObjectTemplate<PrivateKey> {
public:
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
PrivateKey(Data *data, pjs::Object *options);
PrivateKey(pjs::Str *data, pjs::Object *options);
~PrivateKey();
EVP_PKEY* m_pkey = nullptr;
static auto read_pem(const void *data, size_t size) -> EVP_PKEY*;
friend class pjs::ObjectTemplate<PrivateKey>;
};
//
// Cipher
//
class Cipher : public pjs::ObjectTemplate<Cipher> {
public:
enum class Algorithm {
sm4_cbc,
sm4_ecb,
sm4_cfb,
sm4_cfb128,
sm4_ofb,
sm4_ctr,
};
static auto cipher(Algorithm algorithm) -> const EVP_CIPHER*;
auto update(Data *data) -> Data*;
auto update(pjs::Str *str) -> Data*;
auto final() -> Data*;
private:
Cipher(Algorithm algorithm, pjs::Object *options);
~Cipher();
EVP_CIPHER_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Cipher>;
};
//
// Decipher
//
class Decipher : public pjs::ObjectTemplate<Decipher> {
public:
auto update(Data *data) -> Data*;
auto update(pjs::Str *str) -> Data*;
auto final() -> Data*;
private:
Decipher(Cipher::Algorithm algorithm, pjs::Object *options);
~Decipher();
EVP_CIPHER_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Decipher>;
};
//
// Hash
//
class Hash : public pjs::ObjectTemplate<Hash> {
public:
enum class Algorithm {
md4,
md5,
md5_sha1,
blake2b512,
blake2s256,
sha1,
sha224,
sha256,
sha384,
sha512,
sha512_224,
sha512_256,
sha3_224,
sha3_256,
sha3_384,
sha3_512,
shake128,
shake256,
mdc2,
ripemd160,
whirlpool,
sm3,
};
static auto digest(Algorithm algorithm) -> const EVP_MD*;
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto digest() -> Data*;
auto digest(Data::Encoding enc) -> pjs::Str*;
private:
Hash(Algorithm algorithm);
~Hash();
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Hash>;
};
//
// Hmac
//
class Hmac : public pjs::ObjectTemplate<Hmac> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto digest() -> Data*;
auto digest(Data::Encoding enc) -> pjs::Str*;
private:
Hmac(Hash::Algorithm algorithm, Data *key);
Hmac(Hash::Algorithm algorithm, pjs::Str *key);
~Hmac();
HMAC_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Hmac>;
};
//
// Sign
//
class Sign : public pjs::ObjectTemplate<Sign> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
auto sign(PrivateKey *key, Object *options = nullptr) -> Data*;
auto sign(PrivateKey *key, Data::Encoding enc, Object *options = nullptr) -> pjs::Str*;
private:
Sign(Hash::Algorithm algorithm);
~Sign();
const EVP_MD* m_md = nullptr;
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Sign>;
};
//
// Verify
//
class Verify : public pjs::ObjectTemplate<Verify> {
public:
void update(Data *data);
void update(pjs::Str *str, Data::Encoding enc);
bool verify(PublicKey *key, Data *signature, Object *options = nullptr);
bool verify(PublicKey *key, pjs::Str *signature, Data::Encoding enc, Object *options = nullptr);
private:
Verify(Hash::Algorithm algorithm);
~Verify();
const EVP_MD* m_md = nullptr;
EVP_MD_CTX* m_ctx = nullptr;
friend class pjs::ObjectTemplate<Verify>;
};
//
// JWK
//
class JWK : public pjs::ObjectTemplate<JWK> {
public:
bool is_valid() const { return m_pkey; }
auto pkey() const -> EVP_PKEY* { return m_pkey; }
private:
JWK(pjs::Object *json);
~JWK();
EVP_PKEY* m_pkey = nullptr;
friend class pjs::ObjectTemplate<JWK>;
};
//
// JWT
//
class JWT : public pjs::ObjectTemplate<JWT> {
public:
enum class Algorithm {
HS256,
HS384,
HS512,
RS256,
RS384,
RS512,
ES256,
ES384,
ES512,
};
bool is_valid() const { return m_is_valid; }
auto header() const -> const pjs::Value& { return m_header; }
auto payload() const -> const pjs::Value& { return m_payload; }
void sign(pjs::Str *key);
bool verify(Data *key);
bool verify(pjs::Str *key);
bool verify(JWK *key);
private:
JWT(pjs::Str *token);
~JWT();
bool m_is_valid = false;
Algorithm m_algorithm = Algorithm::HS256;
pjs::Value m_header;
pjs::Value m_payload;
std::string m_header_str;
std::string m_payload_str;
std::string m_signature_str;
std::string m_signature;
auto get_md() -> const EVP_MD*;
bool verify(const char *key, int key_len);
bool verify(EVP_PKEY *pkey);
int jose2der(char *out, const char *inp, int len);
friend class pjs::ObjectTemplate<JWT>;
};
//
// Crypto
//
class Crypto : public pjs::ObjectTemplate<Crypto>
{
};
} // namespace crypto
} // namespace pipy
#endif // CRYPTO_HPP | 20.325 | 98 | 0.673739 | zengyuxing007 |
6abca41ee0eab7b863930330842283c3e87d0a4c | 18,412 | cpp | C++ | Code/GraphMol/Fingerprints/AtomPairs.cpp | chcltchunk/rdkit | af0ccf686779a8efd9db7c77f0bb3cab718ea2ba | [
"BSD-3-Clause"
] | 4 | 2020-12-29T14:52:15.000Z | 2021-08-28T08:12:45.000Z | Code/GraphMol/Fingerprints/AtomPairs.cpp | chcltchunk/rdkit | af0ccf686779a8efd9db7c77f0bb3cab718ea2ba | [
"BSD-3-Clause"
] | 2 | 2020-06-08T08:06:39.000Z | 2020-07-03T07:04:42.000Z | Code/GraphMol/Fingerprints/AtomPairs.cpp | chcltchunk/rdkit | af0ccf686779a8efd9db7c77f0bb3cab718ea2ba | [
"BSD-3-Clause"
] | 1 | 2020-05-15T12:15:35.000Z | 2020-05-15T12:15:35.000Z | //
// Copyright (C) 2007-2013 Greg Landrum
//
// @@ All Rights Reserved @@
// This file is part of the RDKit.
// The contents are covered by the terms of the BSD license
// which is included in the file license.txt, found at the root
// of the RDKit source tree.
//
#include <GraphMol/RDKitBase.h>
#include <GraphMol/Fingerprints/AtomPairs.h>
#include <GraphMol/Subgraphs/Subgraphs.h>
#include <DataStructs/SparseIntVect.h>
#include <RDGeneral/hash/hash.hpp>
#include <cstdint>
#include <boost/dynamic_bitset.hpp>
#include <boost/foreach.hpp>
#include <GraphMol/Fingerprints/FingerprintUtil.h>
namespace RDKit {
namespace AtomPairs {
template <typename T1, typename T2>
void updateElement(SparseIntVect<T1> &v, T2 elem) {
v.setVal(elem, v.getVal(elem) + 1);
}
template <typename T1>
void updateElement(ExplicitBitVect &v, T1 elem) {
v.setBit(elem % v.getNumBits());
}
template <typename T>
void setAtomPairBit(std::uint32_t i, std::uint32_t j,
std::uint32_t nAtoms,
const std::vector<std::uint32_t> &atomCodes,
const double *dm, T *bv, unsigned int minLength,
unsigned int maxLength, bool includeChirality) {
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bitId =
getAtomPairCode(atomCodes[i], atomCodes[j], dist, includeChirality);
updateElement(*bv, static_cast<std::uint32_t>(bitId));
}
}
SparseIntVect<std::int32_t> *getAtomPairFingerprint(
const ROMol &mol, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
return getAtomPairFingerprint(mol, 1, maxPathLen - 1, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D,
confId);
};
SparseIntVect<std::int32_t> *getAtomPairFingerprint(
const ROMol &mol, unsigned int minLength, unsigned int maxLength,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
auto *res = new SparseIntVect<std::int32_t>(
1 << (numAtomPairFingerprintBits + 2 * (includeChirality ? 2 : 0)));
const double *dm;
if (use2D) {
dm = MolOps::getDistanceMat(*lmol);
} else {
dm = MolOps::get3DDistanceMat(*lmol, confId);
}
const unsigned int nAtoms = lmol->getNumAtoms();
std::vector<std::uint32_t> atomCodes;
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()] %
((1 << codeSize) - 1));
}
}
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != lmol->endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
} else {
BOOST_FOREACH (std::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
setAtomPairBit(i, j, nAtoms, atomCodes, dm, res, minLength, maxLength,
includeChirality);
}
}
}
}
return res;
}
SparseIntVect<std::int32_t> *getHashedAtomPairFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality,
bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
auto *res = new SparseIntVect<std::int32_t>(nBits);
const double *dm;
try {
if (use2D) {
dm = MolOps::getDistanceMat(*lmol);
} else {
dm = MolOps::get3DDistanceMat(*lmol, confId);
}
} catch (const ConformerException &) {
delete res;
throw;
}
const unsigned int nAtoms = lmol->getNumAtoms();
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(nAtoms);
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
atomCodes.push_back((*atomInvariants)[(*atomItI)->getIdx()]);
}
}
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
unsigned int i = (*atomItI)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(), i) !=
ignoreAtoms->end()) {
continue;
}
if (!fromAtoms) {
for (ROMol::ConstAtomIterator atomItJ = atomItI + 1;
atomItJ != lmol->endAtoms(); ++atomItJ) {
unsigned int j = (*atomItJ)->getIdx();
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<std::int32_t>(bit % nBits));
}
}
} else {
BOOST_FOREACH (std::uint32_t j, *fromAtoms) {
if (j != i) {
if (ignoreAtoms && std::find(ignoreAtoms->begin(), ignoreAtoms->end(),
j) != ignoreAtoms->end()) {
continue;
}
auto dist = static_cast<unsigned int>(floor(dm[i * nAtoms + j]));
if (dist >= minLength && dist <= maxLength) {
std::uint32_t bit = 0;
gboost::hash_combine(bit, std::min(atomCodes[i], atomCodes[j]));
gboost::hash_combine(bit, dist);
gboost::hash_combine(bit, std::max(atomCodes[i], atomCodes[j]));
updateElement(*res, static_cast<std::int32_t>(bit % nBits));
}
}
}
}
}
return res;
}
ExplicitBitVect *getHashedAtomPairFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int minLength,
unsigned int maxLength, const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality, bool use2D, int confId) {
PRECONDITION(minLength <= maxLength, "bad lengths provided");
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
SparseIntVect<std::int32_t> *sres = getHashedAtomPairFingerprint(
mol, blockLength, minLength, maxLength, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality, use2D, confId);
auto *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i)) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
SparseIntVect<boost::int64_t> *getTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
boost::uint64_t sz = 1;
sz = (sz << (targetSize *
(codeSize + (includeChirality ? numChiralBits : 0))));
// NOTE: this -1 is incorrect but it's needed for backwards compatibility.
// hopefully we'll never have a case with a torsion that hits this.
//
// mmm, bug compatible.
sz -= 1;
auto *res = new SparseIntVect<boost::int64_t>(sz);
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(lmol->getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(
(*atomInvariants)[(*atomItI)->getIdx()] % ((1 << codeSize) - 1) + 2);
}
}
boost::dynamic_bitset<> *fromAtomsBV = nullptr;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(mol.getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
boost::dynamic_bitset<> pAtoms(lmol->getNumAtoms());
PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
std::vector<std::uint32_t> pathCodes;
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
pAtoms.reset();
for (auto pIt = path.begin(); pIt < path.end(); ++pIt) {
// look for a cycle that doesn't start at the first atom
// we can't effectively canonicalize these at the moment
// (was github #811)
if (pIt != path.begin() && *pIt != *(path.begin()) && pAtoms[*pIt]) {
pathCodes.clear();
break;
}
pAtoms.set(*pIt);
unsigned int code = atomCodes[*pIt] - 1;
// subtract off the branching number:
if (pIt != path.begin() && pIt + 1 != path.end()) {
--code;
}
pathCodes.push_back(code);
}
if (pathCodes.size()) {
boost::int64_t code =
getTopologicalTorsionCode(pathCodes, includeChirality);
updateElement(*res, code);
}
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
return res;
}
namespace {
template <typename T>
void TorsionFpCalc(T *res, const ROMol &mol, unsigned int nBits,
unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
const ROMol *lmol = &mol;
std::unique_ptr<ROMol> tmol;
if (includeChirality && !mol.hasProp(common_properties::_StereochemDone)) {
tmol = std::unique_ptr<ROMol>(new ROMol(mol));
MolOps::assignStereochemistry(*tmol);
lmol = tmol.get();
}
std::vector<std::uint32_t> atomCodes;
atomCodes.reserve(lmol->getNumAtoms());
for (ROMol::ConstAtomIterator atomItI = lmol->beginAtoms();
atomItI != lmol->endAtoms(); ++atomItI) {
if (!atomInvariants) {
atomCodes.push_back(getAtomCode(*atomItI, 0, includeChirality));
} else {
// need to add to the atomCode here because we subtract off up to 2 below
// as part of the branch correction
atomCodes.push_back(((*atomInvariants)[(*atomItI)->getIdx()] << 1) + 1);
}
}
boost::dynamic_bitset<> *fromAtomsBV = nullptr;
if (fromAtoms) {
fromAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *fromAtoms) { fromAtomsBV->set(fAt); }
}
boost::dynamic_bitset<> *ignoreAtomsBV = nullptr;
if (ignoreAtoms) {
ignoreAtomsBV = new boost::dynamic_bitset<>(lmol->getNumAtoms());
BOOST_FOREACH (std::uint32_t fAt, *ignoreAtoms) {
ignoreAtomsBV->set(fAt);
}
}
PATH_LIST paths = findAllPathsOfLengthN(*lmol, targetSize, false);
for (PATH_LIST::const_iterator pathIt = paths.begin(); pathIt != paths.end();
++pathIt) {
bool keepIt = true;
if (fromAtomsBV) {
keepIt = false;
}
const PATH_TYPE &path = *pathIt;
if (fromAtomsBV) {
if (fromAtomsBV->test(static_cast<std::uint32_t>(path.front())) ||
fromAtomsBV->test(static_cast<std::uint32_t>(path.back()))) {
keepIt = true;
}
}
if (keepIt && ignoreAtomsBV) {
BOOST_FOREACH (int pElem, path) {
if (ignoreAtomsBV->test(pElem)) {
keepIt = false;
break;
}
}
}
if (keepIt) {
std::vector<std::uint32_t> pathCodes(targetSize);
for (unsigned int i = 0; i < targetSize; ++i) {
unsigned int code = atomCodes[path[i]] - 1;
// subtract off the branching number:
if (i > 0 && i < targetSize - 1) {
--code;
}
pathCodes[i] = code;
}
size_t bit = getTopologicalTorsionHash(pathCodes);
updateElement(*res, bit % nBits);
}
}
delete fromAtomsBV;
delete ignoreAtomsBV;
}
} // namespace
SparseIntVect<boost::int64_t> *getHashedTopologicalTorsionFingerprint(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
auto *res = new SparseIntVect<boost::int64_t>(nBits);
TorsionFpCalc(res, mol, nBits, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
return res;
}
ExplicitBitVect *getHashedTopologicalTorsionFingerprintAsBitVect(
const ROMol &mol, unsigned int nBits, unsigned int targetSize,
const std::vector<std::uint32_t> *fromAtoms,
const std::vector<std::uint32_t> *ignoreAtoms,
const std::vector<std::uint32_t> *atomInvariants,
unsigned int nBitsPerEntry, bool includeChirality) {
PRECONDITION(!atomInvariants || atomInvariants->size() >= mol.getNumAtoms(),
"bad atomInvariants size");
static int bounds[4] = {1, 2, 4, 8};
unsigned int blockLength = nBits / nBitsPerEntry;
auto *sres = new SparseIntVect<boost::int64_t>(blockLength);
TorsionFpCalc(sres, mol, blockLength, targetSize, fromAtoms, ignoreAtoms,
atomInvariants, includeChirality);
auto *res = new ExplicitBitVect(nBits);
if (nBitsPerEntry != 4) {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second > static_cast<int>(i)) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
} else {
BOOST_FOREACH (SparseIntVect<boost::int64_t>::StorageType::value_type val,
sres->getNonzeroElements()) {
for (unsigned int i = 0; i < nBitsPerEntry; ++i) {
if (val.second >= bounds[i]) {
res->setBit(val.first * nBitsPerEntry + i);
}
}
}
}
delete sres;
return res;
}
} // end of namespace AtomPairs
} // end of namespace RDKit
| 36.971888 | 80 | 0.620845 | chcltchunk |
6abe596612463c9e7facca31767b80ada6702075 | 404 | cpp | C++ | source/LoopManager/LoopManager.cpp | mvxxx/MarsCombat | c4d10da7cf9bf8a71e00f64e5e364a358b477b15 | [
"MIT"
] | 1 | 2019-08-25T10:36:16.000Z | 2019-08-25T10:36:16.000Z | source/LoopManager/LoopManager.cpp | mvxxx/MarsCombat | c4d10da7cf9bf8a71e00f64e5e364a358b477b15 | [
"MIT"
] | null | null | null | source/LoopManager/LoopManager.cpp | mvxxx/MarsCombat | c4d10da7cf9bf8a71e00f64e5e364a358b477b15 | [
"MIT"
] | null | null | null | #include "LoopManager.hpp"
LoopManager::LoopManager(const sf::Time & _timePerFrame)
:timePerFrame(_timePerFrame)
{
timeSinceLastUpdate = sf::Time::Zero;
}
void LoopManager::increaseTime()
{
timeSinceLastUpdate += clock.restart();
}
bool LoopManager::canChangeTheFrame()
{
return timeSinceLastUpdate <= timePerFrame;
}
void LoopManager::reduceTime()
{
timeSinceLastUpdate -= timePerFrame;
}
| 17.565217 | 56 | 0.752475 | mvxxx |
6abf7aa1d03ea9e237cd1ad07c4ceb1fb1793f0d | 1,811 | cpp | C++ | src/data/label_utils.cpp | ltriess/voxelizer | f8dcc2296cd75d63081cea0edaaf162bbbfb717f | [
"MIT"
] | null | null | null | src/data/label_utils.cpp | ltriess/voxelizer | f8dcc2296cd75d63081cea0edaaf162bbbfb717f | [
"MIT"
] | null | null | null | src/data/label_utils.cpp | ltriess/voxelizer | f8dcc2296cd75d63081cea0edaaf162bbbfb717f | [
"MIT"
] | 4 | 2021-08-18T14:24:01.000Z | 2021-10-06T11:52:36.000Z | #include "label_utils.h"
#include <QtXml/QDomDocument>
#include <QtCore/QFile>
#include <QtCore/QStringList>
#include <QtCore/QString>
void getLabelNames(const std::string& filename,
std::map<uint32_t, std::string>& label_names)
{
QDomDocument doc("mydocument");
QFile file(QString::fromStdString(filename));
if (!file.open(QIODevice::ReadOnly)) return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomElement rootNode = doc.firstChildElement("config");
QDomElement n = rootNode.firstChildElement("label");
for (; !n.isNull(); n = n.nextSiblingElement("label"))
{
std::string name = n.firstChildElement("name").text().toStdString();
uint32_t id = n.firstChildElement("id").text().toInt();
label_names[id] = name;
}
}
void getLabelColors(const std::string& filename,
std::map<uint32_t, glow::GlColor>& label_colors)
{
QDomDocument doc("mydocument");
QFile file(QString::fromStdString(filename));
if (!file.open(QIODevice::ReadOnly)) return;
if (!doc.setContent(&file))
{
file.close();
return;
}
file.close();
QDomElement docElem = doc.documentElement();
QDomElement rootNode = doc.firstChildElement("config");
QDomElement n = rootNode.firstChildElement("label");
for (; !n.isNull(); n = n.nextSiblingElement("label"))
{
std::string name = n.firstChildElement("name").text().toStdString();
uint32_t id = n.firstChildElement("id").text().toInt();
QString color_string = n.firstChildElement("color").text();
QStringList tokens = color_string.split(" ");
int32_t R = tokens.at(0).toInt();
int32_t G = tokens.at(1).toInt();
int32_t B = tokens.at(2).toInt();
label_colors[id] = glow::GlColor::FromRGB(R, G, B);
}
}
| 26.246377 | 72 | 0.675318 | ltriess |
6ac2777870eac3943b7128f02cb8c3590c48100c | 11,109 | cpp | C++ | FileZillaFTP/source/interface/splitex.cpp | JyothsnaMididoddi26/xampp | 8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b | [
"Apache-2.0"
] | 1 | 2017-01-31T08:49:16.000Z | 2017-01-31T08:49:16.000Z | FileZillaFTP/source/interface/splitex.cpp | JyothsnaMididoddi26/xampp | 8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b | [
"Apache-2.0"
] | 2 | 2020-07-17T00:13:41.000Z | 2021-05-08T17:01:54.000Z | FileZillaFTP/source/interface/splitex.cpp | JyothsnaMididoddi26/xampp | 8f34d7fa7c2e6cc37fe4ece5e6886dc4e5c0757b | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////
//
// splitex.cpp
// Based upon code from Oleg G. Galkin
// Modified to handle multiple hidden rows
#include "stdafx.h"
#include "splitex.h"
#if defined(_DEBUG) && !defined(MMGR)
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
////////////////////////////////////////////////////////////////////////////
//
// CSplitterWndEx
CSplitterWndEx::CSplitterWndEx()
{
m_arr = 0;
m_length = 0;
}
CSplitterWndEx::~CSplitterWndEx()
{
delete [] m_arr;
}
int CSplitterWndEx::Id_short(int row, int col)
{
return AFX_IDW_PANE_FIRST + row * 16 + col;
}
void CSplitterWndEx::ShowRow(int r)
{
ASSERT_VALID(this);
ASSERT(m_nRows < m_nMaxRows);
ASSERT(m_arr);
ASSERT(r < m_length);
ASSERT(m_arr[r] >= m_nRows);
ASSERT(m_arr[r] < m_length);
int rowNew = r;
int cyNew = m_pRowInfo[m_arr[r]].nCurSize;
int cyIdealNew = m_pRowInfo[m_arr[r]].nIdealSize;
int new_val = 0;
for (int i = rowNew - 1; i >= 0; i--)
if (m_arr[i] < m_nRows) // not hidden
{
new_val = m_arr[i] + 1;
break;
}
int old_val = m_arr[rowNew];
m_nRows++; // add a row
// fill the hided row
int row;
for (int col = 0; col < m_nCols; col++)
{
CWnd* pPaneShow = GetDlgItem(
Id_short(old_val, col));
ASSERT(pPaneShow != NULL);
pPaneShow->ShowWindow(SW_SHOWNA);
for (row = m_length - 1; row >= 0; row--)
{
if ((m_arr[row] >= new_val) &&
(m_arr[row] < old_val))
{
CWnd* pPane = CSplitterWnd::GetPane(m_arr[row], col);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(m_arr[row] + 1, col));
}
}
pPaneShow->SetDlgCtrlID(Id_short(new_val, col));
}
for (row = 0; row < m_length; row++)
if ((m_arr[row] >= new_val) &&
(m_arr[row] < old_val))
m_arr[row]++;
m_arr[rowNew] = new_val;
//new panes have been created -- recalculate layout
for (row = new_val + 1; row < m_length; row++)
{
if (m_arr[row]<m_nRows)
{
m_pRowInfo[m_arr[row]].nIdealSize = m_pRowInfo[m_arr[row-1]].nCurSize;
m_pRowInfo[m_arr[row]].nCurSize = m_pRowInfo[m_arr[row-1]].nCurSize;
}
}
if (cyNew>=0x10000)
{
int rowToResize=(cyNew>>16)-1;
cyNew%=0x10000;
cyIdealNew%=0x10000;
m_pRowInfo[m_arr[rowToResize]].nCurSize-=cyNew+m_cxSplitter;
m_pRowInfo[m_arr[rowToResize]].nIdealSize=m_pRowInfo[m_arr[rowToResize]].nCurSize;//-=cyIdealNew+m_cxSplitter;
}
m_pRowInfo[new_val].nIdealSize = cyNew;
m_pRowInfo[new_val].nCurSize = cyNew;
RecalcLayout();
}
void CSplitterWndEx::ShowColumn(int c)
{
ASSERT_VALID(this);
ASSERT(m_nCols < m_nMaxCols);
ASSERT(m_arr);
ASSERT(c < m_length);
ASSERT(m_arr[c] >= m_nRows);
ASSERT(m_arr[c] < m_length);
int colNew = c;
int cxNew = m_pColInfo[m_arr[c]].nCurSize;
int cxIdealNew = m_pColInfo[m_arr[c]].nIdealSize;
int new_val = 0;
for (int i = colNew - 1; i >= 0; i--)
if (m_arr[i] < m_nCols) // not hidden
{
new_val = m_arr[i] + 1;
break;
}
int old_val = m_arr[colNew];
m_nCols++; // add a col
// fill the hided col
int col;
for (int row = 0; row < m_nRows; row++)
{
CWnd* pPaneShow = GetDlgItem(
Id_short(row, old_val));
ASSERT(pPaneShow != NULL);
pPaneShow->ShowWindow(SW_SHOWNA);
for (col = m_length - 1; col >= 0; col--)
{
if ((m_arr[col] >= new_val) &&
(m_arr[col] < old_val))
{
CWnd* pPane = CSplitterWnd::GetPane(row, m_arr[col]);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row, m_arr[col]+1));
}
}
pPaneShow->SetDlgCtrlID(Id_short(row, new_val));
}
for (col = 0; col < m_length; col++)
if ((m_arr[col] >= new_val) &&
(m_arr[col] < old_val))
m_arr[col]++;
m_arr[colNew] = new_val;
//new panes have been created -- recalculate layout
for (col = new_val + 1; col < m_length; col++)
{
if (m_arr[col]<m_nCols)
{
m_pColInfo[m_arr[col]].nIdealSize = m_pColInfo[m_arr[col-1]].nCurSize;
m_pColInfo[m_arr[col]].nCurSize = m_pColInfo[m_arr[col-1]].nCurSize;
}
}
if (cxNew>=0x10000)
{
int colToResize=(cxNew>>16)-1;
cxNew%=0x10000;
cxIdealNew%=0x10000;
m_pColInfo[m_arr[colToResize]].nCurSize-=cxNew+m_cySplitter;
m_pColInfo[m_arr[colToResize]].nIdealSize=m_pColInfo[m_arr[colToResize]].nCurSize;//-=cxIdealNew+m_cySplitter;
}
m_pColInfo[new_val].nIdealSize = cxNew;
m_pColInfo[new_val].nCurSize = cxNew;
RecalcLayout();
}
void CSplitterWndEx::HideRow(int rowHide,int rowToResize)
{
ASSERT_VALID(this);
ASSERT(m_nRows > 1);
if (m_arr)
ASSERT(m_arr[rowHide] < m_nRows);
// if the row has an active window -- change it
int rowActive, colActive;
if (!m_arr)
{
m_arr = new int[m_nRows];
for (int i = 0; i < m_nRows; i++)
m_arr[i] = i;
m_length = m_nRows;
}
if (GetActivePane(&rowActive, &colActive) != NULL &&
rowActive == rowHide) //colActive == rowHide)
{
if (++rowActive >= m_nRows)
rowActive = 0;
//SetActivePane(rowActive, colActive);
SetActivePane(rowActive, colActive);
}
// hide all row panes
for (int col = 0; col < m_nCols; col++)
{
CWnd* pPaneHide = CSplitterWnd::GetPane(m_arr[rowHide], col);
ASSERT(pPaneHide != NULL);
pPaneHide->ShowWindow(SW_HIDE);
for (int row = rowHide + 1; row < m_length; row++)
{
if (m_arr[row] < m_nRows )
{
CWnd* pPane = CSplitterWnd::GetPane(m_arr[row], col);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row-1, col));
m_arr[row]--;
}
}
pPaneHide->SetDlgCtrlID(
Id_short(m_nRows -1 , col));
}
int oldsize=m_pRowInfo[m_arr[rowHide]].nCurSize;
for (int row=rowHide;row<(m_length-1);row++)
{
if (m_arr[row+1] < m_nRows )
{
m_pRowInfo[m_arr[row]].nCurSize=m_pRowInfo[m_arr[row+1]].nCurSize;
m_pRowInfo[m_arr[row]].nIdealSize=m_pRowInfo[m_arr[row+1]].nCurSize;
}
}
if (rowToResize!=-1)
{
m_pRowInfo[m_arr[rowToResize]].nCurSize+=oldsize+m_cySplitter;
m_pRowInfo[m_arr[rowToResize]].nIdealSize+=oldsize+m_cySplitter;
oldsize+=0x10000*(rowToResize+1);
}
m_pRowInfo[m_nRows - 1].nCurSize =oldsize;
m_pRowInfo[m_nRows - 1].nIdealSize =oldsize;
m_arr[rowHide] = m_nRows-1;
m_nRows--;
RecalcLayout();
}
void CSplitterWndEx::HideColumn(int colHide, int colToResize)
{
ASSERT_VALID(this);
ASSERT(m_nCols > 1);
if (m_arr)
ASSERT(m_arr[colHide] < m_nCols);
// if the col has an active window -- change it
int colActive, rowActive;
if (!m_arr)
{
m_arr = new int[m_nCols];
for (int i = 0; i < m_nCols; i++)
m_arr[i] = i;
m_length = m_nCols;
}
if (GetActivePane(&rowActive, &colActive) != NULL &&
colActive == colHide)
{
if (++colActive >= m_nCols)
colActive = 0;
SetActivePane(rowActive, colActive);
}
// hide all row panes
for (int row = 0; row < m_nRows; row++)
{
CWnd* pPaneHide = CSplitterWnd::GetPane(row, m_arr[colHide]);
ASSERT(pPaneHide != NULL);
pPaneHide->ShowWindow(SW_HIDE);
for (int col = colHide + 1; col < m_length; col++)
{
if (m_arr[col] < m_nCols )
{
CWnd* pPane = CSplitterWnd::GetPane(row, m_arr[col]);
ASSERT(pPane != NULL);
pPane->SetDlgCtrlID(Id_short(row, col-1));
m_arr[col]--;
}
}
pPaneHide->SetDlgCtrlID(
Id_short(row, m_nCols -1));
}
int oldsize = m_pColInfo[m_arr[colHide]].nCurSize;
for (int col = colHide; col < (m_length - 1); ++col)
{
if (m_arr[col + 1] < m_nCols)
{
m_pColInfo[m_arr[col]].nCurSize = m_pColInfo[m_arr[col + 1]].nCurSize;
m_pColInfo[m_arr[col]].nIdealSize = m_pColInfo[m_arr[col + 1]].nCurSize;
}
}
if (colToResize != -1)
{
m_pColInfo[m_arr[colToResize]].nCurSize += oldsize + m_cxSplitter;
m_pColInfo[m_arr[colToResize]].nIdealSize += oldsize + m_cxSplitter;
oldsize += 0x10000 * (colToResize + 1);
}
m_pColInfo[m_nCols - 1].nCurSize = oldsize;
m_pColInfo[m_nCols - 1].nIdealSize = oldsize;
m_arr[colHide] = m_nCols - 1;
m_nCols--;
RecalcLayout();
}
BEGIN_MESSAGE_MAP(CSplitterWndEx, CSplitterWnd)
//{{AFX_MSG_MAP(CSplitterWndEx)
// NOTE - the ClassWizard will add and remove mapping macros here.
//}}AFX_MSG_MAP
END_MESSAGE_MAP()
CWnd* CSplitterWndEx::GetPane(int row, int col)
{
if (!m_arr)
return CSplitterWnd::GetPane(row,col);
else
{
ASSERT_VALID(this);
CWnd* pView = GetDlgItem(IdFromRowCol(m_arr[row], col));
ASSERT(pView != NULL); // panes can be a CWnd, but are usually CViews
return pView;
}
}
int CSplitterWndEx::IdFromRowCol(int row, int col) const
{
ASSERT_VALID(this);
ASSERT(row >= 0);
ASSERT(row < (m_arr?m_length:m_nRows));
ASSERT(col >= 0);
ASSERT(col < m_nCols);
return AFX_IDW_PANE_FIRST + row * 16 + col;
}
BOOL CSplitterWndEx::IsChildPane(CWnd* pWnd, int* pRow, int* pCol)
{
ASSERT_VALID(this);
ASSERT_VALID(pWnd);
UINT nID = ::GetDlgCtrlID(pWnd->m_hWnd);
if (IsChild(pWnd) && nID >= AFX_IDW_PANE_FIRST && nID <= AFX_IDW_PANE_LAST)
{
if (pWnd->GetParent()!=this)
return FALSE;
if (pRow != NULL)
*pRow = (nID - AFX_IDW_PANE_FIRST) / 16;
if (pCol != NULL)
*pCol = (nID - AFX_IDW_PANE_FIRST) % 16;
ASSERT(pRow == NULL || *pRow < (m_arr?m_length:m_nRows));
ASSERT(pCol == NULL || *pCol < m_nCols);
return TRUE;
}
else
{
if (pRow != NULL)
*pRow = -1;
if (pCol != NULL)
*pCol = -1;
return FALSE;
}
}
CWnd* CSplitterWndEx::GetActivePane(int* pRow, int* pCol)
// return active view, NULL when no active view
{
ASSERT_VALID(this);
// attempt to use active view of frame window
CWnd* pView = NULL;
CFrameWnd* pFrameWnd = GetParentFrame();
ASSERT_VALID(pFrameWnd);
pView = pFrameWnd->GetActiveView();
// failing that, use the current focus
if (pView == NULL)
pView = GetFocus();
// make sure the pane is a child pane of the splitter
if (pView != NULL && !IsChildPane(pView, pRow, pCol))
pView = NULL;
return pView;
}
BOOL CSplitterWndEx::IsRowHidden(int row)
{
return m_arr[row]>=m_nRows;
}
void CSplitterWndEx::GetRowInfoEx(int row, int &cyCur, int &cyMin)
{
if (!m_arr)
GetRowInfo(row,cyCur,cyMin);
else
{
if (m_pRowInfo[m_arr[row]].nCurSize>0x10000)
cyCur=m_pRowInfo[m_arr[row]].nCurSize/0x10000;
else
cyCur=m_pRowInfo[m_arr[row]].nCurSize%0x10000;
cyMin=0;
}
}
__int64 CSplitterWndEx::GetSizes() const
{
LARGE_INTEGER v;
int dummy;
int s1, s2;
if (BarIsHorizontal())
{
GetRowInfo(0, s1, dummy);
GetRowInfo(1, s2, dummy);
v.HighPart = s1;
v.LowPart = s2;
}
else
{
GetColumnInfo(0, s1, dummy);
GetColumnInfo(1, s2, dummy);
v.HighPart = s1;
v.LowPart = s2;
}
return v.QuadPart;
}
| 23.890323 | 113 | 0.606985 | JyothsnaMididoddi26 |
6ac3c7ed0ea2773620a4a6499251243360d79be0 | 394 | cpp | C++ | src/Airline/Ticket.cpp | jlcrodrigues/feup-aed | 9586e984cd725292c7d76645b146ec969f788e19 | [
"MIT"
] | 7 | 2021-12-22T21:57:38.000Z | 2022-01-05T18:08:17.000Z | src/Airline/Ticket.cpp | jlcrodrigues/feup-aed | 9586e984cd725292c7d76645b146ec969f788e19 | [
"MIT"
] | null | null | null | src/Airline/Ticket.cpp | jlcrodrigues/feup-aed | 9586e984cd725292c7d76645b146ec969f788e19 | [
"MIT"
] | 1 | 2021-12-23T00:35:06.000Z | 2021-12-23T00:35:06.000Z | #include "Ticket.h"
using namespace std;
Ticket::Ticket(const Flight& flight, const bool& baggage): flight(flight)
{
this->baggage = baggage;
checked_in = false;
}
Flight Ticket::getFlight() const
{
return flight;
}
bool Ticket::getBaggage() const
{
return baggage;
}
void Ticket::checkIn()
{
checked_in = true;
}
bool Ticket::hasCheckedIn() const
{
return checked_in;
} | 13.586207 | 73 | 0.687817 | jlcrodrigues |
6acf1f004df6d514d9d82e76649e16b7e6e731b1 | 15,832 | cpp | C++ | examples/SharedMemory/plugins/fileIOPlugin/fileIOPlugin.cpp | aaronfranke/bullet3 | 0c6c7976baeb43204dc8adeb3235d960b2a9b340 | [
"Zlib"
] | 2 | 2021-11-08T02:53:13.000Z | 2021-11-08T09:40:43.000Z | examples/SharedMemory/plugins/fileIOPlugin/fileIOPlugin.cpp | aaronfranke/bullet3 | 0c6c7976baeb43204dc8adeb3235d960b2a9b340 | [
"Zlib"
] | null | null | null | examples/SharedMemory/plugins/fileIOPlugin/fileIOPlugin.cpp | aaronfranke/bullet3 | 0c6c7976baeb43204dc8adeb3235d960b2a9b340 | [
"Zlib"
] | null | null | null | #include "fileIOPlugin.h"
#include "../../SharedMemoryPublic.h"
#include "../b3PluginContext.h"
#include <stdio.h>
#include "../../../CommonInterfaces/CommonFileIOInterface.h"
#include "../../../Utils/b3ResourcePath.h"
#include "Bullet3Common/b3HashMap.h"
#include <string.h> //memcpy/strlen
#ifndef B3_EXCLUDE_DEFAULT_FILEIO
#include "../../../Utils/b3BulletDefaultFileIO.h"
#endif //B3_EXCLUDE_DEFAULT_FILEIO
#ifdef B3_USE_ZIPFILE_FILEIO
#include "zipFileIO.h"
#endif //B3_USE_ZIPFILE_FILEIO
#ifdef B3_USE_CNS_FILEIO
#include "CNSFileIO.h"
#endif //B3_USE_CNS_FILEIO
#define B3_MAX_FILEIO_INTERFACES 1024
struct WrapperFileHandle
{
CommonFileIOInterface* childFileIO;
int m_childFileHandle;
};
struct InMemoryFile
{
char* m_buffer;
int m_fileSize;
};
struct InMemoryFileAccessor
{
InMemoryFile* m_file;
int m_curPos;
};
struct InMemoryFileIO : public CommonFileIOInterface
{
b3HashMap<b3HashString,InMemoryFile*> m_fileCache;
InMemoryFileAccessor m_fileHandles[B3_MAX_FILEIO_INTERFACES];
int m_numAllocs;
int m_numFrees;
InMemoryFileIO()
:CommonFileIOInterface(eInMemoryFileIO,0)
{
m_numAllocs=0;
m_numFrees=0;
for (int i=0;i<B3_FILEIO_MAX_FILES;i++)
{
m_fileHandles[i].m_curPos = 0;
m_fileHandles[i].m_file = 0;
}
}
virtual ~InMemoryFileIO()
{
clearCache();
if (m_numAllocs != m_numFrees)
{
printf("Error: InMemoryFile::~InMemoryFileIO (numAllocs %d numFrees %d\n", m_numAllocs, m_numFrees);
}
}
void clearCache()
{
for (int i=0;i<m_fileCache.size();i++)
{
b3HashString name = m_fileCache.getKeyAtIndex(i);
InMemoryFile** memPtr = m_fileCache.getAtIndex(i);
if (memPtr && *memPtr)
{
InMemoryFile* mem = *memPtr;
freeBuffer(mem->m_buffer);
m_numFrees++;
delete (mem);
m_numFrees++;
m_fileCache.remove(name);
}
}
}
char* allocateBuffer(int len)
{
char* buffer = 0;
if (len)
{
m_numAllocs++;
buffer = new char[len];
}
return buffer;
}
void freeBuffer(char* buffer)
{
delete[] buffer;
}
virtual int registerFile(const char* fileName, char* buffer, int len)
{
m_numAllocs++;
InMemoryFile* f = new InMemoryFile();
f->m_buffer = buffer;
f->m_fileSize = len;
b3HashString key(fileName);
m_fileCache.insert(key,f);
return 0;
}
void removeFileFromCache(const char* fileName)
{
InMemoryFile* f = getInMemoryFile(fileName);
if (f)
{
m_fileCache.remove(fileName);
freeBuffer(f->m_buffer);
delete (f);
}
}
InMemoryFile* getInMemoryFile(const char* fileName)
{
InMemoryFile** fPtr = m_fileCache[fileName];
if (fPtr && *fPtr)
{
return *fPtr;
}
return 0;
}
virtual int fileOpen(const char* fileName, const char* mode)
{
//search a free slot
int slot = -1;
for (int i=0;i<B3_FILEIO_MAX_FILES;i++)
{
if (m_fileHandles[i].m_file==0)
{
slot=i;
break;
}
}
if (slot>=0)
{
InMemoryFile* f = getInMemoryFile(fileName);
if (f)
{
m_fileHandles[slot].m_curPos = 0;
m_fileHandles[slot].m_file = f;
} else
{
slot=-1;
}
}
//printf("InMemoryFileIO fileOpen %s, %d\n", fileName, slot);
return slot;
}
virtual int fileRead(int fileHandle, char* destBuffer, int numBytes)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES)
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
//if (numBytes>1)
// printf("curPos = %d\n", f.m_curPos);
if (f.m_curPos+numBytes <= f.m_file->m_fileSize)
{
memcpy(destBuffer,f.m_file->m_buffer+f.m_curPos,numBytes);
f.m_curPos+=numBytes;
//if (numBytes>1)
// printf("read %d bytes, now curPos = %d\n", numBytes, f.m_curPos);
return numBytes;
} else
{
if (numBytes!=1)
{
printf("InMemoryFileIO::fileRead Attempt to read beyond end of file\n");
}
}
}
}
return 0;
}
virtual int fileWrite(int fileHandle,const char* sourceBuffer, int numBytes)
{
return 0;
}
virtual void fileClose(int fileHandle)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES)
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
m_fileHandles[fileHandle].m_file = 0;
m_fileHandles[fileHandle].m_curPos = 0;
//printf("InMemoryFileIO fileClose %d\n", fileHandle);
}
}
}
virtual bool findResourcePath(const char* fileName, char* resourcePathOut, int resourcePathMaxNumBytes)
{
InMemoryFile* f = getInMemoryFile(fileName);
int fileNameLen = strlen(fileName);
if (f && fileNameLen<(resourcePathMaxNumBytes-1))
{
memcpy(resourcePathOut, fileName, fileNameLen);
resourcePathOut[fileNameLen]=0;
return true;
}
return false;
}
virtual char* readLine(int fileHandle, char* destBuffer, int numBytes)
{
int numRead = 0;
int endOfFile = 0;
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES )
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
//return ::fgets(destBuffer, numBytes, m_fileHandles[fileHandle]);
char c = 0;
do
{
int bytesRead = fileRead(fileHandle,&c,1);
if (bytesRead != 1)
{
endOfFile = 1;
c=0;
}
if (c && c!='\n')
{
if (c!=13)
{
destBuffer[numRead++]=c;
} else
{
destBuffer[numRead++]=0;
}
}
} while (c != 0 && c != '\n' && numRead<(numBytes-1));
}
}
if (numRead==0 && endOfFile)
{
return 0;
}
if (numRead<numBytes)
{
if (numRead >=0)
{
destBuffer[numRead]=0;
}
return &destBuffer[0];
} else
{
if (endOfFile==0)
{
printf("InMemoryFileIO::readLine readLine warning: numRead=%d, numBytes=%d\n", numRead, numBytes);
}
}
return 0;
}
virtual int getFileSize(int fileHandle)
{
if (fileHandle>=0 && fileHandle < B3_FILEIO_MAX_FILES )
{
InMemoryFileAccessor& f = m_fileHandles[fileHandle];
if (f.m_file)
{
return f.m_file->m_fileSize;
}
}
return 0;
}
virtual void enableFileCaching(bool enable)
{
(void)enable;
}
};
struct WrapperFileIO : public CommonFileIOInterface
{
CommonFileIOInterface* m_availableFileIOInterfaces[B3_MAX_FILEIO_INTERFACES];
int m_numWrapperInterfaces;
WrapperFileHandle m_wrapperFileHandles[B3_MAX_FILEIO_INTERFACES];
InMemoryFileIO m_cachedFiles;
bool m_enableFileCaching;
WrapperFileIO()
:CommonFileIOInterface(0,0),
m_numWrapperInterfaces(0),
m_enableFileCaching(true)
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
m_availableFileIOInterfaces[i]=0;
m_wrapperFileHandles[i].childFileIO=0;
m_wrapperFileHandles[i].m_childFileHandle=0;
}
//addFileIOInterface(&m_cachedFiles);
}
virtual ~WrapperFileIO()
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
removeFileIOInterface(i);
}
m_cachedFiles.clearCache();
}
int addFileIOInterface(CommonFileIOInterface* fileIO)
{
int result = -1;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_availableFileIOInterfaces[i]==0)
{
m_availableFileIOInterfaces[i]=fileIO;
result = i;
break;
}
}
return result;
}
CommonFileIOInterface* getFileIOInterface(int fileIOIndex)
{
if (fileIOIndex>=0 && fileIOIndex<B3_MAX_FILEIO_INTERFACES)
{
return m_availableFileIOInterfaces[fileIOIndex];
}
return 0;
}
void removeFileIOInterface(int fileIOIndex)
{
if (fileIOIndex>=0 && fileIOIndex<B3_MAX_FILEIO_INTERFACES)
{
if (m_availableFileIOInterfaces[fileIOIndex])
{
delete m_availableFileIOInterfaces[fileIOIndex];
m_availableFileIOInterfaces[fileIOIndex]=0;
}
}
}
virtual int fileOpen(const char* fileName, const char* mode)
{
//find an available wrapperFileHandle slot
int wrapperFileHandle=-1;
int slot = -1;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_wrapperFileHandles[i].childFileIO==0)
{
slot=i;
break;
}
}
if (slot>=0)
{
//first check the cache
int cacheHandle = m_cachedFiles.fileOpen(fileName, mode);
if (cacheHandle>=0)
{
m_cachedFiles.fileClose(cacheHandle);
}
if (cacheHandle<0)
{
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* childFileIO=m_availableFileIOInterfaces[i];
if (childFileIO)
{
int childHandle = childFileIO->fileOpen(fileName, mode);
if (childHandle>=0)
{
if (m_enableFileCaching)
{
int fileSize = childFileIO->getFileSize(childHandle);
char* buffer = 0;
if (fileSize)
{
buffer = m_cachedFiles.allocateBuffer(fileSize);
if (buffer)
{
int readBytes = childFileIO->fileRead(childHandle, buffer, fileSize);
if (readBytes!=fileSize)
{
if (readBytes<fileSize)
{
fileSize = readBytes;
} else
{
printf("WrapperFileIO error: reading more bytes (%d) then reported file size (%d) of file %s.\n", readBytes, fileSize, fileName);
}
}
} else
{
fileSize=0;
}
}
//potentially register a zero byte file, or files that only can be read partially
m_cachedFiles.registerFile(fileName, buffer, fileSize);
}
childFileIO->fileClose(childHandle);
break;
}
}
}
}
{
int childHandle = m_cachedFiles.fileOpen(fileName, mode);
if (childHandle>=0)
{
wrapperFileHandle = slot;
m_wrapperFileHandles[slot].childFileIO = &m_cachedFiles;
m_wrapperFileHandles[slot].m_childFileHandle = childHandle;
} else
{
//figure out what wrapper interface to use
//use the first one that can open the file
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* childFileIO=m_availableFileIOInterfaces[i];
if (childFileIO)
{
int childHandle = childFileIO->fileOpen(fileName, mode);
if (childHandle>=0)
{
wrapperFileHandle = slot;
m_wrapperFileHandles[slot].childFileIO = childFileIO;
m_wrapperFileHandles[slot].m_childFileHandle = childHandle;
break;
}
}
}
}
}
}
return wrapperFileHandle;
}
virtual int fileRead(int fileHandle, char* destBuffer, int numBytes)
{
int fileReadResult=-1;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
fileReadResult = m_wrapperFileHandles[fileHandle].childFileIO->fileRead(
m_wrapperFileHandles[fileHandle].m_childFileHandle, destBuffer, numBytes);
}
}
return fileReadResult;
}
virtual int fileWrite(int fileHandle,const char* sourceBuffer, int numBytes)
{
//todo
return -1;
}
virtual void fileClose(int fileHandle)
{
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
m_wrapperFileHandles[fileHandle].childFileIO->fileClose(
m_wrapperFileHandles[fileHandle].m_childFileHandle);
m_wrapperFileHandles[fileHandle].childFileIO = 0;
m_wrapperFileHandles[fileHandle].m_childFileHandle = -1;
}
}
}
virtual bool findResourcePath(const char* fileName, char* resourcePathOut, int resourcePathMaxNumBytes)
{
if (m_cachedFiles.findResourcePath(fileName, resourcePathOut, resourcePathMaxNumBytes))
return true;
bool found = false;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
if (m_availableFileIOInterfaces[i])
{
found = m_availableFileIOInterfaces[i]->findResourcePath(fileName, resourcePathOut, resourcePathMaxNumBytes);
}
if (found)
break;
}
return found;
}
virtual char* readLine(int fileHandle, char* destBuffer, int numBytes)
{
char* result = 0;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
result = m_wrapperFileHandles[fileHandle].childFileIO->readLine(
m_wrapperFileHandles[fileHandle].m_childFileHandle,
destBuffer, numBytes);
}
}
return result;
}
virtual int getFileSize(int fileHandle)
{
int numBytes = 0;
if (fileHandle>=0 && fileHandle<B3_MAX_FILEIO_INTERFACES)
{
if (m_wrapperFileHandles[fileHandle].childFileIO)
{
numBytes = m_wrapperFileHandles[fileHandle].childFileIO->getFileSize(
m_wrapperFileHandles[fileHandle].m_childFileHandle);
}
}
return numBytes;
}
virtual void enableFileCaching(bool enable)
{
m_enableFileCaching = enable;
if (!enable)
{
m_cachedFiles.clearCache();
}
}
};
struct FileIOClass
{
int m_testData;
WrapperFileIO m_fileIO;
FileIOClass()
: m_testData(42),
m_fileIO()
{
}
virtual ~FileIOClass()
{
}
};
B3_SHARED_API int initPlugin_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = new FileIOClass();
context->m_userPointer = obj;
#ifndef B3_EXCLUDE_DEFAULT_FILEIO
obj->m_fileIO.addFileIOInterface(new b3BulletDefaultFileIO());
#endif //B3_EXCLUDE_DEFAULT_FILEIO
return SHARED_MEMORY_MAGIC_NUMBER;
}
B3_SHARED_API int executePluginCommand_fileIOPlugin(struct b3PluginContext* context, const struct b3PluginArguments* arguments)
{
int result=-1;
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
printf("text argument:%s\n", arguments->m_text);
printf("int args: [");
//remove a fileIO type
if (arguments->m_numInts==1)
{
int fileIOIndex = arguments->m_ints[0];
obj->m_fileIO.removeFileIOInterface(fileIOIndex);
}
if (arguments->m_numInts==2)
{
int action = arguments->m_ints[0];
switch (action)
{
case eAddFileIOAction:
{
//if the fileIO already exists, skip this action
int fileIOType = arguments->m_ints[1];
bool alreadyExists = false;
for (int i=0;i<B3_MAX_FILEIO_INTERFACES;i++)
{
CommonFileIOInterface* fileIO = obj->m_fileIO.getFileIOInterface(i);
if (fileIO)
{
if (fileIO->m_fileIOType == fileIOType)
{
if (fileIO->m_pathPrefix && strcmp(fileIO->m_pathPrefix,arguments->m_text)==0)
{
result = i;
alreadyExists = true;
break;
}
}
}
}
//create new fileIO interface
if (!alreadyExists)
{
switch (fileIOType)
{
case ePosixFileIO:
{
#ifdef B3_EXCLUDE_DEFAULT_FILEIO
printf("ePosixFileIO is not enabled in this build.\n");
#else
result = obj->m_fileIO.addFileIOInterface(new b3BulletDefaultFileIO(ePosixFileIO, arguments->m_text));
#endif
break;
}
case eZipFileIO:
{
#ifdef B3_USE_ZIPFILE_FILEIO
if (arguments->m_text[0])
{
result = obj->m_fileIO.addFileIOInterface(new ZipFileIO(eZipFileIO, arguments->m_text, &obj->m_fileIO));
}
#else
printf("eZipFileIO is not enabled in this build.\n");
#endif
break;
}
case eCNSFileIO:
{
#ifdef B3_USE_CNS_FILEIO
result = obj->m_fileIO.addFileIOInterface(new CNSFileIO(eCNSFileIO, arguments->m_text));
#else//B3_USE_CNS_FILEIO
printf("CNSFileIO is not enabled in this build.\n");
#endif //B3_USE_CNS_FILEIO
break;
}
default:
{
}
}//switch (fileIOType)
}//if (!alreadyExists)
break;
}
case eRemoveFileIOAction:
{
//remove fileIO interface
int fileIOIndex = arguments->m_ints[1];
obj->m_fileIO.removeFileIOInterface(fileIOIndex);
result = fileIOIndex;
break;
}
default:
{
printf("executePluginCommand_fileIOPlugin: unknown action\n");
}
}
}
return result;
}
B3_SHARED_API struct CommonFileIOInterface* getFileIOFunc_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
return &obj->m_fileIO;
}
B3_SHARED_API void exitPlugin_fileIOPlugin(struct b3PluginContext* context)
{
FileIOClass* obj = (FileIOClass*)context->m_userPointer;
delete obj;
context->m_userPointer = 0;
}
| 22.552707 | 141 | 0.669214 | aaronfranke |
6ad19fa15572e3b9d4ea08e8a450cdf5a0a96ed6 | 1,638 | cpp | C++ | exportobjects/exportmaterial.cpp | walbourn/contentexporter | 2559ac92bbb1ce1409f1c63b51957ea088427b24 | [
"MIT"
] | 62 | 2015-04-14T22:28:11.000Z | 2022-03-28T07:02:28.000Z | exportobjects/exportmaterial.cpp | TienAska/contentexporter | 746cf69136b63b0502e9e6e8687ed66b5a268103 | [
"MIT"
] | 18 | 2015-07-01T18:29:14.000Z | 2021-11-13T12:28:08.000Z | exportobjects/exportmaterial.cpp | TienAska/contentexporter | 746cf69136b63b0502e9e6e8687ed66b5a268103 | [
"MIT"
] | 21 | 2015-05-31T07:57:37.000Z | 2021-07-30T10:20:06.000Z | //-------------------------------------------------------------------------------------
// ExportMaterial.cpp
//
// Advanced Technology Group (ATG)
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
//
// http://go.microsoft.com/fwlink/?LinkId=226208
//-------------------------------------------------------------------------------------
#include "stdafx.h"
#include "ExportMaterial.h"
using namespace ATG;
ExportMaterial::ExportMaterial()
: ExportBase(nullptr),
m_pMaterialDefinition(nullptr),
m_bTransparent(false)
{
}
ExportMaterial::ExportMaterial(ExportString name)
: ExportBase(name),
m_pMaterialDefinition(nullptr),
m_bTransparent(false)
{
}
ExportMaterial::~ExportMaterial()
{
}
ExportMaterialParameter* ExportMaterial::FindParameter(const ExportString strName)
{
MaterialParameterList::iterator iter = m_Parameters.begin();
MaterialParameterList::iterator end = m_Parameters.end();
while (iter != end)
{
ExportMaterialParameter& param = *iter;
if (param.Name == strName)
return ¶m;
++iter;
}
return nullptr;
}
ExportString ExportMaterial::GetDefaultDiffuseMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultDiffuseMapTextureName);
}
ExportString ExportMaterial::GetDefaultNormalMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultNormalMapTextureName);
}
ExportString ExportMaterial::GetDefaultSpecularMapTextureName()
{
return ExportString(g_ExportCoreSettings.strDefaultSpecMapTextureName);
}
| 26 | 88 | 0.639805 | walbourn |
6ad1d9211afa891af4726132a404a8fd65ccf94f | 1,012 | cpp | C++ | Client/ui/AddFriendWidget.cpp | LiardeauxQ/Babel | 6cdd475b8947f6a8b0d1c4325a06dfd9bfa65e72 | [
"MIT"
] | 1 | 2020-02-12T12:02:19.000Z | 2020-02-12T12:02:19.000Z | Client/ui/AddFriendWidget.cpp | LiardeauxQ/Babel | 6cdd475b8947f6a8b0d1c4325a06dfd9bfa65e72 | [
"MIT"
] | null | null | null | Client/ui/AddFriendWidget.cpp | LiardeauxQ/Babel | 6cdd475b8947f6a8b0d1c4325a06dfd9bfa65e72 | [
"MIT"
] | 3 | 2020-02-12T12:02:22.000Z | 2021-10-11T11:00:24.000Z | //
// Created by Quentin Liardeaux on 10/5/19.
//
#include "AddFriendWidget.hpp"
ui::AddFriendWidget::AddFriendWidget(boost::shared_ptr<NotificationHandler> notifHandler, QWidget *parent) :
QWidget(parent),
notifHandler_(notifHandler) {
QPointer<QPushButton> closeButton = new QPushButton(tr("Close"));
usernameLineEdit_ = QSharedPointer<QLineEdit>(new QLineEdit());
QPointer<QLabel> usernameLabel = new QLabel(tr("Username:"));
QPointer<QLabel> passwordLabel = new QLabel(tr("Password:"));
connect(closeButton, SIGNAL(clicked()), this, SLOT(closeTap()));
QPointer<QFormLayout> formLayout = new QFormLayout();
formLayout->addRow(closeButton);
formLayout->addRow(usernameLabel, usernameLineEdit_.get());
setLayout(formLayout);
setWindowTitle(tr("Add a friend"));
}
void ui::AddFriendWidget::closeTap()
{
for (auto action : actions()) {
if (action->text() == "close") {
action->trigger();
break;
}
}
}
| 28.111111 | 108 | 0.667984 | LiardeauxQ |
6adacd1f82fbc5257518e3fdd8e3acf6d3ba7bf5 | 430 | cpp | C++ | mts/write-after-reclaim-stack.cpp | comparch-security/cpu-sec-bench | 34506323a80637fae2a4d2add3bbbdaa4e6d8473 | [
"MIT"
] | 4 | 2021-11-12T03:41:54.000Z | 2022-02-28T12:23:49.000Z | mts/write-after-reclaim-stack.cpp | comparch-security/cpu-sec-bench | 34506323a80637fae2a4d2add3bbbdaa4e6d8473 | [
"MIT"
] | null | null | null | mts/write-after-reclaim-stack.cpp | comparch-security/cpu-sec-bench | 34506323a80637fae2a4d2add3bbbdaa4e6d8473 | [
"MIT"
] | 1 | 2021-11-29T08:38:28.000Z | 2021-11-29T08:38:28.000Z | #include "include/gcc_builtin.hpp"
#include "include/mss.hpp"
charBuffer *pb;
int FORCE_NOINLINE helper(bool option) {
charBuffer buffer;
if(option) {
update_by_pointer(pb->data, 0, 8, 1, 'c');
return check(buffer.data, 7, 1, 'c');
} else {
pb = &buffer;
char_buffer_init(&buffer, 'u', 'd', 'o');
return 0;
}
}
int main() {
int rv0 = helper(false);
int rv1 = helper(true);
return rv0+rv1;
}
| 18.695652 | 47 | 0.613953 | comparch-security |
6adada53107ff342115844eddbf6e87ec8bc54a7 | 5,844 | cc | C++ | test/av1_fht4x8_test.cc | merryApple/aom | 7b88ade6135ed4fecd6d745166ce74209ff137de | [
"BSD-2-Clause"
] | null | null | null | test/av1_fht4x8_test.cc | merryApple/aom | 7b88ade6135ed4fecd6d745166ce74209ff137de | [
"BSD-2-Clause"
] | 4 | 2018-01-12T14:03:23.000Z | 2018-01-15T11:23:08.000Z | test/av1_fht4x8_test.cc | merryApple/aom | 7b88ade6135ed4fecd6d745166ce74209ff137de | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2016, Alliance for Open Media. All rights reserved
*
* This source code is subject to the terms of the BSD 2 Clause License and
* the Alliance for Open Media Patent License 1.0. If the BSD 2 Clause License
* was not distributed with this source code in the LICENSE file, you can
* obtain it at www.aomedia.org/license/software. If the Alliance for Open
* Media Patent License 1.0 was not distributed with this source code in the
* PATENTS file, you can obtain it at www.aomedia.org/license/patent.
*/
#include "third_party/googletest/src/googletest/include/gtest/gtest.h"
#include "./aom_dsp_rtcd.h"
#include "./av1_rtcd.h"
#include "aom_ports/mem.h"
#include "test/acm_random.h"
#include "test/clear_system_state.h"
#include "test/register_state_check.h"
#include "test/transform_test_base.h"
#include "test/util.h"
using libaom_test::ACMRandom;
#if !CONFIG_DAALA_TX
namespace {
typedef void (*IhtFunc)(const tran_low_t *in, uint8_t *out, int stride,
const TxfmParam *txfm_param);
using std::tr1::tuple;
using libaom_test::FhtFunc;
typedef tuple<FhtFunc, IhtFunc, TX_TYPE, aom_bit_depth_t, int> Ht4x8Param;
void fht4x8_ref(const int16_t *in, tran_low_t *out, int stride,
TxfmParam *txfm_param) {
av1_fht4x8_c(in, out, stride, txfm_param);
}
void iht4x8_ref(const tran_low_t *in, uint8_t *out, int stride,
const TxfmParam *txfm_param) {
av1_iht4x8_32_add_c(in, out, stride, txfm_param);
}
class AV1Trans4x8HT : public libaom_test::TransformTestBase,
public ::testing::TestWithParam<Ht4x8Param> {
public:
virtual ~AV1Trans4x8HT() {}
virtual void SetUp() {
fwd_txfm_ = GET_PARAM(0);
inv_txfm_ = GET_PARAM(1);
pitch_ = 4;
height_ = 8;
fwd_txfm_ref = fht4x8_ref;
inv_txfm_ref = iht4x8_ref;
bit_depth_ = GET_PARAM(3);
mask_ = (1 << bit_depth_) - 1;
num_coeffs_ = GET_PARAM(4);
txfm_param_.tx_type = GET_PARAM(2);
}
virtual void TearDown() { libaom_test::ClearSystemState(); }
protected:
void RunFwdTxfm(const int16_t *in, tran_low_t *out, int stride) {
fwd_txfm_(in, out, stride, &txfm_param_);
}
void RunInvTxfm(const tran_low_t *out, uint8_t *dst, int stride) {
inv_txfm_(out, dst, stride, &txfm_param_);
}
FhtFunc fwd_txfm_;
IhtFunc inv_txfm_;
};
TEST_P(AV1Trans4x8HT, AccuracyCheck) { RunAccuracyCheck(0, 0.00001); }
TEST_P(AV1Trans4x8HT, CoeffCheck) { RunCoeffCheck(); }
TEST_P(AV1Trans4x8HT, MemCheck) { RunMemCheck(); }
TEST_P(AV1Trans4x8HT, InvCoeffCheck) { RunInvCoeffCheck(); }
TEST_P(AV1Trans4x8HT, InvAccuracyCheck) { RunInvAccuracyCheck(0); }
using std::tr1::make_tuple;
const Ht4x8Param kArrayHt4x8Param_c[] = {
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, DCT_FLIPADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, ADST_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, FLIPADST_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, IDTX, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, V_FLIPADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_c, &av1_iht4x8_32_add_c, H_FLIPADST, AOM_BITS_8, 32)
};
INSTANTIATE_TEST_CASE_P(C, AV1Trans4x8HT,
::testing::ValuesIn(kArrayHt4x8Param_c));
#if HAVE_SSE2
const Ht4x8Param kArrayHt4x8Param_sse2[] = {
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_DCT, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_DCT, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_ADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_DCT,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, DCT_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, ADST_FLIPADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, FLIPADST_ADST,
AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, IDTX, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_DCT, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_ADST, AOM_BITS_8, 32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, V_FLIPADST, AOM_BITS_8,
32),
make_tuple(&av1_fht4x8_sse2, &av1_iht4x8_32_add_sse2, H_FLIPADST, AOM_BITS_8,
32)
};
INSTANTIATE_TEST_CASE_P(SSE2, AV1Trans4x8HT,
::testing::ValuesIn(kArrayHt4x8Param_sse2));
#endif // HAVE_SSE2
} // namespace
#endif // !CONFIG_DAALA_TX
| 40.583333 | 80 | 0.729295 | merryApple |
6adc5c6f9685980e5ab2bd50c57d40ba678fc667 | 143 | cpp | C++ | mia/medium/msx2.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 153 | 2020-07-25T17:55:29.000Z | 2021-10-01T23:45:01.000Z | mia/medium/msx2.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 245 | 2021-10-08T09:14:46.000Z | 2022-03-31T08:53:13.000Z | mia/medium/msx2.cpp | CasualPokePlayer/ares | 58690cd5fc7bb6566c22935c5b80504a158cca29 | [
"BSD-3-Clause"
] | 44 | 2020-07-25T08:51:55.000Z | 2021-09-25T16:09:01.000Z | struct MSX2 : MSX {
auto name() -> string override { return "MSX2"; }
auto extensions() -> vector<string> override { return {"msx2"}; }
};
| 28.6 | 67 | 0.622378 | CasualPokePlayer |
6addb3c8282a4d539b49e5278c83561633f72aad | 2,405 | cpp | C++ | platform/switch/godot_switch.cpp | ryancheung/godot | 39c52e45d330cf4eb5558d06e005b3d4ab2a08d2 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | platform/switch/godot_switch.cpp | ryancheung/godot | 39c52e45d330cf4eb5558d06e005b3d4ab2a08d2 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | platform/switch/godot_switch.cpp | ryancheung/godot | 39c52e45d330cf4eb5558d06e005b3d4ab2a08d2 | [
"CC-BY-3.0",
"Apache-2.0",
"MIT"
] | null | null | null | #include "switch_wrapper.h"
#include <limits.h>
#include <locale.h>
#include <stdlib.h>
#include <unistd.h>
#include <zlib.h>
#include "main/main.h"
#include "os_switch.h"
#define FB_WIDTH 1280
#define FB_HEIGHT 720
int main(int argc, char *argv[])
{
socketInitializeDefault();
nxlinkStdio();
int apptype = appletGetAppletType();
if(apptype != AppletType_Application && apptype != AppletType_SystemApplication)
{
romfsInit();
NWindow* win = nwindowGetDefault();
Framebuffer fb;
framebufferCreate(&fb, win, FB_WIDTH, FB_HEIGHT, PIXEL_FORMAT_RGBA_8888, 1);
framebufferMakeLinear(&fb);
u32 stride;
u32* framebuf = (u32*) framebufferBegin(&fb, &stride);
FILE *splash = fopen("romfs:/applet_splash.rgba.gz", "rb");
if(splash)
{
fseek(splash, 0, SEEK_END);
size_t splash_size = ftell(splash);
u8 *compressed_splash = (u8*)malloc(splash_size);
memset(compressed_splash, 0, splash_size);
fseek(splash, 0, SEEK_SET);
size_t amt_read = fread(compressed_splash, 1, splash_size, splash);
fclose(splash);
memset(framebuf, 0, stride * FB_HEIGHT);
struct z_stream_s stream;
memset(&stream, 0, sizeof(stream));
stream.zalloc = NULL;
stream.zfree = NULL;
stream.next_in = compressed_splash;
stream.avail_in = splash_size;
stream.next_out = (u8*)framebuf;
stream.avail_out = stride * FB_HEIGHT;
if(inflateInit2(&stream, 16+MAX_WBITS) == Z_OK)
{
int err = 0;
if((err = inflate(&stream, 0)) != Z_STREAM_END)
{
// idk
}
inflateEnd(&stream);
}
}
else
{
// this REALLY shouldn't fail. Hm.
}
framebufferEnd(&fb);
while(appletMainLoop())
{
hidScanInput();
if(hidKeysDown(CONTROLLER_P1_AUTO) &
~(KEY_TOUCH|
KEY_LSTICK_LEFT|KEY_LSTICK_RIGHT|
KEY_LSTICK_UP|KEY_LSTICK_DOWN|
KEY_RSTICK_LEFT|KEY_RSTICK_RIGHT|
KEY_RSTICK_UP|KEY_RSTICK_DOWN))
{
break;
}
}
framebufferClose(&fb);
romfsExit();
socketExit();
return 0;
}
OS_Switch os;
os.set_executable_path(argv[0]);
char *cwd = (char *)malloc(PATH_MAX);
getcwd(cwd, PATH_MAX);
Error err = Main::setup(argv[0], argc - 1, &argv[1]);
if (err != OK) {
free(cwd);
socketExit();
return 255;
}
if (Main::start())
{
os.run(); // it is actually the OS that decides how to run
}
Main::cleanup();
chdir(cwd);
free(cwd);
socketExit();
return os.get_exit_code();
}
| 19.552846 | 81 | 0.661538 | ryancheung |
6ae6a7e0e48180369557b67610a597b9a1dc3d7e | 35 | hpp | C++ | src/boost_mpl_erase_key.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 10 | 2018-03-17T00:58:42.000Z | 2021-07-06T02:48:49.000Z | src/boost_mpl_erase_key.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 2 | 2021-03-26T15:17:35.000Z | 2021-05-20T23:55:08.000Z | src/boost_mpl_erase_key.hpp | miathedev/BoostForArduino | 919621dcd0c157094bed4df752b583ba6ea6409e | [
"BSL-1.0"
] | 4 | 2019-05-28T21:06:37.000Z | 2021-07-06T03:06:52.000Z | #include <boost/mpl/erase_key.hpp>
| 17.5 | 34 | 0.771429 | miathedev |
6aea3a9622f0284b176a7c00991e70f413a9a702 | 21,305 | hpp | C++ | include/UnityEngine/TouchScreenKeyboard.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/UnityEngine/TouchScreenKeyboard.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | include/UnityEngine/TouchScreenKeyboard.hpp | Fernthedev/BeatSaber-Quest-Codegen | 716e4ff3f8608f7ed5b83e2af3be805f69e26d9e | [
"Unlicense"
] | null | null | null | // Autogenerated from CppHeaderCreator
// Created by Sc2ad
// =========================================================================
#pragma once
// Begin includes
#include "extern/beatsaber-hook/shared/utils/typedefs.h"
#include "extern/beatsaber-hook/shared/utils/byref.hpp"
// Including type: System.IntPtr
#include "System/IntPtr.hpp"
// Including type: UnityEngine.TouchScreenKeyboardType
#include "UnityEngine/TouchScreenKeyboardType.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp"
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp"
#include "extern/beatsaber-hook/shared/utils/utils.h"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: RangeInt
struct RangeInt;
// Forward declaring type: TouchScreenKeyboard_InternalConstructorHelperArguments
struct TouchScreenKeyboard_InternalConstructorHelperArguments;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Size: 0x18
#pragma pack(push, 1)
// Autogenerated type: UnityEngine.TouchScreenKeyboard
// [TokenAttribute] Offset: FFFFFFFF
// [NativeHeaderAttribute] Offset: DB5D48
// [NativeConditionalAttribute] Offset: DB5D48
// [NativeHeaderAttribute] Offset: DB5D48
class TouchScreenKeyboard : public ::Il2CppObject {
public:
// Nested type: UnityEngine::TouchScreenKeyboard::Status
struct Status;
// System.IntPtr m_Ptr
// Size: 0x8
// Offset: 0x10
System::IntPtr m_Ptr;
// Field size check
static_assert(sizeof(System::IntPtr) == 0x8);
// Creating value type constructor for type: TouchScreenKeyboard
TouchScreenKeyboard(System::IntPtr m_Ptr_ = {}) noexcept : m_Ptr{m_Ptr_} {}
// Creating conversion operator: operator System::IntPtr
constexpr operator System::IntPtr() const noexcept {
return m_Ptr;
}
// Get instance field reference: System.IntPtr m_Ptr
System::IntPtr& dyn_m_Ptr();
// static public System.Boolean get_isSupported()
// Offset: 0x235B8D8
static bool get_isSupported();
// static public System.Boolean get_isInPlaceEditingAllowed()
// Offset: 0x235B960
static bool get_isInPlaceEditingAllowed();
// public System.String get_text()
// Offset: 0x235BABC
::Il2CppString* get_text();
// public System.Void set_text(System.String value)
// Offset: 0x235BAFC
void set_text(::Il2CppString* value);
// static public System.Void set_hideInput(System.Boolean value)
// Offset: 0x235BB4C
static void set_hideInput(bool value);
// public System.Boolean get_active()
// Offset: 0x235BB8C
bool get_active();
// public System.Void set_active(System.Boolean value)
// Offset: 0x235BBCC
void set_active(bool value);
// public UnityEngine.TouchScreenKeyboard/UnityEngine.Status get_status()
// Offset: 0x235BC1C
UnityEngine::TouchScreenKeyboard::Status get_status();
// public System.Void set_characterLimit(System.Int32 value)
// Offset: 0x235BC5C
void set_characterLimit(int value);
// public System.Boolean get_canGetSelection()
// Offset: 0x235BCAC
bool get_canGetSelection();
// public System.Boolean get_canSetSelection()
// Offset: 0x235BCEC
bool get_canSetSelection();
// public UnityEngine.RangeInt get_selection()
// Offset: 0x235BD2C
UnityEngine::RangeInt get_selection();
// public System.Void set_selection(UnityEngine.RangeInt value)
// Offset: 0x235BDD8
void set_selection(UnityEngine::RangeInt value);
// public System.Void .ctor(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure, System.Boolean alert, System.String textPlaceholder, System.Int32 characterLimit)
// Offset: 0x235B71C
template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary>
static TouchScreenKeyboard* New_ctor(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, ::Il2CppString* textPlaceholder, int characterLimit) {
static auto ___internal__logger = ::Logger::get().WithContext("UnityEngine::TouchScreenKeyboard::.ctor");
return THROW_UNLESS((::il2cpp_utils::New<TouchScreenKeyboard*, creationType>(text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit)));
}
// static private System.Void Internal_Destroy(System.IntPtr ptr)
// Offset: 0x235B5C0
static void Internal_Destroy(System::IntPtr ptr);
// private System.Void Destroy()
// Offset: 0x235B600
void Destroy();
// static private System.IntPtr TouchScreenKeyboard_InternalConstructorHelper(ref UnityEngine.TouchScreenKeyboard_InternalConstructorHelperArguments arguments, System.String text, System.String textPlaceholder)
// Offset: 0x235B880
static System::IntPtr TouchScreenKeyboard_InternalConstructorHelper(ByRef<UnityEngine::TouchScreenKeyboard_InternalConstructorHelperArguments> arguments, ::Il2CppString* text, ::Il2CppString* textPlaceholder);
// static public UnityEngine.TouchScreenKeyboard Open(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure, System.Boolean alert, System.String textPlaceholder, System.Int32 characterLimit)
// Offset: 0x235B968
static UnityEngine::TouchScreenKeyboard* Open(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure, bool alert, ::Il2CppString* textPlaceholder, int characterLimit);
// static public UnityEngine.TouchScreenKeyboard Open(System.String text, UnityEngine.TouchScreenKeyboardType keyboardType, System.Boolean autocorrection, System.Boolean multiline, System.Boolean secure)
// Offset: 0x235BA28
static UnityEngine::TouchScreenKeyboard* Open(::Il2CppString* text, UnityEngine::TouchScreenKeyboardType keyboardType, bool autocorrection, bool multiline, bool secure);
// static private System.Void GetSelection(out System.Int32 start, out System.Int32 length)
// Offset: 0x235BD88
static void GetSelection(ByRef<int> start, ByRef<int> length);
// static private System.Void SetSelection(System.Int32 start, System.Int32 length)
// Offset: 0x235BEE0
static void SetSelection(int start, int length);
// protected override System.Void Finalize()
// Offset: 0x235B6B4
// Implemented from: System.Object
// Base method: System.Void Object::Finalize()
void Finalize();
}; // UnityEngine.TouchScreenKeyboard
#pragma pack(pop)
static check_size<sizeof(TouchScreenKeyboard), 16 + sizeof(System::IntPtr)> __UnityEngine_TouchScreenKeyboardSizeCheck;
static_assert(sizeof(TouchScreenKeyboard) == 0x18);
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::TouchScreenKeyboard*, "UnityEngine", "TouchScreenKeyboard");
#include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp"
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_isSupported
// Il2CppName: get_isSupported
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::TouchScreenKeyboard::get_isSupported)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_isSupported", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_isInPlaceEditingAllowed
// Il2CppName: get_isInPlaceEditingAllowed
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (*)()>(&UnityEngine::TouchScreenKeyboard::get_isInPlaceEditingAllowed)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_isInPlaceEditingAllowed", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_text
// Il2CppName: get_text
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<::Il2CppString* (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_text)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_text
// Il2CppName: set_text
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(::Il2CppString*)>(&UnityEngine::TouchScreenKeyboard::set_text)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_text", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_hideInput
// Il2CppName: set_hideInput
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(bool)>(&UnityEngine::TouchScreenKeyboard::set_hideInput)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_hideInput", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_active
// Il2CppName: get_active
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_active)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_active", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_active
// Il2CppName: set_active
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(bool)>(&UnityEngine::TouchScreenKeyboard::set_active)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_active", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_status
// Il2CppName: get_status
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard::Status (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_status)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_status", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_characterLimit
// Il2CppName: set_characterLimit
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(int)>(&UnityEngine::TouchScreenKeyboard::set_characterLimit)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_characterLimit", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_canGetSelection
// Il2CppName: get_canGetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_canGetSelection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_canGetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_canSetSelection
// Il2CppName: get_canSetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<bool (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_canSetSelection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_canSetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::get_selection
// Il2CppName: get_selection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::RangeInt (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::get_selection)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "get_selection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::set_selection
// Il2CppName: set_selection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)(UnityEngine::RangeInt)>(&UnityEngine::TouchScreenKeyboard::set_selection)> {
static const MethodInfo* get() {
static auto* value = &::il2cpp_utils::GetClassFromName("UnityEngine", "RangeInt")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "set_selection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{value});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::New_ctor
// Il2CppName: .ctor
// Cannot get method pointer of value based method overload from template for constructor!
// Try using FindMethod instead!
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Internal_Destroy
// Il2CppName: Internal_Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(System::IntPtr)>(&UnityEngine::TouchScreenKeyboard::Internal_Destroy)> {
static const MethodInfo* get() {
static auto* ptr = &::il2cpp_utils::GetClassFromName("System", "IntPtr")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Internal_Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{ptr});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Destroy
// Il2CppName: Destroy
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::Destroy)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Destroy", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::TouchScreenKeyboard_InternalConstructorHelper
// Il2CppName: TouchScreenKeyboard_InternalConstructorHelper
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<System::IntPtr (*)(ByRef<UnityEngine::TouchScreenKeyboard_InternalConstructorHelperArguments>, ::Il2CppString*, ::Il2CppString*)>(&UnityEngine::TouchScreenKeyboard::TouchScreenKeyboard_InternalConstructorHelper)> {
static const MethodInfo* get() {
static auto* arguments = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboard_InternalConstructorHelperArguments")->this_arg;
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* textPlaceholder = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "TouchScreenKeyboard_InternalConstructorHelper", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{arguments, text, textPlaceholder});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard* (*)(::Il2CppString*, UnityEngine::TouchScreenKeyboardType, bool, bool, bool, bool, ::Il2CppString*, int)>(&UnityEngine::TouchScreenKeyboard::Open)> {
static const MethodInfo* get() {
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* keyboardType = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboardType")->byval_arg;
static auto* autocorrection = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* multiline = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* secure = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* alert = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* textPlaceholder = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* characterLimit = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{text, keyboardType, autocorrection, multiline, secure, alert, textPlaceholder, characterLimit});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Open
// Il2CppName: Open
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<UnityEngine::TouchScreenKeyboard* (*)(::Il2CppString*, UnityEngine::TouchScreenKeyboardType, bool, bool, bool)>(&UnityEngine::TouchScreenKeyboard::Open)> {
static const MethodInfo* get() {
static auto* text = &::il2cpp_utils::GetClassFromName("System", "String")->byval_arg;
static auto* keyboardType = &::il2cpp_utils::GetClassFromName("UnityEngine", "TouchScreenKeyboardType")->byval_arg;
static auto* autocorrection = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* multiline = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
static auto* secure = &::il2cpp_utils::GetClassFromName("System", "Boolean")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Open", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{text, keyboardType, autocorrection, multiline, secure});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::GetSelection
// Il2CppName: GetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(ByRef<int>, ByRef<int>)>(&UnityEngine::TouchScreenKeyboard::GetSelection)> {
static const MethodInfo* get() {
static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->this_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "GetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{start, length});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::SetSelection
// Il2CppName: SetSelection
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (*)(int, int)>(&UnityEngine::TouchScreenKeyboard::SetSelection)> {
static const MethodInfo* get() {
static auto* start = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
static auto* length = &::il2cpp_utils::GetClassFromName("System", "Int32")->byval_arg;
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "SetSelection", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{start, length});
}
};
// Writing MetadataGetter for method: UnityEngine::TouchScreenKeyboard::Finalize
// Il2CppName: Finalize
template<>
struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<void (UnityEngine::TouchScreenKeyboard::*)()>(&UnityEngine::TouchScreenKeyboard::Finalize)> {
static const MethodInfo* get() {
return ::il2cpp_utils::FindMethod(classof(UnityEngine::TouchScreenKeyboard*), "Finalize", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{});
}
};
| 64.560606 | 290 | 0.751936 | Fernthedev |
6aeb0a76c41d41c7ea33721bd2927145d84513e9 | 515 | cpp | C++ | TextRPG/src/UIScreen.cpp | UniqueVN/TextRPG | 78c585a61692c8470145d755d2da3f1a3586af88 | [
"MIT",
"Unlicense"
] | 1 | 2021-03-12T09:47:20.000Z | 2021-03-12T09:47:20.000Z | TextRPG/src/UIScreen.cpp | UniqueVN/TextRPG | 78c585a61692c8470145d755d2da3f1a3586af88 | [
"MIT",
"Unlicense"
] | null | null | null | TextRPG/src/UIScreen.cpp | UniqueVN/TextRPG | 78c585a61692c8470145d755d2da3f1a3586af88 | [
"MIT",
"Unlicense"
] | null | null | null | #include "UIComponent.h"
#include "UIManager.h"
#include "UIScreen.h"
UIScreen::UIScreen(UIComponent* parent) : UIComponent(parent)
{
// Register this screen with the UIManager
}
UIScreen::~UIScreen(void)
{
}
void UIScreen::OnInit()
{
UIComponent::OnInit();
UIManager* manager = UIManager::GetInstance();
manager->RegisterScreen(this);
// Auto make the screen align to the top-left of the screen if its position not specified
if (Pos == vector2i(-1, -1))
Pos = vector2i(0, 0);
} | 21.458333 | 93 | 0.679612 | UniqueVN |
6aef6a491cb032857999c179347498c293e0705b | 734 | hpp | C++ | ares/fc/fds/drive.hpp | moon-chilled/Ares | 909fb098c292f8336d0502dc677050312d8b5c81 | [
"0BSD"
] | 7 | 2020-07-25T11:44:39.000Z | 2021-01-29T13:21:31.000Z | ares/fc/fds/drive.hpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | null | null | null | ares/fc/fds/drive.hpp | jchw-forks/ares | d78298a1e95fd0ce65feabfd4f13b60e31210a7a | [
"0BSD"
] | 1 | 2021-03-22T16:15:30.000Z | 2021-03-22T16:15:30.000Z | struct FDSDrive {
auto clock() -> void;
auto change() -> void;
auto powerup() -> void;
auto rewind() -> void;
auto advance() -> void;
auto crc(uint8 data) -> void;
auto read() -> void;
auto write() -> void;
auto read(uint16 address, uint8 data) -> uint8;
auto write(uint16 address, uint8 data) -> void;
//serialization.cpp
auto serialize(serializer&) -> void;
uint1 enable;
uint1 power;
uint1 changing;
uint1 ready;
uint1 scan;
uint1 rewinding;
uint1 scanning;
uint1 reading; //0 = writing
uint1 writeCRC;
uint1 clearCRC;
uint1 irq;
uint1 pending;
uint1 available;
uint32 counter;
uint32 offset;
uint1 gap;
uint8 data;
uint1 completed;
uint16 crc16;
};
| 20.388889 | 49 | 0.640327 | moon-chilled |
6af4d646d3dd17f02a38d84f06fba84c3a9550ee | 12,441 | cpp | C++ | lib/test/AMRElliptic/testBiCGStab.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 10 | 2018-02-01T20:57:36.000Z | 2022-03-17T02:57:49.000Z | lib/test/AMRElliptic/testBiCGStab.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 19 | 2018-10-04T21:37:18.000Z | 2022-02-25T16:20:11.000Z | lib/test/AMRElliptic/testBiCGStab.cpp | rmrsk/Chombo-3.3 | f2119e396460c1bb19638effd55eb71c2b35119e | [
"BSD-3-Clause-LBNL"
] | 11 | 2019-01-12T23:33:32.000Z | 2021-08-09T15:19:50.000Z | #ifdef CH_LANG_CC
/*
* _______ __
* / ___/ / ___ __ _ / / ___
* / /__/ _ \/ _ \/ V \/ _ \/ _ \
* \___/_//_/\___/_/_/_/_.__/\___/
* Please refer to Copyright.txt, in Chombo's root directory.
*/
#endif
#include <iostream>
using std::endl;
#include "BRMeshRefine.H"
#include "LoadBalance.H"
#include "CH_HDF5.H"
#include "parstream.H"
#include "BoxIterator.H"
#include "FABView.H"
#include "NewPoissonOp.H"
#include "AMRPoissonOp.H"
#include "BCFunc.H"
#include "BiCGStabSolver.H"
#include "RelaxSolver.H"
#include "UsingNamespace.H"
/// Global variables for handling output:
static const char* pgmname = "testBiCGStab" ;
static const char* indent = " ";
static const char* indent2 = " " ;
static bool verbose = true ;
///
// Parse the standard test options (-v -q) out of the command line.
///
void
parseTestOptions( int argc ,char* argv[] )
{
for ( int i = 1 ; i < argc ; ++i )
{
if ( argv[i][0] == '-' ) //if it is an option
{
// compare 3 chars to differentiate -x from -xx
if ( strncmp( argv[i] ,"-v" ,3 ) == 0 )
{
verbose = true ;
// argv[i] = "" ;
}
else if ( strncmp( argv[i] ,"-q" ,3 ) == 0 )
{
verbose = false ;
// argv[i] = "" ;
}
}
}
return ;
}
// u = x*x + y*y + z*z
// du/dx = 2*x
// du/dy = 2*y
// du/dz = 2*z
// Laplace(u) = 2*CH_SPACEDIM
// #define __USE_GNU
// #include <fenv.h>
// #undef __USE_GNU
//static Box domain = Box(IntVect(D_DECL(-64,-64,-64)), IntVect(D_DECL(63,63,63)));
static Box domain = Box(IntVect(D_DECL(0,0,0)), IntVect(D_DECL(63,63,63)));
static Real dx = 0.0125;
static int blockingFactor = 8;
static Real xshift = 0.0;
int
testBiCGStab();
int
main(int argc ,char* argv[])
{
#ifdef CH_MPI
MPI_Init (&argc, &argv);
#endif
// int except = FE_DIVBYZERO | FE_UNDERFLOW | FE_OVERFLOW | FE_INVALID ;
// feenableexcept(except);
parseTestOptions( argc ,argv ) ;
if ( verbose )
pout () << indent2 << "Beginning " << pgmname << " ..." << endl ;
int overallStatus = 0;
int status = testBiCGStab();
if ( status == 0 )
{
pout() << indent << pgmname << " passed." << endl ;
}
else
{
overallStatus = 1;
pout() << indent << pgmname << " failed with return code " << status << endl ;
}
xshift = 0.2;
blockingFactor = 4;
status = testBiCGStab();
if ( status == 0 )
{
pout() << indent << pgmname << " passed." << endl ;
}
else
{
overallStatus = 1;
pout() << indent << pgmname << " failed with return code " << status << endl ;
}
#ifdef CH_MPI
MPI_Finalize ();
#endif
return overallStatus;
}
extern "C"
{
void Parabola_neum(Real* pos,
int* dir,
Side::LoHiSide* side,
Real* a_values)
{
switch (*dir)
{
case 0:
a_values[0]=2.*(pos[0]-xshift);
return;
case 1:
a_values[0]=2.*pos[1];
return;
case 2:
a_values[0]=2.*pos[2];
return;
default:
MayDay::Error("no such dimension");
};
}
void Parabola_diri(Real* pos,
int* dir,
Side::LoHiSide* side,
Real* a_values)
{
a_values[0] = D_TERM((pos[0]-xshift)*(pos[0]-xshift),+pos[1]*pos[1],+pos[2]*pos[2]);
}
void DirParabolaBC(FArrayBox& a_state,
const Box& valid,
const ProblemDomain& a_domain,
Real a_dx,
bool a_homogeneous)
{
for (int i=0; i<CH_SPACEDIM; ++i)
{
DiriBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_diri,
i,
Side::Lo);
DiriBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_diri,
i,
Side::Hi);
}
}
void NeumParabolaBC(FArrayBox& a_state,
const ProblemDomain& a_domain,
Real a_dx,
bool a_homogeneous)
{
Box valid = a_state.box();
valid.grow(-1);
for (int i=0; i<CH_SPACEDIM; ++i)
{
NeumBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_neum,
i,
Side::Lo);
NeumBC(a_state,
valid,
dx,
a_homogeneous,
Parabola_neum,
i,
Side::Hi);
}
}
}
static BCValueFunc pointFunc = Parabola_diri;
void parabola(const Box& box, int comps, FArrayBox& t)
{
RealVect pos;
Side::LoHiSide side;
int dir;
int num = 1;
ForAllXBNN(Real,t, box, 0, comps)
{
num=nR;
D_TERM(pos[0]=dx*(iR+0.5);, pos[1]=dx*(jR+0.5);, pos[2]=dx*(kR+0.5));
pointFunc(&(pos[0]), &dir, &side, &tR);
}EndFor;
}
void makeGrids(DisjointBoxLayout& a_dbl, const Box& a_domain)
{
BRMeshRefine br;
Box domain = a_domain;
domain.coarsen(blockingFactor);
domain.refine(blockingFactor);
CH_assert(domain == a_domain);
domain.coarsen(blockingFactor);
ProblemDomain junk(domain);
IntVectSet pnd(domain);
IntVectSet tags;
for (BoxIterator bit(domain); bit.ok(); ++bit)
{
const IntVect& iv = bit();
if (D_TERM(true, && iv[1]< 2*iv[0] && iv[1]>iv[0]/2, && iv[2] < domain.bigEnd(2)/2))
{
tags|=iv;
}
}
Vector<Box> boxes;
br.makeBoxes(boxes, tags, pnd, junk, 32/blockingFactor, 1);
Vector<int> procs;
LoadBalance(procs, boxes);
for (int i=0; i<boxes.size(); ++i) boxes[i].refine(blockingFactor);
a_dbl.define(boxes, procs);
}
struct setvalue
{
static Real val;
static void setFunc(const Box& box,
int comps, FArrayBox& t)
{
t.setVal(val);
}
};
Real setvalue::val = 0;
int
testBiCGStab()
{
ProblemDomain regularDomain(domain);
pout()<<"\n GSRB unigrid solver \n";
// GSRB single grid solver test
{
Box phiBox = domain;
phiBox.grow(1);
FArrayBox phi(phiBox, 1);
FArrayBox rhs(domain, 1);
FArrayBox error(domain, 1);
FArrayBox phi_exact(domain, 1);
FArrayBox residual(domain, 1);
FArrayBox correction(phiBox, 1);
phi.setVal(0.0);
correction.setVal(0.0);
rhs.setVal(2*CH_SPACEDIM);
parabola(domain, 1, phi_exact);
RealVect pos(IntVect::Unit);
pos*=dx;
NewPoissonOp op;
op.define(pos, regularDomain, DirParabolaBC);
for (int i=0; i<15; ++i)
{
op.residual(residual, phi, rhs);
Real rnorm = residual.norm();
op.preCond(correction, residual);
op.incr(phi, correction, 1.0);
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<"Residual L2 norm "<<rnorm<<" Error max norm = "
<<norm<<std::endl;
}
}
pout()<<"\n unigrid solver \n";
// single grid solver test
{
Box phiBox = domain;
phiBox.grow(1);
FArrayBox phi(phiBox, 1);
FArrayBox rhs(domain, 1);
FArrayBox error(domain, 1);
FArrayBox phi_exact(domain, 1);
FArrayBox residual(domain, 1);
FArrayBox correction(phiBox, 1);
phi.setVal(0.0);
rhs.setVal(2*CH_SPACEDIM);
parabola(domain, 1, phi_exact);
RealVect pos(IntVect::Unit);
pos*=dx;
NewPoissonOp op;
op.define(pos, regularDomain, DirParabolaBC);
BiCGStabSolver<FArrayBox> solver;
solver.define(&op, true);
int iter = 1;
pout()<< "homogeneous solver mode : solver.solve(correction, reisdual)\n"
<< "solver.i_max= "<<solver.m_imax<<" iter = "<<iter<<std::endl;
op.residual(residual, phi, rhs);
Real rnorm = residual.norm();
pout()<<"initial residual "<<rnorm<<"\n";
for (int i=0; i<iter; ++i)
{
correction.setVal(0.0);
solver.solve(correction, residual);
op.incr(phi, correction, 1);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<"residual L2 norm "<< rnorm
<<" Error max norm = "<<norm<<std::endl;
}
pout()<< "\n\n inhomogeneous solver mode : solver.solve(a_phi, a_rhs)\n"<<std::endl;
solver.setHomogeneous(false);
op.scale(phi, 0.0);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
pout()<<"initial residual "<<rnorm<<"\n";
for (int i=0; i<iter; ++i)
{
solver.solve(phi, rhs);
op.residual(residual, phi, rhs);
rnorm = residual.norm();
op.axby(error, phi, phi_exact, 1, -1);
Real norm = error.norm(0);
pout()<<indent<<" residual L2 norm "<< rnorm
<<" Error max norm = "<<norm<<std::endl;
}
}
pout()<<"\n level solver \n";
// Level solve
{
DisjointBoxLayout dbl;
makeGrids(dbl, domain);
dbl.close();
DataIterator dit(dbl);
LevelData<FArrayBox> phi(dbl, 1, IntVect::Unit);
LevelData<FArrayBox> correction(dbl, 1, IntVect::Unit);
LevelData<FArrayBox> phi_exact(dbl, 1);
LevelData<FArrayBox> error(dbl, 1);
LevelData<FArrayBox> rhs(dbl, 1);
LevelData<FArrayBox> residual(dbl, 1);
setvalue::val = 2*CH_SPACEDIM;
rhs.apply(setvalue::setFunc);
setvalue::val = 0;
phi.apply(setvalue::setFunc);
phi_exact.apply(parabola);
RealVect pos(IntVect::Unit);
pos*=dx;
AMRPoissonOp amrop;
amrop.define(dbl, pos[0], regularDomain, DirParabolaBC);
BiCGStabSolver<LevelData<FArrayBox> > bsolver;
RelaxSolver<LevelData<FArrayBox> > rsolver;
bsolver.define(&amrop, true);
rsolver.define(&amrop, true);
int iter = 1;
amrop.scale(phi, 0.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
Real rnorm = amrop.norm(residual, 2);
Real enorm = amrop.norm(error, 0);
pout()<< "homogeneous solver mode : solver.solve(correction, residual)\n"
<< "solver.i_max= "<<bsolver.m_imax<<" iter = "<<iter<<std::endl;
pout()<<"\nInitial residual norm "<<rnorm<<" Error max norm "<<enorm<<"\n\n";
pout()<<indent2<<"BiCGStab\n";
for (int i=0; i<iter; ++i)
{
amrop.scale(correction, 0.0);
bsolver.solve(correction, residual);
amrop.incr(phi, correction, 1.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"RelaxSolver\n";
for (int i=0; i<iter; ++i)
{
amrop.scale(correction, 0.0);
rsolver.solve(correction, residual);
amrop.incr(phi, correction, 1.0);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
pout()<< "\n\ninhomogeneous solver mode : solver.solve(phi, rhs)\n"
<< "solver.i_max= "<<bsolver.m_imax<<" iter = "<<iter<<std::endl;
bsolver.setHomogeneous(false);
rsolver.setHomogeneous(false);
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"BiCGStab\n";
for (int i=0; i<iter; ++i)
{
bsolver.solve(phi, rhs);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
amrop.scale(phi, 0.0);
amrop.residual(residual, phi, rhs, false);
pout()<<indent2<<"RelaxSolver\n";
for (int i=0; i<iter; ++i)
{
rsolver.solve(phi, rhs);
amrop.axby(error, phi, phi_exact, 1, -1);
amrop.residual(residual, phi, rhs, false);
rnorm = amrop.norm(residual, 2);
enorm = amrop.norm(error, 0);
pout()<<indent<<"residual norm "<<rnorm<<" Error max norm = "<<enorm<<std::endl;
}
}
return 0;
}
| 25.441718 | 90 | 0.553332 | rmrsk |
6af62b453e66e057e9b1fef81df24a9388d64184 | 1,354 | cpp | C++ | nau/src/nau/render/opengl/glMaterialGroup.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 29 | 2015-09-16T22:28:30.000Z | 2022-03-11T02:57:36.000Z | nau/src/nau/render/opengl/glMaterialGroup.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 1 | 2017-03-29T13:32:58.000Z | 2017-03-31T13:56:03.000Z | nau/src/nau/render/opengl/glMaterialGroup.cpp | Khirion/nau | 47a2ad8e0355a264cd507da5e7bba1bf7abbff95 | [
"MIT"
] | 10 | 2015-10-15T14:20:15.000Z | 2022-02-17T10:37:29.000Z | #include "nau/render/opengl/glMaterialGroup.h"
#include "nau/render/opengl/glIndexArray.h"
#include "nau/render/opengl/glVertexArray.h"
#include <glbinding/gl/gl.h>
using namespace gl;
//#include <GL/glew.h>
using namespace nau::render::opengl;
GLMaterialGroup::GLMaterialGroup(IRenderable *parent, std::string materialName) :
MaterialGroup(parent, materialName),
m_VAO(0) {
}
GLMaterialGroup::~GLMaterialGroup() {
if (m_VAO)
glDeleteVertexArrays(1, &m_VAO);
}
void
GLMaterialGroup::compile() {
if (m_VAO)
return;
std::shared_ptr<VertexData> &v = m_Parent->getVertexData();
if (!v->isCompiled())
v->compile();
if (!m_IndexData->isCompiled())
m_IndexData->compile();
glGenVertexArrays(1, &m_VAO);
glBindVertexArray(m_VAO);
v->bind();
m_IndexData->bind();
glBindVertexArray(0);
v->unbind();
m_IndexData->unbind();
}
void
GLMaterialGroup::resetCompilationFlag() {
if (!m_VAO)
return;
glDeleteVertexArrays(1, &m_VAO);
m_VAO = 0;
std::shared_ptr<VertexData> &v = m_Parent->getVertexData();
v->resetCompilationFlag();
m_IndexData->resetCompilationFlag();
}
bool
GLMaterialGroup::isCompiled() {
return (m_VAO != 0);
}
void
GLMaterialGroup::bind() {
glBindVertexArray(m_VAO);
}
void
GLMaterialGroup::unbind() {
glBindVertexArray(0);
}
unsigned int
GLMaterialGroup::getVAO() {
return m_VAO;
} | 14.55914 | 81 | 0.711226 | Khirion |
1390f4a6b8e5901176235d44262abf445294de8a | 466 | cc | C++ | src/strings.cc | maxidea1024/simple-lexer | ba3cd91a6a9cdd77aa52bc0965553aa7858c8827 | [
"MIT"
] | null | null | null | src/strings.cc | maxidea1024/simple-lexer | ba3cd91a6a9cdd77aa52bc0965553aa7858c8827 | [
"MIT"
] | null | null | null | src/strings.cc | maxidea1024/simple-lexer | ba3cd91a6a9cdd77aa52bc0965553aa7858c8827 | [
"MIT"
] | null | null | null | #include "strings.h"
std::vector<std::string> Strings::registry_;
const char* Strings::Add(const char* str) { return Add(str, strlen(str)); }
const char* Strings::Add(const char* str, size_t length) {
for (auto& s : registry_) {
if (s.length() == length) {
if (memcmp(s.c_str(), str, length) == 0) {
return s.c_str();
}
}
}
std::string new_str(str, length);
registry_.push_back(new_str);
return registry_.back().c_str();
}
| 22.190476 | 75 | 0.613734 | maxidea1024 |
1391ad0b167b21189b455fa117e579f004a98df5 | 1,939 | cc | C++ | Core/DianYing/Source/Builtin/Shader/RenderPass.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | 4 | 2019-03-17T19:46:54.000Z | 2019-12-09T20:11:01.000Z | Core/DianYing/Source/Builtin/Shader/RenderPass.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | Core/DianYing/Source/Builtin/Shader/RenderPass.cc | liliilli/DianYing | 6e19f67e5d932e346a0ce63a648bed1a04ef618e | [
"MIT"
] | null | null | null | #include <precompiled.h>
///
/// MIT License
/// Copyright (c) 2018-2019 Jongmin Yun
///
/// 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.
///
/// Header file
#include <Dy/Builtin/ShaderGl/RenderPass.h>
namespace
{
constexpr std::string_view vertexShaderCode = R"dy(
#version 430 core
// Quad
layout (location = 0) in vec3 dyPosition;
layout (location = 1) in vec2 dyTexCoord0;
out gl_PerVertex { vec4 gl_Position; };
out VS_OUT { vec2 texCoord; } vs_out;
void main() {
vs_out.texCoord = dyTexCoord0;
gl_Position = vec4(dyPosition, 1.0);
}
)dy";
constexpr std::string_view fragmentShaderCode = R"dy(
#version 430
in VS_OUT { vec2 texCoord; } fs_in;
layout (location = 0) out vec4 outColor;
uniform sampler2D uUnlit;
uniform sampler2D uNormal;
uniform sampler2D uSpecular;
uniform sampler2D uViewPosition;
vec3 dirLight = normalize(vec3(-1, 1, 0));
vec3 ambientColor = vec3(1);
void main() {
vec4 normalValue = (texture(uNormal, fs_in.texCoord) - 0.5f) * 2.0f;
vec4 unlitValue = texture(uUnlit, fs_in.texCoord);
float ambientFactor = 0.1f;
float diffuseFactor = max(dot(normalValue.xyz, dirLight), 0.1);
outColor = vec4(
vec3(1) * diffuseFactor +
ambientColor * ambientFactor,
1.0f);
}
)dy";
} /// ::unnamed namespace
namespace dy::builtin
{
FDyBuiltinShaderGLRenderPass::FDyBuiltinShaderGLRenderPass()
{
this->mSpecifierName = sName;
this->mVertexBuffer = vertexShaderCode;
this->mPixelBuffer = fragmentShaderCode;
}
} /// ::dy::builtin namespace | 24.858974 | 81 | 0.7246 | liliilli |
139d5eb44977f8cba61672d95216750ad571ced0 | 530 | hpp | C++ | splitter/header/predicates/IBMtimePredicate.hpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | splitter/header/predicates/IBMtimePredicate.hpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | splitter/header/predicates/IBMtimePredicate.hpp | spectreCEP/spectre_v1.0 | 30c4af0681f016880c4a78b51669d989d4539850 | [
"MIT"
] | null | null | null | #ifndef IBMTIMEPREDICATE_H
#define IBMTIMEPREDICATE_H
#include "AbstractPredicate.hpp"
#include <set>
namespace splitter
{
class IBMtimePredicate : public AbstractPredicate
{
public:
IBMtimePredicate(unsigned long time);
virtual bool ps(const events::AbstractEvent &event) const;
virtual bool pc(const events::AbstractEvent &event, selection::AbstractSelection &abstractSelection);
virtual ~IBMtimePredicate() {}
private:
unsigned long timeOpen;
set<string> symbols;
};
}
#endif // IBMTIMEPREDICATE_H
| 21.2 | 105 | 0.764151 | spectreCEP |
139d83eae53539c796788bae08d8633796d4e4d3 | 397 | hpp | C++ | chaine/src/mesh/mesh/all.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/mesh/mesh/all.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | chaine/src/mesh/mesh/all.hpp | the-last-willy/id3d | dc0d22e7247ac39fbc1fd8433acae378b7610109 | [
"MIT"
] | null | null | null | #pragma once
#include "create_triangle.hpp"
#include "create_vertex.hpp"
#include "geometry.hpp"
#include "inner_triangle_edges.hpp"
#include "insert_vertex.hpp"
#include "lawson_algorithm.hpp"
#include "mesh.hpp"
#include "random_triangle_edge.hpp"
#include "topology.hpp"
#include "triangle.hpp"
#include "triangles.hpp"
#include "vertex_count.hpp"
#include "vertices.hpp"
#include "split.hpp"
| 23.352941 | 35 | 0.778338 | the-last-willy |
139db5e77c40d06224a6ab25bc72bd6626aa885f | 4,348 | cpp | C++ | samples/snippets/cpp/VS_Snippets_CLR/ConstructorBuilder_SetSymCustomAttribute/CPP/constructorbuilder_setsymcustomattribute.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 421 | 2018-04-01T01:57:50.000Z | 2022-03-28T15:24:42.000Z | samples/snippets/cpp/VS_Snippets_CLR/ConstructorBuilder_SetSymCustomAttribute/CPP/constructorbuilder_setsymcustomattribute.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 5,797 | 2018-04-02T21:12:23.000Z | 2022-03-31T23:54:38.000Z | samples/snippets/cpp/VS_Snippets_CLR/ConstructorBuilder_SetSymCustomAttribute/CPP/constructorbuilder_setsymcustomattribute.cpp | hamarb123/dotnet-api-docs | 6aeb55784944a2f1f5e773b657791cbd73a92dd4 | [
"CC-BY-4.0",
"MIT"
] | 1,482 | 2018-03-31T11:26:20.000Z | 2022-03-30T22:36:45.000Z | // System.Reflection.Emit.ConstructorBuilder.SetSymCustomAttribute()
/* The following program demonstrates the 'SetSymCustomAttribute' method
of ConstructorBuilder class. It creates an assembly in the current
domain with dynamic module in the assembly. Constructor builder is
used in conjunction with the 'TypeBuilder' class to create constructor
at run time. It then sets this constructor's custom attribute associated
with symbolic information.
*/
using namespace System;
using namespace System::Reflection;
using namespace System::Reflection::Emit;
public ref class MyConstructorBuilder
{
private:
Type^ myType1;
ModuleBuilder^ myModuleBuilder;
AssemblyBuilder^ myAssemblyBuilder;
public:
MyConstructorBuilder()
{
myModuleBuilder = nullptr;
myAssemblyBuilder = nullptr;
// <Snippet1>
MethodBuilder^ myMethodBuilder = nullptr;
AppDomain^ myCurrentDomain = AppDomain::CurrentDomain;
// Create assembly in current CurrentDomain.
AssemblyName^ myAssemblyName = gcnew AssemblyName;
myAssemblyName->Name = "TempAssembly";
// Create a dynamic assembly.
myAssemblyBuilder = myCurrentDomain->DefineDynamicAssembly(
myAssemblyName, AssemblyBuilderAccess::Run );
// Create a dynamic module in the assembly.
myModuleBuilder = myAssemblyBuilder->DefineDynamicModule( "TempModule", true );
FieldInfo^ myFieldInfo =
myModuleBuilder->DefineUninitializedData( "myField", 2, FieldAttributes::Public );
// Create a type in the module.
TypeBuilder^ myTypeBuilder = myModuleBuilder->DefineType( "TempClass", TypeAttributes::Public );
FieldBuilder^ myGreetingField = myTypeBuilder->DefineField( "Greeting",
String::typeid, FieldAttributes::Public );
array<Type^>^ myConstructorArgs = {String::typeid};
// Define a constructor of the dynamic class.
ConstructorBuilder^ myConstructor = myTypeBuilder->DefineConstructor( MethodAttributes::Public, CallingConventions::Standard, myConstructorArgs );
// Display the name of the constructor.
Console::WriteLine( "The constructor name is : {0}", myConstructor->Name );
array<Byte>^ temp0 = {01,00,00};
myConstructor->SetSymCustomAttribute( "MySimAttribute", temp0 );
// </Snippet1>
// Generate the IL for the method and call its superclass constructor.
ILGenerator^ myILGenerator3 = myConstructor->GetILGenerator();
myILGenerator3->Emit( OpCodes::Ldarg_0 );
ConstructorInfo^ myConstructorInfo = Object::typeid->GetConstructor( gcnew array<Type^>(0) );
myILGenerator3->Emit( OpCodes::Call, myConstructorInfo );
myILGenerator3->Emit( OpCodes::Ldarg_0 );
myILGenerator3->Emit( OpCodes::Ldarg_1 );
myILGenerator3->Emit( OpCodes::Stfld, myGreetingField );
myILGenerator3->Emit( OpCodes::Ret );
// Add a method to the type.
myMethodBuilder = myTypeBuilder->DefineMethod(
"HelloWorld", MethodAttributes::Public, nullptr, nullptr );
// Generate IL for the method.
ILGenerator^ myILGenerator2 = myMethodBuilder->GetILGenerator();
myILGenerator2->EmitWriteLine( "Hello World from global" );
myILGenerator2->Emit( OpCodes::Ret );
myModuleBuilder->CreateGlobalFunctions();
myType1 = myTypeBuilder->CreateType();
}
property Type^ MyTypeProperty
{
Type^ get()
{
return this->myType1;
}
}
};
int main()
{
MyConstructorBuilder^ myConstructorBuilder = gcnew MyConstructorBuilder;
Type^ myType1 = myConstructorBuilder->MyTypeProperty;
if ( nullptr != myType1 )
{
Console::WriteLine( "Instantiating the new type..." );
array<Object^>^ myObject = {"hello"};
Object^ myObject1 = Activator::CreateInstance( myType1, myObject, nullptr );
MethodInfo^ myMethodInfo = myType1->GetMethod( "HelloWorld" );
if ( nullptr != myMethodInfo )
{
Console::WriteLine( "Invoking dynamically created HelloWorld method..." );
myMethodInfo->Invoke( myObject1, nullptr );
}
else
{
Console::WriteLine( "Could not locate HelloWorld method" );
}
}
else
{
Console::WriteLine( "Could not access Type." );
}
}
| 40.635514 | 153 | 0.682383 | hamarb123 |
13afe562cb97b33f540a1e8e585c0a7f50de2a24 | 51 | cpp | C++ | CompileUnits/example/src/bin/cli/src/main.cpp | yyunon/cmake-modules | 141e793b42c0702e7b73570960bf7f6e23501496 | [
"Apache-2.0"
] | 1 | 2019-06-06T06:28:50.000Z | 2019-06-06T06:28:50.000Z | CompileUnits/example/src/bin/cli/src/main.cpp | yyunon/cmake-modules | 141e793b42c0702e7b73570960bf7f6e23501496 | [
"Apache-2.0"
] | 7 | 2019-06-03T12:17:03.000Z | 2022-01-13T15:54:21.000Z | CompileUnits/example/src/bin/cli/src/main.cpp | yyunon/cmake-modules | 141e793b42c0702e7b73570960bf7f6e23501496 | [
"Apache-2.0"
] | 1 | 2021-05-31T06:27:47.000Z | 2021-05-31T06:27:47.000Z | #include <example/lib/c.hpp>
int main() {
c();
}
| 8.5 | 28 | 0.568627 | yyunon |
13b07629f927f12728ba1c9eeda44a572d8aa5da | 356 | hpp | C++ | src/TypeTraits.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/TypeTraits.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | src/TypeTraits.hpp | jmitchell24/cpp-utility-lib | 76e7bae9f07b741c409a282604a999ab86fc0702 | [
"Apache-2.0"
] | null | null | null | // Copyright 2013, James Mitchell, All rights reserved.
#pragma once
#include "typetraits/EnableIf.hpp"
#include "typetraits/CallTraits.hpp"
#include "typetraits/HasOstreamOut.hpp"
#include "typetraits/HasMemberFunction.hpp"
#include "typetraits/IsArithmetic.hpp"
#include "typetraits/IsPointer.hpp"
#include "typetraits/IsSame.hpp"
namespace util
{
}
| 20.941176 | 55 | 0.789326 | jmitchell24 |
13b0a0104b85e1f4b72acdabf300ee0e2be3023b | 383 | cpp | C++ | chapter_4_computation/exercise/square_rice.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | chapter_4_computation/exercise/square_rice.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | chapter_4_computation/exercise/square_rice.cpp | jamie-prog/programming_principles_and_practice | abd4fec2cd02fc0bab69c9b11e13d9fce04039f9 | [
"Apache-2.0"
] | null | null | null | #include "../../std_lib_facilities.h"
int square(int x)
{
return x * x;
}
int main(void)
{
//constexpr int first {1000};
//constexpr int second {1000000};
constexpr int third {1000000000};
bool is_overflow{false};
for (int i{0}, temp{0}; is_overflow || temp < third; ++i)
{
temp = square(i);
cout << i << " : " << temp << "\n";
}
} | 18.238095 | 61 | 0.537859 | jamie-prog |
13b5c3fb34fecf57c52a99f9100cfde6b29d2d1c | 2,372 | cpp | C++ | ares/ngp/system/system.cpp | kirwinia/ares-emu-v121 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | [
"0BSD"
] | 2 | 2021-06-28T06:04:56.000Z | 2021-06-28T11:30:20.000Z | ares/ngp/system/system.cpp | kirwinia/ares-emu-v121 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | [
"0BSD"
] | null | null | null | ares/ngp/system/system.cpp | kirwinia/ares-emu-v121 | 722aa227caf943a4a64f1678c1bdd07b38b15caa | [
"0BSD"
] | 1 | 2021-06-28T06:05:04.000Z | 2021-06-28T06:05:04.000Z | #include <ngp/ngp.hpp>
namespace ares::NeoGeoPocket {
auto enumerate() -> vector<string> {
return {
"[SNK] Neo Geo Pocket",
"[SNK] Neo Geo Pocket Color",
};
}
auto load(Node::System& node, string name) -> bool {
if(!enumerate().find(name)) return false;
return system.load(node, name);
}
Scheduler scheduler;
System system;
#include "controls.cpp"
#include "debugger.cpp"
#include "serialization.cpp"
auto System::game() -> string {
if(cartridge.node) {
return cartridge.title();
}
return "(no cartridge connected)";
}
auto System::run() -> void {
scheduler.enter();
}
auto System::load(Node::System& root, string name) -> bool {
if(node) unload();
information = {};
if(name.find("Neo Geo Pocket")) {
information.name = "Neo Geo Pocket";
information.model = Model::NeoGeoPocket;
}
if(name.find("Neo Geo Pocket Color")) {
information.name = "Neo Geo Pocket Color";
information.model = Model::NeoGeoPocketColor;
}
node = Node::System::create(information.name);
node->setGame({&System::game, this});
node->setRun({&System::run, this});
node->setPower({&System::power, this});
node->setSave({&System::save, this});
node->setUnload({&System::unload, this});
node->setSerialize({&System::serialize, this});
node->setUnserialize({&System::unserialize, this});
root = node;
if(!node->setPak(pak = platform->pak(node))) return false;
fastBoot = node->append<Node::Setting::Boolean>("Fast Boot", false);
bios.allocate(64_KiB);
if(auto fp = pak->read("bios.rom")) {
bios.load(fp);
}
scheduler.reset();
controls.load(node);
cpu.load(node);
apu.load(node);
kge.load(node);
psg.load(node);
cartridgeSlot.load(node);
debugger.load(node);
return true;
}
auto System::save() -> void {
if(!node) return;
cpu.save();
apu.save();
cartridge.save();
}
auto System::unload() -> void {
if(!node) return;
debugger.unload(node);
bios.reset();
cpu.unload();
apu.unload();
kge.unload();
psg.unload();
cartridgeSlot.unload();
pak.reset();
node.reset();
}
auto System::power(bool reset) -> void {
for(auto& setting : node->find<Node::Setting::Setting>()) setting->setLatch();
cartridge.power();
cpu.power();
apu.power();
kge.power();
psg.power();
scheduler.power(cpu);
if(fastBoot->latch() && cartridge.flash[0]) cpu.fastBoot();
}
}
| 21.369369 | 80 | 0.642496 | kirwinia |
13b71c408f3bce3cfa75daab08f07ca2b81945c8 | 1,058 | cpp | C++ | Q12/Q12.cpp | d9vya/Operating-Systems-Practical | 01ff599d94e955035e8d433037e23262abda2a97 | [
"MIT"
] | null | null | null | Q12/Q12.cpp | d9vya/Operating-Systems-Practical | 01ff599d94e955035e8d433037e23262abda2a97 | [
"MIT"
] | null | null | null | Q12/Q12.cpp | d9vya/Operating-Systems-Practical | 01ff599d94e955035e8d433037e23262abda2a97 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
int sum = 0;
void *summer(void *); //function to run inside thread
int main(int argc, char *argv[])
{
pthread_t tid;
pthread_attr_t attr;
if (argc != 2) // if 2 arguments are not passed on commandline, show error
{
fprintf(stderr, "usage: %s <integer value>\n", argv[0]);
exit(1);
}
else if (atoi(argv[1]) < 0) // if a negative value is passed as an argument, show error
{
fprintf(stderr, "integer value must be > 0\n");
exit(1);
}
pthread_attr_init(&attr); // initializing attributes of the thread
pthread_create(&tid, &attr, summer, argv[1]); // creating thread
pthread_join(tid,NULL); // wating for thread to exit
printf("SUM: %d\n",sum);
return 0;
}
void *summer(void *param)
{
int n = atoi((char*)param);
for(int i=0;i<=n;i++)
sum+=i;
pthread_exit(0);
}
| 28.594595 | 111 | 0.528355 | d9vya |
13b7a78535c5570233c5d97bdad43f941eac46d1 | 259 | cpp | C++ | SPOJ/Week 1/next/next.cpp | VastoLorde95/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 170 | 2017-07-25T14:47:29.000Z | 2022-01-26T19:16:31.000Z | SPOJ/Week 1/next/next.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | null | null | null | SPOJ/Week 1/next/next.cpp | navodit15/Competitive-Programming | 6c990656178fb0cd33354cbe5508164207012f24 | [
"MIT"
] | 55 | 2017-07-28T06:17:33.000Z | 2021-10-31T03:06:22.000Z | #include<iostream>
using namespace std;
int main(){
unsigned long a,b,c;
cin>>a>>b>>c;
while(a != 0, b != 0, c != 0){
if(c-b == b-a){
cout<<"AP "<< c + c - b<<endl;
}
else{
cout<<"GP "<< c * (c/b) <<endl;
}
cin>>a>>b>>c;
}
return 0;
}
| 14.388889 | 34 | 0.46332 | VastoLorde95 |
13beb24b3f7fbd391cf301b7ef293b8015f702b5 | 3,140 | cpp | C++ | ad_map_access/impl/tests/access/GeometryStoreTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/tests/access/GeometryStoreTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | null | null | null | ad_map_access/impl/tests/access/GeometryStoreTests.cpp | seowwj/map | 2afacd50e1b732395c64b1884ccfaeeca0040ee7 | [
"MIT"
] | 1 | 2020-10-27T11:09:30.000Z | 2020-10-27T11:09:30.000Z | // ----------------- BEGIN LICENSE BLOCK ---------------------------------
//
// Copyright (C) 2018-2020 Intel Corporation
//
// SPDX-License-Identifier: MIT
//
// ----------------- END LICENSE BLOCK -----------------------------------
#include <ad/map/access/Factory.hpp>
#include <ad/map/access/Operation.hpp>
#include <ad/map/lane/LaneOperation.hpp>
#include <ad/map/point/Operation.hpp>
#include <ad/map/serialize/SerializerFileCRC32.hpp>
#include <gtest/gtest.h>
#include "../src/access/GeometryStore.hpp"
using namespace ::ad;
using namespace ::ad::map;
using namespace ::ad::map::point;
using namespace ::ad::map::lane;
struct GeometryStoreTest : ::testing::Test
{
GeometryStoreTest()
{
}
virtual void SetUp()
{
}
virtual void TearDown()
{
access::cleanup();
}
};
TEST_F(GeometryStoreTest, GeometryStore)
{
ASSERT_TRUE(access::init("test_files/Town01.txt"));
access::GeometryStore geoStore;
EXPECT_THROW(geoStore.store(NULL), std::runtime_error);
EXPECT_THROW(geoStore.restore(NULL), std::runtime_error);
EXPECT_THROW(geoStore.check(NULL), std::runtime_error);
auto lanes = lane::getLanes();
ASSERT_GT(lanes.size(), 0u);
auto lanePtr = lane::getLanePtr(lanes[0]);
ASSERT_TRUE(geoStore.store(lanePtr));
ASSERT_TRUE(geoStore.check(lanePtr));
lane::Lane::Ptr oneLane;
oneLane.reset(new lane::Lane());
oneLane->id = lanes[0];
ASSERT_TRUE(geoStore.restore(oneLane));
ASSERT_EQ(oneLane->edgeLeft.ecefEdge, lanePtr->edgeLeft.ecefEdge);
ASSERT_EQ(oneLane->edgeRight.ecefEdge, lanePtr->edgeRight.ecefEdge);
}
TEST_F(GeometryStoreTest, StoreSerialization)
{
ASSERT_TRUE(access::init("test_files/Town01.txt"));
access::Store &store = access::getStore();
size_t versionMajor = ::ad::map::serialize::SerializerFileCRC32::VERSION_MAJOR;
size_t versionMinor = ::ad::map::serialize::SerializerFileCRC32::VERSION_MINOR;
serialize::SerializerFileCRC32 serializer_w(true);
ASSERT_TRUE(serializer_w.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
ASSERT_TRUE(store.save(serializer_w, false, false, true));
ASSERT_TRUE(serializer_w.close());
serialize::SerializerFileCRC32 serializer_r(false);
ASSERT_EQ(serializer_r.getStorageType(), "File");
ASSERT_EQ(serializer_r.getChecksumType(), "CRC-32");
ASSERT_TRUE(serializer_r.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
access::Store::Ptr storeRead;
storeRead.reset(new access::Store());
ASSERT_TRUE(storeRead->load(serializer_r));
ASSERT_TRUE(serializer_r.close());
serialize::SerializerFileCRC32 serializer_w2(true);
ASSERT_TRUE(serializer_w2.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
ASSERT_TRUE(store.save(serializer_w2, false, true, true));
ASSERT_TRUE(serializer_w2.close());
serialize::SerializerFileCRC32 serializer_r2(false);
ASSERT_TRUE(serializer_r2.open("test_files/test_StoreSerialization.adm", versionMajor, versionMinor));
access::Store::Ptr storeRead2;
storeRead2.reset(new access::Store());
ASSERT_TRUE(storeRead2->load(serializer_r2));
ASSERT_TRUE(serializer_r2.close());
}
| 33.763441 | 104 | 0.729618 | seowwj |
13bfa37048e98d16dcf3768baccdd5b51d6b3e14 | 54 | cpp | C++ | src/victoryconnect/cpp/logger.cpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | src/victoryconnect/cpp/logger.cpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | src/victoryconnect/cpp/logger.cpp | victoryforphil/VictoryConnect-ClientCPP | 6ad06edcd6339df933af337f2fa9d111c83d6e2d | [
"MIT"
] | null | null | null | #include "logger.hpp"
using namespace VictoryConnect;
| 18 | 31 | 0.814815 | victoryforphil |
13c47789b56d27a1375a573dd1e14827fd83f584 | 5,653 | cpp | C++ | src/cgp/minicgp_blindwatchmaker.cpp | dubkois/ReusWorld | 15ccf4dbde20d6b600b6e5dc706435d6dd4eb620 | [
"MIT"
] | null | null | null | src/cgp/minicgp_blindwatchmaker.cpp | dubkois/ReusWorld | 15ccf4dbde20d6b600b6e5dc706435d6dd4eb620 | [
"MIT"
] | null | null | null | src/cgp/minicgp_blindwatchmaker.cpp | dubkois/ReusWorld | 15ccf4dbde20d6b600b6e5dc706435d6dd4eb620 | [
"MIT"
] | null | null | null | #include <QApplication>
#include <QMainWindow>
#include <QGridLayout>
#include <QPushButton>
#include <QMouseEvent>
#include <QPainter>
#include <QTimer>
#include "kgd/external/cxxopts.hpp"
#include "kgd/utils/indentingostream.h"
#include "minicgp.h"
DEFINE_NAMESPACE_PRETTY_ENUMERATION(watchmaker, VideoInputs, X, Y, T, R, G, B)
DEFINE_NAMESPACE_PRETTY_ENUMERATION(watchmaker, RGBOutputs, R_, G_, B_)
using CGP = cgp::CGP<watchmaker::VideoInputs, 10, watchmaker::RGBOutputs>;
namespace watchmaker {
using Callback = std::function<void(const CGP&)>;
static constexpr int STEPS = 50;
static constexpr int LOOP_DURATION = 2; // seconds
struct CGPViewer : public QPushButton {
static constexpr int SIDE = 50;
static constexpr int MARGIN = 10;
static constexpr QSize SIZE = QSize(SIDE + 2 * MARGIN, SIDE + 2 * MARGIN);
CGP &cgp;
Callback callback;
QImage img;
int step;
bool up = true;
CGPViewer(CGP &cgp, Callback c)
: QPushButton(nullptr), cgp(cgp), callback(c),
img(SIDE, SIDE, QImage::Format_RGB32) {
img.fill(Qt::gray);
setFocusPolicy(Qt::NoFocus);
setAutoExclusive(true);
setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding);
step = 0;
}
void cgpUpdated (void) {
setToolTip(QString::fromStdString(cgp.toTex()));
img.fill(Qt::gray);
}
void nextFrame (void) {
QRgb *pixels = reinterpret_cast<QRgb*>(img.scanLine(0));
CGP::Inputs inputs;
inputs[T] = 2. * step / (STEPS - 1) - 1;
for (int i=0; i<SIDE; i++) {
for (int j=0; j<SIDE; j++) {
inputs[X] = double(2) * i / (SIDE-1) - 1;
inputs[Y] = double(2) * j / (SIDE-1) - 1;
QRgb &pixel = pixels[i*SIDE+j];
inputs[R] = 2 * qRed(pixel) / 255. - 1;
inputs[G] = 2 * qGreen(pixel) / 255. - 1;
inputs[B] = 2 * qBlue(pixel) / 255. - 1;
CGP::Outputs outputs;
cgp.evaluate(inputs, outputs);
pixel = qRgb(255 * (outputs[R_] * .5 + .5),
255 * (outputs[G_] * .5 + .5),
255 * (outputs[B_] * .5 + .5));
}
}
if (up) {
step++;
up = (step < STEPS);
} else {
step--;
up = (step <= 0);
}
update();
}
QSize sizeHint (void) const {
return SIZE;
}
void paintEvent(QPaintEvent *event) {
QPushButton::paintEvent(event);
QPainter painter (this);
painter.drawImage(rect().adjusted(MARGIN, MARGIN, -MARGIN, -MARGIN), img);
}
void mouseReleaseEvent(QMouseEvent *event) {
if (event->button() == Qt::LeftButton)
callback(cgp);
else if (event->button() == Qt::RightButton) {
static int i = 0;
std::ostringstream oss;
oss << "cgp_bw_test_" << i++ << ".pdf";
stdfs::path path = oss.str();
cgp.toDot(path, CGP::FULL | CGP::NO_ARITY);
oss.str("");
oss << "xdg-open " << path;
std::string cmd = oss.str();
system(cmd.c_str());
}
}
};
} // end of namespace watchmaker
int main (int argc, char *argv[]) {
// ===========================================================================
// == Command line arguments parsing
using Verbosity = config::Verbosity;
std::string configFile = "auto"; // Default to auto-config
Verbosity verbosity = Verbosity::SHOW;
cxxopts::Options options("MiniCGP-blindwatchmaker",
"Exhibit MiniCGP capabilities through a blind"
" watchmaker algorithm");
options.add_options()
("h,help", "Display help")
("a,auto-config", "Load configuration data from default location")
("c,config", "File containing configuration data",
cxxopts::value(configFile))
("v,verbosity", "Verbosity level. " + config::verbosityValues(),
cxxopts::value(verbosity))
;
auto result = options.parse(argc, argv);
if (result.count("help")) {
std::cout << options.help()
<< std::endl;
return 0;
}
if (result.count("auto-config") && result["auto-config"].as<bool>())
configFile = "auto";
config::CGP::setupConfig(configFile, verbosity);
if (configFile.empty()) config::CGP::printConfig("");
rng::FastDice dice;
auto cgps = utils::make_array<CGP, 9>([&dice] (auto) {
return CGP::null(dice);
});
std::cout << "Generated with seed " << dice.getSeed() << std::endl;
QApplication app (argc, argv);
QMainWindow w;
QWidget *widget = new QWidget;
QGridLayout *layout = new QGridLayout;
w.setCentralWidget(widget);
widget->setLayout(layout);
std::array<watchmaker::CGPViewer*, 9> viewers;
auto updateCGPs = [&dice, &viewers, &cgps]
(const CGP &newParent) {
cgps[4] = newParent;
for (uint i=0; i<3; i++) {
for (uint j=0; j<3; j++) {
uint ix = i*3+j;
if (ix != 4) {
CGP child = newParent;
// std::cerr << "Mutating IX=" << ix << ", i=" << i << ", j=" << j
// << ":\n";
// utils::IndentingOStreambuf indent (std::cerr);
child.mutate(dice);
cgps[ix] = child;
// std::cerr << std::endl;
}
viewers[ix]->cgpUpdated();
}
}
};
for (int i=0; i<3; i++) {
for (int j=0; j<3; j++) {
uint ix = i*3+j;
auto viewer = new watchmaker::CGPViewer(cgps[ix], updateCGPs);
viewers[ix] = viewer;
layout->addWidget(viewer, i, j);
}
}
updateCGPs(cgps[4]);
w.show();
QTimer timer;
QObject::connect(&timer, &QTimer::timeout, [&viewers] {
for (watchmaker::CGPViewer *v: viewers) v->nextFrame();
});
timer.start(watchmaker::LOOP_DURATION * 1000.f / watchmaker::STEPS);
return app.exec();
}
| 25.931193 | 80 | 0.576685 | dubkois |
13c82c88e3c0ef2adf1066587a763c57d1d1e433 | 34,351 | hxx | C++ | libs/maps/include/mrpt/otherlibs/octomap/OccupancyOcTreeBase.hxx | feroze/mrpt-shivang | 95bf524c5e10ed2e622bd199f1b0597951b45370 | [
"BSD-3-Clause"
] | 4 | 2017-08-04T15:44:04.000Z | 2021-02-02T02:00:18.000Z | libs/maps/include/mrpt/otherlibs/octomap/OccupancyOcTreeBase.hxx | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | null | null | null | libs/maps/include/mrpt/otherlibs/octomap/OccupancyOcTreeBase.hxx | tg1716/SLAM | b8583fb98a4241d87ae08ac78b0420c154f5e1a5 | [
"BSD-3-Clause"
] | 2 | 2017-10-03T23:10:09.000Z | 2018-07-29T09:41:33.000Z | // $Id: OccupancyOcTreeBase.hxx 440 2012-11-02 10:41:10Z ahornung $
/**
* OctoMap:
* A probabilistic, flexible, and compact 3D mapping library for robotic systems.
* @author K. M. Wurm, A. Hornung, University of Freiburg, Copyright (C) 2009.
* @see http://octomap.sourceforge.net/
* License: New BSD License
*/
/*
* Copyright (c) 2009-2011, K. M. Wurm, A. Hornung, University of Freiburg
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the University of Freiburg nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <bitset>
namespace octomap {
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double resolution)
: OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(resolution), use_bbx_limit(false), use_change_detection(false)
{
}
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(double resolution, unsigned int tree_depth, unsigned int tree_max_val)
: OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(resolution, tree_depth, tree_max_val), use_bbx_limit(false), use_change_detection(false)
{
}
template <class NODE>
OccupancyOcTreeBase<NODE>::~OccupancyOcTreeBase(){
}
template <class NODE>
OccupancyOcTreeBase<NODE>::OccupancyOcTreeBase(const OccupancyOcTreeBase<NODE>& rhs) :
OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>(rhs), use_bbx_limit(rhs.use_bbx_limit),
bbx_min(rhs.bbx_min), bbx_max(rhs.bbx_max),
bbx_min_key(rhs.bbx_min_key), bbx_max_key(rhs.bbx_max_key),
use_change_detection(rhs.use_change_detection), changed_keys(rhs.changed_keys)
{
this->clamping_thres_min = rhs.clamping_thres_min;
this->clamping_thres_max = rhs.clamping_thres_max;
this->prob_hit_log = rhs.prob_hit_log;
this->prob_miss_log = rhs.prob_miss_log;
this->occ_prob_thres_log = rhs.occ_prob_thres_log;
}
// performs transformation to data and sensor origin first
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const ScanNode& scan, double maxrange, bool pruning, bool lazy_eval) {
Pointcloud& cloud = *(scan.scan);
pose6d frame_origin = scan.pose;
point3d sensor_origin = frame_origin.inv().transform(scan.pose.trans());
insertScan(cloud, sensor_origin, frame_origin, maxrange, pruning, lazy_eval);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const Pointcloud& scan, const octomap::point3d& sensor_origin,
double maxrange, bool pruning, bool lazy_eval) {
KeySet free_cells, occupied_cells;
computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange);
// insert data into tree -----------------------
for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) {
updateNode(*it, false, lazy_eval);
}
for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) {
updateNode(*it, true, lazy_eval);
}
// TODO: does pruning make sense if we used "lazy_eval"?
if (pruning) this->prune();
}
template <class NODE>
template <class SCAN>
void OccupancyOcTreeBase<NODE>::insertScan_templ(const SCAN& scan, const octomap::point3d& sensor_origin,
double maxrange, bool pruning, bool lazy_eval) {
KeySet free_cells, occupied_cells;
computeUpdate(scan, sensor_origin, free_cells, occupied_cells, maxrange);
// insert data into tree -----------------------
for (KeySet::iterator it = free_cells.begin(); it != free_cells.end(); ++it) {
updateNode(*it, false, lazy_eval);
}
for (KeySet::iterator it = occupied_cells.begin(); it != occupied_cells.end(); ++it) {
updateNode(*it, true, lazy_eval);
}
// TODO: does pruning make sense if we used "lazy_eval"?
if (pruning) this->prune();
}
// performs transformation to data and sensor origin first
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScan(const Pointcloud& pc, const point3d& sensor_origin, const pose6d& frame_origin,
double maxrange, bool pruning, bool lazy_eval) {
Pointcloud transformed_scan (pc);
transformed_scan.transform(frame_origin);
point3d transformed_sensor_origin = frame_origin.transform(sensor_origin);
insertScan(transformed_scan, transformed_sensor_origin, maxrange, pruning, lazy_eval);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::insertScanNaive(const Pointcloud& pc, const point3d& origin, double maxrange, bool pruning, bool lazy_eval) {
if (pc.size() < 1)
return;
// integrate each single beam
octomap::point3d p;
for (octomap::Pointcloud::const_iterator point_it = pc.begin();
point_it != pc.end(); ++point_it) {
this->insertRay(origin, *point_it, maxrange, lazy_eval);
}
if (pruning)
this->prune();
}
template <class NODE>
inline void OccupancyOcTreeBase<NODE>::computeUpdate_onePoint(const point3d& p, const octomap::point3d& origin,
KeySet& free_cells, KeySet& occupied_cells, double maxrange)
{
if (!use_bbx_limit) {
// -------------- no BBX specified ---------------
if ((maxrange < 0.0) || ((p - origin).norm() <= maxrange) ) { // is not maxrange meas.
// free cells
if (this->computeRayKeys(origin, p, this->keyray)){
free_cells.insert(this->keyray.begin(), this->keyray.end());
}
// occupied endpoint
OcTreeKey key;
if (this->coordToKeyChecked(p, key))
occupied_cells.insert(key);
} // end if NOT maxrange
else { // user set a maxrange and this is reached
point3d direction = (p - origin).normalized ();
point3d new_end = origin + direction * (float) maxrange;
if (this->computeRayKeys(origin, new_end, this->keyray)){
free_cells.insert(this->keyray.begin(), this->keyray.end());
}
} // end if maxrange
}
// --- update limited by user specified BBX -----
else {
// endpoint in bbx and not maxrange?
if ( inBBX(p) && ((maxrange < 0.0) || ((p - origin).norm () <= maxrange) ) ) {
// occupied endpoint
OcTreeKey key;
if (this->coordToKeyChecked(p, key))
occupied_cells.insert(key);
// update freespace, break as soon as bbx limit is reached
if (this->computeRayKeys(origin, p, this->keyray)){
for(KeyRay::reverse_iterator rit=this->keyray.rbegin(); rit != this->keyray.rend(); ++rit) {
if (inBBX(*rit)) {
free_cells.insert(*rit);
}
else break;
}
} // end if compute ray
} // end if in BBX and not maxrange
} // end bbx case
}
template <class NODE>
template <class POINTCLOUD>
void OccupancyOcTreeBase<NODE>::computeUpdate_templ( const POINTCLOUD& scan, const octomap::point3d& origin, KeySet& free_cells, KeySet& occupied_cells, double maxrange)
{
const size_t N = scan.size();
const std::vector<float> &xs = scan.getPointsBufferRef_x();
const std::vector<float> &ys = scan.getPointsBufferRef_y();
const std::vector<float> &zs = scan.getPointsBufferRef_z();
for (size_t i=0;i<N;i++)
{
const point3d p(xs[i],ys[i],zs[i]);
computeUpdate_onePoint(p,origin,free_cells,occupied_cells,maxrange);
}
// prefer occupied cells over free ones (and make sets disjunct)
for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; )
{
if (occupied_cells.find(*it) != occupied_cells.end())
it = free_cells.erase(it);
else ++it;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::computeUpdate(const Pointcloud& scan, const octomap::point3d& origin,
KeySet& free_cells, KeySet& occupied_cells,
double maxrange)
{
//#pragma omp parallel private (local_key_ray, point_it)
for (Pointcloud::const_iterator point_it = scan.begin(); point_it != scan.end(); ++point_it) {
const point3d& p = *point_it;
computeUpdate_onePoint(p,origin,free_cells,occupied_cells,maxrange);
}
// prefer occupied cells over free ones (and make sets disjunct)
for(KeySet::iterator it = free_cells.begin(), end=free_cells.end(); it!= end; ){
if (occupied_cells.find(*it) != occupied_cells.end()){
it = free_cells.erase(it);
} else {
++it;
}
}
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, float log_odds_update, bool lazy_eval) {
return updateNodeRecurs(this->root, false, key, 0, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, float log_odds_update, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(value, key))
return NULL;
return updateNode(key, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, float log_odds_update, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(x, y, z, key))
return NULL;
return updateNode(key, log_odds_update, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const OcTreeKey& key, bool occupied, bool lazy_eval) {
NODE* leaf = this->search(key);
// no change: node already at threshold
if (leaf && (this->isNodeAtThreshold(leaf)) && (this->isNodeOccupied(leaf) == occupied)) {
return leaf;
}
if (occupied) return updateNodeRecurs(this->root, false, key, 0, this->prob_hit_log, lazy_eval);
else return updateNodeRecurs(this->root, false, key, 0, this->prob_miss_log, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(const point3d& value, bool occupied, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(value, key))
return NULL;
return updateNode(key, occupied, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNode(double x, double y, double z, bool occupied, bool lazy_eval) {
OcTreeKey key;
if (!this->coordToKeyChecked(x, y, z, key))
return NULL;
return updateNode(key, occupied, lazy_eval);
}
template <class NODE>
NODE* OccupancyOcTreeBase<NODE>::updateNodeRecurs(NODE* node, bool node_just_created, const OcTreeKey& key,
unsigned int depth, const float& log_odds_update, bool lazy_eval) {
unsigned int pos = computeChildIdx(key, this->tree_depth-1-depth);
bool created_node = false;
// follow down to last level
if (depth < this->tree_depth) {
if (!node->childExists(pos)) {
// child does not exist, but maybe it's a pruned node?
if ((!node->hasChildren()) && !node_just_created && (node != this->root)) {
// current node does not have children AND it is not a new node
// AND its not the root node
// -> expand pruned node
node->expandNode();
this->tree_size+=8;
this->size_changed = true;
}
else {
// not a pruned node, create requested child
node->createChild(pos);
this->tree_size++;
this->size_changed = true;
created_node = true;
}
}
if (lazy_eval)
return updateNodeRecurs(node->getChild(pos), created_node, key, depth+1, log_odds_update, lazy_eval);
else {
NODE* retval = updateNodeRecurs(node->getChild(pos), created_node, key, depth+1, log_odds_update, lazy_eval);
// set own probability according to prob of children
node->updateOccupancyChildren();
return retval;
}
}
// at last level, update node, end of recursion
else {
if (use_change_detection) {
bool occBefore = this->isNodeOccupied(node);
updateNodeLogOdds(node, log_odds_update);
if (node_just_created){ // new node
changed_keys.insert(std::pair<OcTreeKey,bool>(key, true));
} else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it
KeyBoolMap::iterator it = changed_keys.find(key);
if (it == changed_keys.end())
changed_keys.insert(std::pair<OcTreeKey,bool>(key, false));
else if (it->second == false)
changed_keys.erase(it);
}
}
else {
updateNodeLogOdds(node, log_odds_update);
}
return node;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::calcNumThresholdedNodes(unsigned int& num_thresholded,
unsigned int& num_other) const {
num_thresholded = 0;
num_other = 0;
// TODO: The recursive call could be completely replaced with the new iterators
calcNumThresholdedNodesRecurs(this->root, num_thresholded, num_other);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::calcNumThresholdedNodesRecurs (NODE* node,
unsigned int& num_thresholded,
unsigned int& num_other) const {
assert(node != NULL);
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
NODE* child_node = node->getChild(i);
if (this->isNodeAtThreshold(child_node))
num_thresholded++;
else
num_other++;
calcNumThresholdedNodesRecurs(child_node, num_thresholded, num_other);
} // end if child
} // end for children
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateInnerOccupancy(){
this->updateInnerOccupancyRecurs(this->root, 0);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateInnerOccupancyRecurs(NODE* node, unsigned int depth){
// only recurse and update for inner nodes:
if (node->hasChildren()){
// return early for last level:
if (depth < this->tree_depth){
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
updateInnerOccupancyRecurs(node->getChild(i), depth+1);
}
}
}
node->updateOccupancyChildren();
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::toMaxLikelihood() {
// convert bottom up
for (unsigned int depth=this->tree_depth; depth>0; depth--) {
toMaxLikelihoodRecurs(this->root, 0, depth);
}
// convert root
nodeToMaxLikelihood(this->root);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::toMaxLikelihoodRecurs(NODE* node, unsigned int depth,
unsigned int max_depth) {
if (depth < max_depth) {
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
toMaxLikelihoodRecurs(node->getChild(i), depth+1, max_depth);
}
}
}
else { // max level reached
nodeToMaxLikelihood(node);
}
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::castRay(const point3d& origin, const point3d& directionP, point3d& end,
bool ignoreUnknown, double maxRange) const {
/// ---------- see OcTreeBase::computeRayKeys -----------
// Initialization phase -------------------------------------------------------
OcTreeKey current_key;
if ( !OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::coordToKeyChecked(origin, current_key) ) {
OCTOMAP_WARNING_STR("Coordinates out of bounds during ray casting");
return false;
}
NODE* startingNode = this->search(current_key);
if (startingNode){
if (this->isNodeOccupied(startingNode)){
// Occupied node found at origin
// (need to convert from key, since origin does not need to be a voxel center)
end = this->keyToCoord(current_key);
return true;
}
} else if(!ignoreUnknown){
OCTOMAP_ERROR_STR("Origin node at " << origin << " for raycasting not found, does the node exist?");
end = this->keyToCoord(current_key);
return false;
}
point3d direction = directionP.normalized();
bool max_range_set = (maxRange > 0.0);
int step[3];
double tMax[3];
double tDelta[3];
for(unsigned int i=0; i < 3; ++i) {
// compute step direction
if (direction(i) > 0.0) step[i] = 1;
else if (direction(i) < 0.0) step[i] = -1;
else step[i] = 0;
// compute tMax, tDelta
if (step[i] != 0) {
// corner point of voxel (in direction of ray)
double voxelBorder = this->keyToCoord(current_key[i]);
voxelBorder += double(step[i] * this->resolution * 0.5);
tMax[i] = ( voxelBorder - origin(i) ) / direction(i);
tDelta[i] = this->resolution / fabs( direction(i) );
}
else {
tMax[i] = std::numeric_limits<double>::max();
tDelta[i] = std::numeric_limits<double>::max();
}
}
if (step[0] == 0 && step[1] == 0 && step[2] == 0){
OCTOMAP_ERROR("Raycasting in direction (0,0,0) is not possible!");
return false;
}
// for speedup:
double maxrange_sq = maxRange *maxRange;
// Incremental phase ---------------------------------------------------------
bool done = false;
while (!done) {
unsigned int dim;
// find minimum tMax:
if (tMax[0] < tMax[1]){
if (tMax[0] < tMax[2]) dim = 0;
else dim = 2;
}
else {
if (tMax[1] < tMax[2]) dim = 1;
else dim = 2;
}
// check for overflow:
if ((step[dim] < 0 && current_key[dim] == 0)
|| (step[dim] > 0 && current_key[dim] == 2* this->tree_max_val-1))
{
OCTOMAP_WARNING("Coordinate hit bounds in dim %d, aborting raycast\n", dim);
// return border point nevertheless:
end = this->keyToCoord(current_key);
return false;
}
// advance in direction "dim"
current_key[dim] += step[dim];
tMax[dim] += tDelta[dim];
// generate world coords from key
end = this->keyToCoord(current_key);
// check for maxrange:
if (max_range_set){
double dist_from_origin_sq(0.0);
for (unsigned int j = 0; j < 3; j++) {
dist_from_origin_sq += ((end(j) - origin(j)) * (end(j) - origin(j)));
}
if (dist_from_origin_sq > maxrange_sq)
return false;
}
NODE* currentNode = this->search(current_key);
if (currentNode){
if (this->isNodeOccupied(currentNode)) {
done = true;
break;
}
// otherwise: node is free and valid, raycasting continues
} else if (!ignoreUnknown){ // no node found, this usually means we are in "unknown" areas
OCTOMAP_WARNING_STR("Search failed in OcTree::castRay() => an unknown area was hit in the map: " << end);
return false;
}
} // end while
return true;
}
template <class NODE> inline bool
OccupancyOcTreeBase<NODE>::integrateMissOnRay(const point3d& origin, const point3d& end, bool lazy_eval) {
if (!this->computeRayKeys(origin, end, this->keyray)) {
return false;
}
for(KeyRay::iterator it=this->keyray.begin(); it != this->keyray.end(); ++it) {
updateNode(*it, false, lazy_eval); // insert freespace measurement
}
return true;
}
template <class NODE> bool
OccupancyOcTreeBase<NODE>::insertRay(const point3d& origin, const point3d& end, double maxrange, bool lazy_eval)
{
// cut ray at maxrange
if ((maxrange > 0) && ((end - origin).norm () > maxrange))
{
point3d direction = (end - origin).normalized ();
point3d new_end = origin + direction * (float) maxrange;
return integrateMissOnRay(origin, new_end,lazy_eval);
}
// insert complete ray
else
{
if (!integrateMissOnRay(origin, end,lazy_eval))
return false;
updateNode(end, true, lazy_eval); // insert hit cell
return true;
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(point3d_list& node_centers, unsigned int max_depth) const {
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it))
node_centers.push_back(it.getCoordinate());
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(std::list<OcTreeVolume>& occupied_nodes, unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it))
occupied_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupied(std::list<OcTreeVolume>& binary_nodes,
std::list<OcTreeVolume>& delta_nodes,
unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(this->isNodeOccupied(*it)){
if (it->getLogOdds() >= this->clamping_thres_max)
binary_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
else
delta_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getFreespace(std::list<OcTreeVolume>& free_nodes, unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(!this->isNodeOccupied(*it))
free_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getFreespace(std::list<OcTreeVolume>& binary_nodes,
std::list<OcTreeVolume>& delta_nodes,
unsigned int max_depth) const{
if (max_depth == 0)
max_depth = this->tree_depth;
for(typename OccupancyOcTreeBase<NODE>::leaf_iterator it = this->begin(max_depth),
end=this->end(); it!= end; ++it)
{
if(!this->isNodeOccupied(*it)){
if (it->getLogOdds() <= this->clamping_thres_min)
binary_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
else
delta_nodes.push_back(OcTreeVolume(it.getCoordinate(), it.getSize()));
}
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::setBBXMin (point3d& min) {
bbx_min = min;
if (!this->genKey(bbx_min, bbx_min_key)) {
OCTOMAP_ERROR("ERROR while generating bbx min key.\n");
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::setBBXMax (point3d& max) {
bbx_max = max;
if (!this->genKey(bbx_max, bbx_max_key)) {
OCTOMAP_ERROR("ERROR while generating bbx max key.\n");
}
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::inBBX(const point3d& p) const {
return ((p.x() >= bbx_min.x()) && (p.y() >= bbx_min.y()) && (p.z() >= bbx_min.z()) &&
(p.x() <= bbx_max.x()) && (p.y() <= bbx_max.y()) && (p.z() <= bbx_max.z()) );
}
template <class NODE>
bool OccupancyOcTreeBase<NODE>::inBBX(const OcTreeKey& key) const {
return ((key[0] >= bbx_min_key[0]) && (key[1] >= bbx_min_key[1]) && (key[2] >= bbx_min_key[2]) &&
(key[0] <= bbx_max_key[0]) && (key[1] <= bbx_max_key[1]) && (key[2] <= bbx_max_key[2]) );
}
template <class NODE>
point3d OccupancyOcTreeBase<NODE>::getBBXBounds () const {
octomap::point3d obj_bounds = (bbx_max - bbx_min);
obj_bounds /= 2.;
return obj_bounds;
}
template <class NODE>
point3d OccupancyOcTreeBase<NODE>::getBBXCenter () const {
octomap::point3d obj_bounds = (bbx_max - bbx_min);
obj_bounds /= 2.;
return bbx_min + obj_bounds;
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupiedLeafsBBX(point3d_list& node_centers, point3d min, point3d max) const {
OcTreeKey root_key, min_key, max_key;
root_key[0] = root_key[1] = root_key[2] = this->tree_max_val;
if (!this->genKey(min, min_key)) return;
if (!this->genKey(max, max_key)) return;
getOccupiedLeafsBBXRecurs(node_centers, this->tree_depth, this->root, 0, root_key, min_key, max_key);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::getOccupiedLeafsBBXRecurs( point3d_list& node_centers, unsigned int max_depth,
NODE* node, unsigned int depth, const OcTreeKey& parent_key,
const OcTreeKey& min, const OcTreeKey& max) const {
if (depth == max_depth) { // max level reached
if (this->isNodeOccupied(node)) {
node_centers.push_back(this->keyToCoords(parent_key, depth));
}
}
if (!node->hasChildren()) return;
unsigned short int center_offset_key = this->tree_max_val >> (depth + 1);
OcTreeKey child_key;
for (unsigned int i=0; i<8; ++i) {
if (node->childExists(i)) {
computeChildKey(i, center_offset_key, parent_key, child_key);
// overlap of query bbx and child bbx?
if (!(
( min[0] > (child_key[0] + center_offset_key)) ||
( max[0] < (child_key[0] - center_offset_key)) ||
( min[1] > (child_key[1] + center_offset_key)) ||
( max[1] < (child_key[1] - center_offset_key)) ||
( min[2] > (child_key[2] + center_offset_key)) ||
( max[2] < (child_key[2] - center_offset_key))
)) {
getOccupiedLeafsBBXRecurs(node_centers, max_depth, node->getChild(i), depth+1, child_key, min, max);
}
}
}
}
// -- I/O -----------------------------------------
template <class NODE>
std::istream& OccupancyOcTreeBase<NODE>::readBinaryData(std::istream &s){
this->readBinaryNode(s, this->root);
this->size_changed = true;
this->tree_size = OcTreeBaseImpl<NODE,AbstractOccupancyOcTree>::calcNumNodes(); // compute number of nodes
return s;
}
template <class NODE>
std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryData(std::ostream &s) const{
OCTOMAP_DEBUG("Writing %u nodes to output stream...", static_cast<unsigned int>(this->size()));
this->writeBinaryNode(s, this->root);
return s;
}
template <class NODE>
std::istream& OccupancyOcTreeBase<NODE>::readBinaryNode(std::istream &s, NODE* node) const {
char child1to4_char;
char child5to8_char;
s.read((char*)&child1to4_char, sizeof(char));
s.read((char*)&child5to8_char, sizeof(char));
std::bitset<8> child1to4 ((unsigned long long) child1to4_char);
std::bitset<8> child5to8 ((unsigned long long) child5to8_char);
// std::cout << "read: "
// << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " "
// << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl;
// inner nodes default to occupied
node->setLogOdds(this->clamping_thres_max);
for (unsigned int i=0; i<4; i++) {
if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 0)) {
// child is free leaf
node->createChild(i);
node->getChild(i)->setLogOdds(this->clamping_thres_min);
}
else if ((child1to4[i*2] == 0) && (child1to4[i*2+1] == 1)) {
// child is occupied leaf
node->createChild(i);
node->getChild(i)->setLogOdds(this->clamping_thres_max);
}
else if ((child1to4[i*2] == 1) && (child1to4[i*2+1] == 1)) {
// child has children
node->createChild(i);
node->getChild(i)->setLogOdds(-200.); // child is unkown, we leave it uninitialized
}
}
for (unsigned int i=0; i<4; i++) {
if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 0)) {
// child is free leaf
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(this->clamping_thres_min);
}
else if ((child5to8[i*2] == 0) && (child5to8[i*2+1] == 1)) {
// child is occupied leaf
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(this->clamping_thres_max);
}
else if ((child5to8[i*2] == 1) && (child5to8[i*2+1] == 1)) {
// child has children
node->createChild(i+4);
node->getChild(i+4)->setLogOdds(-200.); // set occupancy when all children have been read
}
// child is unkown, we leave it uninitialized
}
// read children's children and set the label
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
NODE* child = node->getChild(i);
if (fabs(child->getLogOdds() + 200.)<1e-3) {
readBinaryNode(s, child);
child->setLogOdds(child->getMaxChildLogOdds());
}
} // end if child exists
} // end for children
return s;
}
template <class NODE>
std::ostream& OccupancyOcTreeBase<NODE>::writeBinaryNode(std::ostream &s, const NODE* node) const{
// 2 bits for each children, 8 children per node -> 16 bits
std::bitset<8> child1to4;
std::bitset<8> child5to8;
// 10 : child is free node
// 01 : child is occupied node
// 00 : child is unkown node
// 11 : child has children
// speedup: only set bits to 1, rest is init with 0 anyway,
// can be one logic expression per bit
for (unsigned int i=0; i<4; i++) {
if (node->childExists(i)) {
const NODE* child = node->getChild(i);
if (child->hasChildren()) { child1to4[i*2] = 1; child1to4[i*2+1] = 1; }
else if (this->isNodeOccupied(child)) { child1to4[i*2] = 0; child1to4[i*2+1] = 1; }
else { child1to4[i*2] = 1; child1to4[i*2+1] = 0; }
}
else {
child1to4[i*2] = 0; child1to4[i*2+1] = 0;
}
}
for (unsigned int i=0; i<4; i++) {
if (node->childExists(i+4)) {
const NODE* child = node->getChild(i+4);
if (child->hasChildren()) { child5to8[i*2] = 1; child5to8[i*2+1] = 1; }
else if (this->isNodeOccupied(child)) { child5to8[i*2] = 0; child5to8[i*2+1] = 1; }
else { child5to8[i*2] = 1; child5to8[i*2+1] = 0; }
}
else {
child5to8[i*2] = 0; child5to8[i*2+1] = 0;
}
}
// std::cout << "wrote: "
// << child1to4.to_string<char,std::char_traits<char>,std::allocator<char> >() << " "
// << child5to8.to_string<char,std::char_traits<char>,std::allocator<char> >() << std::endl;
char child1to4_char = (char) child1to4.to_ulong();
char child5to8_char = (char) child5to8.to_ulong();
s.write((char*)&child1to4_char, sizeof(char));
s.write((char*)&child5to8_char, sizeof(char));
// write children's children
for (unsigned int i=0; i<8; i++) {
if (node->childExists(i)) {
const NODE* child = node->getChild(i);
if (child->hasChildren()) {
writeBinaryNode(s, child);
}
}
}
return s;
}
//-- Occupancy queries on nodes:
template <class NODE>
void OccupancyOcTreeBase<NODE>::updateNodeLogOdds(NODE* occupancyNode, const float& update) const {
occupancyNode->addValue(update);
if (occupancyNode->getLogOdds() < this->clamping_thres_min) {
occupancyNode->setLogOdds(this->clamping_thres_min);
return;
}
if (occupancyNode->getLogOdds() > this->clamping_thres_max) {
occupancyNode->setLogOdds(this->clamping_thres_max);
}
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::integrateHit(NODE* occupancyNode) const {
updateNodeLogOdds(occupancyNode, this->prob_hit_log);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::integrateMiss(NODE* occupancyNode) const {
updateNodeLogOdds(occupancyNode, this->prob_miss_log);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE* occupancyNode) const{
if (this->isNodeOccupied(occupancyNode))
occupancyNode->setLogOdds(this->clamping_thres_max);
else
occupancyNode->setLogOdds(this->clamping_thres_min);
}
template <class NODE>
void OccupancyOcTreeBase<NODE>::nodeToMaxLikelihood(NODE& occupancyNode) const{
if (this->isNodeOccupied(occupancyNode))
occupancyNode.setLogOdds(this->clamping_thres_max);
else
occupancyNode.setLogOdds(this->clamping_thres_min);
}
} // namespace
| 35.819604 | 170 | 0.623446 | feroze |
13cb4600cd0847afe1d5de708f5be41f1f87540d | 8,583 | cc | C++ | cc/subtle/aes_gcm_hkdf_streaming_test.cc | rohansingh/tink | c2338bef4663870d3855fb0236ab0092d976434d | [
"Apache-2.0"
] | 1 | 2022-03-15T03:21:44.000Z | 2022-03-15T03:21:44.000Z | cc/subtle/aes_gcm_hkdf_streaming_test.cc | frankfanslc/tink | fee9b771017baeaa65f13f82c8a10b3a1119d44d | [
"Apache-2.0"
] | null | null | null | cc/subtle/aes_gcm_hkdf_streaming_test.cc | frankfanslc/tink | fee9b771017baeaa65f13f82c8a10b3a1119d44d | [
"Apache-2.0"
] | null | null | null | // Copyright 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 "tink/subtle/aes_gcm_hkdf_streaming.h"
#include <sstream>
#include <string>
#include <utility>
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/status/status.h"
#include "absl/strings/str_cat.h"
#include "tink/config/tink_fips.h"
#include "tink/output_stream.h"
#include "tink/subtle/common_enums.h"
#include "tink/subtle/random.h"
#include "tink/subtle/streaming_aead_test_util.h"
#include "tink/subtle/test_util.h"
#include "tink/util/istream_input_stream.h"
#include "tink/util/ostream_output_stream.h"
#include "tink/util/status.h"
#include "tink/util/statusor.h"
#include "tink/util/test_matchers.h"
namespace crypto {
namespace tink {
namespace subtle {
namespace {
using ::crypto::tink::test::IsOk;
using ::crypto::tink::test::StatusIs;
TEST(AesGcmHkdfStreamingTest, testBasic) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
for (HashType hkdf_hash : {SHA1, SHA256, SHA512}) {
for (int ikm_size : {16, 32}) {
for (int derived_key_size = 16;
derived_key_size <= ikm_size;
derived_key_size += 16) {
for (int ct_segment_size : {80, 128, 200}) {
for (int ciphertext_offset : {0, 10, 16}) {
SCOPED_TRACE(absl::StrCat(
"hkdf_hash = ", EnumToString(hkdf_hash),
", ikm_size = ", ikm_size,
", derived_key_size = ", derived_key_size,
", ciphertext_segment_size = ", ct_segment_size,
", ciphertext_offset = ", ciphertext_offset));
// Create AesGcmHkdfStreaming.
AesGcmHkdfStreaming::Params params;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.hkdf_hash = hkdf_hash;
params.derived_key_size = derived_key_size;
params.ciphertext_segment_size = ct_segment_size;
params.ciphertext_offset = ciphertext_offset;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_TRUE(result.ok()) << result.status();
auto streaming_aead = std::move(result.ValueOrDie());
// Try to get an encrypting stream to a "null" ct_destination.
std::string associated_data = "some associated data";
auto failed_result = streaming_aead->NewEncryptingStream(
nullptr, associated_data);
EXPECT_FALSE(failed_result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument,
failed_result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "non-null",
std::string(failed_result.status().message()));
for (int pt_size : {0, 16, 100, 1000, 10000}) {
SCOPED_TRACE(absl::StrCat(" pt_size = ", pt_size));
std::string pt = Random::GetRandomBytes(pt_size);
EXPECT_THAT(
EncryptThenDecrypt(streaming_aead.get(), streaming_aead.get(),
pt, associated_data, ciphertext_offset),
IsOk());
}
}
}
}
}
}
}
TEST(AesGcmHkdfStreamingTest, testIkmSmallerThanDerivedKey) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 16;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 17;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testIkmSize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
for (int ikm_size : {5, 10, 15}) {
AesGcmHkdfStreaming::Params params;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 17;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 0;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ikm too small",
std::string(result.status().message()));
}
}
TEST(AesGcmHkdfStreamingTest, testWrongHkdfHash) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 16;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 16;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA384;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "unsupported hkdf_hash",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongDerivedKeySize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 20;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 20;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = 10;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be 16 or 32",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongCiphertextOffset) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 100;
params.ciphertext_offset = -5;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "must be non-negative",
std::string(result.status().message()));
}
TEST(AesGcmHkdfStreamingTest, testWrongCiphertextSegmentSize) {
if (IsFipsModeEnabled()) {
GTEST_SKIP() << "Not supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 64;
params.ciphertext_offset = 40;
params.hkdf_hash = SHA256;
auto result = AesGcmHkdfStreaming::New(std::move(params));
EXPECT_FALSE(result.ok());
EXPECT_EQ(absl::StatusCode::kInvalidArgument, result.status().code());
EXPECT_PRED_FORMAT2(testing::IsSubstring, "ciphertext_segment_size too small",
std::string(result.status().message()));
}
// FIPS only mode tests
TEST(AesGcmHkdfStreamingTest, TestFipsOnly) {
if (!IsFipsModeEnabled()) {
GTEST_SKIP() << "Only supported in FIPS-only mode";
}
AesGcmHkdfStreaming::Params params;
int ikm_size = 32;
params.ikm = Random::GetRandomKeyBytes(ikm_size);
params.derived_key_size = 32;
params.ciphertext_segment_size = 64;
params.ciphertext_offset = 40;
params.hkdf_hash = SHA256;
EXPECT_THAT(AesGcmHkdfStreaming::New(std::move(params)).status(),
StatusIs(absl::StatusCode::kInternal));
}
} // namespace
} // namespace subtle
} // namespace tink
} // namespace crypto
| 36.368644 | 80 | 0.670628 | rohansingh |
13d525628e0cd5326d11d9868b0bc43343a73ae6 | 1,863 | hpp | C++ | include/voxel/async_structure.hpp | InjectorGames/VoxelLibrary | be8cc4ec179e9d86eb1bd25b1c7f8adfe8ad4198 | [
"BSD-3-Clause"
] | 1 | 2021-09-16T12:30:49.000Z | 2021-09-16T12:30:49.000Z | include/voxel/async_structure.hpp | InjectorGames/VoxelSpaceCPP | be8cc4ec179e9d86eb1bd25b1c7f8adfe8ad4198 | [
"BSD-3-Clause"
] | 1 | 2020-05-08T14:24:41.000Z | 2020-05-08T14:24:41.000Z | include/voxel/async_structure.hpp | InjectorGames/Voxel | be8cc4ec179e9d86eb1bd25b1c7f8adfe8ad4198 | [
"BSD-3-Clause"
] | null | null | null | #pragma once
#include <voxel/structure.hpp>
#include <mutex>
#include <thread>
namespace VOXEL_NAMESPACE
{
template<class T = Sector>
class AsyncStructure : public Structure<T>
{
protected:
bool isRunning;
std::mutex updateMutex;
std::thread updateThread;
inline void update(const Registry& registry)
{
std::chrono::steady_clock::time_point lastTime;
while (isRunning)
{
updateMutex.lock();
const auto time = std::chrono::high_resolution_clock::now();
const auto deltaTime = std::chrono::duration_cast<
std::chrono::duration<time_t>>(time - lastTime);
lastTime = time;
Structure<T>::update(registry, deltaTime.count());
if (sleepDelay > 0)
std::this_thread::sleep_for(std::chrono::milliseconds(sleepDelay));
updateMutex.unlock();
}
}
public:
int sleepDelay;
AsyncStructure(const size3_t& size,
const structure_pos_t& position,
const std::shared_ptr<T> sector,
const int _sleepDelay = 1) :
Structure<T>(size, position, sector),
sleepDelay(_sleepDelay),
isRunning(false),
updateMutex(),
updateThread()
{}
virtual ~AsyncStructure()
{
if (isRunning)
stopUpdate();
}
AsyncStructure(const AsyncStructure<T>&) = delete;
inline void lockUpdate() noexcept
{
updateMutex.lock();
}
inline void unlockUpdate() noexcept
{
updateMutex.unlock();
}
inline void startUpdate(const Registry& registry)
{
if (isRunning)
throw std::runtime_error("Thread is already running");
isRunning = true;
updateThread = std::thread(&AsyncStructure<T>::update, this, registry);
}
inline void stopUpdate()
{
if (!isRunning)
throw std::runtime_error("Thread is not running");
isRunning = false;
if (updateThread.get_id() != std::this_thread::get_id() &&
updateThread.joinable())
updateThread.join();
}
};
}
| 21.170455 | 74 | 0.677939 | InjectorGames |
13d5ebf1966fb98094358874f434b429b88f6306 | 1,316 | cpp | C++ | luogu/P1160.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | 1 | 2020-07-24T03:07:08.000Z | 2020-07-24T03:07:08.000Z | luogu/P1160.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | null | null | null | luogu/P1160.cpp | delphi122/knowledge_planet | e86cb8f9aa47ef8918cde0e814984a6535023c21 | [
"Apache-2.0"
] | null | null | null | //
// Created by yangtao on 20-5-29.
//
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <map>
using namespace std;
struct Node {
Node *left, *right;
int no;
};
map<int, Node*> s;
int n,m;
Node *h , *p;
int main() {
cin >> n;
h = new Node;
Node *t = new Node;
t->no = 1;
h->right = t;
t->left = h;
s[1] = t;
for(int i = 2; i <= n; i++) {
Node *node = new Node;
node->no = i;
int k, q;
scanf("%d%d", &k, &q);
p = h->right;
s[i] = node;
p = s[k];
if(q == 0) {
node->left = p->left;
node->right = p;
p->left->right = node;
p->left = node;
} else {
node->right = p->right;
node->left = p;
p->right = node;
if(node->right)
node->right->left = node;
}
}
cin >> m;
for(int i = 0 ; i < m; i++) {
int q;
scanf("%d", &q);
if(s.find(q) == s.end()) continue;
p = s[q];
s.erase(q);
p->left->right = p->right;
if(p->right) {
p->right->left = p->left;
}
}
p = h->right;
while(p) {
printf("%d ", p->no);
p = p->right;
}
return 0;
} | 18.535211 | 42 | 0.395137 | delphi122 |
13dfc95fad116c2c0a698cf25fcdf84da2d814e9 | 2,902 | cpp | C++ | src/libcore/src/ccmrt/system/SocketTagger.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 6 | 2018-05-08T10:08:21.000Z | 2021-11-13T13:22:58.000Z | src/libcore/src/ccmrt/system/SocketTagger.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 1 | 2018-05-08T10:20:17.000Z | 2018-07-23T05:19:19.000Z | src/libcore/src/ccmrt/system/SocketTagger.cpp | sparkoss/ccm | 9ed67a7cbdc9c69f4182e72be8e8b6b23d7c3c8d | [
"Apache-2.0"
] | 4 | 2018-03-13T06:21:11.000Z | 2021-06-19T02:48:07.000Z | //=========================================================================
// Copyright (C) 2018 The C++ Component Model(CCM) Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//=========================================================================
#include "ccmrt/system/SocketTagger.h"
#include "ccm.io.IFileDescriptor.h"
#include <ccmlogger.h>
using ccm::io::IFileDescriptor;
namespace ccmrt {
namespace system {
CCM_INTERFACE_IMPL_1(SocketTagger, SyncObject, ISocketTagger);
AutoPtr<ISocketTagger> SocketTagger::GetOrSet(
/* [in] */ ISocketTagger* tagger)
{
class _SocketTagger
: public SocketTagger
{
public:
ECode Tag(
/* [in] */ IFileDescriptor* socketDescriptor) override
{
return NOERROR;
}
ECode Untag(
/* [in] */ IFileDescriptor* socketDescriptor) override
{
return NOERROR;
}
};
static AutoPtr<ISocketTagger> sTagger = new _SocketTagger();
if (tagger != nullptr) {
sTagger = tagger;
}
return sTagger;
}
ECode SocketTagger::Tag(
/* [in] */ ISocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Tag(fd);
}
return NOERROR;
}
ECode SocketTagger::Untag(
/* [in] */ ISocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Untag(fd);
}
return NOERROR;
}
ECode SocketTagger::Tag(
/* [in] */ IDatagramSocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Tag(fd);
}
return NOERROR;
}
ECode SocketTagger::Untag(
/* [in] */ IDatagramSocket* socket)
{
Boolean closed;
if (socket->IsClosed(&closed), !closed) {
AutoPtr<IFileDescriptor> fd;
socket->GetFileDescriptor(&fd);
return Untag(fd);
}
return NOERROR;
}
ECode SocketTagger::Set(
/* [in] */ ISocketTagger* tagger)
{
if (tagger == nullptr) {
Logger::E("SocketTagger", "tagger == null");
return ccm::core::E_NULL_POINTER_EXCEPTION;
}
GetOrSet(tagger);
return NOERROR;
}
}
}
| 25.017241 | 75 | 0.599931 | sparkoss |
13e09d8dc5005b4bf52881df046f474e42469bf2 | 1,595 | cpp | C++ | src/tuning/coefficients.cpp | pyxis-roc/sass-math | 0d6d4413e89101366c5b49d62c466e0567bef735 | [
"MIT"
] | null | null | null | src/tuning/coefficients.cpp | pyxis-roc/sass-math | 0d6d4413e89101366c5b49d62c466e0567bef735 | [
"MIT"
] | 1 | 2021-09-23T17:46:24.000Z | 2021-09-23T17:46:24.000Z | src/tuning/coefficients.cpp | pyxis-roc/sass-math | 0d6d4413e89101366c5b49d62c466e0567bef735 | [
"MIT"
] | null | null | null | #include "coefficients.hpp"
#include "bias.hpp"
#include <cstddef>
enum direction
{
DOWN,
UP,
UNKNOWN
};
std::tuple<uint64_t, std::array<uint32_t, 3>, counters>
coefficient_search(const eval_t<uint64_t, const std::array<uint32_t, 3> &> &eval,
const std::array<bool, 3> &negated,
const std::array<uint32_t, 3> &initial)
{
counters count;
uint64_t bias;
std::array<uint32_t, 3> coefficients = initial;
const auto bias_eval = [&coefficients, &eval](uint64_t bias) -> counters
{
return eval(bias, coefficients);
};
std::array<direction, 3> directions = {UNKNOWN, UNKNOWN, UNKNOWN};
while (true)
{
std::tie(bias, count) = bias_search(bias_eval);
if (count.regions() == 0u)
break;
if (count.regions() > 3u)
break;
std::size_t edit = count.regions() - 1u;
direction dir = (count.last() == counters::NEGATIVE) ? UP : DOWN;
if (negated[edit])
dir = (dir == DOWN) ? UP : DOWN;
if (directions[edit] == UNKNOWN)
{
directions[edit] = dir;
}
else if (directions[edit] != dir)
{
if (++edit > 2u)
break;
}
if (directions[edit] == DOWN)
coefficients[edit]--;
else
coefficients[edit]++; // UP is arbitrary for UNKNOWN case
for (std::size_t i = 0; i < edit; i++)
{
directions[i] = UNKNOWN;
}
}
return std::make_tuple(bias, coefficients, count);
}
| 23.115942 | 81 | 0.530408 | pyxis-roc |
13e1b4b357987a32394e5473d995d91316e7bb90 | 1,197 | cpp | C++ | Aphelion/Src/Aphelion/Renderer/old/Renderer.cpp | antjowie/AphelionWeb | e616806844bb06914b32395b2e4998ac518b3773 | [
"MIT"
] | null | null | null | Aphelion/Src/Aphelion/Renderer/old/Renderer.cpp | antjowie/AphelionWeb | e616806844bb06914b32395b2e4998ac518b3773 | [
"MIT"
] | null | null | null | Aphelion/Src/Aphelion/Renderer/old/Renderer.cpp | antjowie/AphelionWeb | e616806844bb06914b32395b2e4998ac518b3773 | [
"MIT"
] | null | null | null | #include "Aphelion/Renderer/Renderer.h"
#include <glm/gtc/type_ptr.hpp>
#include "Aphelion/Renderer/RenderCommand.h"
#include "Aphelion/Renderer/Renderer2D.h"
namespace ap {
struct RendererData {
// PerspectiveCamera camera;
glm::mat4 view;
glm::mat4 projection;
};
static RendererData data;
void Renderer::Init() {
RenderCommand::Init();
Renderer2D::Init();
}
void Renderer::Deinit() { Renderer2D::Deinit(); }
void Renderer::OnWindowResize(uint32_t width, uint32_t height) {
RenderCommand::SetViewport(0, 0, width, height);
}
void Renderer::BeginScene(const PerspectiveCamera& camera) {
data.view = camera.GetViewMatrix();
data.projection = camera.GetProjectionMatrix();
}
void Renderer::EndScene() {}
void Renderer::Submit(const ShaderRef& shader,
const VertexArrayRef& vertexArray,
const glm::mat4& transform) {
// shader->Bind();
shader->SetMat4("aTransform", glm::value_ptr(transform));
shader->SetMat4("aVP", glm::value_ptr(data.projection * data.view));
vertexArray->Bind();
RenderCommand::DrawIndexed(vertexArray,
vertexArray->GetIndexBuffer()->GetCount());
}
} // namespace ap | 25.468085 | 72 | 0.687552 | antjowie |
13e675b8faae7b8ca0101fe15d29d0b5e109a50d | 1,937 | cpp | C++ | Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/mouse.cpp | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 45 | 2017-07-24T05:31:06.000Z | 2019-03-29T12:23:57.000Z | Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/mouse.cpp | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 7 | 2019-01-14T14:46:46.000Z | 2019-01-25T20:57:05.000Z | Real-Time Corruptor/BizHawk_RTC/waterbox/pcfx/input/mouse.cpp | redscientistlabs/Bizhawk50X-Vanguard | 96e0f5f87671a1230784c8faf935fe70baadfe48 | [
"MIT"
] | 10 | 2017-07-24T02:11:43.000Z | 2018-12-27T20:49:37.000Z | /******************************************************************************/
/* Mednafen NEC PC-FX Emulation Module */
/******************************************************************************/
/* mouse.cpp:
** Copyright (C) 2007-2016 Mednafen Team
**
** This program is free software; you can redistribute it and/or
** modify it under the terms of the GNU General Public License
** as published by the Free Software Foundation; either version 2
** of the License, or (at your option) any later version.
**
** This program is distributed in the hope that it will be useful,
** but WITHOUT ANY WARRANTY; without even the implied warranty of
** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
** GNU General Public License for more details.
**
** You should have received a copy of the GNU General Public License
** along with this program; if not, write to the Free Software Foundation, Inc.,
** 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
#include "../pcfx.h"
#include "../input.h"
#include "mouse.h"
namespace MDFN_IEN_PCFX
{
class PCFX_Input_Mouse : public PCFX_Input_Device
{
public:
PCFX_Input_Mouse(int which)
{
dx = 0;
dy = 0;
button = 0;
}
virtual ~PCFX_Input_Mouse() override
{
}
virtual uint32 ReadTransferTime(void) override
{
return (1536);
}
virtual uint32 WriteTransferTime(void) override
{
return (1536);
}
virtual uint32 Read(void) override
{
return FX_SIG_MOUSE << 28 | button << 16 | dx << 8 | dy;
}
virtual void Write(uint32 data) override
{
}
virtual void Power(void) override
{
button = 0;
dx = 0;
dy = 0;
}
virtual void Frame(uint32_t data) override
{
dx = data;
dy = data >> 8;
button = data >> 16 & 3;
}
private:
int8 dx, dy;
// 76543210
// ......RL
uint8 button;
};
PCFX_Input_Device *PCFXINPUT_MakeMouse(int which)
{
return new PCFX_Input_Mouse(which);
}
}
| 21.764045 | 80 | 0.620031 | redscientistlabs |
13e74812db5607c4ddf8cda57e390643adb2baba | 1,646 | cpp | C++ | XBT/misc/xcc_z.cpp | 3evils/pub | 3f0f8e39e6297657ca7e088c0e3250f5c52c9e70 | [
"WTFPL"
] | null | null | null | XBT/misc/xcc_z.cpp | 3evils/pub | 3f0f8e39e6297657ca7e088c0e3250f5c52c9e70 | [
"WTFPL"
] | null | null | null | XBT/misc/xcc_z.cpp | 3evils/pub | 3f0f8e39e6297657ca7e088c0e3250f5c52c9e70 | [
"WTFPL"
] | null | null | null | #include "xbt/xcc_z.h"
#include <cstdio>
#include <string.h>
#include <zlib.h>
#include "stream_int.h"
shared_data xcc_z::gunzip(data_ref s)
{
if (s.size() < 18)
return shared_data();
shared_data d(read_int_le(4, s.end() - 4));
z_stream stream;
stream.zalloc = NULL;
stream.zfree = NULL;
stream.opaque = NULL;
stream.next_in = const_cast<unsigned char*>(s.begin()) + 10;
stream.avail_in = s.size() - 18;
stream.next_out = d.data();
stream.avail_out = d.size();
return stream.next_out
&& Z_OK == inflateInit2(&stream, -MAX_WBITS)
&& Z_STREAM_END == inflate(&stream, Z_FINISH)
&& Z_OK == inflateEnd(&stream)
? d
: shared_data();
}
shared_data xcc_z::gzip(data_ref s)
{
unsigned long cb_d = s.size() + (s.size() + 999) / 1000 + 12;
shared_data d(10 + cb_d + 8);
unsigned char* w = d.data();
*w++ = 0x1f;
*w++ = 0x8b;
*w++ = Z_DEFLATED;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 0;
*w++ = 3;
{
z_stream stream;
stream.zalloc = NULL;
stream.zfree = NULL;
stream.opaque = NULL;
deflateInit2(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -MAX_WBITS, MAX_MEM_LEVEL, Z_DEFAULT_STRATEGY);
stream.next_in = const_cast<unsigned char*>(s.begin());
stream.avail_in = s.size();
stream.next_out = w;
stream.avail_out = cb_d;
deflate(&stream, Z_FINISH);
deflateEnd(&stream);
w = stream.next_out;
}
w = write_int_le(4, w, crc32(crc32(0, NULL, 0), s.data(), s.size()));
w = write_int_le(4, w, s.size());
return d.substr(0, w - d.data());
}
/*
void xcc_z::gzip_out(data_ref s)
{
gzFile f = gzdopen(fileno(stdout), "wb");
gzwrite(f, s.data(), s.size());
gzflush(f, Z_FINISH);
}
*/
| 23.183099 | 106 | 0.631835 | 3evils |
13e7a9f37a885b46be168375bc57e9bd92706076 | 1,724 | hxx | C++ | opencascade/GeomToStep_MakeAxis2Placement2d.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/GeomToStep_MakeAxis2Placement2d.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | opencascade/GeomToStep_MakeAxis2Placement2d.hxx | mgreminger/OCP | 92eacb99497cd52b419c8a4a8ab0abab2330ed42 | [
"Apache-2.0"
] | null | null | null | // Created on: 1994-08-26
// Created by: Frederic MAUPAS
// Copyright (c) 1994-1999 Matra Datavision
// Copyright (c) 1999-2014 OPEN CASCADE SAS
//
// This file is part of Open CASCADE Technology software library.
//
// This library is free software; you can redistribute it and/or modify it under
// the terms of the GNU Lesser General Public License version 2.1 as published
// by the Free Software Foundation, with special exception defined in the file
// OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT
// distribution for complete text of the license and disclaimer of any warranty.
//
// Alternatively, this file may be used under the terms of Open CASCADE
// commercial license or contractual agreement.
#ifndef _GeomToStep_MakeAxis2Placement2d_HeaderFile
#define _GeomToStep_MakeAxis2Placement2d_HeaderFile
#include <Standard.hxx>
#include <Standard_DefineAlloc.hxx>
#include <Standard_Handle.hxx>
#include <GeomToStep_Root.hxx>
class StepGeom_Axis2Placement2d;
class gp_Ax2;
class gp_Ax22d;
//! This class implements the mapping between classes
//! Axis2Placement from Geom and Ax2, Ax22d from gp, and the class
//! Axis2Placement2d from StepGeom which describes an
//! axis2_placement_2d from Prostep.
class GeomToStep_MakeAxis2Placement2d : public GeomToStep_Root
{
public:
DEFINE_STANDARD_ALLOC
Standard_EXPORT GeomToStep_MakeAxis2Placement2d(const gp_Ax2& A);
Standard_EXPORT GeomToStep_MakeAxis2Placement2d(const gp_Ax22d& A);
Standard_EXPORT const Handle(StepGeom_Axis2Placement2d)& Value() const;
protected:
private:
Handle(StepGeom_Axis2Placement2d) theAxis2Placement2d;
};
#endif // _GeomToStep_MakeAxis2Placement2d_HeaderFile
| 23.944444 | 81 | 0.792343 | mgreminger |
13ebdf2f3e672f167ff22ecfc1c9a8f60095ad12 | 6,197 | cpp | C++ | problems/atcoder/abc223/f---parenthesis-checking/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | 7 | 2020-10-15T22:37:10.000Z | 2022-02-26T17:23:49.000Z | problems/atcoder/abc223/f---parenthesis-checking/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | problems/atcoder/abc223/f---parenthesis-checking/code.cpp | brunodccarvalho/competitive | 4177c439174fbe749293b9da3445ce7303bd23c2 | [
"MIT"
] | null | null | null | #include <bits/stdc++.h>
#ifdef LOCAL
#include "code/formatting.hpp"
#else
#define debug(...) (void)0
#endif
using namespace std;
template <typename Node>
struct segtree {
vector<Node> node;
vector<array<int, 2>> range;
vector<int> where;
segtree() = default;
segtree(int L, int R, Node init) { assign(L, R, init); }
template <typename T>
segtree(int L, int R, const vector<T>& arr, int s = 0) {
assign(L, R, arr, s);
}
void assign(int L, int R, Node init) {
int N = R - L;
node.assign(2 * N, init);
range.resize(2 * N);
where.resize(N);
int Q = 1 << (N > 1 ? 8 * sizeof(N) - __builtin_clz(N - 1) : 0);
for (int i = 0; i < N; i++) {
range[i + N] = {L + i, L + i + 1};
}
rotate(begin(range) + N, begin(range) + (3 * N - Q), end(range));
for (int i = 0; i < N; i++) {
where[range[i + N][0] - L] = i + N;
}
for (int u = N - 1; u >= 1; u--) {
range[u] = {range[u << 1][0], range[u << 1 | 1][1]};
pushup(u);
}
}
template <typename T>
void assign(int L, int R, const vector<T>& arr, int s = 0) {
int N = R - L;
node.resize(2 * N);
range.resize(2 * N);
where.resize(N);
int Q = 1 << (N > 1 ? 8 * sizeof(N) - __builtin_clz(N - 1) : 0);
for (int i = 0; i < N; i++) {
range[i + N] = {L + i, L + i + 1};
node[i + N] = Node(arr[L + i - s]);
}
rotate(begin(range) + N, begin(range) + (3 * N - Q), end(range));
rotate(begin(node) + N, begin(node) + (3 * N - Q), end(node));
for (int i = 0; i < N; i++) {
where[range[i + N][0] - L] = i + N;
}
for (int u = N - 1; u >= 1; u--) {
range[u] = {range[u << 1][0], range[u << 1 | 1][1]};
pushup(u);
}
}
auto query_point(int i) const {
assert(range[1][0] <= i && i < range[1][1]);
int u = where[i - range[1][0]];
return node[u];
}
template <typename Update>
void update_point(int i, Update&& update) {
assert(range[1][0] <= i && i < range[1][1]);
int u = where[i - range[1][0]];
apply(u, update);
while ((u >>= 1) >= 1) {
pushup(u);
}
}
auto query_range(int L, int R) const {
assert(range[1][0] <= L && R <= range[1][1]);
return query_range(1, L, R);
}
auto query_all() const { return node[1]; }
// Find first i>=k such that fn([L,i]) holds, or R otherwise
// Fn is F F F F T T T T ...
template <typename Fn>
int prefix_binary_search(int k, Fn&& fn) {
auto [L, R] = range[1];
Node ans;
int i = 1, N = R - L;
while (i < N) {
Node v = combine(ans, node[i << 1]);
if (range[i << 1][1] <= k || !fn(v)) {
ans = move(v);
i = i << 1 | 1;
} else {
i = i << 1;
}
}
Node v = combine(ans, node[i]);
return range[i][0] + !fn(v);
}
// Find last i<=k such that fn([i,R)) holds, or L-1 otherwise
// Fn is T T T T F F F F ...
template <typename Fn>
int suffix_binary_search(int k, Fn&& fn) {
auto [L, R] = range[1];
Node ans;
int i = 1, N = R - L;
while (i < N) {
Node v = combine(node[i << 1 | 1], ans);
if (k < range[i << 1][1] || !fn(v)) {
ans = move(v);
i = i << 1;
} else {
i = i << 1 | 1;
}
}
Node v = combine(ans, node[i]);
return range[i][0] - !fn(v);
}
template <typename Fn>
int prefix_binary_search(Fn&& fn) {
return prefix_binary_search(range[1][0], forward<Fn>(fn));
}
template <typename Fn>
int suffix_binary_search(Fn&& fn) {
return suffix_binary_search(range[1][1] - 1, forward<Fn>(fn));
}
private:
static Node combine(const Node& x, const Node& y) {
Node ans;
ans.pushup(x, y);
return ans;
}
template <typename Update>
void apply(int u, Update&& update) {
if constexpr (Node::RANGES) {
node[u].apply(update, 1);
} else {
node[u].apply(update);
}
}
void pushup(int u) {
node[u].pushup(node[u << 1], node[u << 1 | 1]); //
}
auto query_range(int u, int L, int R) const {
if (L <= range[u][0] && range[u][1] <= R) {
return node[u];
}
int m = range[u << 1][1];
if (R <= m) {
return query_range(u << 1, L, R);
} else if (m <= L) {
return query_range(u << 1 | 1, L, R);
} else {
return combine(query_range(u << 1, L, m), query_range(u << 1 | 1, m, R));
}
}
};
struct segnode {
static constexpr bool LAZY = false, RANGES = false, REVERSE = false;
int side = 0; // +1 for (, -1 for )
int minprefix = 0; // should be 0
segnode() = default;
segnode(int side) : side(side), minprefix(side) { assert(side == +1 || side == -1); }
void pushup(const segnode& lhs, const segnode& rhs) {
side = lhs.side + rhs.side;
minprefix = min(lhs.minprefix, lhs.side + rhs.minprefix);
}
void apply(int set) { side = minprefix = set; }
};
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr);
int N, Q;
cin >> N >> Q;
string s;
cin >> s;
vector<int> side(N);
for (int i = 0; i < N; i++) {
side[i] = s[i] == '(' ? +1 : -1;
}
segtree<segnode> st(0, N, side);
while (Q--) {
int type, l, r;
cin >> type >> l >> r, l--, r--;
if (type == 1 && side[l] != side[r]) {
st.update_point(l, side[r]);
st.update_point(r, side[l]);
swap(side[l], side[r]);
} else if (type == 2) {
auto ans = st.query_range(l, r + 1);
if (ans.side == 0 && ans.minprefix == 0) {
cout << "Yes\n";
} else {
cout << "No\n";
}
}
}
return 0;
}
| 28.168182 | 89 | 0.442472 | brunodccarvalho |
13eee5b68494bb7e016ac2fb5179230f25e60262 | 2,032 | hpp | C++ | lib/lvd/read_bin_sst.hpp | vdods/lvd | 864eaa25bdaddfc0dc7e788e693ebae3b42597be | [
"Apache-2.0"
] | null | null | null | lib/lvd/read_bin_sst.hpp | vdods/lvd | 864eaa25bdaddfc0dc7e788e693ebae3b42597be | [
"Apache-2.0"
] | null | null | null | lib/lvd/read_bin_sst.hpp | vdods/lvd | 864eaa25bdaddfc0dc7e788e693ebae3b42597be | [
"Apache-2.0"
] | null | null | null | // 2021.01.22 - Copyright Victor Dods - Licensed under Apache 2.0
#pragma once
#include "lvd/read_bin_type.hpp"
#include "lvd/sst/SV_t.hpp"
namespace lvd {
template <typename S_, typename C_, auto... Params_>
struct ReadInPlace_t<sst::SV_t<S_,C_>,BinEncoding_t<Params_...>> {
template <typename CharT_, typename Traits_>
std::basic_istream<CharT_,Traits_> &operator() (std::basic_istream<CharT_,Traits_> &in, BinEncoding_t<Params_...> const &enc, sst::SV_t<S_,C_> &dest_val) const {
if constexpr (enc.type_encoding() == TypeEncoding::INCLUDED)
in >> enc.with_demoted_type_encoding().in(type_of(dest_val)); // This will throw if the type doesn't match.
// The type is already known at this point.
auto inner_enc = enc.with_demoted_type_encoding();
// Use assign-move so that the validity check is done automatically.
dest_val = inner_enc.template read<C_>(in);
return in;
}
};
// SV_t<S_,C_> is not in general default-constructible, so ReadValue_t has to be specialized.
template <typename S_, typename C_, typename Encoding_>
struct ReadValue_t<sst::SV_t<S_,C_>,Encoding_> {
template <typename CharT_, typename Traits_>
sst::SV_t<S_,C_> operator() (std::basic_istream<CharT_,Traits_> &in, Encoding_ const &enc) const {
if constexpr (enc.type_encoding() == TypeEncoding::INCLUDED)
in >> enc.with_demoted_type_encoding().in(ty<sst::SV_t<S_,C_>>); // This will throw if the type doesn't match.
// The type is already known at this point.
auto inner_enc = enc.with_demoted_type_encoding();
auto retval = sst::SV_t<S_,C_>{sst::no_check};
retval = inner_enc.template read<C_>(in);
return retval;
// auto retval = sst::SV_t<S_,C_>{sst::no_check, inner_enc.template read<C_>(in)};
// retval->template check<check_policy_for__ctor_move_C(S_{})>();
// return retval;
// return sst::SV_t<S_,C_>{inner_enc.template read<C_>(in)};
}
};
} // end namespace lvd
| 42.333333 | 165 | 0.676181 | vdods |
13ef68cf771eba81d2e52f13c77016214561199b | 289 | cpp | C++ | test/util/value_unittest.cpp | kilasuelika/FastAD | dd070c608c18f5391f2ac68dca4f9db223a33eca | [
"MIT"
] | 50 | 2019-11-28T22:25:01.000Z | 2022-02-20T03:55:19.000Z | test/util/value_unittest.cpp | kilasuelika/FastAD | dd070c608c18f5391f2ac68dca4f9db223a33eca | [
"MIT"
] | 25 | 2019-11-28T20:44:12.000Z | 2021-10-30T00:14:39.000Z | test/util/value_unittest.cpp | kilasuelika/FastAD | dd070c608c18f5391f2ac68dca4f9db223a33eca | [
"MIT"
] | 2 | 2021-02-26T11:14:56.000Z | 2021-07-07T06:40:18.000Z | #include <gtest/gtest.h>
#include <fastad_bits/util/value.hpp>
namespace ad {
namespace util {
struct value_fixture : ::testing::Test
{
protected:
};
TEST_F(value_fixture, ones_scl)
{
double x = 0.;
ones(x);
EXPECT_DOUBLE_EQ(x, 1.);
}
} // namespace util
} // namespace ad
| 13.761905 | 38 | 0.66782 | kilasuelika |
13f970f9e06d8715544b79edbf4236de15b002d6 | 3,829 | cpp | C++ | src/Util/FFT.cpp | roman-ellerbrock/QuTree | 28c5b4eddf20e41cd015a03d33f31693eff17839 | [
"MIT"
] | 6 | 2020-04-24T09:58:23.000Z | 2022-02-06T03:40:55.000Z | src/Util/FFT.cpp | roman-ellerbrock/QuTree | 28c5b4eddf20e41cd015a03d33f31693eff17839 | [
"MIT"
] | 1 | 2020-06-18T11:33:14.000Z | 2020-06-18T11:35:23.000Z | src/Util/FFT.cpp | roman-ellerbrock/QuTree | 28c5b4eddf20e41cd015a03d33f31693eff17839 | [
"MIT"
] | 1 | 2020-12-26T15:23:21.000Z | 2020-12-26T15:23:21.000Z | #include "Util/FFT.h"
size_t FFT::getGoodSize(size_t size)
{
//check if size is a power of 2
size_t mod = size % 2;
if(mod == 0) return size;
//get the next bigger power of 2
size_t potens = 0;
while(size > 0)
{
size = size/2;
potens++;
}
return pow(2,potens);
}
Tensorcd FFT::reverseOrder(const Tensorcd& in)
{
//get the next best size for fft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
size_t N = getGoodSize(size);
//build the output tensor withe the new sizes
vector<size_t> d;
d.push_back(N);
d.push_back(dim.lastDimension());
TensorShape newdim(d);
Tensorcd out(newdim);
for(size_t n = 0; n < states; n++)
for(size_t i = 0; i < size; i++)
out[n*size + i] = in[n*size + i];
complex<double> tmp;
//reverse the order
for(size_t n = 0; n < states; n++)
{
size_t j = 1;
for(size_t i = 1; i <= size; i++)
{
if(j > i)
{
tmp = out[n*size + j-1];
out[n*size + j-1] = out[n*size + i-1];
out[n*size + i-1] = tmp;
}
size_t m = size/2;
while((m >= 2) && (j > m))
{
j -= m;
m /= 2;
}
j += m;
}
}
return out;
}
Tensorcd FFT::generalFFT(const Tensorcd& in, const int sign)
{
//get sizes for fft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
//get primefactors
vector<size_t> primefactors = primeFactorization(size);
size_t numberOfFactors = primefactors.size();
//make a factor 2 fft if possible
if(primefactors[numberOfFactors-1] == 2)
return factor2FFT(in, sign);
//otherwise perform dft
return dft(in, sign);
}
Tensorcd FFT::dft(const Tensorcd& in, const int sign)
{
//get sizes for dft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
//otherwise perform dft
vector<size_t> d;
d.push_back(size);
d.push_back(states);
TensorShape newdim(d);
Tensorcd out(newdim);
for(size_t k = 0; k < states; k++)
{
for(size_t i = 0; i < size; i++)
{
double angle = (2.*M_PI*i*sign)/(1.*size);
complex<double> factor(cos(angle),sin(angle));
complex<double> w(1/sqrt(1.*size),0.);
for(size_t j = 0; j < size; j++)
{
out[k*size + i] += w*in[k*size + j];
w *= factor;
}
}
}
return out;
}
Tensorcd FFT::factor2FFT(const Tensorcd& in, const int sign)
{
Tensorcd out = reverseOrder(in);
danielsonLanczosAlgorithm(out, sign);
return out;
}
void FFT::danielsonLanczosAlgorithm(Tensorcd& in, const int sign)
{
//get sizes for fft
const TensorShape& dim = in.shape();
size_t size = dim.lastBefore();
size_t states = dim.lastDimension();
//save some intermediat results
complex<double> tmp(0., 0.);
//Transform each vector seperadly
for(size_t n = 0; n < states; n++)
{
//Recursion
size_t mmax = 1;
while(mmax < size)
{
size_t j = 0;
size_t step = 2*mmax;
//prefector for exponent
double angle = M_PI/(1.*sign*mmax);
complex<double> factor(-2.*pow(sin(0.5*angle),2), sin(angle));
//transformation factor
complex<double> w(1., 0.);
//go throug all partitions of the vector
for(size_t m = 0; m < mmax; m++)
{
for(size_t i = m; i < size; i += step)
{
//Davidson-Lanczos-Formula
j = i + mmax;
tmp = w*in[n*size + j];
in[n*size + j] = in[n*size + i] - tmp;
in[n*size + i] = in[n*size + i] + tmp;
}
w = w*factor + w;
}
mmax = step;
}
}
in *= 1./sqrt(size);
}
vector<size_t> FFT::primeFactorization(size_t number) const
{
vector<size_t> primefactors;
if(number == 1)
primefactors.push_back(1);
size_t inter = number;
for(size_t i = 2; i <= number; i++)
{
while(inter % i == 0)
{
inter /= i;
primefactors.push_back(i);
}
if(inter == 1) break;
}
return primefactors;
}
| 19.338384 | 65 | 0.610603 | roman-ellerbrock |
13fdb6162e5ceee227f032a1121f7d934275675b | 3,682 | cpp | C++ | logdevice/common/StatsCollectionThread.cpp | Ikhbar-Kebaa/LogDevice | d69d706fb81d665eb94ee844aab94ff4951c9731 | [
"BSD-3-Clause"
] | 1 | 2019-01-17T18:53:25.000Z | 2019-01-17T18:53:25.000Z | logdevice/common/StatsCollectionThread.cpp | abhishekg785/LogDevice | 060da71ef84b61f3371115ed352a7ee7b07ba9e2 | [
"BSD-3-Clause"
] | null | null | null | logdevice/common/StatsCollectionThread.cpp | abhishekg785/LogDevice | 060da71ef84b61f3371115ed352a7ee7b07ba9e2 | [
"BSD-3-Clause"
] | null | null | null | /**
* Copyright (c) 2017-present, Facebook, Inc. and its affiliates.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#include "logdevice/common/StatsCollectionThread.h"
#include <folly/Optional.h>
#include "logdevice/common/ThreadID.h"
#include "logdevice/common/configuration/ServerConfig.h"
#include "logdevice/common/debug.h"
#include "logdevice/common/plugin/PluginRegistry.h"
#include "logdevice/common/plugin/StatsPublisherFactory.h"
#include "logdevice/common/settings/Settings.h"
#include "logdevice/common/settings/UpdateableSettings.h"
#include "logdevice/common/stats/Stats.h"
namespace facebook { namespace logdevice {
StatsCollectionThread::StatsCollectionThread(
const StatsHolder* source,
std::chrono::seconds interval,
std::unique_ptr<StatsPublisher> publisher)
: source_stats_(source),
interval_(interval),
publisher_(std::move(publisher)),
thread_(std::bind(&StatsCollectionThread::mainLoop, this)) {
ld_debug("Stats Collection Thread Started...");
}
StatsCollectionThread::~StatsCollectionThread() {
shutDown();
thread_.join();
}
namespace {
struct StatsSnapshot {
Stats stats;
std::chrono::steady_clock::time_point when;
};
} // namespace
void StatsCollectionThread::mainLoop() {
ThreadID::set(ThreadID::Type::UTILITY, "ld:stats");
folly::Optional<StatsSnapshot> previous;
while (true) {
using namespace std::chrono;
const auto now = steady_clock::now();
const auto next_tick = now + interval_;
StatsSnapshot current = {source_stats_->aggregate(), now};
ld_debug("Publishing Stats...");
if (previous.hasValue()) {
publisher_->publish(
current.stats,
previous.value().stats,
duration_cast<milliseconds>(now - previous.value().when));
}
previous.assign(std::move(current));
{
std::unique_lock<std::mutex> lock(mutex_);
if (stop_) {
break;
}
if (next_tick > steady_clock::now()) {
cv_.wait_until(lock, next_tick, [this]() { return stop_; });
}
// NOTE: even if we got woken up by shutDown(), we still aggregate and
// push once more so we don't lose data from the partial interval
}
}
}
std::unique_ptr<StatsCollectionThread> StatsCollectionThread::maybeCreate(
const UpdateableSettings<Settings>& settings,
std::shared_ptr<ServerConfig> config,
std::shared_ptr<PluginRegistry> plugin_registry,
StatsPublisherScope scope,
int num_shards,
const StatsHolder* source) {
ld_check(settings.get());
ld_check(config);
ld_check(plugin_registry);
auto stats_collection_interval = settings->stats_collection_interval;
if (stats_collection_interval.count() <= 0) {
return nullptr;
}
auto factory = plugin_registry->getSinglePlugin<StatsPublisherFactory>(
PluginType::STATS_PUBLISHER_FACTORY);
if (!factory) {
return nullptr;
}
auto stats_publisher = (*factory)(scope, settings, num_shards);
if (!stats_publisher) {
return nullptr;
}
auto rollup_entity = config->getClusterName();
stats_publisher->addRollupEntity(rollup_entity);
if (scope == StatsPublisherScope::CLIENT) {
// This is here for backward compatibility with our tooling. The
// <tier>.client entity space is deprecated and all new tooling should
// be using the tier name without suffix
stats_publisher->addRollupEntity(rollup_entity + ".client");
}
return std::make_unique<StatsCollectionThread>(
source, stats_collection_interval, std::move(stats_publisher));
}
}} // namespace facebook::logdevice
| 31.741379 | 76 | 0.713199 | Ikhbar-Kebaa |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.