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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
19af1f39d75c27a6499933e4960cf4dda88d20a8 | 1,117 | hpp | C++ | model/behaviour/Farsighted.hpp | xdanielsb/BeastCollider | a4038c78b183cdb93fcbd4ae1402ca26fe553bbd | [
"Apache-2.0"
] | 2 | 2019-12-23T09:07:11.000Z | 2020-08-10T12:10:23.000Z | model/behaviour/Farsighted.hpp | xdanielsb/BeastCollider | a4038c78b183cdb93fcbd4ae1402ca26fe553bbd | [
"Apache-2.0"
] | null | null | null | model/behaviour/Farsighted.hpp | xdanielsb/BeastCollider | a4038c78b183cdb93fcbd4ae1402ca26fe553bbd | [
"Apache-2.0"
] | null | null | null | #ifndef _CFarsighted
#define _CFarsighted
#include"./IBehaviour.hpp"
using namespace std;
/**
* Implementation of behaviour Farsignted
*
* A Farsighted animal estimates the trajectories of critters
* around it and adjusts its trajectory to avoid possible collisions.
*
*
*/
class FarsightedB:public Behaviour{
public:
void move(Animal* a, vector<Animal*> list){
double minDistance = 1e9;
Animal *nearestAnimal=nullptr;
for(Animal* b:list){
if( b->getId() == a->getId() )continue;
double aux = a->getDistance( b->getPosition());
if( aux < minDistance){
minDistance = aux;
nearestAnimal = b;
}
}
if(nearestAnimal){
a->setDirX(nearestAnimal->getDirX());
a->setDirY(nearestAnimal->getDirY());
}
if(isOutOfBoundaryX(a))
a->setDirX(-a->getDirX());
if(isOutOfBoundaryY(a))
a->setDirY(-a->getDirY());
a->setPosX(a->getPosX()+a->getDirX() * a->getSpeed());
a->setPosY(a->getPosY()+a->getDirY() * a->getSpeed());
#ifdef CLI
printf("->F{%.2f, %.2f}\n", a->getPosX(), a->getPosY());
#endif
}
};
#endif
| 24.822222 | 69 | 0.622202 | xdanielsb |
30aadf746e1393372aa1f8fd134e458c914efb3d | 1,507 | cpp | C++ | src/module_run.cpp | sirofen/read-memory-dll | 035b008cdb6ffbf2d00f30234f9ef976c04eee1e | [
"MIT"
] | null | null | null | src/module_run.cpp | sirofen/read-memory-dll | 035b008cdb6ffbf2d00f30234f9ef976c04eee1e | [
"MIT"
] | null | null | null | src/module_run.cpp | sirofen/read-memory-dll | 035b008cdb6ffbf2d00f30234f9ef976c04eee1e | [
"MIT"
] | null | null | null | // module
#include <module/module_run.hpp>
// spdlog
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_TRACE
#include <spdlog/sinks/stdout_color_sinks.h>
#include <spdlog/spdlog.h>
// WINAPI
#include "Windows.h"
namespace {
LRESULT CALLBACK KeyboardProc(int n_code, WPARAM w_param, LPARAM l_param)
{
if (n_code < 0 || n_code == HC_NOREMOVE) {
return CallNextHookEx(NULL, n_code, w_param, l_param);
}
if (w_param == VK_PAUSE) {
}
return CallNextHookEx(NULL, n_code, w_param, l_param);
}
}
namespace module::internal {
module_run::module_run() {}
void module_run::add_listener(std::shared_ptr<module::base_listener> listener) {
module::internal::states::processing_value _m_proc(std::move(listener));
m_vec_proc_val_obj.emplace_back(std::make_unique<module::internal::states::processing_value>(_m_proc));
}
void module_run::set_break_key(unsigned char key) {
m_break_key = key;
}
void module_run::run() {
SPDLOG_DEBUG("Module started");
supply_values();
}
void module_run::supply_values() {
char* _cstr = nullptr;
while (!GetAsyncKeyState(m_break_key)) {
if (this->get_cstr_from_address(_cstr) != 0 && this->get_cstr_from_pointer(_cstr) != 0) {
SPDLOG_TRACE("Empty value skipped");
continue;
}
SPDLOG_TRACE("Supplying value");
for (const auto& _proc : m_vec_proc_val_obj) {
_proc->process_value(_cstr);
}
}
SPDLOG_DEBUG("Module stopped");
}
}// namespace module::internal
| 27.907407 | 107 | 0.686131 | sirofen |
30b562d1a13d5dc9cbabd0d301c0a5e79f9d1aa6 | 1,006 | cpp | C++ | Circles/Circles/Circles.cpp | IgorIgnatiev/Circles | 79ea4dba5e7b8aa1a8aafd1976a0ad0e5881987d | [
"Apache-2.0"
] | null | null | null | Circles/Circles/Circles.cpp | IgorIgnatiev/Circles | 79ea4dba5e7b8aa1a8aafd1976a0ad0e5881987d | [
"Apache-2.0"
] | null | null | null | Circles/Circles/Circles.cpp | IgorIgnatiev/Circles | 79ea4dba5e7b8aa1a8aafd1976a0ad0e5881987d | [
"Apache-2.0"
] | null | null | null | // Circles.cpp : Этот файл содержит функцию "main". Здесь начинается и заканчивается выполнение программы.
//
#include <iostream>
#include<SFML/Graphics.hpp>
#include<thread>
using namespace sf;
CircleShape create()
{
std::shared_ptr<CircleShape> circle = std::make_shared<CircleShape>(20.0f);
(*circle.get()).setFillColor(Color::Green);
(*circle.get()).setPosition(rand() % 900, rand() % 400);
return *circle.get();
}
int main()
{
RenderWindow window(VideoMode(1000, 500), "Circles");
srand(time(0));
const int SIZE = 10;
auto arr = new CircleShape[SIZE];
int count = 0;
for (int i = 0; i < SIZE; i++)
{
arr[i] = create();
}
while (window.isOpen())
{
Event event;
while (window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
}
window.clear();
for (int i = 0; i < count; i++)
{
window.draw(arr[i]);
}
window.display();
std::this_thread::sleep_for(std::chrono::milliseconds(700));
if (count < SIZE)
{
count++;
}
}
}
| 20.12 | 107 | 0.634195 | IgorIgnatiev |
30b7613e495a3ba0622183a934e056c17799a602 | 1,127 | cpp | C++ | gueepo2D/engine/utils/ImageUtils.cpp | guilhermepo2/gueepo2D | deb03ff39c871710c07d36c366b53b34dbfebf08 | [
"MIT"
] | 1 | 2022-02-03T19:24:47.000Z | 2022-02-03T19:24:47.000Z | gueepo2D/engine/utils/ImageUtils.cpp | guilhermepo2/gueepo2D | deb03ff39c871710c07d36c366b53b34dbfebf08 | [
"MIT"
] | 4 | 2021-10-30T19:03:07.000Z | 2022-02-10T01:06:02.000Z | gueepo2D/engine/utils/ImageUtils.cpp | guilhermepo2/gueepo2D | deb03ff39c871710c07d36c366b53b34dbfebf08 | [
"MIT"
] | 1 | 2021-10-01T03:08:21.000Z | 2021-10-01T03:08:21.000Z | #include "gueepo2Dpch.h"
#include "ImageUtils.h"
#include "core/Log.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
namespace gueepo {
unsigned char* g_LoadImage(const char* path, int& outImageWidth, int& outImageHeight, int& outComponentsPerPixel, int stride, bool flip) {
stbi_set_flip_vertically_on_load(flip ? 1 : 0);
unsigned char* data = stbi_load(path, &outImageWidth, &outImageHeight, &outComponentsPerPixel, stride);
if (data == nullptr) {
LOG_ERROR("couldn't load image: {0}", path);
}
LOG_INFO("image {0} was loaded", path);
return data;
}
bool g_FreeImage(void* data) {
if (data == nullptr) {
return false;
}
stbi_image_free(data);
return true;
}
bool g_SaveImage(const char* path, int width, int height, int comp, const void* data, int stride) {
int savingStatus = stbi_write_png(path, width, height, comp, data, stride);
if (savingStatus == 0) {
LOG_ERROR("failed to save image at {0}", path);
return false;
}
LOG_INFO("image {0} saved successfuly", path);
return true;
}
} | 25.044444 | 139 | 0.705413 | guilhermepo2 |
30b871b79bb71b1d92d6785798dc82f0e2213812 | 1,359 | cpp | C++ | src/TableItens/Player.cpp | edubrunaldi/poker-bot | b851aa86c73a5b1b6c586439fbc01ccecac8c0f1 | [
"MIT"
] | null | null | null | src/TableItens/Player.cpp | edubrunaldi/poker-bot | b851aa86c73a5b1b6c586439fbc01ccecac8c0f1 | [
"MIT"
] | null | null | null | src/TableItens/Player.cpp | edubrunaldi/poker-bot | b851aa86c73a5b1b6c586439fbc01ccecac8c0f1 | [
"MIT"
] | 2 | 2019-09-08T10:40:21.000Z | 2021-01-06T16:17:37.000Z | //
// Created by xima on 07/07/19.
//
#include "../../includes/TableItens/Player.hpp"
Player::Player(PlayerPosition position, TableSize tableSize) {
if (position == P0) {
this->card1 = std::make_unique<Card>(Card(HAND_LEFT));
this->card2 = std::make_unique<Card>(Card(HAND_RIGHT));
this->stack = std::make_unique<Stack>(Stack());
} else {
this->playerStatus = std::make_unique<PlayerStatus>(PlayerStatus(position, tableSize));
}
this->dealer = std::make_unique<Dealer>(Dealer(position, tableSize));
}
std::string Player::handValue() {
if (this->playerStatus != nullptr)
return "";
return this->card1->value() + this->card2->value();
}
bool Player::playing() {
if (this->playerStatus == nullptr){
std::cout << " Player = 0" << std::endl;
return true;
}
return this->playerStatus->playing();
}
bool Player::isDealer() {
return this->dealer->dealer();
}
float Player::stackSize() {
return this->stack->size();
}
void Player::accept(AbstractVisitor& visitor) {
if(this->card1 != nullptr) this->card1->accept(visitor);
if(this->card2 != nullptr) this->card2->accept(visitor);
if(this->dealer != nullptr) this->dealer->accept(visitor);
if(this->playerStatus != nullptr) this->playerStatus->accept(visitor);
if(this->stack != nullptr) this->stack->accept(visitor);
return visitor.visit(*this);
} | 27.734694 | 91 | 0.667403 | edubrunaldi |
30bee41ba1cbd7e910014b47efdf680937bacbdf | 316 | cpp | C++ | CommandLine.cpp | tgustafsson/myeditor | c2add8e01664cf58301058af017a9249cfd8832a | [
"Apache-2.0"
] | null | null | null | CommandLine.cpp | tgustafsson/myeditor | c2add8e01664cf58301058af017a9249cfd8832a | [
"Apache-2.0"
] | null | null | null | CommandLine.cpp | tgustafsson/myeditor | c2add8e01664cf58301058af017a9249cfd8832a | [
"Apache-2.0"
] | null | null | null | #include "CommandLine.h"
using namespace std;
KeyCord::command_return_t CommandLine::my_command_line_insert(shared_ptr<Model> model, shared_ptr<View> view, shared_ptr<Control> control, shared_ptr<Control> command_line_control, shared_ptr<Model> command_line_model)
{
return make_tuple(&my_empty_undo, false);
}
| 35.111111 | 218 | 0.816456 | tgustafsson |
30c0b32673f3e1ae21fa57a9f715df32ace30cc0 | 310 | cpp | C++ | 08. Test One/20321009/F/F.cpp | dimitarminchev/CS104 | e42144196b346cb394f0118c833fa2b1e4f06ea5 | [
"MIT"
] | 7 | 2021-03-24T16:30:45.000Z | 2022-03-27T09:02:15.000Z | 08. Test One/20321009/F/F.cpp | dimitarminchev/CS104 | e42144196b346cb394f0118c833fa2b1e4f06ea5 | [
"MIT"
] | null | null | null | 08. Test One/20321009/F/F.cpp | dimitarminchev/CS104 | e42144196b346cb394f0118c833fa2b1e4f06ea5 | [
"MIT"
] | 17 | 2021-03-22T09:42:22.000Z | 2022-03-28T03:24:07.000Z | #include <iostream>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
for (int i = a; i <= b; i++)
{
if (i % 15 == 0)
{
cout << "fizzbuzz ";
}
else if (i % 5 == 0)
{
cout << "buzz ";
}
else if (i % 3 == 0)
{
cout << "fizz ";
}
else cout << i << " ";
}
return 0;
} | 12.4 | 29 | 0.412903 | dimitarminchev |
30c292fa4ff9a9dacb3f83b7984bc59778bc6671 | 3,719 | cc | C++ | source/gpu_perf_api_cl/cl_gpa_pass.cc | AdamJMiles/gpu_performance_api | 7bd0c8b484b2a658610581e2e48b615606130fdc | [
"MIT"
] | 61 | 2020-03-17T12:30:11.000Z | 2022-03-01T18:59:11.000Z | source/gpu_perf_api_cl/cl_gpa_pass.cc | AdamJMiles/gpu_performance_api | 7bd0c8b484b2a658610581e2e48b615606130fdc | [
"MIT"
] | 12 | 2020-03-24T15:46:54.000Z | 2022-01-08T02:03:31.000Z | source/gpu_perf_api_cl/cl_gpa_pass.cc | AdamJMiles/gpu_performance_api | 7bd0c8b484b2a658610581e2e48b615606130fdc | [
"MIT"
] | 19 | 2020-03-16T17:32:09.000Z | 2022-03-29T23:35:31.000Z | //==============================================================================
// Copyright (c) 2018-2020 Advanced Micro Devices, Inc. All rights reserved.
/// @author AMD Developer Tools Team
/// @file
/// @brief CL GPA Pass Object Implementation
//==============================================================================
#include <cassert>
#include "cl_gpa_pass.h"
#include "cl_gpa_command_list.h"
#include "cl_gpa_sample.h"
#include "gpa_hardware_counters.h"
#include "gpa_context_counter_mediator.h"
ClGpaPass::ClGpaPass(IGpaSession* gpa_session, PassIndex pass_index, GpaCounterSource counter_source, CounterList* pass_counters)
: GpaPass(gpa_session, pass_index, counter_source, pass_counters)
{
EnableAllCountersForPass();
InitializeClCounterInfo();
}
GpaSample* ClGpaPass::CreateApiSpecificSample(IGpaCommandList* cmd_list, GpaSampleType sample_type, ClientSampleId sample_id)
{
GpaSample* ret_sample = nullptr;
ClGpaSample* cl_gpa_sample = new (std::nothrow) ClGpaSample(this, cmd_list, sample_type, sample_id);
if (nullptr == cl_gpa_sample)
{
GPA_LOG_ERROR("Unable to allocate memory for the sample.");
}
else
{
ret_sample = cl_gpa_sample;
}
return ret_sample;
}
bool ClGpaPass::ContinueSample(ClientSampleId src_sample_id, IGpaCommandList* primary_gpa_cmd_list)
{
// continuing samples not supported for OpenCL
UNREFERENCED_PARAMETER(src_sample_id);
UNREFERENCED_PARAMETER(primary_gpa_cmd_list);
return false;
}
IGpaCommandList* ClGpaPass::CreateApiSpecificCommandList(void* cmd, CommandListId command_list_id, GpaCommandListType cmd_type)
{
UNREFERENCED_PARAMETER(cmd);
UNREFERENCED_PARAMETER(cmd_type);
ClGpaCommandList* ret_cmd_list = new (std::nothrow) ClGpaCommandList(GetGpaSession(), this, command_list_id);
if (nullptr == ret_cmd_list)
{
GPA_LOG_ERROR("Unable to allocate memory for the command list.");
}
return ret_cmd_list;
}
bool ClGpaPass::EndSample(IGpaCommandList* cmd_list)
{
bool ret_val = false;
if (nullptr != cmd_list)
{
ret_val = cmd_list->CloseLastSample();
}
return ret_val;
}
void ClGpaPass::IterateClCounterMap(std::function<bool(GroupCountersPair group_counters_pair)> function) const
{
bool next = true;
for (auto it = group_counters_map_.cbegin(); it != group_counters_map_.cend() && next; ++it)
{
next = function(*it);
}
}
void ClGpaPass::InitializeClCounterInfo()
{
ClGpaContext* cl_gpa_context = reinterpret_cast<ClGpaContext*>(GetGpaSession()->GetParentContext());
IGpaCounterAccessor* counter_accessor = GpaContextCounterMediator::Instance()->GetCounterAccessor(cl_gpa_context);
const GpaHardwareCounters* hardware_counters = counter_accessor->GetHardwareCounters();
GpaUInt32 group_count = static_cast<GpaUInt32>(hardware_counters->group_count_);
UNREFERENCED_PARAMETER(group_count);
auto add_counter_to_cl_counter_info = [&](CounterIndex counter_index) -> bool {
const GpaHardwareCounterDescExt* counter = counter_accessor->GetHardwareCounterExt(counter_index);
GpaUInt32 group_index = counter->group_id_driver;
assert(group_index <= group_count);
GpaUInt64 num_counters = hardware_counters->internal_counter_groups_[group_index].num_counters;
UNREFERENCED_PARAMETER(num_counters);
assert(counter->hardware_counters->counter_index_in_group <= num_counters);
group_counters_map_[group_index].push_back(counter->hardware_counters->counter_index_in_group);
return true;
};
IterateEnabledCounterList(add_counter_to_cl_counter_info);
}
| 33.809091 | 129 | 0.708255 | AdamJMiles |
30c3aba06a0cc3b1c91fec618dfa49d3f800fac8 | 6,924 | hpp | C++ | 3DGE/include/tools/ResourceLoader.hpp | nflsilva/C3DGE | 9f1596c8e3842aeb095ad57d01f7d2e5e1587c3c | [
"Apache-2.0"
] | null | null | null | 3DGE/include/tools/ResourceLoader.hpp | nflsilva/C3DGE | 9f1596c8e3842aeb095ad57d01f7d2e5e1587c3c | [
"Apache-2.0"
] | null | null | null | 3DGE/include/tools/ResourceLoader.hpp | nflsilva/C3DGE | 9f1596c8e3842aeb095ad57d01f7d2e5e1587c3c | [
"Apache-2.0"
] | null | null | null | #ifndef RESOURCES_HPP
#define RESOURCES_HPP
#include <set>
#include <list>
#include <map>
#include <vector>
#include <iostream>
#include <fstream>
#include <sstream>
#include <stdio.h>
#include <string>
#include <string.h>
#include "tools/Log.hpp"
#include "stb_image/stb_image.h"
#include "tiny_obj_loader/tiny_obj_loader.h"
class ResourceLoader {
public:
class MeshData {
public:
std::vector<float> vertices;
std::vector<float> textureCoordinates;
std::vector<float> colors;
std::vector<float> normals;
std::vector<int> indices;
MeshData(){};
};
class TextureData {
public:
int width, height, bpp;
stbi_uc* buffer;
TextureData() : width(0), height(0), bpp(0), buffer(NULL){};
~TextureData(){ if(buffer) stbi_image_free(buffer); };
};
class Vec4DTO {
public:
float v0, v1, v2, v3;
Vec4DTO(): v0(0), v1(0), v2(0), v3(0) {}
Vec4DTO(float v0, float v1) : v0(v0), v1(v1), v2(0), v3(0) {}
Vec4DTO(float v0, float v1, float v2) : v0(v0), v1(v1), v2(v2), v3(0) {}
Vec4DTO(float v0, float v1, float v2, float v3) : v0(v0), v1(v1), v2(v2), v3(v3) {}
};
static std::string* LoadShaderSource(std::string fileName){
std::ifstream file;
file.open(fileName, std::ios::in);
if(!file)
{
Log::E("Error opening shader file " + fileName);
return NULL;
}
std::string* content = new std::string(
(std::istreambuf_iterator<char>(file)),
(std::istreambuf_iterator<char>()));
file.close();
return content;
}
static MeshData* LoadMeshData(std::string meshFileName, std::string materialFileName){
MeshData* md = new MeshData();
tinyobj::ObjReaderConfig reader_config;
reader_config.mtl_search_path = materialFileName;
tinyobj::ObjReader reader;
if (!reader.ParseFromFile(meshFileName, reader_config)) {
if (!reader.Error().empty()) {
Log::E("TinyObjReader: " + reader.Error());
}
}
if (!reader.Warning().empty()) {
Log::I("TinyObjReader: " + reader.Warning());
}
tinyobj::attrib_t attrib = reader.GetAttrib();
std::vector<tinyobj::shape_t> shapes = reader.GetShapes();
std::vector<tinyobj::material_t> materials = reader.GetMaterials();
Log::D(
std::to_string(attrib.vertices.size()) + " vertices. "
+ std::to_string(attrib.colors.size()) + " colors. "
+ std::to_string(attrib.normals.size()) + " normals. "
);
int i = 0;
for (size_t s = 0; s < shapes.size(); s++) {
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
size_t fv = size_t(shapes[s].mesh.num_face_vertices[f]);
for (size_t v = 0; v < fv; v++) {
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
md->vertices.push_back(attrib.vertices[3 * idx.vertex_index + 0]);
md->vertices.push_back(attrib.vertices[3 * idx.vertex_index + 1]);
md->vertices.push_back(attrib.vertices[3 * idx.vertex_index + 2]);
if(materials.size() > 0){
tinyobj::material_t material = materials[shapes[s].mesh.material_ids[f]];
md->colors.push_back(material.diffuse[0]);
md->colors.push_back(material.diffuse[1]);
md->colors.push_back(material.diffuse[2]);
md->colors.push_back(1.0);
}
if (idx.normal_index >= 0) {
md->normals.push_back(attrib.normals[3 * idx.normal_index + 0]);
md->normals.push_back(attrib.normals[3 * idx.normal_index + 1]);
md->normals.push_back(attrib.normals[3 * idx.normal_index + 2]);
}
if (idx.texcoord_index >= 0) {
md->textureCoordinates.push_back(attrib.texcoords[2 * idx.texcoord_index + 0]);
md->textureCoordinates.push_back(attrib.texcoords[2 * idx.texcoord_index + 1]);
}
md->indices.push_back(i++);
}
index_offset += fv;
}
}
Log::D(
std::to_string(md->vertices.size() / 4) + " vertices. "
+ std::to_string(md->colors.size() / 4) + " colors. "
+ std::to_string(md->normals.size() / 3) + " normals. "
);
return md;
}
static MeshData* LoadMeshDataIndexed(std::string meshFileName){
MeshData* md = new MeshData();
tinyobj::ObjReaderConfig reader_config;
tinyobj::ObjReader reader;
if (!reader.ParseFromFile(meshFileName, reader_config)) {
if (!reader.Error().empty()) {
Log::E("TinyObjReader: " + reader.Error());
}
}
if (!reader.Warning().empty()) {
Log::I("TinyObjReader: " + reader.Warning());
}
tinyobj::attrib_t attrib = reader.GetAttrib();
std::vector<tinyobj::shape_t> shapes = reader.GetShapes();
int i = 0;
for (size_t s = 0; s < shapes.size(); s++) {
size_t index_offset = 0;
for (size_t f = 0; f < shapes[s].mesh.num_face_vertices.size(); f++) {
size_t fv = size_t(shapes[s].mesh.num_face_vertices[f]);
for (size_t v = 0; v < fv; v++) {
tinyobj::index_t idx = shapes[s].mesh.indices[index_offset + v];
md->vertices.push_back(attrib.vertices[3 * idx.vertex_index + 0]);
md->vertices.push_back(attrib.vertices[3 * idx.vertex_index + 1]);
md->vertices.push_back(attrib.vertices[3 * idx.vertex_index + 2]);
if (idx.normal_index >= 0) {
md->normals.push_back(attrib.normals[3 * idx.normal_index + 0]);
md->normals.push_back(attrib.normals[3 * idx.normal_index + 1]);
md->normals.push_back(attrib.normals[3 * idx.normal_index + 2]);
}
if (idx.texcoord_index >= 0) {
md->textureCoordinates.push_back(attrib.texcoords[2 * idx.texcoord_index + 0]);
md->textureCoordinates.push_back(attrib.texcoords[2 * idx.texcoord_index + 1]);
}
md->indices.push_back(i++);
}
index_offset += fv;
}
}
Log::D(
std::to_string(md->vertices.size() / 3) + " vertices. "
+ std::to_string(md->textureCoordinates.size() / 2) + " textCoords. "
+ std::to_string(md->normals.size() / 3) + " normals. "
+ std::to_string(md->indices.size()) + " indices. "
);
return md;
}
static TextureData* LoadTextureData(std::string fileName){
TextureData* data = new TextureData();
stbi_set_flip_vertically_on_load(0);
data->buffer = stbi_load(fileName.c_str(), &data->width, &data->height, &data->bpp, 4);
return data;
}
};
#endif | 32.971429 | 93 | 0.566869 | nflsilva |
30c762bbffb059bf7166ecdef8371179a1c63968 | 2,473 | cpp | C++ | cpp/ip-device/src/main.cpp | PetarZecevic/smart-farm | d118e30cfdaacf75969013c25cd732e31a9345f0 | [
"Apache-2.0"
] | null | null | null | cpp/ip-device/src/main.cpp | PetarZecevic/smart-farm | d118e30cfdaacf75969013c25cd732e31a9345f0 | [
"Apache-2.0"
] | null | null | null | cpp/ip-device/src/main.cpp | PetarZecevic/smart-farm | d118e30cfdaacf75969013c25cd732e31a9345f0 | [
"Apache-2.0"
] | null | null | null | #include <iostream>
//#include <chrono>
#include <unistd.h>
#include "ssdp_client.hpp"
#include "mqtt_client.hpp"
#define WAIT_TIME 1000*1000 // one second in microseconds
using namespace std;
//TODO: 1. Add virtual destructor to ReportFunction
//TODO: 2. Modify parameters and return value so it does not depend on JSON,
// report function only needs to make a measurement of all the parameters and
// return it as some structure where service is binded to it's parameters.
class MyReport : public ReportFunction
{
public:
bool operator()(rapidjson::Document& newState, rapidjson::Document& prevState) override
{
bool difference = false;
/*
// Measure temperature.
int temperature = rand() % 30 + 1;
rapidjson::Value temp;
temp.SetInt(temperature);
// If there is difference, signalize and change state.
if(prevState["temperature"].IsNull() || temperature != prevState["temperature"].GetInt())
{
difference = true;
prevState["temperature"].SetInt(temperature);
newState.AddMember("temperature", temp, newState.GetAllocator());
}
*/
return difference;
}
};
int main(int argc, char** argv)
{
if(argc < 2)
{
cout << "Enter name of json document that describes device as argument" << endl;
return -1;
}
else if(argc != 3)
{
cout << "Enter name of mqtt log file" << endl;
return -1;
}
else
{
string jsonDoc(argv[1]);
srand(time(0));
IPInfo info;
if(info.loadDescFromFile(jsonDoc))
info.setState();
else
return -1;
std::cout << info.getStateString() << std::endl;
SSDP_Client c1(info.getByKey("id"), true);
c1.findGateway();
// Start MQTT logic.
MQTT_Client mqtt_client(info, argv[2]);
mqtt_client.setLog(c1.getLogTopic());
string loc = c1.getLocation();
int pos = loc.find_first_of(':', 0); // Get port number from location.
int port = atoi(loc.substr(pos+1).c_str());
string ip = loc.substr(0, pos);
cout << "Ip : " << ip << endl << "Port: " << port << endl;
if(mqtt_client.connectToBroker(ip, port))
{
if(mqtt_client.subscribe())
{
mqtt_client.waitFor(2000); // 2 seconds.
if(mqtt_client.sendInfo())
{
cout << "Sent info" << endl;
mqtt_client.waitFor(500);
ReportFunction* myReport = new MyReport();
if(mqtt_client.isReportAllowed())
{
cout << "Reporting parameters values..." << endl;
// Send JSON report state.
mqtt_client.report(myReport);
}
delete myReport;
}
}
}
}
return 0;
}
| 24.485149 | 91 | 0.66114 | PetarZecevic |
30c97213c9d48459d40df217fe979f0e6374f4d7 | 3,081 | cpp | C++ | contrib/su4/cpp2tex/source/wtf/bsql.cpp | agrishutin/teambook | 7e9ca28cd10241edbf9cd04ebdc1df3fa1c4b107 | [
"MIT"
] | 13 | 2017-07-04T14:58:47.000Z | 2022-03-23T09:04:41.000Z | contrib/su4/cpp2tex/source/wtf/bsql.cpp | agrishutin/teambook | 7e9ca28cd10241edbf9cd04ebdc1df3fa1c4b107 | [
"MIT"
] | null | null | null | contrib/su4/cpp2tex/source/wtf/bsql.cpp | agrishutin/teambook | 7e9ca28cd10241edbf9cd04ebdc1df3fa1c4b107 | [
"MIT"
] | 5 | 2017-10-14T21:48:20.000Z | 2018-06-18T12:12:15.000Z | /*
* wtf/bsql.cpp — some improvements for sql api
*/
#include "../../include/wtf/bsql.h"
using tamias::chartype;
using tamias::sizetype;
using tamias::uinttype32;
using tamias::Pair;
using tamias::String;
using tamias::Vector;
using tamias::sql::Connection;
using tamias::sql::Result;
using tamias::wtf::BSqlConnection;
String BSqlConnection::quoteString( const String &source ) const
{
String result = "";
for (sizetype i = 0; i < source.length(); i++)
if (source[i] == '\n')
result += "\\n";
else if (source[i] == '\0')
result += "\\0";
else if (source[i] == '\r')
result += "\\r";
else if (source[i] == '\t')
result += "\\t";
else if (source[i] == '\'')
result += "\\\'";
else if (source[i] == '\"')
result += "\\\"";
else if (source[i] == '\\')
result += "\\\\";
else
result += source[i];
return result;
}
BSqlConnection::BSqlConnection( tamias::sql::Driver *driver ) : Connection(driver)
{
}
BSqlConnection::BSqlConnection( const BSqlConnection &connection ) : Connection(connection)
{
}
BSqlConnection& BSqlConnection::operator = ( const BSqlConnection &connection )
{
Connection::operator = (connection);
return *this;
}
BSqlConnection::~BSqlConnection()
{
}
Result BSqlConnection::query( const String &queryString, ... )
{
String realQuery = "";
va_list ap;
va_start(ap, queryString);
for (sizetype i = 0; i < queryString.length(); i++)
{
if (queryString[i] != '%')
{
realQuery += queryString[i];
continue;
}
if (++i >= queryString.length())
continue;
chartype specification = queryString[i];
if (specification == '%')
{
realQuery += specification;
continue;
}
else if (specification == 's')
{
String &value = *(String*)va_arg(ap, String*);
realQuery += '\'' + quoteString(value) + '\'';
}
else if (specification == 'u')
{
uinttype32 value = (uinttype32)va_arg(ap, uinttype32);
String temp = "";
while (value > 0)
temp = (value % 10 + '0') + temp, value /= 10;
if (temp == "")
temp = "0";
realQuery += '\'' + temp + '\'';
}
}
va_end(ap);
return Connection::query(realQuery);
}
void BSqlConnection::lockTables( const Vector <Pair <String, LockType> > &tables )
{
char lock[2][6] = {"read", "write"};
String queryString = "lock tables";
for (sizetype i = 0; i < tables.size(); i++)
queryString += " ,"[i > 0] + tables[i].first + " " + lock[tables[i].second];
Connection::query(queryString);
}
void BSqlConnection::unlockTables()
{
Connection::query("unlock tables");
}
tamias::sizetype BSqlConnection::nextId( const String &tableName, const String &fieldName )
{
Result idResult = query("select max(" + fieldName + ") from " + tableName);
if (!idResult.next())
throw tamias::DefaultException(); // TODO: another exception
if (idResult.get("max(" + fieldName + ")") == "")
return 0;
else
return 1 + tamias::wtf::utilities::stringToInt(idResult.get("max(" + fieldName + ")"));
}
| 25.04878 | 91 | 0.59234 | agrishutin |
30c9bdca28e17cb40ac0dd49cc9f0fa24cfb3dde | 5,099 | cpp | C++ | test/test_ccl_coloring.cpp | tuan1225/parconnect_sc16 | bcd6f99101685d746cf30e22fa3c3f63ddd950c9 | [
"Apache-2.0"
] | null | null | null | test/test_ccl_coloring.cpp | tuan1225/parconnect_sc16 | bcd6f99101685d746cf30e22fa3c3f63ddd950c9 | [
"Apache-2.0"
] | null | null | null | test/test_ccl_coloring.cpp | tuan1225/parconnect_sc16 | bcd6f99101685d746cf30e22fa3c3f63ddd950c9 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016 Georgia Institute of Technology
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @file check_ccl_coloring_undirected.cpp
* @ingroup
* @author Chirag Jain <cjain7@gatech.edu>
* @brief GTest Unit Tests for connected component labeling using coloring
*
* Copyright (c) 2015 Georgia Institute of Technology. All Rights Reserved.
*/
#include <mpi.h>
//Own includes
#include "coloring/labelProp.hpp"
//External includes
#include "mxx/comm.hpp"
#include "gtest.h"
INITIALIZE_EASYLOGGINGPP
/**
* @brief coloring of undirected graph with a small chain
* @details builds a small undirected chain,
* test if program returns 1 as the component count
*/
TEST(connColoring, smallUndirectedChain) {
mxx::comm c = mxx::comm();
//Declare a edgeList vector to save edges
std::vector< std::pair<int64_t, int64_t> > edgeList;
using nodeIdType = int64_t;
using pIdType = uint32_t;
//Start adding the edges
if (c.rank() == 0) {
//Chain (chain 1-2-...1000)
for(int i = 1; i < 1000 ; i++)
{
edgeList.emplace_back(i, i+1);
edgeList.emplace_back(i+1, i);
}
}
std::random_shuffle(edgeList.begin(), edgeList.end());
conn::coloring::ccl<nodeIdType> cclInstance(edgeList, c);
cclInstance.compute();
auto component_count = cclInstance.computeComponentCount();
ASSERT_EQ(1, component_count);
}
/**
* @brief coloring of undirected graph with 3 components
* @details builds a small test graph with three components,
* test if program returns 3 as the component count
*/
TEST(connColoring, smallUndirected) {
mxx::comm c = mxx::comm();
//Declare a edgeList vector to save edges
std::vector< std::pair<int64_t, int64_t> > edgeList;
using nodeIdType = int64_t;
//Start adding the edges
if (c.rank() == 0) {
//First component (2,3,4,11)
//2--11
edgeList.emplace_back(2,11);
edgeList.emplace_back(11,2);
//2--3
edgeList.emplace_back(2,3);
edgeList.emplace_back(3,2);
//2--4
edgeList.emplace_back(2,4);
edgeList.emplace_back(4,2);
//3--4
edgeList.emplace_back(3,4);
edgeList.emplace_back(4,3);
//Second component (5,6,8,10)
//5--6
edgeList.emplace_back(5,6);
edgeList.emplace_back(6,5);
//5--8
edgeList.emplace_back(5,8);
edgeList.emplace_back(8,5);
//6--10
edgeList.emplace_back(6,10);
edgeList.emplace_back(10,6);
//6--8
edgeList.emplace_back(6,8);
edgeList.emplace_back(8,6);
//Third component (50,51,52)
for(int i = 50; i < 52 ; i++)
{
edgeList.emplace_back(i, i+1);
edgeList.emplace_back(i+1, i);
}
}
std::random_shuffle(edgeList.begin(), edgeList.end());
//Since we have a graph of small size, use less processes
c.with_subset(c.rank() < 4, [&](const mxx::comm& comm){
conn::coloring::ccl<nodeIdType> cclInstance(edgeList, comm);
cclInstance.compute();
auto component_count = cclInstance.computeComponentCount();
ASSERT_EQ(3, component_count);
});
}
/**
* @brief coloring of undirected graph with 3 components
* @details builds a medium test graph with three components,
* test if program returns 3 as the component count
*/
TEST(connColoring, mediumUndirected) {
mxx::comm c = mxx::comm();
//Declare a edgeList vector to save edges
std::vector< std::pair<uint64_t, uint64_t> > edgeList;
//Start adding the edges
if (c.rank() == 0) {
//First component (2,3,4,11)
//2--11
edgeList.emplace_back(2,11);
edgeList.emplace_back(11,2);
//2--3
edgeList.emplace_back(2,3);
edgeList.emplace_back(3,2);
//2--4
edgeList.emplace_back(2,4);
edgeList.emplace_back(4,2);
//3--4
edgeList.emplace_back(3,4);
edgeList.emplace_back(4,3);
//Second component (5,6,8,10)
//5--6
edgeList.emplace_back(5,6);
edgeList.emplace_back(6,5);
//5--8
edgeList.emplace_back(5,8);
edgeList.emplace_back(8,5);
//6--10
edgeList.emplace_back(6,10);
edgeList.emplace_back(10,6);
//6--8
edgeList.emplace_back(6,8);
edgeList.emplace_back(8,6);
//Third component (chain 50-51-...1000)
for(int i = 50; i < 1000 ; i++)
{
edgeList.emplace_back(i, i+1);
edgeList.emplace_back(i+1, i);
}
}
std::random_shuffle(edgeList.begin(), edgeList.end());
conn::coloring::ccl<> cclInstance(edgeList, c);
cclInstance.compute();
auto component_count = cclInstance.computeComponentCount();
ASSERT_EQ(3, component_count);
}
| 24.995098 | 76 | 0.654638 | tuan1225 |
30cb0cb5e8df96ebf9ac2fd4ad2467795c603fa5 | 733 | cpp | C++ | IrrlichtCLR/BillboardW.cpp | twesd/editor | 10ea9f535115dadab5694fecdb0c499d0013ac1b | [
"MIT"
] | null | null | null | IrrlichtCLR/BillboardW.cpp | twesd/editor | 10ea9f535115dadab5694fecdb0c499d0013ac1b | [
"MIT"
] | null | null | null | IrrlichtCLR/BillboardW.cpp | twesd/editor | 10ea9f535115dadab5694fecdb0c499d0013ac1b | [
"MIT"
] | null | null | null | #include "StdAfx.h"
#include "BillboardW.h"
#include "Convertor.h"
BillboardW::BillboardW(ISceneNode* node, SharedParams_t* shareParams):
SceneNodeW(node, shareParams)
{
_billboard = dynamic_cast<Billboard*>(node);
}
void BillboardW::SetDimension(f32 width, f32 height)
{
_billboard->SetDimension(dimension2df(width, height));
}
void BillboardW::SetUseUpVector(bool useIt)
{
_billboard->SetUseUpVector(useIt);
}
void BillboardW::SetUpVector(Vertex3dW^ up)
{
vector3df v = up->GetVector();
_billboard->SetUpVector(v);
}
void BillboardW::SetUseViewVector(bool useIt)
{
_billboard->SetUseViewVector(useIt);
}
void BillboardW::SetViewVector(Vertex3dW^ vec)
{
vector3df v = vec->GetVector();
_billboard->SetViewVector(v);
}
| 19.810811 | 70 | 0.758527 | twesd |
30cb583082e1d532477a628c1003d1f61e615e52 | 753 | cpp | C++ | chewbot_gui/QT_widgets/jogAxisWidget/jogaxiswidget.cpp | drewhamiltonasdf/chewbot | 8fcbc8cf5890db2675e0af2c6b85fcd2825397cd | [
"MIT"
] | null | null | null | chewbot_gui/QT_widgets/jogAxisWidget/jogaxiswidget.cpp | drewhamiltonasdf/chewbot | 8fcbc8cf5890db2675e0af2c6b85fcd2825397cd | [
"MIT"
] | null | null | null | chewbot_gui/QT_widgets/jogAxisWidget/jogaxiswidget.cpp | drewhamiltonasdf/chewbot | 8fcbc8cf5890db2675e0af2c6b85fcd2825397cd | [
"MIT"
] | null | null | null | #include "jogaxiswidget.h"
/*
*
* If you make modifications to the form,
* you have to re-make the project, to
* install the QT designer plugin into the
* appropriate directory.
*
* cd ~/ros_ws/src/chewbot/QT_widgets/jogAxisWidget
* sudo qmake
* sudo make
* sudo make install
*
* [restart QT creator or QT designer, and do your
* designing with your fancy new widget.
*
* rosrun chewbot_gui chewbot_gui
*/
jogAxisWidget::jogAxisWidget(QWidget *parent) :
QWidget(parent)
{
ui.setupUi(this);
ui.label_jointName->setText("JT#");
show();
}
void jogAxisWidget::setJointLabel(QString new_name)
{
m_jointName = new_name;
ui.label_jointName->setText(m_jointName);
} | 22.147059 | 56 | 0.657371 | drewhamiltonasdf |
30cfea63786d16f703813270099aa3c88db77628 | 4,960 | hpp | C++ | tcob/include/tcob/gfx/drawables/ParticleSystem.hpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | 2 | 2021-08-18T19:14:35.000Z | 2021-12-01T14:14:49.000Z | tcob/include/tcob/gfx/drawables/ParticleSystem.hpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | null | null | null | tcob/include/tcob/gfx/drawables/ParticleSystem.hpp | TobiasBohnen/tcob | 53092b3c8e657f1ff5e48ce961659edf7cb1cb05 | [
"MIT"
] | null | null | null | // Copyright (c) 2021 Tobias Bohnen
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
#pragma once
#include <tcob/tcob_config.hpp>
#include <functional>
#include <list>
#include <mutex>
#include <optional>
#include <vector>
#include <tcob/core/Random.hpp>
#include <tcob/core/assets/Asset.hpp>
#include <tcob/core/data/AngleUnits.hpp>
#include <tcob/core/data/Rect.hpp>
#include <tcob/gfx/Renderer.hpp>
#include <tcob/gfx/Texture.hpp>
#include <tcob/gfx/Transformable.hpp>
#include <tcob/gfx/drawables/Drawable.hpp>
namespace tcob::gfx {
////////////////////////////////////////////////////////////
class ParticleSystem;
struct ParticleProperties {
DegreeF Direction { 0.f };
f64 Speed { 0. };
DegreeF Spin { 0.f };
f32 Acceleration { 0.f };
i32 Stage { 0 };
tcob::Color Color { Colors::White };
f32 Transparency { 0.f };
};
////////////////////////////////////////////////////////////
class Particle final : public RectTransformable, public Updatable {
friend class ParticleSystem;
public:
Particle();
void update(MilliSeconds deltaTime) override;
auto get_properties() const -> ParticleProperties;
void set_properties(const ParticleProperties& props);
auto get_lifetime_ratio() const -> f32;
void set_lifetime(MilliSeconds life);
auto is_alive() const -> bool;
auto is_visible() const -> bool;
void show();
void hide();
void set_material(AssetPtr<Material>, const std::string& texRegion);
private:
ParticleProperties _props {};
PointF _direction { PointF::Zero };
MilliSeconds _startingLife { 0 };
MilliSeconds _remainingLife { 0 };
AssetPtr<Material> _material {};
TextureRegion _region {};
bool _visible { true };
};
////////////////////////////////////////////////////////////
class ParticleEmitter final {
public:
ParticleEmitter();
auto is_alive() const -> bool;
void reset();
void set_texture_region(const std::string& texRegion);
void set_spawnarea(const RectF& area);
void set_spawnrate(f32 rate);
void set_lifetime(MilliSeconds life);
void set_loop(bool loop);
void set_particle_acceleration(f32 min, std::optional<f32> max = std::nullopt);
void set_particle_direction(DegreeF min, std::optional<DegreeF> max = std::nullopt);
void set_particle_lifetime(MilliSeconds min, std::optional<MilliSeconds> max = std::nullopt);
void set_particle_scale(f32 min, std::optional<f32> max = std::nullopt);
void set_particle_size(SizeF size);
void set_particle_speed(f32 min, std::optional<f32> max = std::nullopt);
void set_particle_spin(DegreeF min, std::optional<DegreeF> max = std::nullopt);
void set_particle_transparency(f32 min, std::optional<f32> max = std::nullopt);
void emit_particles(ParticleSystem& system, MilliSeconds time);
private:
Random _randomGen;
std::string _texture;
RectF _spawnArea { RectF::Zero };
std::pair<f32, f32> _areaXDist;
std::pair<f32, f32> _areaYDist;
f32 _spawnRate { 1 };
MilliSeconds _startLife { 1000 };
MilliSeconds _remainLife { 1000 };
bool _loop { false };
SizeF _parSize { SizeF::Zero };
std::pair<f32, f32> _parAcceleration;
std::pair<DegreeF, DegreeF> _parDirectionDegrees;
std::pair<f32, f32> _parLife;
std::pair<f32, f32> _parScale;
std::pair<f32, f32> _parSpeed;
std::pair<DegreeF, DegreeF> _parSpin;
std::pair<f32, f32> _parTransparency;
f64 _emissionDiff { 0 };
};
////////////////////////////////////////////////////////////
class ParticleSystem final : public Drawable {
friend void ParticleEmitter::emit_particles(ParticleSystem& system, MilliSeconds time);
public:
ParticleSystem() = default;
~ParticleSystem() override = default;
ParticleSystem(const ParticleSystem& other);
auto operator=(const ParticleSystem& other) -> ParticleSystem&;
void start();
void restart();
void stop();
auto create_emitter() -> ParticleEmitter&; // TODO: replace with add_emitter
void remove_all_emitters();
void add_affector(const std::function<void(Particle&)>& func);
auto get_material() const -> AssetPtr<Material>;
void set_material(AssetPtr<Material> material);
auto get_position() const -> PointF;
void set_position(const PointF& position);
auto get_particle_count() const -> u32;
protected:
void do_update(MilliSeconds deltaTime) override;
void do_draw(RenderTarget& target) override;
private:
auto activate_particle() -> Particle&;
void deactivate_particle(isize index);
bool _isRunning { false };
PointF _position { PointF::Zero };
DynamicQuadRenderer _renderer {};
AssetPtr<Material> _material {};
std::vector<std::function<void(Particle&)>> _affectors {};
std::vector<Particle> _particles {};
u32 _aliveParticleCount { 0 };
std::vector<ParticleEmitter> _emitters {};
};
} | 28.505747 | 97 | 0.664315 | TobiasBohnen |
30d68a3a7649a66e3bdd328840f4597bcb9be833 | 12,208 | cpp | C++ | kcgistream.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | kcgistream.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | null | null | null | kcgistream.cpp | ridgeware/dekaf2 | b914d880d1a5b7f5c8f89dedd36b13b7f4b0ee33 | [
"MIT"
] | 1 | 2021-08-20T16:15:01.000Z | 2021-08-20T16:15:01.000Z |
/*
//
// DEKAF(tm): Lighter, Faster, Smarter (tm)
//
// Copyright (c) 2018, Ridgeware, Inc.
//
// +-------------------------------------------------------------------------+
// | /\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\/\|
// |/+---------------------------------------------------------------------+/|
// |/| |/|
// |\| ** THIS NOTICE MUST NOT BE REMOVED FROM THE SOURCE CODE MODULE ** |\|
// |/| |/|
// |\| OPEN SOURCE LICENSE |\|
// |/| |/|
// |\| 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 "kcgistream.h"
#include "klog.h"
#include "ksystem.h"
#include "khttp_header.h"
#include "kctype.h"
#include <array>
namespace dekaf2 {
//-----------------------------------------------------------------------------
std::streamsize KCGIInStream::StreamReader(void* sBuffer, std::streamsize iCount, void* stream_)
//-----------------------------------------------------------------------------
{
// we do not need to loop the reader, as the streambuf requests bytes in blocks
// and calls underflow() if more are expected
if (stream_)
{
auto stream = static_cast<KCGIInStream::Stream*>(stream_);
char* sOutBuf = static_cast<char*>(sBuffer);
auto iRemain = iCount;
// lazy creation of header from CGI env vars
stream->CreateHeader();
if (!stream->sHeader.empty())
{
// copy from the header buffer into the stream buffer
auto iCopy = std::min(static_cast<KStringView::size_type>(iRemain), stream->sHeader.size());
std::memcpy(sOutBuf, stream->sHeader.data(), iCopy);
stream->sHeader.remove_prefix(iCopy);
iRemain -= iCopy;
if (!iRemain)
{
return iCount;
}
// adjust output pointer
sOutBuf += iCopy;
}
if (!stream->chCommentDelimiter)
{
// we do not have to skip comment lines, so read all in one part
stream->istream->read(sOutBuf, iRemain);
return stream->istream->gcount() + (iCount - iRemain);
}
else
{
// we have to skip comment lines, therefore buffer all in a temporary
// string and copy into the output if not a comment, and loop if by
// skipping comment lines we reduced the real output size
KString sBuf;
while (iRemain > 0)
{
// make room for the requested buffer size
sBuf.resize_uninitialized(iRemain);
auto iRead = stream->istream->read(&sBuf[0], iRemain).gcount();
if (!iRead)
{
// no more data - EOF
break;
}
if (iRead < iRemain)
{
// shrink the buffer to the real input size
sBuf.resize(iRead);
}
KStringView svBuf(sBuf);
while (!svBuf.empty())
{
if (stream->bAtStartOfLine)
{
stream->bIsComment = (svBuf.front() == stream->chCommentDelimiter);
}
auto pos = svBuf.find('\n');
if (pos == KStringView::npos)
{
// last fragment, no EOL
stream->bAtStartOfLine = false;
pos = svBuf.size();
}
else
{
stream->bAtStartOfLine = true;
++pos;
}
if (!stream->bIsComment)
{
// copy the current line from the input sv
std::memcpy(sOutBuf, svBuf.data(), pos);
iRemain -= pos;
sOutBuf += pos;
}
// and remove the current line from the input sv
svBuf.remove_prefix(pos);
}
}
return iCount - iRemain;
}
}
return 0;
} // StreamReader
//-----------------------------------------------------------------------------
KString KCGIInStream::ConvertHTTPHeaderNameToCGIVar(KStringView sHeadername)
//-----------------------------------------------------------------------------
{
KString sCGI;
sCGI.reserve(sHeadername.size() + 5);
sCGI = "HTTP_";
for (auto ch : sHeadername)
{
if (KASCII::kIsAlNum(ch))
{
sCGI += KASCII::kToUpper(ch);
}
else if (ch == '-')
{
sCGI += '_';
}
}
return sCGI;
} // ConvertHTTPHeaderNameToCGIVar
//-----------------------------------------------------------------------------
KString KCGIInStream::ConvertCGIVarToHTTPHeaderName(KStringView sCGIVar)
//-----------------------------------------------------------------------------
{
KString sHeaderName;
sCGIVar.remove_prefix("HTTP_");
sHeaderName.reserve(sCGIVar.size());
bool bIsFirst { true };
for (auto ch : sCGIVar)
{
if (KASCII::kIsAlNum(ch))
{
if (bIsFirst)
{
sHeaderName += KASCII::kToUpper(ch);
bIsFirst = false;
}
else
{
sHeaderName += KASCII::kToLower(ch);
}
}
else if (ch == '_')
{
sHeaderName += '-';
bIsFirst = true;
}
}
return sHeaderName;
} // ConvertCGIVarToHTTPHeaderName
//-----------------------------------------------------------------------------
void KCGIInStream::Stream::AddCGIVar(KString sCGIVar, KString sHTTPHeader)
//-----------------------------------------------------------------------------
{
m_AdditionalCGIVars.push_back({std::move(sCGIVar), std::move(sHTTPHeader)});
} // AddCGIVar
//-----------------------------------------------------------------------------
void KCGIInStream::Stream::CreateHeader()
//-----------------------------------------------------------------------------
{
if (bIsCreated)
{
return;
}
bIsCreated = true;
auto sMethod = kGetEnv(KCGIInStream::REQUEST_METHOD);
if (sMethod.empty())
{
kDebug (1, "we are not running within a web server...");
// permitting for comment lines
chCommentDelimiter = '#';
return;
}
kDebug (1, "we are running within a web server that sets the CGI variables...");
// add method, resource and protocol from env vars
m_sHeader = sMethod;
m_sHeader += ' ';
m_sHeader += kGetEnv(KCGIInStream::REQUEST_URI);
m_sHeader += ' ';
m_sHeader += kGetEnv(KCGIInStream::SERVER_PROTOCOL);
kDebug(1, m_sHeader);
m_sHeader += "\r\n";
struct CGIVars_t { KStringViewZ sVar; KHTTPHeader::Header Header; };
static constexpr std::array<CGIVars_t, 12> CGIVars
{{
{ KCGIInStream::HTTP_ACCEPT, KHTTPHeader::ACCEPT },
{ KCGIInStream::HTTP_ACCEPT_ENCODING, KHTTPHeader::ACCEPT_ENCODING },
{ KCGIInStream::HTTP_ACCEPT_LANGUAGE, KHTTPHeader::ACCEPT_LANGUAGE },
{ KCGIInStream::HTTP_AUTHORIZATION, KHTTPHeader::AUTHORIZATION },
{ KCGIInStream::HTTP_CONNECTION, KHTTPHeader::CONNECTION },
{ KCGIInStream::HTTP_COOKIE, KHTTPHeader::COOKIE },
{ KCGIInStream::HTTP_HOST, KHTTPHeader::HOST },
{ KCGIInStream::HTTP_REFERER, KHTTPHeader::REFERER },
{ KCGIInStream::HTTP_USER_AGENT, KHTTPHeader::USER_AGENT },
{ KCGIInStream::CONTENT_TYPE, KHTTPHeader::CONTENT_TYPE },
{ KCGIInStream::CONTENT_LENGTH, KHTTPHeader::CONTENT_LENGTH },
{ KCGIInStream::REMOTE_ADDR, KHTTPHeader::X_FORWARDED_FOR },
}};
// add headers from env vars
for (const auto& it : CGIVars)
{
KString sEnv = kGetEnv(it.sVar);
if (!sEnv.empty())
{
m_sHeader += KHTTPHeader(it.Header).Serialize();
m_sHeader += ": ";
m_sHeader += sEnv;
m_sHeader += "\r\n";
}
}
// add non-standard headers from env vars
for (const auto& it : m_AdditionalCGIVars)
{
KString sEnv = kGetEnv(it.first);
if (!sEnv.empty())
{
m_sHeader += it.second;
m_sHeader += ": ";
m_sHeader += sEnv;
m_sHeader += "\r\n";
}
}
// final end of header line
m_sHeader += "\r\n";
// point string view into the constructed header
sHeader = m_sHeader;
} // CreateHeader
//-----------------------------------------------------------------------------
KCGIInStream::KCGIInStream(std::istream& istream)
//-----------------------------------------------------------------------------
: base_type(&m_StreamBuf)
, m_Stream(&istream)
{
} // ctor
#ifdef DEKAF2_REPEAT_CONSTEXPR_VARIABLE
constexpr KStringViewZ KCGIInStream::AUTH_PASSWORD;
constexpr KStringViewZ KCGIInStream::AUTH_TYPE;
constexpr KStringViewZ KCGIInStream::AUTH_USER;
constexpr KStringViewZ KCGIInStream::CERT_COOKIE;
constexpr KStringViewZ KCGIInStream::CERT_FLAGS;
constexpr KStringViewZ KCGIInStream::CERT_ISSUER;
constexpr KStringViewZ KCGIInStream::CERT_KEYSIZE;
constexpr KStringViewZ KCGIInStream::CERT_SECRETKEYSIZE;
constexpr KStringViewZ KCGIInStream::CERT_SERIALNUMBER;
constexpr KStringViewZ KCGIInStream::CERT_SERVER_ISSUER;
constexpr KStringViewZ KCGIInStream::CERT_SERVER_SUBJECT;
constexpr KStringViewZ KCGIInStream::CERT_SUBJECT;
constexpr KStringViewZ KCGIInStream::CF_TEMPLATE_PATH;
constexpr KStringViewZ KCGIInStream::CONTENT_LENGTH;
constexpr KStringViewZ KCGIInStream::CONTENT_TYPE;
constexpr KStringViewZ KCGIInStream::CONTEXT_PATH;
constexpr KStringViewZ KCGIInStream::GATEWAY_INTERFACE;
constexpr KStringViewZ KCGIInStream::HTTPS;
constexpr KStringViewZ KCGIInStream::HTTPS_KEYSIZE;
constexpr KStringViewZ KCGIInStream::HTTPS_SECRETKEYSIZE;
constexpr KStringViewZ KCGIInStream::HTTPS_SERVER_ISSUER;
constexpr KStringViewZ KCGIInStream::HTTPS_SERVER_SUBJECT;
constexpr KStringViewZ KCGIInStream::HTTP_ACCEPT;
constexpr KStringViewZ KCGIInStream::HTTP_ACCEPT_ENCODING;
constexpr KStringViewZ KCGIInStream::HTTP_ACCEPT_LANGUAGE;
constexpr KStringViewZ KCGIInStream::HTTP_AUTHORIZATION;
constexpr KStringViewZ KCGIInStream::HTTP_CONNECTION;
constexpr KStringViewZ KCGIInStream::HTTP_COOKIE;
constexpr KStringViewZ KCGIInStream::HTTP_HOST;
constexpr KStringViewZ KCGIInStream::HTTP_REFERER;
constexpr KStringViewZ KCGIInStream::HTTP_USER_AGENT;
constexpr KStringViewZ KCGIInStream::QUERY_STRING;
constexpr KStringViewZ KCGIInStream::REMOTE_ADDR;
constexpr KStringViewZ KCGIInStream::REMOTE_HOST;
constexpr KStringViewZ KCGIInStream::REMOTE_USER;
constexpr KStringViewZ KCGIInStream::REQUEST_METHOD;
constexpr KStringViewZ KCGIInStream::REQUEST_URI;
constexpr KStringViewZ KCGIInStream::SCRIPT_NAME;
constexpr KStringViewZ KCGIInStream::SERVER_NAME;
constexpr KStringViewZ KCGIInStream::SERVER_PORT;
constexpr KStringViewZ KCGIInStream::SERVER_PORT_SECURE;
constexpr KStringViewZ KCGIInStream::SERVER_PROTOCOL;
constexpr KStringViewZ KCGIInStream::SERVER_SOFTWARE;
constexpr KStringViewZ KCGIInStream::WEB_SERVER_API;
#endif
} // of namespace dekaf2
| 32.468085 | 96 | 0.573231 | ridgeware |
30d7585356ab37aa28950b5d6addd78897d85f7c | 4,301 | cpp | C++ | src/tex_op/to_io.cpp | cewbost/texgen | f572ea5590457f37b72286c50c020eee25bddc78 | [
"MIT"
] | null | null | null | src/tex_op/to_io.cpp | cewbost/texgen | f572ea5590457f37b72286c50c020eee25bddc78 | [
"MIT"
] | null | null | null | src/tex_op/to_io.cpp | cewbost/texgen | f572ea5590457f37b72286c50c020eee25bddc78 | [
"MIT"
] | null | null | null |
#include "../tex_op.h"
#include "to_common.h"
namespace
{
void _copyc2t(Texture* dest, const uint8_t* src, int from, int to)
{
auto dest_p = dest->data() + from;
src += from * 4;
for(int i = from; i < to; ++i)
{
(*dest_p)[0] = (float)src[0] / 255;
(*dest_p)[1] = (float)src[1] / 255;
(*dest_p)[2] = (float)src[2] / 255;
(*dest_p)[3] = (float)src[3] / 255;
++dest_p;
src += 4;
}
}
void _copyt2c(uint8_t* dest, const Texture* src, int from, int to)
{
auto src_p = src->data() + from;
dest += from * 4;
for(int i = from; i < to; ++i)
{
dest[0] = (uint8_t)((*src_p)[0] * 255.5);
dest[1] = (uint8_t)((*src_p)[1] * 255.5);
dest[2] = (uint8_t)((*src_p)[2] * 255.5);
dest[3] = (uint8_t)((*src_p)[3] * 255.5);
dest += 4;
++src_p;
}
}
void _copyf2t(Texture* dest, const float* src, int from, int to)
{
auto src_p = src + from * 4;
for(int i = from; i < to; ++i)
{
dest->get(i)[0] = (float)src_p[0];
dest->get(i)[1] = (float)src_p[1];
dest->get(i)[2] = (float)src_p[2];
dest->get(i)[3] = (float)src_p[3];
src_p += 4;
}
}
void _copyt2f(float* dest, const Texture* src, int from, int to)
{
auto dest_p = dest + from * 4;
for(int i = from; i < to; ++i)
{
dest_p[0] = (float)src->get(i)[0];
dest_p[1] = (float)src->get(i)[1];
dest_p[2] = (float)src->get(i)[2];
dest_p[3] = (float)src->get(i)[3];
dest_p += 4;
}
}
template<int mask>
class _copyChannelc2t
{
public:
static void func(Texture* dest, const uint8_t* src, int from, int to)
{
auto dest_p = dest->data() + from;
src += from;
for(int i = from; i < to; ++i)
{
if(mask & 0x1) (*dest_p)[0] = (float)(*src) / 255;
if(mask & 0x2) (*dest_p)[1] = (float)(*src) / 255;
if(mask & 0x4) (*dest_p)[2] = (float)(*src) / 255;
if(mask & 0x8) (*dest_p)[3] = (float)(*src) / 255;
++dest_p;
++src;
}
}
};
template<int mask>
class _copyChannelf2t
{
public:
static void func(Texture* dest, const float* src, int from, int to)
{
for(int i = from; i < to; ++i)
{
if(mask & 0x1) dest->get(i)[0] = (float)src[i];
if(mask & 0x2) dest->get(i)[1] = (float)src[i];
if(mask & 0x4) dest->get(i)[2] = (float)src[i];
if(mask & 0x8) dest->get(i)[3] = (float)src[i];
}
}
};
template<int ch>
class _copyChannelt2c
{
public:
static void func(const Texture* src, uint8_t* dest, int from, int to)
{
auto src_p = src->data() + from;
dest += from;
for(int i = from; i < to; ++i)
{
*dest = (uint8_t)((*src_p)[ch] * 255.5);
++dest;
++src_p;
}
}
};
template<int ch>
class _copyChannelt2f
{
public:
static void func(const Texture* src, float* dest, int from, int to)
{
for(int i = from; i < to; ++i)
dest[i] = (float)src->get(i)[ch];
}
};
}
namespace TexOp
{
void writeRawTexture(Texture* dest, const uint8_t* src)
{
int elements = dest->width * dest->height;
_launchThreads(elements, _copyc2t, dest, src);
}
void writeRawTexture(Texture* dest, const float* src)
{
int elements = dest->width * dest->height;
_launchThreads(elements, _copyf2t, dest, src);
}
void writeRawChannel(Texture* dest, const uint8_t* src, std::bitset<4> mask)
{
_launchThreadsMasked<_copyChannelc2t>(mask.to_ulong(), dest, src);
}
void writeRawChannel(Texture* dest, const float* src, std::bitset<4> mask)
{
_launchThreadsMasked<_copyChannelf2t>(mask.to_ulong(), dest, src);
}
void readRawTexture(uint8_t* dest, const Texture* src)
{
int elements = src->width * src->height;
_launchThreads(elements, _copyt2c, dest, src);
}
void readRawTexture(float* dest, const Texture* src)
{
int elements = src->width * src->height;
_launchThreads(elements, _copyt2f, dest, src);
}
void readRawChannel(uint8_t* dest, const Texture* src, int ch)
{
_launchThreadsCh<_copyChannelt2c>(ch, src, dest);
}
void readRawChannel(float* dest, const Texture* src, int ch)
{
_launchThreadsCh<_copyChannelt2f>(ch, src, dest);
}
} | 26.22561 | 78 | 0.54778 | cewbost |
30dc2ac9fad5105724e2208182a2dfe5340ad24b | 898 | cpp | C++ | Questions Level-Wise/Easy/second-minimum-node-in-a-binary-tree.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | 2 | 2021-03-05T22:32:23.000Z | 2021-03-05T22:32:29.000Z | Tree/second-minimum-node-in-a-binary-tree.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | Tree/second-minimum-node-in-a-binary-tree.cpp | PrakharPipersania/LeetCode-Solutions | ea74534bbdcf1ca3ea4d88a1081582e0e15f50c7 | [
"MIT"
] | null | null | null | /**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
void Value(TreeNode* root,map<int,int> &A)
{
A[root->val]++;
if(root->left!= NULL)
Value(root->left,A);
if(root->right!= NULL)
Value(root->right,A);
}
int findSecondMinimumValue(TreeNode* root)
{
int c=0;
map<int,int> A;
if(root==NULL)
return -1;
Value(root,A);
for(auto e: A)
{
c++;
if(c==2)
return e.first;
}
return -1;
}
}; | 24.27027 | 93 | 0.483296 | PrakharPipersania |
30e5591beb92bc041843428a9aa754e426be867e | 1,157 | hpp | C++ | reg/stm32/f0/timer.hpp | pavelrevak/io | c071af35fd0a2b5978e604555a170e48ac698f35 | [
"MIT"
] | 20 | 2018-03-14T11:05:00.000Z | 2022-03-13T13:28:26.000Z | reg/stm32/f0/timer.hpp | pavelrevak/io | c071af35fd0a2b5978e604555a170e48ac698f35 | [
"MIT"
] | null | null | null | reg/stm32/f0/timer.hpp | pavelrevak/io | c071af35fd0a2b5978e604555a170e48ac698f35 | [
"MIT"
] | 5 | 2018-07-15T11:44:03.000Z | 2020-11-08T18:06:33.000Z | /**
* Peripheral Definition File
*
* TIMER - Timers
*
* MCUs containing this peripheral:
* - STM32F0xx
*/
#pragma once
#include <cstdint>
#include <cstddef>
#include "io/reg/stm32/_common/timer.hpp"
namespace io {
namespace base {
static const size_t TIM1 = 0x40012c00;
static const size_t TIM2 = 0x40000000;
static const size_t TIM3 = 0x40000400;
static const size_t TIM6 = 0x40001000;
static const size_t TIM7 = 0x40001400;
static const size_t TIM14 = 0x40002000;
static const size_t TIM15 = 0x40014000;
static const size_t TIM16 = 0x40014400;
static const size_t TIM17 = 0x40014800;
}
static Timer &TIM1 = *reinterpret_cast<Timer *>(base::TIM1);
static Timer &TIM2 = *reinterpret_cast<Timer *>(base::TIM2);
static Timer &TIM3 = *reinterpret_cast<Timer *>(base::TIM3);
static Timer &TIM6 = *reinterpret_cast<Timer *>(base::TIM6);
static Timer &TIM7 = *reinterpret_cast<Timer *>(base::TIM7);
static Timer &TIM14 = *reinterpret_cast<Timer *>(base::TIM14);
static Timer &TIM15 = *reinterpret_cast<Timer *>(base::TIM15);
static Timer &TIM16 = *reinterpret_cast<Timer *>(base::TIM16);
static Timer &TIM17 = *reinterpret_cast<Timer *>(base::TIM17);
}
| 26.295455 | 62 | 0.737252 | pavelrevak |
30e6c0f70a0771445a978297b9216dc992f58398 | 1,269 | cpp | C++ | vsr/private/vsr_framebuffer.cpp | sanglin307/vsr_dev | 21fe9a3cbdc003c51092702bc9445acc49016277 | [
"MIT"
] | null | null | null | vsr/private/vsr_framebuffer.cpp | sanglin307/vsr_dev | 21fe9a3cbdc003c51092702bc9445acc49016277 | [
"MIT"
] | null | null | null | vsr/private/vsr_framebuffer.cpp | sanglin307/vsr_dev | 21fe9a3cbdc003c51092702bc9445acc49016277 | [
"MIT"
] | null | null | null | #include "vsr_common.h"
#include "vsr_framebuffer.h"
#include "vsr_device.h"
VkAllocationCallbacks *MemoryAlloc<VkFramebuffer_T, VK_SYSTEM_ALLOCATION_SCOPE_OBJECT>::_pAllocator = nullptr;
VkFramebuffer_T::VkFramebuffer_T(const VkFramebufferCreateInfo* pCreateInfo)
:_renderPass(pCreateInfo->renderPass),_width(pCreateInfo->width),_height(pCreateInfo->height),_layers(pCreateInfo->layers)
{
for (uint32_t i = 0; i < pCreateInfo->attachmentCount; i++)
{
_vecAttachments.push_back(pCreateInfo->pAttachments[i]);
}
}
VKAPI_ATTR VkResult VKAPI_CALL vkCreateFramebuffer(
VkDevice device,
const VkFramebufferCreateInfo* pCreateInfo,
const VkAllocationCallbacks* pAllocator,
VkFramebuffer* pFramebuffer)
{
try
{
*pFramebuffer = new(pAllocator) VkFramebuffer_T(pCreateInfo);
}
catch (...)
{
return VK_ERROR_OUT_OF_HOST_MEMORY;
}
device->Registe(*pFramebuffer);
return VK_SUCCESS;
}
VKAPI_ATTR void VKAPI_CALL vkDestroyFramebuffer(
VkDevice device,
VkFramebuffer framebuffer,
const VkAllocationCallbacks* pAllocator)
{
device->UnRegiste(framebuffer);
delete framebuffer;
}
| 29.511628 | 123 | 0.687155 | sanglin307 |
30e83e86ed41aa598e132975f1358b910ae76be1 | 2,222 | cc | C++ | src/demo/sky_quad.cc | auygun/kaliber | c6501323cf5c447334a2bfb6b7a5899dea0776e6 | [
"MIT"
] | 3 | 2020-06-22T19:37:49.000Z | 2020-11-14T10:45:27.000Z | src/demo/sky_quad.cc | auygun/kaliber | c6501323cf5c447334a2bfb6b7a5899dea0776e6 | [
"MIT"
] | 1 | 2020-06-03T13:05:24.000Z | 2020-06-03T13:05:24.000Z | src/demo/sky_quad.cc | auygun/kaliber | c6501323cf5c447334a2bfb6b7a5899dea0776e6 | [
"MIT"
] | null | null | null | #include "sky_quad.h"
#include "../base/interpolation.h"
#include "../base/log.h"
#include "../base/random.h"
#include "../engine/engine.h"
#include "../engine/renderer/geometry.h"
#include "../engine/renderer/shader.h"
#include "../engine/shader_source.h"
using namespace base;
using namespace eng;
SkyQuad::SkyQuad()
: shader_(Engine::Get().CreateRenderResource<Shader>()),
sky_offset_{
0, Lerp(0.0f, 10.0f, Engine::Get().GetRandomGenerator().GetFloat())} {
last_sky_offset_ = sky_offset_;
}
SkyQuad::~SkyQuad() = default;
bool SkyQuad::Create(bool without_nebula) {
without_nebula_ = without_nebula;
if (!CreateShaders())
return false;
scale_ = Engine::Get().GetScreenSize();
color_animator_.Attach(this);
SetVisible(true);
return true;
}
void SkyQuad::Update(float delta_time) {
last_sky_offset_ = sky_offset_;
sky_offset_ += {0, delta_time * speed_};
}
void SkyQuad::Draw(float frame_frac) {
Vector2f sky_offset = Lerp(last_sky_offset_, sky_offset_, frame_frac);
shader_->Activate();
shader_->SetUniform("scale", scale_);
shader_->SetUniform("projection", Engine::Get().GetProjectionMatrix());
shader_->SetUniform("sky_offset", sky_offset);
if (!without_nebula_)
shader_->SetUniform("nebula_color",
{nebula_color_.x, nebula_color_.y, nebula_color_.z});
shader_->UploadUniforms();
Engine::Get().GetQuad()->Draw();
}
void SkyQuad::ContextLost() {
CreateShaders();
}
void SkyQuad::SwitchColor(const Vector4f& color) {
color_animator_.Pause(Animator::kBlending);
color_animator_.SetTime(Animator::kBlending, 0);
color_animator_.SetBlending(color, 5,
std::bind(SmoothStep, std::placeholders::_1));
color_animator_.Play(Animator::kBlending, false);
}
bool SkyQuad::CreateShaders() {
Engine& engine = Engine::Get();
auto source = std::make_unique<ShaderSource>();
if (!source->Load(without_nebula_ ? "sky_without_nebula.glsl" : "sky.glsl"))
return false;
shader_->Create(std::move(source), engine.GetQuad()->vertex_description(),
Engine::Get().GetQuad()->primitive(), false);
return true;
}
void SkyQuad::SetSpeed(float speed) {
speed_ = speed;
} | 27.097561 | 80 | 0.687219 | auygun |
30edfa2c47c22a98787740b358212b5adce9ea90 | 3,570 | cpp | C++ | Blue-Flame-Engine/Core/BF/Graphics/TerrainGenerator.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | 2 | 2020-10-12T13:40:05.000Z | 2021-09-17T08:37:03.000Z | Blue-Flame-Engine/Core/BF/Graphics/TerrainGenerator.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | null | null | null | Blue-Flame-Engine/Core/BF/Graphics/TerrainGenerator.cpp | FantasyVII/Blue-Flame-Engine | b0e44ccffdd41539fa9075e5d6a2b3c1cc811d96 | [
"MIT"
] | null | null | null | #include "TerrainGenerator.h"
#include "BF/Engine.h"
#include "BF/Graphics/Mesh.h"
#include "BF/Math/Math.h"
#include "BF/IO/ImageLoader.h"
#include "BF/System/Debug.h"
#define TERRAIN_WIDTH 256
#define TERRAIN_HEIGHT 256
#define QUAD_INDICES 6
#define ROW_VERTICES (TERRAIN_WIDTH + 1)
#define COLUMN_VERTICES (TERRAIN_HEIGHT + 1)
#define VERTICES_SIZE ROW_VERTICES * COLUMN_VERTICES
#define INDICES_SIZE TERRAIN_WIDTH * TERRAIN_HEIGHT * QUAD_INDICES
#define TERRAIN_SCALE 30
namespace BF
{
namespace Graphics
{
using namespace BF::Math;
using namespace BF::Graphics::API;
TerrainGenerator::TerrainGenerator()
{
}
TerrainGenerator::~TerrainGenerator()
{
}
void TerrainGenerator::Initialize()
{
glEnable(GL_CULL_FACE);
glFrontFace(GL_CW);
glCullFace(GL_BACK);
shader.LoadStandardShader(ShaderType::Terrain);
vertexBufferLayout.Push(0, "POSITION", VertexBufferLayout::DataType::Float3, sizeof(MeshData::PUVNVertexData), 0);
vertexBufferLayout.Push(1, "TEXCOORD", VertexBufferLayout::DataType::Float2, sizeof(MeshData::PUVNVertexData), sizeof(Vector3f));
vertexBufferLayout.Push(2, "NORMAL", VertexBufferLayout::DataType::Float3, sizeof(MeshData::PUVNVertexData), sizeof(Vector3f) + sizeof(Vector2f));
}
void TerrainGenerator::Load(const std::string& filename)
{
textureData = BF::IO::ImageLoader::Load(filename);
MeshData::PUVNVertexData* vertices = new MeshData::PUVNVertexData[VERTICES_SIZE];
Vector3f startingPosition;
Vector2f size = Vector2f(2.0f, 2.0f);
int stride = 32 / 8;
unsigned int* indecies = new unsigned int[INDICES_SIZE];
int index = 0;
for (int z = 0; z < COLUMN_VERTICES; z++)
{
startingPosition.z = size.y * z;
for (int x = 0; x < ROW_VERTICES; x++)
{
startingPosition.x = size.x * x;
int pixel = (x * stride) + (z * (int)textureData->width * stride);
int v = textureData->buffer[pixel];
float normalizedData = Normalize(v, 0, 256);
vertices[x + (z * ROW_VERTICES)] = MeshData::PUVNVertexData(Vector3f(startingPosition.x, startingPosition.y + (normalizedData * TERRAIN_SCALE), -startingPosition.z), Vector2f(), Vector3f(0.0f, 1.0f, 0.0f));
if (x < TERRAIN_WIDTH && z < TERRAIN_HEIGHT)
{
indecies[index + 0] = x + 0 + (z * ROW_VERTICES);
indecies[index + 1] = x + 1 + (z * ROW_VERTICES);
indecies[index + 2] = x + 1 + ((z + 1) * ROW_VERTICES);
indecies[index + 3] = x + 1 + ((z + 1) * ROW_VERTICES);
indecies[index + 4] = x + 0 + ((z + 1) * ROW_VERTICES);
indecies[index + 5] = x + 0 + (z * ROW_VERTICES);
index += 6;
}
}
}
for (int z = 0; z < COLUMN_VERTICES - 1; z++)
{
for (int x = 0; x < ROW_VERTICES - 1; x++)
{
const Vector3f &v0 = vertices[x + (z * ROW_VERTICES)].position;
const Vector3f &v1 = vertices[(x + 1) + (z * ROW_VERTICES)].position;
const Vector3f &v2 = vertices[(x + 1) + ((z + 1) * ROW_VERTICES)].position;
Vector3f N = ((v1 - v0).Cross(v2 - v0)).Normalize();
vertices[x + (z * ROW_VERTICES)].normal = N;
}
}
vertexBuffer.Create((unsigned int)VERTICES_SIZE * sizeof(MeshData::PUVNVertexData), vertices);
indexBuffer.Create(indecies, INDICES_SIZE);
vertexBuffer.SetLayout(shader, &vertexBufferLayout);
delete[] indecies;
}
/*void Terrain::Render()
{
shader.Bind();
vertexBuffer.Bind();
indexBuffer.Bind();
Engine::GetContext().Draw(indexBuffer.GetIndicesCount());
indexBuffer.Unbind();
vertexBuffer.Unbind();
shader.Unbind();
}*/
}
} | 29.02439 | 211 | 0.660784 | FantasyVII |
30f296a8f13e25ddbfadf1510a2947350f646505 | 732 | hpp | C++ | lib/filesystem/include/filesystem/detail.hpp | mbwatson/irods | c242db4cb20155500767d76b62bcbc4d4032b6cf | [
"BSD-3-Clause"
] | null | null | null | lib/filesystem/include/filesystem/detail.hpp | mbwatson/irods | c242db4cb20155500767d76b62bcbc4d4032b6cf | [
"BSD-3-Clause"
] | null | null | null | lib/filesystem/include/filesystem/detail.hpp | mbwatson/irods | c242db4cb20155500767d76b62bcbc4d4032b6cf | [
"BSD-3-Clause"
] | null | null | null | #ifndef IRODS_FILESYSTEM_DETAIL_HPP
#define IRODS_FILESYSTEM_DETAIL_HPP
#include "filesystem/path.hpp"
#include "filesystem/filesystem_error.hpp"
#include "rodsDef.h"
#include <cstring>
namespace irods::experimental::filesystem::detail
{
inline void throw_if_path_length_exceeds_limit(const irods::experimental::filesystem::path& _p)
{
if (std::strlen(_p.c_str()) > MAX_NAME_LEN) {
throw irods::experimental::filesystem::filesystem_error{"path length cannot exceed max path size"};
}
}
inline auto is_separator(path::value_type _c) noexcept -> bool
{
return path::separator == _c;
}
} // irods::experimental::filesystem::detail
#endif // IRODS_FILESYSTEM_DETAIL_HPP
| 27.111111 | 111 | 0.718579 | mbwatson |
30f3bfd1cc119978cf3e18485240268ca99b2c08 | 6,550 | hpp | C++ | HEIG_PRG1_labo32/Sint.hpp | DrC0okie/HEIG_PRG1_Labos | c8433a1bd171946cc68ecb95c1a54dc60e832d9b | [
"MIT"
] | null | null | null | HEIG_PRG1_labo32/Sint.hpp | DrC0okie/HEIG_PRG1_Labos | c8433a1bd171946cc68ecb95c1a54dc60e832d9b | [
"MIT"
] | null | null | null | HEIG_PRG1_labo32/Sint.hpp | DrC0okie/HEIG_PRG1_Labos | c8433a1bd171946cc68ecb95c1a54dc60e832d9b | [
"MIT"
] | null | null | null | // File: Sint.hpp
// Author: Timothee Van Hove
// Date: 15.01.2022
// Description: Header of the Sint class
#ifndef SINT_HPP
#define SINT_HPP
#include "Uint.hpp"
class Sint
{
private:
Uint iValue;
bool isPositive;
/** @brief Compares if the left Sint is <, >, or ==
* @param left The left Sint
* @param right The right Sint
* @return 1 if left < right, -1 if left > right and 0 if left == right */
int cmp(const Sint &left, const Sint &right) const;
/** @brief Manage the sign of the left Sint for multiplication and division
* @param a The left Sint to manage
* @param b The right Sint
* @return The Sint with correct sign*/
Sint &manageSign(Sint &a, const Sint &b);
/** @brief delete the sign if zero
* @param s the Sint to check */
Sint &checkZeroSign(Sint &s);
public:
/** @brief Empty constructor */
Sint(){}
/** @brief Constructor with a Uint
* @param u The Uint used to construct the Sint */
Sint(const Uint& u) {iValue = u; isPositive = true;}
/** @brief String constructor
* @param str The string used for the construction */
Sint(const std::string &str);
/** @brief int64_t constructor
* @param number The int64_t used for the construction */
Sint(int64_t number);
/** @brief Returns the absolute value of an Sint
* @return the absolute value as Uint */
Uint abs() const { return iValue;}
/** @brief Overload of the unary - operator for the Sint class
* @return Sint with opposite sign */
Sint &operator-(){isPositive = !isPositive;return *this;}
/** @brief Overload of the << operator for the Sint class
* @param os The output stream (left member)
* @param s The Sint value (right member)
* @return The output stream containing the Sint value */
friend std::ostream &operator<<(std::ostream &os, const Sint &s);
/** @brief Overload of the >> operator for the Sint class
* @param is The input stream (left member)
* @param s The Sint value (right member)
* @return The input stream containing the Sint value */
friend std::istream &operator>>(std::istream &is, Sint &s);
/** @brief Overload of the + operator for the Sint class
* @param left The left member of the addition
* @param right The right member of the addition
* @return The result of the addition */
friend Sint operator+(Sint left, const Sint &right){return left += right;}
/** @brief Overload of the - operator for the Sint class
* @param left The left member of the subtraction
* @param right The right member of the subtraction
* @return The difference of the subtration */
friend Sint operator-(Sint left, const Sint &right){return left -= right;}
/** @brief Overload of the * operator for the Sint class
* @param left The left member of the multiplication
* @param right The right member of the multiplication
* @return The product of the multiplication */
friend Sint operator*(Sint left, const Sint &right){return left *= right;}
/** @brief Overload of the / operator for the Sint class
* @param left The left member of the division (dividend)
* @param right The right member of the division (divizor)
* @return The quotient of the division */
friend Sint operator/(Sint left, const Sint &right){return left /= right;}
/** @brief Overload of the % operator for the Sint class
* @param left The left member of the modulus (remainder)
* @param right The right member of the modulus (divizor)
* @return The result of the modulus */
friend Sint operator%(Sint left, const Sint &right){return left %= right;}
/** @brief Overload of the += operator for the Sint class
* @param right The right member to add (Sint)
* @return The Sint object after the addition */
Sint &operator+=(const Sint &right);
/** @brief Overload of the -= operator for the Sint class
* @param right The right member to subtract (Sint)
* @return The Sint object after the subtraction */
Sint &operator-=(const Sint &right);
/** @brief Overload of the *= operator for the Sint class
* @param right The right member to multiply (Sint)
* @return The Sint object after the multiplication */
Sint &operator*=(const Sint &right);
/** @brief Overload of the /= operator for the Sint class
* @param right The right member (divizor) (Sint)
* @return The Sint object after the division */
Sint &operator/=(const Sint &right);
/** @brief Overload of the %= operator for the Sint class
* @param right The right member (divizor) (Sint)
* @return The Sint object after the modulus */
Sint &operator%=(const Sint &right);
/** @brief Overload of the < operator for the Sint class
* @param right The right member to compare with
* @return true if (left member) < (right member), false if not */
bool operator<(const Sint &right) const { return cmp(*this, right) == -1; }
/** @brief Overload of the <= operator for the Sint class
* @param right The right member to compare with
* @return true if (left member) <= (right member), false if not */
bool operator<=(const Sint &right) const { return cmp(*this, right) != 1; }
/** @brief Overload of the > operator for the Sint class
* @param right The right member to compare with
* @return true if (left member) > (right member), false if not */
bool operator>(const Sint &right) const { return cmp(*this, right) == 1; }
/** @brief Overload of the >= operator for the Sint class
* @param right The right member to compare with
* @return true if (left member) >= (right member), false if not */
bool operator>=(const Sint &right) const { return cmp(*this, right) != -1; }
/** @brief Overload of the == operator for the Sint class
* @param right The right member to compare with
* @return true if (left member) == (right member), false if not */
bool operator==(const Sint &right) const { return cmp(*this, right) == 0; }
/** @brief Overload of the != operator for the Sint class
* @param right The right member to compare with
* @return true if (left member) != (right member), false if not */
bool operator!=(const Sint &right) const { return cmp(*this, right) != 0; }
/** @brief Overload of the cast operator (int64_t cast)
* @return the cast Sint to int64_t */
explicit operator int64_t() const;
};
#endif | 41.455696 | 80 | 0.651756 | DrC0okie |
30f7a34e7ea9b1c8998252d21e081466ed32cd3c | 2,734 | cpp | C++ | examples/inclusivescan/apps/withmess/main.cpp | LouisCharlesC/mess | 4ecae6ff5cfc3313e4d30ca2681f75eb89705d7e | [
"MIT"
] | 22 | 2019-04-08T15:34:13.000Z | 2022-02-13T08:26:07.000Z | examples/inclusivescan/apps/withmess/main.cpp | LouisCharlesC/mess | 4ecae6ff5cfc3313e4d30ca2681f75eb89705d7e | [
"MIT"
] | null | null | null | examples/inclusivescan/apps/withmess/main.cpp | LouisCharlesC/mess | 4ecae6ff5cfc3313e4d30ca2681f75eb89705d7e | [
"MIT"
] | null | null | null | /**
* @file main.cpp
* @author L.-C. C.
* @brief
* @version 0.1
* @date 2020-02-06
*
* @copyright Copyright (c) 2020
*
*/
#include <checker.h>
#include <scanner.h>
#include <source.h>
#include <mess/mess.h>
#include <cassert>
#include <chrono>
#include <cstddef>
#include <iostream>
#include <iterator>
#include <vector>
struct Source:
mess::IsALocalVariable
{};
struct DataSize:
mess::IsALocalVariable
{};
struct OriginalData:
mess::IsTheResultOfCalling<&ex::Source::get>,
mess::OnInstance<Source>,
mess::WithArgument<DataSize>
{};
struct ScannedData:
mess::IsALocalVariable
{};
struct DoScan:
mess::IsTheResultOfALocalLambda,
mess::WithArguments<OriginalData, ScannedData>
{};
struct DoCheck:
mess::IsTheResultOfALocalLambda,
mess::WithArguments<ScannedData, OriginalData>
// mess::WhenAll<DoScan>
{};
int main(int, char const *[])
{
auto doScan =
[]
(const auto& original, auto& scanned)
{
std::partial_sum(original.begin(), original.end(), scanned.begin());
};
auto doCheck =
[]
(const auto& scanned, const auto& original)
{
return ex::check(scanned.cbegin(), scanned.cend(), original.begin());
};
constexpr std::size_t size = 1<<17;
constexpr std::size_t maxSize = size;
static_assert(size<=maxSize, "");
static ex::Source source(maxSize);
static std::vector<int> scanned(maxSize);
bool check = true;
constexpr std::size_t NumberOfIterationsToRun = 1000;
std::chrono::duration<double, std::milli> scanTime = std::chrono::duration<double, std::milli>::zero();
const auto beforeAll = std::chrono::high_resolution_clock::now();
for (std::size_t i = 0; i < NumberOfIterationsToRun; ++i)
{
// Get some data
const auto original = mess::pull<OriginalData>(mess::push<Source>(source), mess::push<DataSize>(size));
// Perform and time computation
const auto beforeScan = std::chrono::high_resolution_clock::now();
mess::pull<DoScan>(mess::push<DoScan>(doScan), mess::push<OriginalData>(original), mess::push<ScannedData>(scanned));
scanTime += std::chrono::duration<double, std::milli>(std::chrono::high_resolution_clock::now()-beforeScan)/NumberOfIterationsToRun;
// Perform dependent computations
check &= mess::pull<DoCheck>(mess::push<DoCheck>(doCheck), mess::push<OriginalData>(original), mess::push<ScannedData>(scanned));
assert(check);
}
const std::chrono::duration<double, std::milli> totalTime = (std::chrono::high_resolution_clock::now()-beforeAll) / NumberOfIterationsToRun;
std::cout << "Scan was correct: " << std::boolalpha << check << std::endl << std::endl;
std::cout << "Mean scan time: " << scanTime.count() << " ms" << std::endl;
std::cout << "Mean total time: " << totalTime.count() << " ms" << std::endl;
return 0;
}
| 27.897959 | 141 | 0.694587 | LouisCharlesC |
30f7f8444719827755239028f97ea1848831bba4 | 2,632 | cpp | C++ | tools/vsimporter/src/PBX/XCConfigurationList.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | 1 | 2016-02-08T02:29:19.000Z | 2016-02-08T02:29:19.000Z | tools/vsimporter/src/PBX/XCConfigurationList.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | tools/vsimporter/src/PBX/XCConfigurationList.cpp | Art52123103/WinObjC | 5672d1c99851b6125514381c39f4243692514b0b | [
"MIT"
] | null | null | null | //******************************************************************************
//
// Copyright (c) 2015 Microsoft Corporation. All rights reserved.
//
// This code is licensed under the MIT License (MIT).
//
// 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 "PlistFuncs.h"
#include "SBLog.h"
#include "XCConfigurationList.h"
#include "XCBuildConfiguration.h"
#include "PBXObjectIdConvert.h"
XCConfigurationList::~XCConfigurationList() {}
XCConfigurationList::XCConfigurationList() {}
XCConfigurationList* XCConfigurationList::createFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc)
{
XCConfigurationList* ret = new XCConfigurationList;
ret->initFromPlist(id, plist, pbxDoc);
return ret;
}
void XCConfigurationList::initFromPlist(const String& id, const Plist::dictionary_type& plist, const PBXDocument* pbxDoc)
{
// Call super init
PBXObject::initFromPlist(id, plist, pbxDoc);
// Get buildConfigurations
getStringVectorForKey(plist, "buildConfigurations", m_buildConfigurationIds, VALUE_REQUIRED, m_parseER);
// Get defaultConfigurationName
getStringForKey(plist, "defaultConfigurationName", m_defaultConfigurationName, VALUE_REQUIRED, m_parseER);
}
void XCConfigurationList::resolvePointers()
{
// Resolve buildConfigurations ptrs
convertObjectIdList(m_pbxDoc, m_buildConfigurationIds, m_buildConfigurationPtrs);
}
const XCBuildConfiguration* XCConfigurationList::getConfiguration(const String& configName) const
{
for (unsigned i = 0; i < m_buildConfigurationPtrs.size(); i++) {
if (m_buildConfigurationPtrs[i]->getName() == configName)
return m_buildConfigurationPtrs[i];
}
SBLog::warning() << "Failed to find \"" << configName << "\" build configuration in \"" << m_pbxDoc->getName() << "\" project." << std::endl;
return NULL;
}
void XCConfigurationList::getConfigurations(const StringSet& configNames, BuildConfigurationList& ret) const
{
for (auto configName : configNames) {
const XCBuildConfiguration* config = getConfiguration(configName);
if (config)
ret.push_back(config);
}
} | 37.6 | 143 | 0.713146 | Art52123103 |
30fcb8b653eedd9869c3fce02ab2ea28bfe5deca | 4,805 | cpp | C++ | trajectory_planner/src/trajectory_planner_nodelet_aux.cpp | ricardolfsilva/trajectory_planner | 0840d74921feb79569de67a765c7d3c011ff8868 | [
"MIT"
] | 1 | 2021-09-25T15:05:04.000Z | 2021-09-25T15:05:04.000Z | trajectory_planner/src/trajectory_planner_nodelet_aux.cpp | ricardolfsilva/trajectory_planner | 0840d74921feb79569de67a765c7d3c011ff8868 | [
"MIT"
] | null | null | null | trajectory_planner/src/trajectory_planner_nodelet_aux.cpp | ricardolfsilva/trajectory_planner | 0840d74921feb79569de67a765c7d3c011ff8868 | [
"MIT"
] | null | null | null | /**************************************************************************************************
Software License Agreement (BSD License)
Copyright (c) 2011-2013, LAR toolkit developers - University of Aveiro - http://lars.mec.ua.pt
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 Aveiro 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 HOLDER OR
CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
***************************************************************************************************/
#ifndef _trajectory_planner_nodelet_aux_CPP_
#define _trajectory_planner_nodelet_aux_CPP_
/**
* @file trajectory_executive.cpp
* @brief publishes a command message to follow a trajectory
* @author Joel Pereira
* @version v0
* @date 2012-05-25
*/
#include <trajectory_planner/trajectory_planner_nodelet.h>
void processFeedback(const visualization_msgs::InteractiveMarkerFeedbackConstPtr &feedback)
{
std::ostringstream s;
s << "Feedback from marker '" << feedback->marker_name << "' "
<< " / control '" << feedback->control_name << "'";
std::ostringstream mouse_point_ss;
if (feedback->mouse_point_valid)
{
mouse_point_ss << " at " << feedback->mouse_point.x << ", " << feedback->mouse_point.y << ", "
<< feedback->mouse_point.z << " in frame " << feedback->header.frame_id;
}
switch (feedback->event_type)
{
case visualization_msgs::InteractiveMarkerFeedback::POSE_UPDATE:
manage_vt->set_attractor_point(feedback->pose.position.x, feedback->pose.position.y,
2.0 * asin(feedback->pose.orientation.z));
break;
}
server->applyChanges();
}
Marker makeBox(InteractiveMarker &msg)
{
Marker marker;
marker.type = Marker::ARROW;
marker.scale.x = msg.scale;
marker.scale.y = msg.scale;
marker.scale.z = msg.scale;
marker.color.r = 0;
marker.color.g = 0.7;
marker.color.b = 0;
marker.color.a = 0.6;
return marker;
}
InteractiveMarkerControl &makeBoxControl(InteractiveMarker &msg)
{
InteractiveMarkerControl control;
control.always_visible = true;
control.markers.push_back(makeBox(msg));
msg.controls.push_back(control);
return msg.controls.back();
}
void make6DofMarker(bool fixed)
{
InteractiveMarker int_marker;
int_marker.header.frame_id = "/vehicle_odometry";
int_marker.pose.position.x = 5;
int_marker.pose.position.y = 0;
int_marker.pose.position.z = 0;
int_marker.scale = 0.4;
int_marker.name = "Control target";
int_marker.description = "Control the final \nposition of the robot";
// insert a box
makeBoxControl(int_marker);
InteractiveMarkerControl control;
control.orientation.w = 1;
control.orientation.x = 1;
control.orientation.y = 0;
control.orientation.z = 0;
control.name = "move_x";
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
int_marker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 0;
control.orientation.z = 1;
control.name = "move_y";
control.interaction_mode = InteractiveMarkerControl::MOVE_AXIS;
int_marker.controls.push_back(control);
control.orientation.w = 1;
control.orientation.x = 0;
control.orientation.y = 1;
control.orientation.z = 0;
control.interaction_mode = InteractiveMarkerControl::ROTATE_AXIS;
control.name = "rotate_z";
int_marker.controls.push_back(control);
server->insert(int_marker);
server->setCallback(int_marker.name, &processFeedback);
}
#endif
| 35.858209 | 100 | 0.713424 | ricardolfsilva |
30fdfdc570d46c64ac40f7438577bcbdd2f94584 | 612 | cpp | C++ | sources/laba06-5.cpp | aleksandrbezzubenko/Sort_set | 2c57005ae5662f3e1e83a8101dd7740235cabd40 | [
"MIT"
] | null | null | null | sources/laba06-5.cpp | aleksandrbezzubenko/Sort_set | 2c57005ae5662f3e1e83a8101dd7740235cabd40 | [
"MIT"
] | null | null | null | sources/laba06-5.cpp | aleksandrbezzubenko/Sort_set | 2c57005ae5662f3e1e83a8101dd7740235cabd40 | [
"MIT"
] | null | null | null | // Copyright 2018 Your Name <your_email>
#include <iostream>
#include <vector>
#include <string>
#include "header.hpp"
#include "student.hpp"
std::vector<Student> VectorMathExcellent(const std::vector<Student>& studmath)
{
std::vector<Student> math5 = {};
for (int i = 0; i < studmath.size(); ++i) {
int l = 0;
for (int j = 0; j < studmath[i].Subjects.size(); ++j) {
if (studmath[i].Subjects[j] == "Math") {
l = j;
}
}
if (studmath[i].Ratings[l] == 5) {
math5.push_back(studmath[i]);
}
}
return math5;
}
| 26.608696 | 78 | 0.535948 | aleksandrbezzubenko |
a509f63d0cc3daeb84d705f9fb7b2e7f6d8d0804 | 11,261 | cpp | C++ | src/kernel.cpp | v-dobrev/occa | 58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c | [
"MIT"
] | null | null | null | src/kernel.cpp | v-dobrev/occa | 58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c | [
"MIT"
] | null | null | null | src/kernel.cpp | v-dobrev/occa | 58e47f5ccf0d87f5b91e6851b2d74a9456c46b2c | [
"MIT"
] | null | null | null | /* The MIT License (MIT)
*
* Copyright (c) 2014-2018 David Medina and Tim Warburton
*
* 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
*/
#include <occa/kernel.hpp>
#include <occa/device.hpp>
#include <occa/memory.hpp>
#include <occa/uva.hpp>
#include <occa/io.hpp>
#include <occa/tools/sys.hpp>
#include <occa/lang/parser.hpp>
#include <occa/lang/builtins/types.hpp>
#include <occa/lang/builtins/transforms/finders.hpp>
namespace occa {
//---[ modeKernel_t ]---------------------
modeKernel_t::modeKernel_t(modeDevice_t *modeDevice_,
const std::string &name_,
const std::string &sourceFilename_,
const occa::properties &properties_) :
modeDevice(modeDevice_),
name(name_),
sourceFilename(sourceFilename_),
properties(properties_) {
modeDevice->addKernelRef(this);
}
modeKernel_t::~modeKernel_t() {
// NULL all wrappers
kernel *head = (kernel*) kernelRing.head;
if (head) {
kernel *ptr = head;
do {
kernel *nextPtr = (kernel*) ptr->rightRingEntry;
ptr->modeKernel = NULL;
ptr->removeRef();
ptr = nextPtr;
} while (ptr != head);
}
// Remove ref from device
if (modeDevice) {
modeDevice->removeKernelRef(this);
}
}
void modeKernel_t::dontUseRefs() {
kernelRing.dontUseRefs();
}
void modeKernel_t::addKernelRef(kernel *ker) {
kernelRing.addRef(ker);
}
void modeKernel_t::removeKernelRef(kernel *ker) {
kernelRing.removeRef(ker);
}
bool modeKernel_t::needsFree() const {
return kernelRing.needsFree();
}
kernelArg* modeKernel_t::argumentsPtr() {
return &(arguments[0]);
}
int modeKernel_t::argumentCount() {
return (int) arguments.size();
}
//====================================
//---[ kernel ]-----------------------
kernel::kernel() :
modeKernel(NULL) {}
kernel::kernel(modeKernel_t *modeKernel_) :
modeKernel(NULL) {
setModeKernel(modeKernel_);
}
kernel::kernel(const kernel &k) :
modeKernel(NULL) {
setModeKernel(k.modeKernel);
}
kernel& kernel::operator = (const kernel &k) {
setModeKernel(k.modeKernel);
return *this;
}
kernel& kernel::operator = (modeKernel_t *modeKernel_) {
setModeKernel(modeKernel_);
return *this;
}
kernel::~kernel() {
removeKernelRef();
}
void kernel::assertInitialized() const {
OCCA_ERROR("Kernel not initialized or has been freed",
modeKernel != NULL);
}
void kernel::setModeKernel(modeKernel_t *modeKernel_) {
if (modeKernel != modeKernel_) {
removeKernelRef();
modeKernel = modeKernel_;
if (modeKernel) {
modeKernel->addKernelRef(this);
}
}
}
void kernel::removeKernelRef() {
if (!modeKernel) {
return;
}
modeKernel->removeKernelRef(this);
if (modeKernel->modeKernel_t::needsFree()) {
free();
}
}
void kernel::dontUseRefs() {
if (modeKernel) {
modeKernel->modeKernel_t::dontUseRefs();
}
}
bool kernel::isInitialized() {
return (modeKernel != NULL);
}
const std::string& kernel::mode() const {
static const std::string noMode = "No Mode";
return (modeKernel
? modeKernel->modeDevice->mode
: noMode);
}
const occa::properties& kernel::properties() const {
static const occa::properties noProperties;
return (modeKernel
? modeKernel->properties
: noProperties);
}
modeKernel_t* kernel::getModeKernel() {
return modeKernel;
}
occa::device kernel::getDevice() {
return occa::device(modeKernel
? modeKernel->modeDevice
: NULL);
}
bool kernel::operator == (const occa::kernel &other) const {
return (modeKernel == other.modeKernel);
}
bool kernel::operator != (const occa::kernel &other) const {
return (modeKernel != other.modeKernel);
}
const std::string& kernel::name() {
static const std::string noName = "";
return (modeKernel
? modeKernel->name
: noName);
}
const std::string& kernel::sourceFilename() {
static const std::string noSourceFilename = "";
return (modeKernel
? modeKernel->sourceFilename
: noSourceFilename);
}
const std::string& kernel::binaryFilename() {
static const std::string noBinaryFilename = "";
return (modeKernel
? modeKernel->binaryFilename
: noBinaryFilename);
}
void kernel::setRunDims(occa::dim outerDims, occa::dim innerDims) {
if (modeKernel) {
modeKernel->innerDims = innerDims;
modeKernel->outerDims = outerDims;
}
}
int kernel::maxDims() {
return (modeKernel
? modeKernel->maxDims()
: -1);
}
dim kernel::maxOuterDims() {
return (modeKernel
? modeKernel->maxOuterDims()
: dim(-1, -1, -1));
}
dim kernel::maxInnerDims() {
return (modeKernel
? modeKernel->maxInnerDims()
: dim(-1, -1, -1));
}
void kernel::addArgument(const int argPos, const kernelArg &arg) {
assertInitialized();
if (modeKernel->argumentCount() <= argPos) {
OCCA_ERROR("Kernels can only have at most [" << OCCA_MAX_ARGS << "] arguments,"
<< " [" << argPos << "] arguments were set",
argPos < OCCA_MAX_ARGS);
modeKernel->arguments.resize(argPos + 1);
}
modeKernel->arguments[argPos] = arg;
}
void kernel::run() const {
assertInitialized();
const int argc = (int) modeKernel->arguments.size();
for (int i = 0; i < argc; ++i) {
const bool argIsConst = modeKernel->metadata.argIsConst(i);
modeKernel->arguments[i].setupForKernelCall(argIsConst);
}
modeKernel->run();
}
void kernel::clearArgumentList() {
if (modeKernel) {
modeKernel->arguments.clear();
}
}
#include "kernelOperators.cpp"
void kernel::free() {
if (modeKernel == NULL) {
return;
}
modeKernel->free();
// ~modeKernel_t NULLs all wrappers
delete modeKernel;
}
//====================================
//---[ kernelBuilder ]----------------
kernelBuilder::kernelBuilder() {}
kernelBuilder::kernelBuilder(const kernelBuilder &k) :
source_(k.source_),
function_(k.function_),
props_(k.props_),
kernelMap(k.kernelMap),
buildingFromFile(k.buildingFromFile) {}
kernelBuilder& kernelBuilder::operator = (const kernelBuilder &k) {
source_ = k.source_;
function_ = k.function_;
props_ = k.props_;
kernelMap = k.kernelMap;
buildingFromFile = k.buildingFromFile;
return *this;
}
kernelBuilder kernelBuilder::fromFile(const std::string &filename,
const std::string &function,
const occa::properties &props) {
kernelBuilder builder;
builder.source_ = filename;
builder.function_ = function;
builder.props_ = props;
builder.buildingFromFile = true;
return builder;
}
kernelBuilder kernelBuilder::fromString(const std::string &content,
const std::string &function,
const occa::properties &props) {
kernelBuilder builder;
builder.source_ = content;
builder.function_ = function;
builder.props_ = props;
builder.buildingFromFile = false;
return builder;
}
bool kernelBuilder::isInitialized() {
return (0 < function_.size());
}
occa::kernel kernelBuilder::build(occa::device device) {
return build(device, hash(device), props_);
}
occa::kernel kernelBuilder::build(occa::device device,
const occa::properties &props) {
occa::properties kernelProps = props_;
kernelProps += props;
return build(device,
hash(device) ^ hash(kernelProps),
kernelProps);
}
occa::kernel kernelBuilder::build(occa::device device,
const hash_t &hash) {
return build(device, hash, props_);
}
occa::kernel kernelBuilder::build(occa::device device,
const hash_t &hash,
const occa::properties &props) {
occa::kernel &k = kernelMap[hash];
if (!k.isInitialized()) {
if (buildingFromFile) {
k = device.buildKernel(source_, function_, props);
} else {
k = device.buildKernelFromString(source_, function_, props);
}
}
return k;
}
occa::kernel kernelBuilder::operator [] (occa::device device) {
return build(device,
hash(device));
}
void kernelBuilder::free() {
hashedKernelMapIterator it = kernelMap.begin();
while (it != kernelMap.end()) {
it->second.free();
++it;
}
}
//====================================
//---[ Kernel Properties ]------------
// defines : Object
// includes : Array
// header : Array
// include_paths : Array
std::string assembleHeader(const occa::properties &props) {
std::string header;
// Add defines
const jsonObject &defines = props["defines"].object();
jsonObject::const_iterator it = defines.begin();
while (it != defines.end()) {
header += "#define ";
header += ' ';
header += it->first;
header += ' ';
header += (std::string) it->second;
header += '\n';
++it;
}
// Add includes
const jsonArray &includes = props["includes"].array();
const int includeCount = (int) includes.size();
for (int i = 0; i < includeCount; ++i) {
if (includes[i].isString()) {
header += "#include \"";
header += (std::string) includes[i];
header += "\"\n";
}
}
// Add header
const jsonArray &lines = props["header"].array();
const int lineCount = (int) lines.size();
for (int i = 0; i < lineCount; ++i) {
if (includes[i].isString()) {
header += (std::string) lines[i];
header += "\n";
}
}
return header;
}
//====================================
}
| 27.266344 | 85 | 0.593375 | v-dobrev |
a50b360c877ccb2bcd385ecdc9dfa0f6a4991d86 | 3,140 | cpp | C++ | src/Soldier.cpp | sunverwerth/olcjamj2020 | cefb7cc4d586cac50653e4073e67d0954071ee46 | [
"MIT"
] | 4 | 2020-09-27T11:46:14.000Z | 2022-01-08T19:08:06.000Z | src/Soldier.cpp | sunverwerth/olcjam2020 | cefb7cc4d586cac50653e4073e67d0954071ee46 | [
"MIT"
] | null | null | null | src/Soldier.cpp | sunverwerth/olcjam2020 | cefb7cc4d586cac50653e4073e67d0954071ee46 | [
"MIT"
] | null | null | null | /*
Copyright(c) 2020 Stephan Unverwerth
Permission is hereby granted, free of charge, to any person obtaining a copy
of this softwareand 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 noticeand 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 "Soldier.h"
#include "utils.h"
#include "globals.h"
#include "Game.h"
#include "Gfx.h"
#include "Sfx.h"
#include "AudioClip.h"
Sprite Soldier::sprites[6];
void Soldier::findTarget(Game& game) {
target = nullptr;
float distance = 9999999999;
for (auto unit : game.getUnits()) {
if ((unit->isComputeCore() || unit->isWall() || unit->isDroneDeployer() || unit->isSiliconRefinery()) && (!target || ((unit->pos - pos).squaredLength() < distance))) {
target = unit;
distance = (unit->pos - pos).squaredLength();
}
}
}
void Soldier::update(float dt, Game& game, Sfx& sfx) {
time += dt;
if (time > 1) time = 0;
shoottime -= dt;
switch (state) {
case STAND:
findTarget(game);
if (target) state = RUN;
break;
case RUN:
if (!target->isAlive()) {
target = nullptr;
state = STAND;
break;
}
auto tpos = target->pos + Vec2(16, 16);
auto vel = (tpos - pos).normalized() * 10;
mirrored = vel.x > 0;
auto newpos = pos + vel * dt;
pos = newpos;
if ((tpos - pos).length() < 32) state = SHOOT;
break;
case SHOOT:
if (!target->isAlive()) {
target = nullptr;
state = STAND;
break;
}
if (shoottime < 0) {
if (grenadier) {
game.spawnGrenade(pos, target->pos + Vec2(16, 16), Faction::CPU);
shoottime = frand(2, 4);
}
else {
target->damage(damage_bullet, Faction::CPU);
sfx.play(sfx.getAudioClip("media/sounds/gun_burst.wav", 2), 0.5f, 0.0f, frand(0.9, 1.1));
shoottime = frand(1, 3);
}
}
break;
}
}
void Soldier::draw_bottom(Gfx& gfx) {
int frame = 0;
switch (state) {
case STAND: frame = 5; break;
case RUN: frame = int(time * 8) % 4; break;
case SHOOT: frame = shoottime < 0.5f ? 4 + int(time * 16) % 2 : 5; break;
}
gfx.drawSprite(sprites[frame], pos + Vec2(-5, -4) - floor(cameraPosition), Vec4::WHITE, mirrored);
}
void Soldier::damage(int amount, Faction originator) {
if (originator == Faction::CPU) return;
health -= amount;
if (health <= 0) alive = false;
}
| 30.485437 | 170 | 0.658917 | sunverwerth |
a510507e881367d066522d09f575b6664d99df68 | 1,091 | cpp | C++ | test/assert/optional_error.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 13 | 2015-02-21T18:35:14.000Z | 2019-12-29T14:08:29.000Z | test/assert/optional_error.cpp | cpreh/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 5 | 2016-08-27T07:35:47.000Z | 2019-04-21T10:55:34.000Z | test/assert/optional_error.cpp | freundlich/fcppt | 17df1b1ad08bf2435f6902d5465e3bc3fe5e3022 | [
"BSL-1.0"
] | 8 | 2015-01-10T09:22:37.000Z | 2019-12-01T08:31:12.000Z | // Copyright Carl Philipp Reh 2009 - 2021.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <fcppt/assert/optional_error.hpp>
#include <fcppt/catch/begin.hpp>
#include <fcppt/catch/end.hpp>
#include <fcppt/catch/movable.hpp>
#include <fcppt/optional/object_impl.hpp>
#include <fcppt/config/external_begin.hpp>
#include <catch2/catch.hpp>
#include <fcppt/config/external_end.hpp>
FCPPT_CATCH_BEGIN
TEST_CASE("assert_optional_error", "[assert]")
{
using optional_int = fcppt::optional::object<int>;
using int_movable = fcppt::catch_::movable<int>;
using optional_int_movable = fcppt::optional::object<int_movable>;
CHECK(FCPPT_ASSERT_OPTIONAL_ERROR(optional_int{42}) == 42);
CHECK(FCPPT_ASSERT_OPTIONAL_ERROR(optional_int_movable{int_movable{10}}).value() == 10);
{
optional_int_movable const opt{int_movable{42}};
int_movable const &ref{FCPPT_ASSERT_OPTIONAL_ERROR(opt)};
CHECK(ref.value() == 42);
}
}
FCPPT_CATCH_END
| 27.974359 | 90 | 0.738772 | freundlich |
a51140fffe69b0aa80f263e22aa044e3291bded0 | 1,104 | cpp | C++ | CSCommon/Source/MPacketHShieldCrypter.cpp | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | CSCommon/Source/MPacketHShieldCrypter.cpp | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | CSCommon/Source/MPacketHShieldCrypter.cpp | WhyWolfie/source2007 | 324257e9c69bbaec872ebb7ae4f96ab2ce98f520 | [
"FSFAP"
] | null | null | null | #include "stdafx.h"
#include "MPacketHShieldCrypter.h"
HSCRYPT_KEYINFO MPacketHShieldCrypter::m_HsKeyInfo;
unsigned char MPacketHShieldCrypter::m_OutputBuf[MAX_PACKET_SIZE];
MPacketHShieldCrypter::MPacketHShieldCrypter(void)
{
}
MPacketHShieldCrypter::~MPacketHShieldCrypter(void)
{
}
DWORD MPacketHShieldCrypter::Init()
{
memcpy(m_HsKeyInfo.byInitKey, "_9+a4%b7&d2$p1q", HSCRYPTLIB_INITKEY_SIZE);
return _HsCrypt_InitCrypt(&m_HsKeyInfo);
}
DWORD MPacketHShieldCrypter::Encrypt(PBYTE pbyInput, UINT nInLength)
{
DWORD ret = _HsCrypt_GetEncMsg(pbyInput, nInLength, m_HsKeyInfo.AesEncKey, m_OutputBuf, nInLength);
CopyMemory(pbyInput, m_OutputBuf, nInLength);
return ret;
}
DWORD MPacketHShieldCrypter::Decrypt(PBYTE pbyInput, UINT nInLength)
{
DWORD ret = _HsCrypt_GetDecMsg(pbyInput, nInLength, m_HsKeyInfo.AesDecKey, m_OutputBuf, nInLength);
CopyMemory(pbyInput, m_OutputBuf, nInLength);
return ret;
}
DWORD MPacketHShieldCrypter::Decrypt(PBYTE pbyInput, UINT nInLength, PBYTE pbyOutput)
{
return _HsCrypt_GetDecMsg(pbyInput, nInLength, m_HsKeyInfo.AesDecKey, pbyOutput, nInLength);
}
| 26.926829 | 100 | 0.811594 | WhyWolfie |
a5138000b24c1e3673b5dadd61be606caa1c8b1a | 3,229 | cpp | C++ | cobs/file/classic_index_header.cpp | danielf-93/cobs | 56157f93f4564f5ef2c5f62401a2e75a6994687f | [
"MIT"
] | 5 | 2019-02-21T10:42:44.000Z | 2020-01-29T01:56:00.000Z | cobs/file/classic_index_header.cpp | danielf-93/cobs | 56157f93f4564f5ef2c5f62401a2e75a6994687f | [
"MIT"
] | null | null | null | cobs/file/classic_index_header.cpp | danielf-93/cobs | 56157f93f4564f5ef2c5f62401a2e75a6994687f | [
"MIT"
] | 2 | 2019-02-10T21:35:06.000Z | 2019-07-14T01:46:09.000Z | /*******************************************************************************
* cobs/file/classic_index_header.cpp
*
* Copyright (c) 2018 Florian Gauger
*
* All rights reserved. Published under the MIT License in the LICENSE file.
******************************************************************************/
#include <cobs/file/classic_index_header.hpp>
#include <cobs/util/file.hpp>
namespace cobs::file {
const std::string classic_index_header::magic_word = "CLASSIC_INDEX";
const std::string classic_index_header::file_extension = ".cla_idx.isi";
void classic_index_header::serialize(std::ofstream& ofs) const {
cobs::serialize(ofs, (uint32_t)m_file_names.size(), m_signature_size, m_num_hashes);
for (const auto& file_name : m_file_names) {
ofs << file_name << std::endl;
}
}
void classic_index_header::deserialize(std::ifstream& ifs) {
uint32_t file_names_size;
cobs::deserialize(ifs, file_names_size, m_signature_size, m_num_hashes);
m_file_names.resize(file_names_size);
for (auto& file_name : m_file_names) {
std::getline(ifs, file_name);
}
}
classic_index_header::classic_index_header(uint64_t signature_size, uint64_t num_hashes, const std::vector<std::string>& file_names)
: m_signature_size(signature_size), m_num_hashes(num_hashes), m_file_names(file_names) { }
uint64_t classic_index_header::signature_size() const {
return m_signature_size;
}
uint64_t classic_index_header::block_size() const {
return (m_file_names.size() + 7) / 8;
}
uint64_t classic_index_header::num_hashes() const {
return m_num_hashes;
}
const std::vector<std::string>& classic_index_header::file_names() const {
return m_file_names;
}
std::vector<std::string>& classic_index_header::file_names() {
return m_file_names;
}
void classic_index_header::write_file(std::ofstream& ofs,
const std::vector<uint8_t>& data) {
ofs.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit);
header<classic_index_header>::serialize(ofs, *this);
ofs.write(reinterpret_cast<const char*>(data.data()), data.size());
}
void classic_index_header::write_file(const fs::path& p,
const std::vector<uint8_t>& data) {
if (!p.parent_path().empty())
fs::create_directories(p.parent_path());
std::ofstream ofs(p.string(), std::ios::out | std::ios::binary);
write_file(ofs, data);
}
void classic_index_header::read_file(std::ifstream& ifs,
std::vector<uint8_t>& data) {
ifs.exceptions(std::ios::eofbit | std::ios::failbit | std::ios::badbit);
header<classic_index_header>::deserialize(ifs, *this);
stream_metadata smd = get_stream_metadata(ifs);
size_t size = smd.end_pos - smd.curr_pos;
data.resize(size);
ifs.read(reinterpret_cast<char*>(data.data()), size);
}
void classic_index_header::read_file(const fs::path& p,
std::vector<uint8_t>& data) {
std::ifstream ifs(p.string(), std::ios::in | std::ios::binary);
read_file(ifs, data);
}
} // namespace cobs::file
/******************************************************************************/
| 35.877778 | 132 | 0.632704 | danielf-93 |
a51551a1da25a001349d4466de4dc5c6557a12cc | 3,000 | hpp | C++ | include/nmp/concepts.hpp | gnzlbg/nmp | a3c1f286abfabaa043f47ea61ab052c54901be2b | [
"BSL-1.0"
] | 21 | 2015-11-24T16:32:35.000Z | 2020-11-24T13:20:06.000Z | include/nmp/concepts.hpp | gnzlbg/nmp | a3c1f286abfabaa043f47ea61ab052c54901be2b | [
"BSL-1.0"
] | null | null | null | include/nmp/concepts.hpp | gnzlbg/nmp | a3c1f286abfabaa043f47ea61ab052c54901be2b | [
"BSL-1.0"
] | 3 | 2017-08-25T15:42:53.000Z | 2019-10-21T06:36:14.000Z | #pragma once
////////////////////////////////////////////////////////////////////////////////
// Copyright (C) 2014 Gonzalo Brito Gadeschi.
//
// Use, modification and distribution is subject to the Boost Software
// License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
////////////////////////////////////////////////////////////////////////////////
/// \file concepts.hpp
///
/// Implements NMP concepts
////////////////////////////////////////////////////////////////////////////////
#include <type_traits>
#include <nmp/data_type/pointer.hpp>
#include <nmp/data_type/map.hpp>
#include <nmp/data_type/size.hpp>
#include <nmp/data_type/unit_of_size.hpp>
#include <nmp/detail/utilities.hpp>
////////////////////////////////////////////////////////////////////////////////
namespace nmp {
namespace concepts {
using ::nmp::data_ptr;
/// A message M, has:
/// - a unit of size U,
/// - a size (in U units), and
/// - a pointer to its data (of type U* or U const*)
///
/// \note if U is void, then the message size is in the unit char (bytes).
///
/// \note The unit of size is obtained from the trait unit_of_size_t<M>
/// \note The trait has_size_t is defined from the non-member function
/// size(M)
/// \note The trait has_data_t is defined from the non-member function
/// data(M)
///
template <class M> struct message {
template <class U> static auto test(U&&, long) -> std::false_type;
template <class U,
NMP_REQUIRES_(
has_size_t<M>{}&& has_data_ptr_t<M>{}&& has_unit_t<M>{} //&&
// std::is_same<decltype(data_ptr(std::declval<M>())),
// std::add_pointer_t<unit_of_size_t<M>>>{}
)>
static auto test(U&&, int) -> std::true_type;
using type = decltype(test(std::declval<M>(), 42));
using unit = unit_of_size_t<M>;
};
} // namespace concepts
namespace models {
template <class M> struct message : ::nmp::concepts::message<M>::type {};
} // namespace models
namespace concepts {
/// A target T of message M, has:
/// - the same unit of size M,
/// - a _writable_ pointer to its data.
template <class T, class M> struct target {
template <class T_, class M_>
static auto test(T_&&, M_&&, long) -> std::false_type;
template <class T_, class M_,
NMP_REQUIRES_(
models::message<T_>{}&&
// is writable if pointer type after removing
// reference is equal
std::is_same<data_ptr_t<T_>, std::remove_cv_t<data_ptr_t<T_>>>{}&&
std::is_same<unit_of_size_t<M_>, unit_of_size_t<T_>>{})>
static auto test(T_&&, M_&&, int) -> std::true_type;
using type = decltype(test(std::declval<T>(), std::declval<M>(), 42));
};
} // namespace concepts
namespace models {
template <class T, class M>
struct target : ::nmp::concepts::target<T, M>::type {};
} // namespace models
} // namespace nmp
////////////////////////////////////////////////////////////////////////////////
| 31.25 | 80 | 0.557 | gnzlbg |
a5157e45c8bfe77eb04abbcd9dd4997c3377849e | 2,309 | cpp | C++ | source/direct3d9/EffectDefault.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 85 | 2015-04-06T05:37:10.000Z | 2022-03-22T19:53:03.000Z | source/direct3d9/EffectDefault.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 10 | 2016-03-17T11:18:24.000Z | 2021-05-11T09:21:43.000Z | source/direct3d9/EffectDefault.cpp | HeavenWu/slimdx | e014bb34b89bbf694d01c8f6d6b6dfa3cba58aac | [
"MIT"
] | 45 | 2015-09-14T03:54:01.000Z | 2022-03-22T19:53:09.000Z | #include "stdafx.h"
/*
* Copyright (c) 2007-2012 SlimDX Group
*
* 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 <d3d9.h>
#include <d3dx9.h>
#include "../DataStream.h"
#include "EffectDefault.h"
using namespace System;
namespace SlimDX
{
namespace Direct3D9
{
bool EffectDefault::operator == ( EffectDefault left, EffectDefault right )
{
return EffectDefault::Equals( left, right );
}
bool EffectDefault::operator != ( EffectDefault left, EffectDefault right )
{
return !EffectDefault::Equals( left, right );
}
int EffectDefault::GetHashCode()
{
return ParameterName->GetHashCode() + Type.GetHashCode() + Value->GetHashCode();
}
bool EffectDefault::Equals( Object^ value )
{
if( value == nullptr )
return false;
if( value->GetType() != GetType() )
return false;
return Equals( safe_cast<EffectDefault>( value ) );
}
bool EffectDefault::Equals( EffectDefault value )
{
return ( ParameterName == value.ParameterName && Type == value.Type && Value == value.Value );
}
bool EffectDefault::Equals( EffectDefault% value1, EffectDefault% value2 )
{
return ( value1.ParameterName == value2.ParameterName && value1.Type == value2.Type && value1.Value == value2.Value );
}
}
} | 32.069444 | 121 | 0.71243 | HeavenWu |
a51eb91f0a613879611dbdb39f9f0bb382c780ee | 20,182 | cpp | C++ | src/Engine/CameraSystem.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Engine/CameraSystem.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | src/Engine/CameraSystem.cpp | fgagamedev/voID | 37cd56fe2878d036c36dafcf595e48ed85408d02 | [
"MIT"
] | null | null | null | /*
@file CameraSystem.cpp
@brief Class that manages the game image,
including the scenes the zoom and speed that the screen moves.
@copyright LGPL. MIT License.
*/
#include "Engine/CameraSystem.hpp"
#include "Customs/MapScript.hpp"
CameraSystem *CameraSystem::m_instance = nullptr;
/*
@brief Sets the camera's default speed.
*/
CameraSystem::CameraSystem() {
this->m_cameraSpeed = 32;
}
/*
@brief Guides the camera to accompany the character when moving up.
@param[in] speed Stores the character's current speed.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::MoveUp(int speed, Scene *scene) {
// Check if is diferent of scene and return.
if (!scene) {
return;
}
// Get all scene game objects.
m_gameObjects = scene->GetAllGameObjects();
if (m_gameObjects.empty()) {
return;
}
// Move all scene objects.
for (auto it = m_gameObjects.begin(); it != m_gameObjects.end(); it++) {
(*it)->SetPosition(Vector((*it)->GetPosition()->m_x, (*it)->GetPosition()->m_y + speed));
}
auto mapscript = (MapScript*)SceneManager::GetInstance()
->GetScene("Gameplay")
->GetGameObject("Map")
->GetComponent("MapScript");
if (mapscript) {
for (int i = 0; i < mapscript->leftWallsAmmount; i++) {
mapscript->leftWalls[i].m_y += speed;
}
for (int j = 0; j < mapscript->rightWallsAmmount; j++) {
mapscript->rightWalls[j].m_y += speed;
}
for (int k = 0; k < mapscript->upWallsAmmount; k++) {
mapscript->upWalls[k].m_y += speed;
}
for (int l = 0; l < mapscript->downWallsAmmount; l++) {
mapscript->downWalls[l].m_y += speed;
}
}
// Set a new position.
worldCameraY = worldCameraY - speed;
}
/*
@brief Guides the camera to accompany the character when moving down.
@param[in] speed Stores the character's current speed.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::MoveDown(int speed, Scene *scene) {
// Check if is diferent of scene and return.
if (!scene) {
return;
}
// Get the scene game objects.
m_gameObjects = scene->GetAllGameObjects();
if (m_gameObjects.empty()) {
return;
}
// Move all scene objects.
for (auto it = m_gameObjects.begin();it!=m_gameObjects.end();it++) {
(*it)->SetPosition(Vector((*it)->GetPosition()->m_x ,(*it)->GetPosition()->m_y - speed));
}
auto mapscript = (MapScript*)SceneManager::GetInstance()
->GetScene("Gameplay")
->GetGameObject("Map")
->GetComponent("MapScript");
if (mapscript) {
for (int i = 0; i < mapscript->leftWallsAmmount; i++) {
mapscript->leftWalls[i].m_y -= speed;
}
for (int j = 0; j < mapscript->rightWallsAmmount; j++) {
mapscript->rightWalls[j].m_y -= speed;
}
for (int k = 0; k < mapscript->upWallsAmmount; k++) {
mapscript->upWalls[k].m_y -= speed;
}
for (int l = 0; l < mapscript->downWallsAmmount; l++) {
mapscript->downWalls[l].m_y -= speed;
}
}
// Move the camera.
worldCameraY = worldCameraY + speed;
}
/*
@brief Guides the camera to accompany the character when moving left.
@param[in] speed Stores the character's current speed.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::MoveLeft(int speed,Scene *scene) {
// Check if is diferent of scene and return.
if (!scene) {
return;
}
// Get the scene game objects.
m_gameObjects = scene->GetAllGameObjects();
if (m_gameObjects.empty()) {
return;
}
// Move all scene objects.
for (auto it = m_gameObjects.begin();it != m_gameObjects.end(); it++) {
(*it)->SetPosition(Vector((*it)->GetPosition()->m_x + speed ,(*it)->GetPosition()->m_y ));
}
auto mapscript = (MapScript*)SceneManager::GetInstance()
->GetScene("Gameplay")
->GetGameObject("Map")
->GetComponent("MapScript");
// mapscript->target.x += speed;
if (mapscript) {
for (int i = 0; i < mapscript->leftWallsAmmount; i++) {
mapscript->leftWalls[i].m_x += speed;
}
for (int j = 0; j < mapscript->rightWallsAmmount; j++) {
mapscript->rightWalls[j].m_x += speed;
}
for (int k = 0; k < mapscript->upWallsAmmount; k++) {
mapscript->upWalls[k].m_x += speed;
}
for (int l = 0; l < mapscript->downWallsAmmount; l++) {
mapscript->downWalls[l].m_x += speed;
}
}
// Set new position camera.
worldCameraX = worldCameraX - speed;
}
/*
@brief Guides the camera to accompany the character when moving right.
@param[in] speed Stores the character's current speed.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::MoveRight(int speed, Scene *scene) {
// Check if is diferent of scene and return.
if(!scene) {
return;
}
// Get the scene game objects.
m_gameObjects = scene->GetAllGameObjects();
if (m_gameObjects.empty()) {
return;
}
// Move all scene objects.
for (auto it = m_gameObjects.begin(); it!=m_gameObjects.end(); it++) {
(*it)->SetPosition(Vector((*it)->GetPosition()->m_x - speed ,(*it)->GetPosition()->m_y));
}
auto mapscript = (MapScript*)SceneManager::GetInstance()
->GetScene("Gameplay")
->GetGameObject("Map")
->GetComponent("MapScript");
// mapscript->target.x-= speed;
if (mapscript) {
for (int i = 0; i < mapscript->leftWallsAmmount; i++) {
mapscript->leftWalls[i].m_x -= speed;
}
for (int j = 0; j < mapscript->rightWallsAmmount; j++) {
mapscript->rightWalls[j].m_x -= speed;
}
for (int k = 0; k < mapscript->upWallsAmmount; k++) {
mapscript->upWalls[k].m_x -= speed;
}
for (int l = 0; l < mapscript->downWallsAmmount; l++) {
mapscript->downWalls[l].m_x -= speed;
}
}
// Moves the camera.
worldCameraX = worldCameraX + speed;
}
/*
@brief Sets a camera shake to find the boss.
@param[in] intensity Stores the intensity of camera shake.
@param[in] duration Vibration duration in minutes.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::CameraShake(int intensity, float duration, Scene *scene) {
// Check if is diferent of scene and return.
if (!scene) {
return;
}
static int last = 0;
m_timer.Update(EngineGlobals::fixed_update_interval);
isShaking = true;
if (m_timer.GetTime() >= duration * 1000) {
isShaking = false;
m_timer.Restart();
return;
}
if (last == 0) {
MoveRight(intensity, scene);
MoveUp(intensity, scene);
last = 1;
} else if(last == 1) {
MoveLeft(intensity, scene);
MoveDown(intensity, scene);
last = 0;
}
}
/*
@brief Get a starting position in axis x on image.
@return worldCameraX Position initial in axis x.
*/
float CameraSystem::GetPositionX() {
return worldCameraX;
}
/*
@brief Get a starting position in axis y on image.
@return worldCameraY Position initial in axis y.
*/
float CameraSystem::GetPositionY() {
return worldCameraY;
}
/*
@brief Get a speed initial.
@return m_cameraSpeed Speed initial.
*/
int CameraSystem::GetCameraSpeed() {
return m_cameraSpeed;
}
/*
@brief Set a speed initial.
@param[in] speed Stores the character's current speed.
@return m_cameraSpeed Speed initial.
*/
void CameraSystem::SetCameraSpeed(int speed) {
m_cameraSpeed = speed;
}
/*
@brief Set a starting position in axis x on image.
@param[in] x Axis X of image.
*/
void CameraSystem::SetAndMovePos_x(float x) {
worldCameraX = x;
}
/*
@brief Set a starting position in axis x on image.
@param[in] y Axis Y of image.
*/
void CameraSystem::SetAndMovePos_y(float y) {
worldCameraY = y;
}
/*
@brief Reset a starting positions.
*/
void CameraSystem::Reset() {
worldCameraX = 0;
worldCameraY = 0;
}
/*
@brief Zooms to the screen.
@param[in] zoomSpeed Helps keep up with camera speed.
@param[in] objectToFollow Character of the game.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::ZoomIn(int zoomSpeed, GameObject *objectToFollow, Scene *scene) {
auto map = SceneManager::GetInstance()->GetScene("Gameplay")->
GetGameObject("Map");
if (!map) {
return;
}
m_beforePositionX = objectToFollow->GetPosition()->m_x;
m_beforePositionY = objectToFollow->GetPosition()->m_y;
this->m_cameraSpeed = zoomSpeed;
auto m_gameObjects = SceneManager::GetInstance()->GetCurrentScene()->
GetAllGameObjects();
for (auto it = m_gameObjects.begin(); it!=m_gameObjects.end(); it++) {
if ((*it)->GetName()!="Map") {
m_proportionX = 100*(((*it)->GetPosition()->m_x + worldCameraX) /
(map->GetWidth()));
m_proportionY = 100*(((*it)->GetPosition()->m_y + worldCameraY) /
(map->GetHeight()));
//if getzoomProportion==(0,0) the object wont be affected by the zoom
if ((*it)->GetZoomProportion()->m_x != 0, (*it)->GetZoomProportion()->m_y != 0) {
(*it)->SetSize(map->GetWidth() / (*it)->GetZoomProportion()->m_x, map->GetHeight() / (*it)->GetZoomProportion()->m_y);
(*it)->GetPosition()->m_x = ((m_proportionX/100) * (map->GetWidth() + zoomSpeed)) - worldCameraX;
(*it)->GetPosition()->m_y = ((m_proportionY/100) * (map->GetHeight() + zoomSpeed)) - worldCameraY;
}
}
}
auto mapscript = (MapScript*)SceneManager::GetInstance()
->GetScene("Gameplay")
->GetGameObject("Map")
->GetComponent("MapScript");
// mapscript->target.x-= speed;
if (mapscript) {
for (int i = 0; i < mapscript->leftWallsAmmount; i++) {
m_proportionX = 100 * ((mapscript->leftWalls[i].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->leftWalls[i].m_y + worldCameraY) / (map->GetHeight()));
mapscript->leftWalls[i].m_w = map->GetWidth()/((map->originalWidth/mapscript->leftWallsOriginal[i].m_w));//SHould be original
mapscript->leftWalls[i].m_h = map->GetHeight()/((map->originalHeight/mapscript->leftWallsOriginal[i].m_h));
mapscript->leftWalls[i].m_x = ((m_proportionX/100) * (map->GetWidth() + zoomSpeed)) - worldCameraX;
mapscript->leftWalls[i].m_y = ((m_proportionY/100) * (map->GetHeight() + zoomSpeed)) - worldCameraY;
}
for (int j = 0; j < mapscript->rightWallsAmmount; j++) {
m_proportionX = 100 * ((mapscript->rightWalls[j].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->rightWalls[j].m_y + worldCameraY) / (map->GetHeight()));
mapscript->rightWalls[j].m_w = map->GetWidth() / ((map->originalWidth/mapscript->rightWallsOriginal[j].m_w));//SHould be original
mapscript->rightWalls[j].m_h = map->GetHeight() / ((map->originalHeight/mapscript->rightWallsOriginal[j].m_h));
mapscript->rightWalls[j].m_x = ((m_proportionX/100) * (map->GetWidth() + zoomSpeed)) - worldCameraX;
mapscript->rightWalls[j].m_y = ((m_proportionY/100) * (map->GetHeight() + zoomSpeed)) - worldCameraY;
}
for (int k = 0; k < mapscript->upWallsAmmount; k++) {
m_proportionX = 100 * ((mapscript->upWalls[k].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->upWalls[k].m_y + worldCameraY) / (map->GetHeight()));
mapscript->upWalls[k].m_w = map->GetWidth() / ((map->originalWidth/mapscript->upWallsOriginal[k].m_w));//SHould be original
mapscript->upWalls[k].m_h = map->GetHeight() / ((map->originalHeight/mapscript->upWallsOriginal[k].m_h));
mapscript->upWalls[k].m_x = ((m_proportionX/100) * (map->GetWidth() + zoomSpeed)) - worldCameraX;
mapscript->upWalls[k].m_y = ((m_proportionY/100) * (map->GetHeight() + zoomSpeed)) - worldCameraY;
}
for (int l = 0; l < mapscript->downWallsAmmount; l++) {
m_proportionX = 100 * ((mapscript->downWalls[l].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->downWalls[l].m_y + worldCameraY) / (map->GetHeight()));
mapscript->downWalls[l].m_w = map->GetWidth() / ((map->originalWidth/mapscript->downWallsOriginal[l].m_w));//SHould be original
mapscript->downWalls[l].m_h = map->GetHeight() / ((map->originalHeight/mapscript->downWallsOriginal[l].m_h));
mapscript->downWalls[l].m_x = ((m_proportionX/100) * (map->GetWidth() + zoomSpeed)) - worldCameraX;
mapscript->downWalls[l].m_y = ((m_proportionY/100) * (map->GetHeight() + zoomSpeed)) - worldCameraY;
}
}
map->SetSize(map->GetWidth() + zoomSpeed, map->GetHeight() + zoomSpeed);
if (m_beforePositionX < objectToFollow->GetPosition()->m_x) {
MoveRight(objectToFollow->GetPosition()->m_x - m_beforePositionX,scene);
} else if (m_beforePositionX > objectToFollow->GetPosition()->m_x) {
MoveLeft(m_beforePositionX - objectToFollow->GetPosition()->m_x,scene);
}
if (m_beforePositionY < objectToFollow->GetPosition()->m_y) {
MoveDown(objectToFollow->GetPosition()->m_y - m_beforePositionY,scene);
} else if (m_beforePositionY > objectToFollow->GetPosition()->m_y) {
MoveDown(m_beforePositionY - objectToFollow->GetPosition()->m_y,scene);
}
}
/*
@brief Zooms out of the screen.
@param[in] zoomSpeed Helps keep up with camera speed.
@param[in] objectToFollow Character of the game.
@param[in] scene Pointer that points to the current scene.
*/
void CameraSystem::ZoomOut(int zoomSpeed, GameObject *objectToFollow, Scene *scene){
auto map = SceneManager::GetInstance()->GetScene("Gameplay")->
GetGameObject("Map");
if (!map) {
return;
}
m_beforePositionX = objectToFollow->GetPosition()->m_x;
m_beforePositionY = objectToFollow->GetPosition()->m_y;
this->m_cameraSpeed = zoomSpeed;
auto m_gameObjects = SceneManager::GetInstance()->GetCurrentScene()->GetAllGameObjects();
for (auto it = m_gameObjects.begin(); it!=m_gameObjects.end(); it++) {
if ((*it)->GetName()!="Map") {
m_proportionX = 100*(((*it)->GetPosition()->m_x + worldCameraX)/(map->GetWidth()));
m_proportionY = 100*(((*it)->GetPosition()->m_y + worldCameraY)/(map->GetHeight()));
if ((*it)->GetZoomProportion()->m_x!=0 && (*it)->GetZoomProportion()->m_y != 0) {
(*it)->SetSize(map->GetWidth()/(*it)->GetZoomProportion()->m_x,map->GetHeight()/(*it)->GetZoomProportion()->m_y);
(*it)->GetPosition()->m_x = ((m_proportionX/100) * (map->GetWidth() - zoomSpeed)) - worldCameraX;
(*it)->GetPosition()->m_y = ((m_proportionY/100) * (map->GetHeight() - zoomSpeed)) - worldCameraY;
}
}
}
auto mapscript = (MapScript*)SceneManager::GetInstance()
->GetScene("Gameplay")
->GetGameObject("Map")
->GetComponent("MapScript");
// mapscript->target.x-= speed;
if (mapscript) {
for (int i = 0; i<mapscript->leftWallsAmmount; i++) {
m_proportionX = 100 * ((mapscript->leftWalls[i].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->leftWalls[i].m_y + worldCameraY) / (map->GetHeight()));
mapscript->leftWalls[i].m_w = map->GetWidth()/((map->originalWidth/mapscript->leftWallsOriginal[i].m_w));//SHould be original
mapscript->leftWalls[i].m_h = map->GetHeight()/((map->originalHeight/mapscript->leftWallsOriginal[i].m_h));
mapscript->leftWalls[i].m_x = ((m_proportionX/100) * (map->GetWidth() - zoomSpeed)) - worldCameraX;
mapscript->leftWalls[i].m_y = ((m_proportionY/100) * (map->GetHeight() - zoomSpeed)) - worldCameraY;
}
for (int j = 0; j < mapscript->rightWallsAmmount; j++) {
m_proportionX = 100 * ((mapscript->rightWalls[j].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->rightWalls[j].m_y + worldCameraY) / (map->GetHeight()));
mapscript->rightWalls[j].m_w = map->GetWidth()/((map->originalWidth/mapscript->rightWallsOriginal[j].m_w));//SHould be original
mapscript->rightWalls[j].m_h = map->GetHeight()/((map->originalHeight/mapscript->rightWallsOriginal[j].m_h));
mapscript->rightWalls[j].m_x = ((m_proportionX/100) * (map->GetWidth() - zoomSpeed)) - worldCameraX;
mapscript->rightWalls[j].m_y = ((m_proportionY/100) * (map->GetHeight() - zoomSpeed)) - worldCameraY;
}
for (int k = 0; k < mapscript->upWallsAmmount; k++) {
m_proportionX = 100 * ((mapscript->upWalls[k].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->upWalls[k].m_y + worldCameraY) / (map->GetHeight()));
mapscript->upWalls[k].m_w = map->GetWidth()/((map->originalWidth/mapscript->upWallsOriginal[k].m_w));//SHould be original
mapscript->upWalls[k].m_h = map->GetHeight()/((map->originalHeight/mapscript->upWallsOriginal[k].m_h));
mapscript->upWalls[k].m_x = ((m_proportionX/100) * (map->GetWidth() - zoomSpeed)) - worldCameraX;
mapscript->upWalls[k].m_y = ((m_proportionY/100) * (map->GetHeight() - zoomSpeed)) - worldCameraY;
}
for (int l = 0; l < mapscript->downWallsAmmount; l++) {
m_proportionX = 100 * ((mapscript->downWalls[l].m_x + worldCameraX) / (map->GetWidth()));
m_proportionY = 100 * ((mapscript->downWalls[l].m_y + worldCameraY) / (map->GetHeight()));
mapscript->downWalls[l].m_w = map->GetWidth()/((map->originalWidth/mapscript->downWallsOriginal[l].m_w));//SHould be original
mapscript->downWalls[l].m_h = map->GetHeight()/((map->originalHeight/mapscript->downWallsOriginal[l].m_h));
mapscript->downWalls[l].m_x = ((m_proportionX/100) * (map->GetWidth() - zoomSpeed)) - worldCameraX;
mapscript->downWalls[l].m_y = ((m_proportionY/100) * (map->GetHeight() - zoomSpeed)) - worldCameraY;
}
}
map->SetSize(map->GetWidth() - zoomSpeed ,map->GetHeight() - zoomSpeed);
if (m_beforePositionX < objectToFollow->GetPosition()->m_x) {
MoveRight(objectToFollow->GetPosition()->m_x - m_beforePositionX,scene);
} else if (m_beforePositionX > objectToFollow->GetPosition()->m_x) {
MoveLeft(m_beforePositionX - objectToFollow->GetPosition()->m_x,scene);
}
if (m_beforePositionY < objectToFollow->GetPosition()->m_y) {
MoveUp(objectToFollow->GetPosition()->m_y - m_beforePositionY,scene);
} else if (m_beforePositionY > objectToFollow->GetPosition()->m_y) {
MoveUp(m_beforePositionY - objectToFollow->GetPosition()->m_y,scene);
}
}
/*
@brief instance of the new class CameraSystem() if not exist.
@return m_instance New class.
*/
CameraSystem *CameraSystem::GetInstance() {
if (!m_instance) {
m_instance = new CameraSystem();
}
return m_instance;
}
| 37.304991 | 141 | 0.596125 | fgagamedev |
a522b6e8176227d7ac73230884e6a4d50397e71a | 3,733 | cpp | C++ | Chapter24/BasicOption.cpp | alamlam1982/fincpp | 470469d35d90fc0fde96f119e329aedbc5f68f89 | [
"CECILL-B"
] | null | null | null | Chapter24/BasicOption.cpp | alamlam1982/fincpp | 470469d35d90fc0fde96f119e329aedbc5f68f89 | [
"CECILL-B"
] | null | null | null | Chapter24/BasicOption.cpp | alamlam1982/fincpp | 470469d35d90fc0fde96f119e329aedbc5f68f89 | [
"CECILL-B"
] | null | null | null | // BasicOption.cpp
//
// Author: Daniel Duffy
//
// 2005-10-15 DD new class for C++ book
// 2006-2-1 DD pathological cases U = 0 and T = 0 for C and P
// 2006-2-2 DD implemented the payoff function for call and put
//
// (C) Datasim Component Technology BV 2003-2006
//
#ifndef BasicOption_cpp
#define BasicOption_cpp
double MyMax(double d1, double d2)
{
if (d1 > d2)
return d1;
return d2;
}
#include "BasicOption.hpp"
#include <math.h>
#include <iostream>
//////////// Gaussian functions /////////////////////////////////
double BasicOption::n(double x) const
{
double A = 1.0/sqrt(2.0 * 3.1415);
return A * exp(-x*x*0.5);
}
double BasicOption::N(double x) const
{ // The approximation to the cumulative normal distribution
double a1 = 0.4361836;
double a2 = -0.1201676;
double a3 = 0.9372980;
double k = 1.0/(1.0 + (0.33267 * x));
if (x >= 0.0)
{
return 1.0 - n(x)* (a1*k + (a2*k*k) + (a3*k*k*k));
}
else
{
return 1.0 - N(-x);
}
}
// Kernel Functions (Haug)
double BasicOption::CallPrice(double U) const
{
double tmp = sig * sqrt(T);
double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp;
double d2 = d1 - tmp;
return (U * exp((b-r)*T) * N(d1)) - (K * exp(-r * T)* N(d2));
}
double BasicOption::PutPrice(double U) const
{
// cout << "Put price" << T << ", " << U << ", " << K << ", " << b << ", " << sig << endl;
double tmp = sig * sqrt(T);
double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp;
double d2 = d1 - tmp;
return (K * exp(-r * T)* N(-d2)) - (U * exp((b-r)*T) * N(-d1));
}
double BasicOption::CallDelta(double U) const
{
double tmp = sig * sqrt(T);
double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp;
return exp((b-r)*T) * N(d1);
}
double BasicOption::PutDelta(double U) const
{
double tmp = sig * sqrt(T);
double d1 = ( log(U/K) + (b+ (sig*sig)*0.5 ) * T )/ tmp;
return exp((b-r)*T) * (N(d1) - 1.0);
}
/////////////////////////////////////////////////////////////////////////////////////
void BasicOption::init()
{ // Initialise all default values
// Default values
r = 0.08;
sig= 0.30;
K = 65.0;
T = 0.25;
b = r; // Black and Scholes stock option model (1973)
otyp = "C"; // European Call Option (this is the default type)
}
void BasicOption::copy(const BasicOption& o2)
{
r = o2.r;
sig = o2.sig;
K = o2.K;
T = o2.T;
b = o2.b;
otyp = o2.otyp;
}
BasicOption::BasicOption()
{ // Default call option
init();
}
BasicOption::BasicOption(const BasicOption& o2)
{ // Copy constructor
copy(o2);
}
BasicOption::BasicOption (const string& optionType)
{ // Create option type
init();
otyp = optionType;
if (otyp == "c")
otyp = "C";
}
BasicOption::~BasicOption()
{
}
BasicOption& BasicOption::operator = (const BasicOption& option2)
{
if (this == &option2) return *this;
copy (option2);
return *this;
}
// Functions that calculate option price and sensitivities
double BasicOption::Price(double U) const
{
if (otyp == "C")
{
return CallPrice(U);
}
else
return PutPrice(U);
}
double BasicOption::Delta(double U) const
{
if (otyp == "C")
return CallDelta(U);
else
return PutDelta(U);
}
// Modifier functions
void BasicOption::toggle()
{ // Change option type (C/P, P/C)
if (otyp == "C")
otyp = "P";
else
otyp = "C";
}
void BasicOption::dumpPrint() const
{
cout << "Interest rate: " << r << endl;
cout << "Volatility: " << sig << endl;
cout << "Strike price: " << K << endl;
cout << "Expiry date: " << T << endl;
cout << "Cost of carry: " << b << endl;
cout << "Option type: " << otyp << endl;
}
double BasicOption::payoff(double U) const
{
if (otyp == "C")
{
return MyMax(U - K, 0.0);
}
else
{
return MyMax(K - U, 0.0);
}
}
#endif
| 15.236735 | 90 | 0.566033 | alamlam1982 |
a525350263d1c9a0e77db32dc0eb9fe7d7e0917b | 1,309 | hpp | C++ | include/codegen/include/UnityEngine/MeshFilter.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 1 | 2021-11-12T09:29:31.000Z | 2021-11-12T09:29:31.000Z | include/codegen/include/UnityEngine/MeshFilter.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | null | null | null | include/codegen/include/UnityEngine/MeshFilter.hpp | Futuremappermydud/Naluluna-Modifier-Quest | bfda34370764b275d90324b3879f1a429a10a873 | [
"MIT"
] | 2 | 2021-10-03T02:14:20.000Z | 2021-11-12T09:29:36.000Z | // Autogenerated from CppHeaderCreator on 7/27/2020 3:10:28 PM
// Created by Sc2ad
// =========================================================================
#pragma once
#pragma pack(push, 8)
// Begin includes
// Including type: UnityEngine.Component
#include "UnityEngine/Component.hpp"
#include "utils/il2cpp-utils.hpp"
// Completed includes
// Begin forward declares
// Forward declaring namespace: UnityEngine
namespace UnityEngine {
// Forward declaring type: Mesh
class Mesh;
}
// Completed forward declares
// Type namespace: UnityEngine
namespace UnityEngine {
// Autogenerated type: UnityEngine.MeshFilter
class MeshFilter : public UnityEngine::Component {
public:
// private System.Void DontStripMeshFilter()
// Offset: 0x13FBD58
void DontStripMeshFilter();
// public UnityEngine.Mesh get_sharedMesh()
// Offset: 0x13FBD5C
UnityEngine::Mesh* get_sharedMesh();
// public System.Void set_sharedMesh(UnityEngine.Mesh value)
// Offset: 0x13FBD9C
void set_sharedMesh(UnityEngine::Mesh* value);
// public System.Void set_mesh(UnityEngine.Mesh value)
// Offset: 0x13FBDEC
void set_mesh(UnityEngine::Mesh* value);
}; // UnityEngine.MeshFilter
}
DEFINE_IL2CPP_ARG_TYPE(UnityEngine::MeshFilter*, "UnityEngine", "MeshFilter");
#pragma pack(pop)
| 33.564103 | 78 | 0.698243 | Futuremappermydud |
a528e65715c8d631d23bc836ad4c8ebe924ae2f3 | 2,718 | cpp | C++ | source/gui/program_data.cpp | korteelko/asp_therm | 4e6aa6e2551bb36418d83b7b5450b42d6896f461 | [
"MIT"
] | 1 | 2018-12-11T09:06:47.000Z | 2018-12-11T09:06:47.000Z | source/gui/program_data.cpp | korteelko/asp_therm | 4e6aa6e2551bb36418d83b7b5450b42d6896f461 | [
"MIT"
] | 3 | 2019-11-10T21:08:59.000Z | 2020-01-23T03:05:21.000Z | source/gui/program_data.cpp | korteelko/asp_therm | 4e6aa6e2551bb36418d83b7b5450b42d6896f461 | [
"MIT"
] | null | null | null | /**
* asp_therm - implementation of real gas equations of state
*
*
* Copyright (c) 2020-2021 Mishutinski Yurii
*
* This library is distributed under the MIT License.
* See LICENSE file in the project root for full license information.
*/
#include "program_data.h"
#include "target_sys.h"
#include <QDir>
#include <algorithm>
#include <assert.h>
#include <string.h>
#if defined(_OS_NIX)
# include <dirent.h>
# include <sys/types.h>
# include <unistd.h>
#elif defined(_OS_WIN)
# include <windows.h>
#endif // _OS
#if defined(_OS_WIN)
# define PATH_DELIMETER '\\'
const std::string data_path = "\\..\\..\\..\\data\\";
const std::string gases_dir = "gases\\";
#elif defined(_OS_NIX)
# define PATH_DELIMETER '/'
const std::string data_path = "/../../../data/";
const std::string gases_dir = "gases/";
#endif // _OS
namespace {
std::string get_file_name(const std::string &full_path) {
size_t dot_pos = full_path.rfind('.'),
del_pos = full_path.rfind(PATH_DELIMETER);
if (dot_pos == std::string::npos)
dot_pos = full_path.size();
if (del_pos == std::string::npos)
del_pos = 0;
return full_path.substr(del_pos + 1, dot_pos - del_pos - 1);
}
} // anonymous namespace
ProgramData::ProgramData()
: error_status_(ERROR_SUCCESS_T) {
init_gas_files();
init_gas_names();
}
ProgramData &ProgramData::Instance() {
static ProgramData pd;
return pd;
}
ERROR_TYPE ProgramData::GetError() {
return error_status_;
}
bool ProgramData::ends_with(const char *src, const char *ending) {
int tmp_end = strlen(ending);
int len_dif = strlen(src) - tmp_end;
if (len_dif < 0)
return false;
while (tmp_end-- > 0)
if (src[len_dif + tmp_end] != ending[tmp_end])
return false;
return true;
}
void ProgramData::init_gas_files() {
QString cwd = QDir::currentPath();
error_status_ = read_gases_dir(cwd.toStdString() + data_path + gases_dir);
}
void ProgramData::init_gas_names() {
if (!gas_names_.empty())
gas_names_.clear();
for (const auto &x : gas_files_)
gas_names_.push_back(get_file_name(x));
}
int ProgramData::read_gases_dir(const std::string &dirname) {
if (!gas_files_.empty())
gas_files_.clear();
#if defined(_OS_NIX)
DIR *dirptr;
struct dirent *drn;
if ((dirptr = opendir(dirname.c_str())) == NULL) {
set_error_message(ERROR_INIT_T, "cannot open dir with gases xml");
return ERROR_INIT_T;
}
while ((drn = readdir(dirptr)) != NULL)
if (ends_with(drn->d_name, ".xml"))
gas_files_.push_back(dirname + drn->d_name);
closedir(dirptr);
return ERROR_SUCCESS_T;
#elif defined(_OS_WIN)
assert(0);
#endif // _OS
}
const std::vector<std::string> &ProgramData::GetGasesList() {
return gas_names_;
}
| 24.053097 | 76 | 0.681015 | korteelko |
a528e68c3fc61ab15a5811780b05f291eccbf43a | 17,042 | cpp | C++ | arangod/Aql/DistributeExecutor.cpp | corona3000/arangodb | e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da | [
"Apache-2.0"
] | null | null | null | arangod/Aql/DistributeExecutor.cpp | corona3000/arangodb | e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da | [
"Apache-2.0"
] | null | null | null | arangod/Aql/DistributeExecutor.cpp | corona3000/arangodb | e4d5a5d2d7e83b1a094c5ac01706a13fdecfc1da | [
"Apache-2.0"
] | null | null | null | ////////////////////////////////////////////////////////////////////////////////
/// DISCLAIMER
///
/// Copyright 2019 ArangoDB GmbH, Cologne, Germany
///
/// 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.
///
/// Copyright holder is ArangoDB GmbH, Cologne, Germany
///
/// @author Tobias Gödderz
////////////////////////////////////////////////////////////////////////////////
#include "DistributeExecutor.h"
#include "Aql/AqlCallStack.h"
#include "Aql/ClusterNodes.h"
#include "Aql/Collection.h"
#include "Aql/ExecutionEngine.h"
#include "Aql/IdExecutor.h"
#include "Aql/OutputAqlItemRow.h"
#include "Aql/Query.h"
#include "Aql/RegisterPlan.h"
#include "Aql/ShadowAqlItemRow.h"
#include "Aql/SkipResult.h"
#include "Basics/StaticStrings.h"
#include "VocBase/LogicalCollection.h"
#include <velocypack/Collection.h>
#include <velocypack/velocypack-aliases.h>
using namespace arangodb;
using namespace arangodb::aql;
DistributeExecutorInfos::DistributeExecutorInfos(
std::shared_ptr<std::unordered_set<RegisterId>> readableInputRegisters,
std::shared_ptr<std::unordered_set<RegisterId>> writeableOutputRegisters,
RegisterId nrInputRegisters, RegisterId nrOutputRegisters,
std::unordered_set<RegisterId> registersToClear,
std::unordered_set<RegisterId> registersToKeep,
std::vector<std::string> clientIds, Collection const* collection,
RegisterId regId, RegisterId alternativeRegId, bool allowSpecifiedKeys,
bool allowKeyConversionToObject, bool createKeys, ScatterNode::ScatterType type)
: ExecutorInfos(readableInputRegisters, writeableOutputRegisters, nrInputRegisters,
nrOutputRegisters, registersToClear, registersToKeep),
ClientsExecutorInfos(std::move(clientIds)),
_regId(regId),
_alternativeRegId(alternativeRegId),
_allowKeyConversionToObject(allowKeyConversionToObject),
_createKeys(createKeys),
_usesDefaultSharding(collection->usesDefaultSharding()),
_allowSpecifiedKeys(allowSpecifiedKeys),
_collection(collection),
_logCol(collection->getCollection()),
_type(type) {
TRI_ASSERT(readableInputRegisters->find(_regId) != readableInputRegisters->end());
if (hasAlternativeRegister()) {
TRI_ASSERT(readableInputRegisters->find(_alternativeRegId) !=
readableInputRegisters->end());
}
}
auto DistributeExecutorInfos::registerId() const noexcept -> RegisterId {
TRI_ASSERT(_regId != RegisterPlan::MaxRegisterId);
return _regId;
}
auto DistributeExecutorInfos::hasAlternativeRegister() const noexcept -> bool {
return _alternativeRegId != RegisterPlan::MaxRegisterId;
}
auto DistributeExecutorInfos::alternativeRegisterId() const noexcept -> RegisterId {
TRI_ASSERT(_alternativeRegId != RegisterPlan::MaxRegisterId);
return _alternativeRegId;
}
auto DistributeExecutorInfos::allowKeyConversionToObject() const noexcept -> bool {
return _allowKeyConversionToObject;
}
auto DistributeExecutorInfos::createKeys() const noexcept -> bool {
return _createKeys;
}
auto DistributeExecutorInfos::usesDefaultSharding() const noexcept -> bool {
return _usesDefaultSharding;
}
auto DistributeExecutorInfos::allowSpecifiedKeys() const noexcept -> bool {
return _allowSpecifiedKeys;
}
auto DistributeExecutorInfos::scatterType() const noexcept -> ScatterNode::ScatterType {
return _type;
}
auto DistributeExecutorInfos::getResponsibleClient(arangodb::velocypack::Slice value) const
-> ResultT<std::string> {
std::string shardId;
int res = _logCol->getResponsibleShard(value, true, shardId);
if (res != TRI_ERROR_NO_ERROR) {
return Result{res};
}
TRI_ASSERT(!shardId.empty());
if (_type == ScatterNode::ScatterType::SERVER) {
// Special case for server based distribution.
shardId = _collection->getServerForShard(shardId);
TRI_ASSERT(!shardId.empty());
}
return shardId;
}
/// @brief create a new document key
auto DistributeExecutorInfos::createKey(VPackSlice input) const -> std::string {
return _logCol->createKey(input);
}
// TODO
// This section is not implemented yet
DistributeExecutor::ClientBlockData::ClientBlockData(ExecutionEngine& engine,
ScatterNode const* node,
ExecutorInfos const& scatterInfos)
: _blockManager(engine.itemBlockManager()), _infos(scatterInfos) {
// We only get shared ptrs to const data. so we need to copy here...
IdExecutorInfos infos{scatterInfos.numberOfInputRegisters(),
*scatterInfos.registersToKeep(),
*scatterInfos.registersToClear(),
false,
0,
"",
false};
// NOTE: Do never change this type! The execute logic below requires this and only this type.
_executor =
std::make_unique<ExecutionBlockImpl<IdExecutor<ConstFetcher>>>(&engine, node,
std::move(infos));
}
auto DistributeExecutor::ClientBlockData::clear() -> void {
_queue.clear();
_executorHasMore = false;
}
auto DistributeExecutor::ClientBlockData::addBlock(SharedAqlItemBlockPtr block,
std::vector<size_t> usedIndexes) -> void {
_queue.emplace_back(block, std::move(usedIndexes));
}
auto DistributeExecutor::ClientBlockData::addSkipResult(SkipResult const& skipResult) -> void {
TRI_ASSERT(_skipped.subqueryDepth() == 1 ||
_skipped.subqueryDepth() == skipResult.subqueryDepth());
_skipped.merge(skipResult, false);
}
auto DistributeExecutor::ClientBlockData::hasDataFor(AqlCall const& call) -> bool {
return _executorHasMore || !_queue.empty();
}
/**
* @brief This call will join as many blocks as available from the queue
* and return them in a SingleBlock. We then use the IdExecutor
* to hand out the data contained in these blocks
* We do on purpose not give any kind of guarantees on the sizing of
* this block to be flexible with the implementation, and find a good
* trade-off between blocksize and block copy operations.
*
* @return SharedAqlItemBlockPtr a joind block from the queue.
*/
auto DistributeExecutor::ClientBlockData::popJoinedBlock()
-> std::tuple<SharedAqlItemBlockPtr, SkipResult> {
// There are some optimizations available in this implementation.
// Namely we could apply good logic to cut the blocks at shadow rows
// in order to allow the IDexecutor to hand them out en-block.
// However we might leverage the restriction to stop at ShadowRows
// at one point anyways, and this Executor has no business with ShadowRows.
size_t numRows = 0;
for (auto const& [block, choosen] : _queue) {
numRows += choosen.size();
if (numRows >= ExecutionBlock::DefaultBatchSize) {
// Avoid to put too many rows into this block.
break;
}
}
SharedAqlItemBlockPtr newBlock =
_blockManager.requestBlock(numRows, _infos.numberOfOutputRegisters());
// We create a block, with correct register information
// but we do not allow outputs to be written.
OutputAqlItemRow output{newBlock, make_shared_unordered_set(),
_infos.registersToKeep(), _infos.registersToClear()};
while (!output.isFull()) {
// If the queue is empty our sizing above would not be correct
TRI_ASSERT(!_queue.empty());
auto const& [block, choosen] = _queue.front();
TRI_ASSERT(output.numRowsLeft() >= choosen.size());
for (auto const& i : choosen) {
// We do not really care what we copy. However
// the API requires to know what it is.
if (block->isShadowRow(i)) {
ShadowAqlItemRow toCopy{block, i};
output.copyRow(toCopy);
} else {
InputAqlItemRow toCopy{block, i};
output.copyRow(toCopy);
}
output.advanceRow();
}
// All required rows copied.
// Drop block form queue.
_queue.pop_front();
}
SkipResult skip = _skipped;
_skipped.reset();
return {newBlock, skip};
}
auto DistributeExecutor::ClientBlockData::execute(AqlCallStack callStack, ExecutionState upstreamState)
-> std::tuple<ExecutionState, SkipResult, SharedAqlItemBlockPtr> {
TRI_ASSERT(_executor != nullptr);
// Make sure we actually have data before you call execute
TRI_ASSERT(hasDataFor(callStack.peek()));
if (!_executorHasMore) {
// This cast is guaranteed, we create this a couple lines above and only
// this executor is used here.
// Unfortunately i did not get a version compiled were i could only forward
// declare the templates in header.
auto casted =
static_cast<ExecutionBlockImpl<IdExecutor<ConstFetcher>>*>(_executor.get());
TRI_ASSERT(casted != nullptr);
auto [block, skipped] = popJoinedBlock();
// We will at least get one block, otherwise the hasDataFor would
// be required to return false!
TRI_ASSERT(block != nullptr);
casted->injectConstantBlock(block, skipped);
_executorHasMore = true;
}
auto [state, skipped, result] = _executor->execute(callStack);
// We have all data locally cannot wait here.
TRI_ASSERT(state != ExecutionState::WAITING);
if (state == ExecutionState::DONE) {
// This executor is finished, including shadowrows
// We are going to reset it on next call
_executorHasMore = false;
// Also we need to adjust the return states
// as this state only represents one single block
if (!_queue.empty()) {
state = ExecutionState::HASMORE;
} else {
state = upstreamState;
}
}
return {state, skipped, result};
}
DistributeExecutor::DistributeExecutor(DistributeExecutorInfos const& infos)
: _infos(infos){};
auto DistributeExecutor::distributeBlock(SharedAqlItemBlockPtr block, SkipResult skipped,
std::unordered_map<std::string, ClientBlockData>& blockMap)
-> void {
std::unordered_map<std::string, std::vector<std::size_t>> choosenMap;
choosenMap.reserve(blockMap.size());
for (size_t i = 0; i < block->size(); ++i) {
if (block->isShadowRow(i)) {
// ShadowRows need to be added to all Clients
for (auto const& [key, value] : blockMap) {
choosenMap[key].emplace_back(i);
}
} else {
auto client = getClient(block, i);
// We can only have clients we are prepared for
TRI_ASSERT(blockMap.find(client) != blockMap.end());
choosenMap[client].emplace_back(i);
}
}
// We cannot have more in choosen than we have blocks
TRI_ASSERT(choosenMap.size() <= blockMap.size());
for (auto const& [key, value] : choosenMap) {
TRI_ASSERT(blockMap.find(key) != blockMap.end());
auto target = blockMap.find(key);
if (target == blockMap.end()) {
// Impossible, just avoid UB.
LOG_TOPIC("7bae6", ERR, Logger::AQL)
<< "Tried to distribute data to shard " << key
<< " which is not part of the query. Ignoring.";
continue;
}
target->second.addBlock(block, std::move(value));
}
// Add the skipResult to all clients.
// It needs to be fetched once for every client.
for (auto& [key, map] : blockMap) {
map.addSkipResult(skipped);
}
}
auto DistributeExecutor::getClient(SharedAqlItemBlockPtr block, size_t rowIndex)
-> std::string {
InputAqlItemRow row{block, rowIndex};
AqlValue val = row.getValue(_infos.registerId());
VPackSlice input = val.slice(); // will throw when wrong type
bool usedAlternativeRegId = false;
if (input.isNull() && _infos.hasAlternativeRegister()) {
// value is set, but null
// check if there is a second input register available (UPSERT makes use of
// two input registers,
// one for the search document, the other for the insert document)
val = row.getValue(_infos.alternativeRegisterId());
input = val.slice(); // will throw when wrong type
usedAlternativeRegId = true;
}
VPackSlice value = input;
bool hasCreatedKeyAttribute = false;
if (input.isString() && _infos.allowKeyConversionToObject()) {
_keyBuilder.clear();
_keyBuilder.openObject(true);
_keyBuilder.add(StaticStrings::KeyString, input);
_keyBuilder.close();
// clear the previous value
block->destroyValue(rowIndex, _infos.registerId());
// overwrite with new value
block->emplaceValue(rowIndex, _infos.registerId(), _keyBuilder.slice());
value = _keyBuilder.slice();
hasCreatedKeyAttribute = true;
} else if (!input.isObject()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_ARANGO_DOCUMENT_TYPE_INVALID);
}
TRI_ASSERT(value.isObject());
if (_infos.createKeys()) {
bool buildNewObject = false;
// we are responsible for creating keys if none present
if (_infos.usesDefaultSharding()) {
// the collection is sharded by _key...
if (!hasCreatedKeyAttribute && !value.hasKey(StaticStrings::KeyString)) {
// there is no _key attribute present, so we are responsible for
// creating one
buildNewObject = true;
}
} else {
// the collection is not sharded by _key
if (hasCreatedKeyAttribute || value.hasKey(StaticStrings::KeyString)) {
// a _key was given, but user is not allowed to specify _key
if (usedAlternativeRegId || !_infos.allowSpecifiedKeys()) {
THROW_ARANGO_EXCEPTION(TRI_ERROR_CLUSTER_MUST_NOT_SPECIFY_KEY);
}
} else {
buildNewObject = true;
}
}
if (buildNewObject) {
_keyBuilder.clear();
_keyBuilder.openObject(true);
_keyBuilder.add(StaticStrings::KeyString, VPackValue(_infos.createKey(value)));
_keyBuilder.close();
_objectBuilder.clear();
VPackCollection::merge(_objectBuilder, input, _keyBuilder.slice(), true);
// clear the previous value and overwrite with new value:
auto reg = usedAlternativeRegId ? _infos.alternativeRegisterId()
: _infos.registerId();
block->destroyValue(rowIndex, reg);
block->emplaceValue(rowIndex, reg, _objectBuilder.slice());
value = _objectBuilder.slice();
}
}
auto res = _infos.getResponsibleClient(value);
THROW_ARANGO_EXCEPTION_IF_FAIL(res.result());
return res.get();
}
ExecutionBlockImpl<DistributeExecutor>::ExecutionBlockImpl(ExecutionEngine* engine,
DistributeNode const* node,
DistributeExecutorInfos&& infos)
: BlocksWithClientsImpl(engine, node, std::move(infos)) {}
/*
/// @brief getOrSkipSomeForShard
std::pair<ExecutionState, arangodb::Result> ExecutionBlockImpl<DistributeExecutor>::getOrSkipSomeForShard(
size_t atMost, bool skipping, SharedAqlItemBlockPtr& result,
size_t& skipped, std::string const& shardId) {
TRI_ASSERT(result == nullptr && skipped == 0);
TRI_ASSERT(atMost > 0);
size_t clientId = getClientId(shardId);
if (!hasMoreForClientId(clientId)) {
return {ExecutionState::DONE, TRI_ERROR_NO_ERROR};
}
std::deque<std::pair<size_t, size_t>>& buf = _distBuffer.at(clientId);
if (buf.empty()) {
auto res = getBlockForClient(atMost, clientId);
if (res.first == ExecutionState::WAITING) {
return {res.first, TRI_ERROR_NO_ERROR};
}
if (!res.second) {
// Upstream is empty!
TRI_ASSERT(res.first == ExecutionState::DONE);
return {ExecutionState::DONE, TRI_ERROR_NO_ERROR};
}
}
skipped = (std::min)(buf.size(), atMost);
if (skipping) {
for (size_t i = 0; i < skipped; i++) {
buf.pop_front();
}
return {getHasMoreStateForClientId(clientId), TRI_ERROR_NO_ERROR};
}
BlockCollector collector(&_engine->itemBlockManager());
std::vector<size_t> chosen;
size_t i = 0;
while (i < skipped) {
size_t const n = buf.front().first;
while (buf.front().first == n && i < skipped) {
chosen.emplace_back(buf.front().second);
buf.pop_front();
i++;
// make sure we are not overreaching over the end of the buffer
if (buf.empty()) {
break;
}
}
SharedAqlItemBlockPtr more{_buffer[n]->slice(chosen, 0, chosen.size())};
collector.add(std::move(more));
chosen.clear();
}
// Skipping was handle before
TRI_ASSERT(!skipping);
result = collector.steal();
// _buffer is left intact, deleted and cleared at shutdown
return {getHasMoreStateForClientId(clientId), TRI_ERROR_NO_ERROR};
}
*/
| 36.105932 | 106 | 0.67627 | corona3000 |
a52bee6770aa24e0bf125bd1404ccb1532f66628 | 414 | cpp | C++ | Gateway/main/src/graphics/API/OGL/VertexBuffer_GL.cpp | Idogftw/ProjectRev | cf3b78d211f0bc38480801bcc3e91b692a6879f4 | [
"MIT"
] | null | null | null | Gateway/main/src/graphics/API/OGL/VertexBuffer_GL.cpp | Idogftw/ProjectRev | cf3b78d211f0bc38480801bcc3e91b692a6879f4 | [
"MIT"
] | null | null | null | Gateway/main/src/graphics/API/OGL/VertexBuffer_GL.cpp | Idogftw/ProjectRev | cf3b78d211f0bc38480801bcc3e91b692a6879f4 | [
"MIT"
] | null | null | null | #include "graphics/API/OGL/VertexBuffer_GL.hpp"
namespace Gateway
{
VertexBuffer_GL::VertexBuffer_GL(VertexObjectTypes m_object_type, VertexDrawTypes t_draw_type, VertexStorageTypes m_storage_type)
: m_draw_type(t_draw_type), IVertexBuffer(m_object_type, t_draw_type, m_storage_type)
{
}
VertexBuffer_GL::~VertexBuffer_GL()
{
}
void VertexBuffer_GL::Bind()
{
}
void VertexBuffer_GL::Unbind()
{
}
}; | 21.789474 | 130 | 0.782609 | Idogftw |
a52d3e30f73b7d2ce696d5f7383e357de4e7c68f | 794 | hpp | C++ | src/external.hpp | mdraven/terrafirmacraft_alloys | b96b47fbbfcc30d1be2b346049814fc47131e82b | [
"MIT"
] | null | null | null | src/external.hpp | mdraven/terrafirmacraft_alloys | b96b47fbbfcc30d1be2b346049814fc47131e82b | [
"MIT"
] | null | null | null | src/external.hpp | mdraven/terrafirmacraft_alloys | b96b47fbbfcc30d1be2b346049814fc47131e82b | [
"MIT"
] | null | null | null |
#ifndef _EXTERNAL_H_917E67ED622B_
#define _EXTERNAL_H_917E67ED622B_
#ifdef __GNUC__
#pragma GCC system_header
#endif
// Qt5
#include <QtCore/QFile>
#include <QtCore/QJsonDocument>
#include <QtCore/QJsonObject>
#include <QtCore/QMap>
#include <QtCore/QString>
#include <QtCore/QtDebug>
#include <QtGui/QPixmap>
#include <QtUiTools/QUiLoader>
#include <QtWidgets/QApplication>
#include <QtWidgets/QComboBox>
#include <QtWidgets/QHeaderView>
#include <QtWidgets/QLabel>
#include <QtWidgets/QMainWindow>
#include <QtWidgets/QTableWidget>
// Boost
#include <boost/optional.hpp>
#include <boost/variant.hpp>
// STL
#include <cmath>
#include <iostream>
#include <map>
#include <memory>
#include <queue>
#include <stack>
#include <string>
#include <vector>
#endif /* _EXTERNAL_H_917E67ED622B_ */
| 19.85 | 38 | 0.7733 | mdraven |
a5311f43636a12976478872610ee503b8375ee19 | 126 | hpp | C++ | Core/Game/Enum/GameCommand.hpp | LinkClinton/MinesweeperVersus | fc5d4fa8aa7e2b6d4fd798d52a1614c243f4e308 | [
"MIT"
] | 1 | 2019-11-30T07:12:32.000Z | 2019-11-30T07:12:32.000Z | Core/Game/Enum/GameCommand.hpp | LinkClinton/MinesweeperVersus | fc5d4fa8aa7e2b6d4fd798d52a1614c243f4e308 | [
"MIT"
] | null | null | null | Core/Game/Enum/GameCommand.hpp | LinkClinton/MinesweeperVersus | fc5d4fa8aa7e2b6d4fd798d52a1614c243f4e308 | [
"MIT"
] | null | null | null | #pragma once
namespace Minesweeper {
enum class GameCommand : unsigned {
eCheckAll = 0,
eCheck = 1,
eFlag = 2
};
} | 11.454545 | 36 | 0.642857 | LinkClinton |
a53282620a38d44b270769c19209c87daa7e1f9a | 464 | cpp | C++ | problem_solving/CodeForces/463A/11651884_AC_15ms_4kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | 2 | 2020-09-02T12:07:47.000Z | 2020-11-17T11:17:16.000Z | problem_solving/CodeForces/463A/11651884_AC_15ms_4kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | null | null | null | problem_solving/CodeForces/463A/11651884_AC_15ms_4kB.cpp | cosmicray001/academic | 6aa142baeba4bb1ad73b8669e37305ca0b5102a7 | [
"MIT"
] | 4 | 2020-08-11T14:23:34.000Z | 2020-11-17T10:52:31.000Z | #include <bits/stdc++.h>
using namespace std;
int main()
{
int len, s;
scanf("%d %d", &len, &s);
int max_ve = 0;
int a, b;
bool f = 0;
for(int i = 0; i < len; i++){
scanf("%d %d", &a, &b);
if(a < s && (100 - b) > max_ve && b){
max_ve = max(max_ve, (100 - b));
f = 1;
}
else if(b == 0 && a <= s){
max_ve = max(max_ve, 0);
f = 1;
}
}
if(f) printf("%d\n", max_ve);
else printf("-1\n");
return 0;
}
| 16.571429 | 41 | 0.43319 | cosmicray001 |
a5383954a101ef638414811375f09c8094cc182a | 2,529 | ipp | C++ | include/benchmarks/implementation/component/BenchmarkParticleSystemSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | null | null | null | include/benchmarks/implementation/component/BenchmarkParticleSystemSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | null | null | null | include/benchmarks/implementation/component/BenchmarkParticleSystemSimple.ipp | thorbenlouw/CUP-CFD | d06f7673a1ed12bef24de4f1b828ef864fa45958 | [
"MIT"
] | null | null | null | /**
* @file
* @author University of Warwick
* @version 1.0
*
* @section LICENSE
*
* @section DESCRIPTION
*
* Header level definitions for the BenchmarkParticleSystem class.
*/
#ifndef CUPCFD_BENCHMARK_BENCHMARK_PARTICLESYSTEM_SIMPLE_IPP_H
#define CUPCFD_BENCHMARK_BENCHMARK_PARTICLESYSTEM_SIMPLE_IPP_H
#include "tt_interface_c.h"
namespace cupcfd
{
namespace benchmark
{
template <class M, class I, class T, class L>
BenchmarkParticleSystemSimple<M,I,T,L>::BenchmarkParticleSystemSimple(std::string benchmarkName, I repetitions,
I nTimesteps,
cupcfd::distributions::Distribution<I,T>& dtDist,
std::shared_ptr<cupcfd::particles::ParticleSystemSimple<M,I,T,L>> particleSystemPtr)
: Benchmark<I,T>(benchmarkName, repetitions),
particleSystemPtr(particleSystemPtr),
nTimesteps(nTimesteps)
{
this->dtDist = dtDist.clone();
}
template <class M, class I, class T, class L>
BenchmarkParticleSystemSimple<M,I,T,L>::~BenchmarkParticleSystemSimple() {
delete this->dtDist;
}
template <class M, class I, class T, class L>
void BenchmarkParticleSystemSimple<M,I,T,L>::setupBenchmark() {
// Nothing to do currently
}
template <class M, class I, class T, class L>
void BenchmarkParticleSystemSimple<M,I,T,L>::recordParameters() {
// Nothing to do currently
}
template <class M, class I, class T, class L>
cupcfd::error::eCodes BenchmarkParticleSystemSimple<M,I,T,L>::runBenchmark() {
// ToDo: Increasing number of repetitions is currently just
// a multiplier for the number of timesteps.
// Need to add a means to reset the Particle System!
cupcfd::error::eCodes status;
this->startBenchmarkBlock(this->benchmarkName);
TreeTimerLogParameterInt("Repetitions", this->repetitions);
this->recordParameters();
for(I i = 0; i < this->repetitions; i++) {
for(I j = 0; j < this->nTimesteps; j++) {
// Generate time for next timestep
T timestep;
this->dtDist->getValues(×tep, 1);
// Advance Particle System by one timestep
this->startBenchmarkBlock("UpdateParticleTimestep");
status = particleSystemPtr->updateSystem(timestep);
if (status != cupcfd::error::E_SUCCESS) {
std::cout << "ERROR: updateSystem() failed" << std::endl;
MPI_Abort(MPI_COMM_WORLD, status);
}
this->stopBenchmarkBlock("UpdateParticleTimestep");
}
}
this->stopBenchmarkBlock(this->benchmarkName);
return cupcfd::error::E_SUCCESS;
}
}
}
#endif
| 29.406977 | 113 | 0.697113 | thorbenlouw |
a53f22692db61fddc8b87bb8977d87ccc0fd8a1a | 3,354 | hpp | C++ | games/saloon/young_gun.hpp | JackLimes/Joueur.cpp | d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b | [
"MIT"
] | 9 | 2015-12-09T18:49:55.000Z | 2021-01-08T21:45:54.000Z | games/saloon/young_gun.hpp | JackLimes/Joueur.cpp | d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b | [
"MIT"
] | 14 | 2015-11-06T19:26:56.000Z | 2019-10-19T07:45:11.000Z | games/saloon/young_gun.hpp | JackLimes/Joueur.cpp | d7dc45b5f95d9b3fc8c9cb846d63d6f44c83a61b | [
"MIT"
] | 21 | 2015-10-16T03:57:23.000Z | 2020-11-08T16:48:16.000Z | #ifndef GAMES_SALOON_YOUNG_GUN_H
#define GAMES_SALOON_YOUNG_GUN_H
// YoungGun
// An eager young person that wants to join your gang, and will call in the veteran Cowboys you need to win the brawl in the saloon.
// DO NOT MODIFY THIS FILE
// Never try to directly create an instance of this class, or modify its member variables.
// Instead, you should only be reading its variables and calling its functions.
#include <vector>
#include <queue>
#include <deque>
#include <unordered_map>
#include <string>
#include <initializer_list>
#include "../../joueur/src/any.hpp"
#include "game_object.hpp"
#include "impl/saloon_fwd.hpp"
// <<-- Creer-Merge: includes -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// you can add additional #includes here
// <<-- /Creer-Merge: includes -->>
namespace cpp_client
{
namespace saloon
{
/// <summary>
/// An eager young person that wants to join your gang, and will call in the veteran Cowboys you need to win the brawl in the saloon.
/// </summary>
class Young_gun_ : public Game_object_
{
public:
/// <summary>
/// The Tile that a Cowboy will be called in on if this YoungGun calls in a Cowboy.
/// </summary>
const Tile& call_in_tile;
/// <summary>
/// True if the YoungGun can call in a Cowboy, false otherwise.
/// </summary>
const bool& can_call_in;
/// <summary>
/// The Player that owns and can control this YoungGun.
/// </summary>
const Player& owner;
/// <summary>
/// The Tile this YoungGun is currently on.
/// </summary>
const Tile& tile;
// <<-- Creer-Merge: member variables -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// You can add additional member variables here. None of them will be tracked or updated by the server.
// <<-- /Creer-Merge: member variables -->>
/// <summary>
/// tells the _young_gun to call in a new _cowboy of the given job to the open _tile nearest to them.
/// </summary>
/// <param name="job"> The job you want the Cowboy being brought to have. </param>
Cowboy call_in(const std::string& job);
// <<-- Creer-Merge: methods -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs.
// You can add additional methods here.
// <<-- /Creer-Merge: methods -->>
~Young_gun_();
// ####################
// Don't edit these!
// ####################
/// \cond FALSE
Young_gun_(std::initializer_list<std::pair<std::string, Any&&>> init);
Young_gun_() : Young_gun_({}){}
virtual void resize(const std::string& name, std::size_t size) override;
virtual void change_vec_values(const std::string& name, std::vector<std::pair<std::size_t, Any>>& values) override;
virtual void remove_key(const std::string& name, Any& key) override;
virtual std::unique_ptr<Any> add_key_value(const std::string& name, Any& key, Any& value) override;
virtual bool is_map(const std::string& name) override;
virtual void rebind_by_name(Any* to_change, const std::string& member, std::shared_ptr<Base_object> ref) override;
/// \endcond
// ####################
// Don't edit these!
// ####################
};
} // saloon
} // cpp_client
#endif // GAMES_SALOON_YOUNG_GUN_H
| 32.882353 | 143 | 0.66458 | JackLimes |
a53f97a4fe6b0cb9078bec0ac5db51d578e78b9e | 5,905 | tcc | C++ | libraries/nodes/tcc/MultiplexerNode.tcc | siddu1998/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2018-11-08T06:19:31.000Z | 2018-11-08T06:19:31.000Z | libraries/nodes/tcc/MultiplexerNode.tcc | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | null | null | null | libraries/nodes/tcc/MultiplexerNode.tcc | vishnoitanuj/ELL | 993d5370f0f7a274e8dfd8f43220c792be46f314 | [
"MIT"
] | 1 | 2019-12-19T10:02:48.000Z | 2019-12-19T10:02:48.000Z | ////////////////////////////////////////////////////////////////////////////////////////////////////
//
// Project: Embedded Learning Library (ELL)
// File: MultiplexerNode.tcc (nodes)
// Authors: Ofer Dekel
//
////////////////////////////////////////////////////////////////////////////////////////////////////
namespace ell
{
namespace nodes
{
template <typename ValueType, typename SelectorType>
MultiplexerNode<ValueType, SelectorType>::MultiplexerNode()
: CompilableNode({ &_elements, &_selector }, { &_output }), _elements(this, {}, elementsPortName), _selector(this, {}, selectorPortName), _output(this, defaultOutputPortName, 1)
{
}
template <typename ValueType, typename SelectorType>
MultiplexerNode<ValueType, SelectorType>::MultiplexerNode(const model::OutputPort<ValueType>& input, const model::OutputPort<SelectorType>& selector)
: CompilableNode({ &_elements, &_selector }, { &_output }), _elements(this, input, elementsPortName), _selector(this, selector, selectorPortName), _output(this, defaultOutputPortName, 1)
{
if (selector.Size() != 1)
{
throw ell::utilities::Exception("Error: Condition must be 1-D signal");
}
};
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::Compute() const
{
int index = static_cast<int>(_selector[0]);
_output.SetOutput({ _elements[index] });
}
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::Copy(model::ModelTransformer& transformer) const
{
const auto& newElements = transformer.GetCorrespondingInputs(_elements);
const auto& newSelector = transformer.GetCorrespondingInputs(_selector);
auto newNode = transformer.AddNode<MultiplexerNode<ValueType, SelectorType>>(newElements, newSelector);
transformer.MapNodeOutput(output, newNode->output);
}
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::Compile(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function)
{
if (std::is_same<SelectorType, bool>())
{
CompileMultiplexerBinary(compiler, function);
}
else if (std::is_same<SelectorType, int>())
{
CompileUnrolled(compiler, function);
}
else
{
throw emitters::EmitterException(emitters::EmitterError::valueTypeNotSupported, "Multiplexer node selectors must be bool or int");
}
}
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::CompileMultiplexerBinary(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function)
{
VerifyIsScalar(selector);
VerifyIsScalar(output);
emitters::LLVMValue pSelector = compiler.EnsurePortEmitted(selector);
emitters::LLVMValue pSelectorVal = function.Load(pSelector);
emitters::LLVMValue pResult = compiler.EnsurePortEmitted(output);
auto lVal = elements.GetInputElement(0); // lval is selected if the result of the "if" comparison is NON-zero
auto rVal = elements.GetInputElement(1);
auto pLMergeableSrc = compiler.GetMergeableNodeRegion(lVal);
auto pRMergeableSrc = compiler.GetMergeableNodeRegion(rVal);
function.If(emitters::TypedComparison::equals, pSelectorVal, function.Literal<SelectorType>(0), [pLMergeableSrc, pResult, &compiler, this](emitters::IRFunctionEmitter& function) {
if (pLMergeableSrc != nullptr)
{
function.MergeRegion(pLMergeableSrc);
}
function.Store(pResult, compiler.LoadPortElementVariable(elements.GetInputElement(0)));
}).Else([pRMergeableSrc, pResult, &compiler, this](emitters::IRFunctionEmitter& function) {
if (pRMergeableSrc != nullptr)
{
function.MergeRegion(pRMergeableSrc);
}
function.Store(pResult, compiler.LoadPortElementVariable(elements.GetInputElement(1)));
});
auto pSelectorNode = selector.GetParentNodes()[0];
if (HasSingleDescendant(*pSelectorNode))
{
compiler.TryMergeNodeRegions(*pSelectorNode, *this);
}
}
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::CompileUnrolled(model::IRMapCompiler& compiler, emitters::IRFunctionEmitter& function)
{
VerifyIsScalar(selector);
VerifyIsScalar(output);
auto numElements = elements.Size();
emitters::LLVMValue pSelector = compiler.EnsurePortEmitted(selector);
auto pSelectorVal = function.Load(pSelector);
emitters::LLVMValue result = compiler.EnsurePortEmitted(output);
for (size_t index = 0; index < numElements; ++index)
{
function.If(emitters::TypedComparison::equals, function.Literal((int)index), pSelectorVal, [index, result, &compiler, this](emitters::IRFunctionEmitter& function) {
emitters::LLVMValue val = compiler.LoadPortElementVariable(elements.GetInputElement(index));
function.Store(result, val);
});
}
}
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::WriteToArchive(utilities::Archiver& archiver) const
{
Node::WriteToArchive(archiver);
archiver["elements"] << _elements;
archiver["selector"] << _selector;
}
template <typename ValueType, typename SelectorType>
void MultiplexerNode<ValueType, SelectorType>::ReadFromArchive(utilities::Unarchiver& archiver)
{
Node::ReadFromArchive(archiver);
archiver["elements"] >> _elements;
archiver["selector"] >> _selector;
}
}
}
| 44.398496 | 194 | 0.657917 | siddu1998 |
a5411101df727829f26e685e806b84c1a319c403 | 395 | hpp | C++ | include/pkg/deb/preinst.hpp | naughtybikergames/pkg | 9a78380c6cf82c95dec3968a7ed69000b349113d | [
"MIT"
] | null | null | null | include/pkg/deb/preinst.hpp | naughtybikergames/pkg | 9a78380c6cf82c95dec3968a7ed69000b349113d | [
"MIT"
] | null | null | null | include/pkg/deb/preinst.hpp | naughtybikergames/pkg | 9a78380c6cf82c95dec3968a7ed69000b349113d | [
"MIT"
] | null | null | null | #ifndef PKG_DEB_PREINST_HPP
#define PKG_DEB_PREINST_HPP
#include <string>
namespace pkg {
namespace deb {
class preinst {
private:
std::string _preinst;
public:
preinst();
std::string to_string() const;
};
}
}
std::ostream& operator<<(std::ostream &out, const pkg::deb::preinst preinst);
#endif | 18.809524 | 77 | 0.556962 | naughtybikergames |
a542bf3623e94562e2ad36d7a27ec2c15bc72343 | 4,507 | cpp | C++ | position-receiver-qt/src/positionreceiver.cpp | keithel/helloworld-capnproto-streamer | 946b14465af4ea7ee5bea4d7e521b38abd6f4d1e | [
"Apache-2.0"
] | 1 | 2017-11-03T08:13:04.000Z | 2017-11-03T08:13:04.000Z | position-receiver-qt/src/positionreceiver.cpp | keithel/helloworld-capnproto-streamer | 946b14465af4ea7ee5bea4d7e521b38abd6f4d1e | [
"Apache-2.0"
] | null | null | null | position-receiver-qt/src/positionreceiver.cpp | keithel/helloworld-capnproto-streamer | 946b14465af4ea7ee5bea4d7e521b38abd6f4d1e | [
"Apache-2.0"
] | null | null | null | #include "positionreceiver.h"
#include <QUdpSocket>
#include <capnp/message.h>
#include <capnp/serialize.h>
#include "position.capnp.h"
#include <QtConcurrent/QtConcurrent>
using ::capnp::word;
PositionReceiver::PositionReceiver(QObject* parent, bool enableTesting)
: QObject(parent)
, m_nPerSecCounter(0)
, m_lastNPerSec(0)
, m_socket(new QUdpSocket(this))
, m_perSecTimer(new QTimer(this))
, m_positionCache(500)
, m_testing(enableTesting)
{
}
PositionReceiver::~PositionReceiver()
{
close();
}
bool PositionReceiver::bind(QHostAddress address, quint16 port, QHostAddress multicastGroup)
{
if (address.isNull())
return false;
if (m_socket->state() == QAbstractSocket::ConnectingState
|| m_socket->state() == QAbstractSocket::ConnectedState)
{
m_socket->disconnectFromHost();
}
if (m_socket->state() == QAbstractSocket::BoundState)
{
m_socket->close();
}
if (!m_socket->bind(address, port))
return false;
if (!multicastGroup.isNull())
{
m_socket->joinMulticastGroup(multicastGroup);
m_multicastGroup = multicastGroup;
}
if (!m_perSecTimer->isActive())
{
connect(m_socket, &QUdpSocket::readyRead, this, &PositionReceiver::receivePositions);
connect(m_perSecTimer, &QTimer::timeout, this, &PositionReceiver::updateRate);
m_perSecTimer->start(1000);
}
return true;
}
void PositionReceiver::close()
{
if (!m_multicastGroup.isNull())
{
m_socket->leaveMulticastGroup(m_multicastGroup);
m_multicastGroup.clear();
}
if (m_socket->state() == QAbstractSocket::ConnectingState
|| m_socket->state() == QAbstractSocket::ConnectedState)
{
m_socket->disconnectFromHost();
}
if (m_socket->state() == QAbstractSocket::BoundState)
{
m_socket->close();
}
if (m_perSecTimer->isActive())
{
m_perSecTimer->stop();
disconnect(m_perSecTimer, &QTimer::timeout, this, &PositionReceiver::updateRate);
disconnect(m_socket, &QUdpSocket::readyRead, this, &PositionReceiver::receivePositions);
}
}
void PositionReceiver::updateRate()
{
if (m_nPerSecCounter != m_lastNPerSec)
{
m_lastNPerSec = m_nPerSecCounter;
emit rateChanged(m_lastNPerSec);
}
m_nPerSecCounter = 0;
}
void PositionReceiver::receivePositions()
{
while(m_socket->pendingDatagramSize() > 0)
{
#if defined(SHOW_HASPENDINGDATAGRAMS_BUG)
if (!m_socket->hasPendingDatagrams())
qWarning() << qPrintable("socket->hasPendingDatagrams() false but pendingDatagramSize nonzero (") << m_socket->pendingDatagramSize() << qPrintable(")");
#endif
QByteArray buffer(m_socket->pendingDatagramSize(), (char)0);
m_socket->readDatagram(buffer.data(), buffer.size());
QtConcurrent::run([=] {
::capnp::FlatArrayMessageReader reader(::kj::ArrayPtr<const word>((const word*)buffer.data(), buffer.size()));
L3::Position::Reader pos = reader.getRoot<L3::Position>();
Position newPos(pos.getHeading(), pos.getElevation(),
pos.getLatitude(), pos.getLongitude(),
pos.getHeightAboveEllipsoid(), pos.getRoll());
if (m_testing)
inspectPosition(newPos);
m_positionCache.append(newPos);
emit positionReceived(newPos);
});
m_nPerSecCounter++;
}
}
void PositionReceiver::inspectPosition(const Position &pos)
{
// Don't bother inspecting the first one.
// We can't know which of the two we'll first receive.
if (m_positionCache.isEmpty())
return;
Position expectedPos = m_positionCache.last();
int nextPosAheadBehind = (qFuzzyCompare(expectedPos.heading, 44.0f)) ? 1 : -1;
expectedPos.heading = expectedPos.heading + (nextPosAheadBehind * 11);
expectedPos.elevation = expectedPos.elevation + (nextPosAheadBehind * 11);
expectedPos.latitude = expectedPos.latitude + (nextPosAheadBehind * 11);
expectedPos.longitude = expectedPos.longitude + (nextPosAheadBehind * 11);
expectedPos.heightAboveEllipsoid = expectedPos.heightAboveEllipsoid + (nextPosAheadBehind * 11);
expectedPos.roll = expectedPos.roll + (nextPosAheadBehind * 11);
if (pos != expectedPos)
{
qWarning() << qPrintable("Received pos doesn't match expected. received:") << pos << qPrintable("expected:") << expectedPos;
}
}
| 31.298611 | 164 | 0.658753 | keithel |
a543bf12b8bfb56239611159a144ce6c7d0cd549 | 1,941 | cpp | C++ | aws-cpp-sdk-appstream/source/model/SharedImagePermissions.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-appstream/source/model/SharedImagePermissions.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-appstream/source/model/SharedImagePermissions.cpp | curiousjgeorge/aws-sdk-cpp | 09b65deba03cfbef9a1e5d5986aa4de71bc03cd8 | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/appstream/model/SharedImagePermissions.h>
#include <aws/core/utils/json/JsonSerializer.h>
#include <utility>
using namespace Aws::Utils::Json;
using namespace Aws::Utils;
namespace Aws
{
namespace AppStream
{
namespace Model
{
SharedImagePermissions::SharedImagePermissions() :
m_sharedAccountIdHasBeenSet(false),
m_imagePermissionsHasBeenSet(false)
{
}
SharedImagePermissions::SharedImagePermissions(JsonView jsonValue) :
m_sharedAccountIdHasBeenSet(false),
m_imagePermissionsHasBeenSet(false)
{
*this = jsonValue;
}
SharedImagePermissions& SharedImagePermissions::operator =(JsonView jsonValue)
{
if(jsonValue.ValueExists("sharedAccountId"))
{
m_sharedAccountId = jsonValue.GetString("sharedAccountId");
m_sharedAccountIdHasBeenSet = true;
}
if(jsonValue.ValueExists("imagePermissions"))
{
m_imagePermissions = jsonValue.GetObject("imagePermissions");
m_imagePermissionsHasBeenSet = true;
}
return *this;
}
JsonValue SharedImagePermissions::Jsonize() const
{
JsonValue payload;
if(m_sharedAccountIdHasBeenSet)
{
payload.WithString("sharedAccountId", m_sharedAccountId);
}
if(m_imagePermissionsHasBeenSet)
{
payload.WithObject("imagePermissions", m_imagePermissions.Jsonize());
}
return payload;
}
} // namespace Model
} // namespace AppStream
} // namespace Aws
| 22.835294 | 78 | 0.756826 | curiousjgeorge |
a5470e0033e2faf088392f6744563ef2d0c86f0a | 823 | cpp | C++ | Reverse Engineering/C++/Medium/Abyss/source/index.cpp | Original-Psych0/SweetChallenges | 828cb622a9320abb0676964e595fb2a95525864e | [
"MIT"
] | 2 | 2021-11-27T06:31:22.000Z | 2022-03-25T02:14:41.000Z | Reverse Engineering/C++/Medium/Abyss/source/index.cpp | Original-Psych0/SweetChallenges | 828cb622a9320abb0676964e595fb2a95525864e | [
"MIT"
] | null | null | null | Reverse Engineering/C++/Medium/Abyss/source/index.cpp | Original-Psych0/SweetChallenges | 828cb622a9320abb0676964e595fb2a95525864e | [
"MIT"
] | 1 | 2022-03-25T02:14:42.000Z | 2022-03-25T02:14:42.000Z | //Dependencies
#include <iostream>
//Workspaces
using namespace std;
//Variables
string the_password = "awnrawraw";
//Functions
int adder(){
the_password += "_21n52859112";
return 0;
}
//Main
int main(){
the_password += "a";
the_password += "c";
the_password += "d";
the_password += "f";
the_password += "h";
the_password += "w";
the_password += "ws";
the_password += "rws";
string password;
cout << "\n";
cout << "Password: ";
cin >> password;
adder(); the_password += "42142124952"; the_password += 0x0f + 0x42; the_password += 0x0e + 0x24;
cout << the_password;
if(password == the_password){
cout << "Congratulation! Looks like your really good!";
}else{
cout << "Invalid password!";
}
cout << "\n";
return 0;
} | 18.704545 | 101 | 0.583232 | Original-Psych0 |
a54859cacb068f67bdb9013c387bc1369287231d | 721 | cpp | C++ | example/main.cpp | martin-olivier/dylib | e06af0f3b5c780d35659c54ea3f7aad9ae008494 | [
"MIT"
] | 19 | 2022-01-24T12:42:48.000Z | 2022-03-26T05:37:48.000Z | example/main.cpp | martin-olivier/Dylib | e06af0f3b5c780d35659c54ea3f7aad9ae008494 | [
"MIT"
] | 1 | 2022-03-01T10:09:51.000Z | 2022-03-02T17:16:58.000Z | example/main.cpp | martin-olivier/dylib | e06af0f3b5c780d35659c54ea3f7aad9ae008494 | [
"MIT"
] | 2 | 2022-01-13T02:50:19.000Z | 2022-01-18T04:22:24.000Z | #include <iostream>
#include "dylib.hpp"
int main() {
try {
dylib lib("./dynamic_lib", dylib::extension);
auto adder = lib.get_function<double(double, double)>("adder");
std::cout << adder(5, 10) << std::endl;
auto printer = lib.get_function<void()>("print_hello");
printer();
double pi_value = lib.get_variable<double>("pi_value");
std::cout << pi_value << std::endl;
void *ptr = lib.get_variable<void *>("ptr");
if (ptr == (void *)1) std::cout << 1 << std::endl;
}
catch (const dylib::exception &e) {
std::cerr << e.what() << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | 28.84 | 72 | 0.539528 | martin-olivier |
a549391dbcc1e656f320def31201b10150472bbc | 2,580 | hpp | C++ | ueye.cpp/include/trigger.hpp | fallfromgrace/ueye.cpp | 775069bca16a6eeea5bb8e5dcda347328f8f2f49 | [
"MIT"
] | null | null | null | ueye.cpp/include/trigger.hpp | fallfromgrace/ueye.cpp | 775069bca16a6eeea5bb8e5dcda347328f8f2f49 | [
"MIT"
] | null | null | null | ueye.cpp/include/trigger.hpp | fallfromgrace/ueye.cpp | 775069bca16a6eeea5bb8e5dcda347328f8f2f49 | [
"MIT"
] | null | null | null | #pragma once
#include <stdexcept>
#include "uEye.h"
#include "includes.hpp"
#include "error.hpp"
namespace ids
{
//
enum trigger_mode
{
// trigger is generated by the driver
software,
// trigger is generated by the hardware.
freerun,
// trigger is external, from hi to lo.
hi_lo,
};
namespace detail
{
//
trigger_mode convert_to_trigger(INT trigger)
{
switch (trigger)
{
case IS_SET_TRIGGER_SOFTWARE: return trigger_mode::software;
case IS_SET_TRIGGER_HI_LO: return trigger_mode::hi_lo;
default: throw std::invalid_argument("Invalid argument.");
}
}
//
INT convert_to_ids(trigger_mode mode)
{
switch (mode)
{
case trigger_mode::software: return IS_SET_TRIGGER_SOFTWARE;
case trigger_mode::hi_lo: return IS_SET_TRIGGER_HI_LO;
default: throw std::invalid_argument("Invalid argument.");
}
}
}
//
class trigger_mode_property
{
public:
//
trigger_mode_property(HIDS camera_handle) :
camera_handle(camera_handle)
{
}
// Gets the current trigger mode.
trigger_mode get() const
{
INT result = is_SetExternalTrigger(
this->camera_handle,
IS_GET_EXTERNALTRIGGER);
return detail::convert_to_trigger(result);
}
// Sets the current trigger mode.
void set(trigger_mode value) const
{
INT trigger = detail::convert_to_ids(value);
INT result = is_SetExternalTrigger(
this->camera_handle,
trigger);
detail::throw_on_error(this->camera_handle, result);
}
private:
const HIDS camera_handle;
};
//
class trigger_delay_property
{
public:
//
trigger_delay_property(HIDS camera_handle) :
camera_handle(camera_handle)
{
}
// Gets the current trigger mode.
int32_t get() const
{
INT result = is_SetTriggerDelay(
this->camera_handle,
IS_GET_TRIGGER_DELAY);
return static_cast<int32_t>(result);
}
// Sets the current trigger mode.
void set(int32_t value) const
{
INT result = is_SetTriggerDelay(
this->camera_handle,
static_cast<INT>(value));
detail::throw_on_error(this->camera_handle, result);
}
private:
const HIDS camera_handle;
};
//
class trigger_property
{
public:
//
trigger_property(HIDS camera_handle) :
camera_handle(camera_handle)
{
}
// Gets or sets the trigger delay.
trigger_delay_property delay() const
{
return trigger_delay_property(this->camera_handle);
}
// Gets or sets the trigger mode.
trigger_mode_property mode() const
{
return trigger_mode_property(this->camera_handle);
}
private:
const HIDS camera_handle;
};
} | 18.297872 | 63 | 0.698062 | fallfromgrace |
a54b163236b066236f43f2cc172d628c9bbe95a6 | 9,014 | cpp | C++ | Source/Engine/Resources/tiledMap/tiledSet.cpp | SirRamEsq/LEngine | 24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c | [
"Apache-2.0"
] | 1 | 2020-05-24T14:04:12.000Z | 2020-05-24T14:04:12.000Z | Source/Engine/Resources/tiledMap/tiledSet.cpp | SirRamEsq/LEngine | 24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c | [
"Apache-2.0"
] | 21 | 2017-09-20T13:39:12.000Z | 2018-01-27T22:21:13.000Z | Source/Engine/Resources/tiledMap/tiledSet.cpp | SirRamEsq/LEngine | 24f748a4f9e29cd5d35d012b46e1bc7a2c285f9c | [
"Apache-2.0"
] | null | null | null | #include "tiledSet.h"
#include "../../Kernel.h"
#include "math.h"
TileAnimation::TileAnimation() {
cachedLength = 0;
cachedSize = 0;
}
int TileAnimation::Length() const {
// update cahcedLength if needed
if (frames.size() != cachedSize) {
int totalLength = 0;
for (auto i = frames.begin(); i != frames.end(); i++) {
totalLength += i->length;
}
cachedLength = totalLength;
cachedSize = frames.size();
}
return cachedLength;
}
TiledSet::TiledSet(const std::string &n, const std::string &tex,
const unsigned int tileW, const unsigned int tileH,
GID first, GIDManager *man)
: GIDEnabled(man),
name(n),
textureName(tex),
tileWidth(tileW),
tileHeight(tileH) {
Init(first, man);
}
TiledSet::TiledSet(const TiledSet &rhs, GIDManager *g)
: GIDEnabled(g),
name(rhs.name),
textureName(rhs.textureName),
tileWidth(rhs.tileWidth),
tileHeight(rhs.tileHeight) {
Init(rhs.GetFirstGID(), g);
transparentColor = rhs.transparentColor;
tileAnimations = rhs.tileAnimations;
// tileHMAPs = rhs.tileHMAPs;
}
void TiledSet::Init(GID first, GIDManager *man) {
try {
LoadTexture();
} catch (LEngineFileException fe) {
std::stringstream ss;
ss << fe.what() << "\n Filename is " << fe.fileName;
LOG_INFO(ss.str());
initializationOK = false;
return;
}
if (texture == NULL) {
LOG_INFO("[C++; TiledSet Constructor] Couldn't load texture from name " +
textureName);
}
tilesWide = texture->GetWidth() / tileWidth;
tilesHigh = texture->GetHeight() / tileHeight;
tilesTotal = tilesWide * tilesHigh;
SetFirstGID(first);
SetLastGID(first + tilesTotal -
1); // Need to subtract one, as the firstGID counts as an index
for (GID id = GetFirstGID(); id <= GetLastGID(); id++) {
LoadHeightMaps(id);
}
man->NewRange(GetFirstGID(), GetLastGID(), this);
initializationOK = true;
}
bool TiledSet::ContainsTile(GID id) const {
if ((id >= GetFirstGID()) and (id <= (GetFirstGID() + tilesTotal))) {
return true;
}
return false;
}
void TiledSet::LoadTexture() {
texture = K_TextureMan.GetItem(textureName);
if (texture == NULL) {
K_TextureMan.LoadItem(textureName, textureName);
texture = K_TextureMan.GetItem(textureName);
if (texture == NULL) {
throw LEngineFileException("Couldn't load texture" + textureName,
Log::typeDefault);
}
}
}
void TiledSet::GetTextureCoordinatesFromGID(GID id, float &left, float &right,
float &top, float &bottom) const {
if ((ContainsTile(id) == false) or (initializationOK == false)) {
left = right = top = bottom = 0.0f;
return;
}
GID indexValue = id - GetFirstGID();
unsigned int x = 0;
unsigned int y = 0;
while (indexValue >= tilesWide) {
y += 1;
indexValue -= tilesWide;
}
x = indexValue;
// Get Top Left
float texX = (float)(x * 16) / (float)(texture->GetWidth());
float texY = (float)(y * 16) / (float)(texture->GetHeight());
left = texX;
top = texY;
// Get Bottom Right
texX = (float)((x * 16) + 16) / (float)(texture->GetWidth());
texY = (float)((y * 16) + 16) / (float)(texture->GetHeight());
right = texX;
bottom = texY;
}
Rect TiledSet::GetTextureRectFromGID(GID id) const {
if (ContainsTile(id) == false) {
return Rect(0, 0, 0, 0);
}
GID indexValue = id - GetFirstGID();
unsigned int x = 0;
unsigned int y = 0;
while (indexValue >= tilesWide) {
y += 1;
indexValue -= tilesWide;
}
x = indexValue;
Rect returnVal(x * 16, y * 16, 16, 16);
return returnVal; // posX, posY, TileWidth, TileHeight
}
void TiledSet::LoadHeightMaps(GID id) {
if (texture == NULL) {
return;
}
Rect coord = GetTextureRectFromGID(id);
int8_t hHMap[16] = {0};
int8_t vHMap[16] = {0};
if ((coord.w != 16) or (coord.h != 16)) {
RSC_Heightmap hmap(hHMap, vHMap);
tileHMAPs[id] = hmap;
return;
}
int xit = coord.x;
int yit = coord.y;
// First, figure out the origin of the image by comparing how many non alpha
// pixels there are between opposite sides
// ie. if there are more solid pixels on the right than the left, the origin
// is at the right
int topsolid = 0;
int bottomsolid = 0;
int leftsolid = 0;
int rightsolid = 0;
int8_t hmapValue = 0;
bool solid = false;
bool topHit = false;
bool bottomHit = false;
bool leftHit = false;
bool rightHit = false;
// Figure out what pixels are visible along each border
for (; xit < coord.GetRight(); xit++) {
// std::stringstream ss;
// ss << "Right: " << coord.GetRight() << "Left: " << coord.GetLeft() <<
// "Top: " << coord.GetTop() << "Bottom: " << coord.GetBottom();
// LOG_INFO(ss.str());
if (texture->GetPixelAlpha(xit, coord.GetTop()) == 255) { // top of image
topsolid += 1;
topHit = true;
}
if (texture->GetPixelAlpha(xit, coord.GetBottom() - 1) ==
255) { // bottom of image
bottomsolid += 1;
bottomHit = true;
}
if ((topHit) and (bottomHit)) {
hHMap[(int)round(xit - coord.x)] = 16;
// the height map was initialized to 0, this sets up the height map if top
// and bottom solid are equal
}
topHit = false;
bottomHit = false;
}
for (; yit < coord.GetBottom(); yit++) {
if (texture->GetPixelAlpha(coord.GetLeft(), yit) == 255) { // left of image
leftsolid += 1;
leftHit = true;
}
if (texture->GetPixelAlpha(coord.GetRight() - 1, yit) ==
255) { // right of image
rightsolid += 1;
rightHit = true;
}
if ((leftHit) and (rightHit)) {
vHMap[(int)round(yit - coord.y)] = 16;
// the height map was initialized to 0, this sets up the height map if top
// and bottom solid are equal
}
leftHit = false;
rightHit = false;
}
// if top and bottom solid are equal, the height map is already set up
if (topsolid != bottomsolid) {
for (unsigned int i = 0; i <= 15; i++) {
hmapValue = 0; // Reset hmap value for every new x value
for (unsigned int ii = 0; ii <= 15; ii++) {
// origin is at the bottom
// Check for alpha values starting from the bottom up
if (topsolid < bottomsolid) {
solid = (texture->GetPixelAlpha(i + coord.x,
coord.GetBottom() - ii - 1) == 255);
if (solid) {
hmapValue++;
} else {
break;
}
}
// origin is at the Top
// Check for alpha values starting from the top down
else if (topsolid > bottomsolid) {
solid =
(texture->GetPixelAlpha(i + coord.x, coord.GetTop() + ii) == 255);
if (solid) {
hmapValue++;
} else {
break;
}
}
}
hHMap[i] = hmapValue;
}
}
// if left and right solid are equal, the height map is already set up
if (leftsolid != rightsolid) {
for (unsigned int i = 0; i <= 15; i++) {
hmapValue = 0; // Reset hmap value for every new x value
for (unsigned int ii = 0; ii <= 15; ii++) {
// origin is at the right
// Check for alpha values starting from the right to the left
if (leftsolid < rightsolid) {
solid = (texture->GetPixelAlpha(coord.GetRight() - ii - 1,
i + coord.y) == 255);
if (solid) {
hmapValue++;
} else {
break;
}
}
// origin is at the left
// Check for alpha values starting from the left to right
else {
solid = (texture->GetPixelAlpha(coord.GetLeft() + ii, i + coord.y) ==
255);
if (solid) {
hmapValue++;
} else {
break;
}
}
}
vHMap[i] = hmapValue;
}
}
RSC_Heightmap hmap(hHMap, vHMap);
tileHMAPs[id] = hmap;
}
std::string TiledSet::GetTileProperty(GID id,
const std::string &property) const {
auto i = tileProperties.find(id);
if (i == tileProperties.end()) {
return "";
}
auto propertyIterator = i->second.find(property);
if (propertyIterator == i->second.end()) {
return "";
}
return std::get<1>(propertyIterator->second);
}
void TiledSet::AddTileAnimation(GID id, TileAnimation animation) {
auto it = tileAnimations.find(id);
if (it != tileAnimations.end()) {
std::stringstream ss;
ss << "Tile Animation for GID " << id << " already exists!";
LOG_ERROR(ss.str());
}
tileAnimations[id] = animation;
}
const std::map<GID, TileAnimation> *TiledSet::GetTileAnimations() const {
return &tileAnimations;
}
const TileAnimation *TiledSet::GetTileAnimation(GID id) {
auto it = tileAnimations.find(id);
if (it != tileAnimations.end()) {
return &it->second;
}
return NULL;
}
| 28.080997 | 80 | 0.577546 | SirRamEsq |
a54fdaae001d52c4982090fb98c07f1ee0d67862 | 12,524 | cc | C++ | src/mesh/mesh_logical/test/test_mesh_logical.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 37 | 2017-04-26T16:27:07.000Z | 2022-03-01T07:38:57.000Z | src/mesh/mesh_logical/test/test_mesh_logical.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 494 | 2016-09-14T02:31:13.000Z | 2022-03-13T18:57:05.000Z | src/mesh/mesh_logical/test/test_mesh_logical.cc | fmyuan/amanzi | edb7b815ae6c22956c8519acb9d87b92a9915ed4 | [
"RSA-MD"
] | 43 | 2016-09-26T17:58:40.000Z | 2022-03-25T02:29:59.000Z | /* -*- mode: c++; c-default-style: "google"; indent-tabs-mode: nil -*- */
#include <UnitTest++.h>
#include <mpi.h>
#include <iostream>
#include "Teuchos_RCP.hpp"
#include "AmanziComm.hh"
#include "RegionEnumerated.hh"
#include "MeshLogical.hh"
#include "MeshLogicalFactory.hh"
#include "Geometry.hh"
#include "MeshLogicalAudit.hh"
#include "demo_mesh.hh"
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
bool POINT_CLOSE(const Point& p1, const Point& p2) {
CHECK_EQUAL(p1.dim(), p2.dim());
CHECK_CLOSE(p1[0], p2[0], 1.e-8);
CHECK_CLOSE(p1[1], p2[1], 1.e-8);
if (p1.dim() > 2) CHECK_CLOSE(p1[2], p2[2], 1.e-8);
return norm(p1 - p2) < 1.e-8;
}
#define CHECK_POINT_CLOSE(p1, p2) CHECK(POINT_CLOSE(p1,p2))
void
test_segment_regular(const Teuchos::RCP<const Amanzi::AmanziMesh::Mesh>& m,
bool test_region) {
MeshLogicalAudit audit(m, std::cout);
CHECK(!audit.Verify());
CHECK_EQUAL(4, m->num_entities(CELL, Parallel_type::ALL));
CHECK_EQUAL(5, m->num_entities(FACE, Parallel_type::ALL));
for (int i=0; i!=4; ++i) {
CHECK_EQUAL(0.25, m->cell_volume(i));
Entity_ID_List faces;
std::vector<int> dirs;
std::vector<Point> bisectors;
m->cell_get_faces_and_dirs(i, &faces, &dirs);
CHECK_EQUAL(2, faces.size());
CHECK_EQUAL(i, faces[0]);
CHECK_EQUAL(i+1, faces[1]);
CHECK_EQUAL(2, dirs.size());
CHECK_EQUAL(1, dirs[0]);
CHECK_EQUAL(-1, dirs[1]);
faces.clear();
m->cell_get_faces_and_bisectors(i, &faces, &bisectors);
CHECK_EQUAL(2, faces.size());
CHECK_EQUAL(i, faces[0]);
CHECK_EQUAL(i+1, faces[1]);
CHECK_EQUAL(2, bisectors.size());
CHECK_POINT_CLOSE(Point(0.125, 0., 0.), bisectors[0]);
CHECK_POINT_CLOSE(Point(-0.125, 0., 0.), bisectors[1]);
}
for (int i=0; i!=5; ++i) {
CHECK_EQUAL(1.0, m->face_area(0));
auto normal = m->face_normal(i);
CHECK_POINT_CLOSE(Point(1.,0.,0.), normal);
Entity_ID_List cells;
m->face_get_cells(i, Parallel_type::ALL, &cells);
if (i == 0) {
CHECK_EQUAL(1, cells.size());
CHECK_EQUAL(0, cells[0]);
} else if (i == 4) {
CHECK_EQUAL(1, cells.size());
CHECK_EQUAL(3, cells[0]);
} else {
CHECK_EQUAL(2, cells.size());
CHECK_EQUAL(i-1, cells[0]);
CHECK_EQUAL(i, cells[1]);
}
}
if (test_region) {
// check regions
CHECK_EQUAL(4, m->get_set_size("myregion", CELL, Parallel_type::ALL));
CHECK_EQUAL(0, m->get_set_size("myregion", FACE, Parallel_type::ALL));
Entity_ID_List set_ents;
m->get_set_entities("myregion", CELL, Parallel_type::ALL, &set_ents);
CHECK_EQUAL(0, set_ents[0]);
CHECK_EQUAL(2, set_ents[2]);
}
}
void
test_segment_irregular(const Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& m,
bool test_region) {
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
MeshLogicalAudit audit(m, std::cout);
CHECK(!audit.Verify());
Teuchos::RCP<const GeometricModel> gm_c = m->geometric_model();
Teuchos::RCP<GeometricModel> gm = Teuchos::rcp_const_cast<GeometricModel>(gm_c);
Entity_ID_List ents;
ents.push_back(0);
ents.push_back(3);
Teuchos::RCP<Region> enum_rgn =
Teuchos::rcp(new RegionEnumerated("myregion", 0, "CELL", ents));
gm->AddRegion(enum_rgn);
CHECK_EQUAL(2, m->get_set_size("myregion", CELL, Parallel_type::ALL));
CHECK_EQUAL(0, m->get_set_size("myregion", FACE, Parallel_type::ALL));
if (test_region) {
Entity_ID_List set_ents;
m->get_set_entities("myregion", CELL, Parallel_type::ALL, &set_ents);
CHECK_EQUAL(0, set_ents[0]);
CHECK_EQUAL(3, set_ents[1]);
}
}
void
test_Y(const Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& m,
bool test_region) {
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
MeshLogicalAudit audit(m, std::cout);
CHECK(!audit.Verify());
CHECK_EQUAL(11, m->num_entities(CELL, Parallel_type::ALL));
CHECK_EQUAL(15, m->num_entities(FACE, Parallel_type::ALL));
// surface
Point zero(0.,0.,0.);
CHECK_CLOSE(0., norm(zero-m->face_centroid(0)), 1.e-6);
// branch point
Point branch(0.,0.,-2.5);
std::cout << "branch = " << branch << std::endl;
std::cout << "centroid = " << m->cell_centroid(2) << std::endl;
CHECK_CLOSE(0., norm(branch - m->cell_centroid(2)), 1.e-6);
branch[2] = -3.0;
Entity_ID_List branch_faces;
std::vector<int> dirs;
m->cell_get_faces_and_dirs(2, &branch_faces, &dirs);
CHECK_EQUAL(5, branch_faces.size());
for (int i=0; i!=3; ++i)
CHECK_CLOSE(1.e-4, m->cell_volume(i), 1.e-8);
for (int i=3; i!=11; ++i)
CHECK_CLOSE(.75*0.25e-4, m->cell_volume(i), 1.e-8);
for (int i=0; i!=3; ++i)
CHECK_CLOSE(1.e-4, m->face_area(i), 1.e-8);
for (int i=3; i!=15; ++i)
CHECK_CLOSE(.25e-4, m->face_area(i), 1.e-8);
if (test_region) {
CHECK_EQUAL(3, m->get_set_size("coarse_root", CELL, Parallel_type::ALL));
CHECK_EQUAL(8, m->get_set_size("fine_root", CELL, Parallel_type::ALL));
}
}
void
test_2Y(const Teuchos::RCP<Amanzi::AmanziMesh::Mesh>& m,
bool test_region) {
using namespace Amanzi::AmanziMesh;
using namespace Amanzi::AmanziGeometry;
MeshLogicalAudit audit(m, std::cout);
CHECK(!audit.Verify());
CHECK_EQUAL(3, m->num_entities(CELL, Parallel_type::ALL));
CHECK_EQUAL(5, m->num_entities(FACE, Parallel_type::ALL));
Entity_ID_List branch_faces;
std::vector<int> dirs;
std::vector<Point> bisectors;
double r22 = sqrt(2.0) / 2.0;
// check topology/geometry
std::cout << " Checking topology/geometry" << std::endl;
// cell 0
m->cell_get_faces_and_dirs(0, &branch_faces, &dirs);
CHECK_EQUAL(3, branch_faces.size());
CHECK_EQUAL(0, branch_faces[0]);
CHECK_EQUAL(1, branch_faces[1]);
CHECK_EQUAL(3, branch_faces[2]);
CHECK_EQUAL(3, dirs.size());
CHECK_CLOSE(1, dirs[0], 1.e-8);
CHECK_CLOSE(-1, dirs[1], 1.e-8);
CHECK_CLOSE(-1, dirs[2], 1.e-8);
CHECK_CLOSE(4.0, m->cell_volume(0), 1.e-8);
m->cell_get_faces_and_bisectors(0, &branch_faces, &bisectors);
CHECK_EQUAL(3, branch_faces.size());
CHECK_EQUAL(0, branch_faces[0]);
CHECK_EQUAL(1, branch_faces[1]);
CHECK_EQUAL(3, branch_faces[2]);
CHECK_EQUAL(3, bisectors.size());
CHECK_POINT_CLOSE(Point(1.0, 0., 0.), bisectors[0]);
CHECK_POINT_CLOSE(Point(-1.0, 0., 0.), bisectors[1]);
CHECK_POINT_CLOSE(Point(-1.0, 0., 0.), bisectors[2]);
// cell 1
m->cell_get_faces_and_dirs(1, &branch_faces, &dirs);
CHECK_EQUAL(2, branch_faces.size());
CHECK_EQUAL(1, branch_faces[0]);
CHECK_EQUAL(2, branch_faces[1]);
CHECK_EQUAL(2, dirs.size());
CHECK_CLOSE(1, dirs[0], 1.e-8);
CHECK_CLOSE(-1, dirs[1], 1.e-8);
CHECK_CLOSE(1.0, m->cell_volume(1), 1.e-8);
m->cell_get_faces_and_bisectors(1, &branch_faces, &bisectors);
CHECK_EQUAL(2, branch_faces.size());
CHECK_EQUAL(1, branch_faces[0]);
CHECK_EQUAL(2, branch_faces[1]);
CHECK_EQUAL(2, bisectors.size());
CHECK_POINT_CLOSE(Point(r22/2., r22/2, 0.), bisectors[0]);
CHECK_POINT_CLOSE(Point(-r22/2., -r22/2, 0.), bisectors[1]);
// cell 2
m->cell_get_faces_and_dirs(2, &branch_faces, &dirs);
CHECK_EQUAL(2, branch_faces.size());
CHECK_EQUAL(3, branch_faces[0]);
CHECK_EQUAL(4, branch_faces[1]);
CHECK_EQUAL(2, dirs.size());
CHECK_CLOSE(1, dirs[0], 1.e-8);
CHECK_CLOSE(-1, dirs[1], 1.e-8);
CHECK_CLOSE(1.0, m->cell_volume(2), 1.e-8);
m->cell_get_faces_and_bisectors(2, &branch_faces, &bisectors);
CHECK_EQUAL(2, branch_faces.size());
CHECK_EQUAL(3, branch_faces[0]);
CHECK_EQUAL(4, branch_faces[1]);
CHECK_EQUAL(2, bisectors.size());
CHECK_POINT_CLOSE(Point(r22/2., -r22/2, 0.), bisectors[0]);
CHECK_POINT_CLOSE(Point(-r22/2., r22/2, 0.), bisectors[1]);
// faces
Amanzi::AmanziGeometry::Point f0_normal = m->face_normal(0);
CHECK_POINT_CLOSE(Point(2,0,0), f0_normal);
CHECK_CLOSE(2.0, m->face_area(0), 1.e-8);
Amanzi::AmanziGeometry::Point f1_normal = m->face_normal(1);
CHECK_POINT_CLOSE(Point(1,0,0), f1_normal);
CHECK_CLOSE(1.0, m->face_area(1), 1.e-8);
Amanzi::AmanziGeometry::Point f2_normal = m->face_normal(2);
CHECK_POINT_CLOSE(Point(sqrt(2)/2,sqrt(2)/2,0), f2_normal);
CHECK_CLOSE(1.0, m->face_area(2), 1.e-8);
Amanzi::AmanziGeometry::Point f3_normal = m->face_normal(3);
CHECK_POINT_CLOSE(Point(1,0,0), f3_normal);
CHECK_CLOSE(1.0, m->face_area(3), 1.e-8);
Amanzi::AmanziGeometry::Point f4_normal = m->face_normal(4);
CHECK_POINT_CLOSE(Point(sqrt(2)/2, -sqrt(2)/2,0), f4_normal);
CHECK_CLOSE(1.0, m->face_area(4), 1.e-8);
// check centroids
std::cout << " Checking centroids" << std::endl;
CHECK_POINT_CLOSE(Point(2.,0.,0.), m->face_centroid(0));
CHECK_POINT_CLOSE(Point(1.,0.,0.), m->cell_centroid(0));
CHECK_POINT_CLOSE(Point(0.,0.,0.), m->face_centroid(1));
CHECK_POINT_CLOSE(Point(-r22/2.,-r22/2.,0.), m->cell_centroid(1));
CHECK_POINT_CLOSE(Point(-r22,-r22,0.), m->face_centroid(2));
CHECK_POINT_CLOSE(Point(0.,0.,0.), m->face_centroid(3));
CHECK_POINT_CLOSE(Point(-r22/2.,r22/2.,0.), m->cell_centroid(2));
CHECK_POINT_CLOSE(Point(-r22,r22,0.), m->face_centroid(4));
if (test_region) {
CHECK_EQUAL(1, m->get_set_size("coarse_root", CELL, Parallel_type::ALL));
CHECK_EQUAL(2, m->get_set_size("fine_root", CELL, Parallel_type::ALL));
}
}
// Tests the construction process, ensures it does not crash.
TEST(MESH_LOGICAL_CONSTRUCTION)
{
using namespace Amanzi::AmanziMesh;
std::cout << std::endl
<< "TEST: MeshLogical Construction" << std::endl
<< "------------------------------" << std::endl;
auto m = Amanzi::Testing::demoMeshLogicalSegmentRegularManual();
}
// Evaulates the manually constructed mesh.
TEST(MESH_LOGICAL_SEGMENT_REGULAR_MANUAL)
{
std::cout << std::endl
<< "TEST: MeshLogical single segment, manual construction" << std::endl
<< "-----------------------------------------------------" << std::endl;
test_segment_regular(Amanzi::Testing::demoMeshLogicalSegmentRegularManual(), false);
}
// Evaulates the manually constructed mesh.
TEST(MESH_LOGICAL_SEGMENT_REGULAR_XML)
{
std::cout << std::endl
<< "TEST: MeshLogical single segment, xml construction" << std::endl
<< "-----------------------------------------------------" << std::endl;
test_segment_regular(Amanzi::Testing::demoMeshLogicalFromXML("regular"), false);
}
// Evaluates an irregularly space mesh
TEST(MESH_LOGICAL_SEGMENT_IRREGULAR_WITH_SETS)
{
std::cout << std::endl
<< "TEST: MeshLogical single segment, deformed" << std::endl
<< "-----------------------------------------------------" << std::endl;
test_segment_irregular(Amanzi::Testing::demoMeshLogicalSegmentIrregularManual(), true);
}
// Evaluates a 2Y-mesh
TEST(MESH_LOGICAL_2Y_XML_WITH_SETS)
{
std::cout << std::endl
<< "TEST: MeshLogical 2Y, from XML" << std::endl
<< "-----------------------------------------------------" << std::endl;
test_2Y(Amanzi::Testing::demoMeshLogicalFromXML("logical mesh 2Y"), true);
}
// Evaluates a Y-mesh
TEST(MESH_LOGICAL_Y)
{
std::cout << std::endl
<< "TEST: MeshLogical Y, manual construction" << std::endl
<< "-----------------------------------------------------" << std::endl;
auto m = Amanzi::Testing::demoMeshLogicalYManual();
test_Y(m, true);
}
// Evaluates a Y-mesh
TEST(MESH_LOGICAL_Y_XML_WITH_SETS)
{
std::cout << std::endl
<< "TEST: MeshLogical Y, from XML" << std::endl
<< "-----------------------------------------------------" << std::endl;
test_Y(Amanzi::Testing::demoMeshLogicalFromXML("logical mesh Y"), true);
}
// Evaluates a Y-mesh embedded in another mesh
TEST(MESH_EMBEDDED_Y)
{
std::cout << std::endl
<< "TEST: MeshLogical Y, embedded in background mesh" << std::endl
<< "-----------------------------------------------------" << std::endl;
auto m = Amanzi::Testing::demoMeshLogicalYEmbedded();
Amanzi::AmanziMesh::MeshLogicalAudit audit(m, std::cout);
CHECK(!audit.Verify());
}
// subgrid model
TEST(MESH_SUBGRID_VARIABLE_TAU)
{
std::cout << std::endl
<< "TEST: subgrid mesh in travel time space" << std::endl
<< "-----------------------------------------------------" << std::endl;
auto m = Amanzi::Testing::demoMeshLogicalFromXML("subgrid mesh");
Amanzi::AmanziMesh::MeshLogicalAudit audit(m, std::cout);
CHECK(!audit.Verify());
}
| 31.706329 | 89 | 0.633424 | fmyuan |
a5501944071accdf8d67cebf61a60eeb19fa0483 | 20,101 | inl | C++ | extensions/winrt/_winrt/include/convert.inl | ms-iot/python | a8f8fba1214289572713520f83409762a4446fea | [
"BSD-3-Clause"
] | 70 | 2015-06-20T17:59:24.000Z | 2021-05-03T02:01:49.000Z | extensions/winrt/_winrt/include/convert.inl | ms-iot/python | a8f8fba1214289572713520f83409762a4446fea | [
"BSD-3-Clause"
] | 16 | 2015-06-11T14:57:43.000Z | 2016-12-03T00:22:13.000Z | extensions/winrt/_winrt/include/convert.inl | ms-iot/python | a8f8fba1214289572713520f83409762a4446fea | [
"BSD-3-Clause"
] | 36 | 2015-05-15T20:30:44.000Z | 2020-11-14T19:31:40.000Z | #pragma once
#include "Python.h"
#include "ExceptionGuard.h"
#include "Windows.Foundation.h"
#include <inspectable.h>
inline PyObjectPtr PyUnicode_FromPlatformString(Platform::String^ str)
{
if (!str)
{
return PyObjectPtr::CreateAttach(PyUnicode_FromUnicode(NULL, 0));
}
return PyObjectPtr::CreateAttach(PyUnicode_FromUnicode(str->Data(), str->Length()));
}
inline Platform::String^ PlatformString_FromPyObject(PyObjectPtr obj)
{
if (obj.Get() == Py_None)
{
// None is translated into Empty string
return ref new Platform::String();
}
else if (PyUnicode_Check(obj.Get()))
{
Py_ssize_t length;
auto wstr = PyUnicode_AsUnicodeAndSize(obj.Get(), &length);
if (length <= UINT32_MAX)
{
return ref new Platform::String(wstr, static_cast<unsigned int>(length));
}
// fallthrough
}
throw PythonException::CreateFromFormat(PyExc_TypeError, L"cannot convert '%s' of type '%s' to string", "(OO)", obj.Get(), obj.GetType().Get());
}
inline __declspec(noreturn) void ThrowConversionError(Platform::Object^ obj)
{
throw PythonException::CreateFromFormat(PyExc_TypeError, L"cannot convert '%s' of type '%s' to python type", "(uu)", obj->ToString()->Data(), obj->GetType()->FullName->Data());
}
inline __declspec(noreturn) void ThrowConversionError(PyObjectPtr obj)
{
throw PythonException::CreateFromFormat(PyExc_TypeError, L"cannot convert '%s' of type '%s' to WinRT type", "(OO)", obj.Get(), obj.GetType().Get());
}
inline Platform::Object^ PlatformBuiltInType_FromPyObject(PyObjectPtr obj)
{
if (obj.GetType().Get() == (PyObject*)&_PyNone_Type)
{
return nullptr;
}
else if (PyBool_Check(obj.Get()))
{
return obj.Get() == Py_True;
}
else if (PyUnicode_Check(obj.Get()))
{
return PlatformString_FromPyObject(obj.Get());
}
else if (PyLong_Check(obj.Get()))
{
int overflow = 0;
Platform::Object^ value = PyLong_AsLongLong(obj.Get());
// Check for overflow
if (PyErr_Occurred())
{
throw PythonException();
}
return value;
}
else if (PyFloat_Check(obj.Get()))
{
Platform::Object^ value = PyFloat_AsDouble(obj.Get());
return value;
}
else if (PyBytes_Check(obj.Get()))
{
Py_ssize_t size = PyBytes_Size(obj.Get());
if (size > UINT32_MAX)
{
ThrowConversionError(obj);
}
return ref new Platform::Array<byte>((unsigned char*)PyBytes_AsString(obj.Get()), static_cast<unsigned int>(size));
}
else if (PyByteArray_Check(obj.Get()))
{
Py_ssize_t size = PyByteArray_Size(obj.Get());
if (size > UINT32_MAX)
{
ThrowConversionError(obj);
}
return ref new Platform::Array<byte>((unsigned char*)PyByteArray_AsString(obj.Get()), static_cast<unsigned int>(size));
}
else if (PyList_Check(obj.Get()))
{
auto pySize = PyList_GET_SIZE(obj.Get());
if (pySize == 0 || pySize > UINT_MAX)
{
ThrowConversionError(obj);
}
unsigned int size = static_cast<unsigned int>(pySize);
PyObjectPtr firstItem = PyList_GetItem(obj.Get(), 0); // PyList_GetItem() returns borrowed reference
auto itemType = firstItem.GetType();
for (unsigned int i = 0; i < size; i++)
{
PyObjectPtr item = PyList_GetItem(obj.Get(), i); // PyList_GetItem() returns borrowed reference
if (itemType.Get() != item.GetType().Get())
{
ThrowConversionError(obj);
}
}
if (PyBool_Check(firstItem.Get()))
{
auto arr = ref new Platform::Array<bool>(size);
for (unsigned int i = 0; i < size; i++)
{
arr[i] = (PyList_GetItem(obj.Get(), i) == Py_True);
}
return arr;
}
else if (PyUnicode_Check(firstItem.Get()))
{
auto arr = ref new Platform::Array<Platform::String^>(size);
for (unsigned int i = 0; i < size; i++)
{
arr[i] = PlatformString_FromPyObject(PyList_GetItem(obj.Get(), i));
}
return arr;
}
else if (PyLong_Check(firstItem.Get()))
{
auto arr = ref new Platform::Array<long long>(size);
for (unsigned int i = 0; i < size; i++)
{
arr[i] = PyLong_AsLongLong(PyList_GetItem(obj.Get(), i));
}
return arr;
}
else if (PyFloat_Check(firstItem.Get()))
{
auto arr = ref new Platform::Array<double>(size);
for (unsigned int i = 0; i < size; i++)
{
arr[i] = PyFloat_AsDouble(PyList_GetItem(obj.Get(), i));
}
return arr;
}
}
ThrowConversionError(obj);
}
inline PyObjectPtr PyObject_FromBuiltInType(bool val)
{
auto result = PyObjectPtr::CreateAttach(PyBool_FromLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(unsigned char val)
{
auto result = PyObjectPtr::CreateAttach(PyBytes_FromStringAndSize((char*)&val, 1));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(wchar_t val)
{
auto result = PyObjectPtr::CreateAttach(PyUnicode_FromWideChar(&val, 1));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(short val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(int val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(long val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(long long val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromLongLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(unsigned short val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromUnsignedLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(unsigned int val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromUnsignedLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(unsigned long val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromUnsignedLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(unsigned long long val)
{
auto result = PyObjectPtr::CreateAttach(PyLong_FromUnsignedLongLong(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(float val)
{
auto result = PyObjectPtr::CreateAttach(PyFloat_FromDouble((double)val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(double val)
{
auto result = PyObjectPtr::CreateAttach(PyFloat_FromDouble(val));
if (!result)
{
throw PythonException();
}
return result;
}
inline PyObjectPtr PyObject_FromBuiltInType(HSTRING val)
{
UINT32 length = 0;
auto wstr = ::WindowsGetStringRawBuffer(val, &length);
auto result = PyObjectPtr::CreateAttach(PyUnicode_FromUnicode(wstr, length));
if (!result)
{
throw PythonException();
}
return result;
}
template <typename Type>
inline PyObjectPtr PyObject_FromBuiltInArray(Type* val, size_t size)
{
auto retval = PyObjectPtr::CreateAttach(PyList_New(size));
if (!retval)
{
throw PythonException();
}
for (size_t i = 0; i < size; i++)
{
auto item = PyObject_FromBuiltInType(val[i]);
// PyList_SetItem() steals the item reference
if (PyList_SetItem(retval.Get(), i, item.Detach()) != 0)
{
// Set item failed
throw PythonException();
}
}
return retval;
}
inline PyObjectPtr PyObject_FromPlatfromBuiltInType(Platform::Object^ obj)
{
if (obj == nullptr)
{
return Py_None;
}
using namespace ::ABI::Windows::Foundation;
using namespace ::Microsoft::WRL;
ComPtr<IPropertyValue> spPropertyValue;
ComPtr<IInspectable> spInspectable = reinterpret_cast<IInspectable*>(obj);
if (FAILED(spInspectable.As<IPropertyValue>(&spPropertyValue)))
{
ThrowConversionError(obj);
}
PropertyType type;
if (FAILED(spPropertyValue->get_Type(&type)))
{
ThrowConversionError(obj);
}
PyObjectPtr retval;
switch (type)
{
case PropertyType::PropertyType_Boolean:
{
boolean val;
if (FAILED(spPropertyValue->GetBoolean(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val != 0);
}
break;
case PropertyType::PropertyType_Char16:
{
wchar_t val;
if (FAILED(spPropertyValue->GetChar16(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_Int16:
{
short val;
if (FAILED(spPropertyValue->GetInt16(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_Int32:
{
int val;
if (FAILED(spPropertyValue->GetInt32(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_Int64:
{
long long val;
if (FAILED(spPropertyValue->GetInt64(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_Single:
{
float val;
if (FAILED(spPropertyValue->GetSingle(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_Double:
{
double val;
if (FAILED(spPropertyValue->GetDouble(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_UInt16:
{
unsigned short val;
if (FAILED(spPropertyValue->GetUInt16(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_UInt32:
{
unsigned int val;
if (FAILED(spPropertyValue->GetUInt32(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_UInt64:
{
unsigned long long val;
if (FAILED(spPropertyValue->GetUInt64(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_String:
{
Microsoft::WRL::Wrappers::HString val;
if (FAILED(spPropertyValue->GetString(val.GetAddressOf())))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val.Get());
}
break;
case PropertyType::PropertyType_UInt8: // byte
{
unsigned char val;
if (FAILED(spPropertyValue->GetUInt8(&val)))
{
ThrowConversionError(obj);
}
return PyObject_FromBuiltInType(val);
}
break;
case PropertyType::PropertyType_BooleanArray:
{
UINT32 size;
boolean* arr;
if (FAILED(spPropertyValue->GetBooleanArray(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
auto retval = PyObjectPtr::CreateAttach(PyList_New(size));
if (!retval)
{
throw PythonException();
}
for (size_t i = 0; i < size; i++)
{
auto item = PyObject_FromBuiltInType(arr[i] != 0);
// PyList_SetItem() steals the item reference
if (PyList_SetItem(retval.Get(), i, item.Detach()) != 0)
{
// Set item failed
throw PythonException();
}
}
return retval;
}
break;
case PropertyType::PropertyType_Char16Array:
{
UINT32 size;
WCHAR* arr;
if (FAILED(spPropertyValue->GetChar16Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_Int16Array:
{
UINT32 size;
short* arr;
if (FAILED(spPropertyValue->GetInt16Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_Int32Array:
{
UINT32 size;
int* arr;
if (FAILED(spPropertyValue->GetInt32Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_Int64Array:
{
UINT32 size;
long long* arr;
if (FAILED(spPropertyValue->GetInt64Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_SingleArray:
{
UINT32 size;
float* arr;
if (FAILED(spPropertyValue->GetSingleArray(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_DoubleArray:
{
UINT32 size;
double* arr;
if (FAILED(spPropertyValue->GetDoubleArray(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_UInt16Array:
{
UINT32 size;
unsigned short* arr;
if (FAILED(spPropertyValue->GetUInt16Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_UInt32Array:
{
UINT32 size;
unsigned int* arr;
if (FAILED(spPropertyValue->GetUInt32Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_UInt64Array:
{
UINT32 size;
unsigned long long* arr;
if (FAILED(spPropertyValue->GetUInt64Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyObject_FromBuiltInArray(arr, size);
}
break;
case PropertyType::PropertyType_StringArray:
{
UINT32 size;
HSTRING* arr;
if (FAILED(spPropertyValue->GetStringArray(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHSTRINGHolder(arr, size);
return PyObject_FromBuiltInArray(arr, size);
}
case PropertyType::PropertyType_UInt8Array: // byte
{
UINT32 size;
unsigned char* arr;
if (FAILED(spPropertyValue->GetUInt8Array(&size, &arr)))
{
ThrowConversionError(obj);
}
CoTaskMemoryHolder cleanup(static_cast<void*>(arr));
return PyBytes_FromStringAndSize((char*)arr, size);
}
}
ThrowConversionError(obj);
}
inline Windows::Foundation::Collections::ValueSet^ PyDict_ToValueSet(PyObjectPtr dict)
{
if (!PyDict_Check(dict.Get()))
{
throw PythonException::CreateFromFormat(PyExc_TypeError, L"Cannot convert '%s' (type: '%s') to WinRT ValueSet", "(OO)", dict.Get(), dict.GetType().Get());
}
auto valueSet = ref new Windows::Foundation::Collections::ValueSet();
auto keyValuePairs = PyObjectPtr::CreateAttach(PyDict_Items(dict.Get()));
if (!keyValuePairs)
{
throw PythonException(); // Error already set
}
auto iterator = PyObjectPtr::CreateAttach(PyObject_GetIter(keyValuePairs.Get()));
if (!iterator)
{
throw PythonException(); // Error already set
}
PyObjectPtr keyValuePair;
while (keyValuePair = PyObjectPtr::CreateAttach(PyIter_Next(iterator.Get())))
{
PyObjectPtr key = PyTuple_GET_ITEM(keyValuePair.Get(), 0);
PyObjectPtr value = PyTuple_GET_ITEM(keyValuePair.Get(), 1);
auto platformKey = PlatformString_FromPyObject(key.Get());
auto platformValue = PlatformBuiltInType_FromPyObject(value.Get());
assert(!PyErr_Occurred());
valueSet->Insert(platformKey, platformValue);
}
return valueSet;
}
inline PyObjectPtr PyDict_FromPlatformValueSet(Windows::Foundation::Collections::ValueSet^ valueSet)
{
if (!valueSet)
{
return Py_None;
}
auto dict = PyObjectPtr::CreateAttach(PyDict_New());
for (auto pair : valueSet)
{
auto key = PyUnicode_FromPlatformString(pair->Key);
auto value = PyObject_FromPlatfromBuiltInType(pair->Value);
if (PyObject_SetItem(dict.Get(), key.Get(), value.Get()) == -1)
{
// Insert failed. Python exception is set by PyObject_SetItem()
return nullptr;
}
}
return dict;
}
| 27.200271 | 180 | 0.571215 | ms-iot |
a550d54270f00620cc18cef8367724c4e8ebd5ef | 128 | cpp | C++ | tensorflow-yolo-ios/dependencies/eigen/doc/examples/Tutorial_BlockOperations_colrow.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 27 | 2017-06-07T19:07:32.000Z | 2020-10-15T10:09:12.000Z | tensorflow-yolo-ios/dependencies/eigen/doc/examples/Tutorial_BlockOperations_colrow.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 3 | 2017-08-25T17:39:46.000Z | 2017-11-18T03:40:55.000Z | tensorflow-yolo-ios/dependencies/eigen/doc/examples/Tutorial_BlockOperations_colrow.cpp | initialz/tensorflow-yolo-face-ios | ba74cf39168d0128e91318e65a1b88ce4d65a167 | [
"MIT"
] | 10 | 2017-06-16T18:04:45.000Z | 2018-07-05T17:33:01.000Z | version https://git-lfs.github.com/spec/v1
oid sha256:6eee36fb9361edc0af6f8605621c45995ebc169735c71ca31c82ac7f243142b3
size 390
| 32 | 75 | 0.882813 | initialz |
a555cb2599585abdee7f98b052c1dfc10a30c904 | 1,871 | cpp | C++ | Sid's Contests/LeetCode contests/Virtual Contests/Weekly Contest 244/Determine Whether Matrix Can Be Obtained By Rotation.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 14 | 2021-08-22T18:21:14.000Z | 2022-03-08T12:04:23.000Z | Sid's Contests/LeetCode contests/Virtual Contests/Weekly Contest 244/Determine Whether Matrix Can Be Obtained By Rotation.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 1 | 2021-10-17T18:47:17.000Z | 2021-10-17T18:47:17.000Z | Sid's Contests/LeetCode contests/Virtual Contests/Weekly Contest 244/Determine Whether Matrix Can Be Obtained By Rotation.cpp | Tiger-Team-01/DSA-A-Z-Practice | e08284ffdb1409c08158dd4e90dc75dc3a3c5b18 | [
"MIT"
] | 5 | 2021-09-01T08:21:12.000Z | 2022-03-09T12:13:39.000Z | class Solution {
public:
//OM GAN GANAPATHAYE NAMO NAMAH
//JAI SHRI RAM
//JAI BAJRANGBALI
//AMME NARAYANA, DEVI NARAYANA, LAKSHMI NARAYANA, BHADRE NARAYANA
vector<vector<int>> rotateMatrix(vector<vector<int>> grid)
{
vector<vector<int>> res;
int m = grid.size();
int n = grid[0].size();
for(int i = 0; i < n; i++)
{
vector<int> temp;
for(int j = 0; j < m; j++)
temp.push_back(grid[j][i]);
reverse(temp.begin(), temp.end());
res.push_back(temp);
}
return res;
}
void printMatrix(vector<vector<int>> res)
{
for(int i = 0; i < res.size(); i++)
{
for(int j = 0; j < res[0].size(); j++)
cout << res[i][j] << " ";
cout << endl;
}
}
bool isEqual(vector<vector<int>> mat1, vector<vector<int>> mat2)
{
if(mat1.size() != mat2.size())
return false;
for(int i = 0; i < mat1.size(); i++)
{
for(int j = 0; j < mat1[0].size(); j++)
{
if(mat1[i][j] != mat2[i][j])
return false;
}
}
return true;
}
bool findRotation(vector<vector<int>>& mat, vector<vector<int>>& target) {
vector<vector<int>> mat1 = rotateMatrix(mat);
vector<vector<int>> mat2 = rotateMatrix(mat1);
vector<vector<int>> mat3 = rotateMatrix(mat2);
vector<vector<int>> mat4 = rotateMatrix(mat3);
bool flag1 = isEqual(mat1, target);
bool flag2 = isEqual(mat2, target);
bool flag3 = isEqual(mat3, target);
bool flag4 = isEqual(mat4, target);
bool flag5 = isEqual(mat, target);
if(flag1 || flag2 || flag3 || flag4 || flag5)
return true;
return false;
}
};
| 31.183333 | 78 | 0.490647 | Tiger-Team-01 |
a224bc436814edb111471057f2485c01eb7699b6 | 266 | cpp | C++ | Sandbox/Source/Thread/IETThread.cpp | Clymiaru/GDPARCM_Sandbox | 21d6d7ccaef1b03a4d631e757cb824341e84e5d6 | [
"MIT"
] | null | null | null | Sandbox/Source/Thread/IETThread.cpp | Clymiaru/GDPARCM_Sandbox | 21d6d7ccaef1b03a4d631e757cb824341e84e5d6 | [
"MIT"
] | null | null | null | Sandbox/Source/Thread/IETThread.cpp | Clymiaru/GDPARCM_Sandbox | 21d6d7ccaef1b03a4d631e757cb824341e84e5d6 | [
"MIT"
] | null | null | null | #include "pch.h"
#include <thread>
#include "IETThread.h"
namespace Thread
{
void IETThread::Start()
{
std::thread(&IETThread::Run, this).detach();
}
void IETThread::Sleep(const int ms)
{
std::this_thread::sleep_for(std::chrono::milliseconds(ms));
}
}
| 14.777778 | 61 | 0.672932 | Clymiaru |
a224d409d24fbd96a51321d4450ead11c2b21ecc | 2,371 | cpp | C++ | QScreenshot/ScreenshotCreator.cpp | dbautsch/QScreenshot | 80fc3113a342eb4498d8f24aa77230a0d8bbc170 | [
"MIT"
] | 2 | 2018-04-10T06:32:26.000Z | 2021-04-23T14:50:04.000Z | QScreenshot/ScreenshotCreator.cpp | dbautsch/QScreenshot | 80fc3113a342eb4498d8f24aa77230a0d8bbc170 | [
"MIT"
] | 2 | 2016-06-10T12:55:45.000Z | 2016-07-08T14:25:48.000Z | QScreenshot/ScreenshotCreator.cpp | dbautsch/QScreenshot | 80fc3113a342eb4498d8f24aa77230a0d8bbc170 | [
"MIT"
] | 1 | 2018-12-07T06:02:24.000Z | 2018-12-07T06:02:24.000Z | /*!
* Copyright (c) 2016 Dawid Bautsch dawid.bautsch@gmail.com
* 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 "ScreenshotCreator.h"
#include <QScreen>
#include <QGuiApplication>
#include <QPixmap>
ScreenshotCreator::ScreenshotCreator(QObject *Parent)
: QObject(Parent)
{
pCaptureRectDrawer = new CaptureRectDrawer(this);
connect(this, SIGNAL(ShowCaptureRect()), pCaptureRectDrawer, SLOT(ShowRect()));
connect(this, SIGNAL(HideCaptureRect()), pCaptureRectDrawer, SLOT(HideRect()));
connect(pCaptureRectDrawer, SIGNAL(RectSubmited(QRect)), this, SLOT(CaptureRectSubmited(QRect)));
}
void ScreenshotCreator::TakeScreenshot(EScreenshotKind kind)
{
switch (kind)
{
case EScreenshotKind::EntireScreen:
TakeScreenshot_EntireScreen();
break;
case EScreenshotKind::ScreenPart:
Takescreenshot_Part();
break;
}
}
void ScreenshotCreator::TakeScreenshot_EntireScreen()
{
QScreen * pScreen = QGuiApplication::primaryScreen();
pPixmap = new QPixmap(pScreen->grabWindow(0));
emit ImageAvailable(pPixmap);
}
void ScreenshotCreator::Takescreenshot_Part()
{
emit ShowCaptureRect();
}
void ScreenshotCreator::SaveToFile(const QString & strFileName)
{
//!< save current picture to file
pPixmap->save(strFileName);
}
void ScreenshotCreator::CaptureRectSubmited(const QRect & r)
{
/*!
* Part of the screen has been submited by user - can
* create screenshot using rect r.
*
* \param r Rectangular part of the screen that will be
* saved to QPixmap.
*/
QScreen * pScreen = QGuiApplication::primaryScreen();
QPixmap * pPixmapScreen = new QPixmap(pScreen->grabWindow(0));
QPixmap * pPixmapPart = new QPixmap(pPixmapScreen->copy(r));
delete pPixmapScreen;
pPixmap = pPixmapPart;
emit HideCaptureRect();
emit ImageAvailable(pPixmap);
}
| 27.569767 | 101 | 0.707296 | dbautsch |
a22837c986bbed983a482bd1a48ba871980f1fc2 | 10,625 | cc | C++ | spatial_pyramid/validate_cli.cc | sanchom/sjm | e6ed4c9f3abcf04a6b02b97b6f14dd50af47364a | [
"BSD-2-Clause"
] | 9 | 2015-06-01T11:47:30.000Z | 2021-09-06T02:36:28.000Z | spatial_pyramid/validate_cli.cc | sanchom/sjm | e6ed4c9f3abcf04a6b02b97b6f14dd50af47364a | [
"BSD-2-Clause"
] | null | null | null | spatial_pyramid/validate_cli.cc | sanchom/sjm | e6ed4c9f3abcf04a6b02b97b6f14dd50af47364a | [
"BSD-2-Clause"
] | 8 | 2015-05-02T03:57:10.000Z | 2017-10-05T06:38:13.000Z | // Copyright 2011 Sancho McCann
// 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.
// 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
// HOLDER 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.
// This command line tool uses learned SVM models to classify a set of
// test files.
#include <map>
#include <set>
#include <string>
#include <vector>
#include "boost/foreach.hpp"
#include "boost/thread.hpp"
#include "gflags/gflags.h"
#include "glog/logging.h"
#include "spatial_pyramid/spatial_pyramid.pb.h"
#include "spatial_pyramid/spatial_pyramid_kernel.h"
#include "spatial_pyramid/svm/svm.h"
#include "util/util.h"
DEFINE_string(
training_list, "",
"A list of the paths to the pyramids to be used as support vectors. "
"Each line is '<train_file>:<ground_truth_category>'.");
DEFINE_string(
model_list, "",
"A list of libsvm model files - one for each category. Each line is "
"'<model_file>:<category>'.");
DEFINE_string(
testing_list, "",
"A list of pyramid files to classify using the models from model_list. "
"Each line is '<test_file>:<ground_truth_category>'.");
DEFINE_string(
result_file, "",
"The file to write the result to.");
DEFINE_int32(
thread_limit, 1,
"The number of threads to use.");
DEFINE_string(
kernel, "intersection",
"The svm type. Options are \"intersection\" or \"linear\".");
using std::map;
using std::pair;
using std::set;
using std::string;
using std::vector;
using sjm::spatial_pyramid::SpatialPyramid;
using sjm::spatial_pyramid::SparseVectorFloat;
typedef map<string, SpatialPyramid> PyramidMap;
typedef map<string, svm_model*> SvmMap;
typedef map<string, pair<int, int> > ResultsMap;
enum SvmKernel {
LINEAR_KERNEL,
INTERSECTION_KERNEL
};
void Classify(const string test_filename,
const string true_category,
const PyramidMap& example_map,
const SvmMap& svm_map,
const SvmKernel svm_kernel,
ResultsMap& results_map,
boost::mutex& results_mutex) {
svm_node* kernel_vector = new svm_node[example_map.size() + 2];
int* label_vector = new int[2];
double decision_value = 0;
SpatialPyramid testing_pyramid;
string pyramid_data;
sjm::util::ReadFileToStringOrDie(test_filename, &pyramid_data);
testing_pyramid.ParseFromString(pyramid_data);
// Form the kernel vector for this example. The first index is zero
// and the value doesn't matter. This is the libsvm library
// convention for test vectors.
kernel_vector[0].index = 0;
kernel_vector[0].value = 0;
int i = 1;
for (PyramidMap::const_iterator it = example_map.begin();
it != example_map.end(); ++it) {
kernel_vector[i].index = i;
if (svm_kernel == INTERSECTION_KERNEL) {
kernel_vector[i].value =
sjm::spatial_pyramid::SpmKernel(testing_pyramid, it->second,
testing_pyramid.level_size());
} else if (svm_kernel == LINEAR_KERNEL) {
kernel_vector[i].value =
sjm::spatial_pyramid::LinearKernel(testing_pyramid, it->second);
}
++i;
}
kernel_vector[example_map.size() + 1].index = -1;
kernel_vector[example_map.size() + 1].value = 0;
// Now, get the decision values for the +1 class in each of the
// models and find the category scored most strongly.
string max_category = "";
double max_score = -10000;
for (SvmMap::const_iterator it = svm_map.begin();
it != svm_map.end(); ++it) {
const string category = it->first;
const svm_model* model = it->second;
// The meaning of decision_value depends on what label is in
// position [0] of the labels structure.
svm_get_labels(model, label_vector);
svm_predict_values(model, kernel_vector, &decision_value);
double category_score;
if (label_vector[0] == 1) {
// If the first label was +1, then the decision value is the
// confidence for +1 class.
category_score = decision_value;
} else {
// If the first label was not +1 (ie. it was -1), then the
// decision value is the confidence for the -1 class.
category_score = -decision_value;
}
if (category_score > max_score) {
max_score = category_score;
max_category = category;
}
}
boost::mutex::scoped_lock l(results_mutex);
if (results_map.find(true_category) != results_map.end()) {
// We've already got some results for this category.
int total = results_map[true_category].first;
int correct = results_map[true_category].second;
int new_total = total + 1;
int new_correct = correct;
if (max_category == true_category) {
new_correct += 1;
}
results_map[true_category] = std::make_pair(new_total, new_correct);
} else {
if (max_category == true_category) {
results_map[true_category] = std::make_pair(1, 1);
} else {
results_map[true_category] = std::make_pair(1, 0);
}
}
LOG(INFO) << "File: " << test_filename <<
", Prediction: " << max_category;
delete[] label_vector;
delete[] kernel_vector;
}
int main(int argc, char* argv[]) {
google::ParseCommandLineFlags(&argc, &argv, true);
google::InitGoogleLogging(argv[0]);
GOOGLE_PROTOBUF_VERIFY_VERSION;
CHECK(!FLAGS_result_file.empty()) << "--result_file needed.";
// Parse the svm kernel parameter.
SvmKernel svm_kernel;
vector<string> svm_kernel_parts;
if (FLAGS_kernel == "intersection") {
svm_kernel = INTERSECTION_KERNEL;
} else if (FLAGS_kernel == "linear") {
svm_kernel = LINEAR_KERNEL;
} else {
LOG(FATAL) << "Unrecognized SVM kernel.";
}
// Load all the list data.
string pyramid_list_data;
sjm::util::ReadFileToStringOrDie(FLAGS_training_list, &pyramid_list_data);
string model_list_data;
sjm::util::ReadFileToStringOrDie(FLAGS_model_list, &model_list_data);
string testing_list_data;
sjm::util::ReadFileToStringOrDie(FLAGS_testing_list, &testing_list_data);
vector<string> pyramid_list;
boost::split(pyramid_list, pyramid_list_data, boost::is_any_of("\n"));
vector<string> model_list;
boost::split(model_list, model_list_data, boost::is_any_of("\n"));
vector<string> testing_list;
boost::split(testing_list, testing_list_data, boost::is_any_of("\n"));
// Load the training data into a map sorted by filename.
PyramidMap file_to_training_data;
BOOST_FOREACH(string t, pyramid_list) {
if (!t.empty()) {
vector<string> training_parts;
boost::split(training_parts, t, boost::is_any_of(":"));
string training_pyramid_name = training_parts[0];
SpatialPyramid pyramid;
string pyramid_data;
sjm::util::ReadFileToStringOrDie(training_pyramid_name, &pyramid_data);
pyramid.ParseFromString(pyramid_data);
file_to_training_data[t] = pyramid;
}
}
// Load all the models and put in map, keyed by category name.
SvmMap category_to_svm_model;
BOOST_FOREACH(string t, model_list) {
if (!t.empty()) {
vector<string> model_parts;
boost::split(model_parts, t, boost::is_any_of(":"));
svm_model* model =
svm_load_model(sjm::util::expand_user(model_parts[0]).c_str());
category_to_svm_model[model_parts[1]] = model;
}
}
ResultsMap results_map;
boost::mutex results_mutex;
vector<boost::thread*> threads_list;
// Classify each of the test images and compare against the ground truth.
BOOST_FOREACH(string t, testing_list) {
if (!t.empty()) {
vector<string> testing_parts;
boost::split(testing_parts, t, boost::is_any_of(":"));
string test_filename = testing_parts[0];
string true_category = testing_parts[1];
while (threads_list.size() >= FLAGS_thread_limit) {
for (vector<boost::thread*>::iterator thread_it = threads_list.begin();
thread_it != threads_list.end();
++thread_it) {
if ((*thread_it)->timed_join(boost::posix_time::milliseconds(25))) {
delete (*thread_it);
threads_list.erase(thread_it);
break;
}
}
}
// TODO(sanchom): Change results_map to a pointer instead of a
// reference. Same with results_mutex.
boost::thread* classify_thread =
new boost::thread(Classify, test_filename, true_category,
boost::ref(file_to_training_data),
boost::ref(category_to_svm_model),
svm_kernel,
boost::ref(results_map),
boost::ref(results_mutex));
threads_list.push_back(classify_thread);
}
}
// Join with any remaining threads.
for (vector<boost::thread*>::iterator thread_it = threads_list.begin();
thread_it != threads_list.end(); ++thread_it) {
(*thread_it)->join();
delete (*thread_it);
}
float average_accuracy = 0;
for (ResultsMap::const_iterator it = results_map.begin();
it != results_map.end(); ++it) {
float category_accuracy =
it->second.second / static_cast<float>(it->second.first);
LOG(INFO) << "[" << it->first << "] accuracy: " << category_accuracy;
average_accuracy += category_accuracy;
}
LOG(INFO) << "Mean accuracy: " << average_accuracy / results_map.size();
const int kBufferSize = 50;
char buffer[kBufferSize];
std::snprintf(buffer, kBufferSize, "%f\n",
average_accuracy / results_map.size());
sjm::util::AppendStringToFileOrDie(FLAGS_result_file, buffer);
return 0;
}
| 36.764706 | 79 | 0.681035 | sanchom |
a22a57077ee4c09670e77e4a7886380002097908 | 586 | cpp | C++ | ch11/fill1.cpp | bashell/CppStandardLibrary | 2aae03019288132c911036aeb9ba36edc56e510b | [
"MIT"
] | null | null | null | ch11/fill1.cpp | bashell/CppStandardLibrary | 2aae03019288132c911036aeb9ba36edc56e510b | [
"MIT"
] | null | null | null | ch11/fill1.cpp | bashell/CppStandardLibrary | 2aae03019288132c911036aeb9ba36edc56e510b | [
"MIT"
] | null | null | null | #include "algostuff.hpp"
using namespace std;
int main()
{
fill_n(ostream_iterator<float>(cout, " "), 10, 7.7);
cout << endl;
list<string> coll;
fill_n(back_inserter(coll), 9, "hello");
PRINT_ELEMENTS(coll, "coll: ");
fill(coll.begin(), coll.end(), "again");
PRINT_ELEMENTS(coll, "coll: ");
fill_n(coll.begin(), coll.size()-2, "hi");
PRINT_ELEMENTS(coll, "coll: ");
list<string>::iterator pos1, pos2;
pos1 = coll.begin();
pos2 = coll.end();
fill(++pos1, --pos2, "hmmm");
PRINT_ELEMENTS(coll, "coll: ");
return 0;
}
| 20.928571 | 56 | 0.581911 | bashell |
a23ec7e80ae2448ac6517fb71d055e2e6188a910 | 585 | cpp | C++ | LAB 1 ASSIGNMENTS/Task_10 Lab_01.cpp | ZapeeoSheikh/Cppfactory | 7bdf9c6dd8053a506f17fc4a0aa2093f06d2be70 | [
"MIT"
] | null | null | null | LAB 1 ASSIGNMENTS/Task_10 Lab_01.cpp | ZapeeoSheikh/Cppfactory | 7bdf9c6dd8053a506f17fc4a0aa2093f06d2be70 | [
"MIT"
] | null | null | null | LAB 1 ASSIGNMENTS/Task_10 Lab_01.cpp | ZapeeoSheikh/Cppfactory | 7bdf9c6dd8053a506f17fc4a0aa2093f06d2be70 | [
"MIT"
] | null | null | null | //task_10 (stock commission)
#include <iostream>
using namespace std;
main()
{
float total_share,price_per_share,commission;
total_share = 600;
price_per_share = 21.77;
commission = 0.02;
cout<<"Amount paid for stock: "<<total_share*price_per_share<<endl;
cout<<"Amount of commission: "<<(total_share*price_per_share)*commission<<endl;
//Simply add "amount paid for stock"+"Amount of commission" to get total amount
cout<<"Total Amount: "<<((total_share*price_per_share)+(total_share*price_per_share)*commission)<<endl;
return 0;
}
| 30.789474 | 108 | 0.697436 | ZapeeoSheikh |
a24284e738e84aa9102fc8f70073f3b9b462a802 | 3,172 | cpp | C++ | solved_problems/399A.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | 1 | 2021-01-27T16:37:31.000Z | 2021-01-27T16:37:31.000Z | solved_problems/399A.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | null | null | null | solved_problems/399A.cpp | archit-1997/codeforces | 6f78a3ed5930531159ae22f7b70dc56e37a9e240 | [
"MIT"
] | null | null | null | /*
User ainta is making a web site. This time he is going to make a navigation of
the pages. In his site, there are n pages numbered by integers from 1 to n.
Assume that somebody is on the p-th page now. The navigation will look like
this:
<< p - k p - k + 1 ... p - 1 (p) p + 1 ... p + k - 1 p + k >>
When someone clicks the button "<<" he is redirected to page 1, and when someone
clicks the button ">>" he is redirected to page n. Of course if someone clicks
on a number, he is redirected to the corresponding page.
There are some conditions in the navigation:
If page 1 is in the navigation, the button "<<" must not be printed.
If page n is in the navigation, the button ">>" must not be printed.
If the page number is smaller than 1 or greater than n, it must not be printed.
You can see some examples of the navigations. Make a program that prints the
navigation.
Input
The first and the only line contains three integers n, p, k (3 ≤ n ≤ 100;
1 ≤ p ≤ n; 1 ≤ k ≤ n)
Output
Print the proper navigation. Follow the format of the output from the test
samples.
Examples
inputCopy
17 5 2
outputCopy
<< 3 4 (5) 6 7 >>
inputCopy
6 5 2
outputCopy
<< 3 4 (5) 6
inputCopy
6 1 2
outputCopy
(1) 2 3 >>
inputCopy
6 2 2
outputCopy
1 (2) 3 4 >>
inputCopy
9 6 3
outputCopy
<< 3 4 5 (6) 7 8 9
inputCopy
10 6 3
outputCopy
<< 3 4 5 (6) 7 8 9 >>
inputCopy
8 5 4
outputCopy
1 2 3 4 (5) 6 7 8
*/
// Archit Singh
#include <bits/stdc++.h>
using namespace std;
#define ll long long int
#define ld long double
#define line cout << "-------------" << endl;
#define f first
#define s second
#define mp(a, b) make_pair(a, b)
#define p pair<ll, ll>
#define pp pair<pair<ll, ll>, ll>
#define v vector<ll>
#define vp vector<pair<ll, ll>>
#define vs vector<string>
#define vv vector<vector<ll>>
#define vvp vector<vector<pair<ll, ll>>>
#define pb push_back
#define pf push_front
#define pqb priority_queue<ll>
#define pqs priority_queue<ll, V, greater<ll>>
#define FOR(i, a, b) for (ll i = a; i < b; i++)
#define setbits(x) __builtin_popocount(x)
#define zrobits(x) __builtin_ctzll(x)
#define mod 1000000007
#define inf 1e18
#define ps(x, y) fixed << setprecision(y) << x
#define ma(arr, n, type) type *arr = new type[n]
#define w(x) \
ll x; \
cin >> x; \
while (x--)
void init() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
// freopen("input.txt", "r", stdin);
// freopen("output.txt", "w", stdout);
}
int main() {
init();
ll n, P, K;
cin >> n >> P >> K;
ll left = max((ll)1, P - K);
ll right = min(P + K, n);
// printing the left part
if (left != 1)
cout << "<< ";
FOR(i, left, P)
cout << i << " ";
// printing the middle part
cout << "(" << P << ") ";
// printing the right part
FOR(i, P + 1, right + 1)
cout << i << " ";
if (right != n)
cout << ">>";
return 0;
} | 24.4 | 81 | 0.576293 | archit-1997 |
a24a2f8d8cdfa2c91252ab2cc9d9a16af76a1906 | 3,929 | cpp | C++ | util/screenrect.cpp | degarashi/resonant | f1a8c86c4d2c89d2397b0c1db55c7dfe7a317f6a | [
"MIT"
] | null | null | null | util/screenrect.cpp | degarashi/resonant | f1a8c86c4d2c89d2397b0c1db55c7dfe7a317f6a | [
"MIT"
] | null | null | null | util/screenrect.cpp | degarashi/resonant | f1a8c86c4d2c89d2397b0c1db55c7dfe7a317f6a | [
"MIT"
] | null | null | null | #include "screenrect.hpp"
#include "../glx.hpp"
#include "../drawtag.hpp"
#include "../sys_uniform.hpp"
#include "../systeminfo.hpp"
namespace rs {
namespace util {
namespace {
HLVb MakeVertex_Base(float minv, float maxv) {
HLVb hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW);
const vertex::screen c_vertex[] = {
{{minv, minv}, {0,0}},
{{minv, maxv}, {0,1}},
{{maxv, maxv}, {1,1}},
{{maxv, minv}, {1,0}}
};
hlVb->get()->initData(c_vertex, countof(c_vertex), sizeof(c_vertex[0]));
return hlVb;
}
void DrawRect(rs::IEffect& e, GLenum dtype, rs::HVb hVb, rs::HIb hIb) {
e.setVDecl(rs::DrawDecl<rs::vdecl::screen>::GetVDecl());
e.setVStream(hVb, 0);
e.setIStream(hIb);
const int nElem = hIb->get()->getNElem();
e.drawIndexed(dtype, nElem, 0);
}
}
// ---------------------- Rect01 ----------------------
GeomP Rect01::MakeGeom(...) {
const GLubyte c_index[] = {
0,1,2, 2,3,0
};
HLIb hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW);
hlIb->get()->initData(c_index, countof(c_index));
return {MakeVertex_Base(0.f, 1.f), std::move(hlIb)};
}
void Rect01::draw(rs::IEffect& e) const {
const auto& g = getGeom();
DrawRect(e, GL_TRIANGLES, g.first, g.second);
}
// ---------------------- WireRect01 ----------------------
GeomP WireRect01::MakeGeom(...) {
const GLubyte c_index[] = {
0, 1, 2, 3
};
HLIb hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW);
hlIb->get()->initData(c_index, countof(c_index));
return {Rect01::MakeGeom().first, std::move(hlIb)};
}
void WireRect01::draw(rs::IEffect& e) const {
const auto& g = getGeom();
DrawRect(e, GL_LINE_LOOP, g.first, g.second);
}
// ---------------------- Rect11 ----------------------
GeomP Rect11::MakeGeom(...) {
return {MakeVertex_Base(-1.f, 1.f), Rect01::MakeGeom().second};
}
void Rect11::draw(rs::IEffect& e) const {
auto& g = getGeom();
DrawRect(e, GL_TRIANGLES, g.first, g.second);
}
// ---------------------- WindowRect ----------------------
WindowRect::WindowRect():
_color(1,1,1),
_alpha(1),
_depth(1),
_bWire(false)
{}
void WindowRect::setColor(const spn::Vec3& c) {
_color = c;
}
void WindowRect::setAlpha(float a) {
_alpha = a;
}
void WindowRect::setDepth(float d) {
_depth = d;
}
void WindowRect::exportDrawTag(DrawTag& tag) const {
auto& g = (_bWire) ? _wrect01.getGeom() : _rect01.getGeom();
tag.idIBuffer = g.second;
tag.idVBuffer[0] = g.first;
tag.zOffset = _depth;
}
void WindowRect::setWireframe(const bool bWireframe) {
_bWire = bWireframe;
}
void WindowRect::draw(IEffect& e) const {
const auto s = mgr_info.getScreenSize();
const float rx = spn::Rcp22Bit(s.width/2),
ry = spn::Rcp22Bit(s.height/2);
const auto& sc = getScale();
const auto& ofs = getOffset();
const float rv = _bWire ? -1 : 0;
auto m = spn::AMat33::Scaling(rx*(sc.x+rv), -ry*(sc.y+rv), 1.f);
m *= spn::AMat33::Translation({-1+rx/2, 1-ry/2});
m *= spn::AMat33::Translation({ofs.x*rx, -ofs.y*ry});
e.setVDecl(DrawDecl<vdecl::screen>::GetVDecl());
auto& s2 = e.ref2D();
s2.setWorld(m);
e.setUniform(unif2d::Color, _color);
e.setUniform(unif2d::Alpha, _alpha);
e.setUniform(unif2d::Depth, _depth);
if(_bWire)
_wrect01.draw(e);
else
_rect01.draw(e);
}
// ---------------------- ScreenRect ----------------------
void ScreenRect::exportDrawTag(DrawTag& tag) const {
auto& g = _rect11.getGeom();
tag.idIBuffer = g.second;
tag.idVBuffer[0] = g.first;
}
void ScreenRect::draw(IEffect& e) const {
_rect11.draw(e);
}
}
// ---------------------- Screen頂点宣言 ----------------------
const SPVDecl& DrawDecl<vdecl::screen>::GetVDecl() {
static SPVDecl vd(new VDecl{
{0,0, GL_FLOAT, GL_FALSE, 2, (GLuint)rs::VSem::POSITION},
{0,8, GL_FLOAT, GL_FALSE, 2, (GLuint)rs::VSem::TEXCOORD0}
});
return vd;
}
}
| 30.457364 | 76 | 0.577501 | degarashi |
a24f62b61053b959f186237a84efb1c423680eec | 1,053 | hpp | C++ | plugins/ecs_plugin/include/components/TransformComponent.hpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | 5 | 2018-08-16T00:55:33.000Z | 2020-06-19T14:30:17.000Z | plugins/ecs_plugin/include/components/TransformComponent.hpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | null | null | null | plugins/ecs_plugin/include/components/TransformComponent.hpp | fuchstraumer/Caelestis | 9c4b76288220681bb245d84e5d7bf8c7f69b2716 | [
"MIT"
] | null | null | null | #pragma once
#ifndef VPSK_TRANSFORM_COMPONENT_HPP
#define VPSK_TRANSFORM_COMPONENT_HPP
#define GLM_SWIZZLE
#include "glm/mat4x4.hpp"
#include "glm/vec4.hpp"
namespace vpsk {
struct WorldTransformComponent {
WorldTransformComponent(glm::vec3 p, glm::vec3 s = glm::vec3(1.0f), glm::vec3 rot = glm::vec3(0.0f));
const glm::mat4& operator()() const;
const glm::mat4& TransformationMatrix() const;
glm::mat4 NormalMatrix() const;
void SetPosition(glm::vec3 p);
void SetScale(glm::vec3 p);
void SetRotation(glm::vec3 p);
const glm::vec3& Position() const noexcept;
const glm::vec3& Scale() const noexcept;
const glm::vec3& Rotation() const noexcept;
private:
const glm::mat4& calculateMatrix() const;
glm::vec3 position;
glm::vec3 scale;
glm::vec3 rotation;
mutable glm::mat4 transformation;
mutable glm::mat4 normal;
mutable bool calculated = false;
};
}
#endif //!VPSK_TRANSFORM_COMPONENT_HPP | 27.710526 | 109 | 0.643875 | fuchstraumer |
a254c513960ca0babc7672cd654504805a691408 | 10,216 | cpp | C++ | grim-code/Engine/DXGfx.cpp | ariabonczek/GrimoireEngine | 94952b98232b4baac8caa1189dac7c38672c6ae0 | [
"MIT"
] | null | null | null | grim-code/Engine/DXGfx.cpp | ariabonczek/GrimoireEngine | 94952b98232b4baac8caa1189dac7c38672c6ae0 | [
"MIT"
] | null | null | null | grim-code/Engine/DXGfx.cpp | ariabonczek/GrimoireEngine | 94952b98232b4baac8caa1189dac7c38672c6ae0 | [
"MIT"
] | null | null | null | #include "Precompiled.h"
#include <Engine/Gfx.h>
#include <Engine/DXGfx.h>
#include <Engine/EngineGlobals.h>
#include <Engine/DrawElement.h>
#include <Engine/GraphicsState.h>
#include <Engine/Surface.h>
#include <Engine/grimInput.h>
#include <Engine/d3dx12.h>
#include <string>
#include <d3dcompiler.h>
namespace plat {
static HWND s_window;
static IDXGISwapChain3* s_swapChain;
static ID3D12Device* s_device;
static ID3D12CommandQueue* s_commandQueue[gfx::kNumCommandQueues];
ID3D12Device* GetDevice()
{
return s_device;
}
ID3D12CommandQueue* GetCommandQueue(int index)
{
GRIM_ASSERT(index <= gfx::kNumCommandQueues, "Invalid command queue index requested");
return s_commandQueue[index];
}
IDXGISwapChain3* GetSwapChain()
{
return s_swapChain;
}
static LRESULT HandleMessages(HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
switch (msg)
{
case WM_CLOSE:
case WM_QUIT:
gfx::TriggerClose();
return 0;
case WM_SIZE:
gfx::ResizeFramebuffer(LOWORD(lParam), HIWORD(lParam));
return 0;
case WM_ENTERSIZEMOVE:
return 0;
case WM_EXITSIZEMOVE:
return 0;
case WM_DESTROY:
gfx::TriggerClose();
return 0;
case WM_LBUTTONDOWN:
return 0;
case WM_LBUTTONUP:
return 0;
case WM_KEYDOWN:
return 0;
case WM_MENUCHAR:
return MAKELRESULT(0, MNC_CLOSE);
case WM_GETMINMAXINFO:
((MINMAXINFO*)lParam)->ptMinTrackSize.x = 200;
((MINMAXINFO*)lParam)->ptMinTrackSize.y = 200;
return 0;
}
return DefWindowProc(hWnd, msg, wParam, lParam);
}
LRESULT CALLBACK WindowProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
return HandleMessages(hwnd, msg, wParam, lParam);
}
static void InitWindow()
{
const HINSTANCE hInstance = GetModuleHandle(NULL);
if (g_engineGlobals.bootingFromEditor)
{
s_window = (HWND)g_engineGlobals.windowHandle;
return;
}
// Initialize the window class.
WNDCLASSEX windowClass = { 0 };
windowClass.cbSize = sizeof(WNDCLASSEX);
windowClass.style = CS_HREDRAW | CS_VREDRAW;
windowClass.lpfnWndProc = WindowProc;
windowClass.hInstance = hInstance;
windowClass.hCursor = LoadCursor(NULL, IDC_ARROW);
windowClass.lpszClassName = "Grimoire";
int ret = RegisterClassEx(&windowClass);
GRIM_ASSERT(ret, "Failed to register window class");
RECT windowRect = { 0, 0, static_cast<LONG>(g_engineGlobals.windowWidth), static_cast<LONG>(g_engineGlobals.windowHeight) };
AdjustWindowRect(&windowRect, WS_OVERLAPPEDWINDOW, FALSE);
// Create the window and store a handle to it.
s_window = CreateWindow(
windowClass.lpszClassName,
g_engineGlobals.windowTitle,
WS_OVERLAPPEDWINDOW,
CW_USEDEFAULT,
CW_USEDEFAULT,
windowRect.right - windowRect.left,
windowRect.bottom - windowRect.top,
nullptr,
nullptr,
hInstance,
nullptr);
GRIM_ASSERT(s_window, "Failed to create window");
const int nCmdShow = SW_SHOWDEFAULT;
ShowWindow(s_window, nCmdShow);
}
static void InitDebugLayer()
{
ID3D12Debug* debugLayer;
if (SUCCEEDED(D3D12GetDebugInterface(IID_PPV_ARGS(&debugLayer))))
{
debugLayer->EnableDebugLayer();
}
}
static void InitDeviceAndCommandQueues(IDXGIFactory4* factory)
{
// TODO: Support warp adapter
IDXGIAdapter1* chosenAdapter = nullptr;
IDXGIAdapter1* currentAdapter = nullptr;
for (int i = 0; DXGI_ERROR_NOT_FOUND != factory->EnumAdapters1(i, ¤tAdapter); ++i)
{
DXGI_ADAPTER_DESC1 currentDesc;
currentAdapter->GetDesc1(¤tDesc);
if (currentDesc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE)
continue;
if (chosenAdapter != nullptr)
{
DXGI_ADAPTER_DESC1 chosenDesc;
chosenAdapter->GetDesc1(&chosenDesc);
if (chosenDesc.DedicatedVideoMemory > currentDesc.DedicatedVideoMemory)
continue;
}
if (SUCCEEDED(D3D12CreateDevice(currentAdapter, D3D_FEATURE_LEVEL_11_0, _uuidof(ID3D12Device), nullptr)))
chosenAdapter = currentAdapter;
}
HRESULT hr = D3D12CreateDevice(chosenAdapter, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&s_device));
GRIM_ASSERT(!hr, " Failed to create device");
s_device->SetName(L"DX12 Device");
D3D12_COMMAND_QUEUE_DESC queueDesc = {};
queueDesc.Flags = D3D12_COMMAND_QUEUE_FLAG_NONE;
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT;
hr = s_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&s_commandQueue[gfx::kGfxQueue]));
GRIM_ASSERT(!hr, "Failed to create command queue");
s_commandQueue[gfx::kGfxQueue]->SetName(L"Gfx Queue");
queueDesc.Type = D3D12_COMMAND_LIST_TYPE_COMPUTE;
hr = s_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&s_commandQueue[gfx::kCompute0]));
GRIM_ASSERT(!hr, "Failed to create command queue");
s_commandQueue[gfx::kCompute0]->SetName(L"Compute Queue 0");
queueDesc.Priority = D3D12_COMMAND_QUEUE_PRIORITY_HIGH;
hr = s_device->CreateCommandQueue(&queueDesc, IID_PPV_ARGS(&s_commandQueue[gfx::kCompute1]));
GRIM_ASSERT(!hr, "Failed to create command queue");
s_commandQueue[gfx::kCompute1]->SetName(L"Compute Queue 1");
}
static void InitSwapChain(IDXGIFactory4* factory)
{
// Create the swap chain.
DXGI_SWAP_CHAIN_DESC1 swapChainDesc = {};
swapChainDesc.BufferCount = g_engineGlobals.numDisplayBuffers;
swapChainDesc.Width = g_engineGlobals.frameBufferWidth;
swapChainDesc.Height = g_engineGlobals.frameBufferHeight;
swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
swapChainDesc.SampleDesc.Count = 1;
IDXGISwapChain1* temp;
HRESULT hr = factory->CreateSwapChainForHwnd(plat::GetCommandQueue(gfx::kGfxQueue), s_window, &swapChainDesc, nullptr, nullptr, &temp);
GRIM_ASSERT(!hr, "Failed to create swap chain");
factory->MakeWindowAssociation(s_window, DXGI_MWA_VALID);
GRIM_ASSERT(!hr, "Failed to associate swap chain with window");
s_swapChain = static_cast<IDXGISwapChain3*>(temp);
}
void InitGfx()
{
InitWindow();
UINT factoryFlags = 0;
#ifdef _DEBUG
InitDebugLayer();
factoryFlags |= DXGI_CREATE_FACTORY_DEBUG;
#endif
IDXGIFactory4* factory;
HRESULT hr = CreateDXGIFactory2(factoryFlags, IID_PPV_ARGS(&factory));
GRIM_ASSERT(!hr, "Failed to create factory");
InitDeviceAndCommandQueues(factory);
InitSwapChain(factory);
factory->Release();
}
void ProcessGfx()
{
// Message loop
MSG msg = {};
if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
{
TranslateMessage(&msg);
DispatchMessage(&msg);
grimInput::HandleMessage(msg);
}
}
void ShutdownGfx()
{
for (int i = 0; i < gfx::kNumCommandQueues; ++i)
{
s_commandQueue[i]->Release();
}
s_swapChain->Release();
#ifdef _DEBUG
ID3D12DebugDevice* debugDevice;
HRESULT hr = s_device->QueryInterface(IID_PPV_ARGS(&debugDevice));
if (!hr)
{
debugDevice->ReportLiveDeviceObjects(D3D12_RLDO_DETAIL | D3D12_RLDO_IGNORE_INTERNAL);
}
#endif
s_device->Release();
}
void Flip()
{
s_swapChain->Present(1, 0);
}
int GetCurrentBackbufferIndex()
{
return s_swapChain->GetCurrentBackBufferIndex();
}
void SetWindowTitle(const char* text)
{
SetWindowText(s_window, text);
}
D3D12_GRAPHICS_PIPELINE_STATE_DESC StateToPipelineDesc(const gfx::GraphicsState& graphicsState, const gfx::ResourceState& resourceState, const gfx::Surface* renderTargets[8], const gfx::Surface* depthRenderTarget)
{
// Rasterizer State
D3D12_RASTERIZER_DESC rd = {};
{
rd.FillMode = (D3D12_FILL_MODE)graphicsState.rasterizerState.fillMode;
rd.CullMode = (D3D12_CULL_MODE)graphicsState.rasterizerState.cullMode;
rd.FrontCounterClockwise = (BOOL)graphicsState.rasterizerState.frontCounterClockwise;
}
// BlendState
D3D12_BLEND_DESC bd = {};
for (int i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
{
bd.RenderTarget[i].BlendEnable = (BOOL)graphicsState.blendState[i].blendEnable;
bd.RenderTarget[i].SrcBlend = (D3D12_BLEND)graphicsState.blendState[i].srcColor;
bd.RenderTarget[i].DestBlend = (D3D12_BLEND)graphicsState.blendState[i].destColor;
bd.RenderTarget[i].BlendOp = (D3D12_BLEND_OP)graphicsState.blendState[i].colorFunc;
bd.RenderTarget[i].SrcBlendAlpha = (D3D12_BLEND)graphicsState.blendState[i].srcAlpha;
bd.RenderTarget[i].DestBlendAlpha = (D3D12_BLEND)graphicsState.blendState[i].destAlpha;
bd.RenderTarget[i].BlendOpAlpha = (D3D12_BLEND_OP)graphicsState.blendState[i].alphaFunc;
bd.RenderTarget[i].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL;
}
// DepthStencilState
D3D12_DEPTH_STENCIL_DESC dsd = {};
{
dsd.DepthEnable = graphicsState.depthStencilState.testEnabled;
dsd.DepthWriteMask = graphicsState.depthStencilState.writeEnabled ? D3D12_DEPTH_WRITE_MASK_ALL : D3D12_DEPTH_WRITE_MASK_ZERO;
dsd.DepthFunc = (D3D12_COMPARISON_FUNC)graphicsState.depthStencilState.depthFunc;
}
// MultisampleState
DXGI_SAMPLE_DESC msd = {};
{
msd.Count = graphicsState.multisampleState.count;
msd.Quality = graphicsState.multisampleState.quality;
}
// Create the pipeline state, which includes compiling and loading shaders.
{
const plat::DXShader& shader = resourceState.shader->platformShader;
// Describe and create the graphics pipeline state object (PSO).
D3D12_GRAPHICS_PIPELINE_STATE_DESC desc = {};
desc.pRootSignature = shader.rootSignature;
desc.InputLayout = shader.inputLayout;
desc.VS = CD3DX12_SHADER_BYTECODE(shader.vertexShader);
desc.PS = CD3DX12_SHADER_BYTECODE(shader.pixelShader);
desc.RasterizerState = rd;
desc.BlendState = bd;
desc.DepthStencilState = dsd;
desc.SampleDesc = msd;
desc.SampleMask = UINT_MAX;
desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE;
int count = 0;
for (int i = 0; i < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT; ++i)
{
if (renderTargets[i])
{
desc.RTVFormats[i] = (DXGI_FORMAT) renderTargets[i]->m_definition.format;
++count;
}
}
desc.NumRenderTargets = count;
if (depthRenderTarget)
desc.DSVFormat = (DXGI_FORMAT) depthRenderTarget->m_definition.format;
// Note: this is valid for compute shaders!
GRIM_ASSERT(count, "Creating a graphics pipeline state with no render targets");
return desc;
}
}
} | 29.022727 | 214 | 0.744323 | ariabonczek |
a2629389f99588607a1f252cee5dd3fd23985d69 | 401 | cpp | C++ | class09/simpleRecursion.cpp | jeremypedersen/cppZero | 69fc8119fdcc8186fee50896ff378a3c55076fa7 | [
"Unlicense"
] | null | null | null | class09/simpleRecursion.cpp | jeremypedersen/cppZero | 69fc8119fdcc8186fee50896ff378a3c55076fa7 | [
"Unlicense"
] | null | null | null | class09/simpleRecursion.cpp | jeremypedersen/cppZero | 69fc8119fdcc8186fee50896ff378a3c55076fa7 | [
"Unlicense"
] | null | null | null | //
// Code by: Jeremy Pedersen
//
// Licensed under the BSD 2-clause license (FreeBSD license)
//
// A simple demonstration of recursion
#include <iostream>
using namespace std;
void countDown(int start) {
if (start > 1) {
cout << start << endl;
countDown(start - 1);
}
else {
cout << 1 << endl;
}
}
int main() {
countDown(10);
return 0;
} | 14.321429 | 61 | 0.561097 | jeremypedersen |
a2646d9ce725dcb0421ae40cf4d1dd4c74d39183 | 2,833 | cpp | C++ | src/UlltraProto.cpp | rtaudio/ulltra | 3007088c7960e52bf7f5e75c4a10a638b27a3f09 | [
"MIT"
] | null | null | null | src/UlltraProto.cpp | rtaudio/ulltra | 3007088c7960e52bf7f5e75c4a10a638b27a3f09 | [
"MIT"
] | null | null | null | src/UlltraProto.cpp | rtaudio/ulltra | 3007088c7960e52bf7f5e75c4a10a638b27a3f09 | [
"MIT"
] | null | null | null |
#include "UlltraProto.h"
#include<iostream>
#include "net/networking.h"
#ifdef _WIN32
LARGE_INTEGER UlltraProto::timerFreq;
VOID(WINAPI*UlltraProto::myGetSystemTime)(_Out_ LPFILETIME);
static UINT gPeriod = 0;
#endif
std::atomic<uint64_t> UlltraProto::tickSeconds;
bool UlltraProto::init() {
tickSeconds = 0;
//startTime = std::clock();
#ifdef _WIN32
TIMECAPS caps;
QueryPerformanceFrequency(&timerFreq);
if (timeGetDevCaps(&caps, sizeof(TIMECAPS)) != TIMERR_NOERROR) {
LOG(logERROR) << ("InitTime : could not get timer device");
return false;
}
else {
gPeriod = caps.wPeriodMin;
if (timeBeginPeriod(gPeriod) != TIMERR_NOERROR) {
LOG(logERROR) << ("InitTime : could not set minimum timer");
gPeriod = 0;
return false;
}
else {
LOG(logINFO) << "InitTime : multimedia timer resolution set to " << gPeriod << " milliseconds";
}
}
// load GetSystemTimePreciseAsFileTime
FARPROC fp;
myGetSystemTime = 0;
auto hk32 = LoadLibraryW(L"kernel32.dll");
if (!hk32) {
LOG(logERROR) << ("Failed to load kernel32.dll");
return false;
}
fp = GetProcAddress(hk32, "GetSystemTimePreciseAsFileTime");
if (fp == NULL) {
LOG(logERROR) << ("Failed to load GetSystemTimePreciseAsFileTime()");
return false;
}
myGetSystemTime = (VOID(WINAPI*)(LPFILETIME)) fp;
#endif
return true;
}
#if ANDROID
#include <stdio.h>
#include <string.h>
#include <sys/system_properties.h>
/* Get device name
--
1/ Compile with the Android NDK Toolchain:
arm-linux-androideabi-gcc -static pname.c -o pname
2/ Transfer on device:
adb push pname /data/local/tmp
3/ Run:
adb shell
$ /data/local/tmp/pname
[device]: [HTC/HTC Sensation Z710e]
NOTE: these properties can be queried via adb:
adb shell getprop ro.product.manufacturer */
std::string androidGetProperty(std::string prop)
{
std::string command = "getprop " + prop;
FILE* file = popen(command.c_str(), "r");
if (!file) {
return "";
}
char * line = NULL;
size_t len = 0;
std::string val;
while ((getline(&line, &len, file)) != -1) {
val += (std::string(line));
}
val = trim(val);
// read the property value from file
pclose(file);
return val;
}
#endif
/*
Log::~Log()
{
os << std::endl;
fprintf(stderr, "%s", os.str().c_str());
fflush(stderr);
}
*/
std::string UlltraProto::deviceName = "";
const std::string& UlltraProto::getDeviceName()
{
if (!deviceName.empty())
return deviceName;
#if ANDROID
deviceName = androidGetProperty("ro.product.manufacturer") + "/" + androidGetProperty("ro.product.model");
LOG(logDEBUG) << "Device name: " << deviceName;
#else
char hostname[32];
gethostname(hostname, 31);
deviceName = std::string(hostname);
#endif
return deviceName;
}
| 20.830882 | 108 | 0.652665 | rtaudio |
a269534217e66d594445e2e684fe8747ca249279 | 987 | cpp | C++ | Framework/Util/animation.cpp | TranQuocTuan1711/Crossy-Road-Game-Application-SFML | 0210513f0e0e56814c8be9bfeac3e49780455ccb | [
"Unlicense"
] | 2 | 2022-01-28T16:51:58.000Z | 2022-01-28T16:52:17.000Z | Framework/Util/animation.cpp | TranQuocTuan1711/Crossy-Road-Game-Application-SFML | 0210513f0e0e56814c8be9bfeac3e49780455ccb | [
"Unlicense"
] | null | null | null | Framework/Util/animation.cpp | TranQuocTuan1711/Crossy-Road-Game-Application-SFML | 0210513f0e0e56814c8be9bfeac3e49780455ccb | [
"Unlicense"
] | null | null | null | #include "animation.h"
animation::frame::frame(const sf::Vector2i pos, sf::Time delay)
: pos(pos)
, delay(delay)
{}
animation::frame::frame(int x, int y, sf::Time delay)
: pos(x,y)
, delay(delay)
{}
animation::animation(size_t frame_width, size_t frame_height)
: m_frame_size(frame_width, frame_height)
{}
void animation::add_frame(sf::Time delay, size_t row, size_t col)
{
m_frames.emplace_back(col * m_frame_size.x, row * m_frame_size.y, delay);
}
const sf::IntRect animation::nextFrame()
{
if (m_timer.getElapsedTime() >= m_frames[m_frame_idx].delay) {
m_timer.restart();
++m_frame_idx;//next frame idx
if (m_frame_idx == m_frames.size())//loop back
reset();
}
return sf::IntRect(m_frames[m_frame_idx].pos, m_frame_size);
}
const sf::IntRect animation::getFrame(size_t idx) const
{
return sf::IntRect(m_frames[m_frame_idx].pos, m_frame_size);
}
void animation::reset()
{
m_frame_idx = 0;
}
size_t animation::totalFrame() const
{
return m_frames.size();
}
| 21 | 74 | 0.714286 | TranQuocTuan1711 |
a26d9da1dbb16177cd83d13877af11d26f5c9b47 | 2,003 | cpp | C++ | LightOJ/LightOJ - 1212/Wrong Answer.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | 1 | 2022-02-11T16:55:36.000Z | 2022-02-11T16:55:36.000Z | LightOJ/LightOJ - 1212/Wrong Answer.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | LightOJ/LightOJ - 1212/Wrong Answer.cpp | kzvd4729/Problem-Solving | 13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab | [
"MIT"
] | null | null | null | /****************************************************************************************
* @author: kzvd4729 created: 2017-05-18 20:01:29
* solution_verdict: Wrong Answer language: C++
* run_time (ms): memory_used (MB):
* problem: https://vjudge.net/problem/LightOJ-1212
****************************************************************************************/
#include<bits/stdc++.h>
using namespace std;
#define long long long int
long t,n,m,x,c,tc;
string s;
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cin>>t;
while(t--)
{
cin>>n>>m;
c=0;
cout<<"Case "<<++tc<<":"<<endl;
while(m--)
{
cin>>s;
if(s=="pushLeft")
{
cin>>x;
if(c<n)
{
c++;
cout<<"Pushed in left: "<<x<<endl;
}
else cout<<"The queue is full"<<endl;
}
else if(s=="pushRight")
{
cin>>x;
if(c<n)
{
c++;
cout<<"Pushed in right: "<<x<<endl;
}
else cout<<"The queue is full"<<endl;
}
else if(s=="popLeft")
{
if(c>0)
{
c--;
cout<<"Popped from left: "<<x<<endl;
}
else cout<<"The queue is empty"<<endl;
}
else if(s=="popRight")
{
if(c>0)
{
c--;
cout<<"Popped from right: "<<x<<endl;
}
else cout<<"The queue is empty"<<endl;
}
}
}
return 0;
} | 30.348485 | 111 | 0.288567 | kzvd4729 |
a26f2c2ba2231465a167a26707e4e8cea5d5a512 | 1,393 | cpp | C++ | structures/enum.cpp | pat-laugh/websson-libraries | c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2 | [
"MIT"
] | null | null | null | structures/enum.cpp | pat-laugh/websson-libraries | c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2 | [
"MIT"
] | 33 | 2017-04-25T21:53:59.000Z | 2017-07-14T13:30:29.000Z | structures/enum.cpp | pat-laugh/websson-libraries | c5c99a98270dee45fcd9ec4e7f03e2e74e3b1ce2 | [
"MIT"
] | null | null | null | //MIT License
//Copyright 2017 Patrick Laughrea
#include "webss.hpp"
using namespace std;
using namespace webss;
Enum::Enum(std::string name) : nspace(std::move(name)) {}
bool Enum::empty() const { return nspace.empty(); }
Enum::size_type Enum::size() const { return nspace.size(); }
void Enum::add(std::string key) { nspace.add(Entity(std::move(key), Webss(size()))); }
void Enum::addSafe(std::string key) { nspace.addSafe(Entity(std::move(key), Webss(size()))); }
bool Enum::has(const std::string& key) const { return nspace.has(key); }
bool Enum::operator==(const Enum& o) const { return nspace == o.nspace; }
bool Enum::operator!=(const Enum& o) const { return !(*this == o); }
Entity& Enum::operator[](const std::string& key) { return nspace[key]; }
const Entity& Enum::operator[](const std::string& key) const { return nspace[key]; }
Entity& Enum::at(const std::string& key) { return nspace.at(key); }
const Entity& Enum::at(const std::string& key) const { return nspace.at(key); }
const std::string& Enum::getName() const { return nspace.getName(); }
const Enum::Namespaces& Enum::getNamespaces() const { return nspace.getNamespaces(); }
Enum::iterator Enum::begin() { return nspace.begin(); }
Enum::iterator Enum::end() { return nspace.end(); }
Enum::const_iterator Enum::begin() const { return nspace.begin(); }
Enum::const_iterator Enum::end() const { return nspace.end(); } | 43.53125 | 94 | 0.690596 | pat-laugh |
a2760a1d4d6aced1e23855f32cdd4918931304ed | 830 | cpp | C++ | SimpleEngine/SimpleEngine/Vector2.cpp | Akara4ok/-__- | b6f76ae2d0e180429eb2c64911327056aa1c8357 | [
"MIT"
] | null | null | null | SimpleEngine/SimpleEngine/Vector2.cpp | Akara4ok/-__- | b6f76ae2d0e180429eb2c64911327056aa1c8357 | [
"MIT"
] | null | null | null | SimpleEngine/SimpleEngine/Vector2.cpp | Akara4ok/-__- | b6f76ae2d0e180429eb2c64911327056aa1c8357 | [
"MIT"
] | null | null | null | #include "Vector2.h"
#include <math.h>
Vector2::Vector2()
{
}
Vector2::Vector2(float x, float y) : x(x), y(y)
{
}
Vector2::Vector2(Vector2 startPoint, Vector2 endPoint)
{
Vector2 res = endPoint - startPoint;
x = res.x;
y = res.y;
}
Vector2 Vector2::getOrt()
{
float absVec = this->absValue();
return Vector2(x / absVec, y / absVec);
}
float Vector2::dot(Vector2 vec1, Vector2 vec2)
{
return vec1.x * vec2.x + vec1.y * vec2.y;
}
float Vector2::absValue()
{
return sqrt(pow(x, 2) + pow(y, 2));
}
Vector2 Vector2::operator-()
{
return Vector2(-x, -y);
}
Vector2 Vector2::operator+(const Vector2 vec1)
{
return Vector2(x + vec1.x, y + vec1.y);
}
Vector2 Vector2::operator-(const Vector2 vec1)
{
return Vector2(x - vec1.x, y - vec1.y);
}
Vector2 Vector2::operator*(const float a)
{
return Vector2(a * x, a * y);
}
| 15.37037 | 54 | 0.651807 | Akara4ok |
a2807a734b221b8beba7650019595fc63299a992 | 12,683 | cpp | C++ | src/clos/datacenter/main_ndp.cpp | Flasew/opera-sim | 1f64017883689c115b8442acab7ef52846ab2c18 | [
"BSD-3-Clause"
] | null | null | null | src/clos/datacenter/main_ndp.cpp | Flasew/opera-sim | 1f64017883689c115b8442acab7ef52846ab2c18 | [
"BSD-3-Clause"
] | null | null | null | src/clos/datacenter/main_ndp.cpp | Flasew/opera-sim | 1f64017883689c115b8442acab7ef52846ab2c18 | [
"BSD-3-Clause"
] | null | null | null | // -*- c-basic-offset: 4; tab-width: 8; indent-tabs-mode: t -*-
#include "config.h"
#include <sstream>
#include <strstream>
#include <iostream>
#include <string.h>
#include <math.h>
#include "network.h"
#include "randomqueue.h"
#include "subflow_control.h"
//#include "shortflows.h"
#include "pipe.h"
#include "eventlist.h"
#include "logfile.h"
#include "loggers.h"
#include "clock.h"
#include "ndp.h"
#include "compositequeue.h"
#include "firstfit.h"
#include "topology.h"
//#include "connection_matrix.h"
#include "ndp_transfer.h"
//#include "vl2_topology.h"
#include "fat_tree_topology.h"
//#include "oversubscribed_fat_tree_topology.h"
//#include "multihomed_fat_tree_topology.h"
//#include "star_topology.h"
//#include "bcube_topology.h"
#include <list>
// Simulation params
#define PRINT_PATHS 0
#define PERIODIC 0
#include "main.h"
//int RTT = 10; // this is per link delay; identical RTT microseconds = 0.02 ms
uint32_t RTT = 1; // this is per link delay in us; identical RTT microseconds = 0.001 ms
int DEFAULT_NODES = 250;
//int N=128;
FirstFit* ff = NULL;
unsigned int subflow_count = 1;
string ntoa(double n);
string itoa(uint64_t n);
//#define SWITCH_BUFFER (SERVICE * RTT / 1000)
#define USE_FIRST_FIT 0
#define FIRST_FIT_INTERVAL 100
EventList eventlist;
Logfile* lg;
void exit_error(char* progr) {
cout << "Usage " << progr << " [UNCOUPLED(DEFAULT)|COUPLED_INC|FULLY_COUPLED|COUPLED_EPSILON] [epsilon][COUPLED_SCALABLE_TCP" << endl;
exit(1);
}
void print_path(std::ofstream &paths,const Route* rt){
for (unsigned int i=1;i<rt->size()-1;i+=2){
RandomQueue* q = (RandomQueue*)rt->at(i);
if (q!=NULL)
paths << q->str() << " ";
else
paths << "NULL ";
}
paths<<endl;
}
int main(int argc, char **argv) {
Packet::set_packet_size(9000);
eventlist.setEndtime(timeFromSec(0.201));
Clock c(timeFromSec(5 / 100.), eventlist);
int algo = COUPLED_EPSILON;
double epsilon = 1;
int no_of_conns = 0, cwnd = 15, no_of_nodes = DEFAULT_NODES;
stringstream filename(ios_base::out);
int i = 1;
filename << "logout.dat";
while (i<argc) {
if (!strcmp(argv[i],"-o")){
filename.str(std::string());
filename << argv[i+1];
i++;
} else if (!strcmp(argv[i],"-sub")){
subflow_count = atoi(argv[i+1]);
i++;
} else if (!strcmp(argv[i],"-conns")){
no_of_conns = atoi(argv[i+1]);
cout << "no_of_conns "<<no_of_conns << endl;
i++;
} else if (!strcmp(argv[i],"-nodes")){
no_of_nodes = atoi(argv[i+1]);
cout << "no_of_nodes "<<no_of_nodes << endl;
i++;
} else if (!strcmp(argv[i],"-cwnd")){
cwnd = atoi(argv[i+1]);
cout << "cwnd "<< cwnd << endl;
i++;
} else if (!strcmp(argv[i], "UNCOUPLED"))
algo = UNCOUPLED;
else if (!strcmp(argv[i], "COUPLED_INC"))
algo = COUPLED_INC;
else if (!strcmp(argv[i], "FULLY_COUPLED"))
algo = FULLY_COUPLED;
else if (!strcmp(argv[i], "COUPLED_TCP"))
algo = COUPLED_TCP;
else if (!strcmp(argv[i], "COUPLED_SCALABLE_TCP"))
algo = COUPLED_SCALABLE_TCP;
else if (!strcmp(argv[i], "COUPLED_EPSILON")) {
algo = COUPLED_EPSILON;
if (argc > i+1){
epsilon = atof(argv[i+1]);
i++;
}
printf("Using epsilon %f\n", epsilon);
} else
exit_error(argv[0]);
i++;
}
srand(13);
cout << "Using subflow count " << subflow_count <<endl;
cout << "Using algo="<<algo<< " epsilon=" << epsilon << endl;
// prepare the loggers
cout << "Logging to " << filename.str() << endl;
//Logfile
Logfile logfile(filename.str(), eventlist);
#if PRINT_PATHS
filename << ".paths";
cout << "Logging path choices to " << filename.str() << endl;
std::ofstream paths(filename.str().c_str());
if (!paths){
cout << "Can't open for writing paths file!"<<endl;
exit(1);
}
#endif
int tot_subs = 0;
int cnt_con = 0;
lg = &logfile;
logfile.setStartTime(timeFromSec(0));
NdpSinkLoggerSampling sinkLogger = NdpSinkLoggerSampling(timeFromMs(10), eventlist);
logfile.addLogger(sinkLogger);
NdpTrafficLogger traffic_logger = NdpTrafficLogger();
logfile.addLogger(traffic_logger);
NdpSrc* ndpSrc;
NdpSink* ndpSnk;
Route* routeout, *routein;
double extrastarttime;
NdpRtxTimerScanner ndpRtxScanner(timeFromMs(10), eventlist);
int dest;
#if USE_FIRST_FIT
if (subflow_count==1){
ff = new FirstFit(timeFromMs(FIRST_FIT_INTERVAL),eventlist);
}
#endif
#ifdef FAT_TREE
FatTreeTopology* top = new FatTreeTopology(no_of_nodes, memFromPkt(8), &logfile, &eventlist,ff,COMPOSITE,1);
#endif
#ifdef OV_FAT_TREE
OversubscribedFatTreeTopology* top = new OversubscribedFatTreeTopology(&logfile, &eventlist,ff);
#endif
#ifdef MH_FAT_TREE
MultihomedFatTreeTopology* top = new MultihomedFatTreeTopology(&logfile, &eventlist,ff);
#endif
#ifdef STAR
StarTopology* top = new StarTopology(&logfile, &eventlist,ff);
#endif
#ifdef BCUBE
BCubeTopology* top = new BCubeTopology(&logfile,&eventlist,ff);
cout << "BCUBE " << K << endl;
#endif
#ifdef VL2
VL2Topology* top = new VL2Topology(&logfile,&eventlist,ff);
#endif
vector<const Route*>*** net_paths;
net_paths = new vector<const Route*>**[no_of_nodes];
int* is_dest = new int[no_of_nodes];
for (int i=0;i<no_of_nodes;i++){
is_dest[i] = 0;
net_paths[i] = new vector<const Route*>*[no_of_nodes];
for (int j = 0;j<no_of_nodes;j++)
net_paths[i][j] = NULL;
}
#if USE_FIRST_FIT
if (ff)
ff->net_paths = net_paths;
#endif
vector<int>* destinations;
// Permutation connections
ConnectionMatrix* conns = new ConnectionMatrix(no_of_nodes);
//conns->setLocalTraffic(top);
cout << "Running perm with " << no_of_conns << " connections" << endl;
conns->setPermutation(no_of_conns);
//conns->setStride(no_of_conns);
//conns->setStaggeredPermutation(top,(double)no_of_conns/100.0);
//conns->setStaggeredRandom(top,512,1);
//conns->setHotspot(no_of_conns,512/no_of_conns);
//conns->setManytoMany(128);
//conns->setVL2();
//conns->setRandom(no_of_conns);
map<int,vector<int>*>::iterator it;
// used just to print out stats data at the end
list <const Route*> routes;
int connID = 0;
for (it = conns->connections.begin(); it!=conns->connections.end();it++){
int src = (*it).first;
destinations = (vector<int>*)(*it).second;
vector<int> subflows_chosen;
for (unsigned int dst_id = 0;dst_id<destinations->size();dst_id++){
connID++;
dest = destinations->at(dst_id);
if (!net_paths[src][dest]) {
vector<const Route*>* paths = top->get_paths(src,dest);
net_paths[src][dest] = paths;
for (unsigned int i = 0; i < paths->size(); i++) {
routes.push_back((*paths)[i]);
}
}
if (!net_paths[dest][src]) {
vector<const Route*>* paths = top->get_paths(dest,src);
net_paths[dest][src] = paths;
}
for (int connection=0;connection<1;connection++){
subflows_chosen.clear();
int it_sub;
int crt_subflow_count = subflow_count;
tot_subs += crt_subflow_count;
cnt_con ++;
it_sub = crt_subflow_count > net_paths[src][dest]->size()?net_paths[src][dest]->size():crt_subflow_count;
//if (connID%10!=0)
//it_sub = 1;
if (connID==-1){
ndpSrc = new NdpSrcTransfer(NULL, NULL, eventlist);
ndpSnk = new NdpSinkTransfer(eventlist, 1 /*pull at line rate*/);
} else {
ndpSrc = new NdpSrc(NULL, NULL, eventlist);
ndpSnk = new NdpSink(eventlist, 1 /*pull at line rate*/);
}
ndpSrc->setCwnd(cwnd*Packet::data_packet_size());
ndpSrc->setName("ndp_" + ntoa(src) + "_" + ntoa(dest)+"("+ntoa(connection)+")");
logfile.writeName(*ndpSrc);
ndpSnk->setName("ndp_sink_" + ntoa(src) + "_" + ntoa(dest)+ "("+ntoa(connection)+")");
logfile.writeName(*ndpSnk);
ndpRtxScanner.registerNdp(*ndpSrc);
int choice = 0;
#ifdef FAT_TREE
choice = rand()%net_paths[src][dest]->size();
#endif
#ifdef OV_FAT_TREE
choice = rand()%net_paths[src][dest]->size();
#endif
#ifdef MH_FAT_TREE
int use_all = it_sub==net_paths[src][dest]->size();
if (use_all)
choice = inter;
else
choice = rand()%net_paths[src][dest]->size();
#endif
#ifdef VL2
choice = rand()%net_paths[src][dest]->size();
#endif
#ifdef STAR
choice = 0;
#endif
#ifdef BCUBE
//choice = inter;
int min = -1, max = -1,minDist = 1000,maxDist = 0;
if (subflow_count==1){
//find shortest and longest path
for (int dd=0;dd<net_paths[src][dest]->size();dd++){
if (net_paths[src][dest]->at(dd)->size()<minDist){
minDist = net_paths[src][dest]->at(dd)->size();
min = dd;
}
if (net_paths[src][dest]->at(dd)->size()>maxDist){
maxDist = net_paths[src][dest]->at(dd)->size();
max = dd;
}
}
choice = min;
}
else
choice = rand()%net_paths[src][dest]->size();
#endif
//cout << "Choice "<<choice<<" out of "<<net_paths[src][dest]->size();
subflows_chosen.push_back(choice);
/*if (net_paths[src][dest]->size()==K*K/4 && it_sub<=K/2){
int choice2 = rand()%(K/2);*/
if (choice>=net_paths[src][dest]->size()){
printf("Weird path choice %d out of %lu\n",choice,net_paths[src][dest]->size());
exit(1);
}
#if PRINT_PATHS
for (int ll=0;ll<net_paths[src][dest]->size();ll++){
paths << "Route from "<< ntoa(src) << " to " << ntoa(dest) << " (" << ll << ") -> " ;
print_path(paths,net_paths[src][dest]->at(ll));
}
/* if (src>=12){
assert(net_paths[src][dest]->size()>1);
net_paths[src][dest]->erase(net_paths[src][dest]->begin());
paths << "Killing entry!" << endl;
if (choice>=net_paths[src][dest]->size())
choice = 0;
}*/
#endif
routeout = new Route(*(net_paths[src][dest]->at(choice)));
routeout->push_back(ndpSnk);
routein = new Route();
routein = new Route(*top->get_paths(dest,src)->at(choice));
routein->push_back(ndpSrc);
extrastarttime = 0 * drand();
ndpSrc->connect(*routeout, *routein, *ndpSnk, timeFromMs(extrastarttime));
#ifdef PACKET_SCATTER
ndpSrc->set_paths(net_paths[src][dest]);
ndpSnk->set_paths(net_paths[dest][src]);
cout << "Using PACKET SCATTER!!!!"<<endl;
vector<const Route*>* rts = net_paths[src][dest];
const Route* rt = rts->at(0);
PacketSink* first_queue = rt->at(0);
if (ndpSrc->_log_me) {
cout << "First hop: " << first_queue->nodename() << endl;
QueueLoggerSimple queue_logger = QueueLoggerSimple();
logfile.addLogger(queue_logger);
((Queue*)first_queue)->setLogger(&queue_logger);
//ndpSrc->set_traffic_logger(&traffic_logger);
}
#endif
// if (ff)
// ff->add_flow(src,dest,ndpSrc);
sinkLogger.monitorSink(ndpSnk);
}
}
}
// ShortFlows* sf = new ShortFlows(2560, eventlist, net_paths,conns,lg, &ndpRtxScanner);
cout << "Mean number of subflows " << ntoa((double)tot_subs/cnt_con)<<endl;
// Record the setup
int pktsize = Packet::data_packet_size();
logfile.write("# pktsize=" + ntoa(pktsize) + " bytes");
logfile.write("# subflows=" + ntoa(subflow_count));
logfile.write("# hostnicrate = " + ntoa(HOST_NIC) + " pkt/sec");
logfile.write("# corelinkrate = " + ntoa(HOST_NIC*CORE_TO_HOST) + " pkt/sec");
//logfile.write("# buffer = " + ntoa((double) (queues_na_ni[0][1]->_maxsize) / ((double) pktsize)) + " pkt");
double rtt = timeAsSec(timeFromUs(RTT));
logfile.write("# rtt =" + ntoa(rtt));
// GO!
while (eventlist.doNextEvent()) {
}
cout << "Done" << endl;
list <const Route*>::iterator rt_i;
int counts[10]; int hop;
for (int i = 0; i < 10; i++)
counts[i] = 0;
for (rt_i = routes.begin(); rt_i != routes.end(); rt_i++) {
const Route* r = (*rt_i);
//print_route(*r);
cout << "Path:" << endl;
hop = 0;
for (int i = 0; i < r->size(); i++) {
PacketSink *ps = r->at(i);
CompositeQueue *q = dynamic_cast<CompositeQueue*>(ps);
if (q == 0) {
cout << ps->nodename() << endl;
} else {
cout << q->nodename() << " id=" << q->id << " " << q->num_packets() << "pkts "
<< q->num_headers() << "hdrs " << q->num_acks() << "acks " << q->num_nacks() << "nacks " << q->num_stripped() << "stripped"
<< endl;
counts[hop] += q->num_stripped();
hop++;
}
}
cout << endl;
}
for (int i = 0; i < 10; i++)
cout << "Hop " << i << " Count " << counts[i] << endl;
}
string ntoa(double n) {
stringstream s;
s << n;
return s.str();
}
string itoa(uint64_t n) {
stringstream s;
s << n;
return s.str();
}
| 27.042644 | 138 | 0.617046 | Flasew |
a2817ca1576245ab8567164ff9ecb334720a638e | 7,838 | cpp | C++ | src/app/clusters/bindings/BindingManager.cpp | sandcatone/connectedhomeip | 098e45578cc34c687feb4b3ecc92b79be8c72716 | [
"Apache-2.0"
] | 1 | 2022-02-21T08:33:37.000Z | 2022-02-21T08:33:37.000Z | src/app/clusters/bindings/BindingManager.cpp | sandcatone/connectedhomeip | 098e45578cc34c687feb4b3ecc92b79be8c72716 | [
"Apache-2.0"
] | null | null | null | src/app/clusters/bindings/BindingManager.cpp | sandcatone/connectedhomeip | 098e45578cc34c687feb4b3ecc92b79be8c72716 | [
"Apache-2.0"
] | null | null | null | /*
*
* Copyright (c) 2022 Project CHIP Authors
*
* 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 <app/clusters/bindings/BindingManager.h>
#include <app/util/binding-table.h>
#include <credentials/FabricTable.h>
namespace {
class BindingFabricTableDelegate : public chip::FabricTableDelegate
{
void OnFabricDeletedFromStorage(chip::CompressedFabricId compressedFabricId, chip::FabricIndex fabricIndex)
{
for (uint8_t i = 0; i < EMBER_BINDING_TABLE_SIZE; i++)
{
EmberBindingTableEntry entry;
emberGetBinding(i, &entry);
if (entry.fabricIndex == fabricIndex)
{
ChipLogProgress(Zcl, "Remove binding for fabric %d\n", entry.fabricIndex);
entry.type = EMBER_UNUSED_BINDING;
}
}
chip::BindingManager::GetInstance().FabricRemoved(compressedFabricId, fabricIndex);
}
// Intentionally left blank
void OnFabricRetrievedFromStorage(chip::FabricInfo * fabricInfo) {}
// Intentionally left blank
void OnFabricPersistedToStorage(chip::FabricInfo * fabricInfo) {}
};
BindingFabricTableDelegate gFabricTableDelegate;
} // namespace
namespace {
chip::PeerId PeerIdForNode(chip::FabricTable & fabricTable, chip::FabricIndex fabric, chip::NodeId node)
{
chip::FabricInfo * fabricInfo = fabricTable.FindFabricWithIndex(fabric);
if (fabricInfo == nullptr)
{
return chip::PeerId();
}
return fabricInfo->GetPeerIdForNode(node);
}
} // namespace
namespace chip {
BindingManager BindingManager::sBindingManager;
CHIP_ERROR BindingManager::UnicastBindingCreated(const EmberBindingTableEntry & bindingEntry)
{
return EstablishConnection(bindingEntry.fabricIndex, bindingEntry.nodeId);
}
CHIP_ERROR BindingManager::UnicastBindingRemoved(uint8_t bindingEntryId)
{
EmberBindingTableEntry entry{};
emberGetBinding(bindingEntryId, &entry);
mPendingNotificationMap.RemoveEntry(bindingEntryId);
return CHIP_NO_ERROR;
}
void BindingManager::SetAppServer(Server * appServer)
{
mAppServer = appServer;
mAppServer->GetFabricTable().AddFabricDelegate(&gFabricTableDelegate);
}
CHIP_ERROR BindingManager::EstablishConnection(FabricIndex fabric, NodeId node)
{
VerifyOrReturnError(mAppServer != nullptr, CHIP_ERROR_INCORRECT_STATE);
PeerId peer = PeerIdForNode(mAppServer->GetFabricTable(), fabric, node);
VerifyOrReturnError(peer.GetNodeId() != kUndefinedNodeId, CHIP_ERROR_NOT_FOUND);
CHIP_ERROR error =
mAppServer->GetCASESessionManager()->FindOrEstablishSession(peer, &mOnConnectedCallback, &mOnConnectionFailureCallback);
if (error == CHIP_ERROR_NO_MEMORY)
{
// Release the least recently used entry
// TODO: Some reference counting mechanism shall be added the CASESessionManager
// so that other session clients don't get accidentally closed.
FabricIndex fabricToRemove;
NodeId nodeToRemove;
if (mPendingNotificationMap.FindLRUConnectPeer(&fabricToRemove, &nodeToRemove) == CHIP_NO_ERROR)
{
mPendingNotificationMap.RemoveAllEntriesForNode(fabricToRemove, nodeToRemove);
PeerId lruPeer = PeerIdForNode(mAppServer->GetFabricTable(), fabricToRemove, nodeToRemove);
mAppServer->GetCASESessionManager()->ReleaseSession(lruPeer);
// Now retry
error = mAppServer->GetCASESessionManager()->FindOrEstablishSession(peer, &mOnConnectedCallback,
&mOnConnectionFailureCallback);
}
}
return error;
}
void BindingManager::HandleDeviceConnected(void * context, OperationalDeviceProxy * device)
{
BindingManager * manager = static_cast<BindingManager *>(context);
manager->HandleDeviceConnected(device);
}
void BindingManager::HandleDeviceConnected(OperationalDeviceProxy * device)
{
FabricIndex fabricToRemove = kUndefinedFabricIndex;
NodeId nodeToRemove = kUndefinedNodeId;
// Note: not using a const ref here, because the mPendingNotificationMap
// iterator returns things by value anyway.
for (PendingNotificationEntry pendingNotification : mPendingNotificationMap)
{
EmberBindingTableEntry entry;
emberGetBinding(pendingNotification.mBindingEntryId, &entry);
PeerId peer = PeerIdForNode(mAppServer->GetFabricTable(), entry.fabricIndex, entry.nodeId);
if (device->GetPeerId() == peer)
{
fabricToRemove = entry.fabricIndex;
nodeToRemove = entry.nodeId;
mBoundDeviceChangedHandler(&entry, device, pendingNotification.mContext);
}
}
mPendingNotificationMap.RemoveAllEntriesForNode(fabricToRemove, nodeToRemove);
}
void BindingManager::HandleDeviceConnectionFailure(void * context, PeerId peerId, CHIP_ERROR error)
{
BindingManager * manager = static_cast<BindingManager *>(context);
manager->HandleDeviceConnectionFailure(peerId, error);
}
void BindingManager::HandleDeviceConnectionFailure(PeerId peerId, CHIP_ERROR error)
{
// Simply release the entry, the connection will be re-established as needed.
ChipLogError(AppServer, "Failed to establish connection to node 0x" ChipLogFormatX64, ChipLogValueX64(peerId.GetNodeId()));
mAppServer->GetCASESessionManager()->ReleaseSession(peerId);
}
void BindingManager::FabricRemoved(CompressedFabricId compressedFabricId, FabricIndex fabricIndex)
{
mPendingNotificationMap.RemoveAllEntriesForFabric(fabricIndex);
mAppServer->GetCASESessionManager()->ReleaseSessionForFabric(compressedFabricId);
}
CHIP_ERROR BindingManager::NotifyBoundClusterChanged(EndpointId endpoint, ClusterId cluster, void * context)
{
VerifyOrReturnError(mAppServer != nullptr, CHIP_ERROR_INCORRECT_STATE);
for (uint8_t i = 0; i < EMBER_BINDING_TABLE_SIZE; i++)
{
EmberBindingTableEntry entry;
if (emberGetBinding(i, &entry) == EMBER_SUCCESS && entry.type != EMBER_UNUSED_BINDING && entry.local == endpoint &&
entry.clusterId == cluster)
{
if (entry.type == EMBER_UNICAST_BINDING)
{
FabricInfo * fabricInfo = mAppServer->GetFabricTable().FindFabricWithIndex(entry.fabricIndex);
VerifyOrReturnError(fabricInfo != nullptr, CHIP_ERROR_NOT_FOUND);
PeerId peer = fabricInfo->GetPeerIdForNode(entry.nodeId);
OperationalDeviceProxy * peerDevice = mAppServer->GetCASESessionManager()->FindExistingSession(peer);
if (peerDevice != nullptr && mBoundDeviceChangedHandler)
{
// We already have an active connection
mBoundDeviceChangedHandler(&entry, peerDevice, context);
}
else
{
mPendingNotificationMap.AddPendingNotification(i, context);
ReturnErrorOnFailure(EstablishConnection(entry.fabricIndex, entry.nodeId));
}
}
else if (entry.type == EMBER_MULTICAST_BINDING)
{
mBoundDeviceChangedHandler(&entry, nullptr, context);
}
}
}
return CHIP_NO_ERROR;
}
} // namespace chip
| 38.610837 | 128 | 0.698648 | sandcatone |
a289b97bc3f4a3bbf96e28e9c84cd6c2cba9fa6c | 1,228 | cpp | C++ | src/coremods/core_maps/cmd_hsearch.cpp | BerilBBJ/beryldb | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 206 | 2021-04-27T21:44:24.000Z | 2022-02-23T12:01:20.000Z | src/coremods/core_maps/cmd_hsearch.cpp | BerilBBJ/beryldb | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 10 | 2021-05-04T19:46:59.000Z | 2021-10-01T23:43:07.000Z | src/coremods/core_maps/cmd_hsearch.cpp | berylcorp/beryl | 6569b568796e4cea64fe7f42785b0319541a0284 | [
"BSD-3-Clause"
] | 7 | 2021-04-28T16:17:56.000Z | 2021-12-10T01:14:42.000Z | /*
* BerylDB - A lightweight database.
* http://www.beryldb.com
*
* Copyright (C) 2021 - Carlos F. Ferry <cferry@beryldb.com>
*
* This file is part of BerylDB. BerylDB is free software: you can
* redistribute it and/or modify it under the terms of the BSD License
* version 3.
*
* More information about our licensing can be found at https://docs.beryl.dev
*/
#include "beryl.h"
#include "core_maps.h"
CommandHKeys::CommandHKeys(Module* Creator) : Command(Creator, "HKEYS", 1, 3)
{
run_conf = true;
group = 'm';
syntax = "<map> <offset> <limit>";
}
COMMAND_RESULT CommandHKeys::Handle(User* user, const Params& parameters)
{
KeyHelper::RetroLimits(user, std::make_shared<hfind_query>(), parameters[0], this->offset, this->limit, true);
return SUCCESS;
}
CommandHList::CommandHList(Module* Creator) : Command(Creator, "HLIST", 1, 3)
{
run_conf = true;
check_key = 0;
group = 'm';
syntax = "<map> <offset> <limit>";
}
COMMAND_RESULT CommandHList::Handle(User* user, const Params& parameters)
{
KeyHelper::RetroLimits(user, std::make_shared<hlist_query>(), parameters[0], this->offset, this->limit);
return SUCCESS;
} | 29.238095 | 117 | 0.653094 | BerilBBJ |
a28a480d9778d00f5ce0e68a335ae73c36c6160c | 3,092 | cpp | C++ | AdaptiveHistogramEqualization.cpp | javierjuan/ONTs | d27168ceafac70f729df7a9138285e2352a49e99 | [
"Apache-2.0"
] | null | null | null | AdaptiveHistogramEqualization.cpp | javierjuan/ONTs | d27168ceafac70f729df7a9138285e2352a49e99 | [
"Apache-2.0"
] | null | null | null | AdaptiveHistogramEqualization.cpp | javierjuan/ONTs | d27168ceafac70f729df7a9138285e2352a49e99 | [
"Apache-2.0"
] | null | null | null | /***************************************************************************
/* Javier Juan Albarracin - jajuaal1@ibime.upv.es */
/* Universidad Politecnica de Valencia, Spain */
/* */
/* Copyright (C) 2020 Javier Juan Albarracin */
/* */
/***************************************************************************
* Adaptive histogram Equalization *
***************************************************************************/
#include <ITKUtils.hpp>
#include <itkImage.h>
#include <itkAdaptiveHistogramEqualizationImageFilter.h>
template<typename ImageType>
void AdaptiveHistogramEqualization(int argc, char *argv[])
{
using AdaptiveHistogramEqualizationImageFilterType = itk::AdaptiveHistogramEqualizationImageFilter<ImageType>;
// Read image
typename ImageType::Pointer image = ITKUtils::ReadNIfTIImage<ImageType>(std::string(argv[1]));
// Default radius, alpha and beta parameters
unsigned int radius = 3;
double alpha = 0.8;
double beta = 1;
// Get user parameters
if (argc > 3)
radius = (unsigned int) std::atoi(argv[3]);
if (argc > 4)
alpha = std::strtod(argv[4], NULL);
if (argc > 5)
beta = std::strtod(argv[5], NULL);
// Adaptive Histogram equalization
typename AdaptiveHistogramEqualizationImageFilterType::Pointer filter = AdaptiveHistogramEqualizationImageFilterType::New();
filter->SetInput(image);
filter->SetRadius(radius);
filter->SetAlpha(alpha);
filter->SetBeta(beta);
// Save image
ITKUtils::WriteNIfTIImage<ImageType>(filter->GetOutput(), std::string(argv[2]));
}
int main(int argc, char *argv[])
{
if (argc < 3)
{
std::cerr << "Error! Invalid number of arguments!" << std::endl << "Usage: AdaptiveHistogramEqualization inputImage outputImage [radius=3] [alpha=0.8] [beta=1]" << std::endl;
return EXIT_FAILURE;
}
typename itk::ImageIOBase::Pointer imageIO = ITKUtils::ReadImageInformation(std::string(argv[1]));
const unsigned int ImageDimension = imageIO->GetNumberOfDimensions();
if (ImageDimension < 2 || ImageDimension > 4)
{
std::cerr << "Unsupported image dimensions" << std::endl;
return EXIT_FAILURE;
}
try
{
if (ImageDimension == 2)
AdaptiveHistogramEqualization<itk::Image<float, 2>>(argc, argv);
else if (ImageDimension == 3)
AdaptiveHistogramEqualization<itk::Image<float, 3>>(argc, argv);
else
AdaptiveHistogramEqualization<itk::Image<float, 4>>(argc, argv);
}
catch (itk::ExceptionObject & err)
{
std::cerr << "ExceptionObject caught !" << std::endl;
std::cerr << err << std::endl;
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
} | 39.641026 | 183 | 0.538486 | javierjuan |
a28aed4c23005743f37594ee9807cecfb6013dd0 | 85,343 | cpp | C++ | src/prod/src/Reliability/Replication/ReplicateCopyOperations.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 2,542 | 2018-03-14T21:56:12.000Z | 2019-05-06T01:18:20.000Z | src/prod/src/Reliability/Replication/ReplicateCopyOperations.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 994 | 2019-05-07T02:39:30.000Z | 2022-03-31T13:23:04.000Z | src/prod/src/Reliability/Replication/ReplicateCopyOperations.Test.cpp | vishnuk007/service-fabric | d0afdea185ae932cc3c9eacf179692e6fddbc630 | [
"MIT"
] | 300 | 2018-03-14T21:57:17.000Z | 2019-05-06T20:07:00.000Z | // ------------------------------------------------------------
// 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"
#include <boost/test/unit_test.hpp>
#include "Common/boost-taef.h"
#include "ComTestStatefulServicePartition.h"
#include "ComTestStateProvider.h"
#include "ComTestOperation.h"
namespace ReplicationUnitTest
{
using namespace Common;
using namespace std;
using namespace Reliability::ReplicationComponent;
typedef std::shared_ptr<REConfig> REConfigSPtr;
static Common::StringLiteral const ReplCopyTestSource("ReplCopyTest");
class TestReplicateCopyOperations
{
protected:
TestReplicateCopyOperations() { BOOST_REQUIRE(Setup()); }
public:
TEST_CLASS_SETUP(Setup);
static void TestReplicateWithRetry(bool hasPersistedState);
static void TestCopyWithRetry(bool hasPersistedState);
static void TestReplicateAndCopy(bool hasPersistedState);
static REConfigSPtr CreateGenericConfig();
static ReplicationTransportSPtr CreateTransport(REConfigSPtr const & config);
class DummyRoot : public Common::ComponentRoot
{
};
static Common::ComponentRoot const & GetRoot();
};
namespace {
typedef std::function<void(std::wstring const &)> MessageReceivedCallback;
static uint MaxQueueCapacity = 8;
class ReplicatorTestWrapper;
class PrimaryReplicatorHelper : public Common::ComponentRoot
{
public:
PrimaryReplicatorHelper(
REConfigSPtr const & config,
bool hasPersistedState,
FABRIC_EPOCH const & epoch,
int64 numberOfCopyOperations,
int64 numberOfCopyContextOperations,
Common::Guid partitionId);
virtual ~PrimaryReplicatorHelper() {}
__declspec(property(get=get_PrimaryId)) FABRIC_REPLICA_ID PrimaryId;
FABRIC_REPLICA_ID get_PrimaryId() const { return primaryId_; }
__declspec(property(get=get_EndpointUniqueId)) ReplicationEndpointId const & EndpointUniqueId;
ReplicationEndpointId const & get_EndpointUniqueId() const { return endpointUniqueId_; }
ReplicationEndpointId const & get_ReplicationEndpointId() const { return endpointUniqueId_; }
virtual void ProcessMessage(__in Transport::Message & message, __out Transport::ReceiverContextUPtr &);
class PrimaryReplicatorWrapper : public PrimaryReplicator
{
public:
PrimaryReplicatorWrapper(
REConfigSPtr const & config,
REPerformanceCountersSPtr & perfCounters,
FABRIC_REPLICA_ID replicaId,
bool hasPersistedState,
ReplicationEndpointId const & endpointUniqueId,
FABRIC_EPOCH const & epoch,
ReplicationTransportSPtr const & transport,
ComProxyStateProvider const & provider,
IReplicatorHealthClientSPtr & healthClient,
ApiMonitoringWrapperSPtr & monitor);
virtual ~PrimaryReplicatorWrapper() {}
virtual void ReplicationAckMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader, PrimaryReplicatorWPtr primaryWPtr);
virtual void CopyContextMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader);
void AddExpectedAck(int64 secondaryId, FABRIC_SEQUENCE_NUMBER replLSN, FABRIC_SEQUENCE_NUMBER copyLSN)
{
Common::AcquireExclusiveLock lock(this->lock_);
AddAckCallerHoldsLock(expectedAcks_, secondaryId, replLSN, copyLSN);
}
void CheckAcks() const;
void AddExpectedCopyContextMessage(ReplicationEndpointId const & fromDemuxer, FABRIC_SEQUENCE_NUMBER sequuenceNumber);
void CheckMessages();
private:
typedef pair<FABRIC_SEQUENCE_NUMBER, FABRIC_SEQUENCE_NUMBER> AckReplCopyPair;
typedef map<int64, AckReplCopyPair> AckReplCopyMap;
static void AddAckCallerHoldsLock(
__in AckReplCopyMap & ackMap, int64 secondaryId, FABRIC_SEQUENCE_NUMBER replLSN, FABRIC_SEQUENCE_NUMBER copyLSN);
static void DumpAckTable(AckReplCopyMap const & mapToDump);
vector<wstring> expectedMessages_;
vector<wstring> receivedMessages_;
AckReplCopyMap receivedAcks_;
AckReplCopyMap expectedAcks_;
mutable Common::ExclusiveLock lock_;
FABRIC_REPLICA_ID id_;
};
__declspec(property(get=get_Replicator)) PrimaryReplicatorWrapper & Replicator;
PrimaryReplicatorWrapper & get_Replicator() { return *(wrapper_.get()); }
void Open();
void Close();
void CheckCurrentProgress(FABRIC_SEQUENCE_NUMBER expectedLsn) const
{
FABRIC_SEQUENCE_NUMBER lsn;
ErrorCode error = wrapper_->GetCurrentProgress(lsn);
VERIFY_IS_TRUE(error.IsSuccess(), L"Primary.GetCurrentProgress succeeded");
VERIFY_ARE_EQUAL_FMT(
lsn,
expectedLsn,
"GetCurrentProgress returned {0}, expected {1}", lsn, expectedLsn);
}
void CheckCatchUpCapability(FABRIC_SEQUENCE_NUMBER expectedLsn) const
{
// Catchup capability check is done usually after "catchup" async operation completes
// In the past, catchup async op completed by looking at the state of the operation queue's -> If there were NO pending operations, catchup completed.
// However, from now, operations are completed in the queue as and when all replicas send a receive ACK + quorum of them send apply ACK.
// As a result, the catchup operation does not depend on the pending operation check in the queue
//
// Catchup completes purely based on the progress of replicas in the CC and in some cases, when there are idle replicas, before their receive ACK's are processed,
// catch up operation completes.
// So we have a retry logic here
FABRIC_SEQUENCE_NUMBER lsn;
for (int i = 0; i < 30; i++)
{
ErrorCode error = wrapper_->GetCatchUpCapability(lsn);
VERIFY_IS_TRUE(error.IsSuccess(), L"Primary.GetCatchUpCapability succeeded");
if (lsn == expectedLsn) break;
else Sleep(10);
}
VERIFY_ARE_EQUAL_FMT(
lsn,
expectedLsn,
"GetCatchUpCapability returned {0}, expected {1}", lsn, expectedLsn);
}
private:
static FABRIC_REPLICA_ID PrimaryReplicaId;
REPerformanceCountersSPtr perfCounters_;
FABRIC_REPLICA_ID primaryId_;
ReplicationEndpointId endpointUniqueId_;
ReplicationTransportSPtr primaryTransport_;
shared_ptr<PrimaryReplicatorWrapper> wrapper_;
};
class SecondaryReplicatorHelper : public Common::ComponentRoot
{
public:
SecondaryReplicatorHelper(
REConfigSPtr const & config,
FABRIC_REPLICA_ID replicaId,
bool hasPersistedState,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
Common::Guid partitionId,
bool dropReplicationAcks);
virtual ~SecondaryReplicatorHelper() {}
__declspec(property(get=get_SecondaryId)) FABRIC_REPLICA_ID SecondaryId;
FABRIC_REPLICA_ID get_SecondaryId() const { return secondaryId_; }
__declspec(property(get=get_ReplicationEndpoint)) std::wstring const & ReplicationEndpoint;
std::wstring const & get_ReplicationEndpoint() const { return endpoint_; }
__declspec(property(get=get_EndpointUniqueId)) ReplicationEndpointId const & EndpointUniqueId;
ReplicationEndpointId const & get_EndpointUniqueId() const { return endpointUniqueId_; }
ReplicationEndpointId const & get_ReplicationEndpointId() const { return endpointUniqueId_; }
virtual void ProcessMessage(__in Transport::Message & message, __out Transport::ReceiverContextUPtr &);
class SecondaryReplicatorWrapper : public SecondaryReplicator
{
public:
SecondaryReplicatorWrapper(
REConfigSPtr const & config,
REPerformanceCountersSPtr & perfCounters,
FABRIC_REPLICA_ID replicaId,
bool hasPersistedState,
ReplicationEndpointId const & endpointUniqueId,
ReplicationTransportSPtr const & transport,
ComProxyStateProvider const & provider,
bool dropReplicationAcks,
IReplicatorHealthClientSPtr & healthClient,
ApiMonitoringWrapperSPtr & monitor);
virtual ~SecondaryReplicatorWrapper() {}
void SetDropCopyAcks(bool dropCopyAcks);
void SetMessageReceivedCallback(MessageReceivedCallback callback) { callback_ = callback; }
virtual void ReplicationOperationMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader);
virtual void CopyOperationMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader);
virtual void StartCopyMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader);
virtual void CopyContextAckMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader);
virtual void RequestAckMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader);
void CheckMessages();
void AddExpectedCopyMessage(ReplicationEndpointId const & fromDemuxer, FABRIC_SEQUENCE_NUMBER seq);
void AddExpectedReplicationMessage(ReplicationEndpointId const & fromDemuxer, FABRIC_SEQUENCE_NUMBER sequenceNumber);
void AddExpectedStartCopyMessage(ReplicationEndpointId const & fromDemuxer);
void AddExpectedCopyContextAckMessage(ReplicationEndpointId const & fromDemuxer, FABRIC_SEQUENCE_NUMBER sequuenceNumber);
private:
vector<wstring> expectedMessages_;
vector<wstring> receivedMessages_;
bool dropReplicationAcks_;
bool dropCopyAcks_;
bool dropCurrentAck_;
bool dropCurrentStartCopyAck_;
MessageReceivedCallback callback_;
FABRIC_REPLICA_ID id_;
int maxReplDropCount_;
int maxCopyDropCount_;
mutable Common::ExclusiveLock lock_;
};
__declspec(property(get=get_Replicator)) SecondaryReplicatorWrapper & Replicator;
SecondaryReplicatorWrapper & get_Replicator() { return *(wrapper_.get()); }
void CheckCurrentProgress(FABRIC_SEQUENCE_NUMBER expectedLsn) const
{
FABRIC_SEQUENCE_NUMBER lsn;
ErrorCode error = wrapper_->GetCurrentProgress(lsn);
VERIFY_IS_TRUE(error.IsSuccess(), L"Secondary.GetCurrentProgress succeeded");
VERIFY_ARE_EQUAL_FMT(
lsn,
expectedLsn,
"GetCurrentProgress returned {0}, expected {1}", lsn, expectedLsn);
}
void CheckCatchUpCapability(FABRIC_SEQUENCE_NUMBER expectedLsn) const
{
FABRIC_SEQUENCE_NUMBER lsn;
ErrorCode error = wrapper_->GetCatchUpCapability(lsn);
VERIFY_IS_TRUE(error.IsSuccess(), L"Secondary.GetCatchUpCapability succeeded");
VERIFY_ARE_EQUAL_FMT(
lsn,
expectedLsn,
"GetCatchUpCapability returned {0}, expected {1}", lsn, expectedLsn);
}
void Open();
void Close();
void StartCopyOperationPump()
{
auto copyStream = wrapper_->GetCopyStream(std::dynamic_pointer_cast<SecondaryReplicator>(wrapper_->shared_from_this()));
StartGetOperation(copyStream);
}
void StartReplicationOperationPump()
{
auto replicationStream = wrapper_->GetReplicationStream(std::dynamic_pointer_cast<SecondaryReplicator>(wrapper_->shared_from_this()));
StartGetOperation(replicationStream);
}
private:
void StartGetOperation(OperationStreamSPtr const & stream);
bool EndGetOperation(AsyncOperationSPtr const & asyncOp, OperationStreamSPtr const & stream);
REPerformanceCountersSPtr perfCounters_;
FABRIC_REPLICA_ID secondaryId_;
ReplicationEndpointId endpointUniqueId_;
ReplicationTransportSPtr secondaryTransport_;
wstring endpoint_;
shared_ptr<SecondaryReplicatorWrapper> wrapper_;
};
typedef std::shared_ptr<PrimaryReplicatorHelper> PrimaryReplicatorHelperSPtr;
typedef std::shared_ptr<SecondaryReplicatorHelper> SecondaryReplicatorHelperSPtr;
class ReplicatorTestWrapper
{
public:
ReplicatorTestWrapper()
: operationList_(),
event_()
{
}
void CreatePrimary(
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
bool smallRetryInterval,
FABRIC_EPOCH const & epoch,
bool hasPersistedState,
Common::Guid partitionId,
__out PrimaryReplicatorHelperSPtr & primary);
void CreateSecondary(
int64 primaryId,
uint index,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
bool dropReplicationAcks,
bool hasPersistedState,
Common::Guid partitionId,
__out int64 & secondaryId,
__out SecondaryReplicatorHelperSPtr & secondary);
void CreateConfiguration(
int numberSecondaries,
int numberIdles,
FABRIC_EPOCH const & epoch,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
bool hasPersistedState,
Common::Guid partitionId,
__out PrimaryReplicatorHelperSPtr & primary,
__out vector<SecondaryReplicatorHelperSPtr> & secondaries,
__out vector<int64> & secondaryIds,
bool dropReplicationAcks = false);
void PromoteIdlesToSecondaries(
int currentNumberSecondaries,
int newNumberSecondaries,
__in PrimaryReplicatorHelperSPtr const & primary,
__in vector<SecondaryReplicatorHelperSPtr> & secondaries,
vector<int64> const & secondaryIds);
void BuildIdles(
int64 startReplSeq,
__in PrimaryReplicatorHelperSPtr & primary,
__in vector<SecondaryReplicatorHelperSPtr> & secondaries,
vector<int64> const & secondaryIds,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps);
void BeginAddIdleCopyNotFinished(
int index,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
PrimaryReplicatorHelperSPtr const & primary,
bool hasPersistedState,
Common::Guid partitionId,
__out SecondaryReplicatorHelperSPtr & secondary,
__out int64 & secondaryId,
__in ManualResetEvent & copyDoneEvent);
void EndAddIdleCopyNotFinished(
__in SecondaryReplicatorHelperSPtr & secondary,
__in ManualResetEvent & copyDoneEvent);
static void Replicate(__in PrimaryReplicatorHelper & repl, FABRIC_SEQUENCE_NUMBER expectedSequenceNumber, uint numberOfOperations = 1);
static void WaitForProgress(
__in PrimaryReplicatorHelper & repl, FABRIC_REPLICA_SET_QUORUM_MODE catchUpMode, bool expectTimeout = false);
static void CheckMessages(
FABRIC_REPLICA_ID id,
__in vector<wstring> & expectedMessages,
__in vector<wstring> & receivedMessages);
static void AddReceivedMessage(
__in vector<wstring> & receivedMessages,
wstring const & content);
private:
void Copy(__in PrimaryReplicatorHelper & repl, vector<ReplicaInformation> const & replicas);
wstring operationList_;
ManualResetEvent event_;
};
} // anonymous namespace
/***********************************
* TestReplicateCopyOperations methods
**********************************/
BOOST_FIXTURE_TEST_SUITE(TestReplicateCopyOperationsSuite,TestReplicateCopyOperations)
BOOST_AUTO_TEST_CASE(TestReplicateWithRetry1)
{
TestReplicateWithRetry(true);
}
BOOST_AUTO_TEST_CASE(TestReplicateWithRetry2)
{
TestReplicateWithRetry(false);
}
BOOST_AUTO_TEST_CASE(TestCopyWithRetry1)
{
TestCopyWithRetry(true);
}
BOOST_AUTO_TEST_CASE(TestCopyWithRetry2)
{
TestCopyWithRetry(false);
}
BOOST_AUTO_TEST_CASE(TestReplicateAndCopy1)
{
TestReplicateAndCopy(true);
}
BOOST_AUTO_TEST_CASE(TestReplicateAndCopy2)
{
TestReplicateAndCopy(false);
}
BOOST_AUTO_TEST_CASE(TestReplicateAndCopyWithIdleReceivedLSN)
{
bool hasPersistedState = true;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestReplicateAndCopyWithIdleReceivedLSN, persisted state {0}, Partitionid = {1}",
hasPersistedState,
partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<int64> secondaryIds;
// Configuration: 1 Primary, 1 secondary, Quorum count = 2
// Replicate done when primary receives 2 ACKs
int numberOfIdles = 1;
int numberOfSecondaries = 2;
int64 numberOfCopyOperations = 0;
int64 numberOfCopyContextOperations = hasPersistedState ? 0 : -1;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 1;
epoch.ConfigurationNumber = 100;
epoch.Reserved = NULL;
wrapper.CreateConfiguration(numberOfSecondaries, numberOfIdles, epoch,
numberOfCopyOperations, numberOfCopyContextOperations, hasPersistedState, partitionId, primary, secondaries, secondaryIds);
PrimaryReplicatorHelper & repl = *primary.get();
wrapper.Replicate(repl, 1);
// Full progress achieved at replicate done,
// so it should return immediately
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
repl.CheckCurrentProgress(1);
repl.CheckCatchUpCapability(0);
// All replicas should receive the replicate message
for(size_t i = 0; i < secondaries.size(); ++i)
{
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 1);
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, 1, Constants::NonInitializedLSN);
}
// Add an idle replica with copy in progress (drop all acks for copy)
// The copy should provide repl seq = 2, because 1 is already committed(and completed)
SecondaryReplicatorHelperSPtr secondary;
int64 secondaryId;
ManualResetEvent copyDoneEvent;
int index = numberOfSecondaries + numberOfIdles;
wrapper.BeginAddIdleCopyNotFinished(index, numberOfCopyOperations, numberOfCopyContextOperations, primary, hasPersistedState, partitionId, secondary, secondaryId, copyDoneEvent);
wrapper.Replicate(repl, 2);
// Even though there is an idle which is in-build, the replica would have
// received repl-2 and ACK'd that it has received it (ReceivedACK)
// Hence, we clear out our queues
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
repl.CheckCurrentProgress(2);
repl.CheckCatchUpCapability(0);
for(size_t i = 0; i < secondaries.size(); ++i)
{
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 2);
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, 2, Constants::NonInitializedLSN);
}
secondary->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 2);
// Finish copy for the last idle
wrapper.EndAddIdleCopyNotFinished(secondary, copyDoneEvent);
primary->Replicator.AddExpectedAck(secondary->SecondaryId, 2, Constants::NonInitializedLSN);
// Full progress should be achieved now
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL, false);
repl.CheckCurrentProgress(2);
repl.CheckCatchUpCapability(0);
wrapper.Replicate(repl, 3);
for(size_t i = 0; i < secondaries.size(); ++i)
{
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, 3, Constants::NonInitializedLSN);
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 3);
}
primary->Replicator.AddExpectedAck(secondary->SecondaryId, 3, Constants::NonInitializedLSN);
secondary->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 3);
// Wait for all operations to be completed on primary
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
repl.CheckCurrentProgress(3);
repl.CheckCatchUpCapability(0);
for(size_t i = 0; i < secondaries.size(); ++i)
{
secondaries[i]->Replicator.CheckMessages();
secondaries[i]->CheckCurrentProgress(3);
secondaries[i]->CheckCatchUpCapability(3);
secondaries[i]->Close();
}
secondary->Replicator.CheckMessages();
secondary->CheckCurrentProgress(3);
secondary->CheckCatchUpCapability(3);
secondary->Close();
primary->Replicator.CheckAcks();
primary->Close();
}
BOOST_AUTO_TEST_CASE(TestCancelCopy)
{
bool hasPersistedState = true;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestCancelCopy, persisted state {0}, partitionId = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
SecondaryReplicatorHelperSPtr secondary;
FABRIC_REPLICA_ID secondaryId;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 132984;
epoch.ConfigurationNumber = 999;
epoch.Reserved = NULL;
int64 numberOfCopyOps = 12132;
int64 numberOfCopyContextOps = hasPersistedState ? 100 : -1;
wrapper.CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, false, epoch, hasPersistedState, partitionId, primary);
wrapper.CreateSecondary(primary->PrimaryId, 0, numberOfCopyOps, numberOfCopyContextOps, false, hasPersistedState, partitionId, secondaryId, secondary);
PrimaryReplicatorHelper & repl = *primary.get();
ReplicaInformation replica(
secondaryId,
::FABRIC_REPLICA_ROLE_IDLE_SECONDARY,
secondary->ReplicationEndpoint,
false);
ManualResetEvent copyDoneEvent;
FABRIC_REPLICA_ID replicaId = replica.Id;
auto copyOp = repl.Replicator.BeginBuildReplica(
replica,
[&repl, replicaId, ©DoneEvent](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = repl.Replicator.EndBuildReplica(operation);
if (error.IsSuccess())
{
VERIFY_FAIL_FMT("Copy succeed when failure expected for replica {0}.", replicaId);
}
Trace.WriteInfo(ReplCopyTestSource, "Copy failed for replica {0} with error {1}.", replicaId, error);
copyDoneEvent.Set();
}, AsyncOperationSPtr());
Sleep(60);
copyOp->Cancel();
copyDoneEvent.WaitOne();
primary->Close();
secondary->Close();
}
BOOST_AUTO_TEST_CASE(TestCopyOperationsExceedQueueCapacity)
{
bool hasPersistedState = false;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestCopyOperationsExceedQueueCapacity, persisted state {0}, partitionId= {1}",
hasPersistedState,
partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<int64> secondaryIds;
// The provider has more operations that the queue capacity
// Because the state provider gives the operations very quickly,
// the queue full will be reached.
int64 numberOfCopyOps = MaxQueueCapacity + 50;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 232;
epoch.ConfigurationNumber = 323;
epoch.Reserved = NULL;
int64 numberOfCopyContextOps = hasPersistedState ? 0 : -1;
wrapper.CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, false, epoch, hasPersistedState, partitionId, primary);
// Create the secondary that will be built
int64 secondaryId;
SecondaryReplicatorHelperSPtr secondary;
wrapper.CreateSecondary(primary->PrimaryId, 0, numberOfCopyOps, numberOfCopyContextOps, false, hasPersistedState, partitionId, secondaryId, secondary);
secondaryIds.push_back(secondaryId);
secondaries.push_back(move(secondary));
PrimaryReplicatorHelper & repl = *primary.get();
ManualResetEvent buildIdleEvent;
ManualResetEvent replEvent;
// Replicate and build idle in parallel
Threadpool::Post([&wrapper, &repl, &replEvent]()
{
wrapper.Replicate(repl, 1, 2);
Sleep(40);
wrapper.Replicate(repl, 3, 2);
replEvent.Set();
});
Threadpool::Post([&]()
{
wrapper.BuildIdles(0, primary, secondaries, secondaryIds, numberOfCopyOps, numberOfCopyContextOps);
buildIdleEvent.Set();
});
buildIdleEvent.WaitOne();
replEvent.WaitOne();
primary->Close();
secondaries[0]->Close();
}
BOOST_AUTO_TEST_CASE(TestReplicatePrimaryOnly)
{
bool hasPersistedState = true;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestReplicatePrimaryOnly, persisted state {0}, partitionId = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 23424;
epoch.ConfigurationNumber = 666;
epoch.Reserved = NULL;
int64 numberOfCopyOps = 2;
int64 numberOfCopyContextOps = 0;
wrapper.CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, false, epoch, hasPersistedState, partitionId, primary);
PrimaryReplicatorHelper & repl = *primary.get();
// Replicate more operations
// than the queue limit
uint numberOfReplicateOps = MaxQueueCapacity + 2;
wrapper.Replicate(repl, 1, numberOfReplicateOps);
repl.CheckCurrentProgress(static_cast<FABRIC_SEQUENCE_NUMBER>(numberOfReplicateOps));
repl.CheckCatchUpCapability(0);
primary->Close();
}
BOOST_AUTO_TEST_CASE(TestNullCopyContext)
{
bool hasPersistedState = true;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestNullCopyContext, persisted state {0}, partitionId = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<int64> secondaryIds;
int numberOfIdles = 0;
int numberOfSecondaries = 1;
int64 numberOfCopyOperations = 4;
int64 numberOfCopyContextOperations = -1;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 4387483;
epoch.ConfigurationNumber = 1111;
epoch.Reserved = NULL;
wrapper.CreateConfiguration(numberOfSecondaries, numberOfIdles, epoch,
numberOfCopyOperations, numberOfCopyContextOperations, hasPersistedState, partitionId, primary, secondaries, secondaryIds);
primary->Replicator.AddExpectedAck(
secondaries[0]->SecondaryId, 0, Constants::NonInitializedLSN);
primary->Replicator.CheckAcks();
primary->Replicator.CheckMessages();
primary->Close();
secondaries[0]->Replicator.CheckMessages();
secondaries[0]->Close();
}
BOOST_AUTO_TEST_CASE(TestBatchAckFromPendingItems)
{
bool hasPersistedState = true;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestBatchAckFromPendingItems, persisted state {0}, partitionId = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
int64 numberOfCopyOps = 3;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 1111;
epoch.ConfigurationNumber = 1111;
epoch.Reserved = NULL;
int64 numberOfCopyContextOps = hasPersistedState ? 0 : -1;
PrimaryReplicatorHelperSPtr primary;
wrapper.CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, false, epoch, hasPersistedState, partitionId, primary);
FABRIC_REPLICA_ID secondaryId;
SecondaryReplicatorHelperSPtr secondary;
// Create an idle
REConfigSPtr config = TestReplicateCopyOperations::CreateGenericConfig();
config->MaxPendingAcknowledgements = 2;
// Set batch ACK period to a large value, to check
// that we force send when the number of pending ack is
// greater or equal than specified value.
config->BatchAcknowledgementInterval = TimeSpan::FromSeconds(60);
config->RetryInterval = TimeSpan::FromSeconds(61);
secondaryId = primary->PrimaryId + 1;
secondary = make_shared<SecondaryReplicatorHelper>(
config,
secondaryId,
hasPersistedState,
numberOfCopyOps,
numberOfCopyContextOps,
partitionId,
false /*dropReplicationAcks*/);
secondary->Open();
// Start copy operation pump; the replication pump will be started
// when all copy received
secondary->StartCopyOperationPump();
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<FABRIC_REPLICA_ID> secondaryIds;
secondaryIds.push_back(secondaryId);
secondaries.push_back(move(secondary));
// Build idle should succeed
// because the ACKs are sent when there are 2 pending operations
wrapper.BuildIdles(0, primary, secondaries, secondaryIds, numberOfCopyOps, numberOfCopyContextOps);
PrimaryReplicatorHelper & repl = *primary.get();
wrapper.Replicate(repl, 1, 2);
// Full progress should return, because there are 2 pending operations,
// so secondary should force send ACK.
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
primary->Close();
secondaries[0]->Close();
}
// This test only has sense for persisted replicas
BOOST_AUTO_TEST_CASE(TestRequestAck)
{
bool hasPersistedState = true;
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestRequestAck, persisted state {0}, partitionId = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
int64 numberOfCopyOps = 2;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 9999;
epoch.ConfigurationNumber = 9999;
epoch.Reserved = NULL;
int64 numberOfCopyContextOps = hasPersistedState ? 0 : -1;
PrimaryReplicatorHelperSPtr primary;
wrapper.CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, true, epoch, hasPersistedState, partitionId, primary);
FABRIC_REPLICA_ID secondaryId;
SecondaryReplicatorHelperSPtr secondary;
// Create an idle
REConfigSPtr config = TestReplicateCopyOperations::CreateGenericConfig();
config->BatchAcknowledgementInterval = TimeSpan::Zero;
secondaryId = primary->PrimaryId + 1;
secondary = make_shared<SecondaryReplicatorHelper>(
config,
secondaryId,
hasPersistedState,
numberOfCopyOps,
numberOfCopyContextOps,
partitionId,
false /*dropReplicationAcks*/);
// Open the secondary, but do not start the operation pump
secondary->Open();
secondary->Replicator.SetMessageReceivedCallback(
[secondary] (wstring const & action)
{
if(action == ReplicationTransport::RequestAckAction)
{
secondary->StartCopyOperationPump();
}
});
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<FABRIC_REPLICA_ID> secondaryIds;
secondaryIds.push_back(secondaryId);
secondaries.push_back(move(secondary));
// Build idle should succeed
// because the pump should be started when request ack is received
wrapper.BuildIdles(0, primary, secondaries, secondaryIds, numberOfCopyOps, numberOfCopyContextOps);
primary->Close();
secondaries[0]->Close();
}
BOOST_AUTO_TEST_SUITE_END()
Common::ComponentRoot const & TestReplicateCopyOperations::GetRoot()
{
static std::shared_ptr<DummyRoot> root = std::make_shared<DummyRoot>();
return *root;
}
void TestReplicateCopyOperations::TestReplicateAndCopy(bool hasPersistedState)
{
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestReplicateAndCopy, persisted state {0}, partitionId = {1}",
hasPersistedState,
partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<int64> secondaryIds;
// Configuration: 1 Primary, 2 secondaries, 1 idle, Quorum count = 2
// Replicate done when primary receives sufficient ACKs
int numberOfIdles = 1;
int numberOfSecondaries = 2;
int64 numberOfCopyOperations = 0;
int64 numberOfCopyContextOperations = hasPersistedState ? 0 : -1;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 1;
epoch.ConfigurationNumber = 100;
epoch.Reserved = NULL;
wrapper.CreateConfiguration(numberOfSecondaries, numberOfIdles, epoch,
numberOfCopyOperations, numberOfCopyContextOperations, hasPersistedState, partitionId, primary, secondaries, secondaryIds);
PrimaryReplicatorHelper & repl = *primary.get();
wrapper.Replicate(repl, 1);
// Full progress achieved at replicate done,
// so it should return immediately
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
repl.CheckCurrentProgress(1);
repl.CheckCatchUpCapability(0);
// All replicas should receive the replicate message
for(size_t i = 0; i < secondaries.size(); ++i)
{
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 1);
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, 1, Constants::NonInitializedLSN);
}
// Add an idle replica with copy in progress (drop all acks for copy)
// The copy should provide repl seq = 2, because 1 is already committed
SecondaryReplicatorHelperSPtr secondary;
int64 secondaryId;
ManualResetEvent copyDoneEvent;
int index = numberOfSecondaries + numberOfIdles;
wrapper.BeginAddIdleCopyNotFinished(index, numberOfCopyOperations, numberOfCopyContextOperations, primary, hasPersistedState, partitionId, secondary, secondaryId, copyDoneEvent);
wrapper.Replicate(repl, 2);
// For Non-persisted services, the replicate operation
// is ACKed optimistically immediately (before copy is done).
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL, false);
repl.CheckCurrentProgress(2);
repl.CheckCatchUpCapability(0);
for(size_t i = 0; i < secondaries.size(); ++i)
{
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 2);
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, 2, Constants::NonInitializedLSN);
}
secondary->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 2);
// Finish copy for the last idle
wrapper.EndAddIdleCopyNotFinished(secondary, copyDoneEvent);
primary->Replicator.AddExpectedAck(secondary->SecondaryId, 2, Constants::NonInitializedLSN);
// Full progress should be achieved now
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL, false);
repl.CheckCurrentProgress(2);
repl.CheckCatchUpCapability(0);
wrapper.Replicate(repl, 3);
for(size_t i = 0; i < secondaries.size(); ++i)
{
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, 3, Constants::NonInitializedLSN);
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 3);
}
primary->Replicator.AddExpectedAck(secondary->SecondaryId, 3, Constants::NonInitializedLSN);
secondary->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, 3);
// Wait for all operations to be completed on primary
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
repl.CheckCurrentProgress(3);
repl.CheckCatchUpCapability(0);
for(size_t i = 0; i < secondaries.size(); ++i)
{
secondaries[i]->Replicator.CheckMessages();
secondaries[i]->CheckCurrentProgress(3);
secondaries[i]->CheckCatchUpCapability(3);
secondaries[i]->Close();
}
secondary->Replicator.CheckMessages();
secondary->CheckCurrentProgress(3);
secondary->CheckCatchUpCapability(3);
secondary->Close();
primary->Replicator.CheckAcks();
primary->Close();
}
void TestReplicateCopyOperations::TestReplicateWithRetry(bool hasPersistedState)
{
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestReplicateWithRetry, persisted state {0}, partitionId = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
vector<SecondaryReplicatorHelperSPtr> secondaries;
vector<int64> secondaryIds;
int numberOfSecondaries = 2;
int64 numberOfCopyOperations = 0;
int64 numberOfCopyContextOperations = hasPersistedState ? 0 : -1;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 2;
epoch.ConfigurationNumber = 100;
epoch.Reserved = NULL;
wrapper.CreateConfiguration(
numberOfSecondaries, 0, epoch, numberOfCopyOperations, numberOfCopyContextOperations, hasPersistedState, partitionId, primary, secondaries, secondaryIds, true);
PrimaryReplicatorHelper &repl = *(primary.get());
uint numberOfOperations = 3;
// All replicas should receive the replicate messages;
for(size_t i = 0; i < secondaries.size(); ++i)
{
for(int64 j = 1; j <= numberOfOperations; ++j)
{
// Primary retries on timer because some of the ACKs are dropped.
// Since we don't know which ACKs are dropped,
// primary may receive different replication numbers each time,
// so we don't check it.
secondaries[i]->Replicator.AddExpectedReplicationMessage(primary->EndpointUniqueId, j);
}
}
wrapper.Replicate(repl, 1, numberOfOperations);
// Wait for all operations to be completed on primary
wrapper.WaitForProgress(repl, FABRIC_REPLICA_SET_QUORUM_ALL);
for(size_t i = 0; i < secondaries.size(); ++i)
{
primary->Replicator.AddExpectedAck(
secondaries[i]->SecondaryId, numberOfOperations, Constants::NonInitializedLSN);
secondaries[i]->Replicator.CheckMessages();
secondaries[i]->CheckCurrentProgress(3);
// Catchup capability depends on if the secondary has received the header about primary's completed LSN or not
// Since this variation drops aCKs randomly, it is hard to be deterministic
// secondaries[i]->CheckCatchUpCapability(3);
secondaries[i]->Close();
}
primary->Replicator.CheckAcks();
primary->CheckCurrentProgress(3);
primary->CheckCatchUpCapability(0);
primary->Close();
}
void TestReplicateCopyOperations::TestCopyWithRetry(bool hasPersistedState)
{
Common::Guid partitionId = Common::Guid::NewGuid();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"Start TestCopyWithRetry, persisted state {0}, partitionID = {1}",
hasPersistedState, partitionId);
ReplicatorTestWrapper wrapper;
PrimaryReplicatorHelperSPtr primary;
// The copy provider will send 6 operations until copy is finished
int64 numberOfCopyOps = 6;
int64 numberOfCopyContextOps = hasPersistedState ? 4 : -1;
FABRIC_EPOCH epoch;
epoch.DataLossNumber = 1;
epoch.ConfigurationNumber = 156;
epoch.Reserved = NULL;
wrapper.CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, true, epoch, hasPersistedState, partitionId, primary);
// Add an idle replica with copy in progress (drop all acks for copy)
SecondaryReplicatorHelperSPtr secondary;
FABRIC_REPLICA_ID secondaryId;
ManualResetEvent copyDoneEvent;
wrapper.BeginAddIdleCopyNotFinished(0, numberOfCopyOps, numberOfCopyContextOps, primary, hasPersistedState, partitionId, secondary, secondaryId, copyDoneEvent);
primary->Replicator.AddExpectedAck(secondary->SecondaryId, 0, Constants::NonInitializedLSN);
// Finish copy for the last idle
wrapper.EndAddIdleCopyNotFinished(secondary, copyDoneEvent);
secondary->Replicator.CheckMessages();
secondary->Close();
primary->Replicator.CheckAcks();
primary->Close();
}
bool TestReplicateCopyOperations::Setup()
{
return TRUE;
}
REConfigSPtr TestReplicateCopyOperations::CreateGenericConfig()
{
REConfigSPtr config = std::make_shared<REConfig>();
config->BatchAcknowledgementInterval = TimeSpan::FromMilliseconds(100);
config->InitialCopyQueueSize = 4;
config->MaxCopyQueueSize = MaxQueueCapacity;
config->InitialReplicationQueueSize = 4;
config->MaxReplicationQueueSize = MaxQueueCapacity;
config->QueueHealthMonitoringInterval = TimeSpan::Zero;
config->UseStreamFaultsAndEndOfStreamOperationAck = true;
config->SlowApiMonitoringInterval = TimeSpan::Zero;
return config;
}
ReplicationTransportSPtr TestReplicateCopyOperations::CreateTransport(REConfigSPtr const & config)
{
auto transport = ReplicationTransport::Create(config->ReplicatorListenAddress);
auto errorCode = transport->Start(L"localhost:0");
ASSERT_IFNOT(errorCode.IsSuccess(), "Failed to start: {0}", errorCode);
return transport;
}
/***********************************
* PrimaryReplicatorHelper methods
**********************************/
PrimaryReplicatorHelper::PrimaryReplicatorHelper(
REConfigSPtr const & config,
bool hasPersistedState,
FABRIC_EPOCH const & epoch,
int64 numberOfCopyOperations,
int64 numberOfCopyContextOperations,
Common::Guid partitionId)
:
primaryId_(PrimaryReplicaId),
perfCounters_(REPerformanceCounters::CreateInstance(partitionId.ToString(), PrimaryReplicaId)),
endpointUniqueId_(partitionId, PrimaryReplicaId),
primaryTransport_(TestReplicateCopyOperations::CreateTransport(config)),
wrapper_()
{
ComProxyStateProvider stateProvider = move(ComTestStateProvider::GetProvider(
numberOfCopyOperations,
numberOfCopyContextOperations,
*this));
IReplicatorHealthClientSPtr temp;
ApiMonitoringWrapperSPtr temp2 = ApiMonitoringWrapper::Create(temp, REInternalSettings::Create(nullptr, config), partitionId, endpointUniqueId_);
wrapper_ = make_shared<PrimaryReplicatorWrapper>(
config, perfCounters_, primaryId_, hasPersistedState, endpointUniqueId_, epoch, primaryTransport_, stateProvider, temp, temp2);
}
int64 PrimaryReplicatorHelper::PrimaryReplicaId = 1;
void PrimaryReplicatorHelper::ProcessMessage(
__in Transport::Message & message, __out Transport::ReceiverContextUPtr &)
{
wstring const & action = message.Action;
if (action != ReplicationTransport::ReplicationAckAction &&
action != ReplicationTransport::CopyContextOperationAction)
{
VERIFY_FAIL(L"Message doesn't have correct action - only ACK and CopyContext supported on primary");
}
ReplicationFromHeader fromHeader;
if (!message.Headers.TryReadFirst(fromHeader))
{
VERIFY_FAIL(L"Message doesn't have correct headers");
}
if (action == ReplicationTransport::ReplicationAckAction)
{
wrapper_->ReplicationAckMessageHandler(message, fromHeader, wrapper_);
}
else
{
wrapper_->CopyContextMessageHandler(message, fromHeader);
}
}
void PrimaryReplicatorHelper::Open()
{
primaryTransport_->RegisterMessageProcessor(*this);
wrapper_->Open();
}
void PrimaryReplicatorHelper::Close()
{
ManualResetEvent closeCompleteEvent;
wrapper_->BeginClose(
false,
Common::TimeSpan::Zero,
[this, &closeCompleteEvent](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = this->wrapper_->EndClose(operation);
VERIFY_IS_TRUE(error.IsSuccess(), L"Primary Replicator closed successfully.");
closeCompleteEvent.Set();
}, AsyncOperationSPtr());
VERIFY_IS_TRUE(closeCompleteEvent.WaitOne(10000), L"Close should succeed");
primaryTransport_->UnregisterMessageProcessor(*this);
primaryTransport_->Stop();
}
PrimaryReplicatorHelper::PrimaryReplicatorWrapper::PrimaryReplicatorWrapper(
REConfigSPtr const & config,
REPerformanceCountersSPtr & perfCounters,
FABRIC_REPLICA_ID replicaId,
bool hasPersistedState,
ReplicationEndpointId const & endpointUniqueId,
FABRIC_EPOCH const & epoch,
ReplicationTransportSPtr const & transport,
ComProxyStateProvider const & provider,
IReplicatorHealthClientSPtr & temp,
ApiMonitoringWrapperSPtr & temp2)
: PrimaryReplicator(
REInternalSettings::Create(nullptr, config),
perfCounters,
replicaId,
hasPersistedState,
endpointUniqueId,
epoch,
provider,
ComProxyStatefulServicePartition(),
Replicator::V1,
transport,
0, /* initial service progress */
endpointUniqueId.PartitionId.ToString(),
temp,
temp2),
expectedMessages_(),
receivedMessages_(),
receivedAcks_(),
expectedAcks_(),
lock_(),
id_(replicaId)
{
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::ReplicationAckMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader, PrimaryReplicatorWPtr primary)
{
FABRIC_SEQUENCE_NUMBER replRLSN;
FABRIC_SEQUENCE_NUMBER replQLSN;
FABRIC_SEQUENCE_NUMBER copyRLSN;
FABRIC_SEQUENCE_NUMBER copyQLSN;
int errorCodeValue;
ReplicationTransport::GetAckFromMessage(message, replRLSN, replQLSN, copyRLSN, copyQLSN, errorCodeValue);
{
Common::AcquireExclusiveLock lock(this->lock_);
this->AddAckCallerHoldsLock(receivedAcks_, fromHeader.DemuxerActor.ReplicaId, replRLSN, copyRLSN);
}
PrimaryReplicator::ReplicationAckMessageHandler(message, fromHeader, primary);
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::CopyContextMessageHandler(
__in Transport::Message & message, ReplicationFromHeader const & fromHeader)
{
CopyContextOperationHeader header;
wstring received;
if (message.Headers.TryReadFirst(header))
{
StringWriter writer(received);
writer.Write("CC:{0}:{1}", fromHeader.DemuxerActor, header.OperationMetadata.SequenceNumber);
}
{
Common::AcquireExclusiveLock lock(this->lock_);
ReplicatorTestWrapper::AddReceivedMessage(receivedMessages_, received);
}
PrimaryReplicator::CopyContextMessageHandler(message, fromHeader);
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::DumpAckTable(AckReplCopyMap const & mapToDump)
{
for(auto it = mapToDump.begin(); it != mapToDump.end(); ++it)
{
auto ackPair = it->second;
Trace.WriteInfo(ReplCopyTestSource, "ID = {0} -> [{1}:{2}]", it->first, ackPair.first, ackPair.second);
}
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::CheckAcks() const
{
Common::AcquireExclusiveLock lock(this->lock_);
bool failed = false;
for(auto it = receivedAcks_.begin(); it != receivedAcks_.end(); ++it)
{
auto ackPair = it->second;
Trace.WriteInfo(ReplCopyTestSource, "{0} -> {1}:{2}", it->first, ackPair.first, ackPair.second);
auto itExpected = expectedAcks_.find(it->first);
if (itExpected == expectedAcks_.end())
{
Trace.WriteInfo(ReplCopyTestSource, "**** Received ACK from not expected secondary : {0}", it->first);
failed = true;
}
else
{
auto ackPairExpected = itExpected->second;
if (ackPair.first != ackPairExpected.first || ackPair.second != ackPairExpected.second)
{
Trace.WriteInfo(ReplCopyTestSource, "**** Expected Ack != received: {0}:{1}",
ackPairExpected.first, ackPairExpected.second);
failed = true;
}
}
}
if (!failed && (expectedAcks_.size() != receivedAcks_.size()))
{
Trace.WriteInfo(ReplCopyTestSource, "***** Expected ACKs not received: {0} != {1}", expectedAcks_.size(), receivedAcks_.size());
Trace.WriteInfo(ReplCopyTestSource, "***** Dumping received acks");
DumpAckTable(receivedAcks_);
Trace.WriteInfo(ReplCopyTestSource, "***** Dumping expected acks");
DumpAckTable(expectedAcks_);
failed = true;
}
VERIFY_IS_FALSE(failed, L"Check that expected Acks are received");
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::AddAckCallerHoldsLock(
__in AckReplCopyMap & ackMap, int64 secondaryId, FABRIC_SEQUENCE_NUMBER replLSN, FABRIC_SEQUENCE_NUMBER copyLSN)
{
auto it = ackMap.find(secondaryId);
if (it == ackMap.end())
{
ackMap.insert(pair<int64, AckReplCopyPair>(
secondaryId, pair<FABRIC_SEQUENCE_NUMBER, FABRIC_SEQUENCE_NUMBER>(replLSN, copyLSN)));
}
else
{
pair<FABRIC_SEQUENCE_NUMBER, FABRIC_SEQUENCE_NUMBER> & ackPair = it->second;
// Update the replication LSN, if the number id higher than the existing one
if (replLSN > ackPair.first)
{
ackPair.first = replLSN;
}
if ((copyLSN == Constants::NonInitializedLSN) || (copyLSN > ackPair.second))
{
ackPair.second = copyLSN;
}
}
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::AddExpectedCopyContextMessage(
ReplicationEndpointId const & fromDemuxer,
FABRIC_SEQUENCE_NUMBER sequenceNumber)
{
Common::AcquireExclusiveLock lock(this->lock_);
wstring content;
StringWriter writer(content);
writer.Write("CC:{0}:{1}", fromDemuxer, sequenceNumber);
expectedMessages_.push_back(content);
}
void PrimaryReplicatorHelper::PrimaryReplicatorWrapper::CheckMessages()
{
Common::AcquireExclusiveLock lock(this->lock_);
return ReplicatorTestWrapper::CheckMessages(id_, expectedMessages_, receivedMessages_);
}
/***********************************
* SecondaryReplicatorHelper methods
**********************************/
SecondaryReplicatorHelper::SecondaryReplicatorHelper(
REConfigSPtr const & config,
FABRIC_REPLICA_ID replicaId,
bool hasPersistedState,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
Common::Guid partitionId,
bool dropReplicationAcks)
:
secondaryId_(replicaId),
perfCounters_(REPerformanceCounters::CreateInstance(partitionId.ToString(), replicaId)),
endpointUniqueId_(partitionId, replicaId),
secondaryTransport_(TestReplicateCopyOperations::CreateTransport(config)),
endpoint_(),
wrapper_()
{
ComProxyStateProvider stateProvider = move(ComTestStateProvider::GetProvider(
numberOfCopyOps,
numberOfCopyContextOps,
*this));
IReplicatorHealthClientSPtr temp;
ApiMonitoringWrapperSPtr temp2 = ApiMonitoringWrapper::Create(temp, REInternalSettings::Create(nullptr, config), partitionId, endpointUniqueId_);
wrapper_ = std::shared_ptr<SecondaryReplicatorWrapper>(new SecondaryReplicatorWrapper(
config, perfCounters_, secondaryId_, hasPersistedState, endpointUniqueId_, secondaryTransport_, stateProvider, dropReplicationAcks, temp, temp2));
secondaryTransport_->GeneratePublishEndpoint(endpointUniqueId_, endpoint_);
wrapper_->Open();
}
void SecondaryReplicatorHelper::StartGetOperation(OperationStreamSPtr const & stream)
{
for(;;)
{
auto op = stream->BeginGetOperation(
[this, stream](AsyncOperationSPtr const& asyncOp)->void
{
if(!asyncOp->CompletedSynchronously && EndGetOperation(asyncOp, stream))
{
this->StartGetOperation(stream);
}
},
wrapper_->CreateAsyncOperationRoot());
if(!op->CompletedSynchronously || (!EndGetOperation(op, stream)))
{
break;
}
}
}
bool SecondaryReplicatorHelper::EndGetOperation(
AsyncOperationSPtr const & asyncOp,
OperationStreamSPtr const & stream)
{
IFabricOperation * operation = nullptr;
ErrorCode error = stream->EndGetOperation(asyncOp, operation);
if (!error.IsSuccess())
{
VERIFY_FAIL(L"GetOperation completed successfully.");
}
if (operation && operation->get_Metadata()->Type != FABRIC_OPERATION_TYPE_END_OF_STREAM)
{
FABRIC_OPERATION_METADATA const *opMetadata = operation->get_Metadata();
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"{0}: GetOperation returned {1} type, {2} sequence number.",
endpointUniqueId_,
opMetadata->Type,
opMetadata->SequenceNumber);
ULONG bufferCount = 0;
FABRIC_OPERATION_DATA_BUFFER const * replicaBuffers = nullptr;
VERIFY_SUCCEEDED(operation->GetData(&bufferCount, &replicaBuffers));
VERIFY_IS_TRUE(bufferCount <= 1);
if (opMetadata->SequenceNumber <= 0)
{
VERIFY_FAIL(L"EndGetOperation returned non-null op with invalid lsn");
}
operation->Acknowledge();
operation->Release();
return true;
}
else
{
ComTestOperation::WriteInfo(ReplCopyTestSource, "{0}: Received NULL operation.", stream->Purpose);
if (operation)
{
VERIFY_IS_TRUE(operation->get_Metadata()->Type == FABRIC_OPERATION_TYPE_END_OF_STREAM);
operation->Acknowledge();
}
if (stream->Purpose == Constants::CopyOperationTrace)
{
StartReplicationOperationPump();
}
}
return false;
}
void SecondaryReplicatorHelper::ProcessMessage(
__in Transport::Message & message, __out Transport::ReceiverContextUPtr &)
{
wstring const & action = message.Action;
ReplicationFromHeader fromHeader;
if (!message.Headers.TryReadFirst(fromHeader))
{
VERIFY_FAIL(L"Message doesn't have correct headers");
}
if (action == ReplicationTransport::ReplicationOperationAction)
{
wrapper_->ReplicationOperationMessageHandler(message, fromHeader);
}
else if (action == ReplicationTransport::CopyOperationAction)
{
wrapper_->CopyOperationMessageHandler(message, fromHeader);
}
else if (action == ReplicationTransport::StartCopyAction)
{
wrapper_->StartCopyMessageHandler(message, fromHeader);
}
else if (action == ReplicationTransport::CopyContextAckAction)
{
wrapper_->CopyContextAckMessageHandler(message, fromHeader);
}
else if (action == ReplicationTransport::RequestAckAction)
{
wrapper_->RequestAckMessageHandler(message, fromHeader);
}
else
{
VERIFY_FAIL(L"Unknown action");
}
}
void SecondaryReplicatorHelper::Open()
{
secondaryTransport_->RegisterMessageProcessor(*this);
}
void SecondaryReplicatorHelper::Close()
{
ManualResetEvent closeCompleteEvent;
wrapper_->BeginClose(
false /*waitForOperationsToBeDrained*/,
[this, &closeCompleteEvent](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = this->wrapper_->EndClose(operation);
VERIFY_IS_TRUE(error.IsSuccess(), L"Secondary Replicator closed successfully.");
closeCompleteEvent.Set();
}, AsyncOperationSPtr());
VERIFY_IS_TRUE(closeCompleteEvent.WaitOne(10000), L"Close should succeed");
secondaryTransport_->UnregisterMessageProcessor(*this);
secondaryTransport_->Stop();
}
SecondaryReplicatorHelper::SecondaryReplicatorWrapper::SecondaryReplicatorWrapper(
REConfigSPtr const & config,
REPerformanceCountersSPtr & perfCounters,
FABRIC_REPLICA_ID replicaId,
bool hasPersistedState,
ReplicationEndpointId const & endpointUniqueId,
ReplicationTransportSPtr const & transport,
ComProxyStateProvider const & provider,
bool dropReplicationAcks,
IReplicatorHealthClientSPtr & temp,
ApiMonitoringWrapperSPtr & temp2)
:
SecondaryReplicator(
REInternalSettings::Create(nullptr, config),
perfCounters,
replicaId,
hasPersistedState,
endpointUniqueId,
provider,
ComProxyStatefulServicePartition(),
Replicator::V1,
transport,
endpointUniqueId.PartitionId.ToString(),
temp,
temp2),
expectedMessages_(),
receivedMessages_(),
dropReplicationAcks_(dropReplicationAcks),
dropCopyAcks_(false),
dropCurrentAck_(dropReplicationAcks),
dropCurrentStartCopyAck_(dropReplicationAcks),
callback_(),
id_(replicaId),
lock_(),
maxReplDropCount_(100),
maxCopyDropCount_(100)
{
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::SetDropCopyAcks(bool dropCopyAcks)
{
dropCopyAcks_ = dropCopyAcks;
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::ReplicationOperationMessageHandler(
__in Transport::Message & message,
ReplicationFromHeader const & fromHeader)
{
vector<const_buffer> msgBuffers;
bool isBodyValid = message.GetBody(msgBuffers);
ASSERT_IF(!isBodyValid, "GetBody() in GetReplicationOperationFromMessage failed with message status {0}", message.Status);
ReplicationOperationHeader header;
wstring received;
bool headerBodyDetected = ReplicationTransport::ReadInBodyOperationHeader(message, msgBuffers, header);
if (headerBodyDetected || message.Headers.TryReadFirst(header))
{
StringWriter writer(received);
writer.Write("R:{0}:{1}", fromHeader.DemuxerActor, header.OperationMetadata.SequenceNumber);
}
if (dropReplicationAcks_)
{
if (dropCurrentAck_ &&
--maxReplDropCount_ > 0)
{
// Drop one of 2 consecutive ACKs
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"-----{0}: TEST drop REPL operation {1}",
id_,
received);
dropCurrentAck_ = false;
return;
}
dropCurrentAck_ = true;
}
{
Common::AcquireExclusiveLock lock(this->lock_);
ReplicatorTestWrapper::AddReceivedMessage(receivedMessages_, received);
}
SecondaryReplicator::ReplicationOperationMessageHandler(message, fromHeader);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::StartCopyMessageHandler(
__in Transport::Message & message,
ReplicationFromHeader const & fromHeader)
{
wstring received;
StringWriter(received).Write("SC:{0}", fromHeader.DemuxerActor);
if (dropReplicationAcks_)
{
if (dropCurrentStartCopyAck_)
{
// Drop the first StartCopy, accept the next one
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"-----{0}: TEST drop StartCOPY {1}",
id_,
received);
dropCurrentStartCopyAck_ = false;
return;
}
dropCurrentStartCopyAck_ = true;
}
{
Common::AcquireExclusiveLock lock(this->lock_);
ReplicatorTestWrapper::AddReceivedMessage(receivedMessages_, received);
}
SecondaryReplicator::StartCopyMessageHandler(message, fromHeader);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::CopyContextAckMessageHandler(
__in Transport::Message & message,
ReplicationFromHeader const & fromHeader)
{
FABRIC_SEQUENCE_NUMBER lsn;
int errorCodeValue;
ReplicationTransport::GetCopyContextAckFromMessage(message, lsn, errorCodeValue);
wstring received;
StringWriter(received).Write("CCAck:{0}:{1}:{2}", fromHeader.DemuxerActor, lsn, errorCodeValue);
Trace.WriteInfo(ReplCopyTestSource, "Received{ 0 }", received);
SecondaryReplicator::CopyContextAckMessageHandler(message, fromHeader);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::RequestAckMessageHandler(
__in Transport::Message & message,
ReplicationFromHeader const & fromHeader)
{
wstring received;
StringWriter(received).Write("RequestAck:{0}", fromHeader.DemuxerActor);
Trace.WriteInfo(ReplCopyTestSource, "Received {0}", received);
if (callback_)
{
callback_(message.Action);
}
SecondaryReplicator::RequestAckMessageHandler(message, fromHeader);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::CopyOperationMessageHandler(
__in Transport::Message & message,
ReplicationFromHeader const & fromHeader)
{
vector<const_buffer> msgBuffers;
bool isBodyValid = message.GetBody(msgBuffers);
ASSERT_IF(!isBodyValid, "GetBody() in GetReplicationOperationFromMessage failed with message status {0}", message.Status);
CopyOperationHeader header;
wstring received;
bool headerBodyDetected = ReplicationTransport::ReadInBodyOperationHeader(message, msgBuffers, header);
if (headerBodyDetected || message.Headers.TryReadFirst(header))
{
StringWriter writer(received);
writer.Write("C:{0}:{1}", fromHeader.DemuxerActor, header.OperationMetadata.SequenceNumber);
}
if (dropCopyAcks_ &&
--maxCopyDropCount_ > 0)
{
ComTestOperation::WriteInfo(
ReplCopyTestSource,
"-----{0}: TEST drop COPY operation {1}",
id_,
received);
}
else
{
{
Common::AcquireExclusiveLock lock(this->lock_);
ReplicatorTestWrapper::AddReceivedMessage(receivedMessages_, received);
}
SecondaryReplicator::CopyOperationMessageHandler(message, fromHeader);
}
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::AddExpectedCopyMessage(
ReplicationEndpointId const & fromDemuxer,
FABRIC_SEQUENCE_NUMBER seq)
{
wstring content;
StringWriter writer(content);
writer.Write("C:{0}:{1}", fromDemuxer, seq);
Common::AcquireExclusiveLock lock(this->lock_);
expectedMessages_.push_back(content);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::AddExpectedReplicationMessage(
ReplicationEndpointId const & fromDemuxer,
FABRIC_SEQUENCE_NUMBER sequenceNumber)
{
wstring content;
StringWriter writer(content);
writer.Write("R:{0}:{1}", fromDemuxer, sequenceNumber);
Common::AcquireExclusiveLock lock(this->lock_);
expectedMessages_.push_back(content);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::AddExpectedStartCopyMessage(
ReplicationEndpointId const & fromDemuxer)
{
wstring content;
StringWriter writer(content);
writer.Write("SC:{0}", fromDemuxer);
Common::AcquireExclusiveLock lock(this->lock_);
expectedMessages_.push_back(content);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::AddExpectedCopyContextAckMessage(
ReplicationEndpointId const & fromDemuxer,
FABRIC_SEQUENCE_NUMBER sequenceNumber)
{
wstring content;
StringWriter writer(content);
writer.Write("CCAck:{0}:{1}", fromDemuxer, sequenceNumber);
Common::AcquireExclusiveLock lock(this->lock_);
expectedMessages_.push_back(content);
}
void SecondaryReplicatorHelper::SecondaryReplicatorWrapper::CheckMessages()
{
Common::AcquireExclusiveLock lock(this->lock_);
return ReplicatorTestWrapper::CheckMessages(id_, expectedMessages_, receivedMessages_);
}
/***********************************
* ReplicatorTestWrapper methods
**********************************/
void ReplicatorTestWrapper::CheckMessages(
FABRIC_REPLICA_ID id,
__in vector<wstring> & expectedMessages,
__in vector<wstring> & receivedMessages)
{
// Wait for the messages to be received
int tryCount = 5;
while(--tryCount > 0)
{
if (expectedMessages.size() <= receivedMessages.size())
{
break;
}
Sleep(300);
}
std::sort(expectedMessages.begin(), expectedMessages.end());
std::sort(receivedMessages.begin(), receivedMessages.end());
size_t size = std::min(expectedMessages.size(), receivedMessages.size());
Trace.WriteInfo(ReplCopyTestSource, "{0}: Check expected messages:", id);
for(size_t i = 0; i < size; ++i)
{
if (expectedMessages[i] != receivedMessages[i])
{
Trace.WriteInfo(ReplCopyTestSource, "Expected message != received: {0} != {1}",
expectedMessages[i], receivedMessages[i]);
}
else
{
Trace.WriteInfo(ReplCopyTestSource, "{0}", receivedMessages[i]);
}
}
for(size_t i = size; i < expectedMessages.size(); ++i)
{
Trace.WriteInfo(ReplCopyTestSource, "***** Expected message not received: {0}", expectedMessages[i]);
}
for(size_t i = size; i < receivedMessages.size(); ++i)
{
Trace.WriteInfo(ReplCopyTestSource, "**** Received message not expected: {0}", receivedMessages[i]);
}
VERIFY_ARE_EQUAL(expectedMessages, receivedMessages);
}
void ReplicatorTestWrapper::AddReceivedMessage(
__in vector<wstring> & receivedMessages,
wstring const & content)
{
// Ignore duplicate messages,
// they could happen because of retries on timer
auto it = std::find(receivedMessages.begin(), receivedMessages.end(), content);
if (it == receivedMessages.end())
{
receivedMessages.push_back(content);
}
}
void ReplicatorTestWrapper::CreatePrimary(
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
bool smallRetryInterval,
FABRIC_EPOCH const & epoch,
bool hasPersistedState,
Common::Guid partitionId,
__out PrimaryReplicatorHelperSPtr & primary)
{
REConfigSPtr primaryConfig = TestReplicateCopyOperations::CreateGenericConfig();
// Minimize the retry interval
if (smallRetryInterval)
{
primaryConfig->RetryInterval = TimeSpan::FromMilliseconds(200);
}
primary = make_shared<PrimaryReplicatorHelper>(
primaryConfig,
hasPersistedState,
epoch,
numberOfCopyOps,
numberOfCopyContextOps,
partitionId);
primary->Open();
}
void ReplicatorTestWrapper::CreateSecondary(
int64 primaryId,
uint index,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
bool dropReplicationAcks,
bool hasPersistedState,
Common::Guid partitionId,
__out int64 & secondaryId,
__out SecondaryReplicatorHelperSPtr & secondary)
{
REConfigSPtr config = TestReplicateCopyOperations::CreateGenericConfig();
secondaryId = primaryId + index + 1;
secondary = make_shared<SecondaryReplicatorHelper>(
config,
secondaryId,
hasPersistedState,
numberOfCopyOps,
numberOfCopyContextOps,
partitionId,
dropReplicationAcks);
secondary->Open();
// Start copy operation pump, which will start the replication pump when
// last copy operation is received
secondary->StartCopyOperationPump();
}
void ReplicatorTestWrapper::CreateConfiguration(
int numberSecondaries,
int numberIdles,
FABRIC_EPOCH const & epoch,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
bool hasPersistedState,
Common::Guid partitionId,
__out PrimaryReplicatorHelperSPtr & primary,
__out vector<SecondaryReplicatorHelperSPtr> & secondaries,
__out vector<int64> & secondaryIds,
bool dropReplicationAcks)
{
CreatePrimary(numberOfCopyOps, numberOfCopyContextOps, dropReplicationAcks, epoch, hasPersistedState, partitionId, primary);
for(int i = 0; i < numberIdles + numberSecondaries; ++i)
{
int64 secondaryId;
SecondaryReplicatorHelperSPtr secondary;
CreateSecondary(primary->PrimaryId, i, numberOfCopyOps, numberOfCopyContextOps, dropReplicationAcks, hasPersistedState, partitionId, secondaryId, secondary);
secondaryIds.push_back(secondaryId);
secondaries.push_back(move(secondary));
}
// Build all replicas
int expectedReplSeq = 0;
if (hasPersistedState && numberOfCopyContextOps == -1)
{
BuildIdles(expectedReplSeq, primary, secondaries, secondaryIds, numberOfCopyOps, 0);
}
else
{
BuildIdles(expectedReplSeq, primary, secondaries, secondaryIds, numberOfCopyOps, numberOfCopyContextOps);
}
// Change active replicas
if (numberSecondaries > 0)
{
PromoteIdlesToSecondaries(0, numberSecondaries, primary, secondaries, secondaryIds);
}
}
void ReplicatorTestWrapper::PromoteIdlesToSecondaries(
int currentNumberSecondaries,
int newNumberSecondaries,
__in PrimaryReplicatorHelperSPtr const & primary,
__in vector<SecondaryReplicatorHelperSPtr> & secondaries,
vector<int64> const & secondaryIds)
{
ReplicaInformationVector replicas;
// Transform idles to secondaries for as many secondaries are required
for(int i = currentNumberSecondaries; i < newNumberSecondaries; ++i)
{
ReplicaInformation replica(
secondaryIds[i],
::FABRIC_REPLICA_ROLE_ACTIVE_SECONDARY,
secondaries[i]->ReplicationEndpoint,
false);
replicas.push_back(std::move(replica));
}
ULONG quorum = static_cast<ULONG>((replicas.size() + 1) / 2 + 1);
ULONG previousQuorum = 0;
ReplicaInformationVector previousReplicas;
ErrorCode error = primary->Replicator.UpdateCatchUpReplicaSetConfiguration(
previousReplicas,
previousQuorum,
replicas,
quorum);
if (!error.IsSuccess())
{
VERIFY_FAIL(L"UpdateCatchUpReplicaSetConfiguration should have succeeded");
}
error = primary->Replicator.UpdateCurrentReplicaSetConfiguration(
replicas,
quorum);
if (!error.IsSuccess())
{
VERIFY_FAIL(L"UpdateCurrentReplicaSetConfiguration should have succeeded");
}
}
void ReplicatorTestWrapper::BuildIdles(
int64 startReplSeq,
__in PrimaryReplicatorHelperSPtr & primary,
__in vector<SecondaryReplicatorHelperSPtr> & secondaries,
vector<int64> const & secondaryIds,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps)
{
vector<ReplicaInformation> replicas;
// Transform idles to secondaries for as many secondaries are required
// Secondary should receive StartCopy and all copy messages (including last NULL).
for(size_t i = 0; i < secondaries.size(); ++i)
{
ReplicaInformation replica(
secondaryIds[i],
::FABRIC_REPLICA_ROLE_IDLE_SECONDARY,
secondaries[i]->ReplicationEndpoint,
false,
Constants::NonInitializedLSN,
Constants::NonInitializedLSN);
replicas.push_back(std::move(replica));
primary->Replicator.AddExpectedAck(secondaries[i]->SecondaryId, startReplSeq, Constants::NonInitializedLSN);
for (int64 j = 1; j <= numberOfCopyOps + 1; ++j)
{
secondaries[i]->Replicator.AddExpectedCopyMessage(primary->EndpointUniqueId, j);
}
if (numberOfCopyContextOps >= 0)
{
for (int64 j = 1; j <= numberOfCopyContextOps + 1; ++j)
{
primary->Replicator.AddExpectedCopyContextMessage(secondaries[i]->EndpointUniqueId, j);
}
}
secondaries[i]->Replicator.AddExpectedStartCopyMessage(primary->EndpointUniqueId);
}
Copy(*(primary.get()), replicas);
}
void ReplicatorTestWrapper::BeginAddIdleCopyNotFinished(
int index,
int64 numberOfCopyOps,
int64 numberOfCopyContextOps,
PrimaryReplicatorHelperSPtr const & primary,
bool hasPersistedState,
Common::Guid partitionId,
__out SecondaryReplicatorHelperSPtr & secondary,
__out int64 & secondaryId,
__in ManualResetEvent & copyDoneEvent)
{
CreateSecondary(primary->PrimaryId, index, numberOfCopyOps, numberOfCopyContextOps, false, hasPersistedState, partitionId, secondaryId, secondary);
ReplicaInformation replica(
secondaryId,
::FABRIC_REPLICA_ROLE_IDLE_SECONDARY,
secondary->ReplicationEndpoint,
false);
// Drop copy operations, to force retry sending them
secondary->Replicator.SetDropCopyAcks(true);
PrimaryReplicatorHelper & repl = *(primary.get());
FABRIC_REPLICA_ID replicaId = replica.Id;
repl.Replicator.BeginBuildReplica(replica,
[&repl, replicaId, ©DoneEvent](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = repl.Replicator.EndBuildReplica(operation);
if (!error.IsSuccess())
{
VERIFY_FAIL_FMT("Copy failed with error {0}.", error);
}
Trace.WriteInfo(ReplCopyTestSource, "Copy done for replica {0}.", replicaId);
copyDoneEvent.Set();
}, AsyncOperationSPtr());
for (int64 i = 1; i <= numberOfCopyOps + 1; ++i)
{
secondary->Replicator.AddExpectedCopyMessage(primary->EndpointUniqueId, i);
}
if (numberOfCopyContextOps >= 0)
{
for (int64 j = 1; j <= numberOfCopyContextOps + 1; ++j)
{
primary->Replicator.AddExpectedCopyContextMessage(secondary->EndpointUniqueId, j);
}
}
secondary->Replicator.AddExpectedStartCopyMessage(primary->EndpointUniqueId);
// Don't wait for the copy to finish -
// It won't, until drop acks is set to false
}
void ReplicatorTestWrapper::EndAddIdleCopyNotFinished(
__in SecondaryReplicatorHelperSPtr & secondary,
__in ManualResetEvent & copyDoneEvent)
{
secondary->Replicator.SetDropCopyAcks(false);
// The primary should retry sending copy operations
// until it gets ACK for the last one.
copyDoneEvent.WaitOne();
}
void ReplicatorTestWrapper::WaitForProgress(
__in PrimaryReplicatorHelper & repl, FABRIC_REPLICA_SET_QUORUM_MODE catchUpMode, bool expectTimeout)
{
ManualResetEvent completeEvent;
AsyncOperationSPtr asyncOp;
volatile bool finished = false;
asyncOp = repl.Replicator.BeginWaitForCatchUpQuorum(
catchUpMode,
[&repl, &completeEvent, &finished, expectTimeout](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = repl.Replicator.EndWaitForCatchUpQuorum(operation);
finished = true;
if (!expectTimeout)
{
VERIFY_IS_TRUE(error.IsSuccess(), L"Wait for full progress completed successfully.");
}
else
{
Trace.WriteInfo(ReplCopyTestSource, "WaitForFullProgress completed with error {0}", error);
}
completeEvent.Set();
}, AsyncOperationSPtr());
if (expectTimeout)
{
completeEvent.WaitOne(2000);
VERIFY_IS_TRUE(!finished, L"WaitForProgress should have timed out");
asyncOp->Cancel();
completeEvent.WaitOne();
VERIFY_IS_TRUE(finished, L"WaitForProgress completed after cancel");
}
else
{
completeEvent.WaitOne();
VERIFY_IS_TRUE(finished, L"WaitForProgress completed in time");
}
}
void ReplicatorTestWrapper::Replicate(
__in PrimaryReplicatorHelper & repl,
FABRIC_SEQUENCE_NUMBER startExpectedSequenceNumber,
uint numberOfOperations)
{
ManualResetEvent replicateDoneEvent;
volatile ULONGLONG count = numberOfOperations;
FABRIC_SEQUENCE_NUMBER sequenceNumber;
for(FABRIC_SEQUENCE_NUMBER i = 0; i < numberOfOperations; ++i)
{
auto operation = make_com<ComTestOperation,IFabricOperationData>(L"ReplicateCopyTest - test replicate operation");
repl.Replicator.BeginReplicate(
std::move(operation),
sequenceNumber,
[&repl, &count, &replicateDoneEvent](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = repl.Replicator.EndReplicate(operation);
if (!error.IsSuccess())
{
VERIFY_FAIL_FMT("Replication failed with error {0}.", error);
}
if (0 == InterlockedDecrement64((volatile LONGLONG *)&count))
{
replicateDoneEvent.Set();
}
}, AsyncOperationSPtr());
Trace.WriteInfo(ReplCopyTestSource, "Replicate operation returned {0} sequence number.", sequenceNumber);
VERIFY_ARE_EQUAL(i + startExpectedSequenceNumber, sequenceNumber,
L"Replicate operation returned expected sequence number");
}
replicateDoneEvent.WaitOne();
}
void ReplicatorTestWrapper::Copy(
__in PrimaryReplicatorHelper & repl,
vector<ReplicaInformation> const & replicas)
{
ManualResetEvent copyDoneEvent;
volatile size_t count = replicas.size();
for(size_t i = 0; i < replicas.size(); ++i)
{
FABRIC_REPLICA_ID replicaId = replicas[i].Id;
repl.Replicator.BeginBuildReplica(replicas[i],
[&repl, replicaId, &count, ©DoneEvent](AsyncOperationSPtr const& operation) -> void
{
ErrorCode error = repl.Replicator.EndBuildReplica(operation);
if (!error.IsSuccess())
{
VERIFY_FAIL_FMT("Copy failed with error {0}.", error);
}
Trace.WriteInfo(ReplCopyTestSource, "Copy done for replica {0}.", replicaId);
if (0 == InterlockedDecrement64((volatile LONGLONG *)&count))
{
copyDoneEvent.Set();
}
}, AsyncOperationSPtr());
}
copyDoneEvent.WaitOne();
}
}
| 39.022862 | 186 | 0.635588 | vishnuk007 |
a28b7993b004b40e3a15ecbe1992cbe30c3fa9f7 | 357 | hpp | C++ | math/camera/3d/orthographic_camera.hpp | aconstlink/natus | d2123c6e1798bd0771b8a1a05721c68392afc92f | [
"MIT"
] | null | null | null | math/camera/3d/orthographic_camera.hpp | aconstlink/natus | d2123c6e1798bd0771b8a1a05721c68392afc92f | [
"MIT"
] | 292 | 2020-03-19T22:38:52.000Z | 2022-03-05T22:49:34.000Z | math/camera/3d/orthographic_camera.hpp | aconstlink/natus | d2123c6e1798bd0771b8a1a05721c68392afc92f | [
"MIT"
] | null | null | null | #pragma once
#include <natus/math/vector/vector3.hpp>
#include <natus/math/vector/vector4.hpp>
#include <natus/math/matrix/matrix3.hpp>
#include <natus/math/matrix/matrix4.hpp>
#include <natus/math/primitive/3d/ray.hpp>
namespace natus
{
namespace math
{
template< typename type_t >
class orthographic_camera
{} ;
}
} | 18.789474 | 42 | 0.683473 | aconstlink |
a28c47c8cad7a6c176b2dc88b1753ae98e8a6d71 | 1,329 | hpp | C++ | include/algorithms/MST.hpp | BPsoda/CS2602 | 94388afa6616625d357cfaf9637018d9609aaeb4 | [
"BSD-3-Clause"
] | 3 | 2021-12-16T09:07:07.000Z | 2021-12-31T16:19:51.000Z | include/algorithms/MST.hpp | BPsoda/CS2602 | 94388afa6616625d357cfaf9637018d9609aaeb4 | [
"BSD-3-Clause"
] | null | null | null | include/algorithms/MST.hpp | BPsoda/CS2602 | 94388afa6616625d357cfaf9637018d9609aaeb4 | [
"BSD-3-Clause"
] | 1 | 2022-01-29T07:06:19.000Z | 2022-01-29T07:06:19.000Z | #include "set/DisjointSet.h"
#include "priority/BinaryHeap.h"
#include "graph/SparseGraph.h"
#include <cstdio>
namespace impl {
template <typename T>
struct Edge {
int from;
int to;
T weight;
};
template <typename T>
struct EdgeLess {
bool operator()(const Edge<T>& lhs, const Edge<T>& rhs) const {
return lhs.weight < rhs.weight;
}
};
}
template <typename T>
void kruskal(SparseGraph<T>& graph) {
int n_vertices = graph.get_num_vertices();
DisjointSet set(n_vertices);
MinBinaryHeap<impl::Edge<T>, impl::EdgeLess<T>> heap;
for (int i =0;i < n_vertices; ++i) {
for (auto it=graph.get_out_edge_begin_iterator(i);it!=graph.get_out_edge_end_iterator(i); ++it) {
if (i < it->to) {
impl::Edge<T> e;
e.from = i;
e.to = it->to;
e.weight = it->edge;
heap.enqueue(e);
}
}
}
int edges_accepted =0;
while (edges_accepted < n_vertices - 1) {
auto edge = heap.front();
heap.dequeue();
if (set.find(edge.from) != set.find(edge.to)) {
++edges_accepted;
set.merge(edge.from, edge.to);
std::printf("(%d, %d)\n", edge.from + 1, edge.to + 1);
}
}
} | 27.122449 | 105 | 0.531226 | BPsoda |
a28e45a00bd2ed30489ee6b6e7a137ebe96777c1 | 710 | hpp | C++ | include/llvm-abi/x86/CPUFeatures.hpp | scrossuk/llvm-abi | bad12c7cb1cdd271cd8804d1ace1b5d1799a2908 | [
"MIT"
] | 29 | 2016-11-14T15:58:23.000Z | 2022-01-07T13:05:39.000Z | include/llvm-abi/x86/CPUFeatures.hpp | scrossuk/llvm-abi | bad12c7cb1cdd271cd8804d1ace1b5d1799a2908 | [
"MIT"
] | null | null | null | include/llvm-abi/x86/CPUFeatures.hpp | scrossuk/llvm-abi | bad12c7cb1cdd271cd8804d1ace1b5d1799a2908 | [
"MIT"
] | 4 | 2017-12-03T15:51:24.000Z | 2020-07-31T23:32:27.000Z | #ifndef LLVMABI_X86_CPUFEATURES_HPP
#define LLVMABI_X86_CPUFEATURES_HPP
#include <set>
#include <string>
#include <llvm/ADT/Triple.h>
#include <llvm-abi/x86/CPUKind.hpp>
namespace llvm_abi {
namespace x86 {
enum SSELevel {
NoSSE,
SSE1,
SSE2,
SSE3,
SSSE3,
SSE41,
SSE42,
AVX,
AVX2,
AVX512F
};
class CPUFeatures {
public:
CPUFeatures();
void add(const std::string& feature);
bool hasAVX() const;
SSELevel sseLevel() const;
private:
std::set<std::string> features_;
SSELevel sseLevel_;
};
CPUFeatures getCPUFeatures(const llvm::Triple& targetTriple,
const CPUKind cpu);
}
}
#endif | 13.921569 | 62 | 0.621127 | scrossuk |
a29d4f48a61a7ca8d749ec06b5c2a8cd13e3e98d | 485 | cpp | C++ | Leetcode/majority-element.cpp | omonimus1/angorithm_AND_dataStructure | 2a6a0cda29cb618a787654b5c66ed6f43fe618e2 | [
"Apache-2.0"
] | 580 | 2020-04-08T16:47:36.000Z | 2022-03-31T15:09:13.000Z | Leetcode/majority-element.cpp | omonimus1/angorithm_AND_dataStructure | 2a6a0cda29cb618a787654b5c66ed6f43fe618e2 | [
"Apache-2.0"
] | 3 | 2020-10-01T08:46:42.000Z | 2020-11-23T17:12:35.000Z | Leetcode/majority-element.cpp | omonimus1/angorithm_AND_dataStructure | 2a6a0cda29cb618a787654b5c66ed6f43fe618e2 | [
"Apache-2.0"
] | 87 | 2020-06-07T16:30:08.000Z | 2022-03-29T19:30:47.000Z | // https://leetcode.com/problems/majority-element/submissions/
class Solution {
public:
int majorityElement(vector<int>& nums) {
int len = nums.size();
int frequency = len/2;
unordered_map<int, int>mp;
for(int i =0; i < len; i++)
{
mp[nums[i]]++;
}
for(auto x: mp)
{
if(x.second > frequency)
return x.first;
}
return -1;
}
}; | 22.045455 | 62 | 0.449485 | omonimus1 |
94789dbfabcf88adf58a403fb608a3cc80d533e1 | 8,345 | cpp | C++ | src/cep/oms/portfolio.cpp | hvsqg/ft | d721ed881a4222ca8790cbfca489ab7012704f0d | [
"MIT"
] | null | null | null | src/cep/oms/portfolio.cpp | hvsqg/ft | d721ed881a4222ca8790cbfca489ab7012704f0d | [
"MIT"
] | null | null | null | src/cep/oms/portfolio.cpp | hvsqg/ft | d721ed881a4222ca8790cbfca489ab7012704f0d | [
"MIT"
] | null | null | null | // Copyright [2020] <Copyright Kevin, kevin.lau.gd@gmail.com>
#include "cep/oms/portfolio.h"
#include <spdlog/spdlog.h>
#include <algorithm>
#include "cep/data/constants.h"
#include "cep/data/contract_table.h"
namespace ft {
Portfolio::Portfolio() {}
void Portfolio::init(uint32_t max_tid, bool sync_to_redis, uint64_t account) {
if (sync_to_redis) {
redis_ = std::make_unique<RedisPositionSetter>();
redis_->set_account(account);
redis_->clear();
}
positions_.resize(max_tid + 1);
uint32_t tid = 0;
for (auto& pos : positions_) pos.tid = tid++;
}
void Portfolio::set_position(const Position& pos) {
positions_[pos.tid] = pos;
if (redis_) {
auto contract = ContractTable::get_by_index(pos.tid);
assert(contract);
redis_->set(contract->ticker, pos);
}
}
void Portfolio::update_pending(uint32_t tid, uint32_t direction,
uint32_t offset, int changed) {
if (changed == 0) return;
if (direction == Direction::BUY || direction == Direction::SELL) {
update_buy_or_sell_pending(tid, direction, offset, changed);
} else if (direction == Direction::PURCHASE ||
direction == Direction::REDEEM) {
update_purchase_or_redeem_pending(tid, direction, changed);
}
}
void Portfolio::update_buy_or_sell_pending(uint32_t tid, uint32_t direction,
uint32_t offset, int changed) {
bool is_close = is_offset_close(offset);
if (is_close) direction = opp_direction(direction);
auto& pos = positions_[tid];
auto& pos_detail = direction == Direction::BUY ? pos.long_pos : pos.short_pos;
if (is_close)
pos_detail.close_pending += changed;
else
pos_detail.open_pending += changed;
if (pos_detail.open_pending < 0) {
pos_detail.open_pending = 0;
// spdlog::warn("[Portfolio::update_buy_or_sell_pending] correct
// open_pending");
}
if (pos_detail.close_pending < 0) {
pos_detail.close_pending = 0;
// spdlog::warn("[Portfolio::update_buy_or_sell_pending] correct
// close_pending");
}
if (redis_) {
const auto* contract = ContractTable::get_by_index(pos.tid);
assert(contract);
redis_->set(contract->ticker, pos);
}
}
void Portfolio::update_purchase_or_redeem_pending(uint32_t tid,
uint32_t direction,
int changed) {
auto& pos = positions_[tid];
auto& pos_detail = pos.long_pos;
if (direction == Direction::PURCHASE) {
pos_detail.open_pending += changed;
} else {
pos_detail.close_pending += changed;
}
if (pos_detail.open_pending < 0) {
pos_detail.open_pending = 0;
// spdlog::warn("[Portfolio::update_purchase_or_redeem_pending] correct
// open_pending");
}
if (pos_detail.close_pending < 0) {
pos_detail.close_pending = 0;
// spdlog::warn("[Portfolio::update_purchase_or_redeem_pending] correct
// close_pending");
}
if (redis_) {
const auto* contract = ContractTable::get_by_index(pos.tid);
assert(contract);
redis_->set(contract->ticker, pos);
}
}
void Portfolio::update_traded(uint32_t tid, uint32_t direction, uint32_t offset,
int traded, double traded_price) {
if (traded <= 0) return;
if (direction == Direction::BUY || direction == Direction::SELL) {
update_buy_or_sell(tid, direction, offset, traded, traded_price);
} else if (direction == Direction::PURCHASE ||
direction == Direction::REDEEM) {
update_purchase_or_redeem(tid, direction, traded);
}
}
void Portfolio::update_buy_or_sell(uint32_t tid, uint32_t direction,
uint32_t offset, int traded,
double traded_price) {
bool is_close = is_offset_close(offset);
if (is_close) direction = opp_direction(direction);
auto& pos = positions_[tid];
auto& pos_detail = direction == Direction::BUY ? pos.long_pos : pos.short_pos;
if (is_close) {
pos_detail.close_pending -= traded;
pos_detail.holdings -= traded;
// 这里close_yesterday也执行这个操作是为了防止有些交易所不区分昨今仓,
// 但用户平仓的时候却使用了close_yesterday
if (offset == Offset::CLOSE_YESTERDAY || offset == Offset::CLOSE)
pos_detail.yd_holdings -= std::min(pos_detail.yd_holdings, traded);
if (pos_detail.holdings < pos_detail.yd_holdings) {
spdlog::warn("yd pos fixed");
pos_detail.yd_holdings = pos_detail.holdings;
}
} else {
pos_detail.open_pending -= traded;
pos_detail.holdings += traded;
}
// TODO(kevin): 这里可能出问题
// 如果abort可能是trade在position之前到达,正常使用不可能出现
// 如果close_pending小于0,也有可能是之前启动时的挂单成交了,
// 这次重启时未重启获取挂单数量导致的
assert(pos_detail.holdings >= 0);
if (pos_detail.open_pending < 0) {
pos_detail.open_pending = 0;
// spdlog::warn("[Portfolio::update_traded] correct open_pending");
}
if (pos_detail.close_pending < 0) {
pos_detail.close_pending = 0;
// spdlog::warn("[Portfolio::update_traded] correct close_pending");
}
const auto* contract = ContractTable::get_by_index(tid);
if (!contract) {
spdlog::error("[Position::update_buy_or_sell] Contract not found");
return;
}
assert(contract->size > 0);
// 如果是开仓则计算当前持仓的成本价
if (is_offset_open(offset) && pos_detail.holdings > 0) {
double cost = contract->size * (pos_detail.holdings - traded) *
pos_detail.cost_price +
contract->size * traded * traded_price;
pos_detail.cost_price = cost / (pos_detail.holdings * contract->size);
}
if (pos_detail.holdings == 0) {
pos_detail.cost_price = 0;
}
if (redis_) redis_->set(contract->ticker, pos);
}
void Portfolio::update_purchase_or_redeem(uint32_t tid, uint32_t direction,
int traded) {
auto& pos = positions_[tid];
auto& pos_detail = pos.long_pos;
if (direction == Direction::PURCHASE) {
pos_detail.open_pending -= traded;
pos_detail.holdings += traded;
pos_detail.yd_holdings += traded;
} else {
pos_detail.close_pending -= traded;
int td_pos = pos_detail.holdings - pos_detail.yd_holdings;
pos_detail.holdings -= traded;
pos_detail.yd_holdings -= std::max(traded - td_pos, 0);
if (pos_detail.holdings == 0) {
pos_detail.float_pnl = 0;
pos_detail.cost_price = 0;
}
}
if (redis_) {
const auto* contract = ContractTable::get_by_index(tid);
if (!contract) {
spdlog::error("[Position::update_purchase_or_redeem] Contract not found");
return;
}
redis_->set(contract->ticker, pos);
}
}
void Portfolio::update_component_stock(uint32_t tid, int traded, bool acquire) {
auto& pos = positions_[tid];
auto& pos_detail = pos.long_pos;
if (acquire) {
pos_detail.holdings += traded;
pos_detail.yd_holdings += traded;
} else {
int td_pos = pos_detail.holdings - pos_detail.yd_holdings;
pos_detail.holdings -= traded;
pos_detail.yd_holdings -= std::max(traded - td_pos, 0);
}
if (redis_) {
const auto* contract = ContractTable::get_by_index(tid);
if (!contract) {
spdlog::error("[Position::update_purchase_or_redeem] Contract not found");
return;
}
redis_->set(contract->ticker, pos);
}
}
void Portfolio::update_float_pnl(uint32_t tid, double last_price) {
auto& pos = positions_[tid];
if (pos.long_pos.holdings > 0 || pos.short_pos.holdings > 0) {
const auto* contract = ContractTable::get_by_index(tid);
if (!contract || contract->size <= 0) return;
auto& lp = pos.long_pos;
auto& sp = pos.short_pos;
if (lp.holdings > 0)
lp.float_pnl =
lp.holdings * contract->size * (last_price - lp.cost_price);
if (sp.holdings > 0)
sp.float_pnl =
sp.holdings * contract->size * (sp.cost_price - last_price);
if (redis_) {
if (lp.holdings > 0 || sp.holdings > 0) {
redis_->set(contract->ticker, pos);
}
}
}
}
void Portfolio::update_on_query_trade(uint32_t tid, uint32_t direction,
uint32_t offset, int closed_volume) {
// auto* pos = find(tid);
// if (!pos) return;
// const auto* contract = ContractTable::get_by_index(tid);
// if (!contract) return;
// redis_.set(proto_.pos_key(contract->ticker), pos, sizeof(*pos));
}
} // namespace ft
| 29.803571 | 80 | 0.650929 | hvsqg |
947b274a140ae0578f5804acce5f2e027e8de63d | 1,972 | hpp | C++ | libs/fnd/tuple/include/bksge/fnd/tuple/detail/tuple_concater.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 4 | 2018-06-10T13:35:32.000Z | 2021-06-03T14:27:41.000Z | libs/fnd/tuple/include/bksge/fnd/tuple/detail/tuple_concater.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 566 | 2017-01-31T05:36:09.000Z | 2022-02-09T05:04:37.000Z | libs/fnd/tuple/include/bksge/fnd/tuple/detail/tuple_concater.hpp | myoukaku/bksge | 0f8b60e475a3f1709723906e4796b5e60decf06e | [
"MIT"
] | 1 | 2018-07-05T04:40:53.000Z | 2018-07-05T04:40:53.000Z | /**
* @file tuple_concater.hpp
*
* @brief tuple_concater の定義
*
* @author myoukaku
*/
#ifndef BKSGE_FND_TUPLE_DETAIL_TUPLE_CONCATER_HPP
#define BKSGE_FND_TUPLE_DETAIL_TUPLE_CONCATER_HPP
#include <bksge/fnd/tuple/tuple_size.hpp>
#include <bksge/fnd/tuple/get.hpp>
#include <bksge/fnd/type_traits/remove_reference.hpp>
#include <bksge/fnd/utility/index_sequence.hpp>
#include <bksge/fnd/utility/make_index_sequence.hpp>
#include <bksge/fnd/config.hpp>
#include <cstddef>
#include <utility>
namespace bksge
{
namespace tuple_detail
{
// Performs the actual concatenation by step-wise expanding tuple-like
// objects into the elements, which are finally forwarded into the
// result tuple.
template <typename Ret, typename... Tuples>
struct tuple_concater;
template <typename Ret, typename T, typename... Tuples>
struct tuple_concater<Ret, T, Tuples...>
{
private:
template <std::size_t... Indices, typename... Args>
static BKSGE_CONSTEXPR Ret
invoke_impl(bksge::index_sequence<Indices...>, T&& tp, Tuples&&... tps, Args&&... args)
{
using next = tuple_concater<Ret, Tuples...>;
return next::invoke(
std::forward<Tuples>(tps)...,
std::forward<Args>(args)...,
bksge::get<Indices>(std::forward<T>(tp))...);
}
public:
template <typename... Args>
static BKSGE_CONSTEXPR Ret
invoke(T&& tp, Tuples&&... tps, Args&&... args)
{
using IndexSeq = bksge::make_index_sequence<
bksge::tuple_size<
bksge::remove_reference_t<T>
>::value>;
return invoke_impl(
IndexSeq{},
std::forward<T>(tp),
std::forward<Tuples>(tps)...,
std::forward<Args>(args)...);
}
};
template <typename Ret>
struct tuple_concater<Ret>
{
template <typename... Args>
static BKSGE_CONSTEXPR Ret
invoke(Args&&... args)
{
return Ret(std::forward<Args>(args)...);
}
};
} // namespace tuple_detail
} // namespace bksge
#endif // BKSGE_FND_TUPLE_DETAIL_TUPLE_CONCATER_HPP
| 24.345679 | 89 | 0.684077 | myoukaku |
947b5b8df77745ac1114654c3ae26162ec08f44e | 1,542 | cpp | C++ | ACW Project Framework/Collider.cpp | Lentono/PhysicsSimulationACW | a73d22571a0742fd960740f04689f6ee095c3986 | [
"MIT"
] | 1 | 2021-06-06T10:29:12.000Z | 2021-06-06T10:29:12.000Z | ACW Project Framework/Collider.cpp | Lentono/PhysicsSimulationACW | a73d22571a0742fd960740f04689f6ee095c3986 | [
"MIT"
] | null | null | null | ACW Project Framework/Collider.cpp | Lentono/PhysicsSimulationACW | a73d22571a0742fd960740f04689f6ee095c3986 | [
"MIT"
] | null | null | null | #include "Collider.h"
Collider::Collider() = default;
Collider::~Collider() = default;
SphereCollider::SphereCollider() = default;
SphereCollider::~SphereCollider() = default;
Collider::ColliderType SphereCollider::GetCollider() const
{
return Sphere;
}
AABBCubeCollider::AABBCubeCollider() = default;
AABBCubeCollider::~AABBCubeCollider() = default;
Collider::ColliderType AABBCubeCollider::GetCollider() const
{
return AABBCube;
}
OBBCubeCollider::OBBCubeCollider() = default;
OBBCubeCollider::~OBBCubeCollider() = default;
Collider::ColliderType OBBCubeCollider::GetCollider() const
{
return OBBCube;
}
PlaneCollider::PlaneCollider() = default;
PlaneCollider::~PlaneCollider() = default;
Collider::ColliderType PlaneCollider::GetCollider() const
{
return Plane;
}
XMVECTOR PlaneCollider::GetNormal() const
{
return m_normal;
}
float PlaneCollider::GetOffset() const
{
return m_offset;
}
void PlaneCollider::SetNormal(const XMFLOAT3& centre, const XMFLOAT3& pointOne, const XMFLOAT3& pointTwo)
{
const auto crossOne = pointOne - centre;
const auto crossTwo = pointTwo - centre;
m_normal = XMVector3Normalize(XMVector3Cross(XMLoadFloat3(&crossOne), XMLoadFloat3(&crossTwo)));
XMStoreFloat(&m_offsetTest, XMVector3Dot(m_normal, XMLoadFloat3(¢re)));
}
void PlaneCollider::SetOffset(const float offset)
{
m_offset = offset;
}
CylinderCollider::CylinderCollider() = default;
CylinderCollider::~CylinderCollider() = default;
Collider::ColliderType CylinderCollider::GetCollider() const
{
return Cylinder;
}
| 20.289474 | 105 | 0.770428 | Lentono |
947db6935b38ee1666973e36f88740c50019b61e | 1,017 | cpp | C++ | plugins/wininput/src/cursor/grab.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 2 | 2016-01-27T13:18:14.000Z | 2018-05-11T01:11:32.000Z | plugins/wininput/src/cursor/grab.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | null | null | null | plugins/wininput/src/cursor/grab.cpp | cpreh/spacegameengine | 313a1c34160b42a5135f8223ffaa3a31bc075a01 | [
"BSL-1.0"
] | 3 | 2018-05-11T01:11:34.000Z | 2021-04-24T19:47:45.000Z | // Copyright Carl Philipp Reh 2006 - 2019.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#include <sge/wininput/cursor/clip.hpp>
#include <sge/wininput/cursor/grab.hpp>
#include <sge/wininput/cursor/set_capture.hpp>
#include <sge/wininput/cursor/show.hpp>
#include <awl/backends/windows/optional_rect.hpp>
#include <awl/backends/windows/window/get_rect.hpp>
#include <awl/backends/windows/window/object_fwd.hpp>
bool sge::wininput::cursor::grab(awl::backends::windows::window::object &_window)
{
sge::wininput::cursor::show(false);
{
// When can this fail?
awl::backends::windows::optional_rect const window_rect(
awl::backends::windows::window::get_rect(_window));
if (!window_rect.has_value())
return false;
if (!sge::wininput::cursor::clip(window_rect))
return false;
}
sge::wininput::cursor::set_capture(_window);
return true;
}
| 29.911765 | 81 | 0.706981 | cpreh |
947e67864b3a21c40f066bb4f4ff5eb330e88e88 | 1,227 | cpp | C++ | ReactQt/runtime/src/componentmanagers/activityindicatormanager.cpp | hlolli/react-native-desktop | 3b7d0fd669d49f29698391f2025860593163fc45 | [
"MIT"
] | 5 | 2020-10-22T19:25:01.000Z | 2020-10-22T19:34:52.000Z | ReactQt/runtime/src/componentmanagers/activityindicatormanager.cpp | hlolli/react-native-desktop | 3b7d0fd669d49f29698391f2025860593163fc45 | [
"MIT"
] | 1 | 2018-11-14T17:45:55.000Z | 2018-11-14T17:45:55.000Z | ReactQt/runtime/src/componentmanagers/activityindicatormanager.cpp | hlolli/react-native-desktop | 3b7d0fd669d49f29698391f2025860593163fc45 | [
"MIT"
] | null | null | null |
/**
* Copyright (c) 2017-present, Status Research and Development GmbH.
* 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. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
*/
#include <QQmlComponent>
#include <QQmlProperty>
#include <QQuickItem>
#include <QString>
#include <QVariant>
#include <QDebug>
#include "attachedproperties.h"
#include "bridge.h"
#include "componentmanagers/activityindicatormanager.h"
#include "propertyhandler.h"
#include "utilities.h"
class ActivityIndicatorManagerPrivate {};
ActivityIndicatorManager::ActivityIndicatorManager(QObject* parent)
: ViewManager(parent), d_ptr(new ActivityIndicatorManagerPrivate) {}
ActivityIndicatorManager::~ActivityIndicatorManager() {}
ViewManager* ActivityIndicatorManager::viewManager() {
return this;
}
QString ActivityIndicatorManager::moduleName() {
return "RCTActivityIndicatorViewManager";
}
QString ActivityIndicatorManager::qmlComponentFile(const QVariantMap& properties) const {
return "qrc:/qml/ReactActivityIndicator.qml";
}
#include "activityindicatormanager.moc"
| 26.673913 | 89 | 0.780766 | hlolli |
9480d3d9a49d0fc0a9088ba1f873249f0917b472 | 732 | cpp | C++ | uri/1049.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 3 | 2018-01-08T02:52:51.000Z | 2021-03-03T01:08:44.000Z | uri/1049.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | null | null | null | uri/1049.cpp | cosmicray001/Online_judge_Solutions- | 5dc6f90d3848eb192e6edea8e8c731f41a1761dd | [
"MIT"
] | 1 | 2020-08-13T18:07:35.000Z | 2020-08-13T18:07:35.000Z | #include <bits/stdc++.h>
using namespace std;
string re(string s1, string s2, string s3)
{
if(s1 == "vertebrado"){
if(s2 == "ave"){
if(s3 == "carnivoro") return "aguia";
else return "pomba";
}
else if(s3 == "onivoro") return "homem";
else return "vaca";
}
else{
if(s2 == "inseto"){
if(s3 == "hematofago") return "pulga";
else return "lagarta";
}
else if(s3 == "hematofago") return "sanguessuga";
else return "minhoca";
}
}
int main()
{
string s1, s2, s3;
getline(cin, s1);
getline(cin, s2);
getline(cin, s3);
string ch = re(s1, s2, s3);
cout << ch << endl;
return 0;
}
| 20.333333 | 57 | 0.493169 | cosmicray001 |
94825d344a83cc171c1f234bc1ac25203f206811 | 4,380 | hpp | C++ | sprig/utility/container.hpp | bolero-MURAKAMI/Sprig | 51ce4db4f4d093dee659a136f47249e4fe91fc7a | [
"BSL-1.0"
] | 2 | 2017-10-24T13:56:24.000Z | 2018-09-28T13:21:22.000Z | sprig/utility/container.hpp | bolero-MURAKAMI/Sprig | 51ce4db4f4d093dee659a136f47249e4fe91fc7a | [
"BSL-1.0"
] | null | null | null | sprig/utility/container.hpp | bolero-MURAKAMI/Sprig | 51ce4db4f4d093dee659a136f47249e4fe91fc7a | [
"BSL-1.0"
] | 2 | 2016-04-12T03:26:06.000Z | 2018-09-28T13:21:22.000Z | /*=============================================================================
Copyright (c) 2010-2016 Bolero MURAKAMI
https://github.com/bolero-MURAKAMI/Sprig
Distributed under the Boost Software License, Version 1.0. (See accompanying
file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt)
=============================================================================*/
#ifndef SPRIG_UTILITY_CONTAINER_HPP
#define SPRIG_UTILITY_CONTAINER_HPP
#include <sprig/config/config.hpp>
#ifdef SPRIG_USING_PRAGMA_ONCE
# pragma once
#endif // #ifdef SPRIG_USING_PRAGMA_ONCE
#include <utility>
#include <functional>
#include <boost/utility/enable_if.hpp>
#include <sprig/type_traits/is_call_copy_param.hpp>
namespace sprig {
//
// push_back_
//
template<typename T1, typename T2 = typename T1::value_type, typename Dummy = void>
struct push_back_ {};
template<typename T1, typename T2>
struct push_back_<T1, T2, typename boost::enable_if<sprig::is_call_copy_param<T2> >::type>
: public std::binary_function<T1, T2, void>
{
private:
typedef std::binary_function<T1, T2, void> binary_function_type;
public:
typedef typename binary_function_type::result_type result_type;
typedef typename binary_function_type::first_argument_type first_argument_type;
typedef typename binary_function_type::second_argument_type second_argument_type;
public:
result_type operator()(first_argument_type& lhs, second_argument_type rhs) const {
lhs.push_back(rhs);
}
};
template<typename T1, typename T2>
struct push_back_<T1, T2, typename boost::disable_if<sprig::is_call_copy_param<T2> >::type>
: public std::binary_function<T1, T2, void>
{
private:
typedef std::binary_function<T1, T2, void> binary_function_type;
public:
typedef typename binary_function_type::result_type result_type;
typedef typename binary_function_type::first_argument_type first_argument_type;
typedef typename binary_function_type::second_argument_type second_argument_type;
public:
result_type operator()(first_argument_type& lhs, second_argument_type const& rhs) const {
lhs.push_back(rhs);
}
};
//
// any_push_back_
//
struct any_push_back_ {
template<typename T1, typename T2>
typename boost::enable_if<sprig::is_call_copy_param<T2> >::type
operator()(T1& lhs, T2 rhs) const {
lhs.push_back(rhs);
}
template<typename T1, typename T2>
typename boost::disable_if<sprig::is_call_copy_param<T2> >::type
operator()(T1& lhs, T2 const& rhs) const {
lhs.push_back(rhs);
}
};
//
// push_front_
//
template<typename T1, typename T2 = typename T1::value_type, typename Dummy = void>
struct push_front_ {};
template<typename T1, typename T2>
struct push_front_<T1, T2, typename boost::enable_if<sprig::is_call_copy_param<T2> >::type>
: public std::binary_function<T1, T2, void>
{
private:
typedef std::binary_function<T1, T2, void> binary_function_type;
public:
typedef typename binary_function_type::result_type result_type;
typedef typename binary_function_type::first_argument_type first_argument_type;
typedef typename binary_function_type::second_argument_type second_argument_type;
public:
result_type operator()(first_argument_type& lhs, second_argument_type rhs) const {
lhs.push_front(rhs);
}
};
template<typename T1, typename T2>
struct push_front_<T1, T2, typename boost::disable_if<sprig::is_call_copy_param<T2> >::type>
: public std::binary_function<T1, T2, void>
{
private:
typedef std::binary_function<T1, T2, void> binary_function_type;
public:
typedef typename binary_function_type::result_type result_type;
typedef typename binary_function_type::first_argument_type first_argument_type;
typedef typename binary_function_type::second_argument_type second_argument_type;
public:
result_type operator()(first_argument_type& lhs, second_argument_type const& rhs) const {
lhs.push_front(rhs);
}
};
//
// any_push_front_
//
struct any_push_front_ {
template<typename T1, typename T2>
typename boost::enable_if<sprig::is_call_copy_param<T2> >::type
operator()(T1& lhs, T2 rhs) const {
lhs.push_front(rhs);
}
template<typename T1, typename T2>
typename boost::disable_if<sprig::is_call_copy_param<T2> >::type
operator()(T1& lhs, T2 const& rhs) const {
lhs.push_front(rhs);
}
};
} // namespace sprig
#endif // #ifndef SPRIG_UTILITY_CONTAINER_HPP
| 34.761905 | 93 | 0.739498 | bolero-MURAKAMI |
948e08d5bde17f769127b63597d833ceb45b5815 | 7,828 | cpp | C++ | xarm_api/src/xarm_driver.cpp | stevewen/xarm_ros | 93770d50faf83be627ad16c268c7477ba72187c5 | [
"BSD-3-Clause"
] | null | null | null | xarm_api/src/xarm_driver.cpp | stevewen/xarm_ros | 93770d50faf83be627ad16c268c7477ba72187c5 | [
"BSD-3-Clause"
] | null | null | null | xarm_api/src/xarm_driver.cpp | stevewen/xarm_ros | 93770d50faf83be627ad16c268c7477ba72187c5 | [
"BSD-3-Clause"
] | null | null | null | /* Copyright 2018 UFACTORY Inc. All Rights Reserved.
*
* Software License Agreement (BSD License)
*
* Author: waylon <weile.wang@ufactory.cc>
============================================================================*/
#include <xarm_driver.h>
#include "xarm/instruction/uxbus_cmd_config.h"
namespace xarm_api
{
XARMDriver::~XARMDriver()
{
arm_cmd_->set_mode(XARM_MODE::POSE);
arm_cmd_->close();
spinner.stop();
}
void XARMDriver::XARMDriverInit(ros::NodeHandle& root_nh, char *server_ip)
{
nh_ = root_nh;
// api command services:
motion_ctrl_server_ = nh_.advertiseService("motion_ctrl", &XARMDriver::MotionCtrlCB, this);
set_mode_server_ = nh_.advertiseService("set_mode", &XARMDriver::SetModeCB, this);
set_state_server_ = nh_.advertiseService("set_state", &XARMDriver::SetStateCB, this);
set_tcp_offset_server_ = nh_.advertiseService("set_tcp_offset", &XARMDriver::SetTCPOffsetCB, this);
go_home_server_ = nh_.advertiseService("go_home", &XARMDriver::GoHomeCB, this);
move_joint_server_ = nh_.advertiseService("move_joint", &XARMDriver::MoveJointCB, this);
move_lineb_server_ = nh_.advertiseService("move_lineb", &XARMDriver::MoveLinebCB, this);
move_line_server_ = nh_.advertiseService("move_line", &XARMDriver::MoveLineCB, this);
move_servoj_server_ = nh_.advertiseService("move_servoj", &XARMDriver::MoveServoJCB, this);
// state feedback topics:
joint_state_ = nh_.advertise<sensor_msgs::JointState>("joint_states", 10, true);
robot_rt_state_ = nh_.advertise<xarm_msgs::RobotMsg>("xarm_states", 10, true);
arm_report_ = connect_tcp_report_norm(server_ip);
// ReportDataNorm norm_data_;
arm_cmd_ = connect_tcp_control(server_ip);
if (arm_cmd_ == NULL)
ROS_ERROR("Xarm Connection Failed!");
}
bool XARMDriver::MotionCtrlCB(xarm_msgs::SetAxis::Request& req, xarm_msgs::SetAxis::Response& res)
{
res.ret = arm_cmd_->motion_en(req.id, req.data);
if(req.data == 1)
{
res.message = "motion enable, ret = " + std::to_string(res.ret);
}
else
{
res.message = "motion disable, ret = " + std::to_string(res.ret);
}
return true;
}
bool XARMDriver::SetModeCB(xarm_msgs::SetInt16::Request& req, xarm_msgs::SetInt16::Response& res)
{
res.ret = arm_cmd_->set_mode(req.data);
switch(req.data)
{
case XARM_MODE::POSE:
{
res.message = "pose mode, ret = " + std::to_string(res.ret);
}break;
case XARM_MODE::SERVO:
{
res.message = "servo mode, ret = " + std::to_string(res.ret);
}break;
case XARM_MODE::TEACH_CART:
{
res.message = "cartesian teach, ret = " + std::to_string(res.ret);
} break;
case XARM_MODE::TEACH_JOINT:
{
res.message = "joint teach , ret = " + std::to_string(res.ret);
} break;
default:
{
res.message = "the failed mode, ret = " + std::to_string(res.ret);
}
}
return true;
}
bool XARMDriver::SetStateCB(xarm_msgs::SetInt16::Request& req, xarm_msgs::SetInt16::Response& res)
{
res.ret = arm_cmd_->set_state(req.data);
switch(req.data)
{
case XARM_STATE::START:
{
res.message = "start, ret = " + std::to_string(res.ret);
}break;
case XARM_STATE::PAUSE:
{
res.message = "pause, ret = " + std::to_string(res.ret);
}break;
case XARM_STATE::STOP:
{
res.message = "stop, ret = " + std::to_string(res.ret);
}break;
default:
{
res.message = "the failed state, ret = " + std::to_string(res.ret);
}
}
return true;
}
bool XARMDriver::SetTCPOffsetCB(xarm_msgs::TCPOffset::Request &req, xarm_msgs::TCPOffset::Response &res)
{
float offsets[6] = {req.x, req.y, req.z, req.roll, req.pitch, req.yaw};
res.ret = arm_cmd_->set_tcp_offset(offsets);
res.message = "set tcp offset: ret = " + std::to_string(res.ret);
return true;
}
bool XARMDriver::GoHomeCB(xarm_msgs::Move::Request &req, xarm_msgs::Move::Response &res)
{
res.ret = arm_cmd_->move_gohome(req.mvvelo, req.mvacc, req.mvtime);
res.message = "go home, ret = " + std::to_string(res.ret);
return true;
}
bool XARMDriver::MoveJointCB(xarm_msgs::Move::Request &req, xarm_msgs::Move::Response &res)
{
float joint[1][7];
int index = 0;
if(req.pose.size() != 7)
{
res.ret = req.pose.size();
res.message = "pose parameters incorrect!";
return true;
}
else
{
for(index = 0; index < 7; index++)
{
joint[0][index] = req.pose[index];
}
}
res.ret = arm_cmd_->move_joint(joint[0], req.mvvelo, req.mvacc, req.mvtime);
res.message = "move joint, ret = " + std::to_string(res.ret);
return true;
}
bool XARMDriver::MoveLineCB(xarm_msgs::Move::Request &req, xarm_msgs::Move::Response &res)
{
float pose[1][6];
int index = 0;
if(req.pose.size() != 6)
{
res.ret = -1;
res.message = "parameters incorrect!";
return true;
}
else
{
for(index = 0; index < 6; index++)
{
pose[0][index] = req.pose[index];
}
}
res.ret = arm_cmd_->move_line(pose[0], req.mvvelo, req.mvacc, req.mvtime);
res.message = "move line, ret = " + std::to_string(res.ret);
return true;
}
bool XARMDriver::MoveLinebCB(xarm_msgs::Move::Request &req, xarm_msgs::Move::Response &res)
{
float pose[1][6];
int index = 0;
if(req.pose.size() != 6)
{
res.ret = -1;
res.message = "parameters incorrect!";
return true;
}
else
{
for(index = 0; index < 6; index++)
{
pose[0][index] = req.pose[index];
}
}
res.ret = arm_cmd_->move_lineb(pose[0], req.mvvelo, req.mvacc, req.mvtime, req.mvradii);
res.message = "move lineb, ret = " + std::to_string(res.ret);
return true;
}
bool XARMDriver::MoveServoJCB(xarm_msgs::Move::Request &req, xarm_msgs::Move::Response &res)
{
float pose[1][7];
int index = 0;
if(req.pose.size() != 7)
{
res.ret = -1;
res.message = "parameters incorrect!";
return true;
}
else
{
for(index = 0; index < 7; index++)
{
pose[0][index] = req.pose[index];
}
}
res.ret = arm_cmd_->move_servoj(pose[0], req.mvvelo, req.mvacc, req.mvtime);
res.message = "move servoj, ret = " + std::to_string(res.ret);
return true;
}
void XARMDriver::pub_robot_msg(xarm_msgs::RobotMsg rm_msg)
{
robot_rt_state_.publish(rm_msg);
}
void XARMDriver::pub_joint_state(sensor_msgs::JointState js_msg)
{
joint_state_.publish(js_msg);
}
int XARMDriver::get_frame(void)
{
int ret;
ret = arm_report_->read_frame(rx_data_);
return ret;
}
int XARMDriver::get_rich_data(ReportDataNorm &norm_data)
{
int ret;
ret = norm_data_.flush_data(rx_data_);
norm_data = norm_data_;
return ret;
}
}
| 31.821138 | 108 | 0.547011 | stevewen |
94983d1e5f27621a8c5faefa5550beb1e3ed465b | 3,401 | cpp | C++ | Practice/2019.5.22/LOJ2979.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | 4 | 2017-10-31T14:25:18.000Z | 2018-06-10T16:10:17.000Z | Practice/2019.5.22/LOJ2979.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | Practice/2019.5.22/LOJ2979.cpp | SYCstudio/OI | 6e9bfc17dbd4b43467af9b19aa2aed41e28972fa | [
"MIT"
] | null | null | null | #include<bits/stdc++.h>
using namespace std;
#define ls (x<<1)
#define rs (ls|1)
const int maxN=310;
const int maxM=11;
const int maxNN=maxN*maxM*9;
const int maxMM=maxNN*8;
const int inf=1000000000;
class Edge
{
public:
int v,flow,w;
};
int n,m;
int ecnt=-1,Hd[maxNN],Nt[maxMM],idcnt=2,S=1,T=2;
Edge E[maxMM];
int Id[2][maxN<<2][maxM],L[maxN][maxM],R[maxN][maxM];
queue<int> Qu;
int vis[maxNN],Dst[maxNN],viscnt;
void Add_Edge(int u,int v,int flow,int w);
void Build(int x,int l,int r,int k0,int k1);
void Query(int x,int l,int r,int ql,int qr,int b,int j,int p);
bool SPFA();
int dfs(int u);
int main()
{
memset(Hd,-1,sizeof(Hd));
scanf("%d%d",&n,&m);
Build(1,1,n,0,0);
for (int i=1; i<=n; i++) for (int j=1; j<=m; j++) scanf("%d",&L[i][j]),++L[i][j];
for (int i=1; i<=n; i++) for (int j=1; j<=m; j++) scanf("%d",&R[i][j]),++R[i][j];
for (int i=1; i<=n; i++)
for (int j=1; j<=m; j++) {
++idcnt;
Add_Edge(S,idcnt,1,0);
if (L[i][j]<=i) Query(1,1,n,L[i][j],min(R[i][j],i),0,j,i);
if (R[i][j]>=i+1) Query(1,1,n,max(L[i][j],i+1),R[i][j],1,j,i);
}
int Ans=0,flow=0;
while (SPFA()) {
while (1) {
++viscnt;
if (!dfs(S)) break;
++flow;
Ans+=Dst[T];
}
}
flow==n*m?printf("%d\n",Ans):puts("no solution");
return 0;
}
void Add_Edge(int u,int v,int flow,int w)
{
Nt[++ecnt]=Hd[u];
Hd[u]=ecnt;
E[ecnt]=((Edge) {
v,flow,w
});
Nt[++ecnt]=Hd[v];
Hd[v]=ecnt;
E[ecnt]=((Edge) {
u,0,-w
});
return;
}
void Build(int x,int l,int r,int k0,int k1)
{
for (int b=0; b<=1; b++) for (int i=1; i<=m; i++) Id[b][x][i]=++idcnt;
int fa=x>>1;
if (fa) for (int i=1; i<=m; i++) Add_Edge(Id[0][fa][i],Id[0][x][i],inf,k0),Add_Edge(Id[1][fa][i],Id[1][x][i],inf,k1);
if (l==r) {
Add_Edge(Id[0][x][m],Id[0][x][1],inf,1);
Add_Edge(Id[0][x][1],Id[0][x][m],inf,1);
Add_Edge(Id[1][x][m],Id[1][x][1],inf,1);
Add_Edge(Id[1][x][1],Id[1][x][m],inf,1);
for (int i=1; i<m; i++) {
Add_Edge(Id[0][x][i],Id[0][x][i+1],inf,1);
Add_Edge(Id[0][x][i+1],Id[0][x][i],inf,1);
Add_Edge(Id[1][x][i],Id[1][x][i+1],inf,1);
Add_Edge(Id[1][x][i+1],Id[1][x][i],inf,1);
}
for (int i=1; i<=m; i++) {
++idcnt;
Add_Edge(idcnt,T,1,0);
Add_Edge(Id[0][x][i],idcnt,1,0);
Add_Edge(Id[1][x][i],idcnt,1,0);
}
return;
}
int mid=(l+r)>>1;
Build(ls,l,mid,(r-mid)*2,0);
Build(rs,mid+1,r,0,(mid-l+1)*2);
return;
}
void Query(int x,int l,int r,int ql,int qr,int b,int j,int p)
{
if (l==ql&&r==qr) {
if (b==0) Add_Edge(idcnt,Id[b][x][j],1,(p-qr)*2);
else Add_Edge(idcnt,Id[b][x][j],1,(ql-p)*2);
return;
}
int mid=(l+r)>>1;
if (qr<=mid) Query(ls,l,mid,ql,qr,b,j,p);
else if (ql>=mid+1) Query(rs,mid+1,r,ql,qr,b,j,p);
else Query(ls,l,mid,ql,mid,b,j,p),Query(rs,mid+1,r,mid+1,qr,b,j,p);
return;
}
bool SPFA()
{
memset(Dst,63,sizeof(Dst));
memset(vis,0,sizeof(vis));
Dst[S]=0;
Qu.push(S);
vis[S]=1;
while (!Qu.empty()) {
int u=Qu.front();
Qu.pop();
for (int i=Hd[u]; i!=-1; i=Nt[i])
if (E[i].flow&&Dst[E[i].v]>Dst[u]+E[i].w) {
Dst[E[i].v]=Dst[u]+E[i].w;
if (!vis[E[i].v]) {
Qu.push(E[i].v);
vis[E[i].v]=1;
}
}
vis[u]=0;
}
return Dst[T]!=Dst[0];
}
int dfs(int u)
{
//cout<<"d at:"<<u<<endl;
if (u==T) return 1;
vis[u]=viscnt;
for (int i=Hd[u]; i!=-1; i=Nt[i])
if (E[i].flow&&Dst[E[i].v]==Dst[u]+E[i].w&&vis[E[i].v]!=viscnt)
if (dfs(E[i].v)) {
--E[i].flow;
++E[i^1].flow;
return 1;
}
return 0;
}
| 22.97973 | 118 | 0.52955 | SYCstudio |
949af51165013096dae010e9350c3e710ff3a5a9 | 4,859 | hpp | C++ | include/actionspace/GenericActionSpace.hpp | JHLee0513/libcozmo | f3a90a39ec1b1c4ead691328fd43459d67a3a44a | [
"BSD-3-Clause"
] | 8 | 2017-01-11T15:49:34.000Z | 2019-04-24T21:49:05.000Z | include/actionspace/GenericActionSpace.hpp | JHLee0513/libcozmo | f3a90a39ec1b1c4ead691328fd43459d67a3a44a | [
"BSD-3-Clause"
] | 6 | 2019-07-19T01:43:45.000Z | 2020-03-10T07:28:30.000Z | include/actionspace/GenericActionSpace.hpp | JHLee0513/libcozmo | f3a90a39ec1b1c4ead691328fd43459d67a3a44a | [
"BSD-3-Clause"
] | 4 | 2019-07-01T20:04:44.000Z | 2020-02-14T10:12:35.000Z | ////////////////////////////////////////////////////////////////////////////////
// Copyright (c) 2019, Brian Lee, Vinitha Ranganeni
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice
// this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// 3. Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
// POSSIBILITY OF SUCH DAMAGE.
////////////////////////////////////////////////////////////////////////////////
#ifndef INCLUDE_ACTIONSPACE_GENERICACTIONSPACE_HPP_
#define INCLUDE_ACTIONSPACE_GENERICACTIONSPACE_HPP_
#include <Eigen/Dense>
#include <vector>
#include <cmath>
#include "utils/utils.hpp"
#include "ActionSpace.hpp"
namespace libcozmo {
namespace actionspace {
/// Actions are applicable regardless of Cozmo's state in the world
///
/// Actions consist of speed, duration and heading
/// The total number of possible actions =
/// number of speeds * number of durations * number of headings
///
/// Headings are represented as angles from [0, 2pi]. The difference between
/// two headings is 2pi/number_of_headings.
class GenericActionSpace : public virtual ActionSpace {
public:
/// Generic Action class
class Action : public ActionSpace::Action {
public:
/// Constructor
/// \param speed The speed of action (mm/s)
/// \param duration The duration of action (s)
/// \param heading The heading of action (radians)
explicit Action(
const double& speed,
const double& duration,
const double& heading) : \
m_speed(speed),
m_duration(duration),
m_heading(heading) {}
/// Documentation inherited
/// The action vector is in the following format:
/// [speed, duration, heading]
Eigen::VectorXd vector() const override {
Eigen::VectorXd action_vector(3);
action_vector << m_speed, m_duration, m_heading;
return action_vector;
}
const double m_speed;
const double m_duration;
const double m_heading;
};
/// Constructs action space with given possible options for speed, duration
/// and heading
///
/// \param m_speeds Vector of available speeds
/// \param m_durations Vector of available durations
/// \param num heading Number of options for heading/direction (required:
/// power of 2 and >= 4)
GenericActionSpace(
const std::vector<double>& speeds,
const std::vector<double>& durations,
const int& num_headings);
~GenericActionSpace() {
for (int i = 0; i < m_actions.size(); ++i) {
delete(m_actions[i]);
}
m_actions.clear();
}
/// Calculates similarity between two actions
/// Similarity based on the Euclidean distance between the actions
///
/// \param action_id1, actionid2 IDs of actions to compare
/// \return similarity value
bool action_similarity(
const int& action_id1,
const int& action_id2,
double* similarity) const override;
/// Documentation inherited
ActionSpace::Action* get_action(const int& action_id) const override;
/// Documentation inherited
bool is_valid_action_id(const int& action_id) const override;
/// Documentation inherited
int size() const override;
private:
/// Vector of actions
std::vector<Action*> m_actions;
};
} /// namespace actionspace
} /// namespace libcozmo
#endif // INCLUDE_ACTIONSPACE_GENERICACTIONSPACE_HPP_
| 38.259843 | 80 | 0.667627 | JHLee0513 |
949e80287d10edfae7f97ba708cb98c80174dae8 | 3,996 | cpp | C++ | packages/core/src/Message.cpp | aaronchongth/soss_v2 | b531c2046e24684670a4a2ea2fd3c134fcba0591 | [
"Apache-2.0"
] | null | null | null | packages/core/src/Message.cpp | aaronchongth/soss_v2 | b531c2046e24684670a4a2ea2fd3c134fcba0591 | [
"Apache-2.0"
] | null | null | null | packages/core/src/Message.cpp | aaronchongth/soss_v2 | b531c2046e24684670a4a2ea2fd3c134fcba0591 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (C) 2018 Open Source Robotics Foundation
*
* 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 <soss/Message.hpp>
namespace soss {
//==============================================================================
class Field::Implementation
{
public:
Implementation()
: _type(nullptr),
_data(nullptr)
{
// Do nothing
}
Implementation(const Implementation& other)
{
*this = other;
}
Implementation& operator=(const Implementation& other)
{
_type = other._type;
_data = other.clone_data();
_copier = other._copier;
_deleter = other._deleter;
return *this;
}
void* clone_data() const
{
return _copier(_data);
}
void _set(const std::type_info& type, void* data,
std::function<void*(const void*)>&& copier,
std::function<void(void*)>&& deleter)
{
_type = &type;
_data = data;
_copier = copier;
_deleter = deleter;
}
void* _cast(const std::type_info& type) const
{
// This means we have an empty field
if(!_type)
return nullptr;
// TODO(MXG): If we ever need to support windows, we probably cannot rely
// on this check
if(*_type == type)
return _data;
// If the type check failed, then we should return a nullptr.
return nullptr;
}
std::string type() const
{
// TODO(MXG): Consider demangling this typename
if(_type)
return _type->name();
return "empty";
}
~Implementation()
{
if(_deleter && _data)
_deleter(_data);
}
private:
const std::type_info* _type;
void* _data;
std::function<void*(const void*)> _copier;
std::function<void(void*)> _deleter;
};
//==============================================================================
Field::Field()
: _pimpl(new Implementation)
{
// Do nothing
}
//==============================================================================
Field::Field(const Field& other)
: _pimpl(new Implementation(*other._pimpl))
{
// Do nothing
}
//==============================================================================
Field::Field(Field&& other)
: _pimpl(std::move(other._pimpl))
{
// Do nothing
}
//==============================================================================
Field& Field::operator=(const Field& other)
{
*_pimpl = *other._pimpl;
return *this;
}
//==============================================================================
Field& Field::operator=(Field&& other)
{
_pimpl = std::move(other._pimpl);
return *this;
}
//==============================================================================
std::string Field::type() const
{
return _pimpl->type();
}
//==============================================================================
Field::~Field()
{
// Do nothing
}
//==============================================================================
void Field::_set(const std::type_info& type, void* data,
std::function<void*(const void*)>&& copier,
std::function<void(void*)>&& deleter)
{
_pimpl->_set(type, data, std::move(copier), std::move(deleter));
}
//==============================================================================
void* Field::_cast(const std::type_info& type)
{
return _pimpl->_cast(type);
}
//==============================================================================
const void* Field::_cast(const std::type_info& type) const
{
return _pimpl->_cast(type);
}
} // namespace soss
| 23.368421 | 80 | 0.50025 | aaronchongth |
94a1db6e4818d6e6a01f0e19421d6f4601cf5dbe | 1,685 | cpp | C++ | sources/libcpp83gts_callback_and_action/ids_path_extensions.cpp | Savraska2/GTS | 78c8b4d634f1379eb3e33642716717f53bf7e1ad | [
"BSD-3-Clause"
] | 61 | 2016-03-26T03:04:43.000Z | 2021-09-17T02:11:18.000Z | sources/libcpp83gts_callback_and_action/ids_path_extensions.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 92 | 2016-04-10T23:40:22.000Z | 2022-03-11T21:49:12.000Z | sources/libcpp83gts_callback_and_action/ids_path_extensions.cpp | sahwar/GTS | b25734116ea81eb0d7e2eabc8ce16cdd1c8b22dd | [
"BSD-3-Clause"
] | 18 | 2016-03-26T11:19:14.000Z | 2021-08-07T00:26:02.000Z | #include <algorithm> // std::find(-)
#include "ids_path_extensions.h"
ids::path::extensions::extensions()
{}
const std::string ids::path::extensions::str_from_num( const int num )
{
if (static_cast<int>(this->dotex_.size()) <= num) {
return std::string();
}
return this->dotex_.at(num);
}
const int ids::path::extensions::num_from_str( const std::string& ext )
{
auto it = std::find(this->dotex_.begin() ,this->dotex_.end() ,ext);
if ( it == this->dotex_.end() ) {
return -1;
}
return static_cast<int>(std::distance(this->dotex_.begin(), it));
}
void ids::path::extensions::set_filter(
const std::string& name ,const std::string& dotex
)
{
this->names_.push_back( name );
this->dotex_.push_back( dotex );
}
const std::string ids::path::extensions::get_native_filters( void )
{
std::string str;
/* Exsamples
"Text\t*.txt\n"
"C Files\t*.{cxx,h,c}"
*/
for (int ii=0 ;ii<static_cast<int>(this->dotex_.size()) ;++ii) {
str += this->names_.at(ii);
str += "\t*";
str += this->dotex_.at(ii);
str += "\n";
}
/* 拡張子が2個以上のときは全部をまとめたFilterも追加しとく */
if (2 <= this->dotex_.size()) {
str += "Image Files\t*.{";
for(int ii=0;ii<static_cast<int>(this->dotex_.size());++ii){
if (0 < ii) {
str += ',';
}
if (this->dotex_.at(ii).at(0) == '.') {
str += this->dotex_.at(ii).substr(1);
}
else {
str += this->dotex_.at(ii);
}
}
str += "}";
}
return str;
}
const std::string ids::path::extensions::get_fltk_filter( const int num )
{
std::string str;
if (num < 0 || static_cast<int>(this->dotex_.size()) <= num) {
return str;
}
str += this->names_.at(num);
str += "(*";
str += this->dotex_.at(num);
str += ")";
return str;
}
| 23.082192 | 73 | 0.602967 | Savraska2 |
94a8b8a92fcc0e019fa0542a7c72c3d5049cb0ab | 5,761 | hpp | C++ | SDK/ARKSurvivalEvolved_Buff_SpaceWhaleTeleport_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 10 | 2020-02-17T19:08:46.000Z | 2021-07-31T11:07:19.000Z | SDK/ARKSurvivalEvolved_Buff_SpaceWhaleTeleport_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 9 | 2020-02-17T18:15:41.000Z | 2021-06-06T19:17:34.000Z | SDK/ARKSurvivalEvolved_Buff_SpaceWhaleTeleport_parameters.hpp | 2bite/ARK-SDK | c38ca9925309516b2093ad8c3a70ed9489e1d573 | [
"MIT"
] | 3 | 2020-07-22T17:42:07.000Z | 2021-06-19T17:16:13.000Z | #pragma once
// ARKSurvivalEvolved (329.9) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
#include "ARKSurvivalEvolved_Buff_SpaceWhaleTeleport_classes.hpp"
namespace sdk
{
//---------------------------------------------------------------------------
//Parameters
//---------------------------------------------------------------------------
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BPDeactivated
struct ABuff_SpaceWhaleTeleport_C_BPDeactivated_Params
{
class AActor** ForInstigator; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.ReceiveDestroyed
struct ABuff_SpaceWhaleTeleport_C_ReceiveDestroyed_Params
{
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BuffTickClient
struct ABuff_SpaceWhaleTeleport_C_BuffTickClient_Params
{
float* DeltaTime; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BPSetupForInstigator
struct ABuff_SpaceWhaleTeleport_C_BPSetupForInstigator_Params
{
class AActor** ForInstigator; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BPCustomAllowAddBuff
struct ABuff_SpaceWhaleTeleport_C_BPCustomAllowAddBuff_Params
{
class APrimalCharacter** forCharacter; // (Parm, ZeroConstructor, IsPlainOldData)
class AActor** DamageCauser; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BPPreventInstigatorMovementMode
struct ABuff_SpaceWhaleTeleport_C_BPPreventInstigatorMovementMode_Params
{
TEnumAsByte<EMovementMode>* NewMovementMode; // (Parm, ZeroConstructor, IsPlainOldData)
unsigned char* NewCustomMode; // (Parm, ZeroConstructor, IsPlainOldData)
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BPOnOwnerMassTeleportEvent
struct ABuff_SpaceWhaleTeleport_C_BPOnOwnerMassTeleportEvent_Params
{
TEnumAsByte<EMassTeleportState>* EventState; // (Parm, ZeroConstructor, IsPlainOldData)
class APrimalCharacter** TeleportInitiatedByChar; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.UserConstructionScript
struct ABuff_SpaceWhaleTeleport_C_UserConstructionScript_Params
{
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.MultiHyperdriveEffect
struct ABuff_SpaceWhaleTeleport_C_MultiHyperdriveEffect_Params
{
class USceneComponent* MeshComp; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector Start; // (Parm, ZeroConstructor, IsPlainOldData)
struct FVector End; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.OnMassTeleportTriggered
struct ABuff_SpaceWhaleTeleport_C_OnMassTeleportTriggered_Params
{
bool Success; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.OnMassTeleportStarted
struct ABuff_SpaceWhaleTeleport_C_OnMassTeleportStarted_Params
{
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.OnMassTeleportCompleted
struct ABuff_SpaceWhaleTeleport_C_OnMassTeleportCompleted_Params
{
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.BPActivated
struct ABuff_SpaceWhaleTeleport_C_BPActivated_Params
{
class AActor** ForInstigator; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.ReceiveBeginPlay
struct ABuff_SpaceWhaleTeleport_C_ReceiveBeginPlay_Params
{
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.SyncMovementMode
struct ABuff_SpaceWhaleTeleport_C_SyncMovementMode_Params
{
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.HideMesh
struct ABuff_SpaceWhaleTeleport_C_HideMesh_Params
{
bool Hide; // (Parm, ZeroConstructor, IsPlainOldData)
};
// Function Buff_SpaceWhaleTeleport.Buff_SpaceWhaleTeleport_C.ExecuteUbergraph_Buff_SpaceWhaleTeleport
struct ABuff_SpaceWhaleTeleport_C_ExecuteUbergraph_Buff_SpaceWhaleTeleport_Params
{
int EntryPoint; // (Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| 46.088 | 173 | 0.614129 | 2bite |
94b120717a100a66cda7b81fed4a8f978f5480f0 | 7,431 | cpp | C++ | Birdee/Intrinsics.cpp | chaofanli/Birdee2 | 32671ca7c30662599266a578f4dd5169d0677bf4 | [
"Apache-2.0"
] | 1 | 2019-07-23T07:33:09.000Z | 2019-07-23T07:33:09.000Z | Birdee/Intrinsics.cpp | chaofanli/Birdee2 | 32671ca7c30662599266a578f4dd5169d0677bf4 | [
"Apache-2.0"
] | null | null | null | Birdee/Intrinsics.cpp | chaofanli/Birdee2 | 32671ca7c30662599266a578f4dd5169d0677bf4 | [
"Apache-2.0"
] | null | null | null | #include "BdAST.h"
#include "CompileError.h"
#include "llvm/IR/IRBuilder.h"
extern llvm::IRBuilder<> builder;
#define CompileAssert(a, p ,msg)\
do\
{\
if (!(a))\
{\
throw CompileError(p, msg);\
}\
}while(0)\
namespace Birdee
{
extern llvm::Type* GetLLVMTypeFromResolvedType(const ResolvedType& ty);
extern int GetLLVMTypeSizeInBit(llvm::Type* ty);
static void CheckIntrinsic(FunctionAST* func, int arg_num, int targ_num)
{
CompileAssert(func->isTemplateInstance, func->Pos, "The intrinsic function should be a template instance");
CompileAssert(func->Proto->resolved_args.size() == arg_num, func->Pos, "Wrong number of parameters for the intrinsic function");
CompileAssert(func->template_instance_args->size() == targ_num, func->Pos, "Wrong number of template parameters for the intrinsic function");
}
static void Intrinsic_UnsafePtrCast_Phase1(FunctionAST* func)
{
CheckIntrinsic(func, 1, 2);
auto& targs = *func->template_instance_args;
CompileAssert(targs[0].kind == TemplateArgument::TEMPLATE_ARG_TYPE &&
(targs[0].type.isReference() || targs[0].type.type == tok_pointer || targs[0].type.isInteger()), //no need to check index level. it is implied in isReference()
func->Pos, "The 1st template argument for unsafe.ptr_cast should be a pointer, reference or integer");
CompileAssert(targs[1].kind == TemplateArgument::TEMPLATE_ARG_TYPE &&
(targs[1].type.isReference() || targs[1].type.type == tok_pointer || targs[1].type.isInteger()), //no need to check index level. it is implied in isReference()
func->Pos, "The 2nd template argument for unsafe.ptr_cast should be a pointer, reference or integer");
}
static void Intrinsic_UnsafePtrLoad_Phase1(FunctionAST* func)
{
CheckIntrinsic(func, 1, 1);
auto& targs = *func->template_instance_args;
CompileAssert(targs[0].kind == TemplateArgument::TEMPLATE_ARG_TYPE,
func->Pos, "The 1st template argument for unsafe.ptr_load should be a type");
auto& arg_t = func->Proto->resolved_args[0]->resolved_type;
CompileAssert(arg_t.type == tok_pointer || arg_t.index_level == 0,
func->Pos, "The parameter for unsafe.ptr_load should be a pointer");
}
static llvm::Value* Intrinsic_UnsafePtrCast_Generate(FunctionAST* func, llvm::Value* obj, vector<unique_ptr<ExprAST>>& args)
{
assert(func->template_instance_args);
assert(func->template_instance_args->size() == 2);
assert(args.size() == 1);
auto& targs = *func->template_instance_args;
auto v = args[0]->Generate();
auto ty = GetLLVMTypeFromResolvedType(targs[0].type);
if (targs[1].type.isInteger())
{
//targs[0] is target type
//targs[1] is source type
if (targs[0].type.isInteger())
{
//if both src and dest are integer, generate int cast
//extension rule is based on whether src is signed
return builder.CreateIntCast(v, ty, targs[1].type.isSigned());
}
return builder.CreateIntToPtr(v, ty);
}
return builder.CreatePointerCast(v, ty);
}
static llvm::Value* Intrinsic_UnsafePtrLoad_Generate(FunctionAST* func, llvm::Value* obj, vector<unique_ptr<ExprAST>>& args)
{
assert(func->template_instance_args);
assert(func->template_instance_args->size() == 1);
assert(args.size() == 1);
auto& targs = *func->template_instance_args;
auto v = args[0]->Generate();
auto ty = GetLLVMTypeFromResolvedType(targs[0].type);
auto ptr = builder.CreatePointerCast(v, ty->getPointerTo());
return builder.CreateLoad(ptr);
}
static void Intrinsic_UnsafePtrStore_Phase1(FunctionAST* func)
{
CheckIntrinsic(func, 2, 1);
auto& targs = *func->template_instance_args;
CompileAssert(targs[0].kind == TemplateArgument::TEMPLATE_ARG_TYPE,
func->Pos, "The 1st template argument for unsafe.ptr_store should be a type");
auto& arg_t = func->Proto->resolved_args[0]->resolved_type;
CompileAssert(arg_t.type == tok_pointer || arg_t.index_level == 0,
func->Pos, "The parameter for unsafe.ptr_store should be a pointer");
}
static llvm::Value* Intrinsic_UnsafePtrStore_Generate(FunctionAST* func, llvm::Value* obj, vector<unique_ptr<ExprAST>>& args)
{
assert(func->template_instance_args);
assert(func->template_instance_args->size() == 1);
assert(args.size() == 2);
auto& targs = *func->template_instance_args;
auto v = args[0]->Generate();
auto ty = GetLLVMTypeFromResolvedType(targs[0].type);
auto ptr = builder.CreatePointerCast(v, ty->getPointerTo());
auto v2 = args[1]->Generate();
return builder.CreateStore(v2, ptr);
}
static void Intrinsic_UnsafeBitCast_Phase1(FunctionAST* func)
{
CheckIntrinsic(func, 1, 2);
auto& targs = *func->template_instance_args;
CompileAssert(targs[0].kind == TemplateArgument::TEMPLATE_ARG_TYPE && targs[1].kind == TemplateArgument::TEMPLATE_ARG_TYPE,
func->Pos, "The 1st and 2nd template arguments for unsafe.bit_cast should be a type");
}
static llvm::Value* Intrinsic_UnsafeBitCast_Generate(FunctionAST* func, llvm::Value* obj, vector<unique_ptr<ExprAST>>& args)
{
assert(func->template_instance_args);
assert(func->template_instance_args->size() == 2);
assert(args.size() == 1);
auto& targs = *func->template_instance_args;
auto v = args[0]->Generate();
auto ty = GetLLVMTypeFromResolvedType(targs[0].type);
auto srcty = GetLLVMTypeFromResolvedType(targs[1].type);
CompileAssert(GetLLVMTypeSizeInBit(ty) == GetLLVMTypeSizeInBit(srcty), func->Pos,
string("Cannot bitcast from type ") + targs[1].type.GetString() + " to type " + targs[0].type.GetString() + ", because they have different sizes");
return builder.CreateBitOrPointerCast(v, ty);
}
static IntrisicFunction unsafe_bit_cast = { Intrinsic_UnsafeBitCast_Generate , Intrinsic_UnsafeBitCast_Phase1 };
static IntrisicFunction unsafe_ptr_cast = { Intrinsic_UnsafePtrCast_Generate , Intrinsic_UnsafePtrCast_Phase1 };
static IntrisicFunction unsafe_ptr_load = { Intrinsic_UnsafePtrLoad_Generate , Intrinsic_UnsafePtrLoad_Phase1 };
static IntrisicFunction unsafe_ptr_store = { Intrinsic_UnsafePtrStore_Generate , Intrinsic_UnsafePtrStore_Phase1 };
static unordered_map<string, unordered_map<string, IntrisicFunction*>> intrinsic_module_names = {
{"unsafe",{
{"ptr_cast",&unsafe_ptr_cast},
{"ptr_load",&unsafe_ptr_load},
{"ptr_store",&unsafe_ptr_store},
{"bit_cast",&unsafe_bit_cast},
}
},
};
bool IsIntrinsicModule(const string& name)
{
return intrinsic_module_names.find(name) != intrinsic_module_names.end();
}
IntrisicFunction* FindIntrinsic(FunctionAST* func)
{
bool _is_intrinsic;
unordered_map<string, unordered_map<string, IntrisicFunction*>>::iterator itr1;
if (func->Proto->prefix_idx == -1)
{
_is_intrinsic = cu.is_intrinsic;
//in most cases, modules are not intrinsic. We can save a map finding here.
if (_is_intrinsic)
itr1 = intrinsic_module_names.find(cu.symbol_prefix.substr(0, cu.symbol_prefix.length() - 1)); //symbol_prefix has a "." at the end
}
else
{
itr1 = intrinsic_module_names.find(cu.imported_module_names[func->Proto->prefix_idx]);
_is_intrinsic = itr1 != intrinsic_module_names.end();
}
if (_is_intrinsic)
{
unordered_map<string, IntrisicFunction*>::iterator itr2;
auto fpos = func->Proto->Name.find('[');
if (fpos != string::npos)
itr2 = itr1->second.find(func->Proto->Name.substr(0, fpos));
else
itr2 = itr1->second.find(func->Proto->Name);
if (itr2 != itr1->second.end())
{
return itr2->second;
}
}
return nullptr;
}
}
| 40.167568 | 162 | 0.729377 | chaofanli |
94b2493044dacddad37da50d78af77e91200b7a9 | 5,936 | cpp | C++ | src/util.cpp | victorvieirar/Empiric-Analysis | 63c7d3a395bbd4d2c0b870a3d291d021c75ed53b | [
"MIT"
] | null | null | null | src/util.cpp | victorvieirar/Empiric-Analysis | 63c7d3a395bbd4d2c0b870a3d291d021c75ed53b | [
"MIT"
] | null | null | null | src/util.cpp | victorvieirar/Empiric-Analysis | 63c7d3a395bbd4d2c0b870a3d291d021c75ed53b | [
"MIT"
] | null | null | null | #include "../include/util.h"
namespace util {
typedef int IterativeFunction(long int vector[], int last, long int value);
typedef int RecursiveFunction(long int vector[], int first, int last, long int value);
void writeHeader() {
std::ofstream records("data/tempos.txt", std::ios::in | std::ios::out | std::ios::trunc);
std::string headerItems[] = {"# N", "ILS", "IBS", "ITS", "IJS", "IFS", "RBS", "RTS"};
std::stringstream header;
for(const auto &s : headerItems) {
header << s;
header << std::setfill(' ') << std::setw(15 - s.size()) << "";
}
records << header.str() << std::endl;
}
void writeAmount(int minSize, int maxSize, int samplesAmount) {
std::ofstream records("data/tempos.txt", std::ios::in | std::ios::out | std::ios::binary);
float step = (maxSize - minSize)/(samplesAmount - 1);
float currentSize = minSize;
int lineCount = 0;
while((int) currentSize <= maxSize) {
if(records.is_open()) {
int lineJump = (lineCount+1) * 121;
std::stringstream value;
std::stringstream line;
records.seekp(lineJump, std::ios::beg);
value << std::setprecision(std::numeric_limits<double>::max_digits10) << currentSize;
line << value.str() << std::setfill(' ') << std::setw(15 - value.str().size()) << "" << std::endl;
records.write(line.str().c_str(), line.str().size());
} else {
std::cout << "Falha ao abrir arquivo" << std::endl;
}
currentSize += step;
lineCount++;
}
}
void writeInFile(int algorithmIndex, std::string value, int lineCount) {
std::ofstream records("data/tempos.txt", std::ios::in | std::ios::out | std::ios::binary);
if(records.is_open()) {
std::stringstream line;
int lineJump = (lineCount+1) * 121;
int tab = 15 * (algorithmIndex+1);
records.seekp(lineJump+tab, std::ios::beg);
line << value;
line << std::setfill(' ') << std::setw(15 - line.str().size()) << std::endl;
records.write(line.str().c_str(), line.str().size());
} else {
std::cout << "Falha ao abrir arquivo" << std::endl;
}
}
void writeBlank(int algorithmIndex, int minSize, int maxSize, int samplesAmount) {
std::ofstream records("data/tempos.txt", std::ios::in | std::ios::out | std::ios::binary);
float step = (maxSize - minSize)/(samplesAmount - 1);
float currentSize = minSize;
int lineCount = 0;
while((int) currentSize <= maxSize) {
if(records.is_open()) {
int lineJump = (lineCount+1) * 121;
int tab = 15 * (algorithmIndex+1);
records.seekp(lineJump+tab, std::ios::beg);
std::stringstream line;
line << std::setfill(' ') << std::setw(15) << "" << std::endl;
records.write(line.str().c_str(), line.str().size());
} else {
std::cout << "Falha ao abrir arquivo" << std::endl;
}
currentSize += step;
lineCount++;
}
}
void callbackFunction(long int *A, IterativeFunction *function, int minSize, int maxSize, int samplesAmount, int testsAmount, int algorithmIndex) {
float step = (maxSize - minSize)/(samplesAmount - 1);
float currentSize = minSize;
double avg = 0;
int line = 0;
while((int) currentSize <= maxSize) {
for(int i = 0; i < testsAmount; i++) {
auto start = std::chrono::high_resolution_clock::now();
(*function)(A, ((int) currentSize) - 1, maxSize);
auto end = std::chrono::high_resolution_clock::now();
double duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
double prevAvg = avg;
avg = prevAvg + (duration - prevAvg) / (i + 1);
}
avg *= 1e-6;
std::stringstream value;
std::stringstream number;
number << std::fixed << std::setprecision(6) << avg;
value << number.str() << std::setfill(' ') << std::setw(15 - number.str().size()) << "";
writeInFile(algorithmIndex, value.str(), line);
currentSize += step;
line++;
}
}
void callbackFunction(long int *A, RecursiveFunction *function, int minSize, int maxSize, int samplesAmount, int testsAmount, int algorithmIndex) {
float step = (maxSize - minSize)/(samplesAmount - 1);
float currentSize = minSize;
double avg = 0;
int line = 0;
while((int) currentSize <= maxSize) {
for(int i = 0; i < testsAmount; i++) {
auto start = std::chrono::high_resolution_clock::now();
(*function)(A, ((int) currentSize) - 1, maxSize, 0);
auto end = std::chrono::high_resolution_clock::now();
double duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end - start).count();
double prevAvg = avg;
avg = prevAvg + (duration - prevAvg) / (i + 1);
}
avg *= 1e-6;
std::stringstream value;
std::stringstream number;
number << std::fixed << std::setprecision(6) << avg;
value << number.str() << std::setfill(' ') << std::setw(15 - number.str().size()) << "";
writeInFile(algorithmIndex, value.str(), line);
currentSize += step;
line++;
}
}
} | 38.545455 | 151 | 0.511119 | victorvieirar |
94b3960eb157d1d65d5c5cf29bb647f6ae9a5c85 | 1,874 | hpp | C++ | h2g_polygon.stratis/Rsc/Titles.hpp | Spayker/b2g-game-connector | f808fa6a67366952a483201507b955ca34b6580c | [
"MIT"
] | null | null | null | h2g_polygon.stratis/Rsc/Titles.hpp | Spayker/b2g-game-connector | f808fa6a67366952a483201507b955ca34b6580c | [
"MIT"
] | 24 | 2021-12-06T17:41:08.000Z | 2021-12-19T15:21:23.000Z | h2g_polygon.stratis/Rsc/Titles.hpp | Spayker/b2g-game-connector | f808fa6a67366952a483201507b955ca34b6580c | [
"MIT"
] | null | null | null | /* Titles */
#define usflag "\ca\ca_e\data\flag_us_co.paa"
#define ruflag "\ca\data\flag_rus_co.paa"
#ifndef usflag
#define usflag "\ca\ca_e\data\flag_us_co.paa"
#define ruflag "\ca\ca_e\data\flag_tkg_co.paa"
#endif
#define height (safeZoneH * 0.05)
#define width (height * 4)
#define startX (safeZoneX + safeZoneW - height)
#define startY (safeZoneY + safeZoneH - height)
class RscTitles {
titles[] = {RscOverlay};
class RscOverlay
{
idd=10200;
movingEnable = 0;
duration=15000;
name="gps";
controls[]={"txt_dwn","txt_crw","OptionsIcon0","OptionsIcon1","OptionsIcon2","OptionsIcon3","OptionsIcon4","OptionsIcon5","OptionsIcon6"};
onload="uiNamespace setVariable['GUI',_this select 0];";
class txt_dwn:RscStructuredTextB
{
idc=6003;
w=0.275;
h=0.036;
x = 0.824 * safezoneW + safezoneX;
y = 0.790000 * safezoneH + safezoneY;
colorText[]={0.95,0.95,0.95,1};
};
class txt_crw:txt_dwn
{
idc=6004;
w=0.25;
h=0.55;
colorBackground[]={0,0,0,0};
};
class OptionsImageAspectRatio: RscPicture
{
w = 0.078431;
h = 0.104575;
style = "0x30+0x800";
};
class OptionsIcon0: OptionsImageAspectRatio
{
IDC = 6005;
x = "(SafeZoneW + SafeZoneX) - (0.0392157)";
y = 0.3;
w = 0.039216;
h = 0.052288;
colortext[] = {1, 1, 1, 0.400000};
text = "";
};
class OptionsIcon1: OptionsIcon0
{
IDC = 6006;
y = "0.3+(0.0522876*1)";
};
class OptionsIcon2: OptionsIcon0
{
IDC = 6007;
y = "0.3+(0.0522876*2)";
};
class OptionsIcon3: OptionsIcon0
{
IDC = 6008;
y = "0.3+(0.0522876*3)";
};
class OptionsIcon4: OptionsIcon0
{
IDC = 6009;
y = "0.3+(0.0522876*4)";
};
class OptionsIcon5: OptionsIcon0
{
IDC = 6010;
y = "0.3+(0.0522876*5)";
};
class OptionsIcon6: OptionsIcon0
{
IDC = 6011;
y = "0.3+(0.0522876*6)";
};
};
}; | 18.74 | 140 | 0.613661 | Spayker |
94b9247190719d92f3edd4231389f8b20f784fb6 | 44 | cc | C++ | demo.cc | r-lyeh-archived/eval | 6094410ba54c565d01487be88d1bf0da3ba380a9 | [
"MIT"
] | 4 | 2018-02-26T01:29:56.000Z | 2021-09-27T02:47:19.000Z | demo.cc | r-lyeh-archived/eval | 6094410ba54c565d01487be88d1bf0da3ba380a9 | [
"MIT"
] | null | null | null | demo.cc | r-lyeh-archived/eval | 6094410ba54c565d01487be88d1bf0da3ba380a9 | [
"MIT"
] | 1 | 2015-09-30T08:13:37.000Z | 2015-09-30T08:13:37.000Z | #define EVAL_BUILD_DEMO
#include "eval.cpp"
| 14.666667 | 23 | 0.795455 | r-lyeh-archived |
94bccf9761d45abd9b37a37a8287da25a81fb73f | 526 | hpp | C++ | include/bluegrass/cturtle/test.hpp | larryk85/cturtle | 93db59b7352995d11b36d53abc3b7c0180f1ed33 | [
"MIT"
] | 1 | 2020-10-16T19:09:55.000Z | 2020-10-16T19:09:55.000Z | include/bluegrass/cturtle/test.hpp | larryk85/cturtle | 93db59b7352995d11b36d53abc3b7c0180f1ed33 | [
"MIT"
] | null | null | null | include/bluegrass/cturtle/test.hpp | larryk85/cturtle | 93db59b7352995d11b36d53abc3b7c0180f1ed33 | [
"MIT"
] | null | null | null | #pragma once
#include "errors.hpp"
#include "log.hpp"
#include <stdexcept>
namespace bluegrass::cturtle {
template <typename... Ts>
inline void test(bool pred, error err, detail::string_view_wrapper err_msg, Ts&&... ts) {
if (!UNLIKELY(pred)) {
error_log(err_msg.info, err_msg.value, std::forward<Ts>(ts)...);
throw runtime_error(err);
}
}
inline void test(bool pred, error err, call_info ci={}) {
test(pred, err, {"assertion failure", ci});
}
} // ns bluegrass::cturtle
| 25.047619 | 92 | 0.63308 | larryk85 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.