hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
109
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
48.5k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
c13f9629a2b7f0e10d6fc6bf1220fe71c39b143a
895
cpp
C++
problem 1-50/21. Merge Two Sorted Lists.cpp
just-essential/LeetCode-Cpp
3ec49434d257defd28bfe4784ecd0ff2f9077a31
[ "MIT" ]
null
null
null
problem 1-50/21. Merge Two Sorted Lists.cpp
just-essential/LeetCode-Cpp
3ec49434d257defd28bfe4784ecd0ff2f9077a31
[ "MIT" ]
null
null
null
problem 1-50/21. Merge Two Sorted Lists.cpp
just-essential/LeetCode-Cpp
3ec49434d257defd28bfe4784ecd0ff2f9077a31
[ "MIT" ]
null
null
null
/* Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 */ class Solution { public: ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { ListNode head(0), *l3 = &head; while (l1 && l2) { if (l1->val < l2->val) { l3->next = l1; l1 = l1->next; } else { l3->next = l2; l2 = l2->next; } l3 = l3->next; } if (l1) { l3->next = l1; } else { l3->next = l2; } return head.next; } void test() { assert(listNodeToString(mergeTwoLists(stringToListNode("[1,2,4]"), stringToListNode("[1,3,4]"))) == "[1, 1, 2, 3, 4, 4]"); } };
24.861111
141
0.459218
just-essential
c14a9437c1fa8ad7de2a867bc432c5242a18810b
13,023
cpp
C++
3rdparty/FlyCube/src/Apps/CoreDxrTriangle/main.cpp
CU-Production/FlyCube-Demos
2763720818499bc9244eb4b16e60e647a5c88827
[ "MIT" ]
8
2021-03-17T19:25:12.000Z
2022-02-05T02:08:21.000Z
3rdparty/FlyCube/src/Apps/CoreDxrTriangle/main.cpp
THISISAGOODNAME/SSSR
ea4b6350b2da3d5656c7aa8c87f9965144369d22
[ "MIT" ]
null
null
null
3rdparty/FlyCube/src/Apps/CoreDxrTriangle/main.cpp
THISISAGOODNAME/SSSR
ea4b6350b2da3d5656c7aa8c87f9965144369d22
[ "MIT" ]
2
2021-09-22T14:39:51.000Z
2021-11-08T09:47:38.000Z
#include <AppBox/AppBox.h> #include <AppBox/ArgsParser.h> #include <Instance/Instance.h> #include <stdexcept> #include <glm/gtx/transform.hpp> #include <Utilities/Common.h> int main(int argc, char* argv[]) { Settings settings = ParseArgs(argc, argv); AppBox app("CoreDxrTriangle", settings); AppRect rect = app.GetAppRect(); std::shared_ptr<Instance> instance = CreateInstance(settings.api_type); std::shared_ptr<Adapter> adapter = std::move(instance->EnumerateAdapters()[settings.required_gpu_index]); app.SetGpuName(adapter->GetName()); std::shared_ptr<Device> device = adapter->CreateDevice(); if (!device->IsDxrSupported()) throw std::runtime_error("Ray Tracing is not supported"); std::shared_ptr<CommandQueue> command_queue = device->GetCommandQueue(CommandListType::kGraphics); std::shared_ptr<CommandQueue> upload_command_queue = device->GetCommandQueue(CommandListType::kGraphics); constexpr uint32_t frame_count = 3; std::shared_ptr<Swapchain> swapchain = device->CreateSwapchain(app.GetNativeWindow(), rect.width, rect.height, frame_count, settings.vsync); uint64_t fence_value = 0; std::shared_ptr<Fence> fence = device->CreateFence(fence_value); std::vector<uint32_t> index_data = { 0, 1, 2 }; std::shared_ptr<Resource> index_buffer = device->CreateBuffer(BindFlag::kIndexBuffer | BindFlag::kCopyDest, sizeof(uint32_t) * index_data.size()); index_buffer->CommitMemory(MemoryType::kDefault); index_buffer->SetName("index_buffer"); std::vector<glm::vec3> vertex_data = { glm::vec3(-0.5, -0.5, 0.0), glm::vec3(0.0, 0.5, 0.0), glm::vec3(0.5, -0.5, 0.0) }; std::shared_ptr<Resource> vertex_buffer = device->CreateBuffer(BindFlag::kVertexBuffer | BindFlag::kCopyDest, sizeof(vertex_data.front()) * vertex_data.size()); vertex_buffer->CommitMemory(MemoryType::kDefault); vertex_buffer->SetName("vertex_buffer"); std::shared_ptr<Resource> upload_buffer = device->CreateBuffer(BindFlag::kCopySource, index_buffer->GetWidth() + vertex_buffer->GetWidth()); upload_buffer->CommitMemory(MemoryType::kUpload); upload_buffer->SetName("upload_buffer"); upload_buffer->UpdateUploadBuffer(0, index_data.data(), sizeof(index_data.front()) * index_data.size()); upload_buffer->UpdateUploadBuffer(index_buffer->GetWidth(), vertex_data.data(), sizeof(vertex_data.front()) * vertex_data.size()); std::shared_ptr<CommandList> upload_command_list = device->CreateCommandList(CommandListType::kGraphics); upload_command_list->CopyBuffer(upload_buffer, index_buffer, { { 0, 0, index_buffer->GetWidth() } }); upload_command_list->CopyBuffer(upload_buffer, vertex_buffer, { { index_buffer->GetWidth(), 0, vertex_buffer->GetWidth() } }); upload_command_list->ResourceBarrier({ { index_buffer, ResourceState::kCopyDest, ResourceState::kNonPixelShaderResource } }); upload_command_list->ResourceBarrier({ { vertex_buffer, ResourceState::kCopyDest, ResourceState::kNonPixelShaderResource } }); RaytracingGeometryDesc raytracing_geometry_desc = { { vertex_buffer, gli::format::FORMAT_RGB32_SFLOAT_PACK32, 3 }, { index_buffer, gli::format::FORMAT_R32_UINT_PACK32, 3 }, RaytracingGeometryFlags::kOpaque }; const uint32_t bottom_count = 2; auto blas_prebuild_info = device->GetBLASPrebuildInfo({ raytracing_geometry_desc }, BuildAccelerationStructureFlags::kAllowCompaction); auto tlas_prebuild_info = device->GetTLASPrebuildInfo(bottom_count, BuildAccelerationStructureFlags::kNone); uint64_t acceleration_structures_size = Align(blas_prebuild_info.acceleration_structure_size, kAccelerationStructureAlignment) + tlas_prebuild_info.acceleration_structure_size; std::shared_ptr<Resource> acceleration_structures_memory = device->CreateBuffer(BindFlag::kAccelerationStructure, acceleration_structures_size); acceleration_structures_memory->CommitMemory(MemoryType::kDefault); acceleration_structures_memory->SetName("acceleration_structures_memory"); std::shared_ptr<Resource> bottom = device->CreateAccelerationStructure( AccelerationStructureType::kBottomLevel, acceleration_structures_memory, 0 ); auto scratch = device->CreateBuffer(BindFlag::kRayTracing, std::max(blas_prebuild_info.build_scratch_data_size, tlas_prebuild_info.build_scratch_data_size)); scratch->CommitMemory(MemoryType::kDefault); scratch->SetName("scratch"); auto blas_compacted_size_buffer = device->CreateBuffer(BindFlag::kCopyDest, sizeof(uint64_t)); blas_compacted_size_buffer->CommitMemory(MemoryType::kReadback); blas_compacted_size_buffer->SetName("blas_compacted_size_buffer"); auto query_heap = device->CreateQueryHeap(QueryHeapType::kAccelerationStructureCompactedSize, 1); upload_command_list->BuildBottomLevelAS({}, bottom, scratch, 0, { raytracing_geometry_desc }, BuildAccelerationStructureFlags::kAllowCompaction); upload_command_list->UAVResourceBarrier(bottom); upload_command_list->WriteAccelerationStructuresProperties({ bottom }, query_heap, 0); upload_command_list->ResolveQueryData(query_heap, 0, 1, blas_compacted_size_buffer, 0); upload_command_list->Close(); upload_command_queue->ExecuteCommandLists({ upload_command_list }); upload_command_queue->Signal(fence, ++fence_value); fence->Wait(fence_value); uint64_t blas_compacted_size = *reinterpret_cast<uint64_t*>(blas_compacted_size_buffer->Map()); blas_compacted_size_buffer->Unmap(); upload_command_list->Reset(); upload_command_list->CopyAccelerationStructure(bottom, bottom, CopyAccelerationStructureMode::kCompact); std::vector<std::pair<std::shared_ptr<Resource>, glm::mat4x4>> geometry = { { bottom, glm::transpose(glm::translate(glm::vec3(-0.5f, 0.0f, 0.0f))) }, { bottom, glm::transpose(glm::translate(glm::vec3(0.5f, 0.0f, 0.0f))) }, }; assert(geometry.size() == bottom_count); std::vector<RaytracingGeometryInstance> instances; for (const auto& mesh : geometry) { RaytracingGeometryInstance& instance = instances.emplace_back(); memcpy(&instance.transform, &mesh.second, sizeof(instance.transform)); instance.instance_offset = static_cast<uint32_t>(instances.size() - 1); instance.instance_mask = 0xff; instance.acceleration_structure_handle = mesh.first->GetAccelerationStructureHandle(); } std::shared_ptr<Resource> top = device->CreateAccelerationStructure( AccelerationStructureType::kTopLevel, acceleration_structures_memory, Align(blas_compacted_size, kAccelerationStructureAlignment) ); auto instance_data = device->CreateBuffer(BindFlag::kRayTracing, instances.size() * sizeof(instances.back())); instance_data->CommitMemory(MemoryType::kUpload); instance_data->SetName("instance_data"); instance_data->UpdateUploadBuffer(0, instances.data(), instances.size() * sizeof(instances.back())); upload_command_list->BuildTopLevelAS({}, top, scratch, 0, instance_data, 0, instances.size(), BuildAccelerationStructureFlags::kNone); upload_command_list->UAVResourceBarrier(top); std::shared_ptr<Resource> uav = device->CreateTexture(TextureType::k2D, BindFlag::kUnorderedAccess | BindFlag::kCopySource, swapchain->GetFormat(), 1, rect.width, rect.height, 1, 1); uav->CommitMemory(MemoryType::kDefault); uav->SetName("uav"); upload_command_list->ResourceBarrier({ { uav, uav->GetInitialState(), ResourceState::kUnorderedAccess } }); upload_command_list->Close(); upload_command_queue->ExecuteCommandLists({ upload_command_list }); upload_command_queue->Signal(fence, ++fence_value); command_queue->Wait(fence, fence_value); ViewDesc top_view_desc = {}; top_view_desc.view_type = ViewType::kAccelerationStructure; std::shared_ptr<View> top_view = device->CreateView(top, top_view_desc); ViewDesc uav_view_desc = {}; uav_view_desc.view_type = ViewType::kRWTexture; uav_view_desc.dimension = ViewDimension::kTexture2D; std::shared_ptr<View> uav_view = device->CreateView(uav, uav_view_desc); std::shared_ptr<Shader> library = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracing.hlsl", "", ShaderType::kLibrary, "6_3" }); std::shared_ptr<Shader> library_hit = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracingHit.hlsl", "", ShaderType::kLibrary, "6_3" }); std::shared_ptr<Shader> library_callable = device->CompileShader({ ASSETS_PATH"shaders/CoreDxrTriangle/RayTracingCallable.hlsl", "", ShaderType::kLibrary, "6_3" }); std::shared_ptr<Program> program = device->CreateProgram({ library, library_hit, library_callable }); BindKey geometry_key = library->GetBindKey("geometry"); BindKey result_key = library->GetBindKey("result"); std::shared_ptr<BindingSetLayout> layout = device->CreateBindingSetLayout({ geometry_key, result_key }); std::shared_ptr<BindingSet> binding_set = device->CreateBindingSet(layout); binding_set->WriteBindings({ { geometry_key, top_view }, { result_key, uav_view } }); std::vector<RayTracingShaderGroup> groups; groups.push_back({ RayTracingShaderGroupType::kGeneral, library->GetId("ray_gen") }); groups.push_back({ RayTracingShaderGroupType::kGeneral, library->GetId("miss") }); groups.push_back({ RayTracingShaderGroupType::kTrianglesHitGroup, 0, library_hit->GetId("closest_red") }); groups.push_back({ RayTracingShaderGroupType::kTrianglesHitGroup, 0, library_hit->GetId("closest_green") }); groups.push_back({ RayTracingShaderGroupType::kGeneral, library_callable->GetId("callable") }); std::shared_ptr<Pipeline> pipeline = device->CreateRayTracingPipeline({ program, layout, groups }); std::shared_ptr<Resource> shader_table = device->CreateBuffer(BindFlag::kShaderTable, device->GetShaderTableAlignment() * groups.size()); shader_table->CommitMemory(MemoryType::kUpload); shader_table->SetName("shader_table"); decltype(auto) shader_handles = pipeline->GetRayTracingShaderGroupHandles(0, groups.size()); for (size_t i = 0; i < groups.size(); ++i) { shader_table->UpdateUploadBuffer(i * device->GetShaderTableAlignment(), shader_handles.data() + i * device->GetShaderGroupHandleSize(), device->GetShaderGroupHandleSize()); } RayTracingShaderTables shader_tables = {}; shader_tables.raygen = { shader_table, 0 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; shader_tables.miss = { shader_table, 1 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; shader_tables.hit = { shader_table, 2 * device->GetShaderTableAlignment(), 2 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; shader_tables.callable = { shader_table, 4 * device->GetShaderTableAlignment(), device->GetShaderTableAlignment(), device->GetShaderTableAlignment() }; std::array<uint64_t, frame_count> fence_values = {}; std::vector<std::shared_ptr<CommandList>> command_lists; for (uint32_t i = 0; i < frame_count; ++i) { std::shared_ptr<Resource> back_buffer = swapchain->GetBackBuffer(i); ViewDesc back_buffer_view_desc = {}; back_buffer_view_desc.view_type = ViewType::kRenderTarget; back_buffer_view_desc.dimension = ViewDimension::kTexture2D; std::shared_ptr<View> back_buffer_view = device->CreateView(back_buffer, back_buffer_view_desc); command_lists.emplace_back(device->CreateCommandList(CommandListType::kGraphics)); std::shared_ptr<CommandList> command_list = command_lists[i]; command_list->BindPipeline(pipeline); command_list->BindBindingSet(binding_set); command_list->DispatchRays(shader_tables, rect.width, rect.height, 1); command_list->ResourceBarrier({ { back_buffer, ResourceState::kPresent, ResourceState::kCopyDest } }); command_list->ResourceBarrier({ { uav, ResourceState::kUnorderedAccess, ResourceState::kCopySource } }); command_list->CopyTexture(uav, back_buffer, { { rect.width, rect.height, 1 } }); command_list->ResourceBarrier({ { uav, ResourceState::kCopySource, ResourceState::kUnorderedAccess } }); command_list->ResourceBarrier({ { back_buffer, ResourceState::kCopyDest, ResourceState::kPresent } }); command_list->Close(); } while (!app.PollEvents()) { uint32_t frame_index = swapchain->NextImage(fence, ++fence_value); command_queue->Wait(fence, fence_value); fence->Wait(fence_values[frame_index]); command_queue->ExecuteCommandLists({ command_lists[frame_index] }); command_queue->Signal(fence, fence_values[frame_index] = ++fence_value); swapchain->Present(fence, fence_values[frame_index]); } command_queue->Signal(fence, ++fence_value); fence->Wait(fence_value); return 0; }
61.140845
186
0.744222
CU-Production
c14ea670d80601a960264ee8bca5a1cbd59b206b
67,124
cpp
C++
common/BaseDatapath.cpp
httsai/NTHU_Aladdin
4140fcdade512b89647608b9b724690c5d3b2ba4
[ "BSL-1.0" ]
null
null
null
common/BaseDatapath.cpp
httsai/NTHU_Aladdin
4140fcdade512b89647608b9b724690c5d3b2ba4
[ "BSL-1.0" ]
null
null
null
common/BaseDatapath.cpp
httsai/NTHU_Aladdin
4140fcdade512b89647608b9b724690c5d3b2ba4
[ "BSL-1.0" ]
null
null
null
#include <sstream> #include <boost/tokenizer.hpp> #include "opcode_func.h" #include "BaseDatapath.h" BaseDatapath::BaseDatapath(std::string bench, string trace_file, string config_file, float cycle_t) { benchName = (char*) bench.c_str(); cycleTime = cycle_t; DDDG *dddg; dddg = new DDDG(this, trace_file); /*Build Initial DDDG*/ if (dddg->build_initial_dddg()) { std::cerr << "-------------------------------" << std::endl; std::cerr << " Aladdin Ends.. " << std::endl; std::cerr << "-------------------------------" << std::endl; exit(0); } delete dddg; std::cerr << "-------------------------------" << std::endl; std::cerr << " Initializing BaseDatapath " << std::endl; std::cerr << "-------------------------------" << std::endl; numTotalNodes = microop.size(); BGL_FORALL_VERTICES(v, graph_, Graph) nameToVertex[get(boost::vertex_index, graph_, v)] = v; vertexToName = get(boost::vertex_index, graph_); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); initDynamicMethodID(dynamic_methodid); for (auto dynamic_func_it = dynamic_methodid.begin(), E = dynamic_methodid.end(); dynamic_func_it != E; dynamic_func_it++) { char func_id[256]; int count; sscanf((*dynamic_func_it).c_str(), "%[^-]-%d\n", func_id, &count); if (functionNames.find(func_id) == functionNames.end()) functionNames.insert(func_id); } parse_config(bench, config_file); num_cycles = 0; } BaseDatapath::~BaseDatapath() {} void BaseDatapath::addDddgEdge(unsigned int from, unsigned int to, uint8_t parid) { if (from != to) add_edge(from, to, EdgeProperty(parid), graph_); } //optimizationFunctions void BaseDatapath::setGlobalGraph() { std::cerr << "=============================================" << std::endl; std::cerr << " Optimizing... " << benchName << std::endl; std::cerr << "=============================================" << std::endl; finalIsolated.assign(numTotalNodes, 1); } void BaseDatapath::memoryAmbiguation() { std::cerr << "-------------------------------" << std::endl; std::cerr << " Memory Ambiguation " << std::endl; std::cerr << "-------------------------------" << std::endl; std::unordered_multimap<std::string, std::string> pair_per_load; std::unordered_set<std::string> paired_store; std::unordered_map<std::string, bool> store_load_pair; std::vector<std::string> instid(numTotalNodes, ""); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); std::vector<std::string> prev_basic_block(numTotalNodes, ""); initInstID(instid); initDynamicMethodID(dynamic_methodid); initPrevBasicBlock(prev_basic_block); std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //nodes with no incoming edges to first for (auto vi = topo_nodes.rbegin(); vi != topo_nodes.rend(); ++vi) { unsigned node_id = vertexToName[*vi]; int node_microop = microop.at(node_id); if (!is_store_op(node_microop)) continue; //iterate its children to find a load op out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(*vi, graph_); out_edge_it != out_edge_end; ++out_edge_it) { int child_id = vertexToName[target(*out_edge_it, graph_)]; int child_microop = microop.at(child_id); if (!is_load_op(child_microop)) continue; std::string node_dynamic_methodid = dynamic_methodid.at(node_id); std::string load_dynamic_methodid = dynamic_methodid.at(child_id); if (node_dynamic_methodid.compare(load_dynamic_methodid) != 0) continue; std::string store_unique_id (node_dynamic_methodid + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); std::string load_unique_id (load_dynamic_methodid+ "-" + instid.at(child_id) + "-" + prev_basic_block.at(child_id)); if (store_load_pair.find(store_unique_id + "-" + load_unique_id ) != store_load_pair.end()) continue; //add to the pair store_load_pair[store_unique_id + "-" + load_unique_id] = 1; paired_store.insert(store_unique_id); auto load_range = pair_per_load.equal_range(load_unique_id); bool found_store = 0; for (auto store_it = load_range.first; store_it != load_range.second; store_it++) { if (store_unique_id.compare(store_it->second) == 0) { found_store = 1; break; } } if (!found_store) { pair_per_load.insert(make_pair(load_unique_id,store_unique_id)); } } } if (store_load_pair.size() == 0) return; std::vector<newEdge> to_add_edges; std::unordered_map<std::string, unsigned> last_store; for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) { int node_microop = microop.at(node_id); if (!is_memory_op(node_microop)) continue; std::string unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); if (is_store_op(node_microop)) { auto store_it = paired_store.find(unique_id); if (store_it == paired_store.end()) continue; last_store[unique_id] = node_id; } else { assert(is_load_op(node_microop)); auto load_range = pair_per_load.equal_range(unique_id); if (std::distance(load_range.first, load_range.second) == 1) continue; for (auto load_store_it = load_range.first; load_store_it != load_range.second; ++load_store_it) { assert(paired_store.find(load_store_it->second) != paired_store.end()); auto prev_store_it = last_store.find(load_store_it->second); if (prev_store_it == last_store.end()) continue; unsigned prev_store_id = prev_store_it->second; if (!doesEdgeExist(prev_store_id, node_id)) { to_add_edges.push_back({prev_store_id, node_id, -1}); dynamicMemoryOps.insert(load_store_it->second + "-" + prev_basic_block.at(prev_store_id)); dynamicMemoryOps.insert(load_store_it->first + "-" + prev_basic_block.at(node_id)); } } } } updateGraphWithNewEdges(to_add_edges); } /* * Read: graph_, microop * Modify: graph_ */ void BaseDatapath::removePhiNodes() { std::cerr << "-------------------------------" << std::endl; std::cerr << " Remove PHI and BitCast Nodes " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; vertex_iter vi, vi_end; int removed_phi = 0; for (tie(vi, vi_end) = vertices(graph_); vi != vi_end; ++vi) { unsigned node_id = vertexToName[*vi]; int node_microop = microop.at(node_id); if (node_microop != LLVM_IR_PHI && node_microop != LLVM_IR_BitCast) continue; //find its children std::vector< pair<unsigned, int> > phi_child; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(*vi, graph_); out_edge_it != out_edge_end; ++out_edge_it) { to_remove_edges.insert(*out_edge_it); phi_child.push_back(make_pair(vertexToName[target(*out_edge_it, graph_)], edge_to_parid[*out_edge_it])); } if (phi_child.size() == 0) continue; //find its parents in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(*vi, graph_); in_edge_it != in_edge_end; ++in_edge_it) { unsigned parent_id = vertexToName[source(*in_edge_it, graph_)]; to_remove_edges.insert(*in_edge_it); for (auto child_it = phi_child.begin(), chil_E = phi_child.end(); child_it != chil_E; ++child_it) to_add_edges.push_back({parent_id, child_it->first, child_it->second}); } std::vector<pair<unsigned, int> >().swap(phi_child); removed_phi++; } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } /* * Read: lineNum.gz, flattenConfig, microop * Modify: graph_ */ void BaseDatapath::loopFlatten() { std::unordered_set<int> flatten_config; if (!readFlattenConfig(flatten_config)) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Loop Flatten " << std::endl; std::cerr << "-------------------------------" << std::endl; std::vector<int> lineNum(numTotalNodes, -1); initLineNum(lineNum); std::vector<unsigned> to_remove_nodes; for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { int node_linenum = lineNum.at(node_id); auto it = flatten_config.find(node_linenum); if (it == flatten_config.end()) continue; if (is_compute_op(microop.at(node_id))) microop.at(node_id) = LLVM_IR_Move; else if (is_branch_op(microop.at(node_id))) to_remove_nodes.push_back(node_id); } updateGraphWithIsolatedNodes(to_remove_nodes); cleanLeafNodes(); } void BaseDatapath::cleanLeafNodes() { EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); /*track the number of children each node has*/ std::vector<int> num_of_children(numTotalNodes, 0); std::vector<unsigned> to_remove_nodes; std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //bottom nodes first for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) { Vertex node_vertex = *vi; if (boost::degree(node_vertex, graph_) == 0) continue; unsigned node_id = vertexToName[node_vertex]; int node_microop = microop.at(node_id); if (num_of_children.at(node_id) == boost::out_degree(node_vertex, graph_) && node_microop != LLVM_IR_SilentStore && node_microop != LLVM_IR_Store && node_microop != LLVM_IR_Ret && !is_branch_op(node_microop)) { to_remove_nodes.push_back(node_id); //iterate its parents in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(node_vertex, graph_); in_edge_it != in_edge_end; ++in_edge_it) { int parent_id = vertexToName[source(*in_edge_it, graph_)]; num_of_children.at(parent_id)++; } } else if (is_branch_op(node_microop)) { //iterate its parents in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(node_vertex, graph_); in_edge_it != in_edge_end; ++in_edge_it) { if (edge_to_parid[*in_edge_it] == CONTROL_EDGE) { int parent_id = vertexToName[source(*in_edge_it, graph_)]; num_of_children.at(parent_id)++; } } } } updateGraphWithIsolatedNodes(to_remove_nodes); } /* * Read: graph_, instid, microop * Modify: microop */ void BaseDatapath::removeInductionDependence() { //set graph std::cerr << "-------------------------------" << std::endl; std::cerr << " Remove Induction Dependence " << std::endl; std::cerr << "-------------------------------" << std::endl; std::vector<std::string> instid(numTotalNodes, ""); initInstID(instid); std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //nodes with no incoming edges to first for (auto vi = topo_nodes.rbegin(); vi != topo_nodes.rend(); ++vi) { unsigned node_id = vertexToName[*vi]; std::string node_instid = instid.at(node_id); if (node_instid.find("indvars") == std::string::npos) continue; if (microop.at(node_id) == LLVM_IR_Add ) microop.at(node_id) = LLVM_IR_IndexAdd; } } //called in the end of the whole flow void BaseDatapath::dumpStats() { clearGraph(); dumpGraph(); writeMicroop(microop); writeFinalLevel(); writeGlobalIsolated(); } void BaseDatapath::loopPipelining() { if (!readPipeliningConfig()) { std::cerr << "Loop Pipelining is not ON." << std::endl; return ; } std::unordered_map<int, int > unrolling_config; if (!readUnrollingConfig(unrolling_config)) { std::cerr << "Loop Unrolling is not defined. " << std::endl; std::cerr << "Loop pipelining is only applied to unrolled loops." << std::endl; return ; } if (loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Loop Pipelining " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); vertex_iter vi, vi_end; std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; //After loop unrolling, we define strict control dependences between basic block, //where all the instructions in the following basic block depend on the prev branch instruction //To support loop pipelining, which allows the next iteration //starting without waiting until the prev iteration finish, we move the control dependences //between last branch node in the prev basic block and instructions in the next basic block //to first non isolated instruction in the prev basic block and instructions in the next basic block... std::map<unsigned, unsigned> first_non_isolated_node; auto bound_it = loopBound.begin(); unsigned node_id = *bound_it; //skip first region bound_it++; while ( (unsigned)node_id < numTotalNodes) { assert(is_branch_op(microop.at(*bound_it))); while (node_id < *bound_it && (unsigned) node_id < numTotalNodes) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0 || is_branch_op(microop.at(node_id)) ) { node_id++; continue; } else { first_non_isolated_node[*bound_it] = node_id; node_id = *bound_it; break; } } if (first_non_isolated_node.find(*bound_it) == first_non_isolated_node.end()) first_non_isolated_node[*bound_it] = *bound_it; bound_it++; if (bound_it == loopBound.end() - 1 ) break; } int prev_branch = -1; int prev_first = -1; for(auto first_it = first_non_isolated_node.begin(), E = first_non_isolated_node.end(); first_it != E; ++first_it) { unsigned br_node = first_it->first; unsigned first_id = first_it->second; if (is_call_op(microop.at(br_node))) { prev_branch = -1; continue; } if (prev_branch != -1) { //adding dependence between prev_first and first_id if (!doesEdgeExist(prev_first, first_id)) to_add_edges.push_back({(unsigned)prev_first, first_id, CONTROL_EDGE}); //adding dependence between first_id and prev_branch's children out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[prev_branch], graph_); out_edge_it != out_edge_end; ++out_edge_it) { Vertex child_vertex = target(*out_edge_it, graph_); unsigned child_id = vertexToName[child_vertex]; if (child_id <= first_id || edge_to_parid[*out_edge_it] != CONTROL_EDGE) continue; if (!doesEdgeExist(first_id, child_id)) to_add_edges.push_back({first_id, child_id, 1}); } } //update first_id's parents, dependence become strict control dependence in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[first_id], graph_); in_edge_it != in_edge_end; ++in_edge_it) { Vertex parent_vertex = source(*in_edge_it, graph_); unsigned parent_id = vertexToName[parent_vertex]; if (is_branch_op(microop.at(parent_id))) continue; to_remove_edges.insert(*in_edge_it); to_add_edges.push_back({parent_id, first_id, CONTROL_EDGE}); } //remove control dependence between br node to its children out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[br_node], graph_); out_edge_it != out_edge_end; ++out_edge_it) { if (is_call_op(microop.at(vertexToName[target(*out_edge_it, graph_)]))) continue; if (edge_to_parid[*out_edge_it] != CONTROL_EDGE) continue; to_remove_edges.insert(*out_edge_it); } prev_branch = br_node; prev_first = first_id; } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } /* * Read: graph_, lineNum.gz, unrollingConfig, microop * Modify: graph_ * Write: loop_bound */ void BaseDatapath::loopUnrolling() { std::unordered_map<int, int > unrolling_config; readUnrollingConfig(unrolling_config); std::cerr << "-------------------------------" << std::endl; std::cerr << " Loop Unrolling " << std::endl; std::cerr << "-------------------------------" << std::endl; std::vector<unsigned> to_remove_nodes; std::unordered_map<std::string, unsigned> inst_dynamic_counts; std::vector<unsigned> nodes_between; std::vector<newEdge> to_add_edges; std::vector<int> lineNum(numTotalNodes, -1); initLineNum(lineNum); bool first = false; int iter_counts = 0; int prev_branch = -1; for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { if (nameToVertex.find(node_id) == nameToVertex.end()) continue; Vertex node_vertex = nameToVertex[node_id]; if (boost::degree(node_vertex, graph_) == 0 && !is_call_op(microop.at(node_id))) continue; if (!first) { first = true; loopBound.push_back(node_id); prev_branch = node_id; } assert(prev_branch != -1); if (prev_branch != node_id && !(is_dma_op(microop.at(prev_branch)) && is_dma_op(microop.at(node_id))) ) { to_add_edges.push_back({(unsigned)prev_branch, node_id, CONTROL_EDGE}); } if (!is_branch_op(microop.at(node_id))) nodes_between.push_back(node_id); else { //for the case that the first non-isolated node is also a call node; if (is_call_op(microop.at(node_id)) && *loopBound.rbegin() != node_id) { loopBound.push_back(node_id); prev_branch = node_id; } int node_linenum = lineNum.at(node_id); auto unroll_it = unrolling_config.find(node_linenum); //not unrolling branch if (unroll_it == unrolling_config.end()) { if (!is_call_op(microop.at(node_id))) { nodes_between.push_back(node_id); continue; } // Enforce dependences between branch nodes, including call nodes // Except for the case that both two branches are DMA operations. // (Two DMA operations can go in parallel.) if (!doesEdgeExist(prev_branch, node_id) && !( is_dma_op(microop.at(prev_branch)) && is_dma_op(microop.at(node_id)) ) ) to_add_edges.push_back({(unsigned)prev_branch, node_id, CONTROL_EDGE}); for (auto prev_node_it = nodes_between.begin(), E = nodes_between.end(); prev_node_it != E; prev_node_it++) { if (!doesEdgeExist(*prev_node_it, node_id) && !( is_dma_op(microop.at(*prev_node_it)) && is_dma_op(microop.at(node_id)) ) ) { to_add_edges.push_back({*prev_node_it, node_id, CONTROL_EDGE}); } } nodes_between.clear(); nodes_between.push_back(node_id); prev_branch = node_id; } else { int factor = unroll_it->second; int node_microop = microop.at(node_id); char unique_inst_id[256]; sprintf(unique_inst_id, "%d-%d", node_microop, node_linenum); auto it = inst_dynamic_counts.find(unique_inst_id); if (it == inst_dynamic_counts.end()) { inst_dynamic_counts[unique_inst_id] = 1; it = inst_dynamic_counts.find(unique_inst_id); } else it->second++; if (it->second % factor == 0) { loopBound.push_back(node_id); iter_counts++; for (auto prev_node_it = nodes_between.begin(), E = nodes_between.end(); prev_node_it != E; prev_node_it++) { if (!doesEdgeExist(*prev_node_it, node_id)) { to_add_edges.push_back({*prev_node_it, node_id, CONTROL_EDGE}); } } nodes_between.clear(); nodes_between.push_back(node_id); prev_branch = node_id; } else to_remove_nodes.push_back(node_id); } } } loopBound.push_back(numTotalNodes); if (iter_counts == 0 && unrolling_config.size() != 0 ) { std::cerr << "-------------------------------" << std::endl; std::cerr << "Loop Unrolling Factor is Larger than the Loop Trip Count." << std::endl; std::cerr << "Loop Unrolling is NOT applied. Please choose a smaller " << "unrolling factor." << std::endl; std::cerr << "-------------------------------" << std::endl; } updateGraphWithNewEdges(to_add_edges); updateGraphWithIsolatedNodes(to_remove_nodes); cleanLeafNodes(); } /* * Read: loop_bound, flattenConfig, graph, actualAddress, microop * Modify: graph_ */ void BaseDatapath::removeSharedLoads() { std::unordered_set<int> flatten_config; if (!readFlattenConfig(flatten_config)&& loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Load Buffer " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::unordered_map<unsigned, long long int> address; initAddress(address); vertex_iter vi, vi_end; std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; int shared_loads = 0; auto bound_it = loopBound.begin(); unsigned node_id = 0; while ( (unsigned)node_id < numTotalNodes) { std::unordered_map<unsigned, unsigned> address_loaded; while (node_id < *bound_it && (unsigned) node_id < numTotalNodes) { if (nameToVertex.find(node_id) == nameToVertex.end()) { node_id++; continue; } if (boost::degree(nameToVertex[node_id], graph_) == 0) { node_id++; continue; } int node_microop = microop.at(node_id); long long int node_address = address[node_id]; auto addr_it = address_loaded.find(node_address); if (is_store_op(node_microop) && addr_it != address_loaded.end()) address_loaded.erase(addr_it); else if (is_load_op(node_microop)) { if (addr_it == address_loaded.end()) address_loaded[node_address] = node_id; else { shared_loads++; microop.at(node_id) = LLVM_IR_Move; unsigned prev_load = addr_it->second; //iterate through its children Vertex load_node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(load_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { Edge curr_edge = *out_edge_it; Vertex child_vertex = target(curr_edge, graph_); unsigned child_id = vertexToName[child_vertex]; Vertex prev_load_vertex = nameToVertex[prev_load]; if (!doesEdgeExistVertex(prev_load_vertex, child_vertex)) to_add_edges.push_back({prev_load, child_id, edge_to_parid[curr_edge]}); to_remove_edges.insert(*out_edge_it); } in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(load_node, graph_); in_edge_it != in_edge_end; ++in_edge_it) to_remove_edges.insert(*in_edge_it); } } node_id++; } bound_it++; if (bound_it == loopBound.end() ) break; } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } /* * Read: loopBound, flattenConfig, graph_, instid, dynamicMethodID, * prevBasicBlock * Modify: graph_ */ void BaseDatapath::storeBuffer() { if (loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Store Buffer " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::vector<std::string> instid(numTotalNodes, ""); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); std::vector<std::string> prev_basic_block(numTotalNodes, ""); initInstID(instid); initDynamicMethodID(dynamic_methodid); initPrevBasicBlock(prev_basic_block); std::vector<newEdge> to_add_edges; std::vector<unsigned> to_remove_nodes; auto bound_it = loopBound.begin(); unsigned node_id = 0; while (node_id < numTotalNodes) { while (node_id < *bound_it && node_id < numTotalNodes) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0) { ++node_id; continue; } if (is_store_op(microop.at(node_id))) { //remove this store std::string store_unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); //dynamic stores, cannot disambiguated in the static time, cannot remove if (dynamicMemoryOps.find(store_unique_id) != dynamicMemoryOps.end()) { ++node_id; continue; } Vertex node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; std::vector<Vertex> store_child; for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { Vertex child_vertex = target(*out_edge_it, graph_); int child_id = vertexToName[child_vertex]; if (is_load_op(microop.at(child_id))) { std::string load_unique_id (dynamic_methodid.at(child_id) + "-" + instid.at(child_id) + "-" + prev_basic_block.at(child_id)); if (dynamicMemoryOps.find(load_unique_id) != dynamicMemoryOps.end() || child_id >= (unsigned)*bound_it ) continue; else store_child.push_back(child_vertex); } } if (store_child.size() > 0) { bool parent_found = false; Vertex store_parent; in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(node, graph_); in_edge_it != in_edge_end; ++in_edge_it) { //parent node that generates value if (edge_to_parid[*in_edge_it] == 1) { parent_found = true; store_parent = source(*in_edge_it, graph_); break; } } if (parent_found) { for (auto load_it = store_child.begin(), E = store_child.end(); load_it != E; ++load_it) { Vertex load_node = *load_it; to_remove_nodes.push_back(vertexToName[load_node]); out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(load_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) to_add_edges.push_back({(unsigned)vertexToName[store_parent], (unsigned)vertexToName[target(*out_edge_it, graph_)], edge_to_parid[*out_edge_it]}); } } } } ++node_id; } ++bound_it; if (bound_it == loopBound.end() ) break; } updateGraphWithNewEdges(to_add_edges); updateGraphWithIsolatedNodes(to_remove_nodes); cleanLeafNodes(); } /* * Read: loopBound, flattenConfig, graph_, address, instid, dynamicMethodID, * prevBasicBlock * Modify: graph_ */ void BaseDatapath::removeRepeatedStores() { std::unordered_set<int> flatten_config; if (!readFlattenConfig(flatten_config)&& loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Remove Repeated Store " << std::endl; std::cerr << "-------------------------------" << std::endl; std::unordered_map<unsigned, long long int> address; initAddress(address); std::vector<std::string> instid(numTotalNodes, ""); std::vector<std::string> dynamic_methodid(numTotalNodes, ""); std::vector<std::string> prev_basic_block(numTotalNodes, ""); initInstID(instid); initDynamicMethodID(dynamic_methodid); initPrevBasicBlock(prev_basic_block); int shared_stores = 0; int node_id = numTotalNodes - 1; auto bound_it = loopBound.end(); bound_it--; bound_it--; while (node_id >=0 ) { unordered_map<unsigned, int> address_store_map; while (node_id >= *bound_it && node_id >= 0) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0 || !is_store_op(microop.at(node_id))) { --node_id; continue; } long long int node_address = address[node_id]; auto addr_it = address_store_map.find(node_address); if (addr_it == address_store_map.end()) address_store_map[node_address] = node_id; else { //remove this store std::string store_unique_id (dynamic_methodid.at(node_id) + "-" + instid.at(node_id) + "-" + prev_basic_block.at(node_id)); //dynamic stores, cannot disambiguated in the run time, cannot remove if (dynamicMemoryOps.find(store_unique_id) == dynamicMemoryOps.end() && boost::out_degree(nameToVertex[node_id], graph_)== 0) { microop.at(node_id) = LLVM_IR_SilentStore; shared_stores++; } } --node_id; } if (--bound_it == loopBound.begin()) break; } cleanLeafNodes(); } /* * Read: loopBound, flattenConfig, graph_, microop * Modify: graph_ */ void BaseDatapath::treeHeightReduction() { if (loopBound.size() <= 2) return; std::cerr << "-------------------------------" << std::endl; std::cerr << " Tree Height Reduction " << std::endl; std::cerr << "-------------------------------" << std::endl; EdgeNameMap edge_to_parid = get(boost::edge_name, graph_); std::vector<bool> updated(numTotalNodes, 0); std::vector<int> bound_region(numTotalNodes, 0); int region_id = 0; unsigned node_id = 0; auto bound_it = loopBound.begin(); while (node_id < *bound_it) { bound_region.at(node_id) = region_id; node_id++; if (node_id == *bound_it) { region_id++; bound_it++; if (bound_it == loopBound.end()) break; } } std::set<Edge> to_remove_edges; std::vector<newEdge> to_add_edges; //nodes with no outgoing edges to first (bottom nodes first) for(int node_id = numTotalNodes -1; node_id >= 0; node_id--) { if (nameToVertex.find(node_id) == nameToVertex.end() || boost::degree(nameToVertex[node_id], graph_) == 0 || updated.at(node_id) || !is_associative(microop.at(node_id)) ) continue; updated.at(node_id) = 1; int node_region = bound_region.at(node_id); std::list<unsigned> nodes; std::vector<Edge> tmp_remove_edges; std::vector<pair<int, bool> > leaves; std::vector<int> associative_chain; associative_chain.push_back(node_id); int chain_id = 0; while (chain_id < associative_chain.size()) { int chain_node_id = associative_chain.at(chain_id); int chain_node_microop = microop.at(chain_node_id); if (is_associative(chain_node_microop)) { updated.at(chain_node_id) = 1; int num_of_chain_parents = 0; in_edge_iter in_edge_it, in_edge_end; for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[chain_node_id] , graph_); in_edge_it != in_edge_end; ++in_edge_it) { int parent_id = vertexToName[source(*in_edge_it, graph_)]; if (is_branch_op(microop.at(parent_id))) continue; num_of_chain_parents++; } if (num_of_chain_parents == 2) { nodes.push_front(chain_node_id); for (tie(in_edge_it, in_edge_end) = in_edges(nameToVertex[chain_node_id] , graph_); in_edge_it != in_edge_end; ++in_edge_it) { Vertex parent_node = source(*in_edge_it, graph_); int parent_id = vertexToName[parent_node]; assert(parent_id < chain_node_id); int parent_region = bound_region.at(parent_id); int parent_microop = microop.at(parent_id); if (is_branch_op(parent_microop)) continue; Edge curr_edge = *in_edge_it; tmp_remove_edges.push_back(curr_edge); if (parent_region == node_region) { updated.at(parent_id) = 1; if (!is_associative(parent_microop)) leaves.push_back(make_pair(parent_id, 0)); else { out_edge_iter out_edge_it, out_edge_end; int num_of_children = 0; for (tie(out_edge_it, out_edge_end) = out_edges(parent_node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { if (edge_to_parid[*out_edge_it] != CONTROL_EDGE) num_of_children++; } if (num_of_children == 1) associative_chain.push_back(parent_id); else leaves.push_back(make_pair(parent_id, 0)); } } else leaves.push_back(make_pair(parent_id, 1)); } } else leaves.push_back(make_pair(chain_node_id, 0)); } else leaves.push_back(make_pair(chain_node_id, 0)); chain_id++; } //build the tree if (nodes.size() < 3) continue; for(auto it = tmp_remove_edges.begin(), E = tmp_remove_edges.end(); it != E; it++) to_remove_edges.insert(*it); std::map<unsigned, unsigned> rank_map; auto leaf_it = leaves.begin(); while (leaf_it != leaves.end()) { if (leaf_it->second == 0) rank_map[leaf_it->first] = 0; else rank_map[leaf_it->first] = numTotalNodes; ++leaf_it; } //reconstruct the rest of the balanced tree auto node_it = nodes.begin(); while (node_it != nodes.end()) { unsigned node1, node2; if (rank_map.size() == 2) { node1 = rank_map.begin()->first; node2 = (++rank_map.begin())->first; } else findMinRankNodes(node1, node2, rank_map); assert((node1 != numTotalNodes) && (node2 != numTotalNodes)); to_add_edges.push_back({node1, *node_it, 1}); to_add_edges.push_back({node2, *node_it, 1}); //place the new node in the map, remove the two old nodes rank_map[*node_it] = max(rank_map[node1], rank_map[node2]) + 1; rank_map.erase(node1); rank_map.erase(node2); ++node_it; } } updateGraphWithIsolatedEdges(to_remove_edges); updateGraphWithNewEdges(to_add_edges); cleanLeafNodes(); } void BaseDatapath::findMinRankNodes(unsigned &node1, unsigned &node2, std::map<unsigned, unsigned> &rank_map) { unsigned min_rank = numTotalNodes; for (auto it = rank_map.begin(); it != rank_map.end(); ++it) { int node_rank = it->second; if (node_rank < min_rank) { node1 = it->first; min_rank = node_rank; } } min_rank = numTotalNodes; for (auto it = rank_map.begin(); it != rank_map.end(); ++it) { int node_rank = it->second; if ((it->first != node1) && (node_rank < min_rank)) { node2 = it->first; min_rank = node_rank; } } } void BaseDatapath::updateGraphWithNewEdges(std::vector<newEdge> &to_add_edges) { for(auto it = to_add_edges.begin(); it != to_add_edges.end(); ++it) { if (it->from != it->to && !doesEdgeExist(it->from, it->to)) get(boost::edge_name, graph_)[add_edge(it->from, it->to, graph_).first] = it->parid; } } void BaseDatapath::updateGraphWithIsolatedNodes(std::vector<unsigned> &to_remove_nodes) { for(auto it = to_remove_nodes.begin(); it != to_remove_nodes.end(); ++it) clear_vertex(nameToVertex[*it], graph_); } void BaseDatapath::updateGraphWithIsolatedEdges(std::set<Edge> &to_remove_edges) { for (auto it = to_remove_edges.begin(), E = to_remove_edges.end(); it!=E; ++it) remove_edge(*it, graph_); } /* * Write per cycle activity to bench_stats. The format is: * cycle_num,num-of-muls,num-of-adds,num-of-bitwise-ops,num-of-reg-reads,num-of-reg-writes * If it is called from ScratchpadDatapath, it also outputs per cycle memory * activity for each partitioned array. */ void BaseDatapath::writePerCycleActivity() { std::string bn(benchName); activity_map mul_activity, add_activity, bit_activity; activity_map ld_activity, st_activity; max_activity_map max_mul_per_function; max_activity_map max_add_per_function; max_activity_map max_bit_per_function; std::vector<std::string> comp_partition_names; std::vector<std::string> mem_partition_names; registers.getRegisterNames(comp_partition_names); getMemoryBlocks(mem_partition_names); initPerCycleActivity(comp_partition_names, mem_partition_names, ld_activity, st_activity, mul_activity, add_activity, bit_activity, max_mul_per_function, max_add_per_function, max_bit_per_function, num_cycles); updatePerCycleActivity(ld_activity, st_activity, mul_activity, add_activity, bit_activity, max_mul_per_function, max_add_per_function, max_bit_per_function); outputPerCycleActivity(comp_partition_names, mem_partition_names, ld_activity, st_activity, mul_activity, add_activity, bit_activity, max_mul_per_function, max_add_per_function, max_bit_per_function); } void BaseDatapath::initPerCycleActivity( std::vector<std::string> &comp_partition_names, std::vector<std::string> &mem_partition_names, activity_map &ld_activity, activity_map &st_activity, activity_map &mul_activity, activity_map &add_activity, activity_map &bit_activity, max_activity_map &max_mul_per_function, max_activity_map &max_add_per_function, max_activity_map &max_bit_per_function, int num_cycles) { for (auto it = comp_partition_names.begin(); it != comp_partition_names.end() ; ++it) { ld_activity.insert({*it, make_vector(num_cycles)}); st_activity.insert({*it, make_vector(num_cycles)}); } for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it) { ld_activity.insert({*it, make_vector(num_cycles)}); st_activity.insert({*it, make_vector(num_cycles)}); } for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { mul_activity.insert({*it, make_vector(num_cycles)}); add_activity.insert({*it, make_vector(num_cycles)}); bit_activity.insert({*it, make_vector(num_cycles)}); max_mul_per_function.insert({*it, 0}); max_add_per_function.insert({*it, 0}); max_bit_per_function.insert({*it, 0}); } } void BaseDatapath::updatePerCycleActivity( activity_map &ld_activity, activity_map &st_activity, activity_map &mul_activity, activity_map &add_activity, activity_map &bit_activity, max_activity_map &max_mul_per_function, max_activity_map &max_add_per_function, max_activity_map &max_bit_per_function) { /*We use two ways to count the number of functional units in accelerators: one * assumes that functional units can be reused in the same region; the other * assumes no reuse of functional units. The advantage of reusing is that it * elimates the cost of duplicating functional units which can lead to high * leakage power and area. However, additional wires and muxes may need to be * added for reusing. * In the current model, we assume that multipliers can be reused, since the * leakage power and area of multipliers are relatively significant, and no * reuse for adders. This way of modeling is consistent with our observation * of accelerators generated with Vivado.*/ std::vector<std::string> dynamic_methodid(numTotalNodes, ""); initDynamicMethodID(dynamic_methodid); int num_adds_so_far = 0, num_bits_so_far = 0; auto bound_it = loopBound.begin(); for(unsigned node_id = 0; node_id < numTotalNodes; ++node_id) { char func_id[256]; int count; sscanf(dynamic_methodid.at(node_id).c_str(), "%[^-]-%d\n", func_id, &count); if (node_id == *bound_it) { if (max_add_per_function[func_id] < num_adds_so_far) max_add_per_function[func_id] = num_adds_so_far; if (max_bit_per_function[func_id] < num_bits_so_far) max_bit_per_function[func_id] = num_bits_so_far; num_adds_so_far = 0; num_bits_so_far = 0; bound_it++; } if (finalIsolated.at(node_id)) continue; int node_level = newLevel.at(node_id); int node_microop = microop.at(node_id); if (is_mul_op(node_microop)) mul_activity[func_id].at(node_level) +=1; else if (is_add_op(node_microop)) { add_activity[func_id].at(node_level) +=1; num_adds_so_far +=1; } else if (is_bit_op(node_microop)) { bit_activity[func_id].at(node_level) +=1; num_bits_so_far +=1; } else if (is_load_op(node_microop)) { std::string base_addr = baseAddress[node_id].first; if (ld_activity.find(base_addr) != ld_activity.end()) ld_activity[base_addr].at(node_level) += 1; } else if (is_store_op(node_microop)) { std::string base_addr = baseAddress[node_id].first; if (st_activity.find(base_addr) != st_activity.end()) st_activity[base_addr].at(node_level) += 1; } } for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) max_mul_per_function[*it] = *(std::max_element(mul_activity[*it].begin(), mul_activity[*it].end())); } void BaseDatapath::outputPerCycleActivity( std::vector<std::string> &comp_partition_names, std::vector<std::string> &mem_partition_names, activity_map &ld_activity, activity_map &st_activity, activity_map &mul_activity, activity_map &add_activity, activity_map &bit_activity, max_activity_map &max_mul_per_function, max_activity_map &max_add_per_function, max_activity_map &max_bit_per_function) { ofstream stats, power_stats; std::string bn(benchName); std::string file_name = bn + "_stats"; stats.open(file_name.c_str()); file_name += "_power"; power_stats.open(file_name.c_str()); stats << "cycles," << num_cycles << "," << numTotalNodes << std::endl; power_stats << "cycles," << num_cycles << "," << numTotalNodes << std::endl; stats << num_cycles << "," ; power_stats << num_cycles << "," ; /*Start writing the second line*/ for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { stats << *it << "-mul," << *it << "-add," << *it << "-bit,"; power_stats << *it << "-mul," << *it << "-add," << *it << "-bit,"; } stats << "reg,"; power_stats << "reg,"; for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it) { stats << *it << "-read," << *it << "-write,"; } stats << std::endl; power_stats << std::endl; /*Finish writing the second line*/ /*Caculating the number of FUs and leakage power*/ int max_reg_read = 0, max_reg_write = 0; for (unsigned level_id = 0; ((int) level_id) < num_cycles; ++level_id) { if (max_reg_read < regStats.at(level_id).reads ) max_reg_read = regStats.at(level_id).reads ; if (max_reg_write < regStats.at(level_id).writes ) max_reg_write = regStats.at(level_id).writes ; } int max_reg = max_reg_read + max_reg_write; int max_add = 0, max_bit = 0, max_mul = 0; for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { max_bit += max_bit_per_function[*it]; max_add += max_add_per_function[*it]; max_mul += max_mul_per_function[*it]; } float add_leakage_power = ADD_leak_power * max_add; float mul_leakage_power = MUL_leak_power * max_mul; float reg_leakage_power = registers.getTotalLeakagePower() + REG_leak_power * 32 * max_reg; float fu_leakage_power = mul_leakage_power + add_leakage_power + reg_leakage_power; /*Finish caculating the number of FUs and leakage power*/ float fu_dynamic_energy = 0; /*Start writing per cycle activity */ for (unsigned curr_level = 0; ((int)curr_level) < num_cycles ; ++curr_level) { stats << curr_level << "," ; power_stats << curr_level << ","; //For FUs for (auto it = functionNames.begin(); it != functionNames.end() ; ++it) { float curr_mul_dynamic_power = (MUL_switch_power + MUL_int_power) * mul_activity[*it].at(curr_level); float curr_add_dynamic_power = (ADD_switch_power + ADD_int_power) * add_activity[*it].at(curr_level); fu_dynamic_energy += ( curr_mul_dynamic_power + curr_add_dynamic_power ) * cycleTime; stats << mul_activity[*it].at(curr_level) << "," << add_activity[*it].at(curr_level) << "," << bit_activity[*it].at(curr_level) << ","; power_stats << curr_mul_dynamic_power + mul_leakage_power << "," << curr_add_dynamic_power + add_leakage_power << "," << "0," ; } //For regs int curr_reg_reads = regStats.at(curr_level).reads; int curr_reg_writes = regStats.at(curr_level).writes; float curr_reg_dynamic_energy = (REG_int_power + REG_sw_power) *(curr_reg_reads + curr_reg_writes) * 32 * cycleTime; for (auto it = comp_partition_names.begin(); it != comp_partition_names.end() ; ++it) { curr_reg_reads += ld_activity.at(*it).at(curr_level); curr_reg_writes += st_activity.at(*it).at(curr_level); curr_reg_dynamic_energy += registers.getReadEnergy(*it) * ld_activity.at(*it).at(curr_level) + registers.getWriteEnergy(*it) * st_activity.at(*it).at(curr_level); } fu_dynamic_energy += curr_reg_dynamic_energy; stats << curr_reg_reads << "," << curr_reg_writes << "," ; power_stats << curr_reg_dynamic_energy / cycleTime + reg_leakage_power; for (auto it = mem_partition_names.begin(); it != mem_partition_names.end() ; ++it) stats << ld_activity.at(*it).at(curr_level) << "," << st_activity.at(*it).at(curr_level) << ","; stats << std::endl; power_stats << std::endl; } stats.close(); power_stats.close(); float avg_mem_power =0, avg_mem_dynamic_power = 0, mem_leakage_power = 0; getAverageMemPower(num_cycles, &avg_mem_power, &avg_mem_dynamic_power, &mem_leakage_power); float avg_fu_dynamic_power = fu_dynamic_energy / (cycleTime * num_cycles); float avg_fu_power = avg_fu_dynamic_power + fu_leakage_power; float avg_power = avg_fu_power + avg_mem_power; float mem_area = getTotalMemArea(); unsigned mem_size = getTotalMemSize(); float fu_area = registers.getTotalArea() + ADD_area * max_add + MUL_area * max_mul + REG_area * 32 * max_reg; float total_area = mem_area + fu_area; //Summary output: //Cycle, Avg Power, Avg FU Power, Avg MEM Power, Total Area, FU Area, MEM Area std::cerr << "===============================" << std::endl; std::cerr << " Aladdin Results " << std::endl; std::cerr << "===============================" << std::endl; std::cerr << "Running : " << benchName << std::endl; std::cerr << "Cycle : " << num_cycles << " cycles" << std::endl; std::cerr << "Avg Power: " << avg_power << " mW" << std::endl; std::cerr << "Avg FU Power: " << avg_fu_power << " mW" << std::endl; std::cerr << "Avg FU Dynamic Power: " << avg_fu_dynamic_power << " mW" << std::endl; std::cerr << "Avg FU leakage Power: " << fu_leakage_power << " mW" << std::endl; std::cerr << "Avg SRAM Power: " << avg_mem_power << " mW" << std::endl; std::cerr << "Avg SRAM Dynamic Power: " << avg_mem_dynamic_power << " mW" << std::endl; std::cerr << "Avg SRAM Leakage Power: " << mem_leakage_power << " mW" << std::endl; std::cerr << "Total Area: " << total_area << " uM^2" << std::endl; std::cerr << "FU Area: " << fu_area << " uM^2" << std::endl; std::cerr << "SRAM Area: " << mem_area << " uM^2" << std::endl; std::cerr << "SRAM size: " << mem_size / 1024 << " KB" << std::endl; std::cerr << "Num of Multipliers (32-bit): " << max_mul << std::endl; std::cerr << "Num of Adders (32-bit): " << max_add << std::endl; std::cerr << "===============================" << std::endl; std::cerr << " Aladdin Results " << std::endl; std::cerr << "===============================" << std::endl; ofstream summary; file_name = bn + "_summary"; summary.open(file_name.c_str()); summary << "===============================" << std::endl; summary << " Aladdin Results " << std::endl; summary << "===============================" << std::endl; summary << "Running : " << benchName << std::endl; summary << "Cycle : " << num_cycles << " cycles" << std::endl; summary << "Avg Power: " << avg_power << " mW" << std::endl; summary << "Avg FU Power: " << avg_fu_power << " mW" << std::endl; summary << "Avg FU Dynamic Power: " << avg_fu_dynamic_power << " mW" << std::endl; summary << "Avg FU leakage Power: " << fu_leakage_power << " mW" << std::endl; summary << "Avg SRAM Power: " << avg_mem_power << " mW" << std::endl; summary << "Avg SRAM Dynamic Power: " << avg_mem_dynamic_power << " mW" << std::endl; summary << "Avg SRAM Leakage Power: " << mem_leakage_power << " mW" << std::endl; summary << "Total Area: " << total_area << " uM^2" << std::endl; summary << "FU Area: " << fu_area << " uM^2" << std::endl; summary << "SRAM Area: " << mem_area << " uM^2" << std::endl; summary << "SRAM size: " << mem_size << " B" << std::endl; summary << "Num of Multipliers (32-bit): " << max_mul << std::endl; summary << "Num of Adders (32-bit): " << max_add << std::endl; summary << "===============================" << std::endl; summary << " Aladdin Results " << std::endl; summary << "===============================" << std::endl; summary.close(); } void BaseDatapath::writeGlobalIsolated() { std::string file_name(benchName); file_name += "_isolated.gz"; write_gzip_bool_file(file_name, finalIsolated.size(), finalIsolated); } void BaseDatapath::writeBaseAddress() { ostringstream file_name; file_name << benchName << "_baseAddr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.str().c_str(), "w"); for (auto it = baseAddress.begin(), E = baseAddress.end(); it != E; ++it) gzprintf(gzip_file, "node:%u,part:%s,base:%lld\n", it->first, it->second.first.c_str(), it->second.second); gzclose(gzip_file); } void BaseDatapath::writeFinalLevel() { std::string file_name(benchName); file_name += "_level.gz"; write_gzip_file(file_name, newLevel.size(), newLevel); } void BaseDatapath::writeMicroop(std::vector<int> &microop) { std::string file_name(benchName); file_name += "_microop.gz"; write_gzip_file(file_name, microop.size(), microop); } void BaseDatapath::initPrevBasicBlock(std::vector<std::string> &prevBasicBlock) { std::string file_name(benchName); file_name += "_prevBasicBlock.gz"; read_gzip_string_file(file_name, prevBasicBlock.size(), prevBasicBlock); } void BaseDatapath::initDynamicMethodID(std::vector<std::string> &methodid) { std::string file_name(benchName); file_name += "_dynamic_funcid.gz"; read_gzip_string_file(file_name, methodid.size(), methodid); } void BaseDatapath::initMethodID(std::vector<int> &methodid) { std::string file_name(benchName); file_name += "_methodid.gz"; read_gzip_file(file_name, methodid.size(), methodid); } void BaseDatapath::initInstID(std::vector<std::string> &instid) { std::string file_name(benchName); file_name += "_instid.gz"; read_gzip_string_file(file_name, instid.size(), instid); } void BaseDatapath::initAddress(std::unordered_map<unsigned, long long int> &address) { std::string file_name(benchName); file_name += "_memaddr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.c_str(), "r"); while (!gzeof(gzip_file)) { char buffer[256]; if (gzgets(gzip_file, buffer, 256) == NULL) break; unsigned node_id, size; long long int addr; sscanf(buffer, "%d,%lld,%d\n", &node_id, &addr, &size); address[node_id] = addr; } gzclose(gzip_file); } void BaseDatapath::initAddressAndSize(std::unordered_map<unsigned, pair<long long int, unsigned> > &address) { std::string file_name(benchName); file_name += "_memaddr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.c_str(), "r"); while (!gzeof(gzip_file)) { char buffer[256]; if (gzgets(gzip_file, buffer, 256) == NULL) break; unsigned node_id, size; long long int addr; sscanf(buffer, "%d,%lld,%d\n", &node_id, &addr, &size); address[node_id] = make_pair(addr, size); } gzclose(gzip_file); } void BaseDatapath::initLineNum(std::vector<int> &line_num) { ostringstream file_name; file_name << benchName << "_linenum.gz"; read_gzip_file(file_name.str(), line_num.size(), line_num); } void BaseDatapath::initGetElementPtr(std::unordered_map<unsigned, pair<std::string, long long int> > &get_element_ptr) { ostringstream file_name; file_name << benchName << "_getElementPtr.gz"; gzFile gzip_file; gzip_file = gzopen(file_name.str().c_str(), "r"); while (!gzeof(gzip_file)) { char buffer[256]; if (gzgets(gzip_file, buffer, 256) == NULL) break; unsigned node_id; long long int address; char label[256]; sscanf(buffer, "%d,%[^,],%lld\n", &node_id, label, &address); get_element_ptr[node_id] = make_pair(label, address); } gzclose(gzip_file); } //stepFunctions //multiple function, each function is a separate graph void BaseDatapath::setGraphForStepping() { std::cerr << "=============================================" << std::endl; std::cerr << " Scheduling... " << benchName << std::endl; std::cerr << "=============================================" << std::endl; newLevel.assign(numTotalNodes, 0); edgeToParid = get(boost::edge_name, graph_); numTotalEdges = boost::num_edges(graph_); numParents.assign(numTotalNodes, 0); latestParents.assign(numTotalNodes, 0); executedNodes = 0; totalConnectedNodes = 0; for (unsigned node_id = 0; node_id < numTotalNodes; node_id++) { Vertex node = nameToVertex[node_id]; if (boost::degree(node, graph_) != 0 || is_dma_op(microop.at(node_id))) { finalIsolated.at(node_id) = 0; numParents.at(node_id) = boost::in_degree(node, graph_); totalConnectedNodes++; } } executingQueue.clear(); readyToExecuteQueue.clear(); initExecutingQueue(); } void BaseDatapath::dumpGraph() { std::string bn(benchName); std::ofstream out(bn + "_graph.dot"); write_graphviz(out, graph_); } int BaseDatapath::clearGraph() { std::vector< Vertex > topo_nodes; boost::topological_sort(graph_, std::back_inserter(topo_nodes)); //bottom nodes first std::vector<int> earliest_child(numTotalNodes, num_cycles); for (auto vi = topo_nodes.begin(); vi != topo_nodes.end(); ++vi) { unsigned node_id = vertexToName[*vi]; if (finalIsolated.at(node_id)) continue; unsigned node_microop = microop.at(node_id); if (!is_memory_op(node_microop) && ! is_branch_op(node_microop)) if ((earliest_child.at(node_id) - 1 ) > newLevel.at(node_id)) newLevel.at(node_id) = earliest_child.at(node_id) - 1; in_edge_iter in_i, in_end; for (tie(in_i, in_end) = in_edges(*vi , graph_); in_i != in_end; ++in_i) { int parent_id = vertexToName[source(*in_i, graph_)]; if (earliest_child.at(parent_id) > newLevel.at(node_id)) earliest_child.at(parent_id) = newLevel.at(node_id); } } updateRegStats(); return num_cycles; } void BaseDatapath::updateRegStats() { regStats.assign(num_cycles, {0, 0, 0}); for(unsigned node_id = 0; node_id < numTotalNodes; node_id++) { if (finalIsolated.at(node_id)) continue; if (is_control_op(microop.at(node_id)) || is_index_op(microop.at(node_id))) continue; int node_level = newLevel.at(node_id); int max_children_level = node_level; Vertex node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; std::set<int> children_levels; for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { int child_id = vertexToName[target(*out_edge_it, graph_)]; int child_microop = microop.at(child_id); if (is_control_op(child_microop)) continue; if (is_load_op(child_microop)) continue; int child_level = newLevel.at(child_id); if (child_level > max_children_level) max_children_level = child_level; if (child_level > node_level && child_level != num_cycles - 1) children_levels.insert(child_level); } for (auto it = children_levels.begin(); it != children_levels.end(); it++) regStats.at(*it).reads++; if (max_children_level > node_level && node_level != 0 ) regStats.at(node_level).writes++; } } void BaseDatapath::copyToExecutingQueue() { auto it = readyToExecuteQueue.begin(); while (it != readyToExecuteQueue.end()) { executingQueue.push_back(*it); it = readyToExecuteQueue.erase(it); } } bool BaseDatapath::step() { stepExecutingQueue(); copyToExecutingQueue(); num_cycles++; if (executedNodes == totalConnectedNodes) return 1; return 0; } // Marks a node as completed and advances the executing queue iterator. void BaseDatapath::markNodeCompleted( std::vector<unsigned>::iterator& executingQueuePos, int& advance_to) { unsigned node_id = *executingQueuePos; executedNodes++; newLevel.at(node_id) = num_cycles; executingQueue.erase(executingQueuePos); updateChildren(node_id); executingQueuePos = executingQueue.begin(); std::advance(executingQueuePos, advance_to); } void BaseDatapath::updateChildren(unsigned node_id) { Vertex node = nameToVertex[node_id]; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(node, graph_); out_edge_it != out_edge_end; ++out_edge_it) { unsigned child_id = vertexToName[target(*out_edge_it, graph_)]; int edge_parid = edgeToParid[*out_edge_it]; if (numParents[child_id] > 0) { numParents[child_id]--; if (numParents[child_id] == 0) { unsigned child_microop = microop.at(child_id); if ( (node_latency(child_microop) == 0 || node_latency(microop.at(node_id))== 0) && edge_parid != CONTROL_EDGE ) executingQueue.push_back(child_id); else readyToExecuteQueue.push_back(child_id); numParents[child_id] = -1; } } } } void BaseDatapath::initExecutingQueue() { for(unsigned i = 0; i < numTotalNodes; i++) { if (numParents[i] == 0 && finalIsolated[i] != 1) executingQueue.push_back(i); } } int BaseDatapath::shortestDistanceBetweenNodes(unsigned int from, unsigned int to) { std::list<pair<unsigned int, unsigned int> > queue; queue.push_back({from, 0}); while(queue.size() != 0) { unsigned int curr_node = queue.front().first; unsigned int curr_dist = queue.front().second; out_edge_iter out_edge_it, out_edge_end; for (tie(out_edge_it, out_edge_end) = out_edges(nameToVertex[curr_node], graph_); out_edge_it != out_edge_end; ++out_edge_it) { if (get(boost::edge_name, graph_, *out_edge_it) != CONTROL_EDGE) { int child_id = vertexToName[target(*out_edge_it, graph_)]; if (child_id == to) return curr_dist + 1; queue.push_back({child_id, curr_dist + 1}); } } queue.pop_front(); } return -1; } //readConfigs bool BaseDatapath::readPipeliningConfig() { ifstream config_file; std::string file_name(benchName); file_name += "_pipelining_config"; config_file.open(file_name.c_str()); if (!config_file.is_open()) return 0; std::string wholeline; getline(config_file, wholeline); if (wholeline.size() == 0) return 0; bool flag = atoi(wholeline.c_str()); return flag; } bool BaseDatapath::readUnrollingConfig(std::unordered_map<int, int > &unrolling_config) { ifstream config_file; std::string file_name(benchName); file_name += "_unrolling_config"; config_file.open(file_name.c_str()); if (!config_file.is_open()) return 0; while(!config_file.eof()) { std::string wholeline; getline(config_file, wholeline); if (wholeline.size() == 0) break; char func[256]; int line_num, factor; sscanf(wholeline.c_str(), "%[^,],%d,%d\n", func, &line_num, &factor); unrolling_config[line_num] =factor; } config_file.close(); return 1; } bool BaseDatapath::readFlattenConfig(std::unordered_set<int> &flatten_config) { ifstream config_file; std::string file_name(benchName); file_name += "_flatten_config"; config_file.open(file_name.c_str()); if (!config_file.is_open()) return 0; while(!config_file.eof()) { std::string wholeline; getline(config_file, wholeline); if (wholeline.size() == 0) break; char func[256]; int line_num; sscanf(wholeline.c_str(), "%[^,],%d\n", func, &line_num); flatten_config.insert(line_num); } config_file.close(); return 1; } bool BaseDatapath::readCompletePartitionConfig(std::unordered_map<std::string, unsigned> &config) { std::string comp_partition_file(benchName); comp_partition_file += "_complete_partition_config"; if (!fileExists(comp_partition_file)) return 0; ifstream config_file; config_file.open(comp_partition_file); std::string wholeline; while(!config_file.eof()) { getline(config_file, wholeline); if (wholeline.size() == 0) break; unsigned size; char type[256]; char base_addr[256]; sscanf(wholeline.c_str(), "%[^,],%[^,],%d\n", type, base_addr, &size); config[base_addr] = size; } config_file.close(); return 1; } bool BaseDatapath::readPartitionConfig(std::unordered_map<std::string, partitionEntry> & partition_config) { ifstream config_file; std::string file_name(benchName); file_name += "_partition_config"; if (!fileExists(file_name)) return 0; config_file.open(file_name.c_str()); std::string wholeline; while (!config_file.eof()) { getline(config_file, wholeline); if (wholeline.size() == 0) break; unsigned size, p_factor, wordsize; char type[256]; char base_addr[256]; sscanf(wholeline.c_str(), "%[^,],%[^,],%d,%d,%d\n", type, base_addr, &size, &wordsize, &p_factor); std::string p_type(type); partition_config[base_addr] = {p_type, size, wordsize, p_factor}; } config_file.close(); return 1; } void BaseDatapath::parse_config(std::string bench, std::string config_file_name) { ifstream config_file; config_file.open(config_file_name); std::string wholeline; std::vector<std::string> flatten_config; std::vector<std::string> unrolling_config; std::vector<std::string> partition_config; std::vector<std::string> comp_partition_config; std::vector<std::string> pipelining_config; while(!config_file.eof()) { wholeline.clear(); getline(config_file, wholeline); if (wholeline.size() == 0) break; string type, rest_line; int pos_end_tag = wholeline.find(","); if (pos_end_tag == -1) break; type = wholeline.substr(0, pos_end_tag); rest_line = wholeline.substr(pos_end_tag + 1); if (!type.compare("flatten")) flatten_config.push_back(rest_line); else if (!type.compare("unrolling")) unrolling_config.push_back(rest_line); else if (!type.compare("partition")) if (wholeline.find("complete") == std::string::npos) partition_config.push_back(rest_line); else comp_partition_config.push_back(rest_line); else if (!type.compare("pipelining")) pipelining_config.push_back(rest_line); else { cerr << "what else? " << wholeline << endl; exit(0); } } config_file.close(); if (flatten_config.size() != 0) { string file_name(bench); file_name += "_flatten_config"; ofstream output; output.open(file_name); for (unsigned i = 0; i < flatten_config.size(); ++i) output << flatten_config.at(i) << endl; output.close(); } if (unrolling_config.size() != 0) { string file_name(bench); file_name += "_unrolling_config"; ofstream output; output.open(file_name); for (unsigned i = 0; i < unrolling_config.size(); ++i) output << unrolling_config.at(i) << endl; output.close(); } if (pipelining_config.size() != 0) { string pipelining(bench); pipelining += "_pipelining_config"; ofstream pipe_config; pipe_config.open(pipelining); for (unsigned i = 0; i < pipelining_config.size(); ++i) pipe_config << pipelining_config.at(i) << endl; pipe_config.close(); } if (partition_config.size() != 0) { string partition(bench); partition += "_partition_config"; ofstream part_config; part_config.open(partition); for (unsigned i = 0; i < partition_config.size(); ++i) part_config << partition_config.at(i) << endl; part_config.close(); } if (comp_partition_config.size() != 0) { string complete_partition(bench); complete_partition += "_complete_partition_config"; ofstream comp_config; comp_config.open(complete_partition); for (unsigned i = 0; i < comp_partition_config.size(); ++i) comp_config << comp_partition_config.at(i) << endl; comp_config.close(); } } /* Tokenizes an input string and returns a vector. */ void BaseDatapath::tokenizeString(std::string input, std::vector<int>& tokenized_list) { using namespace boost; tokenizer<> tok(input); for(tokenizer<>::iterator beg = tok.begin(); beg != tok.end(); ++beg) { int value; istringstream(*beg) >> value; tokenized_list.push_back(value); } }
34.671488
134
0.632218
httsai
c154c8c082fd784e72327c947fa41f216c04e8bb
8,153
hpp
C++
GPU_version/vio/include/vio/nlls_solver_impl.hpp
Pilot-Labs-Dev/vio_svo
8274e4269b383e9816fca5c3102b51cd4d1b95ae
[ "MIT" ]
2
2022-03-17T01:12:10.000Z
2022-03-24T03:17:24.000Z
GPU_version/vio/include/vio/nlls_solver_impl.hpp
Pilot-Labs-Dev/vio_svo
8274e4269b383e9816fca5c3102b51cd4d1b95ae
[ "MIT" ]
null
null
null
GPU_version/vio/include/vio/nlls_solver_impl.hpp
Pilot-Labs-Dev/vio_svo
8274e4269b383e9816fca5c3102b51cd4d1b95ae
[ "MIT" ]
1
2022-03-12T11:42:01.000Z
2022-03-12T11:42:01.000Z
/* * Abstract Nonlinear Least-Squares Solver Class * * nlls_solver.h * * Created on: Nov 5, 2012 * Author: cforster */ #ifndef LM_SOLVER_IMPL_HPP_ #define LM_SOLVER_IMPL_HPP_ #include <stdexcept> template <int D, typename T> void vk::NLLSSolver<D, T>::optimize(ModelType& model) { if(method_ == GaussNewton) optimizeGaussNewton(); else if(method_ == LevenbergMarquardt) optimizeLevenbergMarquardt(model); } template <int D, typename T> void vk::NLLSSolver<D, T>::optimizeGaussNewton() { // Compute weight scale if(use_weights_) computeResiduals(false, true); // perform iterative estimation for (iter_ = 0; iter_<n_iter_; ++iter_) { rho_ = 0; n_meas_ = 0; double new_chi2 = computeResiduals(true, false); // solve the linear system if(!solve()) { // matrix was singular and could not be computed if(verbose_)std::cerr << "Matrix is close to singular! Stop Optimizing." << std::endl; stop_ = true; } // check if error increased since last optimization if((iter_ > 0 && new_chi2 > chi2_) || stop_) { if(verbose_) { std::cerr << "It. " << iter_ << "\t Failure" << "\t new_chi2 = " << new_chi2 << "\t Error increased. Stop optimizing.\n"; } break; } // update the model update(); chi2_ = new_chi2; if(verbose_) { std::cerr << "It. " << iter_ << "\t Success" << "\t new_chi2 = " << new_chi2 << "\t x_norm = " << vk::norm_max(x_)<<'\n'; } // stop when converged, i.e. update step too small if(vk::norm_max(x_)<=eps_) break; } } template <int D, typename T> void vk::NLLSSolver<D, T>::optimizeLevenbergMarquardt(ModelType& model) { // Compute weight scale if(use_weights_) computeResiduals(model, false, true); // compute the initial error chi2_ = computeResiduals(model, true, false); if(verbose_) cout << "init chi2 = " << chi2_ << "\t n_meas = " << n_meas_ << endl; // TODO: compute initial lambda // Hartley and Zisserman: "A typical init value of lambda is 10^-3 times the // average of the diagonal elements of J'J" // Compute Initial Lambda if(mu_ < 0) { double H_max_diag = 0; double tau = 1e-4; for(size_t j=0; j<D; ++j) H_max_diag = max(H_max_diag, fabs(H_(j,j))); mu_ = tau*H_max_diag; } // perform iterative estimation for (iter_ = 0; iter_<n_iter_; ++iter_) { rho_ = 0; startIteration(); bool sign=false; // try to compute and update, if it fails, try with increased mu n_trials_ = 0; do { // init variables ModelType new_model; double new_chi2 = -1; H_.setZero(); //H_ = mu_ * Matrix<double,D,D>::Identity(D,D); Jres_.setZero(); // compute initial error n_meas_ = 0; computeResiduals(model, true, false); // add damping term: H_ += (H_.diagonal()*mu_).asDiagonal(); // add prior if(have_prior_) applyPrior(model); // solve the linear system if(solve()) { // update the model update(model, new_model); // compute error with new model and compare to old error n_meas_ = 0; new_chi2 = computeResiduals(new_model, true, false); rho_ = chi2_-new_chi2; } else { // matrix was singular and could not be computed cout << "Matrix is close to singular!" << endl; cout << "H = " << H_ << endl; cout << "Jres = " << Jres_ << endl; rho_ = -1; } if(rho_>0) { // update decrased the error -> success model = new_model; chi2_ = new_chi2; stop_ = vk::norm_max(x_)<=eps_ ? true : false; mu_ *= max(1./3., min(1.-pow(2*rho_-1,3), 2./3.)); nu_ = 2.; if(verbose_) { cout << "It. " << iter_ << "\t Trial " << n_trials_ << "\t Success" << "\t n_meas = " << n_meas_ << "\t new_chi2 = " << new_chi2 << "\t mu = " << mu_ << "\t nu = " << nu_ << "\t x_norm = " << vk::norm_max(x_) << endl; } } else { if(sign){ if(verbose_) { cout << "It. " << iter_ << "\t Trial " << n_trials_ << "\t Failure" << "\t n_meas = " << n_meas_ << "\t new_chi2 = " << new_chi2 << "\t mu = " << mu_ << "\t nu = " << nu_ << "\t x_norm = " << vk::norm_max(x_) << endl; } mu_ /= nu_; nu_ /= 2.; ++n_trials_; if (n_trials_ >= n_trials_max_) stop_ = true; sign=false; }else{ if(verbose_) { cout << "It. " << iter_ << "\t Trial " << n_trials_ << "\t Failure" << "\t n_meas = " << n_meas_ << "\t new_chi2 = " << new_chi2 << "\t mu = " << mu_ << "\t nu = " << nu_ << "\t x_norm = " << vk::norm_max(x_) << endl; } mu_ *= nu_; nu_ *= 2.; ++n_trials_; if (n_trials_ >= n_trials_max_) stop_ = true; sign=true; } } finishTrial(); } while(!(rho_>0 || stop_)); if (stop_) break; finishIteration(); } } template <int D, typename T> void vk::NLLSSolver<D, T>::setRobustCostFunction( ScaleEstimatorType scale_estimator, WeightFunctionType weight_function) { switch(scale_estimator) { case TDistScale: if(verbose_) printf("Using TDistribution Scale Estimator\n"); scale_estimator_.reset(new robust_cost::TDistributionScaleEstimator()); use_weights_=true; break; case MADScale: if(verbose_) printf("Using MAD Scale Estimator\n"); scale_estimator_.reset(new robust_cost::MADScaleEstimator()); use_weights_=true; break; case NormalScale: if(verbose_) printf("Using Normal Scale Estimator\n"); scale_estimator_.reset(new robust_cost::NormalDistributionScaleEstimator()); use_weights_=true; break; default: if(verbose_) printf("Using Unit Scale Estimator\n"); scale_estimator_.reset(new robust_cost::UnitScaleEstimator()); use_weights_=false; } switch(weight_function) { case TDistWeight: if(verbose_) printf("Using TDistribution Weight Function\n"); weight_function_.reset(new robust_cost::TDistributionWeightFunction()); break; case TukeyWeight: if(verbose_) printf("Using Tukey Weight Function\n"); weight_function_.reset(new robust_cost::TukeyWeightFunction()); break; case HuberWeight: if(verbose_) printf("Using Huber Weight Function\n"); weight_function_.reset(new robust_cost::HuberWeightFunction()); break; default: if(verbose_) printf("Using Unit Weight Function\n"); weight_function_.reset(new robust_cost::UnitWeightFunction()); } } template <int D, typename T> void vk::NLLSSolver<D, T>::setPrior( const T& prior, const Matrix<double, D, D>& Information) { have_prior_ = true; prior_ = prior; I_prior_ = Information; } template <int D, typename T> void vk::NLLSSolver<D, T>::reset() { have_prior_ = false; chi2_ = 1e10; mu_ = mu_init_; nu_ = nu_init_; n_meas_ = 0; n_iter_ = n_iter_init_; iter_ = 0; stop_ = false; } template <int D, typename T> inline const double& vk::NLLSSolver<D, T>::getChi2() const { return chi2_; } template <int D, typename T> inline const vk::Matrix<double, D, D>& vk::NLLSSolver<D, T>::getInformationMatrix() const { return H_; } #endif /* LM_SOLVER_IMPL_HPP_ */
25.800633
92
0.535018
Pilot-Labs-Dev
c155a838b36e948a213f7fab326cccc63469505c
432
hpp
C++
engine/generators/include/RoadGenerator.hpp
sidav/shadow-of-the-wyrm
747afdeebed885b1a4f7ab42f04f9f756afd3e52
[ "MIT" ]
1
2020-05-24T22:44:03.000Z
2020-05-24T22:44:03.000Z
engine/generators/include/RoadGenerator.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
engine/generators/include/RoadGenerator.hpp
cleancoindev/shadow-of-the-wyrm
51b23e98285ecb8336324bfd41ebf00f67b30389
[ "MIT" ]
null
null
null
#pragma once #include "Map.hpp" #include "Directions.hpp" #define DEFAULT_ROAD_WIDTH 3 class RoadGenerator { public: RoadGenerator(const int width=DEFAULT_ROAD_WIDTH); RoadGenerator(const CardinalDirection direction, const int width=DEFAULT_ROAD_WIDTH); virtual MapPtr generate(MapPtr map); protected: void generate_road(MapPtr map); const int ROAD_WIDTH; const CardinalDirection ROAD_DIRECTION; };
20.571429
89
0.763889
sidav
c15a93fcca153424e4d9df95f44a1869f71cfe48
4,279
cpp
C++
plugins/resource_context/src/systems/BufferResourceCache.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
5
2018-08-16T00:55:33.000Z
2020-06-19T14:30:17.000Z
plugins/resource_context/src/systems/BufferResourceCache.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
plugins/resource_context/src/systems/BufferResourceCache.cpp
fuchstraumer/Caelestis
9c4b76288220681bb245d84e5d7bf8c7f69b2716
[ "MIT" ]
null
null
null
#include "systems/BufferResourceCache.hpp" #include "core/ShaderResource.hpp" #include "resource/Buffer.hpp" namespace vpsk { BufferResourceCache::BufferResourceCache(const vpr::Device* dvc) : device(dvc) { } BufferResourceCache::~BufferResourceCache() {} void BufferResourceCache::AddResources(const std::vector<const st::ShaderResource*>& resources) { createResources(resources); } void BufferResourceCache::AddResource(const st::ShaderResource* resource) { if (!HasResource(resource->ParentGroupName(), resource->Name())) { createResource(resource); } } vpr::Buffer* BufferResourceCache::at(const std::string& group, const std::string& name) { return buffers.at(group).at(name).get(); } vpr::Buffer* BufferResourceCache::find(const std::string& group, const std::string& name) noexcept { auto group_iter = buffers.find(group); if (group_iter != buffers.end()) { auto rsrc_iter = group_iter->second.find(name); if (rsrc_iter != group_iter->second.end()) { return rsrc_iter->second.get(); } else { return nullptr; } } else { return nullptr; } } bool BufferResourceCache::HasResource(const std::string& group, const std::string& name) const noexcept { if (buffers.count(group) == 0) { return false; } else if (buffers.at(group).count(name) != 0) { return true; } else { return false; } } void BufferResourceCache::createTexelBuffer(const st::ShaderResource* texel_buffer, bool storage) { auto& group = buffers[texel_buffer->ParentGroupName()]; auto buffer = std::make_unique<vpr::Buffer>(device); auto flags = storage ? VK_BUFFER_USAGE_STORAGE_TEXEL_BUFFER_BIT : VK_BUFFER_USAGE_UNIFORM_TEXEL_BUFFER_BIT; buffer->CreateBuffer(flags, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, texel_buffer->MemoryRequired()); buffer->CreateView(texel_buffer->Format(), buffer->Size(), 0); group.emplace(texel_buffer->Name(), std::move(buffer)); } void BufferResourceCache::createUniformBuffer(const st::ShaderResource* uniform_buffer) { auto& group = buffers[uniform_buffer->ParentGroupName()]; auto buffer = std::make_unique<vpr::Buffer>(device); auto flags = VK_MEMORY_PROPERTY_HOST_COHERENT_BIT | VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT; buffer->CreateBuffer(VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, flags, uniform_buffer->MemoryRequired()); group.emplace(uniform_buffer->Name(), std::move(buffer)); } void BufferResourceCache::createStorageBuffer(const st::ShaderResource* storage_buffer) { auto& group = buffers[storage_buffer->ParentGroupName()]; auto buffer = std::make_unique<vpr::Buffer>(device); buffer->CreateBuffer(VK_BUFFER_USAGE_STORAGE_BUFFER_BIT, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, storage_buffer->MemoryRequired()); group.emplace(storage_buffer->Name(), std::move(buffer)); } void BufferResourceCache::createResources(const std::vector<const st::ShaderResource*>& resources) { for (const auto& rsrc : resources) { if (!HasResource(rsrc->ParentGroupName(), rsrc->Name())) { createResource(rsrc); } } } void BufferResourceCache::createResource(const st::ShaderResource* rsrc) { switch (rsrc->DescriptorType()) { case VK_DESCRIPTOR_TYPE_UNIFORM_TEXEL_BUFFER: createTexelBuffer(rsrc, false); break; case VK_DESCRIPTOR_TYPE_STORAGE_TEXEL_BUFFER: createTexelBuffer(rsrc, true); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER: createUniformBuffer(rsrc); break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER: createStorageBuffer(rsrc); break; case VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER_DYNAMIC: createUniformBuffer(rsrc); break; case VK_DESCRIPTOR_TYPE_STORAGE_BUFFER_DYNAMIC: createStorageBuffer(rsrc); break; default: break; } } }
38.205357
136
0.646179
fuchstraumer
c15c5910de26010cd8cdfeda4e8f0660489a6aeb
424
cpp
C++
Assignment2/IDivable.cpp
JJhuk/C-Unmanaged-Programming
3c78a5be69e4cfd9b8cb33604d5f009b5d34c2fb
[ "MIT" ]
1
2020-04-20T04:33:29.000Z
2020-04-20T04:33:29.000Z
Assignment2/IDivable.cpp
JJhuk/C-Unmanaged-Programming
3c78a5be69e4cfd9b8cb33604d5f009b5d34c2fb
[ "MIT" ]
null
null
null
Assignment2/IDivable.cpp
JJhuk/C-Unmanaged-Programming
3c78a5be69e4cfd9b8cb33604d5f009b5d34c2fb
[ "MIT" ]
null
null
null
#pragma once #include "Person.h" namespace assignment2 { class Vehicle { public: Vehicle(unsigned int maxPassengersCount); ~Vehicle(); virtual unsigned int GetMaxSpeed() const = 0; bool AddPassenger(const Person* person); bool RemovePassenger(unsigned int i); const Person* GetPassenger(unsigned int i) const; unsigned int GetPassengersCount() const; unsigned int GetMaxPassengersCount() const; }; }
19.272727
51
0.742925
JJhuk
c15d575b85f1cfb33f82e192833cf99ecbc34955
822
cpp
C++
shadow/renderer/camera.cpp
thesamhurwitz/shadow
437033ea54f1e1e28280c6d1d45e762aa850eaaa
[ "MIT" ]
null
null
null
shadow/renderer/camera.cpp
thesamhurwitz/shadow
437033ea54f1e1e28280c6d1d45e762aa850eaaa
[ "MIT" ]
null
null
null
shadow/renderer/camera.cpp
thesamhurwitz/shadow
437033ea54f1e1e28280c6d1d45e762aa850eaaa
[ "MIT" ]
null
null
null
#include "camera.h" #include <glm/gtc/matrix_transform.hpp> namespace Shadow { Camera::Camera(float left, float right, float bottom, float top) : mProjectionMatrix(glm::ortho(left, right, bottom, top, -1.0f, 1.0f)), mViewMatrix(1.0f), mPosition(0.0f) { mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } void Camera::SetProjection(float left, float right, float bottom, float top) { mProjectionMatrix = glm::ortho(left, right, bottom, top, -1.0f, 1.0f); Recalculate(); } void Camera::Recalculate() { glm::mat4 transform = glm::translate(glm::mat4(1.0f), mPosition) * glm::rotate(glm::mat4(1.0f), glm::radians(mRotation), glm::vec3(0, 0, 1)); mViewMatrix = glm::inverse(transform); mViewProjectionMatrix = mProjectionMatrix * mViewMatrix; } }
29.357143
100
0.670316
thesamhurwitz
c15dd93bf0661dfebf5efaeca1497419a5a0a0bc
3,690
cpp
C++
scps/Schrodinger1DItem.cpp
gapost/MISfit
882653365d2ae3b3173c763df3fc9b02724d91c2
[ "MIT" ]
null
null
null
scps/Schrodinger1DItem.cpp
gapost/MISfit
882653365d2ae3b3173c763df3fc9b02724d91c2
[ "MIT" ]
null
null
null
scps/Schrodinger1DItem.cpp
gapost/MISfit
882653365d2ae3b3173c763df3fc9b02724d91c2
[ "MIT" ]
null
null
null
// Schrodinger1DItem.cpp: implementation of the CSchrodinger1DItem class. // ////////////////////////////////////////////////////////////////////// #include "stdafx.h" #include "Schrodinger1DItem.h" #include "Schrodinger1D.h" ////////////////////////////////////////////////////////////////////// // Construction/Destruction ////////////////////////////////////////////////////////////////////// void CSchrodinger1DItem::Assign(CSchrodinger1D* pS, int& i) { iequ = i; x = &(pS->x[iequ]); h = &(pS->h[iequ]); L = &(pS->L[iequ]); v = &(pS->v[iequ]); q = &(pS->q[iequ]); dq = &(pS->dq[iequ]); d = &(pS->T.d(iequ)); s = 0; if (iequ) s = &(pS->T.s(iequ)); d1 = &(pS->d1[iequ]); E = pS->E; Z = pS->Z; W1 = pS->W1; W2 = pS->W2; ne = &(pS->ne); i += get_m(); } void CSchrodingerBC::MakeMatrix() { double M1,M2,dE1,dE2; if (Prev) { M1 = ((CSchrodinger1DLayer*)Prev)->Mz; dE1 = ((CSchrodinger1DLayer*)Prev)->dE; } if (Next) { M2 = ((CSchrodinger1DLayer*)Next)->Mz; dE2 = ((CSchrodinger1DLayer*)Next)->dE; } switch (btype) { case box: if (s) { *s = -1/M1/(*L)/(*(L-1))/(*(h-1)); *d1 = 2/M1/(*h)/(*(h-1)) + dE1 + 1e100; } else { *d1 = 2/M2/(*(h+1))/(*h) + dE2 + 1e100; } break; case transmit: if (s) { *s = -1/M1/(*L)/(*(L-1))/(*(h-1)); *d1 = 1/M1/(*h)/(*h) + dE1; } else { *d1 = 1/M2/(*h)/(*h) + dE2; } break; case cont: int i=0; s[i] = -1/M1/L[i]/L[i-1]/h[i-1]; d1[i] = 1/L[i]/L[i]*(1/M2/h[i] + 1/M1/h[i-1]) + dE2; break; } } void CSchrodingerBC::CalcQ() { double M, absM; if (Prev) { M = ((CSchrodinger1DLayer*)Prev)->Md; } if (Next) { M = ((CSchrodinger1DLayer*)Next)->Md; } absM = fabs(M); int k; switch (btype) { case box: break; case transmit: for(k=0; k<*ne; k++) { double z = Z[k][iequ]; *q -= M*z*W1[k]; *dq += absM*z*W2[k]; } break; case cont: for(k=0; k<*ne; k++) { double z = Z[k][iequ]; *q -= M*z*W1[k]; *dq += absM*z*W2[k]; } break; } } double CSchrodingerBC::get_Md() { double M; if (Prev) { M = ((CSchrodinger1DLayer*)Prev)->Md; } if (Next) { M = ((CSchrodinger1DLayer*)Next)->Md; } return M; } void CSchrodinger1DLayer::MakeMatrix() { int m = get_m(); for(int i=0; i<m; i++) { s[i] = -1/Mz/L[i]/L[i-1]/h[i-1]; d1[i] = 2/Mz/h[i]/h[i-1] + dE; } } void CSchrodinger1DLayer::CalcQ() { double absMd = fabs(Md); int m = get_m(); for(int i =0; i<m; i++) { for(int k=0; k<*ne; k++) { double z = Z[k][iequ+i]; q[i] -= Md*z*W1[k]; dq[i] += absMd*z*W2[k]; } } } void CSchrodinger1DLayer::CalcBounds(double& lbound, double& ubound, double eps) { int sign = 1; if (Md<0) sign=-1; double qriterion = sign*(log(sign*Md) - log(eps)); int m = get_m(); if (sign==1) { double vmin = *(v-1); for(int i = 0; i<=m; i++) if (v[i]<vmin) vmin = v[i]; vmin += dE; if (lbound==0. && ubound==0.) { lbound=vmin; ubound=qriterion; } else { if (vmin < lbound) lbound = vmin; if (qriterion > ubound) ubound = qriterion; } } else { double vmax = *(v-1); for(int i = 0; i<=m; i++) if (v[i]>vmax) vmax = v[i]; vmax += dE; if (lbound==0. && ubound==0.) { lbound=qriterion; ubound=vmax; } else { if (vmax > ubound) ubound = vmax; if (qriterion < lbound) lbound = qriterion; } } } void CSchrodinger1DLayer::Dump(ostream& s) { int m = get_m(); for(int i = -1; i<m; i++) { s << x[i] << "\t"; s << (v[i]+dE)/beta << "\t"; s << fabs(q[i]/beta*N0) << "\t"; s << dq[i]/beta*N0 << "\n"; } }
19.52381
81
0.463144
gapost
c15e3c19bb65075988046d812a4a968f4b958c1a
3,490
cpp
C++
RadeonGPUAnalyzerGUI/src/rgUnsavedItemsDialog.cpp
alphonsetai/RGA
76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9
[ "MIT" ]
null
null
null
RadeonGPUAnalyzerGUI/src/rgUnsavedItemsDialog.cpp
alphonsetai/RGA
76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9
[ "MIT" ]
null
null
null
RadeonGPUAnalyzerGUI/src/rgUnsavedItemsDialog.cpp
alphonsetai/RGA
76cd5f36b40bd5e3de40bfb3e79c410aa4c132c9
[ "MIT" ]
null
null
null
// C++. #include <cassert> // Qt. #include <QWidget> #include <QDialog> #include <QSignalMapper> #include <QPainter> // Local. #include <RadeonGPUAnalyzerGUI/include/qt/rgUnsavedItemsDialog.h> #include <RadeonGPUAnalyzerGUI/include/rgUtils.h> #include <RadeonGPUAnalyzerGUI/include/rgDefinitions.h> rgUnsavedItemsDialog::rgUnsavedItemsDialog(QWidget *parent) : QDialog(parent) { // Setup the UI. ui.setupUi(this); // Disable the help button in the titlebar. setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); // Connect the signals. ConnectSignals(); // Create item delegate for the list widget. m_pItemDelegate = new rgUnsavedFileItemDelegate(); bool isDelegateValid = (m_pItemDelegate != nullptr); assert(isDelegateValid); if (isDelegateValid) { // Set custom delegate for the list widget. ui.fileListWidget->setItemDelegate(m_pItemDelegate); } // Disable selection of items. ui.fileListWidget->setSelectionMode(QAbstractItemView::NoSelection); } rgUnsavedItemsDialog::~rgUnsavedItemsDialog() { if (m_pItemDelegate != nullptr) { delete m_pItemDelegate; } } void rgUnsavedItemsDialog::ConnectSignals() { // Create a signal mapper to map the button clicks to the done(int) slot // with appropriate result values. QSignalMapper* pButtonSignalMapper = new QSignalMapper(this); // Yes button. bool isConnected = connect(ui.yesPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map())); assert(isConnected); pButtonSignalMapper->setMapping(ui.yesPushButton, UnsavedFileDialogResult::Yes); // No button. isConnected = connect(ui.noPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map())); assert(isConnected); pButtonSignalMapper->setMapping(ui.noPushButton, UnsavedFileDialogResult::No); // Cancel button. isConnected = connect(ui.cancelPushButton, SIGNAL(clicked()), pButtonSignalMapper, SLOT(map())); assert(isConnected); pButtonSignalMapper->setMapping(ui.cancelPushButton, UnsavedFileDialogResult::Cancel); // Signal mapper. isConnected = connect(pButtonSignalMapper, SIGNAL(mapped(int)), this, SLOT(done(int))); assert(isConnected); } void rgUnsavedItemsDialog::AddFile(QString filename) { ui.fileListWidget->addItem(filename); } void rgUnsavedItemsDialog::AddFiles(QStringList filenames) { foreach(const QString& filename, filenames) { AddFile(filename); } } void rgUnsavedFileItemDelegate::drawDisplay(QPainter* pPainter, const QStyleOptionViewItem& option, const QRect &rect, const QString& text) const { bool isPainterValid = (pPainter != nullptr); assert(isPainterValid); if (isPainterValid) { // Truncate string so it fits within rect. QString truncatedString = rgUtils::TruncateString(text.toStdString(), gs_TEXT_TRUNCATE_LENGTH_FRONT, gs_TEXT_TRUNCATE_LENGTH_BACK, rect.width(), pPainter->font(), rgUtils::EXPAND_BACK).c_str(); // Draw text within rect. pPainter->drawText(rect, Qt::AlignVCenter, truncatedString); } } QSize rgUnsavedFileItemDelegate::sizeHint(const QStyleOptionViewItem& option, const QModelIndex& index) const { // Use standard size hint implementation, but with a fixed width of 0 (width will be determined by view width). QSize adjustedHint = QItemDelegate::sizeHint(option, index); adjustedHint.setWidth(0); return adjustedHint; }
30.347826
145
0.723209
alphonsetai
c1601b8758430a450bffd6a48fd8840b9effcf39
1,564
cpp
C++
aws-cpp-sdk-sagemaker/source/model/OfflineStoreStatus.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-12T08:09:30.000Z
2022-02-12T08:09:30.000Z
aws-cpp-sdk-sagemaker/source/model/OfflineStoreStatus.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-sagemaker/source/model/OfflineStoreStatus.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-11-09T11:58:03.000Z
2021-11-09T11:58:03.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/sagemaker/model/OfflineStoreStatus.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace SageMaker { namespace Model { OfflineStoreStatus::OfflineStoreStatus() : m_status(OfflineStoreStatusValue::NOT_SET), m_statusHasBeenSet(false), m_blockedReasonHasBeenSet(false) { } OfflineStoreStatus::OfflineStoreStatus(JsonView jsonValue) : m_status(OfflineStoreStatusValue::NOT_SET), m_statusHasBeenSet(false), m_blockedReasonHasBeenSet(false) { *this = jsonValue; } OfflineStoreStatus& OfflineStoreStatus::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("Status")) { m_status = OfflineStoreStatusValueMapper::GetOfflineStoreStatusValueForName(jsonValue.GetString("Status")); m_statusHasBeenSet = true; } if(jsonValue.ValueExists("BlockedReason")) { m_blockedReason = jsonValue.GetString("BlockedReason"); m_blockedReasonHasBeenSet = true; } return *this; } JsonValue OfflineStoreStatus::Jsonize() const { JsonValue payload; if(m_statusHasBeenSet) { payload.WithString("Status", OfflineStoreStatusValueMapper::GetNameForOfflineStoreStatusValue(m_status)); } if(m_blockedReasonHasBeenSet) { payload.WithString("BlockedReason", m_blockedReason); } return payload; } } // namespace Model } // namespace SageMaker } // namespace Aws
20.578947
111
0.751279
perfectrecall
c16288695b71e20cbd42e56b2dd3c4785ceb17d8
562
hpp
C++
libs/renderer/include/sge/renderer/texture/volume_shared_ptr.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/renderer/include/sge/renderer/texture/volume_shared_ptr.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/renderer/include/sge/renderer/texture/volume_shared_ptr.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
3
2018-05-11T01:11:34.000Z
2021-04-24T19:47:45.000Z
// Copyright Carl Philipp Reh 2006 - 2019. // Distributed under the Boost Software License, Version 1.0. // (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef SGE_RENDERER_TEXTURE_VOLUME_SHARED_PTR_HPP_INCLUDED #define SGE_RENDERER_TEXTURE_VOLUME_SHARED_PTR_HPP_INCLUDED #include <sge/renderer/texture/volume_fwd.hpp> #include <fcppt/shared_ptr_impl.hpp> namespace sge { namespace renderer { namespace texture { typedef fcppt::shared_ptr<texture::volume> volume_shared_ptr; } } } #endif
21.615385
61
0.770463
cpreh
c1633a5b5840f93790dd65fa5c759adb8a7d65ee
1,875
cpp
C++
src/component/extra/fps.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
2
2021-04-28T20:51:25.000Z
2021-04-28T20:51:38.000Z
src/component/extra/fps.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
src/component/extra/fps.cpp
pepng-CU/pepng
6030798b6936a6f85655d5e5d1ca638be282de92
[ "MIT" ]
null
null
null
#include "fps.hpp" #include <sstream> #include "../../io/io.hpp" #include "../transform.hpp" FPS::FPS(float panSpeed, float rotationSpeed) : Component("FPS"), __pan_speed(panSpeed), __rotation_speed(rotationSpeed) {} FPS::FPS(const FPS& fps) : Component(fps), __pan_speed(fps.__pan_speed), __rotation_speed(fps.__rotation_speed) {} std::shared_ptr<FPS> FPS::make_fps(float panSpeed, float rotationSpeed) { std::shared_ptr<FPS> fps(new FPS(panSpeed, rotationSpeed)); return fps; } std::shared_ptr<FPS> pepng::make_fps(float panSpeed, float rotationSpeed) { return FPS::make_fps(panSpeed, rotationSpeed); } FPS* FPS::clone_implementation() { return new FPS(*this); } void FPS::update(std::shared_ptr<WithComponents> parent) { if(!this->_is_active) { return; } auto transform = parent->get_component<Transform>(); if (transform == nullptr) { std::stringstream ss; ss << *parent << " has an FPS but no Transform."; std::cout << ss.str() << std::endl; std::runtime_error(ss.str()); } auto input = Input::get(); auto mouseDelta = glm::vec2(input->axis("mouseX"), input->axis("mouseY")); if (input->button("pan")) { transform->position += transform->up() * mouseDelta.y * this->__pan_speed + transform->right() * mouseDelta.x * this->__pan_speed; } auto rotation = glm::vec3(mouseDelta.y, mouseDelta.x, 0.0f); if(input->button("rotate") && glm::length(rotation) > 0.25f) { transform->delta_rotate(rotation * this->__rotation_speed); } transform->position -= transform->forward() * input->axis("zoom") * this->__pan_speed; } #ifdef IMGUI void FPS::imgui() { Component::imgui(); ImGui::InputFloat("Pan Speed", &this->__pan_speed); ImGui::InputFloat("Rotation Speed", &this->__rotation_speed); } #endif
25.337838
138
0.6464
pepng-CU
c1639a7bba7ab0bf6112e0444e986527b4cc9e8b
2,547
hpp
C++
include/wire/util/concatenate.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
5
2016-04-07T19:49:39.000Z
2021-08-03T05:24:11.000Z
include/wire/util/concatenate.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
null
null
null
include/wire/util/concatenate.hpp
zmij/wire
9981eb9ea182fc49ef7243eed26b9d37be70a395
[ "Artistic-2.0" ]
1
2020-12-27T11:47:31.000Z
2020-12-27T11:47:31.000Z
/* * stream_feeder.hpp * * Created on: Jan 27, 2016 * Author: zmij */ #ifndef WIRE_UTIL_CONCATENATE_HPP_ #define WIRE_UTIL_CONCATENATE_HPP_ #include <sstream> #include <string> #include <typeinfo> namespace wire { namespace util { namespace detail { struct __io_meta_function_helper { template <typename T> __io_meta_function_helper(T const&); }; ::std::false_type operator << (::std::ostream const&, __io_meta_function_helper const&); template <typename T> struct has_output_operator { private: static ::std::false_type test(::std::false_type); static ::std::true_type test(::std::ostream&); static ::std::ostream& os; static T const& val; public: static constexpr bool value = ::std::is_same< decltype( test( os << val) ), ::std::true_type >::type::value; }; template < typename T, bool > struct output_impl { static void output(::std::ostream& os, T const& arg) { os << arg; } }; template < typename T > struct output_impl<T, false> { static void output(::std::ostream& os, T const&) { os << typeid(T).name(); } }; template < typename T > void concatenate( ::std::ostream& os, T const& arg) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); } template < typename T, typename ... Y > void concatenate( ::std::ostream& os, T const& arg, Y const& ... args ) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); concatenate(os, args ...); } template < typename T > void delim_concatenate( ::std::ostream& os, ::std::string const& delim, T const& arg) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); } template < typename T, typename ... Y > void delim_concatenate( ::std::ostream& os, ::std::string const& delim, T const& arg, Y const& ... args ) { using output = output_impl<T, has_output_operator<T>::value>; output::output(os, arg); os << delim; delim_concatenate(os, delim, args ...); } } // namespace detail template < typename ... T > ::std::string concatenate( T const& ... args) { ::std::ostringstream os; detail::concatenate(os, args ...); return os.str(); } template < typename ... T > ::std::string delim_concatenate(::std::string const& delim, T const& ... args) { ::std::ostringstream os; detail::delim_concatenate(os, delim, args ...); return os.str(); } } // namespace util } // namespace wire #endif /* WIRE_UTIL_CONCATENATE_HPP_ */
22.147826
100
0.647428
zmij
c16dc9367f81c8ff11ae5bed4efdf9351fc6c171
2,176
cpp
C++
src/handler/media_mux.cpp
anjisuan783/media_server
443fdbda8a778c7302020ea16f4fb25cd3fd8dae
[ "MIT" ]
9
2022-01-07T03:10:45.000Z
2022-03-31T03:29:02.000Z
src/handler/media_mux.cpp
anjisuan783/media_server
443fdbda8a778c7302020ea16f4fb25cd3fd8dae
[ "MIT" ]
16
2021-12-17T08:32:57.000Z
2022-03-10T06:16:14.000Z
src/handler/media_mux.cpp
anjisuan783/media_lib
c09c7d48f495a803df79e39cf837bbcb1320ceb8
[ "MIT" ]
1
2022-02-21T15:47:21.000Z
2022-02-21T15:47:21.000Z
// // Copyright (c) 2021- anjisuan783 // // SPDX-License-Identifier: MIT // #include "handler/media_mux.h" #include "common/media_kernel_error.h" #include "utils/json.h" #include "connection/http_conn.h" #include "http/http_stack.h" #include "http/h/http_message.h" #include "connection/h/media_conn_mgr.h" #include "rtmp/media_req.h" #include "handler/media_live_handler.h" #include "handler/media_rtc_handler.h" #include "handler/media_file_handler.h" namespace ma { MediaHttpServeMux::MediaHttpServeMux() : rtc_sevice_{new MediaHttpRtcServeMux}, flv_sevice_{new MediaFlvPlayHandler}, file_sevice_{new MediaFileHandler} { g_conn_mgr_.signal_destroy_conn_.connect(this, &MediaHttpServeMux::conn_destroy); } MediaHttpServeMux::~MediaHttpServeMux() = default; srs_error_t MediaHttpServeMux::init() { return rtc_sevice_->init(); } srs_error_t MediaHttpServeMux::serve_http( std::shared_ptr<IHttpResponseWriter> writer, std::shared_ptr<ISrsHttpMessage> msg) { std::string path = msg->path(); if (path == RTC_PUBLISH_PREFIX || path == RTC_PALY_PREFIX) { return rtc_sevice_->serve_http(std::move(writer), std::move(msg)); } if (path == HTTP_TEST) { return file_sevice_->serve_http(std::move(writer), std::move(msg)); } return flv_sevice_->serve_http(std::move(writer), std::move(msg)); } srs_error_t MediaHttpServeMux::mount_service( std::shared_ptr<MediaSource> s, std::shared_ptr<MediaRequest> r) { srs_error_t err = srs_success; if ((err = rtc_sevice_->mount_service(s, r)) != srs_success) { return srs_error_wrap(err, "rtc mount service"); } return flv_sevice_->mount_service(std::move(s), std::move(r)); } void MediaHttpServeMux::unmount_service( std::shared_ptr<MediaSource> s, std::shared_ptr<MediaRequest> r) { rtc_sevice_->unmount_service(s, r); flv_sevice_->unmount_service(std::move(s), std::move(r)); } void MediaHttpServeMux::conn_destroy(std::shared_ptr<IMediaConnection> conn) { flv_sevice_->conn_destroy(conn); file_sevice_->conn_destroy(conn); } std::unique_ptr<IMediaHttpHandler> ServerHandlerFactor::Create() { return std::make_unique<MediaHttpServeMux>(); } }
27.897436
83
0.737592
anjisuan783
c174b800b5a2517e76055a9369c8b9f60be4a046
2,945
cpp
C++
mesh_processing/VertexWeights.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
23
2015-08-13T07:36:00.000Z
2022-01-24T19:00:04.000Z
mesh_processing/VertexWeights.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
null
null
null
mesh_processing/VertexWeights.cpp
rms80/libgeometry
e60ec7d34968573a9cda3f3bf56d2d4717385dc9
[ "BSL-1.0" ]
6
2015-07-06T21:37:31.000Z
2020-07-01T04:07:50.000Z
// Copyright Ryan Schmidt 2011. // Distributed under the Boost Software License, Version 1.0. // (See copy at http://www.boost.org/LICENSE_1_0.txt) #include "VertexWeights.h" #include "VectorUtil.h" #include "rmsdebug.h" using namespace rms; void VertexWeights::Uniform( VFTriangleMesh & mesh, IMesh::VertexID vID, std::vector<IMesh::VertexID> & vNeighbourhood, std::vector<float> & vWeights, bool bNormalize ) { size_t nNbrs = vNeighbourhood.size(); vWeights.resize(nNbrs); for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] = 1.0f; if ( bNormalize ) { float fWeightSum = (float)nNbrs; for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] /= fWeightSum; } } void VertexWeights::InverseDistance( VFTriangleMesh & mesh, IMesh::VertexID vID, std::vector<IMesh::VertexID> & vNeighbourhood, std::vector<float> & vWeights, float fPow, float fEps, bool bNormalize ) { Wml::Vector3f vVtx, vNbr; mesh.GetVertex(vID, vVtx); float fWeightSum = 0.0f; size_t nNbrs = vNeighbourhood.size(); vWeights.resize(nNbrs); for ( unsigned int k = 0; k < nNbrs; ++k ) { mesh.GetVertex( vNeighbourhood[k], vNbr ); float fDist = (vNbr - vVtx).Length(); vWeights[k] = 1.0f / (fEps + pow(fDist,fPow)); fWeightSum += vWeights[k]; } if ( bNormalize ) { float fWeightSum = (float)nNbrs; for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] /= fWeightSum; } } //! assumes one-ring is ordered void VertexWeights::Cotangent( VFTriangleMesh & mesh, IMesh::VertexID vID, std::vector<IMesh::VertexID> & vOneRing, std::vector<float> & vWeights, bool bNormalize ) { Wml::Vector3f vVtx, vOpp, vPrev, vNext; size_t nNbrs = vOneRing.size(); mesh.GetVertex(vID, vVtx); mesh.GetVertex(vOneRing[0], vOpp); mesh.GetVertex(vOneRing[nNbrs-1], vPrev); vWeights.resize(nNbrs); float fWeightSum = 0.0f; for ( unsigned int k = 0; k < nNbrs; ++k ) { IMesh::VertexID nNext = vOneRing[(k+1)%nNbrs]; mesh.GetVertex(nNext, vNext); Wml::Vector3f a1(vVtx - vPrev); a1.Normalize(); Wml::Vector3f a2(vOpp - vPrev); a2.Normalize(); float fADot = a1.Dot(a2); double fAlpha = acos( rms::Clamp(fADot, -1.0f, 1.0f) ); Wml::Vector3f b1(vVtx - vNext); b1.Normalize(); Wml::Vector3f b2(vOpp - vNext); b2.Normalize(); float fBDot = b1.Dot(b2); double fBeta = acos( rms::Clamp(fBDot, -1.0f, 1.0f) ); vWeights[k] = (float)( 1/tan(fAlpha) + 1/tan(fBeta) ); if ( ! _finite(vWeights[k]) ) _RMSInfo("MeshUtils::CotangentWeights():: non-finite weight at vertex %d [%d/%d] alpha d/a: %f/%f beta d/a: %f/%f\n", vOneRing[k], k, nNbrs, fADot,fAlpha, fBDot, fBeta); fWeightSum += vWeights[k]; vPrev = vOpp; vOpp = vNext; } if ( bNormalize ) { for ( unsigned int k = 0; k < nNbrs; ++k ) vWeights[k] /= fWeightSum; } }
28.872549
177
0.619694
rms80
c17a07f579626e88d8c3f8149000b9873dfb35aa
3,994
cpp
C++
code/src/GeminiClient.cpp
Blackmane/gemini
4c7091aec06826bf2ff440c858a18c9e05730d59
[ "MIT" ]
null
null
null
code/src/GeminiClient.cpp
Blackmane/gemini
4c7091aec06826bf2ff440c858a18c9e05730d59
[ "MIT" ]
null
null
null
code/src/GeminiClient.cpp
Blackmane/gemini
4c7091aec06826bf2ff440c858a18c9e05730d59
[ "MIT" ]
null
null
null
/** * @file GeminiClient.cpp * @brief implementation * * @author Niccolò Pieretti * @date 02 Apr 2021 * **************************************************************************** * * _ _ o __ __ __ _ o _ ,_ _ * / |/ | | / / / \_|/ \_| |/ / | |/ * | |_/|_/\__/\___/\__/ |__/ |_/|__/ |_/|__/ * /| * \| ****************************************************************************/ #include "GeminiClient.hpp" #include "Exception.hpp" #include "Protocol.hpp" #include "TslSocket.hpp" #include "Utils.hpp" #include <iostream> #include <errno.h> #include <netdb.h> #include <openssl/err.h> #include <resolv.h> #include <string.h> #include <unistd.h> // ~~~~~ ~~~~~ ~~~~~ // Implementation // ~~~~~ ~~~~~ ~~~~~ std::unique_ptr<gemini::Response> gemini::GeminiClient::getResponse(std::string request, std::unique_ptr<Socket> connection) { // Send request auto sendRes = connection->send(request); if (sendRes <= 0) { throw connection_error("Error in send request"); } // Read <STATUS><SPACE> const auto statusSize = response::HEADER_STATUS_SIZE + response::HEADER_SPACE_SIZE; char statusBuffer[statusSize + 1]; auto statusRes = connection->read(statusBuffer, statusSize); if ((size_t)statusRes < statusSize) { throw protocol_response_error("Empty response"); } if (!(response::isHeaderStatusFirstValid(statusBuffer[0]) && response::isHeaderStatusSecondValid(statusBuffer[1]))) { throw protocol_response_error("Invalid status --- response"); } if (statusBuffer[2] != ' ') { throw protocol_response_error("Invalid status response"); } std::unique_ptr<Response> response(new Response); response->statusCodeFirst = statusBuffer[0] - '0'; response->statusCodeSecond = statusBuffer[1] - '0'; // Read <META><CR><FL> const auto metaSize = response::HEADER_META_SIZE + 2; char metaBuffer[metaSize + 1]; auto metaRes = connection->read(metaBuffer, metaSize); // Check header termination if (metaRes < 2) { throw protocol_response_error("Empty header"); } // Assure metaBuffer terminates metaBuffer[metaRes > metaSize ? metaSize : metaRes] = '\0'; // Find terminators auto pos = strstr(metaBuffer, "\r\n"); if (pos == nullptr) { throw protocol_response_error("Invalid header termination"); } if ((size_t)(pos - metaBuffer) > response::HEADER_META_SIZE) { throw protocol_response_error("Invalid meta size"); } // Save meta response->meta = std::string(metaBuffer, pos); // Read <BODY> if (response->statusCodeFirst == response::HEADER_STATUS_FIRST::SUCCESS) { const auto bodyChunkSize = response::BODY_CHUNK_SIZE; char bodyBuffer[bodyChunkSize + 1]; // Copy previous part if (pos + 2 < metaBuffer + metaRes) { response->body += std::string(pos + 2, metaBuffer + metaRes); } auto bodyRes = connection->read(bodyBuffer, bodyChunkSize); while (bodyRes > 0) { // Set string terminator bodyBuffer[(size_t)bodyRes > bodyChunkSize ? bodyChunkSize : bodyRes] = '\0'; response->body += std::string(bodyBuffer); bodyRes = connection->read(bodyBuffer, bodyChunkSize); } } return response; } std::unique_ptr<gemini::Response> gemini::GeminiClient::request(const std::string url, const std::string port) { // Check url if (url.length() > request::URL_MAX_SIZE) { throw std::invalid_argument("Invalid url length: expected max " + std::to_string(request::URL_MAX_SIZE)); } // Open socket const std::string hostname = getHostnameFromUrl(url); std::unique_ptr<Socket> socket = std::unique_ptr<Socket>(new TslSocket(hostname, port)); // Build request: <URL><CR><LF> std::string request(url + gemini::CR + gemini::LF); return getResponse(request, std::move(socket)); }
31.698413
78
0.604407
Blackmane
c181b5a07187c900d3ad3a1b4baf132f13cfa7b0
61,082
hpp
C++
hpx/hpx_fwd.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/hpx_fwd.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
hpx/hpx_fwd.hpp
andreasbuhr/hpx
4366a90aacbd3e95428a94ab24a1646a67459cc2
[ "BSL-1.0" ]
null
null
null
// Copyright (c) 2007-2013 Hartmut Kaiser // Copyright (c) 2011 Bryce Lelbach // // Distributed under the Boost Software License, Version 1.0. (See accompanying // file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) /// \file hpx_fwd.hpp #if !defined(HPX_HPX_FWD_MAR_24_2008_1119AM) #define HPX_HPX_FWD_MAR_24_2008_1119AM #include <hpx/config.hpp> #include <cstdlib> #include <vector> #include <boost/config.hpp> #include <boost/version.hpp> #if BOOST_VERSION < 104200 // Please update your Boost installation (see www.boost.org for details). #error HPX cannot be compiled with a Boost version earlier than V1.42. #endif #if defined(BOOST_WINDOWS) #include <winsock2.h> #include <windows.h> #endif #include <boost/shared_ptr.hpp> #include <boost/intrusive_ptr.hpp> #include <boost/cstdint.hpp> #include <boost/thread/mutex.hpp> #include <boost/detail/scoped_enum_emulation.hpp> #include <boost/system/error_code.hpp> #include <hpx/config/function.hpp> #include <hpx/traits.hpp> #include <hpx/lcos/local/once_fwd.hpp> #include <hpx/util/unused.hpp> #include <hpx/util/move.hpp> #include <hpx/util/remove_reference.hpp> #include <hpx/util/coroutine/coroutine.hpp> #include <hpx/runtime/threads/detail/tagged_thread_state.hpp> /// \namespace hpx /// /// The namespace \a hpx is the main namespace of the HPX library. All classes /// functions and variables are defined inside this namespace. namespace hpx { /// \cond NOINTERNAL class error_code; HPX_EXCEPTION_EXPORT extern error_code throws; /// \namespace applier /// /// The namespace \a applier contains all definitions needed for the /// class \a hpx#applier#applier and its related functionality. This /// namespace is part of the HPX core module. namespace applier { class HPX_API_EXPORT applier; /// The function \a get_applier returns a reference to the (thread /// specific) applier instance. HPX_API_EXPORT applier& get_applier(); HPX_API_EXPORT applier* get_applier_ptr(); } namespace agas { struct HPX_API_EXPORT addressing_service; enum service_mode { service_mode_invalid = -1, service_mode_bootstrap = 0, service_mode_hosted = 1 }; } /// \namespace naming /// /// The namespace \a naming contains all definitions needed for the AGAS /// (Active Global Address Space) service. namespace naming { typedef agas::addressing_service resolver_client; struct HPX_API_EXPORT gid_type; struct HPX_API_EXPORT id_type; struct HPX_API_EXPORT address; class HPX_API_EXPORT locality; HPX_API_EXPORT resolver_client& get_agas_client(); } /////////////////////////////////////////////////////////////////////////// /// \namespace parcelset namespace parcelset { enum connection_type { connection_unknown = -1, connection_tcpip = 0, connection_shmem = 1, connection_portals4 = 2, connection_ibverbs = 3, connection_mpi = 4, connection_last }; class HPX_API_EXPORT parcel; class HPX_API_EXPORT parcelport; class HPX_API_EXPORT parcelhandler; namespace server { class parcelport_queue; } struct parcelhandler_queue_base; namespace policies { struct global_parcelhandler_queue; typedef global_parcelhandler_queue parcelhandler_queue; struct message_handler; } HPX_API_EXPORT std::string get_connection_type_name(connection_type); HPX_API_EXPORT connection_type get_connection_type_from_name(std::string const&); HPX_API_EXPORT policies::message_handler* get_message_handler( parcelhandler* ph, char const* name, char const* type, std::size_t num, std::size_t interval, naming::locality const& l, connection_type t, error_code& ec = throws); HPX_API_EXPORT void do_background_work(); } /// \namespace threads /// /// The namespace \a threadmanager contains all the definitions required /// for the scheduling, execution and general management of \a /// hpx#threadmanager#thread's. namespace threads { namespace policies { struct scheduler_base; #if defined(HPX_GLOBAL_SCHEDULER) class HPX_EXPORT global_queue_scheduler; #endif #if defined(HPX_STATIC_PRIORITY_SCHEDULER) template <typename Mutex = boost::mutex> class HPX_API_EXPORT static_priority_queue_scheduler; #endif #if defined(HPX_ABP_SCHEDULER) struct HPX_EXPORT abp_queue_scheduler; #endif #if defined(HPX_ABP_PRIORITY_SCHEDULER) class HPX_EXPORT abp_priority_queue_scheduler; #endif template <typename Mutex = boost::mutex> class HPX_EXPORT local_queue_scheduler; template <typename Mutex = boost::mutex> class HPX_EXPORT local_priority_queue_scheduler; #if defined(HPX_HIERARCHY_SCHEDULER) class HPX_EXPORT hierarchy_scheduler; #endif #if defined(HPX_PERIODIC_PRIORITY_SCHEDULER) class HPX_EXPORT periodic_priority_scheduler; #endif class HPX_EXPORT callback_notifier; // define the default scheduler to use typedef local_priority_queue_scheduler<> queue_scheduler; } struct HPX_EXPORT threadmanager_base; class HPX_EXPORT thread_data; template < typename SchedulingPolicy, typename NotificationPolicy = threads::policies::callback_notifier> class HPX_EXPORT threadmanager_impl; /// \enum thread_state_enum /// /// The \a thread_state_enum enumerator encodes the current state of a /// \a thread instance enum thread_state_enum { unknown = 0, active = 1, /*!< thread is currently active (running, has resources) */ pending = 2, /*!< thread is pending (ready to run, but no hardware resource available) */ suspended = 3, /*!< thread has been suspended (waiting for synchronization event, but still known and under control of the threadmanager) */ depleted = 4, /*!< thread has been depleted (deeply suspended, it is not known to the thread manager) */ terminated = 5, /*!< thread has been stopped an may be garbage collected */ staged = 6 /*!< this is not a real thread state, but allows to reference staged task descriptions, which eventually will be converted into thread objects */ }; /// \ cond NODETAIL /// Please note that if you change the value of threads::terminated /// above, you will need to adjust do_call(dummy<1> = 1) in /// util/coroutine/detail/coroutine_impl.hpp as well. /// \ endcond /// \enum thread_priority enum thread_priority { thread_priority_unknown = -1, thread_priority_default = 0, ///< use default priority thread_priority_low = 1, ///< low thread priority thread_priority_normal = 2, ///< normal thread priority (default) thread_priority_critical = 3 ///< high thread priority }; typedef threads::detail::tagged_thread_state<thread_state_enum> thread_state; HPX_API_EXPORT char const* get_thread_state_name(thread_state_enum state); HPX_API_EXPORT char const* get_thread_priority_name(thread_priority priority); /// \enum thread_state_ex_enum /// /// The \a thread_state_ex_enum enumerator encodes the reason why a /// thread is being restarted enum thread_state_ex_enum { wait_unknown = -1, wait_signaled = 0, ///< The thread has been signaled wait_timeout = 1, ///< The thread has been reactivated after a timeout wait_terminate = 2, ///< The thread needs to be terminated wait_abort = 3 ///< The thread needs to be aborted }; typedef threads::detail::tagged_thread_state<thread_state_ex_enum> thread_state_ex; typedef thread_state_enum thread_function_type(thread_state_ex_enum); /// \enum thread_stacksize enum thread_stacksize { thread_stacksize_small = 1, ///< use small stack size thread_stacksize_medium = 2, ///< use medium sized stack size thread_stacksize_large = 3, ///< use large stack size thread_stacksize_huge = 4, ///< use very large stack size thread_stacksize_nostack = 5, ///< this thread does not suspend (does not need a stack) thread_stacksize_default = thread_stacksize_small, ///< use default stack size thread_stacksize_minimal = thread_stacksize_small, ///< use minimally possible stack size thread_stacksize_maximal = thread_stacksize_huge, ///< use maximally possible stack size }; /////////////////////////////////////////////////////////////////////// /// \ cond NODETAIL namespace detail { template <typename CoroutineImpl> struct coroutine_allocator; } /// \ endcond typedef util::coroutines::coroutine< thread_function_type, detail::coroutine_allocator> coroutine_type; typedef coroutine_type::thread_id_type thread_id_type; typedef coroutine_type::self thread_self; /////////////////////////////////////////////////////////////////////// /// \ cond NODETAIL thread_id_type const invalid_thread_id = reinterpret_cast<thread_id_type>(-1); /// \ endcond /// The function \a get_self returns a reference to the (OS thread /// specific) self reference to the current PX thread. HPX_API_EXPORT thread_self& get_self(); /// The function \a get_self_ptr returns a pointer to the (OS thread /// specific) self reference to the current PX thread. HPX_API_EXPORT thread_self* get_self_ptr(); /// The function \a get_ctx_ptr returns a pointer to the internal data /// associated with each coroutine. HPX_API_EXPORT thread_self::impl_type* get_ctx_ptr(); /// The function \a get_self_ptr_checked returns a pointer to the (OS /// thread specific) self reference to the current HPX thread. HPX_API_EXPORT thread_self* get_self_ptr_checked(error_code& ec = throws); /// The function \a get_self_id returns the HPX thread id of the current /// thread (or zero if the current thread is not a PX thread). HPX_API_EXPORT thread_id_type get_self_id(); /// The function \a get_parent_id returns the HPX thread id of the /// current's thread parent (or zero if the current thread is not a /// PX thread). /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE /// being defined. HPX_API_EXPORT thread_id_type get_parent_id(); /// The function \a get_parent_phase returns the HPX phase of the /// current's thread parent (or zero if the current thread is not a /// PX thread). /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE /// being defined. HPX_API_EXPORT std::size_t get_parent_phase(); /// The function \a get_parent_locality_id returns the id of the locality of /// the current's thread parent (or zero if the current thread is not a /// PX thread). /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_PARENT_REFERENCE /// being defined. HPX_API_EXPORT boost::uint32_t get_parent_locality_id(); /// The function \a get_self_component_id returns the lva of the /// component the current thread is acting on /// /// \note This function will return a meaningful value only if the /// code was compiled with HPX_THREAD_MAINTAIN_TARGET_ADDRESS /// being defined. HPX_API_EXPORT boost::uint64_t get_self_component_id(); /// The function \a get_thread_manager returns a reference to the /// current thread manager. HPX_API_EXPORT threadmanager_base& get_thread_manager(); /// The function \a get_thread_count returns the number of currently /// known threads. /// /// \note If state == unknown this function will not only return the /// number of currently existing threads, but will add the number /// of registered task descriptions (which have not been /// converted into threads yet). HPX_API_EXPORT boost::int64_t get_thread_count( thread_state_enum state = unknown); /// \copydoc get_thread_count(thread_state_enum state) HPX_API_EXPORT boost::int64_t get_thread_count( thread_priority priority, thread_state_enum state = unknown); } /// \namespace actions /// /// The namespace \a actions contains all definitions needed for the /// class \a hpx#action_manager#action_manager and its related /// functionality. This namespace is part of the HPX core module. namespace actions { struct HPX_API_EXPORT base_action; typedef boost::shared_ptr<base_action> action_type; class HPX_API_EXPORT continuation; typedef boost::shared_ptr<continuation> continuation_type; class HPX_API_EXPORT action_manager; template <typename Component, typename Result, typename Arguments, typename Derived> struct action; } class HPX_API_EXPORT runtime; class HPX_API_EXPORT thread; /// A HPX runtime can be executed in two different modes: console mode /// and worker mode. enum runtime_mode { runtime_mode_invalid = -1, runtime_mode_console = 0, ///< The runtime is the console locality runtime_mode_worker = 1, ///< The runtime is a worker locality runtime_mode_connect = 2, ///< The runtime is a worker locality ///< connecting late runtime_mode_default = 3, ///< The runtime mode will be determined ///< based on the command line arguments runtime_mode_last }; /// Get the readable string representing the name of the given runtime_mode /// constant. HPX_API_EXPORT char const* get_runtime_mode_name(runtime_mode state); HPX_API_EXPORT runtime_mode get_runtime_mode_from_name(std::string const& mode); /////////////////////////////////////////////////////////////////////////// /// Retrieve the string value of a configuration entry as given by \p key. HPX_API_EXPORT std::string get_config_entry(std::string const& key, std::string const& dflt); /// Retrieve the integer value of a configuration entry as given by \p key. HPX_API_EXPORT std::string get_config_entry(std::string const& key, std::size_t dflt); /////////////////////////////////////////////////////////////////////////// template < typename SchedulingPolicy, typename NotificationPolicy = threads::policies::callback_notifier> class HPX_API_EXPORT runtime_impl; /// The function \a get_runtime returns a reference to the (thread /// specific) runtime instance. HPX_API_EXPORT runtime& get_runtime(); HPX_API_EXPORT runtime* get_runtime_ptr(); /// The function \a get_locality returns a reference to the locality HPX_API_EXPORT naming::locality const& get_locality(); /// The function \a get_runtime_instance_number returns a unique number /// associated with the runtime instance the current thread is running in. HPX_API_EXPORT std::size_t get_runtime_instance_number(); HPX_API_EXPORT void report_error(std::size_t num_thread , boost::exception_ptr const& e); HPX_API_EXPORT void report_error(boost::exception_ptr const& e); /// Register a function to be called during system shutdown HPX_API_EXPORT bool register_on_exit(HPX_STD_FUNCTION<void()> const&); enum logging_destination { destination_hpx = 0, destination_timing = 1, destination_agas = 2, destination_app = 3 }; /// \namespace components namespace components { enum factory_state_enum { factory_enabled = 0, factory_disabled = 1, factory_check = 2 }; /// \ cond NODETAIL namespace detail { struct this_type {}; struct fixed_component_tag {}; struct simple_component_tag {}; struct managed_component_tag {}; } /// \ endcond /////////////////////////////////////////////////////////////////////// typedef boost::int32_t component_type; enum component_enum_type { component_invalid = -1, // Runtime support component (provides system services such as // component creation, etc). One per locality. component_runtime_support = 0, // Pseudo-component for direct access to local virtual memory. component_memory = 1, // Generic memory blocks. component_memory_block = 2, // Base component for LCOs that do not produce a value. component_base_lco = 3, // Base component for LCOs that do produce values. component_base_lco_with_value = 4, // Synchronization barrier LCO. component_barrier = ((5 << 16) | component_base_lco), // An LCO representing a value which may not have been computed yet. component_promise = ((6 << 16) | component_base_lco_with_value), // AGAS locality services. component_agas_locality_namespace = 7, // AGAS primary address resolution services. component_agas_primary_namespace = 8, // AGAS global type system. component_agas_component_namespace = 9, // AGAS symbolic naming services. component_agas_symbol_namespace = 10, #if defined(HPX_HAVE_SODIUM) // root CA, subordinate CA component_root_certificate_authority = 11, component_subordinate_certificate_authority = 12, #endif component_last, component_first_dynamic = component_last, // Force this enum type to be at least 32 bits. component_upper_bound = 0x7fffffffL //-V112 }; /////////////////////////////////////////////////////////////////////// template <typename Component = detail::this_type> class fixed_component_base; template <typename Component> class fixed_component; template <typename Component = detail::this_type> class abstract_simple_component_base; template <typename Component = detail::this_type> class simple_component_base; template <typename Component> class simple_component; template <typename Component, typename Derived = detail::this_type> class abstract_managed_component_base; template <typename Component, typename Wrapper = detail::this_type, typename CtorPolicy = traits::construct_without_back_ptr, typename DtorPolicy = traits::managed_object_controls_lifetime> class managed_component_base; template <typename Component, typename Derived = detail::this_type> class managed_component; struct HPX_API_EXPORT component_factory_base; template <typename Component> struct component_factory; class runtime_support; class memory; class memory_block; namespace stubs { struct runtime_support; struct memory; struct memory_block; } namespace server { class HPX_API_EXPORT runtime_support; class HPX_API_EXPORT memory; class HPX_API_EXPORT memory_block; } HPX_EXPORT void console_logging(logging_destination dest, std::size_t level, std::string const& msg); HPX_EXPORT void cleanup_logging(); HPX_EXPORT void activate_logging(); } HPX_EXPORT components::server::runtime_support* get_runtime_support_ptr(); /// \namespace lcos namespace lcos { class base_lco; template <typename Result, typename RemoteResult = Result> class base_lco_with_value; template <typename Result, typename RemoteResult = typename traits::promise_remote_result<Result>::type> class promise; template <typename Action, typename Result = typename traits::promise_local_result< typename Action::result_type>::type, typename DirectExecute = typename Action::direct_execution> class packaged_action; template <typename Action, typename Result = typename traits::promise_local_result< typename Action::result_type>::type, typename DirectExecute = typename Action::direct_execution> class deferred_packaged_task; template <typename Result> class future; template <typename ValueType> struct object_semaphore; namespace stubs { template <typename ValueType> struct object_semaphore; } namespace server { template <typename ValueType> struct object_semaphore; } } /// \namespace util namespace util { struct binary_filter; class HPX_EXPORT section; class HPX_EXPORT runtime_configuration; class HPX_EXPORT io_service_pool; /// \brief Expand INI variables in a string HPX_API_EXPORT std::string expand(std::string const& expand); /// \brief Expand INI variables in a string HPX_API_EXPORT void expand(std::string& expand); } namespace performance_counters { struct counter_info; } /////////////////////////////////////////////////////////////////////////// // Launch policy for \a hpx::async BOOST_SCOPED_ENUM_START(launch) { async = 0x01, deferred = 0x02, task = 0x04, // see N3632 sync = 0x08, all = 0x0f // async | deferred | task | sync }; BOOST_SCOPED_ENUM_END inline bool operator&(BOOST_SCOPED_ENUM(launch) lhs, BOOST_SCOPED_ENUM(launch) rhs) { return static_cast<int>(lhs) & static_cast<int>(rhs) ? true : false; } /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of OS-threads running in the runtime instance /// the current HPX-thread is associated with. HPX_API_EXPORT std::size_t get_os_thread_count(); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT bool is_scheduler_numa_sensitive(); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT util::runtime_configuration const& get_config(); /////////////////////////////////////////////////////////////////////////// HPX_API_EXPORT hpx::util::io_service_pool* get_thread_pool(char const* name); /////////////////////////////////////////////////////////////////////////// // Pulling important types into the main namespace using naming::id_type; using lcos::future; using lcos::promise; /// \endcond } namespace hpx { /////////////////////////////////////////////////////////////////////////// /// \brief Return the global id representing this locality /// /// The function \a find_here() can be used to retrieve the global id /// usable to refer to the current locality. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global id representing the locality this function has /// been called on. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return \a hpx::naming::invalid_id /// otherwise. /// /// \see \a hpx::find_all_localities(), \a hpx::find_locality() HPX_API_EXPORT naming::id_type find_here(error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the global id representing the root locality /// /// The function \a find_root_locality() can be used to retrieve the global /// id usable to refer to the root locality. The root locality is the /// locality where the main AGAS service is hosted. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global id representing the root locality for this /// application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return \a hpx::naming::invalid_id /// otherwise. /// /// \see \a hpx::find_all_localities(), \a hpx::find_locality() HPX_API_EXPORT naming::id_type find_root_locality(error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the list of global ids representing all localities /// available to this application. /// /// The function \a find_all_localities() can be used to retrieve the /// global ids of all localities currently available to this application. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global ids representing the localities currently /// available to this application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_all_localities( error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the list of global ids representing all localities /// available to this application which support the given component /// type. /// /// The function \a find_all_localities() can be used to retrieve the /// global ids of all localities currently available to this application /// which support the creation of instances of the given component type. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \param type [in] The type of the components for which the function should /// return the available localities. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \returns The global ids representing the localities currently /// available to this application which support the creation of /// instances of the given component type. If no localities /// supporting the given component type are currently available, /// this function will return an empty vector. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_all_localities( components::component_type type, error_code& ec = throws); /// \brief Return the list of locality ids of remote localities supporting /// the given component type. By default this function will return /// the list of all remote localities (all but the current locality). /// /// The function \a find_remote_localities() can be used to retrieve the /// global ids of all remote localities currently available to this /// application (i.e. all localities except the current one). /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global ids representing the remote localities currently /// available to this application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_remote_localities( error_code& ec = throws); /// \brief Return the list of locality ids of remote localities supporting /// the given component type. By default this function will return /// the list of all remote localities (all but the current locality). /// /// The function \a find_remote_localities() can be used to retrieve the /// global ids of all remote localities currently available to this /// application (i.e. all localities except the current one) which /// support the creation of instances of the given component type. /// /// \param type [in] The type of the components for which the function should /// return the available remote localities. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \returns The global ids representing the remote localities currently /// available to this application. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return an empty vector otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_locality() HPX_API_EXPORT std::vector<naming::id_type> find_remote_localities( components::component_type type, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the global id representing an arbitrary locality which /// supports the given component type. /// /// The function \a find_locality() can be used to retrieve the /// global id of an arbitrary locality currently available to this /// application which supports the creation of instances of the given /// component type. /// /// \note Generally, the id of a locality can be used for instance to /// create new instances of components and to invoke plain actions /// (global functions). /// /// \param type [in] The type of the components for which the function should /// return any available locality. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \returns The global id representing an arbitrary locality currently /// available to this application which supports the creation of /// instances of the given component type. If no locality /// supporting the given component type is currently available, /// this function will return \a hpx::naming::invalid_id. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return \a hpx::naming::invalid_id /// otherwise. /// /// \see \a hpx::find_here(), \a hpx::find_all_localities() HPX_API_EXPORT naming::id_type find_locality(components::component_type type, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of localities which are currently registered /// for the running application. /// /// The function \a get_num_localities returns the number of localities /// currently connected to the console. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::find_all_localities_sync, \a hpx::get_num_localities HPX_API_EXPORT boost::uint32_t get_num_localities_sync(error_code& ec = throws); /// \brief Return the number of localities which were registered at startup /// for the running application. /// /// The function \a get_initial_num_localities returns the number of localities /// which were connected to the console at application startup. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT boost::uint32_t get_initial_num_localities(); /////////////////////////////////////////////////////////////////////////// /// \brief Asynchronously return the number of localities which are /// currently registered for the running application. /// /// The function \a get_num_localities asynchronously returns the /// number of localities currently connected to the console. The returned /// future represents the actual result. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT lcos::future<boost::uint32_t> get_num_localities(); /// \brief Return the number of localities which are currently registered /// for the running application. /// /// The function \a get_num_localities returns the number of localities /// currently connected to the console which support the creation of the /// given component type. /// /// \param t The component type for which the number of connected /// localities should be retrieved. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT boost::uint32_t get_num_localities_sync( components::component_type t, error_code& ec = throws); /// \brief Asynchronously return the number of localities which are /// currently registered for the running application. /// /// The function \a get_num_localities asynchronously returns the /// number of localities currently connected to the console which support /// the creation of the given component type. The returned future represents /// the actual result. /// /// \param t The component type for which the number of connected /// localities should be retrieved. /// /// \note This function will return meaningful results only if called /// from an HPX-thread. It will return 0 otherwise. /// /// \see \a hpx::find_all_localities, \a hpx::get_num_localities HPX_API_EXPORT lcos::future<boost::uint32_t> get_num_localities( components::component_type t); /////////////////////////////////////////////////////////////////////////// /// The type of a function which is registered to be executed as a /// startup or pre-startup function. typedef HPX_STD_FUNCTION<void()> startup_function_type; /////////////////////////////////////////////////////////////////////////// /// \brief Add a function to be executed by a HPX thread before hpx_main /// but guaranteed before any startup function is executed (system-wide). /// /// Any of the functions registered with \a register_pre_startup_function /// are guaranteed to be executed by an HPX thread before any of the /// registered startup functions are executed (see /// \a hpx::register_startup_function()). /// /// \param f [in] The function to be registered to run by an HPX thread as /// a pre-startup function. /// /// \note If this function is called while the pre-startup functions are /// being executed or after that point, it will raise a invalid_status /// exception. /// /// This function is one of the few API functions which can be called /// before the runtime system has been fully initialized. It will /// automatically stage the provided startup function to the runtime /// system during its initialization (if necessary). /// /// \see \a hpx::register_startup_function() HPX_API_EXPORT void register_pre_startup_function(startup_function_type const& f); /////////////////////////////////////////////////////////////////////////// /// \brief Add a function to be executed by a HPX thread before hpx_main /// but guaranteed after any pre-startup function is executed (system-wide). /// /// Any of the functions registered with \a register_startup_function /// are guaranteed to be executed by an HPX thread after any of the /// registered pre-startup functions are executed (see: /// \a hpx::register_pre_startup_function()), but before \a hpx_main is /// being called. /// /// \param f [in] The function to be registered to run by an HPX thread as /// a startup function. /// /// \note If this function is called while the startup functions are /// being executed or after that point, it will raise a invalid_status /// exception. /// /// This function is one of the few API functions which can be called /// before the runtime system has been fully initialized. It will /// automatically stage the provided startup function to the runtime /// system during its initialization (if necessary). /// /// \see \a hpx::register_pre_startup_function() HPX_API_EXPORT void register_startup_function(startup_function_type const& f); /// The type of a function which is registered to be executed as a /// shutdown or pre-shutdown function. typedef HPX_STD_FUNCTION<void()> shutdown_function_type; /// \brief Add a function to be executed by a HPX thread during /// \a hpx::finalize() but guaranteed before any shutdown function is /// executed (system-wide) /// /// Any of the functions registered with \a register_pre_shutdown_function /// are guaranteed to be executed by an HPX thread during the execution of /// \a hpx::finalize() before any of the registered shutdown functions are /// executed (see: \a hpx::register_shutdown_function()). /// /// \param f [in] The function to be registered to run by an HPX thread as /// a pre-shutdown function. /// /// \note If this function is called before the runtime system is /// initialized, or while the pre-shutdown functions are /// being executed, or after that point, it will raise a invalid_status /// exception. /// /// \see \a hpx::register_shutdown_function() HPX_API_EXPORT void register_pre_shutdown_function(shutdown_function_type const& f); /// \brief Add a function to be executed by a HPX thread during /// \a hpx::finalize() but guaranteed after any pre-shutdown function is /// executed (system-wide) /// /// Any of the functions registered with \a register_shutdown_function /// are guaranteed to be executed by an HPX thread during the execution of /// \a hpx::finalize() after any of the registered pre-shutdown functions /// are executed (see: \a hpx::register_pre_shutdown_function()). /// /// \param f [in] The function to be registered to run by an HPX thread as /// a shutdown function. /// /// \note If this function is called before the runtime system is /// initialized, or while the shutdown functions are /// being executed, or after that point, it will raise a invalid_status /// exception. /// /// \see \a hpx::register_pre_shutdown_function() HPX_API_EXPORT void register_shutdown_function(shutdown_function_type const& f); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of the current OS-thread running in the /// runtime instance the current HPX-thread is executed with. /// /// This function returns the zero based index of the OS-thread which /// executes the current HPX-thread. /// /// \note The returned value is zero based and it's maximum value is /// smaller than the overall number of OS-threads executed (as /// returned by \a get_os_thread_count(). /// /// \note This function needs to be executed on a HPX-thread. It will /// fail otherwise (it will return -1). HPX_API_EXPORT std::size_t get_worker_thread_num(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of the locality this function is being called /// from. /// /// This function returns the id of the current locality. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note The returned value is zero based and it's maximum value is /// smaller than the overall number of localities the current /// application is running on (as returned by /// \a get_num_localities()). /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note This function needs to be executed on a HPX-thread. It will /// fail otherwise (it will return -1). HPX_API_EXPORT boost::uint32_t get_locality_id(error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Test whether the runtime system is currently running. /// /// This function returns whether the runtime system is currently running /// or not, e.g. whether the current state of the runtime system is /// \a hpx::runtime::running /// /// \note This function needs to be executed on a HPX-thread. It will /// return false otherwise. HPX_API_EXPORT bool is_running(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the name of the calling thread. /// /// This function returns the name of the calling thread. This name uniquely /// identifies the thread in the context of HPX. If the function is called /// while no HPX runtime system is active, the result will be "<unknown>". HPX_API_EXPORT std::string get_thread_name(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the number of worker OS- threads used to execute HPX /// threads /// /// This function returns the number of OS-threads used to execute HPX /// threads. If the function is called while no HPX runtime system is active, /// it will return zero. HPX_API_EXPORT std::size_t get_num_worker_threads(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the system uptime measure on the thread executing this call. /// /// This function returns the system uptime measured in nanoseconds for the /// thread executing this call. If the function is called while no HPX /// runtime system is active, it will return zero. HPX_API_EXPORT boost::uint64_t get_system_uptime(); /////////////////////////////////////////////////////////////////////////// /// \brief Return the id of the locality where the object referenced by the /// given id is currently located on /// /// The function hpx::get_colocation_id() returns the id of the locality /// where the given object is currently located. /// /// \param id [in] The id of the object to locate. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \see \a hpx::get_colocation_id() HPX_API_EXPORT naming::id_type get_colocation_id_sync( naming::id_type const& id, error_code& ec = throws); /// \brief Asynchronously return the id of the locality where the object /// referenced by the given id is currently located on /// /// \see \a hpx::get_colocation_id_sync() HPX_API_EXPORT lcos::future<naming::id_type> get_colocation_id( naming::id_type const& id); /////////////////////////////////////////////////////////////////////////// /// \brief Return the name of the referenced locality. /// /// This function returns a future referring to the name for the locality /// of the given id. /// /// \param id [in] The global id of the locality for which the name should /// be retrievd /// /// \returns This function returns the name for the locality of the given /// id. The name is retrieved from the underlying networking layer /// and may be different for different parcelports. /// HPX_API_EXPORT future<std::string> get_locality_name( naming::id_type const& id); /////////////////////////////////////////////////////////////////////////// /// \brief Trigger the LCO referenced by the given id /// /// \param id [in] this represents the id of the LCO which should be /// triggered. HPX_API_EXPORT void trigger_lco_event(naming::id_type const& id); /// \brief Set the result value for the LCO referenced by the given id /// /// \param id [in] this represents the id of the LCO which should /// receive the given value. /// \param t [in] this is the value which should be sent to the LCO. template <typename T> void set_lco_value(naming::id_type const& id, BOOST_FWD_REF(T) t); /// \brief Set the error state for the LCO referenced by the given id /// /// \param id [in] this represents the id of the LCO which should /// eceive the error value. /// \param e [in] this is the error value which should be sent to /// the LCO. HPX_API_EXPORT void set_lco_error(naming::id_type const& id, boost::exception_ptr const& e); /// \copydoc hpx::set_lco_error(naming::id_type const& id, boost::exception_ptr const& e) HPX_API_EXPORT void set_lco_error(naming::id_type const& id, BOOST_RV_REF(boost::exception_ptr) e); /////////////////////////////////////////////////////////////////////////// /// \brief Start all active performance counters, optionally naming the /// section of code /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void start_active_counters(error_code& ec = throws); /// \brief Resets all active performance counters. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void reset_active_counters(error_code& ec = throws); /// \brief Stop all active performance counters. /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void stop_active_counters(error_code& ec = throws); /// \brief Evaluate and output all active performance counters, optionally /// naming the point in code marked by this function. /// /// \param reset [in] this is an optional flag allowing to reset /// the counter value after it has been evaluated. /// \param description [in] this is an optional value naming the point in /// the code marked by the call to this function. /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. /// /// \note The output generated by this function is redirected to the /// destination specified by the corresponding command line /// options (see \--hpx:print-counter-destination). /// /// \note The active counters are those which have been specified on /// the command line while executing the application (see command /// line option \--hpx:print-counter) HPX_API_EXPORT void evaluate_active_counters(bool reset = false, char const* description = 0, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Create an instance of a message handler plugin /// /// The function hpx::create_message_handler() creates an instance of a /// message handler plugin based on the parameters specified. /// /// \param message_handler_type /// \param action /// \param pp /// \param num_messages /// \param interval /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. HPX_API_EXPORT parcelset::policies::message_handler* create_message_handler( char const* message_handler_type, char const* action, parcelset::parcelport* pp, std::size_t num_messages, std::size_t interval, error_code& ec = throws); /////////////////////////////////////////////////////////////////////////// /// \brief Create an instance of a binary filter plugin /// /// \param ec [in,out] this represents the error status on exit, if this /// is pre-initialized to \a hpx#throws the function will throw /// on error instead. /// /// \note As long as \a ec is not pre-initialized to \a hpx::throws this /// function doesn't throw but returns the result code using the /// parameter \a ec. Otherwise it throws an instance of /// hpx::exception. HPX_API_EXPORT util::binary_filter* create_binary_filter( char const* binary_filter_type, bool compress, util::binary_filter* next_filter = 0, error_code& ec = throws); #if defined(HPX_HAVE_SODIUM) namespace components { namespace security { class certificate; class certificate_signing_request; class parcel_suffix; class hash; template <typename T> class signed_type; typedef signed_type<certificate> signed_certificate; typedef signed_type<certificate_signing_request> signed_certificate_signing_request; typedef signed_type<parcel_suffix> signed_parcel_suffix; }} #if defined(HPX_HAVE_SECURITY) /// \brief Return the certificate for this locality /// /// \returns This function returns the signed certificate for this locality. HPX_API_EXPORT components::security::signed_certificate const& get_locality_certificate(error_code& ec = throws); /// \brief Return the certificate for the given locality /// /// \param id The id representing the locality for which to retrieve /// the signed certificate. /// /// \returns This function returns the signed certificate for the locality /// identified by the parameter \a id. HPX_API_EXPORT components::security::signed_certificate const& get_locality_certificate(boost::uint32_t locality_id, error_code& ec = throws); /// \brief Add the given certificate to the certificate store of this locality. /// /// \param cert The certificate to add to the certificate store of this /// locality HPX_API_EXPORT void add_locality_certificate( components::security::signed_certificate const& cert, error_code& ec = throws); #endif #endif } #include <hpx/lcos/async_fwd.hpp> #endif
43.167491
105
0.606447
andreasbuhr
c181d6aba3a40cbc3958e0b7b480daf7ef966266
2,158
cpp
C++
NodesKLevelFar.cpp
aak-301/data-structure
13d63e408a0001ceb06e2937ab8fcc3f176db78d
[ "Apache-2.0" ]
null
null
null
NodesKLevelFar.cpp
aak-301/data-structure
13d63e408a0001ceb06e2937ab8fcc3f176db78d
[ "Apache-2.0" ]
null
null
null
NodesKLevelFar.cpp
aak-301/data-structure
13d63e408a0001ceb06e2937ab8fcc3f176db78d
[ "Apache-2.0" ]
null
null
null
// https://leetcode.com/problems/all-nodes-distance-k-in-binary-tree/submissions/ #include<iostream> #include<vector> using namespace std; struct TreeNode{ int val; struct TreeNode *left, *right; TreeNode(int x){ val = x; left=NULL; right=NULL; } }; bool findUntil(TreeNode* root, TreeNode* target,vector<TreeNode* >& v){ if(root == NULL) return false; if(root->val == target->val) { v.push_back(root); return true; } bool b = findUntil(root->left,target,v); if(b){ v.push_back(root); return true; } bool c = findUntil(root->right,target,v); if(c){ v.push_back(root); return true; } return false; } vector<TreeNode*> findNode(TreeNode* root, TreeNode* target){ vector<TreeNode* > v; findUntil(root, target, v); return v; } void GetNodes(TreeNode* root,int k, TreeNode* p, vector<int>& store){ if(root==NULL || root==p || k<0) return; if(k==0){ store.push_back(root->val); } GetNodes(root->left, k-1, p, store); GetNodes(root->right, k-1, p, store); } vector<int> distanceK(TreeNode* root, TreeNode* target, int k) { vector<TreeNode* > v = findNode(root, target); int n = v.size(); vector<int> store; for(int i=0;i<n;i++){ GetNodes(v[i],k-i, i==0?NULL:v[i-1], store); } return store; } int main(){ /* 3 / \ 5 1 / \ / \ 6 2 0 8 / \ 7 4 */ struct TreeNode* root = new TreeNode(3); root->left = new TreeNode(5); root->right = new TreeNode(1); root->left->left = new TreeNode(6); root->left->right = new TreeNode(2); root->right->left = new TreeNode(0); root->right->right = new TreeNode(8); root->left->right->left = new TreeNode(7); root->left->right->right = new TreeNode(4); vector<int> v = distanceK(root, root->left->right->right,2); for(int e : v) cout<<e<<" "; }
28.025974
82
0.517609
aak-301
c1862f98a059c6beab92ef353f27e694106bef60
997
cpp
C++
codeforces/1430/1430D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
8
2020-12-23T07:54:53.000Z
2021-11-23T02:46:35.000Z
codeforces/1430/1430D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2020-11-07T13:22:29.000Z
2020-12-20T12:54:00.000Z
codeforces/1430/1430D/main.cpp
xirc/cp-algorithm
89c67cff2f00459c5bb020ab44bff5ae419a1728
[ "Apache-2.0" ]
1
2021-01-16T03:40:10.000Z
2021-01-16T03:40:10.000Z
#include <bits/stdc++.h> using namespace std; int solve(int N, string const& S) { map<int, int> count; vector<int> next(N, -1); for (int i = 0; i < N; ++i) { int j; for (j = i + 1; j < N; ++j) { if (S[i] != S[j]) break; } if (j > i + 1) { count[i] = j - i; } next[i] = j; i = j - 1; } int ans = 0; for (int i = 0; i < N;) { ++ans; if (count.empty()) { i = next[i]; if (i < N) i = next[i]; } else { auto it = count.begin(); --it->second; if (it->second == 1 || it->first < next[i]) count.erase(it); i = next[i]; } } return ans; } int main() { ios_base::sync_with_stdio(false); cin.tie(0); cout.tie(0); int T, N; string S; cin >> T; for (int tt = 0; tt < T; ++tt) { cin >> N >> S; cout << solve(N, S) << endl; } return 0; }
19.54902
72
0.377131
xirc
c1865d0df63483a4e1ed41a9f9d8eb601daa4d43
1,461
hpp
C++
engine/include/Engine/SpriteBounds.hpp
Alexthehuman3/ASGE
a9cf473a3117f4b67a2dbe8fac00b1a2a4fd6e44
[ "MIT" ]
8
2020-04-26T11:48:29.000Z
2022-02-23T15:13:50.000Z
engine/include/Engine/SpriteBounds.hpp
Alexthehuman3/ASGE
a9cf473a3117f4b67a2dbe8fac00b1a2a4fd6e44
[ "MIT" ]
null
null
null
engine/include/Engine/SpriteBounds.hpp
Alexthehuman3/ASGE
a9cf473a3117f4b67a2dbe8fac00b1a2a4fd6e44
[ "MIT" ]
1
2021-05-13T16:37:24.000Z
2021-05-13T16:37:24.000Z
// Copyright (c) 2021 James Huxtable. All rights reserved. // // This work is licensed under the terms of the MIT license. // // 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. /** * @file * @brief Struct @ref ASGE::SpriteBounds */ #ifndef ASGE_SPRITEBOUNDS_HPP #define ASGE_SPRITEBOUNDS_HPP #include "Point2D.hpp" namespace ASGE { /** * @brief Four vertices defining a sprites bound. * * Used to conveniently store 4 points together. These 4 points * typically define the for vertices defining the bounding rectangle * of a sprite. Note:There is no guarantee that the bounds stored here * are axis-aligned or ordered. */ struct SpriteBounds { Point2D v1 = { 0, 0 }; /**< The first vertex position. */ Point2D v2 = { 0, 0 }; /**< The second vertex position */ Point2D v3 = { 0, 0 }; /**< The third vertex position. */ Point2D v4 = { 0, 0 }; /**< The fourth vertex position. */ }; using TextBounds = SpriteBounds; } // namespace ASGE #endif // ASGE_SPRITEBOUNDS_HPP
33.204545
81
0.698152
Alexthehuman3
c18782859e92c0451ee2ec694d9b240aedca574b
3,083
cpp
C++
winp/winp/test/hook_test.cpp
benbraide/winp2
f2687fe00b8cbda10f3e8d169c0c3823cf8e6c5f
[ "MIT" ]
null
null
null
winp/winp/test/hook_test.cpp
benbraide/winp2
f2687fe00b8cbda10f3e8d169c0c3823cf8e6c5f
[ "MIT" ]
null
null
null
winp/winp/test/hook_test.cpp
benbraide/winp2
f2687fe00b8cbda10f3e8d169c0c3823cf8e6c5f
[ "MIT" ]
null
null
null
#include "hook_test.h" void winp::test::hook::run(int cmd_show){ winp::window::object ws; ws.set_caption(L"Test Window"); ws.set_position(30, 30); ws.set_size(1500, 800); ws.create(); ws.show(cmd_show); ws.get_grid([](winp::grid::object &grd){ grd.add_object([](winp::grid::row &row){ row.add_object([](winp::grid::column &col){ col.add_object([&](control::push_button &btn){ btn.set_text(L"Top-Left Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_left); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Top-Center Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_center); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Top-Right Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::top_right); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Center-Right Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center_right); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Center Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Center-Left Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::center_left); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Bottom-Left Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_left); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Bottom-Center Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_center); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Bottom-Right Aligned"); btn.insert_hook<ui::placement_hook>(ui::placement_hook::alignment_type::bottom_right); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Drag-Hooked"); btn.set_position(200, 90); btn.insert_hook<ui::drag_hook>(); }); col.add_object([&](control::push_button &btn){ btn.set_text(L"Sibling Aligned"); btn.insert_hook<ui::sibling_placement_hook>(ui::sibling_placement_hook::sibling_type::previous, ui::sibling_placement_hook::alignment_type::center_right, POINT{ 5, 0 }); }); }); row.add_object([](winp::grid::column &col){ col.add_object([](winp::window::object &cw){ cw.set_caption(L"Children Contain Window"); cw.insert_hook<ui::children_contain_hook>(SIZE{ 30, 30 }); cw.set_position(30, 30); cw.set_size(900, 500); cw.create(); cw.show(); cw.add_object([](winp::window::object &ccw){ ccw.set_caption(L"Contained Child Window"); ccw.set_position(30, 30); ccw.set_size(450, 250); ccw.create(); ccw.show(); }); }); }); }); }); app::object::run(); }
32.797872
174
0.662018
benbraide
c187b2ab8bcc19a64601b02337c4528c929d6911
5,731
cpp
C++
Project4/src/ofApp.cpp
WenheLI/advanced_creative_code_19
1480c6ff8b7f5f53cc0f3ff8677138e70cff5269
[ "MIT" ]
null
null
null
Project4/src/ofApp.cpp
WenheLI/advanced_creative_code_19
1480c6ff8b7f5f53cc0f3ff8677138e70cff5269
[ "MIT" ]
null
null
null
Project4/src/ofApp.cpp
WenheLI/advanced_creative_code_19
1480c6ff8b7f5f53cc0f3ff8677138e70cff5269
[ "MIT" ]
null
null
null
#include "ofApp.h" //-------------------------------------------------------------- void ofApp::setup(){ ofSetFrameRate(60); for (int i = 0; i < 5; i++) { auto b = make_shared<Ball>(); b->init(); balls.push_back(b); } phase = 0; int bufferSize = 512; volume = 0.6f; pan =0.5f; ofSoundStreamSettings settings; settings.setOutListener(this); settings.sampleRate = sampleRate; settings.numOutputChannels = 2; settings.numInputChannels = 0; settings.bufferSize = bufferSize; soundStream.setup(settings); lAudio.assign(bufferSize, 0.0); rAudio.assign(bufferSize, 0.0); } //-------------------------------------------------------------- void ofApp::update(){ for (int i = 0; i < 5; i++) { for (int j = 0; j < 5; j++) if (i != j) balls[i]->update(balls[j]); } } //-------------------------------------------------------------- void ofApp::draw(){ ofBackground(34, 34, 34); ofSetColor(225); ofDrawBitmapString("press 's' to unpause the audio\npress 'e' to pause the audio", 31, 92); ofNoFill(); // draw the left channel: ofPushStyle(); ofPushMatrix(); ofTranslate(32, 150, 0); ofSetColor(225); ofDrawBitmapString("Left Channel", 4, 18); ofSetLineWidth(1); ofDrawRectangle(0, 0, 450, 200); ofSetColor(245, 58, 135); ofSetLineWidth(1.5); ofBeginShape(); for (unsigned int i = 0; i < lAudio.size(); i++){ float l = ofMap(i, 0, lAudio.size(), 0, 450, true); ofVertex(l, 100 -lAudio[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the right channel: ofPushStyle(); ofPushMatrix(); ofTranslate(500, 150, 0); ofSetColor(225); ofDrawBitmapString("Right Channel", 4, 18); ofSetLineWidth(1); ofDrawRectangle(0, 0, 450, 200); ofSetColor(245, 58, 135); ofSetLineWidth(1.5); ofBeginShape(); for (unsigned int i = 0; i < rAudio.size(); i++){ float l = ofMap(i, 0, rAudio.size(), 0, 450, true); ofVertex(l, 100 -rAudio[i]*180.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); for (int i = 0; i < 5; i++) balls[i]->draw(); } void ofApp::audioOut(ofSoundBuffer &outBuffer){ float leftScale = 1 - pan; float rightScale = pan; while (phase > TWO_PI){ phase -= TWO_PI; } for(int i = 0; i < outBuffer.size(); i += 2) { auto cooin = generateSample(phase, balls[0]); float sample = cooin * (ofMap(balls[0]->vel.length(), 0, 10, 0, .8)+.2); // generating a sine wave sample float x = balls[0]->pos.x; float w = ofGetWidth(); float rightOffset = ofMap(x - w/2.0, -w/2.0 , w/2.0, -1, 1); rightOffset = (-1 * abs(rightOffset)) + 1; float leftOffset = 1 - abs(rightOffset); rAudio[i]= sample * volume*leftOffset; lAudio[i]= sample * volume*rightOffset; outBuffer[i] = sample * volume*rightOffset; // writing/drawing to the left channel outBuffer[i+1] = sample * volume*leftOffset; // writing/drawing to the right channel //memorize this equation! phaseOffset = freq / sampleRate float phaseOffset = ((float)2000 / ofMap(balls[0]->preAcc.length(), 0, 80/balls[0]->r, 60, 2500)); phase += phaseOffset; } } float ofApp::generateSample(float phase, shared_ptr<Ball> ball){ auto waveType = waveTypeGenerator(ball->pos); switch (waveType) { case 1://sine return sin(phase*TWO_PI); break; case 2://square return sin(phase*TWO_PI) > 0 ? .5 : -.5; case 3://sawtooth return fmod(phase,TWO_PI); case 4://triangle return abs(sin(phase*TWO_PI)); default: break; } } int ofApp::waveTypeGenerator(ofVec2f ballPos){ if (ballPos.x >= 0 && ballPos.x < ofGetWidth()/2){ if (ballPos.y >= 0 && ballPos.y < ofGetHeight()/2){ return 1; } else { return 2; } } else { if (ballPos.y >= 0 && ballPos.y < ofGetHeight()/2){ return 3; } else { return 4; } } } //-------------------------------------------------------------- void ofApp::keyPressed(int key){ if( key == 's' ){ soundStream.start(); } if( key == 'e' ){ soundStream.stop(); } } //-------------------------------------------------------------- void ofApp::keyReleased(int key){ } //-------------------------------------------------------------- void ofApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void ofApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void ofApp::mouseEntered(int x, int y){ } //-------------------------------------------------------------- void ofApp::mouseExited(int x, int y){ } //-------------------------------------------------------------- void ofApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void ofApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void ofApp::dragEvent(ofDragInfo dragInfo){ }
24.283898
113
0.462746
WenheLI
c18ed2a631202bf3c99791fc194a9bbd53ad84ae
684
cpp
C++
1 Mathematics/gcd.cpp
AdityaVSM/algorithms
0ab0147a1e3905cf3096576a89cbce13de2673ed
[ "MIT" ]
null
null
null
1 Mathematics/gcd.cpp
AdityaVSM/algorithms
0ab0147a1e3905cf3096576a89cbce13de2673ed
[ "MIT" ]
null
null
null
1 Mathematics/gcd.cpp
AdityaVSM/algorithms
0ab0147a1e3905cf3096576a89cbce13de2673ed
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; int gcd1(int a, int b){ //worst cse:O(min(a,b)) int small = std::min(a,b); while(small > 0){ if(a%small == 0 && b%small == 0){ break; } small--; } return small; } //Euclid algo int gcd2(int a, int b){ while(a != b){ if(a>b) a -= b; else b -= a; } return a; } //optimized Euclid aligo int gcd3(int a, int b){ //Best approach O(log(min(a,b))) if(b == 0) return a; return gcd3(b,a%b); } int main(){ cout<<gcd1(4,6)<<endl; cout<<gcd2(4,6)<<endl; cout<<gcd3(4,6)<<endl; return 0; }
19
60
0.457602
AdityaVSM
c1901445cf21033fb7a2bab6fdc196dbaa46cd42
6,059
cpp
C++
core/src/db/snapshot/Operations.cpp
zhang19941219/milvus
afac02ca2f1cab7bd98afb8fe6981d602b7a9a9b
[ "Apache-2.0" ]
null
null
null
core/src/db/snapshot/Operations.cpp
zhang19941219/milvus
afac02ca2f1cab7bd98afb8fe6981d602b7a9a9b
[ "Apache-2.0" ]
null
null
null
core/src/db/snapshot/Operations.cpp
zhang19941219/milvus
afac02ca2f1cab7bd98afb8fe6981d602b7a9a9b
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2019-2020 Zilliz. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the License // is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express // or implied. See the License for the specific language governing permissions and limitations under the License. #include "db/snapshot/Operations.h" #include <chrono> #include <sstream> #include "db/snapshot/OperationExecutor.h" #include "db/snapshot/Snapshots.h" namespace milvus { namespace engine { namespace snapshot { static ID_TYPE UID = 1; std::ostream& operator<<(std::ostream& out, const Operations& operation) { out << operation.ToString(); return out; } Operations::Operations(const OperationContext& context, ScopedSnapshotT prev_ss, const OperationsType& type) : context_(context), prev_ss_(prev_ss), uid_(UID++), status_(SS_OPERATION_PENDING, "Operation Pending"), type_(type) { } Operations::Operations(const OperationContext& context, ID_TYPE collection_id, ID_TYPE commit_id, const OperationsType& type) : context_(context), uid_(UID++), status_(SS_OPERATION_PENDING, "Operation Pending"), type_(type) { auto status = Snapshots::GetInstance().GetSnapshot(prev_ss_, collection_id, commit_id); if (!status.ok()) prev_ss_ = ScopedSnapshotT(); } std::string Operations::SuccessString() const { return status_.ToString(); } std::string Operations::FailureString() const { return status_.ToString(); } std::string Operations::GetRepr() const { std::stringstream ss; ss << "<" << GetName() << ":" << GetID() << ">"; return ss.str(); } std::string Operations::ToString() const { std::stringstream ss; ss << GetRepr(); ss << (done_ ? " | DONE" : " | PENDING"); if (done_) { if (status_.ok()) { ss << " | " << SuccessString(); } else { ss << " | " << FailureString(); } } return ss.str(); } ID_TYPE Operations::GetID() const { return uid_; } Status Operations::operator()(Store& store) { auto status = PreCheck(); if (!status.ok()) return status; return ApplyToStore(store); } void Operations::SetStatus(const Status& status) { status_ = status; } Status Operations::WaitToFinish() { std::unique_lock<std::mutex> lock(finish_mtx_); finish_cond_.wait(lock, [this] { return done_; }); return status_; } void Operations::Done() { std::unique_lock<std::mutex> lock(finish_mtx_); done_ = true; if (GetType() == OperationsType::W_Compound) { std::cout << ToString() << std::endl; } finish_cond_.notify_all(); } Status Operations::PreCheck() { return Status::OK(); } Status Operations::Push(bool sync) { auto status = PreCheck(); if (!status.ok()) return status; return OperationExecutor::GetInstance().Submit(shared_from_this(), sync); } Status Operations::DoCheckStale(ScopedSnapshotT& latest_snapshot) const { return Status::OK(); } Status Operations::CheckStale(const CheckStaleFunc& checker) const { decltype(prev_ss_) latest_ss; auto status = Snapshots::GetInstance().GetSnapshotNoLoad(latest_ss, prev_ss_->GetCollection()->GetID()); if (!status.ok()) return status; if (prev_ss_->GetID() != latest_ss->GetID()) { if (checker) { status = checker(latest_ss); } else { status = DoCheckStale(latest_ss); } } return status; } Status Operations::DoneRequired() const { Status status; if (!done_) { status = Status(SS_CONSTRAINT_CHECK_ERROR, "Operation is expected to be done"); } return status; } Status Operations::IDSNotEmptyRequried() const { Status status; if (ids_.size() == 0) status = Status(SS_CONSTRAINT_CHECK_ERROR, "No Snapshot is available"); return status; } Status Operations::PrevSnapshotRequried() const { Status status; if (!prev_ss_) { status = Status(SS_CONSTRAINT_CHECK_ERROR, "Prev snapshot is requried"); } return status; } Status Operations::GetSnapshot(ScopedSnapshotT& ss) const { auto status = PrevSnapshotRequried(); if (!status.ok()) return status; status = DoneRequired(); if (!status.ok()) return status; status = IDSNotEmptyRequried(); if (!status.ok()) return status; status = Snapshots::GetInstance().GetSnapshot(ss, prev_ss_->GetCollectionId(), ids_.back()); return status; } Status Operations::ApplyToStore(Store& store) { if (GetType() == OperationsType::W_Compound) { std::cout << ToString() << std::endl; } if (done_) { Done(); return status_; } auto status = OnExecute(store); SetStatus(status); Done(); return status_; } Status Operations::OnExecute(Store& store) { auto status = PreExecute(store); if (!status.ok()) { return status; } status = DoExecute(store); if (!status.ok()) { return status; } return PostExecute(store); } Status Operations::PreExecute(Store& store) { return Status::OK(); } Status Operations::DoExecute(Store& store) { return Status::OK(); } Status Operations::PostExecute(Store& store) { return store.DoCommitOperation(*this); } Status Operations::RollBack() { // TODO: Implement here // Spwarn a rollback operation or re-use this operation return Status::OK(); } Status Operations::ApplyRollBack(Store& store) { // TODO: Implement rollback to remove all resources in steps_ return Status::OK(); } Operations::~Operations() { // TODO: Prefer to submit a rollback operation if status is not ok } } // namespace snapshot } // namespace engine } // namespace milvus
24.139442
113
0.653738
zhang19941219
c1920641d9f469968a5478ece13f1c1ddcd4f8c0
2,415
cpp
C++
src/heap.cpp
tenglvjun/Algorithm
463873ae0dbbbf774ad427e98bf0c71147b1fb5c
[ "MIT" ]
null
null
null
src/heap.cpp
tenglvjun/Algorithm
463873ae0dbbbf774ad427e98bf0c71147b1fb5c
[ "MIT" ]
null
null
null
src/heap.cpp
tenglvjun/Algorithm
463873ae0dbbbf774ad427e98bf0c71147b1fb5c
[ "MIT" ]
null
null
null
#include "heap.h" #include "macro.h" #include <assert.h> #include <cmath> #include "tools.h" Heap::Heap(bool maxHeapify /* = true */) : ContinueContainer(), m_isMaxHeapify(maxHeapify) { } Heap::Heap(int *data, int len, bool maxHeapify /* = true */) : ContinueContainer(data, len), m_isMaxHeapify(maxHeapify) { Heapify(); } Heap::~Heap() { } void Heap::PushBack(const int v) { ContinueContainer::PushBack(v); TrackUp(m_len - 1); } int Heap::PopFront() { Swap(m_data, 0, (m_len - 1)); int value = ContinueContainer::Erase(m_len - 1); TrackDown(0); return value; } void Heap::Sort() { int len = m_len; int *buf = new int[len]; int idx = 0; while (m_len > 0) { buf[idx++] = PopFront(); } Resize(buf, len); } void Heap::Heapify() { int height = (int)log2(m_len); for (int i = height - 1; i >= 0; i--) { for (int j = pow(2, i); j < pow(2, i + 1); j++) { TrackDown(j - 1); } } } void Heap::TrackDown(const int node) { int left = node * 2 + 1; int right = node * 2 + 2; if (left >= m_len) { return; } int sid; int value; if (m_isMaxHeapify) { value = m_data[node] < m_data[left] ? m_data[left] : m_data[node]; if (right < m_len) { value = value < m_data[right] ? m_data[right] : value; } } else { value = m_data[node] > m_data[left] ? m_data[left] : m_data[node]; if (right < m_len) { value = value > m_data[right] ? m_data[right] : value; } } if (value == m_data[node]) { return; } if (value == m_data[left]) { Swap(m_data, node, left); TrackDown(left); } if ((right < m_len) && (value == m_data[right])) { Swap(m_data, node, right); TrackDown(right); } } void Heap::TrackUp(const int node) { if (0 == node) { return; } int parent = (node - 1) / 2; if (m_isMaxHeapify) { if (m_data[parent] < m_data[node]) { Swap(m_data, parent, node); TrackDown(parent); TrackUp(parent); } } else { if (m_data[parent] > m_data[node]) { Swap(m_data, parent, node); TrackDown(parent); TrackUp(parent); } } }
17.888889
74
0.496066
tenglvjun
c192da0b8712aa41516af77289357418d3410ac2
944
cc
C++
below2.1/whatdoesthefoxsay.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/whatdoesthefoxsay.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
below2.1/whatdoesthefoxsay.cc
danzel-py/Kattis-Problem-Archive
bce1929d654b1bceb104f96d68c74349273dd1ff
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <regex> #include <sstream> #include <map> using namespace std; int main() { int n; cin >> n; cin.ignore(11000, '\n'); string str, strdict, animal, goes, sound; regex e("[A-Za-z]+"); for (int i = 0; i < n; i++) { map<string, int> maptoanimal; getline(cin, str); while (true) { getline(cin, strdict); if (strdict == "what does the fox say?") { break; } stringstream ss(strdict); ss >> animal >> goes >> sound; maptoanimal[sound] = 1; } for (sregex_iterator i = sregex_iterator(str.begin(), str.end(), e); i != sregex_iterator(); ++i) { smatch m = *i; string a = m.str(); if(maptoanimal[a]==0){ cout<<a<<' '; } } cout<<'\n'; } return 0; }
21.953488
105
0.439619
danzel-py
c1a2643ada253d12752ac95c546898830176b297
9,925
cpp
C++
test/when_all_tests.cpp
toomuchsalt/cppcoro
552e67e7381166747fe8ec5dc3f71637daf765b8
[ "MIT" ]
13
2020-09-30T17:03:18.000Z
2022-02-21T11:42:12.000Z
test/when_all_tests.cpp
arthurzam/cppcoro
a736b873c599175f551b7bbdedc8365eacdd1334
[ "MIT" ]
null
null
null
test/when_all_tests.cpp
arthurzam/cppcoro
a736b873c599175f551b7bbdedc8365eacdd1334
[ "MIT" ]
5
2020-10-10T14:22:58.000Z
2021-02-10T01:58:40.000Z
/////////////////////////////////////////////////////////////////////////////// // Copyright (c) Lewis Baker // Licenced under MIT license. See LICENSE.txt for details. /////////////////////////////////////////////////////////////////////////////// #include <cppcoro/when_all.hpp> #include <cppcoro/config.hpp> #include <cppcoro/async_manual_reset_event.hpp> #include <cppcoro/async_mutex.hpp> #include <cppcoro/fmap.hpp> #include <cppcoro/shared_task.hpp> #include <cppcoro/sync_wait.hpp> #include <cppcoro/task.hpp> #include "counted.hpp" #include <functional> #include <string> #include <vector> #include <ostream> #include "doctest/cppcoro_doctest.h" TEST_SUITE_BEGIN("when_all"); namespace { template<template<typename T> class TASK, typename T> TASK<T> when_event_set_return(cppcoro::async_manual_reset_event& event, T value) { co_await event; co_return std::move(value); } } TEST_CASE("when_all() with no args completes immediately") { [[maybe_unused]] std::tuple<> result = cppcoro::sync_wait(cppcoro::when_all()); } TEST_CASE("when_all() with one arg") { bool started = false; bool finished = false; auto f = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<std::string> { started = true; co_await event; finished = true; co_return "foo"; }; cppcoro::async_manual_reset_event event; auto whenAllTask = cppcoro::when_all(f(event)); CHECK(!started); cppcoro::sync_wait(cppcoro::when_all_ready( [&]() -> cppcoro::task<> { auto[s] = co_await whenAllTask; CHECK(s == "foo"); }(), [&]() -> cppcoro::task<> { CHECK(started); CHECK(!finished); event.set(); CHECK(finished); co_return; }())); } TEST_CASE("when_all() with awaitables") { cppcoro::sync_wait([]() -> cppcoro::task<> { auto makeTask = [](int x) -> cppcoro::task<int> { co_return x; }; cppcoro::async_manual_reset_event event; event.set(); cppcoro::async_mutex mutex; auto[eventResult, mutexLock, number] = co_await cppcoro::when_all( std::ref(event), mutex.scoped_lock_async(), makeTask(123) | cppcoro::fmap([](int x) { return x + 1; })); (void)eventResult; (void)mutexLock; CHECK(number == 124); CHECK(!mutex.try_lock()); }()); } TEST_CASE("when_all() with all task types") { counted::reset_counts(); auto run = [](cppcoro::async_manual_reset_event& event) -> cppcoro::task<> { using namespace std::string_literals; auto[a, b] = co_await cppcoro::when_all( when_event_set_return<cppcoro::task>(event, "foo"s), when_event_set_return<cppcoro::shared_task>(event, counted{})); CHECK(a == "foo"); CHECK(b.id == 0); // GCC 10.1 fails this check: at this point there are 3 objects alive // * One will be destructed later // * One object is completely leaked #if CPPCORO_COMPILER_GCC && CPPCORO_COMPILER_GCC <= 10'02'00 WARN("GCC <= 10.02 is known to produce memory leaks !!!"); #else CHECK(counted::active_count() == 1); #endif }; cppcoro::async_manual_reset_event event; cppcoro::sync_wait(cppcoro::when_all_ready( run(event), [&]() -> cppcoro::task<> { event.set(); co_return; }())); } TEST_CASE("when_all() throws if any task throws") { struct X {}; struct Y {}; int startedCount = 0; auto makeTask = [&](int value) -> cppcoro::task<int> { ++startedCount; if (value == 0) throw X{}; else if (value == 1) throw Y{}; else co_return value; }; cppcoro::sync_wait([&]() -> cppcoro::task<> { try { // This could either throw X or Y exception. // The exact exception that is thrown is not defined if multiple tasks throw an exception. // TODO: Consider throwing some kind of aggregate_exception that collects all of the exceptions together. (void)co_await cppcoro::when_all(makeTask(0), makeTask(1), makeTask(2)); } catch (const X&) { } catch (const Y&) { } }()); } TEST_CASE("when_all() with task<void>") { int voidTaskCount = 0; auto makeVoidTask = [&]() -> cppcoro::task<> { ++voidTaskCount; co_return; }; auto makeIntTask = [](int x) -> cppcoro::task<int> { co_return x; }; // Single void task in when_all() auto[x] = cppcoro::sync_wait(cppcoro::when_all(makeVoidTask())); (void)x; CHECK(voidTaskCount == 1); // Multiple void tasks in when_all() auto[a, b] = cppcoro::sync_wait(cppcoro::when_all( makeVoidTask(), makeVoidTask())); (void)a; (void)b; CHECK(voidTaskCount == 3); // Mixing void and non-void tasks in when_all() auto[v1, i, v2] = cppcoro::sync_wait(cppcoro::when_all( makeVoidTask(), makeIntTask(123), makeVoidTask())); (void)v1; (void)v2; CHECK(voidTaskCount == 5); CHECK(i == 123); } TEST_CASE("when_all() with vector<task<>>") { int startedCount = 0; auto makeTask = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::task<> { ++startedCount; co_await event; }; cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; bool finished = false; auto run = [&]() -> cppcoro::task<> { std::vector<cppcoro::task<>> tasks; tasks.push_back(makeTask(event1)); tasks.push_back(makeTask(event2)); tasks.push_back(makeTask(event1)); auto allTask = cppcoro::when_all(std::move(tasks)); CHECK(startedCount == 0); co_await allTask; finished = true; }; cppcoro::sync_wait(cppcoro::when_all_ready( run(), [&]() -> cppcoro::task<> { CHECK(startedCount == 3); CHECK(!finished); event1.set(); CHECK(!finished); event2.set(); CHECK(finished); co_return; }())); } TEST_CASE("when_all() with vector<shared_task<>>") { int startedCount = 0; auto makeTask = [&](cppcoro::async_manual_reset_event& event) -> cppcoro::shared_task<> { ++startedCount; co_await event; }; cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; bool finished = false; auto run = [&]() -> cppcoro::task<> { std::vector<cppcoro::shared_task<>> tasks; tasks.push_back(makeTask(event1)); tasks.push_back(makeTask(event2)); tasks.push_back(makeTask(event1)); auto allTask = cppcoro::when_all(std::move(tasks)); CHECK(startedCount == 0); co_await allTask; finished = true; }; cppcoro::sync_wait(cppcoro::when_all_ready( run(), [&]() -> cppcoro::task<> { CHECK(startedCount == 3); CHECK(!finished); event1.set(); CHECK(!finished); event2.set(); CHECK(finished); co_return; }())); } namespace { template<template<typename T> class TASK> void check_when_all_vector_of_task_value() { cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; bool whenAllCompleted = false; cppcoro::sync_wait(cppcoro::when_all_ready( [&]() -> cppcoro::task<> { std::vector<TASK<int>> tasks; tasks.emplace_back(when_event_set_return<TASK>(event1, 1)); tasks.emplace_back(when_event_set_return<TASK>(event2, 2)); auto whenAllTask = cppcoro::when_all(std::move(tasks)); auto values = co_await whenAllTask; REQUIRE(values.size() == 2); CHECK(values[0] == 1); CHECK(values[1] == 2); whenAllCompleted = true; }(), [&]() -> cppcoro::task<> { CHECK(!whenAllCompleted); event2.set(); CHECK(!whenAllCompleted); event1.set(); CHECK(whenAllCompleted); co_return; }())); } } #if defined(CPPCORO_RELEASE_OPTIMISED) constexpr bool isOptimised = true; #else constexpr bool isOptimised = false; #endif // Disable test on MSVC x86 optimised due to bad codegen bug in // `co_await whenAllTask` expression under MSVC 15.7 (Preview 2) and earlier. TEST_CASE("when_all() with vector<task<T>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191426316 && CPPCORO_CPU_X86 && isOptimised)) { check_when_all_vector_of_task_value<cppcoro::task>(); } // Disable test on MSVC x64 optimised due to bad codegen bug in // 'co_await whenAllTask' expression. // Issue reported to MS on 19/11/2017. TEST_CASE("when_all() with vector<shared_task<T>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 && isOptimised && CPPCORO_CPU_X64)) { check_when_all_vector_of_task_value<cppcoro::shared_task>(); } namespace { template<template<typename T> class TASK> void check_when_all_vector_of_task_reference() { cppcoro::async_manual_reset_event event1; cppcoro::async_manual_reset_event event2; int value1 = 1; int value2 = 2; auto makeTask = [](cppcoro::async_manual_reset_event& event, int& value) -> TASK<int&> { co_await event; co_return value; }; bool whenAllComplete = false; cppcoro::sync_wait(cppcoro::when_all_ready( [&]() -> cppcoro::task<> { std::vector<TASK<int&>> tasks; tasks.emplace_back(makeTask(event1, value1)); tasks.emplace_back(makeTask(event2, value2)); auto whenAllTask = cppcoro::when_all(std::move(tasks)); std::vector<std::reference_wrapper<int>> values = co_await whenAllTask; REQUIRE(values.size() == 2); CHECK(&values[0].get() == &value1); CHECK(&values[1].get() == &value2); whenAllComplete = true; }(), [&]() -> cppcoro::task<> { CHECK(!whenAllComplete); event2.set(); CHECK(!whenAllComplete); event1.set(); CHECK(whenAllComplete); co_return; }())); } } // Disable test on MSVC x64 optimised due to bad codegen bug in // 'co_await whenAllTask' expression. // Issue reported to MS on 19/11/2017. TEST_CASE("when_all() with vector<task<T&>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 && isOptimised && CPPCORO_CPU_X64)) { check_when_all_vector_of_task_reference<cppcoro::task>(); } // Disable test on MSVC x64 optimised due to bad codegen bug in // 'co_await whenAllTask' expression. // Issue reported to MS on 19/11/2017. TEST_CASE("when_all() with vector<shared_task<T&>>" * doctest::skip(CPPCORO_COMPILER_MSVC && CPPCORO_COMPILER_MSVC <= 191225805 && isOptimised && CPPCORO_CPU_X64)) { check_when_all_vector_of_task_reference<cppcoro::shared_task>(); } TEST_SUITE_END();
22.816092
111
0.672443
toomuchsalt
c1a3732f8f88d6bcca1283515024ce50f6da54b6
305
cpp
C++
allMatuCommit/根据公式输出圆周率(C++)_202021080718_20210920095442.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/根据公式输出圆周率(C++)_202021080718_20210920095442.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
allMatuCommit/根据公式输出圆周率(C++)_202021080718_20210920095442.cpp
BachWV/matu
d4e3a89385f0a205431dd34c2c7214af40bb8ddb
[ "MIT" ]
null
null
null
#include<iostream> #include<math.h> using namespace std; int main() { double i=0, a=1,sign=1; double sum=0; while (fabs(a) >= 1e-8) { sum = sum + (sign *a); i++; a = 1/(2 * i + 1); sign = -sign; } cout << "steps=" << i<<" " << "PI=" << sum*4.0; }
19.0625
49
0.429508
BachWV
c1a72bedb047741b20802031c3673c820b213dfb
4,378
cpp
C++
src/dataaccess/datalayer/cache/cachebase.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/dataaccess/datalayer/cache/cachebase.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/dataaccess/datalayer/cache/cachebase.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "cachebase.h" #include "db/connpool.h" #include "db/statement.h" #include "db/connection.h" int CacheBase::GetNagtiveCount() { return 100; } void CacheBase::Nagtive(IStatement *stmt) { m_nagtive_lock.Lock(); if( (int)m_nagtive_list.size() <= (GetNagtiveCount() / 2) ) { NagtiveHelper(stmt); } m_nagtive_lock.Unlock(); } void CacheBase::Unnagtive(IStatement *stmt) { m_nagtive_lock.Lock(); for(NagtiveList::const_iterator iter = m_nagtive_list.begin() ; iter != m_nagtive_list.end() ; ++iter) { m_dbcommand->Remove(stmt, *iter, false); } m_nagtive_list.clear(); m_nagtive_lock.Unlock(); } long long CacheBase::GetNagtive() { m_nagtive_lock.Lock(); bool ret = true; if(m_nagtive_list.empty()) { IConnection *conn = ConnPool::Instance()->GetConn(); if (conn == 0) { return 0; } IStatement *stmt_tmp = conn->createStatement(); conn->begin(false); ret = NagtiveHelper(stmt_tmp); conn->commit(); delete stmt_tmp; ConnPool::Instance()->PutConn(conn); } long long nagtive_id = 0; if (ret) { nagtive_id = *m_nagtive_list.begin(); m_nagtive_list.pop_front(); } m_nagtive_lock.Unlock(); return nagtive_id; } bool CacheBase::NagtiveHelper(IStatement *stmt) { DataAdapter t = m_table->GetPrototype(); t.Malloc(); for (int i = 0; i < (int)t.m_data_area.size(); ++i) { if (m_table->m_mata_data[i].type == DATYPE_STRING) { t.m_data_area[i].length = t.m_data_area[i].length > 1 ? 1 : t.m_data_area[i].length; } } bool ret = true; while((int)m_nagtive_list.size() < GetNagtiveCount()) { if (m_dbcommand->Save(stmt, &t, false) != DBCommand::RESULT_SUC) { ret = false; break; } m_nagtive_list.push_back(t.m_data_area[m_table->m_key_id_index].vint64); } t.Free(); return ret; } void CacheBase::Flush(IStatement *stmt) { MEM_NODE_MAP flushMap; { m_lock.Lock(); if(m_flush_map.size() == 0) { m_lock.Unlock(); return; } m_flush_map.swap(flushMap); m_lock.Unlock(); } for(MEM_NODE_MAP::iterator iter = flushMap.begin(); iter != flushMap.end(); ++iter) { switch(iter->second->GetUpdateMode()) { case ECachedUpdateModelUpdate: { m_dbcommand->Update(stmt, *iter->second->GetNode(), false); } break; case ECachedUpdateModelDelete: { DataAdapter *node = iter->second->GetNode(); m_dbcommand->Remove(stmt, node->m_data_area[m_table->m_key_id_index].vint64, false); } break; } iter->second->GetNode()->Free(); delete iter->second; } } void CacheBase::Commit(ITransaction* transation) { m_lock.Lock(); TRANSACTION_MAP::iterator iter = m_transaction_nodes.find(transation); if(m_transaction_nodes.end() == iter) { m_lock.Unlock(); return; } for(MEM_NODE_MAP::const_iterator iter1 = iter->second.begin(); iter1 != iter->second.end(); ++iter1) { MEM_NODE_MAP::iterator iter2 = m_flush_map.find(iter1->first); if(iter1->second->GetUpdateMode() & ECachedUpdateModelDelete) { iter1->second->SetUpdateMode(ECachedUpdateModelDelete); } else if(iter1->second->GetUpdateMode() & ECachedUpdateModelAdd) { iter1->second->SetUpdateMode(ECachedUpdateModelUpdate); } else if(iter1->second->GetUpdateMode() & ECachedUpdateModelUpdate) { iter1->second->SetUpdateMode(ECachedUpdateModelUpdate); } if(iter2 == m_flush_map.end()) { m_flush_map[iter1->first] = iter1->second; } else { iter2->second->GetNode()->Free(); delete iter2->second; iter2->second = iter1->second; } } m_transaction_nodes.erase(iter); m_lock.Unlock(); } void CacheBase::Rollback(ITransaction* transation) { m_lock.Lock(); TRANSACTION_MAP::iterator iter = m_transaction_nodes.find(transation); if(m_transaction_nodes.end() == iter) { m_lock.Unlock(); return; } for(MEM_NODE_MAP::const_iterator iter1 = iter->second.begin(); iter1 != iter->second.end(); ++iter1) { if(iter1->second->GetUpdateMode() & ECachedUpdateModelAdd) { iter1->second->SetUpdateMode(ECachedUpdateModelDelete); MEM_NODE_MAP::iterator iter2 = m_flush_map.find(iter1->first); if(iter2 == m_flush_map.end()) { m_flush_map[iter1->first] = iter1->second; } else { iter2->second->GetNode()->Free(); delete iter2->second; iter2->second = iter1->second; } } else { iter1->second->GetNode()->Free(); delete iter1->second; } } m_transaction_nodes.erase(iter); m_lock.Unlock(); }
21.89
103
0.679534
mage-game
c1aa805b870beded8db42ced40c0281d05694d63
2,760
cpp
C++
KCPlugins/Housing/mealcalendar.cpp
louvainlinux/KapCompta
8d871a718f945748dbed9207222bfd1efb6d5526
[ "MIT" ]
1
2015-08-26T14:17:26.000Z
2015-08-26T14:17:26.000Z
KCPlugins/Housing/mealcalendar.cpp
louvainlinux/KapCompta
8d871a718f945748dbed9207222bfd1efb6d5526
[ "MIT" ]
null
null
null
KCPlugins/Housing/mealcalendar.cpp
louvainlinux/KapCompta
8d871a718f945748dbed9207222bfd1efb6d5526
[ "MIT" ]
null
null
null
/* * Copyright (c) 2012-2013, Olivier Tilmans * * 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 "mealcalendar.h" #include <QPainter> #include <QRect> MealCalendar::MealCalendar(QWidget *parent) : QCalendarWidget(parent) { } void MealCalendar::setCurrentMonthHighlights(const QHash<int,int>& highlights) { this->highlights = QHash<int,int>(highlights); update(); } void MealCalendar::setHighlightsForDay(int day, int highlights) { this->highlights[day] = highlights; updateCell(QDate(QCalendarWidget::yearShown(), QCalendarWidget::monthShown(), day)); } void MealCalendar::paintCell(QPainter *painter, const QRect &rect, const QDate &date) const { QCalendarWidget::paintCell(painter, rect, date); if (highlights.value(date.day()) > 0 && date.month() == QCalendarWidget::selectedDate().month()) { painter->save(); // Set background color to green because there are meal(s) that day QFontMetrics fm = painter->fontMetrics(); int w = fm.width(QString::number(highlights.value(date.day()))); int h = fm.height(); int max = qMax(w, h) + 3; QRect r = QRect(rect.x(), rect.y(), max, max); painter->setBrush(QBrush(Qt::darkCyan, Qt::SolidPattern)); painter->setPen(Qt::NoPen); painter->drawEllipse(r); painter->setBrush(Qt::NoBrush); painter->setPen(Qt::lightGray); painter->drawRect(QRect(rect.x(), rect.y(), rect.width()-1, rect.height()-1)); painter->restore(); painter->drawText(QRect(r.x(), r.y() + max/2 - h/2, max, max), QString::number(highlights.value(date.day())), QTextOption(Qt::AlignCenter)); } }
40.588235
99
0.681884
louvainlinux
c1aad387194468dec80a0d3d8197823493e1dfa5
10,592
cpp
C++
SIGMA/contig_reader.cpp
lorenzgerber/OPERA-MS
bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f
[ "MIT" ]
81
2018-03-22T15:01:08.000Z
2022-01-17T17:52:31.000Z
SIGMA/contig_reader.cpp
lorenzgerber/OPERA-MS
bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f
[ "MIT" ]
68
2017-09-14T08:17:53.000Z
2022-03-09T18:56:12.000Z
SIGMA/contig_reader.cpp
lorenzgerber/OPERA-MS
bd1fb94f73a1bb7cefe3d9ad438bc3c53c069f9f
[ "MIT" ]
21
2017-09-14T06:15:18.000Z
2021-09-30T03:19:22.000Z
#include <cstdlib> #include <cstdio> #include <iostream> #include <fstream> #include <string.h> #include "contig_reader.h" #include "sigma.h" ContigReader::~ContigReader() {} AllReader::AllReader(){} long int AllReader::read(const char* contigs_file, ContigMap* contigs) { int length = 0; long int assembly_size = 0; std::string id; std::ifstream contigs_fp(contigs_file); if (contigs_fp.is_open()) { while(true){ std::string line; if(!std::getline(contigs_fp, line)){ if (length !=0 && length >= Sigma::contig_len_thr){ contigs -> insert(std::make_pair(id, new Contig(id, length))); // std::cerr << length << "\n"; // std::cerr << id <<"\n"; } assembly_size += length; break; } if(line[0] != '>'){ length += (int) line.size(); } else{ assembly_size += length; if (length != 0 && length >= Sigma::contig_len_thr){ contigs -> insert(std::make_pair(id, new Contig(id, length))); // std::cerr << id << "\n"; // std::cerr << length << "\n"; } id = line.substr(1, line.find(' ') - 1); length = 0; } } contigs_fp.close(); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void AllReader::get_assembly_size(const char* contigs_file){ int length = 0; long int assembly_size = 0; long int assembly_nb_contig = 0; std::ifstream contigs_fp(contigs_file); if (contigs_fp.is_open()) { std::string line; while(true){ std::string line; if(!std::getline(contigs_fp, line)){ assembly_size+= length; break; } if(line[0] != '>'){ length += (int) line.size(); } else{ assembly_size += length; assembly_nb_contig++; length = 0; } } contigs_fp.close(); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fprintf(assembly_size_file, "%ld\n", assembly_nb_contig); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; } SOAPdenovoReader::SOAPdenovoReader() {} long int SOAPdenovoReader::read(const char* contigs_file, ContigMap* contigs) { char id[256]; int length; long int assembly_size = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] length [LENGTH] cvg_[COVERAGE]_tip_[TIP]\n if (fscanf(contigs_fp, ">%s %*s %d %*s\n", id, &length) == 2) { assembly_size += length; if (length >= Sigma::contig_len_thr) { contigs->insert(std::make_pair(id, new Contig(id, length))); } } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void SOAPdenovoReader::get_assembly_size(const char* contigs_file) { int length; long int assembly_size = 0; long int assembly_nb_contig = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] length [LENGTH] cvg_[COVERAGE]_tip_[TIP]\n if (fscanf(contigs_fp, ">%*s %*s %d %*s\n", &length) == 1) { assembly_size += length; assembly_nb_contig++; } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fprintf(assembly_size_file, "%ld\n", assembly_nb_contig); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; //return assembly_size; } RAYReader::RAYReader() {} long int RAYReader::read(const char* contigs_file, ContigMap* contigs) { char id[256]; int length; long int assembly_size = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] [LENGTH] nucleotides\n if (fscanf(contigs_fp, ">%s %d %*s\n", id, &length) == 2) { assembly_size += length; if (length >= Sigma::contig_len_thr) { contigs->insert(std::make_pair(id, new Contig(id, length))); } } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void RAYReader::get_assembly_size(const char* contigs_file) { int length; long int assembly_size = 0; long int assembly_nb_contig = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >[ID] [LENGTH] nucleotides\n if (fscanf(contigs_fp, ">%*s %d %*s\n", &length) == 1) { assembly_size += length; assembly_nb_contig++; } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fprintf(assembly_size_file, "%ld\n", assembly_nb_contig); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; //return assembly_size; } VelvetReader::VelvetReader() {} long int VelvetReader::read(const char* contigs_file, ContigMap* contigs) { char id[256]; int length; long int assembly_size = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >NODE_[ID]_length_[LENGTH]_cov_[COVERAGE]\n if (fscanf(contigs_fp, ">%s\n", id) == 1 && sscanf(id, "%*[^_]_%*[^_]_%*[^_]_%d_%*s", &length) == 1) { assembly_size += length; if (length >= Sigma::contig_len_thr) { contigs->insert(std::make_pair(id, new Contig(id, length))); } } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } return assembly_size; } void VelvetReader::get_assembly_size(const char* contigs_file) { char id[256]; int length; long int assembly_size = 0; long int assembly_nb_contig = 0; FILE* contigs_fp = fopen(contigs_file, "r"); if (contigs_fp != NULL) { while (!feof(contigs_fp)) { // >NODE_[ID]_length_[LENGTH]_cov_[COVERAGE]\n if (fscanf(contigs_fp, ">%s\n", id) == 1 && sscanf(id, "%*[^_]_%*[^_]_%*[^_]_%d_%*s", &length) == 1) { assembly_size += length; assembly_nb_contig++; } else { if( fscanf(contigs_fp, "%*[^\n]\n") ); } } fclose(contigs_fp); } else { fprintf(stderr, "Error opening file: %s\n", contigs_file); exit(EXIT_FAILURE); } std::string assembly_size_name = Sigma::output_dir + "/assembly_size.dat"; FILE* assembly_size_file = fopen(assembly_size_name.c_str(), "w"); if (assembly_size_file != NULL) { fprintf(assembly_size_file, "%ld\n", assembly_size); fclose(assembly_size_file); } Sigma::total_assembly_size = assembly_size; Sigma::total_assembly_nb_contig = assembly_nb_contig; //return assembly_size; }
29.179063
114
0.54966
lorenzgerber
c1abd739aa9b31b2058152f6914efece0b0c7b3a
496
hpp
C++
libs/fnd/tuple/include/bksge/fnd/tuple/tuple_tail_type.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/fnd/tuple/include/bksge/fnd/tuple/tuple_tail_type.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/fnd/tuple/include/bksge/fnd/tuple/tuple_tail_type.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file tuple_tail_type.hpp * * @brief tuple_tail_type の定義 * * @author myoukaku */ #ifndef BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP #define BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP #include <bksge/fnd/tuple/fwd/tuple_tail_type_fwd.hpp> namespace bksge { /** * @brief 先頭要素を除いたTupleを返す */ template <typename Tuple> struct tuple_tail_type; } // namespace bksge #include <bksge/fnd/tuple/inl/tuple_tail_type_inl.hpp> #endif // BKSGE_FND_TUPLE_TUPLE_TAIL_TYPE_HPP
17.714286
55
0.729839
myoukaku
c1ae3abca0a1e3e56e8736ed3cfaa22d6255e6da
2,829
cpp
C++
Various_Support_Classes/Path.cpp
ValveDigitalHealth/EPlabResearchWorksApp
bfae0b2e5e492bca778e96457738ba316e77b197
[ "MIT" ]
null
null
null
Various_Support_Classes/Path.cpp
ValveDigitalHealth/EPlabResearchWorksApp
bfae0b2e5e492bca778e96457738ba316e77b197
[ "MIT" ]
null
null
null
Various_Support_Classes/Path.cpp
ValveDigitalHealth/EPlabResearchWorksApp
bfae0b2e5e492bca778e96457738ba316e77b197
[ "MIT" ]
null
null
null
//--------------------------------------------------------------------------- /* MIT LICENSE Copyright (c) 2021 Pawel Kuklik 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. */ //--------------------------------------------------------------------------- //--------------------------------------------------------------------------- #pragma hdrstop #include "Path.h" //--------------------------------------------------------------------------- #pragma package(smart_init) //------------------------------------------------------------------------- int Path_Class::save_object_to_stream(ofstream* File) { int Items_Number,Size; int version = 1; File->write((char*)&version, sizeof (int)); File->write((char*)&Type, sizeof (int)); File->write((char*)&x1, sizeof (double)); File->write((char*)&y1, sizeof (double)); File->write((char*)&z1, sizeof (double)); File->write((char*)&x2, sizeof (double)); File->write((char*)&y2, sizeof (double)); File->write((char*)&z2, sizeof (double)); File->write((char*)&Distance, sizeof (double)); File->write((char*)&LAT_Difference, sizeof (double)); return 1; } //------------------------------------------------------------------------- int Path_Class::load_object_from_stream(ifstream* File) { int Items_Number; int version; File->read((char*)&version, sizeof (int)); if( version == 1 ) { File->read((char*)&Type, sizeof (int)); File->read((char*)&x1, sizeof (double)); File->read((char*)&y1, sizeof (double)); File->read((char*)&z1, sizeof (double)); File->read((char*)&x2, sizeof (double)); File->read((char*)&y2, sizeof (double)); File->read((char*)&z2, sizeof (double)); File->read((char*)&Distance, sizeof (double)); File->read((char*)&LAT_Difference, sizeof (double)); } return 1; } //---------------------------------------------------------------------------
32.147727
78
0.583245
ValveDigitalHealth
c1b22530e46186ee57d0950099f4b8ae13f10b8f
271
cpp
C++
CS154/10-8/A.cpp
daxixi/SJTU-online-Judge-solution
8beb0ef4965a574ce6fffeba0aad308d96ac0c87
[ "Apache-2.0" ]
null
null
null
CS154/10-8/A.cpp
daxixi/SJTU-online-Judge-solution
8beb0ef4965a574ce6fffeba0aad308d96ac0c87
[ "Apache-2.0" ]
null
null
null
CS154/10-8/A.cpp
daxixi/SJTU-online-Judge-solution
8beb0ef4965a574ce6fffeba0aad308d96ac0c87
[ "Apache-2.0" ]
null
null
null
#include<iostream> #include<cstdio> using namespace std; int main() { int a,b; cin>>a>>b; cout<<a<<"+"<<b<<"="<<a+b<<endl; cout<<a<<"*"<<b<<"="<<a*b<<endl; cout<<a<<"/"<<b<<"="<<a/b<<endl; cout<<a<<"%"<<b<<"="<<a%b<<endl; return 0; }
19.357143
39
0.431734
daxixi
c1b427281453c0522ce35641f24cf15a64d5460d
6,140
cc
C++
src/HistogramTest.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
1
2016-01-18T12:41:28.000Z
2016-01-18T12:41:28.000Z
src/HistogramTest.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
src/HistogramTest.cc
taschik/ramcloud
6ef2e1cd61111995881d54bda6f9296b4777b928
[ "0BSD" ]
null
null
null
/* Copyright (c) 2012 Stanford University * * 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(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS 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. */ #include "TestUtil.h" #include "Histogram.h" namespace RAMCloud { /** * Unit tests for Histogram. */ class HistogramTest : public ::testing::Test { public: HistogramTest() {} DISALLOW_COPY_AND_ASSIGN(HistogramTest); }; TEST_F(HistogramTest, constructor_regular) { Histogram h(5000, 10); EXPECT_EQ(5000UL, h.numBuckets); EXPECT_EQ(10UL, h.bucketWidth); for (uint32_t i = 0; i < h.numBuckets; i++) EXPECT_EQ(0UL, h.buckets[i]); EXPECT_EQ(0UL, downCast<uint64_t>(h.sampleSum)); EXPECT_EQ(0UL, h.outliers); EXPECT_EQ(~0UL, h.min); EXPECT_EQ(0UL, h.max); } TEST_F(HistogramTest, constructor_deserializer) { Histogram h1(100, 1); h1.storeSample(8); h1.storeSample(23482); h1.storeSample(27); ProtoBuf::Histogram protoBuf; h1.serialize(protoBuf); Histogram h2(protoBuf); EXPECT_EQ(h1.numBuckets, h2.numBuckets); EXPECT_EQ(h1.bucketWidth, h2.bucketWidth); EXPECT_EQ(downCast<uint64_t>(h1.sampleSum), downCast<uint64_t>(h2.sampleSum)); EXPECT_EQ(h1.outliers, h2.outliers); EXPECT_EQ(h1.max, h2.max); EXPECT_EQ(h1.min, h2.min); EXPECT_EQ(h1.buckets.size(), h2.buckets.size()); for (uint32_t i = 0; i < h1.buckets.size(); i++) EXPECT_EQ(h1.buckets[i], h2.buckets[i]); } TEST_F(HistogramTest, storeSample) { Histogram h(5000, 10); h.storeSample(3); EXPECT_EQ(3UL, h.min); EXPECT_EQ(3UL, h.max); EXPECT_EQ(0UL, h.outliers); EXPECT_EQ(1UL, h.buckets[0]); EXPECT_EQ(0UL, h.buckets[1]); EXPECT_EQ(0UL, h.buckets[2]); h.storeSample(3); h.storeSample(h.numBuckets * h.bucketWidth + 40); h.storeSample(12); h.storeSample(78); EXPECT_EQ(3UL, h.min); EXPECT_EQ(h.numBuckets * h.bucketWidth + 40, h.max); EXPECT_EQ(1UL, h.outliers); EXPECT_EQ(2UL, h.buckets[0]); EXPECT_EQ(1UL, h.buckets[1]); EXPECT_EQ(0UL, h.buckets[2]); EXPECT_EQ(3UL + 3 + 12 + 78 + h.numBuckets * h.bucketWidth + 40, downCast<uint64_t>(h.sampleSum)); } TEST_F(HistogramTest, reset) { Histogram h(100, 1); h.storeSample(23); h.storeSample(23492834); h.reset(); EXPECT_EQ(100UL, h.numBuckets); EXPECT_EQ(1UL, h.bucketWidth); for (uint32_t i = 0; i < h.numBuckets; i++) EXPECT_EQ(0UL, h.buckets[i]); EXPECT_EQ(0UL, downCast<uint64_t>(h.sampleSum)); EXPECT_EQ(0UL, h.outliers); EXPECT_EQ(~0UL, h.min); EXPECT_EQ(0UL, h.max); } TEST_F(HistogramTest, toString) { Histogram h(100, 1); EXPECT_EQ("# Histogram: buckets = 100, bucket width = 1\n" "# 0 samples, 0 outliers, min = 18446744073709551615, max = 0\n" "# median = 0, average = 0\n", h.toString()); h.storeSample(23); h.storeSample(28343); h.storeSample(99); EXPECT_EQ("# Histogram: buckets = 100, bucket width = 1\n" "# 3 samples, 1 outliers, min = 23, max = 28343\n" "# median = 99, average = 9488\n" " 23 1 33.333 33.333\n" " 99 1 33.333 66.667\n", h.toString()); Histogram h2(5, 1); h2.storeSample(3); EXPECT_EQ("# Histogram: buckets = 5, bucket width = 1\n" "# 1 samples, 0 outliers, min = 3, max = 3\n" "# median = 3, average = 3\n" " 0 0 0.000 0.000\n" " 1 0 0.000 0.000\n" " 2 0 0.000 0.000\n" " 3 1 100.000 100.000\n" " 4 0 0.000 100.000\n", h2.toString(0)); } TEST_F(HistogramTest, getOutliers) { Histogram h(1, 1); EXPECT_EQ(0UL, h.getOutliers()); h.storeSample(0); h.storeSample(1); h.storeSample(2); EXPECT_EQ(2UL, h.getOutliers()); uint64_t highestOutlier; h.getOutliers(&highestOutlier); EXPECT_EQ(2UL, highestOutlier); } TEST_F(HistogramTest, getTotalSamples) { Histogram h(1, 1); EXPECT_EQ(0UL, h.getTotalSamples()); h.storeSample(0); h.storeSample(1); h.storeSample(2); EXPECT_EQ(3UL, h.getTotalSamples()); } TEST_F(HistogramTest, getAverage) { // small sum Histogram h(1, 1); EXPECT_EQ(0UL, h.getAverage()); h.storeSample(1); EXPECT_EQ(1UL, h.getAverage()); h.storeSample(20); EXPECT_EQ(10UL, h.getAverage()); // sum that doesn't fit in 64-bits h.storeSample(0xffffffffffffffffUL); h.storeSample(0x0fffffffffffffffUL); EXPECT_EQ(0x4400000000000004UL, h.getAverage()); } TEST_F(HistogramTest, getMedian) { // totalSamples == 0 Histogram noSamples(1, 1); EXPECT_EQ(0UL, noSamples.getMedian()); // numBuckets == 0 Histogram noBuckets(0, 1); noBuckets.storeSample(5); EXPECT_EQ(-1UL, noBuckets.getMedian()); // median falls within outliers Histogram h(2, 1); h.storeSample(10); EXPECT_EQ(-1UL, h.getMedian()); // median falls within buckets h.storeSample(1); h.storeSample(1); EXPECT_EQ(1UL, h.getMedian()); // test a slightly less trivial case Histogram h2(11, 1); for (int i = 0; i <= 10; i++) h2.storeSample(i); EXPECT_EQ(5UL, h2.getMedian()); } TEST_F(HistogramTest, serialize) { // Covered by 'constructor_deserializer'. } } // namespace RAMCloud
29.099526
78
0.617915
taschik
c1b6172a8fe9e87bcf68402ad3cbbbd46eff93ff
5,030
cpp
C++
Source/Tank_To_Target/MyTank.cpp
Mati-C/Tank_To_Target
e506dc0744dff975a3d2f555656adf874b395962
[ "Apache-2.0" ]
null
null
null
Source/Tank_To_Target/MyTank.cpp
Mati-C/Tank_To_Target
e506dc0744dff975a3d2f555656adf874b395962
[ "Apache-2.0" ]
null
null
null
Source/Tank_To_Target/MyTank.cpp
Mati-C/Tank_To_Target
e506dc0744dff975a3d2f555656adf874b395962
[ "Apache-2.0" ]
null
null
null
// Fill out your copyright notice in the Description page of Project Settings. #include "MyTank.h" // Sets default values AMyTank::AMyTank() { // Set this pawn to call Tick() every frame. You can turn this off to improve performance if you don't need it. PrimaryActorTick.bCanEverTick = true; } // Called when the game starts or when spawned void AMyTank::BeginPlay() { Super::BeginPlay(); UGameplayStatics::SetGlobalTimeDilation(GetWorld(), 1); audioComponent = FindComponentByClass<UAudioComponent>(); extraName = GetWorld()->WorldType == EWorldType::PIE ? "UEDPIE_0_" : ""; if (GetWorld()->GetMapName() == extraName + "Level_1") { totalTargets = targetsLV1; timeRemaining = timeLV1; } else { totalTargets = targetsLV2; timeRemaining = timeLV2; } armor = maxArmor; fireTimer = fireDelay; bossBarFill = 1; armorBarFill = 1; isCountingDown = false; } // Called every frame void AMyTank::Tick(float DeltaTime) { Super::Tick(DeltaTime); if (!currentVelocity.IsZero()) { FVector newLocation = GetActorLocation() + (currentVelocity * DeltaTime); SetActorLocation(newLocation); } if (destroyedTargets == totalTargets) Win(); if (GetWorld()->GetMapName() != extraName + "Level_1" || GetWorld()->GetMapName() != extraName + "Level_2") timeRemaining -= DeltaTime; armorBarFill = armor / maxArmor; fireTimer += DeltaTime; powerUpTimer -= DeltaTime; remainingTargets = totalTargets - destroyedTargets; if (powerUpTimer <= 0) { unlimitedFireRate = false; shotgunMode = false; } if (armor <= 0 || timeRemaining <= 0) Lose(); if (timeRemaining <= 5 && !isCountingDown){ audioComponent->Stop(); audioComponent->Sound = countdown; audioComponent->Play(); isCountingDown = true; } } // Called to bind functionality to input void AMyTank::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) { Super::SetupPlayerInputComponent(PlayerInputComponent); PlayerInputComponent->BindAxis("Move X", this, &AMyTank::MoveX); PlayerInputComponent->BindAxis("Move Y", this, &AMyTank::MoveY); PlayerInputComponent->BindAxis("Rotate X", this, &AMyTank::RotateX); PlayerInputComponent->BindAxis("Rotate Y", this, &AMyTank::RotateY); PlayerInputComponent->BindAction("Shoot", IE_Pressed, this, &AMyTank::Shoot); PlayerInputComponent->BindAction("Continue", IE_Pressed, this, &AMyTank::Continue); } void AMyTank::MoveX(float val) { if (won) return; isMovingX = val != 0; if (isMovingY) val *= 0.5f; currentVelocity.X = val * 100 * speed; } void AMyTank::MoveY(float val) { if (won) return; isMovingY = val != 0; if (isMovingX) val *= 0.5f; currentVelocity.Y = -val * 100 * speed; } void AMyTank::RotateX(float val) { if (won) return; FRotator rot = upperBody->RelativeRotation; rot.Yaw += rotationSpeed * val; upperBody->SetRelativeRotation(rot); } void AMyTank::RotateY(float val) { if (won) return; FRotator rot = rotor->RelativeRotation; rot.Roll -= rotationSpeed * val * 0.5f; if (rot.Roll > 15) rot.Roll = 15; else if (rot.Roll < -20) rot.Roll = -20; rotor->SetRelativeRotation(rot); } void AMyTank::Shoot() { if (won) return; if (fireTimer >= fireDelay || unlimitedFireRate) { if (shotgunMode) { for (int i = 0; i <= shotgunPellets; i++) { FRotator rot = PH->GetComponentRotation(); rot.Yaw += FMath::FRandRange(-shotgunSpread, shotgunSpread); rot.Roll += FMath::FRandRange(-shotgunSpread, shotgunSpread); GetWorld()->SpawnActor<AMyBullet>(bullet, PH->GetComponentLocation(), rot, FActorSpawnParameters()); } } else GetWorld()->SpawnActor<AMyBullet>(bullet, PH->GetComponentLocation(), PH->GetComponentRotation(), FActorSpawnParameters()); fireTimer = 0; } } void AMyTank::UnlimitedFireRate() { unlimitedFireRate = true; shotgunMode = false; powerUpTimer = powerUpTime; } void AMyTank::ShotgunMode() { unlimitedFireRate = false; shotgunMode = true; powerUpTimer = powerUpTime; } void AMyTank::Win() { UGameplayStatics::SetGlobalTimeDilation(GetWorld(), 0.0001f); won = true; audioComponent->Stop(); audioComponent->Sound = complete; audioComponent->Play(); if (GetWorld()->GetMapName() == extraName + "Level_3") UGameplayStatics::OpenLevel(GetWorld(), "Complete"); } void AMyTank::Lose() { if (GetWorld()->GetMapName() == extraName + "Level_1") UGameplayStatics::OpenLevel(GetWorld(), "Lose_1"); else if (GetWorld()->GetMapName() == extraName + "Level_2") UGameplayStatics::OpenLevel(GetWorld(), "Lose_2"); else if (GetWorld()->GetMapName() == extraName + "Level_3") UGameplayStatics::OpenLevel(GetWorld(), "Lose_3"); } void AMyTank::Continue() { if (!won) return; if (GetWorld()->GetMapName() == extraName + "Level_1") UGameplayStatics::OpenLevel(GetWorld(), "Victory_1"); else UGameplayStatics::OpenLevel(GetWorld(), "Victory_2"); } void AMyTank::SetGamePaused(bool isPaused) { APlayerController* const MyPlayer = Cast<APlayerController>(GEngine->GetFirstLocalPlayerController(GetWorld())); if (MyPlayer != NULL) MyPlayer->SetPause(isPaused); }
24.778325
130
0.708549
Mati-C
c1b72f6a3c9e99980981f79a102c3a6831b1fd82
417
hpp
C++
src/stan/math/prim/mat/fun/minus.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
1
2019-09-06T15:53:17.000Z
2019-09-06T15:53:17.000Z
src/stan/math/prim/mat/fun/minus.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
8
2019-01-17T18:51:16.000Z
2019-01-17T18:51:39.000Z
src/stan/math/prim/mat/fun/minus.hpp
alashworth/stan-monorepo
75596bc1f860ededd7b3e9ae9002aea97ee1cd46
[ "BSD-3-Clause" ]
null
null
null
#ifndef STAN_MATH_PRIM_MAT_FUN_MINUS_HPP #define STAN_MATH_PRIM_MAT_FUN_MINUS_HPP namespace stan { namespace math { /** * Returns the negation of the specified scalar or matrix. * * @tparam T Type of subtrahend. * @param x Subtrahend. * @return Negation of subtrahend. */ template <typename T> inline T minus(const T& x) { return -x; } } // namespace math } // namespace stan #endif
18.954545
59
0.688249
alashworth
c1ba4af221b5c9c241bd425ab1916236f7fb8228
1,617
cc
C++
lib/Differentiator.cc
wcrvt/zARCS
113dbad3c50aa55f1d8706763f026659799c8ff1
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
null
null
null
lib/Differentiator.cc
wcrvt/zARCS
113dbad3c50aa55f1d8706763f026659799c8ff1
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
null
null
null
lib/Differentiator.cc
wcrvt/zARCS
113dbad3c50aa55f1d8706763f026659799c8ff1
[ "BSD-2-Clause", "BSD-2-Clause-FreeBSD" ]
null
null
null
// 擬似微分器クラス // 2011/02/10 Yuki YOKOKURA // // 擬似微分器 G(s)=(s*gpd)/(s+gpd) (双一次変換) // // Copyright (C) 2011 Yuki YOKOKURA // This program is free software; // you can redistribute it and/or modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 3 of the License, or any later version. // This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; // without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // See the GNU General Public License for more details <http://www.gnu.org/licenses/>. // Besides, you can negotiate about other options of licenses instead of GPL. // If you would like to get other licenses, please contact us<yuki@katsura.sd.keio.ac.jp>. #include "Differentiator.hh" using namespace ARCS; Differentiator::Differentiator(double Bandwidth, double SmplTime) // コンストラクタ Bandwidth;[rad/s] 帯域,SmplTime;[s] 制御周期 : Ts(SmplTime), // [s] 制御周期の格納 gpd(Bandwidth), // [rad/s] 擬似微分の帯域の格納 uZ1(0), yZ1(0) { } Differentiator::~Differentiator(){ // デストラクタ } double Differentiator::GetSignal(double u){ // 出力信号の取得 u;入力信号 double y; y = ( 2.0*gpd*(u-uZ1) + (2.0-Ts*gpd)*yZ1 )/(2.0+Ts*gpd); uZ1=u; yZ1=y; return y; } void Differentiator::SetBandwidth(double Bandwidth){ // 擬似微分の帯域の再設定 Bandwidth;[rad/s] 帯域 gpd=Bandwidth; } void Differentiator::SetSmplTime(double SmplTime){ // 制御周期の再設定 SmplTime;[s] 制御周期 Ts=SmplTime; // [s] 制御周期の再設定 } void Differentiator::ClearStateVars(void){ // すべての状態変数のリセット uZ1=0; // 状態変数1のゼロクリア yZ1=0; // 状態変数2のゼロクリア }
26.080645
103
0.714904
wcrvt
c1bc6a696bf8f877de9dac41d77504f04bc3c10b
6,179
cc
C++
hilti/codegen/instructions/classifier.cc
asilha/hilti
ebfffc7dad31059b43a02eb26abcf7a25f742eb8
[ "BSD-3-Clause" ]
46
2015-01-21T13:31:25.000Z
2020-10-27T10:18:03.000Z
hilti/codegen/instructions/classifier.cc
jjchromik/hilti-104-total
0f9e0cb7114acc157211af24f8254e4b23bd78a5
[ "BSD-3-Clause" ]
29
2015-03-30T08:23:04.000Z
2019-05-03T13:11:35.000Z
hilti/codegen/instructions/classifier.cc
jjchromik/hilti-104-total
0f9e0cb7114acc157211af24f8254e4b23bd78a5
[ "BSD-3-Clause" ]
20
2015-01-27T12:59:38.000Z
2020-10-28T21:40:47.000Z
#include <hilti/hilti-intern.h> #include "../stmt-builder.h" using namespace hilti; using namespace codegen; static void _freeFields(CodeGen* cg, shared_ptr<Type> rtype, llvm::Value* fields, const Location& l) { auto ftypes = ast::type::checkedTrait<type::trait::TypeList>(rtype)->typeList(); auto atype = llvm::ArrayType::get(cg->llvmTypePtr(), ftypes.size()); fields = cg->builder()->CreateBitCast(fields, cg->llvmTypePtr(atype)); for ( int i = 0; i < ftypes.size(); i++ ) { auto addr = cg->llvmGEP(fields, cg->llvmGEPIdx(0), cg->llvmGEPIdx(i)); cg->llvmFree(cg->builder()->CreateLoad(addr), "classifier-free-one-field", l); } cg->llvmFree(fields, "classifier-free-fields", l); } static llvm::Value* _matchAllField(CodeGen* cg) { return cg->llvmClassifierField(cg->llvmConstNull(cg->llvmTypePtr()), cg->llvmConstInt(0, 64)); } static llvm::Value* _llvmFields(CodeGen* cg, shared_ptr<Type> rtype, shared_ptr<Type> stype, llvm::Value* val, const Location& l) { auto ftypes = ast::type::checkedTrait<type::trait::TypeList>(rtype)->typeList(); auto stypes = ast::type::checkedTrait<type::trait::TypeList>(stype)->typeList(); auto atype = llvm::ArrayType::get(cg->llvmTypePtr(), ftypes.size()); auto fields = cg->llvmMalloc(atype, "hlt.classifier", l); // Convert the fields into the internal hlt_classifier_field representation. auto ft = ftypes.begin(); auto st = stypes.begin(); for ( int i = 0; i < ftypes.size(); i++ ) { auto field = cg->llvmStructGet(stype, val, i, [&](CodeGen* cg) -> llvm::Value* { return _matchAllField(cg); }, [&](CodeGen* cg, llvm::Value* v) -> llvm::Value* { return cg->llvmClassifierField(*ft, *st, v, l); }, l); auto addr = cg->llvmGEP(fields, cg->llvmGEPIdx(0), cg->llvmGEPIdx(i)); cg->llvmCreateStore(field, addr); ++ft; ++st; } fields = cg->builder()->CreateBitCast(fields, cg->llvmTypePtr()); return fields; } void StatementBuilder::visit(statement::instruction::classifier::New* i) { auto ctype = ast::rtti::tryCast<type::Classifier>(typedType(i->op1())); auto op1 = builder::integer::create( ast::type::checkedTrait<type::trait::TypeList>(ctype->ruleType())->typeList().size()); auto op2 = builder::type::create(ctype->ruleType()); auto op3 = builder::type::create(ctype->valueType()); CodeGen::expr_list args = {op1, op2, op3}; auto result = cg()->llvmCall("hlt::classifier_new", args); cg()->llvmStore(i, result); } void StatementBuilder::visit(statement::instruction::classifier::Add* i) { auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType(); // op2 can be a tuple (ref<struct>, prio) or a just a rule ref<struct> // // TODO: The separations for the cases below isn't fool-proof but should // be good enough for now. auto ttype = ast::rtti::tryCast<type::Tuple>(i->op2()->type()); if ( ttype ) { auto op2 = cg()->llvmValue(i->op2()); auto rule = cg()->llvmExtractValue(op2, 0); auto reftype = ast::rtti::tryCast<type::Reference>(ttype->typeList().front()); if ( reftype ) { auto stype = reftype->argType(); auto prio = cg()->builder()->CreateZExt(cg()->llvmExtractValue(op2, 1), cg()->llvmTypeInt(64)); auto fields = _llvmFields(cg(), rtype, stype, rule, i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields), builder::codegen::create(builder::integer::type(64), prio), i->op3()}; cg()->llvmCall("hlt::classifier_add", args); return; } } auto rval = i->op2()->coerceTo(builder::reference::type(rtype)); auto rule = cg()->llvmValue(rval); auto reftype = ast::rtti::checkedCast<type::Reference>(rval->type()); auto stype = reftype->argType(); auto fields = _llvmFields(cg(), rtype, stype, rule, i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields), i->op3()}; cg()->llvmCall("hlt::classifier_add_no_prio", args); } void StatementBuilder::visit(statement::instruction::classifier::Compile* i) { CodeGen::expr_list args = {i->op1()}; cg()->llvmCall("hlt::classifier_compile", args); } void StatementBuilder::visit(statement::instruction::classifier::Get* i) { auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType(); auto vtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->valueType(); auto op2 = i->op2()->coerceTo(builder::reference::type(rtype)); auto fields = _llvmFields(cg(), rtype, rtype, cg()->llvmValue(op2), i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields)}; auto voidp = cg()->llvmCall("hlt::classifier_get", args, false, true, [&](CodeGen* cg) { _freeFields(cg, rtype, fields, i->location()); }); auto casted = builder()->CreateBitCast(voidp, cg()->llvmTypePtr(cg()->llvmType(vtype))); auto result = builder()->CreateLoad(casted); cg()->llvmStore(i, result); } void StatementBuilder::visit(statement::instruction::classifier::Matches* i) { auto rtype = ast::rtti::tryCast<type::Classifier>(referencedType(i->op1()))->ruleType(); auto op2 = i->op2()->coerceTo(builder::reference::type(rtype)); auto fields = _llvmFields(cg(), rtype, rtype, cg()->llvmValue(op2), i->location()); CodeGen::expr_list args = {i->op1(), builder::codegen::create(builder::any::type(), fields)}; auto result = cg()->llvmCall("hlt::classifier_matches", args, false, false); _freeFields(cg(), rtype, fields, i->location()); cg()->llvmCheckException(); cg()->llvmStore(i, result); }
39.356688
100
0.603172
asilha
c1be7a57951f38077bfeb5de9a40d7be764888cf
20,287
cpp
C++
src/commlib/zcelib/zce_server_base.cpp
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
72
2015-01-08T05:01:48.000Z
2021-12-28T06:13:03.000Z
src/commlib/zcelib/zce_server_base.cpp
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
4
2016-01-18T12:24:59.000Z
2019-10-12T07:19:15.000Z
src/commlib/zcelib/zce_server_base.cpp
sailzeng/zcelib
88e14ab436f1b40e8071e15ef6d9fae396efc3b4
[ "Apache-2.0" ]
40
2015-01-26T06:49:18.000Z
2021-07-20T08:11:48.000Z
#include "zce_predefine.h" #include "zce_time_value.h" #include "zce_os_adapt_file.h" #include "zce_os_adapt_flock.h" #include "zce_os_adapt_process.h" #include "zce_os_adapt_socket.h" #include "zce_os_adapt_time.h" #include "zce_os_adapt_dirent.h" #include "zce_log_logging.h" #include "zce_server_base.h" /********************************************************************************* class ZCE_Server_Base *********************************************************************************/ ZCE_Server_Base *ZCE_Server_Base::base_instance_ = NULL; // 构造函数,私有,使用单子类的实例, ZCE_Server_Base::ZCE_Server_Base(): pid_handle_(ZCE_INVALID_HANDLE), self_pid_(0), app_run_(true), app_reload_(false), check_leak_times_(0), mem_checkpoint_size_(0), cur_mem_usesize_(0), process_cpu_ratio_(0), system_cpu_ratio_(0), mem_use_ratio_(0) { memset(&last_process_perf_, 0, sizeof(last_process_perf_)); memset(&now_process_perf_, 0, sizeof(now_process_perf_)); memset(&last_system_perf_, 0, sizeof(last_system_perf_)); memset(&now_system_perf_, 0, sizeof(now_system_perf_)); } ZCE_Server_Base::~ZCE_Server_Base() { // 关闭文件 if (pid_handle_ != ZCE_INVALID_HANDLE) { zce::flock_unlock(&pidfile_lock_, SEEK_SET, 0, PID_FILE_LEN); zce::flock_destroy(&pidfile_lock_); zce::close(pid_handle_); } } // 初始化 int ZCE_Server_Base::socket_init() { int ret = 0; ret = zce::socket_init(); if (ret != 0) { return ret; } return 0; } //打印输出PID File int ZCE_Server_Base::out_pid_file(const char *pragramname) { int ret = 0; std::string pidfile_name = pragramname; pidfile_name += ".pid"; self_pid_ = zce::getpid(); //检查PID文件是否存在,, bool must_create_new = false; ret = zce::access(pidfile_name.c_str(), F_OK); if ( 0 != ret) { must_create_new = true; } // 设置文件读取参数,表示其他用户可以读取,open函数会自动帮忙调整参数的。 int fileperms = 0644; pid_handle_ = zce::open(pidfile_name.c_str(), O_RDWR | O_CREAT, static_cast<mode_t>(fileperms)); if (pid_handle_ == ZCE_INVALID_HANDLE) { ZCE_LOG(RS_ERROR, "Open pid file [%s]fail.", pidfile_name.c_str()); return -1; } //如果PID文件不存在,调整文件长度,(说明见下) //这个地方没有原子保护,有一定风险,但…… if (true == must_create_new) { //我是用WINDOWS下的记录锁是模拟和Linux类似,但Windows的文件锁其实没有对将长度参数设置0, //锁定整个文件的功能,所以要先把文件长度调整 zce::ftruncate(pid_handle_, PID_FILE_LEN); } zce::flock_init(&pidfile_lock_, pid_handle_); char tmpbuff[PID_FILE_LEN + 1]; snprintf(tmpbuff, PID_FILE_LEN + 1, "%*.u", (int)PID_FILE_LEN * (-1), self_pid_); // 尝试锁定全部文件,如果锁定不成功,表示有人正在用这个文件 ret = zce::flock_trywrlock(&pidfile_lock_, SEEK_SET, 0, PID_FILE_LEN); if (ret != 0) { ZCE_LOG(RS_ERROR, "Trylock pid file [%s]fail. Last error =%d", pidfile_name.c_str(), zce::last_error()); return ret; } //写入文件内容, 截断文件为BUFFER_LEN, zce::ftruncate(pid_handle_, PID_FILE_LEN); zce::lseek(pid_handle_, 0, SEEK_SET); zce::write(pid_handle_, tmpbuff, PID_FILE_LEN); return 0; } // 监测这个进程的系统状况,每N分钟运行一次就OK了 // 看门狗得到进程的状态 int ZCE_Server_Base::watch_dog_status(bool first_record) { int ret = 0; // 如果不是第一次记录,保存上一次记录的结果 if (!first_record) { last_process_perf_ = now_process_perf_; last_system_perf_ = now_system_perf_; } ret = zce::get_self_perf(&now_process_perf_); if (0 != ret) { return ret; } ret = zce::get_system_perf(&now_system_perf_); if (0 != ret) { return ret; } cur_mem_usesize_ = now_process_perf_.vm_size_; // 记录第一次的内存数据 if (first_record) { mem_checkpoint_size_ = now_process_perf_.vm_size_; return 0; } // 处理内存变化的情况 size_t vary_mem_size = 0; if (now_process_perf_.vm_size_ >= mem_checkpoint_size_) { vary_mem_size = now_process_perf_.vm_size_ - mem_checkpoint_size_; } // 内存居然缩小了…… else { mem_checkpoint_size_ = now_process_perf_.vm_size_; } // 这个告警如何向监控汇报要考虑一下 if (vary_mem_size >= MEMORY_LEAK_THRESHOLD) { ++check_leak_times_; ZCE_LOG(RS_ERROR, "[zcelib] [WATCHDOG][PID:%u] Monitor could memory leak," "mem_checkpoint_size_ =[%u],run_mem_size_=[%u].", self_pid_, mem_checkpoint_size_, now_process_perf_.vm_size_); // 如果已经监测了若干次内存泄漏,则不再记录告警 if (check_leak_times_ > MAX_RECORD_MEMLEAK_NUMBER) { mem_checkpoint_size_ = now_process_perf_.vm_size_; check_leak_times_ = 0; } } // 其实到这个地方了,你可以干的事情很多, // 甚至计算某一段时间内程序的CPU占用率过高(TNNND,后来我真做了) timeval last_to_now = zce::timeval_sub(now_system_perf_.up_time_, last_system_perf_.up_time_); // 得到进程的CPU利用率 timeval proc_utime = zce::timeval_sub(now_process_perf_.run_utime_, last_process_perf_.run_utime_); timeval proc_stime = zce::timeval_sub(now_process_perf_.run_stime_, last_process_perf_.run_stime_); timeval proc_cpu_time = zce::timeval_add(proc_utime, proc_stime); // 如果间隔时间不为0 if (zce::total_milliseconds(last_to_now) > 0) { process_cpu_ratio_ = static_cast<uint32_t>(zce::total_milliseconds(proc_cpu_time) * 1000 / zce::total_milliseconds(last_to_now)); } else { process_cpu_ratio_ = 0; } ZCE_LOG(RS_INFO, "[zcelib] [WATCHDOG][PID:%u] cpu ratio[%u] " "totoal process user/sys[%lld/%lld] milliseconds " "leave last point all/usr/sys[%lld/%lld/%lld] milliseconds " "memory use//add [%ld/%ld].", self_pid_, process_cpu_ratio_, zce::total_milliseconds(now_process_perf_.run_utime_), zce::total_milliseconds(now_process_perf_.run_stime_), zce::total_milliseconds(last_to_now), zce::total_milliseconds(proc_utime), zce::total_milliseconds(proc_stime), cur_mem_usesize_, vary_mem_size); // 计算系统的CPU时间,非IDLE以外的时间都是消耗时间 timeval sys_idletime = zce::timeval_sub(now_system_perf_.idle_time_, last_system_perf_.idle_time_); timeval sys_cputime = zce::timeval_sub(last_to_now, sys_idletime); // 如果间隔时间不为0 if (zce::total_milliseconds(last_to_now) > 0) { system_cpu_ratio_ = static_cast<uint32_t>(zce::total_milliseconds(sys_cputime) * 1000 / zce::total_milliseconds(last_to_now)); } else { ZCE_LOG(RS_ERROR, "system_uptime = %llu, process_start_time = %llu", zce::total_milliseconds(now_system_perf_.up_time_), zce::total_milliseconds(now_process_perf_.start_time_)); system_cpu_ratio_ = 0; } // 系统或进程CPU使用超过阈值时记条账单 if (process_cpu_ratio_ >= PROCESS_CPU_RATIO_THRESHOLD || system_cpu_ratio_ >= SYSTEM_CPU_RATIO_THRESHOLD) { ZCE_LOG(RS_ERROR, "[zcelib] [WATCHDOG][PID:%u] point[%u] vm_size[%u] " "process cpu ratio [%f] threshold [%f], system cpu ratio[%f] threshold[%f] " "totoal process user/sys[%lld/%lld] milliseconds " "leave last point all/usr/sys[%lld/%lld/%lld] milliseconds.", self_pid_, mem_checkpoint_size_, now_process_perf_.vm_size_, double(process_cpu_ratio_) / 10, double(PROCESS_CPU_RATIO_THRESHOLD) / 10, double(system_cpu_ratio_) / 10, double(SYSTEM_CPU_RATIO_THRESHOLD) / 10, zce::total_milliseconds(now_process_perf_.run_utime_), zce::total_milliseconds(now_process_perf_.run_stime_), zce::total_milliseconds(last_to_now), zce::total_milliseconds(proc_utime), zce::total_milliseconds(proc_stime)); } // 内存使用情况的监控 can_use_size_ = now_system_perf_.freeram_size_ + now_system_perf_.cachedram_size_ + now_system_perf_.bufferram_size_; if (now_system_perf_.totalram_size_ > 0) { mem_use_ratio_ = static_cast<uint32_t>((now_system_perf_.totalram_size_ - can_use_size_) * 1000 / now_system_perf_.totalram_size_); } else { mem_use_ratio_ = 0; } ZCE_LOG(RS_INFO, "[zcelib] [WATCHDOG][SYSTEM] cpu radio [%u] " "totoal usr/nice/sys/idle/iowait/hardirq/softirq " "[%lld/%lld/%lld/%lld/%lld/%lld/%lld] milliseconds" "leave last point all/use/idle[%lld/%lld/%lld] milliseconds " "mem ratio[%u] [totoal/can use/free/buffer/cache] " "[%lld/%lld/%lld/%lld/%lld] bytes", system_cpu_ratio_, zce::total_milliseconds(now_system_perf_.user_time_), zce::total_milliseconds(now_system_perf_.nice_time_), zce::total_milliseconds(now_system_perf_.system_time_), zce::total_milliseconds(now_system_perf_.idle_time_), zce::total_milliseconds(now_system_perf_.iowait_time_), zce::total_milliseconds(now_system_perf_.hardirq_time_), zce::total_milliseconds(now_system_perf_.softirq_time_), zce::total_milliseconds(last_to_now), zce::total_milliseconds(sys_cputime), zce::total_milliseconds(sys_idletime), mem_use_ratio_, now_system_perf_.totalram_size_, can_use_size_, now_system_perf_.freeram_size_, now_system_perf_.bufferram_size_, now_system_perf_.cachedram_size_); return 0; } int ZCE_Server_Base::process_signal(void) { //忽视部分信号,这样简单 zce::signal(SIGHUP, SIG_IGN); zce::signal(SIGPIPE, SIG_IGN); zce::signal(SIGCHLD, SIG_IGN); #ifdef ZCE_OS_WINDOWS //Windows下设置退出处理函数,可以用Ctrl + C 退出 SetConsoleCtrlHandler((PHANDLER_ROUTINE)exit_signal, TRUE); #else //这个几个信号被认可为退出信号 zce::signal(SIGINT, exit_signal); zce::signal(SIGQUIT, exit_signal); zce::signal(SIGTERM, exit_signal); //重新加载部分配置,用了SIGUSR1 kill -10 zce::signal(SIGUSR1, reload_cfg_signal); #endif //SIGUSR1,SIGUSR2你可以用来干点自己的活, return 0; } int ZCE_Server_Base::daemon_init() { //Daemon 精灵进程,但是我不清理目录路径, #if defined (ZCE_OS_LINUX) pid_t pid = zce::fork(); if (pid < 0) { return -1; } else if (pid > 0) { ::exit(0); } #endif zce::setsid(); zce::umask(0); #if defined (ZCE_OS_WINDOWS) //设置Console的标题信息 std::string out_str = get_app_basename(); out_str += " "; out_str += app_author_; ::SetConsoleTitle(out_str.c_str()); #endif return 0; } //通过启动参数0,得到app_base_name_,app_run_name_ int ZCE_Server_Base::create_app_name(const char *argv_0) { app_run_name_ = argv_0; // 取得base name char str_base_name[PATH_MAX + 1]; str_base_name[PATH_MAX] = '\0'; zce::basename(argv_0, str_base_name, PATH_MAX); #if defined ZCE_OS_WINDOWS //Windows下要去掉,EXE后缀 const size_t WIN_EXE_SUFFIX_LEN = 4; size_t name_len = strlen(str_base_name); if (name_len <= WIN_EXE_SUFFIX_LEN) { ZCE_LOG(RS_ERROR, "[framework] Exe file name is not expect?Path name[%s].", argv_0); return -1; } //如果有后缀才取消,没有就放鸭子 if (strcasecmp(str_base_name + name_len - WIN_EXE_SUFFIX_LEN, ".EXE") == 0) { str_base_name[name_len - WIN_EXE_SUFFIX_LEN] = '\0'; } #endif //如果是调试版本,去掉后缀符号_d #if defined (DEBUG) || defined (_DEBUG) //如果是调试版本,去掉后缀符号_d const size_t DEBUG_SUFFIX_LEN = 2; size_t debug_name_len = strlen(str_base_name); if (debug_name_len <= DEBUG_SUFFIX_LEN) { ZCE_LOG(RS_ERROR, "[framework] Exe file name is not debug _d suffix?str_base_name[%s].", str_base_name); return -1; } if (0 == strcasecmp(str_base_name + debug_name_len - DEBUG_SUFFIX_LEN, "_D")) { str_base_name[debug_name_len - DEBUG_SUFFIX_LEN] = '\0'; } #endif app_base_name_ = str_base_name; return 0; } //windows下设置服务信息 void ZCE_Server_Base::set_service_info(const char *svc_name, const char *svc_desc) { if (svc_name != NULL) { service_name_ = svc_name; } if (svc_desc != NULL) { service_desc_ = svc_desc; } } //得到运行信息,可能包括路径信息 const char *ZCE_Server_Base::get_app_runname() { return app_run_name_.c_str(); } //得到程序进程名称,,去掉了路径,WINDOWS下去掉了后缀 const char *ZCE_Server_Base::get_app_basename() { return app_base_name_.c_str(); } //设置进程是否运行的标志 void ZCE_Server_Base::set_run_sign(bool app_run) { app_run_ = app_run; } //设置reload标志 void ZCE_Server_Base::set_reload_sign(bool app_reload) { app_reload_ = app_reload; } //信号处理代码, #ifdef ZCE_OS_WINDOWS BOOL ZCE_Server_Base::exit_signal(DWORD) { base_instance_->set_run_sign(false); return TRUE; } #else void ZCE_Server_Base::exit_signal(int) { base_instance_->set_run_sign(false); return; } // USER1信号处理函数 void ZCE_Server_Base::reload_cfg_signal(int) { // 信号处理函数中不能有IO等不可重入的操作,否则容易死锁 base_instance_->set_reload_sign(true); return; } #endif #if defined ZCE_OS_WINDOWS //运行服务 int ZCE_Server_Base::win_services_run() { char service_name[PATH_MAX + 1]; service_name[PATH_MAX] = '\0'; strncpy(service_name, app_base_name_.c_str(), PATH_MAX); SERVICE_TABLE_ENTRY st[] = { { service_name, (LPSERVICE_MAIN_FUNCTION)win_service_main }, { NULL, NULL } }; BOOL b_ret = ::StartServiceCtrlDispatcher(st); if (b_ret) { //LogEvent(_T("Register Service Main Function Success!")); } else { UINT error_info = ::GetLastError(); ZCE_UNUSED_ARG(error_info); //LogEvent(_T("Register Service Main Function Error!")); } return 0; } //安装服务 int ZCE_Server_Base::win_services_install() { if (win_services_isinstalled()) { printf("install service fail. service %s already exist", app_base_name_.c_str()); return 0; } //打开服务控制管理器 SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (handle_scm == NULL) { //::MessageBox(NULL, _T("Couldn't open service manager"), app_base_name_.c_str(), MB_OK); printf("can't open service manager.\n"); return FALSE; } // Get the executable file path char file_path[MAX_PATH + 1]; file_path[MAX_PATH] = '\0'; ::GetModuleFileName(NULL, file_path, MAX_PATH); //创建服务 SC_HANDLE handle_services = ::CreateService( handle_scm, app_base_name_.c_str(), service_name_.c_str(), SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, file_path, NULL, NULL, "", NULL, NULL); if (handle_services == NULL) { printf("install service %s fail. err=%d\n", app_base_name_.c_str(), GetLastError()); ::CloseServiceHandle(handle_scm); //MessageBox(NULL, _T("Couldn't create service"), app_base_name_.c_str(), MB_OK); return -1; } // 修改描述 SC_LOCK lock = LockServiceDatabase(handle_scm); if (lock != NULL) { SERVICE_DESCRIPTION desc; desc.lpDescription = (LPSTR)service_desc_.c_str(); ChangeServiceConfig2(handle_services, SERVICE_CONFIG_DESCRIPTION, &desc); UnlockServiceDatabase(handle_scm); } ::CloseServiceHandle(handle_services); ::CloseServiceHandle(handle_scm); printf("install service %s succ.\n", app_base_name_.c_str()); return 0; } //卸载服务 int ZCE_Server_Base::win_services_uninstall() { if (!win_services_isinstalled()) { printf("uninstall fail. service %s is not exist.\n", app_base_name_.c_str()); return 0; } SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (handle_scm == NULL) { //::MessageBox(NULL, _T("Couldn't open service manager"), app_base_name_.c_str(), MB_OK); printf("uninstall fail. can't open service manager"); return FALSE; } SC_HANDLE handle_services = ::OpenService(handle_scm, app_base_name_.c_str(), SERVICE_STOP | DELETE); if (handle_services == NULL) { ::CloseServiceHandle(handle_scm); //::MessageBox(NULL, _T("Couldn't open service"), app_base_name_.c_str(), MB_OK); printf("can't open service %s\n", app_base_name_.c_str()); return -1; } SERVICE_STATUS status; ::ControlService(handle_services, SERVICE_CONTROL_STOP, &status); //删除服务 BOOL bDelete = ::DeleteService(handle_services); ::CloseServiceHandle(handle_services); ::CloseServiceHandle(handle_scm); if (bDelete) { printf("uninstall service %s succ.\n", app_base_name_.c_str()); return 0; } printf("uninstall service %s fail.\n", app_base_name_.c_str()); //LogEvent(_T("Service could not be deleted")); return -1; } //检查服务是否安装 bool ZCE_Server_Base::win_services_isinstalled() { bool b_result = false; //打开服务控制管理器 SC_HANDLE handle_scm = ::OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS); if (handle_scm != NULL) { //打开服务 SC_HANDLE handle_service = ::OpenService(handle_scm, app_base_name_.c_str(), SERVICE_QUERY_CONFIG); if (handle_service != NULL) { b_result = true; ::CloseServiceHandle(handle_service); } ::CloseServiceHandle(handle_scm); } return b_result; } //服务运行函数 void WINAPI ZCE_Server_Base::win_service_main() { //WIN服务用的状态 static SERVICE_STATUS_HANDLE handle_service_status = NULL; SERVICE_STATUS status; status.dwServiceType = SERVICE_WIN32_OWN_PROCESS; status.dwCurrentState = SERVICE_STOPPED; status.dwControlsAccepted = SERVICE_ACCEPT_STOP; status.dwWin32ExitCode = 0; status.dwServiceSpecificExitCode = 0; status.dwCheckPoint = 0; status.dwWaitHint = 0; // Register the control request handler status.dwCurrentState = SERVICE_START_PENDING; status.dwControlsAccepted = SERVICE_ACCEPT_STOP; //注册服务控制 handle_service_status = ::RegisterServiceCtrlHandler(base_instance_->get_app_basename(), win_services_ctrl); if (handle_service_status == NULL) { //LogEvent(_T("Handler not installed")); return; } SetServiceStatus(handle_service_status, &status); status.dwWin32ExitCode = S_OK; status.dwCheckPoint = 0; status.dwWaitHint = 0; status.dwCurrentState = SERVICE_RUNNING; SetServiceStatus(handle_service_status, &status); //base_instance_->do_run(); status.dwCurrentState = SERVICE_STOPPED; SetServiceStatus(handle_service_status, &status); //LogEvent(_T("Service stopped")); } //服务控制台所需要的控制函数 void WINAPI ZCE_Server_Base::win_services_ctrl(DWORD op_code) { switch (op_code) { case SERVICE_CONTROL_STOP: // base_instance_->app_run_ = false; break; case SERVICE_CONTROL_PAUSE: break; case SERVICE_CONTROL_CONTINUE: break; case SERVICE_CONTROL_INTERROGATE: break; case SERVICE_CONTROL_SHUTDOWN: break; default: //LogEvent(_T("Bad service request")); break; } } #endif //#if defined ZCE_OS_WINDOWS
26.799207
112
0.614285
sailzeng
c1c177ba08b544e018421945e39c3c112afe7c03
544
cpp
C++
Chapter_2/2-7.cpp
MemoryDxx/CPP_Exercises
f789d194a72460fc4c6701c2710e1de53566394d
[ "Apache-2.0" ]
null
null
null
Chapter_2/2-7.cpp
MemoryDxx/CPP_Exercises
f789d194a72460fc4c6701c2710e1de53566394d
[ "Apache-2.0" ]
null
null
null
Chapter_2/2-7.cpp
MemoryDxx/CPP_Exercises
f789d194a72460fc4c6701c2710e1de53566394d
[ "Apache-2.0" ]
null
null
null
// 编写一个程序,要求用户输入小时数和分钟数。在main()函数中,将这两个值传递给一个void函数。 // void函数以下面的格式显示这两个值。 // Enter the number of hours: 9 // Enter the number of minutes: 28 // Time: 9:28 #include <iostream> using namespace std; void show_time(int hour, int minutes); int main() { int hour, minutes; cout << "Enter the number of hours: "; cin >> hour; cout << "Enter the number of minutes: "; cin >> minutes; show_time(hour, minutes); return 0; } void show_time(int hour, int minutes) { cout << "Time: " << hour << ":" << minutes << endl; }
21.76
55
0.637868
MemoryDxx
c1c35e884065eb04f8e68a0df42130d20ab22d46
6,569
cxx
C++
Applications/ShrinkImage/niftkShrinkImage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
13
2018-07-28T13:36:38.000Z
2021-11-01T19:17:39.000Z
Applications/ShrinkImage/niftkShrinkImage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
null
null
null
Applications/ShrinkImage/niftkShrinkImage.cxx
NifTK/NifTK
2358b333c89ff1bba1c232eecbbcdc8003305dfe
[ "BSD-3-Clause" ]
10
2018-08-20T07:06:00.000Z
2021-07-07T07:55:27.000Z
/*============================================================================= NifTK: A software platform for medical image computing. Copyright (c) University College London (UCL). All rights reserved. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See LICENSE.txt in the top level directory for details. =============================================================================*/ #include <niftkLogHelper.h> #include <niftkConversionUtils.h> #include <itkImageFileReader.h> #include <itkImageFileWriter.h> #include <itkNifTKImageIOFactory.h> #include <itkShrinkImageFilter.h> #include <itkCommandLineHelper.h> /*! * \file niftkShrinkImage.cxx * \page niftkShrinkImage * \section niftkShrinkImageSummary Runs the ITK ShrinkImageFilter. */ void Usage(char *exec) { niftk::LogHelper::PrintCommandLineHeader(std::cout); std::cout << " " << std::endl; std::cout << " Runs the ITK ShrinkImageFilter on a 2D or 3D image." << std::endl; std::cout << " " << std::endl; std::cout << " " << exec << " -i inputFileName -o outputFileName [options]" << std::endl; std::cout << " " << std::endl; std::cout << "*** [mandatory] ***" << std::endl << std::endl; std::cout << " -i <filename> Input image " << std::endl; std::cout << " -o <filename> Output image" << std::endl << std::endl; std::cout << "*** [options] ***" << std::endl << std::endl; std::cout << " -f <int> [2] Shrink factor" << std::endl; } struct arguments { std::string inputImage; std::string outputImage; int factor; }; template <int Dimension, class PixelType> int DoMain(arguments args) { typedef typename itk::Image< PixelType, Dimension > InputImageType; typedef typename itk::ImageFileReader< InputImageType > InputImageReaderType; typedef typename itk::ImageFileWriter< InputImageType > OutputImageWriterType; typedef typename itk::ShrinkImageFilter<InputImageType, InputImageType> ShrinkFilterType; typename InputImageReaderType::Pointer imageReader = InputImageReaderType::New(); imageReader->SetFileName(args.inputImage); typename ShrinkFilterType::Pointer filter = ShrinkFilterType::New(); filter->SetInput(imageReader->GetOutput()); for (unsigned int i = 0; i < Dimension; i++) { filter->SetShrinkFactor(i, args.factor); } typename OutputImageWriterType::Pointer imageWriter = OutputImageWriterType::New(); imageWriter->SetFileName(args.outputImage); imageWriter->SetInput(filter->GetOutput()); try { imageWriter->Update(); } catch( itk::ExceptionObject & err ) { std::cerr << "Failed: " << err << std::endl; return EXIT_FAILURE; } return EXIT_SUCCESS; } /** * \brief Takes image and shrinks it by a factor in each dimension. */ int main(int argc, char** argv) { itk::NifTKImageIOFactory::Initialize(); // To pass around command line args struct arguments args; // Define defaults args.factor = 2; // Parse command line args for(int i=1; i < argc; i++){ if(strcmp(argv[i], "-help")==0 || strcmp(argv[i], "-Help")==0 || strcmp(argv[i], "-HELP")==0 || strcmp(argv[i], "-h")==0 || strcmp(argv[i], "--h")==0){ Usage(argv[0]); return -1; } else if(strcmp(argv[i], "-i") == 0){ args.inputImage=argv[++i]; std::cout << "Set -i=" << args.inputImage << std::endl; } else if(strcmp(argv[i], "-o") == 0){ args.outputImage=argv[++i]; std::cout << "Set -o=" << args.outputImage << std::endl; } else if(strcmp(argv[i], "-f") == 0){ args.factor=atoi(argv[++i]); std::cout << "Set -f=" << niftk::ConvertToString(args.factor) << std::endl; } else { std::cerr << argv[0] << ":\tParameter " << argv[i] << " unknown." << std::endl; return -1; } } // Validate command line args if (args.inputImage.length() == 0 || args.outputImage.length() == 0) { Usage(argv[0]); return EXIT_FAILURE; } int dims = itk::PeekAtImageDimension(args.inputImage); if (dims != 2 && dims != 3) { std::cout << "Unsuported image dimension" << std::endl; return EXIT_FAILURE; } int result; switch (itk::PeekAtComponentType(args.inputImage)) { case itk::ImageIOBase::UCHAR: if (dims == 2) { result = DoMain<2, unsigned char>(args); } else { result = DoMain<3, unsigned char>(args); } break; case itk::ImageIOBase::CHAR: if (dims == 2) { result = DoMain<2, char>(args); } else { result = DoMain<3, char>(args); } break; case itk::ImageIOBase::USHORT: if (dims == 2) { result = DoMain<2, unsigned short>(args); } else { result = DoMain<3, unsigned short>(args); } break; case itk::ImageIOBase::SHORT: if (dims == 2) { result = DoMain<2, short>(args); } else { result = DoMain<3, short>(args); } break; case itk::ImageIOBase::UINT: if (dims == 2) { result = DoMain<2, unsigned int>(args); } else { result = DoMain<3, unsigned int>(args); } break; case itk::ImageIOBase::INT: if (dims == 2) { result = DoMain<2, int>(args); } else { result = DoMain<3, int>(args); } break; case itk::ImageIOBase::ULONG: if (dims == 2) { result = DoMain<2, unsigned long>(args); } else { result = DoMain<3, unsigned long>(args); } break; case itk::ImageIOBase::LONG: if (dims == 2) { result = DoMain<2, long>(args); } else { result = DoMain<3, long>(args); } break; case itk::ImageIOBase::FLOAT: if (dims == 2) { result = DoMain<2, float>(args); } else { result = DoMain<3, float>(args); } break; case itk::ImageIOBase::DOUBLE: if (dims == 2) { result = DoMain<2, double>(args); } else { result = DoMain<3, double>(args); } break; default: std::cerr << "non standard pixel format" << std::endl; return EXIT_FAILURE; } return result; }
26.487903
155
0.548942
NifTK
c1c4530a228a487cdcc58517d493942f7c9633b2
8,071
hxx
C++
include/idocp/contact_complementarity/contact_complementarity_component_base.hxx
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
1
2021-09-04T07:43:04.000Z
2021-09-04T07:43:04.000Z
include/idocp/contact_complementarity/contact_complementarity_component_base.hxx
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
null
null
null
include/idocp/contact_complementarity/contact_complementarity_component_base.hxx
KY-Lin22/idocp
8cacfea7bb2184023eb15316aea07154a62d59bb
[ "BSD-3-Clause" ]
null
null
null
#ifndef IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_ #define IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_ #include "idocp/contact_complementarity/contact_complementarity_component_base.hpp" #include "idocp/constraints/pdipm_func.hpp" #include <cmath> #include <exception> #include <assert.h> namespace idocp { template <typename Derived> inline ContactComplementarityComponentBase<Derived>:: ContactComplementarityComponentBase(const double barrier, const double fraction_to_boundary_rate) : barrier_(barrier), fraction_to_boundary_rate_(fraction_to_boundary_rate) { try { if (barrier <= 0) { throw std::out_of_range( "invalid argment: barrirer must be positive"); } if (fraction_to_boundary_rate <= 0) { throw std::out_of_range( "invalid argment: fraction_to_boundary_rate must be positive"); } if (fraction_to_boundary_rate >= 1) { throw std::out_of_range( "invalid argment: fraction_to_boundary_rate must be less than 1"); } } catch(const std::exception& e) { std::cerr << e.what() << '\n'; std::exit(EXIT_FAILURE); } } template <typename Derived> inline ContactComplementarityComponentBase<Derived>:: ContactComplementarityComponentBase() : barrier_(0), fraction_to_boundary_rate_(0) { } template <typename Derived> inline ContactComplementarityComponentBase<Derived>:: ~ContactComplementarityComponentBase() { } template <typename Derived> inline bool ContactComplementarityComponentBase<Derived>::isFeasible( Robot& robot, ConstraintComponentData& data, const SplitSolution& s) const { return static_cast<const Derived*>(this)->isFeasible_impl(robot, data, s); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::setSlackAndDual( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { static_cast<const Derived*>(this)->setSlackAndDual_impl(robot, data, dtau, s); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::augmentDualResidual( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, KKTResidual& kkt_residual) { static_cast<Derived*>(this)->augmentDualResidual_impl(robot, data, dtau, s, kkt_residual); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::condenseSlackAndDual( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, KKTMatrix& kkt_matrix, KKTResidual& kkt_residual) { static_cast<const Derived*>(this)->condenseSlackAndDual_impl(robot, data, dtau, s, kkt_matrix, kkt_residual); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>:: computeSlackAndDualDirection(Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s, const SplitDirection& d) const { static_cast<const Derived*>(this)->computeSlackAndDualDirection_impl( robot, data, dtau, s, d); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::residualL1Nrom( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { return static_cast<const Derived*>(this)->residualL1Nrom_impl( robot, data, dtau, s); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::squaredKKTErrorNorm( Robot& robot, ConstraintComponentData& data, const double dtau, const SplitSolution& s) const { return static_cast<const Derived*>(this)->squaredKKTErrorNorm_impl( robot, data, dtau, s); } template <typename Derived> inline int ContactComplementarityComponentBase<Derived>::dimc() const { return static_cast<const Derived*>(this)->dimc_impl(); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::maxSlackStepSize( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { return static_cast<const Derived*>(this)->maxSlackStepSize_impl( data, is_contact_active); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::maxDualStepSize( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { return static_cast<const Derived*>(this)->maxDualStepSize_impl( data, is_contact_active); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::updateSlack( ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { assert(step_size > 0); static_cast<const Derived*>(this)->updateSlack_impl(data, is_contact_active, step_size); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::updateDual( ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { assert(step_size > 0); static_cast<const Derived*>(this)->updateDual_impl(data, is_contact_active, step_size); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active) const { return static_cast<const Derived*>(this)->costSlackBarrier_impl( data, is_contact_active); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const ConstraintComponentData& data, const std::vector<bool>& is_contact_active, const double step_size) const { return static_cast<const Derived*>(this)->costSlackBarrier_impl( data, is_contact_active, step_size); } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>::setBarrier( const double barrier) { assert(barrier > 0); barrier_ = barrier; } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>:: setFractionToBoundaryRate(const double fraction_to_boundary_rate) { assert(fraction_to_boundary_rate > 0); fraction_to_boundary_rate_ = fraction_to_boundary_rate; } template <typename Derived> inline void ContactComplementarityComponentBase<Derived>:: setSlackAndDualPositive(Eigen::VectorXd& slack, Eigen::VectorXd& dual) const { pdipmfunc::SetSlackAndDualPositive(barrier_, slack, dual); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const double slack) const { return - barrier_ * std::log(slack); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::costSlackBarrier( const double slack, const double dslack, const double step_size) const { return - barrier_ * std::log(slack + step_size * dslack); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::computeDuality( const double slack, const double dual) const { return pdipmfunc::ComputeDuality(barrier_, slack, dual); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::computeDualDirection( const double slack, const double dual, const double dslack, const double duality) const { return pdipmfunc::ComputeDualDirection(slack, dual, dslack, duality); } template <typename Derived> inline double ContactComplementarityComponentBase<Derived>::fractionToBoundary( const double vec, const double dvec) const { return pdipmfunc::FractionToBoundary(fraction_to_boundary_rate_, vec, dvec); } } // namespace idocp #endif // IDOCP_CONTACT_COMPLEMENTARITY_COMPONENT_BASE_HXX_
33.629167
83
0.7408
KY-Lin22
c1c5331af48793255435eb2125ebae830b901c86
1,248
hpp
C++
src/parser/__ast/ClassSymbol.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
src/parser/__ast/ClassSymbol.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
src/parser/__ast/ClassSymbol.hpp
shockazoid/HydroLanguage
25071995477406245911989584cb3e6f036229c0
[ "Apache-2.0" ]
null
null
null
// // __ __ __ // / / / /__ __ ____/ /_____ ____ // / /_/ // / / // __ // ___// __ \ // / __ // /_/ // /_/ // / / /_/ / // /_/ /_/ \__, / \__,_//_/ \____/ // /____/ // // The Hydro Programming Language // // © 2020 Shockazoid, Inc. All Rights Reserved. // #ifndef __h3o_ClassSymbol__ #define __h3o_ClassSymbol__ #include <vector> #include "TypeSpec.hpp" #include "PackageSymbol.hpp" namespace hydro { class ClassSymbol : public Symbol { private: PackageSymbol *_package; std::vector<TypeSpec *> _types; public: ClassSymbol(Modifier *modifier, Name *name, Scope *ownScope, PackageSymbol *package) : Symbol{modifier, name, ownScope, package}, _types{}, _package{package} {} virtual ~ClassSymbol() {} void append(TypeSpec *type) { _types.push_back(type); } const std::vector<TypeSpec *> &types() const { return _types; } PackageSymbol *package() const { return _package; } std::string fullName() const { return _package ? _package->name()->value() + "::" + name()->value() : name()->value(); } }; } // namespace hydro #endif /* __h3o_ClassSymbol__ */
28.363636
164
0.552083
shockazoid
c1c86e247c906b2b7a04e1e853ada6172f61953d
2,268
hpp
C++
libadb/include/libadb/api/guild/data/guild-features.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
1
2022-03-10T15:14:13.000Z
2022-03-10T15:14:13.000Z
libadb/include/libadb/api/guild/data/guild-features.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
9
2022-03-07T21:00:08.000Z
2022-03-15T23:14:52.000Z
libadb/include/libadb/api/guild/data/guild-features.hpp
faserg1/adb
65507dc17589ac6ec00caf2ecd80f6dbc4026ad4
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <libadb/libadb.hpp> #include <cstdint> namespace adb::api { enum class GuildFeature : uint64_t { UNKNOWN, /// guild has access to set an animated guild banner image ANIMATED_BANNER, /// guild has access to set an animated guild icon ANIMATED_ICON, /// guild has access to set a guild banner image BANNER, /// guild has access to use commerce features (i.e. create store channels) COMMERCE, /// guild can enable welcome screen, Membership Screening, stage channels and discovery, and receives community updates COMMUNITY, /// guild is able to be discovered in the directory DISCOVERABLE, /// guild is able to be featured in the directory FEATURABLE, /// guild has access to set an invite splash background INVITE_SPLASH, /// guild has enabled Membership Screening MEMBER_VERIFICATION_GATE_ENABLED, /// guild has enabled monetization MONETIZATION_ENABLED, /// guild has increased custom sticker slots MORE_STICKERS, /// guild has access to create news channels NEWS, /// guild is partnered PARTNERED, /// guild can be previewed before joining via Membership Screening or the directory PREVIEW_ENABLED, /// guild has access to create private threads PRIVATE_THREADS, /// guild is able to set role icons ROLE_ICONS, /// guild has access to the seven day archive time for threads SEVEN_DAY_THREAD_ARCHIVE, /// guild has access to the three day archive time for threads THREE_DAY_THREAD_ARCHIVE, /// guild has enabled ticketed events TICKETED_EVENTS_ENABLED, /// guild has access to set a vanity URL VANITY_URL, /// guild is verified VERIFIED, /// guild has access to set 384kbps bitrate in voice (previously VIP voice servers) VIP_REGIONS, /// guild has enabled the welcome screen WELCOME_SCREEN_ENABLED }; LIBADB_API std::string to_string(GuildFeature e); LIBADB_API void from_string(const std::string &str, GuildFeature &feature); }
36.580645
127
0.648148
faserg1
c1cd2d1fa8ea050fe57df86849a68b839f990fce
465
hpp
C++
lib/c_Homie/c_homie.hpp
Christian-Me/homie-firmware
ea43546e763b7cf08a0393cd2bdcdea297a6462e
[ "Apache-2.0" ]
3
2021-01-03T02:38:55.000Z
2021-01-05T20:18:09.000Z
lib/c_Homie/c_homie.hpp
Christian-Me/homie-firmware
ea43546e763b7cf08a0393cd2bdcdea297a6462e
[ "Apache-2.0" ]
null
null
null
lib/c_Homie/c_homie.hpp
Christian-Me/homie-firmware
ea43546e763b7cf08a0393cd2bdcdea297a6462e
[ "Apache-2.0" ]
null
null
null
#pragma once #include "Arduino.h" #include <Homie.h> // #include "homieSyslog.h" // #include "datatypes.h" #include "homie_property.hpp" #include "homie_node.hpp" #include "homie_device.hpp" bool globalInputHandler(const HomieNode& node, const HomieRange& range, const String& property, const String& value); void onHomieEvent(const HomieEvent& event); void homieParameterSet(const __FlashStringHelper *nodeId, const __FlashStringHelper *parameterId, bool state);
35.769231
117
0.787097
Christian-Me
c1d0e9b8c0fa7e1fac552721151019790254a8e0
12,917
cpp
C++
esp/chips/ulp/assembler/ulp_assembler.cpp
kermitdafrog8/REDasm-Loaders
b401849f9aa54dfd9562aed1a6d2e03f75ac455f
[ "MIT" ]
4
2019-06-09T10:22:28.000Z
2022-02-12T13:11:43.000Z
esp/chips/ulp/assembler/ulp_assembler.cpp
kermitdafrog8/REDasm-Loaders
b401849f9aa54dfd9562aed1a6d2e03f75ac455f
[ "MIT" ]
1
2019-07-15T13:55:31.000Z
2022-01-10T08:06:31.000Z
esp/chips/ulp/assembler/ulp_assembler.cpp
kermitdafrog8/REDasm-Loaders
b401849f9aa54dfd9562aed1a6d2e03f75ac455f
[ "MIT" ]
2
2020-10-11T13:13:46.000Z
2021-09-10T22:35:04.000Z
#include "ulp_assembler.h" #include "ulp_constants.h" #define WORDS_TO_ADDR(instr) (instr) * sizeof(ULPInstruction) std::array<const char*, 7> ULPAssembler::ALUSEL = { "add", "sub", "and", "or", "move", "lsh", "rsh" }; bool ULPAssembler::decode(const RDBufferView* view, ULPInstruction* ulpinstr) { if(!ulpinstr || (view->size < sizeof(ULPInstruction))) return false; ulpinstr->data = RD_FromLittleEndian32(*reinterpret_cast<u32*>(view->data)); return true; } void ULPAssembler::renderInstruction(RDContext*, const RDRendererParams* rp) { ULPInstruction ulpinstr; if(!ULPAssembler::decode(&rp->view, &ulpinstr)) return; switch(ulpinstr.unk.opcode) { case ULP_OP_ALU: ULPAssembler::renderAlu(&ulpinstr, rp); break; case ULP_OP_STORE: ULPAssembler::renderStore(&ulpinstr, rp); break; case ULP_OP_LOAD: ULPAssembler::renderLoad(&ulpinstr, rp); break; case ULP_OP_JUMP: ULPAssembler::renderJmp(&ulpinstr, rp); break; case ULP_OP_HALT: RDRenderer_Mnemonic(rp->renderer, "halt", Theme_Ret); break; case ULP_OP_WAKESLEEP: ULPAssembler::renderWakeSleep(&ulpinstr, rp); break; case ULP_OP_WAIT: ULPAssembler::renderWait(&ulpinstr, rp); break; case ULP_OP_TSENS: ULPAssembler::renderTSens(&ulpinstr, rp); break; case ULP_OP_ADC: ULPAssembler::renderAdc(&ulpinstr, rp); break; case ULP_OP_I2C: ULPAssembler::renderI2C(&ulpinstr, rp); break; case ULP_OP_REGRD: ULPAssembler::renderRegRD(&ulpinstr, rp); break; case ULP_OP_REGWR: ULPAssembler::renderRegWR(&ulpinstr, rp); break; default: RDRenderer_Unknown(rp->renderer); break; } } void ULPAssembler::emulate(RDContext*, RDEmulateResult* result) { ULPInstruction ulpinstr; if(!ULPAssembler::decode(RDEmulateResult_GetView(result), &ulpinstr)) return; RDEmulateResult_SetSize(result, sizeof(ULPInstruction)); switch(ulpinstr.unk.opcode) { case ULP_OP_JUMP: ULPAssembler::emulateJmp(&ulpinstr, result); break; case ULP_OP_HALT: RDEmulateResult_AddReturn(result); break; default: break; } } std::string ULPAssembler::regName(u8 reg) { return "r" + std::to_string(reg); } void ULPAssembler::emulateJmp(const ULPInstruction* ulpinstr, RDEmulateResult* result) { rd_address address = RDEmulateResult_GetAddress(result); switch(ulpinstr->unk.choice) { case 0: { if(!ulpinstr->jump.sel) { if(ulpinstr->jump.type) RDEmulateResult_AddBranchTrue(result, ulpinstr->jump.addr); else RDEmulateResult_AddBranch(result, WORDS_TO_ADDR(ulpinstr->jump.addr)); } else RDEmulateResult_AddBranchIndirect(result); if(ulpinstr->jump.type) RDEmulateResult_AddBranchFalse(result, address + sizeof(ULPInstruction)); break; } case 1: case 2: { rd_address relative = WORDS_TO_ADDR(ulpinstr->jumpr.step & 0x7F); int sign = ulpinstr->jumpr.step & 0x80 ? -1 : +1; RDEmulateResult_AddBranchTrue(result, address + sign * relative); RDEmulateResult_AddBranchFalse(result, address + sizeof(ULPInstruction)); break; } default: break; } } void ULPAssembler::renderAlu(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { switch(ulpinstr->unk.choice) { case 0: ULPAssembler::renderAluReg(ulpinstr, rp); break; case 1: ULPAssembler::renderAluImm(ulpinstr, rp); break; case 2: ULPAssembler::renderAluStage(ulpinstr, rp); break; default: break; } } void ULPAssembler::renderAluReg(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, ALUSEL[ulpinstr->alureg.sel], Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rsrc1).c_str()); if(ulpinstr->alureg.sel == ALU_SEL_MOVE) return; RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->alureg.rsrc2).c_str()); } void ULPAssembler::renderAluImm(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, ALUSEL[ulpinstr->aluimm.sel], Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->aluimm.rdst).c_str()); if(ulpinstr->aluimm.sel != ALU_SEL_MOVE) { RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->aluimm.rsrc1).c_str()); } RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->aluimm.imm); } void ULPAssembler::renderAluStage(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { static std::array<const char*, 3> STAgeSEL = { "stage_inc", "stage_dec", "stage_rst" }; RDRenderer_MnemonicWord(rp->renderer, STAgeSEL[ulpinstr->alustage.sel], Theme_Default); if(ulpinstr->alustage.sel == 2) return; RDRenderer_Unsigned(rp->renderer, ulpinstr->alustage.imm); } void ULPAssembler::renderJmp(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { switch(ulpinstr->unk.choice) { case 0: { RDRenderer_MnemonicWord(rp->renderer, "jump", ulpinstr->jump.type ? Theme_JumpCond : Theme_Jump); if(ulpinstr->jump.sel) RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->jump.rdest).c_str()); else RDRenderer_Reference(rp->renderer, WORDS_TO_ADDR(ulpinstr->jump.addr)); if(ulpinstr->jump.type) { RDRenderer_Text(rp->renderer, ", "); if(ulpinstr->jump.type == 1) RDRenderer_Text(rp->renderer, "eq"); else if(ulpinstr->jump.type == 2) RDRenderer_Text(rp->renderer, "ov"); } break; } case 1: { rd_address relative = WORDS_TO_ADDR(ulpinstr->jumpr.step & 0x7F); int sign = ulpinstr->jumpr.step & 0x80 ? -1 : +1; RDRenderer_MnemonicWord(rp->renderer, "jumpr", Theme_JumpCond); RDRenderer_Reference(rp->renderer, rp->address + sign * relative); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->jumps.thres); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Text(rp->renderer, ulpinstr->jumpr.cond ? "ge" : "lt"); break; } case 2: { rd_address relative = WORDS_TO_ADDR(ulpinstr->jumps.step & 0x7F); int sign = ulpinstr->jumps.step & 0x80 ? -1 : +1; RDRenderer_MnemonicWord(rp->renderer, "jumps", Theme_JumpCond); RDRenderer_Unsigned(rp->renderer, rp->address + (sign * relative)); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->jumps.thres); RDRenderer_Text(rp->renderer, ", "); if(ulpinstr->jumps.cond == 0) RDRenderer_Text(rp->renderer, "lt"); else if(ulpinstr->jumps.cond == 1) RDRenderer_Text(rp->renderer, "gt"); else RDRenderer_Text(rp->renderer, "eq"); break; } default: break; } } void ULPAssembler::renderWakeSleep(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { if(ulpinstr->wakesleep.wakeorsleep) { RDRenderer_MnemonicWord(rp->renderer, "sleep", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->wakesleep.reg); } else RDRenderer_Mnemonic(rp->renderer, "wake", Theme_Default); } void ULPAssembler::renderWait(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { if(ulpinstr->wait.cycles) { RDRenderer_MnemonicWord(rp->renderer, "wait", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->wait.cycles); } else RDRenderer_Mnemonic(rp->renderer, "nop", Theme_Nop); } void ULPAssembler::renderTSens(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "tsens", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->tsens.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->tsens.delay); } void ULPAssembler::renderAdc(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "adc", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->adc.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->adc.sel); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->adc.sarmux); } void ULPAssembler::renderI2C(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { if(ulpinstr->i2c.rw) { RDRenderer_MnemonicWord(rp->renderer, "i2c_wr", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.subaddr); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.data); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.low); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.sel); } else { RDRenderer_MnemonicWord(rp->renderer, "i2c_rd", Theme_Default); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.subaddr); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.low); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->i2c.sel); } } void ULPAssembler::renderRegRD(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { unsigned int address = WORDS_TO_ADDR(ulpinstr->regwr.addr) + DR_REG_RTCCNTL_BASE; unsigned int base; if(address >= DR_REG_RTC_I2C_BASE) base = DR_REG_RTC_I2C_BASE; else if(address >= DR_REG_SENS_BASE) base = DR_REG_SENS_BASE; else if(address >= DR_REG_RTCIO_BASE) base = DR_REG_RTCIO_BASE; else base = DR_REG_RTCCNTL_BASE; unsigned int offset = address - base; RDRenderer_MnemonicWord(rp->renderer, "reg_rd", Theme_Default); if(offset) RDRenderer_Constant(rp->renderer, (rd_tohex(base) + "+" + rd_tohex(offset)).c_str()); else RDRenderer_Unsigned(rp->renderer, base); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.low); } void ULPAssembler::renderRegWR(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { unsigned int address = WORDS_TO_ADDR(ulpinstr->regwr.addr) + DR_REG_RTCCNTL_BASE; unsigned int base; if(address >= DR_REG_RTC_I2C_BASE) base = DR_REG_RTC_I2C_BASE; else if(address >= DR_REG_SENS_BASE) base = DR_REG_SENS_BASE; else if(address >= DR_REG_RTCIO_BASE) base = DR_REG_RTCIO_BASE; else base = DR_REG_RTCCNTL_BASE; unsigned int offset = address - base; RDRenderer_MnemonicWord(rp->renderer, "reg_wr", Theme_Default); if(offset) RDRenderer_Constant(rp->renderer, (rd_tohex(base) + "+" + rd_tohex(offset)).c_str()); else RDRenderer_Unsigned(rp->renderer, base); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.high); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.low); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Unsigned(rp->renderer, ulpinstr->regwr.data); } void ULPAssembler::renderStore(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "st", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rsrc).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Signed(rp->renderer, ulpinstr->ld.offset); } void ULPAssembler::renderLoad(const ULPInstruction* ulpinstr, const RDRendererParams* rp) { RDRenderer_MnemonicWord(rp->renderer, "ld", Theme_Default); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rdst).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Register(rp->renderer, ULPAssembler::regName(ulpinstr->ld.rsrc).c_str()); RDRenderer_Text(rp->renderer, ", "); RDRenderer_Signed(rp->renderer, ulpinstr->ld.offset); }
39.622699
122
0.682821
kermitdafrog8
c1d52f3d55ec9edc06f61216a567651b36c52abd
717
cpp
C++
ITU/proj_1/NormalInput.cpp
mikeek/FIT
da7fb8b4b57b0a28b345348d8fe1ecf30dccb9a2
[ "MIT" ]
1
2017-03-25T11:59:15.000Z
2017-03-25T11:59:15.000Z
ITU/proj_1/NormalInput.cpp
mikeek/FIT
da7fb8b4b57b0a28b345348d8fe1ecf30dccb9a2
[ "MIT" ]
null
null
null
ITU/proj_1/NormalInput.cpp
mikeek/FIT
da7fb8b4b57b0a28b345348d8fe1ecf30dccb9a2
[ "MIT" ]
6
2017-04-06T10:49:03.000Z
2021-01-18T20:29:35.000Z
#include "NormalInput.h" #include <time.h> NormalInput::NormalInput() { } float NormalInput::realTime(clock_t clockDiff) { return ((float) clockDiff) / CLOCKS_PER_SEC; } QChar NormalInput::resolve(int index, QString charField) { clock_t nowTime = clock(); clock_t diff = nowTime - _lastTime; _lastTime = nowTime; if (index == _lastButton && realTime(diff) < QUICK_PRESS_INTEVAL) { /* Quick press, change last character */ _lastResult = CHANGE_LAST; if (_lastPosition >= charField.length()) { _lastPosition = 0; } return charField[_lastPosition++]; } _lastResult = APPEND_NEW; _lastButton = index; _lastPosition = 0; return charField[_lastPosition++]; }
20.485714
69
0.679219
mikeek
c1d7f4b4f194d2668e731bd31795607911da6c76
1,915
cpp
C++
d3util/logger.cpp
d3roch4/d3util
d438e35c6fceff8cdca9ef6ea3e6c043389c6e4c
[ "MIT" ]
null
null
null
d3util/logger.cpp
d3roch4/d3util
d438e35c6fceff8cdca9ef6ea3e6c043389c6e4c
[ "MIT" ]
null
null
null
d3util/logger.cpp
d3roch4/d3util
d438e35c6fceff8cdca9ef6ea3e6c043389c6e4c
[ "MIT" ]
null
null
null
#include "logger.h" #include <boost/log/attributes/attribute_value_set.hpp> #include <boost/log/sources/severity_logger.hpp> #include <boost/log/utility/setup/file.hpp> #include <boost/log/utility/setup/console.hpp> #include <boost/log/utility/setup/common_attributes.hpp> #include <boost/log/expressions.hpp> #include <boost/shared_ptr.hpp> void init_logger(const std::string& prefixFile, boost::log::trivial::severity_level severity) { auto format = "[%TimeStamp%] [%ThreadID%] [%Severity%] [%ProcessID%] [%LineID%] %Message%"; namespace keywords = boost::log::keywords; namespace expr = boost::log::expressions; boost::log::add_console_log( std::clog, keywords::format = ( expr::stream //<< std::hex //To print the LineID in Hexadecimal format // << std::setw(8) << std::setfill('0') << expr::attr< unsigned int >("LineID") // << expr::format_date_time<boost::posix_time::ptime>("TimeStamp","%H:%M:%S.%f") << "<" << boost::log::trivial::severity << ">" << expr::smessage ) ); boost::log::add_file_log ( keywords::file_name = prefixFile, /*< file name pattern >*/ keywords::rotation_size = 10 * 1024, /*< rotate files every 1 KiB >*/ /*< log record format >*/ keywords::format = ( expr::stream //<< std::hex //To print the LineID in Hexadecimal format // << std::setw(8) << std::setfill('0') << expr::attr< unsigned int >("LineID") << "\t" // << expr::format_date_time<boost::posix_time::ptime>("TimeStamp","%H:%M:%S.%f") << "\t: <" << boost::log::trivial::severity << "> \t" << expr::smessage ) ); // boost::log::core::get()->set_filter // ( // boost::log::trivial::severity >= severity // ); }
36.132075
95
0.562924
d3roch4
c1d8c9b1a9b00818d5ae083fa70c5fabe91ba6eb
9,016
cpp
C++
2020/0125_ddcc2020-machine/A.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
7
2019-03-24T14:06:29.000Z
2020-09-17T21:16:36.000Z
2020/0125_ddcc2020-machine/A.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
null
null
null
2020/0125_ddcc2020-machine/A.cpp
kazunetakahashi/atcoder
16ce65829ccc180260b19316e276c2fcf6606c53
[ "MIT" ]
1
2020-07-22T17:27:09.000Z
2020-07-22T17:27:09.000Z
#define DEBUG 1 /** * File : A.cpp * Author : Kazune Takahashi * Created : 2020/1/25 11:32:12 * Powered by Visual Studio Code */ #include <algorithm> #include <bitset> #include <cassert> #include <cctype> #include <chrono> #include <cmath> #include <complex> #include <cstdint> #include <cstdio> #include <cstdlib> #include <functional> #include <iomanip> #include <iostream> #include <map> #include <queue> #include <random> #include <set> #include <stack> #include <string> #include <tuple> #include <unordered_map> #include <unordered_set> #include <vector> // ----- boost ----- #include <boost/rational.hpp> #include <boost/multiprecision/cpp_int.hpp> // ----- using directives and manipulations ----- using namespace std; using boost::rational; using boost::multiprecision::cpp_int; using ll = long long; template <typename T> using max_heap = priority_queue<T>; template <typename T> using min_heap = priority_queue<T, vector<T>, greater<T>>; // ----- constexpr for Mint and Combination ----- constexpr ll MOD{1000000007LL}; // constexpr ll MOD{998244353LL}; // be careful constexpr ll MAX_SIZE{3000010LL}; // constexpr ll MAX_SIZE{30000010LL}; // if 10^7 is needed // ----- ch_max and ch_min ----- template <typename T> void ch_max(T &left, T right) { if (left < right) { left = right; } } template <typename T> void ch_min(T &left, T right) { if (left > right) { left = right; } } // ----- Mint ----- template <ll MOD = MOD> class Mint { public: ll x; Mint() : x{0LL} {} Mint(ll x) : x{(x % MOD + MOD) % MOD} {} Mint operator-() const { return x ? MOD - x : 0; } Mint &operator+=(const Mint &a) { if ((x += a.x) >= MOD) { x -= MOD; } return *this; } Mint &operator-=(const Mint &a) { return *this += -a; } Mint &operator*=(const Mint &a) { (x *= a.x) %= MOD; return *this; } Mint &operator/=(const Mint &a) { Mint b{a}; return *this *= b.power(MOD - 2); } Mint operator+(const Mint &a) const { return Mint(*this) += a; } Mint operator-(const Mint &a) const { return Mint(*this) -= a; } Mint operator*(const Mint &a) const { return Mint(*this) *= a; } Mint operator/(const Mint &a) const { return Mint(*this) /= a; } bool operator<(const Mint &a) const { return x < a.x; } bool operator<=(const Mint &a) const { return x <= a.x; } bool operator>(const Mint &a) const { return x > a.x; } bool operator>=(const Mint &a) const { return x >= a.x; } bool operator==(const Mint &a) const { return x == a.x; } bool operator!=(const Mint &a) const { return !(*this == a); } const Mint power(ll N) { if (N == 0) { return 1; } else if (N % 2 == 1) { return *this * power(N - 1); } else { Mint half = power(N / 2); return half * half; } } }; template <ll MOD> Mint<MOD> operator+(ll lhs, const Mint<MOD> &rhs) { return rhs + lhs; } template <ll MOD> Mint<MOD> operator-(ll lhs, const Mint<MOD> &rhs) { return -rhs + lhs; } template <ll MOD> Mint<MOD> operator*(ll lhs, const Mint<MOD> &rhs) { return rhs * lhs; } template <ll MOD> Mint<MOD> operator/(ll lhs, const Mint<MOD> &rhs) { return Mint<MOD>{lhs} / rhs; } template <ll MOD> istream &operator>>(istream &stream, Mint<MOD> &a) { return stream >> a.x; } template <ll MOD> ostream &operator<<(ostream &stream, const Mint<MOD> &a) { return stream << a.x; } // ----- Combination ----- template <ll MOD = MOD, ll MAX_SIZE = MAX_SIZE> class Combination { public: vector<Mint<MOD>> inv, fact, factinv; Combination() : inv(MAX_SIZE), fact(MAX_SIZE), factinv(MAX_SIZE) { inv[1] = 1; for (auto i = 2LL; i < MAX_SIZE; i++) { inv[i] = (-inv[MOD % i]) * (MOD / i); } fact[0] = factinv[0] = 1; for (auto i = 1LL; i < MAX_SIZE; i++) { fact[i] = Mint<MOD>(i) * fact[i - 1]; factinv[i] = inv[i] * factinv[i - 1]; } } Mint<MOD> operator()(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return fact[n] * factinv[k] * factinv[n - k]; } return 0; } Mint<MOD> catalan(int x, int y) { return (*this)(x + y, y) - (*this)(x + y, y - 1); } }; // ----- for C++14 ----- using mint = Mint<MOD>; using combination = Combination<MOD, MAX_SIZE>; template <typename T> T gcd(T x, T y) { return y ? gcd(y, x % y) : x; } template <typename T> T lcm(T x, T y) { return x / gcd(x, y) * y; } template <typename T> int popcount(T x) // C++20 { int ans{0}; while (x != 0) { ans += x & 1; x >>= 1; } return ans; } // ----- frequently used constexpr ----- // constexpr double epsilon{1e-10}; // constexpr ll infty{1000000000000000LL}; // constexpr int dx[4] = {1, 0, -1, 0}; // constexpr int dy[4] = {0, 1, 0, -1}; // ----- Yes() and No() ----- void Yes() { cout << "Yes" << endl; exit(0); } void No() { cout << "No" << endl; exit(0); } class Sieve { static constexpr ll MAX_SIZE{10000010LL}; ll N; vector<ll> f; vector<ll> prime_nums; public: Sieve(ll N = MAX_SIZE) : N{N}, f(N, 0), prime_nums{} { f[0] = f[1] = -1; for (auto i = 2; i < N; i++) { if (f[i]) { continue; } prime_nums.push_back(i); f[i] = i; for (auto j = 2 * i; j < N; j += i) { if (!f[j]) { f[j] = i; } } } } bool is_prime(ll x) const { // 2 \leq x \leq MAX_SIZE^2 if (x < N) { return f[x]; } for (auto e : prime_nums) { if (x % e == 0) { return false; } } return true; } vector<ll> const &primes() const { return prime_nums; } vector<ll> factor_list(ll x) const { if (x < 2) { return {}; } vector<ll> res; auto it{prime_nums.begin()}; if (x < N) { while (x != 1) { res.push_back(f[x]); x /= f[x]; } } else { while (x != 1 && it != prime_nums.end()) { if (x % *it == 0) { res.push_back(*it); x /= *it; } else { ++it; } } if (x != 1) { res.push_back(x); } } return res; } vector<tuple<ll, ll>> factor(ll x) const { if (x < 2) { return {}; } auto factors{factor_list(x)}; vector<tuple<ll, ll>> res{make_tuple(factors[0], 0)}; for (auto x : factors) { if (x == get<0>(res.back())) { get<1>(res.back())++; } else { res.emplace_back(x, 1); } } return res; } }; // ----- main() ----- using ld = long double; using point = complex<ld>; constexpr ld PI{3.14159265358979323846}; class Solve { ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc; int alpha; Sieve sieve; ld Ta = 0; ld Tb; point Oa{0, 900}, Ob{900, 0}, Oc{900, 900}, Oe{90, 50}; point Aa{1, 0}, Ab{0, 1}, Ac{-1, 0}; ld S{500}, A{3000}, D{60}; public: Solve(ld La, ld Lb, ld Lc, ld Na, ld Nb, ld Nc, ld Ne, ld Ma, ld Mb, ld Mc, ld Tc) : La{La}, Lb{Lb}, Lc{Lc}, Na{Na}, Nb{Nb}, Nc{Nc}, Ne{Ne}, Ma{Ma}, Mb{Mb}, Mc{Mc}, Tc{Tc} {} void flush() { for (auto i = 0; i < 20; ++i) { ld now{0}; ld W{Ma}; if (now + Ma * Na > 100) { W = 500; } flush_A(W); now += Na * W; W = Mb; if (now + Mb * Nb > 100) { W = 500; } flush_B(W); now += Nb * W; W = Mc; if (now + Mc * Nc > 100) { W = 500; } flush_C(W); now += Nc * W; flush_E(now / Ne); } } private: void update_Tb() { if (alpha == 0) { Tb = 0; } else { ll p{sieve.primes()[alpha + 1]}; ll r{p % 180}; Tb = (r <= 90 ? r : 180 - r); } } point arg(ld theta) { return theta / 180 * PI * point(0, 1); } point Pa() { return exp(-arg(Ta)) * La + Oa; } point Pb() { return exp(arg(Tb)) * Lb + Ob; } point Pc() { return exp(arg(Tc)) * Lc + Oc; } void flush_simple(ld X, ld Sx, ld Ax, ld Dx, ld Y, ld Sy, ld Ay, ld Dy, ld Ta, ld Wa, ld Wb, ld Wc, ld We) { cout << fixed << setprecision(0) << X << ", " << Sx << ", " << Ax << ", " << Dx << ", " << Y << ", " << Sy << ", " << Ay << ", " << Dy << ", " << Ta << ", " << Wa << ", " << Wb << ", " << Wc << ", " << We << endl; } void flush_A(ld W) { flush_simple(Pa().real(), S, A, D, Pa().imag(), S, A, D, Ta, W, 0, 0, 0); alpha += W; } void flush_B(ld W) { flush_simple(Pb().real(), S, A, D, Pb().imag(), S, A, D, Ta, 0, W, 0, 0); } void flush_C(ld W) { flush_simple(Pc().real(), S, A, D, Pc().imag(), S, A, D, Ta, 0, 0, W, 0); } void flush_E(ld W) { flush_simple(Oe.real(), S, A, D, Oe.imag(), S, A, D, Ta, 0, 0, 0, W); } }; int main() { ld La, Lb, Lc, Na, Nb, Nc, Ne, Ma, Mb, Mc, Tc; cin >> La >> Lb >> Lc >> Na >> Nb >> Nc >> Ne >> Ma >> Mb >> Mc >> Tc; Solve solve(La, Lb, Lc, Na / 1000, Nb / 1000, Nc / 1000, Ne / 1000, Ma, Mb, Mc, Tc); solve.flush(); }
20.822171
217
0.504326
kazunetakahashi
c1dcfb9b6c8c2eca8d0e535bd836ef6a35f7e905
569
hpp
C++
src/Render.hpp
Sartek/Platformer
a499c870c05d7169aaf56b8a93694668750a4b4e
[ "CC-BY-3.0" ]
null
null
null
src/Render.hpp
Sartek/Platformer
a499c870c05d7169aaf56b8a93694668750a4b4e
[ "CC-BY-3.0" ]
null
null
null
src/Render.hpp
Sartek/Platformer
a499c870c05d7169aaf56b8a93694668750a4b4e
[ "CC-BY-3.0" ]
null
null
null
#ifndef RENDER #define RENDER #include <SFML/Graphics.hpp> #include <vector> class Render { public: Render(); virtual ~Render(); void Background(); void Tile(unsigned int x,unsigned int y,unsigned int id); void Hud(); void Player(); private: sf::Texture Tile1; sf::Texture Tile2; sf::Texture Tile3; sf::Texture background; sf::Sprite backgroundSprite; sf::Texture Sprite1; sf::Texture Sprite2; sf::Sprite playerSprite; sf::RenderTexture hud; sf::Sprite hudSprite; std::vector<std::vector<sf::Sprite*> > SpriteArea; }; #endif // RENDER
18.966667
61
0.697715
Sartek
c1ddba9fc988d2143876f14b51096ac13e954eb6
3,913
hpp
C++
include/RootMotion/BipedReferences_AutoDetectParams.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/RootMotion/BipedReferences_AutoDetectParams.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
include/RootMotion/BipedReferences_AutoDetectParams.hpp
Fernthedev/BeatSaber-Quest-Codegen
716e4ff3f8608f7ed5b83e2af3be805f69e26d9e
[ "Unlicense" ]
null
null
null
// Autogenerated from CppHeaderCreator // Created by Sc2ad // ========================================================================= #pragma once // Begin includes #include "extern/beatsaber-hook/shared/utils/typedefs.h" #include "extern/beatsaber-hook/shared/utils/byref.hpp" // Including type: RootMotion.BipedReferences #include "RootMotion/BipedReferences.hpp" // Including type: System.ValueType #include "System/ValueType.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-properties.hpp" #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-fields.hpp" #include "extern/beatsaber-hook/shared/utils/utils.h" // Completed includes // Type namespace: RootMotion namespace RootMotion { // Size: 0x2 #pragma pack(push, 1) // WARNING Layout: Sequential may not be correctly taken into account! // Autogenerated type: RootMotion.BipedReferences/RootMotion.AutoDetectParams // [TokenAttribute] Offset: FFFFFFFF struct BipedReferences::AutoDetectParams/*, public System::ValueType*/ { public: // public System.Boolean legsParentInSpine // Size: 0x1 // Offset: 0x0 bool legsParentInSpine; // Field size check static_assert(sizeof(bool) == 0x1); // public System.Boolean includeEyes // Size: 0x1 // Offset: 0x1 bool includeEyes; // Field size check static_assert(sizeof(bool) == 0x1); // Creating value type constructor for type: AutoDetectParams constexpr AutoDetectParams(bool legsParentInSpine_ = {}, bool includeEyes_ = {}) noexcept : legsParentInSpine{legsParentInSpine_}, includeEyes{includeEyes_} {} // Creating interface conversion operator: operator System::ValueType operator System::ValueType() noexcept { return *reinterpret_cast<System::ValueType*>(this); } // Get instance field reference: public System.Boolean legsParentInSpine bool& dyn_legsParentInSpine(); // Get instance field reference: public System.Boolean includeEyes bool& dyn_includeEyes(); // static public RootMotion.BipedReferences/RootMotion.AutoDetectParams get_Default() // Offset: 0x1D2FDEC static RootMotion::BipedReferences::AutoDetectParams get_Default(); // public System.Void .ctor(System.Boolean legsParentInSpine, System.Boolean includeEyes) // Offset: 0x1D2FDD8 // template<::il2cpp_utils::CreationType creationType = ::il2cpp_utils::CreationType::Temporary> // ABORTED: conflicts with another method. AutoDetectParams(bool legsParentInSpine, bool includeEyes) }; // RootMotion.BipedReferences/RootMotion.AutoDetectParams #pragma pack(pop) static check_size<sizeof(BipedReferences::AutoDetectParams), 1 + sizeof(bool)> __RootMotion_BipedReferences_AutoDetectParamsSizeCheck; static_assert(sizeof(BipedReferences::AutoDetectParams) == 0x2); } DEFINE_IL2CPP_ARG_TYPE(RootMotion::BipedReferences::AutoDetectParams, "RootMotion", "BipedReferences/AutoDetectParams"); #include "extern/beatsaber-hook/shared/utils/il2cpp-utils-methods.hpp" // Writing MetadataGetter for method: RootMotion::BipedReferences::AutoDetectParams::get_Default // Il2CppName: get_Default template<> struct ::il2cpp_utils::il2cpp_type_check::MetadataGetter<static_cast<RootMotion::BipedReferences::AutoDetectParams (*)()>(&RootMotion::BipedReferences::AutoDetectParams::get_Default)> { static const MethodInfo* get() { return ::il2cpp_utils::FindMethod(classof(RootMotion::BipedReferences::AutoDetectParams), "get_Default", std::vector<Il2CppClass*>(), ::std::vector<const Il2CppType*>{}); } }; // Writing MetadataGetter for method: RootMotion::BipedReferences::AutoDetectParams::AutoDetectParams // Il2CppName: .ctor // Cannot get method pointer of value based method overload from template for constructor! // Try using FindMethod instead!
52.878378
186
0.741375
Fernthedev
c1df4685e1acba2c8fd40b402c8ab3199b11ce7c
4,224
cpp
C++
shapes/rect.cpp
JacobSchneck/Flowers
34f460cc584322f1eb1359bc203d2a89be23bccc
[ "MIT" ]
2
2021-05-28T02:19:01.000Z
2021-05-28T02:19:23.000Z
shapes/rect.cpp
JacobSchneck/Flowers
34f460cc584322f1eb1359bc203d2a89be23bccc
[ "MIT" ]
null
null
null
shapes/rect.cpp
JacobSchneck/Flowers
34f460cc584322f1eb1359bc203d2a89be23bccc
[ "MIT" ]
null
null
null
#include "../graphics.h" #include "rect.h" #include <iostream> using namespace std; /********************* Dimensions Struct ********************/ dimensions::dimensions() : width(0), height(0) {} dimensions::dimensions(double w, double h) : width(w), height(h) {} ostream& operator << (ostream& outs, const dimensions &d) { outs << "[" << d.width << ", " << d.height << "]"; return outs; } Rect::Rect() : Shape(), size({0, 0}) {} Rect::Rect(dimensions size) : Shape() { setSize(size); } Rect::Rect(color fill) : Shape(fill), size({0, 0}) {} Rect::Rect(point2D center) : Shape(center), size({0, 0}) {} Rect::Rect(color fill, point2D center) : Shape(fill, center), size({0, 0}) {} Rect::Rect(double red, double green, double blue, double alpha) : Shape(red, green, blue, alpha), size({0, 0}) {} Rect::Rect(double x, double y) : Shape(x, y), size({0, 0}) {} Rect::Rect(double red, double green, double blue, double alpha, double x, double y) : Shape(red, green, blue, alpha, x, y), size({0, 0}) {} Rect::Rect(color fill, double x, double y) : Shape(fill, x, y), size({0, 0}) {} Rect::Rect(double red, double green, double blue, double alpha, point2D center) : Shape(red, green, blue, alpha, center), size({0, 0}) {} Rect::Rect(color fill, dimensions size) : Shape(fill) { setSize(size); } Rect::Rect(point2D center, dimensions size) : Shape(center) { setSize(size); } Rect::Rect(color fill, point2D center, dimensions size) : Shape(fill, center) { setSize(size); } Rect::Rect(double red, double green, double blue, double alpha, dimensions size) : Shape(red, green, blue, alpha) { setSize(size); } Rect::Rect(double x, double y, dimensions size) : Shape(x, y) { setSize(size); } Rect::Rect(double red, double green, double blue, double alpha, double x, double y, dimensions size) : Shape(red, green, blue, alpha, x, y) { setSize(size); } Rect::Rect(color fill, double x, double y, dimensions size) : Shape(fill, x, y) { setSize(size); } Rect::Rect(double red, double green, double blue, double alpha, point2D center, dimensions size) : Shape(red, green, blue, alpha, center) { setSize(size); } dimensions Rect::getSize() const { return size; } double Rect::getWidth() const { return size.width; } double Rect::getHeight() const { return size.height; } double Rect::getLeftX() const { return center.x - (size.width / 2.0); } double Rect::getRightX() const { return center.x + (size.width / 2.0); } double Rect::getTopY() const { return center.y - (size.height / 2.0); } double Rect::getBottomY() const { return center.y + (size.height / 2.0); } void Rect::setSize(dimensions size) { if (size.width >= 0 && size.height >= 0) { this->size = size; } } void Rect::setSize(double width, double height) { setSize({width, height}); } void Rect::setWidth(double width) { setSize({width, size.height}); } void Rect::setHeight(double height) { setSize({size.width, height}); } void Rect::changeSize(double deltaWidth, double deltaHeight) { setSize({size.width + deltaWidth, size.height + deltaHeight}); } void Rect::changeWidth(double delta) { setSize({size.width + delta, size.height}); } void Rect::changeHeight(double delta) { setSize({size.width, size.height + delta}); } // TODO: Implement this method bool Rect::isOverlapping(const Rect &r) const { // There are only two cases when rectangles are *not* overlapping: // 1. when one is to the left of the other // 2. when one is above the other if ( (r.getLeftX() > getLeftX() && r.getRightX() < getRightX()) && (r.getBottomY() < getBottomY() && r.getTopY() > getTopY())) { return true; } // if (r.getLeftX() > getLeftX() && r.getRightX() < getRightX() && r.getTopY() > getTopY()) { // return true; // } return false; } // TODO: Implement this method void Rect::draw() const { // Don't forget to set the color to the fill field glBegin(GL_QUADS); glColor3f( fill.red, fill.green, fill.blue); glVertex2i(getLeftX(), getBottomY()); glVertex2i(getRightX(), getBottomY()); glVertex2i(getRightX(), getTopY()); glVertex2i(getLeftX(), getTopY()); glEnd(); }
27.076923
141
0.634233
JacobSchneck
c1e419456001f698245dfa37647536f3b621cf1c
3,597
cpp
C++
src/mem/Pem.cpp
OmniNegro123/med
48b00bfb9319f735a2406ff2efe7253c46007236
[ "BSD-3-Clause" ]
37
2015-10-05T17:44:20.000Z
2022-03-24T02:55:04.000Z
src/mem/Pem.cpp
OmniNegro123/med
48b00bfb9319f735a2406ff2efe7253c46007236
[ "BSD-3-Clause" ]
6
2017-04-01T02:26:22.000Z
2022-02-19T07:46:29.000Z
src/mem/Pem.cpp
OmniNegro123/med
48b00bfb9319f735a2406ff2efe7253c46007236
[ "BSD-3-Clause" ]
4
2020-07-23T17:27:36.000Z
2021-12-25T20:29:56.000Z
#include <cinttypes> #include <cstring> #include <cstdio> #include <iostream> #include "mem/Pem.hpp" #include "med/MedCommon.hpp" #include "med/MedException.hpp" #include "med/ScanParser.hpp" #include "med/MedTypes.hpp" #include "med/MemOperator.hpp" Pem::Pem(size_t size, MemIO* memio) : Mem(size) { this->memio = memio; scanType = ScanType::Unknown; } Pem::Pem(Address addr, size_t size, MemIO* memio) : Mem(size) { this->memio = memio; setAddress(addr); scanType = ScanType::Unknown; } Pem::~Pem() {} string Pem::bytesToString(Byte* buf, const string& scanType) { if (scanType == SCAN_TYPE_CUSTOM) { return memToString(buf, SCAN_TYPE_INT_8); } return memToString(buf, scanType); } string Pem::getValue(const string& scanType) { MemPtr pem = memio->read(address, size); if (!pem) { return "(invalid)"; } Byte* buf = pem->getData(); return Pem::bytesToString(buf, scanType); } string Pem::getValue() { string scanType = getScanType(); return getValue(scanType); } BytePtr Pem::getValuePtr(int n) { int size = n > 0 ? n : this->size; BytePtr buf(new Byte[size]); MemPtr pem = memio->read(address, size); if (!pem) { return NULL; } memcpy(buf.get(), pem->getData(), size); return buf; } string Pem::getScanType() { return scanTypeToString(scanType); } SizedBytes Pem::stringToBytes(const string& value, const string& scanType) { // If scanType is string, it will just copy all if (scanType == SCAN_TYPE_STRING) { int size = MAX_STRING_SIZE; Byte* buf = new Byte[size]; sprintf((char*)buf, "%s", value.c_str()); int length = strlen((char*)buf); BytePtr data(new Byte[length]); memcpy(data.get(), buf, length); delete[] buf; return SizedBytes(data, length); } else { // Allows parse comma vector<string> tokens = ScanParser::getValues(value); int size = scanTypeToSize(stringToScanType(scanType)); BytePtr data(new Byte[size * tokens.size()]); Byte* pointer = data.get(); for (size_t i = 0; i < tokens.size(); i++) { stringToMemory(tokens[i], stringToScanType(scanType), pointer); pointer += size; } return SizedBytes(data, size * tokens.size()); } } void Pem::setValue(const string& value, const string& scanType) { SizedBytes buffer = Pem::stringToBytes(value, scanType); Byte* bytes = buffer.getBytes(); int size = buffer.getSize(); MemPtr mem(new Mem(size)); mem->setAddress(address); memcpy(mem->getData(), bytes, size); memio->write(address, mem, size); } void Pem::setScanType(const string& scanType) { this->scanType = stringToScanType(scanType); size_t newSize; Byte* newData; Byte* temp; if (this->scanType == ScanType::String) { newSize = MAX_STRING_SIZE; newData = new Byte[newSize]; } else { newSize = scanTypeToSize(this->scanType); newData = new Byte[newSize]; } temp = data; data = newData; size = newSize; delete[] temp; } MemIO* Pem::getMemIO() { return memio; } void Pem::rememberValue(const string& value, const string& scanType) { rememberedValue = Pem::stringToBytes(value, scanType); } void Pem::rememberValue(Byte* value, size_t size) { rememberedValue = SizedBytes(value, size); } string Pem::recallValue(const string& scanType) { if (rememberedValue.isEmpty()) { return ""; } return Pem::bytesToString(rememberedValue.getBytes(), scanType); } Byte* Pem::recallValuePtr() { return rememberedValue.getBytes(); } PemPtr Pem::convertToPemPtr(MemPtr mem, MemIO* memio) { return PemPtr(new Pem(mem->getAddress(), mem->getSize(), memio)); }
23.98
76
0.671115
OmniNegro123
c1eaf17fe306911b6779f75d8a108fd00525c34f
5,538
cpp
C++
Turtle/Event.cpp
mirek-fidler/Turtle
fd413460c3d92c9a85fc620f6f3db50d96f3be2f
[ "BSD-2-Clause" ]
2
2021-01-07T20:30:16.000Z
2021-02-11T21:33:07.000Z
Turtle/Event.cpp
mirek-fidler/Turtle
fd413460c3d92c9a85fc620f6f3db50d96f3be2f
[ "BSD-2-Clause" ]
null
null
null
Turtle/Event.cpp
mirek-fidler/Turtle
fd413460c3d92c9a85fc620f6f3db50d96f3be2f
[ "BSD-2-Clause" ]
null
null
null
#include "Turtle.h" #define LLOG(x) // RLOG(x) #define LDUMP(x) // RDUMP(x) #define LTIMING(x) namespace Upp { static bool sQuit; // Ctrl::IsEndSession() would be much better to use had it been implemented. static BiVector<String> sEventQueue; Point ReadPoint(CParser& p) { Point pt; pt.x = p.ReadInt(); pt.y = p.ReadInt(); return pt; } bool TurtleServer::ProcessEvent(bool *quit) { if(!IsWaitingEvent()) return false; while(sEventQueue.GetCount() >= 2 && *sEventQueue[0] == 'M' && *sEventQueue[1] == 'M') sEventQueue.DropHead(); // MouseMove compression String event = sEventQueue[0]; sEventQueue.DropHead(); LLOG("Processing event " << event); CParser p(event); try { if(p.Id("i")) { ResetImageCache(); } else if(p.Id("R")) { Resize(p); } else if(p.Id("M")) { MouseMove(p); } else if(p.Id("W")) { MouseWheel(p); } else if(p.Id("I")) { mousein = true; } else if(p.Id("O")) { mousebuttons = 0; mousein = false; } else if(p.Id("D")) { MouseButton(Ctrl::DOWN, p); } else if(p.Id("U")) { MouseButton(Ctrl::UP, p); } else if(p.Id("K")) { KeyDown(event, p); } else if(p.Id("k")) { KeyUp(event, p); } else if(p.Id("C")) { KeyPress(event, p); } } catch(const CParser::Error&) { LLOG("ProcessEvent() -> Parser error"); } return true; } void TurtleServer::WaitEvent(int ms) { websocket.Do(); SocketWaitEvent we; websocket.AddTo(we); we.Wait(ms); } bool TurtleServer::IsWaitingEvent() { websocket.Do(); String s = websocket.Receive(); if(websocket.IsClosed()) { Ctrl::EndSession(); sQuit = true; // Ugly.. return false; } if(s.GetCount() == 0) return sEventQueue.GetCount(); LLOG("Received data " << s); StringStream ss(s); while(!ss.IsEof()) { String s = ss.GetLine(); CParser p(s); try { if(p.Id("S")) { uint32 l = p.ReadNumber(); uint32 h = p.ReadNumber(); recieved_update_serial = MAKEQWORD(l, h); stat_client_ms = p.ReadNumber(); } else sEventQueue.AddTail(s); } catch(const CParser::Error&) { LLOG("IsWaitingEvent() -> Parser error."); } } if(recieved_update_serial == serial_0) { serial_0 = 0; stat_roundtrip_ms = msecs() - serial_time0; serial_time0 = Null; } if(websocket.IsError()) LLOG("ERROR: " << websocket.GetErrorDesc()); return sEventQueue.GetCount(); } void TurtleServer::SyncClient() { while(recieved_update_serial < update_serial && !sQuit) { Ctrl::GuiSleep(10); IsWaitingEvent(); } } void TurtleServer::MouseButton(dword event, CParser& p) { auto MaxDistance = [](Point a, Point b) -> int { return IsNull(a) ? INT_MAX : max(abs(a.x - b.x), abs(a.y - b.y)); }; static int64 sMouseDownTime; static Point sMouseDownPos; int bt = p.ReadInt(); Point pt = ReadPoint(p); int64 tm = p.ReadInt64(); dword down = (dword) event == Ctrl::DOWN; dword bt2 = decode(bt, 0, (1 << 0), 2, (1 << 1), (1 << 2)); mousebuttons = (mousebuttons & ~bt2) | ((dword)-(int32)down & bt2); // Toggles button flags. if(event == Ctrl::DOWN) { if(MaxDistance(sMouseDownPos, pt) < GUI_DragDistance() && tm - sMouseDownTime < 800) { event = Ctrl::DOUBLE; sMouseDownTime = 0; } else { sMouseDownPos = pt; sMouseDownTime = tm; } } ReadModifierKeys(p); Ctrl::DoMouseFB(decode(bt, 0, Ctrl::LEFT, 2, Ctrl::RIGHT, Ctrl::MIDDLE) | event, pt, 0); } void TurtleServer::MouseWheel(CParser& p) { double w = p.ReadDouble(); Point pt = ReadPoint(p); ReadModifierKeys(p); Ctrl::DoMouseFB(Ctrl::MOUSEWHEEL, pt, w < 0 ? 120 : -120); } void TurtleServer::MouseMove(CParser& p) { Point pt = ReadPoint(p); ReadModifierKeys(p); Ctrl::DoMouseFB(Ctrl::MOUSEMOVE, pt, 0); } void TurtleServer::KeyDown(const String& event, CParser& p) { int count = 1; int code = p.ReadInt(); int which = p.ReadInt(); for(;;) { if(sEventQueue.GetCount() && sEventQueue[0] == event) { // Chrome autorepeat sEventQueue.DropHead(); count++; } else if(sEventQueue.GetCount() >= 2 && *sEventQueue[0] == 'C' && sEventQueue[1] == event) { // Firefox autorepeat String h = sEventQueue[0]; sEventQueue.DropHead(); sEventQueue.DropHead(); sEventQueue.AddHead(h); count++; } else break; } ReadModifierKeys(p); Ctrl::DoKeyFB(TranslateWebKeyToK(which), count); } void TurtleServer::KeyUp(const String& event, CParser& p) { int code = p.ReadInt(); int which = p.ReadInt(); ReadModifierKeys(p); Ctrl::DoKeyFB(TranslateWebKeyToK(which) | K_KEYUP, 1); } void TurtleServer::KeyPress(const String& event, CParser& p) { int code = p.ReadInt(); int which = p.ReadInt(); ReadModifierKeys(p); while(sEventQueue.GetCount() && sEventQueue[0] == event) // 'K_'s are not there anymore sEventQueue.DropHead(); if(which && !GetAlt() && !GetCtrl() && findarg(which, 0x09, 0x0D, 0x20) < 0) Ctrl::DoKeyFB(which, 1); } void TurtleServer::Resize(CParser& p) { desktopsize = ReadPoint(p); SetCanvasSize(desktopsize); Ctrl::SetDesktopSize(desktopsize); } void TurtleServer::SetMouseCursor(const Image& image) { int64 q = image.GetAuxData(); if(q) { Put8(STD_CURSORIMAGE); Put8(clamp((int)q, 1, 16)); } else { Point pt = image.GetHotSpot(); String h; h << "url('data:image/png;base64," << Base64Encode(PNGEncoder().SaveString(image)) << "') " << pt.x << ' ' << pt.y << ", default"; Put8(SETCURSORIMAGE); Put16(0); // TODO: Cursor cache Put(h); Put8(MOUSECURSOR); Put16(0); // TODO: Cursor cache } } }
18.646465
95
0.62333
mirek-fidler
c1eb064191533e5c5cc156e350e664c2772c8c64
297
hpp
C++
hiro/reference/popup-menu.hpp
mp-lee/higan
c38a771f2272c3ee10fcb99f031e982989c08c60
[ "Intel", "ISC" ]
38
2018-04-05T05:00:05.000Z
2022-02-06T00:02:02.000Z
hiro/reference/popup-menu.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
1
2018-04-29T19:45:14.000Z
2018-04-29T19:45:14.000Z
hiro/reference/popup-menu.hpp
ameer-bauer/higan-097
a4a28968173ead8251cfa7cd6b5bf963ee68308f
[ "Info-ZIP" ]
8
2018-04-16T22:37:46.000Z
2021-02-10T07:37:03.000Z
namespace phoenix { struct pPopupMenu : public pObject { PopupMenu& popupMenu; void append(Action& action); void remove(Action& action); void setVisible(); pPopupMenu(PopupMenu& popupMenu) : pObject(popupMenu), popupMenu(popupMenu) {} void constructor(); void destructor(); }; }
18.5625
80
0.713805
mp-lee
c1eb0c0f4b9c7f7d610f56c1ff3fd0c93f7860fe
1,270
cpp
C++
Project_Euler/015/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
2
2018-11-08T05:57:22.000Z
2018-11-08T05:57:27.000Z
Project_Euler/015/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
Project_Euler/015/sol.cpp
Zovube/Tasks-solutions
fde056189dd5f630197d0516d3837044bc339e49
[ "MIT" ]
null
null
null
// simple dp #include<bits/stdc++.h> using namespace std; #define PI acos(-1) #define fi first #define se second #define pb push_back #define sz(a) (int)(a).size() #define all(c) (c).begin(), (c).end() #define TIMESTAMP fprintf(stderr, "Execution time: %.3lf s.\n", 1.0*clock()/CLOCKS_PER_SEC) typedef long long ll; typedef long double ld; typedef vector<int> vi; typedef vector<ll> vll; typedef pair <int, int> pii; typedef vector <vi> vvi; typedef vector <pii> vpii; typedef vector<string> vs; const int INF = 1e9; const int MAXN = 500 + 9; const int MOD = 1e9 + 7; bool used[MAXN]; int n, m; ll dp[MAXN][MAXN]; void precalc() { for(int i = 1; i < MAXN; i++) { dp[i][0] = dp[0][i] = 1; } for(int i = 1; i < MAXN; i++) { for(int j = 1; j < MAXN; j++) { dp[i][j] = (dp[i - 1][j] + dp[i][j - 1]) % MOD; } } } void solve() { cin >> n >> m; cout << dp[n][m] << endl; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); #ifdef LOCAL freopen("xxx.in", "r", stdin); freopen("xxx.out", "w", stdout); #else //freopen("xxx.in", "r", stdin); //freopen("xxx.out", "w", stdout); #endif precalc(); int t; cin >> t; while(t--) { solve(); } return 0; }
19.84375
91
0.549606
Zovube
c1ed592b965e247d6105e416c0e74d888d2993f8
17,878
cc
C++
tensorflow/core/kernels/sparse_fill_empty_rows_op.cc
AdaAlarm/tensorflow
e0db063159751276a92d88a4ad6d481b1199318c
[ "Apache-2.0" ]
10
2021-05-25T17:43:04.000Z
2022-03-08T10:46:09.000Z
tensorflow/core/kernels/sparse_fill_empty_rows_op.cc
AdaAlarm/tensorflow
e0db063159751276a92d88a4ad6d481b1199318c
[ "Apache-2.0" ]
1,056
2019-12-15T01:20:31.000Z
2022-02-10T02:06:28.000Z
tensorflow/core/kernels/sparse_fill_empty_rows_op.cc
AdaAlarm/tensorflow
e0db063159751276a92d88a4ad6d481b1199318c
[ "Apache-2.0" ]
6
2016-09-07T04:00:15.000Z
2022-01-12T01:47:38.000Z
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #define EIGEN_USE_THREADS #include "tensorflow/core/kernels/sparse_fill_empty_rows_op.h" #include <algorithm> #include <numeric> #include <unordered_map> #include <utility> #include <vector> #include "tensorflow/core/framework/op_kernel.h" #include "tensorflow/core/framework/register_types.h" #include "tensorflow/core/framework/tensor.h" #include "tensorflow/core/framework/tensor_util.h" #include "tensorflow/core/framework/types.h" #include "tensorflow/core/lib/gtl/inlined_vector.h" #include "tensorflow/core/util/sparse/sparse_tensor.h" namespace tensorflow { using CPUDevice = Eigen::ThreadPoolDevice; using GPUDevice = Eigen::GpuDevice; namespace functor { template <typename T, typename Tindex> struct SparseFillEmptyRows<CPUDevice, T, Tindex> { Status operator()(OpKernelContext* context, const Tensor& default_value_t, const Tensor& indices_t, const Tensor& values_t, const Tensor& dense_shape_t, typename AsyncOpKernel::DoneCallback done) { (void)done; // Unused (only used in GPU implementation) const int kOutputIndicesOutput = 0; const int kOutputValuesOutput = 1; const int kEmptyRowIndicatorOutput = 2; const int kReverseIndexMapOutput = 3; const T& default_value = default_value_t.scalar<T>()(); const auto indices = indices_t.matrix<Tindex>(); const auto values = values_t.vec<T>(); const auto dense_shape = dense_shape_t.vec<Tindex>(); const Tindex N = indices_t.shape().dim_size(0); const Tindex dense_rows = dense_shape(0); bool* empty_row_indicator = nullptr; if (context->output_required(kEmptyRowIndicatorOutput)) { Tensor* empty_row_indicator_t = nullptr; TF_RETURN_IF_ERROR(context->allocate_output(kEmptyRowIndicatorOutput, TensorShape({dense_rows}), &empty_row_indicator_t)); empty_row_indicator = empty_row_indicator_t->vec<bool>().data(); } Tindex* reverse_index_map = nullptr; if (context->output_required(kReverseIndexMapOutput)) { Tensor* reverse_index_map_t = nullptr; TF_RETURN_IF_ERROR(context->allocate_output( kReverseIndexMapOutput, TensorShape({N}), &reverse_index_map_t)); reverse_index_map = reverse_index_map_t->vec<Tindex>().data(); } int rank = indices_t.shape().dim_size(1); if (dense_rows == 0) { if (N != 0) { return errors::InvalidArgument( "Received SparseTensor with dense_shape[0] = 0 but " "indices.shape[0] = ", N); } Tensor* output_indices_t; TensorShape output_indices_shape({0, rank}); TF_RETURN_IF_ERROR(context->allocate_output( kOutputIndicesOutput, output_indices_shape, &output_indices_t)); Tensor* output_values_t; TF_RETURN_IF_ERROR(context->allocate_output( kOutputValuesOutput, TensorShape({0}), &output_values_t)); // Exit early, nothing more to do. return Status::OK(); } bool rows_are_ordered = true; Tindex last_indices_row = 0; std::vector<Tindex> csr_offset(dense_rows, 0); for (int i = 0; i < N; ++i) { const Tindex row = indices(i, 0); if (row < 0 || row >= dense_rows) { return errors::InvalidArgument("indices(", i, ", 0) is invalid: ", row, " >= ", dense_rows); } ++csr_offset[row]; rows_are_ordered = rows_are_ordered & (row >= last_indices_row); last_indices_row = row; } bool all_rows_full = true; for (int row = 0; row < dense_rows; ++row) { // csr_offset here describes the number of elements in this dense row bool row_empty = (csr_offset[row] == 0); if (empty_row_indicator) { empty_row_indicator[row] = row_empty; } all_rows_full = all_rows_full & !row_empty; // In filled version, each row has at least one element. csr_offset[row] = std::max(csr_offset[row], Tindex{1}); // Update csr_offset to represent the number of elements up to and // including dense_row + 1: // csr_offset(0) == #{elements of row 0} // csr_offset(1) == #{elements of row 1} + #{elements of row 0} // .. // csr_offset(i) == starting index for elements in row i + 1. if (row > 0) { csr_offset[row] += csr_offset[row - 1]; } } if (all_rows_full && rows_are_ordered) { context->set_output(kOutputIndicesOutput, indices_t); context->set_output(kOutputValuesOutput, values_t); if (reverse_index_map) { for (Tindex i = 0; i < N; ++i) { reverse_index_map[i] = i; } } } else { Tensor* output_indices_t; const Tindex N_full = csr_offset[dense_rows - 1]; TensorShape output_indices_shape({N_full, rank}); TF_RETURN_IF_ERROR(context->allocate_output( kOutputIndicesOutput, output_indices_shape, &output_indices_t)); auto output_indices = output_indices_t->matrix<Tindex>(); Tensor* output_values_t; TF_RETURN_IF_ERROR(context->allocate_output( kOutputValuesOutput, TensorShape({N_full}), &output_values_t)); auto output_values = output_values_t->vec<T>(); std::vector<Tindex> filled_count(dense_rows, 0); // Fill in values for rows that are not missing for (Tindex i = 0; i < N; ++i) { const Tindex row = indices(i, 0); Tindex& offset = filled_count[row]; const Tindex output_i = ((row == 0) ? 0 : csr_offset[row - 1]) + offset; offset++; // Increment the filled count for this row. std::copy_n(&indices(i, 0), rank, &output_indices(output_i, 0)); output_values(output_i) = values(i); // We'll need this reverse index map to backprop correctly. if (reverse_index_map) { reverse_index_map[i] = output_i; } } // Fill in values for rows that are missing for (Tindex row = 0; row < dense_rows; ++row) { const Tindex row_count = filled_count[row]; if (row_count == 0) { // We haven't filled this row const Tindex starting_index = (row == 0) ? 0 : csr_offset[row - 1]; // Remaining index values were set to zero already. // Just need to set the row index in the right location. output_indices(starting_index, 0) = row; for (Tindex col = 1; col < rank; ++col) { output_indices(starting_index, col) = 0; } output_values(starting_index) = default_value; } } } return Status::OK(); } }; } // namespace functor namespace { template <typename Device, typename T, typename Tindex> void SparseFillEmptyRowsOpImpl(OpKernelContext* context, AsyncOpKernel::DoneCallback done = nullptr) { // Note that setting this empty lambda as the default parameter value directly // can cause strange compiler/linker errors, so we do it like this instead. if (!done) { done = [] {}; } const int kIndicesInput = 0; const int kValuesInput = 1; const int kDenseShapeInput = 2; const int kDefaultValueInput = 3; const Tensor& indices_t = context->input(kIndicesInput); const Tensor& values_t = context->input(kValuesInput); const Tensor& dense_shape_t = context->input(kDenseShapeInput); const Tensor& default_value_t = context->input(kDefaultValueInput); OP_REQUIRES_ASYNC( context, TensorShapeUtils::IsVector(dense_shape_t.shape()), errors::InvalidArgument("dense_shape must be a vector, saw: ", dense_shape_t.shape().DebugString()), done); OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsMatrix(indices_t.shape()), errors::InvalidArgument("indices must be a matrix, saw: ", indices_t.shape().DebugString()), done); OP_REQUIRES_ASYNC(context, TensorShapeUtils::IsVector(values_t.shape()), errors::InvalidArgument("values must be a vector, saw: ", values_t.shape().DebugString()), done); OP_REQUIRES_ASYNC( context, TensorShapeUtils::IsScalar(default_value_t.shape()), errors::InvalidArgument("default_value must be a scalar, saw: ", default_value_t.shape().DebugString()), done); // TODO(ebrevdo): add shape checks between values, indices, // Also add check that dense rank > 0. OP_REQUIRES_ASYNC(context, dense_shape_t.NumElements() != 0, errors::InvalidArgument("Dense shape cannot be empty."), done); using FunctorType = functor::SparseFillEmptyRows<Device, T, Tindex>; OP_REQUIRES_OK_ASYNC(context, FunctorType()(context, default_value_t, indices_t, values_t, dense_shape_t, done), done); } } // namespace template <typename Device, typename T, typename Tindex> class SparseFillEmptyRowsOp : public OpKernel { public: explicit SparseFillEmptyRowsOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { SparseFillEmptyRowsOpImpl<Device, T, Tindex>(context); } }; #define REGISTER_KERNELS(D, T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_##D) \ .HostMemory("dense_shape") \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsOp<D##Device, T, Tindex>) #define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T, int64) TF_CALL_ALL_TYPES(REGISTER_CPU_KERNELS); #undef REGISTER_CPU_KERNELS #undef REGISTER_KERNELS #if 0 && (GOOGLE_CUDA || TENSORFLOW_USE_ROCM) // The GPU implementation is async because it requires waiting for a // host->device memcpy before the output is allocated (similar to // SegmentSumGPUOp). template <typename T, typename Tindex> class SparseFillEmptyRowsGPUOp : public AsyncOpKernel { public: explicit SparseFillEmptyRowsGPUOp(OpKernelConstruction* context) : AsyncOpKernel(context) {} void ComputeAsync(OpKernelContext* context, DoneCallback done) override { SparseFillEmptyRowsOpImpl<GPUDevice, T, Tindex>(context, done); } }; #define REGISTER_KERNELS(T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRows") \ .Device(DEVICE_GPU) \ .HostMemory("dense_shape") \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsGPUOp<T, Tindex>) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T, Tindex) \ template <> \ Status SparseFillEmptyRows<GPUDevice, T, Tindex>::operator()( \ OpKernelContext* context, const Tensor& default_value_t, \ const Tensor& indices_t, const Tensor& values_t, \ const Tensor& dense_shape_t, typename AsyncOpKernel::DoneCallback done); \ extern template struct SparseFillEmptyRows<GPUDevice, T, Tindex>; #define DECLARE_GPU_SPEC_INT64(T) DECLARE_GPU_SPEC(T, int64) TF_CALL_POD_TYPES(DECLARE_GPU_SPEC_INT64) #undef DECLARE_GPU_SPEC_INT64 #undef DECLARE_GPU_SPEC } // namespace functor #define REGISTER_KERNELS_TINDEX(T) REGISTER_KERNELS(T, int64) TF_CALL_POD_TYPES(REGISTER_KERNELS_TINDEX) #undef REGISTER_KERNELS_TINDEX #undef REGISTER_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM namespace functor { template <typename T, typename Tindex> struct SparseFillEmptyRowsGrad<CPUDevice, T, Tindex> { Status operator()(OpKernelContext* context, typename TTypes<Tindex>::ConstVec reverse_index_map, typename TTypes<T>::ConstVec grad_values, typename TTypes<T>::Vec d_values, typename TTypes<T>::Scalar d_default_value) { const CPUDevice& device = context->eigen_device<CPUDevice>(); const Tindex N = reverse_index_map.dimension(0); const Tindex N_full = grad_values.dimension(0); T& d_default_value_scalar = d_default_value(); d_default_value_scalar = T(); Tensor visited_t; TF_RETURN_IF_ERROR( context->allocate_temp(DT_BOOL, TensorShape({N_full}), &visited_t)); auto visited = visited_t.vec<bool>(); visited.device(device) = visited.constant(false); for (int i = 0; i < N; ++i) { // Locate the index of the output of the forward prop associated // with this location in the input of the forward prop. Copy // the gradient into it. Mark it as visited. int64 reverse_index = reverse_index_map(i); if (reverse_index < 0 || reverse_index >= N_full) { return errors::InvalidArgument( "Elements in reverse index must be in [0, ", N_full, ") but got ", reverse_index); } d_values(i) = grad_values(reverse_index); visited(reverse_index) = true; } for (int j = 0; j < N_full; ++j) { // The default value gradient gets the accumulated remainder of // the backprop values (since the default value was used to fill // in these slots in the forward calculation). if (!visited(j)) { d_default_value_scalar += grad_values(j); } } return Status::OK(); } }; } // namespace functor template <typename Device, typename T, typename Tindex> class SparseFillEmptyRowsGradOp : public OpKernel { public: explicit SparseFillEmptyRowsGradOp(OpKernelConstruction* context) : OpKernel(context) {} void Compute(OpKernelContext* context) override { const Tensor* reverse_index_map_t; const Tensor* grad_values_t; OP_REQUIRES_OK(context, context->input("reverse_index_map", &reverse_index_map_t)); OP_REQUIRES_OK(context, context->input("grad_values", &grad_values_t)); OP_REQUIRES( context, TensorShapeUtils::IsVector(reverse_index_map_t->shape()), errors::InvalidArgument("reverse_index_map must be a vector, saw: ", reverse_index_map_t->shape().DebugString())); OP_REQUIRES(context, TensorShapeUtils::IsVector(grad_values_t->shape()), errors::InvalidArgument("grad_values must be a vector, saw: ", grad_values_t->shape().DebugString())); const auto reverse_index_map = reverse_index_map_t->vec<Tindex>(); const auto grad_values = grad_values_t->vec<T>(); const Tindex N = reverse_index_map_t->shape().dim_size(0); Tensor* d_values_t; OP_REQUIRES_OK(context, context->allocate_output( "d_values", TensorShape({N}), &d_values_t)); auto d_values = d_values_t->vec<T>(); Tensor* d_default_value_t; OP_REQUIRES_OK(context, context->allocate_output("d_default_value", TensorShape({}), &d_default_value_t)); auto d_default_value = d_default_value_t->scalar<T>(); OP_REQUIRES_OK(context, functor::SparseFillEmptyRowsGrad<Device, T, Tindex>()( context, reverse_index_map, grad_values, d_values, d_default_value)); } }; #define REGISTER_KERNELS(D, T, Tindex) \ REGISTER_KERNEL_BUILDER(Name("SparseFillEmptyRowsGrad") \ .Device(DEVICE_##D) \ .TypeConstraint<T>("T"), \ SparseFillEmptyRowsGradOp<D##Device, T, Tindex>) #define REGISTER_CPU_KERNELS(T) REGISTER_KERNELS(CPU, T, int64) TF_CALL_NUMBER_TYPES(REGISTER_CPU_KERNELS); #undef REGISTER_CPU_KERNELS #if 0 && (GOOGLE_CUDA || TENSORFLOW_USE_ROCM) // Forward declarations of the functor specializations for GPU. namespace functor { #define DECLARE_GPU_SPEC(T, Tindex) \ template <> \ Status SparseFillEmptyRowsGrad<GPUDevice, T, Tindex>::operator()( \ OpKernelContext* context, \ typename TTypes<Tindex>::ConstVec reverse_index_map, \ typename TTypes<T>::ConstVec grad_values, \ typename TTypes<T>::Vec d_values, \ typename TTypes<T>::Scalar d_default_value); \ extern template struct SparseFillEmptyRowsGrad<GPUDevice, T, Tindex>; #define DECLARE_GPU_SPEC_INT64(T) DECLARE_GPU_SPEC(T, int64) TF_CALL_REAL_NUMBER_TYPES(DECLARE_GPU_SPEC_INT64); #undef DECLARE_GPU_SPEC_INT64 #undef DECLARE_GPU_SPEC } // namespace functor #define REGISTER_GPU_KERNELS(T) REGISTER_KERNELS(GPU, T, int64) TF_CALL_REAL_NUMBER_TYPES(REGISTER_GPU_KERNELS); #undef REGISTER_GPU_KERNELS #endif // GOOGLE_CUDA || TENSORFLOW_USE_ROCM #undef REGISTER_KERNELS } // namespace tensorflow
40.265766
80
0.639277
AdaAlarm
c1eed8184c2b2aafdf58f16ecf2d8030a13da7e5
611
hpp
C++
lib/STL+/strings/print_basic.hpp
knela96/Game-Engine
06659d933c4447bd8d6c8536af292825ce4c2ab1
[ "Unlicense" ]
3
2018-05-07T19:09:23.000Z
2019-05-03T14:19:38.000Z
deps/stlplus/strings/print_basic.hpp
evpo/libencryptmsg
fa1ea59c014c0a9ce339d7046642db4c80fc8701
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
null
null
null
deps/stlplus/strings/print_basic.hpp
evpo/libencryptmsg
fa1ea59c014c0a9ce339d7046642db4c80fc8701
[ "BSD-2-Clause-FreeBSD", "BSD-3-Clause" ]
null
null
null
#ifndef STLPLUS_PRINT_BASIC #define STLPLUS_PRINT_BASIC //////////////////////////////////////////////////////////////////////////////// // Author: Andy Rushton // Copyright: (c) Southampton University 1999-2004 // (c) Andy Rushton 2004 onwards // License: BSD License, see ../docs/license.html // Utilities for converting printing basic C types //////////////////////////////////////////////////////////////////////////////// #include "print_bool.hpp" #include "print_cstring.hpp" #include "print_float.hpp" #include "print_int.hpp" #include "print_pointer.hpp" #endif
29.095238
80
0.517185
knela96
c1eef41280d3d3c2fab97e760c7765473cf58862
4,015
hpp
C++
include/ulocal/http_request_parser.hpp
metthal/ulocal
882dc159ce23f1c30572b8798f05458541bd67a9
[ "MIT" ]
1
2019-11-05T10:59:14.000Z
2019-11-05T10:59:14.000Z
include/ulocal/http_request_parser.hpp
metthal/ulocal
882dc159ce23f1c30572b8798f05458541bd67a9
[ "MIT" ]
null
null
null
include/ulocal/http_request_parser.hpp
metthal/ulocal
882dc159ce23f1c30572b8798f05458541bd67a9
[ "MIT" ]
null
null
null
#pragma once #include <string> #include <ulocal/http_header_table.hpp> #include <ulocal/http_request.hpp> #include <ulocal/string_stream.hpp> #include <ulocal/url_args.hpp> namespace ulocal { namespace detail { enum class RequestState { Start, StatusLineMethod, StatusLineResource, StatusLineHttpVersion, HeaderName, HeaderValue, Content }; } // namespace detail class HttpRequestParser { public: HttpRequestParser() : _state(detail::RequestState::Start) {} HttpRequestParser(const HttpRequestParser&) = delete; HttpRequestParser(HttpRequestParser&&) noexcept = default; HttpRequestParser& operator=(const HttpRequestParser&) = delete; HttpRequestParser& operator=(HttpRequestParser&&) noexcept = default; std::optional<HttpRequest> parse(StringStream& stream) { bool continue_parsing = true; while (continue_parsing) { switch (_state) { case detail::RequestState::Start: { _method.clear(); _resource.clear(); _http_version.clear(); _header_name.clear(); _header_value.clear(); _headers.clear(); _content.clear(); _content_length = 0; _state = detail::RequestState::StatusLineMethod; break; } case detail::RequestState::StatusLineMethod: { auto [str, found_space] = stream.read_until(' '); _method += str; if (found_space) { _state = detail::RequestState::StatusLineResource; stream.skip(1); } else continue_parsing = false; break; } case detail::RequestState::StatusLineResource: { auto [str, found_space] = stream.read_until(' '); _resource += str; if (found_space) { _state = detail::RequestState::StatusLineHttpVersion; stream.skip(1); } else continue_parsing = false; break; } case detail::RequestState::StatusLineHttpVersion: { auto [str, found_newline] = stream.read_until("\r\n"); _http_version += str; if (found_newline) { _state = detail::RequestState::HeaderName; stream.skip(2); } else continue_parsing = false; break; } case detail::RequestState::HeaderName: { if (stream.as_string_view(2) == "\r\n") { stream.skip(2); _state = detail::RequestState::Content; auto content_length_header = _headers.get_header("content-length"); if (content_length_header) _content_length = content_length_header->get_value_as<std::uint64_t>(); } else if (stream.as_string_view(1) == "\r") { continue_parsing = false; } else { auto [str, found_colon] = stream.read_until(':'); _header_name += str; if (found_colon) { _state = detail::RequestState::HeaderValue; stream.skip(1); } else continue_parsing = false; } break; } case detail::RequestState::HeaderValue: { auto [str, found_newline] = stream.read_until("\r\n"); _header_value += str; if (found_newline) { _state = detail::RequestState::HeaderName; stream.skip(2); _headers.add_header(std::move(_header_name), lstrip(_header_value)); _header_name.clear(); _header_value.clear(); } else continue_parsing = false; break; } case detail::RequestState::Content: { auto str = stream.read(_content_length - _content.length()); _content += str; if (_content.length() == _content_length) { _state = detail::RequestState::Start; return HttpRequest{ std::move(_method), std::move(_resource), std::move(_headers), std::move(_content) }; } else continue_parsing = false; break; } } } stream.realign(); return std::nullopt; } private: detail::RequestState _state; std::string _method, _resource, _http_version, _header_name, _header_value, _content; HttpHeaderTable _headers; std::uint64_t _content_length; }; } // namespace ulocal
23.074713
86
0.637111
metthal
c1efaf1f0e22efa51831b570b21b463797966ad9
9,379
cpp
C++
unpack/src/unpack.cpp
legnaleurc/dvd
0c35a56a2d145bd040b36aa3b72270f90e89dd8c
[ "MIT" ]
null
null
null
unpack/src/unpack.cpp
legnaleurc/dvd
0c35a56a2d145bd040b36aa3b72270f90e89dd8c
[ "MIT" ]
12
2020-03-22T04:11:45.000Z
2022-03-13T12:45:49.000Z
unpack/src/unpack.cpp
legnaleurc/dvd
0c35a56a2d145bd040b36aa3b72270f90e89dd8c
[ "MIT" ]
null
null
null
#include "unpack.hpp" #include <memory> #include <iomanip> #include <archive.h> #include <archive_entry.h> #include <cpprest/http_client.h> #include <cpprest/rawptrstream.h> #include <boost/filesystem.hpp> #include "types.hpp" #include "exception.hpp" #include "text.hpp" const uint64_t CHUNK_SIZE = 65536; class Context { public: Context (uint16_t port, const std::string & id); web::http::http_response & getResponse (); int64_t readChunk (const void ** buffer); int64_t seek (int64_t offset, int whence); void reset (); private: web::uri base; web::uri path; web::http::http_response response; int64_t offset; int64_t length; std::array<uint8_t, CHUNK_SIZE> chunk; }; using ContextHandle = std::shared_ptr<Context>; ArchiveHandle createArchiveReader (ContextHandle context); ArchiveHandle createDiskWriter (); std::string resolvePath (Text & text, const std::string & localPath, const std::string & id, const std::string & entryName); void extractArchive (ArchiveHandle reader, ArchiveHandle writer); web::uri makeBase (uint16_t port); web::uri makePath (const std::string & id); int openCallback (struct archive * handle, void * context); int closeCallback (struct archive * handle, void * context); la_ssize_t readCallback (struct archive * handle, void * context, const void ** buffer); la_int64_t seekCallback (struct archive * handle, void * context, la_int64_t offset, int whence); void unpackTo (uint16_t port, const std::string & id, const std::string & localPath) { ContextHandle context = std::make_shared<Context>(port, id); Text text; auto reader = createArchiveReader(context); auto writer = createDiskWriter(); for (;;) { struct archive_entry * entry = nullptr; int rv = archive_read_next_header(reader.get(), &entry); if (rv == ARCHIVE_EOF) { break; } if (rv != ARCHIVE_OK) { throw ArchiveError(reader, "archive_read_next_header"); } // skip folders auto fileType = archive_entry_filetype(entry); if (fileType & AE_IFDIR) { continue; } const char * entryName = archive_entry_pathname(entry); if (!entryName) { throw EntryError("archive_entry_pathname", "nullptr"); } auto entryPath = resolvePath(text, localPath, id, entryName); rv = archive_entry_update_pathname_utf8(entry, entryPath.c_str()); if (!rv) { throw EntryError("archive_entry_update_pathname_utf8", entryPath); } rv = archive_write_header(writer.get(), entry); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_header"); } extractArchive(reader, writer); rv = archive_write_finish_entry(writer.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_finish_entry"); } } } ArchiveHandle createArchiveReader (ContextHandle context) { int rv = 0; ArchiveHandle handle( archive_read_new(), [](ArchiveHandle::element_type * p) -> void { archive_read_free(p); }); rv = archive_read_support_filter_all(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_support_filter_all"); } rv = archive_read_support_format_all(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_support_format_all"); } rv = archive_read_set_open_callback(handle.get(), openCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_open_callback"); } rv = archive_read_set_close_callback(handle.get(), closeCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_close_callback"); } rv = archive_read_set_read_callback(handle.get(), readCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_read_callback"); } rv = archive_read_set_seek_callback(handle.get(), seekCallback); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_seek_callback"); } rv = archive_read_set_callback_data(handle.get(), context.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_set_callback_data"); } rv = archive_read_open1(handle.get()); if (rv != ARCHIVE_OK) { throw ArchiveError(handle, "archive_read_open1"); } return handle; } ArchiveHandle createDiskWriter () { ArchiveHandle handle( archive_write_disk_new(), [](ArchiveHandle::element_type * p) -> void { archive_write_free(p); }); return handle; } void extractArchive (ArchiveHandle reader, ArchiveHandle writer) { for (;;) { int rv = 0; const void * chunk = nullptr; size_t length = 0; la_int64_t offset = 0; rv = archive_read_data_block(reader.get(), &chunk, &length, &offset); if (rv == ARCHIVE_EOF) { break; } if (rv != ARCHIVE_OK) { throw ArchiveError(reader, "archive_read_data_block"); } rv = archive_write_data_block(writer.get(), chunk, length, offset); if (rv != ARCHIVE_OK) { throw ArchiveError(writer, "archive_write_data_block"); } } } int openCallback (struct archive * handle, void * context) { auto ctx = static_cast<Context *>(context); ctx->reset(); return ARCHIVE_OK; } int closeCallback (struct archive * handle, void * context) { auto ctx = static_cast<Context *>(context); ctx->reset(); return ARCHIVE_OK; } la_ssize_t readCallback (struct archive * handle, void * context, const void ** buffer) { auto ctx = static_cast<Context *>(context); try { return ctx->readChunk(buffer); } catch (std::exception & e) { fprintf(stderr, "readCallback %s\n", e.what()); return ARCHIVE_FATAL; } } la_int64_t seekCallback (struct archive * handle, void * context, la_int64_t offset, int whence) { auto ctx = static_cast<Context *>(context); auto rv = ctx->seek(offset, whence); if (rv < 0) { return ARCHIVE_FATAL; } return rv; } web::uri makeBase (uint16_t port) { web::uri_builder builder; builder.set_scheme("http"); builder.set_host("localhost"); builder.set_port(port); return builder.to_uri(); } web::uri makePath (const std::string & id) { std::ostringstream sout; sout << "/api/v1/nodes/" << id << "/stream"; web::uri_builder builder; builder.set_path(sout.str()); return builder.to_uri(); } std::string resolvePath (Text & text, const std::string & localPath, const std::string & id, const std::string & entryName) { auto newEntryName = text.toUtf8(entryName); boost::filesystem::path path = localPath; path /= id; path /= newEntryName; return path.string(); } Context::Context (uint16_t port, const std::string & id) : base(makeBase(port)) , path(makePath(id)) , response() , offset(0) , length(-1) , chunk() {} web::http::http_response & Context::getResponse () { auto status = this->response.status_code(); if (status == web::http::status_codes::OK || status == web::http::status_codes::PartialContent) { return this->response; } web::http::http_request request; request.set_method(web::http::methods::GET); request.set_request_uri(this->path); if (this->length >= 0) { std::ostringstream sout; sout << "bytes=" << this->offset << "-" << (this->length - 1); request.headers().add("Range", sout.str()); } web::http::client::http_client_config cfg; cfg.set_timeout(std::chrono::minutes(1)); web::http::client::http_client client(this->base, cfg); this->response = client.request(request).get(); status = this->response.status_code(); if (status == web::http::status_codes::OK) { this->length = this->response.headers().content_length(); } else if (status != web::http::status_codes::PartialContent) { throw HttpError(status, this->response.reason_phrase()); } return this->response; } int64_t Context::readChunk (const void ** buffer) { using Buffer = Concurrency::streams::rawptr_buffer<uint8_t>; auto & response = this->getResponse(); Buffer glue(&this->chunk[0], CHUNK_SIZE); auto length = response.body().read(glue, CHUNK_SIZE).get(); *buffer = &this->chunk[0]; this->offset += length; return length; } int64_t Context::seek (int64_t offset, int whence) { this->response = web::http::http_response(); switch (whence) { case SEEK_SET: this->offset = offset; break; case SEEK_CUR: this->offset += offset; break; case SEEK_END: if (this->length < 0) { return -1; } this->offset = this->length + offset; break; default: return -1; } return this->offset; } void Context::reset () { this->response = web::http::http_response(); this->offset = 0; this->length = -1; }
27.748521
80
0.624693
legnaleurc
c1f96a7f659ea493bcef1b4a2b79323f2082816b
3,568
hpp
C++
src/DoxygenScraper.hpp
StratifyLabs/dox2md
e09f8ae9a2d2fe86fb87aeb8da13b83eddd5157b
[ "MIT" ]
null
null
null
src/DoxygenScraper.hpp
StratifyLabs/dox2md
e09f8ae9a2d2fe86fb87aeb8da13b83eddd5157b
[ "MIT" ]
null
null
null
src/DoxygenScraper.hpp
StratifyLabs/dox2md
e09f8ae9a2d2fe86fb87aeb8da13b83eddd5157b
[ "MIT" ]
null
null
null
#ifndef DOXYGENSCRAPER_HPP #define DOXYGENSCRAPER_HPP #include "ApplicationPrinter.hpp" #include <sapi/var.hpp> class DoxygenScraperKey { public: DoxygenScraperKey(const String &key, const String &kind, bool is_array) { m_key = key; m_kind = kind; m_is_array = is_array; } const String &key() const { return m_key; } const String &kind() const { return m_kind; } bool is_array() const { return m_is_array; } private: String m_key; String m_kind; bool m_is_array = false; }; class DoxygenScraperObject { public: DoxygenScraperObject(const String &name) { m_name = name; } bool operator==(const DoxygenScraperObject &a) const { return m_name == a.m_name; } void add_key(const String &key, const String &kind, bool is_array = false) { for (size_t i = 0; i < m_keys.count(); i++) { if (m_keys.at(i).key() == key) { // key already exists return; } } m_keys.push_back(DoxygenScraperKey(key, kind, is_array)); } const String &name() const { return m_name; } String constructors() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); if (key.is_array()) { result += " {\n"; result += " JsonArray json_array = object.at(\"" + key.key() + "\").to_array();\n"; result += " for(u32 i=0; i < json_array.count(); i++){\n"; result += " m_" + translate_name(output_key) + ".push_back(" + key.kind() + "(json_array.at(i).to_object()));\n"; result += " }\n"; result += " }\n"; } else if (key.kind() == "String") { result += " m_" + translate_name(output_key) + " = object.at(\"" + key.key() + "\").to_string();\n"; } else { result += " m_" + translate_name(output_key) + " = " + key.kind() + "(object.at(\"" + key.key() + "\").to_object());\n"; } } return result; } String accessors() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); result += " const " + key.kind() + "& " + translate_name(output_key) + "() const { return m_" + translate_name(output_key) + "; }\n"; } return result; } String members() const { String result; for (auto const &key : m_keys) { String output_key = to_output_key(key.key()); if (key.is_array()) { result += " Vector<" + key.kind() + "> m_" + translate_name(output_key) + ";\n"; } else { result += " " + key.kind() + " m_" + translate_name(output_key) + ";\n"; } } return result; } static String translate_name(const String &name, bool is_class = false); const Vector<DoxygenScraperKey> &keys() const { return m_keys; } private: String to_output_key(const String &key) const { String result = key; result.replace(String::ToErase("@"), String::ToInsert("a_")); result.replace(String::ToErase("#"), String::ToInsert("h_")); result.replace(String::ToErase(":"), String::ToInsert("_")); return result; } String m_name; Vector<DoxygenScraperKey> m_keys; }; class DoxygenScraper : public ApplicationPrinter { public: DoxygenScraper(); void generate_code(const String &file); private: int generate_code_object( const String &object_key, const JsonObject &object, int depth); Vector<DoxygenScraperObject> m_objects; }; #endif // DOXYGENSCRAPER_HPP
28.31746
80
0.584361
StratifyLabs
c1f9f7513a2a54aedbe9b6e87fb09dc7446d4a19
2,304
cpp
C++
src/test/interface/diagnose_test.cpp
danluu/cmdstan
7f96708bfbe6c3b8f716aacd2e7053099158a7aa
[ "BSD-3-Clause" ]
null
null
null
src/test/interface/diagnose_test.cpp
danluu/cmdstan
7f96708bfbe6c3b8f716aacd2e7053099158a7aa
[ "BSD-3-Clause" ]
null
null
null
src/test/interface/diagnose_test.cpp
danluu/cmdstan
7f96708bfbe6c3b8f716aacd2e7053099158a7aa
[ "BSD-3-Clause" ]
null
null
null
#include <fstream> #include <sstream> #include <gtest/gtest.h> #include <test/utility.hpp> using cmdstan::test::get_path_separator; using cmdstan::test::run_command; using cmdstan::test::run_command_output; TEST(CommandDiagnose, corr_gauss) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "corr_gauss_output.csv"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/corr_gauss.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); } TEST(CommandDiagnose, eight_schools) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "eight_schools_output.csv"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/eight_schools.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); } TEST(CommandDiagnose, mix) { std::string path_separator; path_separator.push_back(get_path_separator()); std::string command = "bin" + path_separator + "diagnose"; std::string csv_file = "src" + path_separator + "test" + path_separator + "interface" + path_separator + "example_output" + path_separator + "mix_output.*"; run_command_output out = run_command(command + " " + csv_file); ASSERT_FALSE(out.hasError) << "\"" << out.command << "\" quit with an error"; std::ifstream expected_output("src/test/interface/example_output/mix.nom"); std::stringstream ss; ss << expected_output.rdbuf(); EXPECT_EQ(ss.str(), out.output); }
29.538462
87
0.692708
danluu
c1fa62ee8eb65bd86710c7feb664722db9d09a5f
9,908
hpp
C++
ql/experimental/credit/defaultevent.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
3,358
2015-12-18T02:56:17.000Z
2022-03-31T02:42:47.000Z
ql/experimental/credit/defaultevent.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
965
2015-12-21T10:35:28.000Z
2022-03-30T02:47:00.000Z
ql/experimental/credit/defaultevent.hpp
jiangjiali/QuantLib
37c98eccfa18a95acb1e98b276831641be92b38e
[ "BSD-3-Clause" ]
1,663
2015-12-17T17:45:38.000Z
2022-03-31T07:58:29.000Z
/* -*- mode: c++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* Copyright (C) 2009 StatPro Italia srl Copyright (C) 2009 Jose Aparicio This file is part of QuantLib, a free-software/open-source library for financial quantitative analysts and developers - http://quantlib.org/ QuantLib is free software: you can redistribute it and/or modify it under the terms of the QuantLib license. You should have received a copy of the license along with this program; if not, please email <quantlib-dev@lists.sf.net>. The license is also available online at <http://quantlib.org/license.shtml>. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the license for more details. */ /*! \file defaultevent.hpp \brief Classes for default-event description. */ #ifndef quantlib_default_event_hpp #define quantlib_default_event_hpp #include <ql/event.hpp> #include <ql/currency.hpp> #include <ql/math/comparison.hpp> #include <ql/experimental/credit/defaulttype.hpp> #include <ql/experimental/credit/defaultprobabilitykey.hpp> #include <map> namespace QuantLib { /** @class DefaultEvent @brief Credit event on a bond of a certain seniority(ies)/currency Represents a credit event affecting all bonds with a given \ seniority and currency. It assumes that all such bonds suffer \ the event simultaneously. Some events affect all seniorities and this has to be encoded through a different set of events of the same event type. The event is an actual realization, not a contractual reference, as such it contains only an atomic type. */ class DefaultEvent : public Event { public: class DefaultSettlement : public Event { public: friend class DefaultEvent; protected: /*! Default settlement events encode the settlement date and the recovery rates for the affected seniorities. Specific events might require different sets of recoveries to be present. The way these objects are constructed is a prerogative of the particular event class. */ DefaultSettlement(const Date& date, const std::map<Seniority, Real>& recoveryRates); /*! When NoSeniority is passed all seniorities are assumed to have settled to the recovery passed. */ DefaultSettlement(const Date& date = Date(), Seniority seniority = NoSeniority, Real recoveryRate = 0.4); public: Date date() const override; /*! Returns the recovery rate of a default event which has already settled. */ Real recoveryRate(Seniority sen) const; void accept(AcyclicVisitor&) override; private: Date settlementDate_; //! Realized recovery rates std::map<Seniority, Real> recoveryRates_; }; private: // for some reason, gcc chokes on the default parameter below // unless we use the typedef typedef std::map<Seniority, Real> rate_map; public: /*! Credit event with optional settlement information. Represents a credit event that has taken place. Realized events are of an atomic type. If the settlement information is given seniorities present are the seniorities/bonds affected by the event. */ DefaultEvent(const Date& creditEventDate, const DefaultType& atomicEvType, Currency curr, Seniority bondsSen, // Settlement information: const Date& settleDate = Null<Date>(), const std::map<Seniority, Real>& recoveryRates = rate_map()); /*! Use NoSeniority to settle to all seniorities with that recovery. In that case the event is assumed to have affected all seniorities. */ DefaultEvent(const Date& creditEventDate, const DefaultType& atomicEvType, Currency curr, Seniority bondsSen, // Settlement information: const Date& settleDate = Null<Date>(), Real recoveryRate = 0.4); Date date() const override; bool isRestructuring() const { return eventType_.isRestructuring(); } bool isDefault() const { return !isRestructuring();} bool hasSettled() const { return defSettlement_.date() != Null<Date>(); } const DefaultSettlement& settlement() const { return defSettlement_; } const DefaultType& defaultType() const { return eventType_; } //! returns the currency of the bond this event refers to. const Currency& currency() const { return bondsCurrency_; } //! returns the seniority of the bond that triggered the event. Seniority eventSeniority() const { return bondsSeniority_; } /*! returns a value if the event lead to a settlement for the requested seniority. Specializations on the default atomics and recoveries could change the default policy. */ virtual Real recoveryRate(Seniority seniority) const { if(hasSettled()) { return defSettlement_.recoveryRate(seniority); } return Null<Real>(); } /*! matches the event if this event would trigger a contract related to the requested event type. Notice the contractual event types are not neccesarily atomic. Notice it does not check seniority or currency only event type. typically used from Issuer */ virtual bool matchesEventType( const ext::shared_ptr<DefaultType>& contractEvType) const { // remember we are made of an atomic type. // behaviour by default... return contractEvType->containsRestructuringType( eventType_.restructuringType()) && contractEvType->containsDefaultType( eventType_.defaultType()); } /*! Returns true if this event would trigger a contract with the arguments characteristics. */ virtual bool matchesDefaultKey(const DefaultProbKey& contractKey) const; void accept(AcyclicVisitor&) override; protected: Currency bondsCurrency_; Date defaultDate_; DefaultType eventType_; Seniority bondsSeniority_; DefaultSettlement defSettlement_; }; /*! Two credit events are the same independently of their settlement member data. This has the side effect of overwritting different settlements from the same credit event when, say, inserting in a map. But on the other hand one given event can only have one settlement. This means we can not have two restructuring events on a bond on the same date. */ bool operator==(const DefaultEvent& lhs, const DefaultEvent& rhs); inline bool operator!=(const DefaultEvent& lhs, const DefaultEvent& rhs) { return !(lhs == rhs); } template<> struct earlier_than<DefaultEvent> { bool operator()(const DefaultEvent& e1, const DefaultEvent& e2) const { return e1.date() < e2.date(); } }; // ------------------------------------------------------------------------ class FailureToPayEvent : public DefaultEvent { public: FailureToPayEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, Real defaultedAmount, // Settlement information: const Date& settleDate, const std::map<Seniority, Real>& recoveryRates); FailureToPayEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, Real defaultedAmount, // Settlement information: const Date& settleDate, Real recoveryRates); Real amountDefaulted() const {return defaultedAmount_;} bool matchesEventType(const ext::shared_ptr<DefaultType>& contractEvType) const override; private: Real defaultedAmount_; }; // ------------------------------------------------------------------------ class BankruptcyEvent : public DefaultEvent { public: BankruptcyEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, // Settlement information: const Date& settleDate, const std::map<Seniority, Real>& recoveryRates); BankruptcyEvent(const Date& creditEventDate, const Currency& curr, Seniority bondsSen, // Settlement information: const Date& settleDate, // means same for all Real recoveryRates); //! This is a stronger than all event and will trigger all of them. bool matchesEventType(const ext::shared_ptr<DefaultType>&) const override { return true; } }; } #endif
40.11336
98
0.587707
jiangjiali
c1fbe2baa36ea9540f5790c317ca70f0a7a1c796
6,798
cpp
C++
src/runtime/allocators/FreeListAllocator.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
src/runtime/allocators/FreeListAllocator.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
src/runtime/allocators/FreeListAllocator.cpp
smacdo/Shiny
580f8bb240b3ece72d7181288bacaba5ecd7071e
[ "Apache-2.0" ]
null
null
null
#include "runtime/allocators/FreeListAllocator.h" #include <fmt/format.h> #include <cassert> #include <unistd.h> using namespace Shiny; using namespace Shiny::FreeListImpl; //------------------------------------------------------------------------------ FreeListAllocator::~FreeListAllocator() { reset(); } //------------------------------------------------------------------------------ void* FreeListAllocator::allocate(size_t requestedSizeInBytes) { // Support zero sized byte allocations by rounding up to one. auto sizeInBytes = (requestedSizeInBytes > 0 ? requestedSizeInBytes : 1); // Ensure the requested allocation size is rounded up to the nearest aligned // size. auto alignedSizeInBytes = align(sizeInBytes); // Search for an available free block to reuse before allocating a new block. auto block = findFreeBlock(alignedSizeInBytes); if (block == nullptr) { // No free block found - allocate a new block for this request. block = allocateBlock(alignedSizeInBytes); byteCount_ += requestedSizeInBytes; // Track the original requested byte count. // Set the start of the heap to this block if the heap hasn't been // initialized (ie this is the first allocation). if (heapRoot_ == nullptr) { heapRoot_ = block; } // Append the block to the back of the heap so it can be tracked. if (heapBack_ != nullptr) { heapBack_->next = block; } heapBack_ = block; } // Mark block as being used before returning the payload poriton back to the // caller. block->isUsed = true; return reinterpret_cast<void*>(block->data); } //------------------------------------------------------------------------------ Block* FreeListAllocator::allocateBlock(size_t sizeInBytes) { assert(sizeInBytes > 0); // Get a pointer to the current heap break (end of the heap). This will be the // beginning position of our newly allocated block. auto block = reinterpret_cast<Block*>(sbrk(0)); // Bump the heap break by the number of bytes required for this allocation, // and check for a failed allocation after doing this. auto actualSizeInBytes = getAllocationSizeInBytes(sizeInBytes); if (sbrk(actualSizeInBytes) == reinterpret_cast<void*>(-1)) { throw OutOfMemoryException( fmt::format( "Allocation {} bytes failed because out of memory", sizeInBytes), EXCEPTION_CALLSITE_ARGS); } // Initialize header. block->sizeInBytes = sizeInBytes; block->isUsed = true; block->next = nullptr; // Update statistics before returning the block. blockCount_++; actualByteCount_ += actualSizeInBytes; return block; } //------------------------------------------------------------------------------ Block* FreeListAllocator::findFreeBlock(size_t sizeInBytes) { return findFirstFreeFitBlock(sizeInBytes); } //------------------------------------------------------------------------------ Block* FreeListAllocator::findFirstFreeFitBlock(size_t sizeInBytes) { // Search begins where the last block was allocated, or at the start of the // heap if this is the first find. if (findStart_ == nullptr) { findStart_ = heapRoot_; } // Look for the first block that can fit the request. // O(n) linear search. auto block = findStart_; while (block != nullptr) { // Check if this block is free and of the right size to be re-used. if (!block->isUsed && block->sizeInBytes >= sizeInBytes) { findStart_ = block; return block; } // Break out once we reach the block where the start began. if (block->next == findStart_ || (block->next == nullptr && findStart_ == heapRoot_)) { break; } // Move to the next block, or go back to the start if we've reached the end // of the heap. if (block->next == nullptr) { block = heapRoot_; } else { block = block->next; } } // Failed to find a block. return nullptr; } //------------------------------------------------------------------------------ void FreeListAllocator::destroy(void* userPointer) { // Nothing needs to be done when destroying a null pointer. if (userPointer == nullptr) { return; } freeBlock(getHeader(userPointer)); } //------------------------------------------------------------------------------ void FreeListAllocator::reset() { // Nothing to do if already reset. if (heapRoot_ == nullptr) { return; } // Check if blocks should be freed before reset. if (freeBeforeReset_) { freeHeap(); } // Reset the program data segment pointer back to where it was prior to any // allocation by this allocator. // TODO: Switch to mmap to enable multiple concurrent heaps. brk(heapRoot_); heapRoot_ = nullptr; heapBack_ = nullptr; findStart_ = nullptr; blockCount_ = 0; byteCount_ = 0; actualByteCount_ = 0; } //------------------------------------------------------------------------------ void FreeListAllocator::freeHeap() { auto block = heapRoot_; while (block != nullptr) { auto nextBlock = block->next; if (block->isUsed) { freeBlock(block); } block = nextBlock; } // TODO: Return the used space back to the operating system. // (probably once we switch to mmap). } //------------------------------------------------------------------------------ void FreeListAllocator::freeBlock(Block* block) { assert(block != nullptr); // Don't let a block be freed more than once. if (!block->isUsed) { throw DoubleFreeException( reinterpret_cast<void*>(block->data), EXCEPTION_CALLSITE_ARGS); } // Mark as free to let allocator reuse the block. block->isUsed = false; // Clear memory contents if requested. if (clearAfterFree_) { memset(reinterpret_cast<void*>(block->data), 0xC0FEFE, block->sizeInBytes); } } //------------------------------------------------------------------------------ const Block* FreeListAllocator::getHeader(void* userPointer) const { return reinterpret_cast<const Block*>( reinterpret_cast<char*>(userPointer) + sizeof(std::declval<Block>().data) - sizeof(Block)); } //------------------------------------------------------------------------------ Block* FreeListAllocator::getHeader(void* userPointer) { return reinterpret_cast<Block*>( reinterpret_cast<char*>(userPointer) + sizeof(std::declval<Block>().data) - sizeof(Block)); } //------------------------------------------------------------------------------ size_t FreeListAllocator::getAllocationSizeInBytes(size_t userSizeInBytes) { // Since the block structure includes the first word of user data (C++ // doesn't allow zero sized arrays), we subtract it from the size request. return userSizeInBytes + sizeof(Block) - sizeof(std::declval<Block>().data); }
31.041096
80
0.59135
smacdo
c1fd8772618988d03f9f93e386b7fc4c4abe81d5
15,364
hpp
C++
src/lt_math.hpp
leohahn/lt
2f0d2fc4142e5692cedea3607aff39a0a0cf095f
[ "Unlicense" ]
null
null
null
src/lt_math.hpp
leohahn/lt
2f0d2fc4142e5692cedea3607aff39a0a0cf095f
[ "Unlicense" ]
null
null
null
src/lt_math.hpp
leohahn/lt
2f0d2fc4142e5692cedea3607aff39a0a0cf095f
[ "Unlicense" ]
null
null
null
#ifndef LT_MATH_HPP #define LT_MATH_HPP #include <stdio.h> #include <cmath> #include <iostream> #include <iomanip> #include <cstring> #include <type_traits> #include <limits> #include "lt_core.hpp" #include "math.h" #ifndef LT_PI #define LT_PI 3.14159265358979323846 #endif struct Point3f { f32 x, y, z; explicit Point3f(f32 x, f32 y, f32 z) : x(x), y(y), z(z) {} }; struct Size2f { f32 width, height; explicit Size2f(f32 width, f32 height) : width(width), height(height) {} }; template<typename T> typename std::enable_if<!std::numeric_limits<T>::is_integer, bool>::type almost_equal(T x, T y, T epsilon = std::numeric_limits<T>::epsilon()) { // http://realtimecollisiondetection.net/blog/?p=89 bool almost = std::abs(x - y) <= epsilon * std::max(std::max(static_cast<T>(1), std::abs(x)), std::abs(y)); return almost; } ///////////////////////////////////////////////////////// // // Vector2 // // Definition of a vector structure. // template<typename T> union Vec2 { T val[2]; struct { T x, y; }; Vec2(): x(0), y(0) {} explicit Vec2(T k): x(k), y(k) {} explicit Vec2(T x, T y): x(x), y(y) {} inline Vec2<T> operator-(Vec2<T> rhs) const {return Vec2<T>(x - rhs.x, y - rhs.y);} }; template<typename T> static inline Vec2<T> operator*(const Vec2<T>& v, f32 k) { return Vec2<T>(v.x * k, v.y * k); } template<typename T> static inline Vec2<T> operator*(const Vec2<T>& v, f64 k) { return Vec2<T>(v.x * k, v.y * k); } template<typename T> static inline Vec2<T> operator+(const Vec2<T> &a, const Vec2<T> &b) { return Vec2<T>(a.x + b.x, a.y + b.y); } template<typename T> static inline std::ostream & operator<<(std::ostream& os, const Vec2<T> &v) { os << "(" << v.x << ", " << v.y << ")"; return os; } ///////////////////////////////////////////////////////// // // Vector3 // // Definition of a vector structure. // template<typename T> union Vec4; template<typename T> struct Vec3 { union { T val[3]; struct { T x, y, z; }; struct { T r, g, b; }; struct { T i, j, k; }; struct { Vec2<T> xy; f32 _ignored_z; }; struct { f32 _ignored_x; Vec2<T> yz; }; }; Vec3() noexcept : x(0), y(0), z(0) {} explicit Vec3(T val) noexcept : x(val), y(val), z(val) {} explicit Vec3(T x, T y, T z) noexcept : x(x), y(y), z(z) {} explicit Vec3(Vec4<T> v) noexcept : x(v.x), y(v.y), z(v.z) {} explicit Vec3(Vec2<T> v, T z) noexcept : x(v.x), y(v.y), z(z) {} inline Vec3<T> operator-(const Vec3<T>& rhs) const { return Vec3<T>(x-rhs.x, y-rhs.y, z-rhs.z); } inline Vec3<T> operator-() const { return Vec3<T>(-x, -y, -z); } inline Vec3<T> operator+(const Vec3<T>& rhs) const { return Vec3<T>(x+rhs.x, y+rhs.y, z+rhs.z); } inline Vec2<T> xz() const { return Vec2<T>(x, z); } inline void operator-=(const Vec3<T>& rhs) { x -= rhs.x; y -= rhs.y; z -= rhs.z; } inline void operator+=(const Vec3<T>& rhs) { x += rhs.x; y += rhs.y; z += rhs.z; } }; template<typename T> inline bool operator==(const Vec3<T> &a, const Vec3<T> &b) { return a.x == b.x && a.y == b.y && a.z == b.z; } template<> inline bool operator==<f32>(const Vec3<f32> &a, const Vec3<f32> &b) { return almost_equal(a.x, b.x) && almost_equal(a.y, b.y) && almost_equal(a.z, b.z); } template<> inline bool operator==<f64>(const Vec3<f64> &a, const Vec3<f64> &b) { return almost_equal(a.x, b.x) && almost_equal(a.y, b.y) && almost_equal(a.z, b.z); } template<typename T> inline bool operator!=(const Vec3<T> &a, const Vec3<T> &b) { return a.x != b.x && a.y != b.y && a.z != b.z; } template<> inline bool operator!=<f32>(const Vec3<f32> &a, const Vec3<f32> &b) { return !almost_equal(a.x, b.x) || !almost_equal(a.y, b.y) || !almost_equal(a.z, b.z); } template<> inline bool operator!=<f64>(const Vec3<f64> &a, const Vec3<f64> &b) { return !almost_equal(a.x, b.x) || !almost_equal(a.y, b.y) || !almost_equal(a.z, b.z); } template<typename T> static inline std::ostream & operator<<(std::ostream& os, const Vec3<T> &v) { os << "(" << v.x << ", " << v.y << ", " << v.z << ")"; return os; } template<typename T> static inline Vec3<T> operator*(const Vec3<T>& v, f32 k) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(f32 k, const Vec3<T>& v) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(const Vec3<T>& v, f64 k) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } template<typename T> static inline Vec3<T> operator*(f64 k, const Vec3<T>& v) { return Vec3<T>(v.x*k, v.y*k, v.z*k); } ///////////////////////////////////////////////////////// // // Vector4 // // Definition of a vector structure. // template<typename T> union Vec4 { T val[4]; struct { T x, y, z, w; }; struct { T r, g, b, a; }; Vec4(): x(0), y(0), z(0), w(0) {} explicit Vec4(T x, T y, T z, T w): x(x), y(y), z(z), w(w) {} explicit Vec4(const Vec3<T>& v, T w): x(v.x), y(v.y), z(v.z), w(w) {} }; namespace lt { template<typename T> inline T norm(const Vec4<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z + v.w*v.w); } template<typename T> inline T norm(const Vec3<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y + v.z*v.z); } template<typename T> inline T norm(const Vec2<T>& v) { return std::sqrt(v.x*v.x + v.y*v.y); } template<typename T> inline Vec2<T> normalize(const Vec2<T>& v) { return Vec2<T>(v.x/lt::norm(v), v.y/lt::norm(v), v.z/lt::norm(v)); } template<typename T> inline Vec3<T> normalize(const Vec3<T>& v) { const f32 EPSILON = 0.0001f; f32 length = lt::norm(v); if (length <= EPSILON) return v; return Vec3<T>(v.x/length, v.y/length, v.z/length); } template<typename T> inline Vec4<T> normalize(const Vec4<T>& v) { return Vec4<T>(v.x/lt::norm(v), v.y/lt::norm(v), v.z/lt::norm(v), v.w /lt::norm(v)); } template<typename T> inline T radians(T angle) { return angle * (static_cast<T>(M_PI) / static_cast<T>(180)); } template<typename T> inline T degrees(T angle) { return angle * (static_cast<T>(180) / static_cast<T>(M_PI)); } template<typename T> inline T dot(const Vec2<T>& a, const Vec2<T>& b) { return (a.x * b.x) + (a.y * b.y); } template<typename T> inline T dot(const Vec3<T>& lhs, const Vec3<T>& rhs) { return (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z); } template<typename T> inline Vec2<T> projection(const Vec2<T>& p, const Vec2<T>& plane) { f32 alpha = lt::dot(p, plane) / lt::dot(plane, plane); return alpha * plane; } template<typename T> inline Vec3<T> cross(const Vec3<T>& a, const Vec3<T>& b) { return Vec3<T>((a.y * b.z) - (a.z * b.y), (a.z * b.x) - (a.x * b.z), (a.x * b.y) - (a.y * b.x)); } } ///////////////////////////////////////////////////////// // // Matrix // // Column major // union Mat4f { Mat4f(); explicit Mat4f(f32 diag); explicit Mat4f(f32 m00, f32 m01, f32 m02, f32 m03, f32 m10, f32 m11, f32 m12, f32 m13, f32 m20, f32 m21, f32 m22, f32 m23, f32 m30, f32 m31, f32 m32, f32 m33); inline f32 operator()(isize row, isize col) const { return m_col[col].val[row]; } inline f32& operator()(isize row, isize col) { return m_col[col].val[row]; } inline Vec4<f32> col(isize col) { return m_col[col]; } inline f32 *data() const { return (f32*)&m_col[0].val[0]; } Mat4f operator*(const Mat4f& rhs); private: Vec4<f32> m_col[4]; }; inline std::ostream &operator<<(std::ostream& os, const Mat4f &mat) { for (i32 row = 0; row < 4; row++) { os << "| "; for (i32 col = 0; col < 4; col++) { os << std::setw(9) << std::setprecision(3) << mat(row, col) << " "; } os << "|\n"; } return os; } inline Mat4f operator*(const Mat4f &lhs, const Mat4f &rhs) { Mat4f ret(1.0); // First row ret(0,0) = lhs(0,0)*rhs(0,0) + lhs(0,1)*rhs(1,0) + lhs(0,2)*rhs(2,0) + lhs(0,3)*rhs(3,0); ret(0,1) = lhs(0,0)*rhs(0,1) + lhs(0,1)*rhs(1,1) + lhs(0,2)*rhs(2,1) + lhs(0,3)*rhs(3,1); ret(0,2) = lhs(0,0)*rhs(0,2) + lhs(0,1)*rhs(1,2) + lhs(0,2)*rhs(2,2) + lhs(0,3)*rhs(3,2); ret(0,3) = lhs(0,0)*rhs(0,3) + lhs(0,1)*rhs(1,3) + lhs(0,2)*rhs(2,3) + lhs(0,3)*rhs(3,3); // Second row ret(1,0) = lhs(1,0)*rhs(0,0) + lhs(1,1)*rhs(1,0) + lhs(1,2)*rhs(2,0) + lhs(1,3)*rhs(3,0); ret(1,1) = lhs(1,0)*rhs(0,1) + lhs(1,1)*rhs(1,1) + lhs(1,2)*rhs(2,1) + lhs(1,3)*rhs(3,1); ret(1,2) = lhs(1,0)*rhs(0,2) + lhs(1,1)*rhs(1,2) + lhs(1,2)*rhs(2,2) + lhs(1,3)*rhs(3,2); ret(1,3) = lhs(1,0)*rhs(0,3) + lhs(1,1)*rhs(1,3) + lhs(1,2)*rhs(2,3) + lhs(1,3)*rhs(3,3); // Third row ret(2,0) = lhs(2,0)*rhs(0,0) + lhs(2,1)*rhs(1,0) + lhs(2,2)*rhs(2,0) + lhs(2,3)*rhs(3,0); ret(2,1) = lhs(2,0)*rhs(0,1) + lhs(2,1)*rhs(1,1) + lhs(2,2)*rhs(2,1) + lhs(2,3)*rhs(3,1); ret(2,2) = lhs(2,0)*rhs(0,2) + lhs(2,1)*rhs(1,2) + lhs(2,2)*rhs(2,2) + lhs(2,3)*rhs(3,2); ret(2,3) = lhs(2,0)*rhs(0,3) + lhs(2,1)*rhs(1,3) + lhs(2,2)*rhs(2,3) + lhs(2,3)*rhs(3,3); // Fourth row ret(3,0) = lhs(3,0)*rhs(0,0) + lhs(3,1)*rhs(1,0) + lhs(3,2)*rhs(2,0) + lhs(3,3)*rhs(3,0); ret(3,1) = lhs(3,0)*rhs(0,1) + lhs(3,1)*rhs(1,1) + lhs(3,2)*rhs(2,1) + lhs(3,3)*rhs(3,1); ret(3,2) = lhs(3,0)*rhs(0,2) + lhs(3,1)*rhs(1,2) + lhs(3,2)*rhs(2,2) + lhs(3,3)*rhs(3,2); ret(3,3) = lhs(3,0)*rhs(0,3) + lhs(3,1)*rhs(1,3) + lhs(3,2)*rhs(2,3) + lhs(3,3)*rhs(3,3); return ret; } namespace lt { Mat4f perspective(f32 fovy, f32 aspect_ratio, f32 znear, f32 zfar); Mat4f orthographic(f32 left, f32 right, f32 bottom, f32 top, f32 near, f32 far); Mat4f orthographic(f32 left, f32 right, f32 bottom, f32 top); Mat4f look_at(const Vec3<f32> eye, const Vec3<f32> center, const Vec3<f32> up); Mat4f translation(const Mat4f &in_mat, Vec3<f32> amount); Mat4f scale(const Mat4f &in_mat, Vec3<f32> scale); inline Mat4f rotation_x(const Mat4f &in_mat, f32 degrees) { f32 rad = lt::radians(degrees); return in_mat * Mat4f(1, 0, 0, 0, 0, cos(rad), -sin(rad), 0, 0, sin(rad), cos(rad), 0, 0, 0, 0, 1); } inline Mat4f rotation_y(const Mat4f &in_mat, f32 degrees) { f32 rad = lt::radians(degrees); return in_mat * Mat4f(cos(rad), 0, sin(rad), 0, 0, 1, 0, 0, -sin(rad), 0, cos(rad), 0, 0, 0, 0, 1); } } ///////////////////////////////////////////////////////// // // Quaternion // // Definition of a quaternion structure. // // Some properties (not necessarily complete): // - Not comutative (q1q2 != q2q1) // - Associative ((q1q2)q3 == q1(q2q3)) // - The quaternion (1, 0, 0, 0) maps to the identity matrix. // template<typename T> union Quat { T val[4]; struct { T s; Vec3<T> v; }; explicit Quat(T s, T i, T j, T k) : val{s, i, j, k} {} explicit Quat(T s, const Vec3<T>& v) : s(s), v(v) {} Quat() : s(0), v(Vec3<T>(0, 0, 0)) {} static inline Quat<T> identity() { return Quat<T>(1, 0, 0, 0); } static inline Quat<T> rotation(T angle, const Vec3<T>& axis) { Vec3<T> sin_axis = axis * std::sin(angle/static_cast<T>(2)); return Quat<T>(std::cos(angle/static_cast<T>(2)), sin_axis); } Mat4f to_mat4() const { return Mat4f(s, -v.i, -v.j, -v.k, v.i, s, -v.k, v.j, v.j, v.k, s, -v.i, v.k, -v.j, v.i, s); } inline Quat<T> operator+(const Quat<T>& rhs) const { return Quat<T>(s+rhs.s, v.i+rhs.v.i, v.j+rhs.v.j, v.k+rhs.v.k); } inline Quat<T> operator/(T k) const { return Quat<T>(val[0]/k, val[1]/k, val[2]/k, val[3]/k); } }; template<typename T> inline Quat<T> operator*(const Quat<T> &q, T k) { return Quat<T>(q.s*k, q.v*k); } template<typename T> inline Quat<T> operator*(T k, const Quat<T> &q) { return Quat<T>(q.s*k, q.v*k); } template<typename T> static inline Quat<T> operator*(const Quat<T>& lhs, const Quat<T>& rhs) { return Quat<T>((lhs.s*rhs.s) - lt::dot(lhs.v, rhs.v), rhs.s*lhs.v + lhs.s*rhs.v + lt::cross(lhs.v, rhs.v)); } template<typename T> inline std::ostream & operator<<(std::ostream &os, const Quat<T> &q) { os << "(" << std::setprecision(3) << q.val[0] << ", "; os << q.val[1] << ", " << q.val[2] << ", " << q.val[3] << ")"; return os; } template<typename T> inline bool operator==(const Quat<T> &a, const Quat<T> &b) { return (a.val[0] == b.val[0]) && (a.val[1] == b.val[1]) && (a.val[2] == b.val[2]) && (a.val[3] == b.val[3]); } template<> inline bool operator==<f32>(const Quat<f32> &a, const Quat<f32> &b) { return almost_equal(a.val[0], b.val[0]) && almost_equal(a.val[1], b.val[1]) && almost_equal(a.val[2], b.val[2]) && almost_equal(a.val[3], b.val[3]); } template<> inline bool operator==<f64>(const Quat<f64> &a, const Quat<f64> &b) { return almost_equal(a.val[0], b.val[0]) && almost_equal(a.val[1], b.val[1]) && almost_equal(a.val[2], b.val[2]) && almost_equal(a.val[3], b.val[3]); } namespace lt { template<typename T> inline T norm(const Quat<T> &q) { T v = q.val[0]*q.val[0] + q.val[1]*q.val[1] + q.val[2]*q.val[2] + q.val[3]*q.val[3]; return std::sqrt(v); } template<typename T> inline T sqr_norm(const Quat<T> &q) { T v = q.val[0]*q.val[0] + q.val[1]*q.val[1] + q.val[2]*q.val[2] + q.val[3]*q.val[3]; return v; } template<typename T> inline Quat<T> normalize(const Quat<T> &q) { return Quat<T>(q.s/lt::norm(q), q.v.i/lt::norm(q), q.v.j/lt::norm(q), q.v.k/lt::norm(q)); } template<typename T> inline Quat<T> conjugate(const Quat<T> &q) { return Quat<T>(q.s, -q.v); } template<typename T> inline Quat<T> inverse(const Quat<T> &q) { Quat<T> inv = lt::conjugate(q) / lt::sqr_norm(q); LT_Assert(q*inv == Quat<T>::identity()); return inv; } template<typename T> inline Quat<T> rotate(const Quat<T> &q, T angle, const Quat<T> &axis) { const Quat<T> rotor = Quat<T>::rotation(angle, axis.v); return rotor * q * lt::inverse(rotor); } template<typename T> T dot(const Quat<T> &a, const Quat<T> &b) { return a.val[0]*b.val[0] + a.val[1]*b.val[1] + a.val[2]*b.val[2] + a.val[3]*b.val[3]; } template<typename T> Quat<T> slerp(const Quat<T> &start_q, const Quat<T> &end_q, T t) { LT_Assert(t >= 0); LT_Assert(t <= 1); const T EPSILON = static_cast<T>(0.0001); // FIXME: Find a more specific epsilon value here. T start_dot_end = lt::dot(start_q, end_q); if (start_dot_end < 1-EPSILON) { T angle = std::acos(start_dot_end); LT_Assert(angle != static_cast<T>(0)); return (std::sin((static_cast<T>(1) - t) * angle) * start_q + std::sin(t * angle) * end_q) / std::sin(angle); } else { return start_q; } } } typedef Vec2<i32> Vec2i; typedef Vec2<f32> Vec2f; typedef Vec3<i32> Vec3i; typedef Vec3<f32> Vec3f; typedef Vec4<i32> Vec4i; typedef Vec4<f32> Vec4f; typedef Quat<f32> Quatf; typedef Quat<f64> Quatd; #endif // LT_MATH_HPP
25.269737
108
0.545236
leohahn
c1fdca1d9b2367b6916e34a6037e56024d0d6e57
1,190
cpp
C++
lista7/11areaTriangulo.cpp
GE28/exercicios-CPP
7070d6f749c859ca0a7bac39812558b0795d18c6
[ "MIT" ]
1
2021-08-31T22:32:22.000Z
2021-08-31T22:32:22.000Z
lista7/11areaTriangulo.cpp
GE28/exercicios-CPP
7070d6f749c859ca0a7bac39812558b0795d18c6
[ "MIT" ]
null
null
null
lista7/11areaTriangulo.cpp
GE28/exercicios-CPP
7070d6f749c859ca0a7bac39812558b0795d18c6
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; #define LINHAS 2 #define COLUNAS 50 void calculeAreas(double triangulos[LINHAS][COLUNAS], double areas[]) { for (int i = 0; i < COLUNAS; i++) { areas[i] = (triangulos[0][i] * triangulos[1][i]) / 2; cout << "A área do " << i + 1 << "º triângulo é " << areas[i] << endl; } } void imprimaMatriz(double matriz[LINHAS][COLUNAS]) { int j = 0; cout << "[" << endl; for (int i = 0; i < LINHAS; i++) { j = 0; cout << "[" << matriz[i][j] << ", "; for (j = 1; j < COLUNAS - 1; j++) { cout << matriz[i][j] << ", "; } cout << matriz[i][j] << "]," << endl; } cout << "]" << endl; } int main() { double matriz[LINHAS][COLUNAS] = { {12, 5, 6, 7, 6, 9, 8, 3, 6, 10, 2, 7, 6, 9, 2, 5, 9, 5, 9, 5, 9, 6, 3, 10, 7, 10, 4, 5, 1, 9, 6, 6, 5, 1, 4, 10, 9, 1, 2, 7, 3, 6, 3, 8, 6, 4, 5, 5, 10, 3}, {23, 8, 10, 5, 8, 7, 4, 3, 1, 4, 3, 8, 2, 7, 1, 5, 6, 1, 8, 10, 7, 10, 7, 9, 9, 2, 5, 3, 8, 4, 7, 8, 2, 9, 2, 1, 5, 5, 3, 7, 1, 5, 4, 4, 3, 4, 10, 10, 7, 7}}; double areas[COLUNAS] = {}; imprimaMatriz(matriz); calculeAreas(matriz, areas); return 0; }
28.333333
74
0.457983
GE28
c1fe001e93703950318908c961a80d6fb92f1ba1
520
hpp
C++
src/ContourPlotStage.hpp
edroque93/StageCV
4a323eb545879e2d04e5667a17adab06aa4f6c55
[ "MIT" ]
null
null
null
src/ContourPlotStage.hpp
edroque93/StageCV
4a323eb545879e2d04e5667a17adab06aa4f6c55
[ "MIT" ]
null
null
null
src/ContourPlotStage.hpp
edroque93/StageCV
4a323eb545879e2d04e5667a17adab06aa4f6c55
[ "MIT" ]
null
null
null
#pragma once #include <string_view> #include <opencv2/opencv.hpp> #include "GeneratorStage.hpp" #include "FilterStage.hpp" #include "ContourDetectionStage.hpp" class ContourPlotStage : public FilterStage { public: ContourPlotStage(GeneratorStage &input, ContourDetectionStage &contour); void Execute(); std::string_view GetStageName() const { return "ContourPlotStage"; }; cv::Mat GetOutputImage() { return output; }; private: cv::Mat output; ContourDetectionStage contour; cv::RNG rng; };
24.761905
76
0.736538
edroque93
de007515b2da63587cc6a500ff9665679cf2c254
86,107
cpp
C++
Src/lunaui/cards/CardWindowManager.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
3
2018-11-16T14:51:17.000Z
2019-11-21T10:55:24.000Z
Src/lunaui/cards/CardWindowManager.cpp
penk/luna-sysmgr
60c7056a734cdb55a718507f3a739839c9d74edf
[ "Apache-2.0" ]
1
2021-02-20T13:12:15.000Z
2021-02-20T13:12:15.000Z
Src/lunaui/cards/CardWindowManager.cpp
ericblade/luna-sysmgr
82d5d7ced4ba21d3802eb2c8ae063236b6562331
[ "Apache-2.0" ]
null
null
null
/* @@@LICENSE * * Copyright (c) 2008-2012 Hewlett-Packard Development Company, L.P. * * 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. * * LICENSE@@@ */ #include "Common.h" #include "CardWindowManager.h" #include <QGesture> #include "ApplicationDescription.h" #include "AnimationSettings.h" #include "CardWindow.h" #include "HostBase.h" #include "Logging.h" #include "Settings.h" #include "SoundPlayerPool.h" #include "SystemService.h" #include "SystemUiController.h" #include "Time.h" #include "Window.h" #include "WindowServer.h" #include "Utils.h" #include "CardWindowManagerStates.h" #include "CardGroup.h" #include "FlickGesture.h" #include "GhostCard.h" #include "IMEController.h" #include <QTapGesture> #include <QTapAndHoldGesture> #include <QPropertyAnimation> static int kGapBetweenGroups = 0; static qreal kActiveScale = 0.659; static qreal kNonActiveScale = 0.61; static const qreal kWindowOriginRatio = 0.40; static int kWindowOrigin = 0; static int kWindowOriginMax = 0; static const qreal kMinimumWindowScale = 0.26; static int kMinimumHeight = 0; static const int kFlickToCloseWindowVelocityThreshold = -1100; static const int kFlickToCloseWindowDistanceThreshold = -50; static const int kFlickToCloseWindowMinimumVelocity = -500; static const int kModalWindowAnimationTimeout = 45; static const int s_marginSlice = 5; int kAngryCardThreshold = 0; // ------------------------------------------------------------------------------------------------------------- CardWindowManager::CardWindowManager(int maxWidth, int maxHeight) : WindowManagerBase(maxWidth, maxHeight) , m_activeGroup(0) , m_draggedWin(0) , m_penDown(false) , m_cardToRestoreToMaximized(0) , m_lowResMode(false) , m_movement(MovementUnlocked) , m_trackWithinGroup(true) , m_seenFlickOrTap(false) , m_activeGroupPivot(0) , m_reorderZone(ReorderZone_Center) , m_stateMachine(0) , m_minimizeState(0) , m_maximizeState(0) , m_preparingState(0) , m_loadingState(0) , m_focusState(0) , m_reorderState(0) , m_curState(0) , m_addingModalWindow(false) , m_initModalMaximizing(false) , m_parentOfModalCard(0) , m_modalDismissInProgress(false) , m_modalDimissed(false) , m_dismissModalImmediately(-1) , m_animateWindowForModalDismisal(true) , m_modalWindowState(NoModalWindow) , m_playedAngryCardStretchSound(false) , m_animationsActive(false) { setObjectName("CardWindowManager"); SystemUiController* sysui = SystemUiController::instance(); connect(sysui, SIGNAL(signalPositiveSpaceAboutToChange(const QRect&, bool, bool)), SLOT(slotPositiveSpaceAboutToChange(const QRect&, bool, bool))); connect(sysui, SIGNAL(signalPositiveSpaceChangeFinished(const QRect&)), SLOT(slotPositiveSpaceChangeFinished(const QRect&))); connect(sysui, SIGNAL(signalPositiveSpaceChanged(const QRect&)), SLOT(slotPositiveSpaceChanged(const QRect&))); connect(sysui, SIGNAL(signalLauncherVisible(bool, bool)), SLOT(slotLauncherVisible(bool, bool))); connect(sysui, SIGNAL(signalLauncherShown(bool)), SLOT(slotLauncherShown(bool))); connect(sysui, SIGNAL(signalMaximizeActiveCardWindow()), SLOT(slotMaximizeActiveCardWindow())); connect(sysui, SIGNAL(signalMinimizeActiveCardWindow()), SLOT(slotMinimizeActiveCardWindow())); connect(sysui, SIGNAL(signalChangeCardWindow(bool)), SLOT(slotChangeCardWindow(bool))); connect(sysui, SIGNAL(signalFocusMaximizedCardWindow(bool)), SLOT(slotFocusMaximizedCardWindow(bool))); connect(SystemService::instance(), SIGNAL(signalTouchToShareAppUrlTransfered(const std::string&)), SLOT(slotTouchToShareAppUrlTransfered(const std::string&))); connect(SystemService::instance(), SIGNAL(signalDismissModalDialog()), SLOT(slotDismissActiveModalWindow())); connect(SystemService::instance(), SIGNAL(signalStopModalDismissTimer()), SLOT(slotDismissModalTimerStopped())); connect(&m_anims, SIGNAL(finished()), SLOT(slotAnimationsFinished())); grabGesture(Qt::TapGesture); grabGesture(Qt::TapAndHoldGesture); grabGesture((Qt::GestureType) SysMgrGestureFlick); } CardWindowManager::~CardWindowManager() { // doesn't reach here } void CardWindowManager::init() { kGapBetweenGroups = Settings::LunaSettings()->gapBetweenCardGroups; if (g_file_test(Settings::LunaSettings()->firstCardLaunch.c_str(), G_FILE_TEST_EXISTS)){ m_dismissedFirstCard=true; } else{ m_dismissedFirstCard=false; } // register CardWindow::Position types for use as Q_PROPERTY's qRegisterMetaType<CardWindow::Position>("CardWindow::Position"); qRegisterAnimationInterpolator<CardWindow::Position>(positionInterpolator); // needed in order for CardWindow pointers to be used with queued signal and slot // connections, i.e. QStateMachine signal transitions qRegisterMetaType<CardWindow*>("CardWindow*"); m_stateMachine = new QStateMachine(this); // setup our states m_minimizeState = new MinimizeState(this); m_maximizeState = new MaximizeState(this); m_preparingState = new PreparingState(this); m_loadingState = new LoadingState(this); m_focusState = new FocusState(this); m_reorderState = new ReorderState(this); m_stateMachine->addState(m_minimizeState); m_stateMachine->addState(m_maximizeState); m_stateMachine->addState(m_preparingState); m_stateMachine->addState(m_loadingState); m_stateMachine->addState(m_focusState); m_stateMachine->addState(m_reorderState); // connect allowed state transitions m_minimizeState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_minimizeState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_minimizeState->addTransition(this, SIGNAL(signalFocusWindow(CardWindow*)), m_focusState); m_minimizeState->addTransition(this, SIGNAL(signalEnterReorder(QPoint, int)), m_reorderState); m_maximizeState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_maximizeState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_maximizeState->addTransition(new MaximizeToFocusTransition(this, m_focusState)); m_focusState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_focusState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_focusState->addTransition(this, SIGNAL(signalFocusWindow(CardWindow*)), m_focusState); m_focusState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_preparingState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_preparingState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_preparingState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_preparingState->addTransition(this, SIGNAL(signalLoadingActiveWindow()), m_loadingState); m_loadingState->addTransition(this, SIGNAL(signalMinimizeActiveWindow()), m_minimizeState); m_loadingState->addTransition(this, SIGNAL(signalMaximizeActiveWindow()), m_maximizeState); m_loadingState->addTransition(this, SIGNAL(signalPreparingWindow(CardWindow*)), m_preparingState); m_reorderState->addTransition(this, SIGNAL(signalExitReorder(bool)), m_minimizeState); // start off minimized m_stateMachine->setInitialState(m_minimizeState); m_stateMachine->start(); updateAngryCardThreshold(); } bool CardWindowManager::handleNavigationEvent(QKeyEvent* keyEvent, bool& propogate) { propogate = false; return m_curState->handleKeyNavigation(keyEvent); } bool CardWindowManager::okToResize() { if(m_anims.state() != QAbstractAnimation::Stopped) return false; return true; } void CardWindowManager::updateAngryCardThreshold() { kAngryCardThreshold = ((boundingRect().height() / 2) * 0.30); } void CardWindowManager::resize(int width, int height) { // accept requests for resizing to the current dimensions, in case we are doing a force resize due to // previous cancelation of Card Window flip operations. WindowManagerBase::resize(width, height); m_normalScreenBounds = QRect(0, Settings::LunaSettings()->positiveSpaceTopPadding, SystemUiController::instance()->currentUiWidth(), SystemUiController::instance()->currentUiHeight() - Settings::LunaSettings()->positiveSpaceTopPadding); kMinimumHeight = (int) (kMinimumWindowScale * m_normalScreenBounds.height()); kMinimumHeight = (int) ((kMinimumHeight/2) / kWindowOriginRatio); SystemUiController::instance()->setMinimumPositiveSpaceHeight(kMinimumHeight); m_targetPositiveSpace = SystemUiController::instance()->positiveSpaceBounds(); kWindowOrigin = boundingRect().y() + ((m_normalScreenBounds.y() + 48) + (int) ((m_normalScreenBounds.height() - 48) * kWindowOriginRatio)); updateAngryCardThreshold(); if(m_groups.size() > 0) { int index = m_groups.indexOf(m_activeGroup); // first resize the active group m_groups[index]->resize(width, height, m_normalScreenBounds); m_groups[index]->setY(kWindowOrigin); // resize the group to the left of the active group if(index > 0) { m_groups[index-1]->resize(width, height, m_normalScreenBounds); m_groups[index-1]->setY(kWindowOrigin); } // resize the group to the right of the active group if(index < m_groups.size()-1) { m_groups[index+1]->resize(width, height, m_normalScreenBounds); m_groups[index+1]->setY(kWindowOrigin); } // now resize the other groups, if there are any if(index-1 > 0) { // left side for(int x = index-2; x >= 0; x--) { m_groups[x]->resize(width, height, m_normalScreenBounds); m_groups[x]->setY(kWindowOrigin); } } if(index+1 < m_groups.size()-1) { // right side for(int x = index+2; x < m_groups.size(); x++) { m_groups[x]->resize(width, height, m_normalScreenBounds); m_groups[x]->setY(kWindowOrigin); } } } m_curState->relayout(m_boundingRect, false); } void CardWindowManager::removeAnimationForWindow(CardWindow* win, bool includeDeletedAnimations) { if ((m_curState != m_maximizeState) && m_penDown && !includeDeletedAnimations) win->allowUpdates(false); else win->allowUpdates(true); if (m_cardAnimMap.contains(win)) { QPropertyAnimation* a = m_cardAnimMap.value(win); m_anims.removeAnimation(a); m_cardAnimMap.remove(win); delete a; } if (includeDeletedAnimations) { QMap<CardWindow*,QPropertyAnimation*>::iterator it = m_deletedAnimMap.find(win); if (it != m_deletedAnimMap.end()) { QPropertyAnimation* a = qobject_cast<QPropertyAnimation*>(it.value()); if (a) { m_deletedAnimMap.erase(it); delete a; } } } } bool CardWindowManager::windowHasAnimation(CardWindow* win) const { return m_cardAnimMap.contains(win) || m_deletedAnimMap.contains(win); } void CardWindowManager::setAnimationForWindow(CardWindow* win, QPropertyAnimation* anim) { removeAnimationForWindow(win); m_cardAnimMap.insert(win, anim); m_anims.addAnimation(anim); } void CardWindowManager::setAnimationForGroup(CardGroup* group, QPropertyAnimation* anim) { removeAnimationForGroup(group); m_groupAnimMap.insert(group, anim); m_anims.addAnimation(anim); } void CardWindowManager::removeAnimationForGroup(CardGroup* group) { if (m_groupAnimMap.contains(group)) { QPropertyAnimation* a = m_groupAnimMap.value(group); m_anims.removeAnimation(a); m_groupAnimMap.remove(group); delete a; } } bool CardWindowManager::groupHasAnimation(CardGroup* group) const { return m_groupAnimMap.contains(group); } void CardWindowManager::startAnimations() { m_animationsActive = true; updateAllowWindowUpdates(); m_anims.start(); } void CardWindowManager::clearAnimations() { m_anims.stop(); m_anims.clear(); m_cardAnimMap.clear(); m_groupAnimMap.clear(); m_animationsActive = false; updateAllowWindowUpdates(); } void CardWindowManager::resetMouseTrackState() { m_draggedWin = 0; m_penDown = false; updateAllowWindowUpdates(); m_trackWithinGroup = true; m_seenFlickOrTap = false; m_playedAngryCardStretchSound = false; m_movement = MovementUnlocked; } int CardWindowManager::proceedToAddModalWindow(CardWindow* win) { Window* maxCardWindow = SystemUiController::instance()->maximizedCardWindow(); CardWindow* activeWin = activeWindow(); // Check if we have an active card if(!maxCardWindow || !activeWin) return SystemUiController::NoMaximizedCard; // Check if the active window is the same as the maximized window if(activeWin != maxCardWindow) return SystemUiController::ParentDifferent; // Get the id of the currently active window ApplicationDescription* desc = activeWin->appDescription(); if(desc) { std::string id = desc->id(); if(id.length() > 0) { // Compare with what the card thinks it's caller is if((0 == win->launchingAppId().compare(id) && (0 == win->launchingProcessId().compare(activeWin->processId())))) { return SystemUiController::NoErr; } else { return SystemUiController::ParentDifferent; } } } else { // If it's a PDK app and we have no appDescription, comparing to appId if(activeWin->isHost()) { if((0 == win->launchingAppId().compare(activeWin->appId()) && (0 == win->launchingProcessId().compare(activeWin->processId())))) { return SystemUiController::NoErr; } else { return SystemUiController::ParentDifferent; } } } return SystemUiController::LaunchUnknown; } void CardWindowManager::prepareAddWindow(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); if(!card) return; if ((card->hostWindowData() != 0) && !card->isHost() && (card->type() != Window::Type_ModalChildWindowCard) && (card->getCardFixedOrientation() == Event::Orientation_Invalid)) { // safeguard code in case the data card was launched right before we changed orientation, resulting // in possibly a landscape card in portrait mode or vice versa bool isCardLandscape = card->hostWindowData()->width() >= card->hostWindowData()->height(); bool isUiLandscape = SystemUiController::instance()->currentUiWidth() >= SystemUiController::instance()->currentUiHeight(); if(isCardLandscape != isUiLandscape) { // we need to resize this card card->flipEventSync(); } } // Proxy cards don't have to wait if (!card->isHost()) { // delay adding a new card if (card->delayPrepare()) { return; } } // If we have a modal card and we cannot add it for whatever reason, just return if(Window::Type_ModalChildWindowCard == win->type() && (SystemUiController::NoErr != (m_dismissModalImmediately = proceedToAddModalWindow(card)))) { m_modalWindowState = ModalWindowAddInitCheckFail; notifySysControllerOfModalStatus(m_dismissModalImmediately, false, ModalLaunch, win); return; } Q_EMIT signalExitReorder(); card->enableShadow(); // Do this ONLY if we are not adding a MODAL window if(Window::Type_ModalChildWindowCard != card->type()) { // If the currently active card is a modal card, make sure we dismiss it as we are going to get a new active card - don't restore the state as the new card will be the active card if(activeWindow() && Window::Type_ModalChildWindowCard == activeWindow()->type()) { m_modalWindowState = ModalWindowDismissedParentSwitched; notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, true, ModalDismissNoAnimate, activeWindow()); // Set the fact that for all purposes m_parentOfModalCard is the currently active card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } } card->setParentItem(this); } else { m_parentOfModalCard = activeWindow(); // Set the desired fields for the modal card. card->setModalParent(m_parentOfModalCard); // Set the desired fields for the parent of the modal card. m_parentOfModalCard->setCardIsModalParent(true); m_parentOfModalCard->setModalChild(card); m_parentOfModalCard->setModalAcceptInputState(CardWindow::ModalLaunchedNotAcceptingInput); // Let the modal window compute it's initial position card->computeModalWindowPlacementInf(-1); // Set the fact that we are adding a modal window m_addingModalWindow = true; } disableCardRestoreToMaximized(); Q_EMIT signalPreparingWindow(card); SystemUiController::instance()->cardWindowAdded(); } void CardWindowManager::prepareAddWindowSibling(CardWindow* win) { if (m_activeGroup && !win->launchInNewGroup()) { CardWindow* activeWin = m_activeGroup->activeCard(); if(Window::Type_ModalChildWindowCard != win->type()) { if ((activeWin->focused() && (win->launchingProcessId() == activeWin->processId() || (win->launchingAppId() == activeWin->appId())))) { // add to active group m_activeGroup->addToFront(win); setActiveGroup(m_activeGroup); m_cardToRestoreToMaximized = activeWin; } else { // spawn new group to the right of active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); newGroup->addToGroup(win); m_groups.insert(m_groups.indexOf(m_activeGroup)+1, newGroup); setActiveGroup(newGroup); } queueFocusAction(activeWin, false); setActiveCardOffScreen(); slideAllGroups(false); startAnimations(); } else { queueFocusAction(activeWin, false); } } else { CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); newGroup->addToGroup(win); m_groups.append(newGroup); setActiveGroup(newGroup); setActiveCardOffScreen(); } SystemUiController::instance()->setCardWindowAboutToMaximize(); SystemUiController::instance()->cardWindowAdded(); } void CardWindowManager::addWindowTimedOut(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); // Host windows shouldn't fire this handler anyways if (card->isHost()) return; if(Window::Type_ModalChildWindowCard == win->type() && -1 != m_dismissModalImmediately) { m_dismissModalImmediately = -1; return; } Q_EMIT signalExitReorder(); m_curState->windowTimedOut(card); SystemUiController::instance()->cardWindowTimeout(); } void CardWindowManager::addWindowTimedOutNormal(CardWindow* win) { m_penDown = false; updateAllowWindowUpdates(); Q_ASSERT(m_activeGroup && m_activeGroup->activeCard() == win); if(Window::Type_ModalChildWindowCard != win->type()) { setActiveCardOffScreen(false); slideAllGroups(); } if(Window::Type_ModalChildWindowCard == win->type() && -1 != m_dismissModalImmediately) { m_dismissModalImmediately = -1; return; } Q_EMIT signalLoadingActiveWindow(); } void CardWindowManager::addWindow(Window* win) { CardWindow* card = static_cast<CardWindow*>(win); card->setAddedToWindowManager(); // process addWindow once preparing has finished if (!card->isHost() && !card->prepareAddedToWindowManager()) return; Q_EMIT signalExitReorder(); m_curState->windowAdded(card); } void CardWindowManager::removeWindow(Window* win) { if(!win) return; CardWindow* card = static_cast<CardWindow*>(win); if(!card) return; Q_EMIT signalExitReorder(); // Either there are no modal window(s) OR we are not deleting the modal parent - default to the plain vanilla delete. if((win->type() != Window::Type_ModalChildWindowCard && false == m_addingModalWindow) || (win->type() != Window::Type_ModalChildWindowCard && false == card->isCardModalParent())) { removeWindowNoModality(card); } else removeWindowWithModality(card); } void CardWindowManager::removeWindowNoModality(CardWindow* win) { if(!win) return; QPropertyAnimation* anim = NULL; if(false == performCommonWindowRemovalTasks(win, true)) return; // slide card off the top of the screen CardWindow::Position pos = win->position(); QRectF r = pos.toTransform().mapRect(win->boundingRect()); qreal offTop = boundingRect().y() - (win->y() + (r.height()/2)); anim = new QPropertyAnimation(win, "y"); anim->setDuration(AS(cardDeleteDuration)); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setEndValue(offTop); QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(win, anim); anim->start(); m_curState->windowRemoved(win); } void CardWindowManager::removeWindowWithModality(CardWindow* win) { CardWindow* card = NULL, *activeCard = NULL; QPropertyAnimation* anim = NULL; bool restore = false; if(!win) return; activeCard = activeWindow(); if(!activeCard) return; card = win; restore = (activeCard == card && Window::Type_ModalChildWindowCard == card->type()) ? true:false; // If the modal card was deleted because it's parent was deleted externally, don't run any of these, simply remove the modal and return if(Window::Type_ModalChildWindowCard == card->type() && m_modalWindowState == ModalParentDimissedWaitForChildDismissal && NULL == m_parentOfModalCard) { handleModalRemovalForDeletedParent(card); m_modalWindowState = NoModalWindow; return; } /* This function is called externally by some component when it wants the CardWindow to go away. Also when ::closeWindow's call to win->close will result in a call to this function. For the modal windows, we have 2 cases to consider. 1) ::removeWindow is called on a modal window by an external component. 2) ::removeWindow is called on a modal window by as a result of a call to ::closeWindow. We also need to consider the case if the modal was even added. */ // This is not a part of a call to closeWindow and came by externally. This means there is NO need to call close on the window again. if(false == m_modalDismissInProgress) { SystemUiController::ModalWinDismissErrorReason dismiss = SystemUiController::DismissUnknown; // We are removing a modal card externally if(Window::Type_ModalChildWindowCard == card->type()) { m_modalWindowState = ModalWindowDismissedExternally; } // check if w is a modal parent else if(true == card->isCardModalParent() && (Window::Type_ModalChildWindowCard == activeWindow()->type())) { m_modalWindowState = ModalParentDismissed; dismiss = SystemUiController::ParentCardDismissed; } notifySysControllerOfModalStatus(dismiss, restore, ModalDismissNoAnimate); } else { m_modalDismissInProgress = false; } // Signal that we no longer have an active modal window - Either the modal is getting dismissed/parent is getting dismissed/modal add failed as the parent was different etc if(true == restore || m_modalWindowState == ModalParentDismissed || m_modalWindowState == ModalWindowAddInitCheckFail || m_modalWindowState == ModalWindowDismissedParentSwitched) SystemUiController::instance()->notifyModalWindowDeactivated(); // Reset in different ways (if true == restore => modal card was added successfully and is the card being deleted. if(true == restore) resetModalFlags(); // If we are deleting the modal card because of a failure during initialization, just reset the flags here. else if(m_modalWindowState == ModalWindowAddInitCheckFail) resetModalFlags(true); else if(m_modalWindowState == ModalParentDismissed) { // modal parent is deleted - Do the following to make things smoother. // 1 - Make the modal card invisible. // 2 - Set that the parent no longer has a modal child. (Don't reset the state) activeCard->setVisible(false); if(m_parentOfModalCard) { m_parentOfModalCard->setCardIsModalParent(false); m_parentOfModalCard->setModalChild(NULL); m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } } else if(m_modalWindowState == ModalWindowDismissedParentSwitched) { resetModalFlags(true); } if(false == performCommonWindowRemovalTasks(card, (m_modalWindowState == ModalParentDismissed)?true:false)) return; if(Window::Type_ModalChildWindowCard != card->type()) { // slide card off the top of the screen CardWindow::Position pos = card->position(); QRectF r = pos.toTransform().mapRect(card->boundingRect()); qreal offTop = boundingRect().y() - (card->y() + (r.height()/2)); anim = new QPropertyAnimation(card, "y"); anim->setDuration(AS(cardDeleteDuration)); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setEndValue(offTop); } else if(true == m_animateWindowForModalDismisal){ anim = new QPropertyAnimation(); } QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(card, anim); if(true == m_animateWindowForModalDismisal) anim->start(); m_curState->windowRemoved(card); // Finally if we are deleting a modal parent, clean reset the state if(m_modalWindowState == ModalParentDismissed) { resetModalFlags(true); m_modalWindowState = ModalParentDimissedWaitForChildDismissal; } } void CardWindowManager::handleModalRemovalForDeletedParent(CardWindow* card) { if(NULL == card || Window::Type_ModalChildWindowCard != card->type()) return; // ignore the return value. performCommonWindowRemovalTasks(card, false); } bool CardWindowManager::performCommonWindowRemovalTasks(CardWindow* card, bool checkCardGroup) { if(!card) return false; removePendingActionWindow(card); // Mark window as removed. Its safe to delete this now card->setRemoved(); // Is it already on the deleted animation list? if (m_deletedAnimMap.contains(card)) { // if it is animating, let it finish which will delete it QPropertyAnimation* a = m_deletedAnimMap.value(card); if (a && a->state() != QAbstractAnimation::Running) { // nuke the animation removeAnimationForWindow(card, true); delete card; } return false; } if(true == checkCardGroup) Q_ASSERT(card->cardGroup() != 0); removeAnimationForWindow(card); return true; } void CardWindowManager::initiateRemovalOfActiveModalWindow() { // Ensure that the last window we added was a modal window if(true == m_addingModalWindow) { CardWindow* activeWin = activeWindow(); // ERROR. DONT KNOW WHICH CARD WILL BE THE NEW ACTIVE CARD if(!activeWin) { g_warning("Unable to get active modal window %s", __PRETTY_FUNCTION__); return; } // Techinically this should never happen, but just in case. if(!m_parentOfModalCard) m_parentOfModalCard = static_cast<CardWindow*>(activeWin->parentItem()); if(!m_parentOfModalCard) { g_warning("Unable to get parent of active modal window %s", __PRETTY_FUNCTION__); return; } // Start an animation for the opacity of the currently active modal window QPropertyAnimation* winAnim = new QPropertyAnimation(activeWin, "opacity"); winAnim->setEndValue(0.0); winAnim->setDuration(kModalWindowAnimationTimeout); // connect to the slot that gets called when this animation gets done. connect(winAnim, SIGNAL(finished()), SLOT(slotOpacityAnimationFinished())); // start the animation winAnim->start(QAbstractAnimation::DeleteWhenStopped); } } void CardWindowManager::resetModalFlags(bool forceReset) { m_addingModalWindow = false; m_initModalMaximizing = false; m_modalDismissInProgress = false; m_modalDimissed = false; m_dismissModalImmediately = -1; if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } if(true == forceReset) m_parentOfModalCard = NULL; } void CardWindowManager::performPostModalWindowRemovedActions(Window* win, bool restore) { CardWindow* activeWin = (NULL != win)? (static_cast<CardWindow*>(win)) : activeWindow(); if(!activeWin) { g_warning("Unable to get active modal window %s", __PRETTY_FUNCTION__); // Set the parent to the first card of the active card group. if(m_activeGroup) m_activeGroup->makeBackCardActive(); return; } // call close ONLY if the modal was deleted internally if(ModalWindowDismissedExternally != m_modalWindowState || NoModalWindow != m_modalWindowState) { closeWindow(activeWin); } // Make the parent card as the active card. Notify SysUiController of this fact as well. No animations are needed as the parent is already the active card in full screen if(true == restore && NULL != m_parentOfModalCard) { m_modalDimissed = true; // Just set this flag so that the parent doesn't forward events to the modal card anymore m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); // Set the new maximized/active cards. SystemUiController::instance()->setMaximizedCardWindow(m_parentOfModalCard); SystemUiController::instance()->setActiveCardWindow(m_parentOfModalCard); // PDK apps need both Focus and Maximized events to be sent to them to direct render. The call above will give focus, disable DR here and resetModalFlags will re-enable DR on the parent if(m_parentOfModalCard->isHost()) { SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, m_parentOfModalCard, false); } // If we are restoring the parent state coz of active card being switched, don't start an animation, but do all the actions in sequence if(ModalWindowDismissedParentSwitched != m_modalWindowState) { // Queue up the fact that we need to give focus back to the parent queueFocusAction(m_parentOfModalCard, true); // Create an empty animation and add to m_anims.start(). When it completes, it'll call performPendingFocusActions(); to give focus back to the parent. QPropertyAnimation* anim = new QPropertyAnimation(); m_anims.addAnimation(anim); m_anims.start(); } else { // we have a modal card as the active card and a new card is being added to the system. Perform all the actions here. if (m_activeGroup) { m_activeGroup->raiseCards(); } m_parentOfModalCard->aboutToFocusEvent(true); m_parentOfModalCard->queueFocusAction(true); m_parentOfModalCard->performPendingFocusAction(); m_curState->animationsFinished(); m_animationsActive = false; updateAllowWindowUpdates(); //CardWindowManagerStates relies on m_addingModalWindow for it's states. Don't call resetModalFlags, just change this flag m_addingModalWindow = false; } } else { if(!((ModalWindowAddInitCheckFail == m_modalWindowState) || (ModalParentDismissed == m_modalWindowState) || (ModalWindowDismissedParentSwitched == m_modalWindowState))) { resetModalFlags(); } } // Finally - if the modal was dismissed externally then make it invisible here so that it doesn't linger around. ResetModal() will clear out the flags on the parent if((ModalWindowDismissedExternally == m_modalWindowState || ModalWindowDismissedParentSwitched == m_modalWindowState) && (activeWin->type() == Window::Type_ModalChildWindowCard)) activeWin->setVisible(false); } void CardWindowManager::slotOpacityAnimationFinished() { performPostModalWindowRemovedActions(NULL, true); } void CardWindowManager::removeCardFromGroup(CardWindow* win, bool adjustLayout) { if(Window::Type_ModalChildWindowCard == win->type()) return; CardGroup* group = win->cardGroup(); luna_assert(group != 0); group->removeFromGroup(win); if (group->empty()) { // clean up this group m_groups.remove(m_groups.indexOf(group)); removeAnimationForGroup(group); delete group; } // make sure we aren't holding a reference to a soon to be deleted card if (m_draggedWin == win) { // clear any dragging state resetMouseTrackState(); } // If we are removing a modal dialog , we don't need these. if(adjustLayout) { // select a new active group setActiveGroup(groupClosestToCenterHorizontally()); // make sure everything is positioned properly slideAllGroups(); } } void CardWindowManager::removeCardFromGroupMaximized(CardWindow* win) { IMEController::instance()->removeClient(win); if(Window::Type_ModalChildWindowCard == win->type()) return; // Switch out only if we are the active window if (activeWindow() == win) { Q_EMIT signalMinimizeActiveWindow(); removeCardFromGroup(win); return; }else if(NULL != m_parentOfModalCard && m_parentOfModalCard == win && true == m_parentOfModalCard->isCardModalParent()) { removeCardFromGroup(win); return; } removeCardFromGroup(win, false); } void CardWindowManager::layoutGroups(qreal xDiff) { if (!m_activeGroup || m_groups.empty()) return; int activeGroupPosition = m_groups.indexOf(m_activeGroup); removeAnimationForGroup(m_activeGroup); m_activeGroup->setX(m_activeGroup->x() + xDiff); int centerX = -m_activeGroup->left() - kGapBetweenGroups + m_activeGroup->x(); for (int i=activeGroupPosition-1; i>=0; i--) { centerX += -m_groups[i]->right(); removeAnimationForGroup(m_groups[i]); m_groups[i]->setX(centerX); centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups + m_activeGroup->x(); for (int i=activeGroupPosition+1; i<m_groups.size(); i++) { centerX += m_groups[i]->left(); removeAnimationForGroup(m_groups[i]); m_groups[i]->setX(centerX); centerX += kGapBetweenGroups + m_groups[i]->right(); } } void CardWindowManager::maximizeActiveWindow(bool animate) { if (!m_activeGroup) return; Q_EMIT signalExitReorder(); QRect r; // If the currently active card window is a modal window, don't do any of these operations except If we are doing this as a part of rotation if(activeWindow()->type() != Window::Type_ModalChildWindowCard || (activeWindow()->type() == Window::Type_ModalChildWindowCard && true == SystemUiController::instance()->isUiRotating())) { m_activeGroup->raiseCards(); setActiveGroup(m_activeGroup); if(animate) slideAllGroups(false); else layoutAllGroups(false); if(activeWindow()->type() != Window::Type_ModalChildWindowCard) r = normalOrScreenBounds(m_activeGroup->activeCard()); else if(NULL != m_parentOfModalCard) r = normalOrScreenBounds(m_parentOfModalCard); if(animate) { QList<QPropertyAnimation*> maxAnims = m_activeGroup->maximizeActiveCard(r.y()/2); Q_FOREACH(QPropertyAnimation* anim, maxAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } startAnimations(); } else { m_activeGroup->maximizeActiveCardNoAnimation(r.y()/2); } } else { // Create an empty animation and add to m_anims.start(). When it completes, it'll call performPendingFocusActions(); to give focus to the active card. QPropertyAnimation* anim = new QPropertyAnimation(); m_anims.addAnimation(anim); if(false == m_initModalMaximizing) { // Notify SystemUiController that the modal window was added successfully. if(true == m_addingModalWindow) { // Notify SysUiController that we have setup a modal notifySysControllerOfModalStatus(SystemUiController::NoErr, false, ModalLaunch, activeWindow()); } m_initModalMaximizing = true; } // start the animations startAnimations(); } Q_EMIT signalMaximizeActiveWindow(); } void CardWindowManager::slotMaximizeActiveCardWindow() { if(false == m_addingModalWindow) maximizeActiveWindow(); } void CardWindowManager::minimizeActiveWindow(bool animate) { disableCardRestoreToMaximized(); Q_EMIT signalExitReorder(); if (m_activeGroup) m_activeGroup->raiseCards(); // always allow transitions to minimized mode if(false == m_addingModalWindow) { Q_EMIT signalMinimizeActiveWindow(); if(animate) slideAllGroups(); else layoutAllGroups(); } else { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::UiMinimized, true, ModalDismissAnimate); } } void CardWindowManager::markFirstCardDone() { g_message("[%s]: DEBUG: staring markFirstCardDone.", __PRETTY_FUNCTION__); m_dismissedFirstCard=true; // For first-use mode, touch a marker file on the filesystem //if (Settings::LunaSettings()->uiType == Settings::UI_MINIMAL) { g_mkdir_with_parents(Settings::LunaSettings()->lunaPrefsPath.c_str(), 0755); FILE* f = fopen(Settings::LunaSettings()->firstCardLaunch.c_str(), "w"); fclose(f); //} } void CardWindowManager::firstCardAlert() { if(!m_dismissedFirstCard){ Q_EMIT signalFirstCardRun(); markFirstCardDone(); } } void CardWindowManager::handleKeyNavigationMinimized(QKeyEvent* keyEvent) { if (!m_activeGroup || keyEvent->type() != QEvent::KeyPress) return; switch (keyEvent->key()) { case Qt::Key_Left: switchToPrevApp(); break; case Qt::Key_Right: switchToNextApp(); break; case Qt::Key_Return: if (!keyEvent->isAutoRepeat()) maximizeActiveWindow(); break; case Qt::Key_Backspace: if ((keyEvent->modifiers() & Qt::ControlModifier) && !keyEvent->isAutoRepeat()) closeWindow(activeWindow()); break; default: break; } } void CardWindowManager::slotMinimizeActiveCardWindow() { if(false == m_addingModalWindow) minimizeActiveWindow(); else { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::HomeButtonPressed, true, ModalDismissAnimate); } } void CardWindowManager::setActiveCardOffScreen(bool fullsize) { CardWindow* activeCard = activeWindow(); if (!activeCard) return; // safety precaution removeAnimationForWindow(activeCard); CardWindow::Position pos; qreal yOffset = boundingRect().bottom() - activeCard->y(); pos.trans.setZ(fullsize ? 1.0 : kActiveScale); pos.trans.setY(yOffset - activeCard->boundingRect().y() * pos.trans.z()); activeCard->setPosition(pos); } void CardWindowManager::mousePressEvent(QGraphicsSceneMouseEvent* event) { // We may get a second pen down. Just ignore it. if (m_penDown) return; resetMouseTrackState(); if (m_groups.empty() || !m_activeGroup) return; m_penDown = true; updateAllowWindowUpdates(); m_curState->mousePressEvent(event); } void CardWindowManager::mouseDoubleClickEvent(QGraphicsSceneMouseEvent* event) { mousePressEvent(event); } void CardWindowManager::mouseMoveEvent(QGraphicsSceneMouseEvent* event) { if (!m_penDown || m_seenFlickOrTap) return; m_curState->mouseMoveEvent(event); } void CardWindowManager::mouseReleaseEvent(QGraphicsSceneMouseEvent* event) { if (m_penDown) m_curState->mouseReleaseEvent(event); resetMouseTrackState(); } bool CardWindowManager::playAngryCardSounds() const { return WindowServer::instance()->getUiOrientation() == OrientationEvent::Orientation_Down; } bool CardWindowManager::sceneEvent(QEvent* event) { if (event->type() == QEvent::GestureOverride && m_curState != m_maximizeState) { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g) { event->accept(); return true; } g = ge->gesture(Qt::TapAndHoldGesture); if (g) { event->accept(); return true; } g = ge->gesture((Qt::GestureType) SysMgrGestureFlick); if (g) { event->accept(); return true; } } else if (event->type() == QEvent::Gesture) { QGestureEvent* ge = static_cast<QGestureEvent*>(event); QGesture* g = ge->gesture(Qt::TapGesture); if (g) { QTapGesture* tap = static_cast<QTapGesture*>(g); if (tap->state() == Qt::GestureFinished) { tapGestureEvent(tap); } return true; } g = ge->gesture(Qt::TapAndHoldGesture); if (g) { QTapAndHoldGesture* hold = static_cast<QTapAndHoldGesture*>(g); if (hold->state() == Qt::GestureFinished) { tapAndHoldGestureEvent(hold); } return true; } g = ge->gesture((Qt::GestureType) SysMgrGestureFlick); if (g) { FlickGesture* flick = static_cast<FlickGesture*>(g); if (flick->state() == Qt::GestureFinished) { flickGestureEvent(ge); } return true; } } return QGraphicsObject::sceneEvent(event); } void CardWindowManager::tapGestureEvent(QTapGesture* event) { if (!m_penDown) return; m_seenFlickOrTap = true; if (m_groups.empty() || !m_activeGroup) return; m_curState->tapGestureEvent(event); } void CardWindowManager::tapAndHoldGestureEvent(QTapAndHoldGesture* event) { if (!m_penDown) return; if (m_groups.empty() || !m_activeGroup) return; m_curState->tapAndHoldGestureEvent(event); } void CardWindowManager::handleTapAndHoldGestureMinimized(QTapAndHoldGesture* event) { QPoint pt = mapFromScene(event->position()).toPoint(); if (m_activeGroup->setActiveCard(event->position())) { // start reordering the active card Q_EMIT signalEnterReorder(pt, s_marginSlice); } else if (pt.x() < 0) { switchToPrevGroup(); } else { switchToNextGroup(); } } void CardWindowManager::flickGestureEvent(QGestureEvent* event) { g_message("%s", __PRETTY_FUNCTION__); if (!m_penDown || m_seenFlickOrTap) return; m_seenFlickOrTap = true; if (m_groups.empty() || !m_activeGroup) return; m_curState->flickGestureEvent(event); } void CardWindowManager::handleFlickGestureMinimized(QGestureEvent* event) { QGesture* g = event->gesture((Qt::GestureType) SysMgrGestureFlick); if (!g) return; FlickGesture* flick = static_cast<FlickGesture*>(g); if (m_movement == MovementVLocked) { if (!m_draggedWin) { slideAllGroups(); return; } QPointF start = mapFromScene(event->mapToGraphicsScene(flick->hotSpot())); QPointF end = mapFromScene(event->mapToGraphicsScene(flick->endPos())); int distanceY = end.y() - start.y(); static const int flickDistanceVelocityMultiplied = kFlickToCloseWindowVelocityThreshold * kFlickToCloseWindowDistanceThreshold; QRectF pr = m_draggedWin->mapRectToParent(m_draggedWin->boundingRect()); if (distanceY < kFlickToCloseWindowDistanceThreshold && flick->velocity().y() < kFlickToCloseWindowMinimumVelocity && flick->velocity().y() < (flickDistanceVelocityMultiplied / distanceY)) { closeWindow(m_draggedWin); } else if (pr.center().y() > boundingRect().bottom()) { closeWindow(m_draggedWin, true); } else if (pr.center().y() < boundingRect().top()) { closeWindow(m_draggedWin); } else { slideAllGroups(); } } else if (m_movement == MovementHLocked) { if (m_trackWithinGroup) { // adjust the fanning position within the group based on the users flick velocity m_activeGroup->flick(flick->velocity().x()); setActiveGroup(m_activeGroup); slideAllGroups(); } else { // advance to the next/previous group if we are Outer Locked or were still unbiased horizontally if (flick->velocity().x() > 0) switchToPrevGroup(); else switchToNextGroup(); } } } void CardWindowManager::handleMousePressMinimized(QGraphicsSceneMouseEvent* event) { // try to capture the card the user first touched if (m_activeGroup && m_activeGroup->setActiveCard(event->scenePos())) m_draggedWin = m_activeGroup->activeCard(); } void CardWindowManager::handleMouseMoveMinimized(QGraphicsSceneMouseEvent* event) { if (m_groups.isEmpty() || !m_activeGroup) return; QPoint delta = (event->pos() - event->buttonDownPos(Qt::LeftButton)).toPoint(); QPoint diff; // distance move between last and current mouse position // lock movement to an axis if (m_movement == MovementUnlocked) { if ((delta.x() * delta.x() + delta.y() * delta.y()) < Settings::LunaSettings()->tapRadiusSquared) return; if (abs(delta.x()) > 0.866 * abs(delta.y())) { m_movement = MovementHLocked; m_activeGroupPivot = m_activeGroup->x(); } else { m_movement = MovementVLocked; } diff = delta; } else { diff = (event->pos() - event->lastPos()).toPoint(); } if (m_movement == MovementHLocked) { if (m_trackWithinGroup) { m_trackWithinGroup = !m_activeGroup->atEdge(diff.x()); if (m_trackWithinGroup) { // shift cards within the active group m_activeGroup->adjustHorizontally(diff.x()); slideAllGroups(); } else { m_activeGroupPivot = m_activeGroup->x(); } } if (!m_trackWithinGroup) { m_activeGroupPivot += diff.x(); slideAllGroupsTo(m_activeGroupPivot); } } else if (m_movement == MovementVLocked) { if (!m_draggedWin) { if (m_activeGroup->setActiveCard(event->scenePos())) m_draggedWin = m_activeGroup->activeCard(); if (!m_draggedWin) return; } // ignore pen movements outside the vertical pillar around the active window QPointF mappedPos = m_draggedWin->mapFromParent(event->pos()); if (mappedPos.x() < m_draggedWin->boundingRect().x() || mappedPos.x() >= m_draggedWin->boundingRect().right()) { return; } if (delta.y() == 0) return; if (!m_playedAngryCardStretchSound && (delta.y() > kAngryCardThreshold) && playAngryCardSounds()) { SoundPlayerPool::instance()->playFeedback("carddrag"); m_playedAngryCardStretchSound = true; } removeAnimationForWindow(m_draggedWin); // cards are always offset from the parents origin CardWindow::Position pos = m_draggedWin->position(); pos.trans.setY(delta.y()); m_draggedWin->setPosition(pos); } } void CardWindowManager::handleMouseMoveReorder(QGraphicsSceneMouseEvent* event) { CardWindow* activeWin = activeWindow(); if (!activeWin) return; // track the active window under the users finger QPoint delta = (event->pos() - event->lastPos()).toPoint(); CardWindow::Position pos; pos.trans = QVector3D(activeWin->position().trans.x() + delta.x(), activeWin->position().trans.y() + delta.y(), kActiveScale); activeWin->setPosition(pos); // should we switch zones? ReorderZone newZone = getReorderZone(event->pos().toPoint()); if (newZone == m_reorderZone && newZone == ReorderZone_Center) { moveReorderSlotCenter(event->pos()); } else if (newZone != m_reorderZone) { if (newZone == ReorderZone_Right) { m_reorderZone = newZone; moveReorderSlotRight(); } else if (newZone == ReorderZone_Left) { m_reorderZone = newZone; moveReorderSlotLeft(); } else { m_reorderZone = newZone; } } } CardWindowManager::ReorderZone CardWindowManager::getReorderZone(QPoint pt) { qreal section = boundingRect().width() / s_marginSlice; if (pt.x() < boundingRect().left() + section) { return ReorderZone_Left; } else if (pt.x() > boundingRect().right() - section) { return ReorderZone_Right; } return ReorderZone_Center; } void CardWindowManager::enterReorder(QPoint pt) { CardWindow* activeWin = activeWindow(); luna_assert(activeWin != 0); activeWin->setOpacity(0.8); activeWin->disableShadow(); activeWin->setAttachedToGroup(false); // get our initial zone m_reorderZone = getReorderZone(pt); } void CardWindowManager::cycleReorderSlot() { if (m_reorderZone == ReorderZone_Right) moveReorderSlotRight(); else if (m_reorderZone == ReorderZone_Left) moveReorderSlotLeft(); } void CardWindowManager::moveReorderSlotCenter(QPointF pt) { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; // NOTE: it is assumed that the active card has already // been repositioned when making this check if (m_activeGroup->moveActiveCard()) { m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } setActiveGroup(m_activeGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::moveReorderSlotRight() { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; CardGroup* newActiveGroup = m_activeGroup; // have we reached the top card in the group? if (m_activeGroup->moveActiveCard(1)) { // no, update the stacking order within the group m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } else if (m_activeGroup != m_groups.last() || m_activeGroup->size() > 1) { CardWindow* activeWin = activeWindow(); int activeIndex = m_groups.indexOf(m_activeGroup); // yes, remove from the active group m_activeGroup->removeFromGroup(activeWin); if (m_activeGroup->empty()) { // this was a temporarily created group. // delete the temp group. m_groups.remove(activeIndex); delete m_activeGroup; newActiveGroup = m_groups[activeIndex]; } else { // this was an existing group. // insert a new group to the right of the current active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); m_groups.insert(activeIndex+1, newGroup); newActiveGroup = newGroup; } newActiveGroup->addToBack(activeWin); newActiveGroup->raiseCards(); duration = AS(cardGroupReorderDuration); curve = AS_CURVE(cardGroupReorderCurve); animate = true; } setActiveGroup(newActiveGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::moveReorderSlotLeft() { bool animate = false; int duration = 0; QEasingCurve::Type curve = QEasingCurve::Linear; CardGroup* newActiveGroup = m_activeGroup; // have we reached the bottom card in the group? if (m_activeGroup->moveActiveCard(-1)) { // no, update the stacking order within the group m_activeGroup->raiseCards(); duration = AS(cardShuffleReorderDuration); curve = AS_CURVE(cardShuffleReorderCurve); animate = true; } else if (m_activeGroup != m_groups.first() || m_activeGroup->size() > 1) { CardWindow* activeWin = activeWindow(); int activeIndex = m_groups.indexOf(m_activeGroup); // yes, remove from the active group m_activeGroup->removeFromGroup(activeWin); if (m_activeGroup->empty()) { // this was a temporarily created group. // delete the temp group m_groups.remove(activeIndex); delete m_activeGroup; // the previous group is the new active group newActiveGroup = m_groups[qMax(0, activeIndex-1)]; } else { // this was an existing group. // insert a new group to the left of the current active group CardGroup* newGroup = new CardGroup(kActiveScale, kNonActiveScale); newGroup->setPos(QPointF(0, kWindowOrigin)); m_groups.insert(activeIndex, newGroup); newActiveGroup = newGroup; } newActiveGroup->addToFront(activeWin); newActiveGroup->raiseCards(); duration = AS(cardGroupReorderDuration); curve = AS_CURVE(cardGroupReorderCurve); animate = true; } setActiveGroup(newActiveGroup); if (animate) arrangeWindowsAfterReorderChange(duration, curve); } void CardWindowManager::arrangeWindowsAfterReorderChange(int duration, QEasingCurve::Type curve) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardShuffleReorderCurve)); anim->setDuration(AS(cardShuffleReorderDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(duration, curve, false); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(duration, curve); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(curve); anim->setDuration(duration); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(duration, curve); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(curve); anim->setDuration(duration); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::handleMouseReleaseMinimized(QGraphicsSceneMouseEvent* event) { if (m_groups.empty() || m_seenFlickOrTap) return; if (m_movement == MovementVLocked) { // Did we go too close to the top? if (m_draggedWin) { QRectF pr = m_draggedWin->mapRectToParent(m_draggedWin->boundingRect()); if ((!event->canceled()) && (pr.center().y() > boundingRect().bottom())) { closeWindow(m_draggedWin, true); } else if ((!event->canceled()) && (pr.center().y() < boundingRect().top())) { closeWindow(m_draggedWin); } else { // else just restore all windows back to original position slideAllGroups(); } } } else if (m_movement == MovementHLocked) { if(!event->canceled()) setActiveGroup(groupClosestToCenterHorizontally()); slideAllGroups(); } } void CardWindowManager::handleMouseReleaseReorder(QGraphicsSceneMouseEvent* event) { Q_UNUSED(event) Q_EMIT signalExitReorder(false); CardWindow* activeWin = activeWindow(); if (!activeWin) return; // TODO: fix the y for the draggedWin activeWin->setOpacity(1.0); activeWin->enableShadow(); activeWin->setAttachedToGroup(true); slideAllGroups(); } void CardWindowManager::handleTapGestureMinimized(QTapGesture* event) { if (!m_activeGroup) return; //Things that must be done here: //--Perform a hit test to determine if the current active group was hit if (m_activeGroup->testHit(event->position())) { //--If it was, then we need to see if the card hit was in a reasonable // range of the active card. If it was then maximize it. If it was not // slide the card fan over to make it more visible. if (m_activeGroup->shouldMaximizeOrScroll(event->position())) { m_activeGroup->setActiveCard(event->position()); m_activeGroup->moveToActiveCard(); maximizeActiveWindow(); } else { slideAllGroups(); } } else { // first test to see if the tap is not above/below the active group QPointF pt = mapFromScene(event->position()); if (!m_activeGroup->withinColumn(pt)) { if (pt.x() < 0) { // tapped to the left of the active group switchToPrevGroup(); } else { // tapped to the right of the active group switchToNextGroup(); } } else { // poke the groups to make sure they animate to their final positions slideAllGroups(); } } } CardGroup* CardWindowManager::groupClosestToCenterHorizontally() const { if (m_groups.empty()) return 0; qreal deltaX = FLT_MAX; qreal curDeltaX = 0; CardGroup* grp = 0; Q_FOREACH(CardGroup* cg, m_groups) { curDeltaX = qAbs(cg->pos().x()); if (curDeltaX < deltaX) { grp = cg; deltaX = curDeltaX; } } return grp; } void CardWindowManager::setActiveGroup(CardGroup* group) { m_activeGroup = group; SystemUiController::instance()->setActiveCardWindow(m_activeGroup ? m_activeGroup->activeCard() : 0); } void CardWindowManager::switchToNextApp() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (!m_activeGroup->makeNextCardActive()) { // couldn't move, switch to the next group int index = m_groups.indexOf(m_activeGroup); if (index < m_groups.size() - 1) { m_activeGroup = m_groups[index + 1]; m_activeGroup->makeBackCardActive(); } } setActiveGroup(m_activeGroup); slideAllGroups(); } void CardWindowManager::switchToPrevApp() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (!m_activeGroup->makePreviousCardActive()) { // couldn't move, switch to the previous group int index = m_groups.indexOf(m_activeGroup); if (index > 0) { m_activeGroup = m_groups[index - 1]; m_activeGroup->makeFrontCardActive(); } } setActiveGroup(m_activeGroup); slideAllGroups(); } void CardWindowManager::switchToNextGroup() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (m_activeGroup == m_groups.last()) { slideAllGroups(); return; } int activeGroupIndex = m_groups.indexOf(m_activeGroup); activeGroupIndex++; activeGroupIndex = qMin(activeGroupIndex, m_groups.size() - 1); setActiveGroup(m_groups[activeGroupIndex]); slideAllGroups(); } void CardWindowManager::switchToPrevGroup() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; if (m_activeGroup == m_groups.first()) { slideAllGroups(); return; } int activeGroupIndex = m_groups.indexOf(m_activeGroup); activeGroupIndex--; activeGroupIndex = qMax(activeGroupIndex, 0); setActiveGroup(m_groups[activeGroupIndex]); slideAllGroups(); } void CardWindowManager::switchToNextAppMaximized() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; CardWindow* oldActiveCard = activeWindow(); if(!oldActiveCard) return; // Check if the currently active card is a modal card. If so dismiss it if(Window::Type_ModalChildWindowCard == oldActiveCard->type()) { // We don't need to run any animations m_animateWindowForModalDismisal = false; // Set the reason for dismissal m_modalWindowState = ModalWindowDismissedParentSwitched; // Notify SysUi Controller that we no longer have a modal active notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate); // Set the fact that for all purposes m_parentOfModalCard is the currently ative card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } // Get the old active window for further use oldActiveCard = activeWindow(); } SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, oldActiveCard, false); if (!m_activeGroup->makeNextCardActive()) { if (m_activeGroup == m_groups.last()) { // shift card off to the side and let it slide back CardWindow::Position pos = oldActiveCard->position(); pos.trans.setX(pos.trans.x() - 40); oldActiveCard->setPosition(pos); } else { // switch to the bottom card of the next group int index = m_groups.indexOf(m_activeGroup); setActiveGroup(m_groups[index+1]); m_activeGroup->makeBackCardActive(); } } CardWindow* newActiveCard = activeWindow(); if (oldActiveCard != newActiveCard) { QRect r(normalOrScreenBounds(0)); if (oldActiveCard->allowResizeOnPositiveSpaceChange()) oldActiveCard->resizeEventSync(r.width(), r.height()); else oldActiveCard->adjustForPositiveSpaceSize(r.width(), r.height()); queueFocusAction(oldActiveCard, false); oldActiveCard->setAttachedToGroup(true); queueFocusAction(newActiveCard, true); newActiveCard->setAttachedToGroup(false); QRectF boundingRect = normalOrScreenBounds(0); oldActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); boundingRect = normalOrScreenBounds(newActiveCard); newActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); SystemUiController::instance()->setMaximizedCardWindow(newActiveCard); } // maximize the new active window maximizeActiveWindow(); } void CardWindowManager::switchToPrevAppMaximized() { disableCardRestoreToMaximized(); if (!m_activeGroup || m_groups.empty()) return; CardWindow* oldActiveCard = activeWindow(); // Check if the currently active card is a modal card. If so dismiss it if(Window::Type_ModalChildWindowCard == oldActiveCard->type()) { // We don't need to run any animations m_animateWindowForModalDismisal = false; // Set the reason for dismissal m_modalWindowState = ModalWindowDismissedParentSwitched; // Notify SysUi Controller that we no longer have a modal active notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate); // Set the fact that for all purposes m_parentOfModalCard is the currently ative card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); } // Get the old active window for further use oldActiveCard = activeWindow(); } SystemUiController::instance()->setDirectRenderingForWindow(SystemUiController::CARD_WINDOW_MANAGER, oldActiveCard, false); if (!m_activeGroup->makePreviousCardActive()) { if (m_activeGroup == m_groups.first()) { // shift card off to the side and let it slide back CardWindow::Position pos = oldActiveCard->position(); pos.trans.setX(pos.trans.x() + 40); oldActiveCard->setPosition(pos); } else { // shift to the bottom card in the next group int index = m_groups.indexOf(m_activeGroup); setActiveGroup(m_groups[index-1]); m_activeGroup->makeFrontCardActive(); } } CardWindow* newActiveCard = activeWindow(); if (oldActiveCard != newActiveCard) { // current maximized card QRect r(normalOrScreenBounds(0)); if (oldActiveCard->allowResizeOnPositiveSpaceChange()) oldActiveCard->resizeEventSync(r.width(), r.height()); else oldActiveCard->adjustForPositiveSpaceSize(r.width(), r.height()); queueFocusAction(oldActiveCard, false); oldActiveCard->setAttachedToGroup(true); queueFocusAction(newActiveCard, true); newActiveCard->setAttachedToGroup(false); QRectF boundingRect = normalOrScreenBounds(0); oldActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); boundingRect = normalOrScreenBounds(newActiveCard); newActiveCard->setBoundingRect(boundingRect.width(), boundingRect.height()); SystemUiController::instance()->setMaximizedCardWindow(newActiveCard); } // maximize the new active window maximizeActiveWindow(); } void CardWindowManager::slideAllGroups(bool includeActiveCard) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(200, QEasingCurve::OutCubic, includeActiveCard); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } if (includeActiveCard) startAnimations(); } void CardWindowManager::slideAllGroupsTo(int xOffset) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(xOffset); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), xOffset); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups + xOffset; for (int i=activeGrpIndex-1; i>=0;i--) { centerX += -m_groups[i]->right(); cardAnims = m_groups[i]->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), centerX); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups + xOffset; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { centerX += m_groups[i]->left(); cardAnims = m_groups[i]->animateCloseWithOffset(AS(cardTrackDuration), AS_CURVE(cardTrackCurve), centerX); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardTrackGroupCurve)); anim->setDuration(AS(cardTrackGroupDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::layoutAllGroups(bool includeActiveCard) { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); m_activeGroup->layoutCards(true, includeActiveCard); int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { m_groups[i]->layoutCards(false, false); centerX += -m_groups[i]->right(); m_groups[i]->setX(centerX); centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { m_groups[i]->layoutCards(false, false); centerX += m_groups[i]->left(); m_groups[i]->setX(centerX); centerX += kGapBetweenGroups + m_groups[i]->right(); } } void CardWindowManager::slideToActiveCard() { if (m_groups.empty() || !m_activeGroup) return; int activeGrpIndex = m_groups.indexOf(m_activeGroup); clearAnimations(); QPropertyAnimation* anim = new QPropertyAnimation(m_activeGroup, "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(0); setAnimationForGroup(m_activeGroup, anim); QList<QPropertyAnimation*> cardAnims = m_activeGroup->animateOpen(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } int centerX = -m_activeGroup->left() - kGapBetweenGroups; for (int i=activeGrpIndex-1; i>=0;i--) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += -m_groups[i]->right(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += -kGapBetweenGroups - m_groups[i]->left(); } centerX = m_activeGroup->right() + kGapBetweenGroups; for (int i=activeGrpIndex+1; i<m_groups.size(); i++) { cardAnims = m_groups[i]->animateClose(AS(cardSlideDuration), AS_CURVE(cardSlideCurve)); centerX += m_groups[i]->left(); anim = new QPropertyAnimation(m_groups[i], "x"); anim->setEasingCurve(AS_CURVE(cardSlideCurve)); anim->setDuration(AS(cardSlideDuration)); anim->setEndValue(centerX); setAnimationForGroup(m_groups[i], anim); Q_FOREACH(QPropertyAnimation* anim, cardAnims) { setAnimationForWindow(static_cast<CardWindow*>(anim->targetObject()), anim); } centerX += kGapBetweenGroups + m_groups[i]->right(); } startAnimations(); } void CardWindowManager::focusWindow(Window* win) { Q_EMIT signalExitReorder(); disableCardRestoreToMaximized(); // make sure this are window has already been group'd CardWindow* card = static_cast<CardWindow*>(win); if (!m_groups.contains(card->cardGroup()) || !m_activeGroup) return; // If the active card is a modal window and we are focusing another window, we need to dismiss the modal first. if(Window::Type_ModalChildWindowCard == activeWindow()->type() && card != activeWindow()) { // Cehck if we are trying to focus the parent m_modalWindowState = ModalWindowDismissedParentSwitched; if(m_parentOfModalCard != card) { // Some other card is being focussed so no need to restore the state of the parent notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, false, ModalDismissNoAnimate, activeWindow()); // Set the fact that for all purposes m_parentOfModalCard is the currently active card if(m_parentOfModalCard) { // If this card is a modal parent, clear that flag if(m_parentOfModalCard->isCardModalParent()) m_parentOfModalCard->setCardIsModalParent(false); // Set the fact that this card no longer has a modal child if(NULL != m_parentOfModalCard->getModalChild()) m_parentOfModalCard->setModalChild(NULL); // Set that this card needs to process all input m_parentOfModalCard->setModalAcceptInputState(CardWindow::NoModalWindow); //CardWindowManagerStates relies on m_addingModalWindow for it's states. Don't call resetModalFlags, just change this flag m_addingModalWindow = false; m_modalDimissed = true; } } else { // Someone tried to give focus to the parent. notifySysControllerOfModalStatus(SystemUiController::ActiveCardsSwitched, true, ModalDismissNoAnimate, activeWindow()); return; } } Q_EMIT signalFocusWindow(card); } void CardWindowManager::slotPositiveSpaceAboutToChange(const QRect& r, bool fullScreenMode, bool screenResizing) { Q_EMIT signalExitReorder(); m_targetPositiveSpace = r; if (m_curState) m_curState->positiveSpaceAboutToChange(r, fullScreenMode); } void CardWindowManager::slotPositiveSpaceChangeFinished(const QRect& r) { Q_EMIT signalExitReorder(); if (m_curState) m_curState->positiveSpaceChangeFinished(r); } void CardWindowManager::slotPositiveSpaceChanged(const QRect& r) { static bool initialBounds = true; static qreal kActiveWindowScale = Settings::LunaSettings()->activeCardWindowRatio; static qreal kNonActiveWindowScale = Settings::LunaSettings()->nonActiveCardWindowRatio; if (initialBounds) { initialBounds = false; m_normalScreenBounds = r; kMinimumHeight = (int) (kMinimumWindowScale * m_normalScreenBounds.height()); kMinimumHeight = (int) ((kMinimumHeight/2) / kWindowOriginRatio); SystemUiController::instance()->setMinimumPositiveSpaceHeight(kMinimumHeight); m_targetPositiveSpace = r; // TODO: this is a temporary solution to fake the existence of the search pill // which happens to be 48 pixels tall kActiveScale = ((qreal) (r.height() - 48) * kActiveWindowScale) / (qreal) m_normalScreenBounds.height(); kActiveScale = qMax(kMinimumWindowScale, kActiveScale); kNonActiveScale = ((qreal) (r.height() - 48) * kNonActiveWindowScale) / (qreal) m_normalScreenBounds.height(); kNonActiveScale = qMax(kMinimumWindowScale, kNonActiveScale); // allow groups to shift up to a maximum so the tops of cards don't go off the screen kWindowOriginMax = (boundingRect().y() + ((r.y() + 48) + (int) ((r.height() - 48) * kWindowOriginRatio))) - Settings::LunaSettings()->positiveSpaceTopPadding - Settings::LunaSettings()->positiveSpaceBottomPadding; kWindowOrigin = boundingRect().y() + ((r.y() + 48) + (int) ((r.height() - 48) * kWindowOriginRatio)); } QRect rect = r; if (rect.height() < kMinimumHeight) { rect.setHeight(kMinimumHeight); } Q_EMIT signalExitReorder(); if (m_curState) m_curState->positiveSpaceChanged(rect); } void CardWindowManager::disableCardRestoreToMaximized() { m_cardToRestoreToMaximized = 0; } void CardWindowManager::restoreCardToMaximized() { if (!m_cardToRestoreToMaximized || !m_activeGroup) return; if (m_activeGroup->setActiveCard(m_cardToRestoreToMaximized)) maximizeActiveWindow(); disableCardRestoreToMaximized(); } QRect CardWindowManager::normalOrScreenBounds(CardWindow* win) const { if (win && win->fullScreen() && win->type() != Window::Type_ModalChildWindowCard) { return QRect(m_targetPositiveSpace.x(), m_targetPositiveSpace.y(), SystemUiController::instance()->currentUiWidth(), SystemUiController::instance()->currentUiHeight()); } return m_normalScreenBounds; } void CardWindowManager::cancelReorder(bool dueToPenCancel) { handleMouseReleaseReorder(NULL); } void CardWindowManager::closeWindow(CardWindow* win, bool angryCard) { if(!win) return; QPropertyAnimation* anim = NULL; /*// The only case we need to worry about here is if a modal parent called closeWindow() on itself. Then we need to close the child first and then continue if(true == win->isCardModalParent() && (Window::Type_ModalChildWindowCard == activeWindow()->type())) { m_modalWindowState = ModalParentDismissed; notifySysControllerOfModalStatus(SystemUiController::ParentCardDismissed, false, ModalDismissNoAnimate); win->setCardIsModalParent(false); win->setModalChild(NULL); win->setModalAcceptInputState(CardWindow::NoModalWindow); }*/ if (angryCard) win->setDisableKeepAlive(); win->close(); // remove the window from the current animation list removeAnimationForWindow(win, true); if(Window::Type_ModalChildWindowCard != win->type()) { CardWindow::Position pos = win->position(); QRectF r = win->mapRectToParent(win->boundingRect()); qreal offTop = boundingRect().y() - (win->y() + (r.height()/2)); pos.trans.setY(offTop); anim = new QPropertyAnimation(win, "position"); QVariant end; end.setValue(pos); anim->setEasingCurve(AS_CURVE(cardDeleteCurve)); anim->setDuration(AS(cardDeleteDuration)); anim->setEndValue(end); } else { anim = new QPropertyAnimation(); } QM_CONNECT(anim, SIGNAL(finished()), SLOT(slotDeletedAnimationFinished())); m_deletedAnimMap.insert(win, anim); anim->start(); // Modal cards are not a part of any card group. if(Window::Type_ModalChildWindowCard != win->type()) { removeCardFromGroup(win); } if (angryCard && playAngryCardSounds()) SoundPlayerPool::instance()->playFeedback("birdappclose"); else if (!Settings::LunaSettings()->lunaSystemSoundAppClose.empty()) SoundPlayerPool::instance()->playFeedback(Settings::LunaSettings()->lunaSystemSoundAppClose); } void CardWindowManager::queueFocusAction(CardWindow* win, bool focused) { if (win->removed()) return; win->aboutToFocusEvent(focused); win->queueFocusAction(focused); if (!m_pendingActionWinSet.contains(win)) m_pendingActionWinSet.insert(win); } void CardWindowManager::performPendingFocusActions() { Q_FOREACH(CardWindow* card, m_pendingActionWinSet) { card->performPendingFocusAction(); } m_pendingActionWinSet.clear(); } void CardWindowManager::queueTouchToShareAction(CardWindow* win) { if (win->removed()) return; if (!m_pendingTouchToShareWinSet.contains(win)) m_pendingTouchToShareWinSet.insert(win); } void CardWindowManager::performPendingTouchToShareActions() { Q_FOREACH(CardWindow* card, m_pendingTouchToShareWinSet) { GhostCard* ghost = card->createGhost(); if (ghost) { // place the ghost on top of the card we're sharing ghost->setParentItem(card->parentItem()); ghost->stackBefore(card); card->stackBefore(ghost); // anchor the ghost within it's parent's group CardGroup* group = card->cardGroup(); ghost->setPos((group ? group->pos() : QPointF(0,0))); ghost->setOpacity(0.5); QPropertyAnimation* anim = new QPropertyAnimation(ghost, "position"); anim->setDuration(AS(cardGhostDuration)); anim->setEasingCurve(AS_CURVE(cardGhostCurve)); // animate the ghost off the top of the screen CardWindow::Position pos; QRectF r = ghost->mapRectToParent(ghost->boundingRect()); qreal offTop = boundingRect().y() - (ghost->y() + (r.height()/2)); pos.trans.setY(offTop); pos.trans.setZ(Settings::LunaSettings()->ghostCardFinalRatio); QVariant end; end.setValue(pos); anim->setEndValue(end); connect(anim, SIGNAL(finished()), SLOT(slotTouchToShareAnimationFinished())); anim->start(); } } m_pendingTouchToShareWinSet.clear(); } void CardWindowManager::removePendingActionWindow(CardWindow* win) { QSet<CardWindow*>::iterator it = m_pendingActionWinSet.find(win); if (it != m_pendingActionWinSet.end()) m_pendingActionWinSet.erase(it); it = m_pendingTouchToShareWinSet.find(win); if (it != m_pendingTouchToShareWinSet.end()) m_pendingTouchToShareWinSet.erase(it); } CardWindow* CardWindowManager::activeWindow() const { CardWindow* activeCard = NULL; CardWindow* w = NULL; if((NULL == m_activeGroup) || (NULL == (activeCard = m_activeGroup->activeCard()))) { return NULL; } else { w = activeCard->getModalChild(); return( NULL != w)? w: activeCard; } } CardGroup* CardWindowManager::activeGroup() const { return m_activeGroup; } void CardWindowManager::slotAnimationsFinished() { if(false == m_addingModalWindow) { if (m_anims.animationCount() == 0) { return; } } m_cardAnimMap.clear(); m_groupAnimMap.clear(); m_anims.clear(); // make sure the active group stays at the top of the stacking order if (m_activeGroup) { m_activeGroup->raiseCards(); } performPendingFocusActions(); m_curState->animationsFinished(); m_animationsActive = false; updateAllowWindowUpdates(); } void CardWindowManager::slotDeletedAnimationFinished() { QPropertyAnimation* anim = qobject_cast<QPropertyAnimation*>(sender()); Q_ASSERT(anim != 0); // find the card whose animation finished and delete it if webkit already told us we can QMap<CardWindow*,QPropertyAnimation*>::iterator it = m_deletedAnimMap.begin(); for (; it != m_deletedAnimMap.end(); ++it) { QPropertyAnimation* a = qobject_cast<QPropertyAnimation*>(it.value()); if (anim == a) { CardWindow* w = static_cast<CardWindow*>(it.key()); if (w->removed()) { m_deletedAnimMap.erase(it); delete w; delete a; } else { // since we don't adjust these when ui orientation changes, make sure they remain // invisible until the reaper comes to collect them w->setVisible(false); } break; } } } void CardWindowManager::slotTouchToShareAnimationFinished() { g_debug("%s: deleting TapToShare Ghost", __PRETTY_FUNCTION__); QPropertyAnimation* anim = qobject_cast<QPropertyAnimation*>(sender()); Q_ASSERT(anim != 0); GhostCard* target = static_cast<GhostCard*>(anim->targetObject()); delete anim; if (target) { delete target; } } void CardWindowManager::slotLauncherVisible(bool val, bool fullyVisible) { if (fullyVisible && !m_lowResMode) { m_lowResMode = true; Q_FOREACH(CardGroup* group, m_groups) { group->disableShadows(); } } else if (!fullyVisible && m_lowResMode) { m_lowResMode = false; Q_FOREACH(CardGroup* group, m_groups) { group->enableShadows(); } } } void CardWindowManager::slotLauncherShown(bool val) { if (!val) return; if (m_curState && m_curState->supportLauncherOverlay()) return; minimizeActiveWindow(); } void CardWindowManager::slotChangeCardWindow(bool next) { if (m_curState) m_curState->changeCardWindow(next); } void CardWindowManager::slotFocusMaximizedCardWindow(bool focus) { if (m_curState) m_curState->focusMaximizedCardWindow(focus); } void CardWindowManager::slotTouchToShareAppUrlTransfered(const std::string& appId) { if (m_curState) m_curState->processTouchToShareTransfer(appId); } void CardWindowManager::slotDismissActiveModalWindow() { if(Window::Type_ModalChildWindowCard == activeWindow()->type()) { m_modalWindowState = ModalWindowDismissedInternally; notifySysControllerOfModalStatus(SystemUiController::ServiceDismissedModalCard, true, ModalDismissAnimate); } else { resetModalFlags(); } } void CardWindowManager::slotDismissModalTimerStopped() { CardWindow* activeWin = activeWindow(); if(activeWin && (Window::Type_ModalChildWindowCard == activeWin->type()) && m_parentOfModalCard) { m_parentOfModalCard->setModalAcceptInputState(CardWindow::ModalLaunchedAcceptingInput); } } void CardWindowManager::setInModeAnimation(bool animating) { if (animating) { Q_FOREACH(CardGroup* group, m_groups) { group->setCompositionMode(QPainter::CompositionMode_SourceOver); } } else { Q_FOREACH(CardGroup* group, m_groups) { group->setCompositionMode(QPainter::CompositionMode_Source); } } } void CardWindowManager::notifySysControllerOfModalStatus(int reason, bool restore, NotifySystemUiControllerAction type, Window* win) { if(type == Invalid) return; if(type == ModalLaunch) { // Notify SystemUiController of the result of the modal launch SystemUiController::instance()->setModalWindowLaunchErrReason((SystemUiController::ModalWinLaunchErrorReason)(reason)); // Signal that we no longer have an active modal window only if the reason is NoErr, else remove the window if(SystemUiController::NoErr == ((SystemUiController::ModalWinLaunchErrorReason)(reason))) { SystemUiController::instance()->notifyModalWindowActivated(m_parentOfModalCard); } else { // If we are already in the process of deleting a modal and another call comes in to do the same, just ignore it if(true == m_modalDismissInProgress) { return; } // we are going to delete a modal. m_modalDismissInProgress = true; performPostModalWindowRemovedActions(win, restore); } return; } // If we are already in the process of deleting a modal and another call comes in to do the same, just ignore it if(true == m_modalDismissInProgress) { return; } // we are going to delete a modal. m_modalDismissInProgress = true; // Notify SystemUiController of the reason why the modal was dismissed SystemUiController::instance()->setModalWindowDismissErrReason((SystemUiController::ModalWinDismissErrorReason)(reason)); if(type == ModalDismissAnimate) { // We need to animate the removal of the modal. So call this function, which will call performPostModalWindowRemovedActions(restore) with the correct params initiateRemovalOfActiveModalWindow(); } else { // directly get rid of the modal card performPostModalWindowRemovedActions(NULL, restore); } } void CardWindowManager::updateAllowWindowUpdates() { bool allow = true; if (m_animationsActive) allow = false; else if ((m_curState != m_maximizeState) && m_penDown) allow = false; Q_FOREACH(CardGroup* cg, m_groups) { Q_FOREACH(CardWindow* w, cg->cards()) w->allowUpdates(allow); } }
29.960682
189
0.732066
ericblade
de039450ccb7ee81838d6dffa3d0cba18eddfc5a
1,560
cpp
C++
framework/tarscpp/unittest/testcode/source/testcase/util/test_tc_pack.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
framework/tarscpp/unittest/testcode/source/testcase/util/test_tc_pack.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
framework/tarscpp/unittest/testcode/source/testcase/util/test_tc_pack.cpp
hfcrwx/Tars-v2.4.20
b0782b3fad556582470cddaa4416874126bd105c
[ "BSD-3-Clause" ]
null
null
null
#include "TarsServantName.h" #include "TarsTest/TestcaseServer/RPCTest.h" #include "gtest/gtest.h" #include "servant/AdminF.h" #include "servant/Application.h" #include <cassert> #include <iostream> #include "util/tc_pack.h" using namespace std; using namespace tars; using namespace TarsTest; TEST(TarsUtilTestcase, UT_TC_Pack) { bool b = true; char c = 'a'; short si = 3; int ii = 4; char cn[] = "abc"; string sn = "def"; TC_PackIn pi; pi << b << c << si << ii << cn << sn; string s = pi.topacket(); TC_PackOut po(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> c; assert(c == 'a'); cout << "char OK" << endl; po >> si; assert(si == 3); cout << "short OK" << endl; po >> ii; assert(ii == 4); cout << "int OK" << endl; po >> cn; assert(cn == string("abc")); cout << "char[] OK" << endl; po >> sn; assert(sn == "def"); cout << "string OK" << endl; { pi.clear(); pi << b << c; pi.insert(1) << cn; s = pi.topacket(); po.init(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> cn; assert(cn == string("abc")); cout << "char[] OK" << endl; po >> c; assert(c == 'a'); cout << "char OK" << endl; } { pi.clear(); pi << b << c; pi.replace(1) << 'b'; s = pi.topacket(); po.init(s.c_str(), s.length()); po >> b; assert(b == true); cout << "bool OK" << endl; po >> c; assert(c == 'b'); cout << "char OK" << endl; } }
17.333333
44
0.507692
hfcrwx
9007f010fc70494b9cb03902e9bd5a1b000e3a32
4,206
hxx
C++
src/ssl/NameCache.hxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
1
2022-03-15T22:54:39.000Z
2022-03-15T22:54:39.000Z
src/ssl/NameCache.hxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
null
null
null
src/ssl/NameCache.hxx
nn6n/beng-proxy
2cf351da656de6fbace3048ee90a8a6a72f6165c
[ "BSD-2-Clause" ]
null
null
null
/* * Copyright 2007-2021 CM4all GmbH * All rights reserved. * * author: Max Kellermann <mk@cm4all.com> * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * - Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the * distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * FOUNDATION 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. */ #pragma once #include "pg/AsyncConnection.hxx" #include "event/FineTimerEvent.hxx" #include "io/Logger.hxx" #include <unordered_set> #include <unordered_map> #include <set> #include <string> #include <mutex> struct CertDatabaseConfig; class CertNameCacheHandler { public: virtual void OnCertModified(const std::string &name, bool deleted) noexcept = 0; }; /** * A frontend for #CertDatabase which establishes a cache of all host * names and keeps it up to date. * * All modifications run asynchronously in the main thread, and * std::unordered_set queries may be executed from any thread * (protected by the mutex). */ class CertNameCache final : Pg::AsyncConnectionHandler, Pg::AsyncResultHandler { const LLogger logger; CertNameCacheHandler &handler; Pg::AsyncConnection conn; FineTimerEvent update_timer; mutable std::mutex mutex; /** * A list of host names found in the database. */ std::unordered_set<std::string> names; /** * A list of alt_names found in the database. Each alt_name maps * to a list of common_name values it appears in. */ std::unordered_map<std::string, std::set<std::string>> alt_names; /** * The latest timestamp seen in a record. This is used for * incremental updates. */ std::string latest = "1971-01-01"; unsigned n_added, n_updated, n_deleted; /** * This flag is set to true as soon as the cached name list has * become complete for the first time. With an incomplete cache, * Lookup() will always return true, because we don't know yet if * the desired name is just not yet loaded. */ bool complete = false; public: CertNameCache(EventLoop &event_loop, const CertDatabaseConfig &config, CertNameCacheHandler &_handler) noexcept; auto &GetEventLoop() const noexcept { return update_timer.GetEventLoop(); } void Connect() noexcept { conn.Connect(); } void Disconnect() noexcept { conn.Disconnect(); update_timer.Cancel(); } /** * Check if the given name exists in the database. */ bool Lookup(const char *host) const noexcept; private: void OnUpdateTimer() noexcept; void ScheduleUpdate() noexcept; void UnscheduleUpdate() noexcept { update_timer.Cancel(); } void AddAltName(const std::string &common_name, std::string &&alt_name) noexcept; void RemoveAltName(const std::string &common_name, const std::string &alt_name) noexcept; /* virtual methods from Pg::AsyncConnectionHandler */ void OnConnect() override; void OnDisconnect() noexcept override; void OnNotify(const char *name) override; void OnError(std::exception_ptr e) noexcept override; /* virtual methods from Pg::AsyncResultHandler */ void OnResult(Pg::Result &&result) override; void OnResultEnd() override; void OnResultError() noexcept override; };
28.612245
80
0.737993
nn6n
90183a01785e0cb09c6d13539f9d2eabbdb6540f
2,117
cpp
C++
lib/rendering/raytracer.cpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
null
null
null
lib/rendering/raytracer.cpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
2
2017-06-01T16:43:37.000Z
2017-06-07T16:17:51.000Z
lib/rendering/raytracer.cpp
julienlopez/Raytracer
35fa5a00e190592a8780971fcbd2936a54e06d3a
[ "MIT" ]
null
null
null
#include "raytracer.hpp" #include "ray.hpp" #include "scene.hpp" #include "primitive/iprimitive.hpp" namespace Rendering { RayTracer::RayTracer(unsigned long pixelWidth, unsigned long pixelHeight, double width, double height, double depth) : m_pixel_width(pixelWidth) , m_pixel_height(pixelHeight) , width(width) , height(height) , depth(depth) { origin.fill(0.); direction.fill(0.); direction(2) = 1; updateParameters(); } RayTracer::~RayTracer() = default; Image RayTracer::draw() const { Image res{Eigen::Index(m_pixel_height), Eigen::Index(m_pixel_width)}; for(std::size_t j = 0; j < m_pixel_height; ++j) { for(std::size_t i = 0; i < m_pixel_width; ++i) { res(j, i) = computeColor(generateRay(i, j)); } } return res; } void RayTracer::setViewer(double width, double height, const Math::Vector3d& origin, const Math::Vector3d& direction) { this->width = width; this->height = height; this->origin = origin; this->direction = direction; updateParameters(); } void RayTracer::setResolution(unsigned long pixelWidth, unsigned long pixelHeight) { m_pixel_width = pixelWidth; m_pixel_height = pixelHeight; updateParameters(); } void RayTracer::setScene(Scene* scene) { m_scene = scene; } Ray RayTracer::generateRay(const std::size_t x, const std::size_t y) const { Math::Vector3d dir = Math::createPoint(precompWidth * (x - m_pixel_width / 2.), precompHeight * (y - m_pixel_height / 2.), depth); return Ray(origin, Math::normalize(dir)); } Color RayTracer::computeColor(const Ray& ray) const { Color color; color.fill(0.); double distance; const auto index = m_scene->getFirstCollision(ray, distance); if(index) { Math::Vector3d normal; auto& primitive = m_scene->getPrimitive(*index); primitive.computeColorNormal(ray, distance, color, normal); } return color; } void RayTracer::updateParameters() { precompWidth = width / m_pixel_width; precompHeight = height / m_pixel_height; } } // Rendering
23.522222
119
0.665092
julienlopez
901a5e5c825e9912d1fd0125af06fc595a81657e
6,612
cpp
C++
src/editor/src/material/material_thumbnail.cpp
AirGuanZ/Atrc
a0c4bc1b7bb96ddffff8bb1350f88b651b94d993
[ "MIT" ]
358
2018-11-29T08:15:05.000Z
2022-03-31T07:48:37.000Z
src/editor/src/material/material_thumbnail.cpp
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
23
2019-04-06T17:23:58.000Z
2022-02-08T14:22:46.000Z
src/editor/src/material/material_thumbnail.cpp
happyfire/Atrc
74cac111e277be53eddea5638235d97cec96c378
[ "MIT" ]
22
2019-03-04T01:47:56.000Z
2022-01-13T06:06:49.000Z
#include <agz/editor/material/material_thumbnail.h> #include <agz/tracer/core/intersection.h> #include <agz/tracer/core/bsdf.h> #include <agz/tracer/core/light.h> #include <agz/tracer/core/sampler.h> #include <agz/tracer/create/envir_light.h> #include <agz/tracer/create/texture2d.h> #include <agz/tracer/utility/sphere_aux.h> #include <agz-utils/image.h> AGZ_EDITOR_BEGIN namespace { class MaterialThumbnailEnvLight { RC<const tracer::EnvirLight> env_light_; public: MaterialThumbnailEnvLight() { const unsigned char data[] = { #include "./material_thumbnail_env.txt" }; auto tex_data = img::load_rgb_from_hdr_memory(data, sizeof(data)); auto img_data = newRC<Image2D<math::color3f>>(std::move(tex_data)); auto tex = tracer::create_hdr_texture({}, img_data, "linear"); env_light_ = create_ibl_light(tex); } const tracer::EnvirLight *operator->() const { return env_light_.get(); } }; Spectrum illum( const Vec3 &wo, const Vec3 &nor, const tracer::BSDF *bsdf, const MaterialThumbnailEnvLight &light, tracer::Sampler &sampler) { Spectrum bsdf_illum, light_illum; const auto bsdf_sample = bsdf->sample_all( wo, tracer::TransMode::Radiance, sampler.sample3()); if(!bsdf_sample.f.is_black()) { const real cos_v = std::abs(cos(bsdf_sample.dir, nor)); const Spectrum env = light->radiance({}, bsdf_sample.dir); if(bsdf->is_delta()) bsdf_illum = bsdf_sample.f * cos_v * env / bsdf_sample.pdf; else { const real env_pdf = light->pdf({}, bsdf_sample.dir); bsdf_illum = bsdf_sample.f * cos_v * env / (bsdf_sample.pdf + env_pdf); } } const auto light_sample = light->sample({}, sampler.sample5()); if(!light_sample.radiance.is_black()) { const Vec3 wi = light_sample.ref_to_light(); const Spectrum f = bsdf->eval_all(wi, wo, tracer::TransMode::Radiance); const real cos_v = std::abs(cos(wi, nor)); const real bsdf_pdf = bsdf->pdf_all(wi, wo); light_illum = light_sample.radiance * f * cos_v / (light_sample.pdf + bsdf_pdf); } return bsdf_illum + light_illum; } } // IMPROVE: bssrdf is not handled void MaterialThumbnailProvider::run_one_iter(int spp) { static const MaterialThumbnailEnvLight env; tracer::Arena arena; real init_xf, zf, df; if(width_ < height_) { df = real(6) / width_; init_xf = -3 + df / 2; zf = real(height_) / width_ * 3 - df / 2; } else { df = real(6) / height_; zf = 3 - df / 2; init_xf = -real(width_) / height_ * 3 + df / 2; } for(int y = 0; y < height_; ++y) { real xf = init_xf; if(exit_) return; for(int x = 0; x < width_; ++x) { for(int s = 0; s < spp; ++s) { const real pxf = xf + (sampler_->sample1().u - 1) * df; const real pzf = zf + (sampler_->sample1().u - 1) * df; if(pxf * pxf + pzf * pzf < 4) { const real pyf = -std::sqrt(4 - pxf * pxf - pzf * pzf); tracer::FCoord coord; Vec2 uv; tracer::sphere::local_geometry_uv_and_coord( { pxf, pyf, pzf }, &uv, &coord, 2); tracer::SurfacePoint spt; spt.pos = { pxf, pyf, pzf }; spt.uv = uv; spt.geometry_coord = coord; spt.user_coord = coord; tracer::EntityIntersection inct; (tracer::SurfacePoint &)inct = spt; inct.entity = nullptr; inct.material = mat_.get(); inct.medium_in = nullptr; inct.medium_out = nullptr; inct.wr = { 0, 0, 1 }; inct.t = 1; auto shd = mat_->shade(inct, arena); Spectrum color; for(int j = 0; j < 4; ++j) { color += illum( { 0, -1, 0 }, spt.geometry_coord.z, shd.bsdf, env, *sampler_); } accum_color_(y, x) += real(0.25) * color; } else accum_color_(y, x) += Spectrum(real(0.2)); } xf += df; } zf -= df; } ++finished_iters_; finished_spp_ += spp; } QPixmap MaterialThumbnailProvider::compute_pixmap() { assert(finished_iters_ > 0); const real ratio = real(1) / finished_spp_; QImage img(width_, height_, QImage::Format_RGB888); for(int y = 0; y < height_; ++y) { for(int x = 0; x < width_; ++x) { const Spectrum color = accum_color_(y, x).map([=](real c) { return std::pow(c * ratio, 1 / real(2.2)); }).saturate(); img.setPixelColor(x, y, QColor::fromRgbF(color.r, color.g, color.b)); } } QPixmap ret; ret.convertFromImage(img); return ret; } MaterialThumbnailProvider::MaterialThumbnailProvider( int width, int height, RC<const tracer::Material> mat, int iter_spp, int iter_count) : width_(width), height_(height), mat_(std::move(mat)), exit_(false) { iter_spp_ = iter_spp; iter_count_ = iter_count; finished_iters_ = 0; finished_spp_ = 0; } MaterialThumbnailProvider::~MaterialThumbnailProvider() { assert(!exit_); exit_ = true; if(render_thread_.joinable()) render_thread_.join(); } QPixmap MaterialThumbnailProvider::start() { assert(!exit_); accum_color_.initialize(height_, width_, Spectrum()); sampler_ = newRC<tracer::NativeSampler>(42, false); run_one_iter(1); auto ret = compute_pixmap(); render_thread_ = std::thread([=] { for(;;) { if(exit_) return; if(finished_iters_ >= iter_count_) return; run_one_iter(iter_spp_); if(exit_) return; emit update_thumbnail(compute_pixmap()); } }); return ret; } AGZ_EDITOR_END
27.781513
83
0.515578
AirGuanZ
9020cc40228d66a0aee9e49b4b2e3e331d86a334
5,596
cpp
C++
LuaSTG/src/LuaWrapper/LW_ParticleSystem.cpp
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
6
2022-02-26T09:21:40.000Z
2022-02-28T11:03:23.000Z
LuaSTG/src/LuaWrapper/LW_ParticleSystem.cpp
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
null
null
null
LuaSTG/src/LuaWrapper/LW_ParticleSystem.cpp
Legacy-LuaSTG-Engine/LuaSTG-Sub
c7d21da53fc86efe4e3907738f8fed324581dee0
[ "MIT" ]
null
null
null
#include "LuaWrapper.hpp" namespace LuaSTGPlus::LuaWrapper { std::string_view const ParticleSystemWrapper::ClassID("lstg.ParticleSystemInstance"); ParticleSystemWrapper::UserData* ParticleSystemWrapper::Cast(lua_State* L, int idx) { return (UserData*)luaL_checkudata(L, idx, ClassID.data()); } ParticleSystemWrapper::UserData* ParticleSystemWrapper::Create(lua_State* L) { UserData* self = (UserData*)lua_newuserdata(L, sizeof(UserData)); // udata self->res = nullptr; self->ptr = nullptr; luaL_getmetatable(L, ClassID.data()); // udata mt lua_setmetatable(L, -2); // udata return self; } void ParticleSystemWrapper::Register(lua_State* L) { struct Wrapper { static int SetInactive(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { self->ptr->SetInactive(); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int SetActive(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { self->ptr->SetActive(); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int GetAliveCount(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { size_t const alive = self->ptr->GetAliveCount(); lua_pushinteger(L, (lua_Integer)alive); return 1; } else { return luaL_error(L, "invalid particle system instance."); } } static int SetEmission(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const emi = (float)luaL_checknumber(L, 2); self->ptr->SetEmission(emi); return 0; } else { return luaL_error(L, "invalid particle system instance."); } } static int GetEmission(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const emi = self->ptr->GetEmission(); lua_pushnumber(L, emi); return 1; } else { return luaL_error(L, "invalid particle system instance."); } } static int Update(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const x = (float)luaL_checknumber(L, 2); float const y = (float)luaL_checknumber(L, 3); float const rot = (float)luaL_checknumber(L, 4); float const delta = (float)luaL_optnumber(L, 5, 1.0 / 60.0); self->ptr->SetRotation((float)rot); if (self->ptr->IsActived()) // 兼容性处理 { self->ptr->SetInactive(); self->ptr->SetCenter(fcyVec2(x, y)); self->ptr->SetActive(); } else { self->ptr->SetCenter(fcyVec2(x, y)); } self->ptr->Update(delta); } else { return luaL_error(L, "invalid particle system instance."); } return 0; } static int Render(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->ptr) { float const scale = (float)luaL_checknumber(L, 2); LAPP.Render(self->ptr, scale, scale); } else { return luaL_error(L, "invalid particle system instance."); } return 0; } static int __tostring(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->res) { lua_pushfstring(L, "lstg.ParticleSystemInstance(\"%s\")", self->res->GetResName().c_str()); } else { lua_pushstring(L, "lstg.ParticleSystemInstance"); } return 1; } static int __gc(lua_State* L) { UserData* self = (UserData*)luaL_checkudata(L, 1, ClassID.data()); if (self->res) { if (self->ptr) { self->res->FreeInstance(self->ptr); } self->res->Release(); } self->res = nullptr; self->ptr = nullptr; return 0; } static int ParticleSystemInstance(lua_State* L) { char const* ps_name = luaL_checkstring(L, 1); auto p_res = LRES.FindParticle(ps_name); if (!p_res) return luaL_error(L, "particle system '%s' not found.", ps_name); try { auto* p_obj = p_res->AllocInstance(); auto* p_lud = Create(L); p_lud->res = *p_res; p_lud->res->AddRef(); p_lud->ptr = p_obj; } catch (const std::bad_alloc&) { return luaL_error(L, "create particle system instance of '%s' failed, memory allocation failed.", ps_name); } return 1; } }; luaL_Reg const lib[] = { { "SetInactive", &Wrapper::SetInactive }, { "SetActive", &Wrapper::SetActive }, { "GetAliveCount", &Wrapper::GetAliveCount }, { "SetEmission", &Wrapper::SetEmission }, { "GetEmission", &Wrapper::GetEmission }, { "Update", &Wrapper::Update }, { "Render", &Wrapper::Render }, { NULL, NULL } }; luaL_Reg const mt[] = { { "__tostring", &Wrapper::__tostring }, { "__gc", &Wrapper::__gc }, { NULL, NULL }, }; luaL_Reg const ins[] = { { "ParticleSystemInstance", Wrapper::ParticleSystemInstance }, { NULL, NULL } }; luaL_register(L, "lstg", ins); // ??? lstg RegisterClassIntoTable(L, ".ParticleSystemInstance", lib, ClassID.data(), mt); lua_pop(L, 1); } }
25.907407
113
0.580593
Legacy-LuaSTG-Engine
9022058d0badf93cb70ad6ae677ef30a406c68c4
2,560
cpp
C++
main.cpp
kevinyxlu/cs32lab06
784aeae13eec100be6a9e7d9aa69a6fec5a8f8d2
[ "MIT" ]
null
null
null
main.cpp
kevinyxlu/cs32lab06
784aeae13eec100be6a9e7d9aa69a6fec5a8f8d2
[ "MIT" ]
null
null
null
main.cpp
kevinyxlu/cs32lab06
784aeae13eec100be6a9e7d9aa69a6fec5a8f8d2
[ "MIT" ]
null
null
null
// CS32 lab06 // Completed by: Kevin Lu and Kevin Lai #include <iostream> #include <string> #include <fstream> #include <vector> #include <memory> #include "demogData.h" #include "psData.h" #include "parse.h" #include "dataAQ.h" using namespace std; int main() { /*//Deboog output ofstream myfile; myfile.open("output.txt");*/ dataAQ theAnswers; //read in a csv file and create a vector of objects representing each counties data std::vector<shared_ptr<regionData>> theDemogData = read_csv( "county_demographics.csv", DEMOG); std::vector<shared_ptr<regionData>> thePoliceData = read_csv( "police_shootings_cleaned.csv", POLICE); /*//Deboog print for (auto obj : theDemogData) { myfile << *dynamic_pointer_cast<demogData>(obj) << std::endl; } for (auto obj : thePoliceData) { myfile << *dynamic_pointer_cast<psData>(obj) << std::endl; } */ std::vector<shared_ptr<demogData>> castedDemogData; std::vector<shared_ptr<psData>> castedPoliceData; for (auto entry : theDemogData) { castedDemogData.push_back(static_pointer_cast<demogData>(entry)); } for (auto entry : thePoliceData) { castedPoliceData.push_back(static_pointer_cast<psData>(entry)); } theAnswers.createComboDemogData(castedDemogData); theAnswers.createComboPoliceData(castedPoliceData); //cout << theAnswers << endl; theAnswers.comboReport(92); //myfile.close(); /* cout << "*** the state that needs the most pre-schools**" << endl; string needPK = theAnswers.youngestPop(); cout << *(theAnswers.getStateData(needPK)) << endl; cout << "*** the state that needs the most high schools**" << endl; string needHS = theAnswers.teenPop(); cout << *(theAnswers.getStateData(needHS)) << endl; cout << "*** the state that needs the most vaccines**" << endl; string needV = theAnswers.wisePop(); cout << *(theAnswers.getStateData(needV)) << endl; cout << "*** the state that needs the most help with education**" << endl; string noHS = theAnswers.underServeHS(); cout << *(theAnswers.getStateData(noHS)) << endl; cout << "*** the state with most college grads**" << endl; string grads = theAnswers.collegeGrads(); cout << *(theAnswers.getStateData(grads)) << endl; cout << "*** the state with most population below the poverty line**" << endl; string belowPov = theAnswers.belowPoverty(); cout << *(theAnswers.getStateData(belowPov)) << endl; */ return 0; }
32.820513
87
0.657031
kevinyxlu
90228f4eb56d6f1a331f8cec173e6cf50f980f8a
1,264
cpp
C++
Kattis/muddyhike.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
3
2021-02-19T17:01:11.000Z
2021-03-11T16:50:19.000Z
Kattis/muddyhike.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
Kattis/muddyhike.cpp
YourName0729/competitive-programming
437ef18a46074f520e0bfa0bdd718bb6b1c92800
[ "MIT" ]
null
null
null
// DFS binary_searching // https://open.kattis.com/problems/muddyhike #include <bits/stdc++.h> #define For(i, n) for (int i = 0; i < n; ++i) #define Forcase int __t = 0; cin >> __t; while (__t--) #define pb push_back #define ll long long #define ull unsigned long long #define ar array using namespace std; const int MOD = 1e9;//1e9 + 7; const ll INF = 1e18; int n, m; int tb[1010][1010]; bool vst[1010][1010]; int dx[] = {0, 1, 0, -1}; int dy[] = {1, 0, -1, 0}; void dfs(int x, int y, int d) { vst[x][y] = 1; For (i, 4) { int nx = x + dx[i], ny = y + dy[i]; if (nx < 0 || nx >= n || ny < 0 || ny >= m) continue; if (tb[nx][ny] <= d && !vst[nx][ny]) { dfs(nx, ny, d); } } } bool ok(int d) { For (i, n) For (j, m) vst[i][j] = 0; For (i, n) if (tb[i][0] <= d) dfs(i, 0, d); For (i, n) if (vst[i][m - 1]) return 1; return 0; } int main() { ios_base::sync_with_stdio(0); cin.tie(0); cin >> n >> m; For (i, n) For (j, m) cin >> tb[i][j]; int l = 0, r = 1000000; while (l < r) { int mid = (l + r) / 2; if (ok(mid)) { r = mid; } else { l = mid + 1; } } cout << l << '\n'; return 0; }
21.423729
61
0.459652
YourName0729
9025dc4a8b2d99bb948acee1c9ea6a716cb0fb77
552
cpp
C++
applications/ParticlesEditor/src/ParticlesEditor.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/src/ParticlesEditor.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
applications/ParticlesEditor/src/ParticlesEditor.cpp
AluminiumRat/mtt
3052f8ad0ffabead05a1033e1d714a61e77d0aa8
[ "MIT" ]
null
null
null
#include <mtt/editorLib/EditorApplication.h> #include <MainWindow.h> int main(int argc, char* argv[]) { VkPhysicalDeviceFeatures features{}; features.samplerAnisotropy = VK_TRUE; features.geometryShader = VK_TRUE; mtt::EditorApplication application( argc, argv, "Mtt particles editor", { 0, 0, 0 }, features); MainWindow mainWindow; mainWindow.show(); return application.exec(); }
25.090909
61
0.530797
AluminiumRat
902694d213826185749d052ae9ae56617ae2ad58
16,817
cc
C++
Engine/app/physXfeature/physicsCore/PhysicsDynamic.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
26
2015-01-15T12:57:40.000Z
2022-02-16T10:07:12.000Z
Engine/app/physXfeature/physicsCore/PhysicsDynamic.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
null
null
null
Engine/app/physXfeature/physicsCore/PhysicsDynamic.cc
BikkyS/DreamEngine
47da4e22c65188c72f44591f6a96505d8ba5f5f3
[ "MIT" ]
17
2015-02-18T07:51:31.000Z
2020-06-01T01:10:12.000Z
/**************************************************************************** Copyright (c) 2011-2013,WebJet Business Division,CYOU http://www.genesis-3d.com.cn Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __PHYSX_COMMIT__ #include "PxRigidDynamic.h" #include "PhysicsDynamic.h" #include "PhysicsServer.h" #include "PhysicsShape.h" #include "PxScene.h" #include "PxShape.h" #include "PxFlags.h" #include "PxRigidBodyExt.h" #include "PxRigidDynamic.h" #include "PhysicsUtil.h" #include "physXfeature/PhysicsBodyComponent.h" namespace App { __ImplementClass(PhysicsDynamic, 'PYDY', PhysicsEntity); PhysicsDynamic::PhysicsDynamic() : m_pPxActor(NULL) , m_bJointFather(false) , m_bUseGravity(true) , m_bKinematic(false) , m_fLinearDamping(0.0f) , m_fAngularDamping(0.05f) , m_vContantForce(0.f) , m_vContantVelocity(0.f) , m_vContantTorques(0.f) , m_vContantAngularVel(0.f) { m_eType = PHYSICSDYNAMIC; m_fMaxAngularVel = PhysicsServer::Instance()->GetMaxAngularVelocity(); m_fSleepThreshold = PhysicsServer::Instance()->GetSleepThreshold(); } PhysicsDynamic::~PhysicsDynamic() { OnDestory(); } PxRigidActor* PhysicsDynamic::GetRigidActor() { return m_pPxActor; } bool PhysicsDynamic::OnCreate(GPtr<PhysicsBodyComponent> body) { if ( !m_bJointFather && body.isvalid() && body->GetActor() ) { OnDestory(); PxPhysics* pSDK = PhysicsServer::Instance()->GetPhysics(); n_assert(pSDK); Math::vector pos = body->GetActor()->GetWorldPosition(); Math::quaternion rot = body->GetActor()->GetWorldRotation(); PxTransform _ActorPose(PxVec3(pos.x(), pos.y(), pos.z()), PxQuat(rot.x(), rot.y(), rot.z(), rot.w())); m_pPxActor = pSDK->createRigidDynamic(_ActorPose); n_assert(m_pPxActor) m_pPxActor->userData = body.get(); m_pPxActor->setActorFlag(PxActorFlag::eVISUALIZATION, true); if ( m_bKinematic ) { m_pPxActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, m_bKinematic); } else { m_pPxActor->setAngularDamping (m_fAngularDamping); m_pPxActor->setLinearDamping(m_fLinearDamping ); m_pPxActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, false); m_pPxActor->setMaxAngularVelocity(PhysicsServer::Instance()->GetMaxAngularVelocity()); m_pPxActor->setSleepThreshold(PhysicsServer::Instance()->GetSleepThreshold()); m_pPxActor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_bUseGravity); } for ( int i=0; i<m_arrPhysicsShapePtr.Size(); ++i ) { if (!m_arrPhysicsShapePtr[i]->IsValid()) { m_arrPhysicsShapePtr[i]->OnCreate(body); } m_arrPhysicsShapePtr[i]->SetPhysicsEntity(this); m_arrPhysicsShapePtr[i]->CreatePxShape(m_pPxActor, GetGroupID()); } UpdateEntityMass(); // Not using // CaptureShapeFromChildren(); return true; } return m_bJointFather; } void PhysicsDynamic::CaptureShapeFromChildren() { if ( m_pPxActor == NULL ) { return; } for ( int i=0; i<m_pComponent->GetActor()->GetChildCount(); ++i ) { GPtr<PhysicsEntity> _pChildEntity = GetEntityInActor(m_pComponent->GetActor()->GetChild(i)); if ( _pChildEntity.isvalid() && _pChildEntity->GetType()&m_eType ) { GPtr<PhysicsDynamic> _pDynamic = _pChildEntity.downcast<PhysicsDynamic>(); if ( !_pDynamic->IsJointFather() ) { continue; } for ( int i=0; i<_pChildEntity->GetShapeCount(); ++i ) { _pChildEntity->GetShape(i)->CreatePxShape(m_pPxActor, GetGroupID()); } } } } bool PhysicsDynamic::OnDestory() { if ( IsValid() ) { Super::OnDestory(); //ReleaseChildShape(); m_pPxActor->release(); m_pPxActor = NULL; } return true; } void PhysicsDynamic::OnShapeReBuild(PhysicsShape* shape) { if ( GetRigidActor() && shape != NULL) { shape->CreatePxShape(GetRigidActor(),m_eGroup); UpdateEntityMass(); } } void PhysicsDynamic::ReleaseChildShape() { if ( m_pPxActor == NULL || m_pComponent == NULL || !m_pComponent->GetActor() ) { return; } for ( int i=0; i<m_pComponent->GetActor()->GetChildCount(); ++i ) { GPtr<PhysicsEntity> _pChildEntity = GetEntityInActor(m_pComponent->GetActor()->GetChild(i)); if ( _pChildEntity.isvalid() && _pChildEntity->GetType()&m_eType ) { GPtr<PhysicsDynamic> _pDynamic = _pChildEntity.downcast<PhysicsDynamic>(); if ( !_pDynamic->IsJointFather() ) { continue; } for ( int i=0; i<_pChildEntity->GetShapeCount(); ++i ) { _pChildEntity->GetShape(i)->ReleasePxShape(); } } } } void PhysicsDynamic::SetKinematic( bool kinematic ) { m_bKinematic = kinematic; if ( m_pPxActor ) { m_pPxActor->setRigidDynamicFlag(PxRigidDynamicFlag::eKINEMATIC, m_bKinematic); } } void PhysicsDynamic::SetJointFather( bool joint ) { if ( m_bJointFather == joint ) { return; } m_bJointFather = joint; OnCreate(m_pComponent); } void PhysicsDynamic::SetUseGravity( bool usege ) { m_bUseGravity = usege; if ( m_pPxActor && !m_bKinematic ) { m_pPxActor->setActorFlag(PxActorFlag::eDISABLE_GRAVITY, !m_bUseGravity); m_pPxActor->wakeUp(); } } void PhysicsDynamic::SetLinearVelocity( Math::float3& vel ) { if ( m_pPxActor && !m_bKinematic ) { m_pPxActor->setLinearVelocity(PxVec3(vel.x(),vel.y(),vel.z())); } } void PhysicsDynamic::SetAngularVelocity( Math::float3& vel ) { if ( m_pPxActor && !m_bKinematic ) { m_pPxActor->setAngularVelocity(PxVec3(vel.x(),vel.y(),vel.z())); } } Math::float3 PhysicsDynamic::GetLinearVelocity() const { Math::float3 vel(0.0f,0.0f,0.0f); if ( m_pPxActor && !m_bKinematic ) { PxVec3 v = m_pPxActor->getLinearVelocity(); vel.x() = v.x; vel.y() = v.y; vel.z() = v.z; } return vel; } Math::float3 PhysicsDynamic::GetAngularVelocity() const { Math::float3 vel(0.0f,0.0f,0.0f); if ( m_pPxActor && !m_bKinematic ) { PxVec3 v = m_pPxActor->getAngularVelocity(); vel.x() = v.x; vel.y() = v.y; vel.z() = v.z; } return vel; } void PhysicsDynamic::SetLinearDamping( float damping ) { if ( damping < 0.f ) { damping = 0.f; } m_fLinearDamping = damping; if ( m_pPxActor ) { m_pPxActor->setLinearDamping(m_fLinearDamping); } } void PhysicsDynamic::SetAngularDamping( float damping ) { if ( damping < 0.f ) { damping = 0.f; } m_fAngularDamping = damping; if ( m_pPxActor ) { m_pPxActor->setAngularDamping(m_fAngularDamping); } } void PhysicsDynamic::SetMaxAngularVel( float vel ) { if ( vel < 0.f ) { vel = 0.f; } m_fMaxAngularVel = vel; if ( m_pPxActor ) { m_pPxActor->setMaxAngularVelocity(m_fMaxAngularVel); } } void PhysicsDynamic::SetSleepThreshold( float threshold ) { if (threshold < 0.f) { threshold = 0.f; } m_fSleepThreshold = threshold; if ( m_pPxActor ) { m_pPxActor->setSleepThreshold(m_fSleepThreshold); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddForce( const Math::float3& force,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/ ) { if (NULL != m_pPxActor && !m_bKinematic) { m_pPxActor->addForce(PxVec3(force.x(),force.y(),force.z()),(PxForceMode::Enum)forcetype,bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddForceAtPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addForceAtPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddForceAtLocalPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addForceAtLocalPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddLocalForceAtPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addLocalForceAtPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } //------------------------------------------------------------------------ void PhysicsDynamic::AddLocalForceAtLocalPos(const Math::float3& force,const Math::float3& pos,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/) { if (NULL != m_pPxActor && !m_bKinematic) { PxRigidBodyExt::addLocalForceAtLocalPos(*(PxRigidBody*)m_pPxActor, PxVec3(force.x(),force.y(),force.z()), PxVec3(pos.x(),pos.y(),pos.z()), (PxForceMode::Enum)forcetype, bWakeUp); } } void PhysicsDynamic::AddTorque( const Math::float3& torque,ForceType forcetype /*= FORCE_NORMAL*/,bool bWakeUp /*= true*/ ) { if ( NULL != m_pPxActor && !m_bKinematic) { m_pPxActor->addTorque(PxVec3(torque.x(),torque.y(),torque.z()),(PxForceMode::Enum)forcetype,bWakeUp); } } void PhysicsDynamic::Move( const Math::float3& dir ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); _pos.p.x += dir.x(); _pos.p.y += dir.y(); _pos.p.z += dir.z(); if ( !m_bKinematic ) { m_pPxActor->setGlobalPose(_pos); } else { m_pPxActor->setKinematicTarget(_pos); } } } void PhysicsDynamic::MoveToPostion( const Math::float3& pos ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); _pos.p.x = pos.x(); _pos.p.y = pos.y(); _pos.p.z = pos.z(); m_pPxActor->setGlobalPose(_pos); } } void PhysicsDynamic::Rotate( const Math::quaternion& quat ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); Math::quaternion _quat = Math::quaternion::multiply(PxQuatToQuat(_pos.q), quat); _pos.q.x = _quat.x(); _pos.q.y = _quat.y(); _pos.q.z = _quat.z(); _pos.q.w = _quat.w(); if ( !m_bKinematic ) { m_pPxActor->setGlobalPose(_pos); } else { m_pPxActor->setKinematicTarget(_pos); } } } void PhysicsDynamic::RotateToRotation( const Math::quaternion& quat ) { if ( m_pPxActor ) { PxTransform _pos = m_pPxActor->getGlobalPose(); _pos.q.x = quat.x(); _pos.q.y = quat.y(); _pos.q.z = quat.z(); _pos.q.w = quat.w(); m_pPxActor->setGlobalPose(_pos); } } void PhysicsDynamic::Tick( float time ) { if ( m_pPxActor ) { if ( !m_bKinematic ) { if ( m_vContantForce.length() > 0.01f ) { m_pPxActor->addForce((PxVec3&)m_vContantForce); } else if ( m_vContantVelocity.length() > 0.01f ) { m_pPxActor->setLinearVelocity((PxVec3&)m_vContantVelocity); } if ( m_vContantTorques.length() > 0.01f ) { m_pPxActor->addTorque((PxVec3&)m_vContantTorques); } else if ( m_vContantAngularVel.length() > 0.01f ) { m_pPxActor->setAngularVelocity((PxVec3&)m_vContantAngularVel); } } if ( m_pComponent && m_pComponent->GetActor() ) { PxTransform _GlobalPos = m_pPxActor->getGlobalPose(); Math::float4 pos(_GlobalPos.p.x, _GlobalPos.p.y, _GlobalPos.p.z, 1.0f); Math::quaternion rot(_GlobalPos.q.x, _GlobalPos.q.y, _GlobalPos.q.z, _GlobalPos.q.w); m_pComponent->GetActor()->SetWorldPosition(pos); m_pComponent->GetActor()->SetWorldRotation(rot); } } } bool PhysicsDynamic::CopyFrom( GPtr<PhysicsEntity> src ) { if ( !src.isvalid() || src->GetType() != m_eType ) { return false; } Super::CopyFrom(src); GPtr<PhysicsDynamic> _pSrc = src.downcast<PhysicsDynamic>(); this->m_bJointFather = _pSrc->IsJointFather(); this->m_bUseGravity = _pSrc->IsUseGravity(); this->m_bKinematic = _pSrc->IsKinematic(); this->m_fLinearDamping = _pSrc->GetLinearDamping(); this->m_fAngularDamping = _pSrc->GetAngularDamping(); this->m_fMaxAngularVel = _pSrc->GetMaxAngularVel(); this->m_fSleepThreshold = _pSrc->GetSleepThreshold(); this->m_vContantForce = _pSrc->GetConstantForce(); this->m_vContantVelocity = _pSrc->GetConstantVelocity(); this->m_vContantTorques = _pSrc->GetConstantTorques(); this->m_vContantAngularVel = _pSrc->GetConstantAngularVel(); return true; } void PhysicsDynamic::UpdateEntityMass() { if (m_pPxActor != NULL) { int cnt = m_arrPhysicsShapePtr.Size(); int nb = m_pPxActor->getNbShapes(); PxReal* fDensities = new PxReal[nb]; PxShape** mShapes = new PxShape*[nb]; m_pPxActor->getShapes(mShapes,nb*sizeof(PxShape*)); int k=0; for(int i=0;i<nb;i++) { int j=0; for(j=0;j<cnt;j++) { if ( !m_arrPhysicsShapePtr[j]->IsValid() ) { continue; } if(m_arrPhysicsShapePtr[j]->GetName() == mShapes[i]->getName()) break; } if(j>=cnt) { delete []fDensities; delete []mShapes; m_pPxActor->setMass(0.01f); return; } if((PxU8)(mShapes[i]->getFlags() & PxShapeFlag::eSIMULATION_SHAPE) == 0) { continue; } fDensities[k++] = m_arrPhysicsShapePtr[j]->GetDensity(); } if(k<=0) { delete []fDensities; delete []mShapes; m_pPxActor->setMass(0.01f); return; } PxRigidBodyExt::updateMassAndInertia(*m_pPxActor, fDensities,k); delete []fDensities; delete []mShapes; } } float PhysicsDynamic::GetMass() { if ( m_pPxActor == NULL ) { return 0.01f; } bool _needUpdate = false; for ( int i=0; i<m_arrPhysicsShapePtr.Size(); ++i ) { if ( !m_arrPhysicsShapePtr[i]->IsValid() ) { //m_pPxActor->setMass(0.01f); //return 0.01f; continue; } if ( m_arrPhysicsShapePtr[i]->IsMassUpdate() ) { _needUpdate = true; m_arrPhysicsShapePtr[i]->UpdateMass(); } } if ( _needUpdate ) { UpdateEntityMass(); } return m_pPxActor->getMass(); } void PhysicsDynamic::Save( AppWriter* pSerialize ) { Super::Save(pSerialize); pSerialize->SerializeBool("JointFather", m_bJointFather); pSerialize->SerializeBool("UseGravity", m_bUseGravity); pSerialize->SerializeBool("Kinematic", m_bKinematic); pSerialize->SerializeFloat("LinearDamp", m_fLinearDamping); pSerialize->SerializeFloat("AngularDamp", m_fAngularDamping); pSerialize->SerializeFloat("MaxAngularVel", m_fMaxAngularVel); pSerialize->SerializeFloat("SleepThrehold", m_fSleepThreshold); pSerialize->SerializeFloat3("ContantForce", m_vContantForce); pSerialize->SerializeFloat3("ContantVelocity", m_vContantVelocity); pSerialize->SerializeFloat3("ContantTorques", m_vContantTorques); pSerialize->SerializeFloat3("ContantAngularVel", m_vContantAngularVel); } void PhysicsDynamic::Load( Version ver, AppReader* pReader ) { Super::Load(ver,pReader); pReader->SerializeBool("JointFather", m_bJointFather); pReader->SerializeBool("UseGravity", m_bUseGravity); pReader->SerializeBool("Kinematic", m_bKinematic); pReader->SerializeFloat("LinearDamp", m_fLinearDamping); pReader->SerializeFloat("AngularDamp", m_fAngularDamping); pReader->SerializeFloat("MaxAngularVel", m_fMaxAngularVel); pReader->SerializeFloat("SleepThrehold", m_fSleepThreshold); pReader->SerializeFloat3("ContantForce", m_vContantForce); pReader->SerializeFloat3("ContantVelocity", m_vContantVelocity); pReader->SerializeFloat3("ContantTorques", m_vContantTorques); pReader->SerializeFloat3("ContantAngularVel", m_vContantAngularVel); } } #endif
28.263866
159
0.662068
BikkyS
9026bfaae15f2420e5935d7435da17d74021a30d
2,528
cpp
C++
Source/Holodeck/Sensors/Private/RangeFinderSensor.cpp
AdrianSchoisengeier/holodeck-engine
bb55aa49cf8ac90a1f4002952b619564b82900b4
[ "MIT" ]
47
2018-10-05T01:54:17.000Z
2022-02-19T04:53:24.000Z
Source/Holodeck/Sensors/Private/RangeFinderSensor.cpp
AdrianSchoisengeier/holodeck-engine
bb55aa49cf8ac90a1f4002952b619564b82900b4
[ "MIT" ]
36
2018-10-05T03:43:24.000Z
2021-04-23T19:19:47.000Z
Source/Holodeck/Sensors/Private/RangeFinderSensor.cpp
AdrianSchoisengeier/holodeck-engine
bb55aa49cf8ac90a1f4002952b619564b82900b4
[ "MIT" ]
12
2018-10-08T11:45:24.000Z
2021-09-21T08:08:40.000Z
// MIT License (c) 2019 BYU PCCL see LICENSE file #include "Holodeck.h" #include "RangeFinderSensor.h" #include "Json.h" URangeFinderSensor::URangeFinderSensor() { SensorName = "RangeFinderSensor"; } // Allows sensor parameters to be set programmatically from client. void URangeFinderSensor::ParseSensorParms(FString ParmsJson) { Super::ParseSensorParms(ParmsJson); TSharedPtr<FJsonObject> JsonParsed; TSharedRef<TJsonReader<TCHAR>> JsonReader = TJsonReaderFactory<TCHAR>::Create(ParmsJson); if (FJsonSerializer::Deserialize(JsonReader, JsonParsed)) { if (JsonParsed->HasTypedField<EJson::Number>("LaserCount")) { LaserCount = JsonParsed->GetIntegerField("LaserCount"); } if (JsonParsed->HasTypedField<EJson::Number>("LaserAngle")) { LaserAngle = -JsonParsed->GetIntegerField("LaserAngle"); // in client positive angles point up } if (JsonParsed->HasTypedField<EJson::Number>("LaserMaxDistance")) { LaserMaxDistance = JsonParsed->GetIntegerField("LaserMaxDistance") * 100; // meters to centimeters } if (JsonParsed->HasTypedField<EJson::Boolean>("LaserDebug")) { LaserDebug = JsonParsed->GetBoolField("LaserDebug"); } } else { UE_LOG(LogHolodeck, Fatal, TEXT("URangeFinderSensor::ParseSensorParms:: Unable to parse json.")); } } void URangeFinderSensor::InitializeSensor() { Super::InitializeSensor(); //You need to get the pointer to the object you are attached to. Parent = this->GetAttachmentRootActor(); } void URangeFinderSensor::TickSensorComponent(float DeltaTime, ELevelTick TickType, FActorComponentTickFunction* ThisTickFunction) { float* FloatBuffer = static_cast<float*>(Buffer); for (int i = 0; i < LaserCount; i++) { FVector start = GetComponentLocation(); FVector end = GetForwardVector(); FVector right = GetRightVector(); end = end.RotateAngleAxis(360 * i / LaserCount, GetUpVector()); right = right.RotateAngleAxis(360 * i / LaserCount, GetUpVector()); end = end.RotateAngleAxis(LaserAngle, right); end = end * LaserMaxDistance; end = start + end; FCollisionQueryParams QueryParams = FCollisionQueryParams(); QueryParams.AddIgnoredActor(Parent); FHitResult Hit = FHitResult(); bool TraceResult = GetWorld()->LineTraceSingleByChannel(Hit, start, end, ECollisionChannel::ECC_Visibility, QueryParams); FloatBuffer[i] = (TraceResult ? Hit.Distance : LaserMaxDistance) / 100; // centimeter to meters if (LaserDebug) { DrawDebugLine(GetWorld(), start, end, FColor::Green, false, .01, ECC_WorldStatic, 1.f); } } }
33.263158
131
0.741297
AdrianSchoisengeier
9027979e51cf74adfe0e6bc3b083d48950c71fee
755
cpp
C++
problems/baekjoon/p2217.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
problems/baekjoon/p2217.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
problems/baekjoon/p2217.cpp
yejun614/algorithm-solve
ac7aca22e06a8aa39002c9bf6d6d39bbc6148ff9
[ "MIT" ]
null
null
null
/** * (210704) 로프 * https://www.acmicpc.net/problem/2217 * * [풀이] * 로프문제는 각 로프를 선택해서 최대중량을 알아내는 문제입니다. * 여기서 최대중량은 선택한 로프 중 최소중량을 가진 로프의 * 중량에 선택한 로프의 개수를 곱하면 얼마나 중량을 버틸수 있는지 * 계산할 수 있습니다. * * 어떤 로프들을 사용해야 최대중량을 얻을 수 있는지 알고리즘은 * 다음과 같습니다. * * 1) 입력받은 숫자들을 배열에 넣고 오름차순으로 정렬합니다. * 2) 차례대로 배열을 순회하면서 (로프의 개수)-(현재 index) * 를 곱하고 이를 저장합니다. * 3) 배열안에서 최대값을 정답으로 출력합니다. */ #include <cstdio> #include <cstdlib> #include <algorithm> using namespace std; int main() { int N; scanf("%d", &N); int* ropes = (int*)malloc(sizeof(int)*N); for (int i=0; i<N; i++) { scanf("%d", ropes+i); } sort(ropes, ropes+N); for (int i=0; i<N; i++) { ropes[i] *= N-i; } printf("%d\n", *max_element(ropes, ropes+N)); free(ropes); return 0; }
16.413043
46
0.590728
yejun614
9028e5bdb9c61b0fe6c16d878f84453c1a6d71ec
3,076
cpp
C++
src/app/main.cpp
jbuckmccready/staticpendulum_gui
8c14019e5903c531cca5cfefeeb22a1beca8b000
[ "MIT" ]
null
null
null
src/app/main.cpp
jbuckmccready/staticpendulum_gui
8c14019e5903c531cca5cfefeeb22a1beca8b000
[ "MIT" ]
null
null
null
src/app/main.cpp
jbuckmccready/staticpendulum_gui
8c14019e5903c531cca5cfefeeb22a1beca8b000
[ "MIT" ]
null
null
null
/* =========================================================================== * The MIT License (MIT) * * Copyright (c) 2016 Jedidiah Buck McCready <jbuckmccready@gmail.com> * * 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 "Models/modelsrepo.h" #include "QmlHelpers/systemintegrator.h" #include <QApplication> #include <QHash> #include <QObject> #include <QQmlApplicationEngine> #include <QQmlContext> #include <QtQml> #include <QQuickWindow> int main(int argc, char *argv[]) { // uncomment and modify for additional logging // see: http://doc.qt.io/qt-5/qloggingcategory.html // qputenv("QT_LOGGING_RULES", "qt.scenegraph.general=false;qt.scenegraph.time.renderloop=false;qt.scenegraph.time.renderer=false;qt.qpa.gl=true"); // Smoother rendering when resizing the window using the basic render loop // see: http://doc.qt.io/qt-5/qtquick-visualcanvas-scenegraph.html // for details of how it works qputenv("QSG_RENDER_LOOP", "basic"); // Qt::AA_UseSoftwareOpenGL will attempt to force the use of opengl32sw.dll // can be deployed with the llvm mesa library // QApplication::setAttribute(Qt::AA_UseSoftwareOpenGL); // Setting the scene graph backend to software will use the internal Qt // QSG software renderer // QQuickWindow::setSceneGraphBackend(QSGRendererInterface::Software); QApplication app(argc, argv); using namespace staticpendulum; qmlRegisterType<SystemIntegrator>("QmlHelpers", 1, 0, "SystemIntegrator"); qmlRegisterSingletonType<ModelsRepo>("ModelsRepo", 1, 0, "ModelsRepo", &ModelsRepo::qmlInstance); QQmlApplicationEngine engine; // Add import path to resolve Qml modules, note: using qrc path engine.addImportPath("qrc:/Qml/"); engine.rootContext()->setContextProperty("applicationDirPath", qApp->applicationDirPath()); engine.load(QUrl(QLatin1String("qrc:/Qml/Main/Main.qml"))); return app.exec(); }
42.722222
148
0.698635
jbuckmccready
902cd5a585d087fb3212da81977fbf035171d5f7
2,820
cpp
C++
Source/LSL/Private/LSLOutletComponent.cpp
brifsttar/plugin-UE4
9a1dcbe8ad01b58c606d6849fc441ed2306abb7f
[ "MIT" ]
6
2021-01-19T21:47:37.000Z
2022-01-30T21:20:35.000Z
Source/LSL/Private/LSLOutletComponent.cpp
brifsttar/plugin-UE4
9a1dcbe8ad01b58c606d6849fc441ed2306abb7f
[ "MIT" ]
5
2020-09-18T16:23:35.000Z
2022-02-16T13:44:17.000Z
Source/LSL/Private/LSLOutletComponent.cpp
brifsttar/plugin-UE4
9a1dcbe8ad01b58c606d6849fc441ed2306abb7f
[ "MIT" ]
4
2020-05-22T09:57:56.000Z
2021-08-19T04:05:22.000Z
// Copyright (c) 2021 Chadwick Boulay #include "LSLOutletComponent.h" #include "LSLPrivatePCH.h" #include <string> // Sets default values for this component's properties ULSLOutletComponent::ULSLOutletComponent() : StreamName(), StreamType(), SamplingRate(LSL_IRREGULAR_RATE), ChannelFormat(EChannelFormat::cfmt_float32), StreamID("NoStreamID") { // Set this component to be initialized when the game starts, and to be ticked every frame. You can turn these features // off to improve performance if you don't need them. bWantsInitializeComponent = true; } // Called when the game starts void ULSLOutletComponent::BeginPlay() { Super::BeginPlay(); //lsl_streaminfo lsl_myinfo = lsl_create_streaminfo(TCHAR_TO_ANSI(*StreamName), TCHAR_TO_ANSI(*StreamType), ChannelCount, SamplingRate, (lsl_channel_format_t)ChannelFormat, TCHAR_TO_ANSI(*StreamID)); UE_LOG(LogLSL, Log, TEXT("Attempting to create stream outlet with name %s, type %s, sampling rate %d."), *StreamName, *StreamType, SamplingRate); lsl::stream_info data_info( TCHAR_TO_ANSI(*StreamName), TCHAR_TO_ANSI(*StreamType), (int16)Channels.Num(), (double)SamplingRate, lsl::channel_format_t(ChannelFormat), TCHAR_TO_ANSI(*StreamID) ); lsl::xml_element channels = data_info.desc().append_child("channels"); for (auto& ch : Channels) { channels.append_child("channel") .append_child_value("label", TCHAR_TO_UTF8(*(ch.Label))) .append_child_value("unit", TCHAR_TO_UTF8(*(ch.Unit))); } //TODO: Check to see if the stream already exists. my_outlet = new lsl::stream_outlet(data_info); } void ULSLOutletComponent::EndPlay(const EEndPlayReason::Type EndPlayReason) { if (my_outlet != nullptr) { delete my_outlet; my_outlet = nullptr; } Super::EndPlay(EndPlayReason); } //push_sample functions void ULSLOutletComponent::PushSampleFloat(TArray<float> data) { my_outlet->push_sample(data.GetData()); } /* void ULSLOutletComponent::PushSampleDouble(TArray<double> data) { my_outlet->push_sample(data.GetData()); } */ void ULSLOutletComponent::PushSampleLong(TArray<int32> data) { my_outlet->push_sample(data.GetData()); } /* void ULSLOutletComponent::PushSampleInt(TArray<int16> data) { my_outlet->push_sample(data.GetData()); } */ /* void ULSLOutletComponent::PushSampleShort(TArray<int16> data) { my_outlet->push_sample(data.GetData()); } */ void ULSLOutletComponent::PushSampleString(TArray<FString> data) { std::vector<std::string> strVec; int32 b; for(b=0; b < data.Num(); b++) { strVec.push_back(TCHAR_TO_UTF8(*data[b])); } my_outlet->push_sample(strVec); } /* void ULSLOutletComponent::PushSampleChar(TArray<char> data) { lsl_push_sample_ctp(lsl_myoutlet,const_cast<char*>(data),0.0,true); } */
26.603774
203
0.724823
brifsttar
902ec8b78de2dbf6959b99b085cec39bf3b5a3a8
2,510
tcc
C++
ulmblas/level3/mkernel/mtrlsm.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
95
2015-05-14T15:21:44.000Z
2022-03-17T08:02:08.000Z
ulmblas/level3/mkernel/mtrlsm.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
4
2020-06-25T14:59:49.000Z
2022-02-16T12:45:00.000Z
ulmblas/level3/mkernel/mtrlsm.tcc
sneha0401/ulmBLAS
2b7665c6abc1784fe4041febd9d12de519ef4f08
[ "BSD-3-Clause" ]
40
2015-09-14T02:43:43.000Z
2021-12-26T11:43:36.000Z
#ifndef ULMBLAS_LEVEL3_MKERNEL_MTRLSM_TCC #define ULMBLAS_LEVEL3_MKERNEL_MTRLSM_TCC 1 #include <ulmblas/level3/ukernel/ugemm.h> #include <ulmblas/level3/mkernel/mtrlsm.h> #include <ulmblas/level3/ukernel/utrlsm.h> namespace ulmBLAS { template <typename IndexType, typename T, typename TB> void mtrlsm(IndexType mc, IndexType nc, const T &alpha, const T *A_, T *B_, TB *B, IndexType incRowB, IndexType incColB) { const IndexType MR = BlockSizeUGemm<T>::MR; const IndexType NR = BlockSizeUGemm<T>::NR; const IndexType mp = (mc+MR-1) / MR; const IndexType np = (nc+NR-1) / NR; const IndexType mr_ = mc % MR; const IndexType nr_ = nc % NR; IndexType mr, nr; IndexType kc; const T *nextA; const T *nextB; for (IndexType j=0; j<np; ++j) { nr = (j!=np-1 || nr_==0) ? NR : nr_; nextB = &B_[j*mc*NR]; IndexType ia = 0; for (IndexType i=0; i<mp; ++i) { mr = (i!=mp-1 || mr_==0) ? MR : mr_; kc = std::min(i*MR, mc-mr); nextA = &A_[(ia+i+1)*MR*MR]; if (i==mp-1) { nextA = A_; nextB = &B_[(j+1)*mc*NR]; if (j==np-1) { nextB = B_; } } if (mr==MR && nr==NR) { ugemm(kc, T(-1), &A_[ia*MR*MR], &B_[j*mc*NR], alpha, &B_[(j*mc+kc)*NR], NR, IndexType(1), nextA, nextB); utrlsm(&A_[(ia*MR+kc)*MR], &B_[(j*mc+kc)*NR], &B_[(j*mc+kc)*NR], NR, IndexType(1)); } else { // Call buffered micro kernels ugemm(mr, nr, kc, T(-1), &A_[ia*MR*MR], &B_[j*mc*NR], alpha, &B_[(j*mc+kc)*NR], NR, IndexType(1), nextA, nextB); utrlsm(mr, nr, &A_[(ia*MR+kc)*MR], &B_[(j*mc+kc)*NR], &B_[(j*mc+kc)*NR], NR, IndexType(1)); } ia += i+1; } } for (IndexType j=0; j<np; ++j) { nr = (j!=np-1 || nr_==0) ? NR : nr_; gecopy(mc, nr, false, &B_[j*mc*NR], NR, IndexType(1), &B[j*NR*incColB], incRowB, incColB); } } } // namespace ulmBLAS #endif // ULMBLAS_LEVEL3_MKERNEL_MTRLSM_TCC
26.989247
61
0.436653
sneha0401
90322515c4e788b9ffda2393041910b55f07f5a3
3,829
hpp
C++
CSGOSimple/IGameTypes.hpp
YMY1666527646/CustomHooks-csgo
c79cb831dbcab044969abf556b5bfe6fab5b187c
[ "MIT" ]
7
2022-02-08T18:19:07.000Z
2022-03-25T22:17:55.000Z
CSGOSimple/IGameTypes.hpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
null
null
null
CSGOSimple/IGameTypes.hpp
Kajus14/CustomHooks-csgo
aebc092ff4c5930ec7672501ba5b450dc0cbe5ba
[ "MIT" ]
5
2022-02-04T09:29:11.000Z
2022-03-21T15:09:13.000Z
#pragma once class IGameTypes { public: virtual ~IGameTypes() {} virtual bool Initialize(bool force) = 0; virtual bool IsInitialized() const = 0; virtual bool SetGameTypeAndMode(const char* gameType, const char* gameMode) = 0; virtual bool GetGameTypeAndModeFromAlias(const char* alias, int& gameType, int& gameMode) = 0; virtual bool SetGameTypeAndMode(int gameType, int gameMode) = 0; virtual void SetAndParseExtendedServerInfo(void* pExtendedServerInfo) = 0; virtual bool CheckShouldSetDefaultGameModeAndType(const char* mapName) = 0; virtual int GetCurrentGameType() const = 0; virtual int GetCurrentGameMode() const = 0; virtual const char* GetCurrentMapName() = 0; virtual const char* GetCurrentGameTypeNameID() = 0; virtual const char* GetCurrentGameModeNameID() = 0; virtual bool ApplyConvarsForCurrentMode(bool isMultiplayer) = 0; virtual void DisplayConvarsForCurrentMode() = 0; virtual const void* GetWeaponProgressionForCurrentModeCT() = 0; virtual const void* GetWeaponProgressionForCurrentModeT() = 0; virtual int GetNoResetVoteThresholdForCurrentModeCT() = 0; virtual int GetNoResetVoteThresholdForCurrentModeT() = 0; virtual const char* GetGameTypeFromInt(int gameType) = 0; virtual const char* GetGameModeFromInt(int gameType, int gameMode) = 0; virtual bool GetGameModeAndTypeIntsFromStrings(const char* szGameType, const char* szGameMode, int& iOutGameType, int& iOutGameMode) = 0; virtual bool GetGameModeAndTypeNameIdsFromStrings(const char* szGameType, const char* szGameMode, const char*& szOutGameTypeNameId, const char*& szOutGameModeNameId) = 0; virtual void CreateOrUpdateWorkshopMapGroup(const char* mapGroup, const void* mapList) = 0; virtual bool IsWorkshopMapGroup(const char* mapGroup) = 0; virtual const char* GetRandomMapGroup(const char* gameType, const char* gameMode) = 0; virtual const char* GetFirstMap(const char* mapGroup) = 0; virtual const char* GetRandomMap(const char* mapGroup) = 0; virtual const char* GetNextMap(const char* mapGroup, const char* mapName) = 0; virtual int GetMaxPlayersForTypeAndMode(int iType, int iMode) = 0; virtual bool IsValidMapGroupName(const char* mapGroup) = 0; virtual bool IsValidMapInMapGroup(const char* mapGroup, const char* mapName) = 0; virtual bool IsValidMapGroupForTypeAndMode(const char* mapGroup, const char* gameType, const char* gameMode) = 0; virtual bool ApplyConvarsForMap(const char* mapName, bool isMultiplayer) = 0; virtual bool GetMapInfo(const char* mapName, unsigned int& richPresence) = 0; virtual const void* GetTModelsForMap(const char* mapName) = 0; virtual const void* GetCTModelsForMap(const char* mapName) = 0; virtual const void* GetHostageModelsForMap(const char* mapName) = 0; virtual int GetDefaultGameTypeForMap(const char* mapName) = 0; virtual int GetDefaultGameModeForMap(const char* mapName) = 0; virtual const char* GetTViewModelArmsForMap(const char* mapName) = 0; virtual const char* GetCTViewModelArmsForMap(const char* mapName) = 0; virtual const char* GetRequiredAttrForMap(const char* mapName) = 0; virtual int GetRequiredAttrValueForMap(const char* mapName) = 0; virtual const char* GetRequiredAttrRewardForMap(const char* mapName) = 0; virtual int GetRewardDropListForMap(const char* mapName) = 0; virtual const void* GetMapGroupMapList(const char* mapGroup) = 0; virtual bool GetRunMapWithDefaultGametype() = 0; virtual void SetRunMapWithDefaultGameType(bool bUseDefault) = 0; virtual bool GetLoadingScreenDataIsCorrect() = 0; virtual void SetLoadingScreenDataIsCorrect(bool bIsCorrect) = 0; virtual bool SetCustomBotDifficulty(int botDiff) = 0; virtual int GetCustomBotDifficulty() = 0; virtual int GetCurrentServerNumSlots() = 0; virtual int GetCurrentServerSettingInt(const char* settingName, int defaultValue) = 0; };
42.076923
171
0.785061
YMY1666527646
9036671551e843ee603b0533bcce09b44366a71f
7,020
cpp
C++
src/appleseed/renderer/kernel/shading/oslshadergroupexec.cpp
dcoeurjo/appleseed
d5558afa7a351cb834977d8c8411b62542ea7019
[ "MIT" ]
null
null
null
src/appleseed/renderer/kernel/shading/oslshadergroupexec.cpp
dcoeurjo/appleseed
d5558afa7a351cb834977d8c8411b62542ea7019
[ "MIT" ]
null
null
null
src/appleseed/renderer/kernel/shading/oslshadergroupexec.cpp
dcoeurjo/appleseed
d5558afa7a351cb834977d8c8411b62542ea7019
[ "MIT" ]
null
null
null
// // This source file is part of appleseed. // Visit https://appleseedhq.net/ for additional information and resources. // // This software is released under the MIT license. // // Copyright (c) 2014-2018 Esteban Tovagliari, The appleseedhq Organization // // 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. // // Interface header. #include "oslshadergroupexec.h" // appleseed.renderer headers. #include "renderer/kernel/shading/closures.h" #include "renderer/kernel/shading/oslshadingsystem.h" #include "renderer/kernel/shading/shadingpoint.h" #include "renderer/kernel/shading/shadingray.h" #include "renderer/modeling/bsdf/bsdf.h" #include "renderer/modeling/shadergroup/shadergroup.h" // Standard headers. #include <cassert> using namespace foundation; namespace renderer { // // OSLShaderGroupExec class implementation. // OSLShaderGroupExec::OSLShaderGroupExec(OSLShadingSystem& shading_system, Arena& arena) : m_osl_shading_system(shading_system) , m_arena(arena) , m_osl_thread_info(shading_system.create_thread_info()) , m_osl_shading_context(shading_system.get_context(m_osl_thread_info)) { } OSLShaderGroupExec::~OSLShaderGroupExec() { if (m_osl_shading_context) m_osl_shading_system.release_context(m_osl_shading_context); if (m_osl_thread_info) m_osl_shading_system.destroy_thread_info(m_osl_thread_info); } void OSLShaderGroupExec::execute_shading( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const { do_execute( shader_group, shading_point, shading_point.get_ray().m_flags); } void OSLShaderGroupExec::execute_subsurface( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const { do_execute( shader_group, shading_point, VisibilityFlags::SubsurfaceRay); } void OSLShaderGroupExec::execute_transparency( const ShaderGroup& shader_group, const ShadingPoint& shading_point, Alpha& alpha, float* holdout) const { do_execute( shader_group, shading_point, VisibilityFlags::TransparencyRay); process_transparency_tree(shading_point.get_osl_shader_globals().Ci, alpha); if (holdout) *holdout = process_holdout_tree(shading_point.get_osl_shader_globals().Ci); } void OSLShaderGroupExec::execute_shadow( const ShaderGroup& shader_group, const ShadingPoint& shading_point, Alpha& alpha) const { do_execute( shader_group, shading_point, VisibilityFlags::ShadowRay); process_transparency_tree(shading_point.get_osl_shader_globals().Ci, alpha); } void OSLShaderGroupExec::execute_emission( const ShaderGroup& shader_group, const ShadingPoint& shading_point) const { do_execute( shader_group, shading_point, VisibilityFlags::LightRay); } void OSLShaderGroupExec::execute_bump( const ShaderGroup& shader_group, const ShadingPoint& shading_point, const Vector2f& s) const { // Choose between BSSRDF and BSDF. if (shader_group.has_subsurface() && s[0] < 0.5f) { do_execute( shader_group, shading_point, VisibilityFlags::SubsurfaceRay); CompositeSubsurfaceClosure c( Basis3f(shading_point.get_shading_basis()), shading_point.get_osl_shader_globals().Ci, m_arena); // Pick a shading basis from one of the BSSRDF closures. if (c.get_closure_count() > 0) { const size_t index = c.choose_closure(s[1]); shading_point.set_shading_basis( Basis3d(c.get_closure_shading_basis(index))); } } else { do_execute( shader_group, shading_point, VisibilityFlags::CameraRay); choose_bsdf_closure_shading_basis(shading_point, s); } } Color3f OSLShaderGroupExec::execute_background( const ShaderGroup& shader_group, const Vector3f& outgoing) const { assert(m_osl_shading_context); assert(m_osl_thread_info); OSL::ShaderGlobals sg; memset(&sg, 0, sizeof(OSL::ShaderGlobals)); sg.I = outgoing; sg.renderer = m_osl_shading_system.renderer(); sg.raytype = VisibilityFlags::CameraRay; m_osl_shading_system.execute( m_osl_shading_context, *reinterpret_cast<OSL::ShaderGroup*>(shader_group.osl_shader_group()), sg); return process_background_tree(sg.Ci); } void OSLShaderGroupExec::do_execute( const ShaderGroup& shader_group, const ShadingPoint& shading_point, const VisibilityFlags::Type ray_flags) const { assert(m_osl_shading_context); assert(m_osl_thread_info); shading_point.initialize_osl_shader_globals( shader_group, ray_flags, m_osl_shading_system.renderer()); m_osl_shading_system.execute( m_osl_shading_context, *reinterpret_cast<OSL::ShaderGroup*>(shader_group.osl_shader_group()), shading_point.get_osl_shader_globals()); } void OSLShaderGroupExec::choose_bsdf_closure_shading_basis( const ShadingPoint& shading_point, const Vector2f& s) const { CompositeSurfaceClosure c( Basis3f(shading_point.get_shading_basis()), shading_point.get_osl_shader_globals().Ci, m_arena); float pdfs[CompositeSurfaceClosure::MaxClosureEntries]; const size_t num_closures = c.compute_pdfs(ScatteringMode::All, pdfs); if (num_closures == 0) return; const size_t index = c.choose_closure(s[1], num_closures, pdfs); shading_point.set_shading_basis( Basis3d(c.get_closure_shading_basis(index))); } } // namespace renderer
31.061947
86
0.687037
dcoeurjo
9037d20577c7e61345a3e8273e147d6fae44841b
847
cc
C++
packages/SPn/spn/Fixed_Source_Solver.pt.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
19
2015-06-04T09:02:41.000Z
2021-04-27T19:32:55.000Z
packages/SPn/spn/Fixed_Source_Solver.pt.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
null
null
null
packages/SPn/spn/Fixed_Source_Solver.pt.cc
GCZhang/Profugus
d4d8fe295a92a257b26b6082224226ca1edbff5d
[ "BSD-2-Clause" ]
5
2016-10-05T20:48:28.000Z
2021-06-21T12:00:54.000Z
//----------------------------------*-C++-*----------------------------------// /*! * \file SPn/spn/Fixed_Source_Solver.pt.cc * \author Thomas M. Evans * \date Fri Feb 21 14:41:20 2014 * \brief Fixed_Source_Solver explicit instantiation. * \note Copyright (C) 2014 Oak Ridge National Laboratory, UT-Battelle, LLC. */ //---------------------------------------------------------------------------// #include "Fixed_Source_Solver.t.hh" #include "solvers/LinAlgTypedefs.hh" namespace profugus { template class Fixed_Source_Solver<EpetraTypes>; template class Fixed_Source_Solver<TpetraTypes>; } // end namespace profugus //---------------------------------------------------------------------------// // end of Fixed_Source_Solver.pt.cc //---------------------------------------------------------------------------//
33.88
79
0.455726
GCZhang
903b27b7c3f2be22668ea126222a03a54ddcedb3
1,920
cpp
C++
Bullet Hell/Sprite.cpp
PotatoesBasket/Bullet-Hell
0d6c12f4a73d37567afbf885278848cff315a62e
[ "MIT" ]
null
null
null
Bullet Hell/Sprite.cpp
PotatoesBasket/Bullet-Hell
0d6c12f4a73d37567afbf885278848cff315a62e
[ "MIT" ]
null
null
null
Bullet Hell/Sprite.cpp
PotatoesBasket/Bullet-Hell
0d6c12f4a73d37567afbf885278848cff315a62e
[ "MIT" ]
null
null
null
#include "Sprite.h" #include "ResourceManager.h" Sprite::Sprite(SpriteType sprite) { m_texture = ResourceManager::getInstance().loadTexture(sprite.filename); m_columnCount = sprite.columnCount; m_rowCount = sprite.rowCount; m_animSpeed = sprite.animSpeed; m_sheetWidth = m_texture->as<aie::Texture>()->getWidth(); m_sheetHeight = m_texture->as<aie::Texture>()->getHeight(); m_spriteWidth = m_texture->as<aie::Texture>()->getWidth() / m_columnCount; m_spriteHeight = m_texture->as<aie::Texture>()->getHeight() / m_rowCount; } void Sprite::changeSprite(SpriteType sprite) { m_texture = ResourceManager::getInstance().loadTexture(sprite.filename); m_columnCount = sprite.columnCount; m_rowCount = sprite.rowCount; m_animSpeed = sprite.animSpeed; m_sheetWidth = m_texture->as<aie::Texture>()->getWidth(); m_sheetHeight = m_texture->as<aie::Texture>()->getHeight(); m_spriteWidth = m_texture->as<aie::Texture>()->getWidth() / m_columnCount; m_spriteHeight = m_texture->as<aie::Texture>()->getHeight() / m_rowCount; } void Sprite::updateUVRect(aie::Renderer2D* renderer) { //get size of single frame as percentage of total spritesheet float width = 1.0f / m_columnCount; float height = 1.0f / m_rowCount; //initialise renderer->setUVRect(width * m_currentCol, height * m_currentRow, width, height); //play animation if (m_timer > m_animSpeed) { ++m_currentCol; if (m_currentCol == m_columnCount) { ++m_currentRow; m_currentCol = 0; } if (m_currentRow == m_rowCount) m_currentRow = 0; renderer->setUVRect(width * m_currentCol, height * m_currentRow, width, height); m_timer = 0; } } void Sprite::draw(GameObject* gameObject, aie::Renderer2D* renderer) { updateUVRect(renderer); renderer->drawSpriteTransformed3x3(m_texture->as<aie::Texture>(), gameObject->getGlobalTransformFloat(), m_spriteWidth, m_spriteHeight); renderer->setUVRect(1, 1, 1, 1); //reset UV }
28.656716
82
0.732292
PotatoesBasket
9040d3facda72fcc84f533e9ed78e70d9a9b4e93
958
hpp
C++
SandboxRendering/SandboxRendering/Src/GameManagerWorldComponent.hpp
filu005/PolyEngineExamples
7d18753c068617fa5e4167cbc2269d39726253ce
[ "MIT" ]
null
null
null
SandboxRendering/SandboxRendering/Src/GameManagerWorldComponent.hpp
filu005/PolyEngineExamples
7d18753c068617fa5e4167cbc2269d39726253ce
[ "MIT" ]
null
null
null
SandboxRendering/SandboxRendering/Src/GameManagerWorldComponent.hpp
filu005/PolyEngineExamples
7d18753c068617fa5e4167cbc2269d39726253ce
[ "MIT" ]
null
null
null
#pragma once #include <UniqueID.hpp> #include <Collections/Dynarray.hpp> #include <ECS/ComponentBase.hpp> #include <Rendering/MeshRenderingComponent.hpp> #include <Rendering/PostprocessSettingsComponent.hpp> #include <Rendering/Lighting/LightSourceComponent.hpp> using namespace Poly; class GameManagerWorldComponent : public ComponentBase { public: SafePtr<Entity> Camera; PostprocessSettingsComponent* PostCmp; SafePtr<Entity> Model; bool IsDrawingDebugMeshes = true; Dynarray<SafePtr<Entity>> GameEntities; ParticleComponent* particleDefault; ParticleComponent* particleAmbient; ParticleComponent* particleAmbientWind; ParticleComponent* particleLocalSpace; ParticleComponent* particleWorldSpace; ParticleComponent* particleHeart; ParticleComponent* particleHeartImpact0; ParticleComponent* particleHeartImpact1; ParticleComponent* particleHeartImpact2; Dynarray<Vector> LightsStartPositions; Dynarray<Entity*> PointLightEntities; };
28.176471
54
0.836117
filu005
90486f4bb552f7863fce45307fe01193fbb0c9fb
1,491
cpp
C++
longest-palindromic-substring/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
3
2018-05-08T14:08:50.000Z
2019-02-28T00:10:14.000Z
longest-palindromic-substring/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
longest-palindromic-substring/solution.cpp
Javran/leetcode
f3899fe1424d3cda72f44102bab6dd95a7c7a320
[ "MIT" ]
null
null
null
#include <string> #include <iostream> #include <cstdio> #include <cassert> class Solution { public: std::string longestPalindrome(std::string s) { int slen = s.length(); if (slen == 0) return s; // at least one. int beginInd = 0, endInd = 0, maxLen = 1; // try odds first. for (int i = 0; i < slen; ++i) { int j; // try different lengths for (j = 1; i-j >= 0 && i+j < slen; ++j) { if (s[i-j] != s[i+j]) break; } // either j just outside of range or we have a mismatch --j; if (i-j >= 0 && i+j < slen && j*2+1 > maxLen) { beginInd = i-j; endInd = i+j; maxLen = j*2 + 1; } } // try evens for (int i = 0; i < slen; ++i) { int j; // now i stands for using s[i] | s[i+1] as middle point. for (j = 1; i-j+1 >= 0 && i+j < slen; ++j) { if (s[i-j+1] != s[i+j]) break; } --j; if (i-j+1 >= 0 && i+j < slen && j*2 > maxLen) { beginInd = i-j+1; endInd = i+j; maxLen = j*2; } } return s.substr(beginInd, maxLen); } }; int main() { Solution s = Solution(); std::cout << s.longestPalindrome("fasdffdsafcabacgg"); return 0; }
25.706897
68
0.389671
Javran
904be75537e53684ca7b8993089986dcd5fc166c
2,714
cc
C++
neb/test/host_status/ctor_default.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/test/host_status/ctor_default.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
neb/test/host_status/ctor_default.cc
sdelafond/centreon-broker
21178d98ed8a061ca71317d23c2026dbc4edaca2
[ "Apache-2.0" ]
null
null
null
/* ** Copyright 2013,2015 Centreon ** ** 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. ** ** For more information : contact@centreon.com */ #include <cmath> #include <cstdlib> #include "com/centreon/broker/neb/host_status.hh" using namespace com::centreon::broker; /** * Check host_status' default constructor. * * @return EXIT_SUCCESS on success. */ int main() { // Object. neb::host_status hs; // Check. return (((hs.source_id != 0) || (hs.destination_id != 0) || hs.acknowledged || (hs.acknowledgement_type != 0) || hs.active_checks_enabled || !hs.check_command.isEmpty() || (fabs(hs.check_interval) > 0.0001) || !hs.check_period.isEmpty() || (hs.check_type != 0) || (hs.current_check_attempt != 0) || (hs.current_state != 4) || (hs.downtime_depth != 0) || !hs.enabled || !hs.event_handler.isEmpty() || hs.event_handler_enabled || (fabs(hs.execution_time) > 0.0001) || hs.flap_detection_enabled || hs.has_been_checked || (hs.host_id != 0) || hs.is_flapping || (hs.last_check != 0) || (hs.last_hard_state != 4) || (hs.last_hard_state_change != 0) || (hs.last_notification != 0) || (hs.last_state_change != 0) || (hs.last_time_down != 0) || (hs.last_time_unreachable != 0) || (hs.last_time_up != 0) || (hs.last_update != 0) || (fabs(hs.latency) > 0.0001) || (hs.max_check_attempts != 0) || (hs.next_check != 0) || (hs.next_notification != 0) || hs.no_more_notifications || (hs.notification_number != 0) || hs.notifications_enabled || hs.obsess_over || !hs.output.isEmpty() || hs.passive_checks_enabled || (fabs(hs.percent_state_change) > 0.0001) || !hs.perf_data.isEmpty() || (fabs(hs.retry_interval) > 0.0001) || hs.should_be_scheduled || (hs.state_type != 0)) ? EXIT_FAILURE : EXIT_SUCCESS); }
33.097561
75
0.565954
sdelafond
904c01640bec1b7e437075078a10dabc531e405f
289
cpp
C++
Day-6/array-string.cpp
suubh/100-Days-of-Code
9939ea68406459dc8118a37d8cb44da012dfc678
[ "MIT" ]
1
2021-06-03T17:33:51.000Z
2021-06-03T17:33:51.000Z
Day-6/array-string.cpp
suubh/100-Days-of-Code
9939ea68406459dc8118a37d8cb44da012dfc678
[ "MIT" ]
1
2021-07-28T01:31:26.000Z
2021-07-28T01:31:26.000Z
Day-6/array-string.cpp
suubh/100-Days-of-Code
9939ea68406459dc8118a37d8cb44da012dfc678
[ "MIT" ]
1
2021-12-19T15:34:50.000Z
2021-12-19T15:34:50.000Z
#include<iostream> #include<string> using namespace std; int main(){ //Array of string //Method 1 char *str[3]={"Hi","Hello","Bye"}; for(int i=0;i<3;i++){ cout << str[i]; } //Method 2 char s[3][10]={"Hi","Hello","Bye"}; for(int i=0;i<3;i++){ cout << s[i]; } return 0; }
15.210526
36
0.546713
suubh
904fbe01774a8a69afaee24e524997fd64c9e880
11,227
cpp
C++
minorGems/crypto/hashes/sha1.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
1
2020-01-16T00:07:11.000Z
2020-01-16T00:07:11.000Z
minorGems/crypto/hashes/sha1.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
null
null
null
minorGems/crypto/hashes/sha1.cpp
PhilipLudington/CastleDoctrine
443f2b6b0215a6d71515c8887c99b4322965622e
[ "Unlicense" ]
2
2019-09-17T12:08:20.000Z
2020-09-26T00:54:48.000Z
/* * Modification History * * 2002-May-25 Jason Rohrer * Changed to use minorGems endian.h * Added a function for hashing an entire string to a hex digest. * Added a function for getting a raw digest. * Fixed a deletion bug. * * 2003-August-24 Jason Rohrer * Switched to use minorGems hex encoding. * * 2003-September-15 Jason Rohrer * Added support for hashing raw (non-string) data. * * 2003-September-21 Jason Rohrer * Fixed bug that was causing overwrite of input data. * * 2004-January-13 Jason Rohrer * Fixed system includes. * * 2013-January-7 Jason Rohrer * Added HMAC-SHA1 implementation. */ /* * sha1.c * * Originally witten by Steve Reid <steve@edmweb.com> * * Modified by Aaron D. Gifford <agifford@infowest.com> * * NO COPYRIGHT - THIS IS 100% IN THE PUBLIC DOMAIN * * The original unmodified version is available at: * ftp://ftp.funet.fi/pub/crypt/hash/sha/sha1.c * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) 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 AUTHOR(S) 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 "sha1.h" #include <string.h> #include <stdio.h> // for hex encoding #include "minorGems/formats/encodingUtils.h" #define rol(value, bits) (((value) << (bits)) | ((value) >> (32 - (bits)))) /* blk0() and blk() perform the initial expand. */ /* I got the idea of expanding during the round function from SSLeay */ #if __BYTE_ORDER == __LITTLE_ENDIAN #define blk0(i) (block->l[i] = (rol(block->l[i],24)&(sha1_quadbyte)0xFF00FF00) \ |(rol(block->l[i],8)&(sha1_quadbyte)0x00FF00FF)) #else #define blk0(i) block->l[i] #endif #define blk(i) (block->l[i&15] = rol(block->l[(i+13)&15]^block->l[(i+8)&15] \ ^block->l[(i+2)&15]^block->l[i&15],1)) /* (R0+R1), R2, R3, R4 are the different operations used in SHA1 */ #define R0(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk0(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R1(v,w,x,y,z,i) z+=((w&(x^y))^y)+blk(i)+0x5A827999+rol(v,5);w=rol(w,30); #define R2(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0x6ED9EBA1+rol(v,5);w=rol(w,30); #define R3(v,w,x,y,z,i) z+=(((w|x)&y)|(w&x))+blk(i)+0x8F1BBCDC+rol(v,5);w=rol(w,30); #define R4(v,w,x,y,z,i) z+=(w^x^y)+blk(i)+0xCA62C1D6+rol(v,5);w=rol(w,30); typedef union _BYTE64QUAD16 { sha1_byte c[64]; sha1_quadbyte l[16]; } BYTE64QUAD16; /* Hash a single 512-bit block. This is the core of the algorithm. */ void SHA1_Transform(sha1_quadbyte state[5], sha1_byte buffer[64]) { sha1_quadbyte a, b, c, d, e; BYTE64QUAD16 *block; block = (BYTE64QUAD16*)buffer; /* Copy context->state[] to working vars */ a = state[0]; b = state[1]; c = state[2]; d = state[3]; e = state[4]; /* 4 rounds of 20 operations each. Loop unrolled. */ R0(a,b,c,d,e, 0); R0(e,a,b,c,d, 1); R0(d,e,a,b,c, 2); R0(c,d,e,a,b, 3); R0(b,c,d,e,a, 4); R0(a,b,c,d,e, 5); R0(e,a,b,c,d, 6); R0(d,e,a,b,c, 7); R0(c,d,e,a,b, 8); R0(b,c,d,e,a, 9); R0(a,b,c,d,e,10); R0(e,a,b,c,d,11); R0(d,e,a,b,c,12); R0(c,d,e,a,b,13); R0(b,c,d,e,a,14); R0(a,b,c,d,e,15); R1(e,a,b,c,d,16); R1(d,e,a,b,c,17); R1(c,d,e,a,b,18); R1(b,c,d,e,a,19); R2(a,b,c,d,e,20); R2(e,a,b,c,d,21); R2(d,e,a,b,c,22); R2(c,d,e,a,b,23); R2(b,c,d,e,a,24); R2(a,b,c,d,e,25); R2(e,a,b,c,d,26); R2(d,e,a,b,c,27); R2(c,d,e,a,b,28); R2(b,c,d,e,a,29); R2(a,b,c,d,e,30); R2(e,a,b,c,d,31); R2(d,e,a,b,c,32); R2(c,d,e,a,b,33); R2(b,c,d,e,a,34); R2(a,b,c,d,e,35); R2(e,a,b,c,d,36); R2(d,e,a,b,c,37); R2(c,d,e,a,b,38); R2(b,c,d,e,a,39); R3(a,b,c,d,e,40); R3(e,a,b,c,d,41); R3(d,e,a,b,c,42); R3(c,d,e,a,b,43); R3(b,c,d,e,a,44); R3(a,b,c,d,e,45); R3(e,a,b,c,d,46); R3(d,e,a,b,c,47); R3(c,d,e,a,b,48); R3(b,c,d,e,a,49); R3(a,b,c,d,e,50); R3(e,a,b,c,d,51); R3(d,e,a,b,c,52); R3(c,d,e,a,b,53); R3(b,c,d,e,a,54); R3(a,b,c,d,e,55); R3(e,a,b,c,d,56); R3(d,e,a,b,c,57); R3(c,d,e,a,b,58); R3(b,c,d,e,a,59); R4(a,b,c,d,e,60); R4(e,a,b,c,d,61); R4(d,e,a,b,c,62); R4(c,d,e,a,b,63); R4(b,c,d,e,a,64); R4(a,b,c,d,e,65); R4(e,a,b,c,d,66); R4(d,e,a,b,c,67); R4(c,d,e,a,b,68); R4(b,c,d,e,a,69); R4(a,b,c,d,e,70); R4(e,a,b,c,d,71); R4(d,e,a,b,c,72); R4(c,d,e,a,b,73); R4(b,c,d,e,a,74); R4(a,b,c,d,e,75); R4(e,a,b,c,d,76); R4(d,e,a,b,c,77); R4(c,d,e,a,b,78); R4(b,c,d,e,a,79); /* Add the working vars back into context.state[] */ state[0] += a; state[1] += b; state[2] += c; state[3] += d; state[4] += e; /* Wipe variables */ a = b = c = d = e = 0; } /* SHA1_Init - Initialize new context */ void SHA1_Init(SHA_CTX* context) { /* SHA1 initialization constants */ context->state[0] = 0x67452301; context->state[1] = 0xEFCDAB89; context->state[2] = 0x98BADCFE; context->state[3] = 0x10325476; context->state[4] = 0xC3D2E1F0; context->count[0] = context->count[1] = 0; } /* Run your data through this. */ void SHA1_Update(SHA_CTX *context, sha1_byte *data, unsigned int len) { unsigned int i, j; j = (context->count[0] >> 3) & 63; if ((context->count[0] += len << 3) < (len << 3)) context->count[1]++; context->count[1] += (len >> 29); if ((j + len) > 63) { memcpy(&context->buffer[j], data, (i = 64-j)); SHA1_Transform(context->state, context->buffer); for ( ; i + 63 < len; i += 64) { SHA1_Transform(context->state, &data[i]); } j = 0; } else i = 0; memcpy(&context->buffer[j], &data[i], len - i); } /* Add padding and return the message digest. */ void SHA1_Final(sha1_byte digest[SHA1_DIGEST_LENGTH], SHA_CTX *context) { sha1_quadbyte i, j; sha1_byte finalcount[8]; for (i = 0; i < 8; i++) { finalcount[i] = (sha1_byte)((context->count[(i >= 4 ? 0 : 1)] >> ((3-(i & 3)) * 8) ) & 255); /* Endian independent */ } SHA1_Update(context, (sha1_byte *)"\200", 1); while ((context->count[0] & 504) != 448) { SHA1_Update(context, (sha1_byte *)"\0", 1); } /* Should cause a SHA1_Transform() */ SHA1_Update(context, finalcount, 8); for (i = 0; i < SHA1_DIGEST_LENGTH; i++) { digest[i] = (sha1_byte) ((context->state[i>>2] >> ((3-(i & 3)) * 8) ) & 255); } /* Wipe variables */ i = j = 0; memset(context->buffer, 0, SHA1_BLOCK_LENGTH); memset(context->state, 0, SHA1_DIGEST_LENGTH); memset(context->count, 0, 8); memset(&finalcount, 0, 8); } unsigned char *computeRawSHA1Digest( unsigned char *inData, int inDataLength ) { SHA_CTX context; SHA1_Init( &context ); // copy into buffer, since this SHA1 implementation seems to overwrite // parts of the data buffer. unsigned char *buffer = new unsigned char[ inDataLength ]; memcpy( (void *)buffer, (void *)inData, inDataLength ); SHA1_Update( &context, buffer, inDataLength ); delete [] buffer; unsigned char *digest = new unsigned char[ SHA1_DIGEST_LENGTH ]; SHA1_Final( digest, &context ); return digest; } unsigned char *computeRawSHA1Digest( char *inString ) { SHA_CTX context; SHA1_Init( &context ); // copy into buffer, since this SHA1 implementation seems to overwrite // parts of the data buffer. int dataLength = strlen( inString ); unsigned char *buffer = new unsigned char[ dataLength ]; memcpy( (void *)buffer, (void *)inString, dataLength ); SHA1_Update( &context, buffer, strlen( inString ) ); delete [] buffer; unsigned char *digest = new unsigned char[ SHA1_DIGEST_LENGTH ]; SHA1_Final( digest, &context ); return digest; } char *computeSHA1Digest( char *inString ) { unsigned char *digest = computeRawSHA1Digest( inString ); char *digestHexString = hexEncode( digest, SHA1_DIGEST_LENGTH ); delete [] digest; return digestHexString; } char *computeSHA1Digest( unsigned char *inData, int inDataLength ) { unsigned char *digest = computeRawSHA1Digest( inData, inDataLength ); char *digestHexString = hexEncode( digest, SHA1_DIGEST_LENGTH ); delete [] digest; return digestHexString; } // returns new data buffer of length inALength + inBLength static unsigned char *dataConcat( unsigned char *inA, int inALength, unsigned char *inB, int inBLength ) { int netLength = inALength + inBLength; unsigned char *netData = new unsigned char[ netLength ]; int i=0; for( int j=0; j<inALength; j++ ) { netData[i] = inA[j]; i++; } for( int j=0; j<inBLength; j++ ) { netData[i] = inB[j]; i++; } return netData; } #include "minorGems/util/stringUtils.h" char *hmac_sha1( const char *inKey, const char *inData ) { unsigned char *keyRaw = (unsigned char*)stringDuplicate( inKey ); int keyLength = strlen( inKey ); //unsigned char *computeRawSHA1Digest( unsigned char *inData, int inDataLength // shorten long keys down to 20 byte hash of key, if needed if( keyLength > SHA1_BLOCK_LENGTH ) { unsigned char *newKey = computeRawSHA1Digest( keyRaw, keyLength ); delete [] keyRaw; keyRaw = newKey; keyLength = SHA1_DIGEST_LENGTH; } // pad key out to blocksize with zeros if( keyLength < SHA1_BLOCK_LENGTH ) { unsigned char *newKey = new unsigned char[ SHA1_BLOCK_LENGTH ]; memset( newKey, 0, SHA1_BLOCK_LENGTH ); memcpy( newKey, keyRaw, keyLength ); delete [] keyRaw; keyRaw = newKey; keyLength = SHA1_BLOCK_LENGTH; } // computer inner and outer keys by XORing with data block unsigned char *outerKey = new unsigned char[ keyLength ]; unsigned char *innerKey = new unsigned char[ keyLength ]; for( int i=0; i<keyLength; i++ ) { outerKey[i] = 0x5c ^ keyRaw[i]; innerKey[i] = 0x36 ^ keyRaw[i]; } delete [] keyRaw; int dataLength = strlen( inData ); int innerDataLength = keyLength +dataLength; unsigned char *innerData = dataConcat( innerKey, keyLength, (unsigned char*)inData, dataLength ); delete [] innerKey; unsigned char *innerHash = computeRawSHA1Digest( innerData, innerDataLength ); delete [] innerData; int outerDataLength = keyLength + SHA1_DIGEST_LENGTH; unsigned char *outerData = dataConcat( outerKey, keyLength, innerHash, SHA1_DIGEST_LENGTH ); delete [] outerKey; delete [] innerHash; char *digest = computeSHA1Digest( outerData, outerDataLength ); delete [] outerData; return digest; }
30.180108
84
0.607999
PhilipLudington
9056532d5533384a189b6b5822ec03d8b0ba92e2
4,137
cpp
C++
src/GPath.cpp
jkchang62/GraphicsEngine
f38566b57a6ef111c18bed697a90729a5ebeb8d1
[ "MIT" ]
null
null
null
src/GPath.cpp
jkchang62/GraphicsEngine
f38566b57a6ef111c18bed697a90729a5ebeb8d1
[ "MIT" ]
null
null
null
src/GPath.cpp
jkchang62/GraphicsEngine
f38566b57a6ef111c18bed697a90729a5ebeb8d1
[ "MIT" ]
null
null
null
/* * Copyright 2018 Mike Reed */ #include "GPath.h" #include "GMatrix.h" GPath::GPath() {} GPath::~GPath() {} GPath& GPath::operator=(const GPath& src) { if (this != &src) { fPts = src.fPts; fVbs = src.fVbs; } return *this; } GPath& GPath::reset() { fPts.clear(); fVbs.clear(); return *this; } void GPath::dump() const { Iter iter(*this); GPoint pts[GPath::kMaxNextPoints]; for (;;) { switch (iter.next(pts)) { case kMove: printf("M %g %g\n", pts[0].fX, pts[0].fY); break; case kLine: printf("L %g %g\n", pts[1].fX, pts[1].fY); break; case kQuad: printf("Q %g %g %g %g\n", pts[1].fX, pts[1].fY, pts[2].fX, pts[2].fY); break; case kCubic: printf("C %g %g %g %g %g %g\n", pts[1].fX, pts[1].fY, pts[2].fX, pts[2].fY, pts[3].fX, pts[3].fY); break; case kDone: return; } } } GPath& GPath::quadTo(GPoint p1, GPoint p2) { assert(fVbs.size() > 0); fPts.push_back(p1); fPts.push_back(p2); fVbs.push_back(kQuad); return *this; } GPath& GPath::cubicTo(GPoint p1, GPoint p2, GPoint p3) { assert(fVbs.size() > 0); fPts.push_back(p1); fPts.push_back(p2); fPts.push_back(p3); fVbs.push_back(kCubic); return *this; } ///////////////////////////////////////////////////////////////// GPath::Iter::Iter(const GPath& path) { fPrevMove = nullptr; fCurrPt = path.fPts.data(); fCurrVb = path.fVbs.data(); fStopVb = fCurrVb + path.fVbs.size(); } GPath::Verb GPath::Iter::next(GPoint pts[]) { assert(fCurrVb <= fStopVb); if (fCurrVb == fStopVb) { return kDone; } Verb v = *fCurrVb++; switch (v) { case kMove: fPrevMove = fCurrPt; pts[0] = *fCurrPt++; break; case kLine: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; break; case kQuad: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; break; case kCubic: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; pts[3] = *fCurrPt++; break; case kDone: assert(false); // not reached } return v; } GPath::Edger::Edger(const GPath& path) { fPrevMove = nullptr; fCurrPt = path.fPts.data(); fCurrVb = path.fVbs.data(); fStopVb = fCurrVb + path.fVbs.size(); fPrevVerb = kDone; } GPath::Verb GPath::Edger::next(GPoint pts[]) { assert(fCurrVb <= fStopVb); bool do_return = false; while (fCurrVb < fStopVb) { switch (*fCurrVb++) { case kMove: if (fPrevVerb == kLine) { pts[0] = fCurrPt[-1]; pts[1] = *fPrevMove; do_return = true; } fPrevMove = fCurrPt++; fPrevVerb = kMove; break; case kLine: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; fPrevVerb = kLine; return kLine; case kQuad: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; fPrevVerb = kQuad; return kQuad; case kCubic: pts[0] = fCurrPt[-1]; pts[1] = *fCurrPt++; pts[2] = *fCurrPt++; pts[3] = *fCurrPt++; fPrevVerb = kCubic; return kCubic; default: assert(false); // not reached } if (do_return) { return kLine; } } if (fPrevVerb >= kLine && fPrevVerb <= kCubic) { pts[0] = fCurrPt[-1]; pts[1] = *fPrevMove; fPrevVerb = kDone; return kLine; } else { return kDone; } }
25.22561
87
0.435581
jkchang62
905730d5bb507964f80cdf24c2ed765b7ebbdd09
614
cpp
C++
DAY-10/allIndex.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
DAY-10/allIndex.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
null
null
null
DAY-10/allIndex.cpp
Mitushi-23/DSA-60Days
e8bd2766331fb7d99c11ab96fcc803d9c20ccd1e
[ "MIT" ]
1
2021-10-05T10:09:32.000Z
2021-10-05T10:09:32.000Z
#include <bits/stdc++.h> using namespace std; void all(int a[], int n, int x, int i) { if (n == 0) return; if (a[0] == x) { cout << i << " "; } i++; return all(a + 1, n - 1, x, i); } void all1(int a[], int n, int x) { if (n == 0) return; if (a[n - 1] == x) cout << n - 1 << " "; return all1(a, n - 1, x); } int main() { int n; cin >> n; int a[n]; for (int i = 0; i < n; i++) { cin >> a[i]; } int x; cin >> x; int i = 0; all(a, n, x, i); cout << endl; all1(a, n, x); cout << endl; }
14.27907
38
0.369707
Mitushi-23
905aafcc250a9489837ef2f8c9bc61b823efb726
13,683
cpp
C++
src/communication/test/communication_test.cpp
Kurossa/rpi_tcp_listener
68299ba73661a147405e726d8e26a1a68303df39
[ "Unlicense", "MIT" ]
null
null
null
src/communication/test/communication_test.cpp
Kurossa/rpi_tcp_listener
68299ba73661a147405e726d8e26a1a68303df39
[ "Unlicense", "MIT" ]
null
null
null
src/communication/test/communication_test.cpp
Kurossa/rpi_tcp_listener
68299ba73661a147405e726d8e26a1a68303df39
[ "Unlicense", "MIT" ]
null
null
null
#include "gtest/gtest.h" #include "gmock/gmock.h" #include <utilities/zip.h> #include <communication/communication.h> #include <cstring> #include <fstream> #include <sys/time.h> // Mock function that is only available using root privilages int settimeofday (const struct timeval *__tv, const struct timezone *__tz) __THROW { (void)__tv; (void)__tz; return 0; } using namespace comm; namespace { const char compressed_file_name[] = "compressed_123.mp3"; int LinesCount(std::string& s) { return std::count(s.begin(), s.end(), '\n'); } std::string ReadLine(std::string& s, int line_num) { std::istringstream f(s); std::string line; int line_count = 0; while (std::getline(f, line)) { ++line_count; if (line_count == line_num) { return line; } } return ""; } } class CommunicationFixture : public ::testing::Test { public: CommunicationFixture() : logger_m(false, true) , config_manager_m(logger_m) { utils::ZipCompress("123.mp3", compressed_file_name); config_manager_m.ParseConfigFile("audio_app_cfg.xml"); } ~CommunicationFixture() { std::string file_to_remove = "rm /tmp/"; file_to_remove += compressed_file_name; system(file_to_remove.c_str()); } virtual void SetUp() {} virtual void TearDown() {} protected: utils::Logger logger_m; config::ConfigManager config_manager_m; }; // Wrong command structure TEST_F (CommunicationFixture, EmptyCommand) { // Empty Command: // "" comm::Communication communication(config_manager_m, logger_m); char command[1024] = ""; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, WrongCommand) { // Wrong Command: // TCP_STATUS\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, WrongCommandStructure) { // Wrong Command: // TCP_STATUS\n // WWRONG_ATTR\n // END\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\nWWRONG_ATTR\nEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, NoNewLineAtEndOfCommand) { // Wrong Command: // TCP_STATUS\n // END comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\nEND"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } TEST_F (CommunicationFixture, MissingNewLineInCommand) { // Wrong Command: // TCP_STATUS // END\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUSEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(3, lines_count); EXPECT_STREQ("UNKNOWN_COMMAND" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 3).c_str()); } // TCP_STATUS TEST_F (CommunicationFixture, StatusCommand) { // Command: // TCP_STATUS\n // END\n comm::Communication communication(config_manager_m, logger_m); char command[1024] = "TCP_STATUS\nEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_7_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } //TCP_PLAY TEST_F (CommunicationFixture, PlayOncePlayOncePlayWrongFileCommand) { // Command: // TCP_PLAY\n // NR_PLIKU\n // ONCE\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_ONCE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_ONCE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); // Rename file to try open file that no longer exists rename("/tmp/compressed_123.mp3", "/tmp/tmp.mp3"); communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:3" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); rename("/tmp/tmp.mp3", "/tmp/compressed_123.mp3"); } TEST_F (CommunicationFixture, PlayInLoopCommand) { // Command: // TCP_PLAY\n // NR_PLIKU\n // ONCE\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_PLAY\n1\nIN_LOOP\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_IN_LOOP" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } TEST_F (CommunicationFixture, PlayWrongModeCommand) { // Command: // TCP_PLAY\n // NR_PLIKU\n // WRONG_MODE\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_PLAY\n1\nWRONG_MODE\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:2" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } // TCP_STOP TEST_F (CommunicationFixture, StopPlayStopCommand) { // Command: // TCP_STOP\n // END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_STOP\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_2_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); communication.handleCommand("TCP_PLAY\n1\nONCE\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_1_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_PLAY_ONCE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); communication.handleCommand("TCP_STOP\nEND\n", reply); reply_str = std::string(reply); lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_2_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } //TCP_SET_TIME TEST_F (CommunicationFixture, SetTimeCommand) { // Command: //TCP_SET_TIME\n //GG:MM:SS_DD.MM.RRRR\n //END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_SET_TIME\n12:12:12_01.01.1971\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(4, lines_count); EXPECT_STREQ("COMMAND_0_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 4).c_str()); } // TCP_SET_CFG TEST_F (CommunicationFixture, SetCfgCommand) { // Command: // TCP_SET_CFG\n // length_in_bytes\n // charactes_of_configuration\n // END\n std::string config = "<?xml version=\"1.0\"?>\n" "<audio_app_cfg>\n" "\t<network>\n" "\t\t<ip>127.0.0.1</ip>\n" "\t\t<mask>255.255.255.0</mask>\n" "\t\t<gateway>192.168.0.1</gateway>\n" "\t\t<port>9999</port>\n" "\t</network>\n" "\t<sounds>\n" "\t\t<sound>file1</sound>\n" "\t\t<sound>file2</sound>\n" "\t\t<sound>file3</sound>\n" "\t\t<sound>file4</sound>\n" "\t</sounds>\n" "</audio_app_cfg>\n"; std::string msg_cmd = "TCP_SET_CFG\n"; std::ostringstream oss; oss << config.length() << std::endl; msg_cmd += oss.str(); msg_cmd += config; msg_cmd += "END\n"; comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand(msg_cmd.c_str(), reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(4, lines_count); EXPECT_STREQ("COMMAND_3_RECEIVED" ,ReadLine(reply_str, 1).c_str()); // Error code was not tested as on real system file can exists ath this will succes on others will fail writtung EXPECT_STREQ("END" ,ReadLine(reply_str, 4).c_str()); } // TCP_GET_CFG TEST_F (CommunicationFixture, GetCfgCommand) { // Command: //TCP_GET_CFG\n //END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_GET_CFG\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(6, lines_count); EXPECT_STREQ("COMMAND_4_RECEIVED" ,ReadLine(reply_str, 1).c_str()); // Do not test following lines as it vary depending on sytem it runs tests // 2nd line: Time // 3rd line: size // 4th line: config content EXPECT_STREQ("END" ,ReadLine(reply_str, 6).c_str()); } // TCP_SET_VOLUME TEST_F (CommunicationFixture, SetVolumeCommand) { // Command: //TCP_SET_VOLUME\n //20\n //END\n comm::Communication communication(config_manager_m, logger_m); char reply[1024] = {0}; communication.handleCommand("TCP_SET_VOLUME\n20\nEND\n", reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(5, lines_count); EXPECT_STREQ("COMMAND_5_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("AUDIO_IDLE" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 4).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 5).c_str()); } // TCP_RESET TEST_F (CommunicationFixture, RebootCallback) { // Command: // TCP_RESET\n // END\n bool reboot_called = false; comm::Communication communication(config_manager_m, logger_m, [&reboot_called]() { reboot_called = true; }); char command[1024] = "TCP_RESET\nEND\n"; char reply[1024] = {0}; communication.handleCommand(command, reply); std::string reply_str(reply); int lines_count = LinesCount(reply_str); EXPECT_EQ(4, lines_count); EXPECT_STREQ("COMMAND_6_RECEIVED" ,ReadLine(reply_str, 1).c_str()); EXPECT_STREQ("ERROR_CODE:0" ,ReadLine(reply_str, 3).c_str()); EXPECT_STREQ("END" ,ReadLine(reply_str, 4).c_str()); EXPECT_TRUE(reboot_called); }
32.044496
116
0.66652
Kurossa
905d187b46cf46d791d0e4c0eb5f5f6e7b1b3dca
7,092
cpp
C++
src/QPMatrix.cpp
Isaac-Kwon/c-qupid
5e298517d645a433c6fd8b0a17ac3ad5d332f357
[ "BSD-3-Clause" ]
null
null
null
src/QPMatrix.cpp
Isaac-Kwon/c-qupid
5e298517d645a433c6fd8b0a17ac3ad5d332f357
[ "BSD-3-Clause" ]
1
2021-04-12T07:24:39.000Z
2021-04-12T07:25:01.000Z
src/QPMatrix.cpp
Isaac-Kwon/qupid
5e298517d645a433c6fd8b0a17ac3ad5d332f357
[ "BSD-3-Clause" ]
null
null
null
#include "iostream" #include "stdlib.h" #include "stdarg.h" #include "sstream" #include "QPMatrix.hpp" QPMatrix::QPMatrix(): fElement(0), fM(0), fN(0){ // Init(); } QPMatrix::QPMatrix(const int n): fElement(0), fM(n), fN(n){ Init(); } QPMatrix::QPMatrix(const int m, const int n): fElement(0), fM(m), fN(n){ Init(); } QPMatrix::QPMatrix(const int m, const int n, const int npassed, ...): fElement(0), fM(m), fN(n){ Init(); va_list vl; va_start( vl, npassed ); for(int i=0; i<m*n && i<npassed; i++){ fElement[i] = va_arg(vl, double); } va_end(vl); } QPMatrix::QPMatrix(QPVector& vec, int ncomp): fElement(0), fM(ncomp), fN(1){ Init(); for(int i=0; i<ncomp && i<3; i++){ fElement[i] = vec(i); } } QPMatrix::QPMatrix(const QPMatrix& other): fElement(0), fM(other.fM), fN(other.fN){ Init(); int fMN = fM*fN; for(int i=0; i<fMN; i++){ fElement[i] = other.fElement[i]; } } QPMatrix& QPMatrix::operator=(const QPMatrix& other){ Freeing(); fM = other.fM; fN = other.fN; Init(); for(int i=0; i<fM*fN; i++){ fElement[i] = other.fElement[i]; // std::cout<<"COPIED\t"<<fElement[i]<<"\t"<<At(i)<<std::endl; } return *this; } QPMatrix::~QPMatrix(){ Freeing(); } void QPMatrix::Init(){ fElement = (double*) std::malloc(fM*fN*sizeof(double)); for(int i=0; i<fN*fM; i++){ fElement[i] = 0.; } } void QPMatrix::Freeing(){ // if(fElement == nullptr){ // return; // } std::free(fElement); } bool QPMatrix::IsInside(int i){ if(i >= 0 && i< fN*fM) return true; return false; } bool QPMatrix::IsInside(int i, int j){ if (i>=0 && i<fM && j>=0 && j<fN){ return true; } return false; } double QPMatrix::At(int i){ if( !IsInside(i) ){ std::cout<<"QPMatrix::At(1) - Out if index"<<"["<<i<<"]"<<std::endl; return -1; } return fElement[i]; } double QPMatrix::At(int i, int j){ if( !IsInside(i,j) ){ std::cout<<"QPMatrix::At(2) - Out if index "<<"["<<i<<","<<j<<"]"<<std::endl; return -1; } return fElement[i*fN+j]; } bool QPMatrix::IsSameShape(QPMatrix & other){ if(fN == other.fN && fM == other.fM) return true; return false; } bool QPMatrix::IsTransShape(QPMatrix & other){ if(fN == other.fM && fM == other.fN) return true; return false; } double& QPMatrix::operator[](int i){ if( !IsInside(i) ){ std::cout<<"QPMatrix::operator[](1) - Out if index"<<"["<<i<<"]"<<std::endl; return nval; } return fElement[i]; } double& QPMatrix::operator()(int i){ if( !IsInside(i) ){ std::cout<<"QPMatrix::operator()(1) - Out if index"<<"["<<i<<"]"<<std::endl; return nval; } return fElement[i]; } double& QPMatrix::operator()(int i, int j){ if( !IsInside(i, j) ){ std::cout<<"QPMatrix::operator()(2) - Out if index"<<"["<<i<<"]"<<std::endl; return nval; } return fElement[i*fM+j]; } double QPMatrix::Det(){ if(fM != fN){ std::cout<<"QPMatrix::Det() - Determinant can be defined only for square matrix "<<"["<<fM<<","<<fN<<"]"<<std::endl; return 0.; } if(fM==0) return 0.; if(fM==1) return At(0); if(fM==2){ return At(0,0)*At(1,1) - At(0,1)*At(1,0); } double ans = 0; for(int i=0; i<fN; i++){ ans += pow(-1, i)*At(0,i)*SubMatrix(0, i).Det(); } return ans; } double QPMatrix::Trace(){ double ans = 0; int ii = fN>fM ? fM : fN; for(int i=0; i<ii; i++){ ans += operator()(i,i); } return ans; } QPMatrix QPMatrix::SubMatrix(const int i_, const int j_){ QPMatrix ans = QPMatrix(fM-1, fN-1); for(int i=0; i<fM-1; i++){ for(int j=0; j<fN-1; j++){ ans(i,j) = At( i < i_ ? i : i+1, j < j_ ? j : j+1 ); } } return ans; } double QPMatrix::Cofactor(const int i, const int j){ if(fM != fN){ std::cout<<"QPMatrix::Cofactor() - Cofactor can be defined only for square matrix "<<"["<<fM<<","<<fN<<"]"<<std::endl; return 0; } return pow(-1, i+j) * (SubMatrix(i,j).Det()); } QPMatrix QPMatrix::Inverse(){ if(fM != fN){ std::cout<<"QPMatrix::Inverse() - Inverse can be defined only for square matrix "<<"["<<fM<<","<<fN<<"]"<<std::endl; return QPMatrix(); } double det = Det(); if(det<0.0000000001 && det>-0.0000000001 ){ std::cout<<"QPMatrix::Inverse() - Determinant is near zero. No inverse matrix "<<"["<<det<<"]"<<std::endl; return QPMatrix(); } QPMatrix ans = QPMatrix(fM, fN); for(int i=0; i<fM; i++){ for(int j=0; j<fN; j++){ ans(i,j) = Cofactor(j,i); } } ans*=(1/Det()); return ans; } QPMatrix QPMatrix::Transpose(){ QPMatrix ans(fN, fM); for(int i=0; i<fM; i++){ for(int j=0; j<fN; j++){ ans(j,i) = At(i,j); } } return ans; } QPMatrix operator*(QPMatrix self, double other){ QPMatrix ans = QPMatrix(self); for(int i=0; i<(self.fN*self.fM); i++){ ans(i) *= other; } return ans; } QPMatrix operator*(double other, QPMatrix self){ QPMatrix ans = QPMatrix(self); for(int i=0; i<(self.fN*self.fM); i++){ ans(i) *= other; } return ans; } QPMatrix operator*(QPMatrix self, QPMatrix other){ if(self.fN != other.fM){ std::cout<<"QPMatrix::operator*()(3) - inner part of 2 matrices are not same : "<<self.fN<<", "<<other.fM<<std::endl; return QPMatrix(); } QPMatrix ans = QPMatrix(self.fM, other.fN); for(int i=0; i<(ans.fM); i++){ for(int j=0; j<(ans.fN); j++){ for(int k=0; k<(self.fN); k++){ ans(i,j)+= self.At(i,k) * other.At(k,j); } } } return ans; } QPMatrix operator+(QPMatrix & self, QPMatrix & other){ if(! self.IsSameShape(other) ){ std::cout<<"operator+ (QPMatrix&, QPMatrix&) - Not same shape"<<std::endl; return QPMatrix(); } QPMatrix ans = QPMatrix(self.fM, self.fN); int length = self.fN * self.fM; for(int i=0; i<length; i++){ ans[i] = self[i] + other[i]; } return ans; } QPMatrix operator-(QPMatrix & self, QPMatrix & other){ if(! self.IsSameShape(other) ){ std::cout<<"operator- (QPMatrix&, QPMatrix&) - Not same shape"<<std::endl; return QPMatrix(); } QPMatrix ans(self.fM, self.fN); int length = self.fN * self.fM; for(int i=0; i<length; i++){ ans[i] = self[i] - other[i]; } return ans; } std::string QPMatrix::Print(bool quite){ std::ostringstream anss; anss.precision(4); for(int i=0; i<fM; i++){ for(int j=0; j<fN; j++){ anss << At(i,j) << "\t"; } anss<<std::endl; } anss.unsetf(std::ios::fixed); std::string ans = anss.str(); if(!quite){ std::cout<<ans; } return ans; }
21.754601
126
0.516356
Isaac-Kwon
905d8c3c349e1684c79a64080eeff8a41ca4e8a2
6,485
cpp
C++
ReactSkia/textlayoutmanager/RSkTextLayoutManager.cpp
react-native-skia/react-native-skia
44f160ef2bc38e8b60609500e4834212e2728e95
[ "MIT" ]
643
2021-08-02T05:04:20.000Z
2022-03-27T22:56:02.000Z
ReactSkia/textlayoutmanager/RSkTextLayoutManager.cpp
react-native-skia/react-native-skia
44f160ef2bc38e8b60609500e4834212e2728e95
[ "MIT" ]
13
2021-09-01T12:41:42.000Z
2022-03-28T11:08:44.000Z
ReactSkia/textlayoutmanager/RSkTextLayoutManager.cpp
react-native-skia/react-native-skia
44f160ef2bc38e8b60609500e4834212e2728e95
[ "MIT" ]
16
2021-08-31T07:08:45.000Z
2022-02-14T12:36:15.000Z
/* * Copyright (C) 1994-2021 OpenTV, Inc. and Nagravision S.A. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ #include "RSkTextLayoutManager.h" using namespace skia::textlayout; namespace facebook { namespace react { Point calculateFramePoint( Point origin , Size rect , float layoutWidth) { /* Calculate the (x,y) cordinates of fragment attachments,based on the fragment width provided*/ if(origin.x + rect.width < layoutWidth) origin.x += rect.width ; else { auto delta = layoutWidth - origin.x ; origin.x = rect.width - delta ; origin.y += rect.height; } return origin; } TextAlign convertTextAlign (TextAlignment alignment) { switch(alignment) { case TextAlignment::Natural : case TextAlignment::Left : return TextAlign::kLeft; case TextAlignment::Center : return TextAlign::kCenter; case TextAlignment::Right : return TextAlign::kRight; case TextAlignment::Justified : return TextAlign::kJustify; } return TextAlign::kLeft; } SkPaint convertTextColor ( SharedColor textColor ) { SkPaint paint; float ratio = 255.9999; auto color = colorComponentsFromColor(textColor); paint.setColor(SkColorSetARGB( color.alpha * ratio, color.red * ratio, color.green * ratio, color.blue * ratio)); paint.setAntiAlias(true); return paint; } RSkTextLayoutManager::RSkTextLayoutManager() { /* Set default font collection */ collection_ = sk_make_sp<FontCollection>(); collection_->setDefaultFontManager(SkFontMgr::RefDefault()); } TextMeasurement RSkTextLayoutManager::doMeasure (AttributedString attributedString, ParagraphAttributes paragraphAttributes, LayoutConstraints layoutConstraints) const { TextMeasurement::Attachments attachments; ParagraphStyle paraStyle; Size size; std::shared_ptr<ParagraphBuilder> builder = std::static_pointer_cast<ParagraphBuilder>(std::make_shared<ParagraphBuilderImpl>(paraStyle,collection_)); buildParagraph(attributedString, paragraphAttributes, false, builder); auto paragraph = builder->Build(); paragraph->layout(layoutConstraints.maximumSize.width); size.width = paragraph->getMaxIntrinsicWidth() < paragraph->getMaxWidth() ? paragraph->getMaxIntrinsicWidth() : paragraph->getMaxWidth(); size.height = paragraph->getHeight(); Point attachmentPoint = calculateFramePoint({0,0}, size, layoutConstraints.maximumSize.width); for (auto const &fragment : attributedString.getFragments()) { if (fragment.isAttachment()) { Rect rect; rect.size.width = fragment.parentShadowView.layoutMetrics.frame.size.width; rect.size.height = fragment.parentShadowView.layoutMetrics.frame.size.height; /* TODO : We will be unable to calculate exact (x,y) cordinates for the attachments*/ /* Reason : attachment fragment width is clamped width wrt layout width; */ /* so we do not know actual position at which the previous attachment cordinate ends*/ /* But we need to still calculate total container height here, from all attachments */ /* NOTE : height value calculated would be approximate,since we lack the knowledge of actual frag width here*/ attachmentPoint = calculateFramePoint(attachmentPoint, rect.size, layoutConstraints.maximumSize.width); attachments.push_back(TextMeasurement::Attachment{rect, false}); } } /* Update the container height from all attachments */ if(!attachments.empty()) { size.height = attachmentPoint.y + attachments[attachments.size()-1].frame.size.height; } return TextMeasurement{size, attachments}; } uint32_t RSkTextLayoutManager::buildParagraph (AttributedString attributedString, ParagraphAttributes paragraphAttributes, bool fontDecorationRequired, std::shared_ptr<ParagraphBuilder> builder) const { uint32_t attachmentCount = 0; std::unique_ptr<Paragraph> fPara; TextStyle style; ParagraphStyle paraStyle; auto fontSize = TextAttributes::defaultTextAttributes().fontSize; auto fontSizeMultiplier = TextAttributes::defaultTextAttributes().fontSizeMultiplier; for(auto &fragment: attributedString.getFragments()) { if(fragment.isAttachment()) { attachmentCount++; continue; } fontSize = !std::isnan(fragment.textAttributes.fontSize) ? fragment.textAttributes.fontSize : TextAttributes::defaultTextAttributes().fontSize; fontSizeMultiplier = !std::isnan(fragment.textAttributes.fontSizeMultiplier) ? fragment.textAttributes.fontSizeMultiplier : TextAttributes::defaultTextAttributes().fontSizeMultiplier; style.setFontSize(fontSize * fontSizeMultiplier); style.setFontFamilies({SkString(fragment.textAttributes.fontFamily.c_str())}); /* Build paragraph considering text decoration attributes*/ /* Required during text paint */ if(fontDecorationRequired) { style.setForegroundColor(convertTextColor(fragment.textAttributes.foregroundColor ? fragment.textAttributes.foregroundColor : TextAttributes::defaultTextAttributes().foregroundColor)); style.setBackgroundColor(convertTextColor(fragment.textAttributes.backgroundColor ? fragment.textAttributes.backgroundColor : TextAttributes::defaultTextAttributes().backgroundColor)); } if(fragment.textAttributes.alignment.has_value()) paraStyle.setTextAlign(convertTextAlign(fragment.textAttributes.alignment.value())); builder->setParagraphStyle(paraStyle); builder->pushStyle(style); builder->addText(fragment.string.c_str(),fragment.string.length()); } return attachmentCount; } } // namespace react } // namespace facebook
42.94702
227
0.658751
react-native-skia
9061d5688be35392bb652f23bd14aedb69460002
3,943
cpp
C++
demo_app/julia.cpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
12
2021-07-24T18:33:22.000Z
2022-03-12T16:20:49.000Z
demo_app/julia.cpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
null
null
null
demo_app/julia.cpp
nvpro-samples/vk_compute_mipmaps
613b94e4d36e6f357472e9c7a3163046deb55678
[ "Apache-2.0" ]
3
2021-08-04T02:27:12.000Z
2022-03-13T08:43:24.000Z
// Copyright 2021 NVIDIA CORPORATION // SPDX-License-Identifier: Apache-2.0 // Implementation functions for Julia Set compute shader. #include "julia.hpp" #include "nvh/container_utils.hpp" #include "make_compute_pipeline.hpp" // GLSL polyglot #include "shaders/julia.h" Julia::Julia(VkDevice device, VkPhysicalDevice physicalDevice, bool dumpPipelineStats, uint32_t textureWidth, uint32_t textureHeight) : m_device(device) , m_scopedImage(device, physicalDevice) { // Push constant defaults update(0.0, 64); // Set up color texture. m_scopedImage.reallocImage(textureWidth, textureHeight); // Set up compute pipeline. uint32_t pcSize = uint32_t(sizeof(JuliaPushConstant)); VkPushConstantRange range = {VK_SHADER_STAGE_COMPUTE_BIT, 0, pcSize}; VkDescriptorSetLayout descriptorLayout = m_scopedImage.getStorageDescriptorSetLayout(); makeComputePipeline(m_device, "julia.comp.spv", dumpPipelineStats, 1, &descriptorLayout, 1, &range, &m_pipeline, &m_pipelineLayout); } Julia::~Julia() { // Destroy pipelines. vkDestroyPipelineLayout(m_device, m_pipelineLayout, nullptr); vkDestroyPipeline(m_device, m_pipeline, nullptr); } void Julia::resize(uint32_t x, uint32_t y) { m_scopedImage.reallocImage(x, y); update(0.0, 0); } uint32_t Julia::getWidth() const { return m_scopedImage.getImageWidth(); } uint32_t Julia::getHeight() const { return m_scopedImage.getImageHeight(); } void Julia::update(double dt, int maxIterations) { m_alphaNormalized += uint32_t(dt * 0x0600'0000); double alphaRadians = m_alphaNormalized * 1.4629180792671596e-09; m_pushConstant.c_real = float(0.7885 * sin(alphaRadians)); m_pushConstant.c_imag = float(0.7885 * cos(alphaRadians)); float textureWidth = float(m_scopedImage.getImageWidth()); float textureHeight = float(m_scopedImage.getImageHeight()); m_pushConstant.offset_real = -2.0f; m_pushConstant.scale = 4.0f / textureWidth; m_pushConstant.offset_imag = 2.0f * textureHeight / textureWidth; if (maxIterations > 0) m_pushConstant.maxIterations = int32_t(maxIterations); } void Julia::cmdFillColorTexture(VkCommandBuffer cmdBuf) { // Transition color texture image to general layout, protect // earlier reads. VkImageMemoryBarrier imageBarrier = { VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER, nullptr, VK_ACCESS_MEMORY_READ_BIT, VK_ACCESS_MEMORY_WRITE_BIT, VK_IMAGE_LAYOUT_UNDEFINED, VK_IMAGE_LAYOUT_GENERAL, 0, 0, m_scopedImage.getImage(), {VK_IMAGE_ASPECT_COLOR_BIT, 0, VK_REMAINING_MIP_LEVELS, 0, 1} }; vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &imageBarrier); // Bind pipeline, push constant, and descriptors. vkCmdBindPipeline(cmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, m_pipeline); VkDescriptorSet descriptorSet = m_scopedImage.getStorageDescriptorSet(); vkCmdPushConstants(cmdBuf, m_pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(m_pushConstant), &m_pushConstant); vkCmdBindDescriptorSets(cmdBuf, VK_PIPELINE_BIND_POINT_COMPUTE, m_pipelineLayout, 0, 1, &descriptorSet, 0, nullptr); // Fill the image. vkCmdDispatch(cmdBuf, (m_scopedImage.getImageWidth() + 15) / 16, (m_scopedImage.getImageHeight() + 15) / 16, 1); // Pipeline barrier. VkMemoryBarrier barrier = { VK_STRUCTURE_TYPE_MEMORY_BARRIER, nullptr, VK_ACCESS_MEMORY_WRITE_BIT, VK_ACCESS_MEMORY_READ_BIT }; vkCmdPipelineBarrier(cmdBuf, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 1, &barrier, 0, nullptr, 0, nullptr); }
35.522523
75
0.70454
nvpro-samples
9064c34ea8bc0c4ea87d9425f1f54f02ef7ef46b
9,953
cpp
C++
DemoApps/GLES2/Blur/source/TwoPassLinearScaledBlurredDraw.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
3
2019-01-19T20:21:24.000Z
2021-08-10T02:11:32.000Z
DemoApps/GLES2/Blur/source/TwoPassLinearScaledBlurredDraw.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
null
null
null
DemoApps/GLES2/Blur/source/TwoPassLinearScaledBlurredDraw.cpp
alejandrolozano2/OpenGL_DemoFramework
5fd85f05c98cc3d0c0a68bac438035df8cabaee7
[ "MIT", "BSD-3-Clause" ]
1
2021-08-10T02:11:33.000Z
2021-08-10T02:11:33.000Z
/**************************************************************************************************************************************************** * Copyright (c) 2015 Freescale Semiconductor, 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: * * * 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 Freescale Semiconductor, Inc. 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. * ****************************************************************************************************************************************************/ #include <FslBase/Exceptions.hpp> #include <FslBase/Log/Log.hpp> #include <FslDemoApp/Base/Service/Content/IContentManager.hpp> #include <FslDemoApp/Base/Service/Graphics/IGraphicsService.hpp> #include <FslGraphics/Bitmap/Bitmap.hpp> #include <FslGraphics/Vertices/VertexPositionTexture.hpp> #include "GausianHelper.hpp" #include "VBHelper.hpp" #include "TwoPassLinearScaledBlurredDraw.hpp" #include <FslGraphics/Exceptions.hpp> #include <algorithm> #include <cassert> #include <iostream> namespace Fsl { using namespace GLES2; int UpdateScaledKernelLength(const int32_t kernelLength) { int32_t moddedKernelLength = std::max(kernelLength, 5); int32_t newKernelLength = ((moddedKernelLength / 4) * 4) + 1; return (newKernelLength < moddedKernelLength ? newKernelLength + 4 : newKernelLength); } int UpdateKernelLength(const int32_t kernelLength) { int32_t moddedKernelLength = UpdateScaledKernelLength(kernelLength / 2); moddedKernelLength = (moddedKernelLength * 2) + 1; return moddedKernelLength; } //! Uses the two pass linear technique and further reduces the bandwidth requirement by //! downscaling the 'source image' to 1/4 its size (1/2w x 1/2h) before applying the blur and //! and then upscaling the blurred image to provide the final image. //! This works well for large kernel sizes and relatively high sigma's but the downscaling //! produces visible artifacts with low sigma's TwoPassLinearScaledBlurredDraw::TwoPassLinearScaledBlurredDraw(const DemoAppConfig& config, const Config& blurConfig) : ABlurredDraw("Two pass linear scaled") , m_batch2D(std::dynamic_pointer_cast<NativeBatch2D>(config.DemoServiceProvider.Get<IGraphicsService>()->GetNativeBatch2D())) , m_screenResolution(config.ScreenResolution) , m_framebufferOrg(Point2(m_screenResolution.X, m_screenResolution.Y), GLTextureParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), GL_RGB565, GL_DEPTH_COMPONENT16) , m_framebufferBlur1() , m_framebufferBlur2() , m_shaders() { if (!m_batch2D) throw std::runtime_error("NativeBatch2D unavailable"); // Ensure that the kernel size is correct int moddedKernelLength = UpdateKernelLength(blurConfig.KernelLength); FSLLOG_WARNING_IF(moddedKernelLength != blurConfig.KernelLength, "The two pass linear scaled shader is not compatible with the supplied kernel length of " << blurConfig.KernelLength << " using " << moddedKernelLength); // Simplistic scaling of the kernel so it handles the down-sampling of the image correctly moddedKernelLength = UpdateScaledKernelLength(moddedKernelLength / 2); float moddedSigma = blurConfig.Sigma / 2.0f; FSLLOG("Scaled actual kernel length: " << moddedKernelLength << " which becomes a " << ((moddedKernelLength / 2)+1) << " linear kernel" ); // The downscaled framebuffer needs to contain 'half of the kernel width' extra pixels on the left to ensure that we can use // them for the blur calc of the first pixel we are interested in const int quadWidth = m_screenResolution.X / 4; int blurFBWidth = quadWidth + (moddedKernelLength / 2); blurFBWidth += ((blurFBWidth % 16) != 0 ? (16 - (blurFBWidth % 16)) : 0); int addedPixels = blurFBWidth - quadWidth; m_framebufferBlur1.Reset(Point2(blurFBWidth, m_screenResolution.Y / 2), GLTextureParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), GL_RGB565); m_framebufferBlur2.Reset(Point2(blurFBWidth, m_screenResolution.Y / 2), GLTextureParameters(GL_LINEAR, GL_LINEAR, GL_CLAMP_TO_EDGE, GL_CLAMP_TO_EDGE), GL_RGB565); // Prepare the shaders const std::shared_ptr<IContentManager> contentManager = config.DemoServiceProvider.Get<IContentManager>(); moddedSigma = blurConfig.UseOptimalSigma ? -1.0f : moddedSigma; m_shaders.Reset(contentManager, moddedKernelLength, moddedSigma, m_framebufferBlur1.GetSize(), m_framebufferBlur2.GetSize(), TwoPassShaders::Linear, blurConfig.TheShaderType); const float xOrg = ((m_framebufferOrg.GetSize().X - ((m_framebufferOrg.GetSize().X / 2) + addedPixels * 2)) / float(m_framebufferOrg.GetSize().X)); const float xFinal = addedPixels / float(m_framebufferBlur2.GetSize().X); VBHelper::BuildVB(m_vertexBufferLeft, BoxF(-1, -1, 0, 1), BoxF(0.0f, 0.0f, 0.5f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRightX, BoxF(-1, -1, 1, 1), BoxF(xOrg, 0.0f, 1.0f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRightX2, BoxF(-1, -1, 1, 1), BoxF(0.0f, 0.0f, 1.0f, 1.0f)); VBHelper::BuildVB(m_vertexBufferRightY, BoxF(0, -1, 1, 1), BoxF(xFinal, 0.0f, 1.0f, 1.0f)); } void TwoPassLinearScaledBlurredDraw::Draw(AScene*const pScene) { assert(pScene != nullptr); // Render the 'source' image that we want to partially blur glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferOrg.Get()); { glViewport(0, 0, m_framebufferOrg.GetSize().X, m_framebufferOrg.GetSize().Y); pScene->Draw(); } // Since we are only doing opaque 2d-composition type operations we can disable blend and depth testing glDisable(GL_BLEND); glDisable(GL_DEPTH_TEST); // Downscale the right side of the image to 1/4 of its size (1/2w x 1/2h) glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferBlur1.Get()); { glViewport(0, 0, m_framebufferBlur1.GetSize().X, m_framebufferBlur1.GetSize().Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferOrg.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramNormal.Get()); glBindBuffer(m_vertexBufferRightX.GetTarget(), m_vertexBufferRightX.Get()); m_vertexBufferRightX.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Blur the scaled image in X glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferBlur2.Get()); { glViewport(0, 0, m_framebufferBlur2.GetSize().X, m_framebufferBlur2.GetSize().Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferBlur1.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramBlurX.Get()); glBindBuffer(m_vertexBufferRightX2.GetTarget(), m_vertexBufferRightX2.Get()); m_vertexBufferRightX2.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Blur the scaled image in Y glBindFramebuffer(GL_FRAMEBUFFER, m_framebufferBlur1.Get()); { glViewport(0, 0, m_framebufferBlur1.GetSize().X, m_framebufferBlur1.GetSize().Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferBlur2.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramBlurY.Get()); glBindBuffer(m_vertexBufferRightX2.GetTarget(), m_vertexBufferRightX2.Get()); m_vertexBufferRightX2.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } // Since we are only doing opaque non-overlapping 2d-composition type operations we can disable blend and depth testing glBindFramebuffer(GL_FRAMEBUFFER, 0); { glViewport(0, 0, m_screenResolution.X, m_screenResolution.Y); glClear(GL_COLOR_BUFFER_BIT); glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferOrg.GetTextureInfo().Handle); // Draw the left side using the normal shader glUseProgram(m_shaders.ProgramNormal.Get()); glBindBuffer(m_vertexBufferLeft.GetTarget(), m_vertexBufferLeft.Get()); m_vertexBufferLeft.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); // Draw the right side using a normal shader, scaling the blurred image back to normal size glActiveTexture(GL_TEXTURE0); glBindTexture(GL_TEXTURE_2D, m_framebufferBlur1.GetTextureInfo().Handle); glUseProgram(m_shaders.ProgramNormal.Get()); glBindBuffer(m_vertexBufferRightY.GetTarget(), m_vertexBufferRightY.Get()); m_vertexBufferRightY.EnableAttribArrays(); glDrawArrays(GL_TRIANGLE_STRIP, 0, 4); } } }
48.55122
222
0.721491
alejandrolozano2