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
108
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
67k
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
ffc33ffe362865453ca5d4e153cd433cf9efa726
10,393
cpp
C++
Alien Engine/Alien Engine/ComponentCollider.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
7
2020-02-20T15:11:11.000Z
2020-05-19T00:29:04.000Z
Alien Engine/Alien Engine/ComponentCollider.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
125
2020-02-29T17:17:31.000Z
2020-05-06T19:50:01.000Z
Alien Engine/Alien Engine/ComponentCollider.cpp
OverPowered-Team/Alien-GameEngine
713a8846a95fdf253d0869bdcad4ecd006b2e166
[ "MIT" ]
1
2020-05-19T00:29:06.000Z
2020-05-19T00:29:06.000Z
#include "Globals.h" #include "Application.h" #include "ModuleRenderer3D.h" #include "ComponentCollider.h" #include "ComponentTransform.h" #include "ComponentRigidBody.h" #include "ComponentPhysics.h" #include "ComponentMesh.h" #include "GameObject.h" #include "ReturnZ.h" #include "Time.h" #include "Event.h" #include "Gizmos.h" #include "Physics.h" ComponentCollider::ComponentCollider(GameObject* go ) : ComponentBasePhysic(go) { // Default values center = float3::zero(); rotation = float3::zero(); material = App->physx->CreateMaterial(); InitMaterial(); #ifndef GAME_VERSION App->objects->debug_draw_list.emplace(this, std::bind(&ComponentCollider::DrawScene, this)); #endif // !GAME_VERSION } ComponentCollider::~ComponentCollider() { if (!IsController()) { go->SendAlientEventThis(this, AlienEventType::COLLIDER_DELETED); shape->release(); shape = nullptr; } material->release(); material = nullptr; #ifndef GAME_VERSION App->objects->debug_draw_list.erase(App->objects->debug_draw_list.find(this)); #endif // !GAME_VERSION } // Colliders Functions -------------------------------- void ComponentCollider::SetCenter(const float3& value) { center = value; if (IsController()) return; PxTransform trans = shape->getLocalPose(); trans.p = F3_TO_PXVEC3(center.Mul(physics->scale)); BeginUpdateShape(); shape->setLocalPose(trans); EndUpdateShape(); } void ComponentCollider::SetRotation(const float3& value) { rotation = value; if (IsController()) return; PxTransform trans = shape->getLocalPose(); float3 rad_rotation = DEGTORAD * rotation; trans.q = QUAT_TO_PXQUAT(Quat::FromEulerXYZ(rad_rotation.x, rad_rotation.y, rad_rotation.z)); BeginUpdateShape(); shape->setLocalPose(trans); EndUpdateShape(); } void ComponentCollider::SetIsTrigger(bool value) { is_trigger = value; if (IsController()) return; BeginUpdateShape(); if (is_trigger) { shape->setFlag(physx::PxShapeFlag::Enum::eSIMULATION_SHAPE, false); shape->setFlag(physx::PxShapeFlag::Enum::eTRIGGER_SHAPE, true); } else { shape->setFlag(physx::PxShapeFlag::Enum::eTRIGGER_SHAPE, false); shape->setFlag(physx::PxShapeFlag::Enum::eSIMULATION_SHAPE, true); } EndUpdateShape(); } void ComponentCollider::SetBouncing(const float value) { bouncing = value; bouncing = Clamp<float>(bouncing, 0.f, 1.f); material->setRestitution(bouncing); } void ComponentCollider::SetStaticFriction(const float value) { static_friction = value; static_friction = Clamp<float>(static_friction, 0.f, PX_MAX_F32); material->setStaticFriction(static_friction); } void ComponentCollider::SetDynamicFriction(const float value) { dynamic_friction = value; dynamic_friction = Clamp<float>(dynamic_friction, 0.f, PX_MAX_F32); material->setDynamicFriction(dynamic_friction); } void ComponentCollider::SetFrictionCombineMode(CombineMode mode) { friction_combine = mode; material->setFrictionCombineMode((PxCombineMode::Enum)(int)friction_combine); } void ComponentCollider::SetBouncingCombineMode(CombineMode mode) { bouncing_combine = mode; material->setRestitutionCombineMode((PxCombineMode::Enum)(int)bouncing_combine); } void ComponentCollider::SetCollisionLayer(std::string layer) { int index = 0; if (!physics->layers->GetIndexByName(layer, index)) return; layer_num = index; layer_name = layer; BeginUpdateShape(); PxFilterData filter_data; filter_data.word0 = index; filter_data.word1 = physics->ID; shape->setSimulationFilterData(filter_data); shape->setQueryFilterData(filter_data); EndUpdateShape(); physics->ChangedFilters(); } std::string ComponentCollider::GetCollisionLayer() { return layer_name; } void ComponentCollider::SaveComponent(JSONArraypack* to_save) { to_save->SetBoolean("Enabled", enabled); to_save->SetNumber("Type", (int)type); to_save->SetFloat3("Center", center); to_save->SetFloat3("Rotation", rotation); to_save->SetBoolean("IsTrigger", is_trigger); to_save->SetNumber("Bouncing", bouncing); to_save->SetNumber("StaticFriction", static_friction); to_save->SetNumber("DynamicFriction", dynamic_friction); to_save->SetString("CollisionLayer", layer_name.c_str()); } void ComponentCollider::LoadComponent(JSONArraypack* to_load) { enabled = to_load->GetBoolean("Enabled"); if (enabled == false) { OnDisable(); } BeginUpdateShape(true); SetCenter(to_load->GetFloat3("Center")); SetRotation(to_load->GetFloat3("Rotation")); SetIsTrigger(to_load->GetBoolean("IsTrigger")); SetBouncing(to_load->GetNumber("Bouncing")); SetStaticFriction(to_load->GetNumber("StaticFriction")); SetDynamicFriction(to_load->GetNumber("DynamicFriction")); SetCollisionLayer(to_load->GetString("CollisionLayer", "Default")); EndUpdateShape(true); } void ComponentCollider::OnEnable() { physics->AttachCollider(this); } void ComponentCollider::OnDisable() { physics->DettachCollider(this); } void ComponentCollider::DrawScene() { if (enabled && go->IsEnabled() && (go->IsSelected() || App->physx->debug_physics)) { App->physx->DrawCollider(this); } } void ComponentCollider::Reset() { BeginUpdateShape(true); SetCenter(float3::zero()); SetRotation(float3::zero()); SetIsTrigger(false); SetBouncing(0.1f); SetStaticFriction(0.5f); SetDynamicFriction(0.1f); EndUpdateShape(true); } bool ComponentCollider::DrawInspector() { static bool check; check = enabled; ImGui::PushID(this); if (ImGui::Checkbox("##CmpActive", &check)) { enabled = check; if (!enabled) OnDisable(); else OnEnable(); } ImGui::SameLine(); if (ImGui::CollapsingHeader(name.c_str(), &not_destroy)) { ImGui::Spacing(); ImGui::SetCursorPosX(12.0f); ImGui::Title(""); if (ImGui::Button("Fit Collider")) { Reset(); } DrawLayersCombo(); float3 current_center = center; float3 current_rotation = rotation; bool current_is_trigger = is_trigger; float current_bouncing = bouncing; float current_static_friction = static_friction; float current_dynamic_friction = dynamic_friction; CombineMode current_f_mode = friction_combine; CombineMode current_b_mode = bouncing_combine; ImGui::Title("Center", 1); if (ImGui::DragFloat3("##center", current_center.ptr(), 0.05f)) { SetCenter(current_center); } ImGui::Title("Rotation", 1); if (ImGui::DragFloat3("##rotation", current_rotation.ptr(), 0.2f)) { SetRotation(current_rotation); } DrawSpecificInspector(); ImGui::Spacing(); ImGui::Spacing(); ImGui::Title("Is Trigger", 1); if (ImGui::Checkbox("##is_trigger", &current_is_trigger)) { SetIsTrigger(current_is_trigger); } ImGui::Spacing(); ImGui::Title("Physic Material", 1); ImGui::Text(""); ImGui::Spacing(); ImGui::Spacing(); ImGui::Title("Bouncing", 2); if (ImGui::DragFloat("##bouncing", &current_bouncing, 0.01f, 0.00f, 1.f)) { SetBouncing(current_bouncing); } ImGui::Title("Static Fric.", 2); if (ImGui::DragFloat("##static_friction", &current_static_friction, 0.01f, 0.00f, FLT_MAX)) { SetStaticFriction(current_static_friction); } ImGui::Title("Dynamic Fric.", 2); if (ImGui::DragFloat("##dynamic_friction", &current_dynamic_friction, 0.01f, 0.00f, FLT_MAX)) { SetDynamicFriction(current_dynamic_friction); } DrawCombineModeCombo(current_f_mode, 0); DrawCombineModeCombo(current_b_mode, 1); ImGui::Spacing(); } ImGui::PopID(); return true; } void ComponentCollider::DrawLayersCombo() { ImGui::Title("Layer"); if (ImGui::BeginComboEx(std::string("##layers").c_str(), std::string(" " + physics->layers->names[layer_num]).c_str(), 200, ImGuiComboFlags_NoArrowButton)) { for (int n = 0; n < physics->layers->names.size(); ++n) { bool is_selected = (layer_num == n); if (ImGui::Selectable(std::string(" " + physics->layers->names[n]).c_str(), is_selected)) { SetCollisionLayer(physics->layers->names[n]); } if (is_selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } } void ComponentCollider::DrawCombineModeCombo(CombineMode& current_mode, int mode) { const char* name = (mode == 0) ? "Friction Combine" : "Bouncing Combine"; ImGui::PushID(name); ImGui::Title(name, 2); if (ImGui::BeginComboEx(std::string("##" + std::string(name)).c_str(), (std::string(" ") + mode_names[(int)current_mode]).c_str(), 200, ImGuiComboFlags_NoArrowButton)) { for (int n = 0; n < (int)CombineMode::Unknown; ++n) { bool is_selected = ((int)current_mode == n); if (ImGui::Selectable((std::string(" ") + mode_names[n]).c_str(), is_selected)) { if (mode == 0) SetFrictionCombineMode((CombineMode)n); else SetBouncingCombineMode((CombineMode)n); } if (is_selected) ImGui::SetItemDefaultFocus(); } ImGui::EndCombo(); } ImGui::PopID(); } void ComponentCollider::HandleAlienEvent(const AlienEvent& e) { switch (e.type) { case AlienEventType::PHYSICS_SCALE_CHANGED: { ScaleChanged(); break; } case AlienEventType::COLLISION_LAYER_STATE_CHANGED: { LayerChangedData* data = (LayerChangedData*)e.object; if (data->LayerIsChanged(layer_num)) physics->WakeUp(); break; } case AlienEventType::COLLISION_LAYER_REMOVED: { int* layer_num = (int*)e.object; if (layer_num) SetCollisionLayer("Default"); break; } } } void ComponentCollider::InitCollider() { shape->userData = this; SetCollisionLayer("Default"); physics->AddCollider(this); } void ComponentCollider::InitMaterial() { SetStaticFriction(0.5f); SetDynamicFriction(0.5f); SetBouncing(0.5f); SetFrictionCombineMode(CombineMode::Average); SetBouncingCombineMode(CombineMode::Average); } void ComponentCollider::BeginUpdateShape(bool force_update) { if (IsController()) return; if (!this->force_update) physics->DettachCollider(this, true); if (force_update) this->force_update = true; } void ComponentCollider::EndUpdateShape(bool force_update) { if (IsController()) return; if (force_update) this->force_update = false; if (!this->force_update) physics->AttachCollider(this, true); } const float3 ComponentCollider::GetLocalMeshAabbSize() const { const ComponentMesh* mesh = GetMesh(); if (!mesh) return float3::one(); return mesh->GetLocalAABB().Size(); } const AABB ComponentCollider::GetLocalMeshAabb() const { const ComponentMesh* mesh = GetMesh(); if (!mesh) AABB(Sphere(float3::zero(), 0.5f)); return mesh->GetLocalAABB(); } const ComponentMesh* ComponentCollider::GetMesh() const { return game_object_attached->GetComponent<ComponentMesh>(); }
25.917706
179
0.726354
OverPowered-Team
ffc483e828e43b5cd7168ca66b6513cbd138755e
5,251
cpp
C++
RNAstructure_Source/src/phmm/phmm.cpp
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
RNAstructure_Source/src/phmm/phmm.cpp
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
RNAstructure_Source/src/phmm/phmm.cpp
mayc2/PseudoKnot_research
33e94b84435d87aff3d89dbad970c438ac173331
[ "MIT" ]
null
null
null
#include <stdio.h> #include <stdlib.h> #include "phmm.h" #include <string.h> #include "structure/structure_object.h" #include "utils/xmath/log/xlog_math.h" #include "utils/file/utils.h" char t_phmm::state_names[N_STATES][100] = {"STATE_INS1", "STATE_INS2", "STATE_ALN"}; t_phmm::t_phmm(double new_emission_probs[N_OUTPUTS][N_STATES], double new_trans_probs[N_STATES][N_STATES]) { this->alloc_init_params(); // Copy transition matrix. for(int cnt1 = 0; cnt1 < N_STATES; cnt1++) { for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { this->trans_probs[cnt1][cnt2] = xlog(new_trans_probs[cnt1][cnt2]); } // cnt2 loop } // cnt1 loop // Copy emission probabilities. for(int cnt1 = 0; cnt1 < N_OUTPUTS; cnt1++) { for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { this->emission_probs[cnt1][cnt2] = xlog(new_emission_probs[cnt1][cnt2]); } // cnt2 loop } // cnt1 loop } t_phmm::t_phmm(char* phmm_pars_file) { this->alloc_init_params(); // Read the parameters file. This parameters file contains 10 different parameter sets and thresholds. FILE* fam_par_file = open_f(phmm_pars_file, "r"); if(fam_par_file == NULL) { double* p=0; *p = 0; printf("Cannot find phmm parameters file, exiting @ %s(%d).\n", __FILE__, __LINE__); exit(0); } // Load all parameters from file. for(int cnt = 0; cnt < N_BINZ * (N_STATES + N_OUTPUTS) * N_STATES; cnt++) { fscanf(fam_par_file, "%lf", &fam_hmm_pars[cnt]); //printf("%d: %.3f\n", cnt, fam_hmm_pars[cnt]); } //printf("\n\n\nReading thresholds!!!\n"); // Read thresholds. for(int cnt = 0; cnt < N_BINZ; cnt++) { fscanf(fam_par_file, "%lf", &fam_thresholds[cnt]); //printf("%d: %f\n", cnt, fam_thresholds[cnt]); } fclose(fam_par_file); } void t_phmm::alloc_init_params() { // Copy transition matrix. this->trans_probs = (double**)malloc(sizeof(double*) * (N_STATES + 2)); for(int cnt1 = 0; cnt1 < N_STATES; cnt1++) { this->trans_probs[cnt1] = (double*)malloc(sizeof(double) * (N_STATES + 2)); for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { trans_probs[cnt1][cnt2] = xlog(0.0f); } // cnt2 loop } // cnt1 loop // Copy emission probabilities. this->emission_probs = (double**)malloc(sizeof(double*) * (N_OUTPUTS + 2)); for(int cnt1 = 0; cnt1 < N_OUTPUTS; cnt1++) { this->emission_probs[cnt1] = (double*)malloc(sizeof(double) * (N_STATES + 2)); for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { emission_probs[cnt1][cnt2] = xlog(0.0f); } // cnt2 loop } // cnt1 loop this->fam_hmm_pars = (double*)malloc(sizeof(double) * (N_BINZ * (N_STATES + N_OUTPUTS) * N_STATES + 2)); this->fam_thresholds = (double*)malloc(sizeof(double) * (N_BINZ + 2)); } void t_phmm::free_params() { // Free transition matrix. for(int cnt1 = 0; cnt1 < N_STATES; cnt1++) { free(this->trans_probs[cnt1]); } // cnt1 loop free(this->trans_probs); // Free emission probabilities. for(int cnt1 = 0; cnt1 < N_OUTPUTS; cnt1++) { free(this->emission_probs[cnt1]); } // cnt1 loop free(this->emission_probs); free(this->fam_hmm_pars); free(this->fam_thresholds); } t_phmm::~t_phmm() { this->free_params(); } void t_phmm::dump_parameters() { // Dump emission probabilities. for(int cnt1 = 0; cnt1 < N_OUTPUTS; cnt1++) { for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { printf("%.3f ", xexp(emission_probs[cnt1][cnt2])); } printf("\n"); } // Dump transition probabilities. printf("\n"); for(int cnt1 = 0; cnt1 < N_STATES; cnt1++) { for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { printf("%.3f ", xexp(trans_probs[cnt1][cnt2])); } printf("\n"); } } void t_phmm::set_parameters_by_sim(double similarity) { //int fam_par_set_index = (int)(similarity * (double)N_BINZ); int fam_par_set_index = get_bin_index(similarity, N_BINZ); // Load emission probabilities. // Each parameter set is (N_STATES + N_OUTPUTS) * N_STATES doubles long. int start_linear_index = (N_STATES + N_OUTPUTS) * N_STATES * get_bin_index(similarity, N_BINZ); double* par_ptr = fam_hmm_pars + start_linear_index; for(int cnt1 = 0; cnt1 < N_OUTPUTS; cnt1++) { for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { //emission_probs[cnt1][cnt2] = *(par_ptr + cnt1 * N_STATES + cnt2); emission_probs[cnt1][cnt2] = xlog(par_ptr[cnt1 * N_STATES + cnt2]); } } start_linear_index = (N_STATES + N_OUTPUTS) * N_STATES * fam_par_set_index + N_STATES * N_OUTPUTS; par_ptr = fam_hmm_pars + start_linear_index; // Load trans probabilities. for(int cnt1 = 0; cnt1 < N_STATES; cnt1++) { for(int cnt2 = 0; cnt2 < N_STATES; cnt2++) { //trans_probs[cnt1][cnt2] = *(par_ptr + cnt1 * N_STATES + cnt2); trans_probs[cnt1][cnt2] = xlog(par_ptr[cnt1 * N_STATES + cnt2]); } } } // Get index of bin of parameters for a sequence alignment. int t_phmm::get_bin_index(double similarity, int n_bins) { if(similarity == 1.0) { return(n_bins - 1); } else { return((int)(n_bins * similarity)); } } double t_phmm::get_fam_threshold(double similarity) { int bin_index = get_bin_index(similarity, N_BINZ); return(fam_thresholds[bin_index]); } double t_phmm::get_trans_prob(int prev, int next) { return(this->trans_probs[prev][next]); } double t_phmm::get_emit_prob(int sym_index, int state) { return(this->emission_probs[sym_index][state]); }
24.886256
106
0.665397
mayc2
ffc975dfb2fceab0e6ea001deaaf8b8d47844430
54,616
cpp
C++
XMLPullParser.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
XMLPullParser.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
XMLPullParser.cpp
malord/prime
f0e8be99b7dcd482708b9c928322bc07a3128506
[ "MIT" ]
null
null
null
// Copyright 2000-2021 Mark H. P. Lord // TODO: have more information in error messages // TODO: have some way of plugging in proper Unicode support for identifiers, whitespace, etc. #include "XMLPullParser.h" #include "NumberUtils.h" #include "ScopedPtr.h" #include "StringUtils.h" #include "TextEncoding.h" #include <memory> // Leaving this in until I'm sure of the new code. #define TEST_NAMESPACE_MAP 1 namespace Prime { namespace { const char cdataSectionHeader[] = "<![CDATA["; const char doctypeHeader[] = "<!DOCTYPE"; inline bool IsXMLWhitespace(int c, bool lenient) { // TODO: UNICODE support return (c <= 32 && (c == 10 || c == 13 || c == 32 || c == 9 || (lenient && (c == 12)))); } #if 0 inline bool IsExtendedNameStartChar(uint32_t uch) { if (uch >= 0xc0 && uch <= 0xd6) return true; if (uch >= 0xd8 && uch <= 0xf6) return true; if (uch >= 0xf8 && uch <= 0x2ff) return true; if (uch >= 0x370 && uch <= 0x37d) return true; if (uch >= 0x37f && uch <= 0x1fff) return true; if (uch >= 0x200c && uch <= 0x200d) return true; if (uch >= 0x2070 && uch <= 0x218f) return true; if (uch >= 0x2c00 && uch <= 0x2fef) return true; if (uch >= 0x3001 && uch <= 0xd7ff) return true; if (uch >= 0xf900 && uch <= 0xfdcf) return true; if (uch >= 0xfdf0 && uch <= 0xfffd) return true; if (uch >= 0x10000 && uch <= 0xeffff) return true; return false; } inline bool IsExtendedNameChar(uint32_t uch) { if (IsExtendedNameStartChar(uch)) return true; if (uch == 0xb7) return true; if (uch >= 0x0300 && uch <= 0x036f) return true; if (uch >= 0x203f && uch <= 0x2040) return true; return false; } #endif /// Returns true if the Unicode character is valid as the start of a name. inline bool IsNameStartChar(int c, bool lenient) { if (lenient) { return !IsXMLWhitespace(c, true) && !strchr("/>=", c); } else { // Testing for c > 127 covers all the Unicode cases in UTF-8, but it's not strict enough. return (c > 127) || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || c == '_' || c == ':'; } } /// Returns true if the Unicode character is valid within a name. inline bool IsNameChar(int c, bool lenient) { if (lenient) { return IsNameStartChar(c, true); } else { // TODO: Unicode lookup return IsNameStartChar(c, false) || (c >= '0' && c <= '9') || c == '.' || c == '-'; } } inline bool IsNameChar(int c, bool lenient, bool first) { return first ? IsNameStartChar(c, lenient) : IsNameChar(c, lenient); } inline bool IsXMLWhitespace(StringView string, bool lenient) { for (const char* ptr = string.begin(); ptr != string.end(); ++ptr) { if (!IsXMLWhitespace(*ptr, lenient)) { return false; } } return true; } inline size_t CountLeadingWhitespace(const char* begin, size_t length, bool lenient) { const char* end = begin + length; const char* ptr = begin; while (ptr != end && IsXMLWhitespace(*ptr, lenient)) { ++ptr; } return ptr - begin; } inline size_t CountTrailingWhitespace(const char* begin, size_t length, bool lenient) { const char* end = begin + length; const char* ptr = end; while (ptr != begin && IsXMLWhitespace(ptr[-1], lenient)) { --ptr; } return end - ptr; } inline bool IsXMLUnquotedAttributeValueChar(int c, bool lenient) { if (lenient) { // HTML attributes are anything but whitespace and any of "\"'`=<>". return !IsXMLWhitespace(c, true) && c != '>'; } else { return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strchr("-._:", c) != NULL; } } const XMLPullParser::Entity xmlEntities[] = { // Note these are sorted. { "&amp;", '&', NULL }, { "&apos;", '\'', NULL }, { "&gt;", '>', NULL }, { "&lt;", '<', NULL }, { "&quot;", '"', NULL }, }; // // HTML // // There's also the issue of implicit start elements, e.g., a <tr> implies a <table> } const XMLPullParser::Attribute XMLPullParser::emptyAttribute = { "", "", "", "" }; const char* XMLPullParser::getErrorDescription(ErrorCode error) { switch (error) { case ErrorReadFailed: return PRIME_LOCALISE("Read error"); case ErrorNone: return PRIME_LOCALISE("Unknown error"); case ErrorUnexpectedWhitespace: return PRIME_LOCALISE("Unexpected whitespace"); case ErrorUnknownEntity: return PRIME_LOCALISE("Unknown entity reference"); case ErrorInvalidEntity: return PRIME_LOCALISE("Invalid entity reference"); case ErrorInvalidCharacter: return PRIME_LOCALISE("Invalid character"); case ErrorUnexpectedEndOfFile: return PRIME_LOCALISE("Unexpected end of file"); case ErrorIllegalName: return PRIME_LOCALISE("Invalid name"); case ErrorExpectedEquals: return PRIME_LOCALISE("Expected = after attribute name"); case ErrorExpectedQuote: return PRIME_LOCALISE("Expected \" enclosing attribute value"); case ErrorExpectedRightAngleBracket: return PRIME_LOCALISE("Expected >"); case ErrorUnexpectedEndElement: return PRIME_LOCALISE("Unexpected end element"); case ErrorMismatchedEndElement: return PRIME_LOCALISE("Mismatched end element"); case ErrorExpectedText: return PRIME_LOCALISE("Expected text but got an element or attribute"); case ErrorExpectedEmptyElement: return PRIME_LOCALISE("Expected an empty element"); case ErrorTextOutsideElement: return PRIME_LOCALISE("Text outside element"); case ErrorUnknownNamespace: return PRIME_LOCALISE("Unknown namespace"); case ErrorIncorrectlyTerminatedComment: return PRIME_LOCALISE("Incorrectly terminated comment"); case ErrorInvalidAttributeValue: return PRIME_LOCALISE("Invalid character in attribute value"); case ErrorCDATATerminatorInText: return PRIME_LOCALISE("]]> found in text"); case ErrorInvalidDocType: return PRIME_LOCALISE("Invalid DOCTYPE"); case ErrorDuplicateAttribute: return PRIME_LOCALISE("Attribute name occurs more than once"); case ErrorMultipleTopLevelElements: return PRIME_LOCALISE("Multiple top-level elements"); } return "unknown XML error"; } const char* XMLPullParser::getTokenDescription(int token) const { switch (token) { case TokenError: return PRIME_LOCALISE("error"); case TokenEOF: return PRIME_LOCALISE("end of file"); case TokenNone: return PRIME_LOCALISE("null"); case TokenText: return PRIME_LOCALISE("text"); case TokenProcessingInstruction: return PRIME_LOCALISE("processing instruction"); case TokenStartElement: return PRIME_LOCALISE("start element"); case TokenEndElement: return PRIME_LOCALISE("end element"); case TokenComment: return PRIME_LOCALISE("comment"); case TokenDocType: return PRIME_LOCALISE("doctype"); } return "unknown XML token"; } void XMLPullParser::construct() { _textReader = NULL; _options = Options(); _text.resize(0); _text.reserve(2048); _wholeText.reserve(2048); _error = ErrorNone; _emptyElement = false; _popElement = 0; _name = NULL; _localName = NULL; _qualifiedName = NULL; _namespace = NULL; _entities = ArrayView<const Entity>(xmlEntities, COUNTOF(xmlEntities)); _hadFirstTopLevelElement = false; _lastToken = TokenNone; } XMLPullParser::~XMLPullParser() { deleteNamespaces(); } void XMLPullParser::deleteNamespaces() { NamespaceMap::iterator iter = _namespaces.begin(); NamespaceMap::iterator end = _namespaces.end(); for (; iter != end; ++iter) { while (iter->second) { Namespace* nspace = iter->second; iter->second = nspace->prev; delete nspace; } } } int XMLPullParser::setError(ErrorCode code) { _error = code; getLog()->error("%s", getErrorDescription(code)); return TokenError; } void XMLPullParser::warn(ErrorCode code) { getLog()->warning("%s", getErrorDescription(code)); } bool XMLPullParser::setErrorReturnFalseUnlessLenient(ErrorCode code) { if (isLenient()) { warn(code); return true; } setError(code); return false; } void XMLPullParser::init(TextReader* textReader, const Options& options) { _options = options; _textReader = textReader; _lastToken = TokenNone; if (_options.getHTMLEntities()) { setUserEntities(GetHTMLEntities()); } if (_options.getHTMLMode()) { addEmptyElements(GetHTMLEmptyElements(), ""); } } bool XMLPullParser::equalNames(const char* a, const char* b) const { return (_options.getCaseInsensitiveNames()) ? ASCIIEqualIgnoringCase(a, b) : StringsEqual(a, b); } bool XMLPullParser::equalNamespaces(const char* a, const char* b) { return ASCIIEqualIgnoringCase(a ? a : "", b ? b : ""); } void XMLPullParser::addEmptyElements(ArrayView<const char*> elements, const char* namespaceForAll) { const char* const* e = elements.end(); NameAndNamespace nns = { 0, namespaceForAll }; for (const char* const* p = elements.begin(); p != e; ++p) { nns.name = _stringTable.intern(*p); _emptyElements.push_back(nns); } } bool XMLPullParser::isEmptyElement(const char* name, const char* nspace) const { // TODO: binary search (sort the array in addEmptyElements) std::vector<NameAndNamespace>::const_iterator i = _emptyElements.begin(); std::vector<NameAndNamespace>::const_iterator e = _emptyElements.end(); for (; i != e; ++i) { if (equalNames(i->name, name) && equalNamespaces(i->nspace, nspace)) { return true; } } return false; } void XMLPullParser::setUserEntities(ArrayView<const Entity> entities) { _entities = entities; } int XMLPullParser::read() { // Once we encounter an error, keep returning error. if (_lastToken == TokenError) { return TokenError; } _lastToken = read2(); return _lastToken; } int XMLPullParser::read2() { if (_emptyElement) { _emptyElement = false; _popElement = 1; return TokenEndElement; } if (_popElement) { --_popElement; popElement(); if (_popElement != 0) { return TokenEndElement; } } _text.resize(0); int token; do { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { if (_elements.empty()) { if (!_hadFirstTopLevelElement) { if (!isLenient()) { return setError(ErrorUnexpectedEndOfFile); } warn(ErrorUnexpectedEndOfFile); } return TokenEOF; } if (isLenient()) { warn(ErrorUnexpectedEndOfFile); // Auto-pop the remaining elements. _popElement = (int)_elements.size(); setNameAndDetermineNamespace(_elements.back().name); return TokenEndElement; } return setError(ErrorUnexpectedEndOfFile); } } if (c == '<' && (!inScript() || _textReader->hasString("</"))) { token = parseElement(); } else { token = parseText(); } } while (token == TokenNone); return token; } int XMLPullParser::next() { for (;;) { int got = read(); switch ((Token)got) { case TokenStartElement: case TokenText: case TokenEndElement: return got; case TokenEOF: case TokenError: return got; case TokenProcessingInstruction: case TokenComment: case TokenDocType: case TokenNone: break; } // Loop and skip to next token } } XMLPullParser::Attribute XMLPullParser::getAttribute(size_t index) const { PRIME_ASSERT(index < getAttributeCount()); return getAttributeCheckIndex((ptrdiff_t)index); } XMLPullParser::Attribute XMLPullParser::getAttributeCheckIndex(ptrdiff_t index) const { Attribute a; if (index < 0) { a = emptyAttribute; } else { const InternedAttribute& ia = _elements.back().attributes[index]; a.qualifiedName = ia.qualifiedName; a.nspace = ia.nspace; a.localName = ia.localName; a.value = _elements.back().values.data() + ia.valueOffset; } return a; } ptrdiff_t XMLPullParser::getAttributeIndex(StringView localName) const { for (size_t i = 0; i != getAttributeCount(); ++i) { const InternedAttribute& ia = _elements.back().attributes[i]; if (StringsEqual(ia.localName, localName)) { return (ptrdiff_t)i; } } return -1; } ptrdiff_t XMLPullParser::getAttributeIndex(StringView localName, StringView nspace) const { for (size_t i = 0; i != getAttributeCount(); ++i) { const InternedAttribute& ia = _elements.back().attributes[i]; if (StringsEqual(ia.localName, localName) && StringsEqual(ia.nspace, nspace)) { return (ptrdiff_t)i; } } return -1; } XMLPullParser::Attribute XMLPullParser::getAttribute(StringView localName) const { return getAttributeCheckIndex(getAttributeIndex(localName)); } XMLPullParser::Attribute XMLPullParser::getAttribute(StringView localName, StringView nspace) const { return getAttributeCheckIndex(getAttributeIndex(localName, nspace)); } int XMLPullParser::parseElement() { PRIME_DEBUG_ASSERT(_textReader->peekChar(0) == '<'); int c1 = _textReader->peekChar(1); int result; bool skipable = false; if (c1 == '?') { result = parseProcessingInstruction(); } else if (c1 == '!') { result = parseExclamation(); } else if (c1 == '/') { result = parseEndElement(&skipable); } else { result = parseStartElement(&skipable); } if (result == TokenError) { if (skipable) { // parseEndElement and parseStartElement will rewind _textReader->skipChar(); return TokenNone; } } return result; } int XMLPullParser::parseExclamation() { PRIME_DEBUG_ASSERT(_textReader->peekChar(0) == '<' && _textReader->peekChar(1) == '!'); int c2 = _textReader->peekChar(2); int c3 = _textReader->peekChar(3); if (c2 == '-' && c3 == '-') { return parseComment(); } if (c2 == '[' && c3 == 'C' && _textReader->hasString(cdataSectionHeader)) { return parseCDATA(); } if (_textReader->hasString(doctypeHeader)) { return parseDocType(); } if (!isStrict()) { warn(ErrorInvalidDocType); return parseDocType(); } return setError(ErrorInvalidDocType); } bool XMLPullParser::addUnicodeChar(uint32_t n) { if (n & UINT32_C(0x80000000)) { return setErrorReturnFalseUnlessLenient(ErrorInvalidCharacter); } uint8_t ch[7]; size_t len = UTF8Encode(ch, (int32_t)n); ch[len] = 0; if (!ch[0]) { return setErrorReturnFalseUnlessLenient(ErrorInvalidCharacter); } _text.append((char*)ch, len); return true; } bool XMLPullParser::processHexCharacterNumber() { PRIME_DEBUG_ASSERT(_textReader->peekChar() == '&' && _textReader->peekChar(1) == '#' && (_textReader->peekChar(2) == 'x' || _textReader->peekChar(2) == 'X')); _textReader->skipChars(3); uint32_t n = 0; int digitCount = 0; unsigned int digit = 0; for (int i = 0;; ++i) { int c = _textReader->peekChar(i); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { return setErrorReturnFalseUnlessLenient(ErrorUnexpectedEndOfFile); } } if (c == ';') { if (!digitCount) { return setErrorReturnFalseUnlessLenient(ErrorInvalidEntity); } _textReader->skipChars(i + 1); return addUnicodeChar(n); } if (c >= '0' && c <= '9') { digit = c - '0'; } else if (c >= 'a' && c <= 'f') { digit = c - 'a' + 10; } else if (c >= 'A' && c <= 'F') { digit = c - 'A' + 10; } else { return setErrorReturnFalseUnlessLenient(ErrorInvalidEntity); } if (digitCount == 8) { return setErrorReturnFalseUnlessLenient(ErrorInvalidEntity); } n = n * 16 + digit; if (n) { ++digitCount; } } } bool XMLPullParser::processCharacterNumber() { PRIME_DEBUG_ASSERT(_textReader->peekChar() == '&' && _textReader->peekChar(1) == '#'); if (_textReader->peekChar(2) == 'x' || (isLenient() && _textReader->peekChar(2) == 'X')) { return processHexCharacterNumber(); } _textReader->skipChars(2); uint32_t n = 0; int digitCount = 0; for (int i = 0;; ++i) { int c = _textReader->peekChar(i); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { return setErrorReturnFalseUnlessLenient(ErrorUnexpectedEndOfFile); } } if (c == ';') { if (!digitCount) { return setErrorReturnFalseUnlessLenient(ErrorInvalidEntity); } _textReader->skipChars(i + 1); return addUnicodeChar(n); } if (c < '0' || c > '9' || digitCount > 8) { return setErrorReturnFalseUnlessLenient(ErrorInvalidEntity); } n = n * 10 + (c - '0'); if (n) { ++digitCount; } } } bool XMLPullParser::processAmpersand() { PRIME_DEBUG_ASSERT(_textReader->peekChar() == '&'); if (_textReader->peekChar(1) == '#') { return processCharacterNumber(); } bool lenient = isLenient(); int len; bool invalid = false; for (len = 1;; ++len) { int peeked = _textReader->peekChar(len); if (peeked == ';') { ++len; break; } if (!IsNameChar(peeked, lenient, len == 1)) { invalid = true; break; } } if (invalid && isStrict()) { setError(ErrorInvalidEntity); return false; } if (!invalid) { // TODO: binary search (would need the entities to be copied by us and sorted) for (size_t i = 0; i != _entities.size(); ++i) { const Entity& e = _entities[i]; if (strncmp(_textReader->getReadPointer(), e.token, len) == 0) { // Match! if (e.string) { _text.append(e.string); } else { if (!addUnicodeChar(e.entity)) { return false; } } _textReader->skipChars(len); return true; } } } // If we get here then it's an invalid or unknown entity reference. Treat it as literal text. _text += '&'; _textReader->skipChar(); // We can't produce an error here because as far as we know there's a valid ENTITY in the DocType. warn(ErrorUnknownEntity); return true; } void XMLPullParser::processCR() { PRIME_DEBUG_ASSERT(_textReader->peekChar() == 13); // Windows style CRLF becomes plain LF. if (_textReader->peekChar(1) == 10) { _textReader->skipChars(2); _text += (char)10; } else { // Not CRLF, just CR - discard. _textReader->skipChar(); } } void XMLPullParser::processLF() { PRIME_DEBUG_ASSERT(_textReader->peekChar() == 10); // Old Mac style LFCR becomes plain LF. if (_textReader->peekChar(1) == 13) { _textReader->skipChars(2); } else { _textReader->skipChar(); } _text += (char)10; } int XMLPullParser::parseText() { bool isScript = inScript(); for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { break; } } if (c == '<') { if (!isScript || _textReader->hasString("</")) { break; } } if (processCRLF(c)) { continue; } if (!isValidText(c)) { return TokenError; } if (c == '&' && !isScript) { if (!processAmpersand()) { return TokenError; } continue; } if (isScript) { if (c == '\'' || c == '"') { if (!readScriptString()) { return TokenError; } continue; } else if (c == '/') { int c2 = _textReader->peekChar(1); if (c2 == '/') { if (!readScriptSingleLineComment()) { return TokenError; } continue; } else if (c2 == '*') { if (!readScriptMultiLineComment()) { return TokenError; } continue; } } } if (c == ']' && _textReader->peekChar(1) == ']' && _textReader->peekChar(2) == '>') { if (isStrict()) { return setError(ErrorCDATATerminatorInText); } warn(ErrorCDATATerminatorInText); } _text += TextReader::intToChar(c); _textReader->skipChar(); } if (_elements.empty() && !isTextEntirelyWhitespace()) { if (!isLenient()) { return setError(ErrorTextOutsideElement); } warn(ErrorTextOutsideElement); } _cdata = false; return TokenText; } bool XMLPullParser::readScriptString() { int quote = _textReader->readChar(); int lastC = quote; for (;;) { int c = _textReader->readChar(); if (c < 0) { if (c == TextReader::EOFChar) { break; } return false; } _text += TextReader::intToChar(c); if (lastC != '\\' && c == quote) { break; } lastC = c; } return true; } bool XMLPullParser::readScriptSingleLineComment() { for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::EOFChar) { break; } return false; } if (processCRLF(c)) { break; } _text += TextReader::intToChar(c); _textReader->skipChar(); } return true; } bool XMLPullParser::readScriptMultiLineComment() { int lastC = ' '; _text += "/*"; _textReader->skipChars(2); for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::EOFChar) { break; } return false; } if (processCRLF(c)) { continue; } _text += TextReader::intToChar(c); _textReader->skipChar(); if (c == '/' && lastC == '*') { break; } lastC = c; } return true; } int XMLPullParser::parseCDATA() { PRIME_DEBUG_ASSERT(_textReader->hasString(cdataSectionHeader)); _textReader->skipChars(COUNTOF(cdataSectionHeader) - 1); for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); break; } return setError(ErrorUnexpectedEndOfFile); } } if (c == ']' && _textReader->peekChar(1) == ']' && _textReader->peekChar(2) == '>') { _textReader->skipChars(3); break; } if (processCRLF(c)) { continue; } if (!isValidText(c)) { return TokenError; } _text += TextReader::intToChar(c); _textReader->skipChar(); } if (_elements.empty()) { if (!isLenient()) { return setError(ErrorTextOutsideElement); } warn(ErrorTextOutsideElement); } _cdata = true; return TokenText; } void XMLPullParser::popElement() { _elements.pop_back(); popNamespaces(); if (!_elements.empty()) { setNameAndDetermineNamespace(_elements.back().name); } } void XMLPullParser::popNamespaces() { NamespaceMap::iterator iter = _namespaces.begin(); NamespaceMap::iterator end = _namespaces.end(); for (; iter != end; ++iter) { Namespace* nspace = iter->second; if (nspace->depth > _elements.size()) { iter->second = nspace->prev; delete nspace; } } } void XMLPullParser::pushElement(const char* name) { Element el; el.name = name; el.isScript = _options.getHTMLMode() && (ASCIIEqualIgnoringCase(name, "script") || ASCIIEqualIgnoringCase(name, "style")); _elements.push_back(el); } void XMLPullParser::setTopElementNamespace() { Element& el = _elements.back(); for (size_t i = 0; i != el.attributes.size(); ++i) { const InternedAttribute& a = el.attributes[i]; if (strncmp(a.qualifiedName, "xmlns", 5) != 0) { continue; } const char* nspaceName = (a.qualifiedName[5] == ':') ? a.qualifiedName + 6 : ""; const char* value = el.values.c_str() + a.valueOffset; value = _stringTable.intern(value); setNamespace(nspaceName, value); } setNameAndDetermineNamespace(el.name); } void XMLPullParser::setNamespace(const char* name, const char* value) { Namespace* prev; NamespaceMap::const_iterator iter = _namespaces.find(name); if (iter != _namespaces.end()) { if (StringsEqual(iter->second->value, value)) { // Identical values, don't bother creating a new Namespace. return; } prev = iter->second; } else { prev = NULL; } ScopedPtr<Namespace> nspace(new Namespace); nspace->name = name; nspace->value = value; nspace->depth = _elements.size(); nspace->prev = prev; _namespaces[name] = nspace.get(); nspace.detach(); } int XMLPullParser::parseStartElement(bool* skipable) { TextReader::Marker marker(_textReader); // Rewind in case of skipable or element where it shouldn't be _textReader->skipChar(); // < if (!parseName(skipable)) { return TokenError; } const bool isTopLevelElement = _elements.empty(); pushElement(_name); for (;;) { if (!skipWhitespace()) { return TokenError; } int c = _textReader->peekChar(); if (c == '>') { _emptyElement = false; _textReader->skipChar(); break; } if (c == '/' && _textReader->peekChar(1) == '>') { _emptyElement = true; _textReader->skipChars(2); break; } if (!parseAttribute(skipable)) { popElement(); return TokenError; } } if (isTopLevelElement) { if (_hadFirstTopLevelElement) { if (!_options.getHTMLMode()) { return setError(ErrorMultipleTopLevelElements); } warn(ErrorMultipleTopLevelElements); } _hadFirstTopLevelElement = true; } setTopElementNamespace(); Element& el = _elements.back(); for (size_t i = 0; i != el.attributes.size(); ++i) { InternedAttribute& a = el.attributes[i]; determineNamespaceAndLocalName(a.qualifiedName, &a.localName, &a.nspace); PRIME_DEBUG_ASSERT(a.localName); } // Check for duplicate attributes. if (!el.attributes.empty()) { for (size_t i = 0; i != el.attributes.size() - 1; ++i) { const InternedAttribute& a = el.attributes[i]; for (size_t j = i + 1; j != el.attributes.size(); ++j) { const InternedAttribute& a2 = el.attributes[j]; if (a.nspace == a2.nspace && a.localName == a2.localName) { if (isStrict()) { return setError(ErrorDuplicateAttribute); } else { warn(ErrorDuplicateAttribute); } } } } } if (isEmptyElement(_localName, _namespace)) { _emptyElement = true; } if (!canElementBeHere()) { popElement(); _popElement = 1; marker.rewind(); // Alternative to using a marker is to have the _popElement handling code in read2() push an element afterwards return TokenEndElement; } marker.release(); return TokenStartElement; } bool XMLPullParser::canElementBeHere() const { if (_options.getHTMLMode()) { // See http://www.w3.org/TR/html5/index.html#elements-1 // TODO: col, colgroup, datalist, fieldset, legend, figure, figcaption, map, select, // option, optgroup, ruby, rp, rt, rb, rtc, script??, caption, template // TODO: What to do about multiple head/body? // Note that some cases are covered by htmlEmptyElements. if (ASCIIEqualIgnoringCase(_localName, "dd") || ASCIIEqualIgnoringCase(_localName, "dt")) { int dt = findAncestor("dt"); int dd = findAncestor("dd"); int dl = findAncestor("dl"); if (dd > dl || dt > dl) { // Disallow dd/dt inside a dd/dt unless there's another dl return false; } } else if (ASCIIEqualIgnoringCase(_localName, "tr")) { int tr = findAncestor("tr"); int td = findAncestor("td"); int table = findAncestor("table"); if (tr > table || td > table) { // Disallow td inside a tr/td unless there's another table return false; } } else if (ASCIIEqualIgnoringCase(_localName, "tbody") || ASCIIEqualIgnoringCase(_localName, "thead") || ASCIIEqualIgnoringCase(_localName, "tfoot")) { int table = findAncestor("table"); int tr = findAncestor("tr"); int td = findAncestor("td"); int thead = findAncestor("thead"); int tbody = findAncestor("tbody"); int tfoot = findAncestor("tfoot"); if (td > table || tr > table || thead > table || tfoot > table || tbody > table) { // thead, tfoot, tbody cannot occur inside each other unless there's another table return false; } } else if (ASCIIEqualIgnoringCase(_localName, "td")) { int td = findAncestor("td"); int table = findAncestor("table"); if (td > table) { // Disallow td inside a td unless there's another table return false; } } else if (ASCIIEqualIgnoringCase(_localName, "li")) { int list = Max(findAncestor("ol"), findAncestor("ul")); int li = findAncestor("li"); if (li > list) { // Disallow li inside an li unless there's another ol/ul return false; } } else if (ASCIIEqualIgnoringCase(_localName, "param")) { int object = findAncestor("object"); int param = findAncestor("param"); if (param > object) { // Disallow param inside an param unless there's another object return false; } } else if (ASCIIEqualIgnoringCase(_localName, "source")) { int media = Max(findAncestor("video"), findAncestor("audio")); int source = findAncestor("source"); if (source > media) { // Disallow source inside an source unless there's another video/audio return false; } } else if (ASCIIEqualIgnoringCase(_localName, "body")) { if (findAncestor("head") >= 0) { // Disallow body inside head. Good advice in general. return false; } } else if (ASCIIEqualIgnoringCase(_localName, "style")) { if (findAncestor("style") >= 0) { // Disallow style inside style. return false; } } } return true; } int XMLPullParser::findAncestor(const char* localName) const { for (size_t i = _elements.size() - 1; i-- > 0;) { const Element& el = _elements[i]; const char* ptr = strchr(el.name, ':'); ptr = ptr ? ptr + 1 : el.name; if (ASCIIEqualIgnoringCase(ptr, localName)) { return (int)i; } } return -1; } int XMLPullParser::parseProcessingInstruction() { PRIME_DEBUG_ASSERT(_textReader->peekChar(0) == '<' && _textReader->peekChar(1) == '?'); _textReader->skipChars(2); if (!parseName(NULL)) { return TokenError; } if (!skipWhitespace()) { return TokenError; } _qualifiedName = _localName = _name; _namespace = NULL; _text.resize(0); int c; for (;;) { c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); break; } return setError(ErrorUnexpectedEndOfFile); } } if (c == '?' && _textReader->peekChar(1) == '>') { break; } if (processCRLF(c)) { continue; } if (!isValidText(c)) { return TokenError; } _text += TextReader::intToChar(c); _textReader->skipChar(); } if (c >= 0) { _textReader->skipChars(c == '>' ? 1 : 2); } return TokenProcessingInstruction; } bool XMLPullParser::isValidText(int c) { if (c < ' ') { if (c != 13 && c != 10 && c != 9) { if (isStrict()) { return setErrorReturnFalse(ErrorInvalidCharacter); } warn(ErrorInvalidCharacter); } } return true; } bool XMLPullParser::parseName(bool* skipable) { if (skipable) { *skipable = false; } _parseNameBuffer.resize(0); if (!skipWhitespaceIfLenient()) { return false; } bool lenient = isLenient(); bool firstChar = true; for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); break; } return setErrorReturnFalse(ErrorUnexpectedEndOfFile); } } if (firstChar) { if (!IsNameStartChar(c, lenient)) { if (skipable) { warn(ErrorIllegalName); *skipable = true; return false; } else { return setErrorReturnFalse(ErrorIllegalName); } } firstChar = false; } else if (!IsNameChar(c, lenient)) { break; } _parseNameBuffer += TextReader::intToChar(c); _textReader->skipChar(); } // This will only allocate memory the first time a name is encountered. _name = _stringTable.intern(_parseNameBuffer.c_str()); return true; } bool XMLPullParser::parseUnquotedAttributeValue() { _text.resize(0); bool lenient = isLenient(); // will probably always be true if we've reached this method! for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); break; } return setErrorReturnFalse(ErrorUnexpectedEndOfFile); } } if (!IsXMLUnquotedAttributeValueChar(c, lenient)) { break; } if (c == '/' && _textReader->peekChar(1) == '>') { break; } if (processCRLF(c)) { continue; } if (!isValidText(c)) { return false; } if (c == '&') { if (!processAmpersand()) { return false; } continue; } _text += TextReader::intToChar(c); _textReader->skipChar(); } return true; } bool XMLPullParser::parseAttributeValue() { int quot = _textReader->peekChar(); if (quot != '"') { if (quot != '\'') { if (!isLenient()) { setError(ErrorExpectedQuote); return false; } // Allow unquoted attribute values for HTML if (!_options.getHTMLMode()) { warn(ErrorExpectedQuote); } return parseUnquotedAttributeValue(); } else { // Allow ' for HTML if (!_options.getHTMLMode()) { warn(ErrorExpectedQuote); } } } _textReader->skipChar(); _text.resize(0); for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); break; } return setErrorReturnFalse(ErrorUnexpectedEndOfFile); } } if (c == quot) { _textReader->skipChar(); break; } if (processCRLF(c)) { continue; } if (!isValidText(c)) { return false; } if (c == '&') { if (!processAmpersand()) { return false; } continue; } // # is sometimes considered invalid, but I can't find consensus if (strchr("<&", TextReader::intToChar(c))) { if (isStrict()) { return setErrorReturnFalse(ErrorInvalidAttributeValue); } // Allow these characters in HTML. if (!_options.getHTMLMode()) { warn(ErrorInvalidAttributeValue); } } _text += TextReader::intToChar(c); _textReader->skipChar(); } return true; } bool XMLPullParser::parseAttribute(bool* skipable) { // parseName initialises skipable if (!parseName(skipable)) { return false; } InternedAttribute a; a.qualifiedName = _name; if (!skipWhitespaceIfLenient()) { return false; } if (_textReader->peekChar() != '=') { if (!isLenient()) { setError(ErrorExpectedEquals); return false; } // Allow attributes with no value in HTML. if (!_options.getHTMLMode()) { warn(ErrorExpectedEquals); } _text.resize(0); } else { _textReader->skipChar(); if (!skipWhitespaceIfLenient()) { return false; } if (!parseAttributeValue()) { return false; } } Element& el = _elements.back(); a.valueOffset = el.values.size(); el.values.append(_text.c_str(), _text.size() + 1); // include the NUL el.attributes.push_back(a); return true; } bool XMLPullParser::skipWhitespace() { bool lenient = isLenient(); for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { break; } } if (!IsXMLWhitespace(c, lenient)) { break; } _textReader->skipChar(); } return true; } bool XMLPullParser::skipWhitespaceIfLenient() { bool lenient = isLenient(); bool skipped = false; for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return false; } if (c == TextReader::EOFChar) { break; } } if (!IsXMLWhitespace(c, lenient)) { break; } _textReader->skipChar(); skipped = true; } if (skipped) { warn(ErrorUnexpectedWhitespace); } return true; } int XMLPullParser::parseEndElement(bool* skipable) { TextReader::Marker marker(_textReader); // Rewind in case of skipable PRIME_DEBUG_ASSERT(_textReader->peekChar(0) == '<' && _textReader->peekChar(1) == '/'); _textReader->skipChars(2); if (!skipWhitespaceIfLenient()) { return TokenError; } if (_elements.empty()) { if (!isLenient()) { return setError(ErrorUnexpectedEndElement); } warn(ErrorUnexpectedEndElement); return TokenNone; } if (!parseName(skipable)) { return TokenError; } int popCount = 1; if (_name != _elements.back().name) { if (!isLenient()) { return setError(ErrorMismatchedEndElement); } warn(ErrorMismatchedEndElement); setNameAndDetermineNamespace(_name); // See if we can find a match. popCount = 0; size_t i = _elements.size(); while (i--) { // TODO! // if (equalNames(_elements[i].name, _name) && equalNamespaces(_elements[i].nspace, _namespace)) { if (equalNames(_elements[i].name, _name)) { // Found it! popCount = (int)(_elements.size() - i); break; } } } setNameAndDetermineNamespace(_elements.back().name); if (!skipWhitespace()) { return TokenError; } if (_textReader->peekChar() != '>') { if (!isLenient()) { return setError(ErrorExpectedRightAngleBracket); } warn(ErrorExpectedRightAngleBracket); } else { _textReader->skipChar(); } marker.release(); _popElement = popCount; return popCount ? TokenEndElement : TokenNone; } int XMLPullParser::parseComment() { PRIME_DEBUG_ASSERT(_textReader->peekChar(0) == '<' && _textReader->peekChar(1) == '!' && _textReader->peekChar(2) == '-' && _textReader->peekChar(2) == '-'); _textReader->skipChars(4); for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); break; } return setError(ErrorUnexpectedEndOfFile); } } if (c == '-' && _textReader->peekChar(1) == '-') { if (_textReader->peekChar(2) == '>') { _textReader->skipChars(3); break; } if (isStrict()) { return setError(ErrorIncorrectlyTerminatedComment); } } if (!isValidText(c)) { return TokenError; } _text += TextReader::intToChar(c); _textReader->skipChar(); } return TokenComment; } int XMLPullParser::parseDocType() { PRIME_DEBUG_ASSERT(_textReader->peekChar(0) == '<' && _textReader->peekChar(1) == '!'); // Read the entire DocType as raw text, without parsing it. _textReader->skipChars(2); int nest = 1; for (;;) { int c = _textReader->peekChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); return TokenDocType; } return setError(ErrorUnexpectedEndOfFile); } } if (c == '>') { if (!--nest) { _textReader->skipChar(); return TokenDocType; } } else if (c == '<') { if (_textReader->hasString("<!--")) { std::string text2; text2.swap(_text); int token = parseComment(); if (token < TokenNone) { return token; } text2.swap(_text); _text += "<!--"; _text += text2; _text += "-->"; continue; } else { ++nest; } } else if (c == '\'' || c == '"') { int quot = c; _text += TextReader::intToChar(c); _textReader->skipChar(); do { c = _textReader->readChar(); if (c < 0) { if (c == TextReader::ErrorChar) { readFailed(); return TokenError; } if (c == TextReader::EOFChar) { if (isLenient()) { warn(ErrorUnexpectedEndOfFile); return TokenDocType; } return setError(ErrorUnexpectedEndOfFile); } } _text += TextReader::intToChar(c); } while (c != quot); continue; } _text += TextReader::intToChar(c); _textReader->skipChar(); } } void XMLPullParser::determineNamespaceAndLocalName(const char* name, const char** localName, const char** nspace) { // name should already have been interned. PRIME_DEBUG_ASSERT(!*name || _stringTable.intern(name) == name); const char* colon = strchr(name, ':'); if (!colon) { *localName = name; *nspace = findNamespace(); } else { ptrdiff_t colonPos = colon - name; *localName = name + colonPos + 1; std::string prefix(name, colonPos); *nspace = findNamespace(prefix.c_str()); } } void XMLPullParser::setNameAndDetermineNamespace(const char* name) { // name should already have been interned. PRIME_DEBUG_ASSERT(!*name || _stringTable.intern(name) == name); _qualifiedName = name; determineNamespaceAndLocalName(name, &_localName, &_namespace); } const char* XMLPullParser::findNamespace() { return findNamespace(""); } const char* XMLPullParser::findNamespace(const char* prefix) { NamespaceMap::const_iterator iter = _namespaces.find(prefix); const char* value; if (iter == _namespaces.end()) { if (*prefix && !StringsEqual(prefix, "xmlns") && !StringsEqual(prefix, "xml")) { // Don't warn for the default namespace or xmlns. getLog()->warning("%s: %s", getErrorDescription(ErrorUnknownNamespace), prefix); } value = NULL; } else { value = iter->second->value; } #if TEST_NAMESPACE_MAP const char* secondOpinion = *prefix ? findNamespaceOld(prefix) : findNamespaceOld(); PRIME_ASSERT(secondOpinion != NULL || value == NULL); PRIME_ASSERT(StringsEqual(value ? value : "", secondOpinion ? secondOpinion : "")); #endif return value; } const char* XMLPullParser::findNamespaceOld() { std::vector<Element>::iterator ie = _elements.end(); std::vector<Element>::iterator ee = _elements.begin(); while (ie-- != ee) { std::vector<InternedAttribute>::iterator ia = ie->attributes.begin(); std::vector<InternedAttribute>::iterator ea = ie->attributes.end(); for (; ia != ea; ++ia) { if (StringsEqual(ia->qualifiedName, "xmlns")) { return _stringTable.intern(ie->values.data() + ia->valueOffset); } } } return 0; } const char* XMLPullParser::findNamespaceOld(const char* prefix) { static const char xmlnsColon[] = "xmlns:"; static const size_t xmlnsColonLength = sizeof(xmlnsColon) - 1; size_t totalLength = xmlnsColonLength + strlen(prefix); std::vector<Element>::iterator ie = _elements.end(); std::vector<Element>::iterator ee = _elements.begin(); while (ie != ee) { --ie; std::vector<InternedAttribute>::iterator ia = ie->attributes.begin(); std::vector<InternedAttribute>::iterator ea = ie->attributes.end(); for (; ia != ea; ++ia) { if (strlen(ia->qualifiedName) == totalLength && strncmp(ia->qualifiedName, xmlnsColon, xmlnsColonLength) == 0) { if (StringsEqual(ia->qualifiedName + xmlnsColonLength, prefix)) { return _stringTable.intern(ie->values.data() + ia->valueOffset); } } } } return 0; } const char* XMLPullParser::readWholeText(const char* elementDescription) { _wholeText.resize(0); if (_lastToken == TokenText) { _wholeText = _text; } for (;;) { int token = read(); if (token == TokenError) { return NULL; } if (token == TokenComment) { continue; } if (token == TokenText) { _wholeText.append(_text.data(), _text.size()); continue; } if (token == TokenEndElement) { break; } getLog()->error(PRIME_LOCALISE("Unexpected %s in %s element."), getTokenDescription(token), elementDescription); _error = ErrorExpectedText; return NULL; } return _wholeText.c_str(); } const char* XMLPullParser::readWholeTextTrimmed(const char* elementDescription) { const char* got = readWholeText(elementDescription); if (!got) { return NULL; } size_t leading = CountLeadingWhitespace(_wholeText.c_str(), _wholeText.size(), isLenient()); _wholeText.erase(0, leading); size_t trailing = CountTrailingWhitespace(_wholeText.c_str(), _wholeText.size(), isLenient()); _wholeText.resize(_wholeText.size() - trailing); return _wholeText.c_str(); } bool XMLPullParser::skipElement() { if (_lastToken != TokenStartElement) { return true; } PRIME_ASSERT(!_elements.empty()); for (int nest = 1;;) { int token = read(); if (token == TokenError) { return false; } // TokenEOF shouldn't happen since we think we're inside an element. if (token == TokenEOF) { return setErrorReturnFalse(ErrorUnexpectedEndOfFile); } if (token == TokenEndElement) { if (!--nest) { return true; } } if (token == TokenStartElement) { ++nest; } } } bool XMLPullParser::skipEmptyElement() { if (_lastToken != TokenStartElement) { return true; } PRIME_ASSERT(!_elements.empty()); for (;;) { int token = read(); if (token == TokenError) { return false; } // TokenEOF shouldn't happen since we think we're inside an element. if (token == TokenEOF) { return setErrorReturnFalse(ErrorUnexpectedEndOfFile); } if (token == TokenEndElement) { return true; } if (token == TokenStartElement || (token == TokenText && !IsXMLWhitespace(getText(), isLenient()))) { // TODO: In Lenient mode, this could just be a warning? return setErrorReturnFalse(ErrorExpectedEmptyElement); } } } bool XMLPullParser::isTextEntirelyWhitespace() const { return IsXMLWhitespace(_text, isLenient()); } // // XMLPullParser::StringTable // XMLPullParser::StringTable::~StringTable() { for (StringsSet::iterator iter = _strings.begin(); iter != _strings.end(); ++iter) { delete[] * iter; } _strings.clear(); } const char* XMLPullParser::StringTable::intern(const char* string) { StringsSet::iterator iter = _strings.lower_bound((char*)string); if (iter != _strings.end() && StringsEqual(*iter, string)) { return *iter; } StringsSet::const_iterator insertion = _strings.insert(iter, NewString(string)); return *insertion; } const char* XMLPullParser::StringTable::intern(const char* string, size_t len) { _internBuffer.assign(string, string + len); return intern(_internBuffer.c_str()); } }
26.397293
162
0.534587
malord
ffc979b01d6bfe8c61531f6e775cb1c8fa1a36df
9,168
cpp
C++
Gems/PhysX/Code/Editor/EditorSubComponentModeSnap.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
1
2021-07-19T23:54:05.000Z
2021-07-19T23:54:05.000Z
Gems/PhysX/Code/Editor/EditorSubComponentModeSnap.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
null
null
null
Gems/PhysX/Code/Editor/EditorSubComponentModeSnap.cpp
Schneidex69/o3de
d9ec159f0e07ff86957e15212232413c4ff4d1dc
[ "Apache-2.0", "MIT" ]
null
null
null
/* * Copyright (c) Contributors to the Open 3D Engine Project. * For complete copyright and license terms please see the LICENSE at the root of this distribution. * * SPDX-License-Identifier: Apache-2.0 OR MIT * */ #include <PhysX_precompiled.h> #include <AzCore/Component/TransformBus.h> #include <AzToolsFramework/API/ComponentEntitySelectionBus.h> #include <AzToolsFramework/Manipulators/LinearManipulator.h> #include <AzToolsFramework/ViewportSelection/EditorSelectionUtil.h> #include <Editor/EditorJointComponentMode.h> #include <Editor/EditorSubComponentModeSnap.h> #include <PhysX/EditorJointBus.h> #include <Source/Utils.h> namespace PhysX { EditorSubComponentModeSnap::EditorSubComponentModeSnap( const AZ::EntityComponentIdPair& entityComponentIdPair , const AZ::Uuid& componentType , const AZStd::string& name) : EditorSubComponentModeBase(entityComponentIdPair, componentType, name) { AZ::Transform worldTransform = PhysX::Utils::GetEntityWorldTransformWithoutScale(m_entityComponentId.GetEntityId()); AZ::Transform localTransform = AZ::Transform::CreateIdentity(); EditorJointRequestBus::EventResult( localTransform, m_entityComponentId , &EditorJointRequests::GetTransformValue , PhysX::EditorJointComponentMode::s_parameterTransform); m_manipulator = AzToolsFramework::LinearManipulator::MakeShared(worldTransform); m_manipulator->AddEntityComponentIdPair(m_entityComponentId); m_manipulator->SetAxis(AZ::Vector3::CreateAxisX()); m_manipulator->SetLocalTransform(localTransform); Refresh(); const AZ::Color manipulatorColor(0.3f, 0.3f, 0.3f, 1.0f); const float manipulatorSize = 0.05f; AzToolsFramework::ManipulatorViews views; views.emplace_back(AzToolsFramework::CreateManipulatorViewQuadBillboard(manipulatorColor , manipulatorSize)); m_manipulator->SetViews(AZStd::move(views)); } void EditorSubComponentModeSnap::HandleMouseInteraction( const AzToolsFramework::ViewportInteraction::MouseInteractionEvent& mouseInteraction) { if (mouseInteraction.m_mouseEvent == AzToolsFramework::ViewportInteraction::MouseEvent::Move) { const int viewportId = mouseInteraction.m_mouseInteraction.m_interactionId.m_viewportId; const AzFramework::CameraState cameraState = AzToolsFramework::GetCameraState(viewportId); m_pickedEntity = m_picker.PickEntity(cameraState, mouseInteraction, m_pickedPosition, m_pickedEntityAabb); if (m_pickedEntity.IsValid()) { AZ::Transform worldTransform = PhysX::Utils::GetEntityWorldTransformWithoutScale(m_entityComponentId.GetEntityId()); const AZ::Quaternion worldRotate = worldTransform.GetRotation(); const AZ::Quaternion worldRotateInv = worldRotate.GetInverseFull(); m_manipulator->SetLocalPosition(worldRotateInv.TransformVector(m_pickedPosition - worldTransform.GetTranslation())); m_manipulator->SetBoundsDirty(); } } } void EditorSubComponentModeSnap::Refresh() { AZ::Transform localTransform = AZ::Transform::CreateIdentity(); EditorJointRequestBus::EventResult( localTransform, m_entityComponentId , &EditorJointRequests::GetTransformValue , PhysX::EditorJointComponentMode::s_parameterTransform); m_manipulator->SetLocalTransform(localTransform); } void EditorSubComponentModeSnap::DisplayEntityViewport( const AzFramework::ViewportInfo& viewportInfo, AzFramework::DebugDisplayRequests& debugDisplay) { AZ::u32 stateBefore = debugDisplay.GetState(); AZ::Vector3 position = GetPosition(); AZ::Transform worldTransform = PhysX::Utils::GetEntityWorldTransformWithoutScale(m_entityComponentId.GetEntityId()); AZ::Transform localTransform = AZ::Transform::CreateIdentity();; EditorJointRequestBus::EventResult( localTransform, m_entityComponentId , &EditorJointRequests::GetTransformValue , PhysX::EditorJointComponentMode::s_parameterTransform); debugDisplay.PushMatrix(worldTransform); debugDisplay.PushMatrix(localTransform); const float xAxisLineLength = 15.0f; const float yzAxisArrowLength = 1.0f; debugDisplay.SetColor(AZ::Color(1.0f, 0.0f, 0.0f, 1.0f)); debugDisplay.DrawLine(AZ::Vector3(0.0f, 0.0f, 0.0f), AZ::Vector3(xAxisLineLength, 0.0f, 0.0f)); AngleLimitsFloatPair yzSwingAngleLimits; EditorJointRequestBus::EventResult( yzSwingAngleLimits, m_entityComponentId , &EditorJointRequests::GetLinearValuePair , PhysX::EditorJointComponentMode::s_parameterSwingLimit); const AZ::u32 numEllipseSamples = 16; AZStd::array<AZ::Vector3, numEllipseSamples> ellipseSamples; float coneHeight = 3.0f; // Draw inverted cone if angles are larger than 90 deg. if (yzSwingAngleLimits.first > 90.0f || yzSwingAngleLimits.second > 90.0f) { coneHeight = -3.0f; } // Compute points along perimeter of cone base const float coney = tan(AZ::DegToRad(yzSwingAngleLimits.first)) * coneHeight; const float conez = tan(AZ::DegToRad(yzSwingAngleLimits.second)) * coneHeight; const float step = AZ::Constants::TwoPi / numEllipseSamples; for (size_t i = 0; i < numEllipseSamples; ++i) { const float angleStep = step * i; ellipseSamples[i].SetX(coneHeight); ellipseSamples[i].SetY(conez * sin(angleStep)); ellipseSamples[i].SetZ(coney * cos(angleStep)); } // draw cone for (size_t i = 0; i < numEllipseSamples; ++i) { size_t nextIndex = i + 1; if (i == numEllipseSamples - 1) { nextIndex = 0; } // draw cone sides debugDisplay.SetColor(AZ::Color(1.0f, 1.0f, 1.0f, 0.2f)); debugDisplay.DrawTri(AZ::Vector3(0.0f, 0.0f, 0.0f), ellipseSamples[i], ellipseSamples[nextIndex]); // draw parameter of cone base debugDisplay.SetColor(AZ::Color(0.4f, 0.4f, 0.4f, 0.4f)); debugDisplay.DrawLine(ellipseSamples[i], ellipseSamples[nextIndex]); } // draw axis lines at base of cone, and from tip to base. debugDisplay.SetColor(AZ::Color(0.5f, 0.5f, 0.5f, 0.6f)); debugDisplay.DrawLine(ellipseSamples[0], ellipseSamples[numEllipseSamples / 2]); debugDisplay.DrawLine(ellipseSamples[numEllipseSamples * 3 / 4], ellipseSamples[numEllipseSamples / 4]); debugDisplay.DrawLine(AZ::Vector3(0.0f, 0.0f, 0.0f), AZ::Vector3(coneHeight, 0.0f, 0.0f)); debugDisplay.PopMatrix();//pop local transform debugDisplay.PopMatrix();//pop world transform // draw line from joint to mouse-over entity if (m_pickedEntity.IsValid()) { const AZ::Vector3 direction = (m_pickedPosition - position); const float directionLength = direction.GetLength(); const AZ::Vector3 directionNorm = direction.GetNormalized(); const float LineExtend = 1.0f; ///< Distance snap line extends beyond the snapped entity when drawn. const AZ::Color lineColor(0.0f, 1.0f, 0.0f, 1.0f); debugDisplay.SetColor(lineColor); debugDisplay.DrawLine(position, position + (directionNorm * (directionLength + LineExtend))); debugDisplay.DrawWireBox(m_pickedEntityAabb.GetMin(), m_pickedEntityAabb.GetMax()); // draw something, e.g. an icon, to indicate type of snapping DisplaySpecificSnapType(viewportInfo, debugDisplay, position, directionNorm, directionLength); } debugDisplay.SetState(stateBefore); } AZStd::string EditorSubComponentModeSnap::GetPickedEntityName() { AZStd::string pickedEntityName; if (m_pickedEntity.IsValid()) { AZ::ComponentApplicationBus::BroadcastResult(pickedEntityName, &AZ::ComponentApplicationRequests::GetEntityName, m_pickedEntity); } return pickedEntityName; } AZ::Vector3 EditorSubComponentModeSnap::GetPosition() const { AZ::Transform worldTransform = PhysX::Utils::GetEntityWorldTransformWithoutScale(m_entityComponentId.GetEntityId()); AZ::Quaternion worldRotate = worldTransform.GetRotation(); AZ::Transform localTransform = AZ::Transform::CreateIdentity(); EditorJointRequestBus::EventResult( localTransform, m_entityComponentId , &EditorJointRequests::GetTransformValue , PhysX::EditorJointComponentMode::s_parameterTransform); return worldTransform.GetTranslation() + worldRotate.TransformVector(localTransform.GetTranslation()); } } // namespace PhysX
42.444444
132
0.673757
Schneidex69
ffcbfd889ee9e227f648268446c050fbe2c9a90f
3,403
cpp
C++
src/options.cpp
caetanosauer/fineline
03423d7f926435a01c2f0f2264763a11c8f332ce
[ "MIT" ]
null
null
null
src/options.cpp
caetanosauer/fineline
03423d7f926435a01c2f0f2264763a11c8f332ce
[ "MIT" ]
null
null
null
src/options.cpp
caetanosauer/fineline
03423d7f926435a01c2f0f2264763a11c8f332ce
[ "MIT" ]
null
null
null
/* * MIT License * * Copyright (c) 2016 Caetano Sauer * * 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 "options.h" #include <mutex> #include <fstream> namespace fineline { using std::string; void Options::init_description(popt::options_description& opt) { opt.add_options() /* General log manager options */ ("logpath,l", popt::value<string>()->default_value("log"), "Path in which log is stored (directory if file-based)") ("format", popt::value<bool>()->default_value(false)->implicit_value(true), "Whether to format the log, deleting all existing log files or blocks") ("log_recycle", popt::value<bool>()->default_value(false)->implicit_value(true), "Whether to clean-up log by deleting old files/partitions") /* File-based log (legacy::log_storage) options */ ("log_file_size", popt::value<unsigned>()->default_value(1024), "Maximum size of a log file (in MB)") ("log_max_files", popt::value<unsigned>()->default_value(0), "Maximum number of log files to maintain (0 = unlimited)") ("log_index_path", popt::value<string>()->default_value("index.db"), "Path to log index file") ("log_index_path_relative", popt::value<bool>()->default_value(true), "Whether log index path is relative to logpath or absolute") ; } popt::options_description& Options::get_description() { /* * This code makes sure that the descriptions are initialized only once. * After that, all callers will get the same descriptions, regardless of * multi-threaded schedules. */ static std::once_flag init_once_flag; static popt::options_description desc; std::call_once(init_once_flag, init_description, std::ref(desc)); return desc; } Options::Options() { // Initialize with default option values int argc = 0; char* ptr = nullptr; popt::store(popt::parse_command_line(argc, &ptr, get_description()), map_); } Options::Options(int argc, char** argv) { popt::store(popt::parse_command_line(argc, argv, get_description()), map_); } Options::Options(string config_file) { parse_from_file(config_file); } void Options::parse_from_file(string path) { std::ifstream is {path}; popt::store(popt::parse_config_file(is, get_description(), true), map_); } } // namespace fineline
36.98913
100
0.702615
caetanosauer
ffcca59c0d434917aacb28c47ea980f3a3328fa1
2,382
cc
C++
src/minion/executor_reduce.cc
abael/Baidu-Bigdata-shuttle
32bf24cf74d4cd47587436ea96050aa795fd92cd
[ "BSD-3-Clause" ]
69
2015-10-23T04:16:24.000Z
2021-09-10T09:49:36.000Z
src/minion/executor_reduce.cc
abael/Baidu-Bigdata-shuttle
32bf24cf74d4cd47587436ea96050aa795fd92cd
[ "BSD-3-Clause" ]
3
2015-11-13T11:43:20.000Z
2016-05-19T10:34:24.000Z
src/minion/executor_reduce.cc
fxsjy/shuttle
d421d7248376cdb5fbd1ea9bd5de556d0c63cc70
[ "BSD-3-Clause" ]
33
2015-10-20T17:10:34.000Z
2021-10-12T11:48:22.000Z
#include "executor.h" #include <unistd.h> #include <errno.h> #include <boost/scoped_ptr.hpp> #include "common/filesystem.h" namespace baidu { namespace shuttle { ReduceExecutor::ReduceExecutor() { ::setenv("mapred_task_is_map", "false", 1); } ReduceExecutor::~ReduceExecutor() { } TaskState ReduceExecutor::Exec(const TaskInfo& task) { LOG(INFO, "exec reduce task"); ::setenv("mapred_work_output_dir", GetReduceWorkDir(task).c_str(), 1); std::string cmd = "sh ./app_wrapper.sh \"" + task.job().reduce_command() + "\""; LOG(INFO, "reduce command is: %s", cmd.c_str()); FILE* user_app = popen(cmd.c_str(), "r"); if (user_app == NULL) { LOG(WARNING, "start user app fail, cmd is %s, (%s)", cmd.c_str(), strerror(errno)); return kTaskFailed; } FileSystem::Param param; FillParam(param, task); const std::string temp_file_name = GetReduceWorkFilename(task); if (task.job().output_format() == kTextOutput) { TaskState status = TransTextOutput(user_app, temp_file_name, param, task); if (status != kTaskCompleted) { return status; } } else if (task.job().output_format() == kBinaryOutput) { TaskState status = TransBinaryOutput(user_app, temp_file_name, param, task); if (status != kTaskCompleted) { return status; } } else if (task.job().output_format() == kSuffixMultipleTextOutput) { TaskState status = TransMultipleTextOutput(user_app, temp_file_name, param, task); if (status != kTaskCompleted) { return status; } } else { LOG(FATAL, "unknown output format"); } int ret = pclose(user_app); if (ret != 0) { LOG(WARNING, "user app fail, cmd is %s, ret: %d", cmd.c_str(), ret); return kTaskFailed; } FileSystem* fs = FileSystem::CreateInfHdfs(param); boost::scoped_ptr<FileSystem> fs_guard(fs); if (task.job().output_format() == kSuffixMultipleTextOutput) { if (!MoveMultipleTempToOutput(task, fs, false)) { LOG(WARNING, "fail to move multiple output"); return kTaskMoveOutputFailed; } } else { if (!MoveTempToOutput(task, fs, false)) { LOG(WARNING, "fail to move output"); return kTaskMoveOutputFailed; } } return kTaskCompleted; } } }
31.76
90
0.616289
abael
ffceb64ad0844a4e19e637c4f1f6311104cdfb74
10,308
cpp
C++
raygame/Player.cpp
DynashEtvala/Splat2D
44a296a834e5f1def9ef100f1b650174fcfe0d05
[ "MIT" ]
null
null
null
raygame/Player.cpp
DynashEtvala/Splat2D
44a296a834e5f1def9ef100f1b650174fcfe0d05
[ "MIT" ]
null
null
null
raygame/Player.cpp
DynashEtvala/Splat2D
44a296a834e5f1def9ef100f1b650174fcfe0d05
[ "MIT" ]
null
null
null
#include "Player.h" #include "Math.h" #include "Controller.h" #include "FloorTile.h" #include "SpawnPad.h" #include <math.h> Player::Player() { weap = BASE_GUN; speed = weap.walkSpeed; teamColor = BLACK; playerNumber = 0; } Player::Player(Vector2 start, Weapon w, Color tcol, Color ecol, int pnum) { static Texture2D _body = LoadTexture("Sprites/tankBeige_outline.png"); static Texture2D _barrel = LoadTexture("Sprites/barrelBeige_outline.png"); body = _body; barrel = _barrel; weap = w; speed = weap.walkSpeed; teamColor = tcol; enemyColor = ecol; playerNumber = pnum; alive = true; bodyRect1 = Rectangle{ 0, 0, (float)(body.width), (float)(body.height) }; bodyRect2 = Rectangle{ start.x, start.y, 35, 35}; barrelRect1 = Rectangle{ 0, 0, (float)(barrel.width), (float)(barrel.height) }; barrelRect2 = Rectangle{ start.x, start.y, 8, 22 }; } Player::~Player() {} void Player::Update(Controller* controller, FloorTile*** ftile, SpawnPad * pads, Rectangle * walls, Rectangle * pits) { if (alive) { swimming = false; if (speed != weap.walkSpeed) { speed = weap.walkSpeed; } //healing + enemy ink damage if (pointOnScreen((int)(getCenter().x), (int)(getCenter().y)) && ftile[(int)(getCenter().y)][(int)(getCenter().x)]->color == enemyColor) { Damaged(0.05f, controller, ftile); } else if (timeSinceDamaged < 2.5f) { timeSinceDamaged += GetFrameTime(); } else if(currHealth < maxHealth) { currHealth += GetFrameTime() * 40; if (currHealth > maxHealth) { currHealth = maxHealth; } } if (dirBody.x != 0 && dirBody.y != 0) { lastDirBody = NormalizeVector(dirBody); } dirBody = Vector2{ GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_LEFT_X), GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_LEFT_Y) }; if (VectorLength(dirBody) < 0.1) { dirBody = Vector2{ 0, 0 }; } if (dirBarrel.x != 0 && dirBarrel.y != 0) { lastDirBarrel = dirBarrel; } dirBarrel = Vector2{ GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_RIGHT_X), GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_RIGHT_Y) }; if (VectorLength(dirBarrel) < 0.1) { dirBarrel = Vector2{ 0, 0 }; } NormalizeVector(&dirBarrel); // shooting if (GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_RT) > 0.2f && (dirBarrel.y != 0 || dirBarrel.x != 0)) { speed = weap.shootingSpeed; if (fireTimer >= weap.fireRate && ammo > weap.ammoConsume && VectorLength(dirBarrel) > 0.1) { controller->addShot(Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, 10, 10 }, NormalizeVector(dirBarrel + Vector2{GetRandomValue( -weap.accuracy, weap.accuracy) * 0.01f, GetRandomValue(-weap.accuracy, weap.accuracy) * 0.01f }), weap.bulletSpeed, weap.damage, weap.range, weap.burstSize, weap.dripSize, teamColor); ammo -= weap.ammoConsume; fireTimer = 0; } reloadTimer = 0; } else if (GetGamepadAxisMovement(playerNumber, GAMEPAD_XBOX_AXIS_LT) > 0.2f) { swimming = true; if (ftile[(int)(getCenter().y)][(int)(getCenter().x)]->color == teamColor) { speed = swimSpeed; reloadTimer = 5; ammo += 20 * GetFrameTime(); } else { speed = drySwimSpeed; } } if (pointOnScreen((int)(getCenter().x), (int)(getCenter().y)) && ftile[(int)(getCenter().y)][(int)(getCenter().x)]->color == enemyColor) { speed = enemyInkSpeed; } if (fireTimer < weap.fireRate) { fireTimer += GetFrameTime(); } if (reloadTimer < 1) { reloadTimer += GetFrameTime(); } else { if (ammo < 100) { ammo += 20 * GetFrameTime(); } if (ammo > 100) { ammo = 100; } } // movement if (VectorLength(dirBody) >= 0.1) { barrelRect2.x = bodyRect2.x += dirBody.x * speed * GetFrameTime(); barrelRect2.y = bodyRect2.y += dirBody.y * speed * GetFrameTime(); for (int i = 0; i < maxObsticles; i++) { if (CheckCollisionPointRec(getCenter(), pits[i])) { currHealth = 0; barrelRect2.x = bodyRect2.x = -100; barrelRect2.y = bodyRect2.y = -100; alive = false; } } for (int i = 0; i < maxObsticles; i++) { if (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { switch (sideOfRect(walls[i])) { case LEFT: barrelRect2.x = bodyRect2.x = walls[i].x - bodyRect2.width + 0.83f; break; case RIGHT: barrelRect2.x = bodyRect2.x = walls[i].x + walls[i].width; break; case UP: barrelRect2.y = bodyRect2.y = walls[i].y - bodyRect2.height + 0.83f; break; case DOWN: barrelRect2.y = bodyRect2.y = walls[i].y + walls[i].height; break; case TOPLEFT: if (dirBody.x < dirBody.y) { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.y--; } barrelRect2.y = bodyRect2.y += 1 - (bodyRect2.y - (int)(bodyRect2.y)); } else { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.x--; } barrelRect2.x = bodyRect2.x += 1 - (bodyRect2.x - (int)(bodyRect2.x)); } break; case TOPRIGHT: if (dirBody.x * -1 < dirBody.y) { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.y--; } barrelRect2.y = bodyRect2.y += 1 - (bodyRect2.y - (int)(bodyRect2.y)); } else { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.x++; } bodyRect2.x -= bodyRect2.x - (int)(bodyRect2.x); } break; case BOTTOMLEFT: if (dirBody.x < dirBody.y * -1) { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.y++; } bodyRect2.y -= bodyRect2.y - (int)(bodyRect2.y); } else { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.x--; } barrelRect2.x = bodyRect2.x += 1 - (bodyRect2.x - (int)(bodyRect2.x)); } break; case BOTTOMRIGHT: if (dirBody.x * -1 < dirBody.y * -1) { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.y++; } bodyRect2.y -= bodyRect2.y - (int)(bodyRect2.y); } else { while (CheckCollisionCircleRec(getCenter(), getRadius(), walls[i])) { bodyRect2.x++; } bodyRect2.x -= bodyRect2.x - (int)(bodyRect2.x); } break; default: case CENTER: bodyRect2.x -= dirBody.x * speed * GetFrameTime(); bodyRect2.y -= dirBody.y * speed * GetFrameTime(); break; } } } } } else { if (timeSinceDamaged < 5) { timeSinceDamaged += GetFrameTime(); } else if (currHealth < maxHealth) { currHealth += GetFrameTime() * 25; if (currHealth > maxHealth) { currHealth = maxHealth; Vector2 spawn = pads[playerNumber % 2].spawnSpaces[playerNumber/2]; barrelRect2.x = bodyRect2.x = spawn.x; barrelRect2.y = bodyRect2.y = spawn.y; ammo = 100; alive = true; } } } } void Player::Draw() { if (!swimming) { if (dirBody.x != 0 && dirBody.y != 0) { Vector2 norm = NormalizeVector(dirBody); float rot = -atan2f(norm.x, norm.y) * 180 / PI; DrawTexturePro(body, bodyRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, bodyRect2.width, bodyRect2.height }, Vector2{ bodyRect2.width / 2, bodyRect2.height / 2 }, rot - 180, teamColor); } else { Vector2 norm = NormalizeVector(lastDirBody); float rot = -atan2f(norm.x, norm.y) * 180 / PI; DrawTexturePro(body, bodyRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, bodyRect2.width, bodyRect2.height }, Vector2{ bodyRect2.width / 2, bodyRect2.height / 2 }, rot - 180, teamColor); } } if (dirBarrel.x != 0 && dirBarrel.y != 0) { Vector2 norm = NormalizeVector(dirBarrel); float rot = -atan2f(norm.x, norm.y) * 180 / PI; DrawTexturePro(barrel, barrelRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, barrelRect2.width, barrelRect2.height }, Vector2{ barrelRect2.width / 2, barrelRect2.height }, rot - 180, teamColor); } else { Vector2 norm = NormalizeVector(lastDirBarrel); float rot = -atan2f(norm.x, norm.y) * 180 / PI; DrawTexturePro(barrel, barrelRect1, Rectangle{ bodyRect2.x + bodyRect2.width / 2, bodyRect2.y + bodyRect2.height / 2, barrelRect2.width, barrelRect2.height }, Vector2{ barrelRect2.width / 2, barrelRect2.height }, rot - 180, teamColor); } DrawRectangle(bodyRect2.x + bodyRect2.width, bodyRect2.y, 10, 35, BLACK); DrawRectangle(bodyRect2.x + bodyRect2.width + 1, bodyRect2.y + 1, 8, 33, WHITE); DrawRectangle(bodyRect2.x + bodyRect2.width + 1, bodyRect2.y + 34 - ammo * 0.33f, 8, ammo * 0.33f, teamColor); } void Player::Damaged(float dmg, Controller* controller, FloorTile*** ftile) { if (alive) { timeSinceDamaged = 0; currHealth -= dmg; if (currHealth <= 0) { currHealth = 0; controller->paintFloor(getCenter(), deathPopSize, enemyColor, ftile); barrelRect2.x = bodyRect2.x = -100; barrelRect2.y = bodyRect2.y = -100; alive = false; } } } float Player::GetHealth() { return currHealth; } Direction Player::sideOfRect(Rectangle r) { if (getCenter().x < r.x) { if (getCenter().y < r.y) { return TOPLEFT; } else if (getCenter().y > r.y + r.height) { return BOTTOMLEFT; } return LEFT; } else if (getCenter().x > r.x + r.width) { if (getCenter().y < r.y) { return TOPRIGHT; } else if (getCenter().y > r.y + r.height) { return BOTTOMRIGHT; } return RIGHT; } else if (getCenter().y < r.y) { return UP; } else if (getCenter().y > r.y + r.height) { return DOWN; } else { return CENTER; } } Vector2 Player::getCenter() { return Vector2{ bodyRect2.x + getRadius(), bodyRect2.y + getRadius() }; } float Player::getRadius() { return bodyRect2.height < bodyRect2.width ? bodyRect2.height / 2 : bodyRect2.width / 2; } bool Player::pointOnScreen(int x, int y) { if (x >= 0 && x < screenWidth && y >= 0 && y < screenHeight) { return true; } return false; }
26.162437
351
0.617385
DynashEtvala
ffd11be073bb8c2c76d0c3ee2ae642530a73ba20
8,268
cpp
C++
endless-tunnel/app/src/main/cpp/shader.cpp
jiangkang/ndk-samples
0ae8b60d9920753b17bac9da40752eda87154a86
[ "Apache-2.0" ]
2,727
2019-09-26T02:10:17.000Z
2022-03-31T20:12:09.000Z
endless-tunnel/app/src/main/cpp/shader.cpp
jiangkang/ndk-samples
0ae8b60d9920753b17bac9da40752eda87154a86
[ "Apache-2.0" ]
161
2019-10-27T13:59:36.000Z
2022-03-18T02:02:31.000Z
endless-tunnel/app/src/main/cpp/shader.cpp
jiangkang/ndk-samples
0ae8b60d9920753b17bac9da40752eda87154a86
[ "Apache-2.0" ]
1,210
2019-09-26T14:03:49.000Z
2022-03-30T07:00:51.000Z
/* * Copyright (C) Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common.hpp" #include "indexbuf.hpp" #include "shader.hpp" #include "vertexbuf.hpp" Shader::Shader() { mVertShaderH = mFragShaderH = mProgramH = 0; mMVPMatrixLoc = -1; mPositionAttribLoc = -1; mPreparedVertexBuf = NULL; } Shader::~Shader() { if (mVertShaderH) { glDeleteShader(mVertShaderH); mVertShaderH = 0; } if (mFragShaderH) { glDeleteShader(mFragShaderH); mFragShaderH = 0; } if (mProgramH) { glDeleteProgram(mProgramH); mProgramH = 0; } } static void _printShaderLog(GLuint shader) { char buf[2048]; memset(buf, 0, sizeof(buf)); LOGE("*** Getting info log for shader %u", shader); glGetShaderInfoLog(shader, sizeof(buf) - 1, NULL, buf); LOGE("*** Info log:\n%s", buf); } static void _printProgramLog(GLuint program) { char buf[2048]; memset(buf, 0, sizeof(buf)); LOGE("*** Getting info log for program %u", program); glGetProgramInfoLog(program, sizeof(buf) - 1, NULL, buf); LOGE("*** Info log:\n%s", buf); } void Shader::Compile() { const char *vsrc = 0, *fsrc = 0; GLint status = 0; LOGD("Compiling shader."); LOGD("Shader name: %s", GetShaderName()); vsrc = GetVertShaderSource(); fsrc = GetFragShaderSource(); mVertShaderH = glCreateShader(GL_VERTEX_SHADER); mFragShaderH = glCreateShader(GL_FRAGMENT_SHADER); if (!mVertShaderH || !mFragShaderH) { LOGE("*** Failed to create shader."); ABORT_GAME; } glShaderSource(mVertShaderH, 1, &vsrc, NULL); glCompileShader(mVertShaderH); glGetShaderiv(mVertShaderH, GL_COMPILE_STATUS, &status); if (status == 0) { LOGE("*** Vertex shader compilation failed."); _printShaderLog(mVertShaderH); ABORT_GAME; } LOGD("Vertex shader compilation succeeded."); glShaderSource(mFragShaderH, 1, &fsrc, NULL); glCompileShader(mFragShaderH); glGetShaderiv(mFragShaderH, GL_COMPILE_STATUS, &status); if (status == 0) { LOGE("*** Fragment shader compilation failed, %d", status); _printShaderLog(mFragShaderH); ABORT_GAME; } LOGD("Fragment shader compilation succeeded."); mProgramH = glCreateProgram(); if (!mProgramH) { LOGE("*** Failed to create program"); _printProgramLog(mProgramH); ABORT_GAME; } glAttachShader(mProgramH, mVertShaderH); glAttachShader(mProgramH, mFragShaderH); glLinkProgram(mProgramH); glGetProgramiv(mProgramH, GL_LINK_STATUS, &status); if (status == 0) { LOGE("*** Shader program link failed, %d", status); _printProgramLog(mProgramH); ABORT_GAME; } LOGD("Program linking succeeded."); glUseProgram(mProgramH); mMVPMatrixLoc = glGetUniformLocation(mProgramH, "u_MVP"); if (mMVPMatrixLoc < 0) { LOGE("*** Couldn't get shader's u_MVP matrix location from shader."); ABORT_GAME; } mPositionAttribLoc = glGetAttribLocation(mProgramH, "a_Position"); if (mPositionAttribLoc < 0) { LOGE("*** Couldn't get shader's a_Position attribute location."); ABORT_GAME; } LOGD("Shader compilation/linking successful."); glUseProgram(0); } void Shader::BindShader() { if (mProgramH == 0) { LOGW("!!! WARNING: attempt to use shader before compiling."); LOGW("!!! Compiling now. Shader: %s", GetShaderName()); Compile(); } glUseProgram(mProgramH); } void Shader::UnbindShader() { glUseProgram(0); } // To be called by child classes only. void Shader::PushMVPMatrix(glm::mat4 *mat) { MY_ASSERT(mMVPMatrixLoc >= 0); glUniformMatrix4fv(mMVPMatrixLoc, 1, GL_FALSE, glm::value_ptr(*mat)); } // To be called by child classes only. void Shader::PushPositions(int vbo_offset, int stride) { MY_ASSERT(mPositionAttribLoc >= 0); glVertexAttribPointer(mPositionAttribLoc, 3, GL_FLOAT, GL_FALSE, stride, BUFFER_OFFSET(vbo_offset)); glEnableVertexAttribArray(mPositionAttribLoc); } void Shader::BeginRender(VertexBuf *vbuf) { // Activate shader BindShader(); // bind geometry's VBO vbuf->BindBuffer(); // push positions to shader PushPositions(vbuf->GetPositionsOffset(), vbuf->GetStride()); // store geometry mPreparedVertexBuf = vbuf; } void Shader::Render(IndexBuf *ibuf, glm::mat4* mvpMat) { MY_ASSERT(mPreparedVertexBuf != NULL); // push MVP matrix to shader PushMVPMatrix(mvpMat); if (ibuf) { // draw with index buffer ibuf->BindBuffer(); glDrawElements(mPreparedVertexBuf->GetPrimitive(), ibuf->GetCount(), GL_UNSIGNED_SHORT, BUFFER_OFFSET(0)); ibuf->UnbindBuffer(); } else { // draw straight from vertex buffer glDrawArrays(mPreparedVertexBuf->GetPrimitive(), 0, mPreparedVertexBuf->GetCount()); } } void Shader::EndRender() { if (mPreparedVertexBuf) { mPreparedVertexBuf->UnbindBuffer(); mPreparedVertexBuf = NULL; } } TrivialShader::TrivialShader() : Shader() { mColorLoc = -1; mTintLoc = -1; mTint[0] = mTint[1] = mTint[2] = 1.0f; // white } TrivialShader::~TrivialShader() { } void TrivialShader::Compile() { Shader::Compile(); BindShader(); mColorLoc = glGetAttribLocation(mProgramH, "a_Color"); if (mColorLoc < 0) { LOGE("*** Couldn't get color attrib location from shader."); ABORT_GAME; } mTintLoc = glGetUniformLocation(mProgramH, "u_Tint"); if (mTintLoc < 0) { LOGE("*** Couldn't get tint uniform location from shader."); ABORT_GAME; } UnbindShader(); } const char* TrivialShader::GetVertShaderSource() { return "uniform mat4 u_MVP; \n" "uniform vec4 u_Tint; \n" "attribute vec4 a_Position; \n" "attribute vec4 a_Color; \n" "varying vec4 v_Color; \n" "void main() \n" "{ \n" " v_Color = a_Color * u_Tint; \n" " gl_Position = u_MVP \n" " * a_Position; \n" "} \n"; } const char* TrivialShader::GetFragShaderSource() { return "precision mediump float; \n" "varying vec4 v_Color; \n" "void main() \n" "{ \n" " gl_FragColor = v_Color; \n" "}"; } int TrivialShader::GetColorAttribLoc() { return mColorLoc; } const char* TrivialShader::GetShaderName() { return "TrivialShader"; } void TrivialShader::ResetTintColor() { SetTintColor(1.0f, 1.0f, 1.0f); } void TrivialShader::SetTintColor(float r, float g, float b) { mTint[0] = r; mTint[1] = g; mTint[2] = b; if (mPreparedVertexBuf) { // we are in the middle of rendering, so push the new tint color to // the shader right away. glUniform4f(mTintLoc, mTint[0], mTint[1], mTint[2], 1.0f); } } void TrivialShader::BeginRender(VertexBuf *geom) { // let superclass do the basic work Shader::BeginRender(geom); // this shader requires colors, so make sure we have them. MY_ASSERT(geom->HasColors()); MY_ASSERT(mColorLoc >= 0); // push colors to shader glVertexAttribPointer(mColorLoc, 3, GL_FLOAT, GL_FALSE, geom->GetStride(), BUFFER_OFFSET(geom->GetColorsOffset())); glEnableVertexAttribArray(mColorLoc); // push tint color to shader MY_ASSERT(mTintLoc >= 0); glUniform4f(mTintLoc, mTint[0], mTint[1], mTint[2], 1.0f); }
28.608997
95
0.620827
jiangkang
ffd4728dab690c58d52b3740b01e5c33e0c09047
556
cpp
C++
Competitive Programming/3rd day/sportMafia.cpp
Adrian-Garcia/CppLeetCodeSolutions
0b85d02fe60063655cb4f9118e829b17c9bc1ed4
[ "MIT" ]
null
null
null
Competitive Programming/3rd day/sportMafia.cpp
Adrian-Garcia/CppLeetCodeSolutions
0b85d02fe60063655cb4f9118e829b17c9bc1ed4
[ "MIT" ]
null
null
null
Competitive Programming/3rd day/sportMafia.cpp
Adrian-Garcia/CppLeetCodeSolutions
0b85d02fe60063655cb4f9118e829b17c9bc1ed4
[ "MIT" ]
null
null
null
#include<iostream> using namespace std; bool search(long long int val, long long int n, long long int k) { long long int total = 0; for(int i=0; i<n-val; i++) total += i+1; if(total-val > k) return true; else return false; } int main() { long long int n, k; cin >> n >> k; long long int low = 0; long long int big = n-1; long long int mid = low + (big - low)/2; while (big >= low) { mid = low + (big - low)/2; if(search(mid, n, k)) low = mid+1; else big = mid-1; } cout << low << endl; return 0; }
13.238095
66
0.552158
Adrian-Garcia
ffd7390f9b8f9ab2cf776fbcd187b4a6a79d3a4b
458
cpp
C++
C++/Maximizing XOR.cpp
karunagatiyala/hackerrank_problems-or-hackerearth_problems
645bb30465ee962733433a9a30fd5873b9fe33c2
[ "MIT" ]
1
2019-10-15T09:14:29.000Z
2019-10-15T09:14:29.000Z
C++/Maximizing XOR.cpp
karunagatiyala/hackerrank_problems-or-hackerearth_problems
645bb30465ee962733433a9a30fd5873b9fe33c2
[ "MIT" ]
5
2019-10-30T05:24:27.000Z
2019-10-30T05:28:03.000Z
C++/Maximizing XOR.cpp
karunagatiyala/hackerrank_problems-or-hackerearth_problems
645bb30465ee962733433a9a30fd5873b9fe33c2
[ "MIT" ]
10
2019-10-15T03:04:17.000Z
2019-10-29T18:39:11.000Z
#include <bits/stdc++.h> using namespace std; // Complete the maximizingXor function below. int maximizingXor(int l, int r) { } int main() { ofstream fout(getenv("OUTPUT_PATH")); int l; cin >> l; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int r; cin >> r; cin.ignore(numeric_limits<streamsize>::max(), '\n'); int result = maximizingXor(l, r); fout << result << "\n"; fout.close(); return 0; }
14.774194
56
0.591703
karunagatiyala
ffd7c5611d117c634e03300d639e4bca0455cf49
2,140
cpp
C++
drape_frontend/metaline_manager.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
drape_frontend/metaline_manager.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
drape_frontend/metaline_manager.cpp
smartyw/organicmaps
9b10eb9d3ed6833861cef294c2416cc98b15e10d
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#include "drape_frontend/metaline_manager.hpp" #include "drape_frontend/map_data_provider.hpp" #include "drape_frontend/message_subclasses.hpp" #include "drape_frontend/threads_commutator.hpp" #include "base/logging.hpp" #include <functional> namespace df { MetalineManager::MetalineManager(ref_ptr<ThreadsCommutator> commutator, MapDataProvider & model) : m_model(model) , m_commutator(commutator) {} MetalineManager::~MetalineManager() { Stop(); } void MetalineManager::Stop() { m_activeTasks.FinishAll(); } void MetalineManager::Update(std::set<MwmSet::MwmId> const & mwms) { std::lock_guard<std::mutex> lock(m_mwmsMutex); for (auto const & mwm : mwms) { auto const result = m_mwms.insert(mwm); if (!result.second) return; auto readingTask = std::make_shared<ReadMetalineTask>(m_model, mwm); auto routineResult = dp::DrapeRoutine::Run([this, readingTask]() { readingTask->Run(); OnTaskFinished(readingTask); }); if (routineResult) m_activeTasks.Add(readingTask, routineResult); } } m2::SharedSpline MetalineManager::GetMetaline(FeatureID const & fid) const { std::lock_guard<std::mutex> lock(m_metalineCacheMutex); auto const metalineIt = m_metalineCache.find(fid); if (metalineIt == m_metalineCache.end()) return m2::SharedSpline(); return metalineIt->second; } void MetalineManager::OnTaskFinished(std::shared_ptr<ReadMetalineTask> const & task) { if (task->IsCancelled()) return; std::lock_guard<std::mutex> lock(m_metalineCacheMutex); // Update metalines cache. auto const & metalines = task->GetMetalines(); for (auto const & metaline : metalines) m_metalineCache[metaline.first] = metaline.second; // Notify FR. if (!metalines.empty()) { LOG(LDEBUG, ("Metalines prepared:", task->GetMwmId())); m_commutator->PostMessage(ThreadsCommutator::RenderThread, make_unique_dp<UpdateMetalinesMessage>(), MessagePriority::Normal); } // Remove task from active ones. m_activeTasks.Remove(task); } } // namespace df
25.47619
84
0.690654
smartyw
ffda05a12aae3a915f386d16577289974c4d811f
10,998
cpp
C++
SDK/Samples/Plugins/Monitoring/AIDA64/AIDA64SetupSourceDlg.cpp
tjca1/MSI-Afterburner
5bbac4a0af16be326b1f2886ae016ca0a54487e8
[ "MIT" ]
null
null
null
SDK/Samples/Plugins/Monitoring/AIDA64/AIDA64SetupSourceDlg.cpp
tjca1/MSI-Afterburner
5bbac4a0af16be326b1f2886ae016ca0a54487e8
[ "MIT" ]
1
2021-11-21T01:40:59.000Z
2021-11-21T01:40:59.000Z
SDK/Samples/Plugins/Monitoring/AIDA64/AIDA64SetupSourceDlg.cpp
tjca1/MSI-Afterburner
5bbac4a0af16be326b1f2886ae016ca0a54487e8
[ "MIT" ]
1
2021-12-25T03:40:50.000Z
2021-12-25T03:40:50.000Z
// AIDA64SetupSourceDlg.cpp : implementation file // // created by Unwinder ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "AIDA64SetupSourceDlg.h" #include "AIDA64Globals.h" #include "MAHMSharedMemory.h" ////////////////////////////////////////////////////////////////////// // CAIDA64SetupSourceDlg dialog ////////////////////////////////////////////////////////////////////// IMPLEMENT_DYNAMIC(CAIDA64SetupSourceDlg, CDialog) ////////////////////////////////////////////////////////////////////// CAIDA64SetupSourceDlg::CAIDA64SetupSourceDlg(CWnd* pParent /*=NULL*/) : CDialog(CAIDA64SetupSourceDlg::IDD, pParent) , m_strSensorID(_T("")) , m_strReadingName(_T("")) , m_strSourceInstance(_T("")) , m_strSourceName(_T("")) , m_strSourceUnits(_T("")) , m_strSourceFormat(_T("")) , m_strSourceGroup(_T("")) , m_strSourceMin(_T("")) , m_strSourceMax(_T("")) { m_hBrush = NULL; m_lpDesc = NULL; } ////////////////////////////////////////////////////////////////////// CAIDA64SetupSourceDlg::~CAIDA64SetupSourceDlg() { } ////////////////////////////////////////////////////////////////////// void CAIDA64SetupSourceDlg::DoDataExchange(CDataExchange* pDX) { CDialog::DoDataExchange(pDX); DDX_Text(pDX, IDC_SENSOR_ID_EDIT, m_strSensorID); DDX_Control(pDX, IDC_SOURCE_ID_COMBO, m_sourceIdCombo); DDX_Text(pDX, IDC_SOURCE_INSTANCE_EDIT, m_strSourceInstance); DDX_Text(pDX, IDC_SOURCE_NAME_EDIT, m_strSourceName); DDX_Text(pDX, IDC_SOURCE_UNITS_EDIT, m_strSourceUnits); DDX_Text(pDX, IDC_SOURCE_FORMAT_EDIT, m_strSourceFormat); DDX_Text(pDX, IDC_SOURCE_GROUP_EDIT, m_strSourceGroup); DDX_Text(pDX, IDC_SOURCE_MIN_EDIT, m_strSourceMin); DDX_Text(pDX, IDC_SOURCE_MAX_EDIT, m_strSourceMax); } ////////////////////////////////////////////////////////////////////// BEGIN_MESSAGE_MAP(CAIDA64SetupSourceDlg, CDialog) ON_WM_DESTROY() ON_WM_CTLCOLOR() ON_BN_CLICKED(IDOK, &CAIDA64SetupSourceDlg::OnBnClickedOk) END_MESSAGE_MAP() ////////////////////////////////////////////////////////////////////// // CAIDA64SetupSourceDlg message handlers ////////////////////////////////////////////////////////////////////// typedef struct AIDA64_READING_TYPE_DESC { DWORD dwType; LPCSTR lpName; } AIDA64_READING_TYPE_DESC, *LPAIDA64_READING_TYPE_DESC; ////////////////////////////////////////////////////////////////////// typedef struct DATA_SOURCE_ID_DESC { DWORD dwID; LPCSTR lpName; } DATA_SOURCE_ID_DESC, *LPDATA_SOURCE_ID_DESC; ////////////////////////////////////////////////////////////////////// BOOL CAIDA64SetupSourceDlg::OnInitDialog() { CDialog::OnInitDialog(); LocalizeWnd(m_hWnd); AdjustWindowPos(this, GetParent()); if (m_lpDesc) { //sensor ID m_strSensorID = m_lpDesc->szID; //data source id DATA_SOURCE_ID_DESC sourceIds[] = { { MONITORING_SOURCE_ID_GPU_TEMPERATURE , "GPU temperature" }, { MONITORING_SOURCE_ID_PCB_TEMPERATURE , "PCB temperature" }, { MONITORING_SOURCE_ID_MEM_TEMPERATURE , "Memory temperature" }, { MONITORING_SOURCE_ID_VRM_TEMPERATURE , "VRM temperature" }, { MONITORING_SOURCE_ID_FAN_SPEED , "Fan speed" }, { MONITORING_SOURCE_ID_FAN_TACHOMETER , "Fan tachometer" }, { MONITORING_SOURCE_ID_CORE_CLOCK , "Core clock" }, { MONITORING_SOURCE_ID_SHADER_CLOCK , "Shader clock" }, { MONITORING_SOURCE_ID_MEMORY_CLOCK , "Memory clock" }, { MONITORING_SOURCE_ID_GPU_USAGE , "GPU usage" }, { MONITORING_SOURCE_ID_MEMORY_USAGE , "Memory usage" }, { MONITORING_SOURCE_ID_FB_USAGE , "FB usage" }, { MONITORING_SOURCE_ID_VID_USAGE , "VID usage" }, { MONITORING_SOURCE_ID_BUS_USAGE , "BUS usage" }, { MONITORING_SOURCE_ID_GPU_VOLTAGE , "GPU voltage" }, { MONITORING_SOURCE_ID_AUX_VOLTAGE , "Aux voltage" }, { MONITORING_SOURCE_ID_MEMORY_VOLTAGE , "Memory voltage" }, { MONITORING_SOURCE_ID_FRAMERATE , "Framerate" }, { MONITORING_SOURCE_ID_FRAMETIME , "Frametime" }, { MONITORING_SOURCE_ID_FRAMERATE_MIN , "Framerate Min" }, { MONITORING_SOURCE_ID_FRAMERATE_AVG , "Framerate Avg" }, { MONITORING_SOURCE_ID_FRAMERATE_MAX , "Framerate Max" }, { MONITORING_SOURCE_ID_FRAMERATE_1DOT0_PERCENT_LOW , "Framerate 1% Low" }, { MONITORING_SOURCE_ID_FRAMERATE_0DOT1_PERCENT_LOW , "Framerate 0.1% Low" }, { MONITORING_SOURCE_ID_GPU_REL_POWER , "Power percent" }, { MONITORING_SOURCE_ID_GPU_ABS_POWER , "Power" }, { MONITORING_SOURCE_ID_GPU_TEMP_LIMIT , "Temp limit" }, { MONITORING_SOURCE_ID_GPU_POWER_LIMIT , "Power limit" }, { MONITORING_SOURCE_ID_GPU_VOLTAGE_LIMIT , "Voltage limit" }, { MONITORING_SOURCE_ID_GPU_UTIL_LIMIT , "No load limit" }, { MONITORING_SOURCE_ID_CPU_USAGE , "CPU usage" }, { MONITORING_SOURCE_ID_RAM_USAGE , "RAM usage" }, { MONITORING_SOURCE_ID_PAGEFILE_USAGE , "Pagefile usage" }, { MONITORING_SOURCE_ID_CPU_TEMPERATURE , "CPU temperature" }, { MONITORING_SOURCE_ID_GPU_SLI_SYNC_LIMIT ,"SLI sync limit" }, { MONITORING_SOURCE_ID_CPU_CLOCK , "CPU clock" }, { MONITORING_SOURCE_ID_AUX2_VOLTAGE , "Aux2 voltage" }, { MONITORING_SOURCE_ID_GPU_TEMPERATURE2 , "GPU temperature 2" }, { MONITORING_SOURCE_ID_PCB_TEMPERATURE2 , "PCB temperature 2" }, { MONITORING_SOURCE_ID_MEM_TEMPERATURE2 , "Memory temperature 2" }, { MONITORING_SOURCE_ID_VRM_TEMPERATURE2 , "VRM temperature 2" }, { MONITORING_SOURCE_ID_GPU_TEMPERATURE3 , "GPU temperature 3" }, { MONITORING_SOURCE_ID_PCB_TEMPERATURE3 , "PCB temperature 3" }, { MONITORING_SOURCE_ID_MEM_TEMPERATURE3 , "Memory temperature 3" }, { MONITORING_SOURCE_ID_VRM_TEMPERATURE3 , "VRM temperature 3" }, { MONITORING_SOURCE_ID_GPU_TEMPERATURE4 , "GPU temperature 4" }, { MONITORING_SOURCE_ID_PCB_TEMPERATURE4 , "PCB temperature 4" }, { MONITORING_SOURCE_ID_MEM_TEMPERATURE4 , "Memory temperature 4" }, { MONITORING_SOURCE_ID_VRM_TEMPERATURE4 , "VRM temperature 4" }, { MONITORING_SOURCE_ID_GPU_TEMPERATURE5 , "GPU temperature 5" }, { MONITORING_SOURCE_ID_PCB_TEMPERATURE5 , "PCB temperature 5" }, { MONITORING_SOURCE_ID_MEM_TEMPERATURE5 , "Memory temperature 5" }, { MONITORING_SOURCE_ID_VRM_TEMPERATURE5 , "VRM temperature 5" }, { MONITORING_SOURCE_ID_PLUGIN_GPU , "<GPU plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_CPU , "<CPU plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_MOBO , "<motherboard plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_RAM , "<RAM plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_HDD , "<HDD plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_NET , "<NET plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_PSU , "<PSU plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_UPS , "<UPS plugin>" }, { MONITORING_SOURCE_ID_PLUGIN_MISC , "<miscellaneous plugin>" }, { MONITORING_SOURCE_ID_CPU_POWER , "CPU power" } }; m_sourceIdCombo.SetCurSel(0); for (int iIndex=0; iIndex<_countof(sourceIds); iIndex++) { int iItem = m_sourceIdCombo.AddString(LocalizeStr(sourceIds[iIndex].lpName)); m_sourceIdCombo.SetItemData(iItem, sourceIds[iIndex].dwID); if (m_lpDesc->dwID == sourceIds[iIndex].dwID) m_sourceIdCombo.SetCurSel(iItem); } //data source instance if (m_lpDesc->dwInstance != 0xFFFFFFFF) m_strSourceInstance.Format("%d", m_lpDesc->dwInstance); else m_strSourceInstance = ""; //data source name m_strSourceName = m_lpDesc->szName; //data source units m_strSourceUnits = m_lpDesc->szUnits; //data source output format m_strSourceFormat = m_lpDesc->szFormat; //data source group m_strSourceGroup = m_lpDesc->szGroup; //data source range m_strSourceMin.Format("%.1f", m_lpDesc->fltMinLimit); m_strSourceMax.Format("%.1f", m_lpDesc->fltMaxLimit); UpdateData(FALSE); } return TRUE; } ////////////////////////////////////////////////////////////////////// void CAIDA64SetupSourceDlg::SetSourceDesc(LPAIDA64_DATA_SOURCE_DESC lpDesc) { m_lpDesc = lpDesc; } ////////////////////////////////////////////////////////////////////// void CAIDA64SetupSourceDlg::OnDestroy() { if (m_hBrush) { DeleteObject(m_hBrush); m_hBrush = NULL; } CDialog::OnDestroy(); } ////////////////////////////////////////////////////////////////////// HBRUSH CAIDA64SetupSourceDlg::OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor) { COLORREF clrBk = g_dwHeaderBgndColor; COLORREF clrText = g_dwHeaderTextColor; UINT nID = pWnd->GetDlgCtrlID(); if ((nID == IDC_SENSOR_PROPERTIES_HEADER) || (nID == IDC_SOURCE_PROPERTIES_HEADER)) { if (!m_hBrush) m_hBrush = CreateSolidBrush(clrBk); pDC->SetBkColor(clrBk); pDC->SetTextColor(clrText); } else return CDialog::OnCtlColor(pDC, pWnd, nCtlColor); return m_hBrush; } ////////////////////////////////////////////////////////////////////// void CAIDA64SetupSourceDlg::OnBnClickedOk() { int iItem; UpdateData(TRUE); if (!ValidateSource()) { MessageBeep(MB_ICONERROR); return; } if (m_lpDesc) { //sensor ID strcpy_s(m_lpDesc->szID, sizeof(m_lpDesc->szID), m_strSensorID); //data source id iItem = m_sourceIdCombo.GetCurSel(); if (iItem != -1) m_lpDesc->dwID = m_sourceIdCombo.GetItemData(iItem); else m_lpDesc->dwID = MONITORING_SOURCE_ID_UNKNOWN; //data source instance if (sscanf_s(m_strSourceInstance, "%d", &m_lpDesc->dwInstance) != 1) m_lpDesc->dwInstance = 0xFFFFFFFF; //data source name strcpy_s(m_lpDesc->szName, sizeof(m_lpDesc->szName), m_strSourceName); //data source units strcpy_s(m_lpDesc->szUnits, sizeof(m_lpDesc->szUnits), m_strSourceUnits); //data source output format strcpy_s(m_lpDesc->szFormat, sizeof(m_lpDesc->szFormat), m_strSourceFormat); //data source group strcpy_s(m_lpDesc->szGroup, sizeof(m_lpDesc->szGroup), m_strSourceGroup); //data source range if (sscanf_s(m_strSourceMin, "%f", &m_lpDesc->fltMinLimit) != 1) m_lpDesc->fltMinLimit = 0.0f; if (sscanf_s(m_strSourceMax, "%f", &m_lpDesc->fltMaxLimit) != 1) m_lpDesc->fltMaxLimit = 100.0f; } OnOK(); } ////////////////////////////////////////////////////////////////////// BOOL CAIDA64SetupSourceDlg::ValidateSource() { m_strSensorID.Trim(); if (m_strSensorID.IsEmpty()) { GetDlgItem(IDC_SENSOR_ID_EDIT)->SetFocus(); return FALSE; } m_strSourceName.Trim(); if (m_strSourceName.IsEmpty()) { GetDlgItem(IDC_SOURCE_NAME_EDIT)->SetFocus(); return FALSE; } return TRUE; } //////////////////////////////////////////////////////////////////////
34.914286
81
0.619476
tjca1
ffda1739c238bdf51674219dada669155ad4e950
3,737
cpp
C++
sycl/source/detail/kernel_impl.cpp
MochalovaAn/llvm
528aa5ca4aa9df447dc3497ef19da3b124e88d7d
[ "Apache-2.0" ]
61
2019-04-12T18:49:57.000Z
2022-03-19T22:23:16.000Z
sycl/source/detail/kernel_impl.cpp
MochalovaAn/llvm
528aa5ca4aa9df447dc3497ef19da3b124e88d7d
[ "Apache-2.0" ]
127
2019-04-09T00:55:50.000Z
2022-03-21T15:35:41.000Z
sycl/source/detail/kernel_impl.cpp
MochalovaAn/llvm
528aa5ca4aa9df447dc3497ef19da3b124e88d7d
[ "Apache-2.0" ]
10
2019-04-02T18:25:40.000Z
2022-02-15T07:11:37.000Z
//==------- kernel_impl.cpp --- SYCL kernel implementation -----------------==// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <detail/context_impl.hpp> #include <detail/kernel_bundle_impl.hpp> #include <detail/kernel_impl.hpp> #include <detail/program_impl.hpp> #include <memory> __SYCL_INLINE_NAMESPACE(cl) { namespace sycl { namespace detail { kernel_impl::kernel_impl(RT::PiKernel Kernel, ContextImplPtr Context) : kernel_impl(Kernel, Context, std::make_shared<program_impl>(Context, Kernel), /*IsCreatedFromSource*/ true) { // This constructor is only called in the interoperability kernel constructor. // Let the runtime caller handle native kernel retaining in other cases if // it's needed. getPlugin().call<PiApiKind::piKernelRetain>(MKernel); // Enable USM indirect access for interoperability kernels. // Some PI Plugins (like OpenCL) require this call to enable USM // For others, PI will turn this into a NOP. getPlugin().call<PiApiKind::piKernelSetExecInfo>( MKernel, PI_USM_INDIRECT_ACCESS, sizeof(pi_bool), &PI_TRUE); } kernel_impl::kernel_impl(RT::PiKernel Kernel, ContextImplPtr ContextImpl, ProgramImplPtr ProgramImpl, bool IsCreatedFromSource) : MKernel(Kernel), MContext(ContextImpl), MProgramImpl(std::move(ProgramImpl)), MCreatedFromSource(IsCreatedFromSource) { RT::PiContext Context = nullptr; // Using the plugin from the passed ContextImpl getPlugin().call<PiApiKind::piKernelGetInfo>( MKernel, PI_KERNEL_INFO_CONTEXT, sizeof(Context), &Context, nullptr); if (ContextImpl->getHandleRef() != Context) throw cl::sycl::invalid_parameter_error( "Input context must be the same as the context of cl_kernel", PI_INVALID_CONTEXT); } kernel_impl::kernel_impl(RT::PiKernel Kernel, ContextImplPtr ContextImpl, DeviceImageImplPtr DeviceImageImpl, KernelBundleImplPtr KernelBundleImpl) : MKernel(Kernel), MContext(std::move(ContextImpl)), MProgramImpl(nullptr), MCreatedFromSource(false), MDeviceImageImpl(std::move(DeviceImageImpl)), MKernelBundleImpl(std::move(KernelBundleImpl)) { // kernel_impl shared ownership of kernel handle if (!is_host()) { getPlugin().call<PiApiKind::piKernelRetain>(MKernel); } } kernel_impl::kernel_impl(ContextImplPtr Context, ProgramImplPtr ProgramImpl) : MContext(Context), MProgramImpl(std::move(ProgramImpl)) {} kernel_impl::~kernel_impl() { // TODO catch an exception and put it to list of asynchronous exceptions if (!is_host()) { getPlugin().call<PiApiKind::piKernelRelease>(MKernel); } } bool kernel_impl::isCreatedFromSource() const { // TODO it is not clear how to understand whether the SYCL kernel is created // from source code or not when the SYCL kernel is created using // the interoperability constructor. // Here a strange case which does not work now: // context Context; // program Program(Context); // Program.build_with_kernel_type<class A>(); // kernel FirstKernel= Program.get_kernel<class A>(); // cl_kernel ClKernel = FirstKernel.get(); // kernel SecondKernel = kernel(ClKernel, Context); // clReleaseKernel(ClKernel); // FirstKernel.isCreatedFromSource() != FirstKernel.isCreatedFromSource(); return MCreatedFromSource; } } // namespace detail } // namespace sycl } // __SYCL_INLINE_NAMESPACE(cl)
38.927083
80
0.694675
MochalovaAn
ffdabdd4f68355ce6317c319adc23e98a1eb726e
1,852
cpp
C++
Gardenino_Sketch/SensorLogger.cpp
Diebanez/gardenino
88ce597e47dcaecbe1a99eb962bdc95a30bd5932
[ "MIT" ]
null
null
null
Gardenino_Sketch/SensorLogger.cpp
Diebanez/gardenino
88ce597e47dcaecbe1a99eb962bdc95a30bd5932
[ "MIT" ]
4
2021-12-31T13:22:59.000Z
2022-01-03T10:36:22.000Z
Gardenino_Sketch/SensorLogger.cpp
Diebanez/gardenino
88ce597e47dcaecbe1a99eb962bdc95a30bd5932
[ "MIT" ]
null
null
null
#include "SensorLogger.h" #include <SD.h> #include "Debug.h" SensorLogger::SensorLogger(Clock *logClock) : PrintLogSpan(0, 1, 0, 0), LogClock(logClock) { } void SensorLogger::AddSensorToLog(Sensor *target) { SensorToLog.AddElement(target); } void SensorLogger::Init(TimeSpan LogSpan) { PrintLogSpan = LogSpan; Log(); } void SensorLogger::Update() { DateTime now = LogClock->GetNow(); if (now.unixtime() - LastLogTime.unixtime() >= PrintLogSpan.totalseconds()) { Log(); } } void SensorLogger::Log() { LastLogTime = LogClock->GetNow(); if (!SD.exists(LOGS_FOLDER)) { SD.mkdir(LOGS_FOLDER); } String FileName = LOGS_FOLDER + String("/") + String(LastLogTime.day()) + String(LastLogTime.month()) + String(LastLogTime.year()) + String(".csv"); if (!SD.exists(FileName)) { File newFile = SD.open(FileName, FILE_WRITE); if (newFile) { String line = "Time;"; for (int i = 0; i < SensorToLog.GetElementsCount(); i++) { line += SensorToLog.GetElement(i)->GetName(); line += ";"; } newFile.println(line); newFile.close(); } } String newLine = String(LastLogTime.hour()) + String(":") + String(LastLogTime.minute()) + String(":") + String(LastLogTime.second()) + ";"; for (int i = 0; i < SensorToLog.GetElementsCount(); i++) { newLine += String(SensorToLog.GetElement(i)->GetValue()); newLine += ";"; } File appendFile = SD.open(FileName, FILE_WRITE); if (appendFile) { appendFile.println(newLine); appendFile.close(); } SERIAL_LOG("[" + String(LastLogTime.hour()) + ":" + String(LastLogTime.minute()) + ":" + String(LastLogTime.second()) + "] Logged data to sd") }
24.368421
152
0.577214
Diebanez
ffdc05012f1d21cf3bb26478b72da3fff8839626
72,493
cxx
C++
Libs/MRML/Core/vtkMRMLSegmentationStorageNode.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Libs/MRML/Core/vtkMRMLSegmentationStorageNode.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
Libs/MRML/Core/vtkMRMLSegmentationStorageNode.cxx
forfullstack/slicersources-src
91bcecf037a27f3fad4c0ab57e8286fc258bb0f5
[ "Apache-2.0" ]
null
null
null
/*============================================================================== Copyright (c) Laboratory for Percutaneous Surgery (PerkLab) Queen's University, Kingston, ON, Canada. All Rights Reserved. See COPYRIGHT.txt or http://www.slicer.org/copyright/copyright.txt for details. 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. This file was originally developed by Adam Rankin and Csaba Pinter, PerkLab, Queen's University and was supported through the Applied Cancer Research Unit program of Cancer Care Ontario with funds provided by the Ontario Ministry of Health and Long-Term Care ==============================================================================*/ // Segmentations includes #include "vtkMRMLSegmentationStorageNode.h" #include "vtkSegmentation.h" #include "vtkOrientedImageData.h" #include "vtkOrientedImageDataResample.h" // MRML includes #include <vtkMRMLScalarVolumeNode.h> #include <vtkMRMLScene.h> #include "vtkMRMLSegmentationNode.h" #include "vtkMRMLSegmentationDisplayNode.h" // VTK includes #include <vtkDataObject.h> #include <vtkDoubleArray.h> #include <vtkErrorCode.h> #include <vtkFieldData.h> #include <vtkImageAccumulate.h> #include <vtkImageAppendComponents.h> #include <vtkImageCast.h> #include <vtkImageConstantPad.h> #include <vtkImageExtractComponents.h> #include <vtkInformation.h> #include <vtkInformationIntegerVectorKey.h> #include <vtkInformationStringKey.h> #include <vtkITKArchetypeImageSeriesVectorReaderFile.h> #include <vtkMultiBlockDataSet.h> #include <vtkNew.h> #include <vtkTeemNRRDWriter.h> #include <vtkObjectFactory.h> #include <vtkPointData.h> #include <vtkPolyData.h> #include <vtkStringArray.h> #include <vtkTransform.h> #include <vtkXMLMultiBlockDataWriter.h> #include <vtkXMLMultiBlockDataReader.h> #include <vtksys/SystemTools.hxx> #ifdef SUPPORT_4D_SPATIAL_NRRD // ITK includes #include <itkMacro.h> #include <itkImageFileWriter.h> #include <itkImageFileReader.h> #include <itkMetaDataDictionary.h> #include <itkMetaDataObject.h> #include <itkNrrdImageIO.h> #endif // STL & C++ includes #include <iterator> #include <sstream> //---------------------------------------------------------------------------- static const std::string SERIALIZATION_SEPARATOR = "|"; static const std::string KEY_SEGMENT_ID = "ID"; static const std::string KEY_SEGMENT_NAME = "Name"; static const std::string KEY_SEGMENT_COLOR = "Color"; static const std::string KEY_SEGMENT_TAGS = "Tags"; static const std::string KEY_SEGMENT_EXTENT = "Extent"; static const std::string KEY_SEGMENT_LABEL_VALUE = "LabelValue"; static const std::string KEY_SEGMENT_LAYER = "Layer"; static const std::string KEY_SEGMENT_NAME_AUTO_GENERATED = "NameAutoGenerated"; static const std::string KEY_SEGMENT_COLOR_AUTO_GENERATED = "ColorAutoGenerated"; static const std::string KEY_SEGMENTATION_MASTER_REPRESENTATION = "MasterRepresentation"; static const std::string KEY_SEGMENTATION_CONVERSION_PARAMETERS = "ConversionParameters"; static const std::string KEY_SEGMENTATION_EXTENT = "Extent"; // Deprecated, kept only for being able to read legacy files. static const std::string KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET = "ReferenceImageExtentOffset"; static const std::string KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES = "ContainedRepresentationNames"; static const int SINGLE_SEGMENT_INDEX = -1; // used as segment index when there is only a single segment //---------------------------------------------------------------------------- vtkMRMLNodeNewMacro(vtkMRMLSegmentationStorageNode); //---------------------------------------------------------------------------- vtkMRMLSegmentationStorageNode::vtkMRMLSegmentationStorageNode() = default; //---------------------------------------------------------------------------- vtkMRMLSegmentationStorageNode::~vtkMRMLSegmentationStorageNode() = default; //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::PrintSelf(ostream& os, vtkIndent indent) { Superclass::PrintSelf(os,indent); vtkMRMLPrintBeginMacro(os, indent); vtkMRMLPrintBooleanMacro(CropToMinimumExtent); vtkMRMLPrintEndMacro(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::ReadXMLAttributes(const char** atts) { MRMLNodeModifyBlocker blocker(this); Superclass::ReadXMLAttributes(atts); vtkMRMLReadXMLBeginMacro(atts); vtkMRMLReadXMLBooleanMacro(CropToMinimumExtent, CropToMinimumExtent); vtkMRMLReadXMLEndMacro(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::WriteXML(ostream& of, int nIndent) { Superclass::WriteXML(of, nIndent); vtkMRMLWriteXMLBeginMacro(of); vtkMRMLWriteXMLBooleanMacro(CropToMinimumExtent, CropToMinimumExtent); vtkMRMLWriteXMLEndMacro(); } //---------------------------------------------------------------------------- // Copy the node's attributes to this object. // Does NOT copy: ID, FilePrefix, Name, StorageID void vtkMRMLSegmentationStorageNode::Copy(vtkMRMLNode *anode) { MRMLNodeModifyBlocker blocker(anode); Superclass::Copy(anode); vtkMRMLCopyBeginMacro(anode); vtkMRMLCopyBooleanMacro(CropToMinimumExtent); vtkMRMLCopyEndMacro(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::InitializeSupportedReadFileTypes() { this->SupportedReadFileTypes->InsertNextValue("Segmentation (.seg.nrrd)"); this->SupportedReadFileTypes->InsertNextValue("Segmentation (.seg.vtm)"); this->SupportedReadFileTypes->InsertNextValue("Segmentation (.nrrd)"); this->SupportedReadFileTypes->InsertNextValue("Segmentation (.vtm)"); this->SupportedReadFileTypes->InsertNextValue("Segmentation (.nii.gz)"); this->SupportedReadFileTypes->InsertNextValue("Segmentation (.hdr)"); this->SupportedReadFileTypes->InsertNextValue("Segmentation (.nii)"); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::InitializeSupportedWriteFileTypes() { Superclass::InitializeSupportedWriteFileTypes(); vtkMRMLSegmentationNode* segmentationNode = this->GetAssociatedDataNode(); bool masterIsImage = true; bool masterIsPolyData = true; if (segmentationNode) { // restrict write file types to those that are suitable for current master representation masterIsImage = segmentationNode->GetSegmentation()->IsMasterRepresentationImageData(); masterIsPolyData = segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData(); if (!masterIsImage && !masterIsPolyData) { // if contains unknown representation then enable all formats masterIsImage = true; masterIsPolyData = true; } } if (masterIsImage) { this->SupportedWriteFileTypes->InsertNextValue("Segmentation (.seg.nrrd)"); this->SupportedWriteFileTypes->InsertNextValue("Segmentation (.nrrd)"); } if (masterIsPolyData) { this->SupportedWriteFileTypes->InsertNextValue("Segmentation (.seg.vtm)"); this->SupportedWriteFileTypes->InsertNextValue("Segmentation (.vtm)"); } } //---------------------------------------------------------------------------- vtkMRMLSegmentationNode* vtkMRMLSegmentationStorageNode::GetAssociatedDataNode() { if (!this->GetScene()) { return nullptr; } std::vector<vtkMRMLNode*> segmentationNodes; unsigned int numberOfNodes = this->GetScene()->GetNodesByClass("vtkMRMLSegmentationNode", segmentationNodes); for (unsigned int nodeIndex=0; nodeIndex<numberOfNodes; nodeIndex++) { vtkMRMLSegmentationNode* node = vtkMRMLSegmentationNode::SafeDownCast(segmentationNodes[nodeIndex]); if (node) { const char* storageNodeID = node->GetStorageNodeID(); if (storageNodeID && !strcmp(storageNodeID, this->ID)) { return vtkMRMLSegmentationNode::SafeDownCast(node); } } } return nullptr; } //---------------------------------------------------------------------------- const char* vtkMRMLSegmentationStorageNode::GetDefaultWriteFileExtension() { vtkMRMLSegmentationNode* segmentationNode = this->GetAssociatedDataNode(); if (!segmentationNode) { return nullptr; } if (segmentationNode->GetSegmentation()->IsMasterRepresentationImageData()) { return "seg.nrrd"; } else if (segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData()) { return "seg.vtm"; } // Master representation is not supported for writing to file return nullptr; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::ResetSupportedWriteFileTypes() { this->InitializeSupportedWriteFileTypes(); } //---------------------------------------------------------------------------- bool vtkMRMLSegmentationStorageNode::CanReadInReferenceNode(vtkMRMLNode *refNode) { return refNode->IsA("vtkMRMLSegmentationNode"); } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadDataInternal(vtkMRMLNode *refNode) { vtkMRMLSegmentationNode* segmentationNode = vtkMRMLSegmentationNode::SafeDownCast(refNode); if (!segmentationNode) { vtkErrorMacro("ReadDataInternal: Reference node is not a segmentation node"); return 0; } MRMLNodeModifyBlocker blocker(segmentationNode); std::string fullName = this->GetFullNameFromFileName(); if (fullName.empty()) { vtkErrorMacro("ReadDataInternal: File name not specified"); return 0; } // Check that the file exists if (vtksys::SystemTools::FileExists(fullName.c_str()) == false) { vtkErrorMacro("ReadDataInternal: segmentation file '" << fullName.c_str() << "' not found."); return 0; } bool success = false; // Try to read as labelmap first then as poly data if (this->ReadBinaryLabelmapRepresentation(segmentationNode, fullName)) { success = true; } #ifdef SUPPORT_4D_SPATIAL_NRRD else if (this->ReadBinaryLabelmapRepresentation4DSpatial(segmentationNode, fullName)) { success = true; } #endif else if (this->ReadPolyDataRepresentation(segmentationNode, fullName)) { success = true; } // Create display node if segmentation there is none if (success && !segmentationNode->GetDisplayNode()) { segmentationNode->CreateDefaultDisplayNodes(); } if (!success) { // Failed to read vtkErrorMacro("ReadDataInternal: File " << fullName << " could not be read neither as labelmap nor poly data"); return 0; } return 1; } #ifdef SUPPORT_4D_SPATIAL_NRRD //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadBinaryLabelmapRepresentation4DSpatial(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!vtksys::SystemTools::FileExists(path.c_str())) { vtkErrorMacro("ReadBinaryLabelmapRepresentation: Input file " << path << " does not exist!"); return 0; } // Set up output segmentation if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { vtkErrorMacro("ReadBinaryLabelmapRepresentation: Output segmentation must exist and must be empty!"); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); // Read 4D NRRD image file typedef itk::ImageFileReader<BinaryLabelmap4DImageType> FileReaderType; FileReaderType::Pointer reader = FileReaderType::New(); reader->SetFileName(path); try { reader->Update(); } catch (itk::ImageFileReaderException &error) { // Do not report error as the file might contain poly data in which case ReadPolyDataRepresentation will read it alright vtkDebugMacro("ReadBinaryLabelmapRepresentation: Failed to load file " << path << " as segmentation. Exception:\n" << error); return 0; } BinaryLabelmap4DImageType::Pointer allSegmentLabelmapsImage = reader->GetOutput(); // Read succeeded, set master representation segmentation->SetMasterRepresentationName(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName()); // Get metadata dictionary from image itk::MetaDataDictionary metadata = allSegmentLabelmapsImage->GetMetaDataDictionary(); // Read common geometry extent std::string commonExtent; itk::ExposeMetaData<std::string>(metadata, GetSegmentationMetaDataKey(KEY_SEGMENTATION_EXTENT).c_str(), commonExtent); int commonGeometryExtent[6] = {0,-1,0,-1,0,-1}; GetImageExtentFromString(commonGeometryExtent, commonExtent); // Read conversion parameters std::string conversionParameters; itk::ExposeMetaData<std::string>(metadata, GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str(), conversionParameters); segmentation->DeserializeConversionParameters(conversionParameters); // Read contained representation names std::string containedRepresentationNames; itk::ExposeMetaData<std::string>(metadata, GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str(), containedRepresentationNames); // Get image properties BinaryLabelmap4DImageType::RegionType itkRegion = allSegmentLabelmapsImage->GetLargestPossibleRegion(); BinaryLabelmap4DImageType::PointType itkOrigin = allSegmentLabelmapsImage->GetOrigin(); BinaryLabelmap4DImageType::SpacingType itkSpacing = allSegmentLabelmapsImage->GetSpacing(); BinaryLabelmap4DImageType::DirectionType itkDirections = allSegmentLabelmapsImage->GetDirection(); // Make image properties accessible for VTK double origin[3] = {itkOrigin[0], itkOrigin[1], itkOrigin[2]}; double spacing[3] = {itkSpacing[0], itkSpacing[1], itkSpacing[2]}; double directions[3][3] = {{1.0,0.0,0.0},{0.0,1.0,0.0},{0.0,0.0,1.0}}; for (unsigned int col=0; col<3; col++) { for (unsigned int row=0; row<3; row++) { directions[row][col] = itkDirections[row][col]; } } // Read segment binary labelmaps for (unsigned int segmentIndex = itkRegion.GetIndex()[3]; segmentIndex < itkRegion.GetIndex()[3]+itkRegion.GetSize()[3]; ++segmentIndex) { // Create segment vtkSmartPointer<vtkSegment> currentSegment = vtkSmartPointer<vtkSegment>::New(); // Get metadata for current segment // ID std::string currentSegmentID; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_ID), currentSegmentID); // Name std::string currentSegmentName; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME), currentSegmentName); currentSegment->SetName(currentSegmentName.c_str()); // Color std::string colorString; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR), colorString); if (colorString.empty()) { // Backwards compatibility itk::ExposeMetaData<std::string>(metadata, GetSegmentMetaDataKey(segmentIndex, "DefaultColor"), colorString); } double currentSegmentColor[3] = {0.0,0.0,0.0}; GetSegmentColorFromString(currentSegmentColor, colorString); // Extent std::string extentValue; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_EXTENT), extentValue); int currentSegmentExtent[6] = {0,-1,0,-1,0,-1}; GetImageExtentFromString(currentSegmentExtent, extentValue); // Tags std::string tagsValue; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_TAGS), tagsValue); SetSegmentTagsFromString(currentSegment, tagsValue); // NameAutoGenerated std::string currentSegmentNameAutoGenerated; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME_AUTO_GENERATED), currentSegmentNameAutoGenerated); currentSegment->SetNameAutoGenerated(!currentSegmentNameAutoGenerated.compare("1")); // ColorAutoGenerated std::string currentSegmentColorAutoGenerated; itk::ExposeMetaData<std::string>( metadata, GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR_AUTO_GENERATED), currentSegmentColorAutoGenerated); currentSegment->SetColorAutoGenerated(!currentSegmentColorAutoGenerated.compare("1")); // Create binary labelmap volume vtkSmartPointer<vtkOrientedImageData> currentBinaryLabelmap = vtkSmartPointer<vtkOrientedImageData>::New(); currentBinaryLabelmap->SetOrigin(origin); currentBinaryLabelmap->SetSpacing(spacing); currentBinaryLabelmap->SetDirections(directions); currentBinaryLabelmap->SetExtent(currentSegmentExtent); currentBinaryLabelmap->AllocateScalars(VTK_UNSIGNED_CHAR, 1); unsigned char* labelmapPtr = (unsigned char*)currentBinaryLabelmap->GetScalarPointerForExtent(currentSegmentExtent); // Define ITK region for current segment BinaryLabelmap4DImageType::RegionType segmentRegion; BinaryLabelmap4DImageType::SizeType segmentRegionSize; BinaryLabelmap4DImageType::IndexType segmentRegionIndex; segmentRegionIndex[0] = segmentRegionIndex[1] = segmentRegionIndex[2] = 0; segmentRegionIndex[3] = segmentIndex; segmentRegionSize = itkRegion.GetSize(); segmentRegionSize[3] = 1; segmentRegion.SetIndex(segmentRegionIndex); segmentRegion.SetSize(segmentRegionSize); // Iterate through current segment's region and read voxel values into segment labelmap BinaryLabelmap4DIteratorType segmentLabelmapIterator(allSegmentLabelmapsImage, segmentRegion); for (segmentLabelmapIterator.GoToBegin(); !segmentLabelmapIterator.IsAtEnd(); ++segmentLabelmapIterator) { // Skip region outside extent of current segment (consider common extent boundaries) BinaryLabelmap4DImageType::IndexType segmentIndex = segmentLabelmapIterator.GetIndex(); if ( segmentIndex[0] + commonGeometryExtent[0] < currentSegmentExtent[0] || segmentIndex[0] + commonGeometryExtent[0] > currentSegmentExtent[1] || segmentIndex[1] + commonGeometryExtent[2] < currentSegmentExtent[2] || segmentIndex[1] + commonGeometryExtent[2] > currentSegmentExtent[3] || segmentIndex[2] + commonGeometryExtent[4] < currentSegmentExtent[4] || segmentIndex[2] + commonGeometryExtent[4] > currentSegmentExtent[5] ) { continue; } // Get voxel value unsigned char voxelValue = segmentLabelmapIterator.Get(); // Set voxel value in current segment labelmap (*labelmapPtr) = voxelValue; ++labelmapPtr; } // Set loaded binary labelmap to segment currentSegment->AddRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName(), currentBinaryLabelmap); // Add segment to segmentation segmentation->AddSegment(currentSegment, currentSegmentID); } // Create contained representations now that all the data is loaded this->CreateRepresentationsBySerializedNames(segmentation, containedRepresentationNames); return 1; } #endif // SUPPORT_4D_SPATIAL_NRRD //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadBinaryLabelmapRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!vtksys::SystemTools::FileExists(path.c_str())) { vtkErrorMacro("ReadBinaryLabelmapRepresentation: Input file " << path << " does not exist!"); return 0; } // Set up output segmentation if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { vtkErrorMacro("ReadBinaryLabelmapRepresentation: Output segmentation must exist and must be empty!"); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); vtkSmartPointer<vtkImageData> imageData = nullptr; vtkNew<vtkITKArchetypeImageSeriesVectorReaderFile> archetypeImageReader; archetypeImageReader->SetSingleFile(1); archetypeImageReader->SetUseOrientationFromFile(1); archetypeImageReader->ResetFileNames(); archetypeImageReader->SetArchetype(path.c_str()); archetypeImageReader->SetOutputScalarTypeToNative(); archetypeImageReader->SetDesiredCoordinateOrientationToNative(); archetypeImageReader->SetUseNativeOriginOn(); int numberOfSegments = 0; std::map<int, std::vector<int> > segmentIndexInLayer; std::string containedRepresentationNames; vtkMatrix4x4* rasToFileIjk = nullptr; int imageExtentInFile[6] = { 0, -1, 0, -1, 0, -1 }; int commonGeometryExtent[6] = { 0, -1, 0, -1, 0, -1 }; int referenceImageExtentOffset[3] = { 0, 0, 0 }; if (archetypeImageReader->CanReadFile(path.c_str())) { // Read the volume archetypeImageReader->Update(); if (archetypeImageReader->GetErrorCode() != vtkErrorCode::NoError) { vtkErrorMacro("ReadBinaryLabelmapRepresentation: Error reading image!"); return 0; } // Copy image data to sequence of volume nodes imageData = archetypeImageReader->GetOutput(); rasToFileIjk = archetypeImageReader->GetRasToIjkMatrix(); imageData->GetExtent(imageExtentInFile); imageData->GetExtent(commonGeometryExtent); // Get metadata dictionary from image itk::MetaDataDictionary dictionary = archetypeImageReader->GetMetaDataDictionary(); std::string segmentationExtentString; if (this->GetSegmentationMetaDataFromDicitionary(segmentationExtentString, dictionary, KEY_SEGMENTATION_EXTENT)) { // Legacy format. Return and read using ReadBinaryLabelmapRepresentation4DSpatial if availiable. return 0; } // Read common geometry std::string referenceImageExtentOffsetStr; if (this->GetSegmentationMetaDataFromDicitionary(referenceImageExtentOffsetStr, dictionary, KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET)) { // Common geometry extent is specified by an offset (extent[0], extent[2], extent[4]) and the size of the image // NRRD file cannot store start extent, so we store that in KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET and from imageExtentInFile we // only use the extent size. std::stringstream ssExtentValue(referenceImageExtentOffsetStr); ssExtentValue >> referenceImageExtentOffset[0] >> referenceImageExtentOffset[1] >> referenceImageExtentOffset[2]; commonGeometryExtent[0] = referenceImageExtentOffset[0]; commonGeometryExtent[1] = referenceImageExtentOffset[0] + imageExtentInFile[1] - imageExtentInFile[0]; commonGeometryExtent[2] = referenceImageExtentOffset[1]; commonGeometryExtent[3] = referenceImageExtentOffset[1] + imageExtentInFile[3] - imageExtentInFile[2]; commonGeometryExtent[4] = referenceImageExtentOffset[2]; commonGeometryExtent[5] = referenceImageExtentOffset[2] + imageExtentInFile[5] - imageExtentInFile[4]; } else { // KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET is not specified, // which means that this is probably a regular NRRD file that should be imported as a segmentation. // Use the image extent as common geometry extent. vtkInfoMacro(<< KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET << " attribute was not found in NRRD segmentation file. Assume no offset."); imageData->GetExtent(commonGeometryExtent); } // Read conversion parameters std::string conversionParameters; if (this->GetSegmentationMetaDataFromDicitionary(conversionParameters, dictionary, KEY_SEGMENTATION_CONVERSION_PARAMETERS)) { segmentation->DeserializeConversionParameters(conversionParameters); } // Read contained representation names this->GetSegmentationMetaDataFromDicitionary(containedRepresentationNames, dictionary, KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES); // Read contained segment layer numbers while (dictionary.HasKey(GetSegmentMetaDataKey(numberOfSegments, KEY_SEGMENT_ID))) { int segmentIndex = numberOfSegments; std::string layerValue; if (this->GetSegmentMetaDataFromDicitionary(layerValue, dictionary, segmentIndex, KEY_SEGMENT_LAYER)) { segmentIndexInLayer[vtkVariant(layerValue).ToInt()].push_back(segmentIndex); } else { segmentIndexInLayer[segmentIndex].push_back(segmentIndex); } ++numberOfSegments; } } else { vtkDebugMacro("ReadBinaryLabelmapRepresentation: File is not using a supported format!"); return 0; } if (imageData == nullptr) { vtkErrorMacro("vtkMRMLVolumeSequenceStorageNode::ReadDataInternal: invalid image data"); return 0; } int numberOfFrames = imageData->GetNumberOfScalarComponents(); // Read succeeded, set master representation segmentation->SetMasterRepresentationName(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName()); MRMLNodeModifyBlocker blocker(segmentationNode); // Compensate for the extent shift in the image origin. // We change the origin so that if a reader ignores private fields, such as // referenceImageExtentOffset, the image is placed correctly in physical coordinate system. vtkNew<vtkMatrix4x4> fileIjkToIjk; fileIjkToIjk->SetElement(0, 3, referenceImageExtentOffset[0]); fileIjkToIjk->SetElement(1, 3, referenceImageExtentOffset[1]); fileIjkToIjk->SetElement(2, 3, referenceImageExtentOffset[2]); vtkNew<vtkMatrix4x4> rasToIjk; vtkMatrix4x4::Multiply4x4(fileIjkToIjk.GetPointer(), rasToFileIjk, rasToIjk.GetPointer()); vtkNew<vtkMatrix4x4> imageToWorldMatrix; // = ijkToRas; vtkMatrix4x4::Invert(rasToIjk.GetPointer(), imageToWorldMatrix.GetPointer()); imageData->SetExtent(commonGeometryExtent); vtkNew<vtkImageExtractComponents> extractComponents; extractComponents->SetInputData(imageData); vtkNew<vtkImageConstantPad> padder; padder->SetInputConnection(extractComponents->GetOutputPort()); // Get metadata for current segment itk::MetaDataDictionary dictionary = archetypeImageReader->GetMetaDataDictionary(); std::vector<vtkSmartPointer<vtkSegment> > segments(numberOfSegments); std::map<int, vtkSmartPointer<vtkOrientedImageData> > layerToImage; for (int frameIndex = 0; frameIndex < numberOfFrames; ++frameIndex) { // Create binary labelmap volume vtkSmartPointer<vtkOrientedImageData> currentBinaryLabelmap = nullptr; if (numberOfSegments == 0) { currentBinaryLabelmap = vtkSmartPointer<vtkOrientedImageData>::New(); extractComponents->SetComponents(frameIndex); padder->SetOutputWholeExtent(imageExtentInFile); padder->Update(); currentBinaryLabelmap->ShallowCopy(padder->GetOutput()); double scalarRange[2] = { 0 }; currentBinaryLabelmap->GetScalarRange(scalarRange); vtkIdType lowLabel = (vtkIdType)(floor(scalarRange[0])); vtkIdType highLabel = (vtkIdType)(ceil(scalarRange[1])); vtkSmartPointer<vtkImageAccumulate> imageAccumulate = vtkSmartPointer<vtkImageAccumulate>::New(); imageAccumulate->SetInputData(currentBinaryLabelmap); imageAccumulate->IgnoreZeroOn(); // Ignore background value imageAccumulate->SetComponentExtent(lowLabel, highLabel, 0, 0, 0, 0); imageAccumulate->SetComponentOrigin(0, 0, 0); imageAccumulate->SetComponentSpacing(1, 1, 1); imageAccumulate->Update(); std::vector<vtkIdType> labelValues; for (vtkIdType labelValue = lowLabel; labelValue <= highLabel; ++labelValue) { if (labelValue == 0) { continue; } double frequency = imageAccumulate->GetOutput()->GetPointData()->GetScalars()->GetTuple1(labelValue - lowLabel); if (frequency == 0.0) { continue; } vtkSmartPointer<vtkSegment> currentSegment = vtkSmartPointer<vtkSegment>::New(); currentSegment->SetLabelValue(labelValue); currentBinaryLabelmap->SetImageToWorldMatrix(imageToWorldMatrix.GetPointer()); currentSegment->AddRepresentation(vtkSegmentationConverter::GetBinaryLabelmapRepresentationName(), currentBinaryLabelmap); segments.push_back(currentSegment); } } else { for (int segmentIndex : segmentIndexInLayer[frameIndex]) { // Create segment vtkSmartPointer<vtkSegment> currentSegment = vtkSmartPointer<vtkSegment>::New(); std::string segmentColor; if (this->GetSegmentMetaDataFromDicitionary(segmentColor, dictionary, segmentIndex, KEY_SEGMENT_COLOR)) { double currentSegmentColor[3] = { 0.0, 0.0, 0.0 }; this->GetSegmentColorFromString(currentSegmentColor, segmentColor); currentSegment->SetColor(currentSegmentColor); } else if (this->GetSegmentMetaDataFromDicitionary(segmentColor, dictionary, segmentIndex, "DefaultColor")) { double defaultSegmentColor[3] = { 0.0, 0.0, 0.0 }; this->GetSegmentColorFromString(defaultSegmentColor, segmentColor); currentSegment->SetColor(defaultSegmentColor); } // Tags std::string segmentTags; if (this->GetSegmentMetaDataFromDicitionary(segmentTags, dictionary, segmentIndex, KEY_SEGMENT_TAGS)) { this->SetSegmentTagsFromString(currentSegment, segmentTags); } // NameAutoGenerated std::string nameAutoGenerated; if (this->GetSegmentMetaDataFromDicitionary(nameAutoGenerated, dictionary, segmentIndex, KEY_SEGMENT_NAME_AUTO_GENERATED)) { currentSegment->SetNameAutoGenerated(!strcmp(nameAutoGenerated.c_str(), "1")); } // ColorAutoGenerated std::string colorAutoGenerated; if (this->GetSegmentMetaDataFromDicitionary(colorAutoGenerated, dictionary, segmentIndex, KEY_SEGMENT_COLOR_AUTO_GENERATED)) { currentSegment->SetColorAutoGenerated(!strcmp(colorAutoGenerated.c_str(),"1")); } // Label value std::string labelValue; if (this->GetSegmentMetaDataFromDicitionary(labelValue, dictionary, segmentIndex, KEY_SEGMENT_LABEL_VALUE)) { currentSegment->SetLabelValue(vtkVariant(labelValue).ToInt()); } if (currentBinaryLabelmap == nullptr) { currentBinaryLabelmap = vtkSmartPointer<vtkOrientedImageData>::New(); // Extent int currentSegmentExtent[6] = { 0, -1, 0, -1, 0, -1 }; std::string currentExtentString; if (this->GetSegmentMetaDataFromDicitionary(currentExtentString, dictionary, segmentIndex, KEY_SEGMENT_EXTENT)) { GetImageExtentFromString(currentSegmentExtent, currentExtentString); } else { vtkWarningMacro("Segment extent is missing for segment " << segmentIndex); for (int i = 0; i < 6; i++) { currentSegmentExtent[i] = imageExtentInFile[i]; } } for (int i = 0; i < 3; i++) { currentSegmentExtent[i * 2] += referenceImageExtentOffset[i]; currentSegmentExtent[i * 2 + 1] += referenceImageExtentOffset[i]; } // Copy with clipping to specified extent if (currentSegmentExtent[0] <= currentSegmentExtent[1] && currentSegmentExtent[2] <= currentSegmentExtent[3] && currentSegmentExtent[4] <= currentSegmentExtent[5]) { // non-empty segment extractComponents->SetComponents(frameIndex); padder->SetOutputWholeExtent(currentSegmentExtent); padder->Update(); currentBinaryLabelmap->DeepCopy(padder->GetOutput()); } else { // empty segment for (int i = 0; i < 3; ++i) { currentSegmentExtent[2 * i] = 0; currentSegmentExtent[2 * i + 1] = -1; } currentBinaryLabelmap->SetExtent(currentSegmentExtent); currentBinaryLabelmap->AllocateScalars(VTK_UNSIGNED_CHAR, 1); } currentBinaryLabelmap->SetImageToWorldMatrix(imageToWorldMatrix.GetPointer()); } // Set loaded binary labelmap to segment currentSegment->AddRepresentation(vtkSegmentationConverter::GetSegmentationBinaryLabelmapRepresentationName(), currentBinaryLabelmap); segments[segmentIndex] = currentSegment; } } } // Add the created segments to the segmentation for (int segmentIndex = 0; segmentIndex < static_cast<int>(segments.size()); ++segmentIndex) { vtkSegment* currentSegment = segments[segmentIndex]; if (!currentSegment) { vtkErrorMacro("Could not find segment" << segmentIndex); continue; } std::string currentSegmentID; if (numberOfSegments != 0) { // ID if (!this->GetSegmentMetaDataFromDicitionary(currentSegmentID, dictionary, segmentIndex, KEY_SEGMENT_ID)) { // No segment ID is specified, which may mean that it is an empty segmentation. // We consider a segmentation empty if it has only one scalar component that is empty. if (numberOfFrames == 1) { extractComponents->SetComponents(segmentIndex); extractComponents->Update(); vtkImageData* labelmap = extractComponents->GetOutput(); double* scalarRange = labelmap->GetScalarRange(); if (scalarRange[0] >= scalarRange[1]) { // Segmentation contains a single blank segment without segment ID, // which means that it is an empty segmentation. // It may still contain valuable metadata, but we don't create any segments. break; } } currentSegmentID = segmentation->GenerateUniqueSegmentID("Segment"); vtkWarningMacro("Segment ID is missing for segment " << segmentIndex << " adding segment with ID: " << currentSegmentID); } // Name std::string segmentName; if (this->GetSegmentMetaDataFromDicitionary(segmentName, dictionary, segmentIndex, KEY_SEGMENT_NAME)) { currentSegment->SetName(segmentName.c_str()); } else { vtkWarningMacro("Segment name is missing for segment " << segmentIndex); currentSegment->SetName(currentSegmentID.c_str()); } } else { std::stringstream segmentNameSS; segmentNameSS << "Segment_" << currentSegment->GetLabelValue(); currentSegmentID = segmentation->GenerateUniqueSegmentID(segmentNameSS.str()); currentSegment->SetName(currentSegmentID.c_str()); } segmentation->AddSegment(currentSegment, currentSegmentID); } // Create contained representations now that all the data is loaded this->CreateRepresentationsBySerializedNames(segmentation, containedRepresentationNames); return 1; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::ReadPolyDataRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!vtksys::SystemTools::FileExists(path.c_str())) { vtkErrorMacro("ReadPolyDataRepresentation: Input file " << path << " does not exist!"); return 0; } // Set up output segmentation if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { vtkErrorMacro("ReadPolyDataRepresentation: Output segmentation must exist and must be empty!"); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); // Add all files to storage node (multiblock dataset writes segments to individual files in a separate folder) this->AddPolyDataFileNames(path, segmentation); // Read multiblock dataset from disk vtkSmartPointer<vtkXMLMultiBlockDataReader> reader = vtkSmartPointer<vtkXMLMultiBlockDataReader>::New(); reader->SetFileName(path.c_str()); reader->Update(); vtkMultiBlockDataSet* multiBlockDataset = vtkMultiBlockDataSet::SafeDownCast(reader->GetOutput()); if (!multiBlockDataset || multiBlockDataset->GetNumberOfBlocks()==0) { vtkErrorMacro("ReadPolyDataRepresentation: Failed to read file " << path); return 0; } MRMLNodeModifyBlocker blocker(segmentationNode); // Read segment poly datas std::string masterRepresentationName; std::string containedRepresentationNames; std::string conversionParameters; for (unsigned int blockIndex = 0; blockIndex<multiBlockDataset->GetNumberOfBlocks(); ++blockIndex) { // Get poly data representation vtkPolyData* currentPolyData = vtkPolyData::SafeDownCast(multiBlockDataset->GetBlock(blockIndex)); // Set master representation if it has not been set yet // (there is no global place to store it, but every segment field data contains a copy of it) if (masterRepresentationName.empty()) { vtkStringArray* masterRepresentationArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_MASTER_REPRESENTATION).c_str())); if (!masterRepresentationArray) { vtkErrorMacro("ReadPolyDataRepresentation: Unable to find master representation for segmentation in file " << path); return 0; } masterRepresentationName = masterRepresentationArray->GetValue(0); segmentation->SetMasterRepresentationName(masterRepresentationName.c_str()); } // Read conversion parameters (stored in each segment file, but need to set only once) if ( conversionParameters.empty() && currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str()) ) { vtkStringArray* conversionParametersArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str()) ); conversionParameters = conversionParametersArray->GetValue(0); segmentation->DeserializeConversionParameters(conversionParameters); } // Read contained representation names if ( containedRepresentationNames.empty() && currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str()) ) { containedRepresentationNames = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str()) )->GetValue(0); } // Create segment vtkSmartPointer<vtkSegment> currentSegment = vtkSmartPointer<vtkSegment>::New(); currentSegment->AddRepresentation(segmentation->GetMasterRepresentationName(), currentPolyData); // Set segment properties std::string currentSegmentID; vtkStringArray* idArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_ID).c_str()) ); if (idArray && idArray->GetNumberOfValues()>0) { currentSegmentID = idArray->GetValue(0); } else { vtkWarningMacro("ReadPolyDataRepresentation: Segment ID property not found when reading segment " << blockIndex << " from file " << path); } std::string currentSegmentName; vtkStringArray* nameArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME).c_str()) ); if (nameArray && nameArray->GetNumberOfValues()>0) { currentSegmentName = nameArray->GetValue(0); } else { vtkWarningMacro("ReadPolyDataRepresentation: Segment Name property not found when reading segment " << blockIndex << " from file " << path); std::stringstream ssCurrentSegmentName; ssCurrentSegmentName << "Segment " << blockIndex; currentSegmentName = ssCurrentSegmentName.str(); } currentSegment->SetName(currentSegmentName.c_str()); double color[3]={1.0, 0.0, 0.0}; vtkDoubleArray* colorArray = vtkDoubleArray::SafeDownCast( currentPolyData->GetFieldData()->GetArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR).c_str()) ); if (!colorArray || colorArray->GetNumberOfTuples() == 0) { // Backwards compatibility colorArray = vtkDoubleArray::SafeDownCast( currentPolyData->GetFieldData()->GetArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, "DefaultColor").c_str()) ); } if (colorArray && colorArray->GetNumberOfTuples() > 0 && colorArray->GetNumberOfComponents() == 3) { colorArray->GetTuple(0, color); } else { vtkWarningMacro("ReadPolyDataRepresentation: Segment color property not found when reading segment " << blockIndex << " from file " << path); } currentSegment->SetColor(color); // Tags vtkStringArray* tagsArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_TAGS).c_str()) ); if (tagsArray) { std::string tags(tagsArray->GetValue(0).c_str()); std::string separatorCharacter("|"); size_t separatorPosition = tags.find(separatorCharacter); while (separatorPosition != std::string::npos) { std::string mapPairStr = tags.substr(0, separatorPosition); size_t colonPosition = mapPairStr.find(":"); if (colonPosition == std::string::npos) { continue; } currentSegment->SetTag(mapPairStr.substr(0, colonPosition), mapPairStr.substr(colonPosition+1)); tags = tags.substr(separatorPosition+1); separatorPosition = tags.find(separatorCharacter); } } // NameAutoGenerated vtkStringArray* nameAutoGeneratedArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME_AUTO_GENERATED).c_str()) ); if (nameAutoGeneratedArray && nameAutoGeneratedArray->GetNumberOfValues()>0) { currentSegment->SetNameAutoGenerated(!nameAutoGeneratedArray->GetValue(0).compare("1")); } // ColorAutoGenerated vtkStringArray* colorAutoGeneratedArray = vtkStringArray::SafeDownCast( currentPolyData->GetFieldData()->GetAbstractArray(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR_AUTO_GENERATED).c_str()) ); if (colorAutoGeneratedArray && colorAutoGeneratedArray->GetNumberOfValues()>0) { currentSegment->SetColorAutoGenerated(!colorAutoGeneratedArray->GetValue(0).compare("1")); } // Add segment to segmentation segmentation->AddSegment(currentSegment, currentSegmentID); } // Create contained representations now that all the data is loaded this->CreateRepresentationsBySerializedNames(segmentation, containedRepresentationNames); return 1; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::WriteDataInternal(vtkMRMLNode *refNode) { std::string fullName = this->GetFullNameFromFileName(); if (fullName.empty()) { vtkErrorMacro("vtkMRMLModelNode: File name not specified"); return 0; } vtkMRMLSegmentationNode *segmentationNode = vtkMRMLSegmentationNode::SafeDownCast(refNode); if (segmentationNode == nullptr) { vtkErrorMacro("Segmentation node expected. Unable to write node to file."); return 0; } if (segmentationNode->GetSegmentation() == nullptr) { vtkErrorMacro("Segmentation node does not contain segmentation object. Unable to write node to file."); return 0; } // Write only master representation if (segmentationNode->GetSegmentation()->IsMasterRepresentationImageData()) { return this->WriteBinaryLabelmapRepresentation(segmentationNode, fullName); } else if (segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData()) { return this->WritePolyDataRepresentation(segmentationNode, fullName); } vtkErrorMacro("Segmentation master representation " << segmentationNode->GetSegmentation()->GetMasterRepresentationName() << " cannot be written to file"); return 0; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::WriteBinaryLabelmapRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string fullName) { if (!segmentationNode) { vtkErrorMacro("WriteBinaryLabelmapRepresentation: Invalid segmentation to write to disk"); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); segmentation->CollapseBinaryLabelmaps(false); // Get and check master representation if (!segmentationNode->GetSegmentation()->IsMasterRepresentationImageData()) { vtkErrorMacro("WriteBinaryLabelmapRepresentation: Invalid master representation to write as image data"); return 0; } vtkIdType scalarType = VTK_UNSIGNED_CHAR; vtkIdType scalarSize = 0; std::vector< std::string > segmentIDs; segmentation->GetSegmentIDs(segmentIDs); for (std::vector< std::string >::const_iterator segmentIdIt = segmentIDs.begin(); segmentIdIt != segmentIDs.end(); ++segmentIdIt) { std::string currentSegmentID = *segmentIdIt; vtkSegment* currentSegment = segmentation->GetSegment(*segmentIdIt); vtkSmartPointer<vtkOrientedImageData> currentBinaryLabelmap = vtkOrientedImageData::SafeDownCast( currentSegment->GetRepresentation(segmentationNode->GetSegmentation()->GetMasterRepresentationName())); if (currentBinaryLabelmap->GetScalarSize() > scalarSize) { scalarSize = currentBinaryLabelmap->GetScalarSize(); scalarType = currentBinaryLabelmap->GetScalarType(); } } // Determine shared labelmap dimensions and properties vtkSmartPointer<vtkOrientedImageData> commonGeometryImage = vtkSmartPointer<vtkOrientedImageData>::New(); int commonGeometryExtent[6] = { 0, -1, 0, -1, 0, -1 }; if (segmentation->GetNumberOfSegments() > 0) { std::string commonGeometryString = segmentation->DetermineCommonLabelmapGeometry( this->CropToMinimumExtent ? vtkSegmentation::EXTENT_UNION_OF_EFFECTIVE_SEGMENTS : vtkSegmentation::EXTENT_REFERENCE_GEOMETRY); vtkSegmentationConverter::DeserializeImageGeometry(commonGeometryString, commonGeometryImage, true, scalarType, 1); commonGeometryImage->GetExtent(commonGeometryExtent); } if (commonGeometryExtent[0] > commonGeometryExtent[1] || commonGeometryExtent[2] > commonGeometryExtent[3] || commonGeometryExtent[4] > commonGeometryExtent[5]) { // common image is empty, which cannot be written to image file // change it to a 1x1x1 image instead commonGeometryExtent[0] = 0; commonGeometryExtent[1] = 0; commonGeometryExtent[2] = 0; commonGeometryExtent[3] = 0; commonGeometryExtent[4] = 0; commonGeometryExtent[5] = 0; commonGeometryImage->SetExtent(commonGeometryExtent); commonGeometryImage->AllocateScalars(scalarType, 1); } vtkOrientedImageDataResample::FillImage(commonGeometryImage, 0); vtkNew<vtkTeemNRRDWriter> writer; writer->SetFileName(fullName.c_str()); writer->SetUseCompression(this->GetUseCompression()); writer->SetSpace(nrrdSpaceLeftPosteriorSuperior); writer->SetMeasurementFrameMatrix(nullptr); // Create metadata dictionary // Save extent start of common geometry image so that we can restore original extents when reading from file //writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_EXTENT).c_str(), GetImageExtentAsString(commonGeometryImage)); int referenceImageExtentOffset[3] = { commonGeometryExtent[0], commonGeometryExtent[2], commonGeometryExtent[4] }; std::stringstream ssReferenceImageExtentOffset; ssReferenceImageExtentOffset << referenceImageExtentOffset[0] << " " << referenceImageExtentOffset[1] << " " << referenceImageExtentOffset[2]; writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_REFERENCE_IMAGE_EXTENT_OFFSET).c_str(), ssReferenceImageExtentOffset.str()); vtkNew<vtkMatrix4x4> rasToIjk; commonGeometryImage->GetWorldToImageMatrix(rasToIjk.GetPointer()); // Compensate for the extent shift in the image origin: vtkNew<vtkMatrix4x4> ijkToFileIjk; ijkToFileIjk->SetElement(0, 3, -referenceImageExtentOffset[0]); ijkToFileIjk->SetElement(1, 3, -referenceImageExtentOffset[1]); ijkToFileIjk->SetElement(2, 3, -referenceImageExtentOffset[2]); vtkNew<vtkMatrix4x4> rasToFileIjk; vtkMatrix4x4::Multiply4x4(ijkToFileIjk.GetPointer(), rasToIjk.GetPointer(), rasToFileIjk.GetPointer()); vtkNew<vtkMatrix4x4> fileIjkToRas; vtkMatrix4x4::Invert(rasToFileIjk.GetPointer(), fileIjkToRas.GetPointer()); writer->SetIJKToRASMatrix(fileIjkToRas.GetPointer()); // Save master representation name writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_MASTER_REPRESENTATION).c_str(), segmentationNode->GetSegmentation()->GetMasterRepresentationName()); // Save conversion parameters std::string conversionParameters = segmentation->SerializeAllConversionParameters(); writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str(), conversionParameters); // Save created representation names so that they are re-created when loading std::string containedRepresentationNames = this->SerializeContainedRepresentationNames(segmentation); writer->SetAttribute(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str(), containedRepresentationNames); vtkNew<vtkImageAppendComponents> appender; unsigned int layerIndex = 0; std::map<vtkDataObject*, int> labelmapLayers; // Dimensions of the output 4D NRRD file: (i, j, k, segment) unsigned int segmentIndex = 0; for (std::vector< std::string >::const_iterator segmentIdIt = segmentIDs.begin(); segmentIdIt != segmentIDs.end(); ++segmentIdIt, ++segmentIndex) { std::string currentSegmentID = *segmentIdIt; vtkSegment* currentSegment = segmentation->GetSegment(*segmentIdIt); // Get master representation from segment vtkSmartPointer<vtkOrientedImageData> currentBinaryLabelmap = vtkOrientedImageData::SafeDownCast( currentSegment->GetRepresentation(segmentationNode->GetSegmentation()->GetMasterRepresentationName())); if (!currentBinaryLabelmap) { vtkErrorMacro("WriteBinaryLabelmapRepresentation: Failed to retrieve master representation from segment " << currentSegmentID); continue; } int currentBinaryLabelmapExtent[6] = { 0, -1, 0, -1, 0, -1 }; currentBinaryLabelmap->GetExtent(currentBinaryLabelmapExtent); if (currentBinaryLabelmapExtent[0] <= currentBinaryLabelmapExtent[1] && currentBinaryLabelmapExtent[2] <= currentBinaryLabelmapExtent[3] && currentBinaryLabelmapExtent[4] <= currentBinaryLabelmapExtent[5]) { // There is a valid labelmap // Get transformed extents of the segment in the common labelmap geometry vtkNew<vtkTransform> currentBinaryLabelmapToCommonGeometryImageTransform; vtkOrientedImageDataResample::GetTransformBetweenOrientedImages(currentBinaryLabelmap, commonGeometryImage, currentBinaryLabelmapToCommonGeometryImageTransform.GetPointer()); int currentBinaryLabelmapExtentInCommonGeometryImageFrame[6] = { 0, -1, 0, -1, 0, -1 }; vtkOrientedImageDataResample::TransformExtent(currentBinaryLabelmapExtent, currentBinaryLabelmapToCommonGeometryImageTransform.GetPointer(), currentBinaryLabelmapExtentInCommonGeometryImageFrame); for (int i = 0; i < 3; i++) { currentBinaryLabelmapExtent[i * 2] = std::max(currentBinaryLabelmapExtentInCommonGeometryImageFrame[i * 2], commonGeometryExtent[i * 2]); currentBinaryLabelmapExtent[i * 2 + 1] = std::min(currentBinaryLabelmapExtentInCommonGeometryImageFrame[i * 2 + 1], commonGeometryExtent[i * 2 + 1]); } // TODO: maybe calculate effective extent to make sure the data is as compact as possible? (saving may be a good time to make segments more compact) // Pad/resample current binary labelmap representation to common geometry vtkSmartPointer<vtkOrientedImageData> resampledCurrentBinaryLabelmap = vtkSmartPointer<vtkOrientedImageData>::New(); bool success = vtkOrientedImageDataResample::ResampleOrientedImageToReferenceOrientedImage( currentBinaryLabelmap, commonGeometryImage, resampledCurrentBinaryLabelmap); if (!success) { vtkWarningMacro("WriteBinaryLabelmapRepresentation: Segment " << currentSegmentID << " cannot be resampled to common geometry!"); continue; } // currentBinaryLabelmap smart pointer will keep the temporary labelmap valid until it is needed currentBinaryLabelmap = resampledCurrentBinaryLabelmap; if (currentBinaryLabelmap->GetScalarType() != scalarType) { vtkNew<vtkImageCast> castFilter; castFilter->SetInputData(resampledCurrentBinaryLabelmap); castFilter->SetOutputScalarType(scalarType); castFilter->Update(); currentBinaryLabelmap->ShallowCopy(castFilter->GetOutput()); } } else { // empty segment, use the commonGeometryImage (filled with 0) currentBinaryLabelmap = commonGeometryImage; } // Set metadata for current segment writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_ID).c_str(), currentSegmentID); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME).c_str(), currentSegment->GetName()); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR).c_str(), GetSegmentColorAsString(segmentationNode, currentSegmentID)); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_NAME_AUTO_GENERATED).c_str(), (currentSegment->GetNameAutoGenerated() ? "1" : "0") ); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_COLOR_AUTO_GENERATED).c_str(), (currentSegment->GetColorAutoGenerated() ? "1" : "0") ); // Save the geometry relative to the current image (so that the extent in the file describe the extent of the segment in the // saved image buffer) for (int i = 0; i < 3; i++) { currentBinaryLabelmapExtent[i * 2] -= referenceImageExtentOffset[i]; currentBinaryLabelmapExtent[i * 2 + 1] -= referenceImageExtentOffset[i]; } writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_EXTENT).c_str(), GetImageExtentAsString(currentBinaryLabelmapExtent)); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_TAGS).c_str(), GetSegmentTagsAsString(currentSegment)); std::stringstream labelValueSS; labelValueSS << currentSegment->GetLabelValue(); writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_LABEL_VALUE).c_str(), labelValueSS.str()); vtkDataObject* originalRepresentation = currentSegment->GetRepresentation(segmentationNode->GetSegmentation()->GetMasterRepresentationName()); if (labelmapLayers.find(originalRepresentation) == labelmapLayers.end()) { labelmapLayers[originalRepresentation] = layerIndex; appender->AddInputData(currentBinaryLabelmap); ++layerIndex; } unsigned int layer = labelmapLayers[originalRepresentation]; std::stringstream layerIndexSS; layerIndexSS << layer; writer->SetAttribute(GetSegmentMetaDataKey(segmentIndex, KEY_SEGMENT_LAYER).c_str(), layerIndexSS.str()); } // For each segment if (segmentationNode->GetSegmentation()->GetNumberOfSegments() > 0) { appender->Update(); writer->SetInputConnection(appender->GetOutputPort()); writer->SetVectorAxisKind(nrrdKindList); } else { // If there are no segments, we still write the data so that we can store // various metadata fields. writer->SetInputData(commonGeometryImage); } writer->Write(); int writeFlag = 1; if (writer->GetWriteError()) { vtkErrorMacro("ERROR writing NRRD file " << (writer->GetFileName() == nullptr ? "null" : writer->GetFileName())); writeFlag = 0; } return writeFlag; } //---------------------------------------------------------------------------- int vtkMRMLSegmentationStorageNode::WritePolyDataRepresentation(vtkMRMLSegmentationNode* segmentationNode, std::string path) { if (!segmentationNode || segmentationNode->GetSegmentation()->GetNumberOfSegments() == 0) { vtkErrorMacro("WritePolyDataRepresentation: Invalid segmentation to write to disk"); return 0; } vtkSegmentation* segmentation = segmentationNode->GetSegmentation(); // Get and check master representation if (!segmentationNode->GetSegmentation()->IsMasterRepresentationPolyData()) { vtkErrorMacro("WritePolyDataRepresentation: Invalid master representation to write as poly data"); return 0; } // Initialize dataset to write vtkSmartPointer<vtkMultiBlockDataSet> multiBlockDataset = vtkSmartPointer<vtkMultiBlockDataSet>::New(); multiBlockDataset->SetNumberOfBlocks(segmentation->GetNumberOfSegments()); // Add segment polydata objects to dataset std::vector< std::string > segmentIDs; segmentation->GetSegmentIDs(segmentIDs); unsigned int segmentIndex = 0; for (std::vector< std::string >::const_iterator segmentIdIt = segmentIDs.begin(); segmentIdIt != segmentIDs.end(); ++segmentIdIt, ++segmentIndex) { std::string currentSegmentID = *segmentIdIt; vtkSegment* currentSegment = segmentation->GetSegment(*segmentIdIt); // Get master representation from segment vtkPolyData* currentPolyData = vtkPolyData::SafeDownCast(currentSegment->GetRepresentation( segmentationNode->GetSegmentation()->GetMasterRepresentationName())); if (!currentPolyData) { vtkErrorMacro("WritePolyDataRepresentation: Failed to retrieve master representation from segment " << currentSegmentID); continue; } // Make temporary duplicate of the poly data so that adding the metadata does not cause invalidating the other // representations (which is done when the master representation is modified) vtkSmartPointer<vtkPolyData> currentPolyDataCopy = vtkSmartPointer<vtkPolyData>::New(); currentPolyDataCopy->ShallowCopy(currentPolyData); // Set metadata for current segment // MasterRepresentation vtkSmartPointer<vtkStringArray> masterRepresentationArray = vtkSmartPointer<vtkStringArray>::New(); masterRepresentationArray->SetNumberOfValues(1); masterRepresentationArray->SetValue(0, segmentationNode->GetSegmentation()->GetMasterRepresentationName()); masterRepresentationArray->SetName(GetSegmentationMetaDataKey(KEY_SEGMENTATION_MASTER_REPRESENTATION).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(masterRepresentationArray); // ID vtkSmartPointer<vtkStringArray> idArray = vtkSmartPointer<vtkStringArray>::New(); idArray->SetNumberOfValues(1); idArray->SetValue(0,currentSegmentID.c_str()); idArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_ID).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(idArray); // Name vtkSmartPointer<vtkStringArray> nameArray = vtkSmartPointer<vtkStringArray>::New(); nameArray->SetNumberOfValues(1); nameArray->SetValue(0,currentSegment->GetName()); nameArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(nameArray); // Color vtkSmartPointer<vtkDoubleArray> colorArray = vtkSmartPointer<vtkDoubleArray>::New(); colorArray->SetNumberOfComponents(3); colorArray->SetNumberOfTuples(1); colorArray->SetTuple(0, currentSegment->GetColor()); colorArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(colorArray); // Tags std::map<std::string,std::string> tags; currentSegment->GetTags(tags); std::stringstream ssTags; std::map<std::string,std::string>::iterator tagIt; for (tagIt=tags.begin(); tagIt!=tags.end(); ++tagIt) { ssTags << tagIt->first << ":" << tagIt->second << "|"; } vtkSmartPointer<vtkStringArray> tagsArray = vtkSmartPointer<vtkStringArray>::New(); tagsArray->SetNumberOfValues(1); tagsArray->SetValue(0,ssTags.str().c_str()); tagsArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_TAGS).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(tagsArray); // NameAutoGenerated vtkSmartPointer<vtkStringArray> nameAutoGeneratedArray = vtkSmartPointer<vtkStringArray>::New(); nameAutoGeneratedArray->SetNumberOfValues(1); nameAutoGeneratedArray->SetValue(0, (currentSegment->GetNameAutoGenerated() ? "1" : "0") ); nameAutoGeneratedArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_NAME_AUTO_GENERATED).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(nameAutoGeneratedArray); // ColorAutoGenerated vtkSmartPointer<vtkStringArray> colorAutoGeneratedArray = vtkSmartPointer<vtkStringArray>::New(); colorAutoGeneratedArray->SetNumberOfValues(1); colorAutoGeneratedArray->SetValue(0, (currentSegment->GetColorAutoGenerated() ? "1" : "0") ); colorAutoGeneratedArray->SetName(GetSegmentMetaDataKey(SINGLE_SEGMENT_INDEX, KEY_SEGMENT_COLOR_AUTO_GENERATED).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(colorAutoGeneratedArray); // Save conversion parameters as metadata (save in each segment file) std::string conversionParameters = segmentation->SerializeAllConversionParameters(); vtkSmartPointer<vtkStringArray> conversionParametersArray = vtkSmartPointer<vtkStringArray>::New(); conversionParametersArray->SetNumberOfValues(1); conversionParametersArray->SetValue(0,conversionParameters); conversionParametersArray->SetName(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONVERSION_PARAMETERS).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(conversionParametersArray); // Save contained representation names as metadata (save in each segment file) std::string containedRepresentationNames = this->SerializeContainedRepresentationNames(segmentation); vtkSmartPointer<vtkStringArray> containedRepresentationNamesArray = vtkSmartPointer<vtkStringArray>::New(); containedRepresentationNamesArray->SetNumberOfValues(1); containedRepresentationNamesArray->SetValue(0,containedRepresentationNames); containedRepresentationNamesArray->SetName(GetSegmentationMetaDataKey(KEY_SEGMENTATION_CONTAINED_REPRESENTATION_NAMES).c_str()); currentPolyDataCopy->GetFieldData()->AddArray(containedRepresentationNamesArray); // Set segment poly data to dataset multiBlockDataset->SetBlock(segmentIndex, currentPolyDataCopy); } // Write multiblock dataset to disk vtkSmartPointer<vtkXMLMultiBlockDataWriter> writer = vtkSmartPointer<vtkXMLMultiBlockDataWriter>::New(); writer->SetInputData(multiBlockDataset); writer->SetFileName(path.c_str()); if (this->UseCompression) { writer->SetDataModeToBinary(); writer->SetCompressorTypeToZLib(); } else { writer->SetDataModeToAscii(); writer->SetCompressorTypeToNone(); } writer->Write(); // Add all files to storage node (multiblock dataset writes segments to individual files in a separate folder) this->AddPolyDataFileNames(path, segmentation); return 1; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::AddPolyDataFileNames(std::string path, vtkSegmentation* segmentation) { if (!segmentation) { vtkErrorMacro("AddPolyDataFileNames: Invalid segmentation!"); return; } this->AddFileName(path.c_str()); std::string fileNameWithoutExtension = vtksys::SystemTools::GetFilenameWithoutLastExtension(path); std::string parentDirectory = vtksys::SystemTools::GetParentDirectory(path); std::string multiBlockDirectory = parentDirectory + "/" + fileNameWithoutExtension; for (int segmentIndex = 0; segmentIndex < segmentation->GetNumberOfSegments(); ++segmentIndex) { std::stringstream ssSegmentFilePath; ssSegmentFilePath << multiBlockDirectory << "/" << fileNameWithoutExtension << "_" << segmentIndex << ".vtp"; std::string segmentFilePath = ssSegmentFilePath.str(); this->AddFileName(segmentFilePath.c_str()); } } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::SerializeContainedRepresentationNames(vtkSegmentation* segmentation) { if (!segmentation) { vtkErrorMacro("SerializeContainedRepresentationNames: Invalid segmentation!"); return ""; } std::stringstream ssRepresentationNames; std::vector<std::string> containedRepresentationNames; segmentation->GetContainedRepresentationNames(containedRepresentationNames); for (std::vector<std::string>::iterator reprIt = containedRepresentationNames.begin(); reprIt != containedRepresentationNames.end(); ++reprIt) { ssRepresentationNames << (*reprIt) << SERIALIZATION_SEPARATOR; } return ssRepresentationNames.str(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::CreateRepresentationsBySerializedNames(vtkSegmentation* segmentation, std::string representationNames) { if (!segmentation) { vtkErrorMacro("CreateRepresentationsBySerializedNames: Invalid segmentation!"); return; } if (segmentation->GetNumberOfSegments() == 0) { vtkDebugMacro("CreateRepresentationsBySerializedNames: Segmentation is empty, nothing to do"); return; } if (representationNames.empty()) { vtkDebugMacro("CreateRepresentationsBySerializedNames: Empty representation names list, nothing to create"); return; } std::string masterRepresentation(segmentation->GetMasterRepresentationName()); size_t separatorPosition = representationNames.find(SERIALIZATION_SEPARATOR); while (separatorPosition != std::string::npos) { std::string representationName = representationNames.substr(0, separatorPosition); // Only create non-master representations if (representationName.compare(masterRepresentation)) { segmentation->CreateRepresentation(representationName); } representationNames = representationNames.substr(separatorPosition+1); separatorPosition = representationNames.find(SERIALIZATION_SEPARATOR); } } //---------------------------------------------------------------------------- bool vtkMRMLSegmentationStorageNode::GetSegmentMetaDataFromDicitionary(std::string& headerValue, itk::MetaDataDictionary dictionary, int segmentIndex, std::string keyName) { if (!dictionary.HasKey(GetSegmentMetaDataKey(segmentIndex, keyName))) { return false; } itk::ExposeMetaData<std::string>(dictionary, GetSegmentMetaDataKey(segmentIndex, keyName), headerValue); return true; } //---------------------------------------------------------------------------- bool vtkMRMLSegmentationStorageNode::GetSegmentationMetaDataFromDicitionary(std::string& headerValue, itk::MetaDataDictionary dictionary, std::string keyName) { if (!dictionary.HasKey(GetSegmentationMetaDataKey(keyName))) { return false; } itk::ExposeMetaData<std::string>(dictionary, GetSegmentationMetaDataKey(keyName), headerValue); return true; } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentMetaDataKey(int segmentIndex, const std::string& keyName) { std::stringstream key; key << "Segment"; if (segmentIndex != SINGLE_SEGMENT_INDEX) { key << segmentIndex; } key << "_" << keyName; return key.str(); } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentationMetaDataKey(const std::string& keyName) { std::stringstream key; key << "Segmentation" << "_" << keyName; return key.str(); } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentTagsAsString(vtkSegment* segment) { std::map<std::string, std::string> tags; if (segment) { segment->GetTags(tags); } std::stringstream ssTagsValue; std::map<std::string, std::string>::iterator tagIt; for (tagIt = tags.begin(); tagIt != tags.end(); ++tagIt) { ssTagsValue << tagIt->first << ":" << tagIt->second << "|"; } std::string tagsValue = ssTagsValue.str(); return tagsValue; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::SetSegmentTagsFromString(vtkSegment* segment, std::string tagsValue) { std::string separatorCharacter("|"); size_t separatorPosition = tagsValue.find(separatorCharacter); while (separatorPosition != std::string::npos) { std::string mapPairStr = tagsValue.substr(0, separatorPosition); size_t colonPosition = mapPairStr.find(":"); if (colonPosition == std::string::npos) { tagsValue = tagsValue.substr(separatorPosition + 1); separatorPosition = tagsValue.find(separatorCharacter); continue; } segment->SetTag(mapPairStr.substr(0, colonPosition), mapPairStr.substr(colonPosition + 1)); tagsValue = tagsValue.substr(separatorPosition + 1); separatorPosition = tagsValue.find(separatorCharacter); } } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetImageExtentAsString(vtkOrientedImageData* image) { int extent[6] = { 0, -1, 0, -1, 0, -1 }; if (image) { image->GetExtent(extent); } return GetImageExtentAsString(extent); } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetImageExtentAsString(int extent[6]) { std::stringstream ssExtentValue; ssExtentValue << extent[0] << " " << extent[1] << " " << extent[2] << " " << extent[3] << " " << extent[4] << " " << extent[5]; std::string extentValue = ssExtentValue.str(); return extentValue; } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::GetImageExtentFromString(int extent[6], std::string extentValue) { std::stringstream ssExtentValue(extentValue); extent[0] = 0; extent[1] = -1; extent[2] = 0; extent[3] = -1; extent[4] = 0; extent[5] = -1; ssExtentValue >> extent[0] >> extent[1] >> extent[2] >> extent[3] >> extent[4] >> extent[5]; } //---------------------------------------------------------------------------- std::string vtkMRMLSegmentationStorageNode::GetSegmentColorAsString(vtkMRMLSegmentationNode* segmentationNode, const std::string& segmentId) { double color[3] = { vtkSegment::SEGMENT_COLOR_INVALID[0], vtkSegment::SEGMENT_COLOR_INVALID[1], vtkSegment::SEGMENT_COLOR_INVALID[2] }; vtkSegment* segment = segmentationNode->GetSegmentation()->GetSegment(segmentId); if (segment) { segment->GetColor(color); } std::stringstream colorStream; colorStream << color[0] << " " << color[1] << " " << color[2]; return colorStream.str(); } //---------------------------------------------------------------------------- void vtkMRMLSegmentationStorageNode::GetSegmentColorFromString(double color[3], std::string colorString) { std::stringstream colorStream(colorString); color[0] = 0.5; color[1] = 0.5; color[2] = 0.5; colorStream >> color[0] >> color[1] >> color[2]; }
43.279403
202
0.708179
forfullstack
ffde21b56ac873665291a65e9a9c13bcb998a662
1,064
cpp
C++
rabbitsLife/rabbitsLife/Draw/DrawTruckYellow.cpp
VitorNevess/Rabbits-Life
24d46ca84ad441b25a37bc2d9a4b2c65a03d3d46
[ "Apache-2.0" ]
null
null
null
rabbitsLife/rabbitsLife/Draw/DrawTruckYellow.cpp
VitorNevess/Rabbits-Life
24d46ca84ad441b25a37bc2d9a4b2c65a03d3d46
[ "Apache-2.0" ]
1
2019-11-16T00:54:00.000Z
2019-11-16T00:54:00.000Z
rabbitsLife/rabbitsLife/Draw/DrawTruckYellow.cpp
VitorNevess/Rabbits-Life
24d46ca84ad441b25a37bc2d9a4b2c65a03d3d46
[ "Apache-2.0" ]
null
null
null
// // DrawTruckYellow.cpp // rabbitsLife // // Created by joao.vitor.f.naves on 13/10/19. // Copyright © 2019 vitor.neves. All rights reserved. // #define GL_SILENCE_DEPRECATION #include <GLUT/GLUT.h> class DrawTruckYellow { //public public: float xCloser = 0;//mais perto float xFurther = 0;//mais longe public: void truckYellow(int x){ glColor3f(1,1,0); glBegin(GL_QUADS); _truckYellow(x); glEnd(); glColor3f(1,1,1); glBegin(GL_POINTS); wheelsTruckYellow(x); glEnd(); } //private private: void _truckYellow(int x){ //CAMINHAO FRENTE glVertex2f(x+1,26);//Ponto A glVertex2f(x+3,26);//Ponto B glVertex2f(x+3,28);//Ponto C glVertex2f(x+1,28);//Ponto D //CAMINHAO TRASEIRA glVertex2f(x+2.5,26);//Ponto A glVertex2f(x+5,26);//Ponto B glVertex2f(x+5,29);//Ponto C glVertex2f(x+2.5,29);//Ponto D xCloser = x+1; xFurther = x+5; } private: void wheelsTruckYellow(int x){ glVertex2f(x+2,26);//Ponto A glVertex2f(x+4,26);//Ponto A } };
19.703704
54
0.620301
VitorNevess
ffe014718f2000d4a9a9296dacc787a66d5e5db0
5,003
cpp
C++
runtime/class.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
1
2021-09-09T03:17:23.000Z
2021-09-09T03:17:23.000Z
runtime/class.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
null
null
null
runtime/class.cpp
openharmony-gitee-mirror/ark_runtime_core
2e6f195caf482dc9607efda7cfb5cc5f98da5598
[ "Apache-2.0" ]
1
2021-09-13T11:21:57.000Z
2021-09-13T11:21:57.000Z
/* * Copyright (c) 2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include "libpandabase/macros.h" #include "libpandabase/utils/hash.h" #include "libpandabase/utils/logger.h" #include "libpandafile/class_data_accessor.h" #include "runtime/include/class-inl.h" #include "runtime/include/class_linker.h" #include "runtime/include/runtime.h" namespace panda { std::ostream &operator<<(std::ostream &os, const Class::State &state) { switch (state) { case Class::State::INITIAL: { os << "INITIAL"; break; } case Class::State::LOADED: { os << "LOADED"; break; } case Class::State::VERIFIED: { os << "VERIFIED"; break; } case Class::State::INITIALIZING: { os << "INITIALIZING"; break; } case Class::State::ERRONEOUS: { os << "ERRONEOUS"; break; } case Class::State::INITIALIZED: { os << "INITIALIZED"; break; } default: { UNREACHABLE(); break; } } return os; } Class::UniqId Class::CalcUniqId(const panda_file::File *file, panda_file::File::EntityId file_id) { constexpr uint64_t HALF = 32ULL; uint64_t uid = file->GetUniqId(); uid <<= HALF; uid |= file_id.GetOffset(); return uid; } Class::UniqId Class::CalcUniqId(const uint8_t *descriptor) { uint64_t uid; uid = GetHash32String(descriptor); constexpr uint64_t HALF = 32ULL; constexpr uint64_t NO_FILE = 0xFFFFFFFFULL << HALF; uid = NO_FILE | uid; return uid; } Class::UniqId Class::CalcUniqId() const { if (panda_file_ != nullptr) { return CalcUniqId(panda_file_, file_id_); } return CalcUniqId(descriptor_); } Class::Class(const uint8_t *descriptor, panda_file::SourceLang lang, uint32_t vtable_size, uint32_t imt_size, uint32_t size) : BaseClass(lang), descriptor_(descriptor), vtable_size_(vtable_size), imt_size_(imt_size), class_size_(size) { // Initializa all static fields with 0 value. auto statics_offset = GetStaticFieldsOffset(); auto sp = GetClassSpan(); ASSERT(sp.size() >= statics_offset); auto size_to_set = sp.size() - statics_offset; if (size_to_set > 0) { (void)memset_s(&sp[statics_offset], size_to_set, 0, size_to_set); } } void Class::SetState(Class::State state) { if (state_ == State::ERRONEOUS || state <= state_) { LOG(FATAL, RUNTIME) << "Invalid class state transition " << state_ << " -> " << state; } state_ = state; } std::string Class::GetName() const { return ClassHelper::GetName(descriptor_); } void Class::DumpClass(std::ostream &os, size_t flags) { if ((flags & DUMPCLASSFULLDETAILS) == 0) { os << GetDescriptor(); if ((flags & DUMPCLASSCLASSLODER) != 0) { LOG(INFO, RUNTIME) << " Panda can't get classloader at now\n"; } if ((flags & DUMPCLASSINITIALIZED) != 0) { LOG(INFO, RUNTIME) << " There is no status structure of class in Panda at now\n"; } os << "\n"; return; } os << "\n"; os << "----- " << (IsInterface() ? "interface" : "class") << " " << "'" << GetDescriptor() << "' -----\n"; os << " objectSize=" << BaseClass::GetObjectSize() << " \n"; os << " accessFlags=" << GetAccessFlags() << " \n"; if (IsArrayClass()) { os << " componentType=" << GetComponentType() << "\n"; } size_t num_direct_interfaces = this->num_ifaces_; if (num_direct_interfaces > 0) { os << " interfaces (" << num_direct_interfaces << "):\n"; } if (!IsLoaded()) { os << " class not yet loaded"; } else { os << " vtable (" << this->GetVTable().size() << " entries)\n"; if (this->num_sfields_ > 0) { os << " static fields (" << this->num_sfields_ << " entries)\n"; } if (this->num_fields_ - this->num_sfields_ > 0) { os << " instance fields (" << this->num_fields_ - this->num_sfields_ << " entries)\n"; } } } Class *Class::FromClassObject(const ObjectHeader *obj) { return Runtime::GetCurrent()->GetClassLinker()->ObjectToClass(obj); } size_t Class::GetClassObjectSizeFromClass(Class *cls) { return Runtime::GetCurrent()->GetClassLinker()->GetClassObjectSize(cls); } } // namespace panda
29.958084
113
0.59984
openharmony-gitee-mirror
ffe0ead6be26d6b7242ca321c59d350efa7b43b7
309
cpp
C++
GeneratorType.cpp
Xecutor/paparl
fb0096d49d11a4110ba4eb2b0d42508f9c87d4bc
[ "MIT" ]
null
null
null
GeneratorType.cpp
Xecutor/paparl
fb0096d49d11a4110ba4eb2b0d42508f9c87d4bc
[ "MIT" ]
null
null
null
GeneratorType.cpp
Xecutor/paparl
fb0096d49d11a4110ba4eb2b0d42508f9c87d4bc
[ "MIT" ]
null
null
null
#include "GeneratorType.hpp" std::string getGeneratorNameByType(GeneratorType gt) { using GT=GeneratorType; switch(gt) { case GT::downtown:return "Downtown"; case GT::seaport:return "Seaport"; case GT::suburbs:return "Suburbs"; case GT::warehouse:return "Warehouse"; } return ""; }
20.6
52
0.68932
Xecutor
ffe2da45917417d1bbc4c7e6d2fda4cb68ccf694
60,493
cpp
C++
c++/src/algo/blast/api/blast_options_cxx.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/algo/blast/api/blast_options_cxx.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/algo/blast/api/blast_options_cxx.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
#ifndef SKIP_DOXYGEN_PROCESSING static char const rcsid[] = "$Id: blast_options_cxx.cpp 371842 2012-08-13 13:56:38Z fongah2 $"; #endif /* SKIP_DOXYGEN_PROCESSING */ /* =========================================================================== * * PUBLIC DOMAIN NOTICE * National Center for Biotechnology Information * * This software/database is a "United States Government Work" under the * terms of the United States Copyright Act. It was written as part of * the author's official duties as a United States Government employee and * thus cannot be copyrighted. This software/database is freely available * to the public for use. The National Library of Medicine and the U.S. * Government have not placed any restriction on its use or reproduction. * * Although all reasonable efforts have been taken to ensure the accuracy * and reliability of the software and data, the NLM and the U.S. * Government do not and cannot warrant the performance or results that * may be obtained by using this software or data. The NLM and the U.S. * Government disclaim all warranties, express or implied, including * warranties of performance, merchantability or fitness for any particular * purpose. * * Please cite the author in any work or product based on this material. * * =========================================================================== * * Author: Christiam Camacho * */ /// @file blast_options_cxx.cpp /// Implements the CBlastOptions class, which encapsulates options structures /// from algo/blast/core #include <ncbi_pch.hpp> #include <algo/blast/api/blast_options.hpp> #include "blast_setup.hpp" #include "blast_options_local_priv.hpp" #include "blast_memento_priv.hpp" #include <algo/blast/core/blast_extend.h> #include <objects/seqloc/Seq_loc.hpp> #include <objects/blast/Blast4_cutoff.hpp> #include <objects/blast/names.hpp> /** @addtogroup AlgoBlast * * @{ */ BEGIN_NCBI_SCOPE USING_SCOPE(objects); BEGIN_SCOPE(blast) #ifndef SKIP_DOXYGEN_PROCESSING /// Encapsulates all blast input parameters class NCBI_XBLAST_EXPORT CBlastOptionsRemote : public CObject { public: CBlastOptionsRemote(void) : m_DefaultsMode(false) { m_ReqOpts.Reset(new objects::CBlast4_parameters); } ~CBlastOptionsRemote() { } /// Copy constructor CBlastOptionsRemote(const CBlastOptionsRemote& optsRemote) : m_DefaultsMode(false) { x_DoDeepCopy(optsRemote); } /// Assignment operator CBlastOptionsRemote& operator=(const CBlastOptionsRemote& optsRemote) { x_DoDeepCopy(optsRemote); return *this; } // the "new paradigm" typedef ncbi::objects::CBlast4_parameters TBlast4Opts; TBlast4Opts * GetBlast4AlgoOpts() { return m_ReqOpts; } typedef vector< CConstRef<objects::CSeq_loc> > TSeqLocVector; // SetValue(x,y) with different types: void SetValue(EBlastOptIdx opt, const EProgram & x); void SetValue(EBlastOptIdx opt, const int & x); void SetValue(EBlastOptIdx opt, const double & x); void SetValue(EBlastOptIdx opt, const char * x); void SetValue(EBlastOptIdx opt, const TSeqLocVector & x); void SetValue(EBlastOptIdx opt, const ESeedContainerType & x); void SetValue(EBlastOptIdx opt, const bool & x); void SetValue(EBlastOptIdx opt, const Int8 & x); // Pseudo-types: void SetValue(EBlastOptIdx opt, const short & x) { int x2 = x; SetValue(opt, x2); } void SetValue(EBlastOptIdx opt, const unsigned int & x) { int x2 = x; SetValue(opt, x2); } void SetValue(EBlastOptIdx opt, const unsigned char & x) { int x2 = x; SetValue(opt, x2); } void SetValue(EBlastOptIdx opt, const objects::ENa_strand & x) { int x2 = x; SetValue(opt, x2); } /// Remove any objects matching this Blast4 field object. /// /// The given field object represents a Blast4 field to remove /// from the list of remote options. /// /// @param opt Field object representing option to remove. void ResetValue(CBlast4Field & opt) { x_ResetValue(opt); } void SetDefaultsMode(bool dmode) { m_DefaultsMode = dmode; } bool GetDefaultsMode() { return m_DefaultsMode; } private: //CRef<objects::CBlast4_queue_search_request> m_Req; CRef<objects::CBlast4_parameters> m_ReqOpts; bool m_DefaultsMode; /// Perform a "deep copy" of remote Blast options /// @param optsRemote remote Blast options object to copy from. void x_DoDeepCopy(const CBlastOptionsRemote& optsRemote) { if (&optsRemote != this) { m_ReqOpts.Reset(new objects::CBlast4_parameters); m_ReqOpts->Assign(*optsRemote.m_ReqOpts); m_DefaultsMode = optsRemote.m_DefaultsMode; } } template<class T> void x_SetParam(CBlast4Field & name, T & value) { x_SetOneParam(name, & value); } void x_SetOneParam(CBlast4Field & field, const int * x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetInteger(*x); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_SetOneParam(CBlast4Field & field, const char ** x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetString().assign((x && (*x)) ? (*x) : ""); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_SetOneParam(CBlast4Field & field, const bool * x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetBoolean(*x); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_SetOneParam(CBlast4Field & field, CRef<objects::CBlast4_cutoff> * x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetCutoff(**x); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_SetOneParam(CBlast4Field & field, const double * x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetReal(*x); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_SetOneParam(CBlast4Field & field, const Int8 * x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetBig_integer(*x); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_SetOneParam(CBlast4Field & field, objects::EBlast4_strand_type * x) { CRef<objects::CBlast4_value> v(new objects::CBlast4_value); v->SetStrand_type(*x); CRef<objects::CBlast4_parameter> p(new objects::CBlast4_parameter); p->SetName(field.GetName()); p->SetValue(*v); x_AttachValue(p); } void x_AttachValue(CRef<objects::CBlast4_parameter> p) { typedef objects::CBlast4_parameter TParam; NON_CONST_ITERATE(list< CRef<TParam> >, iter, m_ReqOpts->Set()) { if ((**iter).GetName() == p->GetName()) { (*iter) = p; return; } } m_ReqOpts->Set().push_back(p); } /// Remove values for a given Blast4 field. /// @param f Field to search for and remove. void x_ResetValue(CBlast4Field & f) { typedef list< CRef<objects::CBlast4_parameter> > TParamList; typedef TParamList::iterator TParamIter; const string & nm = f.GetName(); TParamList & lst = m_ReqOpts->Set(); TParamIter pos = lst.begin(), end = lst.end(); while(pos != end) { TParamIter current = pos; pos++; if ((**current).GetName() == nm) { lst.erase(current); } } } void x_Throwx(const string& msg) const { NCBI_THROW(CBlastException, eInvalidOptions, msg); } }; CBlastOptions::CBlastOptions(EAPILocality locality) : m_Local (0), m_Remote(0), m_DefaultsMode(false) { if (locality == eRemote) locality = eBoth; if (locality != eRemote) { m_Local = new CBlastOptionsLocal(); } if (locality != eLocal) { m_Remote = new CBlastOptionsRemote(); } } CBlastOptions::~CBlastOptions() { if (m_Local) { delete m_Local; } if (m_Remote) { delete m_Remote; } } CRef<CBlastOptions> CBlastOptions::Clone() const { CRef<CBlastOptions> optsRef; optsRef.Reset(new CBlastOptions(GetLocality())); optsRef->x_DoDeepCopy(*this); return optsRef; } CBlastOptions::EAPILocality CBlastOptions::GetLocality(void) const { if (! m_Remote) { return eLocal; } if (! m_Local) { return eRemote; } return eBoth; } // Note: only some of the options are supported for the remote case; // An exception is thrown if the option is not available. void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const EProgram & v) { if (m_DefaultsMode) { return; } switch(opt) { case eBlastOpt_Program: return; default: break; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%d), line (%d).", int(opt), v, __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const int & v) { if (m_DefaultsMode) { return; } switch(opt) { case eBlastOpt_WordSize: x_SetParam(CBlast4Field::Get(opt), v); return; // Added for rmblastn and the new masklevel option. -RMH- case eBlastOpt_MaskLevel: x_SetParam(CBlast4Field::Get(opt),v); return; case eBlastOpt_LookupTableType: // do nothing, should be specified by the task return; case eBlastOpt_StrandOption: { typedef objects::EBlast4_strand_type TSType; TSType strand; bool set_strand = true; switch(v) { case 1: strand = eBlast4_strand_type_forward_strand; break; case 2: strand = eBlast4_strand_type_reverse_strand; break; case 3: strand = eBlast4_strand_type_both_strands; break; default: set_strand = false; } if (set_strand) { x_SetParam(CBlast4Field::Get(opt), strand); return; } } case eBlastOpt_WindowSize: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapOpeningCost: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapExtensionCost: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_HitlistSize: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_CutoffScore: if (0) { typedef objects::CBlast4_cutoff TCutoff; CRef<TCutoff> cutoff(new TCutoff); cutoff->SetRaw_score(v); x_SetParam(CBlast4Field::Get(opt), cutoff); } return; case eBlastOpt_MatchReward: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_MismatchPenalty: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_WordThreshold: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_PseudoCount: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_CompositionBasedStats: if (v < eNumCompoAdjustModes) { x_SetParam(CBlast4Field::Get(opt), v); return; } case eBlastOpt_MBTemplateLength: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_MBTemplateType: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapExtnAlgorithm: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapTracebackAlgorithm: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_SegFilteringWindow: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DustFilteringLevel: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DustFilteringWindow: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DustFilteringLinker: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_CullingLimit: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_LongestIntronLength: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_QueryGeneticCode: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DbGeneticCode: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_UnifiedP: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_WindowMaskerTaxId: x_SetParam(CBlast4Field::Get(opt), v); return; //For handling rpsblast save search strategy with mutli-dbs case eBlastOpt_DbSeqNum: case eBlastOpt_DbLength: return; default: break; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%d), line (%d).", int(opt), v, __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const double & v) { if (m_DefaultsMode) { return; } switch(opt) { case eBlastOpt_EvalueThreshold: { typedef objects::CBlast4_cutoff TCutoff; CRef<TCutoff> cutoff(new TCutoff); cutoff->SetE_value(v); x_SetParam(CBlast4Field::Get(opt), cutoff); } return; case eBlastOpt_PercentIdentity: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_InclusionThreshold: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapXDropoff: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapXDropoffFinal: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_XDropoff: //x_SetParam(B4Param_XDropoff, v); return; case eBlastOpt_SegFilteringLocut: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_SegFilteringHicut: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_GapTrigger: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_BestHitScoreEdge: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_BestHitOverhang: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DomainInclusionThreshold: x_SetParam(CBlast4Field::Get(opt), v); return; default: break; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%f), line (%d).", int(opt), v, __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const char * v) { if (m_DefaultsMode) { return; } switch(opt) { case eBlastOpt_FilterString: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_RepeatFilteringDB: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_MatrixName: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_WindowMaskerDatabase: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_PHIPattern: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_MbIndexName: x_SetParam(CBlast4Field::Get(opt), v); return; default: break; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%.20s), line (%d).", int(opt), v, __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const TSeqLocVector & v) { if (m_DefaultsMode) { return; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and TSeqLocVector (size %zd), line (%d).", int(opt), v.size(), __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const ESeedContainerType & v) { if (m_DefaultsMode) { return; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%d), line (%d).", int(opt), v, __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const bool & v) { if (m_DefaultsMode) { return; } switch(opt) { case eBlastOpt_GappedMode: { bool ungapped = ! v; x_SetParam(CBlast4Field::Get(opt), ungapped); // inverted return; } // Added for rmblastn and the new complexity adjusted scoring -RMH- case eBlastOpt_ComplexityAdjMode: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_OutOfFrameMode: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_SegFiltering: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DustFiltering: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_RepeatFiltering: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_MaskAtHash: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_SumStatisticsMode: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_SmithWatermanMode: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_ForceMbIndex: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_IgnoreMsaMaster: x_SetParam(CBlast4Field::Get(opt), v); return; default: break; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%s), line (%d).", int(opt), (v ? "true" : "false"), __LINE__); x_Throwx(string("err:") + errbuf); } void CBlastOptionsRemote::SetValue(EBlastOptIdx opt, const Int8 & v) { if (m_DefaultsMode) { return; } switch(opt) { case eBlastOpt_EffectiveSearchSpace: x_SetParam(CBlast4Field::Get(opt), v); return; case eBlastOpt_DbLength: x_SetParam(CBlast4Field::Get(opt), v); return; default: break; } char errbuf[1024]; sprintf(errbuf, "tried to set option (%d) and value (%f), line (%d).", int(opt), double(v), __LINE__); x_Throwx(string("err:") + errbuf); } const CBlastOptionsMemento* CBlastOptions::CreateSnapshot() const { if ( !m_Local ) { NCBI_THROW(CBlastException, eInvalidArgument, "Cannot create CBlastOptionsMemento without a local " "CBlastOptions object"); } return new CBlastOptionsMemento(m_Local); } bool CBlastOptions::operator==(const CBlastOptions& rhs) const { if (m_Local && rhs.m_Local) { return (*m_Local == *rhs.m_Local); } else { NCBI_THROW(CBlastException, eNotSupported, "Equality operator unsupported for arguments"); } } bool CBlastOptions::operator!=(const CBlastOptions& rhs) const { return !(*this == rhs); } bool CBlastOptions::Validate() const { bool local_okay = m_Local ? (m_Local ->Validate()) : true; return local_okay; } EProgram CBlastOptions::GetProgram() const { if (! m_Local) { x_Throwx("Error: GetProgram() not available."); } return m_Local->GetProgram(); } EBlastProgramType CBlastOptions::GetProgramType() const { if (! m_Local) { x_Throwx("Error: GetProgramType() not available."); } return m_Local->GetProgramType(); } void CBlastOptions::SetProgram(EProgram p) { if (m_Local) { m_Local->SetProgram(p); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_Program, p); } } /******************* Lookup table options ***********************/ double CBlastOptions::GetWordThreshold() const { if (! m_Local) { x_Throwx("Error: GetWordThreshold() not available."); } return m_Local->GetWordThreshold(); } void CBlastOptions::SetWordThreshold(double w) { if (m_Local) { m_Local->SetWordThreshold(w); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_WordThreshold, static_cast<int>(w)); } } ELookupTableType CBlastOptions::GetLookupTableType() const { if (! m_Local) { x_Throwx("Error: GetLookupTableType() not available."); } return m_Local->GetLookupTableType(); } void CBlastOptions::SetLookupTableType(ELookupTableType type) { if (m_Local) { m_Local->SetLookupTableType(type); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_LookupTableType, type); } } int CBlastOptions::GetWordSize() const { if (! m_Local) { x_Throwx("Error: GetWordSize() not available."); } return m_Local->GetWordSize(); } void CBlastOptions::SetWordSize(int ws) { if (m_Local) { m_Local->SetWordSize(ws); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_WordSize, ws); } } /// Megablast only lookup table options unsigned char CBlastOptions::GetMBTemplateLength() const { if (! m_Local) { x_Throwx("Error: GetMBTemplateLength() not available."); } return m_Local->GetMBTemplateLength(); } void CBlastOptions::SetMBTemplateLength(unsigned char len) { if (m_Local) { m_Local->SetMBTemplateLength(len); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MBTemplateLength, len); } } unsigned char CBlastOptions::GetMBTemplateType() const { if (! m_Local) { x_Throwx("Error: GetMBTemplateType() not available."); } return m_Local->GetMBTemplateType(); } void CBlastOptions::SetMBTemplateType(unsigned char type) { if (m_Local) { m_Local->SetMBTemplateType(type); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MBTemplateType, type); } } /******************* Query setup options ************************/ void CBlastOptions::ClearFilterOptions() { SetDustFiltering(false); SetSegFiltering(false); SetRepeatFiltering(false); SetMaskAtHash(false); SetWindowMaskerTaxId(0); SetWindowMaskerDatabase(NULL); return; } char* CBlastOptions::GetFilterString() const { if (! m_Local) { x_Throwx("Error: GetFilterString() not available."); } return m_Local->GetFilterString();/* NCBI_FAKE_WARNING */ } void CBlastOptions::SetFilterString(const char* f, bool clear) { // Clear if clear is true or filtering set to FALSE. if (clear == true || NStr::CompareNocase("F", f) == 0) { ClearFilterOptions(); } if (m_Local) { m_Local->SetFilterString(f);/* NCBI_FAKE_WARNING */ } if (m_Remote) { // When maintaining this code, please insure the following: // // 1. This list of items is parallel to the list found // below, in the "set" block. // // 2. Both lists should also correspond to the list of // options in names.hpp and names.cpp that are related // to filtering options. // // 3. Blast4's code in CCollectFilterOptions should also // handle the set of options handled here. // // 4. CRemoteBlast and CRemoteBlastService's handling of // filtering options (CBlastOptionsBuilder) should // include all of these elements. // // 5. Libnet2blast should deal with all of these filtering // options when it builds CBlastOptionsHandle objects. // // 6. Probably at least one or two other places that I forgot. m_Remote->SetValue(eBlastOpt_MaskAtHash, m_Local->GetMaskAtHash()); bool do_dust(false), do_seg(false), do_rep(false); if (Blast_QueryIsProtein(GetProgramType()) || Blast_QueryIsTranslated(GetProgramType())) { do_seg = m_Local->GetSegFiltering(); m_Remote->SetValue(eBlastOpt_SegFiltering, do_seg); } else { m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFiltering)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFilteringWindow)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFilteringLocut)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_SegFilteringHicut)); } if (Blast_QueryIsNucleotide(GetProgramType()) && !Blast_QueryIsTranslated(GetProgramType())) { do_dust = m_Local->GetDustFiltering(); do_rep = m_Local->GetRepeatFiltering(); m_Remote->SetValue(eBlastOpt_DustFiltering, do_dust); m_Remote->SetValue(eBlastOpt_RepeatFiltering, do_rep); } else { m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFiltering)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFilteringLevel)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFilteringWindow)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_DustFilteringLinker)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_RepeatFiltering)); m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_RepeatFilteringDB)); } if (do_dust) { m_Remote->SetValue(eBlastOpt_DustFilteringLevel, m_Local->GetDustFilteringLevel()); m_Remote->SetValue(eBlastOpt_DustFilteringWindow, m_Local->GetDustFilteringWindow()); m_Remote->SetValue(eBlastOpt_DustFilteringLinker, m_Local->GetDustFilteringLinker()); } if (do_rep) { m_Remote->SetValue(eBlastOpt_RepeatFilteringDB, m_Local->GetRepeatFilteringDB()); } if (do_seg) { m_Remote->SetValue(eBlastOpt_SegFilteringWindow, m_Local->GetSegFilteringWindow()); m_Remote->SetValue(eBlastOpt_SegFilteringLocut, m_Local->GetSegFilteringLocut()); m_Remote->SetValue(eBlastOpt_SegFilteringHicut, m_Local->GetSegFilteringHicut()); } } } bool CBlastOptions::GetMaskAtHash() const { if (! m_Local) { x_Throwx("Error: GetMaskAtHash() not available."); } return m_Local->GetMaskAtHash(); } void CBlastOptions::SetMaskAtHash(bool val) { if (m_Local) { m_Local->SetMaskAtHash(val); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MaskAtHash, val); } } bool CBlastOptions::GetDustFiltering() const { if (! m_Local) { x_Throwx("Error: GetDustFiltering() not available."); } return m_Local->GetDustFiltering(); } void CBlastOptions::SetDustFiltering(bool val) { if (m_Local) { m_Local->SetDustFiltering(val); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DustFiltering, val); } } int CBlastOptions::GetDustFilteringLevel() const { if (! m_Local) { x_Throwx("Error: GetDustFilteringLevel() not available."); } return m_Local->GetDustFilteringLevel(); } void CBlastOptions::SetDustFilteringLevel(int m) { if (m_Local) { m_Local->SetDustFilteringLevel(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DustFilteringLevel, m); } } int CBlastOptions::GetDustFilteringWindow() const { if (! m_Local) { x_Throwx("Error: GetDustFilteringWindow() not available."); } return m_Local->GetDustFilteringWindow(); } void CBlastOptions::SetDustFilteringWindow(int m) { if (m_Local) { m_Local->SetDustFilteringWindow(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DustFilteringWindow, m); } } int CBlastOptions::GetDustFilteringLinker() const { if (! m_Local) { x_Throwx("Error: GetDustFilteringLinker() not available."); } return m_Local->GetDustFilteringLinker(); } void CBlastOptions::SetDustFilteringLinker(int m) { if (m_Local) { m_Local->SetDustFilteringLinker(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DustFilteringLinker, m); } } bool CBlastOptions::GetSegFiltering() const { if (! m_Local) { x_Throwx("Error: GetSegFiltering() not available."); } return m_Local->GetSegFiltering(); } void CBlastOptions::SetSegFiltering(bool val) { if (m_Local) { m_Local->SetSegFiltering(val); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_SegFiltering, val); } } int CBlastOptions::GetSegFilteringWindow() const { if (! m_Local) { x_Throwx("Error: GetSegFilteringWindow() not available."); } return m_Local->GetSegFilteringWindow(); } void CBlastOptions::SetSegFilteringWindow(int m) { if (m_Local) { m_Local->SetSegFilteringWindow(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_SegFilteringWindow, m); } } double CBlastOptions::GetSegFilteringLocut() const { if (! m_Local) { x_Throwx("Error: GetSegFilteringLocut() not available."); } return m_Local->GetSegFilteringLocut(); } void CBlastOptions::SetSegFilteringLocut(double m) { if (m_Local) { m_Local->SetSegFilteringLocut(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_SegFilteringLocut, m); } } double CBlastOptions::GetSegFilteringHicut() const { if (! m_Local) { x_Throwx("Error: GetSegFilteringHicut() not available."); } return m_Local->GetSegFilteringHicut(); } void CBlastOptions::SetSegFilteringHicut(double m) { if (m_Local) { m_Local->SetSegFilteringHicut(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_SegFilteringHicut, m); } } bool CBlastOptions::GetRepeatFiltering() const { if (! m_Local) { x_Throwx("Error: GetRepeatFiltering() not available."); } return m_Local->GetRepeatFiltering(); } void CBlastOptions::SetRepeatFiltering(bool val) { if (m_Local) { m_Local->SetRepeatFiltering(val); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_RepeatFiltering, val); } } const char* CBlastOptions::GetRepeatFilteringDB() const { if (! m_Local) { x_Throwx("Error: GetRepeatFilteringDB() not available."); } return m_Local->GetRepeatFilteringDB(); } void CBlastOptions::SetRepeatFilteringDB(const char* db) { if (m_Local) { m_Local->SetRepeatFilteringDB(db); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_RepeatFilteringDB, db); } } int CBlastOptions::GetWindowMaskerTaxId() const { if (! m_Local) { x_Throwx("Error: GetWindowMaskerTaxId() not available."); } return m_Local->GetWindowMaskerTaxId(); } void CBlastOptions::SetWindowMaskerTaxId(int value) { if (m_Local) { m_Local->SetWindowMaskerTaxId(value); } if (m_Remote) { if (value) { m_Remote->SetValue(eBlastOpt_WindowMaskerTaxId, value); } else { m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_WindowMaskerTaxId)); } } } const char * CBlastOptions::GetWindowMaskerDatabase() const { if (! m_Local) { x_Throwx("Error: GetWindowMaskerDatabase() not available."); } return m_Local->GetWindowMaskerDatabase(); } void CBlastOptions::SetWindowMaskerDatabase(const char * value) { if (m_Local) { m_Local->SetWindowMaskerDatabase(value); } if (m_Remote) { if (value) { m_Remote->SetValue(eBlastOpt_WindowMaskerDatabase, value); } else { m_Remote->ResetValue(CBlast4Field::Get(eBlastOpt_WindowMaskerDatabase)); } } } objects::ENa_strand CBlastOptions::GetStrandOption() const { if (! m_Local) { x_Throwx("Error: GetStrandOption() not available."); } return m_Local->GetStrandOption(); } void CBlastOptions::SetStrandOption(objects::ENa_strand s) { if (m_Local) { m_Local->SetStrandOption(s); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_StrandOption, s); } } int CBlastOptions::GetQueryGeneticCode() const { if (! m_Local) { x_Throwx("Error: GetQueryGeneticCode() not available."); } return m_Local->GetQueryGeneticCode(); } void CBlastOptions::SetQueryGeneticCode(int gc) { if (m_Local) { m_Local->SetQueryGeneticCode(gc); m_GenCodeSingletonVar.AddGeneticCode(gc); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_QueryGeneticCode, gc); } } /******************* Initial word options ***********************/ int CBlastOptions::GetWindowSize() const { if (! m_Local) { x_Throwx("Error: GetWindowSize() not available."); } return m_Local->GetWindowSize(); } void CBlastOptions::SetWindowSize(int w) { if (m_Local) { m_Local->SetWindowSize(w); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_WindowSize, w); } } int CBlastOptions::GetOffDiagonalRange() const { if (! m_Local) { x_Throwx("Error: GetOffDiagonalRange() not available."); } return m_Local->GetOffDiagonalRange(); } void CBlastOptions::SetOffDiagonalRange(int w) { if (m_Local) { m_Local->SetOffDiagonalRange(w); } // N/A for the time being //if (m_Remote) { // m_Remote->SetValue(eBlastOpt_OffDiagonalRange, w); //} } double CBlastOptions::GetXDropoff() const { if (! m_Local) { x_Throwx("Error: GetXDropoff() not available."); } return m_Local->GetXDropoff(); } void CBlastOptions::SetXDropoff(double x) { if (m_Local) { m_Local->SetXDropoff(x); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_XDropoff, x); } } /******************* Gapped extension options *******************/ double CBlastOptions::GetGapXDropoff() const { if (! m_Local) { x_Throwx("Error: GetGapXDropoff() not available."); } return m_Local->GetGapXDropoff(); } void CBlastOptions::SetGapXDropoff(double x) { if (m_Local) { m_Local->SetGapXDropoff(x); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapXDropoff, x); } } double CBlastOptions::GetGapXDropoffFinal() const { if (! m_Local) { x_Throwx("Error: GetGapXDropoffFinal() not available."); } return m_Local->GetGapXDropoffFinal(); } void CBlastOptions::SetGapXDropoffFinal(double x) { if (m_Local) { m_Local->SetGapXDropoffFinal(x); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapXDropoffFinal, x); } } double CBlastOptions::GetGapTrigger() const { if (! m_Local) { x_Throwx("Error: GetGapTrigger() not available."); } return m_Local->GetGapTrigger(); } void CBlastOptions::SetGapTrigger(double g) { if (m_Local) { m_Local->SetGapTrigger(g); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapTrigger, g); } } EBlastPrelimGapExt CBlastOptions::GetGapExtnAlgorithm() const { if (! m_Local) { x_Throwx("Error: GetGapExtnAlgorithm() not available."); } return m_Local->GetGapExtnAlgorithm(); } void CBlastOptions::SetGapExtnAlgorithm(EBlastPrelimGapExt a) { if (m_Local) { m_Local->SetGapExtnAlgorithm(a); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapExtnAlgorithm, a); } } EBlastTbackExt CBlastOptions::GetGapTracebackAlgorithm() const { if (! m_Local) { x_Throwx("Error: GetGapTracebackAlgorithm() not available."); } return m_Local->GetGapTracebackAlgorithm(); } void CBlastOptions::SetGapTracebackAlgorithm(EBlastTbackExt a) { if (m_Local) { m_Local->SetGapTracebackAlgorithm(a); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapTracebackAlgorithm, a); } } ECompoAdjustModes CBlastOptions::GetCompositionBasedStats() const { if (! m_Local) { x_Throwx("Error: GetCompositionBasedStats() not available."); } return m_Local->GetCompositionBasedStats(); } void CBlastOptions::SetCompositionBasedStats(ECompoAdjustModes mode) { if (m_Local) { m_Local->SetCompositionBasedStats(mode); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_CompositionBasedStats, mode); } } bool CBlastOptions::GetSmithWatermanMode() const { if (! m_Local) { x_Throwx("Error: GetSmithWatermanMode() not available."); } return m_Local->GetSmithWatermanMode(); } void CBlastOptions::SetSmithWatermanMode(bool m) { if (m_Local) { m_Local->SetSmithWatermanMode(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_SmithWatermanMode, m); } } int CBlastOptions::GetUnifiedP() const { if (! m_Local) { x_Throwx("Error: GetUnifiedP() not available."); } return m_Local->GetUnifiedP(); } void CBlastOptions::SetUnifiedP(int u) { if (m_Local) { m_Local->SetUnifiedP(u); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_UnifiedP, u); } } /******************* Hit saving options *************************/ int CBlastOptions::GetHitlistSize() const { if (! m_Local) { x_Throwx("Error: GetHitlistSize() not available."); } return m_Local->GetHitlistSize(); } void CBlastOptions::SetHitlistSize(int s) { if (m_Local) { m_Local->SetHitlistSize(s); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_HitlistSize, s); } } int CBlastOptions::GetMaxNumHspPerSequence() const { if (! m_Local) { x_Throwx("Error: GetMaxNumHspPerSequence() not available."); } return m_Local->GetMaxNumHspPerSequence(); } void CBlastOptions::SetMaxNumHspPerSequence(int m) { if (m_Local) { m_Local->SetMaxNumHspPerSequence(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MaxNumHspPerSequence, m); } } int CBlastOptions::GetCullingLimit() const { if (! m_Local) { x_Throwx("Error: GetCullingMode() not available."); } return m_Local->GetCullingLimit(); } void CBlastOptions::SetCullingLimit(int s) { if (m_Local) { m_Local->SetCullingLimit(s); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_CullingLimit, s); } } double CBlastOptions::GetBestHitOverhang() const { if (! m_Local) { x_Throwx("Error: GetBestHitOverhangMode() not available."); } return m_Local->GetBestHitOverhang(); } void CBlastOptions::SetBestHitOverhang(double overhang) { if (m_Local) { m_Local->SetBestHitOverhang(overhang); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_BestHitOverhang, overhang); } } double CBlastOptions::GetBestHitScoreEdge() const { if (! m_Local) { x_Throwx("Error: GetBestHitScoreEdgeMode() not available."); } return m_Local->GetBestHitScoreEdge(); } void CBlastOptions::SetBestHitScoreEdge(double score_edge) { if (m_Local) { m_Local->SetBestHitScoreEdge(score_edge); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_BestHitScoreEdge, score_edge); } } double CBlastOptions::GetEvalueThreshold() const { if (! m_Local) { x_Throwx("Error: GetEvalueThreshold() not available."); } return m_Local->GetEvalueThreshold(); } void CBlastOptions::SetEvalueThreshold(double eval) { if (m_Local) { m_Local->SetEvalueThreshold(eval); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_EvalueThreshold, eval); } } int CBlastOptions::GetCutoffScore() const { if (! m_Local) { x_Throwx("Error: GetCutoffScore() not available."); } return m_Local->GetCutoffScore(); } void CBlastOptions::SetCutoffScore(int s) { if (m_Local) { m_Local->SetCutoffScore(s); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_CutoffScore, s); } } double CBlastOptions::GetPercentIdentity() const { if (! m_Local) { x_Throwx("Error: GetPercentIdentity() not available."); } return m_Local->GetPercentIdentity(); } void CBlastOptions::SetPercentIdentity(double p) { if (m_Local) { m_Local->SetPercentIdentity(p); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_PercentIdentity, p); } } int CBlastOptions::GetMinDiagSeparation() const { if (! m_Local) { x_Throwx("Error: GetMinDiagSeparation() not available."); } return m_Local->GetMinDiagSeparation(); } void CBlastOptions::SetMinDiagSeparation(int d) { if (! m_Local) { x_Throwx("Error: SetMinDiagSeparation() not available."); } m_Local->SetMinDiagSeparation(d); } bool CBlastOptions::GetSumStatisticsMode() const { if (! m_Local) { x_Throwx("Error: GetSumStatisticsMode() not available."); } return m_Local->GetSumStatisticsMode(); } void CBlastOptions::SetSumStatisticsMode(bool m) { if (m_Local) { m_Local->SetSumStatisticsMode(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_SumStatisticsMode, m); } } int CBlastOptions::GetLongestIntronLength() const { if (! m_Local) { x_Throwx("Error: GetLongestIntronLength() not available."); } return m_Local->GetLongestIntronLength(); } void CBlastOptions::SetLongestIntronLength(int l) { if (m_Local) { m_Local->SetLongestIntronLength(l); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_LongestIntronLength, l); } } bool CBlastOptions::GetGappedMode() const { if (! m_Local) { x_Throwx("Error: GetGappedMode() not available."); } return m_Local->GetGappedMode(); } void CBlastOptions::SetGappedMode(bool m) { if (m_Local) { m_Local->SetGappedMode(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GappedMode, m); } } // -RMH- int CBlastOptions::GetMaskLevel() const { if (! m_Local) { x_Throwx("Error: GetMaskLevel() not available."); } return m_Local->GetMaskLevel(); } // -RMH- void CBlastOptions::SetMaskLevel(int s) { if (m_Local) { m_Local->SetMaskLevel(s); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MaskLevel, s); } } // -RMH- bool CBlastOptions::GetComplexityAdjMode() const { if (! m_Local) { x_Throwx("Error: GetComplexityAdjMode() not available."); } return m_Local->GetComplexityAdjMode(); } // -RMH- void CBlastOptions::SetComplexityAdjMode(bool m) { if (m_Local) { m_Local->SetComplexityAdjMode(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_ComplexityAdjMode, m); } } double CBlastOptions::GetLowScorePerc() const { if (! m_Local) { x_Throwx("Error: GetLowScorePerc() not available."); } return m_Local->GetLowScorePerc(); } void CBlastOptions::SetLowScorePerc(double p) { if (m_Local) m_Local->SetLowScorePerc(p); } /************************ Scoring options ************************/ const char* CBlastOptions::GetMatrixName() const { if (! m_Local) { x_Throwx("Error: GetMatrixName() not available."); } return m_Local->GetMatrixName(); } void CBlastOptions::SetMatrixName(const char* matrix) { if (m_Local) { m_Local->SetMatrixName(matrix); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MatrixName, matrix); } } int CBlastOptions::GetMatchReward() const { if (! m_Local) { x_Throwx("Error: GetMatchReward() not available."); } return m_Local->GetMatchReward(); } void CBlastOptions::SetMatchReward(int r) { if (m_Local) { m_Local->SetMatchReward(r); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MatchReward, r); } } int CBlastOptions::GetMismatchPenalty() const { if (! m_Local) { x_Throwx("Error: GetMismatchPenalty() not available."); } return m_Local->GetMismatchPenalty(); } void CBlastOptions::SetMismatchPenalty(int p) { if (m_Local) { m_Local->SetMismatchPenalty(p); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_MismatchPenalty, p); } } int CBlastOptions::GetGapOpeningCost() const { if (! m_Local) { x_Throwx("Error: GetGapOpeningCost() not available."); } return m_Local->GetGapOpeningCost(); } void CBlastOptions::SetGapOpeningCost(int g) { if (m_Local) { m_Local->SetGapOpeningCost(g); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapOpeningCost, g); } } int CBlastOptions::GetGapExtensionCost() const { if (! m_Local) { x_Throwx("Error: GetGapExtensionCost() not available."); } return m_Local->GetGapExtensionCost(); } void CBlastOptions::SetGapExtensionCost(int e) { if (m_Local) { m_Local->SetGapExtensionCost(e); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_GapExtensionCost, e); } } int CBlastOptions::GetFrameShiftPenalty() const { if (! m_Local) { x_Throwx("Error: GetFrameShiftPenalty() not available."); } return m_Local->GetFrameShiftPenalty(); } void CBlastOptions::SetFrameShiftPenalty(int p) { if (m_Local) { m_Local->SetFrameShiftPenalty(p); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_FrameShiftPenalty, p); } } bool CBlastOptions::GetOutOfFrameMode() const { if (! m_Local) { x_Throwx("Error: GetOutOfFrameMode() not available."); } return m_Local->GetOutOfFrameMode(); } void CBlastOptions::SetOutOfFrameMode(bool m) { if (m_Local) { m_Local->SetOutOfFrameMode(m); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_OutOfFrameMode, m); } } /******************** Effective Length options *******************/ Int8 CBlastOptions::GetDbLength() const { if (! m_Local) { x_Throwx("Error: GetDbLength() not available."); } return m_Local->GetDbLength(); } void CBlastOptions::SetDbLength(Int8 l) { if (m_Local) { m_Local->SetDbLength(l); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DbLength, l); } } unsigned int CBlastOptions::GetDbSeqNum() const { if (! m_Local) { x_Throwx("Error: GetDbSeqNum() not available."); } return m_Local->GetDbSeqNum(); } void CBlastOptions::SetDbSeqNum(unsigned int n) { if (m_Local) { m_Local->SetDbSeqNum(n); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DbSeqNum, n); } } Int8 CBlastOptions::GetEffectiveSearchSpace() const { if (! m_Local) { x_Throwx("Error: GetEffectiveSearchSpace() not available."); } return m_Local->GetEffectiveSearchSpace(); } void CBlastOptions::SetEffectiveSearchSpace(Int8 eff) { if (m_Local) { m_Local->SetEffectiveSearchSpace(eff); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_EffectiveSearchSpace, eff); } } void CBlastOptions::SetEffectiveSearchSpace(const vector<Int8>& eff) { if (m_Local) { m_Local->SetEffectiveSearchSpace(eff); } if (m_Remote) { _ASSERT( !eff.empty() ); // This is the best we can do because remote BLAST only accepts one // value for the effective search space m_Remote->SetValue(eBlastOpt_EffectiveSearchSpace, eff.front()); } } int CBlastOptions::GetDbGeneticCode() const { if (! m_Local) { x_Throwx("Error: GetDbGeneticCode() not available."); } return m_Local->GetDbGeneticCode(); } void CBlastOptions::SetDbGeneticCode(int gc) { if (m_Local) { m_Local->SetDbGeneticCode(gc); m_GenCodeSingletonVar.AddGeneticCode(gc); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DbGeneticCode, gc); } } const char* CBlastOptions::GetPHIPattern() const { if (! m_Local) { x_Throwx("Error: GetPHIPattern() not available."); } return m_Local->GetPHIPattern(); } void CBlastOptions::SetPHIPattern(const char* pattern, bool is_dna) { if (m_Local) { m_Local->SetPHIPattern(pattern, is_dna); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_PHIPattern, pattern); // For now I will assume this is handled when the data is passed to the // code in blast4_options - i.e. that code will discriminate on the basis // of the type of *OptionHandle that is passed in. // // if (is_dna) { // m_Remote->SetProgram("blastn"); // } else { // m_Remote->SetProgram("blastp"); // } // // m_Remote->SetService("phi"); } } /******************** PSIBlast options *******************/ double CBlastOptions::GetInclusionThreshold() const { if (! m_Local) { x_Throwx("Error: GetInclusionThreshold() not available."); } return m_Local->GetInclusionThreshold(); } void CBlastOptions::SetInclusionThreshold(double u) { if (m_Local) { m_Local->SetInclusionThreshold(u); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_InclusionThreshold, u); } } int CBlastOptions::GetPseudoCount() const { if (! m_Local) { x_Throwx("Error: GetPseudoCount() not available."); } return m_Local->GetPseudoCount(); } void CBlastOptions::SetPseudoCount(int u) { if (m_Local) { m_Local->SetPseudoCount(u); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_PseudoCount, u); } } bool CBlastOptions::GetIgnoreMsaMaster() const { if (! m_Local) { x_Throwx("Error: GetIgnoreMsaMaster() not available."); } return m_Local->GetIgnoreMsaMaster(); } void CBlastOptions::SetIgnoreMsaMaster(bool val) { if (m_Local) { m_Local->SetIgnoreMsaMaster(val); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_IgnoreMsaMaster, val); } } /******************** DELTA-Blast options *******************/ double CBlastOptions::GetDomainInclusionThreshold() const { if (! m_Local) { x_Throwx("Error: GetDomainInclusionThreshold() not available."); } return m_Local->GetDomainInclusionThreshold(); } void CBlastOptions::SetDomainInclusionThreshold(double th) { if (m_Local) { m_Local->SetDomainInclusionThreshold(th); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_DomainInclusionThreshold, th); } } /// Allows to dump a snapshot of the object void CBlastOptions::DebugDump(CDebugDumpContext ddc, unsigned int depth) const { if (m_Local) { m_Local->DebugDump(ddc, depth); } } void CBlastOptions::DoneDefaults() const { if (m_Remote) { m_Remote->SetDefaultsMode(false); } } // typedef ncbi::objects::CBlast4_queue_search_request TBlast4Req; // CRef<TBlast4Req> GetBlast4Request() const // { // CRef<TBlast4Req> result; // if (m_Remote) { // result = m_Remote->GetBlast4Request(); // } // return result; // } // the "new paradigm" CBlastOptions::TBlast4Opts * CBlastOptions::GetBlast4AlgoOpts() { TBlast4Opts * result = 0; if (m_Remote) { result = m_Remote->GetBlast4AlgoOpts(); } return result; } bool CBlastOptions::GetUseIndex() const { if (! m_Local) { x_Throwx("Error: GetUseIndex() not available."); } return m_Local->GetUseIndex(); } bool CBlastOptions::GetForceIndex() const { if (! m_Local) { x_Throwx("Error: GetForceIndex() not available."); } return m_Local->GetForceIndex(); } bool CBlastOptions::GetIsOldStyleMBIndex() const { if (! m_Local) { x_Throwx("Error: GetIsOldStyleMBIndex() not available."); } return m_Local->GetIsOldStyleMBIndex(); } bool CBlastOptions::GetMBIndexLoaded() const { if (! m_Local) { x_Throwx("Error: GetMBIndexLoaded() not available."); } return m_Local->GetMBIndexLoaded(); } const string CBlastOptions::GetIndexName() const { if (! m_Local) { x_Throwx("Error: GetIndexName() not available."); } return m_Local->GetIndexName(); } void CBlastOptions::SetUseIndex( bool use_index, const string & index_name, bool force_index, bool old_style_index ) { if (m_Local) { m_Local->SetUseIndex( use_index, index_name, force_index, old_style_index ); } if (m_Remote) { m_Remote->SetValue(eBlastOpt_ForceMbIndex, force_index); if ( !index_name.empty() ) { m_Remote->SetValue(eBlastOpt_MbIndexName, index_name.c_str()); } } } void CBlastOptions::SetMBIndexLoaded( bool index_loaded ) { if (! m_Local) { x_Throwx("Error: SetMBIndexLoaded() not available."); } m_Local->SetMBIndexLoaded( index_loaded ); } QuerySetUpOptions * CBlastOptions::GetQueryOpts() const { return m_Local ? m_Local->GetQueryOpts() : 0; } LookupTableOptions * CBlastOptions::GetLutOpts() const { return m_Local ? m_Local->GetLutOpts() : 0; } BlastInitialWordOptions * CBlastOptions::GetInitWordOpts() const { return m_Local ? m_Local->GetInitWordOpts() : 0; } BlastExtensionOptions * CBlastOptions::GetExtnOpts() const { return m_Local ? m_Local->GetExtnOpts() : 0; } BlastHitSavingOptions * CBlastOptions::GetHitSaveOpts() const { return m_Local ? m_Local->GetHitSaveOpts() : 0; } PSIBlastOptions * CBlastOptions::GetPSIBlastOpts() const { return m_Local ? m_Local->GetPSIBlastOpts() : 0; } BlastDatabaseOptions * CBlastOptions::GetDbOpts() const { return m_Local ? m_Local->GetDbOpts() : 0; } BlastScoringOptions * CBlastOptions::GetScoringOpts() const { return m_Local ? m_Local->GetScoringOpts() : 0; } BlastEffectiveLengthsOptions * CBlastOptions::GetEffLenOpts() const { return m_Local ? m_Local->GetEffLenOpts() : 0; } void CBlastOptions::x_Throwx(const string& msg) const { NCBI_THROW(CBlastException, eInvalidOptions, msg); } void CBlastOptions::SetDefaultsMode(bool dmode) { if (m_Remote) { m_Remote->SetDefaultsMode(dmode); } } bool CBlastOptions::GetDefaultsMode() const { if (m_Remote) { return m_Remote->GetDefaultsMode(); } else return false; } void CBlastOptions::x_DoDeepCopy(const CBlastOptions& opts) { if (&opts != this) { // Clean up the old object if (m_Local) { delete m_Local; m_Local = 0; } if (m_Remote) { delete m_Remote; m_Remote = 0; } // Copy the contents of the new object if (opts.m_Remote) { m_Remote = new CBlastOptionsRemote(*opts.m_Remote); } if (opts.m_Local) { m_Local = new CBlastOptionsLocal(*opts.m_Local); } m_ProgramName = opts.m_ProgramName; m_ServiceName = opts.m_ServiceName; m_DefaultsMode = opts.m_DefaultsMode; } } ////////////////////////////////////////////////////////////////////////// //added by kyzhao for GPU blastn /* *********** START ************* */ int CBlastOptions::GetMethod() const { if (! m_Local) { x_Throwx("Error: GetMethod() not available."); } return m_Local->GetMethod(); } string CBlastOptions::GetQueryList() const { if (! m_Local) { x_Throwx("Error: GetQueryList() not available."); } return m_Local->GetQueryList(); } bool CBlastOptions::GetUseGpu() const { if (! m_Local) { x_Throwx("Error: GetUseGPU() not available."); } return m_Local->GetUseGpu(); } int CBlastOptions::GetGpuID() const { if (! m_Local) { x_Throwx("Error: GetGpuID() not available."); } return m_Local->GetGpuID(); } int CBlastOptions::GetPrepareNum() const { if (! m_Local) { x_Throwx("Error: GetPrepareNum() not available."); } return m_Local->GetPrepareNum(); } int CBlastOptions::GetPrelimNum() const { if (! m_Local) { x_Throwx("Error: GetPrelimNum() not available."); } return m_Local->GetPrelimNum(); } int CBlastOptions::GetTraceNum() const { if (! m_Local) { x_Throwx("Error: GetTraceNum() not available."); } return m_Local->GetTraceNum(); } int CBlastOptions::GetPrintNum() const { if (! m_Local) { x_Throwx("Error: GetPrintNum() not available."); } return m_Local->GetPrintNum(); } bool CBlastOptions::GetConverted() const { if (! m_Local) { x_Throwx("Error: GetConverted() not available."); } return m_Local->GetConverted(); } ////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////// void CBlastOptions::SetMethod(int method) { if (m_Local) { m_Local->SetMethod( method ); } if (m_Remote) { // } } void CBlastOptions::SetQueryList(string query_list) { if (m_Local) { m_Local->SetQueryList( query_list ); } if (m_Remote) { // } } void CBlastOptions::SetUseGpu( bool use_gpu ) { if (m_Local) { m_Local->SetUseGpu( use_gpu ); } if (m_Remote) { // } } void CBlastOptions::SetConverted(bool is_converted_db) { if (m_Local) { m_Local->SetConverted(is_converted_db); } if (m_Remote) { } } void CBlastOptions::SetGpuID( int gpu_id ) { if (m_Local) { m_Local->SetGpuID( gpu_id ); } if (m_Remote) { // } } void CBlastOptions::SetPrepareNum( int prepare_num ) { if (m_Local) { m_Local->SetPrepareNum( prepare_num ); } if (m_Remote) { // } } void CBlastOptions::SetPrelimNum( int prelim_num ) { if (m_Local) { m_Local->SetPrelimNum( prelim_num ); } if (m_Remote) { // } } void CBlastOptions::SetTraceNum( int trace_num ) { if (m_Local) { m_Local->SetTraceNum( trace_num ); } if (m_Remote) { // } } void CBlastOptions::SetPrintNum( int print_num ) { if (m_Local) { m_Local->SetPrintNum( print_num ); } if (m_Remote) { // } } /* ********** FINISH ************* */ #endif /* SKIP_DOXYGEN_PROCESSING */ END_SCOPE(blast) END_NCBI_SCOPE /* @} */
23.257593
98
0.609277
OpenHero
ffe40f7d4488ee495de9bd09bb1b3f7358dff1b2
5,528
cpp
C++
src/Main/calculateEvec.cpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
1
2022-01-27T14:45:51.000Z
2022-01-27T14:45:51.000Z
src/Main/calculateEvec.cpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
3
2021-09-14T01:30:26.000Z
2021-09-25T14:05:10.000Z
src/Main/calculateEvec.cpp
pmu2022/lsms
3c5f266812cad0b6d570bef9f5abb590d044ef92
[ "BSD-3-Clause" ]
1
2022-01-03T18:16:26.000Z
2022-01-03T18:16:26.000Z
#include "calculateEvec.hpp" void calculateEvec(LSMSSystemParameters &lsms, LocalTypeInfo &local) { const Real tolerance = 1.0e-8; for (int i=0; i<local.num_local; i++) { // Small part in mufind_c.f from LSMS 1.9 if (lsms.n_spin_cant == 2) // nspin >=3 { // Calculate moment Real moment[3]; moment[0] = local.atom[i].dosckint[1] + local.atom[i].evec[0] * local.atom[i].mcpsc_mt; moment[1] = local.atom[i].dosckint[2] + local.atom[i].evec[1] * local.atom[i].mcpsc_mt; moment[2] = local.atom[i].dosckint[3] + local.atom[i].evec[2] * local.atom[i].mcpsc_mt; // getevec.f from LSMS 1.9 // Determine evecNew according to moment Real evecMagnitude = std::sqrt(moment[0] * moment[0] + \ moment[1] * moment[1] + \ moment[2] * moment[2]); if (lsms.global.iprint >= 0) { printf(" GETDOS: moment = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].dosckint[1], local.atom[i].dosckint[2], local.atom[i].dosckint[3]); printf(" GETCS: moment = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].evec[0] * local.atom[i].mcpsc_mt, local.atom[i].evec[1] * local.atom[i].mcpsc_mt, local.atom[i].evec[2] * local.atom[i].mcpsc_mt); printf(" GETEVEC: moment = (%12.8f, %12.8f, %12.8f) magnitude = %12.8f\n", moment[0], moment[1], moment[2], evecMagnitude); } if (evecMagnitude > tolerance) { /* ================================================================= evecNew is the new moment orientation: evecNew[0] = the x-component of e-vector evecNew[1] = the y-component of e-vector evecNew[2] = the z-component of e-vector it is determined by the total moment inside the muffin-tin sphere ================================================================= */ local.atom[i].evecNew[0] = moment[0] / evecMagnitude; local.atom[i].evecNew[1] = moment[1] / evecMagnitude; local.atom[i].evecNew[2] = moment[2] / evecMagnitude; } else { local.atom[i].evecNew[0] = local.atom[i].evec[0]; local.atom[i].evecNew[1] = local.atom[i].evec[1]; local.atom[i].evecNew[2] = local.atom[i].evec[2]; } } else // nspin = 1 or 2 { local.atom[i].evecNew[0] = local.atom[i].evec[0]; local.atom[i].evecNew[1] = local.atom[i].evec[1]; local.atom[i].evecNew[2] = local.atom[i].evec[2]; } /* ================================================================ Store direction & mag. mom. corresponding to output chg. den.... ================================================================ Not yet implemented. (need to see where evec_out and mm_out are used for) */ if (lsms.global.iprint >= 0) { printf(" EVEC OLD: moment = %12.8f, %12.8f, %12.8f\n", local.atom[i].evecOut[0], local.atom[i].evecOut[1],local.atom[i].evecOut[2]); printf(" EVEC FIX: moment = %12.8f, %12.8f, %12.8f\n", local.atom[i].evec[0], local.atom[i].evec[1],local.atom[i].evec[2]); printf(" EVEC NEW: moment = %12.8f, %12.8f, %12.8f\n", local.atom[i].evecNew[0], local.atom[i].evecNew[1],local.atom[i].evecNew[2]); } local.atom[i].evecOut[0] = local.atom[i].evecNew[0]; local.atom[i].evecOut[1] = local.atom[i].evecNew[1]; local.atom[i].evecOut[2] = local.atom[i].evecNew[2]; // local.atom[i].magneticMomentOut = evecMagnitude; } return; } void mixEvec(LSMSSystemParameters &lsms, LocalTypeInfo &local, Real alpev) { /* ================================================================ perform simple mixing of evec_new and evec_old, and redefine evec_new........................................................ ================================================================ !! This should be placed in mixing.hpp !! */ Real tolerance = 1.0e-8; for (int i=0; i<local.num_local; i++) { if (lsms.global.iprint > 0) { printf("Moment direction before mixing = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].evecNew[0], local.atom[i].evecNew[1], local.atom[i].evecNew[2]); } local.atom[i].evecNew[0] = alpev * local.atom[i].evecNew[0] + (1.0-alpev) * local.atom[i].evec[0]; local.atom[i].evecNew[1] = alpev * local.atom[i].evecNew[1] + (1.0-alpev) * local.atom[i].evec[1]; local.atom[i].evecNew[2] = alpev * local.atom[i].evecNew[2] + (1.0-alpev) * local.atom[i].evec[2]; Real evecMagnitude = std::sqrt(local.atom[i].evecNew[0] * local.atom[i].evecNew[0] + \ local.atom[i].evecNew[1] * local.atom[i].evecNew[1] + \ local.atom[i].evecNew[2] * local.atom[i].evecNew[2]); if (evecMagnitude < tolerance) { printf("GETEVEC: magnitude of evec too small. (= %35.25f)\n", evecMagnitude); } local.atom[i].evecNew[0] = local.atom[i].evecNew[0] / evecMagnitude; local.atom[i].evecNew[1] = local.atom[i].evecNew[1] / evecMagnitude; local.atom[i].evecNew[2] = local.atom[i].evecNew[2] / evecMagnitude; if (lsms.global.iprint > 0) { printf("Moment direction after mixing = (%12.8f, %12.8f, %12.8f)\n", local.atom[i].evecNew[0], local.atom[i].evecNew[1], local.atom[i].evecNew[2]); } } return; }
38.124138
154
0.516281
pmu2022
ffe4485adf577a78dbafbdce23b9b679fdd896f5
774
cpp
C++
libsnes/bsnes/snes/chip/msu1/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
libsnes/bsnes/snes/chip/msu1/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
libsnes/bsnes/snes/chip/msu1/serialization.cpp
ircluzar/BizhawkLegacy-Vanguard
cd8b6dfe881f3c9d322b73c29f0d71df2ce3178e
[ "MIT" ]
null
null
null
#ifdef MSU1_CPP void MSU1::serialize(serializer &s) { Processor::serialize(s); s.integer(mmio.data_offset); s.integer(mmio.audio_offset); s.integer(mmio.audio_loop_offset); s.integer(mmio.audio_track); s.integer(mmio.audio_volume); s.integer(mmio.data_busy); s.integer(mmio.audio_busy); s.integer(mmio.audio_repeat); s.integer(mmio.audio_play); if(datafile.open()) datafile.close(); if(datafile.open(interface()->path(Cartridge::Slot::Base, "msu1.rom"), file::mode::read)) { datafile.seek(mmio.data_offset); } if(audiofile.open()) audiofile.close(); if(audiofile.open(interface()->path(Cartridge::Slot::Base, { "track-", (unsigned)mmio.audio_track, ".pcm" }), file::mode::read)) { audiofile.seek(mmio.audio_offset); } } #endif
25.8
132
0.697674
ircluzar
ffe60ac81a3223be2a12b8dce2baa45abd78a8f1
3,982
cpp
C++
src/core/physics/body_template.cpp
texel-sensei/eversim
187262756186add9ee8583cbaa1d3ef9e6d0aa53
[ "Apache-2.0" ]
null
null
null
src/core/physics/body_template.cpp
texel-sensei/eversim
187262756186add9ee8583cbaa1d3ef9e6d0aa53
[ "Apache-2.0" ]
72
2017-07-18T16:38:29.000Z
2020-09-01T15:25:22.000Z
src/core/physics/body_template.cpp
texel-sensei/eversim
187262756186add9ee8583cbaa1d3ef9e6d0aa53
[ "Apache-2.0" ]
null
null
null
#include "core/physics/body_template.h" #include "core/physics/errors.h" #include <fstream> #include <sstream> using namespace std; namespace eversim { namespace core { namespace physics { void body_template_loader::register_factory(std::string const& type, factory_ptr factory) { constraint_loaders[type] = move(factory); } body_template body_template_loader::parse(std::istream& data) const { data.exceptions(istream::badbit | istream::failbit); body_template templ; try{ load_particles(templ, data); load_constraints(templ, data); } catch(ios::failure const& c) { if (c.code() == io_errc::stream) { EVERSIM_THROW(body_template_error::SyntaxError); } EVERSIM_THROW(c.code()); } return templ; } shared_ptr<body_template_loader::value_type> body_template_loader::load_file(std::string const& path) { auto data = ifstream(path); return make_shared<body_template>(parse(data)); } void body_template_loader::load_particles(body_template& templ, std::istream& data) const { auto in = istringstream(load_line(data)); int num; in >> num; if(num <= 0) { EVERSIM_THROW(body_template_error::NotEnoughParticles); } templ.particles.resize(num); for(int i = 0; i < num;++i) { auto line = load_line(data); templ.particles[i] = particle_descriptor::parse(line); } } void body_template_loader::load_constraints(body_template& templ, std::istream& data) const { auto in = istringstream(load_line(data)); int num; in >> num; if (num < 0) { EVERSIM_THROW(body_template_error::NotEnoughConstraints); } templ.constraints.resize(num); for (int i = 0; i < num; ++i) { auto line = load_line(data); auto c = constraint_descriptor::parse(line, [this](string const& type) -> constraint_factory const& { return *constraint_loaders.at(type); }); for(auto index : c.particles) { if(index >= templ.particles.size()) { EVERSIM_THROW(body_template_error::InvalidIndex); } } templ.constraints[i] = move(c); } } string body_template_loader::load_line(istream& in) const { string line; while(true){ in >> ws; getline(in, line); if(line.empty() || line[0] == '#') { continue; } return line; } } namespace { std::string get_remainder(istream& data) { if (data) { data.exceptions(istream::badbit); data >> ws; string remainder; getline(data, remainder); auto pos = remainder.find('#'); if(pos != string::npos) remainder = remainder.erase(pos); remainder.erase(remainder.find_last_not_of(" \t") + 1); return remainder; } return ""; } } particle_descriptor particle_descriptor::parse(std::string const& str) { auto desc = particle_descriptor{}; auto data = istringstream(str); data.exceptions(istream::badbit | istream::failbit); data >> desc.pos.x >> desc.pos.y >> desc.mass; auto rem = get_remainder(data); if(!rem.empty()) { EVERSIM_THROW(body_template_error::SyntaxError, "Too much data while parsing particle! " + rem); } return desc; } constraint_descriptor constraint_descriptor::parse( string const& str, factory_getter get_factory ){ auto desc = constraint_descriptor{}; auto data = istringstream(str); data.exceptions(istream::badbit | istream::failbit); data >> desc.arity; desc.particles.resize(desc.arity); for(int i = 0; i < desc.arity; ++i) { data >> desc.particles[i]; } data >> desc.stiffness; data >> desc.type; auto rem = get_remainder(data); auto extra = stringstream(rem); auto const& f = get_factory(desc.type); desc.factory = &f; extra.exceptions(istream::badbit | istream::failbit); desc.extra_data = f.parse(extra); extra.exceptions(istream::badbit); extra >> ws; rem.clear(); getline(extra, rem); if (!rem.empty()) { EVERSIM_THROW(body_template_error::SyntaxError, "Too much data while parsing particle! " + rem); } return desc; } }}}
22
102
0.670517
texel-sensei
ffe7144243e30615abcc8e67abda78cfd1699428
448
cpp
C++
src/statusbar.cpp
roediger/tableau-log-viewer
4c63f8f91e71ebc0a1524f103a40459f9808bb06
[ "MIT" ]
133
2016-10-14T04:36:10.000Z
2022-03-10T21:27:15.000Z
src/statusbar.cpp
Tableau-projects/tableau-log-viewer
4c63f8f91e71ebc0a1524f103a40459f9808bb06
[ "MIT" ]
39
2016-10-14T06:28:35.000Z
2020-07-24T00:42:40.000Z
src/statusbar.cpp
Tableau-projects/tableau-log-viewer
4c63f8f91e71ebc0a1524f103a40459f9808bb06
[ "MIT" ]
46
2016-10-18T15:38:10.000Z
2021-11-17T07:51:33.000Z
#include "statusbar.h" StatusBar::StatusBar(QMainWindow* parent) : m_qbar(parent->statusBar()), m_statusLabel(new QLabel(parent)) { m_statusLabel->setContentsMargins(0, 0, 8, 0); m_qbar->addPermanentWidget(m_statusLabel); } void StatusBar::ShowMessage(const QString& message, int timeout) { m_qbar->showMessage(message, timeout); } void StatusBar::SetRightLabelText(const QString& text) { m_statusLabel->setText(text); }
22.4
64
0.729911
roediger
ffe79cd49638447df53aa245cbc54edf31ef1b49
683
cpp
C++
tests/library/OpLibraryCoupler.cpp
mmore500/signalgp-lite
1b95f43b5e8f57de6ca062db4e0049f9d75f6928
[ "MIT" ]
1
2021-07-21T23:34:45.000Z
2021-07-21T23:34:45.000Z
tests/library/OpLibraryCoupler.cpp
mmore500/signalgp-lite
1b95f43b5e8f57de6ca062db4e0049f9d75f6928
[ "MIT" ]
9
2020-10-07T05:17:48.000Z
2021-11-16T21:08:14.000Z
tests/library/OpLibraryCoupler.cpp
mmore500/signalgp-lite
1b95f43b5e8f57de6ca062db4e0049f9d75f6928
[ "MIT" ]
2
2020-10-10T19:36:31.000Z
2020-12-10T00:10:48.000Z
#include "Catch/single_include/catch2/catch.hpp" #include "Empirical/include/emp/math/Random.hpp" #include "sgpl/library/OpLibraryCoupler.hpp" #include "sgpl/library/prefab/CompleteOpLibrary.hpp" struct ExampleOp { template<typename Spec> static void run( sgpl::Core<Spec>&, const sgpl::Instruction<Spec>&, const sgpl::Program<Spec>&, typename Spec::peripheral_t& ) {} static std::string name() { return "ExampleOp"; } }; TEST_CASE("Test OpLibraryCoupler") { using library_t = sgpl::OpLibraryCoupler< sgpl::CompleteOpLibrary, ExampleOp >; REQUIRE( library_t::GetOpName( library_t::GetOpCode( "ExampleOp" ) ) == "ExampleOp" ); }
19.514286
78
0.696925
mmore500
ffee4de2ae3d9b280dac966a1ffced153c8a454c
11,699
cpp
C++
Engine/source/scene/zones/sceneZoneSpace.cpp
vbillet/Torque3D
ece8823599424ea675e5f79d9bcb44e42cba8cae
[ "MIT" ]
2,113
2015-01-01T11:23:01.000Z
2022-03-28T04:51:46.000Z
Engine/source/scene/zones/sceneZoneSpace.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
948
2015-01-02T01:50:00.000Z
2022-02-27T05:56:40.000Z
Engine/source/scene/zones/sceneZoneSpace.cpp
Ashry00/Torque3D
33e3e41c8b7eb41c743a589558bc21302207ef97
[ "MIT" ]
944
2015-01-01T09:33:53.000Z
2022-03-15T22:23:03.000Z
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- #include "platform/platform.h" #include "scene/zones/sceneZoneSpace.h" #include "scene/zones/sceneTraversalState.h" #include "scene/zones/sceneZoneSpaceManager.h" #include "scene/sceneRenderState.h" #include "sim/netConnection.h" #include "core/stream/bitStream.h" #include "console/engineAPI.h" //#define DEBUG_SPEW ClassChunker< SceneZoneSpace::ZoneSpaceRef > SceneZoneSpace::smZoneSpaceRefChunker; //----------------------------------------------------------------------------- SceneZoneSpace::SceneZoneSpace() : mManager( NULL ), mZoneRangeStart( SceneZoneSpaceManager::InvalidZoneId ), mZoneGroup( InvalidZoneGroup ), mNumZones( 0 ), mZoneFlags( ZoneFlag_IsClosedOffSpace ), mConnectedZoneSpaces( NULL ) { VECTOR_SET_ASSOCIATION( mOccluders ); } //----------------------------------------------------------------------------- SceneZoneSpace::~SceneZoneSpace() { AssertFatal( mConnectedZoneSpaces == NULL, "SceneZoneSpace::~SceneZoneSpace - Still have connected zone spaces!" ); } //----------------------------------------------------------------------------- void SceneZoneSpace::onSceneRemove() { _disconnectAllZoneSpaces(); Parent::onSceneRemove(); } //----------------------------------------------------------------------------- void SceneZoneSpace::initPersistFields() { addGroup( "Zoning" ); addProtectedField( "zoneGroup", TypeS32, Offset( mZoneGroup, SceneZoneSpace ), &_setZoneGroup, &defaultProtectedGetFn, "ID of group the zone is part of." ); endGroup( "Zoning" ); Parent::initPersistFields(); } //----------------------------------------------------------------------------- bool SceneZoneSpace::writeField( StringTableEntry fieldName, const char* value ) { // Don't write zoneGroup field if at default. static StringTableEntry sZoneGroup = StringTable->insert( "zoneGroup" ); if( fieldName == sZoneGroup && getZoneGroup() == InvalidZoneGroup ) return false; return Parent::writeField( fieldName, value ); } //----------------------------------------------------------------------------- void SceneZoneSpace::setZoneGroup( U32 group ) { if( mZoneGroup == group ) return; mZoneGroup = group; setMaskBits( ZoneGroupMask ); // Rezone to establish new connectivity. if( mManager ) mManager->notifyObjectChanged( this ); } //----------------------------------------------------------------------------- U32 SceneZoneSpace::packUpdate( NetConnection* connection, U32 mask, BitStream* stream ) { U32 retMask = Parent::packUpdate( connection, mask, stream ); if( stream->writeFlag( mask & ZoneGroupMask ) ) stream->write( mZoneGroup ); return retMask; } //----------------------------------------------------------------------------- void SceneZoneSpace::unpackUpdate( NetConnection* connection, BitStream* stream ) { Parent::unpackUpdate( connection, stream ); if( stream->readFlag() ) // ZoneGroupMask { U32 zoneGroup; stream->read( &zoneGroup ); setZoneGroup( zoneGroup ); } } //----------------------------------------------------------------------------- bool SceneZoneSpace::getOverlappingZones( SceneObject* obj, U32* outZones, U32& outNumZones ) { return getOverlappingZones( obj->getWorldBox(), outZones, outNumZones ); } //----------------------------------------------------------------------------- void SceneZoneSpace::_onZoneAddObject( SceneObject* object, const U32* zoneIDs, U32 numZones ) { if( object->isVisualOccluder() ) _addOccluder( object ); // If this isn't the root zone and the object is zone space, // see if we should automatically connect the two. if( !isRootZone() && object->getTypeMask() & ZoneObjectType ) { SceneZoneSpace* zoneSpace = dynamic_cast< SceneZoneSpace* >( object ); // Don't connect a zone space that has the same closed off status // that we have except it is assigned to the same zone group. if( zoneSpace && ( zoneSpace->mZoneFlags.test( ZoneFlag_IsClosedOffSpace ) != mZoneFlags.test( ZoneFlag_IsClosedOffSpace ) || ( zoneSpace->getZoneGroup() == getZoneGroup() && zoneSpace->getZoneGroup() != InvalidZoneGroup ) ) && _automaticallyConnectZoneSpace( zoneSpace ) ) { connectZoneSpace( zoneSpace ); } } } //----------------------------------------------------------------------------- void SceneZoneSpace::_onZoneRemoveObject( SceneObject* object ) { if( object->isVisualOccluder() ) _removeOccluder( object ); if( !isRootZone() && object->getTypeMask() & ZoneObjectType ) { SceneZoneSpace* zoneSpace = dynamic_cast< SceneZoneSpace* >( object ); if( zoneSpace ) disconnectZoneSpace( zoneSpace ); } } //----------------------------------------------------------------------------- bool SceneZoneSpace::_automaticallyConnectZoneSpace( SceneZoneSpace* zoneSpace ) const { //TODO: This is suboptimal. While it prevents the most blatantly wrong automatic connections, // we need a true polyhedron/polyhedron intersection to accurately determine zone intersection // when it comes to automatic connections. U32 numZones = 0; U32 zones[ SceneObject::MaxObjectZones ]; zoneSpace->getOverlappingZones( getWorldBox(), zones, numZones ); return ( numZones > 0 ); } //----------------------------------------------------------------------------- void SceneZoneSpace::connectZoneSpace( SceneZoneSpace* zoneSpace ) { // If the zone space is already in the list, do nothing. for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext ) if( ref->mZoneSpace == zoneSpace ) return; // Link the zone space to the zone space refs. ZoneSpaceRef* ref = smZoneSpaceRefChunker.alloc(); ref->mZoneSpace = zoneSpace; ref->mNext = mConnectedZoneSpaces; mConnectedZoneSpaces = ref; #ifdef DEBUG_SPEW Platform::outputDebugString( "[SceneZoneSpace] Connecting %i-%i to %i-%i", getZoneRangeStart(), getZoneRangeStart() + getZoneRange(), zoneSpace->getZoneRangeStart(), zoneSpace->getZoneRangeStart() + zoneSpace->getZoneRange() ); #endif } //----------------------------------------------------------------------------- void SceneZoneSpace::disconnectZoneSpace( SceneZoneSpace* zoneSpace ) { ZoneSpaceRef* prev = NULL; for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; prev = ref, ref = ref->mNext ) if( ref->mZoneSpace == zoneSpace ) { if( prev ) prev->mNext = ref->mNext; else mConnectedZoneSpaces = ref->mNext; #ifdef DEBUG_SPEW Platform::outputDebugString( "[SceneZoneSpace] Disconnecting %i-%i from %i-%i", getZoneRangeStart(), getZoneRangeStart() + getZoneRange(), zoneSpace->getZoneRangeStart(), zoneSpace->getZoneRangeStart() + zoneSpace->getZoneRange() ); #endif smZoneSpaceRefChunker.free( ref ); break; } } //----------------------------------------------------------------------------- void SceneZoneSpace::_disconnectAllZoneSpaces() { #ifdef DEBUG_SPEW if( mConnectedZoneSpaces != NULL ) Platform::outputDebugString( "[SceneZoneSpace] Disconnecting all from %i-%i", getZoneRangeStart(), getZoneRangeStart() + getZoneRange() ); #endif for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ) { ZoneSpaceRef* next = ref->mNext; smZoneSpaceRefChunker.free( ref ); ref = next; } mConnectedZoneSpaces = NULL; } //----------------------------------------------------------------------------- void SceneZoneSpace::_addOccluder( SceneObject* object ) { AssertFatal( !mOccluders.contains( object ), "SceneZoneSpace::_addOccluder - Occluder already added to this zone space!" ); mOccluders.push_back( object ); } //----------------------------------------------------------------------------- void SceneZoneSpace::_removeOccluder( SceneObject* object ) { const U32 numOccluders = mOccluders.size(); for( U32 i = 0; i < numOccluders; ++ i ) if( mOccluders[ i ] == object ) { mOccluders.erase_fast( i ); break; } AssertFatal( !mOccluders.contains( object ), "SceneZoneSpace::_removeOccluder - Occluder still added to this zone space!" ); } //----------------------------------------------------------------------------- void SceneZoneSpace::_addOccludersToCullingState( SceneCullingState* state ) const { const U32 numOccluders = mOccluders.size(); for( U32 i = 0; i < numOccluders; ++ i ) state->addOccluder( mOccluders[ i ] ); } //----------------------------------------------------------------------------- void SceneZoneSpace::_traverseConnectedZoneSpaces( SceneTraversalState* state ) { // Hand the traversal over to all connected zone spaces. for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext ) { SceneZoneSpace* zoneSpace = ref->mZoneSpace; zoneSpace->traverseZones( state ); } } //----------------------------------------------------------------------------- void SceneZoneSpace::dumpZoneState( bool update ) { // Nothing to dump if not registered. if( !mManager ) return; // If we should update, trigger rezoning for the space // we occupy. if( update ) mManager->_rezoneObjects( getWorldBox() ); Con::printf( "====== Zones in: %s =====", describeSelf().c_str() ); // Dump connections. for( ZoneSpaceRef* ref = mConnectedZoneSpaces; ref != NULL; ref = ref->mNext ) Con::printf( "Connected to: %s", ref->mZoneSpace->describeSelf().c_str() ); // Dump objects. for( U32 i = 0; i < getZoneRange(); ++ i ) { U32 zoneId = getZoneRangeStart() + i; Con::printf( "--- Zone %i", zoneId ); for( SceneZoneSpaceManager::ZoneContentIterator iter( mManager, zoneId, false ); iter.isValid(); ++ iter ) Con::printf( iter->describeSelf() ); } } //----------------------------------------------------------------------------- bool SceneZoneSpace::_setZoneGroup( void* object, const char* index, const char* data ) { SceneZoneSpace* zone = reinterpret_cast< SceneZoneSpace* >( object ); zone->setZoneGroup( EngineUnmarshallData< S32 >()( data ) ); return false; }
32.22865
127
0.578511
vbillet
ffefedcba791021cbd75d2aeb98d576ae1bc6cee
1,493
cpp
C++
src/core/testing/plg_python27_ui_test/python_panel.cpp
wgsyd/wgtf
d8cacb43e2c5d40080d33c18a8c2f5bd27d21bed
[ "BSD-3-Clause" ]
28
2016-06-03T05:28:25.000Z
2019-02-14T12:04:31.000Z
src/core/testing/plg_python27_ui_test/python_panel.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
null
null
null
src/core/testing/plg_python27_ui_test/python_panel.cpp
karajensen/wgtf
740397bcfdbc02bc574231579d57d7c9cd5cc26d
[ "BSD-3-Clause" ]
14
2016-06-03T05:52:27.000Z
2019-03-21T09:56:03.000Z
#include "python_panel.hpp" #include "core_logging/logging.hpp" #include "core_reflection/reflected_object.hpp" #include "core_reflection/i_definition_manager.hpp" #include "core_reflection/reflection_macros.hpp" #include "core_reflection/metadata/meta_types.hpp" #include "core_reflection/function_property.hpp" #include "core_reflection/utilities/reflection_function_utilities.hpp" #include "core_reflection/property_accessor_listener.hpp" #include "core_logging/logging.hpp" #include "core_ui_framework/i_ui_framework.hpp" #include "core_ui_framework/i_ui_application.hpp" #include "core_ui_framework/interfaces/i_view_creator.hpp" namespace wgt { PythonPanel::PythonPanel(ManagedObjectPtr contextObject) : contextObject_(std::move(contextObject)) { this->addPanel(); } PythonPanel::~PythonPanel() { this->removePanel(); } bool PythonPanel::addPanel() { auto viewCreator = get<IViewCreator>(); if (viewCreator == nullptr) { NGT_ERROR_MSG("Failed to find IViewCreator\n"); return false; } pythonView_ = viewCreator->createView("Python27UITest/PythonObjectTestPanel.qml", contextObject_->getHandle()); return true; } void PythonPanel::removePanel() { auto uiApplication = get<IUIApplication>(); if (uiApplication == nullptr) { NGT_ERROR_MSG("Failed to find IUIApplication\n"); return; } if (pythonView_.valid()) { auto view = pythonView_.get(); uiApplication->removeView(*view); view = nullptr; } contextObject_ = nullptr; } } // end namespace wgt
24.883333
112
0.77361
wgsyd
fff098f07b243bc508116a069c4da83d1a40d185
44,300
cc
C++
src/redis_strings.cc
WyattJia/blackwidow
5d070e2970f68fafde8105d358acd09c571ea398
[ "BSD-3-Clause" ]
67
2018-08-01T05:52:25.000Z
2022-03-22T04:08:22.000Z
src/redis_strings.cc
WyattJia/blackwidow
5d070e2970f68fafde8105d358acd09c571ea398
[ "BSD-3-Clause" ]
7
2018-11-30T01:48:07.000Z
2022-02-10T12:17:07.000Z
src/redis_strings.cc
WyattJia/blackwidow
5d070e2970f68fafde8105d358acd09c571ea398
[ "BSD-3-Clause" ]
30
2018-08-15T06:34:31.000Z
2022-03-20T09:04:27.000Z
// Copyright (c) 2017-present, Qihoo, Inc. 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 "src/redis_strings.h" #include <memory> #include <climits> #include <algorithm> #include <limits> #include "blackwidow/util.h" #include "src/strings_filter.h" #include "src/scope_record_lock.h" #include "src/scope_snapshot.h" namespace blackwidow { RedisStrings::RedisStrings(BlackWidow* const bw, const DataType& type) : Redis(bw, type) { } Status RedisStrings::Open(const BlackwidowOptions& bw_options, const std::string& db_path) { rocksdb::Options ops(bw_options.options); ops.compaction_filter_factory = std::make_shared<StringsFilterFactory>(); // use the bloom filter policy to reduce disk reads rocksdb::BlockBasedTableOptions table_ops(bw_options.table_options); if (!bw_options.share_block_cache && bw_options.block_cache_size > 0) { table_ops.block_cache = rocksdb::NewLRUCache(bw_options.block_cache_size); } table_ops.filter_policy.reset(rocksdb::NewBloomFilterPolicy(10, true)); ops.table_factory.reset(rocksdb::NewBlockBasedTableFactory(table_ops)); return rocksdb::DB::Open(ops, db_path, &db_); } Status RedisStrings::CompactRange(const rocksdb::Slice* begin, const rocksdb::Slice* end, const ColumnFamilyType& type) { return db_->CompactRange(default_compact_range_options_, begin, end); } Status RedisStrings::GetProperty(const std::string& property, uint64_t* out) { std::string value; db_->GetProperty(property, &value); *out = std::strtoull(value.c_str(), NULL, 10); return Status::OK(); } Status RedisStrings::ScanKeyNum(KeyInfo* key_info) { uint64_t keys = 0; uint64_t expires = 0; uint64_t ttl_sum = 0; uint64_t invaild_keys = 0; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; int64_t curtime; rocksdb::Env::Default()->GetCurrentTime(&curtime); // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* iter = db_->NewIterator(iterator_options); for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedStringsValue parsed_strings_value(iter->value()); if (parsed_strings_value.IsStale()) { invaild_keys++; } else { keys++; if (!parsed_strings_value.IsPermanentSurvival()) { expires++; ttl_sum += parsed_strings_value.timestamp() - curtime; } } } delete iter; key_info->keys = keys; key_info->expires = expires; key_info->avg_ttl = (expires != 0) ? ttl_sum / expires : 0; key_info->invaild_keys = invaild_keys; return Status::OK(); } Status RedisStrings::ScanKeys(const std::string& pattern, std::vector<std::string>* keys) { std::string key; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* iter = db_->NewIterator(iterator_options); for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedStringsValue parsed_strings_value(iter->value()); if (!parsed_strings_value.IsStale()) { key = iter->key().ToString(); if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } } } delete iter; return Status::OK(); } Status RedisStrings::PKPatternMatchDel(const std::string& pattern, int32_t* ret) { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; std::string key; std::string value; int32_t total_delete = 0; Status s; rocksdb::WriteBatch batch; rocksdb::Iterator* iter = db_->NewIterator(iterator_options); iter->SeekToFirst(); while (iter->Valid()) { key = iter->key().ToString(); value = iter->value().ToString(); ParsedStringsValue parsed_strings_value(&value); if (!parsed_strings_value.IsStale() && StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { batch.Delete(key); } // In order to be more efficient, we use batch deletion here if (static_cast<size_t>(batch.Count()) >= BATCH_DELETE_LIMIT) { s = db_->Write(default_write_options_, &batch); if (s.ok()) { total_delete += batch.Count(); batch.Clear(); } else { *ret = total_delete; return s; } } iter->Next(); } if (batch.Count()) { s = db_->Write(default_write_options_, &batch); if (s.ok()) { total_delete += batch.Count(); batch.Clear(); } } *ret = total_delete; return s; } Status RedisStrings::Append(const Slice& key, const Slice& value, int32_t* ret) { std::string old_value; *ret = 0; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { *ret = value.size(); StringsValue strings_value(value); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { int32_t timestamp = parsed_strings_value.timestamp(); std::string old_user_value = parsed_strings_value.value().ToString(); std::string new_value = old_user_value + value.ToString(); StringsValue strings_value(new_value); strings_value.set_timestamp(timestamp); *ret = new_value.size(); return db_->Put(default_write_options_, key, strings_value.Encode()); } } else if (s.IsNotFound()) { *ret = value.size(); StringsValue strings_value(value); return db_->Put(default_write_options_, key, strings_value.Encode()); } return s; } int GetBitCount(const unsigned char* value, int64_t bytes) { int bit_num = 0; static const unsigned char bitsinbyte[256] = {0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2, 3, 2, 3, 3, 4, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 1, 2, 2, 3, 2, 3, 3, 4, 2, 3, 3, 4, 3, 4, 4, 5, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 2, 3, 3, 4, 3, 4, 4, 5, 3, 4, 4, 5, 4, 5, 5, 6, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 3, 4, 4, 5, 4, 5, 5, 6, 4, 5, 5, 6, 5, 6, 6, 7, 4, 5, 5, 6, 5, 6, 6, 7, 5, 6, 6, 7, 6, 7, 7, 8}; for (int i = 0; i < bytes; i++) { bit_num += bitsinbyte[static_cast<unsigned int>(value[i])]; } return bit_num; } Status RedisStrings::BitCount(const Slice& key, int64_t start_offset, int64_t end_offset, int32_t* ret, bool have_range) { *ret = 0; std::string value; Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); const unsigned char* bit_value = reinterpret_cast<const unsigned char*>(value.data()); int64_t value_length = value.length(); if (have_range) { if (start_offset < 0) { start_offset = start_offset + value_length; } if (end_offset < 0) { end_offset = end_offset + value_length; } if (start_offset < 0) { start_offset = 0; } if (end_offset < 0) { end_offset = 0; } if (end_offset >= value_length) { end_offset = value_length -1; } if (start_offset > end_offset) { return Status::OK(); } } else { start_offset = 0; end_offset = std::max(value_length - 1, static_cast<int64_t>(0)); } *ret = GetBitCount(bit_value + start_offset, end_offset - start_offset + 1); } } else { return s; } return Status::OK(); } std::string BitOpOperate(BitOpType op, const std::vector<std::string> &src_values, int64_t max_len) { char* dest_value = new char[max_len]; char byte, output; for (int64_t j = 0; j < max_len; j++) { if (j < static_cast<int64_t>(src_values[0].size())) { output = src_values[0][j]; } else { output = 0; } if (op == kBitOpNot) { output = ~(output); } for (size_t i = 1; i < src_values.size(); i++) { if (static_cast<int64_t>(src_values[i].size()) - 1 >= j) { byte = src_values[i][j]; } else { byte = 0; } switch (op) { case kBitOpNot: break; case kBitOpAnd: output &= byte; break; case kBitOpOr: output |= byte; break; case kBitOpXor: output ^= byte; break; case kBitOpDefault: break; } } dest_value[j] = output; } std::string dest_str(dest_value, max_len); delete[] dest_value; return dest_str; } Status RedisStrings::BitOp(BitOpType op, const std::string& dest_key, const std::vector<std::string>& src_keys, int64_t* ret) { Status s; if (op == kBitOpNot && src_keys.size() != 1) { return Status::InvalidArgument("the number of source keys is not right"); } else if (src_keys.size() < 1) { return Status::InvalidArgument("the number of source keys is not right"); } int64_t max_len = 0, value_len = 0; std::vector<std::string> src_values; for (size_t i = 0; i < src_keys.size(); i++) { std::string value; s = db_->Get(default_read_options_, src_keys[i], &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { src_values.push_back(std::string("")); value_len = 0; } else { parsed_strings_value.StripSuffix(); src_values.push_back(value); value_len = value.size(); } } else if (s.IsNotFound()) { src_values.push_back(std::string("")); value_len = 0; } else { return s; } max_len = std::max(max_len, value_len); } std::string dest_value = BitOpOperate(op, src_values, max_len); *ret = dest_value.size(); StringsValue strings_value(Slice(dest_value.c_str(), static_cast<size_t>(max_len))); ScopeRecordLock l(lock_mgr_, dest_key); return db_->Put(default_write_options_, dest_key, strings_value.Encode()); } Status RedisStrings::Decrby(const Slice& key, int64_t value, int64_t* ret) { std::string old_value; std::string new_value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { *ret = -value; new_value = std::to_string(*ret); StringsValue strings_value(new_value); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { int32_t timestamp = parsed_strings_value.timestamp(); std::string old_user_value = parsed_strings_value.value().ToString(); char* end = nullptr; int64_t ival = strtoll(old_user_value.c_str(), &end, 10); if (*end != 0) { return Status::Corruption("Value is not a integer"); } if ((value >= 0 && LLONG_MIN + value > ival) || (value < 0 && LLONG_MAX + value < ival)) { return Status::InvalidArgument("Overflow"); } *ret = ival - value; new_value = std::to_string(*ret); StringsValue strings_value(new_value); strings_value.set_timestamp(timestamp); return db_->Put(default_write_options_, key, strings_value.Encode()); } } else if (s.IsNotFound()) { *ret = -value; new_value = std::to_string(*ret); StringsValue strings_value(new_value); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { return s; } } Status RedisStrings::Get(const Slice& key, std::string* value) { value->clear(); Status s = db_->Get(default_read_options_, key, value); if (s.ok()) { ParsedStringsValue parsed_strings_value(value); if (parsed_strings_value.IsStale()) { value->clear(); return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); } } return s; } Status RedisStrings::GetBit(const Slice& key, int64_t offset, int32_t* ret) { std::string meta_value; Status s = db_->Get(default_read_options_, key, &meta_value); if (s.ok() || s.IsNotFound()) { std::string data_value; if (s.ok()) { ParsedStringsValue parsed_strings_value(&meta_value); if (parsed_strings_value.IsStale()) { *ret = 0; return Status::OK(); } else { data_value = parsed_strings_value.value().ToString(); } } size_t byte = offset >> 3; size_t bit = 7 - (offset & 0x7); if (byte + 1 > data_value.length()) { *ret = 0; } else { *ret = ((data_value[byte] & (1 << bit)) >> bit); } } else { return s; } return Status::OK(); } Status RedisStrings::Getrange(const Slice& key, int64_t start_offset, int64_t end_offset, std::string* ret) { *ret = ""; std::string value; Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); int64_t size = value.size(); int64_t start_t = start_offset >= 0 ? start_offset : size + start_offset; int64_t end_t = end_offset >= 0 ? end_offset : size + end_offset; if (start_t > size - 1 || (start_t != 0 && start_t > end_t) || (start_t != 0 && end_t < 0) ) { return Status::OK(); } if (start_t < 0) { start_t = 0; } if (end_t >= size) { end_t = size - 1; } if (start_t == 0 && end_t < 0) { end_t = 0; } *ret = value.substr(start_t, end_t-start_t+1); return Status::OK(); } } else { return s; } } Status RedisStrings::GetSet(const Slice& key, const Slice& value, std::string* old_value) { ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(old_value); if (parsed_strings_value.IsStale()) { *old_value = ""; } else { parsed_strings_value.StripSuffix(); } } else if (!s.IsNotFound()) { return s; } StringsValue strings_value(value); return db_->Put(default_write_options_, key, strings_value.Encode()); } Status RedisStrings::Incrby(const Slice& key, int64_t value, int64_t* ret) { std::string old_value; std::string new_value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { *ret = value; char buf[32]; Int64ToStr(buf, 32, value); StringsValue strings_value(buf); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { int32_t timestamp = parsed_strings_value.timestamp(); std::string old_user_value = parsed_strings_value.value().ToString(); char* end = nullptr; int64_t ival = strtoll(old_user_value.c_str(), &end, 10); if (*end != 0) { return Status::Corruption("Value is not a integer"); } if ((value >= 0 && LLONG_MAX - value < ival) || (value < 0 && LLONG_MIN - value > ival)) { return Status::InvalidArgument("Overflow"); } *ret = ival + value; new_value = std::to_string(*ret); StringsValue strings_value(new_value); strings_value.set_timestamp(timestamp); return db_->Put(default_write_options_, key, strings_value.Encode()); } } else if (s.IsNotFound()) { *ret = value; char buf[32]; Int64ToStr(buf, 32, value); StringsValue strings_value(buf); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { return s; } } Status RedisStrings::Incrbyfloat(const Slice& key, const Slice& value, std::string* ret) { std::string old_value, new_value; long double long_double_by; if (StrToLongDouble(value.data(), value.size(), &long_double_by) == -1) { return Status::Corruption("Value is not a vaild float"); } ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { LongDoubleToStr(long_double_by, &new_value); *ret = new_value; StringsValue strings_value(new_value); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { int32_t timestamp = parsed_strings_value.timestamp(); std::string old_user_value = parsed_strings_value.value().ToString(); long double total, old_number; if (StrToLongDouble(old_user_value.data(), old_user_value.size(), &old_number) == -1) { return Status::Corruption("Value is not a vaild float"); } total = old_number + long_double_by; if (LongDoubleToStr(total, &new_value) == -1) { return Status::InvalidArgument("Overflow"); } *ret = new_value; StringsValue strings_value(new_value); strings_value.set_timestamp(timestamp); return db_->Put(default_write_options_, key, strings_value.Encode()); } } else if (s.IsNotFound()) { LongDoubleToStr(long_double_by, &new_value); *ret = new_value; StringsValue strings_value(new_value); return db_->Put(default_write_options_, key, strings_value.Encode()); } else { return s; } } Status RedisStrings::MGet(const std::vector<std::string>& keys, std::vector<ValueStatus>* vss) { vss->clear(); Status s; std::string value; rocksdb::ReadOptions read_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); read_options.snapshot = snapshot; for (const auto& key : keys) { s = db_->Get(read_options, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { vss->push_back({std::string(), Status::NotFound("Stale")}); } else { vss->push_back( {parsed_strings_value.user_value().ToString(), Status::OK()}); } } else if (s.IsNotFound()) { vss->push_back({std::string(), Status::NotFound()}); } else { vss->clear(); return s; } } return Status::OK(); } Status RedisStrings::MSet(const std::vector<KeyValue>& kvs) { std::vector<std::string> keys; for (const auto& kv : kvs) { keys.push_back(kv.key); } MultiScopeRecordLock ml(lock_mgr_, keys); rocksdb::WriteBatch batch; for (const auto& kv : kvs) { StringsValue strings_value(kv.value); batch.Put(kv.key, strings_value.Encode()); } return db_->Write(default_write_options_, &batch); } Status RedisStrings::MSetnx(const std::vector<KeyValue>& kvs, int32_t* ret) { Status s; bool exists = false; *ret = 0; std::string value; for (size_t i = 0; i < kvs.size(); i++) { s = db_->Get(default_read_options_, kvs[i].key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (!parsed_strings_value.IsStale()) { exists = true; break; } } } if (!exists) { s = MSet(kvs); if (s.ok()) { *ret = 1; } } return s; } Status RedisStrings::Set(const Slice& key, const Slice& value) { StringsValue strings_value(value); ScopeRecordLock l(lock_mgr_, key); return db_->Put(default_write_options_, key, strings_value.Encode()); } Status RedisStrings::Setxx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { bool not_found = true; std::string old_value; StringsValue strings_value(value); ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(old_value); if (!parsed_strings_value.IsStale()) { not_found = false; } } else if (!s.IsNotFound()) { return s; } if (not_found) { *ret = 0; return s; } else { *ret = 1; if (ttl > 0) { strings_value.SetRelativeTimestamp(ttl); } return db_->Put(default_write_options_, key, strings_value.Encode()); } } Status RedisStrings::SetBit(const Slice& key, int64_t offset, int32_t on, int32_t* ret) { std::string meta_value; if (offset < 0) { return Status::InvalidArgument("offset < 0"); } ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &meta_value); if (s.ok() || s.IsNotFound()) { std::string data_value; if (s.ok()) { ParsedStringsValue parsed_strings_value(&meta_value); if (!parsed_strings_value.IsStale()) { data_value = parsed_strings_value.value().ToString(); } } size_t byte = offset >> 3; size_t bit = 7 - (offset & 0x7); char byte_val; size_t value_lenth = data_value.length(); if (byte + 1 > value_lenth) { *ret = 0; byte_val = 0; } else { *ret = ((data_value[byte] & (1 << bit)) >> bit); byte_val = data_value[byte]; } if (*ret == on) { return Status::OK(); } byte_val &= static_cast<char>(~(1 << bit)); byte_val |= static_cast<char>((on & 0x1) << bit); if (byte + 1 <= value_lenth) { data_value.replace(byte, 1, &byte_val, 1); } else { data_value.append(byte + 1 - value_lenth - 1, 0); data_value.append(1, byte_val); } StringsValue strings_value(data_value); return db_->Put(rocksdb::WriteOptions(), key, strings_value.Encode()); } else { return s; } } Status RedisStrings::Setex(const Slice& key, const Slice& value, int32_t ttl) { if (ttl <= 0) { return Status::InvalidArgument("invalid expire time"); } StringsValue strings_value(value); strings_value.SetRelativeTimestamp(ttl); ScopeRecordLock l(lock_mgr_, key); return db_->Put(default_write_options_, key, strings_value.Encode()); } Status RedisStrings::Setnx(const Slice& key, const Slice& value, int32_t* ret, const int32_t ttl) { *ret = 0; std::string old_value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { StringsValue strings_value(value); if (ttl > 0) { strings_value.SetRelativeTimestamp(ttl); } s = db_->Put(default_write_options_, key, strings_value.Encode()); if (s.ok()) { *ret = 1; } } } else if (s.IsNotFound()) { StringsValue strings_value(value); if (ttl > 0) { strings_value.SetRelativeTimestamp(ttl); } s = db_->Put(default_write_options_, key, strings_value.Encode()); if (s.ok()) { *ret = 1; } } return s; } Status RedisStrings::Setvx(const Slice& key, const Slice& value, const Slice& new_value, int32_t* ret, const int32_t ttl) { *ret = 0; std::string old_value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { *ret = 0; } else { if (!value.compare(parsed_strings_value.value())) { StringsValue strings_value(new_value); if (ttl > 0) { strings_value.SetRelativeTimestamp(ttl); } s = db_->Put(default_write_options_, key, strings_value.Encode()); if (!s.ok()) { return s; } *ret = 1; } else { *ret = -1; } } } else if (s.IsNotFound()) { *ret = 0; } else { return s; } return Status::OK(); } Status RedisStrings::Delvx(const Slice& key, const Slice& value, int32_t* ret) { *ret = 0; std::string old_value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); if (parsed_strings_value.IsStale()) { *ret = 0; return Status::NotFound("Stale"); } else { if (!value.compare(parsed_strings_value.value())) { *ret = 1; return db_->Delete(default_write_options_, key); } else { *ret = -1; } } } else if (s.IsNotFound()) { *ret = 0; } return s; } Status RedisStrings::Setrange(const Slice& key, int64_t start_offset, const Slice& value, int32_t* ret) { std::string old_value; std::string new_value; if (start_offset < 0) { return Status::InvalidArgument("offset < 0"); } ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &old_value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&old_value); parsed_strings_value.StripSuffix(); if (parsed_strings_value.IsStale()) { std::string tmp(start_offset, '\0'); new_value = tmp.append(value.data()); *ret = new_value.length(); } else { if (static_cast<size_t>(start_offset) > old_value.length()) { old_value.resize(start_offset); new_value = old_value.append(value.data()); } else { std::string head = old_value.substr(0, start_offset); std::string tail; if (start_offset + value.size() - 1 < old_value.length() - 1) { tail = old_value.substr(start_offset + value.size()); } new_value = head + value.data() + tail; } } *ret = new_value.length(); StringsValue strings_value(new_value); return db_->Put(default_write_options_, key, strings_value.Encode()); } else if (s.IsNotFound()) { std::string tmp(start_offset, '\0'); new_value = tmp.append(value.data()); *ret = new_value.length(); StringsValue strings_value(new_value); return db_->Put(default_write_options_, key, strings_value.Encode()); } return s; } Status RedisStrings::Strlen(const Slice& key, int32_t *len) { std::string value; Status s = Get(key, &value); if (s.ok()) { *len = value.size(); } else { *len = 0; } return s; } int32_t GetBitPos(const unsigned char* s, unsigned int bytes, int bit) { uint64_t word = 0; uint64_t skip_val = 0; unsigned char* value = const_cast<unsigned char *>(s); uint64_t* l = reinterpret_cast<uint64_t *>(value); int pos = 0; if (bit == 0) { skip_val = std::numeric_limits<uint64_t>::max(); } else { skip_val = 0; } // skip 8 bytes at one time, find the first int64 that should not be skipped while (bytes >= sizeof(*l)) { if (*l != skip_val) { break; } l++; bytes = bytes - sizeof(*l); pos = pos + 8 * sizeof(*l); } unsigned char * c = reinterpret_cast<unsigned char *>(l); for (size_t j = 0; j < sizeof(*l); j++) { word = word << 8; if (bytes) { word = word | *c; c++; bytes--; } } if (bit == 1 && word == 0) { return -1; } // set each bit of mask to 0 except msb uint64_t mask = std::numeric_limits<uint64_t>::max(); mask = mask >> 1; mask = ~(mask); while (mask) { if (((word & mask) != 0) == bit) { return pos; } pos++; mask = mask >> 1; } return pos; } Status RedisStrings::BitPos(const Slice& key, int32_t bit, int64_t* ret) { Status s; std::string value; s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { if (bit == 1) { *ret = -1; } else if (bit == 0) { *ret = 0; } return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); const unsigned char* bit_value = reinterpret_cast<const unsigned char* >(value.data()); int64_t value_length = value.length(); int64_t start_offset = 0; int64_t end_offset = std::max(value_length - 1, static_cast<int64_t>(0)); int64_t bytes = end_offset - start_offset + 1; int64_t pos = GetBitPos(bit_value + start_offset, bytes, bit); if (pos == (8 * bytes) && bit == 0) { pos = -1; } if (pos != -1) { pos = pos + 8 * start_offset; } *ret = pos; } } else { return s; } return Status::OK(); } Status RedisStrings::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t* ret) { Status s; std::string value; s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { if (bit == 1) { *ret = -1; } else if (bit == 0) { *ret = 0; } return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); const unsigned char* bit_value = reinterpret_cast<const unsigned char* >(value.data()); int64_t value_length = value.length(); int64_t end_offset = std::max(value_length - 1, static_cast<int64_t>(0)); if (start_offset < 0) { start_offset = start_offset + value_length; } if (start_offset < 0) { start_offset = 0; } if (start_offset > end_offset) { *ret = -1; return Status::OK(); } if (start_offset > value_length - 1) { *ret = -1; return Status::OK(); } int64_t bytes = end_offset - start_offset + 1; int64_t pos = GetBitPos(bit_value + start_offset, bytes, bit); if (pos == (8 * bytes) && bit == 0) { pos = -1; } if (pos != -1) { pos = pos + 8 * start_offset; } *ret = pos; } } else { return s; } return Status::OK(); } Status RedisStrings::BitPos(const Slice& key, int32_t bit, int64_t start_offset, int64_t end_offset, int64_t* ret) { Status s; std::string value; s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { if (bit == 1) { *ret = -1; } else if (bit == 0) { *ret = 0; } return Status::NotFound("Stale"); } else { parsed_strings_value.StripSuffix(); const unsigned char* bit_value = reinterpret_cast<const unsigned char* >(value.data()); int64_t value_length = value.length(); if (start_offset < 0) { start_offset = start_offset + value_length; } if (start_offset < 0) { start_offset = 0; } if (end_offset < 0) { end_offset = end_offset + value_length; } // converting to int64_t just avoid warning if (end_offset > static_cast<int64_t>(value.length()) - 1) { end_offset = value_length - 1; } if (end_offset < 0) { end_offset = 0; } if (start_offset > end_offset) { *ret = -1; return Status::OK(); } if (start_offset > value_length - 1) { *ret = -1; return Status::OK(); } int64_t bytes = end_offset - start_offset + 1; int64_t pos = GetBitPos(bit_value + start_offset, bytes, bit); if (pos == (8 * bytes) && bit == 0) { pos = -1; } if (pos != -1) { pos = pos + 8 * start_offset; } *ret = pos; } } else { return s; } return Status::OK(); } Status RedisStrings::PKSetexAt(const Slice& key, const Slice& value, int32_t timestamp) { StringsValue strings_value(value); ScopeRecordLock l(lock_mgr_, key); strings_value.set_timestamp(timestamp); return db_->Put(default_write_options_, key, strings_value.Encode()); } Status RedisStrings::PKScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector<KeyValue>* kvs, std::string* next_key) { next_key->clear(); std::string key, value; int32_t remain = limit; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) > 0)) { return Status::InvalidArgument("error in given range"); } // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* it = db_->NewIterator(iterator_options); if (start_no_limit) { it->SeekToFirst(); } else { it->Seek(key_start); } while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Next(); } else { key = it->key().ToString(); value = parsed_strings_value.value().ToString(); if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { kvs->push_back({key, value}); } remain--; it->Next(); } } while (it->Valid() && (end_no_limit || it->key().compare(key_end) <= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Next(); } else { *next_key = it->key().ToString(); break; } } delete it; return Status::OK(); } Status RedisStrings::PKRScanRange(const Slice& key_start, const Slice& key_end, const Slice& pattern, int32_t limit, std::vector<KeyValue>* kvs, std::string* next_key) { std::string key, value; int32_t remain = limit; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; bool start_no_limit = !key_start.compare(""); bool end_no_limit = !key_end.compare(""); if (!start_no_limit && !end_no_limit && (key_start.compare(key_end) < 0)) { return Status::InvalidArgument("error in given range"); } // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* it = db_->NewIterator(iterator_options); if (start_no_limit) { it->SeekToLast(); } else { it->SeekForPrev(key_start); } while (it->Valid() && remain > 0 && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Prev(); } else { key = it->key().ToString(); value = parsed_strings_value.value().ToString(); if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { kvs->push_back({key, value}); } remain--; it->Prev(); } } while (it->Valid() && (end_no_limit || it->key().compare(key_end) >= 0)) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Prev(); } else { *next_key = it->key().ToString(); break; } } delete it; return Status::OK(); } Status RedisStrings::Expire(const Slice& key, int32_t ttl) { std::string value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { return Status::NotFound("Stale"); } if (ttl > 0) { parsed_strings_value.SetRelativeTimestamp(ttl); return db_->Put(default_write_options_, key, value); } else { return db_->Delete(default_write_options_, key); } } return s; } Status RedisStrings::Del(const Slice& key) { std::string value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { return Status::NotFound("Stale"); } return db_->Delete(default_write_options_, key); } return s; } bool RedisStrings::Scan(const std::string& start_key, const std::string& pattern, std::vector<std::string>* keys, int64_t* count, std::string* next_key) { std::string key; bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; // Note: This is a string type and does not need to pass the column family as // a parameter, use the default column family rocksdb::Iterator* it = db_->NewIterator(iterator_options); it->Seek(start_key); while (it->Valid() && (*count) > 0) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Next(); continue; } else { key = it->key().ToString(); if (StringMatch(pattern.data(), pattern.size(), key.data(), key.size(), 0)) { keys->push_back(key); } (*count)--; it->Next(); } } std::string prefix = isTailWildcard(pattern) ? pattern.substr(0, pattern.size() - 1) : ""; if (it->Valid() && (it->key().compare(prefix) <= 0 || it->key().starts_with(prefix))) { is_finish = false; *next_key = it->key().ToString(); } else { *next_key = ""; } delete it; return is_finish; } bool RedisStrings::PKExpireScan(const std::string& start_key, int32_t min_timestamp, int32_t max_timestamp, std::vector<std::string>* keys, int64_t* leftover_visits, std::string* next_key) { bool is_finish = true; rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; rocksdb::Iterator* it = db_->NewIterator(iterator_options); it->Seek(start_key); while (it->Valid() && (*leftover_visits) > 0) { ParsedStringsValue parsed_strings_value(it->value()); if (parsed_strings_value.IsStale()) { it->Next(); continue; } else { if (min_timestamp < parsed_strings_value.timestamp() && parsed_strings_value.timestamp() < max_timestamp) { keys->push_back(it->key().ToString()); } (*leftover_visits)--; it->Next(); } } if (it->Valid()) { is_finish = false; *next_key = it->key().ToString(); } else { *next_key = ""; } delete it; return is_finish; } Status RedisStrings::Expireat(const Slice& key, int32_t timestamp) { std::string value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { return Status::NotFound("Stale"); } else { if (timestamp > 0) { parsed_strings_value.set_timestamp(timestamp); return db_->Put(default_write_options_, key, value); } else { return db_->Delete(default_write_options_, key); } } } return s; } Status RedisStrings::Persist(const Slice& key) { std::string value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { return Status::NotFound("Stale"); } else { int32_t timestamp = parsed_strings_value.timestamp(); if (timestamp == 0) { return Status::NotFound("Not have an associated timeout"); } else { parsed_strings_value.set_timestamp(0); return db_->Put(default_write_options_, key, value); } } } return s; } Status RedisStrings::TTL(const Slice& key, int64_t* timestamp) { std::string value; ScopeRecordLock l(lock_mgr_, key); Status s = db_->Get(default_read_options_, key, &value); if (s.ok()) { ParsedStringsValue parsed_strings_value(&value); if (parsed_strings_value.IsStale()) { *timestamp = -2; return Status::NotFound("Stale"); } else { *timestamp = parsed_strings_value.timestamp(); if (*timestamp == 0) { *timestamp = -1; } else { int64_t curtime; rocksdb::Env::Default()->GetCurrentTime(&curtime); *timestamp = *timestamp - curtime >= 0 ? *timestamp - curtime : -2; } } } else if (s.IsNotFound()) { *timestamp = -2; } return s; } void RedisStrings::ScanDatabase() { rocksdb::ReadOptions iterator_options; const rocksdb::Snapshot* snapshot; ScopeSnapshot ss(db_, &snapshot); iterator_options.snapshot = snapshot; iterator_options.fill_cache = false; int32_t current_time = time(NULL); printf("\n***************String Data***************\n"); auto iter = db_->NewIterator(iterator_options); for (iter->SeekToFirst(); iter->Valid(); iter->Next()) { ParsedStringsValue parsed_strings_value(iter->value()); int32_t survival_time = 0; if (parsed_strings_value.timestamp() != 0) { survival_time = parsed_strings_value.timestamp() - current_time > 0 ? parsed_strings_value.timestamp() - current_time : -1; } printf("[key : %-30s] [value : %-30s] [timestamp : %-10d] [version : %d] [survival_time : %d]\n", iter->key().ToString().c_str(), parsed_strings_value.value().ToString().c_str(), parsed_strings_value.timestamp(), parsed_strings_value.version(), survival_time); } delete iter; } } // namespace blackwidow
30.785268
101
0.599797
WyattJia
fff3a9a001b1d1a1190b0de3d9c5570bc8cface2
67
cpp
C++
test/com/facebook/buck/cxx/testdata/step_test/source_full_header.cpp
Unknoob/buck
2dfc734354b326f2f66896dde7746a11965d5a13
[ "Apache-2.0" ]
8,027
2015-01-02T05:31:44.000Z
2022-03-31T07:08:09.000Z
test/com/facebook/buck/cxx/testdata/step_test/source_full_header.cpp
Unknoob/buck
2dfc734354b326f2f66896dde7746a11965d5a13
[ "Apache-2.0" ]
2,355
2015-01-01T15:30:53.000Z
2022-03-30T20:21:16.000Z
test/com/facebook/buck/cxx/testdata/step_test/source_full_header.cpp
Unknoob/buck
2dfc734354b326f2f66896dde7746a11965d5a13
[ "Apache-2.0" ]
1,280
2015-01-09T03:29:04.000Z
2022-03-30T15:14:14.000Z
#include "prefix/source_full_header.h" int main() { return 0; }
11.166667
38
0.686567
Unknoob
fff3c70ae2abda3d5d44cc736ac9dc25e5b28f4b
499
cpp
C++
BinarySearch/BinarySearch/BinarySearchIterative.cpp
gabrieltavares0123/AlgorithmDesignAndAnalysis
8c19772f0e6805812e4be74f7276637112c9b444
[ "Apache-2.0" ]
null
null
null
BinarySearch/BinarySearch/BinarySearchIterative.cpp
gabrieltavares0123/AlgorithmDesignAndAnalysis
8c19772f0e6805812e4be74f7276637112c9b444
[ "Apache-2.0" ]
null
null
null
BinarySearch/BinarySearch/BinarySearchIterative.cpp
gabrieltavares0123/AlgorithmDesignAndAnalysis
8c19772f0e6805812e4be74f7276637112c9b444
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <vector> using namespace std; int binarySearchIterative(vector<int> vctr, int target) { int min = 0; int max = vctr.size() - 1; while (min < max) { int guess = (min + max) / 2; if (vctr.at(guess) == target) { return guess; } else if (vctr.at(guess) < target) { min = guess + 1; } else { max = guess - 1; } } return -1; }
16.633333
56
0.442886
gabrieltavares0123
fff433d8a1669eab3c752b3bad20b40baf5674ae
14,013
cpp
C++
dev/MRTCore/mrt/mrm/UnitTests/ResourcePackMerge.UnitTests.cpp
Andrea-MariaDB-2/WindowsAppSDK
5a6b4064f7dc23a548c9f3a4065c12a5ee9f15c7
[ "CC-BY-4.0", "MIT" ]
2,002
2020-05-19T15:16:02.000Z
2021-06-24T13:28:05.000Z
dev/MRTCore/mrt/mrm/UnitTests/ResourcePackMerge.UnitTests.cpp
oldnewthing/WindowsAppSDK
e82f072c131807765efd84f4d55ab4de3ecbb75c
[ "CC-BY-4.0", "MIT" ]
1,065
2021-06-24T16:08:11.000Z
2022-03-31T23:12:32.000Z
dev/MRTCore/mrt/mrm/UnitTests/ResourcePackMerge.UnitTests.cpp
oldnewthing/WindowsAppSDK
e82f072c131807765efd84f4d55ab4de3ecbb75c
[ "CC-BY-4.0", "MIT" ]
106
2020-05-19T15:20:00.000Z
2021-06-24T15:03:57.000Z
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See LICENSE in the project root for license information. #include "StdAfx.h" #include "Helpers.h" #include "mrm/build/Base.h" #include "mrm/readers/MrmReaders.h" #include "mrm/build/MrmBuilders.h" #include "mrm/build/ResourcePackMerge.h" #include "TestPri.h" #include "TestMap.h" using namespace WEX::Common; using namespace WEX::TestExecution; using namespace WEX::Logging; using namespace Microsoft::Resources; using namespace Microsoft::Resources::Build; namespace UnitTests { class ResourcePackMergeTests : public WEX::TestClass<ResourcePackMergeTests> { public: TEST_CLASS(ResourcePackMergeTests); BEGIN_TEST_METHOD(ThreeFilesMergeTest) TEST_METHOD_PROPERTY(L"DataSource", L"Table:ResourcePackMerge.UnitTests.xml#ThreeFilesMergeTests") END_TEST_METHOD(); BEGIN_TEST_METHOD(LoadUnloadWithResourcePackTest) TEST_METHOD_PROPERTY(L"DataSource", L"Table:ResourcePackMerge.UnitTests.xml#LoadPriWitMergeTests") END_TEST_METHOD(); private: bool _BuildAndVerifyPri(_In_ TestHPri* pTestHPri, _In_ PCWSTR pVarPrefix, _In_ bool bAutoMerge, _In_ bool bResourcePackMerge); bool _CreatePriFile( _In_ PCWSTR pszPrefix, _In_opt_ PCWSTR pszFolder, _In_ PCWSTR pszFileName, _Inout_ TestHPri& testHPri, _Inout_ String& strOutPath, _In_ bool bAlwasyCreateClassFolder, _In_ bool bResourcePackMerge); bool _VerifyMergedFile(_In_ PCWSTR pszMergedFile, _In_ PCWSTR pszManifestClassName, _In_ TestHPri* pTestHPri); }; /* - SimpleTest - Merge three files without preload flag - PreloadSimpleTest - Merge three files with preload the first file on - */ void ResourcePackMergeTests::ThreeFilesMergeTest() { FileBasedTest fileBasedTestObj; String strPri3FilePath; String strPri4FilePath; String strPri5FilePath; TestHPri testHPri3; TestHPri testHPri4; TestHPri testHPri5; //StringResult strMergedFilePath; VERIFY_IS_TRUE(fileBasedTestObj.SetupClassFolders(L"ResourcePackMergeTests")); // Build Pri1 VERIFY_IS_TRUE(_CreatePriFile( L"Pri3_", L"ResourcePackMergeTests_ThreeFilesMerge", L"ResourcePackMergeTests_Main.pri", testHPri3, strPri3FilePath, true, true)); // Build Pri2 VERIFY_IS_TRUE(_CreatePriFile( L"Pri4_", L"ResourcePackMergeTests_ThreeFilesMerge", L"ResourcePackMergeTests_it-it.pri", testHPri4, strPri4FilePath, false, true)); // Build Pri3 VERIFY_IS_TRUE(_CreatePriFile( L"Pri5_", L"ResourcePackMergeTests_ThreeFilesMerge", L"ResourcePackMergeTests_ko-KR.pri", testHPri5, strPri5FilePath, false, true)); // Call LoadPriFiles AutoDeletePtr<CoreProfile> pProfile; VERIFY_SUCCEEDED(CoreProfile::ChooseDefaultProfile(&pProfile)); AutoDeletePtr<UnifiedResourceView> spUnifiedResourceView; VERIFY_SUCCEEDED(UnifiedResourceView::CreateInstance(pProfile, &spUnifiedResourceView)); DynamicArray<PCWSTR> priPathsCollection; StringResult srPriFile3; VERIFY_SUCCEEDED(srPriFile3.Init(reinterpret_cast<PCWSTR>(strPri3FilePath.GetBuffer()))); StringResult srPriFile4; VERIFY_SUCCEEDED(srPriFile4.Init(reinterpret_cast<PCWSTR>(strPri4FilePath.GetBuffer()))); StringResult srPriFile5; VERIFY_SUCCEEDED(srPriFile5.Init(reinterpret_cast<PCWSTR>(strPri5FilePath.GetBuffer()))); VERIFY_SUCCEEDED(priPathsCollection.Add(srPriFile3.GetRef())); VERIFY_SUCCEEDED(priPathsCollection.Add(srPriFile4.GetRef())); VERIFY_SUCCEEDED(priPathsCollection.Add(srPriFile5.GetRef())); AutoDeletePtr<ResourcePackMerge> spResourcePackMerge; VERIFY_SUCCEEDED(ResourcePackMerge::CreateInstance(pProfile, &spResourcePackMerge)); VERIFY(spResourcePackMerge != NULL); //preload set PCWSTR path; VERIFY_SUCCEEDED(priPathsCollection.Get(0, &path)); VERIFY_SUCCEEDED(spResourcePackMerge->AddPriFile( path, PriFileMerger::InPlaceMerge | PriFileMerger::SetPreLoad | PriFileMerger::DefaultPriMergeFlags)); for (UINT i = 1; i < priPathsCollection.Count(); i++) { VERIFY_SUCCEEDED(priPathsCollection.Get(i, &path)); VERIFY_SUCCEEDED(spResourcePackMerge->AddPriFile(path, PriFileMerger::InPlaceMerge | PriFileMerger::DefaultPriMergeFlags)); } VERIFY_FAILED(spResourcePackMerge->AddPriFile(srPriFile5.GetRef(), PriFileMerger::InPlaceMerge | PriFileMerger::DefaultPriMergeFlags)); priPathsCollection.Reset(); String strOutPath; // Get the merged file path fileBasedTestObj.GetTestOutputDirectory(L"ResourcePackMergeTests_ThreeFilesMerge", NULL, strOutPath); strOutPath += L"\\"; strOutPath += L"MergedPriFile.pri"; VERIFY_SUCCEEDED(spResourcePackMerge->WriteToFile(strOutPath)); _VerifyMergedFile(strOutPath, L"PriMerged_3_4_5_", &testHPri3); fileBasedTestObj.CleanupClassFolders(); } void ResourcePackMergeTests::LoadUnloadWithResourcePackTest() { FileBasedTest fileBasedTestObj; String strPri3FilePath; String strPri4FilePath; String strPri5FilePath; TestHPri testHPri3; TestHPri testHPri4; TestHPri testHPri5; //StringResult strMergedFilePath; VERIFY_IS_TRUE(fileBasedTestObj.SetupClassFolders(L"LoadPriWithMergedFile")); // Build Pri3 VERIFY_IS_TRUE( _CreatePriFile(L"Pri3_", L"LoadPriWithMergedFile", L"LoadPriWithMergedFile_Main.pri", testHPri3, strPri3FilePath, true, true)); // Build Pri4 VERIFY_IS_TRUE( _CreatePriFile(L"Pri4_", L"LoadPriWithMergedFile", L"LoadPriWithMergedFile_it-it.pri", testHPri4, strPri4FilePath, false, true)); // Build Pri5 VERIFY_IS_TRUE( _CreatePriFile(L"Pri5_", L"LoadPriWithMergedFile", L"LoadPriWithMergedFile_ko-KR.pri", testHPri5, strPri5FilePath, false, true)); // Call LoadPriFiles AutoDeletePtr<CoreProfile> pProfile; VERIFY_SUCCEEDED(CoreProfile::ChooseDefaultProfile(&pProfile)); StringResult srPriFile3; VERIFY_SUCCEEDED(srPriFile3.Init(reinterpret_cast<PCWSTR>(strPri3FilePath.GetBuffer()))); StringResult srPriFile4; VERIFY_SUCCEEDED(srPriFile4.Init(reinterpret_cast<PCWSTR>(strPri4FilePath.GetBuffer()))); StringResult srPriFile5; VERIFY_SUCCEEDED(srPriFile5.Init(reinterpret_cast<PCWSTR>(strPri5FilePath.GetBuffer()))); AutoDeletePtr<ResourcePackMerge> spResourcePackMerge; VERIFY_SUCCEEDED(ResourcePackMerge::CreateInstance(pProfile, &spResourcePackMerge)); VERIFY(spResourcePackMerge != NULL); //preload set VERIFY_SUCCEEDED( spResourcePackMerge->AddPriFile(srPriFile3.GetRef(), PriFileMerger::InPlaceMerge | PriFileMerger::DefaultPriMergeFlags)); VERIFY_SUCCEEDED(spResourcePackMerge->AddPriFile( srPriFile4.GetRef(), PriFileMerger::InPlaceMerge | PriFileMerger::SetPreLoad | PriFileMerger::DefaultPriMergeFlags)); String strOutPath; // Get the merged file path fileBasedTestObj.GetTestOutputDirectory(L"ResourcePackMergeTests_ThreeFilesMerge", NULL, strOutPath); strOutPath += L"\\"; strOutPath += L"MergedPriFile.pri"; // Merged file that has Pri3 and Pri4 VERIFY_SUCCEEDED(spResourcePackMerge->WriteToFile(strOutPath)); // LoadPriFiles Merged file as well as single resource PRI file. AutoDeletePtr<UnifiedResourceView> spUnifiedResourceView; VERIFY_SUCCEEDED(UnifiedResourceView::CreateInstance(pProfile, &spUnifiedResourceView)); DynamicArray<StringResult*> priPathsCollection; DynamicArray<UnifiedResourceView::PriFileInfo*>* pLoadedPriFilesInfo = NULL; StringResult srMergedFile; VERIFY_SUCCEEDED(srMergedFile.Init(strOutPath)); VERIFY_SUCCEEDED(priPathsCollection.Add(&srMergedFile)); // Merged file becom main pri package { // Load Merged file first VERIFY_SUCCEEDED( spUnifiedResourceView->LoadPriFiles(PACKAGE_INIT, &priPathsCollection, LoadPriFlags::Default, &pLoadedPriFilesInfo)); for (UINT uItr = 0; uItr < pLoadedPriFilesInfo->Count(); uItr++) { UnifiedResourceView::PriFileInfo* pLoadedPriFileInfo; pLoadedPriFilesInfo->Get(uItr, &pLoadedPriFileInfo); delete pLoadedPriFileInfo; } delete pLoadedPriFilesInfo; pLoadedPriFilesInfo = NULL; priPathsCollection.Reset(); // remove merged pri file VERIFY_SUCCEEDED(srPriFile5.Init(reinterpret_cast<PCWSTR>(strPri5FilePath.GetBuffer()))); priPathsCollection.Add(&srPriFile5); // Load additional PRI (deployment merge-able flag set) File with EXPLICIT_LOAD { VERIFY_SUCCEEDED( spUnifiedResourceView->LoadPriFiles(EXPLICIT_LOAD, &priPathsCollection, LoadPriFlags::Default, &pLoadedPriFilesInfo)); for (UINT uItr = 0; uItr < pLoadedPriFilesInfo->Count(); uItr++) { UnifiedResourceView::PriFileInfo* pLoadedPriFileInfo; pLoadedPriFilesInfo->Get(uItr, &pLoadedPriFileInfo); delete pLoadedPriFileInfo; } delete pLoadedPriFilesInfo; pLoadedPriFilesInfo = NULL; } // Unload resource pack that is already loaded as part of Merged file HRESULT hr = spUnifiedResourceView->RemoveFileReference(srPriFile4.GetRef()); VERIFY_ARE_EQUAL(hr, HRESULT_FROM_WIN32(ERROR_MRM_UNSUPPORTED_FILE_TYPE_FOR_LOAD_UNLOAD_PRI_FILE)); } fileBasedTestObj.CleanupClassFolders(); } bool ResourcePackMergeTests::_VerifyMergedFile(_In_ PCWSTR pszMergedFile, _In_ PCWSTR pszManifestClassName, _In_ TestHPri* pTestHPri) { // Load the merged PRI file with official API DynamicArray<StringResult*> priPathsCollection; AutoDeletePtr<CoreProfile> pProfile; VERIFY_SUCCEEDED(CoreProfile::ChooseDefaultProfile(&pProfile)); AutoDeletePtr<UnifiedResourceView> spUnifiedResourceView; VERIFY_SUCCEEDED(UnifiedResourceView::CreateInstance(pProfile, &spUnifiedResourceView)); StringResult strFilePath; VERIFY_SUCCEEDED(strFilePath.Init(pszMergedFile)); priPathsCollection.Add(&strFilePath); DynamicArray<UnifiedResourceView::PriFileInfo*>* pLoadedPriFilesInfo = nullptr; VERIFY_SUCCEEDED(spUnifiedResourceView->LoadPriFiles(EXPLICIT_LOAD, &priPathsCollection, LoadPriFlags::Default, &pLoadedPriFilesInfo)); // Test Managed Resource Map of the Merged Pri file UnifiedResourceView::PriFileInfo* pLoadedPriFileInfo; pLoadedPriFilesInfo->Get(0, &pLoadedPriFileInfo); VERIFY(pLoadedPriFileInfo != nullptr); const ManagedResourceMap* pManagedResourceMap = pLoadedPriFileInfo->GetManagedResourceMap(); TestResourceMap::VerifyAllAgainstTestVars( (const IResourceMapBase*)pManagedResourceMap, pTestHPri->GetTestDI(), spUnifiedResourceView->GetUnifiedEnvironment(), pszManifestClassName); for (UINT uItr = 0; uItr < pLoadedPriFilesInfo->Count(); uItr++) { pLoadedPriFilesInfo->Get(uItr, &pLoadedPriFileInfo); delete pLoadedPriFileInfo; } delete pLoadedPriFilesInfo; return true; } bool ResourcePackMergeTests::_CreatePriFile( _In_ PCWSTR pszPrefix, _In_opt_ PCWSTR pszClassName, _In_ PCWSTR pszFileName, _Inout_ TestHPri& testHPri, _Inout_ String& strOutPath, _In_ bool bAlwasyCreateClassFolder, _In_ bool bResourcePackMerge) { FileBasedTest fileBasedTestObj; String strVarPrefix; bool bRetVal = true; String strOutputFile; strVarPrefix = pszPrefix; if (bAlwasyCreateClassFolder) { bRetVal = fileBasedTestObj.SetupClassFolders(pszClassName); fileBasedTestObj.GetOutputFilePath(pszFileName, strOutPath); } else { fileBasedTestObj.GetTestOutputDirectory(pszClassName, nullptr, strOutPath); strOutPath += L"\\"; strOutPath += pszFileName; } bRetVal = bRetVal ? _BuildAndVerifyPri(&testHPri, strVarPrefix, false, bResourcePackMerge) : bRetVal; VERIFY(bRetVal); if (FAILED(testHPri.GetPriFileBuilder()->WriteToFile(strOutPath))) { Log::Error(L"Error building test PRI 1"); bRetVal = false; } return bRetVal; } bool ResourcePackMergeTests::_BuildAndVerifyPri( __in TestHPri* pTestHPri, __in PCWSTR strVarPrefix, __in bool bAutoMerge, _In_ bool bResourcePackMerge) { UINT32 nPriFileFlags = bAutoMerge ? MRMFILE_PRI_FLAGS_AUTO_MERGE : 0; nPriFileFlags |= bResourcePackMerge ? MRMFILE_PRI_FLAGS_DEPLOYMENT_MERGEABLE : 0; AutoDeletePtr<CoreProfile> pProfile; VERIFY_SUCCEEDED(CoreProfile::ChooseDefaultProfile(&pProfile)); Log::Comment(L"[ Setting up test PRI ]"); if (FAILED(pTestHPri->InitFromTestVars(strVarPrefix, NULL, pProfile, NULL))) { Log::Error(L"[ Couldn't init TestPri ]"); } // Set auto merge flag if (FAILED(pTestHPri->GetPriSectionBuilder()->SetPriFileFlags(nPriFileFlags))) { Log::Error(L"[ Error in setting auto merge flag ]"); return false; } // Okay, we're ready to build. Log::Comment(L"[ Building test PRI ]"); if (FAILED(pTestHPri->Build())) { Log::Error(L"[ Couldn't build test PRI ]"); return false; } // Now we have to read the PRI file back into something we can use... Log::Comment(L"[ Reading back test PRI ]"); if (FAILED(pTestHPri->CreateReader(pProfile))) { Log::Error(L"Couldn't read back test PRI"); return false; } Log::Comment(L"[ Verifying test PRI ]"); return SUCCEEDED(TestHPri::VerifyAgainstTestVars(pTestHPri->GetPriFile(), L"", pTestHPri->GetTestDI(), strVarPrefix)); } } // namespace UnitTests
38.078804
141
0.717691
Andrea-MariaDB-2
fff809952b508086fcae4b643b9104c6d1842cf6
5,520
cpp
C++
src/friMonitoringMessageDecoder.cpp
KCL-BMEIS/fri
ed70c51bb3cbc3047673888d05a562371b8e91ce
[ "MIT" ]
null
null
null
src/friMonitoringMessageDecoder.cpp
KCL-BMEIS/fri
ed70c51bb3cbc3047673888d05a562371b8e91ce
[ "MIT" ]
3
2021-02-05T14:23:19.000Z
2022-02-28T10:10:57.000Z
src/friMonitoringMessageDecoder.cpp
KCL-BMEIS/fri
ed70c51bb3cbc3047673888d05a562371b8e91ce
[ "MIT" ]
2
2021-05-14T06:07:59.000Z
2022-01-19T15:02:19.000Z
/** The following license terms and conditions apply, unless a redistribution agreement or other license is obtained by KUKA Roboter GmbH, Augsburg, Germany. SCOPE The software "KUKA Sunrise.Connectivity FRI Client SDK" is targeted to work in conjunction with the "KUKA Sunrise.Connectivity FastRobotInterface" toolkit. In the following, the term "software" refers to all material directly belonging to the provided SDK "Software development kit", particularly source code, libraries, binaries, manuals and technical documentation. COPYRIGHT All Rights Reserved Copyright (C) 2014-2019 KUKA Roboter GmbH Augsburg, Germany LICENSE Redistribution and use of the software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: a) The software is used in conjunction with KUKA products only. b) Redistributions of source code must retain the above copyright notice, this list of conditions and the disclaimer. c) Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the disclaimer in the documentation and/or other materials provided with the distribution. Altered source code of the redistribution must be made available upon request with the distribution. d) Modification and contributions to the original software provided by KUKA must be clearly marked and the authorship must be stated. e) Neither the name of KUKA nor the trademarks owned by KUKA may be used to endorse or promote products derived from this software without specific prior written permission. DISCLAIMER OF WARRANTY The Software is provided "AS IS" and "WITH ALL FAULTS," without warranty of any kind, including without limitation the warranties of merchantability, fitness for a particular purpose and non-infringement. KUKA makes no warranty that the Software is free of defects or is suitable for any particular purpose. In no event shall KUKA be responsible for loss or damages arising from the installation or use of the Software, including but not limited to any indirect, punitive, special, incidental or consequential damages of any character including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. The entire risk to the quality and performance of the Software is not borne by KUKA. Should the Software prove defective, KUKA is not liable for the entire cost of any service and repair. \file \version {1.15} */ #include <cstdio> #include <friMonitoringMessageDecoder.h> #include <nanopb/pb_decode.h> using namespace KUKA::FRI; //****************************************************************************** MonitoringMessageDecoder::MonitoringMessageDecoder(FRIMonitoringMessage* pMessage, int num) : m_nNum(num), m_pMessage(pMessage) { initMessage(); } //****************************************************************************** MonitoringMessageDecoder::~MonitoringMessageDecoder() { } //****************************************************************************** void MonitoringMessageDecoder::initMessage() { // set initial data // it is assumed that no robot information and monitoring data is available and therefore the // optional fields are initialized with false m_pMessage->has_robotInfo = false; m_pMessage->has_monitorData = false; m_pMessage->has_connectionInfo = true; m_pMessage->has_ipoData = false; m_pMessage->requestedTransformations_count = 0; m_pMessage->has_endOfMessageData = false; m_pMessage->header.messageIdentifier = 0; m_pMessage->header.reflectedSequenceCounter = 0; m_pMessage->header.sequenceCounter = 0; m_pMessage->connectionInfo.sessionState = FRISessionState_IDLE; m_pMessage->connectionInfo.quality = FRIConnectionQuality_POOR; m_pMessage->monitorData.readIORequest_count = 0; // allocate and map memory for protobuf repeated structures map_repeatedDouble(FRI_MANAGER_NANOPB_DECODE, m_nNum, &m_pMessage->monitorData.measuredJointPosition.value, &m_tSendContainer.m_AxQMsrLocal); map_repeatedDouble(FRI_MANAGER_NANOPB_DECODE, m_nNum, &m_pMessage->monitorData.measuredTorque.value, &m_tSendContainer.m_AxTauMsrLocal); map_repeatedDouble(FRI_MANAGER_NANOPB_DECODE, m_nNum, &m_pMessage->monitorData.commandedJointPosition.value, &m_tSendContainer.m_AxQCmdT1mLocal); map_repeatedDouble(FRI_MANAGER_NANOPB_DECODE, m_nNum, &m_pMessage->monitorData.commandedTorque.value, &m_tSendContainer.m_AxTauCmdLocal); map_repeatedDouble(FRI_MANAGER_NANOPB_DECODE, m_nNum, &m_pMessage->monitorData.externalTorque.value, &m_tSendContainer.m_AxTauExtMsrLocal); map_repeatedDouble(FRI_MANAGER_NANOPB_DECODE,m_nNum, &m_pMessage->ipoData.jointPosition.value, &m_tSendContainer.m_AxQCmdIPO); map_repeatedInt(FRI_MANAGER_NANOPB_DECODE, m_nNum, &m_pMessage->robotInfo.driveState, &m_tSendContainer.m_AxDriveStateLocal); } //****************************************************************************** bool MonitoringMessageDecoder::decode(char* buffer, int size) { pb_istream_t stream = pb_istream_from_buffer((uint8_t*)buffer, size); bool status = pb_decode(&stream, FRIMonitoringMessage_fields, m_pMessage); if (!status) { printf("!!decoding error: %s!!\n", PB_GET_ERROR(&stream)); } return status; }
37.808219
97
0.733696
KCL-BMEIS
fffa5e882f086e22a2285b40d3032c15c0a7c0ee
96
cpp
C++
engine/tile.cpp
jarreed0/ArchGE
c995caf86b11f89f45fcfe1027c6068662dfcde0
[ "Apache-2.0" ]
12
2017-02-09T21:03:41.000Z
2021-04-26T14:50:20.000Z
engine/tile.cpp
jarreed0/ArchGE
c995caf86b11f89f45fcfe1027c6068662dfcde0
[ "Apache-2.0" ]
null
null
null
engine/tile.cpp
jarreed0/ArchGE
c995caf86b11f89f45fcfe1027c6068662dfcde0
[ "Apache-2.0" ]
null
null
null
#include "tile.h" Tile::Tile() {} Tile::~Tile() {} void Tile::setValue(int v) { value = v; }
12
28
0.5625
jarreed0
fffd62bbb6e1b8264051b74822bb0478aceb7ad0
1,159
cpp
C++
leetcode/_190_reverse_bits.cpp
WindyDarian/OJ_Submissions
a323595c3a32ed2e07af65374ef90c81d5333f96
[ "Apache-2.0" ]
3
2017-02-19T14:38:32.000Z
2017-07-22T17:06:55.000Z
leetcode/_190_reverse_bits.cpp
WindyDarian/OJ_Submissions
a323595c3a32ed2e07af65374ef90c81d5333f96
[ "Apache-2.0" ]
null
null
null
leetcode/_190_reverse_bits.cpp
WindyDarian/OJ_Submissions
a323595c3a32ed2e07af65374ef90c81d5333f96
[ "Apache-2.0" ]
null
null
null
//============================================================================== // Copyright 2016 Windy Darian (Ruoyu Fan) // // 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. //============================================================================== // https://leetcode.com/problems/reverse-bits/ class Solution { public: uint32_t reverseBits(uint32_t n) { n = (n & 0xFFFF0000) >> 16 | (n & 0x0000FFFF) << 16; n = (n & 0xFF00FF00) >> 8 | (n & 0x00FF00FF) << 8; n = (n & 0xF0F0F0F0) >> 4 | (n & 0x0F0F0F0F) << 4; n = (n & 0xCCCCCCCC) >> 2 | (n & 0x33333333) << 2; n = (n & 0xAAAAAAAA) >> 1 | (n & 0x55555555) << 1; return n; } };
37.387097
80
0.572908
WindyDarian
fffe8b330a6e5fcd721da4dd534bc318934d6e1c
6,889
cc
C++
cc/jwt/jwt_object.cc
iambrosie/tink
33accb5bcdff71f34d7551a669831ec9a52674aa
[ "Apache-2.0" ]
2
2020-11-09T11:25:34.000Z
2022-03-04T06:21:44.000Z
cc/jwt/jwt_object.cc
iambrosie/tink
33accb5bcdff71f34d7551a669831ec9a52674aa
[ "Apache-2.0" ]
null
null
null
cc/jwt/jwt_object.cc
iambrosie/tink
33accb5bcdff71f34d7551a669831ec9a52674aa
[ "Apache-2.0" ]
1
2020-08-11T04:52:46.000Z
2020-08-11T04:52:46.000Z
// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // /////////////////////////////////////////////////////////////////////////////// #include "tink/jwt/jwt_object.h" #include "absl/strings/numbers.h" #include "absl/strings/str_format.h" #include "absl/strings/substitute.h" #include "tink/jwt/json_object.h" #include "tink/jwt/jwt_names.h" namespace crypto { namespace tink { JwtObject::JwtObject(const JsonObject& payload) { payload_ = payload; } JwtObject::JwtObject() {} util::StatusOr<std::vector<std::string>> JwtObject::GetClaimAsStringList( absl::string_view name) const { return payload_.GetValueAsStringList(name); } util::StatusOr<std::vector<int>> JwtObject::GetClaimAsNumberList( absl::string_view name) const { return payload_.GetValueAsNumberList(name); } util::StatusOr<std::vector<std::string>> JwtObject::GetAudiences() const { std::vector<std::string> vec; auto aud_or = payload_.GetValueAsString(kJwtClaimAudience); if (aud_or.status().ok()) { vec.push_back(aud_or.ValueOrDie()); return vec; } return payload_.GetValueAsStringList(kJwtClaimAudience); } util::StatusOr<int> JwtObject::GetClaimAsNumber(absl::string_view name) const { return payload_.GetValueAsNumber(name); } util::StatusOr<bool> JwtObject::GetClaimAsBool(absl::string_view name) const { return payload_.GetValueAsBool(name); } util::StatusOr<std::string> JwtObject::GetSubject() const { return payload_.GetValueAsString(kJwtClaimSubject); } util::StatusOr<absl::Time> JwtObject::GetExpiration() const { return payload_.GetValueAsTime(kJwtClaimExpiration); } util::StatusOr<absl::Time> JwtObject::GetNotBefore() const { return payload_.GetValueAsTime(kJwtClaimNotBefore); } util::StatusOr<absl::Time> JwtObject::GetIssuedAt() const { return payload_.GetValueAsTime(kJwtClaimIssuedAt); } util::StatusOr<std::string> JwtObject::GetIssuer() const { return payload_.GetValueAsString(kJwtClaimIssuer); } util::StatusOr<std::string> JwtObject::GetJwtId() const { return payload_.GetValueAsString(kJwtClaimJwtId); } util::StatusOr<std::string> JwtObject::GetClaimAsString( absl::string_view name) const { return payload_.GetValueAsString(name); } util::Status JwtObject::SetIssuer(absl::string_view issuer) { return payload_.SetValueAsString(kJwtClaimIssuer, issuer); } util::Status JwtObject::SetSubject(absl::string_view subject) { return payload_.SetValueAsString(kJwtClaimSubject, subject); } util::Status JwtObject::SetJwtId(absl::string_view jwid) { return payload_.SetValueAsString(kJwtClaimJwtId, jwid); } util::Status JwtObject::SetExpiration(absl::Time expiration) { return payload_.SetValueAsTime(kJwtClaimExpiration, expiration); } util::Status JwtObject::SetNotBefore(absl::Time notBefore) { return payload_.SetValueAsTime(kJwtClaimNotBefore, notBefore); } util::Status JwtObject::SetIssuedAt(absl::Time issuedAt) { return payload_.SetValueAsTime(kJwtClaimIssuedAt, issuedAt); } util::Status JwtObject::AddAudience(absl::string_view audience) { return payload_.AppendValueToStringList(kJwtClaimAudience, audience); } util::Status JwtObject::SetClaimAsString(absl::string_view name, absl::string_view value) { auto status = ValidatePayloadName(name); if (status != util::Status::OK) { return status; } return payload_.SetValueAsString(name, value); } util::Status JwtObject::SetClaimAsNumber(absl::string_view name, int value) { auto status = ValidatePayloadName(name); if (status != util::Status::OK) { return status; } return payload_.SetValueAsNumber(name, value); } util::Status JwtObject::SetClaimAsBool(absl::string_view name, bool value) { auto status = ValidatePayloadName(name); if (status != util::Status::OK) { return status; } return payload_.SetValueAsBool(name, value); } util::Status JwtObject::AppendClaimToStringList(absl::string_view name, absl::string_view value) { auto status = ValidatePayloadName(name); if (status != util::Status::OK) { return status; } return payload_.AppendValueToStringList(name, value); } util::Status JwtObject::AppendClaimToNumberList(absl::string_view name, int value) { auto status = ValidatePayloadName(name); if (status != util::Status::OK) { return status; } return payload_.AppendValueToNumberList(name, value); } util::StatusOr<absl::string_view> JwtObject::AlgorithmTypeToString( const enum JwtAlgorithm algorithm) const { switch (algorithm) { case JwtAlgorithm::kHs256: return kJwtAlgorithmHs256; case JwtAlgorithm::kEs256: return kJwtAlgorithmEs256; case JwtAlgorithm::kRs256: return kJwtAlgorithmRs256; default: return crypto::tink::util::Status( util::error::UNIMPLEMENTED, absl::Substitute( "algorithm '$0' is not supported", static_cast<std::underlying_type<JwtAlgorithm>::type>( algorithm))); } } util::StatusOr<absl::flat_hash_map<std::string, enum JsonFieldType>> JwtObject::getClaimNamesAndTypes() { return payload_.getFieldNamesAndTypes(); } util::StatusOr<enum JwtAlgorithm> JwtObject::AlgorithmStringToType( absl::string_view algo_name) const { if (algo_name == kJwtAlgorithmHs256) { return JwtAlgorithm::kHs256; } if (algo_name == kJwtAlgorithmEs256) { return JwtAlgorithm::kEs256; } if (algo_name == kJwtAlgorithmRs256) { return JwtAlgorithm::kRs256; } return crypto::tink::util::Status( util::error::INVALID_ARGUMENT, absl::Substitute("algorithm '$0' does not exist", algo_name)); } util::Status JwtObject::ValidatePayloadName(absl::string_view name) { if (IsRegisteredPayloadName(name)) { return absl::InvalidArgumentError(absl::Substitute( "claim '$0' is invalid because it's a registered name; " "use the corresponding setter method.", name)); } return util::OkStatus(); } bool JwtObject::IsRegisteredPayloadName(absl::string_view name) { return name == kJwtClaimIssuer || name == kJwtClaimSubject || name == kJwtClaimAudience || name == kJwtClaimExpiration || name == kJwtClaimNotBefore || name == kJwtClaimIssuedAt || name == kJwtClaimJwtId; } } // namespace tink } // namespace crypto
30.082969
79
0.710553
iambrosie
fffe9f8d48a97a626d0f8198b81a118d0ea08a58
9,071
cpp
C++
externals/IBKMK/src/IBKMK_3DCalculations.cpp
ghorwin/IFC2BESplusplus
0c8e6d735faf56c84ff9c741773da92bc82b23dd
[ "MIT" ]
null
null
null
externals/IBKMK/src/IBKMK_3DCalculations.cpp
ghorwin/IFC2BESplusplus
0c8e6d735faf56c84ff9c741773da92bc82b23dd
[ "MIT" ]
null
null
null
externals/IBKMK/src/IBKMK_3DCalculations.cpp
ghorwin/IFC2BESplusplus
0c8e6d735faf56c84ff9c741773da92bc82b23dd
[ "MIT" ]
null
null
null
/* IBK Math Kernel Library Copyright (c) 2001-today, Institut fuer Bauklimatik, TU Dresden, Germany Written by A. Nicolai, A. Paepcke, H. Fechner, St. Vogelsang All rights reserved. This file is part of the IBKMK Library. 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 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 library contains derivative work based on other open-source libraries, see LICENSE and OTHER_LICENSES files. */ #include "IBKMK_3DCalculations.h" #include "IBKMK_Vector3D.h" namespace IBKMK { /* Solves equation system with Cramer's rule: a x + c y = e b x + d y = f */ static bool solve(double a, double b, double c, double d, double e, double f, double & x, double & y) { double det = a*d - b*c; // Prevent division by very small numbers if (std::fabs(det) < 1e-6) return false; x = (e*d - c*f)/det; y = (a*f - e*b)/det; return true; } /* Computes the coordinates x, y of a point 'p' in a plane spanned by vectors a and b from a point 'offset', where rhs = p-offset. The computed plane coordinates are stored in variables x and y (the factors for vectors a and b, respectively). If no solution could be found (only possible if a and b are collinear or one of the vectors has length 0?), the function returns false. Note: when the point p is not in the plane, this function will still get a valid result. */ bool planeCoordinates(const Vector3D & offset, const Vector3D & a, const Vector3D & b, const Vector3D & v, double & x, double & y, double tolerance) { // TODO : first project vector v onto plane (using normal vector) and check distance between v and vOnPlane // if larger than tolerance, bail out // otherwise perform point-coordinate calculation with projected point // We have 3 equations, but only two unknowns - so we have 3 different options to compute them. // Some of them may fail, so we try them all. const Vector3D & rhs = v-offset; // rows 1 and 2 bool success = solve(a.m_x, a.m_y, b.m_x, b.m_y, rhs.m_x, rhs.m_y, x, y); if (!success) // rows 1 and 3 success = solve(a.m_x, a.m_z, b.m_x, b.m_z, rhs.m_x, rhs.m_z, x, y); if (!success) // rows 2 and 3 success = solve(a.m_y, a.m_z, b.m_y, b.m_z, rhs.m_y, rhs.m_z, x, y); if (!success) return false; // check that the point was indeed in the plane Vector3D v2 = offset + x*a + y*b; v2 -= v; if (v2.magnitude() > tolerance) return false; else return true; } double lineToPointDistance(const Vector3D & a, const Vector3D & d, const Vector3D & p, double & lineFactor, Vector3D & p2) { // vector from starting point of line to target point Vector3D v = p - a; // scalar product (projection of v on d) gives scale factor lineFactor = v.scalarProduct(d); double directionVectorProjection = d.scalarProduct(d); // magnitude squared lineFactor /= directionVectorProjection; // normalize line factor // compute "lotpunkt" p2 = a + lineFactor * d; // return distance between lotpunkt and target point return (p2-p).magnitude(); } bool lineShereIntersection(const Vector3D & a, const Vector3D & d, const Vector3D & p, double r, double & lineFactor, Vector3D & lotpoint) { // compute lotpoint and distance between line and sphere center double lineFactorToLotPoint; double distanceLineToSphereCenter = lineToPointDistance(a, d, p, lineFactorToLotPoint, lotpoint); // pass by? if (distanceLineToSphereCenter > r) return false; // solve for intersection with radius // extreme cases: // r = b -> x = 0, intersection with sphere = lotpoint // b = 0 -> x = r, line passes through center of sphere, our sphere intersection point is distance // 'r' closer to the point a double x = std::sqrt(r*r - distanceLineToSphereCenter*distanceLineToSphereCenter); // and normalize to get distance as fraction of direction vector (line factor) x /= d.magnitude(); // subtract distance to get lineFactor to intersection point with sphere lineFactor = lineFactorToLotPoint-x; return true; } double lineToLineDistance(const Vector3D & a1, const Vector3D & d1, const Vector3D & a2, const Vector3D & d2, double & l1, Vector3D & p1, double & l2) { /// source: http://geomalgorithms.com/a02-_lines.html Vector3D v = a1 - a2; double d1Scalar = d1.scalarProduct(d1);// always >= 0 double d1d2Scalar = d1.scalarProduct(d2); double d2Scalar = d2.scalarProduct(d2); double d1vScalar = d1.scalarProduct(v);// always >= 0 double d2vScalar = d2.scalarProduct(v); double d = d1Scalar*d2Scalar - d1d2Scalar*d1d2Scalar;// always >= 0 // compute the line parameters of the two closest points if (d<1E-4) { // the lines are almost parallel l1 = 0.0; // we have to set one factor to determine a point since there are infinite l2 = (d1d2Scalar>d2Scalar ? d1vScalar/d1d2Scalar : d2vScalar/d2Scalar); // use the largest denominator } else { l1 = (d1d2Scalar*d2vScalar - d2Scalar*d1vScalar) / d; l2 = (d1Scalar*d2vScalar - d1d2Scalar*d1vScalar) / d; } p1 = a1 + ( l1 * d1 ); // point 1 Vector3D p2 = a2 + (l2 * d2 ); // point 2 // get the difference of the two closest points return ( p1 - p2 ).magnitude(); // return the closest distance } void pointProjectedOnPlane(const Vector3D & a, const Vector3D & normal, const Vector3D & p, Vector3D & projectedP) { // vector from point to plane origin projectedP = p-a; // scalar product between this vector and plane's normal double dist = normal.m_x*projectedP.m_x + normal.m_y*projectedP.m_y + normal.m_z*projectedP.m_z; // subtract normal vector's contribution of project P from p projectedP = p - dist*normal; } // Eleminate one coolinear point. If a point is erased return true. static bool eleminateColinearPtsHelper(std::vector<IBKMK::Vector3D> &polyline) { if(polyline.size()<=2) return false; const double eps = 1e-4; unsigned int polySize = (unsigned int)polyline.size(); for(unsigned int idx=0; idx<polySize; ++idx){ unsigned int idx0 = idx-1; if(idx==0) idx0 = polySize-1; IBKMK::Vector3D a = polyline.at(idx0) - polyline.at(idx); IBKMK::Vector3D b = polyline.at((idx+1) % polySize) - polyline.at(idx); a.normalize(); b.normalize(); double cosAngle = a.scalarProduct(b); if(cosAngle < -1+eps || cosAngle > 1-eps){ polyline.erase(polyline.begin()+idx); return true; } } return false; } void eleminateColinearPoints(std::vector<IBKMK::Vector3D> & polygon) { if(polygon.size()<2) return; //check for duplicate points in polyline and remove duplicates for (int i=(int)polygon.size()-1; i>=0; --i) { if(polygon.size()<2) return; size_t j=(size_t)i-1; if(i==0) j=polygon.size()-1; if((polygon[(size_t)i]-polygon[j]).magnitude()<0.001) polygon.erase(polygon.begin()+i); } bool tryAgain =true; while (tryAgain) tryAgain = eleminateColinearPtsHelper(polygon); } bool linePlaneIntersection(const Vector3D & a, const Vector3D & normal, const Vector3D & p, const IBKMK::Vector3D & d, IBKMK::Vector3D & intersectionPoint, double & dist) { // plane is given by offset 'a' and normal vector 'normal'. // line is given by point 'p' and its line vector 'd' // first the normal test double d_dot_normal = d.scalarProduct(normal); double angle = d_dot_normal/d.magnitude(); // line parallel to plane? no intersection if (angle < 1e-8 && angle > -1e-8) return false; // Condition 1: same direction of normal vectors? if (angle >= 0) return false; // no intersection possible double t = (a - p).scalarProduct(normal) / d_dot_normal; // now determine location on plane IBKMK::Vector3D x0 = p + t*d; intersectionPoint = x0; dist = t; return true; } } // namespace IBKMK
33.349265
130
0.709514
ghorwin
ffff16f67e2c31036540669161cfba4f91fd25a9
1,093
hpp
C++
agency/cuda/detail/concurrency/heterogeneous_barrier.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
129
2016-08-18T23:24:15.000Z
2022-03-25T12:06:05.000Z
agency/cuda/detail/concurrency/heterogeneous_barrier.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
86
2016-08-19T03:43:33.000Z
2020-07-20T14:27:41.000Z
agency/cuda/detail/concurrency/heterogeneous_barrier.hpp
nerikhman/agency
966ac59101f2fc3561a86b11874fbe8de361d0e4
[ "BSD-3-Clause" ]
23
2016-08-18T23:52:13.000Z
2022-02-28T16:28:20.000Z
#include <agency/detail/config.hpp> namespace agency { namespace cuda { namespace detail { template<class HostBarrier, class DeviceBarrier> class heterogeneous_barrier { public: using host_barrier_type = HostBarrier; using device_barrier_type = DeviceBarrier; __agency_exec_check_disable__ __AGENCY_ANNOTATION heterogeneous_barrier(size_t num_threads) : #ifndef __CUDA_ARCH__ host_barrier_(num_threads) #else device_barrier_(num_threads) #endif {} __agency_exec_check_disable__ __AGENCY_ANNOTATION std::size_t count() const { #ifndef __CUDA_ARCH__ return host_barrier_.count(); #else return device_barrier_.count(); #endif } __agency_exec_check_disable__ __AGENCY_ANNOTATION void arrive_and_wait() { #ifndef __CUDA_ARCH__ host_barrier_.arrive_and_wait(); #else device_barrier_.arrive_and_wait(); #endif } private: #ifndef __CUDA_ARCH__ host_barrier_type host_barrier_; #else device_barrier_type device_barrier_; #endif }; } // end detail } // end cuda } // end agency
17.078125
48
0.732845
nerikhman
0800547f1460cf6d60e590ab2d6519d50a0acb5c
7,602
cpp
C++
wallet/api/v6_3/v6_3_api_parse.cpp
unwaz/beam
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
[ "Apache-2.0" ]
null
null
null
wallet/api/v6_3/v6_3_api_parse.cpp
unwaz/beam
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
[ "Apache-2.0" ]
null
null
null
wallet/api/v6_3/v6_3_api_parse.cpp
unwaz/beam
a9aa45dce5dd759f3eb67d7d07ecdc9154aa8db0
[ "Apache-2.0" ]
null
null
null
// Copyright 2018 The Beam Team // // 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 "v6_3_api.h" #include "version.h" namespace beam::wallet { namespace { uint32_t parseTimeout(V63Api& api, const nlohmann::json& params) { if(auto otimeout = api.getOptionalParam<uint32_t>(params, "timeout")) { return *otimeout; } return 0; } bool ExtractPoint(ECC::Point::Native& point, const json& j) { auto s = type_get<NonEmptyString>(j); auto buf = from_hex(s); ECC::Point pt; Deserializer dr; dr.reset(buf); dr& pt; return point.ImportNnz(pt); } } template<> const char* type_name<ECC::Point::Native>() { return "hex encoded elliptic curve point"; } template<> bool type_check<ECC::Point::Native>(const json& j) { ECC::Point::Native pt; return type_check<NonEmptyString>(j) && ExtractPoint(pt, j); } template<> ECC::Point::Native type_get<ECC::Point::Native>(const json& j) { ECC::Point::Native pt; ExtractPoint(pt, j); return pt; } std::pair<IPFSAdd, IWalletApi::MethodInfo> V63Api::onParseIPFSAdd(const JsonRpcId& id, const nlohmann::json& params) { IPFSAdd message; message.timeout = parseTimeout(*this, params); json data = getMandatoryParam<NonEmptyJsonArray>(params, "data"); data.get<std::vector<uint8_t>>().swap(message.data); if (auto opin = getOptionalParam<bool>(params, "pin")) { message.pin = *opin; } return std::make_pair(std::move(message), MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const IPFSAdd::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"hash", res.hash}, {"pinned", res.pinned} } } }; } std::pair<IPFSHash, IWalletApi::MethodInfo> V63Api::onParseIPFSHash(const JsonRpcId& id, const nlohmann::json& params) { IPFSHash message; message.timeout = parseTimeout(*this, params); json data = getMandatoryParam<NonEmptyJsonArray>(params, "data"); data.get<std::vector<uint8_t>>().swap(message.data); return std::make_pair(std::move(message), MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const IPFSHash::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"hash", res.hash} } } }; } std::pair<IPFSGet, IWalletApi::MethodInfo> V63Api::onParseIPFSGet(const JsonRpcId& id, const nlohmann::json& params) { IPFSGet message; message.timeout = parseTimeout(*this, params); message.hash = getMandatoryParam<NonEmptyString>(params, "hash"); return std::make_pair(std::move(message), MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const IPFSGet::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"hash", res.hash}, {"data", res.data} } } }; } std::pair<IPFSPin, IWalletApi::MethodInfo> V63Api::onParseIPFSPin(const JsonRpcId& id, const nlohmann::json& params) { IPFSPin message; message.timeout = parseTimeout(*this, params); message.hash = getMandatoryParam<NonEmptyString>(params, "hash"); return std::make_pair(std::move(message), MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const IPFSPin::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"hash", res.hash} } } }; } std::pair<IPFSUnpin, IWalletApi::MethodInfo> V63Api::onParseIPFSUnpin(const JsonRpcId& id, const nlohmann::json& params) { IPFSUnpin message; message.hash = getMandatoryParam<NonEmptyString>(params, "hash"); return std::make_pair(std::move(message), MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const IPFSUnpin::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"hash", res.hash} } } }; } std::pair<IPFSGc, IWalletApi::MethodInfo> V63Api::onParseIPFSGc(const JsonRpcId& id, const nlohmann::json& params) { IPFSGc message; message.timeout = parseTimeout(*this, params); return std::make_pair(message, MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const IPFSGc::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"result", true} } } }; } std::pair<SignMessage, IWalletApi::MethodInfo> V63Api::onParseSignMessage(const JsonRpcId& id, const nlohmann::json& params) { SignMessage message; message.message = getMandatoryParam<NonEmptyString>(params, "message"); auto km = getMandatoryParam<NonEmptyString>(params, "key_material"); message.keyMaterial = from_hex(km); return std::make_pair(message, MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const SignMessage::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", { {"signature", res.signature} } } }; } std::pair<VerifySignature, IWalletApi::MethodInfo> V63Api::onParseVerifySignature(const JsonRpcId& id, const nlohmann::json& params) { VerifySignature message; message.message = getMandatoryParam<NonEmptyString>(params, "message"); message.publicKey = getMandatoryParam<ECC::Point::Native>(params, "public_key"); message.signature = getMandatoryParam<ValidHexBuffer>(params, "signature"); return std::make_pair(message, MethodInfo()); } void V63Api::getResponse(const JsonRpcId& id, const VerifySignature::Response& res, json& msg) { msg = json { {JsonRpcHeader, JsonRpcVersion}, {"id", id}, {"result", res.result } }; } }
30.408
136
0.549724
unwaz
08015cfc4fb0c74687667d358446a4aa478dd6b8
21,417
hpp
C++
source/utils/ImageCopiers.hpp
bobvodka/GameTextureLoader3
47db5781eb650b9746ffed327786c7e73410cbe0
[ "MIT" ]
null
null
null
source/utils/ImageCopiers.hpp
bobvodka/GameTextureLoader3
47db5781eb650b9746ffed327786c7e73410cbe0
[ "MIT" ]
null
null
null
source/utils/ImageCopiers.hpp
bobvodka/GameTextureLoader3
47db5781eb650b9746ffed327786c7e73410cbe0
[ "MIT" ]
null
null
null
// A series of templated routines to copy image objects between memory buffers #ifndef GTL_IMAGECOPIERS_HPP #define GTL_IMAGECOPIERS_HPP #include <boost/function.hpp> #include <boost/bind.hpp> #include "Utils.hpp" #include "memoryIterators.hpp" //CHECK ALL THE OFFSET MATHS!!! //IT FEELS LIKE BAD BAD VOODOO!!! // namespace GTLImageCopiers { // confirmed to work (or at least not crash) template<class T> void flipImageAndCopy(GTLUtils::flipResult flips, GameTextureLoader3::DecoderImageData const &data, GTLCore::ImageImpl *img, int headeroffset = 0) { using namespace GTLMemoryIterators; typedef typename forward_memory_iter<T> forward_mem_iter; typedef typename reverse_memory_iter<T> reverse_mem_iter; if(flips.flipBoth()) { const int len = img->width_ * img->height_; forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset)); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len); reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + len - 1); std::copy(src,end,dest); } else if (flips.flipy()) { for(int i = 0; i < img->height_; ++i) { // const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8); forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*i); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + (i+1)*img->width_); const int destoffset = img->width_ * img->height_ - ((i+1) * img->width_); // reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset - 1); forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset); std::copy(src,end,dest); } } else if(flips.flipx()) { for (int i = 0; i < img->height_; ++i) { // const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8); forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*i); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + (i+1)*img->width_); const int destoffset = (img->width_ * (i +1)) - 1; reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset); std::copy(src,end,dest); } } else { const int len = img->width_ * img->height_; forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset)); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len); forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get())); std::copy(src,end,dest); } } // confirmed to work (or at least not crash) template<class T> void flipRowAndCopy(GTLUtils::flipResult flips, T * data, GTLCore::ImageImpl *img, int rowcout ) { using namespace GTLMemoryIterators; typedef typename forward_memory_iter<T> forward_mem_iter; typedef typename reverse_memory_iter<T> reverse_mem_iter; forward_mem_iter src(reinterpret_cast<T*>(data)); forward_mem_iter end(reinterpret_cast<T*>(data) + img->width_); if(flips.flipBoth()) { reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + (img->width_ * (img->height_ - rowcout - 1) + (img->width_ - 1) )); std::copy(src,end,dest); } else if (flips.flipy()) // confirmed to work { //forward_mem_iter dest(reinterpret_cast<T*>(data) + (img->width_ * (img->height_ - rowcout - 1))); const int offset = img->width_ * (img->height_ - rowcout) - img->width_; forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + offset); std::copy(src,end,dest); } else if(flips.flipx()) { const int offset = (img->width_ * (rowcout +1)) - 1; reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + offset /*+ (img->width_ * rowcout) + (img->width_ - 1)*/); std::copy(src,end,dest); } else { forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + (img->width_ * rowcout)); std::copy(src,end,dest); } } // confirmed to work (or at least not crash) template<class T> void flipImageAndTransform(GTLUtils::flipResult flips, GameTextureLoader3::DecoderImageData const &data, GTLCore::ImageImpl *img, boost::function<T (T const &)> func, int headeroffset = 0) { using namespace GTLMemoryIterators; typedef typename forward_memory_iter<T> forward_mem_iter; typedef typename reverse_memory_iter<T> reverse_mem_iter; if(flips.flipBoth()) { const int len = img->width_ * img->height_; forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset)); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len); reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + len - 1); std::transform(src,end,dest,func); } else if (flips.flipy()) { for(int i = 0; i < img->height_; ++i) { // const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8); forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*i); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + img->width_*(i+1)); const int destoffset = img->width_ * img->height_ - ((i+1) * img->width_); forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset); std::transform(src,end,dest,func); } } else if(flips.flipx()) { for (int i = 0; i < img->height_; ++i) { // const int offset = headeroffset + (img->width_ * i * img->colourdepth_/8); forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset) + i*img->width_); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + (i+1)*img->width_); // const int destoffset = (img->width_ * i) + (img->width_ - 1); const int destoffset = (img->width_ * (i +1)) - 1; reverse_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get()) + destoffset); std::transform(src,end,dest,func); } } else { const int len = img->width_ * img->height_; forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset)); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset) + len); forward_mem_iter dest(reinterpret_cast<T*>(img->imgdata_.get())); std::transform(src,end,dest,func); } } // DXTn Copying routines template<class T> T fullFlipLookup(T src, T srcmask) { T dest = 0; const int offset = (sizeof(T) * 8) - (2 * (sizeof(T)/4)); // for 32bit = 30, 64bit = 60 const int shiftamount = 2 * sizeof(T)/4; // for 32bit = 2, 64bit = 4 for (int i = 0; i < 16; i++) { int tmpshift = offset - (i * shiftamount); T tmpdata = src & srcmask; // shift to start of bit pattern tmpdata = tmpdata >> (offset - tmpshift); // then shift it to the correct location T shiftdata = tmpdata << tmpshift; dest |= shiftdata; srcmask = srcmask << shiftamount; } return dest; } template<class T> T yFlipLookup(T src, T srcmask) { T dest = 0; // const int offset = (sizeof(T) * 8) - (2 * (sizeof(T)/4)); // for 32bit = 30, 64bit = 60 const int offset = (sizeof(T) * 8) - (2 * (sizeof(T))); // for 32bit = 24, 64bit = 48 const int shiftamount = 2 * sizeof(T)/4; // for 32bit = 2, 64bit = 4 const int incamount = sizeof(T); // for 32bit = 4, 64bit = 8 // for(int i = 0; i < 16; i+= incamount) for(int i = 0; i < 16; i+= 4) // always moving 4 pixels at a time { int tmpshift = offset - i*shiftamount; T tmpdata = src & srcmask; //tmpdata = tmpdata >> (offset - tmpshift); int tmpamount = i*shiftamount; tmpdata = tmpdata >> tmpamount; T shiftdata = tmpdata << tmpshift; dest |= shiftdata; srcmask = srcmask << (incamount*2); } return dest; } template<class T> T xFlipLookup(T src, T /*original*/srcmask) { T dest = 0; const int xoffset = (sizeof(T)/4) * 6; // for 32bit = 6, 64bit = 12 const int yoffset = (sizeof(T)*2); // for 32bit = 8, 64bit = 16 const int shiftamount = 2 * sizeof(T)/4; // for 32bit = 2, 64bit = 4 // const int incamount = (sizeof(T)/8) * 4; // for 32bit = 4, 64bit = 8 for (int i = 0; i < 4; i++) { // We don't need to move the mask as we move the src data! //T srcmask = (originalsrcmask << (incamount*i*shiftamount)); for (int j = 0; j < 4; j++) { T srcbits = src & srcmask; T xshift = xoffset - j*shiftamount; T yshift = yoffset*i; T totalshift = xshift + yshift; // dest |= (srcbits << ((xoffset - j*shiftamount) + (yoffset*i))); T tmpdata = srcbits << totalshift; dest |= tmpdata; src = src >> shiftamount; } } return dest; } GTLUtils::dxt1 fullFlip(GTLUtils::dxt1 &src); GTLUtils::dxt1 xFlip(GTLUtils::dxt1 &src); GTLUtils::dxt1 yFlip(GTLUtils::dxt1 &src); GTLUtils::dxt2 fullFlip(GTLUtils::dxt2 &src); GTLUtils::dxt2 xFlip(GTLUtils::dxt2 &src); GTLUtils::dxt2 yFlip(GTLUtils::dxt2 &src); GTLUtils::dxt4 fullFlip(GTLUtils::dxt4 &src); GTLUtils::dxt4 xFlip(GTLUtils::dxt4 &src); GTLUtils::dxt4 yFlip(GTLUtils::dxt4 &src); // We need to do the flips for each images and mipmap in the chain // 3D textures might have to be ignored until I can think of some sane way to handle it template<class T> void flipDXTnImage(GTLUtils::flipResult flips, GameTextureLoader3::DecoderImageData const &data, GTLCore::ImageImpl *img, int headeroffset = 0) { using namespace GTLMemoryIterators; typedef typename forward_memory_iter<T> forward_mem_iter; typedef typename reverse_memory_iter<T> reverse_mem_iter; int realheight = (img->height_ < 16) ? img->height_ : img->height_/4; int realwidth = (img->width_ < 16) ? img->width_ : img->width_/4; const int numImages = img->getNumImages(); const int numMipMaps = img->getNumMipMaps(); const unsigned char* baseptr = img->getDataPtr(); for (int image = 0; image < numImages; ++image) { for (int mipmap = 0; mipmap < numMipMaps; ++mipmap) { int currentWidth = realwidth >> mipmap; if (currentWidth < 16) currentWidth = 16; int currentHeight = realheight >> mipmap; if (currentHeight < 16) currentHeight = 16; const ptrdiff_t offset = img->getDataPtr(mipmap,image) - baseptr; // get an offset in bytes to the correct image:mipmap data if(flips.flipBoth()) { const int len = currentHeight * currentWidth; forward_mem_iter src(reinterpret_cast<T*>(data.get() + headeroffset + offset)); forward_mem_iter end(reinterpret_cast<T*>(data.get() + headeroffset + offset) + len); reverse_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)) + len - 1); std::transform(src,end,dest,boost::bind<T>(fullFlip, _1)); // std::transform(src,end,dest,fullFlip); }// TODO: redo the below two functions to take into account the fact we are working with blocks of 16 pixels at a time else if (flips.flipy()) { for(int i = 0; i < currentHeight; ++i) { forward_mem_iter src(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*i); forward_mem_iter end(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*(i+1)); const int destoffset = currentWidth * currentHeight - ((i+1) * currentWidth); forward_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)) + destoffset); std::transform(src,end,dest,boost::bind<T>(yFlip, _1)); //std::transform(src,end,dest,yFlip); } } else if(flips.flipx()) { for (int i = 0; i < currentHeight; ++i) { forward_mem_iter src(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*i); forward_mem_iter end(reinterpret_cast<T*>(data.get()+headeroffset + offset) + currentWidth*(i+1)); const int destoffset = /*currentWidth*currentHeight -*/ ((i+1)*currentWidth) - 1; reverse_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image)) + destoffset); std::transform(src,end,dest,boost::bind<T>(xFlip, _1)); //std::transform(src,end,dest,xFlip); } } else { const int len = currentWidth * currentHeight; forward_mem_iter src(reinterpret_cast<T*>(data.get()+headeroffset + offset)); forward_mem_iter end(reinterpret_cast<T*>(data.get()+headeroffset + offset) + len); forward_mem_iter dest(reinterpret_cast<T*>(img->getDataPtr(mipmap,image))); //std::transform(src,end,dest,func); std::copy(src,end,dest); } } } } // TGA copying routines template<class T, class U> void PerformCopy(T src, T srcend, U dest) { std::copy(src,srcend, dest); } template<class T, class U> void PerformRepeatedCopy(T src, U dest, int count) { std::fill_n(dest,count,*src); } template<class U> void PerformCopy(GTLMemoryIterators::forward_memory_iter<GTLUtils::rgba> src, GTLMemoryIterators::forward_memory_iter<GTLUtils::rgba> srcend, U dest) { std::transform(src,srcend, dest, GTLUtils::convertBGRAtoRGBA); } template<class U> void PerformRepeatedCopy(GTLMemoryIterators::forward_memory_iter<GTLUtils::rgba> src, U dest, int count) { GTLUtils::rgba val = GTLUtils::convertBGRAtoRGBA(*src); std::fill_n(dest,count,val); } template<class T> void CopyData(T * src, T* dest, int width, int height, int count, int offset, GTLUtils::flipResult flips, bool repeated) { using namespace GTLMemoryIterators; typedef typename forward_memory_iter<T> forward_mem_iter; typedef typename reverse_memory_iter<T> reverse_mem_iter; if(flips.flipBoth()) { const int imgsize = width * height; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + count); reverse_mem_iter dest_itor(dest + imgsize - offset - 1); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,count); else PerformCopy(src_itor,end_itor,dest_itor); } else if (flips.flipy()) { const int imgsize = width * height; while (count > 0) { int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...) int rowRemains = width - (offset % width); int copyAmount = (count > rowRemains) ? rowRemains : count; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + copyAmount); forward_mem_iter dest_itor(dest + imgsize - ((row + 1) * width) + (width - rowRemains)); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,copyAmount); else PerformCopy(src_itor,end_itor,dest_itor); count -= copyAmount; offset += copyAmount; src += copyAmount; } } else if(flips.flipx()) { // const int imgsize = width * height; while (count > 0) { int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...) int rowRemains = width - (offset % width); int copyAmount = (count > rowRemains) ? rowRemains : count; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + copyAmount); int rowoffset = ((row+1) * width) - (width - rowRemains) - 1; reverse_mem_iter dest_itor(dest + rowoffset ); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,copyAmount); else PerformCopy(src_itor,end_itor,dest_itor); count -= copyAmount; offset += copyAmount; src += copyAmount; } } else { forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + count); forward_mem_iter dest_itor(dest + offset); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,count); else PerformCopy(src_itor,end_itor,dest_itor); } /* if(flips.flipBoth()) { const int imgsize = width * height; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + count); reverse_mem_iter dest_itor(dest + imgsize - offset); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,count); else PerformNormalCopy(src_itor,end_itor,dest_itor); } else if (flips.flipy()) { const int imgsize = width * height; while (count > 0) { int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...) int rowRemains = width - (offset % width); int copyAmount = (count > rowRemains) ? rowRemains : count; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + copyAmount); forward_mem_iter dest_itor(dest + imgsize - (row * width)); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,copyAmount); else PerformNormalCopy(src_itor,end_itor,dest_itor); count -= copyAmount; offset += copyAmount; } } else if(flips.flipx()) { const int imgsize = width * height; while (count > 0) { int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...) int rowRemains = width - (offset % width); int copyAmount = (count > rowRemains) ? rowRemains : count; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + copyAmount); reverse_mem_iter dest_itor(dest + imgsize - (row * width) - (width - rowRemains)); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,copyAmount); else PerformNormalCopy(src_itor,end_itor,dest_itor); count -= copyAmount; offset += copyAmount; } } else { forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + count); forward_mem_iter dest_itor(dest); if (repeated) PerformRepeatedCopy(src_itor,dest_itor,count); else PerformNormalCopy(src_itor,end_itor,dest_itor); } */ } /* template<class T, class U> void PerformTransformedCopy(T src, T srcend, U dest) { std::transform(src,srcend, dest, GTLUtils::convertBGRAtoRGBA); } template<class T, class U> void PerformTransformedRepeatedCopy(T src, U dest, int count) { GTLUtils::rgba val = GTLUtils::convertBGRAtoRGBA(*src); std::fill_n(dest,count,val); } template<> void CopyData(GTLUtils::rgba * src, GTLUtils::rgba* dest, int width, int height, int count, int offset, GTLUtils::flipResult flips, bool repeated); */ /* { using namespace GTLMemoryIterators; typedef forward_memory_iter<GTLUtils::rgba> forward_mem_iter; typedef reverse_memory_iter<GTLUtils::rgba> reverse_mem_iter; if(flips.flipBoth()) { const int imgsize = width * height; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + count); reverse_mem_iter dest_itor(dest + imgsize - offset); if (repeated) PerformTransformedRepeatedCopy(src_itor,dest_itor,count); else PerformTransformedCopy(src_itor,end_itor,dest_itor); } else if (flips.flipy()) { const int imgsize = width * height; while (count > 0) { int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...) int rowRemains = width - (offset % width); int copyAmount = (count > rowRemains) ? rowRemains : count; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + copyAmount); forward_mem_iter dest_itor(dest + imgsize - (row * width)); if (repeated) PerformTransformedRepeatedCopy(src_itor,dest_itor,copyAmount); else PerformTransformedCopy(src_itor,end_itor,dest_itor); count -= copyAmount; offset += copyAmount; } } else if(flips.flipx()) { const int imgsize = width * height; while (count > 0) { int row = offset / width; // get the row we are on i.e. 12 / 10 = row 1 (check interger divsion...) int rowRemains = width - (offset % width); int copyAmount = (count > rowRemains) ? rowRemains : count; forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + copyAmount); reverse_mem_iter dest_itor(dest + imgsize - (row * width) - (width - rowRemains)); if (repeated) PerformTransformedRepeatedCopy(src_itor,dest_itor,copyAmount); else PerformTransformedCopy(src_itor,end_itor,dest_itor); count -= copyAmount; offset += copyAmount; } } else { forward_mem_iter src_itor(src); forward_mem_iter end_itor(src + count); forward_mem_iter dest_itor(dest); if (repeated) PerformTransformedRepeatedCopy(src_itor,dest_itor,count); else PerformTransformedCopy(src_itor,end_itor,dest_itor); } } */ template<class T> bool decodeRLEData(GameTextureLoader3::ImagePtr image, GameTextureLoader3::DecoderImageData data, GTLUtils::flipResult flips, int offset) { GTLCore::ImageImpl * img = dynamic_cast<GTLCore::ImageImpl*>(image.get()); const int pixelsize = img->colourdepth_/8; const int size = img->width_ * img->height_ * pixelsize; const bool repeated = true; signed int currentbyte = 0; GTLUtils::byte * bytedata = reinterpret_cast<GTLUtils::byte*>(data.get() + offset); T * localimg = reinterpret_cast<T*>(img->imgdata_.get()); while(currentbyte < size ) { GTLUtils::byte chunkheader = *bytedata; bytedata++; // I'm pretty sure the line below here is wrong and shouldn't be there... // ++currentbyte; T * localdata = reinterpret_cast<T*>(bytedata); if(chunkheader < 128) // Then the next chunkheader++ blocks of data are unique pixels { chunkheader++; CopyData(localdata, localimg, img->width_, img->height_, chunkheader,(currentbyte/pixelsize),flips,!repeated); bytedata += chunkheader * pixelsize; } else // RLE compressed data, chunkheader -127 gives us the total number of repeats { chunkheader -= 127; CopyData(localdata,localimg, img->width_, img->height_, chunkheader,(currentbyte/pixelsize),flips,repeated); bytedata+=pixelsize; // move on the size of a pixel } currentbyte += pixelsize * chunkheader; } return true; } } #endif
33.780757
150
0.673344
bobvodka
0801e69aabfd892b207c36f3d04c8b5c070f3df5
280
cpp
C++
lib/AST/Break.cpp
yangzh1998/purpo
87cdf981580fa25f5b7062e5fd90c920c49ff116
[ "MIT" ]
4
2021-11-25T14:26:39.000Z
2021-11-25T19:22:38.000Z
lib/AST/Break.cpp
yangzh1998/purpo
87cdf981580fa25f5b7062e5fd90c920c49ff116
[ "MIT" ]
null
null
null
lib/AST/Break.cpp
yangzh1998/purpo
87cdf981580fa25f5b7062e5fd90c920c49ff116
[ "MIT" ]
null
null
null
// // Created by YANG Zehai on 2021/11/11. // #include "AST/Break.h" using namespace pur; using namespace pur::ast; Break::Break(const pars::Location& loc): Stmt(ASTNodeType::kBreak, loc) { /* empty */ } void Break::Accept(Visitor& visitor) { visitor.VisitBreak(*this); }
16.470588
73
0.678571
yangzh1998
0803804b40f4c17f08a295bce2e3497e4ed0407b
5,577
cpp
C++
src/tests/conduit/t_conduit_node_update.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
120
2015-12-09T00:58:22.000Z
2022-03-25T00:14:39.000Z
src/tests/conduit/t_conduit_node_update.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
808
2016-02-27T22:25:15.000Z
2022-03-30T23:42:12.000Z
src/tests/conduit/t_conduit_node_update.cpp
adrienbernede/conduit
38379643d570941164b4fad76e269d2862f0e47b
[ "BSD-3-Clause" ]
49
2016-02-12T17:19:16.000Z
2022-02-01T14:36:21.000Z
// Copyright (c) Lawrence Livermore National Security, LLC and other Conduit // Project developers. See top-level LICENSE AND COPYRIGHT files for dates and // other details. No copyright assignment is required to contribute to Conduit. //----------------------------------------------------------------------------- /// /// file: conduit_node_update.cpp /// //----------------------------------------------------------------------------- #include "conduit.hpp" #include <iostream> #include "gtest/gtest.h" #include "rapidjson/document.h" using namespace conduit; //----------------------------------------------------------------------------- TEST(conduit_node_update, update_simple) { uint32 a_val = 10; uint32 b_val = 20; float64 c_val = 30.0; Node n; n["a"] = a_val; n["b"] = b_val; n["c"] = c_val; Node n2; n2["a"] = a_val + 10; n2["d/aa"] = a_val; n2["d/bb"] = b_val; n.update(n2); EXPECT_EQ(n["a"].as_uint32(),a_val+10); EXPECT_EQ(n["b"].as_uint32(),b_val); EXPECT_EQ(n["c"].as_float64(),c_val); EXPECT_EQ(n["d/aa"].as_uint32(),a_val); EXPECT_EQ(n["d/bb"].as_uint32(),b_val); } //----------------------------------------------------------------------------- TEST(conduit_node_update, update_with_list) { uint32 a_val = 10; uint32 b_val = 20; float64 c_val = 30.0; float32 d_val = 40.0; float64 c_val_double = 60.0; Node n1; n1.append().set(a_val); n1.append().set(b_val); n1.append().set_external(&c_val); Node n2; n2.append().set(a_val*2); n2.append().set(b_val*2); n2.append().set(c_val*2); n2.append().set(d_val); n1.update(n2); EXPECT_EQ(n1[0].as_uint32(),a_val*2); EXPECT_EQ(n1[1].as_uint32(),b_val*2); EXPECT_EQ(n1[2].as_float64(),c_val_double); EXPECT_EQ(n1[3].as_float32(),d_val); // we did something tricky with set external for c_val, see if it worked. EXPECT_NEAR(c_val,c_val_double,0.001); } //----------------------------------------------------------------------------- TEST(conduit_node_update, update_realloc_like) { std::vector<uint32> vals; for(index_t i=0;i<10;i++) { vals.push_back(i); } Node n; n["a"].set(vals); n["b"] = "test"; n.print(); Node n2; n2["a"].set(DataType::uint32(15)); // zero out the buffer just to be safe for this unit test memset(n2["a"].data_ptr(),0,sizeof(uint32)*15); n2.update(n); n2.print(); uint32 *n_v_ptr = n["a"].as_uint32_ptr(); uint32 *n2_v_ptr = n2["a"].as_uint32_ptr(); for(index_t i=0;i<10;i++) { EXPECT_EQ(n_v_ptr[i],n2_v_ptr[i]); } for(index_t i=10;i<15;i++) { EXPECT_EQ(n2_v_ptr[i],0); // assumes zeroed-alloc } EXPECT_TRUE(n2.has_path("b")); } //----------------------------------------------------------------------------- TEST(conduit_node_update, update_compatible_realloc_like) { std::vector<uint32> vals; for(index_t i=0;i<10;i++) { vals.push_back(i); } Node n; n["a"].set(vals); n["b"] = "test"; Node n2; n2["a"].set(DataType::uint32(15)); // zero out the buffer just to be safe for this unit test memset(n2["a"].data_ptr(),0,sizeof(uint32)*15); uint32 *n2_v_ptr_pre_update = n2["a"].as_uint32_ptr(); n2.update_compatible(n); uint32 *n_v_ptr = n["a"].as_uint32_ptr(); uint32 *n2_v_ptr = n2["a"].as_uint32_ptr(); // there should not be an alloc, so the n2 ptr should be the same EXPECT_EQ(n2_v_ptr_pre_update,n2_v_ptr); for(index_t i=0;i<10;i++) { EXPECT_EQ(n_v_ptr[i],n2_v_ptr[i]); } for(index_t i=10;i<15;i++) { EXPECT_EQ(n2_v_ptr[i],0); // assumes zeroed-alloc } EXPECT_FALSE(n2.has_path("b")); } //----------------------------------------------------------------------------- TEST(conduit_node_update, update_compatible) { std::vector<uint32> vals; for(index_t i=0;i<5;i++) { vals.push_back(i); } Node n; n["a"].set(vals); n["b"] = "test"; Node n2; n2["a"].set(DataType::uint32(5)); // zero out the buffer just to be safe for this unit test memset(n2["a"].data_ptr(),0,sizeof(uint32)*5); uint32 *n2_v_ptr_pre_update = n2["a"].as_uint32_ptr(); n2.update_compatible(n); uint32 *n_v_ptr = n["a"].as_uint32_ptr(); uint32 *n2_v_ptr = n2["a"].as_uint32_ptr(); // there should not be an alloc, so the n2 ptr should be the same EXPECT_EQ(n2_v_ptr_pre_update,n2_v_ptr); for(index_t i=0;i<5;i++) { EXPECT_EQ(n_v_ptr[i],n2_v_ptr[i]); } EXPECT_FALSE(n2.has_path("b")); } //----------------------------------------------------------------------------- TEST(conduit_node_update, update_external) { std::vector<uint32> vals; for(index_t i=0;i<5;i++) { vals.push_back(i); } Node n; n["a"].set_external(vals); n["b"].set_int64(-100); n.print(); Node n2; n2["c"].set_int16(-127); n2.update_external(n); n2.print(); uint32 *n_v_ptr = n2["a"].value(); for(index_t i=0;i<5;i++) { EXPECT_EQ(&n_v_ptr[i],&vals[i]); EXPECT_EQ(n_v_ptr[i],i); } int64 *n_b_ptr = n["b"].value(); int64 *n2_b_ptr = n2["b"].value(); EXPECT_EQ(n_b_ptr,n2_b_ptr); EXPECT_EQ(n2_b_ptr[0],-100); EXPECT_EQ(n2["c"].as_int16(),-127); }
22.950617
79
0.511027
adrienbernede
0806dfd15fb0d6a556746c8cf7be22daca89549b
3,965
cc
C++
reading-notes/PythonCore/pysmall/main.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
22
2015-05-18T07:04:36.000Z
2021-08-02T03:01:43.000Z
reading-notes/PythonCore/pysmall/main.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
1
2017-08-31T22:13:57.000Z
2017-09-05T15:00:25.000Z
reading-notes/PythonCore/pysmall/main.cc
ASMlover/study
5878f862573061f94c5776a351e30270dfd9966a
[ "BSD-2-Clause" ]
6
2015-06-06T07:16:12.000Z
2021-07-06T13:45:56.000Z
// Copyright (c) 2018 ASMlover. 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 ofconditions 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 materialsprovided 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. #include <cctype> #include <iostream> #include <memory> #include <string> #include "pysmall_object.h" #include "pysmall_intobject.h" #include "pysmall_strobject.h" #include "pysmall_dictobject.h" static std::unique_ptr<pysmall::DictObject> g_ENV(new pysmall::DictObject()); static bool __isdigit(const std::string& s) { for (auto c : s) { if (!std::isdigit(c)) return false; } return true; } static pysmall::Object* symbol_as_object(const std::string& symbol) { auto* key = new pysmall::StrObject(symbol.c_str()); auto* val = g_ENV->getitem(key); if (val == nullptr) std::cerr << "[ERROR]: " << symbol << " is not defined!!!" << std::endl; return val; } static void pysmall_exec_print(const std::string& symbol) { auto* x = symbol_as_object(symbol); if (x != nullptr) x->type->print_fn(x); } static void pysmall_exec_add(const std::string& t, const std::string& s) { if (__isdigit(s)) { auto* val = new pysmall::IntObject(std::atoi(s.c_str())); auto* key = new pysmall::StrObject(t.c_str()); g_ENV->setitem(key, val); } else if (s.find("\"") != std::string::npos) { auto* val = new pysmall::StrObject(s.substr(1, s.size() - 2).c_str()); auto* key = new pysmall::StrObject(t.c_str()); g_ENV->setitem(key, val); } else if (auto pos = s.find(" + "); pos != std::string::npos) { auto* lobj = symbol_as_object(s.substr(0, pos)); auto* robj = symbol_as_object(s.substr(pos + 3)); if (lobj != nullptr && robj != nullptr && lobj->type == robj->type) { auto* val = lobj->type->plus_fn(lobj, robj); auto* key = new pysmall::StrObject(t.c_str()); g_ENV->setitem(key, val); } g_ENV->type->print_fn(g_ENV.get()); } } static void pysmall_exec_command(const std::string& s) { std::size_t pos{}; if ((pos = s.find("print ")) != std::string::npos) { pysmall_exec_print(s.substr(6)); } else if ((pos = s.find(" = ")) != std::string::npos) { auto x = s.substr(0, pos); auto y = s.substr(pos + 3); pysmall_exec_add(x, y); } } static void pysmall_exec(void) { static const char* info = "********* pysmall research *********"; static const char* prompt = ">>> "; std::string s; std::cout << info << std::endl; std::cout << prompt; while (std::getline(std::cin, s)) { if (s.empty()) { std::cout << prompt; continue; } else if (s == "exit") { break; } else { pysmall_exec_command(s); } std::cout << prompt; } } int main(int argc, char* argv[]) { (void)argc, (void)argv; pysmall_exec(); return 0; }
31.72
77
0.657503
ASMlover
080ab7fa5adf4750d4a44aa398d617ffea615351
2,605
cc
C++
tests/test.cc
sv1990/automatic-differentiation
b2eb0685c0bb31086a57957464641965a5b6ae0c
[ "MIT" ]
null
null
null
tests/test.cc
sv1990/automatic-differentiation
b2eb0685c0bb31086a57957464641965a5b6ae0c
[ "MIT" ]
null
null
null
tests/test.cc
sv1990/automatic-differentiation
b2eb0685c0bb31086a57957464641965a5b6ae0c
[ "MIT" ]
null
null
null
#include "ad/ad.hh" #include "ad/ostream.hh" #include <cassert> #undef NDEBUG template <typename T, typename U> constexpr bool same_type(T, U) noexcept { return std::is_same_v<T, U>; } template <typename T> constexpr bool is_static_expression(T) { return ad::detail::is_static_v<T>; } int main() { using namespace ad::literals; constexpr auto x = ad::_0; constexpr auto y = ad::_1; static_assert(same_type(123_c, ad::static_constant<123>{})); static_assert(same_type(x.derive(x), 1_c)); static_assert(same_type(x.derive(y), 0_c)); static_assert(same_type(y.derive(x), 0_c)); static_assert(same_type(y.derive(y), 1_c)); static_assert(same_type(x.derive(x, x), 0_c)); static_assert(same_type((x * y).derive(x, y), 1_c)); static_assert(same_type(ad::log(x).derive(x), 1_c / x)); static_assert(same_type(ad::exp(x).derive(x), ad::exp(x))); static_assert(same_type(ad::sin(x).derive(x), ad::cos(x))); static_assert(same_type(ad::sin(x).derive(x, x), -ad::sin(x))); static_assert(same_type(ad::sin(x).derive(x, x, x), -ad::cos(x))); static_assert(same_type(ad::sin(x).derive(x, x, x, x), ad::sin(x))); static_assert(same_type(ad::exp(ad::sin(x)).derive(x), ad::cos(x) * ad::exp(ad::sin(x)))); static_assert(same_type((ad::exp(x) * ad::sin(x)).derive(x), ad::exp(x) * ad::sin(x) + ad::exp(x) * ad::cos(x))); static_assert(same_type(-(-x * 1_c), x)); static_assert(same_type(-0_c, 0_c)); static_assert(same_type(ad::pow(1_c / x, -1_c), x)); static_assert(same_type(ad::exp(1_c) * ad::exp(x), ad::exp(1_c + x))); static_assert(same_type(ad::pow(ad::exp(x), 2_c), ad::exp(x * 2_c))); static_assert(same_type(ad::pow(ad::pow(x, 2_c), 2_c), ad::pow(x, 4_c))); #if __has_attribute(no_unique_address) static_assert(sizeof(ad::exp(x)) == 1); static_assert(sizeof(x + 1_c) == 1); static_assert(sizeof((x + 1_c) * (x - 1_c)) <= 2); #endif assert(ad::to_string(1_c / (x * ad::exp(x))) == "1 / (x0 * exp(x0))"); assert(ad::to_string(1_c - (x + 1_c)) == "1 - (x0 + 1)"); assert(ad::to_string(1_c + (x + 1_c)) == "1 + x0 + 1"); assert(ad::to_string(2_c * (x * 2_c)) == "2 * x0 * 2"); assert(ad::to_string(-ad::exp(x)) == "-exp(x0)"); assert(ad::to_string(-(x + 2)) == "-(x0 + 2)"); assert(ad::to_string(-(x - 2)) == "-(x0 - 2)"); static_assert(is_static_expression(x)); static_assert(is_static_expression(x + 1_c)); static_assert(!is_static_expression(x + 1)); static_assert(same_type(ad::sin(x) - ad::sin(x), 0_c)); static_assert(same_type(ad::sin(x) / ad::sin(x), 1_c)); }
34.733333
78
0.619578
sv1990
080d328b2ae90baa12db3ff3a8778a02da56280c
133
cpp
C++
recursive/tests/failing_test.cpp
PhilipDaniels/autotools-template
e11ee788c7ca9f9b941778330cac4e562b23d8fe
[ "MIT" ]
20
2016-02-01T13:07:45.000Z
2020-08-30T18:59:39.000Z
recursive/tests/failing_test.cpp
PhilipDaniels/autotools-template
e11ee788c7ca9f9b941778330cac4e562b23d8fe
[ "MIT" ]
null
null
null
recursive/tests/failing_test.cpp
PhilipDaniels/autotools-template
e11ee788c7ca9f9b941778330cac4e562b23d8fe
[ "MIT" ]
4
2018-05-13T19:05:28.000Z
2021-12-29T18:08:46.000Z
#define CATCH_CONFIG_MAIN #include "mycatch.hpp" #include "foo.hpp" TEST_CASE("Testing works", "[works]") { REQUIRE(2 > 3); }
12.090909
37
0.661654
PhilipDaniels
080e32a0c1261e77869375530610f956681a9dda
2,283
cpp
C++
gym/101190/E.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
1
2021-07-16T19:59:39.000Z
2021-07-16T19:59:39.000Z
gym/101190/E.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
gym/101190/E.cpp
albexl/codeforces-gym-submissions
2a51905c50fcf5d7f417af81c4c49ca5217d0753
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; #ifdef DGC #include "debug.h" #else #define debug(...) #endif typedef long long ll; typedef long double ld; typedef complex<ll> point; #define F first #define S second struct info { ll a, b; }; int main() { #ifdef DGC freopen("a.txt", "r", stdin); //freopen("b.txt", "w", stdout); #endif ios_base::sync_with_stdio(0), cin.tie(0); freopen("expect.in", "r", stdin); freopen("expect.out", "w", stdout); int n, q; cin >> n >> q; vector<info> a(n); char ch; for (auto &i : a) { cin >> ch >> i.a >> i.b; if (ch == '+') i.b *= -1; } vector<ll> sb(n); // sum of b vector<pair<ll, int>> vp; // val, pos for (int i = 0; i < n; ++i) { sb[i] = a[i].b; if (i > 0) sb[i] += sb[i-1]; if (sb[i] > 0 && (vp.empty() || sb[i] > vp.back().F)) vp.push_back({ sb[i], i }); } vector<ll> difa(n); // a[i+1]-a[i] for (int i = n-2; i >= 0; --i) difa[i] = a[i+1].a - a[i].a; vector<pair<ll, int>> z(q); for (auto &i : z) cin >> i.F, i.S = &i-&z[0]; sort(z.begin(), z.end()); vector<ll> ans(q, -2); vector<ll> sump(q); // sum on prefix vector<ll> sum2p(q); // sum2 on prefix //vector<ll> sum3p(q); // sum3 on prefix vector<ll> coef(q, 1LL); for (int i = q-2; i >= 0; --i) coef[i] = coef[i+1] + z[i+1].F-z[i].F; debug(coef) for (int i = 0; i < n-1; ++i) { ll x = sb[i]; auto it = lower_bound(z.begin(), z.end(), make_pair(x, 0)); if (it != z.begin()) { int pos = prev(it) - z.begin(); ll init = -z[pos].F + x; //sum3p[pos] += difa[i] * (init - 1); sum2p[pos] += difa[i]; sump[pos] += difa[i] * (init - 1); sump[pos] -= (coef[pos] - 1) * difa[i]; } } debug(sum2p) debug(sump) for (int i = q-2; i >= 0; --i) { sum2p[i] += sum2p[i+1]; sump[i] += sump[i+1]; } debug(vp) for (auto &temp : z) { ll init = -temp.F; int pos = temp.S; int pos2 = &temp-&z[0]; if (sb[n-1] + init > 0) { ans[pos] = -1; continue; } /*auto it = lower_bound(vp.begin(), vp.end(), make_pair(-init, 1<<30)); if (it == vp.end()) { ans[pos] = 0; continue; }*/ ans[pos] = sum2p[pos2] * coef[pos2] + sump[pos2]; debug(temp, ans[pos]) } for (auto i : ans) { if (i == -1) cout << "INFINITY\n"; else cout << i << "\n"; } return 0; }
17.037313
73
0.505475
albexl
080ef9b7d80aaaad57c68515a6eeeef80697a3cb
545
cpp
C++
algorithm/kmp.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
algorithm/kmp.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
algorithm/kmp.cpp
freedomDR/coding
310a68077de93ef445ccd2929e90ba9c22a9b8eb
[ "MIT" ]
null
null
null
#include<iostream> #include<vector> #include<string> using namespace std; string s1, s2; void kmp() { string new_s = s2+"#"+s1; vector<int> prefix_func(new_s.size()); for(int i = 1; i < new_s.size(); i++) { int j = prefix_func[i-1]; while(j>0&&new_s[j]!=new_s[i]) j=prefix_func[j-1]; if(new_s[i]==new_s[j]) j++; prefix_func[i] = j; } cout << new_s << endl; for(auto v:prefix_func) cout << v << " "; cout << endl; } int main() { cin >> s1 >> s2; kmp(); return 0; }
18.166667
58
0.522936
freedomDR
0812f9fe0d02c6d8e4cfe9bb47c354b503f81d57
1,294
cpp
C++
uva.onlinejudge.org/TheTwinTowers.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
6
2016-09-10T03:16:34.000Z
2020-04-07T14:45:32.000Z
uva.onlinejudge.org/TheTwinTowers.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
null
null
null
uva.onlinejudge.org/TheTwinTowers.cpp
facug91/OJ-Solutions
9aa55be066ce5596e4e64737c28cd3ff84e092fe
[ "Apache-2.0" ]
2
2018-08-11T20:55:35.000Z
2020-01-15T23:23:11.000Z
/* By: facug91 From: http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1007 Name: The Twin Towers Number: 10066 Date: 22/08/2014 */ #include <bits/stdc++.h> #define MAX_INT 2147483647 #define MAX_LONG 9223372036854775807ll #define MAX_ULONG 18446744073709551615ull #define MAX_DBL 1.7976931348623158e+308 #define EPS 1e-9 const double PI = 2.0*acos(0.0); #define INF 1000000000 //#define MOD 1000000007 using namespace std; typedef long long ll; typedef pair<int, int> ii; typedef pair<int, pair<int, int> > iii; int n1, n2, seq1[105], seq2[105], LCS[105][105]; int lcs () { int i, j; for (i=0; i<=n1; i++) LCS[i][0] = 0; for (j=0; j<=n2; j++) LCS[0][j] = 0; for (i=1; i<=n1; i++) { for (j=1; j<=n2; j++) { if (seq1[i] == seq2[j]) LCS[i][j] = LCS[i-1][j-1] + 1; else LCS[i][j] = max(LCS[i-1][j], LCS[i][j-1]); } } return LCS[n1][n2]; } int main () { ios_base::sync_with_stdio(0); int TC = 1, i, j; while (scanf("%d %d", &n1, &n2), n1 || n2) { for (i=1; i<=n1; i++) scanf("%d", &seq1[i]); for (j=1; j<=n2; j++) scanf("%d", &seq2[j]); printf("Twin Towers #%d\nNumber of Tiles : %d\n\n", TC++, lcs()); } return 0; }
23.962963
114
0.564142
facug91
081396bdef5c61cb3eccd6f19a0c2fe9e838fed5
8,925
cpp
C++
test/omp/test_omp_external_distance_interaction.cpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
null
null
null
test/omp/test_omp_external_distance_interaction.cpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
2
2020-04-07T11:41:45.000Z
2020-04-08T10:01:38.000Z
test/omp/test_omp_external_distance_interaction.cpp
yutakasi634/Mjolnir
ab7a29a47f994111e8b889311c44487463f02116
[ "MIT" ]
null
null
null
#define BOOST_TEST_MODULE "test_omp_external_distance_interaction" #ifdef BOOST_TEST_DYN_LINK #include <boost/test/unit_test.hpp> #else #include <boost/test/included/unit_test.hpp> #endif #include <mjolnir/math/math.hpp> #include <mjolnir/core/BoundaryCondition.hpp> #include <mjolnir/core/SimulatorTraits.hpp> #include <mjolnir/core/AxisAlignedPlane.hpp> #include <mjolnir/forcefield/external/LennardJonesWallPotential.hpp> #include <mjolnir/omp/System.hpp> #include <mjolnir/omp/RandomNumberGenerator.hpp> #include <mjolnir/omp/UnlimitedGridCellList.hpp> #include <mjolnir/omp/ExternalDistanceInteraction.hpp> #include <mjolnir/util/make_unique.hpp> BOOST_AUTO_TEST_CASE(omp_ExternalDistacne_calc_force) { constexpr double tol = 1e-8; mjolnir::LoggerManager::set_default_logger("test_omp_external_distance_interaction.log"); using traits_type = mjolnir::OpenMPSimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = typename traits_type::real_type; using coordinate_type = typename traits_type::coordinate_type; using boundary_type = typename traits_type::boundary_type; using system_type = mjolnir::System<traits_type>; using topology_type = mjolnir::Topology; using potential_type = mjolnir::LennardJonesWallPotential<real_type>; using parameter_type = typename potential_type::parameter_type; using shape_type = mjolnir::AxisAlignedPlane<traits_type, mjolnir::PositiveZDirection<traits_type>>; using interaction_type = mjolnir::ExternalDistanceInteraction<traits_type, potential_type, shape_type>; using rng_type = mjolnir::RandomNumberGenerator<traits_type>; using sequencial_system_type = mjolnir::System< mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>>; using sequencial_shape_type = mjolnir::AxisAlignedPlane< mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>, mjolnir::PositiveZDirection<traits_type>>; using sequencial_interaction_type = mjolnir::ExternalDistanceInteraction< mjolnir::SimulatorTraits<double, mjolnir::UnlimitedBoundary>, potential_type, sequencial_shape_type>; const int max_number_of_threads = omp_get_max_threads(); BOOST_TEST_WARN(max_number_of_threads > 2); BOOST_TEST_MESSAGE("maximum number of threads = " << max_number_of_threads); const std::size_t N_particle = 64; std::vector<std::pair<std::size_t, parameter_type>> parameters(N_particle); for(std::size_t i=0; i<N_particle; ++i) { parameters.emplace_back(i, parameter_type(1.0, 1.0)); } const potential_type potential(2.5, parameters); for(int num_thread=1; num_thread<=max_number_of_threads; ++num_thread) { omp_set_num_threads(num_thread); BOOST_TEST_MESSAGE("maximum number of threads = " << omp_get_max_threads()); rng_type rng(123456789); system_type sys(N_particle, boundary_type{}); for(std::size_t i=0; i<sys.size(); ++i) { const auto i_x = i % 4; const auto i_y = i / 4; const auto i_z = i / 16; sys.mass(i) = 1.0; sys.position(i) = mjolnir::math::make_coordinate<coordinate_type>(i_x*2.0, i_y*2.0, i_z*2.0); sys.velocity(i) = mjolnir::math::make_coordinate<coordinate_type>(0, 0, 0); sys.force(i) = mjolnir::math::make_coordinate<coordinate_type>(0, 0, 0); sys.name(i) = "X"; sys.group(i) = "TEST"; } topology_type topol(N_particle); // add perturbation for(std::size_t i=0; i<sys.size(); ++i) { mjolnir::math::X(sys.position(i)) += rng.uniform_real(-0.1, 0.1); mjolnir::math::Y(sys.position(i)) += rng.uniform_real(-0.1, 0.1); mjolnir::math::Z(sys.position(i)) += rng.uniform_real(-0.1, 0.1); } // init sequential one with the same coordinates sequencial_system_type seq_sys(N_particle, boundary_type{}); assert(sys.size() == seq_sys.size()); for(std::size_t i=0; i<sys.size(); ++i) { seq_sys.mass(i) = sys.mass(i); seq_sys.position(i) = sys.position(i); seq_sys.velocity(i) = sys.velocity(i); seq_sys.force(i) = sys.force(i); seq_sys.name(i) = sys.name(i); seq_sys.group(i) = sys.group(i); } shape_type xyplane (0.0); sequencial_shape_type seq_xyplane(0.0); topol.construct_molecules(); xyplane .initialize(sys, potential); seq_xyplane.initialize(seq_sys, potential); interaction_type interaction( std::move(xyplane), potential_type(potential)); sequencial_interaction_type seq_interaction( std::move(seq_xyplane), potential_type(potential)); interaction .initialize(sys); seq_interaction.initialize(seq_sys); // calculate forces with openmp interaction.calc_force(sys); sys.postprocess_forces(); // calculate forces without openmp seq_interaction.calc_force(seq_sys); // check the values are the same for(std::size_t i=0; i<sys.size(); ++i) { BOOST_TEST(mjolnir::math::X(seq_sys.force(i)) == mjolnir::math::X(sys.force(i)), boost::test_tools::tolerance(tol)); BOOST_TEST(mjolnir::math::Y(seq_sys.force(i)) == mjolnir::math::Y(sys.force(i)), boost::test_tools::tolerance(tol)); BOOST_TEST(mjolnir::math::Z(seq_sys.force(i)) == mjolnir::math::Z(sys.force(i)), boost::test_tools::tolerance(tol)); } BOOST_TEST(interaction.calc_energy(sys) == seq_interaction.calc_energy(seq_sys), boost::test_tools::tolerance(tol)); } } BOOST_AUTO_TEST_CASE(omp_ExternalDistance_calc_force_and_energy) { mjolnir::LoggerManager::set_default_logger( "test_omp_external_distance_interaction.log"); using traits_type = mjolnir::OpenMPSimulatorTraits<double, mjolnir::UnlimitedBoundary>; using real_type = traits_type::real_type; using coordinate_type = traits_type::coordinate_type; using boundary_type = traits_type::boundary_type; using system_type = mjolnir::System<traits_type>; using potential_type = mjolnir::LennardJonesWallPotential<real_type>; using shape_type = mjolnir::AxisAlignedPlane<traits_type, mjolnir::PositiveZDirection<traits_type>>; using interaction_type = mjolnir::ExternalDistanceInteraction<traits_type, potential_type, shape_type>; interaction_type interaction(shape_type(0.0, 0.5), potential_type(/* cutoff = */2.0, { {0, {1.0, 1.0}}, {1, {1.0, 1.0}} })); system_type sys(2, boundary_type{}); sys.at(0).mass = 1.0; sys.at(1).mass = 1.0; sys.at(0).rmass = 1.0; sys.at(1).rmass = 1.0; sys.at(0).position = coordinate_type( 0.0, 0.0, 1.0); sys.at(1).position = coordinate_type( 0.0, 0.0, 1.0); sys.at(0).velocity = coordinate_type( 0.0, 0.0, 0.0); sys.at(1).velocity = coordinate_type( 0.0, 0.0, 0.0); sys.at(0).force = coordinate_type( 0.0, 0.0, 0.0); sys.at(1).force = coordinate_type( 0.0, 0.0, 0.0); sys.at(0).name = "X"; sys.at(1).name = "X"; sys.at(0).group = "NONE"; sys.at(1).group = "NONE"; std::mt19937 mt(123456789); std::uniform_real_distribution<real_type> uni(-1.0, 1.0); std::normal_distribution<real_type> gauss(0.0, 1.0); for(int i = 0; i < 10000; ++i) { sys.at(0).position = coordinate_type(0.0, 0.0, 1.0); sys.at(1).position = coordinate_type(0.0, 0.0, 1.0); // move particles a bit, randomly. and reset forces. for(std::size_t idx=0; idx<sys.size(); ++idx) { sys.position(idx) += coordinate_type(0.01 * uni(mt), 0.01 * uni(mt), 0.01 * uni(mt)); sys.force(idx) = coordinate_type(0.0, 0.0, 0.0); } system_type ref_sys = sys; constexpr real_type tol = 1e-4; const auto energy = interaction.calc_force_and_energy(sys); const auto ref_energy = interaction.calc_energy(ref_sys); interaction.calc_force(ref_sys); BOOST_TEST(ref_energy == energy, boost::test_tools::tolerance(tol)); for(std::size_t idx=0; idx<sys.size(); ++idx) { BOOST_TEST(mjolnir::math::X(sys.force(idx)) == mjolnir::math::X(ref_sys.force(idx)), boost::test_tools::tolerance(tol)); BOOST_TEST(mjolnir::math::Y(sys.force(idx)) == mjolnir::math::Y(ref_sys.force(idx)), boost::test_tools::tolerance(tol)); BOOST_TEST(mjolnir::math::Z(sys.force(idx)) == mjolnir::math::Z(ref_sys.force(idx)), boost::test_tools::tolerance(tol)); } } }
41.901408
132
0.643249
yutakasi634
0819301c98d806c431bdf1c95c36fa35d20f7475
3,400
hpp
C++
IGC/Compiler/Optimizer/OpenCLPasses/ProgramScopeConstants/ProgramScopeConstantAnalysis.hpp
ConiKost/intel-graphics-compiler
f5227c9658da35d08d7f711552ebcb12638ebc18
[ "Intel", "MIT" ]
1
2020-09-03T17:11:47.000Z
2020-09-03T17:11:47.000Z
IGC/Compiler/Optimizer/OpenCLPasses/ProgramScopeConstants/ProgramScopeConstantAnalysis.hpp
ConiKost/intel-graphics-compiler
f5227c9658da35d08d7f711552ebcb12638ebc18
[ "Intel", "MIT" ]
null
null
null
IGC/Compiler/Optimizer/OpenCLPasses/ProgramScopeConstants/ProgramScopeConstantAnalysis.hpp
ConiKost/intel-graphics-compiler
f5227c9658da35d08d7f711552ebcb12638ebc18
[ "Intel", "MIT" ]
null
null
null
/*========================== begin_copyright_notice ============================ Copyright (C) 2017-2021 Intel Corporation SPDX-License-Identifier: MIT ============================= end_copyright_notice ===========================*/ #pragma once #include "Compiler/MetaDataUtilsWrapper.h" #include "common/LLVMWarningsPush.hpp" #include <llvm/Pass.h> #include <llvm/IR/DataLayout.h> #include <llvm/ADT/MapVector.h> #include "common/LLVMWarningsPop.hpp" namespace IGC { /// @brief This pass creates annotations for OpenCL program-scope structures. // Currently this is program-scope constants, but for OpenCL 2.0, it should // also support program-scope globals. class ProgramScopeConstantAnalysis : public llvm::ModulePass { public: // Pass identification, replacement for typeid static char ID; /// @brief Constructor ProgramScopeConstantAnalysis(); /// @brief Destructor ~ProgramScopeConstantAnalysis() {} /// @brief Provides name of pass virtual llvm::StringRef getPassName() const override { return "ProgramScopeConstantAnalysisPass"; } virtual void getAnalysisUsage(llvm::AnalysisUsage& AU) const override { AU.setPreservesCFG(); AU.addRequired<MetaDataUtilsWrapper>(); AU.addRequired<CodeGenContextWrapper>(); } /// @brief Main entry point. /// Runs on all GlobalVariables in this module, finds the constants, and /// generates annotations for them. /// @param M The destination module. virtual bool runOnModule(llvm::Module& M) override; protected: typedef std::vector<unsigned char> DataVector; typedef llvm::MapVector<llvm::GlobalVariable*, int> BufferOffsetMap; struct PointerOffsetInfo { unsigned AddressSpaceWherePointerResides; uint64_t PointerOffsetFromBufferBase; unsigned AddressSpacePointedTo; PointerOffsetInfo( unsigned AddressSpaceWherePointerResides, uint64_t PointerOffsetFromBufferBase, unsigned AddressSpacePointedTo) : AddressSpaceWherePointerResides(AddressSpaceWherePointerResides), PointerOffsetFromBufferBase(PointerOffsetFromBufferBase), AddressSpacePointedTo(AddressSpacePointedTo) {} }; typedef std::list<PointerOffsetInfo> PointerOffsetInfoList; /// @brief Add data from the inline constant into the buffer. /// @param initializer The initializer of the constant being added. /// @param inlineConstantBuffer The buffer the data is being added to. void addData( llvm::Constant* initializer, DataVector& inlineConstantBuffer, PointerOffsetInfoList& pointerOffsetInfo, BufferOffsetMap& inlineProgramScopeOffsets, unsigned addressSpace); /// @brief Align the buffer according to the required alignment /// @param buffer The buffer to align. /// @param alignment Required alignment in bytes. void alignBuffer(DataVector& buffer, unsigned int alignment); const llvm::DataLayout* m_DL; ModuleMetaData* m_pModuleMd; }; } // namespace IGC
35.789474
88
0.632059
ConiKost
08196178478447608c42dee8386ed18a7bd59944
26,759
hpp
C++
src/sframe/sframe.hpp
karthikdash/turicreate
86a6d9a339a77b7b55f67233352da0e7471400bc
[ "BSD-3-Clause" ]
1
2018-04-11T19:06:57.000Z
2018-04-11T19:06:57.000Z
src/sframe/sframe.hpp
karthikdash/turicreate
86a6d9a339a77b7b55f67233352da0e7471400bc
[ "BSD-3-Clause" ]
null
null
null
src/sframe/sframe.hpp
karthikdash/turicreate
86a6d9a339a77b7b55f67233352da0e7471400bc
[ "BSD-3-Clause" ]
1
2019-01-12T01:07:34.000Z
2019-01-12T01:07:34.000Z
/* Copyright © 2017 Apple Inc. All rights reserved. * * Use of this source code is governed by a BSD-3-clause license that can * be found in the LICENSE.txt file or at https://opensource.org/licenses/BSD-3-Clause */ #ifndef TURI_UNITY_LIB_SFRAME_HPP #define TURI_UNITY_LIB_SFRAME_HPP #include <iostream> #include <algorithm> #include <memory> #include <vector> #include <logger/logger.hpp> #include <flexible_type/flexible_type.hpp> #include <sframe/sarray.hpp> #include <sframe/dataframe.hpp> #include <sframe/sframe_index_file.hpp> #include <sframe/sframe_constants.hpp> #include <sframe/output_iterator.hpp> namespace turi { // forward declaration of th csv_line_tokenizer to avoid a // circular dependency struct csv_line_tokenizer; class sframe_reader; class csv_writer; typedef turi::sframe_function_output_iterator< std::vector<flexible_type>, std::function<void(const std::vector<flexible_type>&)>, std::function<void(std::vector<flexible_type>&&)>, std::function<void(const sframe_rows&)> > sframe_output_iterator; /** * \ingroup sframe_physical * \addtogroup sframe_main Main SFrame Objects * \{ */ /** * The SFrame is an immutable object that represents a table with rows * and columns. Each column is an \ref sarray<flexible_type>, which is a * sequence of an object T split into segments. The sframe writes an sarray * for each column of data it is given to disk, each with a prefix that extends * the prefix given to open. The SFrame is referenced on disk by a single * ".frame_idx" file which then has a list of file names, one file for each * column. * * The SFrame is \b write-once, \b read-many. The SFrame can be opened for * writing \b once, after which it is read-only. * * Since each column of the SFrame is an independent sarray, as an independent * shared_ptr<sarray<flexible_type> > object, columns can be added / removed * to form new sframes without problems. As such, certain operations * (such as the object returned by add_column) recan be "ephemeral" in that * there is no .frame_idx file on disk backing it. An "ephemeral" frame can be * identified by checking the result of get_index_file(). If this is empty, * it is an ephemeral frame. * * The interface for the SFrame pretty much matches that of the \ref sarray * as in the SArray's stored type is std::vector<flexible_type>. The SFrame * however, also provides a large number of other capabilities such as * csv parsing, construction from sarrays, etc. */ class sframe : public swriter_base<sframe_output_iterator> { public: /// The reader type typedef sframe_reader reader_type; /// The iterator type which \ref get_output_iterator returns typedef sframe_output_iterator iterator; /// The type contained in the sframe typedef std::vector<flexible_type> value_type; /**************************************************************************/ /* */ /* Constructors */ /* */ /**************************************************************************/ /** * default constructor; does nothing; use \ref open_for_read or * \ref open_for_write after construction to read/create an sarray. */ inline sframe() { } /** * Copy constructor. * If the source frame is opened for writing, this will throw * an exception. Otherwise, this will create a frame opened for reading, * which shares column arrays with the source frame. */ sframe(const sframe& other); /** * Move constructor. */ sframe(sframe&& other) : sframe() { (*this) = std::move(other); } /** * Assignment operator. * If the source frame is opened for writing, this will throw * an exception. Otherwise, this will create a frame opened for reading, * which shares column arrays with the source frame. */ sframe& operator=(const sframe& other); /** * Move Assignment operator. * Moves other into this. Other will be cleared as if it is a newly * constructed sframe object. */ sframe& operator=(sframe&& other); /** * Attempts to construct an sframe which reads from the given frame * index file. This should be a .frame_idx file. * If the index cannot be opened, an exception is thrown. */ explicit inline sframe(std::string frame_idx_file) { auto frame_index_info = read_sframe_index_file(frame_idx_file); open_for_read(frame_index_info); } /** * Construct an sframe from sframe index information. */ explicit inline sframe(sframe_index_file_information frame_index_info) { open_for_read(frame_index_info); }; /** * Constructs an SFrame from a vector of Sarrays. * * \param columns List of sarrays to form as columns * \param column_names List of the name for each column, with the indices * corresponding with the list of columns. If the length of the column_names * vector does not match columns, the column gets a default name. * For example, if four columns are given and column_names = {id, num}, * the columns will be named {"id, "num", "X3", "X4"}. Entries that are * zero-length strings will also be given a default name. * \param fail_on_column_names If true, will throw an exception if any column * names are unique. If false, will automatically adjust column names so * they are unique. * * Throws an exception if any column names are not unique (if * fail_on_column_names is true), or if the number of segments, segment * sizes, or total sizes of each sarray is not equal. The constructed SFrame * is ephemeral, and is not backed by a disk index. */ explicit inline sframe( const std::vector<std::shared_ptr<sarray<flexible_type> > > &new_columns, const std::vector<std::string>& column_names = {}, bool fail_on_column_names=true) { open_for_read(new_columns, column_names, fail_on_column_names); } /** * Constructs an SFrame from a csv file. * * All columns will be parsed into flex_string unless the column type is * specified in the column_type_hints. * * \param path The url to the csv file. The url can points to local * filesystem, hdfs, or s3. \param tokenizer The tokenization rules to use * \param use_header If true, the first line will be parsed as column * headers. Otherwise, R-style column names, i.e. X1, X2, X3... will be used. * \param continue_on_failure If true, lines with parsing errors will be skipped. * \param column_type_hints A map from column name to the column type. * \param output_columns The subset of column names to output * \param row_limit If non-zero, the maximum number of rows to read * \param skip_rows If non-zero, the number of lines to skip at the start * of each file * * Throws an exception if IO error or csv parse failed. */ std::map<std::string, std::shared_ptr<sarray<flexible_type>>> init_from_csvs( const std::string& path, csv_line_tokenizer& tokenizer, bool use_header, bool continue_on_failure, bool store_errors, std::map<std::string, flex_type_enum> column_type_hints, std::vector<std::string> output_columns = std::vector<std::string>(), size_t row_limit = 0, size_t skip_rows = 0); /** * Constructs an SFrame from dataframe_t. * * \note Throw an exception if the dataframe contains undefined values (e.g. * in sparse rows), */ sframe(const dataframe_t& data); ~sframe(); /**************************************************************************/ /* */ /* Openers */ /* */ /**************************************************************************/ /** * Initializes the SFrame with an index_information. * If the SFrame is already inited, this will throw an exception */ inline void open_for_read(sframe_index_file_information frame_index_info) { Dlog_func_entry(); ASSERT_MSG(!inited, "Attempting to init an SFrame " "which has already been inited."); inited = true; create_arrays_for_reading(frame_index_info); } /** * Initializes the SFrame with a collection of columns. If the SFrame is * already inited, this will throw an exception. Will throw an exception if * column_names are not unique and fail_on_column_names is true. */ void open_for_read( const std::vector<std::shared_ptr<sarray<flexible_type> > > &new_columns, const std::vector<std::string>& column_names = {}, bool fail_on_column_names=true) { Dlog_func_entry(); ASSERT_MSG(!inited, "Attempting to init an SFrame " "which has already been inited."); inited = true; create_arrays_for_reading(new_columns, column_names, fail_on_column_names); } /** * Opens the SFrame with an arbitrary temporary file. * The array must not already been inited. * * \param column_names The name for each column. If the vector is shorter * than column_types, or empty values are given, names are handled with * default names of "X<column id+1>". Each column name must be unique. * This will let you write non-unique column names, but if you do that, * the sframe will throw an exception while constructing the output of * this class. * \param column_types The type of each column expressed as a * flexible_type. Currently this is required to tell how many columns * are a part of the sframe. Throws an exception if this is an empty * vector. * \param nsegments The number of parallel output segments on each * sarray. Throws an exception if this is 0. * \param frame_sidx_file If not specified, an argitrary temporary * file will be created. Otherwise, all frame * files will be written to the same location * as the frame_sidx_file. Must end in * ".frame_idx" * \param fail_on_column_names If true, will throw an exception if any column * names are unique. If false, will * automatically adjust column names so they are * unique. */ inline void open_for_write(const std::vector<std::string>& column_names, const std::vector<flex_type_enum>& column_types, const std::string& frame_sidx_file = "", size_t nsegments = SFRAME_DEFAULT_NUM_SEGMENTS, bool fail_on_column_names=true) { Dlog_func_entry(); ASSERT_MSG(!inited, "Attempting to init an SFrame " "which has already been inited."); if (column_names.size() != column_types.size()) { log_and_throw(std::string("Names and Types array length mismatch")); } inited = true; create_arrays_for_writing(column_names, column_types, nsegments, frame_sidx_file, fail_on_column_names); } /**************************************************************************/ /* */ /* Basic Accessors */ /* */ /**************************************************************************/ /** * Returns true if the Array is opened for reading. * i.e. get_reader() will succeed */ inline bool is_opened_for_read() const { return (inited && !writing); } /** * Returns true if the Array is opened for writing. * i.e. get_output_iterator() will succeed */ inline bool is_opened_for_write() const { return (inited && writing); } /** * Return the index file of the sframe */ inline const std::string& get_index_file() const { ASSERT_TRUE(inited); return index_file; } /** * Reads the value of a key associated with the sframe * Returns true on success, false on failure. */ inline bool get_metadata(const std::string& key, std::string &val) const { bool ret; std::tie(ret, val) = get_metadata(key); return ret; } /** * Reads the value of a key associated with the sframe * Returns a pair of (true, value) on success, and (false, empty_string) * on failure. */ inline std::pair<bool, std::string> get_metadata(const std::string& key) const { ASSERT_MSG(inited, "Invalid SFrame"); if (index_info.metadata.count(key)) { return std::pair<bool, std::string>(true, index_info.metadata.at(key)); } else { return std::pair<bool, std::string>(false, ""); } } /// Returns the number of columns in the SFrame. Does not throw. inline size_t num_columns() const { return index_info.ncolumns; } /// Returns the length of each sarray. inline size_t num_rows() const { return size(); } /** * Returns the number of elements in the sframe. If the sframe was not initialized, returns 0. */ inline size_t size() const { return inited ? index_info.nrows : 0; } /** * Returns the name of the given column. Throws an exception if the * column id is out of range. */ inline std::string column_name(size_t i) const { if(i >= index_info.column_names.size()) { log_and_throw("Column index out of range!"); } return index_info.column_names[i]; } /** * Returns the type of the given column. Throws an exception if the * column id is out of range. */ inline flex_type_enum column_type(size_t i) const { if (writing) { if(i >= group_writer->get_index_info().columns.size()) { log_and_throw("Column index out of range!"); } return (flex_type_enum) (atoi(group_writer->get_index_info().columns[i].metadata["__type__"].c_str())); } else { if(i >= columns.size()) { log_and_throw("Column index out of range!"); } return columns[i]->get_type(); } } /** * Returns the type of the given column. Throws an exception if the * column id is out of range. * \overload */ inline flex_type_enum column_type(const std::string& column_name) const { return columns[column_index(column_name)]->get_type(); } /** Returns the column names as a single vector. */ inline const std::vector<std::string>& column_names() const { return index_info.column_names; } /** Returns the column types as a single vector. */ inline std::vector<flex_type_enum> column_types() const { std::vector<flex_type_enum> tv(num_columns()); for(size_t i = 0; i < num_columns(); ++i) tv[i] = column_type(i); return tv; } /** * Returns true if the sframe contains the given column. */ inline bool contains_column(const std::string& column_name) const { Dlog_func_entry(); auto iter = std::find(index_info.column_names.begin(), index_info.column_names.end(), column_name); return iter != index_info.column_names.end(); } /** * Returns the number of segments that this SFrame will be * written with. Never fails. */ inline size_t num_segments() const { ASSERT_MSG(inited, "Invalid SFrame"); if (writing) { return group_writer->num_segments(); } else { if (index_info.ncolumns == 0) return 0; return columns[0]->num_segments(); } } /** * Return the number of segments in the collection. * Will throw an exception if the writer is invalid (there is an error * opening/writing files) */ inline size_t segment_length(size_t i) const { DASSERT_MSG(inited, "Invalid SFrame"); if (index_info.ncolumns == 0) return 0; else return columns[0]->segment_length(i); } /** * Returns the column index of column_name. * * Throws an exception of the column_ does not exist. */ inline size_t column_index(const std::string& column_name) const { auto iter = std::find(index_info.column_names.begin(), index_info.column_names.end(), column_name); if (iter != index_info.column_names.end()) { return (iter) - index_info.column_names.begin(); } else { log_and_throw(std::string("Column name " + column_name + " does not exist.")); } __builtin_unreachable(); } /** * Returns the current index info of the array. */ inline const sframe_index_file_information get_index_info() const { return index_info; } /** * Merges another SFrame with the same schema with the current SFrame * returning a new SFrame. * Both SFrames can be empty, but cannot be opened for writing. */ sframe append(const sframe& other) const; /** * Gets an sframe reader object with the segment layout of the first column. */ std::unique_ptr<reader_type> get_reader() const; /** * Gets an sframe reader object with num_segments number of logical segments. */ std::unique_ptr<reader_type> get_reader(size_t num_segments) const; /** * Gets an sframe reader object with a custom segment layout. segment_lengths * must sum up to the same length as the original array. */ std::unique_ptr<reader_type> get_reader(const std::vector<size_t>& segment_lengths) const; /**************************************************************************/ /* */ /* Other SFrame Unique Accessors */ /* */ /**************************************************************************/ /** * Converts the sframe into a dataframe_t. Will reset iterators before * and after the operation. */ dataframe_t to_dataframe(); /** * Returns an sarray of the specific column. * * Throws an exception if the column does not exist. */ std::shared_ptr<sarray<flexible_type> > select_column(size_t column_id) const; /** * Returns an sarray of the specific column by name. * * Throws an exception if the column does not exist. */ std::shared_ptr<sarray<flexible_type> > select_column(const std::string &name) const; /** * Returns new sframe containing only the chosen columns in the same order. * The new sframe is "ephemeral" in that it is not backed by an index * on disk. * * Throws an exception if the column name does not exist. */ sframe select_columns(const std::vector<std::string>& names) const; /** * Returns a new ephemeral SFrame with the new column added to the end. * The new sframe is "ephemeral" in that it is not backed by an index * on disk. * * \param sarr_ptr Shared pointer to the SArray * \param column_name The name to give this column. If empty it will * be given a default name (X<column index>) * */ sframe add_column(std::shared_ptr<sarray<flexible_type> > sarr_ptr, const std::string& column_name=std::string("")) const; /** * Set the ith column name to name. This can be done when the * frame is open in either reading or writing mode. Changes are ephemeral, * and do not affect what is stored on disk. */ void set_column_name(size_t column_id, const std::string& name); /** * Returns a new ephemeral SFrame with the column removed. * The new sframe is "ephemeral" in that it is not backed by an index * on disk. * * \param column_id The index of the column to remove. * */ sframe remove_column(size_t column_id) const; /** * Returns a new ephemeral SFrame with two columns swapped. * The new sframe is "ephemeral" in that it is not backed by an index * on disk. * * \param column_1 The index of the first column. * \param column_2 The index of the second column. * */ sframe swap_columns(size_t column_1, size_t column_2) const; /** * Replace the column of the given column name with a new sarray. * Return the new sframe with old column_name sarray replaced by the new sarray. */ sframe replace_column(std::shared_ptr<sarray<flexible_type>> sarr_ptr, const std::string& column_name) const; /**************************************************************************/ /* */ /* Writing Functions */ /* */ /**************************************************************************/ // These functions are only valid when the array is opened for writing /** * Sets the number of segments in the output. * Frame must be first opened for writing. * Once an output iterator has been obtained, the number of segments * can no longer be changed. Returns true on sucess, false on failure. */ bool set_num_segments(size_t numseg); /** * Gets an output iterator for the given segment. This can be used to * write data to the segment, and is currently the only supported way * to do so. * * The iterator is invalid once the segment is closed (See \ref close). * Accessing the iterator after the writer is destroyed is undefined * behavior. * * Cannot be called until the sframe is open. * * Example: * \code * // example to write the same vector to 7 rows of segment 1 * // let's say the sframe has 5 columns of type FLEX_TYPE_ENUM::INTEGER * // and sfw is the sframe. * auto iter = sfw.get_output_iterator(1); * std::vector<flexible_type> vals{1,2,3,4,5} * for(int i = 0; i < 7; ++i) { * *iter = vals; * ++iter; * } * \endcode */ iterator get_output_iterator(size_t segmentid); /** * Closes the sframe. close() also implicitly closes all segments. After * the writer is closed, no segments can be written. * After the sframe is closed, it becomes read only and can be read * with the get_reader() function. */ void close(); /** * Flush writes for a particular segment */ void flush_write_to_segment(size_t segment); /** * Saves a copy of the current sframe as a CSV file. * Does not modify the current sframe. * * \param csv_file target CSV file to save into * \param writer The CSV writer configuration */ void save_as_csv(std::string csv_file, csv_writer& writer); /** * Adds meta data to the frame. * Frame must be first opened for writing. */ bool set_metadata(const std::string& key, std::string val); /** * Saves a copy of the current sframe into a different location. * Does not modify the current sframe. */ void save(std::string index_file) const; /** * SFrame serializer. oarc must be associated with a directory. * Saves into a prefix inside the directory. */ void save(oarchive& oarc) const; /** * SFrame deserializer. iarc must be associated with a directory. * Loads from the next prefix inside the directory. */ void load(iarchive& iarc); bool delete_files_on_destruction(); /** * Internal API. * Used to obtain the internal writer object. */ inline std::shared_ptr<sarray_group_format_writer<flexible_type> > get_internal_writer() { return group_writer; } private: /** * Clears all internal structures. Used by \ref create_arrays_for_reading * and \ref create_arrays_for_writing to clear all the index information * and column information */ void reset(); /** * Internal function that actually writes the values to each SArray's * output iterator. Used by the sframe_output_iterator. */ void write(size_t segmentid, const std::vector<flexible_type>& t); /** * Internal function that actually writes the values to each SArray's * output iterator. Used by the sframe_output_iterator. */ void write(size_t segmentid, std::vector<flexible_type>&& t); /** * Internal function that actually writes the values to each SArray's * output iterator. Used by the sframe_output_iterator. */ void write(size_t segmentid, const sframe_rows& t); /** * Internal function. Given the index_information, this function * initializes each of the sarrays for reading; filling up * the columns array */ void create_arrays_for_reading(sframe_index_file_information frame_index_info); /** * Internal function. Given a collection of sarray columns, this function * makes an sframe representing the combination of all the columns. This * sframe does not have an index file (it is ephemeral), and get_index_file * will return an empty file. Will throw an exception if column_names are not * unique and fail_on_column_names is true. */ void create_arrays_for_reading( const std::vector<std::shared_ptr<sarray<flexible_type> > > &columns, const std::vector<std::string>& column_names = {}, bool fail_on_column_names=true); /** * Internal function. Given the index_file, this function initializes each of * the sarrays for writing; filling up the columns array. Will throw an * exception if column_names are not unique and fail_on_column_names is true. */ void create_arrays_for_writing(const std::vector<std::string>& column_names, const std::vector<flex_type_enum>& column_types, size_t nsegments, const std::string& frame_sidx_file, bool fail_on_column_names); void keep_array_file_ref(); /** * Internal function. Resolve conflicts in column names. */ std::string generate_valid_column_name(const std::string &column_name) const; sframe_index_file_information index_info; std::string index_file; std::vector<std::shared_ptr<fileio::file_ownership_handle> > index_file_handle; std::vector<std::shared_ptr<sarray<flexible_type> > > columns; std::shared_ptr<sarray_group_format_writer<flexible_type> > group_writer; mutex lock; bool inited = false; bool writing = false; friend class sframe_reader; public: /** * For debug purpose, print the information about the sframe. */ void debug_print(); }; /// \} } // end of namespace #endif #include <sframe/sframe_reader.hpp>
34.394602
96
0.630704
karthikdash
081fb04b87b9bf4a565b7e4702c1a2608373d1cc
67
cpp
C++
core/Instruments/AnalogDrums/AnalogDrum.cpp
ferluht/pocketdaw
0e40b32191e431cde54cd5944611c4b5b293ea68
[ "BSD-2-Clause" ]
null
null
null
core/Instruments/AnalogDrums/AnalogDrum.cpp
ferluht/pocketdaw
0e40b32191e431cde54cd5944611c4b5b293ea68
[ "BSD-2-Clause" ]
null
null
null
core/Instruments/AnalogDrums/AnalogDrum.cpp
ferluht/pocketdaw
0e40b32191e431cde54cd5944611c4b5b293ea68
[ "BSD-2-Clause" ]
1
2022-03-29T19:45:51.000Z
2022-03-29T19:45:51.000Z
// // Created by ibelikov on 23.12.19. // #include "AnalogDrum.h"
11.166667
35
0.641791
ferluht
0827622e6748b8e62d1effaf51041b021fb28ab8
794
cpp
C++
src/diff/deltas/asset_type_2_delta.cpp
kmichel/zizany
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
[ "MIT" ]
3
2017-07-02T08:33:22.000Z
2019-03-16T00:48:11.000Z
src/diff/deltas/asset_type_2_delta.cpp
kmichel/zizany
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
[ "MIT" ]
null
null
null
src/diff/deltas/asset_type_2_delta.cpp
kmichel/zizany
cfd21b5a58e0935c66b6b4ee2ef2a4d22ad4c435
[ "MIT" ]
null
null
null
#include "asset_type_2_delta.hpp" #include "../../json_writer.hpp" namespace zizany { asset_type_2_delta::asset_type_2_delta(const int asset_id_, const int old_type_2_, const int new_type_2_) : asset_id(asset_id_), old_type_2(old_type_2_), new_type_2(new_type_2_) { } void asset_type_2_delta::print_action(json_writer &writer) const { writer.add_string("change asset type 2"); } void asset_type_2_delta::print_details(json_writer &writer) const { writer.start_object(); writer.add_key("asset_id"); writer.add_number(asset_id); writer.add_key("old_type_2"); writer.add_number(old_type_2); writer.add_key("new_type_2"); writer.add_number(new_type_2); writer.end_object(); } }
29.407407
109
0.675063
kmichel
082764dadca0c252f699262421dec95cb44715f2
1,438
hpp
C++
libobs-for-HQ-Windows/libobs/util/dstr.hpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
45
2019-01-09T01:50:12.000Z
2021-08-09T20:51:22.000Z
libobs-for-HQ-Windows/libobs/util/dstr.hpp
jayliu1989/HQ
470d9919742412795447c81c3f160278b4418ba7
[ "MIT" ]
8
2019-01-14T10:30:55.000Z
2021-06-16T11:38:39.000Z
Agora-Live-Shop-Windows/obs-studio/include/util/dstr.hpp
AgoraIO/Live-Shop-Use-Case
75b27587d282ad99f3d072e2ec7a2569705083a8
[ "MIT" ]
24
2019-02-15T17:24:23.000Z
2021-09-09T23:45:19.000Z
/* * Copyright (c) 2014 Hugh Bailey <obs.jim@gmail.com> * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #pragma once #include "dstr.h" class DStr { dstr str; DStr(DStr const&) = delete; DStr &operator=(DStr const&) = delete; public: inline DStr() {dstr_init(&str);} inline DStr(DStr &&other) : DStr() { dstr_move(&str, &other.str); } inline DStr &operator=(DStr &&other) { dstr_move(&str, &other.str); return *this; } inline ~DStr() {dstr_free(&str);} inline operator dstr*() {return &str;} inline operator const dstr*() const {return &str;} inline operator char*() {return str.array;} inline operator const char*() const {return str.array;} inline dstr *operator->() {return &str;} };
28.76
75
0.697497
jayliu1989
082a0dec5a4414f0ce972588177e96140b513227
1,130
cpp
C++
libsnn/src/loss/hillinger.cpp
rahulsrma26/simpleNN
4a8858df503336ce5cf00850d89015e93e07cb36
[ "MIT" ]
11
2019-11-02T13:48:36.000Z
2020-03-06T22:57:40.000Z
libsnn/src/loss/hillinger.cpp
rahulsrma26/simpleAI
4a8858df503336ce5cf00850d89015e93e07cb36
[ "MIT" ]
1
2019-12-13T15:08:55.000Z
2019-12-15T17:16:08.000Z
libsnn/src/loss/hillinger.cpp
rahulsrma26/simpleAI
4a8858df503336ce5cf00850d89015e93e07cb36
[ "MIT" ]
null
null
null
#include "snn/loss/hillinger.hpp" namespace snn { namespace losses { constexpr real h_eps = 1e-5f; hillinger::hillinger(const kwargs& args) { std::ignore = args; } std::string hillinger::type() { return TEXT::HILLINGER; } std::string hillinger::name() const { return this->type(); } real hillinger::f(const tensor<real>& o, const tensor<real>& l) const { real r = 0; for (size_t i = 0; i < o.size(); i++) { const real d = std::sqrt(o[i]) - std::sqrt(l[i]); r += d * d; } return r / (std::sqrt(real(2.0)) * o.get_shape().front()); } tensor<real> hillinger::df(const tensor<real>& o, const tensor<real>& l) const { tensor<real> r(o.get_shape()); const auto n = o.get_shape().front(); for (uint i = 0; i < o.size(); i++) { const real denom = std::sqrt(2.0f * o[i]); r[i] = (std::sqrt(o[i]) - std::sqrt(l[i])) / ((h_eps + denom) * n); } return r; } void hillinger::save(std::ostream& os) const { std::ignore = os; } hillinger::hillinger(std::istream& is) { std::ignore = is; } } // namespace losses } // namespace snn
28.974359
81
0.567257
rahulsrma26
082bf53f1d88f591ebf74b485c0f627e0453b678
527
cpp
C++
Source/restrict.cpp
mikeeq/devilution-nx
d59170c5f1ab884b0539ec38bbfc8655ea9866b8
[ "Unlicense" ]
878
2019-07-01T11:52:52.000Z
2022-02-20T21:31:45.000Z
Source/restrict.cpp
mikeeq/devilution-nx
d59170c5f1ab884b0539ec38bbfc8655ea9866b8
[ "Unlicense" ]
29
2019-07-01T22:43:59.000Z
2021-12-06T09:32:17.000Z
Source/restrict.cpp
mikeeq/devilution-nx
d59170c5f1ab884b0539ec38bbfc8655ea9866b8
[ "Unlicense" ]
79
2019-07-01T13:01:43.000Z
2021-12-06T08:52:52.000Z
#include "diablo.h" DEVILUTION_BEGIN_NAMESPACE BOOL SystemSupported() { return TRUE; } BOOL RestrictedTest() { #ifndef SWITCH FILE *f; char Buffer[MAX_PATH]; BOOL ret = FALSE; if (SystemSupported() && GetWindowsDirectory(Buffer, sizeof(Buffer))) { strcat(Buffer, "\\Diablo1RestrictedTest.foo"); f = fopen(Buffer, "wt"); if (f) { fclose(f); remove(Buffer); } else { ret = TRUE; } } return ret; #else return TRUE; #endif } BOOL ReadOnlyTest() { return false; } DEVILUTION_END_NAMESPACE
12.853659
72
0.664137
mikeeq
082ccc3a9c7bcc14fa687824a82bb5879e39d530
1,099
cpp
C++
pwiz/utility/bindings/SWIG/python_pwiz_RAMPAdapter.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
11
2015-01-08T08:33:44.000Z
2019-07-12T06:14:54.000Z
pwiz/utility/bindings/SWIG/python_pwiz_RAMPAdapter.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
61
2015-05-27T11:20:11.000Z
2019-12-20T15:06:21.000Z
pwiz/utility/bindings/SWIG/python_pwiz_RAMPAdapter.cpp
edyp-lab/pwiz-mzdb
d13ce17f4061596c7e3daf9cf5671167b5996831
[ "Apache-2.0" ]
4
2016-02-03T09:41:16.000Z
2021-08-01T18:42:36.000Z
// // python_pwiz_RAMPAdapter.cpp // // $Id: python_pwiz_RAMPAdapter.cpp 3300 2012-02-15 22:38:20Z chambm $ // // a lightweight wrapper allowing SWIG to wrap some useful pwiz code // Q: why a wrapper wrapper? A: SWIG can't handle namespaces // // // Original author: Brian Pratt <Brian.Pratt@insilicos.com> // // Copyright 2011 Insilicos LLC All Rights Reserved // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // actually this is just here to make it easier to create an object file // with different compile switches #include "pwiz_RAMPAdapter.cpp"
35.451613
77
0.720655
edyp-lab
082de51b2466a3d550828e03f9ba9d304e9ae335
6,537
cpp
C++
heart/src/components/hEntityFactory.cpp
JoJo2nd/Heart
4b50dfa6cbf87d32768f6c01b578bc1b23c18591
[ "BSD-3-Clause" ]
1
2016-05-14T09:22:26.000Z
2016-05-14T09:22:26.000Z
heart/src/components/hEntityFactory.cpp
JoJo2nd/Heart
4b50dfa6cbf87d32768f6c01b578bc1b23c18591
[ "BSD-3-Clause" ]
null
null
null
heart/src/components/hEntityFactory.cpp
JoJo2nd/Heart
4b50dfa6cbf87d32768f6c01b578bc1b23c18591
[ "BSD-3-Clause" ]
null
null
null
/******************************************************************** Written by James Moran Please see the file HEART_LICENSE.txt in the source's root directory. *********************************************************************/ #pragma once #include "components/hEntityFactory.h" #include "base/hUUID.h" #include "base/hMemory.h" #include "base/hMemoryUtil.h" #include "base/hLinkedList.h" #include "components/hEntity.h" #include <unordered_map> #include <unordered_set> #include <memory> namespace Heart { static struct hEntityContextManager { typedef std::unordered_map<hUuid_t, hEntity*> hEntityHashTable; //!!JM TODO: Make this a handle based system? typedef hEntityHashTable::value_type hEntityEntry; typedef std::unordered_map<const hObjectDefinition*, hEntityFactory::hComponentMgt> hComponentMgtHashTable; typedef hComponentMgtHashTable::value_type hComponentMgtEntry; hEntityHashTable entityTable; hComponentMgtHashTable componentMgt; } g_entityContextManager; namespace hEntityFactory { void registerComponentManagement(const hComponentMgt& comp_mgt) { hcAssertMsg(g_entityContextManager.componentMgt.find(comp_mgt.object_def) == g_entityContextManager.componentMgt.end(), "Component Management for '%s' registered more than once", comp_mgt.object_def->objectName_.c_str()); g_entityContextManager.componentMgt.insert(hEntityContextManager::hComponentMgtEntry(comp_mgt.object_def, comp_mgt)); } hEntity* createEntity(hUuid_t id, hComponentDefinition* compents, hSize_t component_def_count) { hcAssertMsg(compents && !hUUID::isNull(id), "Invalid args to %s", __FUNCTION__); Heart::hEntity* new_entity = new Heart::hEntity(); // TODO!!JM Freelist this! new_entity->entityId = id; new_entity->entityComponents.resize(component_def_count); for (hSize_t ci = 0, cn = component_def_count; ci < cn; ++ci) { const auto& comp_def = compents[ci]; auto comp_mgt = g_entityContextManager.componentMgt.find(comp_def.typeDefintion); hEntityComponent* obj = nullptr; hcAssertMsg(comp_mgt != g_entityContextManager.componentMgt.end(), "Type '%s' is not a component type", comp_def.typeDefintion->objectName_.c_str()); obj = comp_mgt->second.construct(new_entity, comp_def.marshall); obj->owner = new_entity; obj->componentDestruct = comp_mgt->second.destruct; new_entity->entityComponents[ci].typeID = comp_def.typeDefintion->runtimeTypeID; new_entity->entityComponents[ci].typeDef = comp_def.typeDefintion; new_entity->entityComponents[ci].id = comp_def.id; new_entity->entityComponents[ci].ptr = obj; } g_entityContextManager.entityTable[id] = new_entity;//! return new_entity; } void destroyEntity(hUuid_t entity_id) { auto* entity = findEntity(entity_id); hcAssert(entity); for (auto& i : entity->entityComponents) { i.ptr->componentDestruct(i.ptr); } g_entityContextManager.entityTable.erase(g_entityContextManager.entityTable.find(entity_id)); delete entity; } void destroyEntity(hEntity* entity) { hcAssert(entity); hUuid_t entity_id = entity->getEntityID(); for (auto& i : entity->entityComponents) { i.ptr->componentDestruct(i.ptr); } g_entityContextManager.entityTable.erase(g_entityContextManager.entityTable.find(entity_id)); delete entity; } hEntity* findEntity(hUuid_t entity_id) { auto it = g_entityContextManager.entityTable.find(entity_id); return it != g_entityContextManager.entityTable.end() ? it->second : nullptr; } void serialiseEntities(hSerialisedEntitiesParameters* in_out_params) { hcAssert(in_out_params); auto& state = in_out_params->engineState; hChar entity_guid_str_buff[64]; for (const auto& i : g_entityContextManager.entityTable) { hUUID::toString(i.first, entity_guid_str_buff, hStaticArraySize(entity_guid_str_buff)); state.add_aliveentityid(entity_guid_str_buff); auto* entity_def = state.add_aliveentities(); auto* entity = i.second; state.set_maxentitycomponentcount(hMax(state.maxentitycomponentcount(), i.second->getComponentCount())); if (in_out_params->includeTransientEntites || !entity->getTransient()) entity->serialise(entity_def, entity_guid_str_buff, *in_out_params); } } void deserialiseEntities(const hSerialisedEntitiesParameters& in_params) { std::vector<hComponentDefinition> components; components.reserve(in_params.engineState.maxentitycomponentcount()); for (hInt i = 0, n = in_params.engineState.aliveentities_size(); i < n; ++i) { auto& entity = in_params.engineState.aliveentities(i); hUuid_t guid = hUUID::fromString(entity.objectguid().c_str(), entity.objectguid().length()); hSize_t totalComponents = entity.components_size(); components.clear(); components.reserve(totalComponents); for (hInt ci = 0, cn = entity.components_size(); ci < cn; ++ci) { hComponentDefinition comp_def; comp_def.typeDefintion = hObjectFactory::getObjectDefinitionFromSerialiserName(entity.components(ci).type_name().c_str()); comp_def.id = entity.components(ci).componentid(); if (comp_def.typeDefintion) { comp_def.marshall = comp_def.typeDefintion->constructMarshall_(); comp_def.marshall->ParseFromString(entity.components(ci).messagedata()); components.push_back(std::move(comp_def)); } } auto* new_entity = hEntityFactory::createEntity(guid, components.data(), components.size()); new_entity->setTransitent(entity.has_transient() ? entity.transient() : false); } } void destroyAllEntities() { for (const auto& i : g_entityContextManager.entityTable) { destroyEntity(i.second); } } } void hEntity::serialise(proto::EntityDefinition* obj, const char* entity_guid_str, const hSerialisedEntitiesParameters& params) const { obj->set_transient(transient); obj->set_friendlyname(friendlyName.c_str()); obj->set_objectguid(entity_guid_str); for (const auto& i : entityComponents) { auto* msg_cntr = obj->add_components(); hObjectMarshall* marshall = i.typeDef->constructMarshall_(); // We could pool these, make them cheaper on memory. msg_cntr->set_type_name(i.typeDef->serialiserName_.c_str()); msg_cntr->set_componentid(i.id); i.typeDef->serialise_(i.ptr, marshall, params); } } }
43.58
157
0.707052
JoJo2nd
082e073c4a0e6203ee39e170ddc5f4e8270d6d2c
926
cpp
C++
Tareas/Tarea #2/Factura.cpp
JDaniel1010/cpp
ef067f3f0109812d7104cd8a21439d1ea5702afa
[ "MIT" ]
null
null
null
Tareas/Tarea #2/Factura.cpp
JDaniel1010/cpp
ef067f3f0109812d7104cd8a21439d1ea5702afa
[ "MIT" ]
null
null
null
Tareas/Tarea #2/Factura.cpp
JDaniel1010/cpp
ef067f3f0109812d7104cd8a21439d1ea5702afa
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main(int argc, char** argv) { double subtotal = 0; double total = 0; double impuesto = 0.15; int descuento = 0; char facturaExenta; double calculoDescuento = 0; double calculoImpuesto = 0; cout << " Ingrese el subtotal de la factura: "; cin >> subtotal; cout << " Ingrese el descuento (0, 10, 15, 20): "; cin >> descuento; cout << " La factura esta exenta? s/n "; cin >> facturaExenta; if ( facturaExenta == 's' || facturaExenta == 'S' ) { calculoDescuento = (subtotal * descuento) / 100; calculoImpuesto = 0; } else { calculoDescuento = (subtotal * descuento) / 100; calculoImpuesto = (subtotal - calculoDescuento) * 0.15; } total = subtotal - calculoDescuento + calculoImpuesto; cout << endl; cout << " El total a pagar es: " << total; return 0; }
23.15
63
0.588553
JDaniel1010
0831e05a3c32abd2ae33c73902806a15beda0125
3,199
cpp
C++
a1022/main.cpp
Ji-Yuhang/pat_cpp
100525878db4119eaa4be25ef192af9a3b9543bd
[ "MIT" ]
null
null
null
a1022/main.cpp
Ji-Yuhang/pat_cpp
100525878db4119eaa4be25ef192af9a3b9543bd
[ "MIT" ]
null
null
null
a1022/main.cpp
Ji-Yuhang/pat_cpp
100525878db4119eaa4be25ef192af9a3b9543bd
[ "MIT" ]
null
null
null
#include <iostream> #include <vector> #include <string> #include <sstream> #include <map> #include <set> #include <algorithm> using namespace std; // 1022 Digital Library struct Book{ string id; string title; string author; vector<string> keys; string publisher; string year; }; //Line #1: the 7-digit ID number; //Line #2: the book title -- a string of no more than 80 characters; //Line #3: the author -- a string of no more than 80 characters; //Line #4: the key words -- each word is a string of no more than 10 characters without any white space, and the keywords are separated by exactly one space; //Line #5: the publisher -- a string of no more than 80 characters; //Line #6: the published year -- a 4-digit number which is in the range [1000, 3000]. int main() { int n,m; string n_str; getline(cin, n_str); n = stoi(n_str); //map<string, Book> books; vector<Book> books; for (int i = 0; i < n; i++){ Book book; getline(cin, book.id); getline(cin, book.title); getline(cin, book.author); string keys_str; getline(cin, keys_str); stringstream ss(keys_str); string key; while(getline(ss, key, ' ')){ book.keys.push_back(key); } getline(cin, book.publisher); getline(cin, book.year); //books[book.id] = book; books.push_back(book); } string m_str; getline(cin, m_str); m = stoi(m_str); vector<pair<int, string> > querys; for (int i = 0; i < m; i++){ string str; getline(cin, str); int type; string query_str; auto index = str.find(':'); type = stoi(str.substr(0, index)); while(str[index] == ':' || isspace(str[index])){ index++; } query_str = str.substr(index); querys.push_back(make_pair(type, query_str)); } map<pair<int, string>, set<string> > result; for (int i = 0; i < books.size(); i++){ Book& book = books[i]; for (auto query : querys){ int type = query.first; string query_str = query.second; if(type == 1 && book.title == query_str){ result[query].insert(book.id); } else if(type == 2 && book.author == query_str){ result[query].insert(book.id); } else if(type == 3 ){ vector<string> keys = book.keys; vector<string>::iterator it = find(keys.begin(), keys.end(), query_str); if (it != keys.end()) result[query].insert(book.id); } else if(type == 4 && book.publisher == query_str){ result[query].insert(book.id); } else if(type == 5 && book.year == query_str){ result[query].insert(book.id); } } } for (auto query : querys){ int type = query.first; string query_str = query.second; cout << type <<": "<< query_str <<"\n"; if (result[query].empty()) cout << "Not Found" <<"\n"; for(auto id: result[query]){ cout << id <<"\n"; } } return 0; }
30.179245
157
0.538918
Ji-Yuhang
0832797a2656e085e8c60dd8f647e1b5ca1e84c9
6,486
hxx
C++
include/itkRSHReconImageFilter.hxx
bloyl/DiffusionImagingTK
0516d32b7b0d41ed161134812746ef02aab000de
[ "Apache-2.0" ]
4
2016-01-09T19:02:28.000Z
2017-07-31T19:41:32.000Z
include/itkRSHReconImageFilter.hxx
bloyl/DiffusionImagingTK
0516d32b7b0d41ed161134812746ef02aab000de
[ "Apache-2.0" ]
null
null
null
include/itkRSHReconImageFilter.hxx
bloyl/DiffusionImagingTK
0516d32b7b0d41ed161134812746ef02aab000de
[ "Apache-2.0" ]
2
2016-08-06T00:58:26.000Z
2019-02-18T01:03:13.000Z
/*========================================================================= * * Copyright Section of Biomedical Image Analysis * University of Pennsylvania * * 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.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef __itkRSHReconImageFilter_hxx_ #define __itkRSHReconImageFilter_hxx_ #include <cmath> #include <itkImageRegionConstIterator.h> #include <itkImageRegionConstIteratorWithIndex.h> #include <itkImageRegionIterator.h> #include <itkArray.h> #include <vnl/vnl_vector.h> #include <itkProgressReporter.h> #include <itkRSHReconImageFilter.h> namespace itk { template< class TDiffusionModelCalculator, unsigned int TImageDimension > RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension > ::RSHReconImageFilter() { // At least 1 inputs is necessary for a vector image. // For images added one at a time we need at least six this->SetNumberOfRequiredInputs( 1 ); m_ImageMask = NULL; //Must be suplied by the user m_DiffusionModelCalculator = NULL; //Must be suplied by the user m_ResidualImage = NULL; m_CalculateResidualImage = false; } template< class TDiffusionModelCalculator, unsigned int TImageDimension > void RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension > ::BeforeThreadedGenerateData() { itkDebugMacro( "RSHReconImageFilter::BeforeThreadedGenerateData ") if ( m_DiffusionModelCalculator.IsNull() ) { itkExceptionMacro( << "Diffusion Calculator Not Set" ); } //Initialize the m_DiffusionModelCalculator // m_DiffusionModelCalculator->InitializeTensorFitting(); m_DiffusionModelCalculator->InitializeRSHFitting(); /** Setup both fscores Image and residuals Image */ //Initialize the residualImage if we are going to calculate it. if (m_CalculateResidualImage) { typename InputImageType::ConstPointer dwiImage = static_cast< const InputImageType * >( this->ProcessObject::GetInput(0) ); m_ResidualImage = ResidualImageType::New(); m_ResidualImage->CopyInformation(this->ProcessObject::GetInput(0)); m_ResidualImage->SetRegions(m_ResidualImage->GetLargestPossibleRegion() ); m_ResidualImage->SetVectorLength( dwiImage->GetNumberOfComponentsPerPixel() ); m_ResidualImage->Allocate(); } itkDebugMacro( "RSHReconImageFilter::BeforeThreadedGenerateData done") } template< class TDiffusionModelCalculator, unsigned int TImageDimension > void RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension > ::ThreadedGenerateData(const OutputImageRegionType& outputRegionForThread, ThreadIdType threadId) { itkDebugMacro( "RSHReconImageFilter::ThreadedGenerateData Begin") //Get inputs and outputs OutputImagePointer outputImage = static_cast< OutputImageType * >(this->ProcessObject::GetOutput(0)); InputImageConstPointer dwiImage = static_cast< const InputImageType * >( this->ProcessObject::GetInput(0) ); //Get the diffusion Calculator DiffusionModelCalculatorConstPointer dtCalc = this->GetDiffusionModelCalculator(); ImageMaskConstPointer mask = this->GetImageMask(); //Generate iterators ImageRegionConstIteratorWithIndex< InputImageType > git(dwiImage, outputRegionForThread ); ImageRegionIterator< OutputImageType > oit(outputImage, outputRegionForThread); ImageRegionIterator< ResidualImageType > res_iter; git.GoToBegin(); oit.GoToBegin(); const unsigned int numberOfGradientImages = dwiImage->GetNumberOfComponentsPerPixel(); //if we are calculateing the Residual set up an iterator... if (m_CalculateResidualImage) { res_iter = ImageRegionIterator< ResidualImageType >( m_ResidualImage, outputRegionForThread); res_iter.GoToBegin(); } //Check is mask had been provided bool hasMask = mask.IsNotNull(); // Support for progress methods/callbacks ProgressReporter progress(this, threadId, outputRegionForThread.GetNumberOfPixels()); //Local variables to check supplied mask. typename InputImageType::IndexType index; typename InputImageType::PointType point; OutputPixelType pixValue; ResidualPixelType residualValue( numberOfGradientImages ); while( !git.IsAtEnd() ) { //Check if the current location is outside of the mask if (hasMask) { index = git.GetIndex(); dwiImage->TransformIndexToPhysicalPoint(index,point); if ( not mask->IsInside(point) ) { //don't compute anything for this pixel oit.Set( NumericTraits<OutputPixelType>::Zero ); ++oit; if (m_CalculateResidualImage) { residualValue.Fill(NumericTraits<typename ResidualPixelType::ComponentType>::Zero); res_iter.Set( residualValue ); ++res_iter; } progress.CompletedPixel(); ++git; // Gradient image iterator } } //Grab the dwi const InputPixelType dwi = static_cast<InputPixelType>(git.Get()); pixValue = dtCalc->ComputeRSH(dwi); ///TODO need to get this from dtCalc... residualValue.Fill(NumericTraits<typename ResidualPixelType::ComponentType>::Zero); oit.Set( pixValue ); ++oit; if (m_CalculateResidualImage) { res_iter.Set( residualValue ); ++res_iter; } progress.CompletedPixel(); ++git; // Gradient image iterator } itkDebugMacro( "RSHReconImageFilter::ThreadedGenerateData done") } template< class TDiffusionModelCalculator, unsigned int TImageDimension > void RSHReconImageFilter< TDiffusionModelCalculator, TImageDimension > ::PrintSelf(std::ostream& os, Indent indent) const { Superclass::PrintSelf(os,indent); os << indent << "m_CalculateResidualImage: " << m_CalculateResidualImage << std::endl; if (m_CalculateResidualImage) { os << indent << "m_ResidualImage: " << std::endl << indent << indent << m_ResidualImage << std::endl; } os << indent << "NEEDS MORE INFO" << std::endl; } } //end Itk namespace #endif
34.136842
110
0.721708
bloyl
0832acd08611e58252d192cd7d9a5636aafd0d2a
10,212
cc
C++
components/download/public/task/task_manager_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
14,668
2015-01-01T01:57:10.000Z
2022-03-31T23:33:32.000Z
components/download/public/task/task_manager_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
86
2015-10-21T13:02:42.000Z
2022-03-14T07:50:50.000Z
components/download/public/task/task_manager_unittest.cc
chromium/chromium
df46e572c3449a4b108d6e02fbe4f6d24cf98381
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
5,941
2015-01-02T11:32:21.000Z
2022-03-31T16:35:46.000Z
// Copyright 2018 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "components/download/public/task/task_manager_impl.h" #include <stdint.h> #include <memory> #include <utility> #include "base/bind.h" #include "base/memory/raw_ptr.h" #include "base/test/test_mock_time_task_runner.h" #include "base/test/test_simple_task_runner.h" #include "base/threading/thread_task_runner_handle.h" #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" namespace download { namespace { class MockTaskScheduler : public TaskScheduler { public: MockTaskScheduler() = default; ~MockTaskScheduler() override = default; // TaskScheduler implementation. MOCK_METHOD6(ScheduleTask, void(DownloadTaskType, bool, bool, int, int64_t, int64_t)); MOCK_METHOD1(CancelTask, void(DownloadTaskType)); }; class MockTaskWaiter { public: MockTaskWaiter() = default; ~MockTaskWaiter() = default; MOCK_METHOD1(TaskFinished, void(bool)); }; class TaskManagerImplTest : public testing::Test { public: TaskManagerImplTest() : task_runner_(new base::TestMockTimeTaskRunner), handle_(task_runner_) { auto scheduler = std::make_unique<MockTaskScheduler>(); task_scheduler_ = scheduler.get(); task_manager_ = std::make_unique<TaskManagerImpl>(std::move(scheduler)); } TaskManagerImplTest(const TaskManagerImplTest&) = delete; TaskManagerImplTest& operator=(const TaskManagerImplTest&) = delete; ~TaskManagerImplTest() override = default; protected: TaskManager::TaskParams CreateTaskParams() { TaskManager::TaskParams params; params.require_unmetered_network = false; params.require_charging = false; params.optimal_battery_percentage = 15; params.window_start_time_seconds = 0; params.window_end_time_seconds = 10; return params; } void ExpectCallToScheduleTask(DownloadTaskType task_type, const TaskManager::TaskParams& params, int call_count) { EXPECT_CALL( *task_scheduler_, ScheduleTask(task_type, params.require_unmetered_network, params.require_charging, params.optimal_battery_percentage, params.window_start_time_seconds, params.window_end_time_seconds)) .Times(call_count); } scoped_refptr<base::TestMockTimeTaskRunner> task_runner_; base::ThreadTaskRunnerHandle handle_; raw_ptr<MockTaskScheduler> task_scheduler_; std::unique_ptr<TaskManagerImpl> task_manager_; }; } // namespace TEST_F(TaskManagerImplTest, ScheduleTask) { auto params = CreateTaskParams(); // Schedule a task. ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 1); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); // Schedule another task with same params. This should be a no-op. ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 0); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); // Schedule another task with different params. This task should override the // already scheduled task. params.optimal_battery_percentage = 20; ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 1); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, UnscheduleTask) { auto params = CreateTaskParams(); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); EXPECT_CALL(*task_scheduler_, CancelTask(DownloadTaskType::DOWNLOAD_TASK)) .Times(1); task_manager_->UnscheduleTask(DownloadTaskType::DOWNLOAD_TASK); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); EXPECT_CALL(*task_scheduler_, CancelTask(DownloadTaskType::DOWNLOAD_TASK)) .Times(1); task_manager_->UnscheduleTask(DownloadTaskType::DOWNLOAD_TASK); // Cancel is called even if we are not aware of scheduling a task. EXPECT_CALL(*task_scheduler_, CancelTask(DownloadTaskType::DOWNLOAD_TASK)) .Times(1); task_manager_->UnscheduleTask(DownloadTaskType::DOWNLOAD_TASK); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, NotifyTaskFinished) { auto params = CreateTaskParams(); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); MockTaskWaiter waiter; auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); EXPECT_CALL(waiter, TaskFinished(false)).Times(1); task_manager_->NotifyTaskFinished(DownloadTaskType::DOWNLOAD_TASK, false); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, DifferentTasksCanBeRunIndependently) { auto params = CreateTaskParams(); ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 1); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); ExpectCallToScheduleTask(DownloadTaskType::CLEANUP_TASK, params, 1); task_manager_->ScheduleTask(DownloadTaskType::CLEANUP_TASK, params); MockTaskWaiter waiter; auto callback1 = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); auto callback2 = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); EXPECT_CALL(waiter, TaskFinished(false)).Times(1); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback1)); task_manager_->NotifyTaskFinished(DownloadTaskType::DOWNLOAD_TASK, false); EXPECT_CALL(waiter, TaskFinished(true)).Times(1); task_manager_->OnStartScheduledTask(DownloadTaskType::CLEANUP_TASK, std::move(callback2)); task_manager_->NotifyTaskFinished(DownloadTaskType::CLEANUP_TASK, true); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, ScheduleTaskWithDifferentParamsWhileRunningTask) { auto params = CreateTaskParams(); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); MockTaskWaiter waiter; auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); params.optimal_battery_percentage = 20; task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 1); EXPECT_CALL(waiter, TaskFinished(false)).Times(1); task_manager_->NotifyTaskFinished(DownloadTaskType::DOWNLOAD_TASK, false); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, ScheduleTaskWithSameParamsWhileRunningTask) { auto params = CreateTaskParams(); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); MockTaskWaiter waiter; auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 0); EXPECT_CALL(waiter, TaskFinished(false)).Times(1); task_manager_->NotifyTaskFinished(DownloadTaskType::DOWNLOAD_TASK, false); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, StopTaskWillClearTheCallback) { auto params = CreateTaskParams(); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); MockTaskWaiter waiter; auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); EXPECT_CALL(waiter, TaskFinished(false)).Times(0); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); task_manager_->OnStopScheduledTask(DownloadTaskType::DOWNLOAD_TASK); task_manager_->NotifyTaskFinished(DownloadTaskType::DOWNLOAD_TASK, false); task_runner_->RunUntilIdle(); } // Verifies that OnStartScheduledTask() can be called without preceding // ScheduleTask() calls. TEST_F(TaskManagerImplTest, StartTaskWithoutPendingParams) { MockTaskWaiter waiter; auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); EXPECT_CALL(waiter, TaskFinished(false)).Times(1); task_manager_->NotifyTaskFinished(DownloadTaskType::DOWNLOAD_TASK, false); task_runner_->RunUntilIdle(); } // Verifies that OnStopScheduledTask() can be called without preceding // ScheduleTask() calls. TEST_F(TaskManagerImplTest, StopTaskWithoutPendingParams) { MockTaskWaiter waiter; EXPECT_CALL(waiter, TaskFinished(false)).Times(0); auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); task_manager_->OnStopScheduledTask(DownloadTaskType::DOWNLOAD_TASK); task_runner_->RunUntilIdle(); } TEST_F(TaskManagerImplTest, StopTaskWillSchedulePendingParams) { auto params = CreateTaskParams(); task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); MockTaskWaiter waiter; auto callback = base::BindOnce(&MockTaskWaiter::TaskFinished, base::Unretained(&waiter)); task_manager_->OnStartScheduledTask(DownloadTaskType::DOWNLOAD_TASK, std::move(callback)); ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 0); params.optimal_battery_percentage = 20; task_manager_->ScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params); ExpectCallToScheduleTask(DownloadTaskType::DOWNLOAD_TASK, params, 1); task_manager_->OnStopScheduledTask(DownloadTaskType::DOWNLOAD_TASK); task_runner_->RunUntilIdle(); } } // namespace download
36.733813
80
0.749608
chromium
083840e8fbd13209fa104b0f4668efe7d663d3a0
472
hpp
C++
src/utils/nd_bool_array.hpp
ut-amrl/pips
1f553dc850f8c27a460f020d91b35c8a18c479bb
[ "MIT" ]
null
null
null
src/utils/nd_bool_array.hpp
ut-amrl/pips
1f553dc850f8c27a460f020d91b35c8a18c479bb
[ "MIT" ]
null
null
null
src/utils/nd_bool_array.hpp
ut-amrl/pips
1f553dc850f8c27a460f020d91b35c8a18c479bb
[ "MIT" ]
null
null
null
// Copyright (c) Jarrett Holtz. All rights reserved. // Licensed under the MIT License. #include <vector> class nd_bool_array { const std::vector<size_t> dims_; std::vector<bool> data_; public: nd_bool_array(const std::vector<size_t>& dims); bool get(const std::vector<size_t>& coords) const; void set(const std::vector<size_t>& coords, bool new_value); size_t size() const; private: size_t coords_to_index(const std::vector<size_t>& coords) const; };
24.842105
66
0.720339
ut-amrl
083b5eb371943035be1536423b5f9d70620737f3
2,133
cpp
C++
tools/export/export.cpp
paulhuggett/pstore2
a0c663d10a2e2713fdf39ecdae1f9c1e96041f5c
[ "Apache-2.0" ]
11
2018-02-02T21:24:49.000Z
2020-12-11T04:06:03.000Z
tools/export/export.cpp
SNSystems/pstore
74e9dd960245d6bfc125af03ed964d8ad660a62d
[ "Apache-2.0" ]
63
2018-02-05T17:24:59.000Z
2022-03-22T17:26:28.000Z
tools/export/export.cpp
paulhuggett/pstore
067be94d87c87fce524c8d76c6f47c347d8f1853
[ "Apache-2.0" ]
5
2020-01-13T22:47:11.000Z
2021-05-14T09:31:15.000Z
//===- tools/export/export.cpp --------------------------------------------===// //* _ * //* _____ ___ __ ___ _ __| |_ * //* / _ \ \/ / '_ \ / _ \| '__| __| * //* | __/> <| |_) | (_) | | | |_ * //* \___/_/\_\ .__/ \___/|_| \__| * //* |_| * //===----------------------------------------------------------------------===// // // Part of the pstore project, under the Apache License v2.0 with LLVM Exceptions. // See https://github.com/SNSystems/pstore/blob/master/LICENSE.txt for license // information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <iostream> #include "pstore/exchange/export.hpp" #include "pstore/core/database.hpp" #include "pstore/command_line/command_line.hpp" using namespace pstore::command_line; namespace { opt<std::string> db_path{positional, usage{"repository"}, desc{"Path of the pstore repository to be exported."}, required}; opt<bool> no_comments{ "no-comments", desc{"Disable embedded comments. (Required for output to be ECMA-404 compliant.)"}, init (false)}; } // end anonymous namespace. #ifdef _WIN32 int _tmain (int argc, TCHAR const * argv[]) { #else int main (int argc, char * argv[]) { #endif int exit_code = EXIT_SUCCESS; PSTORE_TRY { parse_command_line_options (argc, argv, "pstore export utility\n"); pstore::exchange::export_ns::ostream os{stdout}; pstore::database db{db_path.get (), pstore::database::access_mode::read_only}; pstore::exchange::export_ns::emit_database (db, os, !no_comments); os.flush (); } // clang-format off PSTORE_CATCH (std::exception const & ex, { // clang-format on std::cerr << "Error: " << ex.what () << '\n'; exit_code = EXIT_FAILURE; }) // clang-format off PSTORE_CATCH (..., { // clang-format on std::cerr << "Error: an unknown error occurred\n"; exit_code = EXIT_FAILURE; }) return exit_code; }
33.857143
94
0.534459
paulhuggett
083c40e6225df441704e84f55c2af4808fcb9257
1,496
cpp
C++
legacy/tools/dtkDistributedServer/main.cpp
papadop/dtk
5d5bd7234987f01a23fbc6c7414a21c15e1455ab
[ "BSD-3-Clause" ]
null
null
null
legacy/tools/dtkDistributedServer/main.cpp
papadop/dtk
5d5bd7234987f01a23fbc6c7414a21c15e1455ab
[ "BSD-3-Clause" ]
null
null
null
legacy/tools/dtkDistributedServer/main.cpp
papadop/dtk
5d5bd7234987f01a23fbc6c7414a21c15e1455ab
[ "BSD-3-Clause" ]
1
2020-04-21T14:41:52.000Z
2020-04-21T14:41:52.000Z
/* @(#)main.cpp --- * * Author: Nicolas Niclausse * Copyright (C) 2012 - Nicolas Niclausse, Inria. * Created: 2012/04/03 14:41:29 * Version: $Id$ * Last-Updated: mer. avril 25 13:08:30 2012 (+0200) * By: Nicolas Niclausse * Update #: 13 */ /* Commentary: * */ /* Change log: * */ #include <dtkCore> #include <dtkDistributed> #include <dtkLog/dtkLog.h> #include <QtCore> int main(int argc, char **argv) { QCoreApplication application(argc, argv); if(!dtkApplicationArgumentsContain(&application, "--torque") && !dtkApplicationArgumentsContain(&application, "--oar") && !dtkApplicationArgumentsContain(&application, "--ssh")) { qDebug() << "Usage:" << argv[0] << " dtk://server:port [--oar || --torque || --ssh]"; return DTK_SUCCEED; } application.setApplicationName("dtkDistributedServer"); application.setApplicationVersion("0.0.1"); application.setOrganizationName("inria"); application.setOrganizationDomain("fr"); QSettings settings("inria", "dtk"); settings.beginGroup("server"); if (settings.contains("log_level")) dtkLogger::instance().setLevel(settings.value("log_level").toString()); else dtkLogger::instance().setLevel(dtkLog::Debug); dtkLogger::instance().attachFile(dtkLogPath(&application)); dtkDistributedServer server(argc, argv); qDebug() << "server started"; server.run(); int status = application.exec(); return status; }
23.746032
93
0.644385
papadop
083da310246009436e6aa707c20423d5e1019167
7,616
cpp
C++
tests/integration/pipelining_tests/pipeline_recompute_ir_test_2.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
null
null
null
tests/integration/pipelining_tests/pipeline_recompute_ir_test_2.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
null
null
null
tests/integration/pipelining_tests/pipeline_recompute_ir_test_2.cpp
gglin001/popart
3225214343f6d98550b6620e809a3544e8bcbfc6
[ "MIT" ]
null
null
null
// Copyright (c) 2019 Graphcore Ltd. All rights reserved. #define BOOST_TEST_MODULE PipelineRecomputeIrTest2 #include <memory> #include "pipeline_recompute_string.hpp" #include <boost/test/unit_test.hpp> #include <filereader.hpp> #include <popart/builder.hpp> #include <popart/dataflow.hpp> #include <popart/graph.hpp> #include <popart/ir.hpp> #include <popart/op/identity.hpp> #include <popart/op/ipucopy.hpp> #include <popart/op/l1.hpp> #include <popart/op/nll.hpp> #include <popart/op/restore.hpp> #include <popart/op/stash.hpp> #include <popart/sgd.hpp> #include <popart/tensor.hpp> #include <popart/tensordata.hpp> #include <popart/testdevice.hpp> BOOST_AUTO_TEST_CASE(PipelineRecomputeIrTest2) { bool withLogging = true; using namespace popart; enum class NlType { Sin, Sigmoid }; auto test = [withLogging](NlType nlt, bool recomp) { auto builder = Builder::create(); auto aiOnnx = builder->aiOnnxOpset9(); auto aiGraphcore = builder->aiGraphcoreOpset1(); TensorInfo info{"FLOAT", std::vector<int64_t>{8, 4}}; std::vector<float> wVals(4 * 8, 1.0f); ConstVoidData wData = {wVals.data(), info}; auto input1 = builder->addInputTensor(info); auto w1 = builder->addInitializedInputTensor(wData); auto act = aiOnnx.add({input1, w1}); auto getPipe = [nlt, &aiOnnx, &aiGraphcore](TensorId act, VGraphId vgid) { // >-------- [8,4] --------------------------------------- // / \ | // slice left slice right | // scale scale | // [6,4] [6,4]-------- | // | \ | // | / \ // / \ / \ | // / \ / \ // / \ slice left slice right | // slice left slice right scale scale // scale scale [4,4] [4,4] // [4,4] [4,4] | | | // | | postnl postnl // postnl postnl | / // \ / | / // \ / | / | // \ / matmul // matmul / // | sigmoid // sigmoid / // \ | | // ------------- cat [8,4] ----------> add // | | // | sigmoid // | | // -------------------> add // | // --> // where postnl is either sin or sigmoid // The difference between sin and sigmoid, is that the // gradients require the input and output, respectively auto postnl = [&aiOnnx, nlt](TensorId id) { if (nlt == NlType::Sigmoid) { return aiOnnx.sigmoid({id}); } else { return aiOnnx.sin({id}); } }; (void)vgid; auto actIn = act; auto act0 = aiOnnx.slice({act}, {6, 4}, {0, 0}, {0, 1}); act0 = aiGraphcore.scale({act0}, 0.6); auto act1 = aiOnnx.slice({act}, {8, 4}, {2, 0}, {0, 1}); act1 = aiGraphcore.scale({act1}, 0.7); auto act00 = aiOnnx.slice({act0}, {4, 4}, {0, 0}, {0, 1}); act00 = aiGraphcore.scale({act00}, 0.8); act00 = postnl(act00); auto act01 = aiOnnx.slice({act0}, {6, 4}, {2, 0}, {0, 1}); act01 = aiGraphcore.scale({act01}, 0.9); act01 = postnl(act01); auto act10 = aiOnnx.slice({act1}, {4, 4}, {0, 0}, {0, 1}); act10 = aiGraphcore.scale({act10}, 1.1); act10 = postnl(act10); auto act11 = aiOnnx.slice({act1}, {6, 4}, {2, 0}, {0, 1}); act11 = aiGraphcore.scale({act11}, 1.2); act11 = postnl(act11); act0 = aiOnnx.matmul({act00, act01}); act0 = aiOnnx.sigmoid({act0}); act1 = aiOnnx.matmul({act10, act11}); act1 = aiOnnx.sigmoid({act1}); auto cat = aiOnnx.concat({act0, act1}, 0); act = aiOnnx.add({cat, actIn}); act = aiOnnx.sigmoid({act}); act = aiOnnx.add({act, cat}); return act; }; act = getPipe(act, 0); act = getPipe(act, 1); act = getPipe(act, 2); act = getPipe(act, 3); auto l1 = builder->aiGraphcoreOpset1().l1loss({act}, 0.1); auto proto = builder->getModelProto(); auto modelProto = io::getModelFromString(proto); auto dataFlow = DataFlow(100, {{act, AnchorReturnType("All")}}); SessionOptions userOptions; userOptions.virtualGraphMode = VirtualGraphMode::Auto; userOptions.enableOutlining = false; userOptions.enablePipelining = true; if (recomp) { userOptions.autoRecomputation = RecomputationType::Standard; } constexpr int64_t nIpus{4}; std::map<std::string, std::string> deviceOpts{ {"numIPUs", std::to_string(nIpus)}}; auto optimizer = ConstSGD(0.01); auto device = createTestDevice(TEST_TARGET, nIpus); Patterns patterns(PatternsLevel::Default); patterns.enableMatMulOp(false); patterns.enableMatMulLhsGradOp(false); patterns.enableMatMulRhsGradOp(false); Ir ir; ir.prepare({modelProto, InputShapeInfo(), dataFlow, l1, &optimizer, *device, userOptions, patterns}); auto sched = ir.getMainGraph().getOpSchedule({}, RequireOptimalSchedule::Yes); std::vector<int64_t> stashIpus(nIpus, 0); for (auto op : sched) { if (dynamic_cast<StashOp *>(op)) { ++stashIpus[op->getVirtualGraphId()]; } // Backwards pass Ops must not be Recompute if (op->fromLoss == PathFromLoss::Yes) { BOOST_CHECK(op->settings.recomputeType == RecomputeType::Checkpoint); } } for (auto ipu = 0; ipu < nIpus - 1; ++ipu) { if (nlt == NlType::Sigmoid && recomp == false) { BOOST_CHECK(stashIpus[ipu] == 7); } else if (nlt == NlType::Sigmoid && recomp == true) { // Two of the sigmoid outputs will be recomputed BOOST_CHECK(stashIpus[ipu] == 5); } } if (withLogging) { std::array<std::stringstream, nIpus> sss; pipeline_recompute_util::fillLogStreams(sss, sched); for (int64_t ipu = 0; ipu < nIpus; ++ipu) { std::cout << "On IPU " << ipu << std::endl; std::cout << sss[ipu].str() << "\n\n" << std::endl; } } }; // Assumptions made in this test: // - The auto-sharder will put 1 of the above pipes on each IPU. // - Sin grad requires Sin's input and Sigmoid grad requires Sigmoid's output test(NlType::Sigmoid, true); test(NlType::Sigmoid, false); // testing with NlType::Sin assumes that the Cos for the backwards pass is // always scheduled in the forwards pass, which seems like a bad long-term // assumption. So not testing NlType::Sin }
35.423256
79
0.481749
gglin001
083eb282c9bfcfe896f58fd64a0b9a969b60addd
437
hpp
C++
AddinCfy/utils.hpp
eehlers/QuantLibAddin
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
[ "BSD-3-Clause" ]
5
2016-07-13T14:05:01.000Z
2022-01-24T15:15:17.000Z
AddinCfy/utils.hpp
eehlers/QuantLibAddin
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
[ "BSD-3-Clause" ]
null
null
null
AddinCfy/utils.hpp
eehlers/QuantLibAddin
bcbd9d1c0e7a4f4ce608470c6576d6e772305980
[ "BSD-3-Clause" ]
12
2016-01-28T07:18:28.000Z
2021-11-15T03:48:52.000Z
#ifndef addincfy_utils_hpp #define addincfy_utils_hpp #include <vector> #include "FlyLib/FlyLib_Types.h" #include <rp/property.hpp> namespace QuantLib { class Date; }; std::vector<bool> f6(FLYLIB_OPAQUE); std::vector<long> f2(FLYLIB_OPAQUE); std::vector<double> f1(FLYLIB_OPAQUE); std::vector<std::string> f4(FLYLIB_OPAQUE); std::vector<reposit::property_t> f3(FLYLIB_OPAQUE); std::vector<QuantLib::Date> f5(FLYLIB_OPAQUE); #endif
19.863636
51
0.764302
eehlers
083f7f46147b7fa40de49d41801d7fd0945af81a
1,481
hpp
C++
include/eschaton/eschaton.hpp
ortfero/eschaton
abc1ce77dd96105208a4563edba7550880ca8530
[ "MIT" ]
null
null
null
include/eschaton/eschaton.hpp
ortfero/eschaton
abc1ce77dd96105208a4563edba7550880ca8530
[ "MIT" ]
null
null
null
include/eschaton/eschaton.hpp
ortfero/eschaton
abc1ce77dd96105208a4563edba7550880ca8530
[ "MIT" ]
null
null
null
#pragma once #include <cstdint> #include <chrono> #include <tuple> #ifndef HAS_UNCAUGHT_EXCEPTIONS #define HAS_UNCAUGHT_EXCEPTIONS 1 #endif #include <date/date.h> namespace eschaton { using system_time = std::chrono::system_clock::time_point; using system_duration = std::chrono::system_clock::duration; using time_of_day = date::hh_mm_ss<std::chrono::microseconds>; template<typename D> std::int64_t to(system_time const& tp) noexcept { return std::int64_t(std::chrono::floor<D>(tp.time_since_epoch()).count()); } template<typename D> system_time from(std::int64_t units) noexcept { return system_time{D{units}}; } template<typename D> std::int64_t current() noexcept { return to<D>(std::chrono::system_clock::now()); } template<typename D> std::int64_t elapsed(std::int64_t from) noexcept { return current<D>() - from; } template<class Rep, class Period> bool is_occured(system_time const& tp, std::chrono::duration<Rep, Period> const& tod) noexcept { namespace chr = std::chrono; auto const daypoint = chr::floor<date::days>(tp); return chr::floor<chr::duration<Rep, Period>>(tp - daypoint) == tod; } template<typename D> std::tuple<date::year_month_day, date::hh_mm_ss<D>> to_ymd_hms(system_time const& tp) { namespace chr = std::chrono; namespace dt = date; auto const dp = chr::floor<dt::days>(tp); dt::year_month_day const ymd{dp}; dt::hh_mm_ss<D> const tod{chr::floor<D>(tp - dp)}; return {ymd, tod}; } } // eschaton
25.534483
91
0.713032
ortfero
08422fbda571158a4d48978ee6f2f69cc524da80
26,750
cpp
C++
lib/Greenspun/Interpreter.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
lib/Greenspun/Interpreter.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
lib/Greenspun/Interpreter.cpp
LLcat1217/arangodb
67c51272915699e0a489e1f8d9da786f4226221a
[ "Apache-2.0" ]
null
null
null
//////////////////////////////////////////////////////////////////////////////// /// DISCLAIMER /// /// Copyright 2014-2022 ArangoDB GmbH, Cologne, Germany /// Copyright 2004-2014 triAGENS 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 Heiko Kernbach /// @author Lars Maier /// @author Markus Pfeiffer //////////////////////////////////////////////////////////////////////////////// #include "Interpreter.h" #include "Greenspun/lib/DateTime.h" #include "Greenspun/lib/Dicts.h" #include "Greenspun/lib/Lists.h" #include "Greenspun/lib/Math.h" #include "Greenspun/lib/Strings.h" #include "Primitives.h" #include <iostream> #include <numeric> #include <sstream> #include <Basics/VelocyPackHelper.h> #include <velocypack/Iterator.h> namespace { int calc_levenshtein(std::string const& lhs, std::string const& rhs) { int const lhsLength = static_cast<int>(lhs.size()); int const rhsLength = static_cast<int>(rhs.size()); int* col = new int[lhsLength + 1]; int start = 1; // fill with initial values std::iota(col + start, col + lhsLength + 1, start); for (int x = start; x <= rhsLength; ++x) { col[0] = x; int last = x - start; for (int y = start; y <= lhsLength; ++y) { int const save = col[y]; col[y] = (std::min)({ col[y] + 1, // deletion col[y - 1] + 1, // insertion last + (lhs[y - 1] == rhs[x - 1] ? 0 : 1) // substitution }); last = save; } } // fetch final value int result = col[lhsLength]; // free memory delete[] col; return result; } } // namespace using namespace arangodb::velocypack; namespace arangodb::greenspun { void InitMachine(Machine& m) { RegisterAllPrimitives(m); RegisterAllDateTimeFunctions(m); RegisterAllMathFunctions(m); RegisterAllStringFunctions(m); RegisterAllListFunctions(m); RegisterAllDictFunctions(m); } EvalResult Apply(Machine& ctx, std::string const& function, VPackSlice const params, VPackBuilder& result) { return ctx.applyFunction(function, params, result); } EvalResult SpecialIf(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { for (auto iter = paramIterator; iter.valid(); ++iter) { auto pair = *iter; if (!pair.isArray() || pair.length() != 2) { return EvalError("in case " + std::to_string(iter.index()) + ", expected pair, found: " + pair.toJson()); } auto&& [cond, body] = arangodb::basics::VelocyPackHelper::unpackTuple<VPackSlice, VPackSlice>( pair); VPackBuilder condResult; { StackFrameGuard<StackFrameGuardMode::KEEP_SCOPE> guard(ctx); auto res = Evaluate(ctx, cond, condResult); if (!res) { return res.mapError([&](EvalError& err) { err.wrapMessage("in condition " + std::to_string(iter.index())); }); } } if (!condResult.slice().isFalse()) { StackFrameGuard<StackFrameGuardMode::KEEP_SCOPE> guard(ctx); return Evaluate(ctx, body, result).mapError([&](EvalError& err) { err.wrapMessage("in case " + std::to_string(iter.index())); }); } } result.add(VPackSlice::nullSlice()); return {}; } EvalResult SpecialQuote(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { if (!paramIterator.valid()) { return EvalError("quote expects one parameter"); } auto value = *paramIterator++; if (paramIterator.valid()) { return EvalError("Excess elements in quote call"); } result.add(value); return {}; } EvalResult SpecialQuoteSplice(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { if (!result.isOpenArray()) { return EvalError("quote-splice nothing to splice into"); } if (!paramIterator.valid()) { return EvalError("quote expects one parameter"); } auto value = *paramIterator++; if (paramIterator.valid()) { return EvalError("Excess elements in quote call"); } if (!value.isArray()) { return EvalError("Can only splice lists, found: " + value.toJson()); } result.add(VPackArrayIterator(value)); return {}; } EvalResult SpecialCons(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { auto&& [head, list] = arangodb::basics::VelocyPackHelper::unpackTuple<VPackSlice, VPackSlice>( paramIterator); if (paramIterator.valid()) { return EvalError("Excess elements in cons call"); } if (!list.isArray()) { return EvalError("Expected array as second parameter"); } VPackArrayBuilder array(&result); result.add(head); result.add(ArrayIterator(list)); return {}; } EvalResult SpecialAnd(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { for (; paramIterator.valid(); ++paramIterator) { VPackBuilder value; if (auto res = Evaluate(ctx, *paramIterator, value); res.fail()) { return res.mapError([&](EvalError& err) { err.wrapMessage("in case " + std::to_string(paramIterator.index())); }); } if (ValueConsideredFalse(value.slice())) { result.add(VPackSlice::falseSlice()); return {}; } } result.add(VPackValue(true)); return {}; } EvalResult SpecialOr(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { for (; paramIterator.valid(); ++paramIterator) { VPackBuilder value; if (auto res = Evaluate(ctx, *paramIterator, value); res.fail()) { return res.mapError([&](EvalError& err) { err.wrapMessage("in case " + std::to_string(paramIterator.index())); }); } if (ValueConsideredTrue(value.slice())) { result.add(VPackSlice::trueSlice()); return {}; } } result.add(VPackValue(false)); return {}; } EvalResult SpecialSeq(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { VPackBuilder store; if (!paramIterator.valid()) { result.add(VPackSlice::nullSlice()); return {}; } for (; paramIterator.valid(); ++paramIterator) { auto& usedBuilder = std::invoke([&]() -> VPackBuilder& { if (paramIterator.isLast()) { return result; } store.clear(); return store; }); if (auto res = Evaluate(ctx, *paramIterator, usedBuilder); res.fail()) { return res.mapError([&](EvalError& err) { err.wrapMessage("at position " + std::to_string(paramIterator.index())); }); } } return {}; } EvalResult SpecialMatch(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { if (!paramIterator.valid()) { return EvalError("expected at least one argument"); } VPackBuilder proto; if (auto res = Evaluate(ctx, *paramIterator, proto); !res) { return res; } if (!proto.slice().isNumber()) { return EvalError("expected numeric expression in pattern"); } auto pattern = proto.slice().getNumber<double>(); ++paramIterator; for (; paramIterator.valid(); ++paramIterator) { auto pair = *paramIterator; if (!pair.isArray() || pair.length() != 2) { return EvalError("in case " + std::to_string(paramIterator.index()) + ", expected pair, found: " + pair.toJson()); } auto&& [cmp, body] = arangodb::basics::VelocyPackHelper::unpackTuple<VPackSlice, VPackSlice>( pair); VPackBuilder cmpValue; if (auto res = Evaluate(ctx, cmp, cmpValue); !res) { return res.mapError([&](EvalError& err) { err.wrapMessage("in condition " + std::to_string(paramIterator.index() - 1)); }); } if (!cmpValue.slice().isNumber()) { return EvalError("in condition " + std::to_string(paramIterator.index() - 1) + " expected numeric value, found: " + cmpValue.toJson()); } if (pattern == cmpValue.slice().getNumber<double>()) { return Evaluate(ctx, body, result).mapError([&](EvalError& err) { err.wrapMessage("in case " + std::to_string(paramIterator.index() - 1)); }); } } result.add(VPackSlice::nullSlice()); return {}; } EvalResult SpecialForEach(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { if (!paramIterator.valid()) { return EvalError("Expected at least one argument"); } auto lists = *paramIterator++; struct IteratorTriple { std::string_view varName; VPackBuilder value; ArrayIterator iterator; IteratorTriple(std::string_view name, VPackBuilder v) : varName(name), value(std::move(v)), iterator(value.slice()) {} }; std::vector<IteratorTriple> iterators; auto const readIteratorPair = [&](VPackSlice pair) -> EvalResult { if (!pair.isArray() || pair.length() != 2) { return EvalError("Expected pair, found: " + pair.toJson()); } auto&& [var, array] = arangodb::basics::VelocyPackHelper::unpackTuple<VPackSlice, VPackSlice>( pair); if (!var.isString()) { return EvalError("Expected string as first entry, found: " + var.toJson()); } if (!array.isArray()) { return EvalError("Expected array as second entry, found: " + array.toJson()); } VPackBuilder listResult; if (auto res = Evaluate(ctx, array, listResult); res.fail()) { return res; } iterators.emplace_back(var.stringView(), std::move(listResult)); return {}; }; if (!lists.isArray()) { return EvalError("first parameter expected to be list, found: " + lists.toJson()); } for (auto&& pair : VPackArrayIterator(lists)) { if (auto res = readIteratorPair(pair); res.fail()) { return res.mapError([&](EvalError& err) { err.wrapMessage("at position " + std::to_string(paramIterator.index() - 1)); }); } } auto const runIterators = [&](Machine& ctx, std::size_t index, auto next) -> EvalResult { if (index == iterators.size()) { VPackBuilder sink; return SpecialSeq(ctx, paramIterator, sink).mapError([](EvalError& err) { err.wrapMessage("in evaluation of for-statement"); }); } else { auto pair = iterators.at(index); for (auto&& x : pair.iterator) { StackFrameGuard<StackFrameGuardMode::NEW_SCOPE> guard(ctx); ctx.setVariable(std::string{pair.varName}, x); if (auto res = next(ctx, index + 1, next); res.fail()) { return res.mapError([&](EvalError& err) { std::string msg = "with "; msg += pair.varName; msg += " = "; msg += x.toJson(); err.wrapMessage(std::move(msg)); }); } } return {}; } }; result.add(VPackSlice::nullSlice()); return runIterators(ctx, 0, runIterators); } EvalResult Call(Machine& ctx, VPackSlice const functionSlice, ArrayIterator paramIterator, VPackBuilder& result, bool isEvaluateParameter) { VPackBuilder paramBuilder; if (isEvaluateParameter) { VPackArrayBuilder builder(&paramBuilder); for (; paramIterator.valid(); ++paramIterator) { StackFrameGuard<StackFrameGuardMode::KEEP_SCOPE> guard(ctx); if (auto res = Evaluate(ctx, *paramIterator, paramBuilder); !res) { return res.mapError([&](EvalError& err) { err.wrapParameter(functionSlice.copyString(), paramIterator.index()); }); } } } else { VPackArrayBuilder builder(&paramBuilder); paramBuilder.add(paramIterator); } return Apply(ctx, functionSlice.copyString(), paramBuilder.slice(), result); } EvalResult LambdaCall(Machine& ctx, VPackSlice paramNames, VPackSlice captures, ArrayIterator paramIterator, VPackSlice body, VPackBuilder& result, bool isEvaluateParams) { if (!paramNames.isArray()) { return EvalError( "bad lambda format: expected parameter name array, found: " + paramNames.toJson()); } VPackBuilder paramBuilder; if (isEvaluateParams) { VPackArrayBuilder builder(&paramBuilder); for (; paramIterator.valid(); ++paramIterator) { StackFrameGuard<StackFrameGuardMode::KEEP_SCOPE> guard(ctx); if (auto res = Evaluate(ctx, *paramIterator, paramBuilder); !res) { return res.mapError([&](EvalError& err) { err.wrapParameter( "<lambda>" + captures.toJson() + paramNames.toJson(), paramIterator.index()); }); } } } StackFrameGuard<StackFrameGuardMode::NEW_SCOPE_HIDE_PARENT> captureFrameGuard( ctx); for (auto&& pair : ObjectIterator(captures)) { ctx.setVariable(pair.key.copyString(), pair.value); } StackFrameGuard<StackFrameGuardMode::NEW_SCOPE> parameterFrameGuard(ctx); VPackArrayIterator builderIter = (isEvaluateParams ? VPackArrayIterator(paramBuilder.slice()) : paramIterator); for (auto&& paramName : ArrayIterator(paramNames)) { if (!paramName.isString()) { return EvalError( "bad lambda format: expected parameter name (string), found: " + paramName.toJson()); } if (!builderIter.valid()) { return EvalError("lambda expects " + std::to_string(paramNames.length()) + " parameters " + paramNames.toJson() + ", found " + std::to_string(builderIter.index())); } ctx.setVariable(paramName.copyString(), *builderIter); ++builderIter; } return Evaluate(ctx, body, result).mapError([&](EvalError& err) { VPackBuilder foo; { VPackArrayBuilder ab(&foo); foo.add(isEvaluateParams ? VPackArrayIterator(paramBuilder.slice()) : paramIterator); } err.wrapCall("<lambda>" + captures.toJson() + paramNames.toJson(), foo.slice()); }); } EvalResult SpecialLet(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { std::vector<VPackBuilder> store; if (!paramIterator.valid()) { return EvalError("Expected at least one argument"); } auto bindings = *paramIterator++; if (!bindings.isArray()) { return EvalError("Expected list of bindings, found: " + bindings.toJson()); } StackFrame frame( ctx.getAllVariables()); // immer_map does not support transient for (VPackArrayIterator iter(bindings); iter.valid(); ++iter) { auto&& pair = *iter; if (pair.isArray() && pair.length() == 2) { auto nameSlice = pair.at(0); auto valueSlice = pair.at(1); if (!nameSlice.isString()) { return EvalError("expected string as bind name at position " + std::to_string(iter.index()) + ", found: " + nameSlice.toJson()); } auto& builder = store.emplace_back(); if (auto res = Evaluate(ctx, valueSlice, builder); res.fail()) { return res.mapError([&](EvalError& err) { err.wrapMessage("when evaluating value for binding `" + nameSlice.copyString() + "` at position " + std::to_string(iter.index())); }); } if (auto res = frame.setVariable(nameSlice.copyString(), builder.slice()); res.fail()) { return res; } } else { return EvalError("expected pair at position " + std::to_string(iter.index()) + " at list of bindings, found: " + pair.toJson()); } } StackFrameGuard<StackFrameGuardMode::NEW_SCOPE> guard(ctx, std::move(frame)); // Now do a seq evaluation of the remaining parameter return SpecialSeq(ctx, paramIterator, result).mapError([](EvalError& err) { err.wrapMessage("in evaluation of let-statement"); }); } EvalResult Evaluate(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result); EvalResult SpecialQuasiQuoteInternal(Machine& ctx, ArrayIterator other, VPackBuilder& result) { if (other.valid()) { Slice first = *other; if (first.isString() && first.isEqualString("unquote")) { ++other; if (!other.valid() || !other.isLast()) { return EvalError("expected one parameter for unquote"); } return Evaluate(ctx, *other, result); } else if (first.isString() && first.isEqualString("unquote-splice")) { ++other; if (!other.valid() || !other.isLast()) { return EvalError("expected one parameter for unquote"); } VPackBuilder tempResult; if (auto res = Evaluate(ctx, *other, tempResult); res.fail()) { return res; } auto tempSlice = tempResult.slice(); if (tempSlice.isArray()) { result.add(VPackArrayIterator(tempSlice)); } else { result.add(tempSlice); } return {}; } } { VPackArrayBuilder ab(&result); for (; other.valid(); ++other) { auto&& part = *other; if (part.isArray()) { if (auto res = SpecialQuasiQuoteInternal(ctx, VPackArrayIterator(part), result); res.fail()) { return res; } } else { result.add(part); } } } return {}; } EvalResult SpecialQuasiQuote(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { if (!paramIterator.valid()) { return EvalError("quasi-quote expects one parameter"); } auto value = *paramIterator++; if (paramIterator.valid()) { return EvalError("Excess elements in quasi-quote call"); } if (value.isArray()) { return SpecialQuasiQuoteInternal(ctx, ArrayIterator(value), result); } result.add(value); return {}; } EvalResult EvaluateApply(Machine& ctx, VPackSlice const functionSlice, ArrayIterator paramIterator, VPackBuilder& result, bool isEvaluateParameter) { if (functionSlice.isString()) { auto callSpecialForm = [&](auto specialForm) { return specialForm(ctx, paramIterator, result) .mapError([&](EvalError& err) { return err.wrapSpecialForm(functionSlice.copyString()); }); }; // check for special forms if (functionSlice.isEqualString("if")) { return callSpecialForm(SpecialIf); } else if (functionSlice.isEqualString("quote")) { return callSpecialForm(SpecialQuote); } else if (functionSlice.isEqualString("quote-splice")) { return callSpecialForm(SpecialQuoteSplice); } else if (functionSlice.isEqualString("quasi-quote")) { return callSpecialForm(SpecialQuasiQuote); } else if (functionSlice.isEqualString("cons")) { return callSpecialForm(SpecialCons); } else if (functionSlice.isEqualString("and")) { return callSpecialForm(SpecialAnd); } else if (functionSlice.isEqualString("or")) { return callSpecialForm(SpecialOr); } else if (functionSlice.isEqualString("seq")) { return callSpecialForm(SpecialSeq); } else if (functionSlice.isEqualString("match")) { return callSpecialForm(SpecialMatch); } else if (functionSlice.isEqualString("for-each")) { return callSpecialForm(SpecialForEach); } else if (functionSlice.isEqualString("let")) { return callSpecialForm(SpecialLet); } else { return Call(ctx, functionSlice, paramIterator, result, isEvaluateParameter); } } else if (functionSlice.isObject()) { auto body = functionSlice.get("_call"); if (!body.isNone()) { auto params = functionSlice.get("_params"); if (!params.isArray()) { return EvalError("lambda params have to be an array, found: " + params.toJson()); } auto captures = functionSlice.get("_captures"); if (!captures.isObject()) { return EvalError("lambda captures have to be an object, found: " + params.toJson()); } return LambdaCall(ctx, params, captures, paramIterator, body, result, isEvaluateParameter); } } return EvalError("function is not a string, found " + functionSlice.toJson()); } template<typename F> auto exceptionIntoResult(F&& f) -> std::invoke_result_t<F> try { return std::forward<F>(f)(); } catch (std::exception const& e) { return EvalError(std::string{"uncaught exception with message: "} + e.what()); } catch (...) { return EvalError("uncaught exception"); } EvalResult Evaluate(Machine& ctx, ArrayIterator paramIterator, VPackBuilder& result) { return exceptionIntoResult([&]() -> EvalResult { if (!paramIterator.valid()) { return EvalError("empty application"); } VPackBuilder functionBuilder; { StackFrameGuard<StackFrameGuardMode::KEEP_SCOPE> guard(ctx); auto err = Evaluate(ctx, *paramIterator, functionBuilder); if (err.fail()) { return err.mapError( [&](EvalError& err) { err.wrapMessage("in function expression"); }); } } ++paramIterator; VPackSlice functionSlice = functionBuilder.slice(); return EvaluateApply(ctx, functionSlice, paramIterator, result, true); }); } EvalResult Evaluate(Machine& ctx, VPackSlice const slice, VPackBuilder& result) { if (slice.isArray()) { return Evaluate(ctx, ArrayIterator(slice), result); } result.add(slice); return {}; } Machine::Machine() { // Top level variables pushStack(); } EvalResult Machine::getVariable(const std::string& name, VPackBuilder& result) { if (!frames.empty()) { if (auto* iter = frames.back().bindings.find(name); iter) { result.add(*iter); return {}; } } result.add(VPackSlice::nullSlice()); return EvalError("variable `" + name + "` not found"); } EvalResult StackFrame::getVariable(std::string const& name, VPackBuilder& result) const { if (auto* iter = bindings.find(name); iter) { result.add(*iter); return {}; } result.add(VPackSlice::nullSlice()); return EvalError("variable `" + name + "` not found"); } EvalResult StackFrame::setVariable(const std::string& name, VPackSlice value) { if (auto i = bindings.find(name); i) { return EvalError("duplicate variable `" + name + "`"); } bindings = bindings.set(name, value); return {}; } EvalResult Machine::setVariable(std::string const& name, VPackSlice value) { TRI_ASSERT(!frames.empty()); return frames.back().setVariable(name, value); } void Machine::pushStack(bool noParentScope) { frames.emplace_back(noParentScope ? VariableBindings{} : getAllVariables()); } void Machine::emplaceStack(StackFrame sf) { frames.emplace_back(std::move(sf)); } void Machine::popStack() { // Top level variables must not be popped TRI_ASSERT(frames.size() > 1); frames.pop_back(); } EvalResult Machine::setFunction(std::string_view name, function_type&& f) { auto sname = std::string{name}; if (functions.find(sname) != functions.end()) { return EvalError("function `" + sname + "` already registered"); } functions.try_emplace(sname, std::move(f)); return {}; } EvalResult Machine::applyFunction(std::string function, VPackSlice const params, VPackBuilder& result) { TRI_ASSERT(params.isArray()); auto f = functions.find(function); if (f != functions.end()) { return f->second(*this, params, result).mapError([&](EvalError& err) { err.wrapCall(function, params); }); } std::string minFunctionName; int minDistance = std::numeric_limits<int>::max(); for (auto&& [key, value] : functions) { int distance = calc_levenshtein(function, key); if (distance < minDistance) { minFunctionName = key; minDistance = distance; } } return EvalError("function not found `" + function + "`" + (!minFunctionName.empty() ? ", did you mean `" + minFunctionName + "`?" : "")); } VariableBindings Machine::getAllVariables() { if (frames.empty()) { return VariableBindings{}; } else { return frames.back().bindings; } } std::string EvalError::toString() const { std::stringstream ss; struct PrintErrorVisistor { std::stringstream& ss; void operator()(EvalError::CallFrame const& f) { ss << "in function `" << f.function << "` called with ("; bool first = true; for (auto&& s : f.parameter) { if (!first) { ss << ","; } else { first = false; } ss << " `" << s << "`"; } ss << " )" << std::endl; } void operator()(EvalError::SpecialFormFrame const& f) { ss << "when evaluating special form `" << f.specialForm << "`" << std::endl; } void operator()(EvalError::WrapFrame const& f) { ss << f.message << std::endl; } void operator()(EvalError::ParamFrame const& f) { ss << "in function `" << f.function << "` at parameter " << f.offset << std::endl; } }; ss << message << std::endl; for (auto&& f : frames) { std::visit(PrintErrorVisistor{ss}, f); } return ss.str(); } bool ValueConsideredFalse(VPackSlice const value) { return value.isFalse() || value.isNone(); } bool ValueConsideredTrue(VPackSlice const value) { return !ValueConsideredFalse(value); } std::string paramsToString(VPackArrayIterator const iter) { std::stringstream ss; for (auto&& p : iter) { if (p.isString()) { ss << p.stringView(); } else if (p.isNumber()) { ss << p.getNumber<double>(); } else if (p.isBool()) { ss << std::boolalpha << p.getBool(); } else { ss << p.toJson(); } ss << " "; } return ss.str(); } std::string paramsToString(VPackSlice const params) { return paramsToString(VPackArrayIterator(params)); } } // namespace arangodb::greenspun
31.032483
80
0.608037
LLcat1217
084279133dea1dbd01db23f8ca48ac8d9ac4b95a
3,075
cpp
C++
include/Lexer.cpp
Thomilist/math-converter
d0028f5096921fa34e9b4b1ddd086812ec5732f5
[ "MIT" ]
null
null
null
include/Lexer.cpp
Thomilist/math-converter
d0028f5096921fa34e9b4b1ddd086812ec5732f5
[ "MIT" ]
null
null
null
include/Lexer.cpp
Thomilist/math-converter
d0028f5096921fa34e9b4b1ddd086812ec5732f5
[ "MIT" ]
null
null
null
#include "Lexer.hpp" namespace mcon { Lexer::Lexer( std::unique_ptr<CharacterStream> const &a_character_stream, std::unique_ptr<CharacterSet> const &a_character_set ): character_set(a_character_set), character_stream(a_character_stream) { } Lexer::~Lexer() { } void Lexer::Scan() { // Create an initial token to mark the start of the token sequence Token temp_token(TokenType::StartOfStream); // Pair up the character sets and their corresponding token types for easy iteration std::set<std::pair<TokenType, std::set<std::string>*>> character_sets = { {TokenType::EndOfStream, &character_set->end_of_stream}, {TokenType::Whitespace, &character_set->whitespace}, {TokenType::Text, &character_set->letter}, {TokenType::Number, &character_set->number}, {TokenType::Symbol, &character_set->symbol} }; // Main lexing loop while (true) { // Variable to check if the character was appended and therefore recognised bool character_appended = false; // Obtain the current character std::string current_character = character_stream->Peek(0); // Iterate over the character sets for (auto& set : character_sets) { // Attempt to find the current character in a set if (set.second->find(current_character) != set.second->end()) { // If the character type does not correspond to the current token type, // or if the token is of "symbol" type, which should only hold one character, // append the token to the token vector and create a new one of the correct type if (temp_token.type != set.first || temp_token.type == TokenType::Symbol) { tokens.push_back(temp_token); temp_token = Token(set.first); } // Append the current character to the current token character_appended = temp_token.append(character_stream->Consume(0)); // If the current token marks the end of the stream, finish lexing if (temp_token.type == TokenType::EndOfStream) { tokens.push_back(temp_token); return; } } } // Check if the character was not found in any of the character sets if (!character_appended) { // Ignore character and continue... character_stream->Consume(0); // ... or throw exception // throw std::runtime_error("Unknown character."); } } } Token Lexer::Peek(uint8_t a_offset) { } Token Lexer::Consume(uint8_t a_offset) { } }
34.166667
100
0.541138
Thomilist
0842810492eff06872223655a9a0dfdbe6244c76
3,632
cpp
C++
DotNetLibrary/src/Int32Value.cpp
lambertlb/CppTranslator
8d9e94f01a0eb099c224fbd9720a0d060a49bda9
[ "MIT" ]
null
null
null
DotNetLibrary/src/Int32Value.cpp
lambertlb/CppTranslator
8d9e94f01a0eb099c224fbd9720a0d060a49bda9
[ "MIT" ]
null
null
null
DotNetLibrary/src/Int32Value.cpp
lambertlb/CppTranslator
8d9e94f01a0eb099c224fbd9720a0d060a49bda9
[ "MIT" ]
null
null
null
// Copyright (c) 2019 LLambert // // 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, sub-license, 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 "DotnetTypes.h" #include <cwchar> namespace DotnetLibrary { DLL_EXPORT Int32 Int32Value::MaxValue = 2147483647; DLL_EXPORT Int32 Int32Value::MinValue = 0X80000000; Boolean Int32Value::get_AsBoolean() { return value != 0; } Char Int32Value::get_AsChar() { return (Char) value; } Byte Int32Value::get_AsByte() { return (Byte) value; } SByte Int32Value::get_AsSByte() { return (SByte) value; } Int16 Int32Value::get_AsInt16() { return (Int16) value; } UInt16 Int32Value::get_AsUInt16() { return (UInt16) value; } Int32 Int32Value::get_AsInt32() { return (Int32) value; } UInt32 Int32Value::get_AsUInt32() { return (UInt32) value; } Int64 Int32Value::get_AsInt64() { return (Int64) value; } UInt64 Int32Value::get_AsUInt64() { return (UInt64) value; } Single Int32Value::get_AsSingle() { return (Single) value; } Double Int32Value::get_AsDouble() { return (Double) value; } Int32 Int32Value::CompareTo(Int32 valueToCompare) { return value - valueToCompare; } Int32 Int32Value::CompareTo(Object* valueToCompare) { if (valueToCompare == nullptr) { return 1; } if (valueToCompare->GetRawDataType() != Int32Type) { throw new ArgumentException(); } return value - ((Int32Value*) valueToCompare)->value; } bool Int32Value::Equals(Object* valueToCompare) { if (valueToCompare->GetRawDataType() != Int32Type) { return false; } return value == ((Int32Value*) valueToCompare)->value; } bool Int32Value::Equals(Int32 valueToCompare) { return value == valueToCompare; } Int32 Int32Value::FormatString(Char* where, const Int32 whereSize) { #ifdef __MINGW32__ return(swprintf(where, L"%d", value)); #else return (swprintf(where, whereSize, L"%d", value)); #endif } Int32 Int32Value::Parse(String* stringToParse) { UInt64 value = 0; Int32 sign = 0; if (!UInt64Value::TryParseInternal(stringToParse, value, sign)) throw new FormatException(); if (sign > 0 && value > MaxValue) throw new OverflowException(); if (sign < 0 && (Int64) value < MinValue) throw new OverflowException(); return ((Int32) value * sign); } bool Int32Value::TryParse(String* stringToParse, Int32& result) { Boolean goodNumber = true; UInt64 value = 0; Int32 sign = 0; if (!UInt64Value::TryParseInternal(stringToParse, value, sign)) goodNumber = false; if (sign > 0 && value > MaxValue) goodNumber = false; if (sign < 0 && (Int64) value < MinValue) goodNumber = false; result = (Int32) value * sign; return (goodNumber); } }
31.582609
94
0.71696
lambertlb
36b041859da7a7627fafaa9f402e464b40a6cd3e
744
hpp
C++
Sources/etwprof/OS/ETW/ETWSessionCommon.hpp
Donpedro13/etwprof
a9db371ef556d564529c5112c231157d3789292b
[ "MIT" ]
38
2018-06-11T19:09:16.000Z
2022-03-17T04:15:15.000Z
Sources/etwprof/OS/ETW/ETWSessionCommon.hpp
Donpedro13/etwprof
a9db371ef556d564529c5112c231157d3789292b
[ "MIT" ]
12
2018-06-12T20:24:05.000Z
2021-07-31T18:28:48.000Z
Sources/etwprof/OS/ETW/ETWSessionCommon.hpp
Donpedro13/etwprof
a9db371ef556d564529c5112c231157d3789292b
[ "MIT" ]
5
2019-02-23T04:11:03.000Z
2022-03-17T04:15:18.000Z
#ifndef ETWP_ETW_SESSION_COMMON_HPP #define ETWP_ETW_SESSION_COMMON_HPP #include <windows.h> #include <evntrace.h> #include <memory> #include <string> namespace ETWP { bool StopETWSession (TRACEHANDLE hSession, const std::wstring& name, PEVENT_TRACE_PROPERTIES pProperties); bool StartRealTimeETWSession (const std::wstring& name, ULONG logFileMode, ULONG enableFlags, PTRACEHANDLE pHandle, std::unique_ptr<EVENT_TRACE_PROPERTIES>* pPropertiesOut); bool EnableStackCachingForSession (TRACEHANDLE pSession, uint32_t cacheSize, uint32_t bucketCount); } // namespace ETWP #endif // #ifndef ETWP_ETW_SESSION_COMMON_HPP
32.347826
106
0.685484
Donpedro13
36b2393fa5390cb0fefe620a0ab3f3b823039779
535
cpp
C++
testsuite/tests/alldatadisposedlistener_dds1619/dds1619_A_proc1.cpp
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
133
2017-11-09T02:10:00.000Z
2022-03-29T09:45:10.000Z
testsuite/tests/alldatadisposedlistener_dds1619/dds1619_A_proc1.cpp
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
131
2017-11-07T14:48:43.000Z
2022-03-13T15:30:47.000Z
testsuite/tests/alldatadisposedlistener_dds1619/dds1619_A_proc1.cpp
brezillon/opensplice
725ae9d949c83fce1746bd7d8a154b9d0a81fe3e
[ "Apache-2.0" ]
94
2017-11-09T02:26:19.000Z
2022-02-24T06:38:25.000Z
#include "CPPProc1.h" int main (int argc, char *argv[]) { int test_result = 0; // default the process name to exe name CPPProc1 dds1619_A_proc1 ("ccpp_alldatadisposedlistener_dds1619_proc1"); dds1619_A_proc1.set_other_process_name ("ccpp_alldatadisposedlistener_dds1619_proc2"); try { dds1619_A_proc1.init (argc, argv); test_result = dds1619_A_proc1.run (); } catch (...) { test_result = -1; } dds1619_A_proc1.wait_for_termination(); return test_result; }
19.814815
90
0.663551
brezillon
36b242d03dbd8b79c3f56e6b06612b0750f3981b
1,190
cpp
C++
Sorting/quick.cpp
fossabot/Algorithms
53a2abb8e9b47a84ead93f84cbff31352d0f6668
[ "MIT" ]
null
null
null
Sorting/quick.cpp
fossabot/Algorithms
53a2abb8e9b47a84ead93f84cbff31352d0f6668
[ "MIT" ]
null
null
null
Sorting/quick.cpp
fossabot/Algorithms
53a2abb8e9b47a84ead93f84cbff31352d0f6668
[ "MIT" ]
1
2020-04-17T04:55:06.000Z
2020-04-17T04:55:06.000Z
/* Quick Sort = O(n log n) */ #include<iostream> using namespace std; template <typename T> void quick(T arr[],int f,int l){ int left, right, t, pivot = 0; if (f < l) { pivot = f; left = f; right = l; while (left < right) { while (arr[left] <= arr[pivot] && left < l) left++; while (arr[right] > arr[pivot]) right--; if (left < right) { t = arr[left]; arr[left] = arr[right]; arr[right] = t; } } t = arr[pivot]; arr[pivot] = arr[right]; arr[right] = t; quick(arr,f, right - 1); quick(arr,right + 1, l); } } int main(){ int size,*arr; cout<<"\n\tEnter Size of Array : "; cin>>size; arr = new int[size]; //allocate memory for 'size' elements if(arr == nullptr){ cout<<"\n\t\tMemory Error !"; } else{ cout<<"\n\tEnter "<<size<<" Elements : "; for(int i=0;i<size;i++){ cin>>arr[i]; } quick(arr,0,size-1); cout<<"\n\tArray After Quick() : "; for(int i=0;i<size;i++){ cout<<arr[i]<<" "; } } delete[] arr; return 0; }
18.030303
59
0.453782
fossabot
36b55ce1816fe3c54955cef0595b31d4653ca121
2,542
cpp
C++
apps/Quant/quantcontroller.cpp
ekoeppen/RDCL
bc8efd0577f8ee231ebdab1e330dde106ff92b15
[ "BSD-3-Clause" ]
3
2016-01-09T11:40:36.000Z
2018-04-07T18:12:13.000Z
apps/Quant/quantcontroller.cpp
ekoeppen/RDCL
bc8efd0577f8ee231ebdab1e330dde106ff92b15
[ "BSD-3-Clause" ]
null
null
null
apps/Quant/quantcontroller.cpp
ekoeppen/RDCL
bc8efd0577f8ee231ebdab1e330dde106ff92b15
[ "BSD-3-Clause" ]
null
null
null
#include <QFileDialog> #include <QDebug> #include "mainwindow.h" #include "quantcontroller.h" #include "settingsdialog.h" #ifdef Q_WS_WIN #include "quantcontrollerwindows.h" #else #include "quantcontrollerposix.h" #endif QuantController *QuantController::controllerFactory(MainWindow *aMainWindow) { #ifdef Q_WS_WIN return new QuantControllerWindows(aMainWindow); #else return new QuantControllerPosix(aMainWindow); #endif } QuantController::QuantController(MainWindow *aMainWindow) : mainWindow(aMainWindow), settings(NULL) { } QuantController::~QuantController() { if (settings) { delete settings; settings = NULL; } } QString QuantController::selectFile(void) { return QFileDialog::getOpenFileName(mainWindow, tr("Select Package File")); } void QuantController::getInfo(void) { mainWindow->clearOutput(); mainWindow->disableButtons(); QObject::connect(this, SIGNAL(gotNwtOutput(const QString&)), this, SLOT(infoData(const QString&))); QObject::connect(this, SIGNAL(nwtCompleted()), this, SLOT(infoCompleted())); launchNwt(QString("-n")); } void QuantController::install(void) { } void QuantController::uninstall(void) { } void QuantController::sync(void) { } void QuantController::backup(void) { } void QuantController::editSettings(void) { } void QuantController::readSettings(void) { launchNwt(QString("--show-settings")); } void QuantController::saveSettings(const QString& settings) { QTemporaryFile* file = new QTemporaryFile(); QString cmd("--write-settings "); file->open(); cmd += file->fileName(); file->write(settings.toAscii()); file->close(); tempFile = file; QObject::connect(this, SIGNAL(nwtCompleted()), this, SLOT(saveSettingsCompleted())); launchNwt(cmd); } void QuantController::launchSettingsDialog(void) { SettingsDialog settings(this); settings.exec(); } void QuantController::infoData(const QString& data) { mainWindow->addOutput(data); qDebug() << data; } void QuantController::infoCompleted(void) { QObject::disconnect(this, SIGNAL(gotNwtOutput(const QString&))); QObject::disconnect(this, SIGNAL(nwtCompleted())); mainWindow->enableButtons(); } void QuantController::cancel(void) { } void QuantController::saveSettingsCompleted(void) { tempFile->remove(); delete tempFile; QObject::disconnect(this, SLOT(saveSettingsCompleted())); }
21.542373
104
0.684894
ekoeppen
36b64d7611223a2a607e21c7d71612ab1baa01ec
391
cpp
C++
poprithms/poprithms/src/poprithms/memory/chain/logging.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
24
2020-07-06T17:11:30.000Z
2022-01-01T07:39:12.000Z
poprithms/poprithms/src/poprithms/memory/chain/logging.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
null
null
null
poprithms/poprithms/src/poprithms/memory/chain/logging.cpp
graphcore/poprithms
9975a6a343891e3c5f8968a9507261c1185029ed
[ "MIT" ]
2
2020-07-15T12:33:22.000Z
2021-07-27T06:07:16.000Z
// Copyright (c) 2021 Graphcore Ltd. All rights reserved. #include <poprithms/logging/logging.hpp> #include <poprithms/memory/chain/logging.hpp> namespace poprithms { namespace memory { namespace chain { poprithms::logging::Logger &log() { static poprithms::logging::Logger logger("memory::chain"); return logger; } } // namespace chain } // namespace memory } // namespace poprithms
23
60
0.73913
graphcore
36b8f1075415da3e489d32e067cffbcf25828afd
5,438
hpp
C++
src/rule/tile-type.hpp
drelatgithub/mahjong-calc
fee7a938ebbc4952ab703d95c628890a48d5125a
[ "MIT" ]
null
null
null
src/rule/tile-type.hpp
drelatgithub/mahjong-calc
fee7a938ebbc4952ab703d95c628890a48d5125a
[ "MIT" ]
null
null
null
src/rule/tile-type.hpp
drelatgithub/mahjong-calc
fee7a938ebbc4952ab703d95c628890a48d5125a
[ "MIT" ]
null
null
null
#ifndef MAHJCALC_RULE_TILE_TYPE_HPP #define MAHJCALC_RULE_TILE_TYPE_HPP #include <cstdint> #include <type_traits> #include "common.hpp" namespace mahjcalc { constexpr size_t num_tile_types_total = 35; // Including Undefined // Red Doras are not considered here enum class TileType { M1, M2, M3, M4, M5, M6, M7, M8, M9, P1, P2, P3, P4, P5, P6, P7, P8, P9, S1, S2, S3, S4, S5, S6, S7, S8, S9, E, S, W, N, Hk, Ht, Cn, // As in Haku, Hatsu, Chun Undefined }; constexpr auto underlying(TileType p) { return static_cast<std::underlying_type_t<TileType>>(p); } constexpr const char* tile_type_name[] { "1m", "2m", "3m", "4m", "5m", "6m", "7m", "8m", "9m", "1p", "2p", "3p", "4p", "5p", "6p", "7p", "8p", "9p", "1s", "2s", "3s", "4s", "5s", "6s", "7s", "8s", "9s", "E ", "S ", "W ", "N ", "Hk", "Ht", "Cn", "Undefined" }; constexpr auto name(TileType t) { return tile_type_name[underlying(t)]; } enum class TileTypeCat { Man, Pin, Sou, Kazehai, Sangenpai, Undefined }; constexpr TileTypeCat category_of_tile_type[] { // Man TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, TileTypeCat::Man, // Pin TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, TileTypeCat::Pin, // Sou TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, TileTypeCat::Sou, // Kaze TileTypeCat::Kazehai, TileTypeCat::Kazehai, TileTypeCat::Kazehai, TileTypeCat::Kazehai, // Sangen TileTypeCat::Sangenpai, TileTypeCat::Sangenpai, TileTypeCat::Sangenpai, // Undefined TileTypeCat::Undefined }; constexpr TileTypeCat category(size_t tile_type_index) { return category_of_tile_type[tile_type_index]; } constexpr TileTypeCat category(TileType p) { return category(underlying(p)); } constexpr mc_uif8 number_of_tile_type[] { /* Man */ 1, 2, 3, 4, 5, 6, 7, 8, 9, /* Pin */ 1, 2, 3, 4, 5, 6, 7, 8, 9, /* Sou */ 1, 2, 3, 4, 5, 6, 7, 8, 9, /* Kaze */ 0, 0, 0, 0, /* Sangen */ 0, 0, 0, /* Undefined */ 0 }; constexpr mc_uif8 number(TileType p) { return number_of_tile_type[underlying(p)]; } template< mc_uif8 num_players > struct CanStartShuntsu; template<> struct CanStartShuntsu<4> { static constexpr bool value[] { // Man, Pin, Sou true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, false, false, // Kaze false, false, false, false, // Sangen false, false, false, // Undefined false }; }; template<> struct CanStartShuntsu<3> { static constexpr bool value[] { // Man, Pin, Sou false, false, false, false, false, false, false, false, false, true, true, true, true, true, true, true, false, false, true, true, true, true, true, true, true, false, false, // Kaze false, false, false, false, // Sangen false, false, false, // Undefined false }; }; template< typename Rule > constexpr bool can_start_shuntsu(size_t tile_type_index) { return CanStartShuntsu<Rule::num_players>::value[tile_type_index]; } template< typename Rule > constexpr bool can_start_shuntsu(TileType t) { return can_start_shuntsu<Rule>(underlying(t)); } template< mc_uif8 num_players > struct DoraTileType; template<> struct DoraTileType<4> { static constexpr TileType value[] { // Man TileType::M2, TileType::M3, TileType::M4, TileType::M5, TileType::M6, TileType::M7, TileType::M8, TileType::M9, TileType::M1, // Pin TileType::P2, TileType::P3, TileType::P4, TileType::P5, TileType::P6, TileType::P7, TileType::P8, TileType::P9, TileType::P1, // Sou TileType::S2, TileType::S3, TileType::S4, TileType::S5, TileType::S6, TileType::S7, TileType::S8, TileType::S9, TileType::S1, // Kaze TileType::S, TileType::W, TileType::N, TileType::E, // Sangen TileType::Ht, TileType::Cn, TileType::Hk, // Undefined TileType::Undefined }; }; template<> struct DoraTileType<3> { static constexpr TileType value[] { // Man TileType::M9, TileType::Undefined, TileType::Undefined, TileType::Undefined, TileType::Undefined, TileType::Undefined, TileType::Undefined, TileType::Undefined, TileType::M1, // Pin TileType::P2, TileType::P3, TileType::P4, TileType::P5, TileType::P6, TileType::P7, TileType::P8, TileType::P9, TileType::P1, // Sou TileType::S2, TileType::S3, TileType::S4, TileType::S5, TileType::S6, TileType::S7, TileType::S8, TileType::S9, TileType::S1, // Kaze TileType::S, TileType::W, TileType::N, TileType::E, // Sangen TileType::Ht, TileType::Cn, TileType::Hk, // Undefined TileType::Undefined }; }; template< typename Rule > constexpr TileType get_dora_from_indicator(TileType p) { return DoraTileType<Rule::num_players>::value[underlying(p)]; } } // namespace mahjcalc #endif
33.9875
105
0.622839
drelatgithub
36b9a7bef0b30507baeef49c4f709dc360c6f002
1,433
cpp
C++
Tree/Lowestcommonancestor.cpp
Anirban166/GeeksforGeeks
3b0f4a5a5c9476477e5920692258c097b20b64a0
[ "MIT" ]
19
2019-07-22T06:23:36.000Z
2021-09-12T13:01:41.000Z
Tree/Lowestcommonancestor.cpp
Anirban166/GeeksforGeeks
3b0f4a5a5c9476477e5920692258c097b20b64a0
[ "MIT" ]
null
null
null
Tree/Lowestcommonancestor.cpp
Anirban166/GeeksforGeeks
3b0f4a5a5c9476477e5920692258c097b20b64a0
[ "MIT" ]
3
2019-10-10T03:41:06.000Z
2020-05-05T08:27:46.000Z
#include<bits/stdc++.h> using namespace std; struct Node { int data; Node* right; Node* left; Node(int x){ data = x; right = NULL; left = NULL; } }; void insert(Node ** tree, int val) { Node *temp = NULL; if(!(*tree)) { *tree = new Node(val); return; } if(val < (*tree)->data) { insert(&(*tree)->left, val); } else if(val > (*tree)->data) { insert(&(*tree)->right, val); } } Node* LCA(Node *root, int , int ); int main() { int T; cin>>T; while(T--) { Node *root; Node *tmp; root = NULL; int N; cin>>N; for(int i=0;i<N;i++) { int k; cin>>k; insert(&root, k); } int l,r; cin>>l>>r; cout<<LCA(root,l,r)->data<<endl; } } } /*This is a function problem.You only need to complete the function given below*/ /*The structure of a BST Node is as follows: struct Node { int data; Node* right; Node* left; Node(int x){ data = x; right = NULL; left = NULL; } }; */ /*You are required to complete this function*/ Node* LCA(Node *root, int n1, int n2) { if(root==NULL)return NULL; if((n1<root->data)&&(n2<root->data)) return LCA(root->left,n1,n2); if((n1>root->data)&&(n2>root->data)) return LCA(root->right,n1,n2); return root; }
17.47561
81
0.486392
Anirban166
36bc0edc5c1e7019d82cda76f0c173923b325d24
3,249
hh
C++
src/GroupDomain_cube.hh
lucjaulmes/FaultSim-A-Memory-Reliability-Simulator
fac1cee8780c5cb783f2ffcc25682b9e0172b11e
[ "BSD-3-Clause" ]
null
null
null
src/GroupDomain_cube.hh
lucjaulmes/FaultSim-A-Memory-Reliability-Simulator
fac1cee8780c5cb783f2ffcc25682b9e0172b11e
[ "BSD-3-Clause" ]
null
null
null
src/GroupDomain_cube.hh
lucjaulmes/FaultSim-A-Memory-Reliability-Simulator
fac1cee8780c5cb783f2ffcc25682b9e0172b11e
[ "BSD-3-Clause" ]
null
null
null
/* Copyright (c) 2015, Advanced Micro Devices, Inc. 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 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 GROUPDOMAIN_CUBE_HH_ #define GROUPDOMAIN_CUBE_HH_ #include <random> #include "dram_common.hh" #include "GroupDomain.hh" class GroupDomain_cube : public GroupDomain { /** Total Chips in a DIMM */ const uint64_t m_chips; /** Total Banks per Chip */ const uint64_t m_banks; /** The burst length per access, this determines the number of TSVs */ const uint64_t m_burst_size; // 3D memory variables enum { HORIZONTAL, VERTICAL } cube_model; uint64_t cube_data_tsv; uint64_t enable_tsv; bool *tsv_bitmap; uint64_t *tsv_info; /** Address Decoding Depth */ uint64_t m_cube_addr_dec_depth; uint64_t cube_ecc_tsv; uint64_t cube_redun_tsv; uint64_t total_addr_tsv; uint64_t total_tsv; bool tsv_shared_accross_chips; //Static Arrays for ISCA2014 uint64_t tsv_swapped_hc[9]; uint64_t tsv_swapped_vc[8]; uint64_t tsv_swapped_mc[9][8]; double tsv_transientFIT; double tsv_permanentFIT; uint64_t tsv_n_faults_transientFIT_class; uint64_t tsv_n_faults_permanentFIT_class; std::mt19937_64 gen; std::uniform_int_distribution<uint64_t> tsv_dist; void generateTSV(bool transient); GroupDomain_cube(const std::string& name, unsigned cube_model, uint64_t chips, uint64_t banks, uint64_t burst_length, uint64_t cube_addr_dec_depth, uint64_t cube_ecc_tsv, uint64_t cube_redun_tsv, bool enable_tsv); public: static GroupDomain_cube* genModule(Settings &settings, int module_id); ~GroupDomain_cube(); inline void setFIT_TSV(bool isTransient_TSV, double FIT_TSV) { if (isTransient_TSV) tsv_transientFIT = FIT_TSV; else tsv_permanentFIT = FIT_TSV; } inline bool horizontalTSV() { return cube_model == HORIZONTAL; } void addDomain(FaultDomain *domain); }; #endif /* GROUPDOMAIN_CUBE_HH_ */
33.153061
120
0.794398
lucjaulmes
36be82a2802978cfdc56bac2ee6566f55d8d96e8
1,653
hpp
C++
Offer_015/Solution.hpp
DreamWaterFound/JZ_Offer
054fd4bc08d00c94128bce93d30536a918b077bd
[ "WTFPL" ]
null
null
null
Offer_015/Solution.hpp
DreamWaterFound/JZ_Offer
054fd4bc08d00c94128bce93d30536a918b077bd
[ "WTFPL" ]
null
null
null
Offer_015/Solution.hpp
DreamWaterFound/JZ_Offer
054fd4bc08d00c94128bce93d30536a918b077bd
[ "WTFPL" ]
null
null
null
#ifndef __SOLUTION_HPP__ #define __SOLUTION_HPP__ #include "./ListNode.hpp" class Solution { public: ListNode* Merge(ListNode* pHead1, ListNode* pHead2); }; ListNode* Solution::Merge(ListNode* pHead1, ListNode* pHead2) { ListNode *pCurr1=nullptr,*pCurr2=nullptr; ListNode* pHead=nullptr; ListNode* pTmp=nullptr; //首先判断输入的节点是否合法 if(pHead1==nullptr && pHead2==nullptr) return nullptr; else if(pHead1 == nullptr && pHead2) return pHead2; else if(pHead2 == nullptr && pHead1) return pHead1; //首先是初始化的问题,如果只有头节点? pCurr1=pHead1; pCurr2=pHead2; //确定头指针 if(pCurr1->val <= pCurr2->val) { pHead=pCurr1; } else { pHead=pCurr2; } //先不考虑链表结束的问题 while(pCurr1 && pCurr2) { if(pCurr1->val <= pCurr2->val) { //这里其实合并了两种情况下的操作 //NOTICE 技巧:在逻辑或表达式中,如果第一个条件满足,那么就不会执行第二个表达式的计算和判断 if(pCurr1->next == nullptr || pCurr2->val <= pCurr1->next->val) { pTmp=pCurr1->next; pCurr1->next=pCurr2; pCurr1=pTmp; } else { pCurr1=pCurr1->next; } } else { if( pCurr2->next == nullptr || pCurr1->val <= pCurr2->next->val) { pTmp=pCurr2->next; pCurr2->next=pCurr1; pCurr2=pTmp; } else { pCurr2=pCurr2->next; } } } //如果有一个链表已经空了,说明后面的部分都不用管了 return pHead; } #endif //__SOLUTION_HPP__
19.678571
76
0.502722
DreamWaterFound
36c0ce9909908ed6fa6008b8453fd840eee0cc2e
3,434
cc
C++
mindspore/ccsrc/minddata/dataset/kernels/ir/vision/random_posterize_ir.cc
Greatpanc/mindspore_zhb
c2511f7d6815b9232ac4427e27e2c132ed03e0d9
[ "Apache-2.0" ]
1
2021-11-19T14:21:45.000Z
2021-11-19T14:21:45.000Z
mindspore/ccsrc/minddata/dataset/kernels/ir/vision/random_posterize_ir.cc
LaiYongqiang/mindspore
1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e
[ "Apache-2.0" ]
null
null
null
mindspore/ccsrc/minddata/dataset/kernels/ir/vision/random_posterize_ir.cc
LaiYongqiang/mindspore
1b7a38ccd86b55af50a0ea55c7f2f43813ed3e0e
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2020-2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <algorithm> #include "minddata/dataset/kernels/ir/vision/random_posterize_ir.h" #ifndef ENABLE_ANDROID #include "minddata/dataset/kernels/image/random_posterize_op.h" #endif #include "minddata/dataset/kernels/ir/validators.h" namespace mindspore { namespace dataset { namespace vision { #ifndef ENABLE_ANDROID // RandomPosterizeOperation RandomPosterizeOperation::RandomPosterizeOperation(const std::vector<uint8_t> &bit_range) : TensorOperation(true), bit_range_(bit_range) {} RandomPosterizeOperation::~RandomPosterizeOperation() = default; std::string RandomPosterizeOperation::Name() const { return kRandomPosterizeOperation; } Status RandomPosterizeOperation::ValidateParams() { constexpr size_t dimension_zero = 0; constexpr size_t dimension_one = 1; constexpr size_t size_two = 2; constexpr uint8_t kMinimumBitValue = 1; constexpr uint8_t kMaximumBitValue = 8; if (bit_range_.size() != size_two) { std::string err_msg = "RandomPosterize: bit_range needs to be of size 2 but is of size: " + std::to_string(bit_range_.size()); LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg); } if (bit_range_[dimension_zero] < kMinimumBitValue || bit_range_[dimension_zero] > kMaximumBitValue) { std::string err_msg = "RandomPosterize: min_bit value is out of range [1-8]: " + std::to_string(bit_range_[dimension_zero]); LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg); } if (bit_range_[dimension_one] < kMinimumBitValue || bit_range_[dimension_one] > kMaximumBitValue) { std::string err_msg = "RandomPosterize: max_bit value is out of range [1-8]: " + std::to_string(bit_range_[dimension_one]); LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg); } if (bit_range_[dimension_one] < bit_range_[dimension_zero]) { std::string err_msg = "RandomPosterize: max_bit value is less than min_bit: max =" + std::to_string(bit_range_[dimension_one]) + ", min = " + std::to_string(bit_range_[dimension_zero]); LOG_AND_RETURN_STATUS_SYNTAX_ERROR(err_msg); } return Status::OK(); } std::shared_ptr<TensorOp> RandomPosterizeOperation::Build() { std::shared_ptr<RandomPosterizeOp> tensor_op = std::make_shared<RandomPosterizeOp>(bit_range_); return tensor_op; } Status RandomPosterizeOperation::to_json(nlohmann::json *out_json) { (*out_json)["bits"] = bit_range_; return Status::OK(); } Status RandomPosterizeOperation::from_json(nlohmann::json op_params, std::shared_ptr<TensorOperation> *operation) { CHECK_FAIL_RETURN_UNEXPECTED(op_params.find("bits") != op_params.end(), "Failed to find bits"); std::vector<uint8_t> bit_range = op_params["bits"]; *operation = std::make_shared<vision::RandomPosterizeOperation>(bit_range); return Status::OK(); } #endif } // namespace vision } // namespace dataset } // namespace mindspore
38.155556
115
0.752475
Greatpanc
36c244ea95072445e74ec096bb4a6e850690009c
1,704
cpp
C++
src/Viewer/tst/Segment2DSubsegments.unit.cpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/Viewer/tst/Segment2DSubsegments.unit.cpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
src/Viewer/tst/Segment2DSubsegments.unit.cpp
bakonyidani/Windows-CalcEngine
afa4c4a9f88199c6206af8bc994a073931fc8b91
[ "BSD-3-Clause-LBNL" ]
null
null
null
#include <memory> #include <gtest/gtest.h> #include <memory> #include <vector> #include "WCEViewer.hpp" using namespace Viewer; class TestSegment2DSubsegments : public testing::Test { protected: virtual void SetUp() { } }; TEST_F( TestSegment2DSubsegments, Segment2DTest1 ) { SCOPED_TRACE( "Begin Test: Segment 2D - subsegments creation." ); std::shared_ptr< CPoint2D > aStartPoint = std::make_shared< CPoint2D >( 0, 0 ); std::shared_ptr< CPoint2D > aEndPoint = std::make_shared< CPoint2D >( 10, 10 ); CViewSegment2D aSegment = CViewSegment2D( aStartPoint, aEndPoint ); std::shared_ptr< std::vector< std::shared_ptr< CViewSegment2D > > > aSubSegments = aSegment.subSegments( 4 ); std::vector< double > correctStartX = { 0, 2.5, 5, 7.5 }; std::vector< double > correctEndX = { 2.5, 5, 7.5, 10 }; std::vector< double > correctStartY = { 0, 2.5, 5, 7.5 }; std::vector< double > correctEndY = { 2.5, 5, 7.5, 10 }; size_t i = 0; for ( std::shared_ptr< CViewSegment2D > aSubSegment : *aSubSegments ) { double xStart = aSubSegment->startPoint()->x(); double xEnd = aSubSegment->endPoint()->x(); double yStart = aSubSegment->startPoint()->y(); double yEnd = aSubSegment->endPoint()->y(); EXPECT_NEAR( correctStartX[ i ], xStart, 1e-6 ); EXPECT_NEAR( correctEndX[ i ], xEnd, 1e-6 ); EXPECT_NEAR( correctStartY[ i ], yStart, 1e-6 ); EXPECT_NEAR( correctEndY[ i ], yEnd, 1e-6 ); ++i; } // std::shared_ptr< CSegment2D > aNormal = aSegment.getNormal(); // std::shared_ptr< const CPoint2D > aNormalPoint = aNormal->endPoint(); // double x = aNormalPoint->x(); // double y = aNormalPoint->y(); // // EXPECT_NEAR( 0, x, 1e-6 ); // EXPECT_NEAR( -1, y, 1e-6 ); }
27.934426
110
0.664906
bakonyidani
36c782d74d02e318d5d59adadd72f5184bddca75
1,782
cpp
C++
Upsolving/URI/1025.cpp
rodrigoAMF7/Notebook---Maratonas
06b38197a042bfbd27b20f707493e0a19fda7234
[ "MIT" ]
4
2019-01-25T21:22:55.000Z
2019-03-20T18:04:01.000Z
Upsolving/URI/1025.cpp
rodrigoAMF/competitive-programming-notebook
06b38197a042bfbd27b20f707493e0a19fda7234
[ "MIT" ]
null
null
null
Upsolving/URI/1025.cpp
rodrigoAMF/competitive-programming-notebook
06b38197a042bfbd27b20f707493e0a19fda7234
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> // Nome de Tipos typedef long long ll; typedef unsigned long long ull; typedef long double ld; // Valores #define INF 0x3F3F3F3F #define LINF 0x3F3F3F3F3F3F3F3FLL #define DINF (double)1e+30 #define EPS (double)1e-9 #define RAD(x) (double)(x*PI)/180.0 #define PCT(x,y) (double)x*100.0/y // Atalhos #define F first #define S second #define PB push_back #define MP make_pair #define forn(i, n) for ( int i = 0; i < (n); ++i ) using namespace std; int binarySearch(vector<int> arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l)/2; // If the element is present at the middle // itself if (arr.at(mid) == x) return mid+1; // If element is smaller than mid, then // it can only be present in left subarray if (arr.at(mid) > x) return binarySearch(arr, l, mid-1, x); // Else the element can only be present // in right subarray return binarySearch(arr, mid+1, r, x); } // We reach here when element is not // present in array return -1; } int linearSearch(vector<int> arr, int x){ forn(i, arr.size()){ if(arr.at(i) == x) return i+1; } return -1; } int n, q; int main(){ int contador = 1; while(true){ cin >> n >> q; if(n == q && n == 0) break; cout << "CASE# " << contador << ":" << endl; vector<int> numeros; forn(i, n){ int aux; cin >> aux; numeros.push_back(aux); } sort(numeros.begin(), numeros.end()); forn(i, q){ int aux, resultado; cin >> aux; resultado = linearSearch(numeros, aux); if(resultado != -1){ cout << aux << " found at " << resultado << endl; }else{ cout << aux << " not found" << endl; } } contador++; } return 0; }
19.16129
54
0.570146
rodrigoAMF7
36cd25104f9088fa3393b26bea86e5da5d2075f7
329
cpp
C++
livro/cap_03 (finalizado)/02_ano_bissexto.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
livro/cap_03 (finalizado)/02_ano_bissexto.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
livro/cap_03 (finalizado)/02_ano_bissexto.cpp
sueyvid/Atividade_de_programacao_cpp
691941fc94125eddd4e5466862d5a1fe04dfb520
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; int main() { int ano; bool eh_bissexto; cin >> ano; eh_bissexto = ((ano%4 == 0 && !(ano%100 == 0)) || ano%400 == 0); if(eh_bissexto){ cout << ano << " e um ano bissexto"; } else{ cout << ano << " nao e um ano bissexto"; } return 0; }
17.315789
68
0.50152
sueyvid
36d33c3f56c0b85d99f4e4671415bd696e0d01d1
19,061
cpp
C++
source/loonyland/endgame.cpp
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
source/loonyland/endgame.cpp
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
source/loonyland/endgame.cpp
AutomaticFrenzy/HamSandwich
d991c840fd688cb2541806a33f152ba9aac41a1a
[ "MIT" ]
null
null
null
#include "endgame.h" #include "display.h" #include "player.h" #include "fireworks.h" #include "badge.h" #include "bossbash.h" #include "highscore.h" #include "log.h" char rankText[][32]={ "Scalliwag", "Cad", "Ruffian", "Weenie", "Peon", "Peasant", "Citizen", "Upper Crust", "High Class", "Knight", "Baron", "Duke", "Lord", "King", "Emperor", "Hero", "Superhero", "Ultrahero", "Uberhero", "Gyro Sandwich", "Jamulio", }; #define ST_NUM 0 #define ST_TIME 1 #define ST_PCT 2 #define ST_BASH 3 // bash power level typedef struct stat_t { byte type; char name[32]; int val; char xtra[32]; int points; int curPts; byte visible; } stat_t; // `stat` is a thing that might already exist depending on header coincidences #define stat loonystat stat_t stat[16]; byte numStats; byte curStat; int totalScore; void Commaize(char *s,int n) { char s2[8]; byte zero; s[0]='\0'; zero=0; if(n<0) { n=-n; s[0]='-'; s[1]='\0'; } if(n>=1000000) { zero=1; sprintf(s2,"%d,",n/1000000); strcat(s,s2); } if(n>=1000) { if(!zero) sprintf(s2,"%d,",(n/1000)%1000); else sprintf(s2,"%03d,",(n/1000)%1000); strcat(s,s2); zero=1; } if(!zero) sprintf(s2,"%d",n%1000); else sprintf(s2,"%03d",n%1000); strcat(s,s2); } void ShowStat(byte w,int x,int y) { char s[88]; Print(x,y,stat[w].name,0,0); switch(stat[w].type) { case ST_NUM: // straight number Commaize(s,stat[w].val); RightPrint(x+210,y,s,0,0); break; case ST_TIME: // time sprintf(s,"%02d:%02d:%02d", stat[w].val/(30*60*60),(stat[w].val/(30*60))%60,(stat[w].val/30)%60); RightPrint(x+210,y,s,0,0); break; case ST_PCT: // percent sprintf(s,"%0.2f%%",(float)stat[w].val/10000); RightPrint(x+210,y,s,0,0); break; case ST_BASH: // bash power level RightPrint(x+210,y,BashPowerName(stat[w].val),0,0); break; } Print(x+220,y,stat[w].xtra,0,0); Print(x+360,y,"=",0,0); Commaize(s,stat[w].curPts); RightPrint(x+500,y,s,0,0); } byte GetRank(int score) { if(score<0) score=0; score/=100000; if(score>20) score=20; return (byte)score; } int GetTimePoints(dword time,dword best,dword bestScore,dword betterPts,dword worsePts) { int result; if(time<=best) { result=bestScore+(betterPts*(best-time))/30; } else { result=bestScore-(worsePts*(time-best))/30; } return result; } void InitEndGame(void) { int i; DBG("InitEndGame"); for(i=0;i<16;i++) { stat[i].curPts=0; stat[i].type=ST_NUM; stat[i].val=0; stat[i].visible=0; stat[i].xtra[0]='\0'; stat[i].name[0]='\0'; } switch(player.worldNum) { case WORLD_NORMAL: case WORLD_REMIX: case WORLD_RANDOMIZER: numStats=10; // percent done strcpy(stat[0].name,"Complete"); stat[0].val=(int)(CalcPercent(&player)*10000); strcpy(stat[0].xtra,"x10,000"); stat[0].points=(int)(CalcPercent(&player)*10000); stat[0].type=ST_PCT; // time to finish if((player.cheatsOn&PC_HARDCORE) && player.hearts==0) { strcpy(stat[1].name,"Time"); stat[1].val=player.timeToFinish; stat[1].points=0; stat[1].type=ST_TIME; strcpy(stat[1].xtra,"(failed)"); } else { strcpy(stat[1].name,"Time"); stat[1].val=player.timeToFinish; stat[1].points=GetTimePoints(player.timeToFinish,30*60*60*8,1000000,200,200); stat[1].type=ST_TIME; strcpy(stat[1].xtra,"(8:00:00 par)"); } // monster points strcpy(stat[2].name,"Monster Pts"); stat[2].val=player.monsterPoints; strcpy(stat[2].xtra,"x10"); stat[2].points=player.monsterPoints*10; // gems collected strcpy(stat[3].name,"Gems Obtained"); stat[3].val=player.gemsGotten; strcpy(stat[3].xtra,"x10"); stat[3].points=player.gemsGotten*10; // best combo strcpy(stat[4].name,"Best Combo"); stat[4].val=player.bestCombo; strcpy(stat[4].xtra,"x5,000"); stat[4].points=player.bestCombo*5000; // badguys killed strcpy(stat[5].name,"Badguys Slain"); stat[5].val=player.guysKilled; strcpy(stat[5].xtra,"x5"); stat[5].points=player.guysKilled*5; // shotsFired strcpy(stat[6].name,"Shots Fired"); stat[6].val=player.shotsFired; strcpy(stat[6].xtra,"x-10"); stat[6].points=player.shotsFired*-10; // special shots fired strcpy(stat[7].name,"Special Shots"); stat[7].val=player.specialShotsFired; strcpy(stat[7].xtra,"x-10"); stat[7].points=player.specialShotsFired*-10; // number of saves strcpy(stat[8].name,"Saved Games"); stat[8].val=player.numSaves; strcpy(stat[8].xtra,"x-5,000"); stat[8].points=player.numSaves*-5000; // hits taken strcpy(stat[9].name,"Hits Taken"); stat[9].val=player.hitsTaken; strcpy(stat[9].xtra,"x-500"); stat[9].points=player.hitsTaken*-500; break; case WORLD_SURVIVAL: numStats=9; // level reached strcpy(stat[0].name,"Level Passed"); stat[0].val=player.numSaves; strcpy(stat[0].xtra,"x50,000"); stat[0].points=player.numSaves*50000; if(player.cheatsOn&PC_INFSURV) { strcpy(stat[0].xtra,"x25,000"); stat[0].points=player.numSaves*25000; } // time to finish if(player.cheatsOn&PC_INFSURV) { strcpy(stat[1].name,"Time"); stat[1].val=player.timeToFinish; stat[1].points=0; stat[1].type=ST_TIME; strcpy(stat[1].xtra,"(no points)"); } else { if(player.numSaves==25) { strcpy(stat[1].name,"Time"); stat[1].val=player.timeToFinish; stat[1].points=GetTimePoints(player.timeToFinish,30*60*10,1000000,1000,1000); stat[1].type=ST_TIME; strcpy(stat[1].xtra,"(10:00 par)"); } else { strcpy(stat[1].name,"Time"); stat[1].val=player.timeToFinish; stat[1].points=-1000000; stat[1].type=ST_TIME; strcpy(stat[1].xtra,"(failed)"); } } // monster points strcpy(stat[2].name,"Monster Pts"); stat[2].val=player.monsterPoints; strcpy(stat[2].xtra,"x100"); stat[2].points=player.monsterPoints*100; if(player.cheatsOn&PC_INFSURV) { stat[2].val=player.monsterPoints; strcpy(stat[2].xtra,"x500"); stat[2].points=player.monsterPoints*500; } // gems collected strcpy(stat[3].name,"Gems Obtained"); stat[3].val=player.gemsGotten; strcpy(stat[3].xtra,"x100"); stat[3].points=player.gemsGotten*100; // best combo strcpy(stat[4].name,"Best Combo"); stat[4].val=player.bestCombo; strcpy(stat[4].xtra,"x10,000"); stat[4].points=player.bestCombo*10000; // badguys killed strcpy(stat[5].name,"Badguys Slain"); stat[5].val=player.guysKilled; strcpy(stat[5].xtra,"x500"); stat[5].points=player.guysKilled*500; // shotsFired strcpy(stat[6].name,"Shots Fired"); stat[6].val=player.shotsFired; strcpy(stat[6].xtra,"x-500"); stat[6].points=player.shotsFired*-500; // special shots fired strcpy(stat[7].name,"Special Shots"); stat[7].val=player.specialShotsFired; strcpy(stat[7].xtra,"x-200"); stat[7].points=player.specialShotsFired*-200; // hits taken strcpy(stat[8].name,"Hits Taken"); stat[8].val=player.hitsTaken; strcpy(stat[8].xtra,"x-5000"); stat[8].points=player.hitsTaken*-5000; if(player.cheatsOn&PC_INFSURV) { stat[8].val=player.hitsTaken; strcpy(stat[8].xtra,"x-2000"); stat[8].points=player.hitsTaken*-2000; } break; case WORLD_BOWLING: numStats=5; // points strcpy(stat[0].name,"Points"); stat[0].val=player.monsterPoints; strcpy(stat[0].xtra,"x10,000"); stat[0].points=player.monsterPoints*10000; // strikes strcpy(stat[1].name,"Strikes"); stat[1].val=player.gemsGotten; strcpy(stat[1].xtra,"x100,000"); stat[1].points=player.gemsGotten*100000; // gutterballs strcpy(stat[2].name,"Gutterballs"); stat[2].val=player.specialShotsFired; strcpy(stat[2].xtra,"x-50,000"); stat[2].points=player.specialShotsFired*-50000; // used balls strcpy(stat[3].name,"Balls Used"); stat[3].val=player.shotsFired; strcpy(stat[3].xtra,"x-50,000"); stat[3].points=player.shotsFired*-50000; // time strcpy(stat[4].name,"Time"); stat[4].val=player.timeToFinish; stat[4].points=GetTimePoints(player.timeToFinish,30*60*2,100000,5000,1000); stat[4].type=ST_TIME; strcpy(stat[4].xtra,"(2:00 par)"); break; case WORLD_LOONYBALL: numStats=5; // points strcpy(stat[0].name,"Points"); stat[0].val=(player.gemsGotten-5000); strcpy(stat[0].xtra,"x100,000"); stat[0].points=(player.gemsGotten-5000)*100000; // strikes strcpy(stat[1].name,"Penalties"); stat[1].val=player.numSaves; strcpy(stat[1].xtra,"x-100,000"); stat[1].points=player.numSaves*-100000; // gutterballs strcpy(stat[2].name,"Games Played"); stat[2].val=player.levelNum; strcpy(stat[2].xtra,"x250,000"); stat[2].points=player.levelNum*250000; // used balls strcpy(stat[3].name,"Out Of Bounds"); player.guysKilled=player.oob; stat[3].val=player.guysKilled; strcpy(stat[3].xtra,"x-100,000"); stat[3].points=player.guysKilled*-100000; // time if(player.levelNum==5) { strcpy(stat[4].name,"Time"); stat[4].val=player.timeToFinish; stat[4].points=GetTimePoints(player.timeToFinish,30*60*6,100000,10000,10000); stat[4].type=ST_TIME; strcpy(stat[4].xtra,"(6:00 par)"); } else { strcpy(stat[4].name,"Time"); stat[4].val=player.timeToFinish; stat[4].points=-100000; stat[4].type=ST_TIME; strcpy(stat[4].xtra,"(failed)"); } break; case WORLD_BOSSBASH: DBG("BB-Setup"); numStats=3; // time DBG("BB1"); if(player.hearts>0) { DBG("BB2"); strcpy(stat[0].name,"Time"); stat[0].val=player.timeToFinish; DBG("BB3"); i=player.numSaves-30*30*BashPower(); if(i<0) i=10*30; DBG("BB4"); stat[0].points=GetTimePoints(player.timeToFinish,i,2000000,40000,10000); stat[0].type=ST_TIME; DBG("BB5"); sprintf(stat[0].xtra,"(%d:%02d par)",i/(30*60),(i/30)%60); } else { strcpy(stat[0].name,"Time"); stat[0].val=player.timeToFinish; stat[0].points=0; stat[0].type=ST_TIME; strcpy(stat[0].xtra,"(failed)"); } DBG("BB6"); // power level strcpy(stat[1].name,"Power"); stat[1].val=BashPower(); DBG("BB7"); strcpy(stat[1].xtra,"x-100,000"); stat[1].points=BashPower()*-100000; stat[1].type=ST_BASH; DBG("BB8"); // hits taken strcpy(stat[2].name,"Hits Taken"); stat[2].val=player.hitsTaken; DBG("BB9"); strcpy(stat[2].xtra,"x-100,000"); stat[2].points=player.hitsTaken*-100000; DBG("BB10"); break; } DBG("BB-Setup2"); player.rank=0; curStat=0; totalScore=0; GetDisplayMGL()->LastKeyPressed(); DBG("BB-Setup3"); GetTaps(); DBG("BB-Setup4"); InitFireworks(); DBG("BB-Setup5"); } void RenderFinalScore(int x,int y,MGLDraw *mgl) { char s[48]; DrawBox(x,y,x+500,y+1,31); RightPrint(x+340,y+5,"Total Score",0,0); Commaize(s,totalScore); RightPrint(x+500,y+5,s,0,0); RightPrint(x+340,y+35,"Rank",0,0); sprintf(s,"%s",rankText[player.rank]); RightPrint(x+500,y+35,s,0,0); } void ShowHighScore(int x,int y,int score,byte on,byte col,MGLDraw *mgl) { char s[48]; Commaize(s,score); if(on) { PrintGlow(x,y,s,0,0); PrintGlow(x+120,y,rankText[GetRank(score)],0,0); } else { PrintColor(x,y,s,col,-10,0); PrintColor(x+120,y,rankText[GetRank(score)],col,-10,0); } } void ShowScoreStats(int x,int y,highScore_t *me,MGLDraw *mgl) { char s[32]; switch(me->mode) { case WORLD_NORMAL: case WORLD_REMIX: case WORLD_RANDOMIZER: PrintGlow(x,y,"Percent Done",0,0); sprintf(s,"%2.1f%%",(float)me->spclValue/FIXAMT); RightPrintGlow(x+250,y,s,0,0); PrintGlow(x,y+25,"Time",0,0); sprintf(s,"%02d:%02d:%02d", me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60); RightPrintGlow(x+250,y+25,s,0,0); PrintGlow(x,y+25*2,"Monster Pts",0,0); sprintf(s,"%d",me->monsterPoints); RightPrintGlow(x+250,y+25*2,s,0,0); PrintGlow(x,y+25*3,"Gems Collected",0,0); sprintf(s,"%d",me->gemsGotten); RightPrintGlow(x+250,y+25*3,s,0,0); PrintGlow(x,y+25*4,"Best Combo",0,0); sprintf(s,"%d",me->bestCombo); RightPrintGlow(x+250,y+25*4,s,0,0); PrintGlow(x,y+25*5,"Badguys Slain",0,0); sprintf(s,"%d",me->guysKilled); RightPrintGlow(x+250,y+25*5,s,0,0); PrintGlow(x,y+25*6,"Shots Fired",0,0); sprintf(s,"%d",me->shotsFired); RightPrintGlow(x+250,y+25*6,s,0,0); PrintGlow(x,y+25*7,"Special Shots",0,0); sprintf(s,"%d",me->specialShotsFired); RightPrintGlow(x+250,y+25*7,s,0,0); PrintGlow(x,y+25*8,"Saved Games",0,0); sprintf(s,"%d",me->numSaves); RightPrintGlow(x+250,y+25*8,s,0,0); PrintGlow(x,y+25*9,"Hits Taken",0,0); sprintf(s,"%d",me->hitsTaken); RightPrintGlow(x+250,y+25*9,s,0,0); break; case WORLD_SURVIVAL: case WORLD_INFSURV: PrintGlow(x,y+25*0,"Level Passed",0,0); sprintf(s,"%d",me->numSaves); RightPrintGlow(x+250,y+25*0,s,0,0); PrintGlow(x,y+25,"Time",0,0); sprintf(s,"%02d:%02d:%02d", me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60); RightPrintGlow(x+250,y+25,s,0,0); PrintGlow(x,y+25*2,"Monster Pts",0,0); sprintf(s,"%d",me->monsterPoints); RightPrintGlow(x+250,y+25*2,s,0,0); PrintGlow(x,y+25*3,"Gems Collected",0,0); sprintf(s,"%d",me->gemsGotten); RightPrintGlow(x+250,y+25*3,s,0,0); PrintGlow(x,y+25*4,"Best Combo",0,0); sprintf(s,"%d",me->bestCombo); RightPrintGlow(x+250,y+25*4,s,0,0); PrintGlow(x,y+25*5,"Badguys Slain",0,0); sprintf(s,"%d",me->guysKilled); RightPrintGlow(x+250,y+25*5,s,0,0); PrintGlow(x,y+25*6,"Shots Fired",0,0); sprintf(s,"%d",me->shotsFired); RightPrintGlow(x+250,y+25*6,s,0,0); PrintGlow(x,y+25*7,"Special Shots",0,0); sprintf(s,"%d",me->specialShotsFired); RightPrintGlow(x+250,y+25*7,s,0,0); PrintGlow(x,y+25*8,"Hits Taken",0,0); sprintf(s,"%d",me->hitsTaken); RightPrintGlow(x+250,y+25*8,s,0,0); break; case WORLD_BOWLING: PrintGlow(x,y+25*0,"Points",0,0); sprintf(s,"%d",me->monsterPoints); RightPrintGlow(x+250,y+25*0,s,0,0); PrintGlow(x,y+25*1,"Strikes",0,0); sprintf(s,"%d",me->gemsGotten); RightPrintGlow(x+250,y+25*1,s,0,0); PrintGlow(x,y+25*2,"Gutterballs",0,0); sprintf(s,"%d",me->specialShotsFired); RightPrintGlow(x+250,y+25*2,s,0,0); PrintGlow(x,y+25*3,"Balls Used",0,0); sprintf(s,"%d",me->shotsFired); RightPrintGlow(x+250,y+25*3,s,0,0); PrintGlow(x,y+25*4,"Time",0,0); sprintf(s,"%02d:%02d:%02d", me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60); RightPrintGlow(x+250,y+25*4,s,0,0); break; case WORLD_LOONYBALL: PrintGlow(x,y+25*0,"Points",0,0); sprintf(s,"%d",me->gemsGotten-5000); RightPrintGlow(x+250,y+25*0,s,0,0); PrintGlow(x,y+25*1,"Penalties",0,0); sprintf(s,"%d",me->numSaves); RightPrintGlow(x+250,y+25*1,s,0,0); PrintGlow(x,y+25*2,"Games Played",0,0); sprintf(s,"%d",me->bestCombo); RightPrintGlow(x+250,y+25*2,s,0,0); PrintGlow(x,y+25*3,"Out Of Bounds",0,0); sprintf(s,"%d",me->guysKilled); RightPrintGlow(x+250,y+25*3,s,0,0); PrintGlow(x,y+25*4,"Time",0,0); sprintf(s,"%02d:%02d:%02d", me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60); RightPrintGlow(x+250,y+25*4,s,0,0); break; case WORLD_BOSSBASH: //PrintGlow(x,y,"Victim",0,0); PrintGlow(x,y,BashLevelName(me->spclValue),0,0); PrintGlow(x,y+25*1,"Time",0,0); sprintf(s,"%02d:%02d:%02d", me->time/(30*60*60),(me->time/(30*60))%60,(me->time/30)%60); RightPrintGlow(x+250,y+25*1,s,0,0); PrintGlow(x,y+25*2,"Power Level",0,0); sprintf(s,"%d",me->gemsGotten); RightPrintGlow(x+250,y+25*2,BashPowerName((byte)me->gemsGotten),0,0); PrintGlow(x,y+25*3,"Hits Taken",0,0); sprintf(s,"%d",me->hitsTaken); RightPrintGlow(x+250,y+25*3,s,0,0); break; } } void RenderEndGame(MGLDraw *mgl) { int i,x,y; DBG("RenderEndGame"); mgl->ClearScreen(); RenderFireworks(mgl); CenterPrint(320,2,"Final Score",0,2); x=75; y=70; i=0; while(i<numStats) { if(stat[i].visible) ShowStat(i,x,y); y+=30; i++; } y+=10; RenderFinalScore(x,y,mgl); } byte UpdateEndGame(int *lastTime,MGLDraw *mgl) { int i; char c; byte t; static byte fwClock; DBG("UpdateEndGame"); if(*lastTime>TIME_PER_FRAME*30) *lastTime=TIME_PER_FRAME*30; while(*lastTime>=TIME_PER_FRAME) { c=mgl->LastKeyPressed(); t=GetTaps(); if(curStat<numStats) { MakeNormalSound(SND_MENUCLICK); // make this stat visible stat[curStat].visible=1; // start cranking up the points if(stat[curStat].curPts<stat[curStat].points) { if(stat[curStat].points-stat[curStat].curPts>100000) { stat[curStat].curPts+=10000; totalScore+=10000; } else if(stat[curStat].points-stat[curStat].curPts>1000) { stat[curStat].curPts+=1000; totalScore+=1000; } else if(stat[curStat].points-stat[curStat].curPts>100) { stat[curStat].curPts+=100; totalScore+=100; } else if(stat[curStat].points-stat[curStat].curPts>10) { stat[curStat].curPts+=10; totalScore+=10; } else { stat[curStat].curPts++; totalScore++; } } else if(stat[curStat].curPts>stat[curStat].points) { if(stat[curStat].points-stat[curStat].curPts<-100000) { stat[curStat].curPts-=10000; totalScore-=10000; } else if(stat[curStat].points-stat[curStat].curPts<-1000) { stat[curStat].curPts-=1000; totalScore-=1000; } else if(stat[curStat].points-stat[curStat].curPts<-100) { stat[curStat].curPts-=100; totalScore-=100; } else if(stat[curStat].points-stat[curStat].curPts<-10) { stat[curStat].curPts-=10; totalScore-=10; } else { stat[curStat].curPts--; totalScore--; } } else curStat++; if(c || t) { curStat=numStats; totalScore=0; for(i=0;i<numStats;i++) { stat[i].visible=1; stat[i].curPts=stat[i].points; totalScore+=stat[i].curPts; } } } else if(c || t) { return 0; } player.rank=GetRank(totalScore); if(fwClock>0) { fwClock--; if(fwClock==0) { if(Random(100)<player.rank) LaunchShell(player.rank); } } else fwClock=10; UpdateFireworks(); *lastTime-=TIME_PER_FRAME; } return 1; } TASK(void) EndGameTally(MGLDraw *mgl) { byte b; int lastTime=1; dword now,then,hangon; highScore_t hs; DBG("EndGameTally"); EndClock(); hangon=TimeLength(); now=timeGetTime(); InitEndGame(); DBG("SurvivedInitEndGame"); b=1; while(b==1) { lastTime+=TimeLength(); StartClock(); b=UpdateEndGame(&lastTime,mgl); RenderEndGame(mgl); AWAIT mgl->Flip(); if(!mgl->Process()) { CO_RETURN; } EndClock(); } DBG("ExitEndGameTally1"); ExitFireworks(); DBG("ExitEndGameTally2"); then=timeGetTime(); ResetClock(hangon); //AddGarbageTime(then-now); MakeHighScore(&hs,totalScore); AWAIT CheckForHighScore(hs); if(totalScore>=10000000) EarnBadge(BADGE_SCORE); BadgeCheck(BE_ENDGAME,0,curMap); DBG("ExitEndGameTally3"); }
23.132282
87
0.627826
AutomaticFrenzy
36d3addf468bd4ab1783ae5b617426e702dfe553
3,039
hh
C++
src/clang_tu.hh
SysRay/ccls
daac41a52be06822f2c93407bd5ff8384b0329f8
[ "Apache-2.0" ]
null
null
null
src/clang_tu.hh
SysRay/ccls
daac41a52be06822f2c93407bd5ff8384b0329f8
[ "Apache-2.0" ]
null
null
null
src/clang_tu.hh
SysRay/ccls
daac41a52be06822f2c93407bd5ff8384b0329f8
[ "Apache-2.0" ]
null
null
null
/* Copyright 2017-2018 ccls 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. ==============================================================================*/ #pragma once #include "log.hh" #include "position.hh" #include "utils.hh" #include <clang/Basic/FileManager.h> #include <clang/Basic/LangOptions.h> #include <clang/Basic/SourceManager.h> #include <clang/Frontend/CompilerInstance.h> #include <clang/Lex/PreprocessorOptions.h> #include <mutex> #include <unordered_map> #if LLVM_VERSION_MAJOR < 8 // D52783 Lift VFS from clang to llvm namespace llvm { namespace vfs = clang::vfs; } #endif namespace ccls { std::string PathFromFileEntry(const clang::FileEntry &file); Range FromCharSourceRange(const clang::SourceManager &SM, const clang::LangOptions &LangOpts, clang::CharSourceRange R, llvm::sys::fs::UniqueID *UniqueID = nullptr); Range FromCharRange(const clang::SourceManager &SM, const clang::LangOptions &LangOpts, clang::SourceRange R, llvm::sys::fs::UniqueID *UniqueID = nullptr); Range FromTokenRange(const clang::SourceManager &SM, const clang::LangOptions &LangOpts, clang::SourceRange R, llvm::sys::fs::UniqueID *UniqueID = nullptr); Range FromTokenRangeDefaulted(const clang::SourceManager &SM, const clang::LangOptions &Lang, clang::SourceRange R, const clang::FileEntry *FE, Range range); std::unique_ptr<clang::CompilerInvocation> BuildCompilerInvocation(const std::string &main, std::vector<const char *> args, llvm::IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS); class SystemFileCacher { std::unordered_map<std::string, std::string> files; std::mutex m_mtx; public: void addFile(std::string const &path) { std::unique_lock lock(m_mtx); if (files.find(path) == files.end()) { auto file = ccls::ReadContent(path); if (file) { files.emplace(std::make_pair(path, *file)); } } } void remapFiles(clang::CompilerInvocation* CI ) { std::unique_lock lock(m_mtx); for (auto &item : files) { CI->getPreprocessorOpts().addRemappedFile( item.first, llvm::MemoryBuffer::getMemBuffer(item.second).release()); } } static SystemFileCacher &getInstance() { static SystemFileCacher inst; return inst; } private: }; const char *ClangBuiltinTypeName(int); } // namespace ccls
32.677419
80
0.654163
SysRay
36d5280e189a823721c5bd19846b120eb11d98ba
12,656
cc
C++
src/game/Strategic/QuestText.cc
FluffyQuack/ja2-stracciatella
59781890986dc5360ed4b148b83836c029121d5f
[ "BSD-Source-Code" ]
346
2016-02-16T11:17:25.000Z
2022-03-28T18:18:14.000Z
src/game/Strategic/QuestText.cc
FluffyQuack/ja2-stracciatella
59781890986dc5360ed4b148b83836c029121d5f
[ "BSD-Source-Code" ]
1,119
2016-02-14T23:19:56.000Z
2022-03-31T21:57:58.000Z
src/game/Strategic/QuestText.cc
FluffyQuack/ja2-stracciatella
59781890986dc5360ed4b148b83836c029121d5f
[ "BSD-Source-Code" ]
90
2016-02-17T22:17:11.000Z
2022-03-12T11:59:56.000Z
#include "Types.h" #include "QuestText.h" #include "Quests.h" const ST::string QuestDescText[] = { "Deliver Letter", "Food Route", "Terrorists", "Kingpin Chalice", "Kingpin Money", "Runaway Joey", "Rescue Maria", "Chitzena Chalice", "Held in Alma", "Interogation", "Hillbilly Problem", //10 "Find Scientist", "Deliver Video Camera", "Blood Cats", "Find Hermit", "Creatures", "Find Chopper Pilot", "Escort SkyRider", "Free Dynamo", "Escort Tourists", "Doreen", //20 "Leather Shop Dream", "Escort Shank", "No 23 Yet", "No 24 Yet", "Kill Deidranna", "No 26 Yet", "No 27 Yet", "No 28 Yet", "No 29 Yet", }; const ST::string FactDescText[] = { "Omerta Liberated", "Drassen Liberated", "Sanmona Liberated", "Cambria Liberated", "Alma Liberated", "Grumm Liberated", "Tixa Liberated", "Chitzena Liberated", "Estoni Liberated", "Balime Liberated", "Orta Liberated", //10 "Meduna Liberated", "Pacos approched", "Fatima Read note", "Fatima Walked away from player", "Dimitri (#60) is dead", "Fatima responded to Dimitri's supprise", "Carlo's exclaimed 'no one moves'", "Fatima described note", "Fatima arrives at final dest", "Dimitri said Fatima has proof", //20 "Miguel overheard conversation", "Miguel asked for letter", "Miguel read note", "Ira comment on Miguel reading note", "Rebels are enemies", "Fatima spoken to before given note", "Start Drassen quest", "Miguel offered Ira", "Pacos hurt/Killed", "Pacos is in A10", //30 "Current Sector is safe", "Bobby R Shpmnt in transit", "Bobby R Shpmnt in Drassen", "33 is TRUE and it arrived within 2 hours", "33 is TRUE 34 is false more then 2 hours", "Player has realized part of shipment is missing", "36 is TRUE and Pablo was injured by player", "Pablo admitted theft", "Pablo returned goods, set 37 false", "Miguel will join team", //40 "Gave some cash to Pablo", "Skyrider is currently under escort", "Skyrider is close to his chopper in Drassen", "Skyrider explained deal", "Player has clicked on Heli in Mapscreen at least once", "NPC is owed money", "Npc is wounded", "Npc was wounded by Player", "Father J.Walker was told of food shortage", "Ira is not in sector", //50 "Ira is doing the talking", "Food quest over", "Pablo stole something from last shpmnt", "Last shipment crashed", "Last shipment went to wrong airport", "24 hours elapsed since notified that shpment went to wrong airport", "Lost package arrived with damaged goods. 56 to False", "Lost package is lost permanently. Turn 56 False", "Next package can (random) be lost", "Next package can(random) be delayed", //60 "Package is medium sized", "Package is largesized", "Doreen has conscience", "Player Spoke to Gordon", "Ira is still npc and in A10-2(hasnt joined)", "Dynamo asked for first aid", "Dynamo can be recruited", "Npc is bleeding", "Shank wnts to join", "NPC is bleeding", //70 "Player Team has head & Carmen in San Mona", "Player Team has head & Carmen in Cambria", "Player Team has head & Carmen in Drassen", "Father is drunk", "Player has wounded mercs within 8 tiles of NPC", "1 & only 1 merc wounded within 8 tiles of NPC", "More then 1 wounded merc within 8 tiles of NPC", "Brenda is in the store ", "Brenda is Dead", "Brenda is at home", //80 "NPC is an enemy", "Speaker Strength >= 84 and < 3 males present", "Speaker Strength >= 84 and at least 3 males present", "Hans lets you see Tony", "Hans is standing on 13523", "Tony isnt available Today", "Female is speaking to NPC", "Player has enjoyed the Brothel", "Carla is available", "Cindy is available", //90 "Bambi is available", "No girls is available", "Player waited for girls", "Player paid right amount of money", "Mercs walked by goon", "More thean 1 merc present within 3 tiles of NPC", "At least 1 merc present withing 3 tiles of NPC", "Kingping expectingh visit from player", "Darren expecting money from player", "Player within 5 tiles and NPC is visible", // 100 "Carmen is in San Mona", "Player Spoke to Carmen", "KingPin knows about stolen money", "Player gave money back to KingPin", "Frank was given the money ( not to buy booze )", "Player was told about KingPin watching fights", "Past club closing time and Darren warned Player. (reset every day)", "Joey is EPC", "Joey is in C5", "Joey is within 5 tiles of Martha(109) in sector G8", //110 "Joey is Dead!", "At least one player merc within 5 tiles of Martha", "Spike is occuping tile 9817", "Angel offered vest", "Angel sold vest", "Maria is EPC", "Maria is EPC and inside leather Shop", "Player wants to buy vest", "Maria rescue was noticed by KingPin goons and Kingpin now enemy", "Angel left deed on counter", //120 "Maria quest over", "Player bandaged NPC today", "Doreen revealed allegiance to Queen", "Pablo should not steal from player", "Player shipment arrived but loyalty to low, so it left", "Helicopter is in working condition", "Player is giving amount of money >= $1000", "Player is giving amount less than $1000", "Waldo agreed to fix helicopter( heli is damaged )", "Helicopter was destroyed", //130 "Waldo told us about heli pilot", "Father told us about Deidranna killing sick people", "Father told us about Chivaldori family", "Father told us about creatures", "Loyalty is OK", "Loyalty is Low", "Loyalty is High", "Player doing poorly", "Player gave valid head to Carmen", "Current sector is G9(Cambria)", //140 "Current sector is C5(SanMona)", "Current sector is C13(Drassen", "Carmen has at least $10,000 on him", "Player has Slay on team for over 48 hours", "Carmen is suspicous about slay", "Slay is in current sector", "Carmen gave us final warning", "Vince has explained that he has to charge", "Vince is expecting cash (reset everyday)", "Player stole some medical supplies once", //150 "Player stole some medical supplies again", "Vince can be recruited", "Vince is currently doctoring", "Vince was recruited", "Slay offered deal", "All terrorists killed", "", "Maria left in wrong sector", "Skyrider left in wrong sector", "Joey left in wrong sector", //160 "John left in wrong sector", "Mary left in wrong sector", "Walter was bribed", "Shank(67) is part of squad but not speaker", "Maddog spoken to", "Jake told us about shank", "Shank(67) is not in secotr", "Bloodcat quest on for more than 2 days", "Effective threat made to Armand", "Queen is DEAD!", //170 "Speaker is with Aim or Aim person on squad within 10 tiles", "Current mine is empty", "Current mine is running out", "Loyalty low in affiliated town (low mine production)", "Creatures invaded current mine", "Player LOST current mine", "Current mine is at FULL production", "Dynamo(66) is Speaker or within 10 tiles of speaker", "Fred told us about creatures", "Matt told us about creatures", //180 "Oswald told us about creatures", "Calvin told us about creatures", "Carl told us about creatures", "Chalice stolen from museam", "John(118) is EPC", "Mary(119) and John (118) are EPC's", "Mary(119) is alive", "Mary(119)is EPC", "Mary(119) is bleeding", "John(118) is alive", //190 "John(118) is bleeding", "John or Mary close to airport in Drassen(B13)", "Mary is Dead", "Miners placed", "Krott planning to shoot player", "Madlab explained his situation", "Madlab expecting a firearm", "Madlab expecting a video camera.", "Item condition is < 70 ", "Madlab complained about bad firearm.", //200 "Madlab complained about bad video camera.", "Robot is ready to go!", "First robot destroyed.", "Madlab given a good camera.", "Robot is ready to go a second time!", "Second robot destroyed.", "Mines explained to player.", "Dynamo (#66) is in sector J9.", "Dynamo (#66) is alive.", "One PC hasn't fought, but is able, and less than 3 fights have occured", //210 "Player receiving mine income from Drassen, Cambria, Alma & Chitzena", "Player has been to K4_b1", "Brewster got to talk while Warden was alive", "Warden (#103) is dead.", "Ernest gave us the guns", "This is the first bartender", "This is the second bartender", "This is the third bartender", "This is the fourth bartender", "Manny is a bartender.", //220 "Nothing is repaired yet (some stuff being worked on, nothing to give player right now)", "Player made purchase from Howard (#125)", "Dave sold vehicle", "Dave's vehicle ready", "Dave expecting cash for car", "Dave has gas. (randomized daily)", "Vehicle is present", "First battle won by player", "Robot recruited and moved", "No club fighting allowed", //230 "Player already fought 3 fights today", "Hans mentioned Joey", "Player is doing better than 50% (Alex's function)", "Player is doing very well (better than 80%)", "Father is drunk and sci-fi option is on", "Micky (#96) is drunk", "Player has attempted to force their way into brothel", "Rat effectively threatened 3 times", "Player paid for two people to enter brothel", "", //240 "", "Player owns 2 towns including omerta", "Player owns 3 towns including omerta",// 243 "Player owns 4 towns including omerta",// 244 "", "", "", "Fact male speaking female present", "Fact hicks married player merc",// 249 "Fact museum open",// 250 "Fact brothel open",// 251 "Fact club open",// 252 "Fact first battle fought",// 253 "Fact first battle being fought",// 254 "Fact kingpin introduced self",// 255 "Fact kingpin not in office",// 256 "Fact dont owe kingpin money",// 257 "Fact pc marrying daryl is flo",// 258 "", "", //260 "Fact npc cowering", // 261, "", "", "Fact top and bottom levels cleared", "Fact top level cleared",// 265 "Fact bottom level cleared",// 266 "Fact need to speak nicely",// 267 "Fact attached item before",// 268 "Fact skyrider ever escorted",// 269 "Fact npc not under fire",// 270 "Fact willis heard about joey rescue",// 271 "Fact willis gives discount",// 272 "Fact hillbillies killed",// 273 "Fact keith out of business", // 274 "Fact mike available to army",// 275 "Fact kingpin can send assassins",// 276 "Fact estoni refuelling possible",// 277 "Fact museum alarm went off",// 278 "", "Fact maddog is speaker", //280, "", "Fact angel mentioned deed", // 282, "Fact iggy available to army",// 283 "Fact pc has conrads recruit opinion",// 284 "", "", "", "", "Fact npc hostile or pissed off", //289, "", //290 "Fact tony in building", //291, "Fact shank speaking", // 292, "Fact doreen alive",// 293 "Fact waldo alive",// 294 "Fact perko alive",// 295 "Fact tony alive",// 296 "", "Fact vince alive",// 298, "Fact jenny alive",// 299 "", //300 "", "Fact arnold alive",// 302, "", "Fact rocket rifle exists",// 304, "", "", "", "", "", "", //310 "", "", "", "", "", "", "", "", "", "", //320 "", "", "", "", "", "", "", "", "", "", //330 "", "", "", "", "", "", "", "", "", "", //340 "", "", "", "", "", "", "", "", "", "", //350 "", "", "", "", "", "", "", "", "", "", //360 "", "", "", "", "", "", "", "", "", "", //370 "", "", "", "", "", "", "", "", "", "", //380 "", "", "", "", "", "", "", "", "", "", //390 "", "", "", "", "", "", "", "", "", "", //400 "", "", "", "", "", "", "", "", "", "", //410 "", "", "", "", "", "", "", "", "", "", //420 "", "", "", "", "", "", "", "", "", "", //430 "", "", "", "", "", "", "", "", "", "", //440 "", "", "", "", "", "", "", "", "", "", //450 "", "", "", "", "", "", "", "", "", "", //460 "", "", "", "", "", "", "", "", "", "", //470 "", "", "", "", "", "", "", "", "", "", //480 "", "", "", "", "", "", "", "", "", "", //490 "", "", "", "", "", "", "", "", "", "", //500 };
21.093333
90
0.591182
FluffyQuack
36d7a391b698a64e5b35e2b5024bc8b651ea9e3e
14,085
cpp
C++
osquery/tables/manual/filesystem.cpp
bowlofstew/osquery
77d4777eedc9a63329ce5dd9a5142eaab1b4cda0
[ "BSD-3-Clause" ]
null
null
null
osquery/tables/manual/filesystem.cpp
bowlofstew/osquery
77d4777eedc9a63329ce5dd9a5142eaab1b4cda0
[ "BSD-3-Clause" ]
null
null
null
osquery/tables/manual/filesystem.cpp
bowlofstew/osquery
77d4777eedc9a63329ce5dd9a5142eaab1b4cda0
[ "BSD-3-Clause" ]
null
null
null
// Copyright 2004-present Facebook. All Rights Reserved. #include "osquery/tables/manual/filesystem.h" #include <string> #include <vector> #include <iostream> #include <cstring> #include <boost/filesystem/operations.hpp> #include <boost/filesystem/path.hpp> namespace fs = boost::filesystem; /* ** Definition of the sqlite3_filesystem object. ** ** The internal representation of an filesystem object is subject ** to change, is not externally visible, and should be used by ** the implementation of filesystem only. This object is opaque ** to users. */ struct sqlite3_filesystem { int n; /* number of elements */ std::vector<std::string> path; /* the full path of a filesystem object */ std::vector<bool> is_file; /* if the filesystem object is a file */ std::vector<bool> is_dir; /* if the filesystem object is a directory */ std::vector<bool> is_link; /* if the filesystem object is a symlink */ }; /* * Objects used internally by the virtual table implementation * * we write "typedef struct x x" here so that we can write "x" later instead of * "stuct x" **/ typedef struct filesystem_vtab filesystem_vtab; typedef struct filesystem_cursor filesystem_cursor; /* * Our virtual table object **/ struct filesystem_vtab { // virtual table implementations will normally subclass this structure to add // additional private and implementation-specific fields sqlite3_vtab base; // to get custom functionality, add our own struct as well sqlite3_filesystem *pContent; }; /* * Our cursor object **/ struct filesystem_cursor { // similarly to sqlite3_vtab, practical implementations will likely subclass // this structure to add additional private fields. sqlite3_vtab_cursor base; // field that will be used to represent the current cursor position int row; // the path that is being queried std::string path; }; /* ** Free an sqlite3_filesystem object. */ static void filesystemFree(sqlite3_filesystem *p) { sqlite3_free(p); } /* * This method releases a connection to a virtual table, just like the * xDisconnect method, and it also destroys the underlying table * implementation. This method undoes the work of xCreate. */ static int filesystemDestroy(sqlite3_vtab *p) { filesystem_vtab *pVtab = (filesystem_vtab *)p; sqlite3_free(pVtab); return SQLITE_OK; } /* ** Table constructor for the filesystem module. */ static int filesystemCreate( sqlite3 *db, /* Database where module is created */ void *pAux, /* clientdata for the module */ int argc, /* Number of arguments */ const char *const *argv, /* Value for all arguments */ sqlite3_vtab **ppVtab, /* Write the new virtual table object here */ char **pzErr /* Put error message text here */ ) { // this will get overwritten if pVtab was successfully allocated. if pVtab // wasn't allocated, it means we have no memory int rc = SQLITE_NOMEM; // allocate the correct amount of memory for your virtual table structure // filesystem_vtab *pVtab = sqlite3_malloc(sizeof(filesystem_vtab)); filesystem_vtab *pVtab = new filesystem_vtab; // if the virtual table structure was successfully allocated if (pVtab) { // overwrite the entire memory that was allocated with zeros memset(pVtab, 0, sizeof(filesystem_vtab)); // the pAux argument is the copy of the client data pointer that was the // fourth argument to the sqlite3_create_module() or // sqlite3_create_module_v2() call that registered the virtual table // module. This sets the pContent value of the virtual table struct to // whatever that value was pVtab->pContent = (sqlite3_filesystem *)pAux; // this interface is called to declare the format (the names and datatypes // of the columns) of the virtual tables they implement const char *create_table_statement = "CREATE TABLE fs(" "path VARCHAR, " "filename VARCHAR, " "is_file INTEGER, " "is_dir INTEGER, " "is_link INTEGER" ")"; rc = sqlite3_declare_vtab(db, create_table_statement); } // cast your virtual table object back to type sqlite3_vtab and assign it to // the address supplied by the function call *ppVtab = (sqlite3_vtab *)pVtab; // if all went well, sqlite3_declare_vtab will have returned SQLITE_OK and // that is what will be returned return rc; } /* ** Open a new cursor on the filesystem table. */ static int filesystemOpen(sqlite3_vtab *pVTab, sqlite3_vtab_cursor **ppCursor) { // this will get overwritten if pVtab was successfully allocated. if pVtab // wasn't allocated, it means we have no memory int rc = SQLITE_NOMEM; // declare a value to be used as the virtual table's cursor filesystem_cursor *pCur; // allocate the correct amount of memory for your virtual table cursor // pCur = sqlite3_malloc(sizeof(filesystem_cursor)); pCur = new filesystem_cursor; // if the cursor was successfully allocated if (pCur) { // overwrite the entire memory that was allocated with zeros memset(pCur, 0, sizeof(filesystem_cursor)); // cast the cursor object back to type sqlite3_vtab_cursor and assign it to // the address that was supplied by the function call *ppCursor = (sqlite3_vtab_cursor *)pCur; // if you've gotten this far, everything succeeded so we can set rc, which // will be used as our return value, to SQLITE_OK rc = SQLITE_OK; } // return the value we set to rc, which can either be SQLITE_OK or // SQLITE_NOMEM return rc; } /* ** Close a filesystem table cursor. */ static int filesystemClose(sqlite3_vtab_cursor *cur) { // the xClose interface accepts a sqlite3_vtab_cursor. if we need to do // something specific to our virtual table to free it, cast it back to // your own cursor type filesystem_cursor *pCur = (filesystem_cursor *)cur; // finally, free the structure using sqlite's built-in memory allocation // function // in C, we would use sqlite3_free(pCur); delete pCur; // return SQLITE_OK because everything succeeded return SQLITE_OK; } /* ** Retrieve a column of data. */ static int filesystemColumn(sqlite3_vtab_cursor *cur, sqlite3_context *ctx, int col) { filesystem_cursor *pCur = (filesystem_cursor *)cur; filesystem_vtab *pVtab = (filesystem_vtab *)cur->pVtab; // return a specific column from a specific row, depending on the state of // the cursor if (pCur->row >= 0 && pCur->row < pVtab->pContent->n) { switch (col) { // path case 0: sqlite3_result_text(ctx, (pCur->path).c_str(), -1, nullptr); break; // filename case 1: sqlite3_result_text( ctx, (pVtab->pContent->path[pCur->row]).c_str(), -1, nullptr); break; // is_file case 2: sqlite3_result_int(ctx, (int)pVtab->pContent->is_file[pCur->row]); break; // is_dir case 3: sqlite3_result_int(ctx, (int)pVtab->pContent->is_dir[pCur->row]); break; // is_link case 4: sqlite3_result_int(ctx, (int)pVtab->pContent->is_link[pCur->row]); break; } } return SQLITE_OK; } /* ** Retrieve the current rowid. */ static int filesystemRowid(sqlite3_vtab_cursor *cur, sqlite_int64 *pRowid) { filesystem_cursor *pCur = (filesystem_cursor *)cur; // return the value of i, which is set to 0 in xFilter and incremented in // xNext *pRowid = pCur->row; return SQLITE_OK; } static int filesystemEof(sqlite3_vtab_cursor *cur) { filesystem_cursor *pCur = (filesystem_cursor *)cur; filesystem_vtab *pVtab = (filesystem_vtab *)cur->pVtab; return pCur->row >= pVtab->pContent->n; } /* ** Advance the cursor to the next row. */ static int filesystemNext(sqlite3_vtab_cursor *cur) { filesystem_cursor *pCur = (filesystem_cursor *)cur; // increment the value of i, so that xColumn knowns what value to return pCur->row++; return SQLITE_OK; } /* * This function resets the cursor for a new query. From the documentation: * * This method begins a search of a virtual table. The first argument is a * cursor opened by xOpen. The next two arguments define a particular search * index previously chosen by xBestIndex. The specific meanings of idxNum and * idxStr are unimportant as long as xFilter and xBestIndex agree on what that * meaning is. * * This method must return SQLITE_OK if successful, or an sqlite error code if * an error occurs. **/ static int filesystemFilter(sqlite3_vtab_cursor *pVtabCursor, int idxNum, const char *idxStr, int argc, sqlite3_value **argv) { // you need to operate on the sqlite3_vtab_cursor object as your own // virtual table's cursor type, so cast it back to x_cursor filesystem_cursor *pCur = (filesystem_cursor *)pVtabCursor; filesystem_vtab *pVtab = (filesystem_vtab *)pVtabCursor->pVtab; // reset the count value of your cursor's structure pCur->row = 0; // the filesystem table requires you to have a where clause to specify the // path. if argc is 0, then no values were specified as valid constraints in // xBestIndex. there's currently logic in xBestIndex to prevent execution // from getting this far if that were to happen, but we check argc here as // well to illustrate the requirement if (argc <= 0) { return SQLITE_MISUSE; } // extract the RHS value for the path constraint into the cursor's path field pCur->path = std::string((const char *)sqlite3_value_text(argv[0])); // if the path doesn't exist, return early if (!fs::exists(pCur->path)) { std::cerr << pCur->path << " doesn't exist" << std::endl; return SQLITE_OK; } // iterate through the directory that is being queried upon and gather the // information needed to complete a table scan fs::directory_iterator end_iter; for (fs::directory_iterator dir_itr(pCur->path); dir_itr != end_iter; ++dir_itr) { pVtab->pContent->path.push_back(dir_itr->path().string()); pVtab->pContent->is_file.push_back(fs::is_regular_file(dir_itr->status())); pVtab->pContent->is_dir.push_back(fs::is_directory(dir_itr->status())); pVtab->pContent->is_link.push_back(fs::is_symlink(dir_itr->status())); } // set the size of the table based on the amount of results that were queried pVtab->pContent->n = pVtab->pContent->path.size(); // return SQLITE_OK because everything went as planned return SQLITE_OK; } /* * This is executed when you query a virtual table with a WHERE claue. From * the documentation: * * SQLite calls this method when it is running sqlite3_prepare() or the * equivalent. By calling this method, the SQLite core is saying to the virtual * table that it needs to access some subset of the rows in the virtual table * and it wants to know the most efficient way to do that access. The xBestIndex * method replies with information that the SQLite core can then use to conduct * an efficient search of the virtual table. **/ static int filesystemBestIndex(sqlite3_vtab *tab, sqlite3_index_info *pIdxInfo) { filesystem_vtab *pVtab = (filesystem_vtab *)tab; if (pIdxInfo->nConstraint == 0) { // the filesystem table requires you to have a where clause to specify the // path. if nConstrain is 0, then there were no where clauses. goto fail; } // iterate through all of the constraints (aka where clauses) and look for // the constraint on the "path" column for (int i = 0; i < pIdxInfo->nConstraint; i++) { if (pIdxInfo->aConstraint[i].iColumn == 0 && pIdxInfo->aConstraint[i].usable) { pIdxInfo->aConstraintUsage[i].argvIndex = pIdxInfo->aConstraint[i].iColumn + 1; goto finish; } } // if the code has gotten this far, it means that there were constraints in // the query, but none of them were for the path column, which is required goto fail; finish: return SQLITE_OK; fail: return SQLITE_MISUSE; } /* ** A virtual table module that merely echoes method calls into TCL ** variables. */ static sqlite3_module filesystemModule = { 0, /* iVersion */ filesystemCreate, /* xCreate - create a new virtual table */ filesystemCreate, /* xConnect - connect to an existing vtab */ filesystemBestIndex, /* xBestIndex - find the best query index */ filesystemDestroy, /* xDisconnect - disconnect a vtab */ filesystemDestroy, /* xDestroy - destroy a vtab */ filesystemOpen, /* xOpen - open a cursor */ filesystemClose, /* xClose - close a cursor */ filesystemFilter, /* xFilter - configure scan constraints */ filesystemNext, /* xNext - advance a cursor */ filesystemEof, /* xEof */ filesystemColumn, /* xColumn - read data */ filesystemRowid, /* xRowid - read data */ 0, /* xUpdate */ 0, /* xBegin */ 0, /* xSync */ 0, /* xCommit */ 0, /* xRollback */ 0, /* xFindMethod */ 0, /* xRename */ }; /* ** Invoke this routine to create a specific instance of an filesystem object. ** The new filesystem object is returned by the 3rd parameter. ** ** Each filesystem object corresponds to a virtual table in the TEMP table ** with a name of zName. ** ** Destroy the filesystem object by dropping the virtual table. If not done ** explicitly by the application, the virtual table will be dropped implicitly ** by the system when the database connection is closed. */ int sqlite3_filesystem_create(sqlite3 *db, const char *zName, sqlite3_filesystem **ppReturn) { int rc = SQLITE_OK; sqlite3_filesystem *p; *ppReturn = p = new sqlite3_filesystem; if (p == 0) { return SQLITE_NOMEM; } memset(p, 0, sizeof(*p)); rc = sqlite3_create_module_v2( db, zName, &filesystemModule, p, (void (*)(void *))filesystemFree); if (rc == SQLITE_OK) { char *zSql; zSql = sqlite3_mprintf("CREATE VIRTUAL TABLE temp.%Q USING %Q", zName, zName); rc = sqlite3_exec(db, zSql, 0, 0, 0); sqlite3_free(zSql); } return rc; }
33.615752
80
0.69322
bowlofstew
36d89906b5ba9e66ffcae5b71fc944eb4c5a5d4a
28,876
cpp
C++
third_party/occmapping/src/robustoctree.cpp
SRI-IPS/general-tools
b3113cbcf83c3a430c630d050d1b96e722dfb043
[ "BSD-3-Clause" ]
null
null
null
third_party/occmapping/src/robustoctree.cpp
SRI-IPS/general-tools
b3113cbcf83c3a430c630d050d1b96e722dfb043
[ "BSD-3-Clause" ]
null
null
null
third_party/occmapping/src/robustoctree.cpp
SRI-IPS/general-tools
b3113cbcf83c3a430c630d050d1b96e722dfb043
[ "BSD-3-Clause" ]
null
null
null
/* * Copyright (c) 2013-2014, Konstantin Schauwecker * * This code is based on the original OctoMap implementation. The original * copyright notice and source code license are as follows: * * Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg * All rights reserved. * License: New BSD * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <cmath> #include <chrono> #include <iostream> #include <exception> #include <list> #include "robustoctree.h" #define MODEL_Z_ERROR // remove this constant if depth error should not be modeled // #define this to enable debugging the calcVisibilities() graph traversal logic. #undef OCC_DEBUG_CALC_VISIBILITIES #undef OCC_PROFILE_CALC_VISIBILITIES #undef OCC_PROFILE_COMPUTE_UPDATE #undef OCC_PROFILE_INSERT_POINT_CLOUD namespace occmapping { // A dummy value we use to represent the root key of a ray. octomap::OcTreeKey RobustOcTree::ROOT_KEY(0xFFFF, 0xFFFF, 0xFFFF); RobustOcTree::StaticMemberInitializer RobustOcTree::ocTreeMemberInit; RobustOcTree::RobustOcTree() : Base(RobustOcTreeParameters().octreeResolution) { initFromParameters(); } RobustOcTree::RobustOcTree(const RobustOcTreeParameters& parameters) : Base(parameters.octreeResolution), parameters(parameters) { initFromParameters(); } RobustOcTree::~RobustOcTree() { delete lookup; } void RobustOcTree::initFromParameters() { // We keep the inverse probabilities too probMissIfOccupied = 1.0 - parameters.probHitIfOccupied; probMissIfNotOccupied = 1.0 - parameters.probHitIfNotOccupied; probMissIfNotVisible = 1.0 - parameters.probHitIfNotVisible; // Convert minimum and maximum height to octree keys octomap::OcTreeKey key; if (!coordToKeyChecked(0, 0, parameters.minHeight, key)) minZKey = 0; else minZKey = key[2]; if (!coordToKeyChecked(0, 0, parameters.maxHeight, key)) maxZKey = 0xFFFF; else maxZKey = key[2]; // Generate probability look-up table. // Some parameters are hard coded here, but you propability don't want to change them anyway. lookup = new ProbabilityLookup(parameters.octreeResolution, parameters.depthErrorResolution, 0.1, parameters.maxRange, 0, 1, 0.05, parameters.depthErrorScale); // Hopefully makes accesses to the hash faster voxelUpdateCache.max_load_factor(0.75); voxelUpdateCache.rehash(1000); } void RobustOcTree::insertPointCloud(const octomap::Pointcloud& scan, const octomap::point3d& sensor_origin, const octomap::point3d& forwardVec, bool lazy_eval) { #ifdef OCC_PROFILE_INSERT_POINT_CLOUD static auto max_calc_vis_t = 0; static auto calc_vis_t_sum = 0; static auto calc_vis_count = 0; ++calc_vis_count; auto t0 = std::chrono::high_resolution_clock::now(); #endif // Do ray casting stuff computeUpdate(scan, sensor_origin, forwardVec); #ifdef OCC_PROFILE_INSERT_POINT_CLOUD auto t1 = std::chrono::high_resolution_clock::now(); #endif // Calculate a visibility for all voxels that will be updated calcVisibilities(sensor_origin); #ifdef OCC_PROFILE_INSERT_POINT_CLOUD auto t2 = std::chrono::high_resolution_clock::now(); auto calc_vis_t = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1).count(); calc_vis_t_sum += calc_vis_t; if (calc_vis_t > max_calc_vis_t) { max_calc_vis_t = calc_vis_t; } #endif // Perform update for (OccPrevKeySet::iterator it = voxelUpdateCache.begin(); it != voxelUpdateCache.end(); it++) { float visibility = visibilities[it->key]; if (visibility >= parameters.visibilityClampingMin) updateNode(it->key, visibility, it->occupancy, lazy_eval); } #ifdef OCC_PROFILE_INSERT_POINT_CLOUD auto t3 = std::chrono::high_resolution_clock::now(); std::cerr << "InsertPointCloud: computeUpdate: " << std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count() << " ms, calcVisibilities: " << calc_vis_t << " ms (max: " << max_calc_vis_t << " ms, avg: " << calc_vis_t_sum / calc_vis_count << " ms)," << " updateNode(s): " << std::chrono::duration_cast<std::chrono::milliseconds>(t3 - t2).count() << " ms" << std::endl; #endif } void RobustOcTree::calcKeyVisibility(const OccPrevKey& key, const octomap::OcTreeKey& originKey) { KeyVisMap::iterator visIter = visibilities.find(key.prevKey); if (visIter == visibilities.end()) { assert(false && "visIter not found"); OCTOMAP_WARNING_STR("visIter not found!!!"); return; } // Find occupancies for the three neighbor nodes bordering // the visible faces octomap::OcTreeKey currKey = key.key; int step[3] = {currKey[0] > originKey[0] ? 1 : -1, currKey[1] > originKey[1] ? 1 : -1, currKey[2] > originKey[2] ? 1 : -1}; octomap::OcTreeKey neighborKeys[3] = { octomap::OcTreeKey(currKey[0] - step[0], currKey[1], currKey[2]), octomap::OcTreeKey(currKey[0], currKey[1] - step[1], currKey[2]), octomap::OcTreeKey(currKey[0], currKey[1], currKey[2] - step[2])}; float occupancies[3] = {0.5F, 0.5F, 0.5F}; for (unsigned int i = 0; i < 3; i++) { RobustOcTreeNode* neighborNode = search(neighborKeys[i]); if (neighborNode != NULL) { occupancies[i] = neighborNode->getOccupancy(); if (occupancies[i] <= parameters.clampingThresholdMin) occupancies[i] = 0; } } // Get the probabilities that the current voxel is occluded by its neighbors float occlusionProb = std::min(occupancies[0], std::min(occupancies[1], occupancies[2])); float visibility = visIter->second * (parameters.probVisibleIfOccluded * occlusionProb + parameters.probVisibleIfNotOccluded * (1.0F - occlusionProb)); // clamp visibility if (visibility > parameters.visibilityClampingMax) visibility = 1.0F; visibilities[currKey] = visibility; } void RobustOcTree::calcVisibilities(const octomap::point3d& sensor_origin) { #ifdef OCC_PROFILE_CALC_VISIBILITIES auto voxel_update_cache_size = voxelUpdateCache.size(); #endif #ifdef OCC_DEBUG_CALC_VISIBILITIES std::cerr << "voxelUpdateCache size: " << voxelUpdateCache.size() << std::endl; #endif // Find the origin key octomap::OcTreeKey originKey; if (!coordToKeyChecked(sensor_origin, originKey)) { OCTOMAP_WARNING_STR("origin coordinates ( " << sensor_origin << ") out of bounds in calcVisibilities"); return; } visibilities.clear(); visibilities[ROOT_KEY] = 1.0; keyGraph.clear(); #ifdef OCC_PROFILE_CALC_VISIBILITIES auto t0 = std::chrono::high_resolution_clock::now(); #endif // Stores the parent's iterator and the child iterator that is currently being processed. auto parentStack = std::stack< std::pair<KeyGraphMap::iterator, std::list<const OccPrevKey *>::iterator>>{}; auto visitedKeys = std::unordered_set<octomap::OcTreeKey, octomap::OcTreeKey::KeyHash>{}; for (const auto& cacheKey : voxelUpdateCache) { keyGraph[cacheKey.prevKey].push_back(&cacheKey); } #ifdef OCC_PROFILE_CALC_VISIBILITIES auto t1 = std::chrono::high_resolution_clock::now(); auto create_key_graph_t = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count(); #endif #ifdef OCC_PROFILE_CALC_VISIBILITIES auto key_graph_size = keyGraph.size(); #endif #ifdef OCC_DEBUG_CALC_VISIBILITIES std::cerr << "keyGraph size: " << keyGraph.size() << std::endl; #endif #ifdef OCC_PROFILE_CALC_VISIBILITIES auto calc_key_visibilities_count = 0; auto calc_key_visibilities_t_sum = 0; t0 = std::chrono::high_resolution_clock::now(); #endif auto currNode = keyGraph.find(ROOT_KEY); if (currNode == keyGraph.end()) { OCTOMAP_WARNING_STR("Empty key graph in calcVisibilities"); return; } visitedKeys.insert(currNode->first); auto childIt = currNode->second.begin(); while (true) { if (childIt == currNode->second.end()) { if (parentStack.empty()) { // We are done! break; } #ifdef OCC_DEBUG_CALC_VISIBILITIES std::cerr << "Leaving child " << *childIt << std::endl; #endif // Advance to the next child of the parent. currNode = parentStack.top().first; childIt = parentStack.top().second; parentStack.pop(); ++childIt; continue; } #ifdef OCC_DEBUG_CALC_VISIBILITIES std::cerr << "Updating visibility for child " << *childIt << std::endl; #endif #ifdef OCC_PROFILE_CALC_VISIBILITIES ++calc_key_visibilities_count; auto calc_key_visibility_t0 = std::chrono::high_resolution_clock::now(); #endif calcKeyVisibility(**childIt, originKey); #ifdef OCC_PROFILE_CALC_VISIBILITIES auto calc_key_visibility_t1 = std::chrono::high_resolution_clock::now(); calc_key_visibilities_t_sum += std::chrono::duration_cast<std::chrono::nanoseconds>( calc_key_visibility_t1 - calc_key_visibility_t0) .count(); #endif auto childNode = keyGraph.find((*childIt)->key); if (childNode == keyGraph.end()) { // This child has no sub-children to recurse to, so just advance to the next child. ++childIt; #ifdef OCC_DEBUG_CALC_VISIBILITIES std::cerr << "Child has no children, advancing to child " << *childIt << std::endl; #endif continue; } if (visitedKeys.count(childNode->first)) { // TODO(kgreenek): Verify whether this can actually happen. assert(false && "Cycle detected in key graph"); OCTOMAP_WARNING_STR("Cycle detected in key graph"); ++childIt; continue; } #ifdef OCC_DEBUG_CALC_VISIBILITIES std::cerr << "Recursing into child " << *childIt << std::endl; #endif // Recurse down into the childNode. parentStack.push({currNode, childIt}); currNode = childNode; visitedKeys.insert(currNode->first); childIt = currNode->second.begin(); } #ifdef OCC_PROFILE_CALC_VISIBILITIES t1 = std::chrono::high_resolution_clock::now(); auto key_graph_traversal_t = std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0).count(); std::cerr << "calcVisibilities:\n" << " voxelUpdateCache size: " << voxel_update_cache_size << "\n" << " keyGraph size: " << key_graph_size << ", create_t: " << create_key_graph_t << " ms\n" << " key_graph_traversal_t: " << key_graph_traversal_t << "\n" << " calcKeyVisibility: count: " << calc_key_visibilities_count << ", total_t: " << calc_key_visibilities_t_sum / 1000000 << " ms, avg_t: " << calc_key_visibilities_t_sum / calc_key_visibilities_count / 1000 << " us" << std::endl; #endif } void RobustOcTree::insertPointCloud(const octomap::Pointcloud& pc, const octomap::point3d& sensor_origin, const octomap::pose6d& frame_origin, bool lazy_eval) { // performs transformation to data and sensor origin first octomap::Pointcloud transformed_scan(pc); transformed_scan.transform(frame_origin); octomap::point3d transformed_sensor_origin = frame_origin.transform(sensor_origin); octomap::point3d forwardVec = frame_origin.transform(sensor_origin + octomap::point3d(0, 1.0, 0.0)) - transformed_sensor_origin; // Process transformed point cloud insertPointCloud(transformed_scan, transformed_sensor_origin, forwardVec, lazy_eval); } void RobustOcTree::computeUpdate(const octomap::Pointcloud& scan, const octomap::point3d& origin, const octomap::point3d& forwardVec) { voxelUpdateCache.clear(); prevKeyray.reset(); #ifdef OCC_PROFILE_COMPUTE_UPDATE auto compute_ray_keys_sum = 0; auto compute_ray_keys_count = 0; auto update_cache_sum = 0; auto update_cache_count = 0; #endif for (int i = 0; i < (int)scan.size(); ++i) { // Compute a new ray const octomap::point3d& p = scan[i]; #ifdef OCC_PROFILE_COMPUTE_UPDATE auto t0 = std::chrono::high_resolution_clock::now(); #endif computeRayKeys(origin, p, forwardVec); #ifdef OCC_PROFILE_COMPUTE_UPDATE auto t1 = std::chrono::high_resolution_clock::now(); compute_ray_keys_sum += std::chrono::duration_cast<std::chrono::nanoseconds>(t1 - t0).count(); ++compute_ray_keys_count; #endif // Insert cells into the update cache if they haven't been // part of a previous ray, or if their occupancy is higher than // for any previous ray. // First perform lookup against previous ray OccPrevKeyRay::iterator currIt = keyray.begin(); OccPrevKeyRay::iterator currEnd = prevKeyray.size() > keyray.size() ? keyray.end() : keyray.begin() + prevKeyray.size(); for (OccPrevKeyRay::iterator prevIt = prevKeyray.begin(); currIt != currEnd; currIt++, prevIt++) { if (currIt->key == prevIt->key) { // Cell already exists in previous ray if (currIt->occupancy > prevIt->occupancy) { OccPrevKeySet::iterator updateIter = voxelUpdateCache.find(*currIt); OccPrevKeySet::iterator insertHint = voxelUpdateCache.erase(updateIter); voxelUpdateCache.insert(insertHint, *currIt); } else { currIt->occupancy = prevIt->occupancy; // Keep best occupancy for next ray } } else { // Perform full lookup against hash map OccPrevKeySet::iterator updateIter = voxelUpdateCache.find(*currIt); if (updateIter == voxelUpdateCache.end()) { voxelUpdateCache.insert(*currIt); } else if (currIt->occupancy > updateIter->occupancy) { OccPrevKeySet::iterator insertHint = voxelUpdateCache.erase(updateIter); voxelUpdateCache.insert(insertHint, *currIt); } else { currIt->occupancy = updateIter->occupancy; // Keep best occupancy for next ray } } } #ifdef OCC_PROFILE_COMPUTE_UPDATE auto t2 = std::chrono::high_resolution_clock::now(); #endif // Lookup remaining cells against hash map for (; currIt != keyray.end(); currIt++) { OccPrevKeySet::iterator updateIter = voxelUpdateCache.find(*currIt); if (updateIter == voxelUpdateCache.end()) { voxelUpdateCache.insert(*currIt); } else if (currIt->occupancy > updateIter->occupancy) { OccPrevKeySet::iterator insertHint = voxelUpdateCache.erase(updateIter); voxelUpdateCache.insert(insertHint, *currIt); } else { currIt->occupancy = updateIter->occupancy; // Keep best occupancy for next ray } } #ifdef OCC_PROFILE_COMPUTE_UPDATE auto t3 = std::chrono::high_resolution_clock::now(); update_cache_sum += std::chrono::duration_cast<std::chrono::nanoseconds>(t3 - t2).count(); ++update_cache_count; #endif keyray.swap(prevKeyray); } #ifdef OCC_PROFILE_COMPUTE_UPDATE std::cerr << "computeUpdate: computeRayKeys: " << compute_ray_keys_sum / 1000000 << " ms, voxelUpdateCache: " << update_cache_sum / 1000000 << " ms" << std::endl; #endif } void RobustOcTree::computeRayKeys(const octomap::point3d& origin, const octomap::point3d& end, const octomap::point3d& forwardVec) { // see "A Faster Voxel Traversal Algorithm for Ray Tracing" by Amanatides & Woo // basically: DDA in 3D keyray.reset(); octomap::point3d direction = (end - origin); double length = direction.norm(); direction /= length; // normalize vector octomap::OcTreeKey key_origin, key_end; if (!coordToKeyChecked(origin, key_origin)) { OCTOMAP_WARNING_STR("origin coordinates ( " << origin << " -> " << end << ") out of bounds in computeRayKeys"); return; } if (!coordToKeyChecked(end, key_end) && !coordToKeyChecked(origin + direction * (2.0 * parameters.maxRange), key_end)) { OCTOMAP_WARNING_STR("end coordinates ( " << origin << " -> " << end << ") out of bounds in computeRayKeys"); return; } // Initialization phase ------------------------------------------------------- int step[3]; double tMax[3]; double tDelta[3]; octomap::OcTreeKey prev_key = ROOT_KEY; octomap::OcTreeKey current_key = key_origin; for (unsigned int i = 0; i < 3; ++i) { // compute step direction if (direction(i) > 0.0) step[i] = 1; else if (direction(i) < 0.0) step[i] = -1; else step[i] = 0; // compute tMax, tDelta if (step[i] != 0) { // corner point of voxel (in direction of ray) double voxelBorder = keyToCoord(current_key[i]); voxelBorder += step[i] * resolution * 0.5; tMax[i] = (voxelBorder - origin(i)) / direction(i); tDelta[i] = this->resolution / fabs(direction(i)); } else { tMax[i] = std::numeric_limits<double>::max(); tDelta[i] = std::numeric_limits<double>::max(); } } // for speedup: octomap::point3d origin_scaled = origin; origin_scaled /= resolution; double length_to_key = (keyToCoord(key_end) - origin).norm(); double length_scaled = (std::min(length_to_key, parameters.maxRange)) / resolution; length_scaled = length_scaled * length_scaled; double maxrange_scaled = parameters.maxRange / resolution; maxrange_scaled *= maxrange_scaled; // Conversion factor from length to depth (length of one z-step) double lengthToDepth = forwardVec.x() * direction.x() + forwardVec.y() * direction.y() + forwardVec.z() * forwardVec.z(); double depth = length / lengthToDepth; double probApproxMaxDistScaled, probApproxMaxDist; std::vector<float>* lookupEntry = lookup->lookupEntry(depth); if (lookupEntry == NULL) { probApproxMaxDist = std::numeric_limits<double>::max(); probApproxMaxDistScaled = maxrange_scaled; } else { probApproxMaxDist = lengthToDepth * (depth - (lookupEntry->size() / 2.0) * parameters.depthErrorResolution); probApproxMaxDistScaled = probApproxMaxDist / resolution; probApproxMaxDistScaled = std::min(probApproxMaxDistScaled * probApproxMaxDistScaled, maxrange_scaled); } double treeMax05 = tree_max_val - 0.5F; // Incremental phase --------------------------------------------------------- unsigned int dim = 0; double squareDistFromOrigVec[3] = {(current_key[0] - treeMax05 - origin_scaled(0)) * (current_key[0] - treeMax05 - origin_scaled(0)), (current_key[1] - treeMax05 - origin_scaled(1)) * (current_key[1] - treeMax05 - origin_scaled(1)), (current_key[2] - treeMax05 - origin_scaled(2)) * (current_key[2] - treeMax05 - origin_scaled(2))}; while (true) { // Calculate distance from origin double squareDistFromOrig = squareDistFromOrigVec[0] + squareDistFromOrigVec[1] + squareDistFromOrigVec[2]; #ifdef MODEL_Z_ERROR if (squareDistFromOrig < probApproxMaxDistScaled) { // Use approximate probabilities keyray.addOccPrevKey(0.0, current_key, prev_key); } else if (squareDistFromOrig >= maxrange_scaled) { // The point is too far away. Lets stop. break; } else { // Detailed calculation int index = int((sqrt(squareDistFromOrig) * resolution - probApproxMaxDist) / (parameters.depthErrorResolution * lengthToDepth) + 0.5); double occupancyFactor = 1.0; bool done = false; if (index >= (int)lookupEntry->size()) { done = true; // Continue to make sure we integrate one full hit } else { occupancyFactor = (*lookupEntry)[index]; } keyray.addOccPrevKey(occupancyFactor, current_key, prev_key); if (done) break; } #else // reached endpoint? if (current_key == key_end) { keyray.addOccPrevKey(1.0, current_key, prev_key); break; } else if (squareDistFromOrig >= length_scaled) { // We missed it :-( if (length_to_key < parameters.maxRange) keyray.addOccPrevKey(1.0, key_end, prev_key); break; } else { keyray.addOccPrevKey(0.0, current_key, prev_key); } #endif // find minimum tMax: if (tMax[0] < tMax[1]) { if (tMax[0] < tMax[2]) dim = 0; else dim = 2; } else { if (tMax[1] < tMax[2]) dim = 1; else dim = 2; } // advance in direction "dim" prev_key = current_key; current_key[dim] += step[dim]; tMax[dim] += tDelta[dim]; squareDistFromOrigVec[dim] = current_key[dim] - treeMax05 - origin_scaled(dim); squareDistFromOrigVec[dim] *= squareDistFromOrigVec[dim]; assert(current_key[dim] < 2 * this->tree_max_val); if (current_key[2] < minZKey || current_key[2] > maxZKey) break; // Exceeded min or max height // TODO(kgreenek): Re-enable this assert once a17hq/a17#150 is fixed. This assert is being // triggered for some datasets, when it shouldn't be. #if 0 assert(keyray.size() < keyray.sizeMax() - 1); #else if (keyray.size() >= keyray.sizeMax() - 1) { std::cerr << "WARNING: keyraw.size >= keyraw.sizeMax(). Skipping scan..." << std::endl; break; } #endif } } RobustOcTreeNode* RobustOcTree::updateNode(const octomap::OcTreeKey& key, float visibility, float occupancy, bool lazy_eval) { // early abort (no change will happen). // may cause an overhead in some configuration, but more often helps RobustOcTreeNode* leaf = this->search(key); // no change: node already at minimum threshold if (leaf != NULL && occupancy == 0.0F && leaf->getOccupancy() <= parameters.clampingThresholdMin) return leaf; bool createdRoot = false; if (this->root == NULL) { this->root = new RobustOcTreeNode(); this->tree_size++; createdRoot = true; } return updateNodeRecurs(this->root, visibility, createdRoot, key, 0, occupancy, lazy_eval); } RobustOcTreeNode* RobustOcTree::updateNodeRecurs(RobustOcTreeNode* node, float visibility, bool node_just_created, const octomap::OcTreeKey& key, unsigned int depth, float occupancy, bool lazy_eval) { // Differences to OccupancyOcTreeBase implementation: only cosmetic unsigned int pos = computeChildIdx(key, this->tree_depth - 1 - depth); bool created_node = false; assert(node); // follow down to last level if (depth < this->tree_depth) { if (!nodeChildExists(node, pos)) { // child does not exist, but maybe it's a pruned node? if ((!nodeHasChildren(node)) && !node_just_created) { // current node does not have children AND it is not a new node // -> expand pruned node expandNode(node); this->tree_size += 8; this->size_changed = true; } else { // not a pruned node, create requested child createNodeChild(node, pos); this->tree_size++; this->size_changed = true; created_node = true; } } if (lazy_eval) return updateNodeRecurs(getNodeChild(node, pos), visibility, created_node, key, depth + 1, occupancy, lazy_eval); else { RobustOcTreeNode* retval = updateNodeRecurs(getNodeChild(node, pos), visibility, created_node, key, depth + 1, occupancy, lazy_eval); // prune node if possible, otherwise set own probability // note: combining both did not lead to a speedup! if (pruneNode(node)) this->tree_size -= 8; else node->updateOccupancyChildren(); return retval; } } // at last level, update node, end of recursion else { if (use_change_detection) { bool occBefore = this->isNodeOccupied(node); updateNodeOccupancy(node, visibility, occupancy); if (node_just_created) { // new node changed_keys.insert(std::pair<octomap::OcTreeKey, bool>(key, true)); } else if (occBefore != this->isNodeOccupied(node)) { // occupancy changed, track it auto it = changed_keys.find(key); if (it == changed_keys.end()) { changed_keys.insert(std::pair<octomap::OcTreeKey, bool>(key, false)); } else if (it->second == false) { // This happens when the value changes back to what it was, so we can just remove it, // because it has no longer changed since the last time changed_keys was cleared. changed_keys.erase(it); } } } else { updateNodeOccupancy(node, visibility, occupancy); } return node; } } void RobustOcTree::updateNodeOccupancy(RobustOcTreeNode* occupancyNode, float probVisible, float occupancy) { float probOccupied = occupancyNode->getOccupancy(); // Decide which update procedure to perform if (occupancy == 0.0F) { // Perform update for certainly free voxels float probMiss = calcOccupiedProbability(probOccupied, probVisible, probMissIfOccupied, probMissIfNotOccupied, probMissIfNotVisible); occupancyNode->setOccupancy( probMiss > parameters.clampingThresholdMin ? probMiss : parameters.clampingThresholdMin); } else { float probHit = calcOccupiedProbability(probOccupied, probVisible, parameters.probHitIfOccupied, parameters.probHitIfNotOccupied, parameters.probHitIfNotVisible); if (occupancy == 1.0F) { // Perform update for certainly occupied voxels occupancyNode->setOccupancy( probHit < parameters.clampingThresholdMax ? probHit : parameters.clampingThresholdMax); } else { // We are not certain, but we know the occupancy probability. // Lets interpolate between the update for free and occupied voxels. float probMiss = calcOccupiedProbability(probOccupied, probVisible, probMissIfOccupied, probMissIfNotOccupied, parameters.probHitIfNotVisible); occupancyNode->setOccupancy(occupancy * probHit + (1.0F - occupancy) * probMiss); // Perform probability clamping if (occupancyNode->getOccupancy() < parameters.clampingThresholdMin) occupancyNode->setOccupancy(parameters.clampingThresholdMin); else if (occupancyNode->getOccupancy() > parameters.clampingThresholdMax) occupancyNode->setOccupancy(parameters.clampingThresholdMax); } } } float RobustOcTree::calcOccupiedProbability(float probOccupied, float probVisible, float probMeasIfOccupied, float probMeasIfNotOccupied, float probMeasNotVisible) { // This is our update equation. See our paper for a derivation of this formula (Eq. 4 - 6). return (probMeasIfOccupied * probVisible * probOccupied + probMeasNotVisible * (1.0F - probVisible) * probOccupied) / (probMeasIfOccupied * probVisible * probOccupied + probMeasIfNotOccupied * probVisible * (1.0F - probOccupied) + probMeasNotVisible * (1.0F - probVisible)); } } // namespace occmapping
38.968961
100
0.659717
SRI-IPS
36d8a1efb7fd96f399a9902441662899f9db2bfe
1,301
cxx
C++
Src/Neill3d_Archive/userobject_normalSolver/solver_normals.cxx
musterchef/OpenMoBu
b98e9f8d6182d84e54da1b790bbe69620ea818de
[ "BSD-3-Clause" ]
53
2018-04-21T14:16:46.000Z
2022-03-19T11:27:37.000Z
Src/Neill3d_Archive/userobject_normalSolver/solver_normals.cxx
musterchef/OpenMoBu
b98e9f8d6182d84e54da1b790bbe69620ea818de
[ "BSD-3-Clause" ]
6
2019-06-05T16:37:29.000Z
2021-09-20T07:17:03.000Z
Src/Neill3d_Archive/userobject_normalSolver/solver_normals.cxx
musterchef/OpenMoBu
b98e9f8d6182d84e54da1b790bbe69620ea818de
[ "BSD-3-Clause" ]
10
2019-02-22T18:43:59.000Z
2021-09-02T18:53:37.000Z
///////////////////////////////////////////////////////////////////////////////////////// // // Licensed under the "New" BSD License. // License page - https://github.com/Neill3d/MoBu/blob/master/LICENSE // // GitHub repository - https://github.com/Neill3d/MoBu // // Author Sergey Solokhin (Neill3d) 2014-2017 // e-mail to: s@neill3d.com // www.neill3d.com ///////////////////////////////////////////////////////////////////////////////////////// /** \file solver_normals.cxx * Library declarations. * Contains the basic routines to declare the DLL as a loadable * library. */ //--- SDK include #include <fbsdk/fbsdk.h> #ifdef KARCH_ENV_WIN #include <windows.h> #endif #include <GL\glew.h> #include "ResourceUtils.h" //--- Library declaration. FBLibraryDeclare( solvercalculatenormals ) { FBLibraryRegister(SolverCalculateNormals) FBLibraryRegister( KNormalSolverAssociation ); } FBLibraryDeclareEnd; /************************************************ * Library functions. ************************************************/ bool FBLibrary::LibInit() { return true; } bool FBLibrary::LibOpen() { glewInit(); InitResourceUtils(); return true; } bool FBLibrary::LibReady() { return true; } bool FBLibrary::LibClose() { return true; } bool FBLibrary::LibRelease() { return true; }
26.02
89
0.567256
musterchef
36d964a0571b9bdec37447907b20634637c26a4f
862
cpp
C++
cse419/CodeForces/349A/22273399_AC_218ms_8kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
2
2020-09-02T12:07:47.000Z
2020-11-17T11:17:16.000Z
cse419/CodeForces/349A/22273399_AC_218ms_8kB.cpp
cosmicray001/academic
6aa142baeba4bb1ad73b8669e37305ca0b5102a7
[ "MIT" ]
null
null
null
cse419/CodeForces/349A/22273399_AC_218ms_8kB.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() { map<int,int>t; bool check = true; int n,v; cin>>n; for(int i=0;i<n;i++){ cin>>v; if(v==100){ if(t[50]>=1 && t[25]>=1){ t[50]--; t[25]--; } else if(t[25]>=3){ t[25]-=3; } else{ cout<<"NO"<<endl; check=false; break; } } else if(v==50){ if(t[25]>=1){ t[50]++; t[25]--; } else{ cout<<"NO"<<"\n"; check=false; break; } } else{ t[25]++; } } if(check){ cout<<"YES"<<endl; } return 0; }
18.73913
37
0.267981
cosmicray001
36dfd3e497e94478162e3edbe06481d562332f35
4,189
cpp
C++
src/ui/VKUMainForm.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/VKUMainForm.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
src/ui/VKUMainForm.cpp
igorglotov/tizen-vk-client
de213ede7185818285f78abad36592bc864f76cc
[ "Unlicense" ]
null
null
null
#include "VKUMainForm.h" #include "AppResourceId.h" #include "SceneRegister.h" #include "VKUColors.h" #include "VKUContactsPanel.h" #include "VKUApi.h" #include "JsonParseUtils.h" #include "ObjectCounter.h" using namespace Tizen::Base; using namespace Tizen::App; using namespace Tizen::Ui; using namespace Tizen::Ui::Controls; using namespace Tizen::Ui::Scenes; using namespace Tizen::Graphics; using namespace Tizen::Web::Json; VKUMainForm::VKUMainForm(void) { CONSTRUCT(L"VKUMainForm"); } VKUMainForm::~VKUMainForm(void) { DESTRUCT(L"VKUMainForm"); } bool VKUMainForm::Initialize(void) { Construct(IDF_MAIN); return true; } result VKUMainForm::OnInitializing(void) { result r = E_SUCCESS; Color headerColor(HEADER_BG_COLOR, false); // TODO: // Add your initialization code here Header* pHeader = GetHeader(); if (pHeader) { pHeader->AddActionEventListener(*this); pHeader->SetColor(headerColor); } // Setup back event listener SetFormBackEventListener(this); return r; } result VKUMainForm::OnTerminating(void) { result r = E_SUCCESS; // TODO: // Add your termination code here return r; } void VKUMainForm::OnActionPerformed(const Tizen::Ui::Control& source, int actionId) { SceneManager* pSceneManager = SceneManager::GetInstance(); AppAssert(pSceneManager); UpdateCounters(); switch (actionId) { case ID_HEADER_MESSAGES: pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_DIALOGS)); break; case ID_HEADER_CONTACTS: pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_CONTACTS)); break; case ID_HEADER_SEARCH: pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_SEARCH)); break; case ID_HEADER_SETTINGS: pSceneManager->GoForward(ForwardSceneTransition(SCENE_MAIN_SETTINGS)); break; default: break; } } void VKUMainForm::OnFormBackRequested(Tizen::Ui::Controls::Form& source) { AppLog("Back requested. Finishing app"); UiApp* pApp = UiApp::GetInstance(); AppAssert(pApp); pApp->Terminate(); } void VKUMainForm::OnSceneActivatedN( const Tizen::Ui::Scenes::SceneId& previousSceneId, const Tizen::Ui::Scenes::SceneId& currentSceneId, Tizen::Base::Collection::IList* pArgs) { // TODO: Add your implementation codes here UpdateCounters(); } void VKUMainForm::OnSceneDeactivated( const Tizen::Ui::Scenes::SceneId& currentSceneId, const Tizen::Ui::Scenes::SceneId& nextSceneId) { // TODO: Add your implementation codes here } /* void VKUMainForm::ClearContacts() { //Frame* frame = VKUApp::GetInstance()->GetFrame(FRAME_NAME); //Form* form = frame->GetCurrentForm(); //if (form->GetName() == IDF_MAIN) { VKUContactsPanel* contactsPanel = static_cast<VKUContactsPanel*>(GetControl(IDC_PANEL_CONTACTS)); if (contactsPanel != null) { contactsPanel->ClearItems(); } //} } */ void VKUMainForm::UpdateCounters() { VKUApi::GetInstance().CreateRequest("account.getCounters", this)->Put(L"filter", L"messages,friends")->Submit(REQUEST_COUNTERS); } void VKUMainForm::OnResponseN(RequestId requestId, JsonObject *object) { result r; if(requestId != REQUEST_COUNTERS) { return; } JsonObject *response; int messages, friends; Header *header = GetHeader(); r = JsonParseUtils::GetObject(object, L"response", response); if(r != E_SUCCESS) { return; } r = JsonParseUtils::GetInteger(*response, L"messages", messages); if(r == E_SUCCESS) { header->SetItemNumberedBadgeIcon(0, messages); Tizen::Shell::NotificationRequest notificationBadge; notificationBadge.SetBadgeNumber(messages); Tizen::Shell::NotificationManager notificationManager; notificationManager.Construct(); notificationManager.NotifyByAppId(L"iEl2RaVlnG.VKU", notificationBadge); } else { header->SetItemNumberedBadgeIcon(0, 0); Tizen::Shell::NotificationRequest notificationBadge; notificationBadge.SetBadgeNumber(0); Tizen::Shell::NotificationManager notificationManager; notificationManager.Construct(); notificationManager.NotifyByAppId(L"iEl2RaVlnG.VKU", notificationBadge); } r = JsonParseUtils::GetInteger(*response, L"friends", friends); if(r == E_SUCCESS) { header->SetItemNumberedBadgeIcon(2, friends); } else { header->SetItemNumberedBadgeIcon(2, 0); } }
25.387879
129
0.752208
igorglotov
36e1ba9d1e4a83cd1fdbe3e9dbda6d6a2ca76b1c
3,145
cpp
C++
Signal Flow Simulation/truetime-2.0/kernel/matlab/ttCreateTask.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
1
2019-08-31T08:06:48.000Z
2019-08-31T08:06:48.000Z
Signal Flow Simulation/truetime-2.0/kernel/matlab/ttCreateTask.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
null
null
null
Signal Flow Simulation/truetime-2.0/kernel/matlab/ttCreateTask.cpp
raulest50/MicroGrid_GITCoD
885001242c8e581a6998afb4be2ae1c0b923e9c4
[ "MIT" ]
1
2020-01-07T10:46:23.000Z
2020-01-07T10:46:23.000Z
/* * Copyright (c) 2016 Lund University * * Written by Anton Cervin, Dan Henriksson and Martin Ohlin, * Department of Automatic Control LTH, Lund University, Sweden. * * This file is part of TrueTime 2.0. * * TrueTime 2.0 is free software: you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * TrueTime 2.0 is distributed in the hope that it will be useful, but * without any warranty; without even the implied warranty of * merchantability or fitness for a particular purpose. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with TrueTime 2.0. If not, see <http://www.gnu.org/licenses/> */ #define KERNEL_MATLAB #include "../ttkernel.h" #include "../createtask.cpp" #include "getrtsys.cpp" #include "../checkinputargs.cpp" void mexFunction( int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[] ) { rtsys = getrtsys() ; // Get pointer to rtsys if (rtsys==NULL) { return; } /* Check and parse input arguments */ char name[MAXCHARS]; double starttime; double deadline; char codeFcn[MAXCHARS]; const mxArray *data; if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_STRING)) { mxGetString(prhs[0], name, MAXCHARS); deadline = *mxGetPr(prhs[1]); mxGetString(prhs[2], codeFcn, MAXCHARS); starttime = -1.0; data = NULL; } else if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_STRING,TT_STRUCT)) { mxGetString(prhs[0], name, MAXCHARS); deadline = *mxGetPr(prhs[1]); mxGetString(prhs[2], codeFcn, MAXCHARS); data = prhs[3]; starttime = -1.0; } else if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_SCALAR,TT_STRING)) { mxGetString(prhs[0], name, MAXCHARS); starttime = *mxGetPr(prhs[1]); deadline = *mxGetPr(prhs[2]); mxGetString(prhs[3], codeFcn, MAXCHARS); data = NULL; } else if (checkinputargs(nrhs,prhs,TT_STRING,TT_SCALAR,TT_SCALAR,TT_STRING,TT_STRUCT)) { mxGetString(prhs[0], name, MAXCHARS); starttime = *mxGetPr(prhs[1]); deadline = *mxGetPr(prhs[2]); mxGetString(prhs[3], codeFcn, MAXCHARS); data = prhs[4]; } else { TT_MEX_ERROR("ttCreateTask: Wrong input arguments!\n" "Usage: ttCreateTask(name, deadline, codeFcn)\n" " ttCreateTask(name, deadline, codeFcn, data)\n" " ttCreateTask(name, starttime, deadline, codeFcn)\n" " ttCreateTask(name, starttime, deadline, codeFcn, data)"); return; } /* Check that the code function exists */ mxArray *lhs[1], *rhs[1]; rhs[0] = mxCreateString(codeFcn); mexCallMATLAB(1, lhs, 1, rhs, "exist"); int number = (int) *mxGetPr(lhs[0]); if (number != 2) { char buf[MAXERRBUF]; sprintf(buf, "ttCreateTask: codeFcn '%s.m' not in path! Task '%s' not created!", codeFcn, name); TT_MEX_ERROR(buf); return; } ttCreateTaskMATLAB(name, starttime, -1.0, deadline, codeFcn, data); }
29.392523
100
0.66868
raulest50
36e3e5670a02fcd3c2516626898c3f536877befe
117
cpp
C++
testing/kvstore/exp_throughput.cpp
fengggli/comanche
035f2a87e0236e9ff744c10331250dcfab835ee1
[ "Apache-2.0" ]
null
null
null
testing/kvstore/exp_throughput.cpp
fengggli/comanche
035f2a87e0236e9ff744c10331250dcfab835ee1
[ "Apache-2.0" ]
13
2019-06-12T17:50:29.000Z
2019-08-08T21:15:16.000Z
testing/kvstore/exp_throughput.cpp
fengggli/comanche
035f2a87e0236e9ff744c10331250dcfab835ee1
[ "Apache-2.0" ]
1
2019-07-26T21:39:13.000Z
2019-07-26T21:39:13.000Z
#include "exp_throughput.h" std::mutex ExperimentThroughput::_iops_lock; unsigned long ExperimentThroughput::_iops;
23.4
44
0.82906
fengggli
36e70d0faa5b99e46248dc857d0fba598422590b
1,764
cpp
C++
src/mbgl/shaders/collision_box.cpp
sp0n-7/mapbox-gl-native
0df37421faeaffb83564a81a469faa099434b767
[ "BSL-1.0", "Apache-2.0" ]
2
2018-11-28T21:38:52.000Z
2019-04-04T19:17:05.000Z
src/mbgl/shaders/collision_box.cpp
sp0n-7/mapbox-gl-native
0df37421faeaffb83564a81a469faa099434b767
[ "BSL-1.0", "Apache-2.0" ]
null
null
null
src/mbgl/shaders/collision_box.cpp
sp0n-7/mapbox-gl-native
0df37421faeaffb83564a81a469faa099434b767
[ "BSL-1.0", "Apache-2.0" ]
1
2020-12-26T06:09:50.000Z
2020-12-26T06:09:50.000Z
// NOTE: DO NOT CHANGE THIS FILE. IT IS AUTOMATICALLY GENERATED. #include <mbgl/shaders/collision_box.hpp> #include <mbgl/shaders/source.hpp> namespace mbgl { namespace shaders { const char* collision_box::name = "collision_box"; const char* collision_box::vertexSource = source() + 14428; const char* collision_box::fragmentSource = source() + 15252; // Uncompressed source of collision_box.vertex.glsl: /* attribute vec2 a_pos; attribute vec2 a_anchor_pos; attribute vec2 a_extrude; attribute vec2 a_placed; uniform mat4 u_matrix; uniform vec2 u_extrude_scale; uniform float u_camera_to_center_distance; varying float v_placed; varying float v_notUsed; void main() { vec4 projectedPoint = u_matrix * vec4(a_anchor_pos, 0, 1); highp float camera_to_anchor_distance = projectedPoint.w; highp float collision_perspective_ratio = clamp( 0.5 + 0.5 * (u_camera_to_center_distance / camera_to_anchor_distance), 0.0, // Prevents oversized near-field boxes in pitched/overzoomed tiles 4.0); gl_Position = u_matrix * vec4(a_pos, 0.0, 1.0); gl_Position.xy += a_extrude * u_extrude_scale * gl_Position.w * collision_perspective_ratio; v_placed = a_placed.x; v_notUsed = a_placed.y; } */ // Uncompressed source of collision_box.fragment.glsl: /* varying float v_placed; varying float v_notUsed; void main() { float alpha = 0.5; // Red = collision, hide label gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0) * alpha; // Blue = no collision, label is showing if (v_placed > 0.5) { gl_FragColor = vec4(0.0, 0.0, 1.0, 0.5) * alpha; } if (v_notUsed > 0.5) { // This box not used, fade it out gl_FragColor *= .1; } } */ } // namespace shaders } // namespace mbgl
24.84507
96
0.697279
sp0n-7
36e74399e6af9a3055b96e2b58bf83365a6611c2
3,314
hpp
C++
PlayRho/Common/Real.hpp
Hexlord/PlayRho
a3a91554cf9b267894d06a996c5799a0479c5b5f
[ "Zlib" ]
88
2017-07-13T18:12:40.000Z
2022-03-23T03:43:11.000Z
PlayRho/Common/Real.hpp
Hexlord/PlayRho
a3a91554cf9b267894d06a996c5799a0479c5b5f
[ "Zlib" ]
388
2017-07-13T04:32:09.000Z
2021-11-10T20:59:23.000Z
PlayRho/Common/Real.hpp
Hexlord/PlayRho
a3a91554cf9b267894d06a996c5799a0479c5b5f
[ "Zlib" ]
18
2017-07-20T16:14:57.000Z
2021-06-20T07:17:23.000Z
/* * Copyright (c) 2021 Louis Langholtz https://github.com/louis-langholtz/PlayRho * * This software is provided 'as-is', without any express or implied * warranty. In no event will the authors be held liable for any damages * arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, * including commercial applications, and to alter it and redistribute it * freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not * claim that you wrote the original software. If you use this software * in a product, an acknowledgment in the product documentation would be * appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be * misrepresented as being the original software. * 3. This notice may not be removed or altered from any source distribution. */ /** * @file * @brief Real number definition file. * @details This file may have been autogenerated from the Real.hpp.in file. */ #ifndef PLAYRHO_COMMON_REAL_HPP #define PLAYRHO_COMMON_REAL_HPP #include <PlayRho/Common/Fixed.hpp> #include <PlayRho/Common/FixedMath.hpp> #include <PlayRho/Common/FixedLimits.hpp> namespace playrho { /// @brief Real-number type. /// /// @details This is the number type underlying numerical calculations conceptually involving /// real-numbers. Ideally the implementation of this type doesn't suffer from things like: /// catastrophic cancellation, catastrophic division, overflows, nor underflows. /// /// @note This can be implemented using any of the fundamental floating point types ( /// <code>float</code>, <code>double</code>, or <code>long double</code>). /// @note This can also be implemented using a <code>LiteralType</code> that has the necessary /// support: all common mathematical functions, support for infinity and NaN, and a /// specialization of the <code>std::numeric_limits</code> class template for it. /// @note At present, the <code>Fixed32</code> and <code>Fixed64</code> aliases of the /// <code>Fixed</code> template type are provided as examples of qualifying literal types /// though the usability of these are limited and their use is discouraged. /// /// @note Regarding division: /// - While dividing 1 by a real, caching the result, and then doing multiplications with the /// result may well be faster (than repeatedly dividing), dividing 1 by the real can also /// result in an underflow situation that's then compounded every time it's multiplied with /// other values. /// - Meanwhile, dividing every time by a real isolates any underflows to the particular /// division where underflow occurs. /// /// @warning Using <code>Fixed32</code> is not advised as its numerical limitations are more /// likely to result in problems like overflows or underflows. /// @warning The note regarding division applies even more so when using a fixed-point type /// (for <code>Real</code>). /// /// @see https://en.cppreference.com/w/cpp/language/types /// @see https://en.cppreference.com/w/cpp/types/is_floating_point /// @see https://en.cppreference.com/w/cpp/named_req/LiteralType /// using Real = float; } // namespace playrho #endif // PLAYRHO_COMMON_REAL_HPP
45.39726
94
0.742004
Hexlord
36e750b9077beed22edab1cb202f2df8794fb31d
1,000
cpp
C++
codeforces/A - Fancy Fence/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
1
2022-02-11T16:55:36.000Z
2022-02-11T16:55:36.000Z
codeforces/A - Fancy Fence/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
codeforces/A - Fancy Fence/Accepted.cpp
kzvd4729/Problem-Solving
13b105e725a4c2f8db7fecc5d7a8f932b9fef4ab
[ "MIT" ]
null
null
null
/**************************************************************************************** * @author: kzvd4729 created: Oct/09/2017 21:27 * solution_verdict: Accepted language: GNU C++14 * run_time: 0 ms memory_used: 0 KB * problem: https://codeforces.com/contest/270/problem/A ****************************************************************************************/ #include<bits/stdc++.h> #define long long long using namespace std; long t,a,vis[200]; int main() { ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0); cin>>t; while(t--) { for(long i=3;i<=1000;i++) { long x=(i-2)*180; if(x%i==0)vis[x/i]=1; } cin>>a; if(vis[a])cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
33.333333
111
0.337
kzvd4729
36e76fa676db29ff8af7e32fd96821479a2873e4
1,038
cpp
C++
Miscellaneous/Dynamic Programming/wildcard.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
24
2021-02-09T17:59:54.000Z
2022-03-11T07:30:38.000Z
Miscellaneous/Dynamic Programming/wildcard.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
null
null
null
Miscellaneous/Dynamic Programming/wildcard.cpp
chirag-singhal/-Data-Structures-and-Algorithms
9f01b5cc0f382ed59bcd74444a0be1c3aa6cd1a3
[ "MIT" ]
3
2021-06-22T03:09:49.000Z
2022-03-09T18:25:14.000Z
#include <iostream> int main() { int n, m; std::cout<<"Enter length of string : "; std::cin>>n; char str[n + 1]; std::cout<<"Enter string : "; std::cin>>str; std::cout<<"Enter length of pattern : "; std::cin>>m; char pat[m + 1]; std::cout<<"Enter pattern : "; std::cin>>pat; bool arr[n + 1][m + 1]; for(int i = 0; i <= n; i++) for(int j = 0; j <=m; j++) arr[i][j] = false; arr[0][0] = true; for(int i = 1; i <= m; i++) if(pat[i - 1] == '*') arr[0][i] = arr[0][i - 1]; for(int i = 0; i <= n; i++) { for(int j = 0; j <=m; j++) { if(pat[j - 1] == '*') arr[i][j] = arr[i - 1][j] || arr[i][j - 1]; else if(pat[j - 1] == '?' || pat[j - 1] == str[i - 1]) arr[i][j] = arr[i - 1][j - 1]; else arr[i][j] = false; } } if(arr[n][m]) std::cout<<"TRUE"<<std::endl; else std::cout<<"FALSE"<<std::endl; return 0; }
22.085106
66
0.381503
chirag-singhal
36e77dc424ba1f1b76f4c450deba1d04c17567b9
1,452
cpp
C++
usaco/section2.4/comehome.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
1
2017-10-13T10:34:46.000Z
2017-10-13T10:34:46.000Z
usaco/section2.4/comehome.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
usaco/section2.4/comehome.cpp
chasingegg/Online_Judge
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
[ "MIT" ]
null
null
null
/* PROG: comehome LANG: C++ */ //2017.5.12 //承接上题 用floyd算法求出最短路径 #include<iostream> #include<fstream> using namespace std; #define oo 1047400000 ifstream fin("comehome.in"); ofstream fout("comehome.out"); int P; int a[55][55], f[55]; int cha(char x) { if(x >= 'a' && x <= 'z') return x - 'a'; else if(x >= 'A' && x <= 'Z') { f[x - 'A' + 26] = 1; return x - 'A' + 26; } } void floyd() { for(int k = 0; k < 52; ++k) for(int i = 0; i < 52; ++i) for(int j = 0; j < 52; ++j) { if(a[i][k] + a[k][j] < a[i][j]) a[i][j] = a[i][k] + a[k][j]; } } int main() { fin >> P; int res = oo; char ch; for(int i = 0; i < 52; ++i) for(int j = 0; j < 52; ++j) { if(i != j) a[i][j] = oo; } for(int i = 0; i < P; ++i) { char c1, c2; int dis; int x, y; fin >> c1 >> c2 >> dis; x = cha(c1); y = cha(c2); //这两地方 导致此题很久没过 if(a[x][y] > dis) //这也很重要可能重复输入 { //不要忘记写两遍!!!这和邻接表的输入有区别 a[x][y] = dis; a[y][x] = dis; } } floyd(); for(int i = 26; i < 51; ++i) { if(f[i] && a[i][51] < res) { res = a[i][51]; ch = (char)(i + 'A' - 26); } } fout << ch << " " << res << endl; return 0; }
18.379747
48
0.356749
chasingegg
36e84838eea8780afe1b2e460e0675b0a94a633f
1,661
cpp
C++
Source/Magneto/Magnet/Magnet.cpp
AlecLafita/Magneto
8b7f1aab34572e9991717ffb7484b45ccecabe20
[ "MIT" ]
null
null
null
Source/Magneto/Magnet/Magnet.cpp
AlecLafita/Magneto
8b7f1aab34572e9991717ffb7484b45ccecabe20
[ "MIT" ]
null
null
null
Source/Magneto/Magnet/Magnet.cpp
AlecLafita/Magneto
8b7f1aab34572e9991717ffb7484b45ccecabe20
[ "MIT" ]
null
null
null
#include "Magnet.h" #include "MagnetRay.h" #include "Components/StaticMeshComponent.h" #include "Components/InputComponent.h" #include "GameFramework/PlayerController.h" #include "Kismet/KismetMathLibrary.h" AMagnet::AMagnet() { PrimaryActorTick.bCanEverTick = true; mMeshComponent = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("Mesh")); RootComponent = mMeshComponent; } void AMagnet::BeginPlay() { Super::BeginPlay(); } void AMagnet::Tick(float DeltaTime) { Super::Tick(DeltaTime); } void AMagnet::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); } void AMagnet::PostInitProperties() { Super::PostInitProperties(); UWorld* World = GetWorld(); if (mRayClass != nullptr && World != nullptr) { FActorSpawnParameters SpawnParams; SpawnParams.Owner = this; mRay = World->SpawnActor<AMagnetRay>(mRayClass, SpawnParams); mRay->AttachToActor(this, FAttachmentTransformRules::KeepRelativeTransform); mRay->SetActorHiddenInGame(true); } } void AMagnet::Fire(const FVector& aDestinationPoint) { mRay->SetActorHiddenInGame(false); RestartRay(); FRotator LookAt = UKismetMathLibrary::FindLookAtRotation(mRay->GetActorLocation(), aDestinationPoint); mRay->SetActorRotation(LookAt); mRay->FireInDirection(LookAt.Vector()); } void AMagnet::StopFire() { mRay->SetActorHiddenInGame(true); mRay->StopFire(); } void AMagnet::RestartRay() { FVector Origin; FVector BoxExtent; GetActorBounds(true, Origin, BoxExtent); //TODO add projectile size. Also this does not get the magnet size at all mRay->SetActorRelativeLocation(FVector(BoxExtent.X, 0.0f, 0.0f)); }
24.791045
103
0.771222
AlecLafita
36ed6a0238d1d1e593ef14937f6cb965cbe08ebc
247
cpp
C++
kontrolnya-rabota-1/task2/task2.cpp
MuKaTiR/orazbaev-timur-2021
2e44f1d336fbe87a0d096e0d9f56cfef6b98104f
[ "Apache-2.0" ]
null
null
null
kontrolnya-rabota-1/task2/task2.cpp
MuKaTiR/orazbaev-timur-2021
2e44f1d336fbe87a0d096e0d9f56cfef6b98104f
[ "Apache-2.0" ]
null
null
null
kontrolnya-rabota-1/task2/task2.cpp
MuKaTiR/orazbaev-timur-2021
2e44f1d336fbe87a0d096e0d9f56cfef6b98104f
[ "Apache-2.0" ]
null
null
null
#include<iostream> using namespace std; main() { int x, max, min, i = 2; cin >> min >> max; while (cin >> x) { i++; if (i % 2) { if (x < min) { min = x; } } else if (x > max) { max = x; } } cout << max + min; }
10.73913
24
0.425101
MuKaTiR
36fa294236a47a5d466d1326caf0c40ee7ff8f93
1,372
cpp
C++
GripPoints/DbDgnUnderlayGripPoints.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
1
2020-09-07T07:06:19.000Z
2020-09-07T07:06:19.000Z
GripPoints/DbDgnUnderlayGripPoints.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
null
null
null
GripPoints/DbDgnUnderlayGripPoints.cpp
terry-texas-us/Eo
5652b68468c0bacd8e8da732befa2374360a4bbd
[ "MIT" ]
2
2019-10-24T00:36:58.000Z
2020-09-30T16:45:56.000Z
#include <OdaCommon.h> #include "DbDgnUnderlayGripPoints.h" #include <DbUnderlayReference.h> #include <DbUnderlayDefinition.h> #include <Gi/GiDummyGeometry.h> #include <Ge/GeNurbCurve3d.h> OdResult OdDbDgnUnderlayGripPointsPE::getOsnapPoints(const OdDbEntity* entity, const OdDb::OsnapMode objectSnapMode, const OdGsMarker selectionMarker, const OdGePoint3d& pickPoint, const OdGePoint3d& lastPoint, const OdGeMatrix3d& worldToEyeTransform, OdGePoint3dArray& snapPoints) const { const auto DgnGripPointsModule {odrxDynamicLinker()->loadModule(ExDgnGripPointsModuleName)}; if (DgnGripPointsModule.isNull()) { return eTxError; } const auto Result {OdDbUnderlayGripPointsPE::getOsnapPoints(entity, objectSnapMode, selectionMarker, pickPoint, lastPoint, worldToEyeTransform, snapPoints)}; if (eOk == Result) { auto UnderlayReference {OdDbUnderlayReference::cast(entity)}; OdDbUnderlayDefinitionPtr UnderlayDefinition {UnderlayReference->definitionId().openObject()}; auto UnderlayItem {UnderlayDefinition->getUnderlayItem()}; OdIntArray GeometryIds; // NB: last parameter of this call needs to be changed to last parameter of this function return UnderlayItem->getOsnapPoints(UnderlayReference->transform(), objectSnapMode, selectionMarker, pickPoint, lastPoint, worldToEyeTransform, OdGeMatrix3d::kIdentity, snapPoints, GeometryIds); } return Result; }
57.166667
289
0.815598
terry-texas-us