hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
5ab5452484bd28924f5702f898a4fabeb8873687
1,590
cpp
C++
graph-source-code/350-E/4644199.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/4644199.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/350-E/4644199.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <stdio.h> #include <iostream> #include <string.h> #include <stdlib.h> #include <time.h> #define abs(a) (((a)>0)?(a):(-(a))) #define max(a, b) (((a)>(b))?(a):(b)) #define min(a, b) (((a)<(b))?(a):(b)) #define N 303 #define oo int(1e9) #define eps 1e-8 using namespace std; bool g[N][N], cl[N]; int main() { // freopen("input.txt", "r", stdin); int n, m, k, i, j, c, u, v, v1, v2; cin >> n >> m >> k; for(i=0; i<N; ++i) cl[i] = 0; for(i=0; i<N; ++i) for(j=0; j<N; ++j) g[i][j] = 0; v1 = v2 = -1; for(i=0; i<k; ++i) { cin >> c; cl[--c] = 1; if(v1 == -1) v1 = c; else if(v2 == -1) v2 = c; } v = 0; while(v<n && cl[v]) ++v; if(v == n) { cout << -1 << endl; return 0; } g[v][v2] = g[v2][v] = 1; --m; for(i=0; i<n; ++i) { if((i == v1) || (i == v2)) continue; g[v1][i] = g[i][v1] = 1; --m; } if(m<0) { cout << -1 << endl; return 0; } for(i=0; (i<n) && m; ++i) for(j=i+1; (j<n) && m; ++j) { if(cl[i] && cl[j] && ( (v2 == i) || (v2 == j))) continue; if(g[i][j]) continue; g[i][j] = 1; --m; } if(m) { cout << -1 << endl; return 0; } for(i=0; i<n; ++i) for(j=i+1; j<n; ++j) if(g[i][j]) cout << i+1 << " " << j+1 << endl; return 0; }
15.588235
59
0.330189
AmrARaouf
5ab7c41752f47e96c7046a5f0bef21e0a5476634
3,475
cpp
C++
source/AnimationPlayer.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
2
2018-01-11T13:00:14.000Z
2018-01-12T02:02:16.000Z
source/AnimationPlayer.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
null
null
null
source/AnimationPlayer.cpp
sindney/nest3d-cpp
033575364c14a48499ddbb0cbf489b7e72b0d9b7
[ "MIT" ]
null
null
null
#include <iterator> #include "AnimationPlayer.h" namespace nest { using namespace std; void AnimationPlayer::advanceTime(float dt) { time += dt; int i, j = poses.size(); PoseData *pose = NULL; AnimationChannel *channel = NULL; vector<QuatKeyFrame>::iterator k; QuatKeyFrame *quatFirst = NULL, *quatSecond = NULL; vector<Vec3KeyFrame>::iterator l; Vec3KeyFrame *vec3First = NULL, *vec3Second = NULL; Quaternion q0, q1; Vector4 v0, v1; float current = 0.0f, ratio = 0.0f, size = 0.0f; current = time * clip->ticksPerSecond * speed; size = clip->duration; if(clip->loop || current <= size) { // calculate the right time. while(current > size) current -= size; // trigger events AnimationEvent event(current); dispatch(&event); // traverse the clip. for(i = 0; i < j; i++) { pose = &poses[i]; channel = clip->channels[i]; // position keyframes if(channel->positionKeys.size() == 1) { vec3First = &channel->positionKeys[channel->positionKeys.size() - 1]; pose->position.x = vec3First->x; pose->position.y = vec3First->y; pose->position.z = vec3First->z; } else { l = channel->positionKeys.begin(); while(true) { if(l == channel->positionKeys.end()) break; vec3First = &*l++; vec3Second = &*l; if(vec3First-> t <= current && vec3Second->t >= current) { ratio = (current - vec3First->t) / (vec3Second->t - vec3First->t); v0.x = vec3First->x; v0.y = vec3First->y; v0.z = vec3First->z; v1.x = vec3Second->x; v1.y = vec3Second->y; v1.z = vec3Second->z; v0 = v0 + (v1 - v0) * ratio; pose->position = v0; break; } } } // rotation keyframes if(channel->rotationKeys.size() == 1) { quatFirst = &channel->rotationKeys[channel->rotationKeys.size() - 1]; pose->rotation.x = quatFirst->x; pose->rotation.y = quatFirst->y; pose->rotation.z = quatFirst->z; pose->rotation.w = quatFirst->w; } else { k = channel->rotationKeys.begin(); while(true) { if(k == channel->rotationKeys.end()) break; quatFirst = &*k++; quatSecond = &*k; if(quatFirst->t <= current && quatSecond->t >= current) { ratio = (current - quatFirst->t) / (quatSecond->t - quatFirst->t); q0.x = quatFirst->x; q0.y = quatFirst->y; q0.z = quatFirst->z; q0.w = quatFirst->w; q1.x = quatSecond->x; q1.y = quatSecond->y; q1.z = quatSecond->z; q1.w = quatSecond->w; pose->rotation = Quaternion::slerp(q0, q1, ratio); break; } } } // scaling keyframes if(channel->scalingKeys.size() == 1) { vec3First = &channel->scalingKeys[channel->scalingKeys.size() - 1]; pose->scaling.x = vec3First->x; pose->scaling.y = vec3First->y; pose->scaling.z = vec3First->z; } else { l = channel->scalingKeys.begin(); while(true) { if(l == channel->scalingKeys.end()) break; vec3First = &*l++; vec3Second = &*l; if(vec3First-> t <= current && vec3Second->t >= current) { ratio = (current - vec3First->t) / (vec3Second->t - vec3First->t); v0.x = vec3First->x; v0.y = vec3First->y; v0.z = vec3First->z; v1.x = vec3Second->x; v1.y = vec3Second->y; v1.z = vec3Second->z; v0 = v0 + (v1 - v0) * ratio; pose->scaling = v0; break; } } } } } } }
27.579365
94
0.565755
sindney
5ac1a14ceb5b36616b777529e204a4532891459e
13,823
cpp
C++
src/graphics/bloomFFT.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2019-12-24T04:00:36.000Z
2022-01-26T02:44:04.000Z
src/graphics/bloomFFT.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
null
null
null
src/graphics/bloomFFT.cpp
liuhongyi0101/SaturnRender
c6ec7ee39ef14749b09be4ae47f76613c71533cf
[ "MIT" ]
2
2020-09-26T04:19:40.000Z
2021-02-19T07:24:57.000Z
#include "graphics/bloomFFT.h" #include "utils/loadshader.h" BloomFFT::BloomFFT(vks::VulkanDevice * vulkanDevice) { this->vulkanDevice = vulkanDevice; this->device = vulkanDevice->logicalDevice; } BloomFFT::~BloomFFT() { } // Find and create a compute capable device queue void BloomFFT::getComputeQueue() { uint32_t queueFamilyCount; vkGetPhysicalDeviceQueueFamilyProperties(vulkanDevice->physicalDevice, &queueFamilyCount, NULL); assert(queueFamilyCount >= 1); std::vector<VkQueueFamilyProperties> queueFamilyProperties; queueFamilyProperties.resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(vulkanDevice->physicalDevice, &queueFamilyCount, queueFamilyProperties.data()); // Some devices have dedicated compute queues, so we first try to find a queue that supports compute and not graphics bool computeQueueFound = false; for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++) { if ((queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) && ((queueFamilyProperties[i].queueFlags & VK_QUEUE_GRAPHICS_BIT) == 0)) { compute.queueFamilyIndex = i; computeQueueFound = true; break; } } // If there is no dedicated compute queue, just find the first queue family that supports compute if (!computeQueueFound) { for (uint32_t i = 0; i < static_cast<uint32_t>(queueFamilyProperties.size()); i++) { if (queueFamilyProperties[i].queueFlags & VK_QUEUE_COMPUTE_BIT) { compute.queueFamilyIndex = i; computeQueueFound = true; break; } } } // Compute is mandatory in Vulkan, so there must be at least one queue family that supports compute assert(computeQueueFound); // Get a compute queue from the device vkGetDeviceQueue(device, compute.queueFamilyIndex, 0, &compute.queue); } // Prepare a texture target that is used to store compute shader calculations void BloomFFT::prepareTextureTarget( uint32_t width, uint32_t height, VkCommandPool &cmdPool,VkQueue queue) { createUniformBuffers(queue); // Prepare blit target texture textureComputeTarget.width = width; textureComputeTarget.height = height; VkImageCreateInfo imageCreateInfo = vks::initializers::imageCreateInfo(); imageCreateInfo.imageType = VK_IMAGE_TYPE_2D; imageCreateInfo.format = VK_FORMAT_R8G8B8A8_UNORM; imageCreateInfo.extent = { width, height, 1 }; imageCreateInfo.mipLevels = 1; imageCreateInfo.arrayLayers = 1; imageCreateInfo.samples = VK_SAMPLE_COUNT_1_BIT; imageCreateInfo.tiling = VK_IMAGE_TILING_OPTIMAL; // Image will be sampled in the fragment shader and used as storage target in the compute shader imageCreateInfo.usage = VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_STORAGE_BIT; imageCreateInfo.flags = 0; // Sharing mode exclusive means that ownership of the image does not need to be explicitly transferred between the compute and graphics queue imageCreateInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkMemoryAllocateInfo memAllocInfo = vks::initializers::memoryAllocateInfo(); VkMemoryRequirements memReqs; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &textureComputeTarget.image)); vkGetImageMemoryRequirements(device, textureComputeTarget.image, &memReqs); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAllocInfo, nullptr, &textureComputeTarget.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textureComputeTarget.image, textureComputeTarget.deviceMemory, 0)); VkCommandBuffer layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true, cmdPool); textureComputeTarget.imageLayout = VK_IMAGE_LAYOUT_GENERAL; vks::tools::setImageLayout( layoutCmd, textureComputeTarget.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, textureComputeTarget.imageLayout); flushCommandBuffer(layoutCmd, queue, true, cmdPool); // Create sampler VkSamplerCreateInfo sampler = vks::initializers::samplerCreateInfo(); sampler.magFilter = VK_FILTER_LINEAR; sampler.minFilter = VK_FILTER_LINEAR; sampler.mipmapMode = VK_SAMPLER_MIPMAP_MODE_LINEAR; sampler.addressModeU = VK_SAMPLER_ADDRESS_MODE_CLAMP_TO_BORDER; sampler.addressModeV = sampler.addressModeU; sampler.addressModeW = sampler.addressModeU; sampler.mipLodBias = 0.0f; sampler.maxAnisotropy = 1.0f; sampler.compareOp = VK_COMPARE_OP_NEVER; sampler.minLod = 0.0f; sampler.maxLod =static_cast<float>(textureComputeTarget.mipLevels); sampler.borderColor = VK_BORDER_COLOR_FLOAT_OPAQUE_WHITE; VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &textureComputeTarget.sampler)); // Create image view VkImageViewCreateInfo view = vks::initializers::imageViewCreateInfo(); view.image = VK_NULL_HANDLE; view.viewType = VK_IMAGE_VIEW_TYPE_2D; view.format = VK_FORMAT_R8G8B8A8_UNORM; view.components = { VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G, VK_COMPONENT_SWIZZLE_B, VK_COMPONENT_SWIZZLE_A }; view.subresourceRange = { VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1 }; view.image = textureComputeTarget.image; VK_CHECK_RESULT(vkCreateImageView(device, &view, nullptr, &textureComputeTarget.view)); // Initialize a descriptor for later use textureComputeTarget.descriptor.imageLayout = textureComputeTarget.imageLayout; textureComputeTarget.descriptor.imageView = textureComputeTarget.view; textureComputeTarget.descriptor.sampler = textureComputeTarget.sampler; textureComputeTarget.device = vulkanDevice; // Prepare blit target texture textureComputeTargetOut.width = width; textureComputeTargetOut.height = height; VK_CHECK_RESULT(vkCreateImage(device, &imageCreateInfo, nullptr, &textureComputeTargetOut.image)); vkGetImageMemoryRequirements(device, textureComputeTargetOut.image, &memReqs); memAllocInfo.allocationSize = memReqs.size; memAllocInfo.memoryTypeIndex = vulkanDevice->getMemoryType(memReqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT); VK_CHECK_RESULT(vkAllocateMemory(device, &memAllocInfo, nullptr, &textureComputeTargetOut.deviceMemory)); VK_CHECK_RESULT(vkBindImageMemory(device, textureComputeTargetOut.image, textureComputeTargetOut.deviceMemory, 0)); layoutCmd = createCommandBuffer(VK_COMMAND_BUFFER_LEVEL_PRIMARY, true, cmdPool); textureComputeTargetOut.imageLayout = VK_IMAGE_LAYOUT_GENERAL; vks::tools::setImageLayout( layoutCmd, textureComputeTargetOut.image, VK_IMAGE_ASPECT_COLOR_BIT, VK_IMAGE_LAYOUT_UNDEFINED, textureComputeTargetOut.imageLayout); flushCommandBuffer(layoutCmd, queue, true, cmdPool); sampler.maxLod = static_cast<float>(textureComputeTargetOut.mipLevels); VK_CHECK_RESULT(vkCreateSampler(device, &sampler, nullptr, &textureComputeTargetOut.sampler)); view.image = textureComputeTargetOut.image; VK_CHECK_RESULT(vkCreateImageView(device, &view, nullptr, &textureComputeTargetOut.view)); // Initialize a descriptor for later use textureComputeTargetOut.descriptor.imageLayout = textureComputeTargetOut.imageLayout; textureComputeTargetOut.descriptor.imageView = textureComputeTargetOut.view; textureComputeTargetOut.descriptor.sampler = textureComputeTargetOut.sampler; textureComputeTarget.device = vulkanDevice; } void BloomFFT::createUniformBuffers(VkQueue queue) { // Scene matrices vulkanDevice->createBuffer( VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, &uniformBuffers, sizeof(uboParams)); updateUniformBuffer(1); }void BloomFFT::updateUniformBuffer(int direction) { uboParams.direction = 1; uboParams.scale = 2.5; uboParams.strength = 1.0; VK_CHECK_RESULT(uniformBuffers.map()); uniformBuffers.copyTo(&uboParams, sizeof(uboParams)); uniformBuffers.unmap(); } void BloomFFT::prepareCompute(VkDescriptorPool &descriptorPool, VkDescriptorImageInfo &texDescriptor) { getComputeQueue(); // Create compute pipeline // Compute pipelines are created separate from graphics pipelines even if they use the same queue std::vector<VkDescriptorSetLayoutBinding> setLayoutBindings = { // Binding 0: Input image (read-only) vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 0), // Binding 1: Output image (write) vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, VK_SHADER_STAGE_COMPUTE_BIT, 1), vks::initializers::descriptorSetLayoutBinding(VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, VK_SHADER_STAGE_COMPUTE_BIT, 2), }; VkDescriptorSetLayoutCreateInfo descriptorLayout = vks::initializers::descriptorSetLayoutCreateInfo(setLayoutBindings); VK_CHECK_RESULT(vkCreateDescriptorSetLayout(device, &descriptorLayout, nullptr, &compute.descriptorSetLayout)); VkPipelineLayoutCreateInfo pPipelineLayoutCreateInfo = vks::initializers::pipelineLayoutCreateInfo(&compute.descriptorSetLayout, 1); VkPushConstantRange pushConstantRange = vks::initializers::pushConstantRange( VK_SHADER_STAGE_VERTEX_BIT, sizeof(uboParams), 0); pPipelineLayoutCreateInfo.pushConstantRangeCount = 1; pPipelineLayoutCreateInfo.pPushConstantRanges = &pushConstantRange; VK_CHECK_RESULT(vkCreatePipelineLayout(device, &pPipelineLayoutCreateInfo, nullptr, &compute.pipelineLayout)); VkDescriptorSetAllocateInfo allocInfo = vks::initializers::descriptorSetAllocateInfo(descriptorPool, &compute.descriptorSetLayout, 1); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &compute.descriptorSet)); std::vector<VkWriteDescriptorSet> computeWriteDescriptorSets = { vks::initializers::writeDescriptorSet(compute.descriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, &texDescriptor), vks::initializers::writeDescriptorSet(compute.descriptorSet, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &textureComputeTarget.descriptor), vks::initializers::writeDescriptorSet(compute.descriptorSet, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformBuffers.descriptor) }; vkUpdateDescriptorSets(device, static_cast<uint32_t>(computeWriteDescriptorSets.size()), computeWriteDescriptorSets.data(), 0, NULL); VK_CHECK_RESULT(vkAllocateDescriptorSets(device, &allocInfo, &compute.descriptorSetOut)); std::vector<VkWriteDescriptorSet> computeWriteDescriptorSetsOut = { vks::initializers::writeDescriptorSet(compute.descriptorSetOut, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 0, &textureComputeTarget.descriptor), vks::initializers::writeDescriptorSet(compute.descriptorSetOut, VK_DESCRIPTOR_TYPE_STORAGE_IMAGE, 1, &textureComputeTargetOut.descriptor), vks::initializers::writeDescriptorSet(compute.descriptorSetOut, VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER, 2, &uniformBuffers.descriptor) }; vkUpdateDescriptorSets(device, static_cast<uint32_t>(computeWriteDescriptorSetsOut.size()), computeWriteDescriptorSetsOut.data(), 0, NULL); // Create compute shader pipelines VkComputePipelineCreateInfo computePipelineCreateInfo = vks::initializers::computePipelineCreateInfo(compute.pipelineLayout, 0); std::string fileName = getAssetPath + "computeshader/gaussianBlur.comp.spv"; computePipelineCreateInfo.stage = loadShader(fileName, VK_SHADER_STAGE_COMPUTE_BIT, device, shaderModules); VkPipeline pipeline; VK_CHECK_RESULT(vkCreateComputePipelines(device, 0, 1, &computePipelineCreateInfo, nullptr, &pipeline)); compute.pipelines.push_back(pipeline); // Separate command pool as queue family for compute may be different than graphics VkCommandPoolCreateInfo cmdPoolInfo = {}; cmdPoolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; cmdPoolInfo.queueFamilyIndex = compute.queueFamilyIndex; cmdPoolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT; VK_CHECK_RESULT(vkCreateCommandPool(device, &cmdPoolInfo, nullptr, &compute.commandPool)); // Create a command buffer for compute operations VkCommandBufferAllocateInfo cmdBufAllocateInfo = vks::initializers::commandBufferAllocateInfo( compute.commandPool, VK_COMMAND_BUFFER_LEVEL_PRIMARY, 1); VK_CHECK_RESULT(vkAllocateCommandBuffers(device, &cmdBufAllocateInfo, &compute.commandBuffer)); // Fence for compute CB sync VkFenceCreateInfo fenceCreateInfo = vks::initializers::fenceCreateInfo(VK_FENCE_CREATE_SIGNALED_BIT); VK_CHECK_RESULT(vkCreateFence(device, &fenceCreateInfo, nullptr, &compute.fence)); // Build a single command buffer containing the compute dispatch commands //buildComputeCommandBuffer(); } void BloomFFT::buildComputeCommandBuffer() { // Flush the queue if we're rebuilding the command buffer after a pipeline change to ensure it's not currently in use vkQueueWaitIdle(compute.queue); VkCommandBufferBeginInfo cmdBufInfo = vks::initializers::commandBufferBeginInfo(); VK_CHECK_RESULT(vkBeginCommandBuffer(compute.commandBuffer, &cmdBufInfo)); uboParams.direction = 1; uboParams.scale = 4.5; uboParams.strength = 1.0; vkCmdPushConstants( compute.commandBuffer, compute.pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uboParams), &uboParams); vkCmdBindPipeline(compute.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipelines[compute.pipelineIndex]); vkCmdBindDescriptorSets(compute.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipelineLayout, 0, 1, &compute.descriptorSet, 0, 0); vkCmdDispatch(compute.commandBuffer, textureComputeTarget.width / 16, textureComputeTarget.height / 16, 1); uboParams.direction = 0; vkCmdPushConstants( compute.commandBuffer, compute.pipelineLayout, VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(uboParams), &uboParams); vkCmdBindDescriptorSets(compute.commandBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, compute.pipelineLayout, 0, 1, &compute.descriptorSetOut, 0, 0); vkCmdDispatch(compute.commandBuffer, textureComputeTarget.width / 16, textureComputeTarget.height / 16, 1); vkEndCommandBuffer(compute.commandBuffer); }
43.196875
143
0.818419
liuhongyi0101
5ac3f2e8ad5d7b8f0836af365f2c48061ba84948
604
cpp
C++
InterviewBit/Tree Data Structure/TwoSumBinaryTree.cpp
Code-With-Aagam/competitive-programming
610520cc396fb13a03c606b5fb6739cfd68cc444
[ "MIT" ]
2
2022-02-08T12:37:41.000Z
2022-03-09T03:48:56.000Z
InterviewBit/Tree Data Structure/TwoSumBinaryTree.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
null
null
null
InterviewBit/Tree Data Structure/TwoSumBinaryTree.cpp
ShubhamJagtap2000/competitive-programming-1
3a9a2e3dd08f8fa8ab823f295cd020d08d3bff84
[ "MIT" ]
2
2021-01-23T14:35:48.000Z
2021-03-15T05:04:24.000Z
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ void inorder(TreeNode *root, vector<int> &arr) { if (root == NULL) { return; } inorder(root->left, arr); arr.push_back(root->val); inorder(root->right, arr); } int Solution::t2Sum(TreeNode *root, int k) { vector<int> arr; inorder(root, arr); int lo = 0, hi = arr.size() - 1; while (lo < hi) { int curr = arr[lo] + arr[hi]; if (curr == k) { return 1; } curr < k ? lo++ : hi--; } return 0; }
18.30303
59
0.559603
Code-With-Aagam
5ac525f8af8438fdc1a9aa2dfa5bfd4d703a8344
4,474
cpp
C++
src/Jogo/Fases/FaseMontanha.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Fases/FaseMontanha.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
src/Jogo/Fases/FaseMontanha.cpp
MatheusKunnen/Jogo-TecProg
66f4320e51e42d12da74e487cc8552377ce865bb
[ "MIT" ]
null
null
null
// // FaseMontanha.cpp // Jogo-SFML // // Created by Matheus Kunnen Ledesma on 11/10/19. // Copyright © 2019 Matheus Kunnen Ledesma. All rights reserved. // #include "FaseMontanha.hpp" namespace Game { namespace Fases { // Const const string FaseMontanha::CONFIG_FILE("Resources/config/fase_b_config.json"); // Constructor && Destructor FaseMontanha::FaseMontanha(Jogador* jogador_a, Jogador* jogador_b): Fase(ID::fase_montanha, FaseMontanha::CONFIG_FILE, jogador_a, jogador_b) { } FaseMontanha::~FaseMontanha(){ this->l_entidades.clear(); } // Init Methods void FaseMontanha::initInimigos() { Inimigo* desmatador = nullptr; const vector<Vector2f>& lista = this->parametros.getListaPosInimigos(); for (Vector2f pos : lista){ if (rand() % 10 > 3){ desmatador = new Narcotraficante(pos, &this->textures.get(Resources::Textures::narcotraficante), this->jogador_a, this->jogador_b, this); this->l_entidades += desmatador; this->g_colisoes += desmatador; } } } void FaseMontanha::initObstaculos() { Obstaculo* obstaculo = nullptr; const vector<Vector2f>& lista = this->parametros.getListaPosObstaculos(); for (Vector2f pos : lista){ if (rand() % 10 > 3) { if (rand() % 2 == 1) obstaculo = new Pedra(pos, &this->textures.get(Resources::Textures::pedra)); else obstaculo = new Espinho(pos, &this->textures.get(Resources::Textures::espinhos)); Vector2f ppos = obstaculo->getPosition(); ppos.y -= obstaculo->getGlobalBounds().height; obstaculo->setPosition(ppos); this->l_entidades+= obstaculo; this->g_colisoes += obstaculo; } } } void FaseMontanha::initBoss(){ Inimigo* inimigo = new NarcotraficanteDesmatador(this->parametros.getPosBoss(), &this->textures.get(Resources::Textures::narcotraficante_desmatador), this->jogador_a, this->jogador_b, this); this->l_entidades+= inimigo; this->g_colisoes += inimigo; } void FaseMontanha::onSavedFase() { // Inicia posicao jogadores vector<Vector2f> l_pos = this->salvadora.getPositions(Entidades::ID::jogador); this->jogador_a->setPosition(l_pos[0]); this->jogador_a->setNumVidas(this->salvadora.getVidaJogador(1)); if (this->jogador_b && l_pos.size() > 1){ this->jogador_b->setPosition(l_pos[1]); this->jogador_b->setNumVidas(this->salvadora.getVidaJogador(2)); } l_pos = this->salvadora.getPositions(Entidades::ID::boss); for(Vector2f pos : l_pos) this->addEntidade(new NarcotraficanteDesmatador(pos, &this->textures.get(Resources::Textures::narcotraficante), this->jogador_a, this->jogador_b, this)); l_pos = this->salvadora.getPositions(Entidades::ID::narcotraficante); for(Vector2f pos : l_pos) this->addEntidade(new Narcotraficante(pos, &this->textures.get(Resources::Textures::narcotraficante), this->jogador_a, this->jogador_b, this)); l_pos = this->salvadora.getPositions(Entidades::ID::espinhos); for(Vector2f pos : l_pos) this->addEntidade(new Espinho(pos, &this->textures.get(Resources::Textures::espinhos))); l_pos = this->salvadora.getPositions(Entidades::ID::pedra); for(Vector2f pos : l_pos) this->addEntidade(new Pedra(pos, &this->textures.get(Resources::Textures::planta_venenosa))); } // Methods void FaseMontanha::onInitFase(Jogador* jogador_a, Jogador* jogador_b, FaseEventHandler* event_handler){ // Agrega mapa this->l_entidades.add(&mapa); // Atualiza ponteiros de jogadores this->jogador_a = jogador_a; this->jogador_b = jogador_b; // Inicia jogadores this->initJogadores(); // Carrega salvadora this->salvadora.load(); if (!this->salvadora.isSavedFase()){ // Inicia boss this->initBoss(); // Inicia Obstaculos this->initObstaculos(); // Inicia Inimigos this->initInimigos(); // Muda estado this->salvadora.setSavedFase(true); } else { this->onSavedFase(); } // Retorna o mapa a sua posicao inicial this->mapa.reset(); // Atualiza EventHandler this->setEventHandler(event_handler); // Adapta View para resolucoes maiores GerenciadorGrafico::getInstance()->moveView(0, - (GerenciadorGrafico::getInstance()->getView()->getSize().y - this->mapa.getHeight())); } }}
35.507937
194
0.660483
MatheusKunnen
5ac62f82592e415ee827d5189293c7f3233b15a7
165
cpp
C++
codeforces/617A.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
3
2018-01-08T02:52:51.000Z
2021-03-03T01:08:44.000Z
codeforces/617A.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
null
null
null
codeforces/617A.cpp
cosmicray001/Online_judge_Solutions-
5dc6f90d3848eb192e6edea8e8c731f41a1761dd
[ "MIT" ]
1
2020-08-13T18:07:35.000Z
2020-08-13T18:07:35.000Z
#include <bits/stdc++.h> using namespace std; int main(){ int n; cin >> n; int ans = 0; if(n % 5 != 0) ans++; printf("%d\n", (n / 5) + ans); return 0; }
15
32
0.50303
cosmicray001
5acc4ab4d9834f6261945e202b17ad0eaa29e43f
394
cpp
C++
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
3
2021-03-31T03:42:42.000Z
2021-12-13T03:03:03.000Z
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
null
null
null
src/State.cpp
JoanStinson/AI_Decisions
22632090c80b4a12e0f1049b4e6c78be3d024b2a
[ "MIT" ]
1
2021-12-13T03:02:55.000Z
2021-12-13T03:02:55.000Z
#include "State.h" State::State() { bankPosition = Vector2D(208, 624); homePosition = Vector2D(624, 624); minePosition = Vector2D(272, 112); saloonPosition = Vector2D(1040, 624); } State::~State() { delete agent; } void State::Init(Agent * agent, Uint32 delayTime) { this->agent = agent; this->delayTime = delayTime; } void State::Quit(State * state) { agent->SwitchState(state); }
17.909091
51
0.682741
JoanStinson
5ace0782dec3b99ee0a5f4f46b0d1c899d9277ad
2,326
cpp
C++
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
graph-source-code/362-E/8343555.cpp
AmrARaouf/algorithm-detection
59f3028d2298804870b32729415d71eec6116557
[ "MIT" ]
null
null
null
//Language: GNU C++ #include <iostream> #include <cstdio> #include <cstring> #include <cmath> #include <algorithm> #include <climits> #include <vector> #include <queue> #include <cstdlib> #include <string> #include <set> #include <stack> #define LL long long #define pii pair<int,int> #define INF 0x3f3f3f3f using namespace std; const int maxn = 110; struct arc { int to,flow,cost,next; arc(int x = 0,int y = 0,int z = 0,int nxt = -1) { to = x; flow = y; cost = z; next = nxt; } }; arc e[10000]; int head[maxn],d[maxn],p[maxn],S,T,n,k,tot; bool in[maxn]; void add(int u,int v,int flow,int cost) { e[tot] = arc(v,flow,cost,head[u]); head[u] = tot++; e[tot] = arc(u,0,-cost,head[v]); head[v] = tot++; } bool spfa() { queue<int>q; for(int i = 0; i <= n; ++i) { d[i] = INF; p[i] = -1; in[i] = false; } d[S] = 0; q.push(S); while(!q.empty()) { int u = q.front(); q.pop(); in[u] = false; for(int i = head[u]; ~i; i = e[i].next) { if(e[i].flow && d[e[i].to] > d[u] + e[i].cost) { d[e[i].to] = d[u] + e[i].cost; p[e[i].to] = i; if(!in[e[i].to]){ in[e[i].to] = true; q.push(e[i].to); } } } } return p[T] > -1; } int solve() { int cost = 0,flow = 0; while(spfa()) { int theMin = INF; for(int i = p[T]; ~i; i = p[e[i^1].to]) theMin = min(theMin,e[i].flow); if(cost + d[T]*theMin > k) return flow + (k - cost)/d[T]; flow += theMin; cost += d[T]*theMin; for(int i = p[T]; ~i; i = p[e[i^1].to]) { e[i].flow -= theMin; e[i^1].flow += theMin; } } return flow; } int main() { while(~scanf("%d %d",&n,&k)) { memset(head,-1,sizeof(head)); S = 0; T = n-1; int tmp; for(int i = tot = 0; i < n; ++i) for(int j = 0; j < n; ++j) { scanf("%d",&tmp); if(tmp) { add(i,j,tmp,0); add(i,j,k,1); } } printf("%d\n",solve()); } return 0; }
23.029703
65
0.410146
AmrARaouf
5ace2172fa2ef85d29199534b22ab9249c590b0d
1,792
hpp
C++
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
63
2016-02-06T21:06:40.000Z
2021-11-16T19:58:27.000Z
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
11
2019-05-23T20:55:12.000Z
2021-12-08T22:18:01.000Z
tools/json-ast-exporter/src/json_utils.hpp
TheoKant/cclyzer-souffle
dfcd01daa592a2356e36aaeaa9c933305c253cba
[ "MIT" ]
14
2016-02-21T17:12:36.000Z
2021-09-26T02:48:41.000Z
#ifndef JSON_UTILS_HPP__ #define JSON_UTILS_HPP__ #include <string> #include <clang-c/Index.h> #include <jsoncons/json.hpp> namespace cclyzer { namespace ast_exporter { namespace jsonexport { typedef jsoncons::json json_t; // Recording routines void record_extent( json_t &, CXCursor ); void record_extent(json_t &, CXSourceRange ); void record_kind( json_t &, CXCursor ); void record_spelling( json_t &, CXCursor ); void record_tokens( json_t &, CXCursor, CXTranslationUnit ); void record_token( json_t & , CXToken, CXTranslationUnit ); // AST Node properties namespace node { const std::string FILE = "file"; const std::string KIND = "kind"; const std::string DATA = "data"; const std::string START_LINE = "start_line"; const std::string START_COLUMN = "start_column"; const std::string START_OFFSET = "start_offset"; const std::string END_LINE = "end_line"; const std::string END_COLUMN = "end_column"; const std::string END_OFFSET = "end_offset"; const std::string TOKENS = "tokens"; const std::string TREE = "ast"; } // Lexical Token Properties namespace lex_token { const std::string KIND = "kind"; const std::string DATA = "data"; const std::string FILE = "file"; const std::string LINE = "line"; const std::string COLUMN = "column"; const std::string OFFSET = "offset"; } } } } #endif /* JSON_UTILS_HPP__ */
32
72
0.541853
TheoKant
62c26d2c087b23d3802b9a3ea8eeba0faf253fea
601
cpp
C++
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
238-product-of-array-except-self/238-product-of-array-except-self.cpp
dishanp/LeetCode-World
6c49c8731dae772fb7bc47f777a4d3b3e01dd70e
[ "MIT" ]
null
null
null
class Solution { public: vector<int> productExceptSelf(vector<int>& nums) { int p=1; int ctr=0; int zp=1; for(int i:nums) { p*=i; if(i==0) ++ctr; if(ctr>1){ vector<int>ans(nums.size(),0); return ans; } if(i!=0) zp*=i; } vector<int>res; for(int i:nums) { if(i==0) res.push_back(zp); else res.push_back(p/i); } return res; } };
20.724138
54
0.344426
dishanp
62c349af6daabc492e41738d9210e08562d02708
1,499
cpp
C++
alon/primeNumbers.cpp
Jhoneagle/CplusplusCollection
a58d2407fbd397749d7bc07796ac052f632dcb73
[ "MIT" ]
null
null
null
alon/primeNumbers.cpp
Jhoneagle/CplusplusCollection
a58d2407fbd397749d7bc07796ac052f632dcb73
[ "MIT" ]
null
null
null
alon/primeNumbers.cpp
Jhoneagle/CplusplusCollection
a58d2407fbd397749d7bc07796ac052f632dcb73
[ "MIT" ]
1
2020-03-09T22:18:40.000Z
2020-03-09T22:18:40.000Z
#include<bits/stdc++.h> #include <iostream> using namespace std; bool prime(long long n) { if (n <= 3) { return (n > 1); } if (((n % 2) == 0) || ((n % 3) == 0)) { return false; } long i = 5; while ((i * i) <= n) { if (((n % i) == 0) || ((n % (i + 2)) == 0)) { return false; } i += 6; } return true; } int main() { long long n; cin >> n; if (prime(n + 1)) { for(long long i = 1; i <= n; i++) { cout << i << " "; } cout << "\n"; for(long long j = n; j > 0; j--) { cout << j << " "; } } else { long long r; long long s; vector<long long> second; long long i = n; //asked number while(i > 0) { for(long long a = (i - 1); a >= 1; a--) { if (prime(a + i)) { r = a; } } s = i - r; for (long long a = 0; a <= s; a++) { second.push_back(r + a); } i = (r - 1); if (i == 3) { second.push_back(2); second.push_back(3); second.push_back(1); break; } else if (i == 2) { second.push_back(1); second.push_back(2); break; } else if (i == 1) { second.push_back(1); break; } } for(long long j = n; j > 0; j--){ cout << j << " "; } cout << "\n"; for(long long j = 0; j < n; j++) { long long number = second[j]; cout << number << " "; } } return 0; }
16.293478
51
0.378252
Jhoneagle
62c7c24a915b70d87ec6da0b51c9364ddca01ca9
1,290
hpp
C++
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
5
2019-02-12T07:23:55.000Z
2020-06-22T15:03:36.000Z
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
null
null
null
engine/source/src/Engine_collision_listener.hpp
mateusgondim/Demos
6aa5da3a6c0e960d10811c9e71e9a0a746e8d6ab
[ "MIT" ]
2
2019-06-17T05:04:21.000Z
2020-04-22T09:05:57.000Z
#ifndef _ENGINE_COLLISION_LISTENER_HPP #define _ENGINE_COLLISION_LISTENER_HPP #include "Collision_listener.hpp" #include <cstdint> namespace physics_2d { class Body_2d; } namespace gom { class Game_object; } class Engine_collision_listener final : public physics_2d::Collision_listener { public: Engine_collision_listener(); void begin_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; void in_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; void end_body_collision(physics_2d::Body_2d * pbody_a, physics_2d::Body_2d * pbody_b) const override; private: void send_collision_event(gom::Game_object * pfrom_object, gom::Game_object * pto_object, std::uint32_t event_type) const; std::uint32_t m_begin_collision_id; std::uint32_t m_in_collision_id; std::uint32_t m_end_collision_id; std::uint32_t m_game_object_id; std::uint32_t m_game_object_handle_index; }; #endif // !_ENGINE_COLLISION_LISTENER_HPP
40.3125
80
0.633333
mateusgondim
62d2ddf952e573be0f198c825ffdbc27578ee2d0
2,023
cpp
C++
libhpx/scheduler/events.cpp
luglio/hpx5
6cbeebb8e730ee9faa4487dba31a38e3139e1ce7
[ "BSD-3-Clause" ]
1
2021-05-21T16:54:43.000Z
2021-05-21T16:54:43.000Z
libhpx/scheduler/events.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
null
null
null
libhpx/scheduler/events.cpp
ldalessa/hpx
c8888c38f5c12c27bfd80026d175ceb3839f0b40
[ "BSD-3-Clause" ]
3
2019-06-21T07:05:43.000Z
2020-11-21T15:24:04.000Z
// ============================================================================= // High Performance ParalleX Library (libhpx) // // Copyright (c) 2013-2017, Trustees of Indiana University, // All rights reserved. // // This software may be modified and distributed under the terms of the BSD // license. See the COPYING file for details. // // This software was created at the Indiana University Center for Research in // Extreme Scale Technologies (CREST). // ============================================================================= #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "libhpx/Worker.h" #include "libhpx/events.h" #include "libhpx/parcel.h" #include "hpx/hpx.h" namespace { using libhpx::Worker; } void Worker::EVENT_THREAD_RUN(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX // if this is NOT a null or lightweight action, send a "start" event to APEX if (p->action != hpx_lco_set_action) { CHECK_ACTION(p->action); void* handler = (void*)actions[p->action].handler; profiler_ = (void*)(apex_start(APEX_FUNCTION_ADDRESS, handler)); } #endif EVENT_PARCEL_RUN(p->id, p->action, p->size); } void Worker::EVENT_THREAD_END(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX if (profiler_ != NULL) { apex_stop((apex_profiler_handle)(profiler_)); profiler_ = NULL; } #endif EVENT_PARCEL_END(p->id, p->action); } void Worker::EVENT_THREAD_SUSPEND(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX if (profiler_ != NULL) { apex_stop((apex_profiler_handle)(profiler_)); profiler_ = NULL; } #endif EVENT_PARCEL_SUSPEND(p->id, p->action); } void Worker::EVENT_THREAD_RESUME(hpx_parcel_t *p) { if (p == system_) { return; } #ifdef HAVE_APEX if (p->action != hpx_lco_set_action) { void* handler = (void*)actions[p->action].handler; profiler_ = (void*)(apex_resume(APEX_FUNCTION_ADDRESS, handler)); } #endif EVENT_PARCEL_RESUME(p->id, p->action); }
23.8
80
0.630746
luglio
62d8c6581a358517d4a8e20777178ac28fc2767c
16,104
cpp
C++
dynamicEDT3D/src/dynamicEDT3D.cpp
hero9968/OctoMap
bf3b3949a99c13ef34d11dc8bc23dcd6680a9f3c
[ "BSD-3-Clause" ]
1,323
2015-01-02T08:33:08.000Z
2022-03-31T22:57:08.000Z
dynamicEDT3D/src/dynamicEDT3D.cpp
hero9968/OctoMap
bf3b3949a99c13ef34d11dc8bc23dcd6680a9f3c
[ "BSD-3-Clause" ]
267
2015-01-21T05:34:55.000Z
2022-03-29T18:38:21.000Z
dynamicEDT3D/src/dynamicEDT3D.cpp
hero9968/OctoMap
bf3b3949a99c13ef34d11dc8bc23dcd6680a9f3c
[ "BSD-3-Clause" ]
610
2015-01-02T08:33:38.000Z
2022-03-31T03:04:06.000Z
/** * dynamicEDT3D: * A library for incrementally updatable Euclidean distance transforms in 3D. * @author C. Sprunk, B. Lau, W. Burgard, University of Freiburg, Copyright (C) 2011. * @see http://octomap.sourceforge.net/ * License: New BSD License */ /* * Copyright (c) 2011-2012, C. Sprunk, B. Lau, W. Burgard, University of Freiburg * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the University of Freiburg nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ #include <dynamicEDT3D/dynamicEDT3D.h> #include <math.h> #include <stdlib.h> #define FOR_EACH_NEIGHBOR_WITH_CHECK(function, p, ...) \ int x=p.x;\ int y=p.y;\ int z=p.z;\ int xp1 = x+1;\ int xm1 = x-1;\ int yp1 = y+1;\ int ym1 = y-1;\ int zp1 = z+1;\ int zm1 = z-1;\ \ if(z<sizeZm1) function(x, y, zp1, ##__VA_ARGS__);\ if(z>0) function(x, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(x, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(x, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(x, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(x, ym1, zm1, ##__VA_ARGS__);\ }\ \ \ if(x<sizeXm1){\ function(xp1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xp1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xp1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xp1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xp1, ym1, zm1, ##__VA_ARGS__);\ }\ }\ \ if(x>0){\ function(xm1, y, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, y, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, y, zm1, ##__VA_ARGS__);\ \ if(y<sizeYm1){\ function(xm1, yp1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, yp1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, yp1, zm1, ##__VA_ARGS__);\ }\ \ if(y>0){\ function(xm1, ym1, z, ##__VA_ARGS__);\ if(z<sizeZm1) function(xm1, ym1, zp1, ##__VA_ARGS__);\ if(z>0) function(xm1, ym1, zm1, ##__VA_ARGS__);\ }\ } float DynamicEDT3D::distanceValue_Error = -1.0; int DynamicEDT3D::distanceInCellsValue_Error = -1; DynamicEDT3D::DynamicEDT3D(int _maxdist_squared) { sqrt2 = sqrt(2.0); maxDist_squared = _maxdist_squared; maxDist = sqrt((double) maxDist_squared); data = NULL; gridMap = NULL; } DynamicEDT3D::~DynamicEDT3D() { if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } } void DynamicEDT3D::initializeEmpty(int _sizeX, int _sizeY, int _sizeZ, bool initGridMap) { sizeX = _sizeX; sizeY = _sizeY; sizeZ = _sizeZ; sizeXm1 = sizeX-1; sizeYm1 = sizeY-1; sizeZm1 = sizeZ-1; if (data) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] data[x][y]; delete[] data[x]; } delete[] data; } data = new dataCell**[sizeX]; for (int x=0; x<sizeX; x++){ data[x] = new dataCell*[sizeY]; for(int y=0; y<sizeY; y++) data[x][y] = new dataCell[sizeZ]; } if (initGridMap) { if (gridMap) { for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++) delete[] gridMap[x][y]; delete[] gridMap[x]; } delete[] gridMap; } gridMap = new bool**[sizeX]; for (int x=0; x<sizeX; x++){ gridMap[x] = new bool*[sizeY]; for (int y=0; y<sizeY; y++) gridMap[x][y] = new bool[sizeZ]; } } dataCell c; c.dist = maxDist; c.sqdist = maxDist_squared; c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = fwNotQueued; c.needsRaise = false; for (int x=0; x<sizeX; x++){ for (int y=0; y<sizeY; y++){ for (int z=0; z<sizeZ; z++){ data[x][y][z] = c; } } } if (initGridMap) { for (int x=0; x<sizeX; x++) for (int y=0; y<sizeY; y++) for (int z=0; z<sizeZ; z++) gridMap[x][y][z] = 0; } } void DynamicEDT3D::initializeMap(int _sizeX, int _sizeY, int _sizeZ, bool*** _gridMap) { gridMap = _gridMap; initializeEmpty(_sizeX, _sizeY, _sizeZ, false); for (int x=0; x<sizeX; x++) { for (int y=0; y<sizeY; y++) { for (int z=0; z<sizeZ; z++) { if (gridMap[x][y][z]) { dataCell c = data[x][y][z]; if (!isOccupied(x,y,z,c)) { bool isSurrounded = true; for (int dx=-1; dx<=1; dx++) { int nx = x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = z+dz; if (nz<0 || nz>sizeZ-1) continue; if (!gridMap[nx][ny][nz]) { isSurrounded = false; break; } } } } if (isSurrounded) { c.obstX = x; c.obstY = y; c.obstZ = z; c.sqdist = 0; c.dist = 0; c.queueing = fwProcessed; data[x][y][z] = c; } else setObstacle(x,y,z); } } } } } } void DynamicEDT3D::occupyCell(int x, int y, int z) { gridMap[x][y][z] = 1; setObstacle(x,y,z); } void DynamicEDT3D::clearCell(int x, int y, int z) { gridMap[x][y][z] = 0; removeObstacle(x,y,z); } void DynamicEDT3D::setObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c)) return; addList.push_back(INTPOINT3D(x,y,z)); c.obstX = x; c.obstY = y; c.obstZ = z; data[x][y][z] = c; } void DynamicEDT3D::removeObstacle(int x, int y, int z) { dataCell c = data[x][y][z]; if(isOccupied(x,y,z,c) == false) return; removeList.push_back(INTPOINT3D(x,y,z)); c.obstX = invalidObstData; c.obstY = invalidObstData; c.obstZ = invalidObstData; c.queueing = bwQueued; data[x][y][z] = c; } void DynamicEDT3D::exchangeObstacles(std::vector<INTPOINT3D> points) { for (unsigned int i=0; i<lastObstacles.size(); i++) { int x = lastObstacles[i].x; int y = lastObstacles[i].y; int z = lastObstacles[i].z; bool v = gridMap[x][y][z]; if (v) continue; removeObstacle(x,y,z); } lastObstacles.clear(); for (unsigned int i=0; i<points.size(); i++) { int x = points[i].x; int y = points[i].y; int z = points[i].z; bool v = gridMap[x][y][z]; if (v) continue; setObstacle(x,y,z); lastObstacles.push_back(points[i]); } } void DynamicEDT3D::update(bool updateRealDist) { commitAndColorize(updateRealDist); while (!open.empty()) { INTPOINT3D p = open.pop(); int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing==fwProcessed) continue; if (c.needsRaise) { // RAISE raiseCell(p, c, updateRealDist); data[x][y][z] = c; } else if (c.obstX != invalidObstData && isOccupied(c.obstX,c.obstY,c.obstZ,data[c.obstX][c.obstY][c.obstZ])) { // LOWER propagateCell(p, c, updateRealDist); data[x][y][z] = c; } } } void DynamicEDT3D::raiseCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellRaise(nx,ny,nz, updateRealDist); } } } */ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellRaise,p, updateRealDist) c.needsRaise = false; c.queueing = bwProcessed; } void DynamicEDT3D::inspectCellRaise(int &nx, int &ny, int &nz, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if (nc.obstX!=invalidObstData && !nc.needsRaise) { if(!isOccupied(nc.obstX,nc.obstY,nc.obstZ,data[nc.obstX][nc.obstY][nc.obstZ])) { open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; nc.needsRaise = true; nc.obstX = invalidObstData; nc.obstY = invalidObstData; nc.obstZ = invalidObstData; if (updateRealDist) nc.dist = maxDist; nc.sqdist = maxDist_squared; data[nx][ny][nz] = nc; } else { if(nc.queueing != fwQueued){ open.push(nc.sqdist, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; data[nx][ny][nz] = nc; } } } } void DynamicEDT3D::propagateCell(INTPOINT3D &p, dataCell &c, bool updateRealDist){ c.queueing = fwProcessed; /* for (int dx=-1; dx<=1; dx++) { int nx = p.x+dx; if (nx<0 || nx>sizeX-1) continue; for (int dy=-1; dy<=1; dy++) { int ny = p.y+dy; if (ny<0 || ny>sizeY-1) continue; for (int dz=-1; dz<=1; dz++) { if (dx==0 && dy==0 && dz==0) continue; int nz = p.z+dz; if (nz<0 || nz>sizeZ-1) continue; inspectCellPropagate(nx, ny, nz, c, updateRealDist); } } } */ if(c.sqdist==0){ FOR_EACH_NEIGHBOR_WITH_CHECK(inspectCellPropagate, p, c, updateRealDist) } else { int x=p.x; int y=p.y; int z=p.z; int xp1 = x+1; int xm1 = x-1; int yp1 = y+1; int ym1 = y-1; int zp1 = z+1; int zm1 = z-1; int dpx = (x - c.obstX); int dpy = (y - c.obstY); int dpz = (z - c.obstZ); // dpy=0; // dpz=0; if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(x, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(x, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(x, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(x, ym1, zm1, c, updateRealDist); } if(dpx>=0 && x<sizeXm1){ inspectCellPropagate(xp1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xp1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xp1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xp1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xp1, ym1, zm1, c, updateRealDist); } } if(dpx<=0 && x>0){ inspectCellPropagate(xm1, y, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, y, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, y, zm1, c, updateRealDist); if(dpy>=0 && y<sizeYm1){ inspectCellPropagate(xm1, yp1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, yp1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, yp1, zm1, c, updateRealDist); } if(dpy<=0 && y>0){ inspectCellPropagate(xm1, ym1, z, c, updateRealDist); if(dpz >=0 && z<sizeZm1) inspectCellPropagate(xm1, ym1, zp1, c, updateRealDist); if(dpz <=0 && z>0) inspectCellPropagate(xm1, ym1, zm1, c, updateRealDist); } } } } void DynamicEDT3D::inspectCellPropagate(int &nx, int &ny, int &nz, dataCell &c, bool updateRealDist){ dataCell nc = data[nx][ny][nz]; if(!nc.needsRaise) { int distx = nx-c.obstX; int disty = ny-c.obstY; int distz = nz-c.obstZ; int newSqDistance = distx*distx + disty*disty + distz*distz; if(newSqDistance > maxDist_squared) newSqDistance = maxDist_squared; bool overwrite = (newSqDistance < nc.sqdist); if(!overwrite && newSqDistance==nc.sqdist) { //the neighbor cell is marked to be raised, has no valid source obstacle if (nc.obstX == invalidObstData){ overwrite = true; } else { //the neighbor has no valid source obstacle but the raise wave has not yet reached it dataCell tmp = data[nc.obstX][nc.obstY][nc.obstZ]; if((tmp.obstX==nc.obstX && tmp.obstY==nc.obstY && tmp.obstZ==nc.obstZ)==false) overwrite = true; } } if (overwrite) { if(newSqDistance < maxDist_squared){ open.push(newSqDistance, INTPOINT3D(nx,ny,nz)); nc.queueing = fwQueued; } if (updateRealDist) { nc.dist = sqrt((double) newSqDistance); } nc.sqdist = newSqDistance; nc.obstX = c.obstX; nc.obstY = c.obstY; nc.obstZ = c.obstZ; } data[nx][ny][nz] = nc; } } float DynamicEDT3D::getDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].dist; } else return distanceValue_Error; } INTPOINT3D DynamicEDT3D::getClosestObstacle( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ dataCell c = data[x][y][z]; return INTPOINT3D(c.obstX, c.obstY, c.obstZ); } else return INTPOINT3D(invalidObstData, invalidObstData, invalidObstData); } int DynamicEDT3D::getSQCellDistance( int x, int y, int z ) const { if( (x>=0) && (x<sizeX) && (y>=0) && (y<sizeY) && (z>=0) && (z<sizeZ)){ return data[x][y][z].sqdist; } else return distanceInCellsValue_Error; } void DynamicEDT3D::commitAndColorize(bool updateRealDist) { // ADD NEW OBSTACLES for (unsigned int i=0; i<addList.size(); i++) { INTPOINT3D p = addList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if(c.queueing != fwQueued){ if (updateRealDist) c.dist = 0; c.sqdist = 0; c.obstX = x; c.obstY = y; c.obstZ = z; c.queueing = fwQueued; data[x][y][z] = c; open.push(0, INTPOINT3D(x,y,z)); } } // REMOVE OLD OBSTACLES for (unsigned int i=0; i<removeList.size(); i++) { INTPOINT3D p = removeList[i]; int x = p.x; int y = p.y; int z = p.z; dataCell c = data[x][y][z]; if (isOccupied(x,y,z,c)==true) continue; // obstacle was removed and reinserted open.push(0, INTPOINT3D(x,y,z)); if (updateRealDist) c.dist = maxDist; c.sqdist = maxDist_squared; c.needsRaise = true; data[x][y][z] = c; } removeList.clear(); addList.clear(); } bool DynamicEDT3D::isOccupied(int x, int y, int z) const { dataCell c = data[x][y][z]; return (c.obstX==x && c.obstY==y && c.obstZ==z); } bool DynamicEDT3D::isOccupied(int &x, int &y, int &z, dataCell &c) { return (c.obstX==x && c.obstY==y && c.obstZ==z); }
27.202703
112
0.613885
hero9968
62e0aa2965d32d1d3c12ecf9565dca58fe324e95
4,543
hpp
C++
server/drivers/laser.hpp
Koheron/koheron-sdk
82b732635f1adf5dd0b04b9290b589c1fc091f29
[ "MIT" ]
77
2016-09-20T18:44:14.000Z
2022-03-30T16:04:09.000Z
server/drivers/laser.hpp
rsarwar87/koheron-sdk
02c35bf3c1c29f1029fad18b881dbd193efac5a7
[ "MIT" ]
101
2016-09-05T15:44:25.000Z
2022-03-29T09:22:09.000Z
server/drivers/laser.hpp
rsarwar87/koheron-sdk
02c35bf3c1c29f1029fad18b881dbd193efac5a7
[ "MIT" ]
34
2016-12-12T07:21:57.000Z
2022-01-12T21:00:52.000Z
/// Laser controller /// /// (c) Koheron #ifndef __DRIVERS_LASER_CONTROLLER_HPP__ #define __DRIVERS_LASER_CONTROLLER_HPP__ #include <context.hpp> #include <xadc.hpp> #include <eeprom.hpp> #include <chrono> namespace Laser_params { constexpr uint32_t power_channel = 1; //xadc channel constexpr uint32_t current_channel = 8; //xadc channel constexpr float max_laser_current = 50.0; // mA constexpr float current_gain = 47.7; // mA/V constexpr float pwm_max_voltage = 1.8; // V constexpr float pwm_max_value = (1 << prm::pwm_width); constexpr float current_to_pwm = pwm_max_value / ( current_gain * pwm_max_voltage); constexpr float measured_current_gain = current_gain * 1E-7F; } class Laser { public: Laser(Context& ctx_) : ctx(ctx_) , ctl(ctx.mm.get<mem::control>()) , sts(ctx.mm.get<mem::status>()) , xadc(ctx.get<Xadc>()) , eeprom(ctx.get<Eeprom>()) { stop(); current = 0; set_current(current); read_calibration(); } void start() { ctl.clear_bit<reg::laser_control, 0>(); laser_on = true; } void stop() { ctl.set_bit<reg::laser_control, 0>(); laser_on = false; } void set_current(float current_value) { if (constant_power_on == true) { // Switch to constant current mode ctl.clear_bit<reg::laser_control, 2>(); constant_power_on = false; } current = std::min(current_value, Laser_params::max_laser_current); ctl.write<reg::laser_current>(uint32_t(current * Laser_params::current_to_pwm)); } void set_power(float power_value) { if (constant_power_on == false) { // Switch to constant power_mode ctl.set_bit<reg::laser_control, 2>(); constant_power_on = true; } power = power_value; ctl.write<reg::power_setpoint>(uint32_t((power_1mW - power_0mW) / 1000.0F * power_value + power_0mW)); } float get_measured_current() { return Laser_params::measured_current_gain * float(xadc.read(Laser_params::current_channel)); } float get_measured_power() { return 1000 * (float(xadc.read(Laser_params::power_channel)) - power_0mW) / (power_1mW - power_0mW); } void switch_mode() { if (!constant_power_on) { if (laser_on) { // integral reset stop(); start(); } set_power(get_measured_power()); } else { set_current(sts.read<reg::pid_control>() / Laser_params::current_to_pwm); } } auto get_status() { float measured_current = get_measured_current(); float measured_power = get_measured_power(); return std::make_tuple( laser_on, constant_power_on, is_calibrated, current, power, measured_current, measured_power ); } void read_calibration() { if (eeprom.read(0) == 1) { is_calibrated = true; power_0mW = eeprom.read(1); power_1mW = eeprom.read(2); } else { is_calibrated = false; power_0mW = 300; power_1mW = 1850; } } void calibrate_0mW() { using namespace std::chrono_literals; stop(); std::this_thread::sleep_for(200ms); uint32_t sum = 0; for (auto i = 0; i<100; i++) { sum += xadc.read(Laser_params::power_channel); } eeprom.write(1, sum/100); std::this_thread::sleep_for(5ms); ctx.log<INFO>("Power 0mW = %u\n", eeprom.read(1)); set_current(15.0); start(); } void calibrate_1mW() { using namespace std::chrono_literals; uint32_t sum = 0; for (auto i = 0; i<100; i++) { sum += xadc.read(Laser_params::power_channel); } eeprom.write(2, sum/100); std::this_thread::sleep_for(5ms); eeprom.write(0, 1); std::this_thread::sleep_for(5ms); ctx.log<INFO>("Power 1mW = %u\n", eeprom.read(2)); read_calibration(); } private: float current; float power; bool laser_on; bool constant_power_on; bool is_calibrated; Context& ctx; Memory<mem::control>& ctl; Memory<mem::status>& sts; Xadc& xadc; // Calibration Eeprom& eeprom; uint32_t power_0mW; uint32_t power_1mW; }; #endif // __DRIVERS_LASER_HPP__
27.70122
110
0.580233
Koheron
62e10d8a12b4458cb11b750206a6dd865e96bda7
1,409
cpp
C++
examples/broadcast_sender/main.cpp
toivjon/multiplatform-sockets
f2c204e36ddebb698fc07d4d41ec0e1824b6712e
[ "MIT" ]
null
null
null
examples/broadcast_sender/main.cpp
toivjon/multiplatform-sockets
f2c204e36ddebb698fc07d4d41ec0e1824b6712e
[ "MIT" ]
null
null
null
examples/broadcast_sender/main.cpp
toivjon/multiplatform-sockets
f2c204e36ddebb698fc07d4d41ec0e1824b6712e
[ "MIT" ]
null
null
null
#include "mps.h" #include <chrono> #include <iostream> #include <thread> using namespace mps; constexpr auto MessageCount = 100; constexpr auto MessageInterval = std::chrono::seconds(1); int main(int argc, char* argv[]) { // sanity check to check that we have enough arguments. if (argc != 3) { std::cout << "Usage: <executable> <broadcast-ip> <broadcast-port>" << std::endl; return -1; } try { // parse host and port from the commandline arguments. auto host = std::string(argv[1]); auto port = std::stoi(argv[2]); auto broadcastAddr = Address(host, port); // build and bind a new UDP socket and enable broadcasting. UDPSocket socket(broadcastAddr.getFamily()); socket.setBroadcasting(true); // broadcast messages N-times with the provided interval. std::cout << "Starting UDP broadcast to "; std::cout << broadcastAddr.getAddress(); std::cout << ":"; std::cout << broadcastAddr.getPort(); std::cout << std::endl; for (auto i = MessageCount; i > 0; i--) { socket.send(UDPPacket{ broadcastAddr, {'p','i','n','g','\0'} }); std::cout << "[ping]" << std::endl; std::this_thread::sleep_for(MessageInterval); } } catch (const AddressException& e){ std::cerr << "Error: " << e.what() << std::endl; } catch (const SocketException& e) { std::cerr << "Error: " << e.what() << std::endl; } return 0; }
29.978723
84
0.623847
toivjon
62e13304ec181f0310e516012ce590692c08d901
816
cpp
C++
src/core/hooks/vmt.cpp
Metaphysical1/gamesneeze
59d31ee232bbcc80d29329e0f64ebdde599c37df
[ "MIT" ]
1,056
2020-11-17T11:49:12.000Z
2022-03-23T12:32:42.000Z
src/core/hooks/vmt.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
102
2021-01-15T12:05:18.000Z
2022-02-26T00:19:58.000Z
src/core/hooks/vmt.cpp
dweee/gamesneeze
99f574db2617263470280125ec78afa813f27099
[ "MIT" ]
121
2020-11-18T12:08:21.000Z
2022-03-31T07:14:32.000Z
#include "vmt.hpp" #include <stdint.h> #include <unistd.h> #include <sys/mman.h> int pagesize = sysconf(_SC_PAGE_SIZE); int pagemask = ~(pagesize-1); int unprotect(void* region) { mprotect((void*) ((intptr_t)region & pagemask), pagesize, PROT_READ|PROT_WRITE|PROT_EXEC); return PROT_READ|PROT_EXEC; } void protect(void* region, int protection) { mprotect((void*) ((intptr_t)region & pagemask), pagesize, protection); } void* VMT::hook(void* instance, void* hook, int offset) { intptr_t vtable = *((intptr_t*)instance); intptr_t entry = vtable + sizeof(intptr_t) * offset; intptr_t original = *((intptr_t*) entry); int originalProtection = unprotect((void*)entry); *((intptr_t*)entry) = (intptr_t)hook; protect((void*)entry, originalProtection); return (void*)original; }
29.142857
94
0.689951
Metaphysical1
62e8b82ae340868a4bdd8ab29df1733b2677d8a7
6,723
hpp
C++
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
6
2015-01-07T17:29:40.000Z
2019-03-28T15:18:27.000Z
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
2
2017-04-12T19:01:21.000Z
2017-04-14T16:18:38.000Z
include/boost/numpy/dstream/detail/caller.hpp
IceCube-SPNO/BoostNumpy
66538c0b6e38e2f985e0b44d8191c878cea0332d
[ "BSL-1.0" ]
2
2018-01-15T07:32:24.000Z
2020-10-14T02:55:55.000Z
/** * $Id$ * * Copyright (C) * 2014 - $Date$ * Martin Wolf <boostnumpy@martin-wolf.org> * This file has been adopted from <boost/python/detail/caller.hpp>. * * @file boost/numpy/dstream/detail/caller.hpp * @version $Revision$ * @date $Date$ * @author Martin Wolf <boostnumpy@martin-wolf.org> * * @brief This file defines the caller template that is used as the caller * implementation for boost::python of boost::numpy generalized universal * functions. * * This file is 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). */ #if !defined(BOOST_PP_IS_ITERATING) #ifndef BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #define BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #include <boost/preprocessor/cat.hpp> #include <boost/preprocessor/dec.hpp> #include <boost/preprocessor/if.hpp> #include <boost/preprocessor/iterate.hpp> #include <boost/preprocessor/facilities/intercept.hpp> #include <boost/preprocessor/repetition/enum_trailing_params.hpp> #include <boost/preprocessor/repetition/enum_trailing_binary_params.hpp> #include <boost/preprocessor/repetition/repeat.hpp> #include <boost/mpl/int.hpp> #include <boost/mpl/next.hpp> #include <boost/mpl/size.hpp> // For this dedicated caller, we use function templates from the boost::python // caller. #include <boost/python/detail/caller.hpp> #include <boost/numpy/limits.hpp> namespace boost { namespace numpy { namespace dstream { namespace detail { template <unsigned> struct invoke_arity; template <unsigned> struct caller_arity; // The +1 is for the class instance and the +2 is for the possible automatically // added extra arguments ("out" and "nthreads"). // The minimum input arity is forced to be 1 instead of 0 because a vectorized // function with no input is just non-sense. #define BOOST_PP_ITERATION_PARAMS_1 \ (3, (1, BOOST_NUMPY_LIMIT_INPUT_ARITY + 1 + 2, <boost/numpy/dstream/detail/caller.hpp>)) #include BOOST_PP_ITERATE() template <class Callable> struct caller_base_select { // Note: arity includes the class type if Callable::f_t is a member function // pointer. BOOST_STATIC_CONSTANT(unsigned, arity = boost::mpl::size<typename Callable::signature_t>::value - 1); typedef typename caller_arity<arity>::template impl<Callable> type; }; template <class Callable> struct caller : caller_base_select<Callable>::type { typedef typename caller_base_select<Callable>::type base; caller(Callable ca) : base(ca) {} }; }// namespace detail }// namespace dstream }// namespace numpy }// namespace boost #endif // ! BOOST_NUMPY_DSTREAM_DETAIL_CALLER_HPP_INCLUDED #else #define N BOOST_PP_ITERATION() template <> struct invoke_arity<N> { template <class RC, class Callable BOOST_PP_ENUM_TRAILING_PARAMS_Z(1, N, class AC)> inline static PyObject* invoke(RC const& rc, Callable const & ca BOOST_PP_ENUM_TRAILING_BINARY_PARAMS_Z(1, N, AC, & ac)) { return rc( ca(BOOST_PP_ENUM_BINARY_PARAMS_Z(1, N, ac, () BOOST_PP_INTERCEPT)) ); } }; template <> struct caller_arity<N> { template <class Callable> struct impl { // Since we will always take Python objects as arguments and return // Python objects, we will always use the default_call_policies as call // policies. typedef python::default_call_policies call_policies_t; impl(Callable ca) : m_callable(ca) {} PyObject* operator()(PyObject* args_, PyObject*) // eliminate // this // trailing // keyword dict { call_policies_t call_policies; typedef typename boost::mpl::begin<typename Callable::signature_t>::type first; //typedef typename first::type result_t; typedef typename python::detail::select_result_converter<call_policies_t, python::object>::type result_converter_t; typedef typename call_policies_t::argument_package argument_package_t; // Create argument from_python converter objects c#. argument_package_t inner_args(args_); #define BOOST_NUMPY_NEXT(init, name, n) \ typedef BOOST_PP_IF(n,typename boost::mpl::next< BOOST_PP_CAT(name,BOOST_PP_DEC(n)) >::type, init) name##n; #define BOOST_NUMPY_ARG_CONVERTER(n) \ BOOST_NUMPY_NEXT(typename boost::mpl::next<first>::type, arg_iter,n) \ typedef python::arg_from_python<BOOST_DEDUCED_TYPENAME BOOST_PP_CAT(arg_iter,n)::type> BOOST_PP_CAT(c_t,n); \ BOOST_PP_CAT(c_t,n) BOOST_PP_CAT(c,n)(python::detail::get(boost::mpl::int_<n>(), inner_args)); \ if(!BOOST_PP_CAT(c,n).convertible()) { \ return 0; \ } #define BOOST_NUMPY_DEF(z, n, data) \ BOOST_NUMPY_ARG_CONVERTER(n) BOOST_PP_REPEAT(N, BOOST_NUMPY_DEF, ~) #undef BOOST_NUMPY_DEF #undef BOOST_NUMPY_ARG_CONVERTER #undef BOOST_NUMPY_NEXT // All converters have been checked. Now we can do the // precall part of the policy. // Note: The precall of default_call_policies does nothing at all as // of boost::python <=1.55 but we keep this call for forward // compatibility and to follow the interface definition. if(!call_policies.precall(inner_args)) return 0; PyObject* result = invoke_arity<N>::invoke( python::detail::create_result_converter(args_, (result_converter_t*)0, (result_converter_t*)0) , m_callable BOOST_PP_ENUM_TRAILING_PARAMS(N, c) ); // Note: the postcall of default_call_policies does nothing at all // as of boost::python <=1.55 but we keep this call for // forward compatibility and to follow the interface // definition. return call_policies.postcall(inner_args, result); } static unsigned min_arity() { return N; } private: Callable m_callable; }; }; #undef N #endif // BOOST_PP_IS_ITERATING
34.834197
125
0.62844
IceCube-SPNO
62ecbe261582bd004825d91639ba33c012f6258a
2,604
cpp
C++
SysLib/Demand/Files/Matrix_File.cpp
kravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
2
2018-04-27T11:07:02.000Z
2020-04-24T06:53:21.000Z
SysLib/Demand/Files/Matrix_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
SysLib/Demand/Files/Matrix_File.cpp
idkravitz/transims4
ea0848bf3dc71440d54724bb3ecba3947b982215
[ "NASA-1.3" ]
null
null
null
//********************************************************* // Matrix_File.cpp - Matrix File Input/Output //********************************************************* #include "Matrix_File.hpp" //----------------------------------------------------------- // Matrix_File constructors //----------------------------------------------------------- Matrix_File::Matrix_File (Access_Type access, Format_Type format) : Db_Header (access, format) { Setup (); } Matrix_File::Matrix_File (char *filename, Access_Type access, Format_Type format) : Db_Header (access, format) { Setup (); Open (filename); } //----------------------------------------------------------- // Matrix_File destructor //----------------------------------------------------------- Matrix_File::~Matrix_File (void) { } //----------------------------------------------------------- // Setup //----------------------------------------------------------- void Matrix_File::Setup (void) { File_Type ("Matrix File"); File_ID ("Matrix"); Period_Flag (false); org = des = period = data = 0; } //--------------------------------------------------------- // Create_Fields //--------------------------------------------------------- bool Matrix_File::Create_Fields (void) { if (Dbase_Format () == VERSION3) { Header_Lines (0); } Add_Field ("ORG", INTEGER, 5); Add_Field ("DES", INTEGER, 5); if (Period_Flag ()) { Add_Field ("PERIOD", INTEGER, 3); } Add_Field ("DATA", INTEGER, 10); return (Set_Field_Numbers ()); } //----------------------------------------------------------- // Set_Field_Numbers //----------------------------------------------------------- bool Matrix_File::Set_Field_Numbers (void) { //---- required fields ---- org = Required_Field ("ORG", "ORIGIN", "FROM", "FROM_ZONE", "I"); des = Required_Field ("DES", "DESTINATION", "TO", "TO_ZONE", "J"); if (!org || !des) return (false); //---- optional fields ---- period = Optional_Field ("PERIOD", "INTERVAL"); period_flag = (period != 0); data = Optional_Field ("DATA", "TRIPS"); if (data == 0) { if (Num_Fields () > 2 && org == 1 && des == 2) { if (period == 3) { data = 4; } else { data = 3; } } else { Required_Field ("DATA", "TRIPS"); return (false); } } return (true); } //----------------------------------------------------------- // Default_Definition //----------------------------------------------------------- bool Matrix_File::Default_Definition (void) { if (Dbase_Format () == VERSION3) { Create_Fields (); return (Write_Def_Header (NULL)); } else { return (false); } }
22.448276
84
0.422043
kravitz
62eed194e14ec20219bfcc92913587fb6ffc1fd7
9,451
cc
C++
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
dcmtk-master2/dcmsr/libsrc/dsrtpltn.cc
happymanx/Weather_FFI
a7f9bf8f1bda2b50c9d9a875c08fccf58379ad9f
[ "MIT" ]
null
null
null
/* * * Copyright (C) 2015-2018, J. Riesmeier, Oldenburg, Germany * All rights reserved. See COPYRIGHT file for details. * * This software and supporting documentation are maintained by * * OFFIS e.V. * R&D Division Health * Escherweg 2 * D-26121 Oldenburg, Germany * * * Module: dcmsr * * Author: Joerg Riesmeier * * Purpose: * classes: DSRIncludedTemplateTreeNode * */ #include "dcmtk/config/osconfig.h" /* make sure OS specific configuration is included first */ #include "dcmtk/dcmsr/dsrtypes.h" #include "dcmtk/dcmsr/dsrtpltn.h" #include "dcmtk/dcmsr/dsrstpl.h" #include "dcmtk/dcmsr/dsrxmld.h" DSRIncludedTemplateTreeNode::DSRIncludedTemplateTreeNode(const DSRSharedSubTemplate &referencedTemplate, const E_RelationshipType defaultRelType) : DSRDocumentTreeNode(defaultRelType, VT_includedTemplate), ReferencedTemplate(referencedTemplate) { if (ReferencedTemplate) { /* store template identification of the referenced template */ DSRDocumentTreeNode::setTemplateIdentification(ReferencedTemplate->getTemplateIdentifier(), ReferencedTemplate->getMappingResource(), ReferencedTemplate->getMappingResourceUID()); } } DSRIncludedTemplateTreeNode::DSRIncludedTemplateTreeNode(const DSRIncludedTemplateTreeNode &node) : DSRDocumentTreeNode(node), ReferencedTemplate(node.ReferencedTemplate) { } DSRIncludedTemplateTreeNode::~DSRIncludedTemplateTreeNode() { } OFBool DSRIncludedTemplateTreeNode::operator==(const DSRDocumentTreeNode &node) const { /* call comparison operator of base class (includes check of value type) */ OFBool result = DSRDocumentTreeNode::operator==(node); if (result) { /* it's safe to cast the type since the value type has already been checked */ result = (ReferencedTemplate.get() == OFstatic_cast(const DSRIncludedTemplateTreeNode &, node).ReferencedTemplate.get()); } return result; } OFBool DSRIncludedTemplateTreeNode::operator!=(const DSRDocumentTreeNode &node) const { /* call comparison operator of base class (includes check of value type) */ OFBool result = DSRDocumentTreeNode::operator!=(node); if (!result) { /* it's safe to cast the type since the value type has already been checked */ result = (ReferencedTemplate.get() != OFstatic_cast(const DSRIncludedTemplateTreeNode &, node).ReferencedTemplate.get()); } return result; } DSRIncludedTemplateTreeNode *DSRIncludedTemplateTreeNode::clone() const { return new DSRIncludedTemplateTreeNode(*this); } void DSRIncludedTemplateTreeNode::clear() { DSRDocumentTreeNode::clear(); ReferencedTemplate.reset(); } OFBool DSRIncludedTemplateTreeNode::isValid() const { return DSRDocumentTreeNode::isValid() && hasValidValue(); } OFBool DSRIncludedTemplateTreeNode::hasValidValue() const { /* check whether the reference to the included template is valid */ return ReferencedTemplate ? OFTrue : OFFalse; } OFBool DSRIncludedTemplateTreeNode::isShort(const size_t /*flags*/) const { return !hasValidValue(); } OFCondition DSRIncludedTemplateTreeNode::print(STD_NAMESPACE ostream &stream, const size_t flags) const { stream << "# INCLUDE "; /* check whether template identification is set */ if (hasTemplateIdentification()) { OFString templateIdentifier, mappingResource; getTemplateIdentification(templateIdentifier, mappingResource); stream << "TID " << templateIdentifier << " (" << mappingResource << ")"; } else { /* no details on the template available */ stream << "<unknown template>"; } /* check whether default relationship type is specified */ if (getRelationshipType() != RT_unknown) stream << " with default relationship type " << relationshipTypeToDefinedTerm(getRelationshipType()); /* print annotation (optional) */ if (hasAnnotation() && (flags & PF_printAnnotation)) stream << " \"" << getAnnotation().getText() << "\""; return EC_Normal; } OFCondition DSRIncludedTemplateTreeNode::writeXML(STD_NAMESPACE ostream &stream, const size_t flags) const { OFCondition result = EC_Normal; /* write content of included template in XML format (if non-empty) */ if (hasValidValue() && !ReferencedTemplate->isEmpty()) { OFString templateIdentifier, mappingResource; /* output details on beginning of included template (if enabled) */ if (hasTemplateIdentification() && (flags & XF_addCommentsForIncludedTemplate)) { getTemplateIdentification(templateIdentifier, mappingResource); stream << "<!-- BEGIN: included template TID " << templateIdentifier << " (" << mappingResource << ") -->" << OFendl; } /* write content of referenced document subtree */ result = ReferencedTemplate->writeXML(stream, flags); /* output details on end of included template (if available, see above) */ if (!templateIdentifier.empty() && !mappingResource.empty()) stream << "<!-- END: included template TID " << templateIdentifier << " (" << mappingResource << ") -->" << OFendl; } return result; } OFCondition DSRIncludedTemplateTreeNode::setValue(const DSRSharedSubTemplate &referencedTemplate) { ReferencedTemplate = referencedTemplate; /* currently, no checks are performed */ return EC_Normal; } // protected methods OFCondition DSRIncludedTemplateTreeNode::read(DcmItem & /*dataset*/, const DSRIODConstraintChecker * /*constraintChecker*/, const size_t /*flags*/) { /* invalid: cannot read document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::write(DcmItem & /*dataset*/, DcmStack * /*markedItems*/) { /* invalid: cannot write document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::readXML(const DSRXMLDocument & /*doc*/, DSRXMLCursor /*cursor*/, const E_DocumentType /*documentType*/, const size_t /*flags*/) { /* invalid: cannot read document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::renderHTML(STD_NAMESPACE ostream & /*docStream*/, STD_NAMESPACE ostream & /*annexStream*/, const size_t /*nestingLevel*/, size_t & /*annexNumber*/, const size_t /*flags*/) const { /* invalid: cannot render document with included templates */ return SR_EC_CannotProcessIncludedTemplates; } OFCondition DSRIncludedTemplateTreeNode::setConceptName(const DSRCodedEntryValue & /*conceptName*/, const OFBool /*check*/) { /* invalid: no concept name allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(const OFString & /*observationDateTime*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(const DcmElement & /*delem*/, const unsigned long /*pos*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationDateTime(DcmItem & /*dataset*/, const DcmTagKey & /*tagKey*/, const unsigned long /*pos*/, const OFBool /*check*/) { /* invalid: no observation date/time allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setObservationUID(const OFString & /*observationUID*/, const OFBool /*check*/) { /* invalid: no observation unique identifier allowed */ return EC_IllegalCall; } OFCondition DSRIncludedTemplateTreeNode::setTemplateIdentification(const OFString & /*templateIdentifier*/, const OFString & /*mappingResource*/, const OFString & /*mappingResourceUID*/, const OFBool /*check*/) { /* invalid: no manual setting of template identification allowed */ return EC_IllegalCall; }
35.799242
129
0.611575
happymanx
62f634551b97e38323aebd4169816d37be6f3994
5,049
cc
C++
Chapter20_08.cc
ucarlos/Programming-Principles-Chapter20
3bea0db2693eb7dd00a1071bb6bf0d392e4961ff
[ "MIT" ]
null
null
null
Chapter20_08.cc
ucarlos/Programming-Principles-Chapter20
3bea0db2693eb7dd00a1071bb6bf0d392e4961ff
[ "MIT" ]
null
null
null
Chapter20_08.cc
ucarlos/Programming-Principles-Chapter20
3bea0db2693eb7dd00a1071bb6bf0d392e4961ff
[ "MIT" ]
null
null
null
/* * ----------------------------------------------------------------------------- * Created by Ulysses Carlos on 03/25/2020 at 10:57 PM * * Chapter20_08.cc * * Define a function that counts the number of characters in a Document. * ----------------------------------------------------------------------------- */ #include <iostream> #include <list> #include <vector> #include <algorithm> #include <iterator> #include <cstdint> #include <experimental/filesystem> #include <fstream> #include <memory> using namespace std; using Line = vector<char>; string file_name = "../Navy Seals Copypasta.txt"; string alt_file_name = "./Navy Seals Copypasta.txt"; void handle_file(ifstream &is){ // If file_name exists, then open it. if (experimental::filesystem::exists(file_name)) is.open(file_name, ios_base::in); else if (experimental::filesystem::exists(alt_file_name)) is.open(alt_file_name, ios_base::in); else{ string error = "Could not find " + file_name + " or " + alt_file_name + " . Exiting."; throw runtime_error(error); } } //------------------------------------------------------------------------------ // Text_iterator //------------------------------------------------------------------------------ class Text_iterator : public std::iterator<std::bidirectional_iterator_tag, char, char, const long*, long>{ list<Line>::iterator ln; Line::iterator pos; public: Text_iterator(list<Line>::iterator ll, Line::iterator pp) : ln{ll}, pos{pp} { } char& operator*() { return *pos; } Line::iterator get_position() { return pos;} Line& getLine() { return *ln; } Text_iterator& operator++(); Text_iterator& operator--(); bool operator==(const Text_iterator &other) const { return ln == other.ln && pos == other.pos; } bool operator!=(const Text_iterator &other) const { return !(*this == other); } }; Text_iterator& Text_iterator::operator++(){ ++pos; if (pos == (*ln).end()){ ++ln; pos = (*ln).begin(); } return *this; } Text_iterator& Text_iterator::operator--(){ if (pos == (*ln).begin()){ --ln; pos = (*ln).end(); } else --pos; return *this; } template<typename Iter> void my_advance(Iter &p, int n){ if (!n) return; if (n < 0){ for (int i = 0; i > n; i--) --p; } else{ for (int i = 0; i < n; i++) ++p; } } //------------------------------------------------------------------------------ // Document //------------------------------------------------------------------------------ struct Document{ list<Line> line; Document() { line.push_back(Line{}); } Text_iterator begin() { return Text_iterator(line.begin(), line.begin()->begin()); } Text_iterator end(){ auto last = line.end(); --last; return Text_iterator(last, last->end()); } }; istream& operator>>(istream &is, Document &d){ char stop = '~'; for (char ch; is.get(ch);){ if (ch == stop) // Break if null character is inputted. break; d.line.back().push_back(ch); // Add the character if (ch == '\n') d.line.push_back(Line{}); // Add another line. } if (d.line.back().size()) d.line.push_back(Line{}); // Add final empty line. return is; } bool match(Text_iterator p, Text_iterator &last, const string &s){ if (p == last) return false; for (auto i = 0; i < s.length() && p != last; i++){ if (*p == s[i]) ++p; else return false; } return true; } Text_iterator find_txt(Text_iterator first, Text_iterator last, const string& s){ if (s.size()==0) return last; // can’t find an empty string char first_char = s[0]; while (true) { auto p = find(first,last,first_char); if (p==last || match(p,last,s)) return p; first = ++p; // look at the next character } } Text_iterator find_and_replace_txt(Text_iterator first, Text_iterator last, const string &search, const string &replace){ Text_iterator result = find_txt(first, last, search); if (result == last) return last; else{ auto start = result.get_position(); my_advance(start, 1); auto stop = result.get_position(); my_advance(stop, search.length()); result.getLine().erase(start, stop); *result = replace[0]; for (int i = 1; i < replace.size(); i++) result.getLine().push_back(replace[i]); return result; } } uint64_t count_characters(Text_iterator first, Text_iterator last){ uint64_t count = 0; while (first != last){ count++; ++first; } return count; } void print(Document &d){ for (char & p : d){ cout << p; } } int main(void){ Document d; ifstream is; handle_file(is); is >> d; // find_and_replace_txt(d.begin(), d.end(), "little bitch?", "miserable pile of secrets?"); // find_and_replace_txt(d.begin(), d.end(), "bitch?", "HARLOT?"); is.close(); uint64_t value = count_characters(d.begin(), d.end()); cout << "Number of characters in Document: " << value << endl; }
23.375
107
0.55199
ucarlos
62f8a945d1122a19d6a5aba08b02631a769d9347
2,742
cpp
C++
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
texture_handler.cpp
paracelso93/rocket-simulator
746469b2ffea032bed5793ef499eba0cd443240d
[ "MIT" ]
null
null
null
#include "texture_handler.h" TextureHandler* TextureHandler::mInstance = nullptr; bool TextureHandler::add_texture(const std::string& filePath, texture_t& id, SDL_Renderer* renderer) { id = std::hash<std::string>()(filePath); if (mTextures.find(id) != mTextures.end()) { return true; } SDL_Surface* sur = IMG_Load(filePath.c_str()); LOG(sur, "load surface " + filePath); SDL_Texture* tex = SDL_CreateTextureFromSurface(renderer, sur); LOG(tex, "create texture " + filePath); mTextures[id] = tex; int w, h; SDL_QueryTexture(mTextures[id], nullptr, nullptr, &w, &h); //mSizes[id] = Vector2<float>(w, h); mSizes.insert(std::pair<texture_t, Vector2<float> >(id, Vector2<float>(w, h))); mSizes.insert(std::pair<texture_t, Vector2<float> >(id, Vector2<float>(0, 0))); return true; } SDL_Texture* TextureHandler::get_texture(texture_t id) { if (mTextures.find(id) != mTextures.end()) { return mTextures[id]; } std::cerr << "Unable to load " << std::to_string(id) << std::endl; return nullptr; } void TextureHandler::render(SDL_Renderer* renderer, texture_t id, const Vector2<float>& position, const Vector2<float>& scale, float rotation, const Vector2<float>& center, SDL_RendererFlip flip) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } SDL_Rect src; src.x = mPositions[id].x; src.y = mPositions[id].y; src.w = mSizes[id].x; src.h = mSizes[id].y; SDL_Rect dst; dst.x = position.x; dst.y = position.y; dst.w = mSizes[id].x * scale.x; dst.h = mSizes[id].y * scale.y; SDL_Point cen; cen.x = center.x; cen.y = center.y; SDL_RenderCopyEx(renderer, mTextures[id], &src, &dst, rotation, &cen, flip); } void TextureHandler::set_src_rect(texture_t id, const Vector2<float>& src) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } mSizes[id] = src; } void TextureHandler::set_src_position(texture_t id, const Vector2<float>& src) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return; } mPositions[id] = src; } bool TextureHandler::point_in_texture(const Vector2<float>& point, const Vector2<float>& position, texture_t id) { if (mTextures.find(id) == mTextures.end()) { std::cerr << "texture " << std::to_string(id) << " doesn't exists!" << std::endl; return false; } int w, h; SDL_QueryTexture(mTextures[id], nullptr, nullptr, &w, &h); return point_in_rectangle(point, position, Vector2<float>(static_cast<float>(w), static_cast<float>(h))); }
30.808989
197
0.659373
paracelso93
62fbaca3bfaa78e541b1665b57744139a23cba24
1,223
cpp
C++
318. Maximum Product of Word Lengths.cpp
rajeev-ranjan-au6/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
3
2020-12-30T00:29:59.000Z
2021-01-24T22:43:04.000Z
318. Maximum Product of Word Lengths.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
318. Maximum Product of Word Lengths.cpp
rajeevranjancom/Leetcode_Cpp
f64cd98ab96ec110f1c21393f418acf7d88473e8
[ "MIT" ]
null
null
null
// Solution 1. Straight forward, 165ms class Solution { public: int maxProduct(vector<string>& words) { int maxlen = 0; for(int i = 0; i < words.size(); i++) for(int j = i + 1; j < words.size(); j++){ if(words[i].size() * words[j].size() <= maxlen) continue; if(noCommon(words[i], words[j])) maxlen = max(maxlen, (int)(words[i].size() * words[j].size())); } return maxlen; } bool noCommon(string& a, string& b){ for(auto x: a) for(auto y: b) if(x == y) return false; return true; } }; // Solution 2. Bit Manipulation, 43ms class Solution { public: int maxProduct(vector<string>& words) { int maxlen = 0; vector<int>val(words.size()); for(int i = 0; i < words.size(); i++) for(auto c: words[i]) val[i] |= (1 << (c - 'a')); for(int i = 0; i < words.size(); i++) for(int j = i + 1; j < words.size(); j++) if((val[i] & val[j]) == 0 && words[i].size() * words[j].size() > maxlen) maxlen = max(maxlen, (int)(words[i].size() * words[j].size())); return maxlen; } };
32.184211
112
0.472608
rajeev-ranjan-au6
62fdd32bf4578aadeef43d6531ee0cdb52538338
2,264
hh
C++
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
include/io/ssl.hh
king1600/Valk
b376a0dcce522ae03ced7d882835e4dea98df86e
[ "MIT" ]
null
null
null
#pragma once #include <boost/asio.hpp> #include <boost/asio/ssl.hpp> #include <boost/asio/ip/tcp.hpp> namespace io { namespace asio = boost::asio; namespace ssl = asio::ssl; typedef asio::ip::tcp tcp; typedef boost::system::error_code error_code; static const error_code Success = boost::system::errc::make_error_code( boost::system::errc::success); class Timer { private: asio::deadline_timer timer; std::function<void(Timer*)> timer_cb; public: void *data; Timer(asio::io_service& service); void cancel(); void async(const long ms, const std::function<void(Timer*)> &cb); }; class Service { private: std::shared_ptr<tcp::resolver> resolver; std::shared_ptr<ssl::context> ssl_ctx; std::shared_ptr<asio::io_service> loop; public: Service(); void Run(); ssl::context& getContext(); asio::io_service& getService(); Timer* createTimer(); Timer* spawn(const long ms, void *data, const std::function<void(Timer*)> &cb); void Resolve(const std::string &host, int port, std::function<void(const error_code&, tcp::resolver::iterator)> cb); }; class SSLClient { private: Service &service; bool connected = false; std::vector<char> builder; std::array<char, 8192> buffer; std::shared_ptr<ssl::stream<tcp::socket>> sock; std::function<void(const error_code&)> on_close; std::function<void(const error_code&)> on_connect; std::function<void(const std::vector<char>&)> on_read; void _read_handler(const error_code&, std::size_t); void _connect_handler(const error_code&, tcp::resolver::iterator, std::function<void(const error_code&)> callback); void _connect(const tcp::endpoint&, tcp::resolver::iterator&, std::function<void(const error_code&)> callback); public: SSLClient(Service& loop); void Connect(const std::string& host, int port); void Send(const char* data, const std::size_t len); void Close(const error_code& err, bool callback = true); const bool isConnected() const; void onClose(std::function<void(const error_code&)>); void onConnect(std::function<void(const error_code&)>); void onRead(std::function<void(const std::vector<char>&)>); }; }
28.3
83
0.673587
king1600
1a00460bc973876f44572786544f572a32f203f7
103,251
cpp
C++
platform_bionic-android-vts-12.0_r2/tests/pthread_test.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
1
2019-05-04T02:30:08.000Z
2019-05-04T02:30:08.000Z
platform_bionic-android-vts-12.0_r2/tests/pthread_test.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
platform_bionic-android-vts-12.0_r2/tests/pthread_test.cpp
webos21/xbionic
ffb3965e86ae4a921d0cffbfdc44cbdfe6acf67a
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2012 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <gtest/gtest.h> #include <errno.h> #include <inttypes.h> #include <limits.h> #include <malloc.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <sys/mman.h> #include <sys/prctl.h> #include <sys/resource.h> #include <sys/syscall.h> #include <time.h> #include <unistd.h> #include <unwind.h> #include <atomic> #include <future> #include <vector> #include <android-base/macros.h> #include <android-base/parseint.h> #include <android-base/scopeguard.h> #include <android-base/silent_death_test.h> #include <android-base/strings.h> #include "private/bionic_constants.h" #include "SignalUtils.h" #include "utils.h" using pthread_DeathTest = SilentDeathTest; TEST(pthread, pthread_key_create) { pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); ASSERT_EQ(0, pthread_key_delete(key)); // Can't delete a key that's already been deleted. ASSERT_EQ(EINVAL, pthread_key_delete(key)); } TEST(pthread, pthread_keys_max) { // POSIX says PTHREAD_KEYS_MAX should be at least _POSIX_THREAD_KEYS_MAX. ASSERT_GE(PTHREAD_KEYS_MAX, _POSIX_THREAD_KEYS_MAX); } TEST(pthread, sysconf_SC_THREAD_KEYS_MAX_eq_PTHREAD_KEYS_MAX) { int sysconf_max = sysconf(_SC_THREAD_KEYS_MAX); ASSERT_EQ(sysconf_max, PTHREAD_KEYS_MAX); } TEST(pthread, pthread_key_many_distinct) { // As gtest uses pthread keys, we can't allocate exactly PTHREAD_KEYS_MAX // pthread keys, but We should be able to allocate at least this many keys. int nkeys = PTHREAD_KEYS_MAX / 2; std::vector<pthread_key_t> keys; auto scope_guard = android::base::make_scope_guard([&keys] { for (const auto& key : keys) { EXPECT_EQ(0, pthread_key_delete(key)); } }); for (int i = 0; i < nkeys; ++i) { pthread_key_t key; // If this fails, it's likely that LIBC_PTHREAD_KEY_RESERVED_COUNT is wrong. ASSERT_EQ(0, pthread_key_create(&key, nullptr)) << i << " of " << nkeys; keys.push_back(key); ASSERT_EQ(0, pthread_setspecific(key, reinterpret_cast<void*>(i))); } for (int i = keys.size() - 1; i >= 0; --i) { ASSERT_EQ(reinterpret_cast<void*>(i), pthread_getspecific(keys.back())); pthread_key_t key = keys.back(); keys.pop_back(); ASSERT_EQ(0, pthread_key_delete(key)); } } TEST(pthread, pthread_key_not_exceed_PTHREAD_KEYS_MAX) { std::vector<pthread_key_t> keys; int rv = 0; // Pthread keys are used by gtest, so PTHREAD_KEYS_MAX should // be more than we are allowed to allocate now. for (int i = 0; i < PTHREAD_KEYS_MAX; i++) { pthread_key_t key; rv = pthread_key_create(&key, nullptr); if (rv == EAGAIN) { break; } EXPECT_EQ(0, rv); keys.push_back(key); } // Don't leak keys. for (const auto& key : keys) { EXPECT_EQ(0, pthread_key_delete(key)); } keys.clear(); // We should have eventually reached the maximum number of keys and received // EAGAIN. ASSERT_EQ(EAGAIN, rv); } TEST(pthread, pthread_key_delete) { void* expected = reinterpret_cast<void*>(1234); pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); ASSERT_EQ(0, pthread_setspecific(key, expected)); ASSERT_EQ(expected, pthread_getspecific(key)); ASSERT_EQ(0, pthread_key_delete(key)); // After deletion, pthread_getspecific returns nullptr. ASSERT_EQ(nullptr, pthread_getspecific(key)); // And you can't use pthread_setspecific with the deleted key. ASSERT_EQ(EINVAL, pthread_setspecific(key, expected)); } TEST(pthread, pthread_key_fork) { void* expected = reinterpret_cast<void*>(1234); pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); ASSERT_EQ(0, pthread_setspecific(key, expected)); ASSERT_EQ(expected, pthread_getspecific(key)); pid_t pid = fork(); ASSERT_NE(-1, pid) << strerror(errno); if (pid == 0) { // The surviving thread inherits all the forking thread's TLS values... ASSERT_EQ(expected, pthread_getspecific(key)); _exit(99); } AssertChildExited(pid, 99); ASSERT_EQ(expected, pthread_getspecific(key)); ASSERT_EQ(0, pthread_key_delete(key)); } static void* DirtyKeyFn(void* key) { return pthread_getspecific(*reinterpret_cast<pthread_key_t*>(key)); } TEST(pthread, pthread_key_dirty) { pthread_key_t key; ASSERT_EQ(0, pthread_key_create(&key, nullptr)); size_t stack_size = 640 * 1024; void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, stack); memset(stack, 0xff, stack_size); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setstack(&attr, stack, stack_size)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, DirtyKeyFn, &key)); void* result; ASSERT_EQ(0, pthread_join(t, &result)); ASSERT_EQ(nullptr, result); // Not ~0! ASSERT_EQ(0, munmap(stack, stack_size)); ASSERT_EQ(0, pthread_key_delete(key)); } TEST(pthread, static_pthread_key_used_before_creation) { #if defined(__BIONIC__) // See http://b/19625804. The bug is about a static/global pthread key being used before creation. // So here tests if the static/global default value 0 can be detected as invalid key. static pthread_key_t key; ASSERT_EQ(nullptr, pthread_getspecific(key)); ASSERT_EQ(EINVAL, pthread_setspecific(key, nullptr)); ASSERT_EQ(EINVAL, pthread_key_delete(key)); #else GTEST_SKIP() << "bionic-only test"; #endif } static void* IdFn(void* arg) { return arg; } class SpinFunctionHelper { public: SpinFunctionHelper() { SpinFunctionHelper::spin_flag_ = true; } ~SpinFunctionHelper() { UnSpin(); } auto GetFunction() -> void* (*)(void*) { return SpinFunctionHelper::SpinFn; } void UnSpin() { SpinFunctionHelper::spin_flag_ = false; } private: static void* SpinFn(void*) { while (spin_flag_) {} return nullptr; } static std::atomic<bool> spin_flag_; }; // It doesn't matter if spin_flag_ is used in several tests, // because it is always set to false after each test. Each thread // loops on spin_flag_ can find it becomes false at some time. std::atomic<bool> SpinFunctionHelper::spin_flag_; static void* JoinFn(void* arg) { return reinterpret_cast<void*>(pthread_join(reinterpret_cast<pthread_t>(arg), nullptr)); } static void AssertDetached(pthread_t t, bool is_detached) { pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(t, &attr)); int detach_state; ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &detach_state)); pthread_attr_destroy(&attr); ASSERT_EQ(is_detached, (detach_state == PTHREAD_CREATE_DETACHED)); } static void MakeDeadThread(pthread_t& t) { ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST(pthread, pthread_create) { void* expected_result = reinterpret_cast<void*>(123); // Can we create a thread? pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, IdFn, expected_result)); // If we join, do we get the expected value back? void* result; ASSERT_EQ(0, pthread_join(t, &result)); ASSERT_EQ(expected_result, result); } TEST(pthread, pthread_create_EAGAIN) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, static_cast<size_t>(-1) & ~(getpagesize() - 1))); pthread_t t; ASSERT_EQ(EAGAIN, pthread_create(&t, &attributes, IdFn, nullptr)); } TEST(pthread, pthread_no_join_after_detach) { SpinFunctionHelper spin_helper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr)); // After a pthread_detach... ASSERT_EQ(0, pthread_detach(t1)); AssertDetached(t1, true); // ...pthread_join should fail. ASSERT_EQ(EINVAL, pthread_join(t1, nullptr)); } TEST(pthread, pthread_no_op_detach_after_join) { SpinFunctionHelper spin_helper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr)); // If thread 2 is already waiting to join thread 1... pthread_t t2; ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1))); sleep(1); // (Give t2 a chance to call pthread_join.) #if defined(__BIONIC__) ASSERT_EQ(EINVAL, pthread_detach(t1)); #else ASSERT_EQ(0, pthread_detach(t1)); #endif AssertDetached(t1, false); spin_helper.UnSpin(); // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). void* join_result; ASSERT_EQ(0, pthread_join(t2, &join_result)); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); } TEST(pthread, pthread_join_self) { ASSERT_EQ(EDEADLK, pthread_join(pthread_self(), nullptr)); } struct TestBug37410 { pthread_t main_thread; pthread_mutex_t mutex; static void main() { TestBug37410 data; data.main_thread = pthread_self(); ASSERT_EQ(0, pthread_mutex_init(&data.mutex, nullptr)); ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, TestBug37410::thread_fn, reinterpret_cast<void*>(&data))); // Wait for the thread to be running... ASSERT_EQ(0, pthread_mutex_lock(&data.mutex)); ASSERT_EQ(0, pthread_mutex_unlock(&data.mutex)); // ...and exit. pthread_exit(nullptr); } private: static void* thread_fn(void* arg) { TestBug37410* data = reinterpret_cast<TestBug37410*>(arg); // Unlocking data->mutex will cause the main thread to exit, invalidating *data. Save the handle. pthread_t main_thread = data->main_thread; // Let the main thread know we're running. pthread_mutex_unlock(&data->mutex); // And wait for the main thread to exit. pthread_join(main_thread, nullptr); return nullptr; } }; // Even though this isn't really a death test, we have to say "DeathTest" here so gtest knows to // run this test (which exits normally) in its own process. TEST_F(pthread_DeathTest, pthread_bug_37410) { // http://code.google.com/p/android/issues/detail?id=37410 ASSERT_EXIT(TestBug37410::main(), ::testing::ExitedWithCode(0), ""); } static void* SignalHandlerFn(void* arg) { sigset64_t wait_set; sigfillset64(&wait_set); return reinterpret_cast<void*>(sigwait64(&wait_set, reinterpret_cast<int*>(arg))); } TEST(pthread, pthread_sigmask) { // Check that SIGUSR1 isn't blocked. sigset_t original_set; sigemptyset(&original_set); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &original_set)); ASSERT_FALSE(sigismember(&original_set, SIGUSR1)); // Block SIGUSR1. sigset_t set; sigemptyset(&set); sigaddset(&set, SIGUSR1); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, &set, nullptr)); // Check that SIGUSR1 is blocked. sigset_t final_set; sigemptyset(&final_set); ASSERT_EQ(0, pthread_sigmask(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); // ...and that sigprocmask agrees with pthread_sigmask. sigemptyset(&final_set); ASSERT_EQ(0, sigprocmask(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember(&final_set, SIGUSR1)); // Spawn a thread that calls sigwait and tells us what it received. pthread_t signal_thread; int received_signal = -1; ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal)); // Send that thread SIGUSR1. pthread_kill(signal_thread, SIGUSR1); // See what it got. void* join_result; ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); ASSERT_EQ(SIGUSR1, received_signal); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); // Restore the original signal mask. ASSERT_EQ(0, pthread_sigmask(SIG_SETMASK, &original_set, nullptr)); } TEST(pthread, pthread_sigmask64_SIGTRMIN) { // Check that SIGRTMIN isn't blocked. sigset64_t original_set; sigemptyset64(&original_set); ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &original_set)); ASSERT_FALSE(sigismember64(&original_set, SIGRTMIN)); // Block SIGRTMIN. sigset64_t set; sigemptyset64(&set); sigaddset64(&set, SIGRTMIN); ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, &set, nullptr)); // Check that SIGRTMIN is blocked. sigset64_t final_set; sigemptyset64(&final_set); ASSERT_EQ(0, pthread_sigmask64(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN)); // ...and that sigprocmask64 agrees with pthread_sigmask64. sigemptyset64(&final_set); ASSERT_EQ(0, sigprocmask64(SIG_BLOCK, nullptr, &final_set)); ASSERT_TRUE(sigismember64(&final_set, SIGRTMIN)); // Spawn a thread that calls sigwait64 and tells us what it received. pthread_t signal_thread; int received_signal = -1; ASSERT_EQ(0, pthread_create(&signal_thread, nullptr, SignalHandlerFn, &received_signal)); // Send that thread SIGRTMIN. pthread_kill(signal_thread, SIGRTMIN); // See what it got. void* join_result; ASSERT_EQ(0, pthread_join(signal_thread, &join_result)); ASSERT_EQ(SIGRTMIN, received_signal); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); // Restore the original signal mask. ASSERT_EQ(0, pthread_sigmask64(SIG_SETMASK, &original_set, nullptr)); } static void test_pthread_setname_np__pthread_getname_np(pthread_t t) { ASSERT_EQ(0, pthread_setname_np(t, "short")); char name[32]; ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name))); ASSERT_STREQ("short", name); // The limit is 15 characters --- the kernel's buffer is 16, but includes a NUL. ASSERT_EQ(0, pthread_setname_np(t, "123456789012345")); ASSERT_EQ(0, pthread_getname_np(t, name, sizeof(name))); ASSERT_STREQ("123456789012345", name); ASSERT_EQ(ERANGE, pthread_setname_np(t, "1234567890123456")); // The passed-in buffer should be at least 16 bytes. ASSERT_EQ(0, pthread_getname_np(t, name, 16)); ASSERT_EQ(ERANGE, pthread_getname_np(t, name, 15)); } TEST(pthread, pthread_setname_np__pthread_getname_np__self) { test_pthread_setname_np__pthread_getname_np(pthread_self()); } TEST(pthread, pthread_setname_np__pthread_getname_np__other) { SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); test_pthread_setname_np__pthread_getname_np(t); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } // http://b/28051133: a kernel misfeature means that you can't change the // name of another thread if you've set PR_SET_DUMPABLE to 0. TEST(pthread, pthread_setname_np__pthread_getname_np__other_PR_SET_DUMPABLE) { ASSERT_EQ(0, prctl(PR_SET_DUMPABLE, 0)) << strerror(errno); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); test_pthread_setname_np__pthread_getname_np(t); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST_F(pthread_DeathTest, pthread_setname_np__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_setname_np(dead_thread, "short 3"), "invalid pthread_t (.*) passed to pthread_setname_np"); } TEST_F(pthread_DeathTest, pthread_setname_np__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ENOENT, pthread_setname_np(null_thread, "short 3")); } TEST_F(pthread_DeathTest, pthread_getname_np__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); char name[64]; EXPECT_DEATH(pthread_getname_np(dead_thread, name, sizeof(name)), "invalid pthread_t (.*) passed to pthread_getname_np"); } TEST_F(pthread_DeathTest, pthread_getname_np__null_thread) { pthread_t null_thread = 0; char name[64]; EXPECT_EQ(ENOENT, pthread_getname_np(null_thread, name, sizeof(name))); } TEST(pthread, pthread_kill__0) { // Signal 0 just tests that the thread exists, so it's safe to call on ourselves. ASSERT_EQ(0, pthread_kill(pthread_self(), 0)); } TEST(pthread, pthread_kill__invalid_signal) { ASSERT_EQ(EINVAL, pthread_kill(pthread_self(), -1)); } static void pthread_kill__in_signal_handler_helper(int signal_number) { static int count = 0; ASSERT_EQ(SIGALRM, signal_number); if (++count == 1) { // Can we call pthread_kill from a signal handler? ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); } } TEST(pthread, pthread_kill__in_signal_handler) { ScopedSignalHandler ssh(SIGALRM, pthread_kill__in_signal_handler_helper); ASSERT_EQ(0, pthread_kill(pthread_self(), SIGALRM)); } TEST(pthread, pthread_kill__exited_thread) { static std::promise<pid_t> tid_promise; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, [](void*) -> void* { tid_promise.set_value(gettid()); return nullptr; }, nullptr)); pid_t tid = tid_promise.get_future().get(); while (TEMP_FAILURE_RETRY(syscall(__NR_tgkill, getpid(), tid, 0)) != -1) { continue; } ASSERT_EQ(ESRCH, errno); ASSERT_EQ(ESRCH, pthread_kill(thread, 0)); } TEST_F(pthread_DeathTest, pthread_detach__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_detach(dead_thread), "invalid pthread_t (.*) passed to pthread_detach"); } TEST_F(pthread_DeathTest, pthread_detach__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_detach(null_thread)); } TEST(pthread, pthread_getcpuclockid__clock_gettime) { SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, spin_helper.GetFunction(), nullptr)); clockid_t c; ASSERT_EQ(0, pthread_getcpuclockid(t, &c)); timespec ts; ASSERT_EQ(0, clock_gettime(c, &ts)); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST_F(pthread_DeathTest, pthread_getcpuclockid__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); clockid_t c; EXPECT_DEATH(pthread_getcpuclockid(dead_thread, &c), "invalid pthread_t (.*) passed to pthread_getcpuclockid"); } TEST_F(pthread_DeathTest, pthread_getcpuclockid__null_thread) { pthread_t null_thread = 0; clockid_t c; EXPECT_EQ(ESRCH, pthread_getcpuclockid(null_thread, &c)); } TEST_F(pthread_DeathTest, pthread_getschedparam__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); int policy; sched_param param; EXPECT_DEATH(pthread_getschedparam(dead_thread, &policy, &param), "invalid pthread_t (.*) passed to pthread_getschedparam"); } TEST_F(pthread_DeathTest, pthread_getschedparam__null_thread) { pthread_t null_thread = 0; int policy; sched_param param; EXPECT_EQ(ESRCH, pthread_getschedparam(null_thread, &policy, &param)); } TEST_F(pthread_DeathTest, pthread_setschedparam__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); int policy = 0; sched_param param; EXPECT_DEATH(pthread_setschedparam(dead_thread, policy, &param), "invalid pthread_t (.*) passed to pthread_setschedparam"); } TEST_F(pthread_DeathTest, pthread_setschedparam__null_thread) { pthread_t null_thread = 0; int policy = 0; sched_param param; EXPECT_EQ(ESRCH, pthread_setschedparam(null_thread, policy, &param)); } TEST_F(pthread_DeathTest, pthread_setschedprio__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_setschedprio(dead_thread, 123), "invalid pthread_t (.*) passed to pthread_setschedprio"); } TEST_F(pthread_DeathTest, pthread_setschedprio__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_setschedprio(null_thread, 123)); } TEST_F(pthread_DeathTest, pthread_join__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_join(dead_thread, nullptr), "invalid pthread_t (.*) passed to pthread_join"); } TEST_F(pthread_DeathTest, pthread_join__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_join(null_thread, nullptr)); } TEST_F(pthread_DeathTest, pthread_kill__no_such_thread) { pthread_t dead_thread; MakeDeadThread(dead_thread); EXPECT_DEATH(pthread_kill(dead_thread, 0), "invalid pthread_t (.*) passed to pthread_kill"); } TEST_F(pthread_DeathTest, pthread_kill__null_thread) { pthread_t null_thread = 0; EXPECT_EQ(ESRCH, pthread_kill(null_thread, 0)); } TEST(pthread, pthread_join__multijoin) { SpinFunctionHelper spin_helper; pthread_t t1; ASSERT_EQ(0, pthread_create(&t1, nullptr, spin_helper.GetFunction(), nullptr)); pthread_t t2; ASSERT_EQ(0, pthread_create(&t2, nullptr, JoinFn, reinterpret_cast<void*>(t1))); sleep(1); // (Give t2 a chance to call pthread_join.) // Multiple joins to the same thread should fail. ASSERT_EQ(EINVAL, pthread_join(t1, nullptr)); spin_helper.UnSpin(); // ...but t2's join on t1 still goes ahead (which we can tell because our join on t2 finishes). void* join_result; ASSERT_EQ(0, pthread_join(t2, &join_result)); ASSERT_EQ(0U, reinterpret_cast<uintptr_t>(join_result)); } TEST(pthread, pthread_join__race) { // http://b/11693195 --- pthread_join could return before the thread had actually exited. // If the joiner unmapped the thread's stack, that could lead to SIGSEGV in the thread. for (size_t i = 0; i < 1024; ++i) { size_t stack_size = 640*1024; void* stack = mmap(nullptr, stack_size, PROT_READ|PROT_WRITE, MAP_ANON|MAP_PRIVATE, -1, 0); pthread_attr_t a; pthread_attr_init(&a); pthread_attr_setstack(&a, stack, stack_size); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &a, IdFn, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); ASSERT_EQ(0, munmap(stack, stack_size)); } } static void* GetActualGuardSizeFn(void* arg) { pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); pthread_attr_getguardsize(&attributes, reinterpret_cast<size_t*>(arg)); return nullptr; } static size_t GetActualGuardSize(const pthread_attr_t& attributes) { size_t result; pthread_t t; pthread_create(&t, &attributes, GetActualGuardSizeFn, &result); pthread_join(t, nullptr); return result; } static void* GetActualStackSizeFn(void* arg) { pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); pthread_attr_getstacksize(&attributes, reinterpret_cast<size_t*>(arg)); return nullptr; } static size_t GetActualStackSize(const pthread_attr_t& attributes) { size_t result; pthread_t t; pthread_create(&t, &attributes, GetActualStackSizeFn, &result); pthread_join(t, nullptr); return result; } TEST(pthread, pthread_attr_setguardsize_tiny) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // No such thing as too small: will be rounded up to one page by pthread_create. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 128)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(128U, guard_size); ASSERT_EQ(4096U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setguardsize_reasonable) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Large enough and a multiple of the page size. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024U, guard_size); ASSERT_EQ(32*1024U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setguardsize_needs_rounding) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Large enough but not a multiple of the page size. ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024 + 1)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024U + 1, guard_size); ASSERT_EQ(36*1024U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setguardsize_enormous) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Larger than the stack itself. (Historically we mistakenly carved // the guard out of the stack itself, rather than adding it after the // end.) ASSERT_EQ(0, pthread_attr_setguardsize(&attributes, 32*1024*1024)); size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(32*1024*1024U, guard_size); ASSERT_EQ(32*1024*1024U, GetActualGuardSize(attributes)); } TEST(pthread, pthread_attr_setstacksize) { pthread_attr_t attributes; ASSERT_EQ(0, pthread_attr_init(&attributes)); // Get the default stack size. size_t default_stack_size; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &default_stack_size)); // Too small. ASSERT_EQ(EINVAL, pthread_attr_setstacksize(&attributes, 128)); size_t stack_size; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(default_stack_size, stack_size); ASSERT_GE(GetActualStackSize(attributes), default_stack_size); // Large enough and a multiple of the page size; may be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(32*1024U, stack_size); ASSERT_GE(GetActualStackSize(attributes), 32*1024U); // Large enough but not aligned; will be rounded up by pthread_create. ASSERT_EQ(0, pthread_attr_setstacksize(&attributes, 32*1024 + 1)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size)); ASSERT_EQ(32*1024U + 1, stack_size); #if defined(__BIONIC__) ASSERT_GT(GetActualStackSize(attributes), 32*1024U + 1); #else // __BIONIC__ // glibc rounds down, in violation of POSIX. They document this in their BUGS section. ASSERT_EQ(GetActualStackSize(attributes), 32*1024U); #endif // __BIONIC__ } TEST(pthread, pthread_rwlockattr_smoke) { pthread_rwlockattr_t attr; ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); int pshared_value_array[] = {PTHREAD_PROCESS_PRIVATE, PTHREAD_PROCESS_SHARED}; for (size_t i = 0; i < sizeof(pshared_value_array) / sizeof(pshared_value_array[0]); ++i) { ASSERT_EQ(0, pthread_rwlockattr_setpshared(&attr, pshared_value_array[i])); int pshared; ASSERT_EQ(0, pthread_rwlockattr_getpshared(&attr, &pshared)); ASSERT_EQ(pshared_value_array[i], pshared); } int kind_array[] = {PTHREAD_RWLOCK_PREFER_READER_NP, PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP}; for (size_t i = 0; i < sizeof(kind_array) / sizeof(kind_array[0]); ++i) { ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_array[i])); int kind; ASSERT_EQ(0, pthread_rwlockattr_getkind_np(&attr, &kind)); ASSERT_EQ(kind_array[i], kind); } ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); } TEST(pthread, pthread_rwlock_init_same_as_PTHREAD_RWLOCK_INITIALIZER) { pthread_rwlock_t lock1 = PTHREAD_RWLOCK_INITIALIZER; pthread_rwlock_t lock2; ASSERT_EQ(0, pthread_rwlock_init(&lock2, nullptr)); ASSERT_EQ(0, memcmp(&lock1, &lock2, sizeof(lock1))); } TEST(pthread, pthread_rwlock_smoke) { pthread_rwlock_t l; ASSERT_EQ(0, pthread_rwlock_init(&l, nullptr)); // Single read lock ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Multiple read lock ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Write lock ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try writer lock ASSERT_EQ(0, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try reader lock ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(0, pthread_rwlock_tryrdlock(&l)); ASSERT_EQ(EBUSY, pthread_rwlock_trywrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // Try writer lock after unlock ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // EDEADLK in "read after write" ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(EDEADLK, pthread_rwlock_rdlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); // EDEADLK in "write after write" ASSERT_EQ(0, pthread_rwlock_wrlock(&l)); ASSERT_EQ(EDEADLK, pthread_rwlock_wrlock(&l)); ASSERT_EQ(0, pthread_rwlock_unlock(&l)); ASSERT_EQ(0, pthread_rwlock_destroy(&l)); } struct RwlockWakeupHelperArg { pthread_rwlock_t lock; enum Progress { LOCK_INITIALIZED, LOCK_WAITING, LOCK_RELEASED, LOCK_ACCESSED, LOCK_TIMEDOUT, }; std::atomic<Progress> progress; std::atomic<pid_t> tid; std::function<int (pthread_rwlock_t*)> trylock_function; std::function<int (pthread_rwlock_t*)> lock_function; std::function<int (pthread_rwlock_t*, const timespec*)> timed_lock_function; clockid_t clock; }; static void pthread_rwlock_wakeup_helper(RwlockWakeupHelperArg* arg) { arg->tid = gettid(); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock)); ASSERT_EQ(0, arg->lock_function(&arg->lock)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_RELEASED, arg->progress); ASSERT_EQ(0, pthread_rwlock_unlock(&arg->lock)); arg->progress = RwlockWakeupHelperArg::LOCK_ACCESSED; } static void test_pthread_rwlock_reader_wakeup_writer(std::function<int (pthread_rwlock_t*)> lock_function) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_trywrlock; wakeup_arg.lock_function = lock_function; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_reader_wakeup_writer) { test_pthread_rwlock_reader_wakeup_writer(pthread_rwlock_wrlock); } TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait) { timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock(lock, &ts); }); } TEST(pthread, pthread_rwlock_reader_wakeup_writer_timedwait_monotonic_np) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer( [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedwrlock_monotonic_np(lock, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_reader_wakeup_writer_clockwait) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockwrlock(lock, CLOCK_MONOTONIC, &ts); }); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_reader_wakeup_writer([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockwrlock(lock, CLOCK_REALTIME, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockwrlock not available"; #endif // __BIONIC__ } static void test_pthread_rwlock_writer_wakeup_reader(std::function<int (pthread_rwlock_t*)> lock_function) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock; wakeup_arg.lock_function = lock_function; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_RELEASED; ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_ACCESSED, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_writer_wakeup_reader) { test_pthread_rwlock_writer_wakeup_reader(pthread_rwlock_rdlock); } TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait) { timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock(lock, &ts); }); } TEST(pthread, pthread_rwlock_writer_wakeup_reader_timedwait_monotonic_np) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader( [&](pthread_rwlock_t* lock) { return pthread_rwlock_timedrdlock_monotonic_np(lock, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_writer_wakeup_reader_clockwait) { #if defined(__BIONIC__) timespec ts; ASSERT_EQ(0, clock_gettime(CLOCK_MONOTONIC, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockrdlock(lock, CLOCK_MONOTONIC, &ts); }); ASSERT_EQ(0, clock_gettime(CLOCK_REALTIME, &ts)); ts.tv_sec += 1; test_pthread_rwlock_writer_wakeup_reader([&](pthread_rwlock_t* lock) { return pthread_rwlock_clockrdlock(lock, CLOCK_REALTIME, &ts); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } static void pthread_rwlock_wakeup_timeout_helper(RwlockWakeupHelperArg* arg) { arg->tid = gettid(); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_INITIALIZED, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_WAITING; ASSERT_EQ(EBUSY, arg->trylock_function(&arg->lock)); timespec ts; ASSERT_EQ(0, clock_gettime(arg->clock, &ts)); ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); ts.tv_nsec = -1; ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts)); ts.tv_nsec = NS_PER_S; ASSERT_EQ(EINVAL, arg->timed_lock_function(&arg->lock, &ts)); ts.tv_nsec = NS_PER_S - 1; ts.tv_sec = -1; ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); ASSERT_EQ(0, clock_gettime(arg->clock, &ts)); ts.tv_sec += 1; ASSERT_EQ(ETIMEDOUT, arg->timed_lock_function(&arg->lock, &ts)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, arg->progress); arg->progress = RwlockWakeupHelperArg::LOCK_TIMEDOUT; } static void pthread_rwlock_timedrdlock_timeout_helper( clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_wrlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_tryrdlock; wakeup_arg.timed_lock_function = lock_function; wakeup_arg.clock = clock; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_timedrdlock_timeout) { pthread_rwlock_timedrdlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedrdlock); } TEST(pthread, pthread_rwlock_timedrdlock_monotonic_np_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedrdlock_timeout_helper(CLOCK_MONOTONIC, pthread_rwlock_timedrdlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedrdlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockrdlock_monotonic_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedrdlock_timeout_helper( CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockrdlock(__rwlock, CLOCK_MONOTONIC, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockrdlock_realtime_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedrdlock_timeout_helper( CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockrdlock(__rwlock, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockrdlock_invalid) { #if defined(__BIONIC__) pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_rwlock_clockrdlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrdlock not available"; #endif // __BIONIC__ } static void pthread_rwlock_timedwrlock_timeout_helper( clockid_t clock, int (*lock_function)(pthread_rwlock_t* __rwlock, const timespec* __timeout)) { RwlockWakeupHelperArg wakeup_arg; ASSERT_EQ(0, pthread_rwlock_init(&wakeup_arg.lock, nullptr)); ASSERT_EQ(0, pthread_rwlock_rdlock(&wakeup_arg.lock)); wakeup_arg.progress = RwlockWakeupHelperArg::LOCK_INITIALIZED; wakeup_arg.tid = 0; wakeup_arg.trylock_function = &pthread_rwlock_trywrlock; wakeup_arg.timed_lock_function = lock_function; wakeup_arg.clock = clock; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_rwlock_wakeup_timeout_helper), &wakeup_arg)); WaitUntilThreadSleep(wakeup_arg.tid); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_WAITING, wakeup_arg.progress); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(RwlockWakeupHelperArg::LOCK_TIMEDOUT, wakeup_arg.progress); ASSERT_EQ(0, pthread_rwlock_unlock(&wakeup_arg.lock)); ASSERT_EQ(0, pthread_rwlock_destroy(&wakeup_arg.lock)); } TEST(pthread, pthread_rwlock_timedwrlock_timeout) { pthread_rwlock_timedwrlock_timeout_helper(CLOCK_REALTIME, pthread_rwlock_timedwrlock); } TEST(pthread, pthread_rwlock_timedwrlock_monotonic_np_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedwrlock_timeout_helper(CLOCK_MONOTONIC, pthread_rwlock_timedwrlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_timedwrlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockwrlock_monotonic_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedwrlock_timeout_helper( CLOCK_MONOTONIC, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockwrlock(__rwlock, CLOCK_MONOTONIC, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockwrlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockwrlock_realtime_timeout) { #if defined(__BIONIC__) pthread_rwlock_timedwrlock_timeout_helper( CLOCK_REALTIME, [](pthread_rwlock_t* __rwlock, const timespec* __timeout) { return pthread_rwlock_clockwrlock(__rwlock, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockwrlock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_rwlock_clockwrlock_invalid) { #if defined(__BIONIC__) pthread_rwlock_t lock = PTHREAD_RWLOCK_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_rwlock_clockwrlock(&lock, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_rwlock_clockrwlock not available"; #endif // __BIONIC__ } class RwlockKindTestHelper { private: struct ThreadArg { RwlockKindTestHelper* helper; std::atomic<pid_t>& tid; ThreadArg(RwlockKindTestHelper* helper, std::atomic<pid_t>& tid) : helper(helper), tid(tid) { } }; public: pthread_rwlock_t lock; public: explicit RwlockKindTestHelper(int kind_type) { InitRwlock(kind_type); } ~RwlockKindTestHelper() { DestroyRwlock(); } void CreateWriterThread(pthread_t& thread, std::atomic<pid_t>& tid) { tid = 0; ThreadArg* arg = new ThreadArg(this, tid); ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WriterThreadFn), arg)); } void CreateReaderThread(pthread_t& thread, std::atomic<pid_t>& tid) { tid = 0; ThreadArg* arg = new ThreadArg(this, tid); ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(ReaderThreadFn), arg)); } private: void InitRwlock(int kind_type) { pthread_rwlockattr_t attr; ASSERT_EQ(0, pthread_rwlockattr_init(&attr)); ASSERT_EQ(0, pthread_rwlockattr_setkind_np(&attr, kind_type)); ASSERT_EQ(0, pthread_rwlock_init(&lock, &attr)); ASSERT_EQ(0, pthread_rwlockattr_destroy(&attr)); } void DestroyRwlock() { ASSERT_EQ(0, pthread_rwlock_destroy(&lock)); } static void WriterThreadFn(ThreadArg* arg) { arg->tid = gettid(); RwlockKindTestHelper* helper = arg->helper; ASSERT_EQ(0, pthread_rwlock_wrlock(&helper->lock)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); delete arg; } static void ReaderThreadFn(ThreadArg* arg) { arg->tid = gettid(); RwlockKindTestHelper* helper = arg->helper; ASSERT_EQ(0, pthread_rwlock_rdlock(&helper->lock)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper->lock)); delete arg; } }; TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_READER_NP) { RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_READER_NP); ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); pthread_t writer_thread; std::atomic<pid_t> writer_tid; helper.CreateWriterThread(writer_thread, writer_tid); WaitUntilThreadSleep(writer_tid); pthread_t reader_thread; std::atomic<pid_t> reader_tid; helper.CreateReaderThread(reader_thread, reader_tid); ASSERT_EQ(0, pthread_join(reader_thread, nullptr)); ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); ASSERT_EQ(0, pthread_join(writer_thread, nullptr)); } TEST(pthread, pthread_rwlock_kind_PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP) { RwlockKindTestHelper helper(PTHREAD_RWLOCK_PREFER_WRITER_NONRECURSIVE_NP); ASSERT_EQ(0, pthread_rwlock_rdlock(&helper.lock)); pthread_t writer_thread; std::atomic<pid_t> writer_tid; helper.CreateWriterThread(writer_thread, writer_tid); WaitUntilThreadSleep(writer_tid); pthread_t reader_thread; std::atomic<pid_t> reader_tid; helper.CreateReaderThread(reader_thread, reader_tid); WaitUntilThreadSleep(reader_tid); ASSERT_EQ(0, pthread_rwlock_unlock(&helper.lock)); ASSERT_EQ(0, pthread_join(writer_thread, nullptr)); ASSERT_EQ(0, pthread_join(reader_thread, nullptr)); } static int g_once_fn_call_count = 0; static void OnceFn() { ++g_once_fn_call_count; } TEST(pthread, pthread_once_smoke) { pthread_once_t once_control = PTHREAD_ONCE_INIT; ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); ASSERT_EQ(0, pthread_once(&once_control, OnceFn)); ASSERT_EQ(1, g_once_fn_call_count); } static std::string pthread_once_1934122_result = ""; static void Routine2() { pthread_once_1934122_result += "2"; } static void Routine1() { pthread_once_t once_control_2 = PTHREAD_ONCE_INIT; pthread_once_1934122_result += "1"; pthread_once(&once_control_2, &Routine2); } TEST(pthread, pthread_once_1934122) { // Very old versions of Android couldn't call pthread_once from a // pthread_once init routine. http://b/1934122. pthread_once_t once_control_1 = PTHREAD_ONCE_INIT; ASSERT_EQ(0, pthread_once(&once_control_1, &Routine1)); ASSERT_EQ("12", pthread_once_1934122_result); } static int g_atfork_prepare_calls = 0; static void AtForkPrepare1() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 1; } static void AtForkPrepare2() { g_atfork_prepare_calls = (g_atfork_prepare_calls * 10) + 2; } static int g_atfork_parent_calls = 0; static void AtForkParent1() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 1; } static void AtForkParent2() { g_atfork_parent_calls = (g_atfork_parent_calls * 10) + 2; } static int g_atfork_child_calls = 0; static void AtForkChild1() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 1; } static void AtForkChild2() { g_atfork_child_calls = (g_atfork_child_calls * 10) + 2; } TEST(pthread, pthread_atfork_smoke) { ASSERT_EQ(0, pthread_atfork(AtForkPrepare1, AtForkParent1, AtForkChild1)); ASSERT_EQ(0, pthread_atfork(AtForkPrepare2, AtForkParent2, AtForkChild2)); pid_t pid = fork(); ASSERT_NE(-1, pid) << strerror(errno); // Child and parent calls are made in the order they were registered. if (pid == 0) { ASSERT_EQ(12, g_atfork_child_calls); _exit(0); } ASSERT_EQ(12, g_atfork_parent_calls); // Prepare calls are made in the reverse order. ASSERT_EQ(21, g_atfork_prepare_calls); AssertChildExited(pid, 0); } TEST(pthread, pthread_attr_getscope) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int scope; ASSERT_EQ(0, pthread_attr_getscope(&attr, &scope)); ASSERT_EQ(PTHREAD_SCOPE_SYSTEM, scope); } TEST(pthread, pthread_condattr_init) { pthread_condattr_t attr; pthread_condattr_init(&attr); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_REALTIME, clock); int pshared; ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); } TEST(pthread, pthread_condattr_setclock) { pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_REALTIME)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_REALTIME, clock); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); ASSERT_EQ(EINVAL, pthread_condattr_setclock(&attr, CLOCK_PROCESS_CPUTIME_ID)); } TEST(pthread, pthread_cond_broadcast__preserves_condattr_flags) { #if defined(__BIONIC__) pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); ASSERT_EQ(0, pthread_condattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); pthread_cond_t cond_var; ASSERT_EQ(0, pthread_cond_init(&cond_var, &attr)); ASSERT_EQ(0, pthread_cond_signal(&cond_var)); ASSERT_EQ(0, pthread_cond_broadcast(&cond_var)); attr = static_cast<pthread_condattr_t>(*reinterpret_cast<uint32_t*>(cond_var.__private)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); int pshared; ASSERT_EQ(0, pthread_condattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); #else // !defined(__BIONIC__) GTEST_SKIP() << "bionic-only test"; #endif // !defined(__BIONIC__) } class pthread_CondWakeupTest : public ::testing::Test { protected: pthread_mutex_t mutex; pthread_cond_t cond; enum Progress { INITIALIZED, WAITING, SIGNALED, FINISHED, }; std::atomic<Progress> progress; pthread_t thread; std::function<int (pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function; protected: void SetUp() override { ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr)); } void InitCond(clockid_t clock=CLOCK_REALTIME) { pthread_condattr_t attr; ASSERT_EQ(0, pthread_condattr_init(&attr)); ASSERT_EQ(0, pthread_condattr_setclock(&attr, clock)); ASSERT_EQ(0, pthread_cond_init(&cond, &attr)); ASSERT_EQ(0, pthread_condattr_destroy(&attr)); } void StartWaitingThread( std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex)> wait_function) { progress = INITIALIZED; this->wait_function = wait_function; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(WaitThreadFn), this)); while (progress != WAITING) { usleep(5000); } usleep(5000); } void RunTimedTest( clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout)> wait_function) { timespec ts; ASSERT_EQ(0, clock_gettime(clock, &ts)); ts.tv_sec += 1; StartWaitingThread([&wait_function, &ts](pthread_cond_t* cond, pthread_mutex_t* mutex) { return wait_function(cond, mutex, &ts); }); progress = SIGNALED; ASSERT_EQ(0, pthread_cond_signal(&cond)); } void RunTimedTest(clockid_t clock, std::function<int(pthread_cond_t* cond, pthread_mutex_t* mutex, clockid_t clock, const timespec* timeout)> wait_function) { RunTimedTest(clock, [clock, &wait_function](pthread_cond_t* cond, pthread_mutex_t* mutex, const timespec* timeout) { return wait_function(cond, mutex, clock, timeout); }); } void TearDown() override { ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(FINISHED, progress); ASSERT_EQ(0, pthread_cond_destroy(&cond)); ASSERT_EQ(0, pthread_mutex_destroy(&mutex)); } private: static void WaitThreadFn(pthread_CondWakeupTest* test) { ASSERT_EQ(0, pthread_mutex_lock(&test->mutex)); test->progress = WAITING; while (test->progress == WAITING) { ASSERT_EQ(0, test->wait_function(&test->cond, &test->mutex)); } ASSERT_EQ(SIGNALED, test->progress); test->progress = FINISHED; ASSERT_EQ(0, pthread_mutex_unlock(&test->mutex)); } }; TEST_F(pthread_CondWakeupTest, signal_wait) { InitCond(); StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) { return pthread_cond_wait(cond, mutex); }); progress = SIGNALED; ASSERT_EQ(0, pthread_cond_signal(&cond)); } TEST_F(pthread_CondWakeupTest, broadcast_wait) { InitCond(); StartWaitingThread([](pthread_cond_t* cond, pthread_mutex_t* mutex) { return pthread_cond_wait(cond, mutex); }); progress = SIGNALED; ASSERT_EQ(0, pthread_cond_broadcast(&cond)); } TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_REALTIME) { InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_REALTIME, pthread_cond_timedwait); } TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC) { InitCond(CLOCK_MONOTONIC); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait); } TEST_F(pthread_CondWakeupTest, signal_timedwait_CLOCK_MONOTONIC_np) { #if defined(__BIONIC__) InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_monotonic) { #if defined(__BIONIC__) InitCond(CLOCK_MONOTONIC); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_monotonic_realtime) { #if defined(__BIONIC__) InitCond(CLOCK_MONOTONIC); RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_monotonic) { #if defined(__BIONIC__) InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_MONOTONIC, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST_F(pthread_CondWakeupTest, signal_clockwait_realtime_realtime) { #if defined(__BIONIC__) InitCond(CLOCK_REALTIME); RunTimedTest(CLOCK_REALTIME, pthread_cond_clockwait); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } static void pthread_cond_timedwait_timeout_helper(bool init_monotonic, clockid_t clock, int (*wait_function)(pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout)) { pthread_mutex_t mutex; ASSERT_EQ(0, pthread_mutex_init(&mutex, nullptr)); pthread_cond_t cond; if (init_monotonic) { pthread_condattr_t attr; pthread_condattr_init(&attr); ASSERT_EQ(0, pthread_condattr_setclock(&attr, CLOCK_MONOTONIC)); clockid_t clock; ASSERT_EQ(0, pthread_condattr_getclock(&attr, &clock)); ASSERT_EQ(CLOCK_MONOTONIC, clock); ASSERT_EQ(0, pthread_cond_init(&cond, &attr)); } else { ASSERT_EQ(0, pthread_cond_init(&cond, nullptr)); } ASSERT_EQ(0, pthread_mutex_lock(&mutex)); timespec ts; ASSERT_EQ(0, clock_gettime(clock, &ts)); ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts)); ts.tv_nsec = -1; ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts)); ts.tv_nsec = NS_PER_S; ASSERT_EQ(EINVAL, wait_function(&cond, &mutex, &ts)); ts.tv_nsec = NS_PER_S - 1; ts.tv_sec = -1; ASSERT_EQ(ETIMEDOUT, wait_function(&cond, &mutex, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&mutex)); } TEST(pthread, pthread_cond_timedwait_timeout) { pthread_cond_timedwait_timeout_helper(false, CLOCK_REALTIME, pthread_cond_timedwait); } TEST(pthread, pthread_cond_timedwait_monotonic_np_timeout) { #if defined(__BIONIC__) pthread_cond_timedwait_timeout_helper(false, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); pthread_cond_timedwait_timeout_helper(true, CLOCK_MONOTONIC, pthread_cond_timedwait_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_timedwait_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_cond_clockwait_timeout) { #if defined(__BIONIC__) pthread_cond_timedwait_timeout_helper( false, CLOCK_MONOTONIC, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout); }); pthread_cond_timedwait_timeout_helper( true, CLOCK_MONOTONIC, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_MONOTONIC, __timeout); }); pthread_cond_timedwait_timeout_helper( false, CLOCK_REALTIME, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout); }); pthread_cond_timedwait_timeout_helper( true, CLOCK_REALTIME, [](pthread_cond_t* __cond, pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_cond_clockwait(__cond, __mutex, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST(pthread, pthread_cond_clockwait_invalid) { #if defined(__BIONIC__) pthread_cond_t cond = PTHREAD_COND_INITIALIZER; pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_cond_clockwait(&cond, &mutex, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_cond_clockwait not available"; #endif // __BIONIC__ } TEST(pthread, pthread_attr_getstack__main_thread) { // This test is only meaningful for the main thread, so make sure we're running on it! ASSERT_EQ(getpid(), syscall(__NR_gettid)); // Get the main thread's attributes. pthread_attr_t attributes; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); // Check that we correctly report that the main thread has no guard page. size_t guard_size; ASSERT_EQ(0, pthread_attr_getguardsize(&attributes, &guard_size)); ASSERT_EQ(0U, guard_size); // The main thread has no guard page. // Get the stack base and the stack size (both ways). void* stack_base; size_t stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); size_t stack_size2; ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); // The two methods of asking for the stack size should agree. EXPECT_EQ(stack_size, stack_size2); #if defined(__BIONIC__) // Find stack in /proc/self/maps using a pointer to the stack. // // We do not use "[stack]" label because in native-bridge environment it is not // guaranteed to point to the right stack. A native bridge implementation may // keep separate stack for the guest code. void* maps_stack_hi = nullptr; std::vector<map_record> maps; ASSERT_TRUE(Maps::parse_maps(&maps)); uintptr_t stack_address = reinterpret_cast<uintptr_t>(untag_address(&maps_stack_hi)); for (const auto& map : maps) { if (map.addr_start <= stack_address && map.addr_end > stack_address){ maps_stack_hi = reinterpret_cast<void*>(map.addr_end); break; } } // The high address of the /proc/self/maps stack region should equal stack_base + stack_size. // Remember that the stack grows down (and is mapped in on demand), so the low address of the // region isn't very interesting. EXPECT_EQ(maps_stack_hi, reinterpret_cast<uint8_t*>(stack_base) + stack_size); // The stack size should correspond to RLIMIT_STACK. rlimit rl; ASSERT_EQ(0, getrlimit(RLIMIT_STACK, &rl)); uint64_t original_rlim_cur = rl.rlim_cur; if (rl.rlim_cur == RLIM_INFINITY) { rl.rlim_cur = 8 * 1024 * 1024; // Bionic reports unlimited stacks as 8MiB. } EXPECT_EQ(rl.rlim_cur, stack_size); auto guard = android::base::make_scope_guard([&rl, original_rlim_cur]() { rl.rlim_cur = original_rlim_cur; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); }); // // What if RLIMIT_STACK is smaller than the stack's current extent? // rl.rlim_cur = rl.rlim_max = 1024; // 1KiB. We know the stack must be at least a page already. rl.rlim_max = RLIM_INFINITY; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); EXPECT_EQ(stack_size, stack_size2); ASSERT_EQ(1024U, stack_size); // // What if RLIMIT_STACK isn't a whole number of pages? // rl.rlim_cur = rl.rlim_max = 6666; // Not a whole number of pages. rl.rlim_max = RLIM_INFINITY; ASSERT_EQ(0, setrlimit(RLIMIT_STACK, &rl)); ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attributes)); ASSERT_EQ(0, pthread_attr_getstack(&attributes, &stack_base, &stack_size)); ASSERT_EQ(0, pthread_attr_getstacksize(&attributes, &stack_size2)); EXPECT_EQ(stack_size, stack_size2); ASSERT_EQ(6666U, stack_size); #endif } struct GetStackSignalHandlerArg { volatile bool done; void* signal_stack_base; size_t signal_stack_size; void* main_stack_base; size_t main_stack_size; }; static GetStackSignalHandlerArg getstack_signal_handler_arg; static void getstack_signal_handler(int sig) { ASSERT_EQ(SIGUSR1, sig); // Use sleep() to make current thread be switched out by the kernel to provoke the error. sleep(1); pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr)); void* stack_base; size_t stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attr, &stack_base, &stack_size)); // Verify if the stack used by the signal handler is the alternate stack just registered. ASSERT_LE(getstack_signal_handler_arg.signal_stack_base, &attr); ASSERT_LT(static_cast<void*>(untag_address(&attr)), static_cast<char*>(getstack_signal_handler_arg.signal_stack_base) + getstack_signal_handler_arg.signal_stack_size); // Verify if the main thread's stack got in the signal handler is correct. ASSERT_EQ(getstack_signal_handler_arg.main_stack_base, stack_base); ASSERT_LE(getstack_signal_handler_arg.main_stack_size, stack_size); getstack_signal_handler_arg.done = true; } // The previous code obtained the main thread's stack by reading the entry in // /proc/self/task/<pid>/maps that was labeled [stack]. Unfortunately, on x86/x86_64, the kernel // relies on sp0 in task state segment(tss) to label the stack map with [stack]. If the kernel // switches a process while the main thread is in an alternate stack, then the kernel will label // the wrong map with [stack]. This test verifies that when the above situation happens, the main // thread's stack is found correctly. TEST(pthread, pthread_attr_getstack_in_signal_handler) { // This test is only meaningful for the main thread, so make sure we're running on it! ASSERT_EQ(getpid(), syscall(__NR_gettid)); const size_t sig_stack_size = 16 * 1024; void* sig_stack = mmap(nullptr, sig_stack_size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); ASSERT_NE(MAP_FAILED, sig_stack); stack_t ss; ss.ss_sp = sig_stack; ss.ss_size = sig_stack_size; ss.ss_flags = 0; stack_t oss; ASSERT_EQ(0, sigaltstack(&ss, &oss)); pthread_attr_t attr; ASSERT_EQ(0, pthread_getattr_np(pthread_self(), &attr)); void* main_stack_base; size_t main_stack_size; ASSERT_EQ(0, pthread_attr_getstack(&attr, &main_stack_base, &main_stack_size)); ScopedSignalHandler handler(SIGUSR1, getstack_signal_handler, SA_ONSTACK); getstack_signal_handler_arg.done = false; getstack_signal_handler_arg.signal_stack_base = sig_stack; getstack_signal_handler_arg.signal_stack_size = sig_stack_size; getstack_signal_handler_arg.main_stack_base = main_stack_base; getstack_signal_handler_arg.main_stack_size = main_stack_size; kill(getpid(), SIGUSR1); ASSERT_EQ(true, getstack_signal_handler_arg.done); ASSERT_EQ(0, sigaltstack(&oss, nullptr)); ASSERT_EQ(0, munmap(sig_stack, sig_stack_size)); } static void pthread_attr_getstack_18908062_helper(void*) { char local_variable; pthread_attr_t attributes; pthread_getattr_np(pthread_self(), &attributes); void* stack_base; size_t stack_size; pthread_attr_getstack(&attributes, &stack_base, &stack_size); // Test whether &local_variable is in [stack_base, stack_base + stack_size). ASSERT_LE(reinterpret_cast<char*>(stack_base), &local_variable); ASSERT_LT(untag_address(&local_variable), reinterpret_cast<char*>(stack_base) + stack_size); } // Check whether something on stack is in the range of // [stack_base, stack_base + stack_size). see b/18908062. TEST(pthread, pthread_attr_getstack_18908062) { pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, reinterpret_cast<void* (*)(void*)>(pthread_attr_getstack_18908062_helper), nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); } #if defined(__BIONIC__) static pthread_mutex_t pthread_gettid_np_mutex = PTHREAD_MUTEX_INITIALIZER; static void* pthread_gettid_np_helper(void* arg) { *reinterpret_cast<pid_t*>(arg) = gettid(); // Wait for our parent to call pthread_gettid_np on us before exiting. pthread_mutex_lock(&pthread_gettid_np_mutex); pthread_mutex_unlock(&pthread_gettid_np_mutex); return nullptr; } #endif TEST(pthread, pthread_gettid_np) { #if defined(__BIONIC__) ASSERT_EQ(gettid(), pthread_gettid_np(pthread_self())); // Ensure the other thread doesn't exit until after we've called // pthread_gettid_np on it. pthread_mutex_lock(&pthread_gettid_np_mutex); pid_t t_gettid_result; pthread_t t; pthread_create(&t, nullptr, pthread_gettid_np_helper, &t_gettid_result); pid_t t_pthread_gettid_np_result = pthread_gettid_np(t); // Release the other thread and wait for it to exit. pthread_mutex_unlock(&pthread_gettid_np_mutex); ASSERT_EQ(0, pthread_join(t, nullptr)); ASSERT_EQ(t_gettid_result, t_pthread_gettid_np_result); #else GTEST_SKIP() << "pthread_gettid_np not available"; #endif } static size_t cleanup_counter = 0; static void AbortCleanupRoutine(void*) { abort(); } static void CountCleanupRoutine(void*) { ++cleanup_counter; } static void PthreadCleanupTester() { pthread_cleanup_push(CountCleanupRoutine, nullptr); pthread_cleanup_push(CountCleanupRoutine, nullptr); pthread_cleanup_push(AbortCleanupRoutine, nullptr); pthread_cleanup_pop(0); // Pop the abort without executing it. pthread_cleanup_pop(1); // Pop one count while executing it. ASSERT_EQ(1U, cleanup_counter); // Exit while the other count is still on the cleanup stack. pthread_exit(nullptr); // Calls to pthread_cleanup_pop/pthread_cleanup_push must always be balanced. pthread_cleanup_pop(0); } static void* PthreadCleanupStartRoutine(void*) { PthreadCleanupTester(); return nullptr; } TEST(pthread, pthread_cleanup_push__pthread_cleanup_pop) { pthread_t t; ASSERT_EQ(0, pthread_create(&t, nullptr, PthreadCleanupStartRoutine, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); ASSERT_EQ(2U, cleanup_counter); } TEST(pthread, PTHREAD_MUTEX_DEFAULT_is_PTHREAD_MUTEX_NORMAL) { ASSERT_EQ(PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_DEFAULT); } TEST(pthread, pthread_mutexattr_gettype) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); int attr_type; ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_NORMAL)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_NORMAL, attr_type); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_ERRORCHECK)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_ERRORCHECK, attr_type); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)); ASSERT_EQ(0, pthread_mutexattr_gettype(&attr, &attr_type)); ASSERT_EQ(PTHREAD_MUTEX_RECURSIVE, attr_type); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } TEST(pthread, pthread_mutexattr_protocol) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); int protocol; ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol)); ASSERT_EQ(PTHREAD_PRIO_NONE, protocol); for (size_t repeat = 0; repeat < 2; ++repeat) { for (int set_protocol : {PTHREAD_PRIO_NONE, PTHREAD_PRIO_INHERIT}) { ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, set_protocol)); ASSERT_EQ(0, pthread_mutexattr_getprotocol(&attr, &protocol)); ASSERT_EQ(protocol, set_protocol); } } } struct PthreadMutex { pthread_mutex_t lock; explicit PthreadMutex(int mutex_type, int protocol = PTHREAD_PRIO_NONE) { init(mutex_type, protocol); } ~PthreadMutex() { destroy(); } private: void init(int mutex_type, int protocol) { pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_settype(&attr, mutex_type)); ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, protocol)); ASSERT_EQ(0, pthread_mutex_init(&lock, &attr)); ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); } void destroy() { ASSERT_EQ(0, pthread_mutex_destroy(&lock)); } DISALLOW_COPY_AND_ASSIGN(PthreadMutex); }; static int UnlockFromAnotherThread(pthread_mutex_t* mutex) { pthread_t thread; pthread_create(&thread, nullptr, [](void* mutex_voidp) -> void* { pthread_mutex_t* mutex = static_cast<pthread_mutex_t*>(mutex_voidp); intptr_t result = pthread_mutex_unlock(mutex); return reinterpret_cast<void*>(result); }, mutex); void* result; EXPECT_EQ(0, pthread_join(thread, &result)); return reinterpret_cast<intptr_t>(result); }; static void TestPthreadMutexLockNormal(int protocol) { PthreadMutex m(PTHREAD_MUTEX_NORMAL, protocol); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); if (protocol == PTHREAD_PRIO_INHERIT) { ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); } ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); } static void TestPthreadMutexLockErrorCheck(int protocol) { PthreadMutex m(PTHREAD_MUTEX_ERRORCHECK, protocol); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); ASSERT_EQ(EDEADLK, pthread_mutex_lock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); if (protocol == PTHREAD_PRIO_NONE) { ASSERT_EQ(EBUSY, pthread_mutex_trylock(&m.lock)); } else { ASSERT_EQ(EDEADLK, pthread_mutex_trylock(&m.lock)); } ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); } static void TestPthreadMutexLockRecursive(int protocol) { PthreadMutex m(PTHREAD_MUTEX_RECURSIVE, protocol); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(EPERM, UnlockFromAnotherThread(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_trylock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(EPERM, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_lock_NORMAL) { TestPthreadMutexLockNormal(PTHREAD_PRIO_NONE); } TEST(pthread, pthread_mutex_lock_ERRORCHECK) { TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_NONE); } TEST(pthread, pthread_mutex_lock_RECURSIVE) { TestPthreadMutexLockRecursive(PTHREAD_PRIO_NONE); } TEST(pthread, pthread_mutex_lock_pi) { TestPthreadMutexLockNormal(PTHREAD_PRIO_INHERIT); TestPthreadMutexLockErrorCheck(PTHREAD_PRIO_INHERIT); TestPthreadMutexLockRecursive(PTHREAD_PRIO_INHERIT); } TEST(pthread, pthread_mutex_pi_count_limit) { #if defined(__BIONIC__) && !defined(__LP64__) // Bionic only supports 65536 pi mutexes in 32-bit programs. pthread_mutexattr_t attr; ASSERT_EQ(0, pthread_mutexattr_init(&attr)); ASSERT_EQ(0, pthread_mutexattr_setprotocol(&attr, PTHREAD_PRIO_INHERIT)); std::vector<pthread_mutex_t> mutexes(65536); // Test if we can use 65536 pi mutexes at the same time. // Run 2 times to check if freed pi mutexes can be recycled. for (int repeat = 0; repeat < 2; ++repeat) { for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_init(&m, &attr)); } pthread_mutex_t m; ASSERT_EQ(ENOMEM, pthread_mutex_init(&m, &attr)); for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_lock(&m)); } for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_unlock(&m)); } for (auto& m : mutexes) { ASSERT_EQ(0, pthread_mutex_destroy(&m)); } } ASSERT_EQ(0, pthread_mutexattr_destroy(&attr)); #else GTEST_SKIP() << "pi mutex count not limited to 64Ki"; #endif } TEST(pthread, pthread_mutex_init_same_as_static_initializers) { pthread_mutex_t lock_normal = PTHREAD_MUTEX_INITIALIZER; PthreadMutex m1(PTHREAD_MUTEX_NORMAL); ASSERT_EQ(0, memcmp(&lock_normal, &m1.lock, sizeof(pthread_mutex_t))); pthread_mutex_destroy(&lock_normal); pthread_mutex_t lock_errorcheck = PTHREAD_ERRORCHECK_MUTEX_INITIALIZER_NP; PthreadMutex m2(PTHREAD_MUTEX_ERRORCHECK); ASSERT_EQ(0, memcmp(&lock_errorcheck, &m2.lock, sizeof(pthread_mutex_t))); pthread_mutex_destroy(&lock_errorcheck); pthread_mutex_t lock_recursive = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP; PthreadMutex m3(PTHREAD_MUTEX_RECURSIVE); ASSERT_EQ(0, memcmp(&lock_recursive, &m3.lock, sizeof(pthread_mutex_t))); ASSERT_EQ(0, pthread_mutex_destroy(&lock_recursive)); } class MutexWakeupHelper { private: PthreadMutex m; enum Progress { LOCK_INITIALIZED, LOCK_WAITING, LOCK_RELEASED, LOCK_ACCESSED }; std::atomic<Progress> progress; std::atomic<pid_t> tid; static void thread_fn(MutexWakeupHelper* helper) { helper->tid = gettid(); ASSERT_EQ(LOCK_INITIALIZED, helper->progress); helper->progress = LOCK_WAITING; ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); ASSERT_EQ(LOCK_RELEASED, helper->progress); ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); helper->progress = LOCK_ACCESSED; } public: explicit MutexWakeupHelper(int mutex_type) : m(mutex_type) { } void test() { ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); progress = LOCK_INITIALIZED; tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(MutexWakeupHelper::thread_fn), this)); WaitUntilThreadSleep(tid); ASSERT_EQ(LOCK_WAITING, progress); progress = LOCK_RELEASED; ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); ASSERT_EQ(LOCK_ACCESSED, progress); } }; TEST(pthread, pthread_mutex_NORMAL_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_NORMAL); helper.test(); } TEST(pthread, pthread_mutex_ERRORCHECK_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_ERRORCHECK); helper.test(); } TEST(pthread, pthread_mutex_RECURSIVE_wakeup) { MutexWakeupHelper helper(PTHREAD_MUTEX_RECURSIVE); helper.test(); } static int GetThreadPriority(pid_t tid) { // sched_getparam() returns the static priority of a thread, which can't reflect a thread's // priority after priority inheritance. So read /proc/<pid>/stat to get the dynamic priority. std::string filename = android::base::StringPrintf("/proc/%d/stat", tid); std::string content; int result = INT_MAX; if (!android::base::ReadFileToString(filename, &content)) { return result; } std::vector<std::string> strs = android::base::Split(content, " "); if (strs.size() < 18) { return result; } if (!android::base::ParseInt(strs[17], &result)) { return INT_MAX; } return result; } class PIMutexWakeupHelper { private: PthreadMutex m; int protocol; enum Progress { LOCK_INITIALIZED, LOCK_CHILD_READY, LOCK_WAITING, LOCK_RELEASED, }; std::atomic<Progress> progress; std::atomic<pid_t> main_tid; std::atomic<pid_t> child_tid; PthreadMutex start_thread_m; static void thread_fn(PIMutexWakeupHelper* helper) { helper->child_tid = gettid(); ASSERT_EQ(LOCK_INITIALIZED, helper->progress); ASSERT_EQ(0, setpriority(PRIO_PROCESS, gettid(), 1)); ASSERT_EQ(21, GetThreadPriority(gettid())); ASSERT_EQ(0, pthread_mutex_lock(&helper->m.lock)); helper->progress = LOCK_CHILD_READY; ASSERT_EQ(0, pthread_mutex_lock(&helper->start_thread_m.lock)); ASSERT_EQ(0, pthread_mutex_unlock(&helper->start_thread_m.lock)); WaitUntilThreadSleep(helper->main_tid); ASSERT_EQ(LOCK_WAITING, helper->progress); if (helper->protocol == PTHREAD_PRIO_INHERIT) { ASSERT_EQ(20, GetThreadPriority(gettid())); } else { ASSERT_EQ(21, GetThreadPriority(gettid())); } helper->progress = LOCK_RELEASED; ASSERT_EQ(0, pthread_mutex_unlock(&helper->m.lock)); } public: explicit PIMutexWakeupHelper(int mutex_type, int protocol) : m(mutex_type, protocol), protocol(protocol), start_thread_m(PTHREAD_MUTEX_NORMAL) { } void test() { ASSERT_EQ(0, pthread_mutex_lock(&start_thread_m.lock)); main_tid = gettid(); ASSERT_EQ(20, GetThreadPriority(main_tid)); progress = LOCK_INITIALIZED; child_tid = 0; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(PIMutexWakeupHelper::thread_fn), this)); WaitUntilThreadSleep(child_tid); ASSERT_EQ(LOCK_CHILD_READY, progress); ASSERT_EQ(0, pthread_mutex_unlock(&start_thread_m.lock)); progress = LOCK_WAITING; ASSERT_EQ(0, pthread_mutex_lock(&m.lock)); ASSERT_EQ(LOCK_RELEASED, progress); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); ASSERT_EQ(0, pthread_join(thread, nullptr)); } }; TEST(pthread, pthread_mutex_pi_wakeup) { for (int type : {PTHREAD_MUTEX_NORMAL, PTHREAD_MUTEX_RECURSIVE, PTHREAD_MUTEX_ERRORCHECK}) { for (int protocol : {PTHREAD_PRIO_INHERIT}) { PIMutexWakeupHelper helper(type, protocol); helper.test(); } } } TEST(pthread, pthread_mutex_owner_tid_limit) { #if defined(__BIONIC__) && !defined(__LP64__) FILE* fp = fopen("/proc/sys/kernel/pid_max", "r"); ASSERT_TRUE(fp != nullptr); long pid_max; ASSERT_EQ(1, fscanf(fp, "%ld", &pid_max)); fclose(fp); // Bionic's pthread_mutex implementation on 32-bit devices uses 16 bits to represent owner tid. ASSERT_LE(pid_max, 65536); #else GTEST_SKIP() << "pthread_mutex supports 32-bit tid"; #endif } static void pthread_mutex_timedlock_helper(clockid_t clock, int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout)) { pthread_mutex_t m; ASSERT_EQ(0, pthread_mutex_init(&m, nullptr)); // If the mutex is already locked, pthread_mutex_timedlock should time out. ASSERT_EQ(0, pthread_mutex_lock(&m)); timespec ts; ASSERT_EQ(0, clock_gettime(clock, &ts)); ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts)); ts.tv_nsec = -1; ASSERT_EQ(EINVAL, lock_function(&m, &ts)); ts.tv_nsec = NS_PER_S; ASSERT_EQ(EINVAL, lock_function(&m, &ts)); ts.tv_nsec = NS_PER_S - 1; ts.tv_sec = -1; ASSERT_EQ(ETIMEDOUT, lock_function(&m, &ts)); // If the mutex is unlocked, pthread_mutex_timedlock should succeed. ASSERT_EQ(0, pthread_mutex_unlock(&m)); ASSERT_EQ(0, clock_gettime(clock, &ts)); ts.tv_sec += 1; ASSERT_EQ(0, lock_function(&m, &ts)); ASSERT_EQ(0, pthread_mutex_unlock(&m)); ASSERT_EQ(0, pthread_mutex_destroy(&m)); } TEST(pthread, pthread_mutex_timedlock) { pthread_mutex_timedlock_helper(CLOCK_REALTIME, pthread_mutex_timedlock); } TEST(pthread, pthread_mutex_timedlock_monotonic_np) { #if defined(__BIONIC__) pthread_mutex_timedlock_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_mutex_clocklock) { #if defined(__BIONIC__) pthread_mutex_timedlock_helper( CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout); }); pthread_mutex_timedlock_helper( CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_clocklock not available"; #endif // __BIONIC__ } static void pthread_mutex_timedlock_pi_helper(clockid_t clock, int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout)) { PthreadMutex m(PTHREAD_MUTEX_NORMAL, PTHREAD_PRIO_INHERIT); timespec ts; clock_gettime(clock, &ts); ts.tv_sec += 1; ASSERT_EQ(0, lock_function(&m.lock, &ts)); struct ThreadArgs { clockid_t clock; int (*lock_function)(pthread_mutex_t* __mutex, const timespec* __timeout); PthreadMutex& m; }; ThreadArgs thread_args = { .clock = clock, .lock_function = lock_function, .m = m, }; auto ThreadFn = [](void* arg) -> void* { auto args = static_cast<ThreadArgs*>(arg); timespec ts; clock_gettime(args->clock, &ts); ts.tv_sec += 1; intptr_t result = args->lock_function(&args->m.lock, &ts); return reinterpret_cast<void*>(result); }; pthread_t thread; ASSERT_EQ(0, pthread_create(&thread, nullptr, ThreadFn, &thread_args)); void* result; ASSERT_EQ(0, pthread_join(thread, &result)); ASSERT_EQ(ETIMEDOUT, reinterpret_cast<intptr_t>(result)); ASSERT_EQ(0, pthread_mutex_unlock(&m.lock)); } TEST(pthread, pthread_mutex_timedlock_pi) { pthread_mutex_timedlock_pi_helper(CLOCK_REALTIME, pthread_mutex_timedlock); } TEST(pthread, pthread_mutex_timedlock_monotonic_np_pi) { #if defined(__BIONIC__) pthread_mutex_timedlock_pi_helper(CLOCK_MONOTONIC, pthread_mutex_timedlock_monotonic_np); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_timedlock_monotonic_np not available"; #endif // __BIONIC__ } TEST(pthread, pthread_mutex_clocklock_pi) { #if defined(__BIONIC__) pthread_mutex_timedlock_pi_helper( CLOCK_MONOTONIC, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_MONOTONIC, __timeout); }); pthread_mutex_timedlock_pi_helper( CLOCK_REALTIME, [](pthread_mutex_t* __mutex, const timespec* __timeout) { return pthread_mutex_clocklock(__mutex, CLOCK_REALTIME, __timeout); }); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_clocklock not available"; #endif // __BIONIC__ } TEST(pthread, pthread_mutex_clocklock_invalid) { #if defined(__BIONIC__) pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER; timespec ts; EXPECT_EQ(EINVAL, pthread_mutex_clocklock(&mutex, CLOCK_PROCESS_CPUTIME_ID, &ts)); #else // __BIONIC__ GTEST_SKIP() << "pthread_mutex_clocklock not available"; #endif // __BIONIC__ } TEST_F(pthread_DeathTest, pthread_mutex_using_destroyed_mutex) { #if defined(__BIONIC__) pthread_mutex_t m; ASSERT_EQ(0, pthread_mutex_init(&m, nullptr)); ASSERT_EQ(0, pthread_mutex_destroy(&m)); ASSERT_EXIT(pthread_mutex_lock(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_lock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_unlock(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_unlock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_trylock(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_trylock called on a destroyed mutex"); timespec ts; ASSERT_EXIT(pthread_mutex_timedlock(&m, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_timedlock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_timedlock_monotonic_np(&m, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_timedlock_monotonic_np called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_MONOTONIC, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_clocklock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_REALTIME, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_clocklock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_clocklock(&m, CLOCK_PROCESS_CPUTIME_ID, &ts), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_clocklock called on a destroyed mutex"); ASSERT_EXIT(pthread_mutex_destroy(&m), ::testing::KilledBySignal(SIGABRT), "pthread_mutex_destroy called on a destroyed mutex"); #else GTEST_SKIP() << "bionic-only test"; #endif } class StrictAlignmentAllocator { public: void* allocate(size_t size, size_t alignment) { char* p = new char[size + alignment * 2]; allocated_array.push_back(p); while (!is_strict_aligned(p, alignment)) { ++p; } return p; } ~StrictAlignmentAllocator() { for (const auto& p : allocated_array) { delete[] p; } } private: bool is_strict_aligned(char* p, size_t alignment) { return (reinterpret_cast<uintptr_t>(p) % (alignment * 2)) == alignment; } std::vector<char*> allocated_array; }; TEST(pthread, pthread_types_allow_four_bytes_alignment) { #if defined(__BIONIC__) // For binary compatibility with old version, we need to allow 4-byte aligned data for pthread types. StrictAlignmentAllocator allocator; pthread_mutex_t* mutex = reinterpret_cast<pthread_mutex_t*>( allocator.allocate(sizeof(pthread_mutex_t), 4)); ASSERT_EQ(0, pthread_mutex_init(mutex, nullptr)); ASSERT_EQ(0, pthread_mutex_lock(mutex)); ASSERT_EQ(0, pthread_mutex_unlock(mutex)); ASSERT_EQ(0, pthread_mutex_destroy(mutex)); pthread_cond_t* cond = reinterpret_cast<pthread_cond_t*>( allocator.allocate(sizeof(pthread_cond_t), 4)); ASSERT_EQ(0, pthread_cond_init(cond, nullptr)); ASSERT_EQ(0, pthread_cond_signal(cond)); ASSERT_EQ(0, pthread_cond_broadcast(cond)); ASSERT_EQ(0, pthread_cond_destroy(cond)); pthread_rwlock_t* rwlock = reinterpret_cast<pthread_rwlock_t*>( allocator.allocate(sizeof(pthread_rwlock_t), 4)); ASSERT_EQ(0, pthread_rwlock_init(rwlock, nullptr)); ASSERT_EQ(0, pthread_rwlock_rdlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_wrlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_unlock(rwlock)); ASSERT_EQ(0, pthread_rwlock_destroy(rwlock)); #else GTEST_SKIP() << "bionic-only test"; #endif } TEST(pthread, pthread_mutex_lock_null_32) { #if defined(__BIONIC__) && !defined(__LP64__) // For LP32, the pthread lock/unlock functions allow a NULL mutex and return // EINVAL in that case: http://b/19995172. // // We decorate the public defintion with _Nonnull so that people recompiling // their code with get a warning and might fix their bug, but need to pass // NULL here to test that we remain compatible. pthread_mutex_t* null_value = nullptr; ASSERT_EQ(EINVAL, pthread_mutex_lock(null_value)); #else GTEST_SKIP() << "32-bit bionic-only test"; #endif } TEST(pthread, pthread_mutex_unlock_null_32) { #if defined(__BIONIC__) && !defined(__LP64__) // For LP32, the pthread lock/unlock functions allow a NULL mutex and return // EINVAL in that case: http://b/19995172. // // We decorate the public defintion with _Nonnull so that people recompiling // their code with get a warning and might fix their bug, but need to pass // NULL here to test that we remain compatible. pthread_mutex_t* null_value = nullptr; ASSERT_EQ(EINVAL, pthread_mutex_unlock(null_value)); #else GTEST_SKIP() << "32-bit bionic-only test"; #endif } TEST_F(pthread_DeathTest, pthread_mutex_lock_null_64) { #if defined(__BIONIC__) && defined(__LP64__) pthread_mutex_t* null_value = nullptr; ASSERT_EXIT(pthread_mutex_lock(null_value), testing::KilledBySignal(SIGSEGV), ""); #else GTEST_SKIP() << "64-bit bionic-only test"; #endif } TEST_F(pthread_DeathTest, pthread_mutex_unlock_null_64) { #if defined(__BIONIC__) && defined(__LP64__) pthread_mutex_t* null_value = nullptr; ASSERT_EXIT(pthread_mutex_unlock(null_value), testing::KilledBySignal(SIGSEGV), ""); #else GTEST_SKIP() << "64-bit bionic-only test"; #endif } extern _Unwind_Reason_Code FrameCounter(_Unwind_Context* ctx, void* arg); static volatile bool signal_handler_on_altstack_done; __attribute__((__noinline__)) static void signal_handler_backtrace() { // Check if we have enough stack space for unwinding. int count = 0; _Unwind_Backtrace(FrameCounter, &count); ASSERT_GT(count, 0); } __attribute__((__noinline__)) static void signal_handler_logging() { // Check if we have enough stack space for logging. std::string s(2048, '*'); GTEST_LOG_(INFO) << s; signal_handler_on_altstack_done = true; } __attribute__((__noinline__)) static void signal_handler_snprintf() { // Check if we have enough stack space for snprintf to a PATH_MAX buffer, plus some extra. char buf[PATH_MAX + 2048]; ASSERT_GT(snprintf(buf, sizeof(buf), "/proc/%d/status", getpid()), 0); } static void SignalHandlerOnAltStack(int signo, siginfo_t*, void*) { ASSERT_EQ(SIGUSR1, signo); signal_handler_backtrace(); signal_handler_logging(); signal_handler_snprintf(); } TEST(pthread, big_enough_signal_stack) { signal_handler_on_altstack_done = false; ScopedSignalHandler handler(SIGUSR1, SignalHandlerOnAltStack, SA_SIGINFO | SA_ONSTACK); kill(getpid(), SIGUSR1); ASSERT_TRUE(signal_handler_on_altstack_done); } TEST(pthread, pthread_barrierattr_smoke) { pthread_barrierattr_t attr; ASSERT_EQ(0, pthread_barrierattr_init(&attr)); int pshared; ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_PRIVATE, pshared); ASSERT_EQ(0, pthread_barrierattr_setpshared(&attr, PTHREAD_PROCESS_SHARED)); ASSERT_EQ(0, pthread_barrierattr_getpshared(&attr, &pshared)); ASSERT_EQ(PTHREAD_PROCESS_SHARED, pshared); ASSERT_EQ(0, pthread_barrierattr_destroy(&attr)); } struct BarrierTestHelperData { size_t thread_count; pthread_barrier_t barrier; std::atomic<int> finished_mask; std::atomic<int> serial_thread_count; size_t iteration_count; std::atomic<size_t> finished_iteration_count; BarrierTestHelperData(size_t thread_count, size_t iteration_count) : thread_count(thread_count), finished_mask(0), serial_thread_count(0), iteration_count(iteration_count), finished_iteration_count(0) { } }; struct BarrierTestHelperArg { int id; BarrierTestHelperData* data; }; static void BarrierTestHelper(BarrierTestHelperArg* arg) { for (size_t i = 0; i < arg->data->iteration_count; ++i) { int result = pthread_barrier_wait(&arg->data->barrier); if (result == PTHREAD_BARRIER_SERIAL_THREAD) { arg->data->serial_thread_count++; } else { ASSERT_EQ(0, result); } int mask = arg->data->finished_mask.fetch_or(1 << arg->id); mask |= 1 << arg->id; if (mask == ((1 << arg->data->thread_count) - 1)) { ASSERT_EQ(1, arg->data->serial_thread_count); arg->data->finished_iteration_count++; arg->data->finished_mask = 0; arg->data->serial_thread_count = 0; } } } TEST(pthread, pthread_barrier_smoke) { const size_t BARRIER_ITERATION_COUNT = 10; const size_t BARRIER_THREAD_COUNT = 10; BarrierTestHelperData data(BARRIER_THREAD_COUNT, BARRIER_ITERATION_COUNT); ASSERT_EQ(0, pthread_barrier_init(&data.barrier, nullptr, data.thread_count)); std::vector<pthread_t> threads(data.thread_count); std::vector<BarrierTestHelperArg> args(threads.size()); for (size_t i = 0; i < threads.size(); ++i) { args[i].id = i; args[i].data = &data; ASSERT_EQ(0, pthread_create(&threads[i], nullptr, reinterpret_cast<void* (*)(void*)>(BarrierTestHelper), &args[i])); } for (size_t i = 0; i < threads.size(); ++i) { ASSERT_EQ(0, pthread_join(threads[i], nullptr)); } ASSERT_EQ(data.iteration_count, data.finished_iteration_count); ASSERT_EQ(0, pthread_barrier_destroy(&data.barrier)); } struct BarrierDestroyTestArg { std::atomic<int> tid; pthread_barrier_t* barrier; }; static void BarrierDestroyTestHelper(BarrierDestroyTestArg* arg) { arg->tid = gettid(); ASSERT_EQ(0, pthread_barrier_wait(arg->barrier)); } TEST(pthread, pthread_barrier_destroy) { pthread_barrier_t barrier; ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, 2)); pthread_t thread; BarrierDestroyTestArg arg; arg.tid = 0; arg.barrier = &barrier; ASSERT_EQ(0, pthread_create(&thread, nullptr, reinterpret_cast<void* (*)(void*)>(BarrierDestroyTestHelper), &arg)); WaitUntilThreadSleep(arg.tid); ASSERT_EQ(EBUSY, pthread_barrier_destroy(&barrier)); ASSERT_EQ(PTHREAD_BARRIER_SERIAL_THREAD, pthread_barrier_wait(&barrier)); // Verify if the barrier can be destroyed directly after pthread_barrier_wait(). ASSERT_EQ(0, pthread_barrier_destroy(&barrier)); ASSERT_EQ(0, pthread_join(thread, nullptr)); #if defined(__BIONIC__) ASSERT_EQ(EINVAL, pthread_barrier_destroy(&barrier)); #endif } struct BarrierOrderingTestHelperArg { pthread_barrier_t* barrier; size_t* array; size_t array_length; size_t id; }; void BarrierOrderingTestHelper(BarrierOrderingTestHelperArg* arg) { const size_t ITERATION_COUNT = 10000; for (size_t i = 1; i <= ITERATION_COUNT; ++i) { arg->array[arg->id] = i; int result = pthread_barrier_wait(arg->barrier); ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); for (size_t j = 0; j < arg->array_length; ++j) { ASSERT_EQ(i, arg->array[j]); } result = pthread_barrier_wait(arg->barrier); ASSERT_TRUE(result == 0 || result == PTHREAD_BARRIER_SERIAL_THREAD); } } TEST(pthread, pthread_barrier_check_ordering) { const size_t THREAD_COUNT = 4; pthread_barrier_t barrier; ASSERT_EQ(0, pthread_barrier_init(&barrier, nullptr, THREAD_COUNT)); size_t array[THREAD_COUNT]; std::vector<pthread_t> threads(THREAD_COUNT); std::vector<BarrierOrderingTestHelperArg> args(THREAD_COUNT); for (size_t i = 0; i < THREAD_COUNT; ++i) { args[i].barrier = &barrier; args[i].array = array; args[i].array_length = THREAD_COUNT; args[i].id = i; ASSERT_EQ(0, pthread_create(&threads[i], nullptr, reinterpret_cast<void* (*)(void*)>(BarrierOrderingTestHelper), &args[i])); } for (size_t i = 0; i < THREAD_COUNT; ++i) { ASSERT_EQ(0, pthread_join(threads[i], nullptr)); } } TEST(pthread, pthread_barrier_init_zero_count) { pthread_barrier_t barrier; ASSERT_EQ(EINVAL, pthread_barrier_init(&barrier, nullptr, 0)); } TEST(pthread, pthread_spinlock_smoke) { pthread_spinlock_t lock; ASSERT_EQ(0, pthread_spin_init(&lock, 0)); ASSERT_EQ(0, pthread_spin_trylock(&lock)); ASSERT_EQ(0, pthread_spin_unlock(&lock)); ASSERT_EQ(0, pthread_spin_lock(&lock)); ASSERT_EQ(EBUSY, pthread_spin_trylock(&lock)); ASSERT_EQ(0, pthread_spin_unlock(&lock)); ASSERT_EQ(0, pthread_spin_destroy(&lock)); } TEST(pthread, pthread_attr_getdetachstate__pthread_attr_setdetachstate) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int state; ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); ASSERT_EQ(PTHREAD_CREATE_DETACHED, state); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_JOINABLE)); ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state); ASSERT_EQ(EINVAL, pthread_attr_setdetachstate(&attr, 123)); ASSERT_EQ(0, pthread_attr_getdetachstate(&attr, &state)); ASSERT_EQ(PTHREAD_CREATE_JOINABLE, state); } TEST(pthread, pthread_create__mmap_failures) { // After thread is successfully created, native_bridge might need more memory to run it. SKIP_WITH_NATIVE_BRIDGE; pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)); const auto kPageSize = sysconf(_SC_PAGE_SIZE); // Use up all the VMAs. By default this is 64Ki (though some will already be in use). std::vector<void*> pages; pages.reserve(64 * 1024); int prot = PROT_NONE; while (true) { void* page = mmap(nullptr, kPageSize, prot, MAP_ANON|MAP_PRIVATE, -1, 0); if (page == MAP_FAILED) break; pages.push_back(page); prot = (prot == PROT_NONE) ? PROT_READ : PROT_NONE; } // Try creating threads, freeing up a page each time we fail. size_t EAGAIN_count = 0; size_t i = 0; for (; i < pages.size(); ++i) { pthread_t t; int status = pthread_create(&t, &attr, IdFn, nullptr); if (status != EAGAIN) break; ++EAGAIN_count; ASSERT_EQ(0, munmap(pages[i], kPageSize)); } // Creating a thread uses at least three VMAs: the combined stack and TLS, and a guard on each // side. So we should have seen at least three failures. ASSERT_GE(EAGAIN_count, 3U); for (; i < pages.size(); ++i) { ASSERT_EQ(0, munmap(pages[i], kPageSize)); } } TEST(pthread, pthread_setschedparam) { sched_param p = { .sched_priority = INT_MIN }; ASSERT_EQ(EINVAL, pthread_setschedparam(pthread_self(), INT_MIN, &p)); } TEST(pthread, pthread_setschedprio) { ASSERT_EQ(EINVAL, pthread_setschedprio(pthread_self(), INT_MIN)); } TEST(pthread, pthread_attr_getinheritsched__pthread_attr_setinheritsched) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); int state; ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); ASSERT_EQ(PTHREAD_INHERIT_SCHED, state); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state); ASSERT_EQ(EINVAL, pthread_attr_setinheritsched(&attr, 123)); ASSERT_EQ(0, pthread_attr_getinheritsched(&attr, &state)); ASSERT_EQ(PTHREAD_EXPLICIT_SCHED, state); } TEST(pthread, pthread_attr_setinheritsched__PTHREAD_INHERIT_SCHED__PTHREAD_EXPLICIT_SCHED) { pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); // If we set invalid scheduling attributes but choose to inherit, everything's fine... sched_param param = { .sched_priority = sched_get_priority_max(SCHED_FIFO) + 1 }; ASSERT_EQ(0, pthread_attr_setschedparam(&attr, &param)); ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_FIFO)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, IdFn, nullptr)); ASSERT_EQ(0, pthread_join(t, nullptr)); #if defined(__LP64__) // If we ask to use them, though, we'll see a failure... ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); ASSERT_EQ(EINVAL, pthread_create(&t, &attr, IdFn, nullptr)); #else // For backwards compatibility with broken apps, we just ignore failures // to set scheduler attributes on LP32. #endif } TEST(pthread, pthread_attr_setinheritsched_PTHREAD_INHERIT_SCHED_takes_effect) { sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param); if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM"; ASSERT_EQ(0, rc); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); int actual_policy; sched_param actual_param; ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); ASSERT_EQ(SCHED_FIFO, actual_policy); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST(pthread, pthread_attr_setinheritsched_PTHREAD_EXPLICIT_SCHED_takes_effect) { sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO, &param); if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM"; ASSERT_EQ(0, rc); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_EXPLICIT_SCHED)); ASSERT_EQ(0, pthread_attr_setschedpolicy(&attr, SCHED_OTHER)); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); int actual_policy; sched_param actual_param; ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); ASSERT_EQ(SCHED_OTHER, actual_policy); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } TEST(pthread, pthread_attr_setinheritsched__takes_effect_despite_SCHED_RESET_ON_FORK) { sched_param param = { .sched_priority = sched_get_priority_min(SCHED_FIFO) }; int rc = pthread_setschedparam(pthread_self(), SCHED_FIFO | SCHED_RESET_ON_FORK, &param); if (rc == EPERM) GTEST_SKIP() << "pthread_setschedparam failed with EPERM"; ASSERT_EQ(0, rc); pthread_attr_t attr; ASSERT_EQ(0, pthread_attr_init(&attr)); ASSERT_EQ(0, pthread_attr_setinheritsched(&attr, PTHREAD_INHERIT_SCHED)); SpinFunctionHelper spin_helper; pthread_t t; ASSERT_EQ(0, pthread_create(&t, &attr, spin_helper.GetFunction(), nullptr)); int actual_policy; sched_param actual_param; ASSERT_EQ(0, pthread_getschedparam(t, &actual_policy, &actual_param)); ASSERT_EQ(SCHED_FIFO | SCHED_RESET_ON_FORK, actual_policy); spin_helper.UnSpin(); ASSERT_EQ(0, pthread_join(t, nullptr)); } extern "C" bool android_run_on_all_threads(bool (*func)(void*), void* arg); TEST(pthread, run_on_all_threads) { #if defined(__BIONIC__) pthread_t t; ASSERT_EQ( 0, pthread_create( &t, nullptr, [](void*) -> void* { pthread_attr_t detached; if (pthread_attr_init(&detached) != 0 || pthread_attr_setdetachstate(&detached, PTHREAD_CREATE_DETACHED) != 0) { return reinterpret_cast<void*>(errno); } for (int i = 0; i != 1000; ++i) { pthread_t t1, t2; if (pthread_create( &t1, &detached, [](void*) -> void* { return nullptr; }, nullptr) != 0 || pthread_create( &t2, nullptr, [](void*) -> void* { return nullptr; }, nullptr) != 0 || pthread_join(t2, nullptr) != 0) { return reinterpret_cast<void*>(errno); } } if (pthread_attr_destroy(&detached) != 0) { return reinterpret_cast<void*>(errno); } return nullptr; }, nullptr)); for (int i = 0; i != 1000; ++i) { ASSERT_TRUE(android_run_on_all_threads([](void* arg) { return arg == nullptr; }, nullptr)); } void *retval; ASSERT_EQ(0, pthread_join(t, &retval)); ASSERT_EQ(nullptr, retval); #else GTEST_SKIP() << "bionic-only test"; #endif }
34.166446
108
0.737368
webos21
1a058f089c816fe656fccfdf5b0d50e4ca781b28
2,870
cpp
C++
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
3
2021-12-23T23:31:42.000Z
2022-02-16T07:17:41.000Z
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
2
2021-11-22T05:33:43.000Z
2022-01-23T07:01:47.000Z
src/CAN/CANMotor_PSOC.cpp
huskyroboticsteam/Resurgence
649f78103b6d76709fdf55bb38d08c0ff50da140
[ "Apache-2.0" ]
null
null
null
#include "CAN.h" #include "CANMotor.h" #include "CANUtils.h" #include <chrono> #include <cmath> #include <condition_variable> #include <mutex> #include <queue> #include <thread> #include <vector> extern "C" { #include "../HindsightCAN/CANCommon.h" #include "../HindsightCAN/CANMotorUnit.h" #include "../HindsightCAN/CANPacket.h" } using namespace std::chrono_literals; using std::chrono::milliseconds; namespace can::motor { namespace { using clock = std::chrono::steady_clock; using timepoint_t = std::chrono::time_point<clock>; struct telemschedule_t { timepoint_t nextSendTime; milliseconds telemPeriod; deviceserial_t serial; }; bool operator<(const telemschedule_t& t1, const telemschedule_t& t2) { return t1.nextSendTime < t2.nextSendTime; } std::priority_queue<telemschedule_t> telemetrySchedule; bool startedMotorThread = false; bool newMotorAdded = false; std::condition_variable motorsCV; std::mutex motorsMutex; // protects telemetrySchedule, startedMotorThread, newMotorAdded void motorThreadFn() { while (true) { std::unique_lock lock(motorsMutex); if (telemetrySchedule.empty()) { motorsCV.wait(lock, [] { return newMotorAdded; }); newMotorAdded = false; } else { auto now = clock::now(); auto ts = telemetrySchedule.top(); if (ts.nextSendTime <= now) { telemetrySchedule.pop(); pullMotorPosition(ts.serial); telemetrySchedule.push( {ts.nextSendTime + ts.telemPeriod, ts.telemPeriod, ts.serial}); } else { motorsCV.wait_until(lock, ts.nextSendTime, [] { return newMotorAdded; }); newMotorAdded = false; } } } } void startMonitoringMotor(deviceserial_t motor, std::chrono::milliseconds period) { { std::unique_lock lock(motorsMutex); if (!startedMotorThread) { startedMotorThread = true; std::thread motorThread(motorThreadFn); motorThread.detach(); } telemetrySchedule.push({clock::now(), period, motor}); newMotorAdded = true; } motorsCV.notify_one(); } } // namespace void initEncoder(deviceserial_t serial, bool invertEncoder, bool zeroEncoder, int32_t pulsesPerJointRev, std::optional<std::chrono::milliseconds> telemetryPeriod) { auto motorGroupCode = static_cast<uint8_t>(devicegroup_t::motor); CANPacket p; AssembleEncoderInitializePacket(&p, motorGroupCode, serial, sensor_t::encoder, invertEncoder, zeroEncoder); sendCANPacket(p); std::this_thread::sleep_for(1000us); AssembleEncoderPPJRSetPacket(&p, motorGroupCode, serial, pulsesPerJointRev); sendCANPacket(p); std::this_thread::sleep_for(1000us); if (telemetryPeriod) { startMonitoringMotor(serial, telemetryPeriod.value()); } } void pullMotorPosition(deviceserial_t serial) { CANPacket p; AssembleTelemetryPullPacket(&p, static_cast<uint8_t>(devicegroup_t::motor), serial, static_cast<uint8_t>(telemtype_t::angle)); sendCANPacket(p); } } // namespace can::motor
27.596154
91
0.74216
huskyroboticsteam
1a05fd4f32bf7ac9e3f364b003d152b41f41516b
2,184
cpp
C++
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
Hello 2019/c.cpp
anirudha-ani/Codeforces
6c7f64257939d44b1c2ec9dd202f1c9f899f1cad
[ "Apache-2.0" ]
null
null
null
#include <bits/stdc++.h> using namespace std ; int main() { stack <char> data; char input[500005]; int n ; scanf("%d", &n); map <int , int> marking ; int balanced= 0 ; long long int ans = 0 ; for(int i = 0 ; i < n ; i++) { scanf("%s", input); int k = 0 ; int score = 0 ; stack <char> store ; //cout <<"HE" << endl ; while(input[k] != '\0') { //cout << input[k] << endl ; if(input[k] == '(') { store.push(input[k]); //cout << "1" << endl ; } else { if(!store.empty() && store.top() == '(') { store.pop(); //cout << "2" << endl; } else { store.push(input[k]); //cout << "3" << endl ; } } //cout << k << endl ; k++; } if(store.size() == 0) { balanced++; } else { bool possible = true; char init = store.top() ; store.pop(); if(init == '(') { score++; } else score--; //cout << "HERE" << endl ; while(!store.empty()) { if(store.top() != init) { possible = false ; break; } else if(store.top() == '(') { score++; } else score--; store.pop(); } if(!possible) continue; else if(marking[score * -1] > 0) { marking[score * -1] = marking[score * -1] - 1 ; ans++ ; } else { marking[score] = marking[score] + 1 ; } } } ans += balanced/2; printf("%lld\n", ans); return 0 ; }
24
64
0.287088
anirudha-ani
1a0823730e616552e21f820c37d0889c43151bc6
1,769
cpp
C++
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
codes/POJ/poj3468.cpp
JeraKrs/ACM
edcd61ec6764b8cd804bf1538dfde53d0ff572b5
[ "Apache-2.0" ]
null
null
null
#include <cstdio> #include <cstring> #include <algorithm> using namespace std; #define lson(x) ((x)<<1) #define rson(x) (((x)<<1)+1) const int maxn = 100005; typedef long long ll; struct Node { int l, r; ll sum, add; void set (int l, int r, ll sum, ll add) { this->l = l; this->r = r; this->sum = sum; this->add = add; } void maintain (ll v) { sum += (r - l + 1) * v; add += v; } }nd[maxn * 4]; int N, Q, A[maxn]; void pushup (int u) { nd[u].sum = nd[lson(u)].sum + nd[rson(u)].sum; } void pushdown(int u) { if (nd[u].add) { nd[lson(u)].maintain(nd[u].add); nd[rson(u)].maintain(nd[u].add); nd[u].add = 0; } } void build (int u, int l, int r) { nd[u].l = l; nd[u].r = r; nd[u].add = 0; if (l == r) { nd[u].sum = A[l]; return; } int mid = (l + r) / 2; build(lson(u), l, mid); build(rson(u), mid + 1, r); pushup(u); } ll query(int u, int l, int r) { if (l <= nd[u].l && nd[u].r <= r) return nd[u].sum; pushdown(u); ll ret = 0; int mid = (nd[u].l + nd[u].r) / 2; if (l <= mid) ret += query(lson(u), l, r); if (r > mid) ret += query(rson(u), l, r); pushup(u); return ret; } void modify (int u, int l, int r, int v) { if (l <= nd[u].l && nd[u].r <= r) { nd[u].maintain(v); return; } pushdown(u); int mid = (nd[u].l + nd[u].r) / 2; if (l <= mid) modify(lson(u), l, r, v); if (r > mid) modify(rson(u), l, r, v); pushup(u); } int main () { while (scanf("%d%d", &N, &Q) == 2) { for (int i = 1; i <= N; i++) scanf("%d", &A[i]); build(1, 1, N); int l, r, v; char order[5]; for (int i = 0; i < Q; i++) { scanf("%s%d%d", order, &l, &r); if (order[0] == 'Q') printf("%lld\n", query(1, l, r)); else { scanf("%d", &v); modify(1, l, r, v); } } } return 0; }
16.229358
47
0.487846
JeraKrs
1a0ed3e7186d638471d1b6fd0a646abe72bf17ce
871
cpp
C++
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
19
2018-12-02T05:59:44.000Z
2021-07-24T14:11:54.000Z
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
null
null
null
Binary Tree/Ancestors_Of_A_Node.cpp
susantabiswas/placementPrep
22a7574206ddc63eba89517f7b68a3d2f4d467f5
[ "MIT" ]
13
2019-04-25T16:20:00.000Z
2021-09-06T19:50:04.000Z
//Print all the ancestors of a given node #include<iostream> using namespace std; struct Node { int data; Node *left; Node *right; }; //creates a node Node* create(int data) { try { Node *node=new Node; node->data=data; node->left=NULL; node->right=NULL; return node; } catch(bad_alloc xa) { cout<<"Memory overflow!!"; return NULL; } } //prints all the ancestors of a gievn key node bool printAncestors(Node *root,int key) { if(root==NULL) return false; if(root->data==key) return true; if(printAncestors(root->left,key)||printAncestors(root->right,key)) { cout<<root->data<<" "; return true; } else false; } int main() { Node *root=create(1); root->left=create(2); root->right=create(3); root->left->left=create(4); root->right->right=create(6); root->left->right=create(5); if(printAncestors(root,4)); return 0; }
14.278689
68
0.657865
susantabiswas
1a0ff312380fc1200503bb7f17cbbec9408ee287
404
hpp
C++
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
examples/rucksack/testbed/include/sge/rucksack/testbed/object_impl_fwd.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_RUCKSACK_TESTBED_OBJECT_IMPL_FWD_HPP_INCLUDED #define SGE_RUCKSACK_TESTBED_OBJECT_IMPL_FWD_HPP_INCLUDED namespace sge::rucksack::testbed { class object_impl; } #endif
23.764706
61
0.759901
cpreh
1a10a79e16490f9837cc80b4d97b6cc4c35fa011
835
cpp
C++
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
3
2019-07-03T14:03:31.000Z
2021-12-19T10:18:49.000Z
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
6
2020-02-17T12:01:30.000Z
2021-12-09T22:02:33.000Z
streambox/WinKeyReducer/WinKeyReducerEval-yahoo-winbundle.cpp
chenzongxiong/streambox
76f95780d1bf6c02731e39d8ac73937cea352b95
[ "Unlicense" ]
2
2020-12-03T04:41:18.000Z
2021-01-11T21:44:42.000Z
// // Created by manuelrenz on 12.04.18. // #include "WinKeyReducerEval.h" /* ----------------------------------------- * specialized for yahoo -- using normal hashtable * NB: we have to do full specialization per C++ * ----------------------------------------- */ // using MyWinKeyReduerEval = WinKeyReducerEval<std::pair<uint64_t, long>, /* kv in */ // WinKeyFragLocal_Std, WinKeyFrag_Std, /* internal map format */ // std::pair<uint64_t, long>, /* kvout */ // WindowsBundle /* output bundle */ // >; using MyWinKeyReduerEval = WinKeyReducerEval<std::pair<uint64_t, uint64_t>, /* kv in */ WinKeyFragLocal_Std, WinKeyFrag_Std, /* internal map format */ std::pair<uint64_t, uint64_t>, /* kvout */ WindowsBundle /* output bundle */ >; #include "WinKeyReducerEval-yahoo-common.h"
32.115385
87
0.590419
chenzongxiong
1a143a76a1c87083c7987e104a76b6db72592a9f
554
cpp
C++
Codechef - Contests/JULY16/POLYEVAL.cpp
Gurupradeep/Codes
5595f2e0f867a2a21d050379ead18bd6ef563978
[ "MIT" ]
null
null
null
Codechef - Contests/JULY16/POLYEVAL.cpp
Gurupradeep/Codes
5595f2e0f867a2a21d050379ead18bd6ef563978
[ "MIT" ]
null
null
null
Codechef - Contests/JULY16/POLYEVAL.cpp
Gurupradeep/Codes
5595f2e0f867a2a21d050379ead18bd6ef563978
[ "MIT" ]
null
null
null
#include<bits/stdc++.h> using namespace std; #define MOD 786433 int main() { long long n; long long a[10002]; scanf("%lld",&n); for(int i=0;i<=n;i++) scanf("%lld",&a[i]); long long q; scanf("%lld",&q); while(q--) { long long x; scanf("%lld",&x); long long ans = a[0]; long long temp = 1; for(int i=1;i<=n;i++) { temp = (temp*x)%MOD; ans = (ans + (temp*a[i])%MOD)%MOD; } printf("%lld\n",ans); } }
20.518519
47
0.415162
Gurupradeep
1a150466293290bde2678ab09e37514c5e673198
594
cpp
C++
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
1
2017-12-24T07:51:07.000Z
2017-12-24T07:51:07.000Z
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
null
null
null
LeetCode/0003.LongestSubstringWithoutRepeatingCharacters/LSWRC.cpp
luspock/algorithms
91644427f3f683481f911f6bc30c9eeb19934cdd
[ "MIT" ]
null
null
null
#include <unordered_map> #include <iostream> #include <string> int lengthOfLongestSubstring(std::string s){ std::unordered_map<char, int> smap; int n = s.length(); int max_length = 0; if(n<2){ return n; } for(int i=0,j=0;j<n;++j){ char c = s.at(j); if(smap.count(c)){ i=smap[c]>i?smap[c]:i; } smap[c]=j+1; max_length = max_length<(j-i+1)?(j-i+1):max_length; } return max_length; }; int main(int argc, char **argv){ std::string test_s = "pwwerkw"; std::cout<< test_s<<"\n"; std::cout<<lengthOfLongestSubstring(test_s)<<"\n"; return 0; };
20.482759
54
0.60101
luspock
1a188685b8533ef9c29a86aa81c89e2f18be079a
794
cpp
C++
tests/test/main.cpp
n-krueger/faabric
c95c3baf9406613629e5f382efc0fc8366b22752
[ "Apache-2.0" ]
null
null
null
tests/test/main.cpp
n-krueger/faabric
c95c3baf9406613629e5f382efc0fc8366b22752
[ "Apache-2.0" ]
null
null
null
tests/test/main.cpp
n-krueger/faabric
c95c3baf9406613629e5f382efc0fc8366b22752
[ "Apache-2.0" ]
null
null
null
#define CATCH_CONFIG_RUNNER #include <catch.hpp> #include "faabric_utils.h" #include <faabric/util/logging.h> #include <faabric/util/testing.h> struct LogListener : Catch::TestEventListenerBase { using TestEventListenerBase::TestEventListenerBase; void testCaseStarting(Catch::TestCaseInfo const& testInfo) override { auto logger = faabric::util::getLogger(); logger->debug("---------------------------------------------"); logger->debug("TEST: {}", testInfo.name); logger->debug("---------------------------------------------"); } }; CATCH_REGISTER_LISTENER(LogListener) int main(int argc, char* argv[]) { faabric::util::setTestMode(true); int result = Catch::Session().run(argc, argv); fflush(stdout); return result; }
23.352941
71
0.602015
n-krueger
1a19c14e380f519b3eedb83c76f7ee7dcd473c07
57
hpp
C++
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_fusion_view_filter_view_filter_view.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/fusion/view/filter_view/filter_view.hpp>
28.5
56
0.824561
miathedev
1a1b0f533febd3eea6b49484a2587e41d528f5e9
1,938
cpp
C++
uva/nonstop.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
uva/nonstop.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
uva/nonstop.cpp
bryanoliveira/programming-marathon
071e3e6898f9b10cabbf4ed0d8ba1c5fbbf3fac4
[ "MIT" ]
null
null
null
#include <bits/stdc++.h> using namespace std; int main() { int ni, ncase = 1; while(cin >> ni && ni) { map<int, vector<pair<int, int> > > graph; // from -> [to, cost] for(int i = 1; i <= ni; i++) { int roads; cin >> roads; while (roads > 0) { int outroad, cost; cin >> outroad >> cost; graph[i].push_back({outroad, cost}); roads--; } } int s, t; cin >> s >> t; priority_queue< pair<int, int>, vector< pair<int, int> >, greater< pair<int, int> > > que; vector<bool> vis; vector<int> dist; vector<int> pred; dist.resize(ni + 1, INT_MAX); pred.resize(ni + 1, INT_MAX); vis.resize(ni + 1, false); que.push({0, s}); dist[s] = 0; pred[s] = -1; while(!que.empty()) { int atual = que.top().second; que.pop(); if(vis[atual]) continue; for(int i = 0; i < graph[atual].size(); i++) { int vizinho = graph[atual].at(i).first; int cost = graph[atual].at(i).second; if(dist[vizinho] > dist[atual] + cost) { dist[vizinho] = dist[atual] + cost; pred[vizinho] = atual; que.push({dist[vizinho], vizinho}); } } vis[atual] = true; } vector<int> path; int atual = t; do { path.insert(path.begin(), atual); atual = pred[atual]; } while(atual > -1); cout << "Case " << ncase << ": Path ="; for(int i = 0; i < path.size(); i++) cout << " " << path[i]; cout << "; " << dist[t] << " second delay" << endl; ncase++; } return 0; }
26.547945
99
0.400413
bryanoliveira
1a1bf305dff57f8ef966632556b29af27fdd2b66
1,162
cpp
C++
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
gesture-sensor.cpp
memorial-ece/arduino-seeed
170875ab65aff1a00e05fe2a5eb4c8049ea82525
[ "BSD-2-Clause" ]
null
null
null
#include "gesture-sensor.h" #include "Gesture_PAJ7620/paj7620.h" /** Initialiazes gesture sensor **/ unsigned int gestureInit() { paj7620Init(); } /** Reads gesture sensor and returns value of gesture (or 0 if no gesture detected) For more info see: http://wiki.seeedstudio.com/Grove-Gesture_v1.0/ @returns data = 0 if no gesture detected, otherwise the value of one of the constants below Up Gesture, data = GES_UP_FLAG Down Gesture, data = GES_DOWN_FLAG Left Gesture, data = GES_LEFT_FLAG Right Gesture, data = GES_RIGHT_FLAG Forward Gesture, data = GES_FORWARD_FLAG Backward Gesture, data = GES_BACKWARD_FLAG Clockwise Gesture, data = GES_CLOCKWISE_FLAG Count Clockwise Gesture, data = GES_COUNT_CLOCKWISE_FLAG Wave Gesture, data = GES_WAVE_FLAG */ unsigned int gestureRead() { unsigned char gestureData = 0; // Read Bank_0_Reg_0x43/0x44 for gesture result. paj7620ReadReg(0x43, 1, &gestureData); // When different gestures be detected, the variable 'data' will be set to different values by paj7620ReadReg(0x43, 1, &data). if (gestureData == 0) //check for wave paj7620ReadReg(0x44, 1, &gestureData); return gestureData; }
29.05
170
0.754733
memorial-ece
1a1e6d1996dd998faef62fad2eac4b71a73a209c
3,009
cc
C++
src/sys/fuzzing/framework/engine/adapter-client-unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-12-29T10:11:08.000Z
2022-01-04T15:37:09.000Z
src/sys/fuzzing/framework/engine/adapter-client-unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
src/sys/fuzzing/framework/engine/adapter-client-unittest.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/sys/fuzzing/framework/engine/adapter-client.h" #include <fuchsia/fuzzer/cpp/fidl.h> #include <string> #include <vector> #include <gtest/gtest.h> #include "src/lib/files/directory.h" #include "src/lib/files/file.h" #include "src/lib/files/path.h" #include "src/sys/fuzzing/common/input.h" #include "src/sys/fuzzing/common/options.h" #include "src/sys/fuzzing/common/signal-coordinator.h" #include "src/sys/fuzzing/framework/engine/corpus.h" #include "src/sys/fuzzing/framework/testing/adapter.h" using fuchsia::fuzzer::TargetAdapterSyncPtr; namespace fuzzing { // Test fixtures class TargetAdapterClientTest : public ::testing::Test { protected: std::shared_ptr<Options> DefaultOptions() { auto options = std::make_shared<Options>(); TargetAdapterClient::AddDefaults(options.get()); return options; } void Configure(const std::shared_ptr<Options>& options) { adapter_ = std::make_unique<FakeTargetAdapter>(); client_ = std::make_unique<TargetAdapterClient>(adapter_->GetHandler()); client_->Configure(options); } std::unique_ptr<FakeTargetAdapter> TakeAdapter() { return std::move(adapter_); } std::unique_ptr<TargetAdapterClient> TakeClient() { return std::move(client_); } private: std::unique_ptr<FakeTargetAdapter> adapter_; std::unique_ptr<TargetAdapterClient> client_; }; // Unit tests TEST_F(TargetAdapterClientTest, AddDefaults) { Options options; TargetAdapterClient::AddDefaults(&options); EXPECT_EQ(options.max_input_size(), kDefaultMaxInputSize); } TEST_F(TargetAdapterClientTest, StartAndFinish) { Configure(DefaultOptions()); auto adapter = TakeAdapter(); auto client = TakeClient(); Input sent("foo"); client->Start(&sent); EXPECT_EQ(adapter->AwaitSignal(), kStart); EXPECT_EQ(adapter->test_input(), sent); adapter->SignalPeer(kFinish); client->AwaitFinish(); } TEST_F(TargetAdapterClientTest, StartAndError) { Configure(DefaultOptions()); auto adapter = TakeAdapter(); auto client = TakeClient(); Input sent1("foo"); client->Start(&sent1); EXPECT_EQ(adapter->AwaitSignal(), kStart); EXPECT_EQ(adapter->test_input(), sent1); client->SetError(); client->AwaitFinish(); // |Start| after |SetError| is a no-op... Input sent2("bar"); client->Start(&sent2); client->AwaitFinish(); // ...until |ClearError|. client->ClearError(); client->Start(&sent2); EXPECT_EQ(adapter->AwaitSignal(), kStart); EXPECT_EQ(adapter->test_input(), sent2); adapter->SignalPeer(kFinish); client->AwaitFinish(); } TEST_F(TargetAdapterClientTest, StartAndClose) { Configure(DefaultOptions()); auto adapter = TakeAdapter(); auto client = TakeClient(); Input sent("foo"); client->Start(&sent); EXPECT_EQ(adapter->AwaitSignal(), kStart); client->Close(); client->AwaitFinish(); } } // namespace fuzzing
27.108108
82
0.724826
allansrc
1a21833b125a42eaea4adc2df9fbb966b754a605
2,744
cpp
C++
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
bitreverse.cpp
k9bao/tools
18b52767f4e6c9e5001462d828b1bba69c3832a0
[ "Apache-2.0" ]
null
null
null
#include <cstring> #include <ctime> #include <fstream> #include <iostream> using namespace std; void usage() { cout << "para is error." << endl; cout << "example: a.out in out pwd" << endl; } std::chrono::steady_clock::time_point now() { return std::chrono::steady_clock::now(); } long long subSecond(std::chrono::steady_clock::time_point before) { return std::chrono::duration_cast<std::chrono::seconds>(now() - before).count(); } int main(int argc, char **argv) { if (argc != 4) { usage(); return -1; } string file = argv[1]; long long totalSize = 0; ifstream in(file, ios::in | ios::in | ios::binary); if (in.is_open() == false) { cout << file << " is can not open.[read]" << endl; return -1; } else { in.seekg(0, ios_base::end); totalSize = in.tellg(); in.seekg(0, ios_base::beg); } string outFile = argv[2]; ofstream out(outFile, ios::out | ios::binary | ios::ate); if (out.is_open() == false) { cout << outFile << " is can not open.[write]" << endl; return -1; } long long pw; if (strlen(argv[3]) > 0) { pw = std::atoll(argv[3]); } else { usage(); return -1; } bool encode = true; unsigned long long curSize = 0; const int size = 4096; char buffer[size]; string head = "lahFv9y&RCluQl%r8bNzh#FiCml7!%tq"; auto count = in.read(buffer, head.size()).gcount(); if (count == head.size() && memcmp(buffer, head.c_str(), head.size()) != 0) { for (size_t i = 0; i < count; i++) { if (((curSize + i) % pw) != 0) { buffer[i] = ~buffer[i]; } } curSize += count; out.write(head.c_str(), head.size()); out.write(buffer, count); cout << "file is will encode" << endl; } else { cout << "file is will decode" << endl; encode = false; } auto curTime = now(); while (true) { if (in.good() == false) { break; } auto count = in.read(buffer, size).gcount(); for (size_t i = 0; i < count; i++) { if (((curSize + i) % pw) != 0) { buffer[i] = ~buffer[i]; } } curSize += count; if (count > 0) { out.write(buffer, count); } if (subSecond(curTime) >= 10) { curTime = now(); cout << "process is " << (double)curSize / totalSize << endl; } } if (in.eof() && out.good()) { cout << "process ok" << endl; return -1; } else { cout << "process fail" << endl; return -1; } in.close(); out.close(); return 0; }
25.64486
84
0.492347
k9bao
1a21cb2d3ab3b4f974a0062f92d74b4be234f1e9
1,560
cpp
C++
example_contests/fk_2014_beta/problems/rod/submissions/accepted/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
6
2016-03-28T13:57:54.000Z
2017-07-25T06:04:05.000Z
example_contests/fk_2014_delta/problems/rod/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
25
2015-01-23T18:02:35.000Z
2015-03-17T01:40:27.000Z
example_contests/fk_2014_delta/problems/rod/solution_2.cpp
ForritunarkeppniFramhaldsskolanna/epsilon
a31260ad33aba3d1846cda585840d7e7d2f2349c
[ "MIT" ]
3
2016-06-28T00:48:38.000Z
2017-05-25T05:29:25.000Z
#include <algorithm> #include <bitset> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> #include <cstring> #include <ctime> #include <fstream> #include <iomanip> #include <iostream> #include <list> #include <map> #include <queue> #include <set> #include <sstream> #include <stack> #include <string> #include <utility> #include <vector> using namespace std; #define all(o) (o).begin(), (o).end() #define allr(o) (o).rbegin(), (o).rend() const int INF = 2147483647; typedef long long ll; typedef pair<int, int> ii; typedef vector<int> vi; typedef vector<ii> vii; typedef vector<vi> vvi; typedef vector<vii> vvii; template <class T> int size(T &x) { return x.size(); } // assert or gtfo int main() { int n, m; scanf("%d %d\n", &n, &m); int **step = new int*[m]; for (int i = 0; i < m; i++) { step[i] = new int[n]; memset(step[i], 0, n << 2); } for (int i = 0; i < m; i++) { string line; getline(cin, line); for (int j = 0; j < n; j++) { if (2*j-1 >= 0 && line[2*j-1] == '-') assert(step[i][j] == 0), step[i][j] = -1; if (2*j+1 < size(line) && line[2*j+1] == '-') assert(step[i][j] == 0), step[i][j] = 1; } } char *res = new char[n]; for (int i = 0; i < n; i++) { int at = i; for (int r = 0; r < m; r++) { at += step[r][at]; } res[at] = 'A' + i; } for (int i = 0; i < n; i++) printf("%c", res[i]); printf("\n"); return 0; }
19.5
98
0.502564
ForritunarkeppniFramhaldsskolanna
1a23311b821d1bb428105d6656d6357ef83fc1b0
732
cpp
C++
TAO/tao/Strategies/OC_Endpoint_Selector_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
36
2015-01-10T07:27:33.000Z
2022-03-07T03:32:08.000Z
TAO/tao/Strategies/OC_Endpoint_Selector_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
2
2018-08-13T07:30:51.000Z
2019-02-25T03:04:31.000Z
TAO/tao/Strategies/OC_Endpoint_Selector_Loader.cpp
cflowe/ACE
5ff60b41adbe1772372d1a43bcc1f2726ff8f810
[ "DOC" ]
38
2015-01-08T14:12:06.000Z
2022-01-19T08:33:00.000Z
// ================================================================= /** * @file OC_Endpoint_Selector_Loader.cpp * * $Id: OC_Endpoint_Selector_Loader.cpp 91628 2010-09-07 11:11:12Z johnnyw $ * * @author Phil Mesnier <mesnier_p@ociweb.com> * */ // ================================================================= // $Id: OC_Endpoint_Selector_Loader.cpp 91628 2010-09-07 11:11:12Z johnnyw $ #include "tao/Strategies/OC_Endpoint_Selector_Loader.h" #include "tao/Strategies/OC_Endpoint_Selector_Factory.h" TAO_BEGIN_VERSIONED_NAMESPACE_DECL int TAO_OC_Endpoint_Selector_Loader::init (void) { return ACE_Service_Config::process_directive (ace_svc_desc_TAO_OC_Endpoint_Selector_Factory); } TAO_END_VERSIONED_NAMESPACE_DECL
29.28
96
0.653005
cflowe
1a2d220b03104c81c8e904a466f499037ba4da15
398
cpp
C++
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_9/Lesson 9.6 Default Constructor That Accepts Parameters with Default Values to Set Members Using Initialization Lists.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_9/Lesson 9.6 Default Constructor That Accepts Parameters with Default Values to Set Members Using Initialization Lists.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
Courses/Sams_Teach_Yourself_C++_in_One_Hour_a_Day/Chap_9/Lesson 9.6 Default Constructor That Accepts Parameters with Default Values to Set Members Using Initialization Lists.cpp
mccrudd3n/practise
26a65c0515c9bea7583bcb8f4c0022659b48dcf5
[ "Unlicense" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Human { private: string Name; int Age; public: Human(string InputName = "Adam", int InputAge = 22) :Name(InputName), Age(InputAge) { cout << "Constructed a Human called " << Name; cout << ", " << Age << " years old" << endl; } }; int main() { Human FirstMan; Human FirstWoman("Alice", 21); return 0; }
14.214286
53
0.613065
mccrudd3n
1a2ef9f4e0f1a167b3ccd77dfee875e7e2e5f181
375
cpp
C++
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
39
2015-01-22T08:13:28.000Z
2021-02-03T07:29:56.000Z
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
20
2015-04-27T02:35:31.000Z
2021-01-20T16:47:23.000Z
tests/e2e/e2e_test_case.cpp
avs/odatacpp-client
c2af181468d345aef0c952a8a0182a1ff11b4b57
[ "MIT" ]
30
2015-01-29T21:23:57.000Z
2021-01-11T14:19:47.000Z
//--------------------------------------------------------------------- // <copyright file="e2e_test_case.cpp" company="Microsoft"> // Copyright (C) Microsoft Corporation. All rights reserved. See License.txt in the project root for license information. // </copyright> //--------------------------------------------------------------------- #include "e2e_test_case.h"
53.571429
126
0.458667
avs
1a2f2aff78994a592508932704d8b48c8e74ec75
2,505
cpp
C++
books/C++_advanced_programming/code/Chapter23/Logger.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
5
2019-09-17T09:12:15.000Z
2021-05-29T10:54:39.000Z
C++11/C++11_1/Logger.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
null
null
null
C++11/C++11_1/Logger.cpp
liangjisheng/C-Cpp
8b33ba1f43580a7bdded8bb4ce3d92983ccedb81
[ "MIT" ]
2
2021-07-26T06:36:12.000Z
2022-01-23T15:20:30.000Z
#include <iostream> #include "Logger.h" #include <fstream> using std::thread; using std::cout; using std::endl; using std::cerr; using std::unique_lock; using std::mutex; using std::ofstream; //Logger::Logger() //{ // // Start background thread // mThread = thread{ &Logger::processEntries, this }; //} //void Logger::log(const std::string& entry) //{ // // Lock mutex and entry to the queue // unique_lock<mutex> lock(mMutex); // mQueue.push(entry); // // Notify condition variable to wake up thread // mCondVar.notify_all(); //} //void Logger::processEntries() //{ // // Open log file. // ofstream ofs("log.txt"); // if (ofs.fail()) // { // cerr << "Failed to open logfile." << endl; // return; // } // // // Start processing loop. // unique_lock<mutex> lock(mMutex); // while (true) // { // // Wait for a notification // mCondVar.wait(lock); // // Condition variable is notified, so something might be in the queue. // lock.unlock(); // while (true) // { // lock.lock(); // if (mQueue.empty()) // break; // else // { // ofs << mQueue.front() << endl; // mQueue.pop(); // } // lock.unlock(); // } // } //} Logger::Logger() : mExit(false) { // Start background thread mThread = thread{ &Logger::processEntries, this }; } Logger::~Logger() { { unique_lock<mutex> lock(mMutex); // Gracefully shut down the thread by setting mExit. // to true and notifying the thread. mExit = true; // Notify condition variable to wake up thread mCondVar.notify_all(); } // Wait unitl thread is shut down. This should be outside the above code // block because the lock on mMutex must be released before calling join() mThread.join(); } void Logger::log(const std::string& entry) { // Lock mutex and entry to the queue unique_lock<mutex> lock(mMutex); mQueue.push(entry); // Notify condition variable to wake up thread mCondVar.notify_all(); } void Logger::processEntries() { // Open log file. ofstream ofs("log.txt"); if (ofs.fail()) { cerr << "Failed to open logfile." << endl; return; } // Start processing loop. unique_lock<mutex> lock(mMutex); while (true) { if (!mExit) mCondVar.wait(lock); // Wait for a notification // mCondVar.wait(lock); // Condition variable is notified, so something might be in the queue. lock.unlock(); while (true) { lock.lock(); if (mQueue.empty()) break; else { ofs << mQueue.front() << endl; mQueue.pop(); } lock.unlock(); } if (mExit) break; } }
18.284672
75
0.631138
liangjisheng
1a31cdf344682d4a296557effad4459f6f2376ff
17,601
cpp
C++
src/UnitTest.cpp
ibest/seqyclean
45d6d52ffc62078c91588ef3c10f28ff8e1dca13
[ "MIT" ]
22
2015-08-25T16:39:55.000Z
2022-03-10T12:37:45.000Z
src/UnitTest.cpp
ibest/seqyclean
45d6d52ffc62078c91588ef3c10f28ff8e1dca13
[ "MIT" ]
4
2015-06-22T18:56:01.000Z
2020-05-19T06:57:13.000Z
src/UnitTest.cpp
ibest/seqyclean
45d6d52ffc62078c91588ef3c10f28ff8e1dca13
[ "MIT" ]
4
2015-11-02T18:43:01.000Z
2017-12-13T15:29:11.000Z
/* * File: UnitTest.cpp * Author: kwt * * Created on July 28, 2013, 11:18 AM */ #include "UnitTest.h" UnitTest::UnitTest() { //Test Illumina PE //Test Illumina SE //Test overlap Illumins } UnitTest::UnitTest(const UnitTest& orig) { } UnitTest::~UnitTest() { } void UnitTest::Test454() { //Test 454 roche_names.push_back("test_data/in.sff"); trim_adapters_flag = true; qual_trim_flag = true; output_prefix = "UnitTest454"; sum_stat_tsv << "Version\tFiles\tNUM_THREADS\tAdaptersTrimming\tVectorTrimming\tkmer_size\tDistance\tContamScr\tkmer_contam_size\tQualTrim\tQual_max_avg_error\tQual_max_err_at_ends\tOutputPrefix\tRepFilename\tOutputFilename\tMax_align_mismatches\tMinReadLen\tReadsAnalyzed\tBases\tleft_mid_tags_found\tpercentage_left_mid_tags_found\tright_mid_tags_found\tpercentage_right_mid_tags_found\tReadsWithVector_found\tpercentage_ReadsWithVector_found\tReadsWithContam_found\tpercentage_ReadsWithContam_found\tLeftTrimmedByAdapter\tLeftTrimmedByQual\tLeftTrimmedByVector\tAvgLeftTrimLen\tRightTrimmedByAdapter\tRightTrimmedByQual\tRightTrimmedByVector\tAvgRightTrimLen\tDiscardedTotal\tDiscByContam\tDiscByLength\tReadsKept\tPercentageKept\tAvgTrimmedLen\n"; cout << "Unit test 454..." << endl; cout << "--------------------Basic parameters--------------------\n"; sum_stat << "--------------------Basic parameters--------------------\n"; cout << "Provided data file(s) : \n" ; sum_stat << "Provided data file(s) : \n" ; for(int i=0; i<(int)roche_names.size(); ++i) { cout << roche_names[i] << "\n"; sum_stat << roche_names[i] << "\n"; } cout << string("Adapters trimming: ") + ( trim_adapters_flag ? "YES. Custom RLMIDS: " + ( custom_rlmids_flag ? "YES, file_of_RL_MIDS: " + string(rlmids_file) : "NO. Default RL MIDs will be used." ) : " ") << endl; sum_stat << string("Adapters trimming: ") + ( trim_adapters_flag ? "YES. Custom RLMIDS: " + ( custom_rlmids_flag ? "YES, file_of_RL_MIDS: " + string(rlmids_file) : "NO. Default RL MIDs will be used." ) : " " ) << endl; if(vector_flag) { cout << "Vector screening: YES. Vector_file provided: " << vector_file << endl; sum_stat << "Vector screening: YES. Vector_file provided: " << vector_file << endl; cout << "K-mer_size for for vector trimming: " << KMER_SIZE << " bp\n"; sum_stat << "K-mer_size for vector trimming: " << KMER_SIZE << " bp\n"; cout << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; sum_stat << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; } else { cout << "Vector screening: NO" << endl; sum_stat << "Vector screening: NO" << endl; } if(contaminants_flag) { cout << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; sum_stat << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; cout << "K-mer size for contaminants: " << KMER_SIZE_CONT << " bp\n"; sum_stat << "K-mer size for contaminants: " << KMER_SIZE_CONT << " bp\n"; } else { cout << "Contaminants screening: NO" << endl; sum_stat << "Contaminants screening: NO" << endl; } if(qual_trim_flag) { cout << "Quality trimming: YES" << endl; sum_stat << "Quality trimming: YES" << endl; cout << "Maximim error: " << -10*log10(max_a_error) << endl; sum_stat << "Maximim error: " << -10*log10(max_a_error) << endl; cout << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; sum_stat << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; } else { cout << "Quality trimming: NO" << endl; sum_stat << "Quality trimming: NO" << endl; } cout << "--------------------Output files--------------------\n"; sum_stat << "--------------------Output files--------------------\n"; cout << "Output prefix: " << output_prefix << endl; sum_stat << "Output prefix: " << output_prefix << endl; roche_output_file_name = output_prefix + ".sff";// + (output_fastqfile_flag ? ", " + output_prefix + ".fastq" : "" ); roche_rep_file_name = output_prefix + "_Report.tsv" ; cout << "Report file: " << roche_rep_file_name << "\n"; sum_stat << "Report file: " << roche_rep_file_name << "\n"; cout << "Roche output file(s): " << ( roche_output_file_name + (output_fastqfile_flag ? ", " + output_prefix + ".fastq" : "" ) ) << "\n"; sum_stat << "Roche output file(s): " << ( roche_output_file_name + (output_fastqfile_flag ? ", " + output_prefix + ".fastq" : "" ) ) << "\n"; cout << "--------------------Other parameters--------------------\n"; sum_stat << "--------------------Other parameters--------------------\n"; cout << "k-mer_size: " << KMER_SIZE << " bp\n"; sum_stat << "k-mer_size: " << KMER_SIZE << " bp\n"; cout << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; sum_stat << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; cout << "Minimum read length to accept: " << minimum_read_length << " bp\n"; sum_stat << "Minimum read length to accept: " << minimum_read_length << " bp\n"; cout << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; sum_stat << "Distance between the first bases of two consequitve kmers: " << DISTANCE << " bp\n"; cout << "number_of_threads: " << NUM_THREADS << endl; sum_stat << "number_of_threads: " << NUM_THREADS << endl; if(vector_flag ) { BuildVectorDictionary(vector_file); } if(contaminants_flag ) { /*Building dictionary for contaminants :*/ BuildContDictionary(cont_file); } RocheRoutine(); } void UnitTest::TestIlluminaPE() { cout << "--------------------Basic parameters--------------------\n"; sum_stat << "--------------------Basic parameters--------------------\n"; //Sum stat TSV header sum_stat_tsv << "Version\tPE1PE2\tAdapters_trim\tVectorTrim\tK_mer_size\tDistance\tContamScr\tkc_size\tQualTrim\tQual_max_avg_error\tQual_max_err_at_ends\tOutputPrefix\tRepFilename1\tRepFilename2\tPE1OutputFilename\tPE2OutputFilename\tShuffledFilename\tSEFilename\tMax_align_mismatches\tMinReadLen\tnew2old_illumina\tPE1ReadsAn\tPE1Bases\tPE1TruSeqAdap_found\tPerc_PE1TruSeq\tPE1ReadsWVector_found\tPerc_PE1ReadsWVector\tPE1ReadsWContam_found\tPerc_PE1ReadsWContam\tPE1LeftTrimmedQual\tPE1LeftTrimmedVector\tPE1AvgLeftTrimLen\tPE1RightTrimmedAdap\tPE1RightTrimmedQual\tPE1RightTrimmedVector\tPE1AvgRightTrimLen\tPE1DiscardedTotal\tPE1DiscByContam\tPE1DiscByLength\tPE2ReadsAn\tPE2Bases\tPE2TruSeqAdap_found\tPerc_PE2TruSeq\tPE2ReadsWVector_found\tPerc_PE2ReadsWVector\tPE2ReadsWContam_found\tPerc_PE2ReadsWContam\tPE2LeftTrimmedQual\tPE2LeftTrimmedVector\tPE2AvgLeftTrimLen\tPE2RightTrimmedAdap\tPE2RightTrimmedQual\tPE2RightTrimmedVector\tPE2AvgRightTrimLen\tPE2DiscardedTotal\tPE2DiscByContam\tPE2DiscByLength\tPairsKept\tPerc_Kept\tBases\tPerc_Bases\tPairsDiscarded\tPerc_Discarded\tBases\tPerc_Bases\tSE_PE1_Kept\tSE_PE1_Bases\tSE_PE2_Kept\tSE_PE2_Bases\tAvgTrimmedLenPE1\tAvgTrimmedLenPE2\tAvgLenPE1\tAvgLenPE2\tperfect_ov\tpartial_ov\n"; cout << "Provided data files : " << endl; sum_stat << "Provided data files : " << endl; string filename_str = ""; for(int i=0; i<(int)pe1_names.size(); ++i) { cout << "PE1: " << pe1_names[i] << ", PE2: " << pe2_names[i] << endl; sum_stat << "PE1: " << pe1_names[i] << ", PE2: " << pe2_names[i] << endl; filename_str += "\t" + string(pe1_names[i]) + "\t" + string(pe2_names[i]); } cout << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; sum_stat << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; if(vector_flag) { cout << "Vector screening: YES. Vector_file provided: " << vector_file << endl; sum_stat << "Vector screening: YES. Vector_file provided: " << vector_file << endl; cout << "K-mer_size for for vector trimming: " << KMER_SIZE << endl; sum_stat << "K-mer_size for vector trimming: " << KMER_SIZE << endl; cout << "Distance between the first bases of two consecutive kmers: " << DISTANCE << endl; sum_stat << "Distance between the first bases of two consecutive kmers: " << DISTANCE << endl; } else { cout << "Vector screening: NO" << endl; sum_stat << "Vector screening: NO" << endl; } if(contaminants_flag) { cout << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; sum_stat << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; cout << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; sum_stat << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; } else { cout << "Contaminants screening: NO" << endl; sum_stat << "Contaminants screening: NO" << endl; } if(qual_trim_flag) { cout << "Quality trimming: YES" << endl; sum_stat << "Quality trimming: YES" << endl; cout << "Maximum error: " << -10*log10(max_a_error) << endl; sum_stat << "Maximum error: " << -10*log10(max_a_error) << endl; cout << "Maximum error at ends: " << -10*log10(max_e_at_ends) << endl; sum_stat << "Maximum error at ends: " << -10*log10(max_e_at_ends) << endl; } else { cout << "Quality trimming: NO" << endl; sum_stat << "Quality trimming: NO" << endl; } cout << "--------------------Output files--------------------\n"; sum_stat << "--------------------Output files--------------------\n"; cout << "Output prefix: " << output_prefix << endl; sum_stat << "Output prefix: " << output_prefix << endl; rep_file_name1 = output_prefix + "_PE1_Report.tsv"; rep_file_name2 = output_prefix + "_PE2_Report.tsv"; pe_output_filename1 = output_prefix + "_PE1.fastq" ; pe_output_filename2 = output_prefix + "_PE2.fastq" ; shuffle_filename = output_prefix + "_shuffled.fastq"; se_filename = output_prefix + "_SE.fastq"; cout << "Report files: " << rep_file_name1 << ", " << rep_file_name2 << endl; sum_stat << "Report files: " << rep_file_name1 << ", " << rep_file_name2 << endl; if (!shuffle_flag) { cout << "PE1 file: " << pe_output_filename1 << endl; sum_stat << "PE1 file: " << pe_output_filename1 << endl; cout << "PE2 file: " << pe_output_filename2 << endl; sum_stat << "PE2 file: " << pe_output_filename2 << endl; } else { cout << "Shuffled file: " << shuffle_filename << endl; sum_stat << "Shuffled file: " << shuffle_filename << endl; } cout << "Single-end reads: "<< se_filename << endl; sum_stat << "Single-end reads: "<< se_filename << endl; if(overlap_flag) { overlap_file_name = output_prefix + "_SEOLP.fastq"; sum_stat << "Single-end overlapped reads: "<< overlap_file_name << endl; } cout << "--------------------Other parameters--------------------\n"; sum_stat << "--------------------Other parameters--------------------\n"; cout << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; sum_stat << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; cout << "Minimum read length to accept: " << minimum_read_length << endl; sum_stat << "Minimum read length to accept: " << minimum_read_length << endl; cout << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; sum_stat << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; cout << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; sum_stat << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; cout << "Q-value: " << phred_coeff_illumina << endl; sum_stat << "Q-value: " << phred_coeff_illumina << endl; } void UnitTest::TestIlluminaSE() { sum_stat_tsv << "Version\tSE\tAdapters_trim\tVectorTrim\tK_mer_size\tDistance\tContamScr\tkc_size\tQualTrim\tQual_max_avg_error\tQual_max_err_at_ends\tOutputPrefix\tRepFilename\ttSEOutputFilename\tMax_align_mismatches\tMinReadLen\tnew2old_illumina\tSEReadsAn\tSEBases\tSETruSeqAdap_found\tPerc_SETruSeq\tSEReadsWVector_found\tPerc_SEReadsWVector\tSEReadsWContam_found\tPerc_SEReadsWContam\tSELeftTrimmedQual\tSELeftTrimmedVector\tSEAvgLeftTrimLen\tSERightTrimmedAdap\tSERightTrimmedQual\tSERightTrimmedVector\tSEAvgRightTrimLen\tSEDiscardedTotal\tSEDiscByContam\tSEDiscByLength\tSEReadsKept\tPerc_Kept\tBases\tPerc_Bases\tAvgTrimmedLenSE\n"; cout << "Provided data file(s) : " << endl; sum_stat << "Provided data file(s) : " << endl; for(int i=0; i<(int)se_names.size(); ++i) { cout << "SE: " << se_names[i] << endl; sum_stat << "SE: " << se_names[i] << endl; } cout << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; sum_stat << "Adapters trimming: " << (trim_adapters_flag ? "YES. " : "NO") << endl; if(vector_flag) { cout << "Vector screening: YES. Vector_file provided: " << vector_file << endl; sum_stat << "Vector screening: YES. Vector_file provided: " << vector_file << endl; cout << "K-mer_size for for vector trimming: " << KMER_SIZE << endl; sum_stat << "K-mer_size for vector trimming: " << KMER_SIZE << endl; cout << "Distance between the first bases of two consequitve kmers: " << DISTANCE << endl; sum_stat << "Distance between the first bases of two consequitve kmers: " << DISTANCE << endl; } else { cout << "Vector screening: NO" << endl; sum_stat << "Vector screening: NO" << endl; } if(contaminants_flag) { cout << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; sum_stat << "Contaminants screening: YES. File_of_contaminants: " << cont_file << endl; cout << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; sum_stat << "K-mer size for contaminants: " << KMER_SIZE_CONT << endl; } else { cout << "Contaminants screening: NO" << endl; sum_stat << "Contaminants screening: NO" << endl; } if(qual_trim_flag) { cout << "Quality trimming: YES" << endl; sum_stat << "Quality trimming: YES" << endl; cout << "Maximim error: " << -10*log10(max_a_error) << endl; sum_stat << "Maximim error: " << -10*log10(max_a_error) << endl; cout << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; sum_stat << "Maximim error at ends: " << -10*log10(max_e_at_ends) << endl; } else { cout << "Quality trimming: NO" << endl; sum_stat << "Quality trimming: NO" << endl; } cout << "--------------------Output files--------------------\n"; sum_stat << "--------------------Output files--------------------\n"; cout << "Output prefix: " << output_prefix << endl; sum_stat << "Output prefix: " << output_prefix << endl; rep_file_name1 = output_prefix + "_SE_Report.tsv"; se_output_filename = output_prefix + "_SE.fastq" ; cout << "Report file: " << rep_file_name1 << endl; sum_stat << "Report file: " << rep_file_name1<< endl; cout << "SE file: " << se_output_filename << endl; sum_stat << "SE file: " << se_output_filename << endl; cout << "Single-end reads: "<< se_filename << endl; sum_stat << "Single-end reads: "<< se_filename << endl; cout << "--------------------Other parameters--------------------\n"; sum_stat << "--------------------Other parameters--------------------\n"; cout <//Test is the files provided are old-style illumina< "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; sum_stat << "Maximum number of mismatches allowed in alignment: " << max_al_mism << endl; cout << "Minimum read length to accept: " << minimum_read_length << endl; sum_stat << "Minimum read length to accept: " << minimum_read_length << endl; cout << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; sum_stat << "New to old-style Illumina headers: " << (new2old_illumina == false ? "NO" : "YES") << endl; cout << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; sum_stat << "Old-style Illumina: " << (old_style_illumina_flag == false ? "NO" : "YES") << endl; cout << "Q-value: " << phred_coeff_illumina << endl; sum_stat << "Q-value: " << phred_coeff_illumina << endl; }
49.720339
1,247
0.600932
ibest
1a31d7d4b5ea19d59daef6364171585a63d77769
13,752
cpp
C++
common/operations/BatchMatmul.cpp
riscv-android-src/platform-packages-modules-NeuralNetworks
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
[ "Apache-2.0" ]
null
null
null
common/operations/BatchMatmul.cpp
riscv-android-src/platform-packages-modules-NeuralNetworks
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
[ "Apache-2.0" ]
null
null
null
common/operations/BatchMatmul.cpp
riscv-android-src/platform-packages-modules-NeuralNetworks
32a7fbe0cec3a17f9cdd8c6f11d94ae77e30add5
[ "Apache-2.0" ]
null
null
null
/* * Copyright (C) 2021 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #define LOG_TAG "Operations" #ifdef NN_INCLUDE_CPU_IMPLEMENTATION #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wunused-parameter" #pragma clang diagnostic ignored "-Wsign-compare" #pragma clang diagnostic ignored "-Winvalid-partial-specialization" #include <tensorflow/lite/kernels/internal/reference/reference_ops.h> #include <tensorflow/lite/kernels/internal/runtime_shape.h> #pragma clang diagnostic pop #include <limits> #include <memory> #include <vector> #include "CpuOperationUtils.h" #endif // NN_INCLUDE_CPU_IMPLEMENTATION #include "BatchMatmul.h" #include "OperationResolver.h" #include "OperationsUtils.h" #include "Tracing.h" namespace android { namespace nn { namespace batch_matmul_op { #ifdef NN_INCLUDE_CPU_IMPLEMENTATION namespace { // Checks if two matrices can be multiplied. bool canMatrixMul(uint32_t LHSRow, uint32_t LHSCol, uint32_t RHSRow, uint32_t RHSCol, bool adjX, bool adjY) { if (LHSRow == 0 || LHSCol == 0 || RHSRow == 0 || RHSCol == 0) { return false; } if (adjX) { LHSCol = LHSRow; } if (adjY) { RHSRow = RHSCol; } return LHSCol == RHSRow; } // Computes the dimensions of output tensor. std::vector<uint32_t> computeOutputDimensions(const Shape& LHSTensorShape, const Shape& RHSTensorShape, bool adjX, bool adjY) { uint32_t numDims = getNumberOfDimensions(LHSTensorShape); auto outputTensorDimensions = LHSTensorShape.dimensions; outputTensorDimensions[numDims - 2] = adjX ? LHSTensorShape.dimensions[numDims - 1] : LHSTensorShape.dimensions[numDims - 2]; outputTensorDimensions[numDims - 1] = adjY ? RHSTensorShape.dimensions[numDims - 2] : RHSTensorShape.dimensions[numDims - 1]; return outputTensorDimensions; } // Swaps row and column dimensions for a shape. Shape swapRowColumnDims(const Shape& shape) { Shape swappedShape = shape; uint32_t numDims = getNumberOfDimensions(shape); swappedShape.dimensions[numDims - 2] = shape.dimensions[numDims - 1]; swappedShape.dimensions[numDims - 1] = shape.dimensions[numDims - 2]; return swappedShape; } // Transposes a matrix. template <typename T> void transposeRowsColumns(const T* inputData, const Shape& inputShape, T* outputData) { Shape transposedShape = swapRowColumnDims(inputShape); tflite::TransposeParams params; int rank = getNumberOfDimensions(inputShape); params.perm_count = rank; for (int i = 0; i < rank - 2; ++i) { params.perm[i] = i; } params.perm[rank - 2] = rank - 1; params.perm[rank - 1] = rank - 2; tflite::reference_ops::Transpose(params, convertShapeToTflshape(inputShape), inputData, convertShapeToTflshape(transposedShape), outputData); } // Creates a temporary space in heap. // Note that it is caller's responsibility to free the memory. template <typename T> std::unique_ptr<T> getTempData(uint32_t numElems) { return std::unique_ptr<T>(new (std::nothrow) T[numElems]); } // Performs batch matmul. // LHS <..., A, B> X RHS<..., B, C> // We assume that LHS and RHS are both row oriented (adjacent values in memory // are in the same row) and will output in the same memory layout. However, // TFLite's fast GEMM libraries assume RCC layout (LHS row oriented, // RHS column oriented, output column oriented). Therefore, we perform // RHS <..., C, B> X LHS <..., B, A> // where output is a C X A column-oriented, which is equivalent to // A X C row-oriented. template <typename T> bool batchMatMulGeneric(const T* inputLHSData, const Shape& inputLHSShape, const T* inputRHSData, const Shape& inputRHSShape, const bool adjX, const bool adjY, T* outputData, const Shape& outputShape) { NNTRACE_TRANS("batchMatMulGeneric"); // Only performs transpose without conjugation for adjoint since complex number is not // supported. NNTRACE_COMP_SWITCH("reference_ops::Transpose"); const T* realInputLHSData = inputLHSData; const T* realInputRHSData = inputRHSData; auto tempInputLHSData = getTempData<T>(getNumberOfElements(inputLHSShape)); auto tempInputRHSData = getTempData<T>(getNumberOfElements(inputRHSShape)); // For LHS, it's passed as RHS and column-oriented. // If adjX is false, needs to swap shape but no need to do data transpose. // If adjX is true, no need to swap shape but needs to do data transpose. // For RHS, it's passed as LHS and row-oriented. // If adjY is false, needs to swap shape also needs to do data transpose. // If adjY is true, no need to swap shape also no need to do data transpose. if (adjX) { transposeRowsColumns(inputLHSData, inputLHSShape, tempInputLHSData.get()); realInputLHSData = tempInputLHSData.get(); } if (!adjY) { transposeRowsColumns(inputRHSData, inputRHSShape, tempInputRHSData.get()); realInputRHSData = tempInputRHSData.get(); } Shape realInputLHSShape = adjX ? inputLHSShape : swapRowColumnDims(inputLHSShape); Shape realInputRHSShape = adjY ? inputRHSShape : swapRowColumnDims(inputRHSShape); NNTRACE_COMP_SWITCH("reference_ops::BatchMatMul"); tflite::reference_ops::BatchMatMul(convertShapeToTflshape(realInputRHSShape), realInputRHSData, convertShapeToTflshape(realInputLHSShape), realInputLHSData, convertShapeToTflshape(outputShape), outputData); return true; } // Performs batch matmul for quantized types. template <typename T> bool batchMatMulQuantized(const T* inputLHSData, const Shape& inputLHSShape, const T* inputRHSData, const Shape& inputRHSShape, const bool adjX, const bool adjY, T* outputData, const Shape& outputShape) { NNTRACE_TRANS("batchMatMulQuantized"); NNTRACE_COMP_SWITCH("reference_ops::Transpose"); const T* realInputLHSData = inputLHSData; const T* realInputRHSData = inputRHSData; auto tempInputLHSData = getTempData<T>(getNumberOfElements(inputLHSShape)); auto tempInputRHSData = getTempData<T>(getNumberOfElements(inputRHSShape)); if (adjX) { transposeRowsColumns(inputLHSData, inputLHSShape, tempInputLHSData.get()); realInputLHSData = tempInputLHSData.get(); } if (!adjY) { transposeRowsColumns(inputRHSData, inputRHSShape, tempInputRHSData.get()); realInputRHSData = tempInputRHSData.get(); } Shape realInputLHSShape = adjX ? inputLHSShape : swapRowColumnDims(inputLHSShape); Shape realInputRHSShape = adjY ? inputRHSShape : swapRowColumnDims(inputRHSShape); NNTRACE_COMP_SWITCH("reference_ops::BatchMatMul"); double realMultiplier = 0.0; int32_t outputMultiplier = 0; int32_t outputShift = 0; NN_RET_CHECK(GetQuantizedConvolutionMultiplier(realInputLHSShape, realInputRHSShape, outputShape, &realMultiplier)); NN_RET_CHECK(QuantizeMultiplier(realMultiplier, &outputMultiplier, &outputShift)); tflite::FullyConnectedParams params; params.input_offset = -realInputLHSShape.offset; params.weights_offset = -realInputRHSShape.offset; params.output_offset = outputShape.offset; params.output_multiplier = outputMultiplier; params.output_shift = outputShift; // BatchMatMul has no fused activation functions. Therefore, sets // output activation min and max to min and max of int8_t. params.quantized_activation_min = std::numeric_limits<int8_t>::min(); params.quantized_activation_max = std::numeric_limits<int8_t>::max(); params.lhs_cacheable = false; params.rhs_cacheable = false; tflite::reference_ops::BatchMatMul<T, int32_t>( params, convertShapeToTflshape(realInputRHSShape), realInputRHSData, convertShapeToTflshape(realInputLHSShape), realInputLHSData, convertShapeToTflshape(outputShape), outputData); return true; } } // namespace bool prepare(IOperationExecutionContext* context) { Shape inputLHSTensorShape = context->getInputShape(kInputLHSTensor); Shape inputRHSTensorShape = context->getInputShape(kInputRHSTensor); // Checks two input tensors have same number of dimensions. NN_RET_CHECK_EQ(getNumberOfDimensions(inputLHSTensorShape), getNumberOfDimensions(inputRHSTensorShape)) << "Input tensor ranks do not match with each other."; NN_RET_CHECK_GE(getNumberOfDimensions(inputLHSTensorShape), 2u) << "Input tensor rank should be at least 2."; NN_RET_CHECK_LE(getNumberOfDimensions(inputLHSTensorShape), 4u) << "Input tensor rank should be at most 4."; uint32_t numDims = getNumberOfDimensions(inputLHSTensorShape); const bool adjX = context->getInputValue<bool>(kInputLHSAdj); const bool adjY = context->getInputValue<bool>(kInputRHSAdj); // Checks dimensions work for matrix multiplication. NN_RET_CHECK(canMatrixMul(getSizeOfDimension(inputLHSTensorShape, numDims - 2), getSizeOfDimension(inputLHSTensorShape, numDims - 1), getSizeOfDimension(inputRHSTensorShape, numDims - 2), getSizeOfDimension(inputRHSTensorShape, numDims - 1), adjX, adjY)) << "Input tensors are not able to perform matrix multiplication."; Shape outputTensorShape = context->getOutputShape(kOutputTensor); outputTensorShape.dimensions = computeOutputDimensions(inputLHSTensorShape, inputRHSTensorShape, adjX, adjY); return context->setOutputShape(kOutputTensor, outputTensorShape); } bool execute(IOperationExecutionContext* context) { switch (context->getInputType(kInputLHSTensor)) { case OperandType::TENSOR_FLOAT32: return batchMatMulGeneric(context->getInputBuffer<float>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<float>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<float>(kOutputTensor), context->getOutputShape(kOutputTensor)); case OperandType::TENSOR_FLOAT16: return batchMatMulGeneric(context->getInputBuffer<_Float16>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<_Float16>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<_Float16>(kOutputTensor), context->getOutputShape(kOutputTensor)); case OperandType::TENSOR_INT32: return batchMatMulGeneric(context->getInputBuffer<int32_t>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<int32_t>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<int32_t>(kOutputTensor), context->getOutputShape(kOutputTensor)); case OperandType::TENSOR_QUANT8_ASYMM_SIGNED: return batchMatMulQuantized(context->getInputBuffer<int8_t>(kInputLHSTensor), context->getInputShape(kInputLHSTensor), context->getInputBuffer<int8_t>(kInputRHSTensor), context->getInputShape(kInputRHSTensor), context->getInputValue<bool>(kInputLHSAdj), context->getInputValue<bool>(kInputRHSAdj), context->getOutputBuffer<int8_t>(kOutputTensor), context->getOutputShape(kOutputTensor)); default: NN_RET_CHECK_FAIL() << "Unsupported tensor type for operation " << kOperationName; } return true; } #endif // NN_INCLUDE_CPU_IMPLEMENTATION } // namespace batch_matmul_op NN_REGISTER_OPERATION(BATCH_MATMUL, batch_matmul_op::kOperationName, batch_matmul_op::validate, batch_matmul_op::prepare, batch_matmul_op::execute); } // namespace nn } // namespace android
48.939502
100
0.666885
riscv-android-src
1a345ae3458244a74c91c876824819c90e3a90b0
2,662
cc
C++
zircon/system/ulib/fbl/test/algorithm_tests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
5
2022-01-10T20:22:17.000Z
2022-01-21T20:14:17.000Z
zircon/system/ulib/fbl/test/algorithm_tests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
2
2021-09-19T21:55:09.000Z
2021-12-19T03:34:53.000Z
zircon/system/ulib/fbl/test/algorithm_tests.cc
allansrc/fuchsia
a2c235b33fc4305044d496354a08775f30cdcf37
[ "BSD-2-Clause" ]
1
2021-08-23T11:33:57.000Z
2021-08-23T11:33:57.000Z
// Copyright 2016 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include <algorithm> #include <limits> #include <fbl/algorithm.h> #include <zxtest/zxtest.h> namespace { TEST(AlgorithmTest, RoundUp) { EXPECT_EQ(fbl::round_up(0u, 1u), 0u); EXPECT_EQ(fbl::round_up(0u, 5u), 0u); EXPECT_EQ(fbl::round_up(5u, 5u), 5u); EXPECT_EQ(fbl::round_up(1u, 6u), 6u); EXPECT_EQ(fbl::round_up(6u, 1u), 6u); EXPECT_EQ(fbl::round_up(6u, 3u), 6u); EXPECT_EQ(fbl::round_up(6u, 4u), 8u); EXPECT_EQ(fbl::round_up(15u, 8u), 16u); EXPECT_EQ(fbl::round_up(16u, 8u), 16u); EXPECT_EQ(fbl::round_up(17u, 8u), 24u); EXPECT_EQ(fbl::round_up(123u, 100u), 200u); EXPECT_EQ(fbl::round_up(123456u, 1000u), 124000u); uint64_t large_int = std::numeric_limits<uint32_t>::max() + 1LLU; EXPECT_EQ(fbl::round_up(large_int, 64U), large_int); EXPECT_EQ(fbl::round_up(large_int, 64LLU), large_int); EXPECT_EQ(fbl::round_up(large_int + 63LLU, 64U), large_int + 64LLU); EXPECT_EQ(fbl::round_up(large_int + 63LLU, 64LLU), large_int + 64LLU); EXPECT_EQ(fbl::round_up(large_int, 3U), large_int + 2LLU); EXPECT_EQ(fbl::round_up(large_int, 3LLU), large_int + 2LLU); EXPECT_EQ(fbl::round_up(2U, large_int), large_int); EXPECT_EQ(fbl::round_up(2LLU, large_int), large_int); } TEST(AlgorithmTest, RoundDown) { EXPECT_EQ(fbl::round_down(0u, 1u), 0u); EXPECT_EQ(fbl::round_down(0u, 5u), 0u); EXPECT_EQ(fbl::round_down(5u, 5u), 5u); EXPECT_EQ(fbl::round_down(1u, 6u), 0u); EXPECT_EQ(fbl::round_down(6u, 1u), 6u); EXPECT_EQ(fbl::round_down(6u, 3u), 6u); EXPECT_EQ(fbl::round_down(6u, 4u), 4u); EXPECT_EQ(fbl::round_down(15u, 8u), 8u); EXPECT_EQ(fbl::round_down(16u, 8u), 16u); EXPECT_EQ(fbl::round_down(17u, 8u), 16u); EXPECT_EQ(fbl::round_down(123u, 100u), 100u); EXPECT_EQ(fbl::round_down(123456u, 1000u), 123000u); uint64_t large_int = std::numeric_limits<uint32_t>::max() + 1LLU; EXPECT_EQ(fbl::round_down(large_int, 64U), large_int); EXPECT_EQ(fbl::round_down(large_int, 64LLU), large_int); EXPECT_EQ(fbl::round_down(large_int + 63LLU, 64U), large_int); EXPECT_EQ(fbl::round_down(large_int + 63LLU, 64LLU), large_int); EXPECT_EQ(fbl::round_down(large_int + 65LLU, 64U), large_int + 64LLU); EXPECT_EQ(fbl::round_down(large_int + 65LLU, 64LLU), large_int + 64LLU); EXPECT_EQ(fbl::round_down(large_int + 2LLU, 3U), large_int + 2LLU); EXPECT_EQ(fbl::round_down(large_int + 2LLU, 3LLU), large_int + 2LLU); EXPECT_EQ(fbl::round_down(2U, large_int), 0); EXPECT_EQ(fbl::round_down(2LLU, large_int), 0); } } // namespace
36.972222
74
0.706987
allansrc
1a3481fd62fddf822dd050eb0f24ebee0a0dfd13
2,375
cpp
C++
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/priority-booster
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
3
2020-09-19T07:27:34.000Z
2022-01-02T21:10:38.000Z
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/windows-kernel-programming
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
null
null
null
DelProtect2Config/DelProtect2Config.cpp
pvthuyet/windows-kernel-programming
1f0036a4528b799a6ddd862787d4181a1d082917
[ "BSL-1.0" ]
null
null
null
// DelProtect2Config.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "stdafx.h" #include "..\DelProtect2\DelProtectCommon.h" #include <iostream> int Error(const char* text) { printf("%s (%d)\n", text, ::GetLastError()); return 1; } int PrintUsage() { printf("Usage: DelProtect2Config <option> [exename]\n"); printf("\tOption: add, remove or clear\n"); return 0; } int wmain(int argc, const wchar_t* argv[]) { if (argc < 2) { return PrintUsage(); } HANDLE hDevice = ::CreateFileW(USER_FILE_NAME, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, OPEN_EXISTING, 0, nullptr); if (hDevice == INVALID_HANDLE_VALUE) return Error("Failed to open handle to device"); DWORD returned{ 0 }; BOOL success { FALSE }; bool badOption = false; if (::_wcsicmp(argv[1], L"add") == 0) { if (argc < 3) { return PrintUsage(); } success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_ADD_EXE, (PVOID)argv[2], ((DWORD)::wcslen(argv[2]) + 1) * sizeof(WCHAR), nullptr, 0, &returned, nullptr); } else if (::_wcsicmp(argv[1], L"remove") == 0) { if (argc < 3) { return PrintUsage(); } success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_REMOVE_EXE, (PVOID)argv[2], ((DWORD)::wcslen(argv[2]) + 1) * sizeof(WCHAR), nullptr, 0, &returned, nullptr); } else if (::_wcsicmp(argv[1], L"clear") == 0) { success = ::DeviceIoControl(hDevice, IOCTL_DELPROTECT_CLEAR, nullptr, 0, nullptr, 0, &returned, nullptr); } else { badOption = true; printf("Unknown option.\n"); PrintUsage(); } if (!badOption) { if (!success) { Error("Failed in operation"); } else { printf("Success.\n"); } } ::CloseHandle(hDevice); return 0; } // Run program: Ctrl + F5 or Debug > Start Without Debugging menu // Debug program: F5 or Debug > Start Debugging menu // Tips for Getting Started: // 1. Use the Solution Explorer window to add/manage files // 2. Use the Team Explorer window to connect to source control // 3. Use the Output window to see build output and other messages // 4. Use the Error List window to view errors // 5. Go to Project > Add New Item to create new code files, or Project > Add Existing Item to add existing code files to the project // 6. In the future, to open this project again, go to File > Open > Project and select the .sln file
26.988636
135
0.671579
pvthuyet
1a3e64646759c6e42fb554b1722fb23abd9fac41
907
hpp
C++
output/include/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
1
2019-07-31T06:44:46.000Z
2019-07-31T06:44:46.000Z
src/pilo/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
src/pilo/core/threading/read_write_lock.hpp
picofox/pilo
59e12c947307d664c4ca9dcc232b481d06be104a
[ "MIT" ]
null
null
null
#pragma once #include "core/coredefs.hpp" namespace pilo { namespace core { namespace threading { class read_write_lock { public: #ifdef WINDOWS read_write_lock() { ::InitializeSRWLock(&m_lock); } #else read_write_lock() { ::pthread_rwlock_init(&m_lock, NULL); } ~read_write_lock(); #endif void lock_read(); void lock_write(); bool try_lock_read(); bool try_lock_write(); void unlock_read(); void unlock_write(); protected: #ifdef WINDOWS SRWLOCK m_lock; #else pthread_rwlock_t m_lock; #endif }; } } }
18.895833
57
0.416759
picofox
1a40c72b20b9825a1fb3a4c6019aa141d52ec6d0
1,256
cc
C++
caffe2/contrib/prof/profiling_annotations_test.cc
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
1
2019-07-21T02:13:22.000Z
2019-07-21T02:13:22.000Z
caffe2/contrib/prof/profiling_annotations_test.cc
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
caffe2/contrib/prof/profiling_annotations_test.cc
DavidKo3/mctorch
53ffe61763059677978b4592c8b2153b0c15428f
[ "BSD-3-Clause" ]
null
null
null
// Unit tests for profiling_annotations.h. #include "caffe2/contrib/prof/profiling_annotations.h" #include <gtest/gtest.h> namespace caffe2 { namespace contrib { namespace prof { namespace { TEST(TwoNumberStatsTest, ComputeAndGetOpStatsSummary) { // e.g., 2 and 3 TwoNumberStats stats; stats.addPoint(2); stats.addPoint(3); EXPECT_FLOAT_EQ(2.5, stats.getMean()); // Population standard deviation. EXPECT_FLOAT_EQ(0.5, stats.getStddev()); } TEST(TwoNumberStatsTest, TestRestore) { // Expect that restore&recompute is still the same. // E.g., 2 and 3 (above). TwoNumberStats stats(2.5, 0.5, 2); // Expect that restore&recompute is still the same. EXPECT_FLOAT_EQ(2.5, stats.getMean()); // Population standard deviation. EXPECT_FLOAT_EQ(0.5, stats.getStddev()); } TEST(ProfilingAnnotationsTest, BasicAccessToActiveData) { ProfilingOperatorAnnotation op_annotation; op_annotation.getMutableExecutionTimeMs()->addPoint(5); EXPECT_EQ(5, op_annotation.getExecutionTimeMs().getMean()); ProfilingDataAnnotation data_annotation; data_annotation.getMutableUsedBytes()->addPoint(7); EXPECT_EQ(7, data_annotation.getUsedBytes().getMean()); } } // namespace } // namespace prof } // namespace contrib } // namespace caffe2
27.911111
61
0.749204
DavidKo3
1a412569050244cbdd0b2b246b2ecbf4c5c37b3a
164
hpp
C++
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
chaine/src/mesh/vertex/is_valid.hpp
the-last-willy/id3d
dc0d22e7247ac39fbc1fd8433acae378b7610109
[ "MIT" ]
null
null
null
#pragma once #include "proxy.hpp" #include "topology.hpp" namespace face_vertex { inline bool is_valid(VertexProxy vp) { return is_valid(topology(vp)); } }
11.714286
34
0.719512
the-last-willy
1a43b6233a940ecb5091f95246199e1d08b44a81
1,461
cpp
C++
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
18
2020-08-27T05:27:50.000Z
2022-03-08T02:56:48.000Z
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
null
null
null
leetcode/problems/easy/859-buddy-string.cpp
wingkwong/competitive-programming
e8bf7aa32e87b3a020b63acac20e740728764649
[ "MIT" ]
1
2020-10-13T05:23:58.000Z
2020-10-13T05:23:58.000Z
/* Buddy Strings https://leetcode.com/problems/buddy-strings/ Given two strings A and B of lowercase letters, return true if you can swap two letters in A so the result is equal to B, otherwise, return false. Swapping letters is defined as taking two indices i and j (0-indexed) such that i != j and swapping the characters at A[i] and A[j]. For example, swapping at indices 0 and 2 in "abcd" results in "cbad". Example 1: Input: A = "ab", B = "ba" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'b' to get "ba", which is equal to B. Example 2: Input: A = "ab", B = "ab" Output: false Explanation: The only letters you can swap are A[0] = 'a' and A[1] = 'b', which results in "ba" != B. Example 3: Input: A = "aa", B = "aa" Output: true Explanation: You can swap A[0] = 'a' and A[1] = 'a' to get "aa", which is equal to B. Example 4: Input: A = "aaaaaaabc", B = "aaaaaaacb" Output: true Example 5: Input: A = "", B = "aa" Output: false Constraints: 0 <= A.length <= 20000 0 <= B.length <= 20000 A and B consist of lowercase letters. */ class Solution { public: bool buddyStrings(string A, string B) { // aaa aaa 1 < 3 // abc abc 3 < 3 int n = A.size(); if(A==B) return (set<char>(A.begin(), A.end()).size() < n); int l = 0, r = n - 1; while(l < n && A[l] == B[l]) l++; while(r >= 0 && A[r] == B[r]) r--; if(l < r) swap(A[l], A[r]); return A == B; } };
26.089286
202
0.590691
wingkwong
1a44e14db33b2f2ab59aecad07e52ca9a292ea61
2,159
cpp
C++
Development/Editor/Core/LuaEngine/logging_backend.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
2
2016-05-30T11:42:33.000Z
2017-10-31T11:53:42.000Z
Development/Editor/Core/LuaEngine/logging_backend.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
null
null
null
Development/Editor/Core/LuaEngine/logging_backend.cpp
shawwwn/YDWE
b83ffe041d9623409d9ffd951988e2b482d9cfc3
[ "Apache-2.0" ]
null
null
null
#include "logging_backend.h" #include <boost/filesystem/fstream.hpp> #include <base/util/format.h> #include <base/exception/exception.h> namespace logging { struct logging_backend::implementation { boost::filesystem::path root_path_; boost::filesystem::ofstream file_; uintmax_t written_; implementation(const boost::filesystem::path& root_path) : root_path_(root_path) , file_() , written_(0) { } }; logging_backend::logging_backend(const boost::filesystem::path& root_path) : impl_(new implementation(root_path)) { } logging_backend::~logging_backend() { delete impl_; } void logging_backend::consume(record_view const& rec, string_type const& formatted_message) { if((impl_->file_.is_open() && (impl_->written_ + formatted_message.size() >= 512*1024) ) || !impl_->file_.good() ) { rotate_file(); } if (!impl_->file_.is_open()) { boost::filesystem::create_directories(impl_->root_path_); impl_->file_.open(impl_->root_path_ / L"ydwe.log", std::ios_base::app | std::ios_base::out); if (!impl_->file_.is_open()) { throw base::exception("Failed to open file '%s' for writing.", (impl_->root_path_ / L"ydwe.log").string().c_str()); } impl_->written_ = static_cast<std::streamoff>(impl_->file_.tellp()); } impl_->file_.write(formatted_message.data(), static_cast<std::streamsize>(formatted_message.size())); impl_->file_.put(static_cast<string_type::value_type>('\n')); impl_->written_ += formatted_message.size() + 1; } void logging_backend::flush() { if (impl_->file_.is_open()) impl_->file_.flush(); } void logging_backend::rotate_file() { impl_->file_.close(); impl_->file_.clear(); impl_->written_ = 0; size_t i = 1; for (; i < 10; ++i) { boost::filesystem::path p = impl_->root_path_ / base::format(L"ydwe%03d.log", i); if (!boost::filesystem::exists(p)) { break; } } if (i == 10) i = 1; boost::filesystem::rename(impl_->root_path_ / L"ydwe.log", impl_->root_path_ / base::format(L"ydwe%03d.log", i)); ++i; if (i == 10) i = 1; boost::filesystem::remove(impl_->root_path_ / base::format(L"ydwe%03d.log", i)); } }
25.702381
119
0.666975
shawwwn
1a46daba1ed7553485e49f5066597902ebe065d4
3,415
cpp
C++
recast_ros/src/nodes/test_planning_service_interactive.cpp
ori-drs/recast_ros
f1516d43578aa7550fbb3ee6d91bf4fe8eb773f8
[ "Zlib" ]
8
2020-04-13T16:34:35.000Z
2021-12-21T14:24:31.000Z
recast_ros/src/nodes/test_planning_service_interactive.cpp
ori-drs/recast_ros
f1516d43578aa7550fbb3ee6d91bf4fe8eb773f8
[ "Zlib" ]
3
2020-06-24T16:05:02.000Z
2022-01-18T08:15:20.000Z
recast_ros/src/nodes/test_planning_service_interactive.cpp
ori-drs/recast_ros
f1516d43578aa7550fbb3ee6d91bf4fe8eb773f8
[ "Zlib" ]
2
2021-02-20T08:39:36.000Z
2021-02-22T09:48:22.000Z
// // Copyright (c) 2019 Martim Brandão martim@robots.ox.ac.uk, Omer Burak Aladag aladagomer@sabanciuniv.edu, Ioannis Havoutis ioannis@robots.ox.ac.uk // As a part of Dynamic Robot Systems Group, Oxford Robotics Institute, University of Oxford // // This software is provided 'as-is', without any express or implied // warranty. In no event will the authors be held liable for any damages // arising from the use of this software. // Permission is granted to anyone to use this software for any purpose, // including commercial applications, and to alter it and redistribute it // freely, subject to the following restrictions: // 1. The origin of this software must not be misrepresented; you must not // claim that you wrote the original software. If you use this software // in a product, an acknowledgment in the product documentation would be // appreciated but is not required. // 2. Altered source versions must be plainly marked as such, and must not be // misrepresented as being the original software. // 3. This notice may not be removed or altered from any source distribution. #include "recast_ros/RecastPathSrv.h" #include <geometry_msgs/PoseStamped.h> #include <ros/ros.h> class TestPlanningServiceInteractive { public: TestPlanningServiceInteractive(ros::NodeHandle &node_handle) : node_handle_(node_handle) { // ros params node_handle_.param("target_topic", target_topic_, std::string("/move_base_simple/goal")); node_handle_.param("path_service", path_service_, std::string("/recast_node/plan_path")); node_handle_.param("loop_rate", loop_rate_, 1.0); // subscribe target subscriber_ = node_handle_.subscribe(target_topic_, 1, &TestPlanningServiceInteractive::callback, this); } void callback(const geometry_msgs::PoseStamped &msg) { ROS_INFO("Received point: %f %f %f", msg.pose.position.x, msg.pose.position.y, msg.pose.position.z); target_ = msg.pose.position; } void run() { // ros ros::ServiceClient client_recast = node_handle_.serviceClient<recast_ros::RecastPathSrv>(path_service_); // wait until the client exists... ROS_INFO("Waiting for Recast path planning service to become available..."); client_recast.waitForExistence(); ROS_INFO("Recast planning service active!"); // loop ros::Rate loop_rate(loop_rate_); while (ros::ok()) { // get current state. TODO: take as param? geometry_msgs::Point current; current.x = 0; current.y = 0; current.z = 0; // recast plan to goal recast_ros::RecastPathSrv srv; srv.request.startXYZ = current; srv.request.goalXYZ = target_; if (!client_recast.call(srv)) { ROS_ERROR("Failed to call recast query service"); // continue; } if (srv.response.path.size() < 2) { ROS_ERROR("Could not find a path"); // continue; } ros::spinOnce(); loop_rate.sleep(); } } protected: ros::NodeHandle node_handle_; ros::Subscriber subscriber_; std::string target_topic_; std::string path_service_; double loop_rate_; geometry_msgs::Point target_; }; int main(int argc, char *argv[]) { ros::init(argc, argv, "high_level_planner_node"); ros::NodeHandle node_handle("~"); TestPlanningServiceInteractive test_planning_service_interactive(node_handle); test_planning_service_interactive.run(); return 0; }
34.846939
147
0.70981
ori-drs
1a49226dab9c37637f639d113eaa776ed9b030cf
1,352
hpp
C++
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
38
2016-01-14T13:51:13.000Z
2021-12-29T01:49:30.000Z
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
null
null
null
Programming Guide/Headers/Siv3D/RenderTexture.hpp
Reputeless/Siv3D-Reference
d58e92885241d11612007fb9187ce0289a7ee9cb
[ "MIT" ]
16
2016-01-15T11:07:51.000Z
2021-12-29T01:49:37.000Z
//----------------------------------------------- // // This file is part of the Siv3D Engine. // // Copyright (C) 2008-2016 Ryo Suzuki // // Licensed under the MIT License. // //----------------------------------------------- # pragma once # include "Texture.hpp" namespace s3d { class RenderTexture : public Texture { protected: struct _swapChain {}; RenderTexture(const _swapChain&); public: RenderTexture(); RenderTexture(uint32 width, uint32 height, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); explicit RenderTexture(const Size& size, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); RenderTexture(uint32 width, uint32 height, const ColorF& color, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); RenderTexture(const Size& size, const ColorF& color, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); void clear(const ColorF& color); void beginReset(); bool endReset(const Size& size, TextureFormat format = TextureFormat::R8G8B8A8_Unorm, const MultiSampling& multiSampling = MultiSampling(1, 0)); bool saveDDS(const FilePath& path) const; }; }
30.044444
178
0.699704
Reputeless
1a495c21c102171ec676f78c94de7d3c26d81452
2,096
cc
C++
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
null
null
null
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
56
2021-06-03T03:16:25.000Z
2022-03-20T01:07:44.000Z
src/graphics/bin/vulkan_loader/loader.cc
dreamboy9/fuchsia
4ec0c406a28f193fe6e7376ee7696cca0532d4ba
[ "BSD-2-Clause" ]
null
null
null
// Copyright 2021 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/graphics/bin/vulkan_loader/loader.h" #include <lib/fdio/directory.h> #include <lib/fdio/io.h> LoaderImpl::~LoaderImpl() { app_->RemoveObserver(this); } // static void LoaderImpl::Add(LoaderApp* app, const std::shared_ptr<sys::OutgoingDirectory>& outgoing) { outgoing->AddPublicService(fidl::InterfaceRequestHandler<fuchsia::vulkan::loader::Loader>( [app](fidl::InterfaceRequest<fuchsia::vulkan::loader::Loader> request) { auto impl = std::make_unique<LoaderImpl>(app); LoaderImpl* impl_ptr = impl.get(); impl_ptr->bindings_.AddBinding(std::move(impl), std::move(request), nullptr); })); } // LoaderApp::Observer implementation. void LoaderImpl::OnIcdListChanged(LoaderApp* app) { auto it = callbacks_.begin(); while (it != callbacks_.end()) { std::optional<zx::vmo> vmo = app->GetMatchingIcd(it->first); if (!vmo) { ++it; } else { it->second(*std::move(vmo)); it = callbacks_.erase(it); } } if (callbacks_.empty()) { app_->RemoveObserver(this); } } // fuchsia::vulkan::loader::Loader impl void LoaderImpl::Get(std::string name, GetCallback callback) { AddCallback(std::move(name), std::move(callback)); } void LoaderImpl::ConnectToDeviceFs(zx::channel channel) { app_->ServeDeviceFs(std::move(channel)); } void LoaderImpl::GetSupportedFeatures(GetSupportedFeaturesCallback callback) { fuchsia::vulkan::loader::Features features = fuchsia::vulkan::loader::Features::CONNECT_TO_DEVICE_FS | fuchsia::vulkan::loader::Features::GET; callback(features); } void LoaderImpl::AddCallback(std::string name, fit::function<void(zx::vmo)> callback) { std::optional<zx::vmo> vmo = app_->GetMatchingIcd(name); if (vmo) { callback(*std::move(vmo)); return; } callbacks_.emplace_back(std::make_pair(std::move(name), std::move(callback))); if (callbacks_.size() == 1) { app_->AddObserver(this); } }
32.75
100
0.689885
dreamboy9
1a5413d982d8ec4139e18bfbc2ad0598067a66cb
1,803
hpp
C++
external/bayesopt/include/criteria/criteria_a_opt.hpp
pchrapka/brain-modelling
f232b5a858e45f10b0b0735269010454129ab017
[ "MIT" ]
1
2017-10-13T19:37:52.000Z
2017-10-13T19:37:52.000Z
external/bayesopt/include/criteria/criteria_a_opt.hpp
pchrapka/brain-modelling
f232b5a858e45f10b0b0735269010454129ab017
[ "MIT" ]
null
null
null
external/bayesopt/include/criteria/criteria_a_opt.hpp
pchrapka/brain-modelling
f232b5a858e45f10b0b0735269010454129ab017
[ "MIT" ]
1
2019-11-25T12:22:05.000Z
2019-11-25T12:22:05.000Z
/** \file criteria_a_opt.hpp \brief A-optimality (uncertainty) based criteria */ /* ------------------------------------------------------------------------- This file is part of BayesOpt, an efficient C++ library for Bayesian optimization. Copyright (C) 2011-2015 Ruben Martinez-Cantin <rmcantin@unizar.es> BayesOpt is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. BayesOpt is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with BayesOpt. If not, see <http://www.gnu.org/licenses/>. ------------------------------------------------------------------------ */ #ifndef _CRITERIA_A_OPT_HPP_ #define _CRITERIA_A_OPT_HPP_ #include "criteria_functors.hpp" namespace bayesopt { /**\addtogroup CriteriaFunctions */ //@{ /** * \brief Greedy A-Optimality criterion. * Used for learning the function, not to minimize. Some authors * name it I-optimality because it minimizes the error on the * prediction, not on the parameters. */ class GreedyAOptimality: public Criteria { public: virtual ~GreedyAOptimality(){}; void setParameters(const vectord &params) {}; size_t nParameters() {return 0;}; double operator() (const vectord &x) { return -mProc->prediction(x)->getStd(); }; std::string name() {return "cAopt";}; }; //@} } //namespace bayesopt #endif
31.086207
81
0.655019
pchrapka
1a55fef6e547e747fbd7704e3b90f38d875e7382
1,831
cc
C++
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
selfdrive/common/testparams/test_params.cc
lukeadams/openpilot
c3bd28c2d5029749c47ee03440b3cc509f786968
[ "MIT" ]
null
null
null
#include "selfdrive/common/params.h" #include <cstring> static const char* const kUsage = "%s: read|write|read_block params_path key [value]\n"; int main(int argc, const char* argv[]) { if (argc < 4) { printf(kUsage, argv[0]); return 0; } Params params(argv[2]); const char* key = argv[3]; if (strcmp(argv[1], "read") == 0) { char* value; size_t value_size; int result = params.read_db_value(key, &value, &value_size); if (result >= 0) { fprintf(stdout, "Read %zu bytes: ", value_size); fwrite(value, 1, value_size, stdout); fprintf(stdout, "\n"); free(value); } else { fprintf(stderr, "Error reading: %d\n", result); return -1; } } else if (strcmp(argv[1], "write") == 0) { if (argc < 5) { fprintf(stderr, "Error: write value required\n"); return 1; } const char* value = argv[4]; const size_t value_size = strlen(value); int result = params.write_db_value(key, value, value_size); if (result >= 0) { fprintf(stdout, "Wrote %s to %s\n", value, key); } else { fprintf(stderr, "Error writing: %d\n", result); return -1; } } else if (strcmp(argv[1], "read_block") == 0) { char* value; size_t value_size; params.read_db_value_blocking(key, &value, &value_size); fprintf(stdout, "Read %zu bytes: ", value_size); fwrite(value, 1, value_size, stdout); fprintf(stdout, "\n"); free(value); } else { printf(kUsage, argv[0]); return 1; } return 0; } // BUILD: // $ gcc -I$HOME/one selfdrive/common/test_params.c selfdrive/common/params.c selfdrive/common/util.c -o ./test_params // $ seq 0 100000 | xargs -P20 -I{} ./test_params write /data/params DongleId {} && sleep 0.1 & // $ while ./test_params read /data/params DongleId; do sleep 0.05; done
29.063492
118
0.607318
lukeadams
1a5b1fb2d6c86019f43255d5c217e30395d9c968
7,517
cpp
C++
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
src/com/cyosp/mpa/api/rest/v1/MPAOFactory.cpp
cyosp/MPA
f640435c483dcbf7bfe7ff7887a25e6c76612528
[ "BSD-3-Clause" ]
null
null
null
/* * MPAOFactory.cpp * * Created on: 21 March 2015 * Author: cyosp */ #include <com/cyosp/mpa/api/rest/v1/MPAOFactory.hpp> namespace mpa_api_rest_v1 { // Initialize static member MPAOFactory * MPAOFactory::mpaofactory = NULL; MPAOFactory * MPAOFactory::getInstance() { if( mpaofactory == NULL ) mpaofactory = new MPAOFactory(); return mpaofactory; } MPAOFactory::MPAOFactory() { //tokenList = new map<string, Token>(); } // Return NULL if URL is bad // GET // /mpa/res/logout // /mpa/res/accounts // /mpa/res/accounts/10 // /mpa/res/accounts/10/categories // /mpa/res/infos // /mpa/res/locales // POST // /mpa/res/users/login // /mpa/res/users/logout // /mpa/res/users/add // /mpa/res/users/0/del?version=0 // /mpa/res/users/10/upd?version=1 // /mpa/res/accounts/add // /mpa/res/accounts/20/del?version=1 // /mpa/res/accounts/20/upd?version=1 // /mpa/res/categories/add // /mpa/res/categories/30/del?version=1 mpa_api_rest_v1::MPAO * MPAOFactory::getMPAO(HttpRequestType requestType, const string& url, const map<string, string>& argvals) { mpa_api_rest_v1::MPAO * ret = NULL; // // Decode URL // ActionType actionType = NONE; vector<std::pair<string, int> > urlPairs; boost::smatch matches; const boost::regex startUrl("^/api/rest/v1(/.*)$"); if( boost::regex_match(url, matches, startUrl) ) { MPA_LOG_TRIVIAL(trace, "Match with start URL"); // Remove start of URL string urlToAnalyse = matches[1]; if( requestType == POST ) { const boost::regex actionTypeRegex("(.*)/([a-z]+)$"); if( boost::regex_match(urlToAnalyse, matches, actionTypeRegex) ) { MPA_LOG_TRIVIAL(trace, "Action type: " + matches[2]); // Remove URL action type urlToAnalyse = matches[1]; if( matches[2] == "login" ) { actionType = LOGIN; // Update URL in order to be compliant to the standard others urlToAnalyse = "/login/0"; } else if( matches[2] == "add" ) { actionType = ADD; // Update URL in order to be compliant to the standard others urlToAnalyse += "/0"; } else if( matches[2] == "del" ) actionType = DELETE; else if( matches[2] == "upd" ) actionType = UPDATE; const boost::regex urlPairRegex("^/([a-z]+)/([0-9]+)(.*)$"); // Fill vector starting by the beginning of URL while( boost::regex_match(urlToAnalyse, matches, urlPairRegex) ) { // Update URL string name = matches[1]; string idString = matches[2]; int id = atoi(idString); urlToAnalyse = matches[3]; MPA_LOG_TRIVIAL(trace, "Name: " + name + ", id: " + idString); urlPairs.push_back(std::pair<string, int>(name, id)); } MPA_LOG_TRIVIAL(trace, "End URL analyze"); } else MPA_LOG_TRIVIAL(trace, "URL doesn't match action type"); } else { MPA_LOG_TRIVIAL(trace, "URL to analyze: " + urlToAnalyse); // Manage URL like: GET /mpa/res/accounts const boost::regex urlStartRegex("^/([a-z]+)(.*)$"); while( boost::regex_match(urlToAnalyse, matches, urlStartRegex) ) { MPA_LOG_TRIVIAL(trace, "URL start match"); // Set values string name = matches[1]; string idString = ""; int id = 0; urlToAnalyse = matches[2]; MPA_LOG_TRIVIAL(trace, "New URL to analyze: " + urlToAnalyse); // Manage URL like: GET /mpa/res/accounts/10 const boost::regex urlIdRegex("^/([0-9]+)(.*)$"); // Fill vector starting by beginning of URL if( boost::regex_match(urlToAnalyse, matches, urlIdRegex) ) { MPA_LOG_TRIVIAL(trace, "URL ID match"); idString = matches[1]; id = atoi(idString); urlToAnalyse = matches[2]; } MPA_LOG_TRIVIAL(trace, "Name: " + name + ", id: " + idString); urlPairs.push_back(std::pair<string, int>(name, id)); } } // Manage case where URL doesn't match with an expected one if( urlPairs.size() > 0 ) { int lastPosition = urlPairs.size() - 1; string lastIdentifier = urlPairs[lastPosition].first; MPA_LOG_TRIVIAL(trace, "Last identifier: " + lastIdentifier); if( lastIdentifier == mpa_api_rest_v1::Login::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Login(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Logout::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Logout(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Account::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Account(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::User::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::User(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Info::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Info(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Locale::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Locale(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Category::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Category(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Provider::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Provider(requestType, actionType, argvals, urlPairs); else if( lastIdentifier == mpa_api_rest_v1::Operation::URL_STRING_PATH_IDENTIFIER ) ret = new mpa_api_rest_v1::Operation(requestType, actionType, argvals, urlPairs); } else MPA_LOG_TRIVIAL(info, "Bad URL"); } else MPA_LOG_TRIVIAL(trace, "Doesn't match with POST start URL"); return ret; } map<string, string> & MPAOFactory::getTokenList() { return tokenList; } }
37.585
101
0.518159
cyosp
1a5cad6550b20dbdefcd13178dd1e94768258ae2
3,141
cc
C++
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
67
2018-03-01T06:56:49.000Z
2022-03-08T18:44:47.000Z
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
93
2018-12-07T17:38:04.000Z
2022-03-31T10:04:51.000Z
src/tests/functionspace/test_reduced_halo.cc
twsearle/atlas
a1916fd521f9935f846004e6194f80275de4de83
[ "Apache-2.0" ]
33
2018-02-28T17:06:19.000Z
2022-01-20T12:12:27.000Z
/* * (C) Copyright 2013 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation * nor does it submit to any jurisdiction. */ #include <algorithm> #include <array> #include <string> #include <vector> #include "atlas/functionspace/EdgeColumns.h" #include "atlas/functionspace/NodeColumns.h" #include "atlas/grid/StructuredGrid.h" #include "atlas/mesh/HybridElements.h" #include "atlas/mesh/Mesh.h" #include "atlas/mesh/Nodes.h" #include "atlas/meshgenerator.h" #include "atlas/parallel/mpi/mpi.h" #include "tests/AtlasTestEnvironment.h" using namespace atlas::functionspace; using namespace atlas::grid; using namespace atlas::meshgenerator; namespace atlas { namespace test { template <typename Container> Container reversed(const Container& a) { Container a_reversed = a; std::reverse(a_reversed.begin(), a_reversed.end()); return a_reversed; } static std::array<bool, 2> false_true{false, true}; //----------------------------------------------------------------------------- CASE("halo nodes") { Grid grid("O8"); std::vector<int> halos{0, 1, 2, 3, 4}; std::vector<int> nodes{560, 592, 624, 656, 688}; for (bool reduce : false_true) { SECTION(std::string(reduce ? "reduced" : "increased")) { Mesh mesh = StructuredMeshGenerator().generate(grid); EXPECT(mesh.nodes().size() == nodes[0]); for (int h : (reduce ? reversed(halos) : halos)) { NodeColumns fs(mesh, option::halo(h)); if (mpi::comm().size() == 1) { EXPECT(fs.nb_nodes() == nodes[h]); } } } } } //----------------------------------------------------------------------------- CASE("halo edges") { Grid grid("O8"); std::vector<int> halos{0, 1, 2, 3, 4}; std::vector<int> edges{1559, 1649, 1739, 1829, 1919}; for (bool reduce : false_true) { for (bool with_pole_edges : false_true) { int pole_edges = with_pole_edges ? StructuredGrid(grid).nx().front() : 0; SECTION(std::string(reduce ? "reduced " : "increased ") + std::string(with_pole_edges ? "with_pole_edges" : "without_pole_edges")) { Mesh mesh = StructuredMeshGenerator().generate(grid); EXPECT(mesh.edges().size() == 0); for (int h : (reduce ? reversed(halos) : halos)) { EdgeColumns fs(mesh, option::halo(h) | option::pole_edges(with_pole_edges)); if (mpi::comm().size() == 1) { EXPECT(fs.nb_edges() == edges[h] + pole_edges); } } } } } } //----------------------------------------------------------------------------- } // namespace test } // namespace atlas int main(int argc, char** argv) { return atlas::test::run(argc, argv); }
32.05102
96
0.559058
twsearle
1a61d1a6a96afadc80416f46aaf1e217616dc71f
4,176
cpp
C++
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
ktotheoz/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
83
2015-01-08T15:06:14.000Z
2021-07-20T17:07:00.000Z
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
PixelLightFoundation/pixellight
43a661e762034054b47766d7e38d94baf22d2038
[ "MIT" ]
27
2019-06-18T06:46:07.000Z
2020-02-02T11:11:28.000Z
Plugins/SPARK_PL/src/RenderingAPIs/PixelLight/SPK_PLLineRenderer.cpp
naetherm/PixelLight
d7666f5b49020334cbb5debbee11030f34cced56
[ "MIT" ]
40
2015-02-25T18:24:34.000Z
2021-03-06T09:01:48.000Z
/*********************************************************\ * File: SPK_PLLineRenderer.cpp * * * Copyright (C) 2002-2013 The PixelLight Team (http://www.pixellight.org/) * * This file is part of PixelLight. * * 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. \*********************************************************/ //[-------------------------------------------------------] //[ Includes ] //[-------------------------------------------------------] #include <PLMath/Math.h> // On Mac OS X I'am getting the compiler error "error: ‘isfinite’ was not declared in this scope" when not including this header, first... I'am not sure what SPARK is changing in order to cause this error... #include <PLCore/PLCore.h> PL_WARNING_PUSH PL_WARNING_DISABLE(4530) // "warning C4530: C++ exception handler used, but unwind semantics are not enabled. Specify /EHsc" // [HACK] There are missing forward declarations within the SPARK headers... namespace SPK { class Group; } #include <Core/SPK_Group.h> PL_WARNING_POP #include "SPARK_PL/RenderingAPIs/PixelLight/SPK_PLBuffer.h" #include "SPARK_PL/RenderingAPIs/PixelLight/SPK_PLLineRenderer.h" //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] namespace SPARK_PL { //[-------------------------------------------------------] //[ Protected definitions ] //[-------------------------------------------------------] const std::string SPK_PLLineRenderer::PLBufferName("SPK_PLLineRenderer_Buffer"); //[-------------------------------------------------------] //[ Public functions ] //[-------------------------------------------------------] /** * @brief * Destructor of SPK_PLLineRenderer */ SPK_PLLineRenderer::~SPK_PLLineRenderer() { } //[-------------------------------------------------------] //[ Public virtual SPK::BufferHandler functions ] //[-------------------------------------------------------] void SPK_PLLineRenderer::createBuffers(const SPK::Group &group) { // Create the SPK_PLBuffer instance m_pSPK_PLBuffer = static_cast<SPK_PLBuffer*>(group.createBuffer(PLBufferName, PLBufferCreator(GetPLRenderer(), 14, 0, SPK::TEXTURE_NONE), 0U, false)); } void SPK_PLLineRenderer::destroyBuffers(const SPK::Group &group) { group.destroyBuffer(PLBufferName); } //[-------------------------------------------------------] //[ Protected functions ] //[-------------------------------------------------------] /** * @brief * Constructor of SPK_PLLineRenderer */ SPK_PLLineRenderer::SPK_PLLineRenderer(PLRenderer::Renderer &cRenderer, float fLength, float fWidth) : SPK_PLRenderer(cRenderer), SPK::LineRendererInterface(fLength, fWidth), m_pSPK_PLBuffer(nullptr) { } //[-------------------------------------------------------] //[ Namespace ] //[-------------------------------------------------------] } // SPARK_PL
42.612245
232
0.534722
ktotheoz
1a680e179daa526101317eb8f2d21d4435439a12
1,803
cpp
C++
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
1
2020-07-11T12:39:03.000Z
2020-07-11T12:39:03.000Z
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
null
null
null
src/demo/main.cpp
Glockenspiel/Fibers4U
69dac46b0995164d16bdb048071f43909b1faf5f
[ "Apache-2.0" ]
null
null
null
#include "include/fbr.h" #include "Player.h" using namespace std; using namespace fbr; int main(){ Player *p = new Player(); BaseTask *printHP = new TaskArgs<>(&Player::printHp, p); TaskArgs<int> *taskArg = new TaskArgs<int>(&Player::addHp, p); int a = 20; taskArg->setArgs(a); TaskArgs<int, bool> *test = new TaskArgs<int, bool>(&Player::damage, p); int b = 5; bool isMagic=false; test->setArgs(b, isMagic); TaskArgsCopy<int, int, int> *move = new TaskArgsCopy<int, int, int>(&Player::move, p); int c = 0; move->setArgs(54, c, std::thread::hardware_concurrency()); Task *inputtask = new Task(&Player::taskInput, p); inputtask->setReuseable(true); Scheduler *scheduler = new Scheduler(0,4, taskArg,true,true); if (scheduler->getIsConstructed() == false){ return 0; } fbr::con_cout << "All workers ready! " << fbr::endl; Task *update = new Task(&Player::update, p); //wake up main thread Task *endTask = new Task(&Scheduler::wakeUpMain); Task *longTask = new Task(&Player::longTask, p); //run all task unsyncronized //example with vector //vector<BaseTask*> allTasks = { printHP, move, update,longTask }; //scheduler->runTasks(allTasks, priority::low); //example with variadic function Scheduler::runTasks(priority::low, 4, printHP, move, update, longTask); //scheduler->waitAllFibersFree(); //Scheduler::waitForCounter(0, inputtask); //Scheduler::waitForCounter(0, inputtask); //puts main thread to wait and doesn't cunsume cpu time //wakes up when endTask is run Scheduler::waitMain(); scheduler->close(); //system("pause"); //delete scheduler and display msg delete scheduler; //fbr::log << "here" << Log::endl; fbr::con_cout << "Scheduler deleted" << fbr::endl; SpinUntil *timer = new SpinUntil(); timer->wait(2); delete timer; }
25.757143
87
0.684415
Glockenspiel
1a6885151eed7a9c4445dd976ea5a82ec986cb63
898
cpp
C++
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
euler065.cpp
suihan74/ProjectEuler
0ccd2470206a606700ab5c2a7162b2a3d3de2f8d
[ "MIT" ]
null
null
null
#include <cstdint> #include <iostream> #include <utility> #include "continued_fraction.h" #include "largeint.h" using uInt = std::uint_fast32_t; using LInt = Euler::LargeInt<uInt>; using Fraction = std::pair<LInt, LInt>; // first: 分子, second: 分母 using namespace Euler::ContinuedFraction; int main(void) { constexpr uInt DEPTH_BOUND = 100; // 項目は1始まりで数える(1項目, 2項目, ...) Fraction frac = std::make_pair(1, 1); if (DEPTH_BOUND <= 1) { frac.first = napiers_term_at(0); } else { frac.second = napiers_term_at(DEPTH_BOUND - 1); } // 地道に分数計算 for (uInt i = 2; i <= DEPTH_BOUND; i++) { const uInt a = napiers_term_at(DEPTH_BOUND - i); frac.first += frac.second * a; if (i == DEPTH_BOUND) { continue; } // 1/(fr.f/fr.s) => fr.s/fr.f std::swap(frac.first, frac.second); } std::cout << "Euler065: " << frac.first.digits_sum() << std::endl; return 0; }
23.631579
68
0.635857
suihan74
1a69b234e05419fabf8a71196bb209069b6d6387
3,385
cpp
C++
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/wnd/XFadeShape.cpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
/***************************************************************************** XFadeShape.cpp Author: Laurent de Soras, 2017 --- Legal stuff --- This program is free software. It comes without any warranty, to the extent permitted by applicable law. You can redistribute it and/or modify it under the terms of the Do What The Fuck You Want To Public License, Version 2, as published by Sam Hocevar. See http://sam.zoy.org/wtfpl/COPYING for more details. *Tab=3***********************************************************************/ #if defined (_MSC_VER) #pragma warning (1 : 4130 4223 4705 4706) #pragma warning (4 : 4355 4786 4800) #endif /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include "fstb/Approx.h" #include "fstb/fnc.h" #include "fstb/ToolsSimd.h" #include "mfx/dsp/wnd/XFadeShape.h" #include <cassert> namespace mfx { namespace dsp { namespace wnd { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void XFadeShape::set_duration (double duration, float fade_ratio) { assert (duration > 0); assert (fade_ratio > 0); assert (fade_ratio <= 1); if (duration != _duration || fade_ratio != _fade_ratio) { _duration = duration; _fade_ratio = fade_ratio; if (is_ready ()) { make_shape (); } } } void XFadeShape::set_sample_freq (double sample_freq) { assert (sample_freq > 0); _sample_freq = sample_freq; make_shape (); } bool XFadeShape::is_ready () const { return (_sample_freq > 0); } int XFadeShape::get_len () const { assert (_len > 0); return _len; } const float * XFadeShape::use_shape () const { assert (_len > 0); return (&_shape [0]); } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ void XFadeShape::make_shape () { const int len = fstb::round_int (_sample_freq * _duration); if (len != _len) { _len = len; // +3 because we could read (or write) a full vector from the last // position const int len_margin = len + 3; _shape.resize (len_margin); #if 1 const float p = 0.25f / _fade_ratio; fstb::ToolsSimd::VectF32 x; fstb::ToolsSimd::VectF32 step; fstb::ToolsSimd::start_lerp (x, step, -p, p, len); const auto half = fstb::ToolsSimd::set1_f32 ( 0.5f ); const auto mi = fstb::ToolsSimd::set1_f32 (-0.25f); const auto ma = fstb::ToolsSimd::set1_f32 (+0.25f); for (int pos = 0; pos < len; pos += 4) { auto xx = x; xx = fstb::ToolsSimd::min_f32 (xx, ma); xx = fstb::ToolsSimd::max_f32 (xx, mi); auto v = fstb::Approx::sin_nick_2pi (xx); v *= half; v += half; fstb::ToolsSimd::store_f32 (&_shape [pos], v); x += step; } #else // Reference implementation const float p = 0.25f / _fade_ratio; const float dif = p * 2; const float step = dif * fstb::rcp_uint <float> (len); const float x = -p; for (int pos = 0; pos < len; ++pos) { const float xx = fstb::limit (x, -0.25f, +0.25f); const float v = fstb::Approx::sin_nick_2pi (xx) * 0.5f + 0.5f; _shape [pos] = v; x += step; } #endif } } } // namespace wnd } // namespace dsp } // namespace mfx /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
19.454023
78
0.534417
mikelange49
1a6e268dde28804830c7cc3dcdd417023249b707
93
cpp
C++
Source/Nova/Game/NovaDestination.cpp
Sabrave/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
17
2022-02-19T05:39:33.000Z
2022-03-01T01:56:19.000Z
Source/Nova/Game/NovaDestination.cpp
Frank1eJohnson/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
null
null
null
Source/Nova/Game/NovaDestination.cpp
Frank1eJohnson/ShipBuilder
4610c16701ccb85d6f1e0de77f914e58bcf4de7e
[ "BSD-3-Clause" ]
null
null
null
// Nova project - Gwennaël Arbona #include "NovaDestination.h" #include "Nova/Nova.h"
15.5
34
0.688172
Sabrave
1a6f4a155ba3def3a2ad336ba461a65aed37ae45
5,536
cpp
C++
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
src/core.cpp
xiroV/ninja-castle-game
92b5adde81e68cc98c6a696d6b3f6837a17499ca
[ "MIT" ]
null
null
null
#include"core.h" Collision::Collision() {} void Collision::init(std::string filename) { std::ifstream inFile; this->center_point = glm::vec2(22.5, 31.0); this->player_position.push_back(glm::vec4(0, 0, 0, 0)); this->player_position.push_back(glm::vec4(0, 0, 0, 0)); std::vector<unsigned int> vertex_indices, normal_indices; std::vector<glm::vec3> temp_v; std::vector<glm::vec3> temp_vn; bool read = true; inFile.open(filename); if(!inFile) { std::cout << "Can't open collision file " << filename << std::endl; exit(1); } // Read floor std::string ch; while(inFile >> ch && read) { if(ch == "v") { glm::vec3 vertex; inFile >> vertex.x; inFile >> vertex.y; inFile >> vertex.z; temp_v.push_back(vertex); } else if (ch == "o") { inFile >> ch; int s1 = ch.find("_"); if(ch.substr(0, s1) != "floor") { read = false; } } else if (ch == "vn") { glm::vec3 normal; inFile >> normal.x; inFile >> normal.y; inFile >> normal.z; temp_vn.push_back(normal); } else if (ch == "f") { unsigned int vertex_index[3], normal_index[3]; //unsigned int uv_index[3] for(int i = 0; i < 3; i++) { inFile >> ch; int s1 = ch.find("/"); vertex_index[i] = std::stoi(ch.substr(0, s1)); std::string ch2 = ch.substr(s1+1, ch.length()); int s2 = ch2.find("/"); /*if(s2 > 0) { uv_index[i] = std::stoi(ch.substr(s1, s2)); }*/ normal_index[i] = std::stoi(ch2.substr(s2+1, ch.length())); } vertex_indices.push_back(vertex_index[0]); vertex_indices.push_back(vertex_index[1]); vertex_indices.push_back(vertex_index[2]); normal_indices.push_back(normal_index[0]); normal_indices.push_back(normal_index[1]); normal_indices.push_back(normal_index[2]); } } // Done reading floor // Now processing floor indices for(unsigned int i=0; i < vertex_indices.size(); i++) { unsigned int vertex_index = vertex_indices[i]; unsigned int normal_index = normal_indices[i]; glm::vec3 v = temp_v[vertex_index-1]; this->floor_verts.push_back(v); glm::vec3 normal = temp_vn[normal_index-1]; this->floor_norms.push_back(normal); } inFile.close(); std::cout << "Collision map intialized" << std::endl; } bool Collision::on_floor(float x, float y) { for(unsigned int i = 0; i < this->floor_verts.size(); i+=3) { glm::vec2 p1, p2, p3; p1.x = this->floor_verts[i].x; p1.y = this->floor_verts[i].z; p2.x = this->floor_verts[i+1].x; p2.y = this->floor_verts[i+1].z; p3.x = this->floor_verts[i+2].x; p3.y = this->floor_verts[i+2].z; // Barycentric coordinates float alpha = ((p2.y - p3.y) * (x - p3.x) + (p3.x - p2.x) * (y - p3.y)) / ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x) * (p1.y - p3.y)); float beta = ((p3.y - p1.y) * (x - p3.x) + (p1.x - p3.x) * (y - p3.y)) / ((p2.y - p3.y)*(p1.x - p3.x) + (p3.x - p2.x)*(p1.y - p3.y)); float gamma = 1.0f - alpha - beta; if(alpha > 0.0 && beta > 0.0 && gamma > 0.0) { return true; } } return false; } bool Collision::wall_hit_x(float x, float y) { if(x > 10 && x < 34 && y > 18 && y < 45) { return false; } return !this->on_floor(x, y); } bool Collision::wall_hit_y(float x, float y) { if(x > 10 && x < 34 && y > 18 && y < 45) { return false; } return !this->on_floor(x, y); } float Collision::distance(glm::vec2 p1, glm::vec2 p2) { float distance = sqrt( pow(p1.x-p2.x, 2) + pow(p1.y-p2.y, 2) ); return distance; } float Collision::player_distance(unsigned int id) { glm::vec4 player = this->player_position[id]; glm::vec4 enemy = this->get_enemy_pos(id); // Calculate enemy ray float ray_x = enemy.x + (sin(enemy.w*PI/180) * CHAR_MOVE_SPEED); float ray_y = enemy.y + (cos(enemy.w*PI/180) * CHAR_MOVE_SPEED); float distance = sqrt( pow(player.x-ray_x, 2) + pow(player.y-ray_y, 2) + pow(player.z-enemy.z, 2) ); return distance; } bool Collision::player_collision(unsigned int player) { // Set to true if the player collided with enemy // Used to set velocities on knock-back for character if(this->player_distance(player) < 1.0) { return true; } return false; } // Method for players to report their position void Collision::report(unsigned int id, float x, float y, float z, float angle) { this->player_position[id].x = x; this->player_position[id].y = y; this->player_position[id].z = z; this->player_position[id].w = angle; } glm::vec4 Collision::get_enemy_pos(unsigned int player) { unsigned int enemy; if(player == 0) { enemy = 1; } else { enemy = 0; } return this->player_position[enemy]; } bool Collision::in_center(unsigned int id) { float distance = this->distance(glm::vec2(this->player_position[id].x, this->player_position[id].y), this->center_point); if(distance < 8.5) { return true; } return false; }
28.536082
144
0.53974
xiroV
2b2dd61a9b564be843b5a4a768fe43e64162ec90
6,944
hpp
C++
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
1
2021-03-29T06:09:19.000Z
2021-03-29T06:09:19.000Z
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
null
null
null
INCLUDE/ServiceConfiguration.hpp
SammyB428/WFC
64aee7c7953e38c8a418ba9530339e8f4faac046
[ "BSD-2-Clause" ]
null
null
null
/* ** Author: Samuel R. Blackburn ** Internet: wfc@pobox.com ** ** Copyright, 1995-2019, Samuel R. Blackburn ** ** "You can get credit for something or get it done, but not both." ** Dr. Richard Garwin ** ** BSD License follows. ** ** 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 WFC nor the names of its contributors may be used to endorse or ** promote products derived from this software without specific prior ** written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ** $Workfile: ServiceConfiguration.hpp $ ** $Revision: 12 $ ** $Modtime: 6/26/01 11:07a $ */ /* SPDX-License-Identifier: BSD-2-Clause */ #if ! defined( SERVICE_CONFIGURATION_CLASS_HEADER ) #define SERVICE_CONFIGURATION_CLASS_HEADER class CServiceConfigurationA { protected: DWORD m_TypeOfService{ 0 }; DWORD m_WhenToStart{ 0 }; DWORD m_ErrorControl{ 0 }; DWORD m_Tag{ 0 }; std::string m_NameOfExecutableFile; std::string m_LoadOrderGroup; std::string m_StartName; std::string m_DisplayName; std::vector<std::string> m_Dependencies; public: CServiceConfigurationA() noexcept; explicit CServiceConfigurationA( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; explicit CServiceConfigurationA( _In_ _QUERY_SERVICE_CONFIGA const * source ) noexcept; explicit CServiceConfigurationA( _In_ CServiceConfigurationA const& source ) noexcept; explicit CServiceConfigurationA( _In_ CServiceConfigurationA const * source ) noexcept; virtual ~CServiceConfigurationA() = default; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGA const * source ) noexcept; virtual void Copy( _In_ CServiceConfigurationA const& source ) noexcept; virtual void Copy( _In_ CServiceConfigurationA const * source ) noexcept; virtual void Empty( void ) noexcept; virtual void GetDependencies( _Out_ std::vector<std::string>& dependencies ) const noexcept; virtual void GetDisplayName( _Out_ std::string& display_name ) const noexcept; virtual _Check_return_ DWORD GetErrorControl( void ) const noexcept; virtual void GetLoadOrderGroup( _Out_ std::string& load_order_group ) const noexcept; virtual void GetNameOfExecutableFile( _Out_ std::string& name_of_executable ) const noexcept; virtual void GetStartName( _Out_ std::string& start_name ) const noexcept; virtual _Check_return_ DWORD GetTag( void ) const noexcept; virtual _Check_return_ DWORD GetTypeOfService( void ) const noexcept; virtual _Check_return_ DWORD GetWhenToStart( void ) const noexcept; virtual _Check_return_ CServiceConfigurationA& operator=( _In_ CServiceConfigurationA const& source ) noexcept; virtual _Check_return_ CServiceConfigurationA& operator=( _In_ _QUERY_SERVICE_CONFIGA const& source ) noexcept; #if defined( _DEBUG ) && ! defined( WFC_NO_DUMPING ) virtual void Dump( CDumpContext& dump_context ) const; #endif // _DEBUG }; class CServiceConfigurationW { protected: DWORD m_TypeOfService{0}; DWORD m_WhenToStart{0}; DWORD m_ErrorControl{0}; DWORD m_Tag{0}; std::wstring m_NameOfExecutableFile; std::wstring m_LoadOrderGroup; std::wstring m_StartName; std::wstring m_DisplayName; std::vector<std::wstring> m_Dependencies; public: CServiceConfigurationW() noexcept; explicit CServiceConfigurationW( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; explicit CServiceConfigurationW( _In_ _QUERY_SERVICE_CONFIGW const * source ) noexcept; explicit CServiceConfigurationW( _In_ CServiceConfigurationW const& source ) noexcept; explicit CServiceConfigurationW( _In_ CServiceConfigurationW const * source ) noexcept; virtual ~CServiceConfigurationW(); virtual void Copy( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; virtual void Copy( _In_ _QUERY_SERVICE_CONFIGW const * source ) noexcept; virtual void Copy( _In_ CServiceConfigurationW const& source ) noexcept; virtual void Copy( _In_ CServiceConfigurationW const * source ) noexcept; virtual void Empty( void ) noexcept; virtual void GetDependencies( _Out_ std::vector<std::wstring>& dependencies ) const noexcept; virtual void GetDisplayName( _Out_ std::wstring& display_name ) const noexcept; inline constexpr _Check_return_ DWORD GetErrorControl(void) const noexcept { return(m_ErrorControl); } virtual void GetLoadOrderGroup( _Out_ std::wstring& load_order_group ) const noexcept; virtual void GetNameOfExecutableFile( _Out_ std::wstring& name_of_executable ) const noexcept; virtual void GetStartName( _Out_ std::wstring& start_name ) const noexcept; inline constexpr _Check_return_ DWORD GetTag(void) const noexcept { return(m_Tag); } inline constexpr _Check_return_ DWORD GetTypeOfService(void) const noexcept { return(m_TypeOfService); } inline constexpr _Check_return_ DWORD GetWhenToStart(void) const noexcept { return(m_WhenToStart); } virtual _Check_return_ CServiceConfigurationW& operator=( _In_ CServiceConfigurationW const& source ) noexcept; virtual _Check_return_ CServiceConfigurationW& operator=( _In_ _QUERY_SERVICE_CONFIGW const& source ) noexcept; #if defined( _DEBUG ) && ! defined( WFC_NO_DUMPING ) virtual void Dump( CDumpContext& dump_context ) const; #endif // _DEBUG }; #if defined( UNICODE ) #define CServiceConfiguration CServiceConfigurationW #else #define CServiceConfiguration CServiceConfigurationA #endif // UNICODE #endif // SERVICE_CONFIGURATION_CLASS_HEADER
45.986755
117
0.751296
SammyB428
2b303ea879083312a7aa10e39830d4871b6b87d2
14,571
cpp
C++
lib/sram/src/sram.cpp
sinanislekdemir/MedlarII
ca5923c7408aae6f71b8e9b79a569e4a8b9da5e8
[ "MIT" ]
2
2021-03-14T07:29:22.000Z
2021-03-15T16:02:14.000Z
lib/sram/src/sram.cpp
sinanislekdemir/MedlarII
ca5923c7408aae6f71b8e9b79a569e4a8b9da5e8
[ "MIT" ]
null
null
null
lib/sram/src/sram.cpp
sinanislekdemir/MedlarII
ca5923c7408aae6f71b8e9b79a569e4a8b9da5e8
[ "MIT" ]
null
null
null
#include "sram.h" #include <Arduino.h> #include <freemem.h> #include <mdisplay.h> #include <stdint.h> SRam::SRam() { } SRam::~SRam() { this->close(); } char *dtoc(double d) { char *value = reinterpret_cast<char *>(&d); return value; } double ctod(char *data) { double resp = *reinterpret_cast<double *const>(data); return resp; } uint8_t argc(char *text, char delimiter) { // return argument count given in a text bool string_literal = false; uint8_t count = 1; for (uint8_t i = 0; i < strlen(text); i++) { if (text[i] == '"') { string_literal = !string_literal; } if (!string_literal && text[i] == '#') { break; } if (!string_literal && text[i] == delimiter) { count += 1; } } return count; } int extract_size(char *text, char delimiter, uint8_t part) { int result = 0; int n = strlen(text); int counter = 0; bool ignore = false; for (uint8_t i = 0; i < n; i++) { if (text[i] == '"') { ignore = !ignore; } if (text[i] != delimiter) { if (counter == part) { result++; } } else { if (ignore && counter == part) { result++; } } if (text[i] == delimiter && !ignore) { counter++; } } return result; } // strtok should do fine but I need to keep "..." intact int extract(char *text, char delimiter, uint8_t part, char *back) { int n = strlen(text); int j; j = 0; int counter = 0; bool ignore = false; for (uint8_t i = 0; i < n; i++) { if (text[i] == '"') { ignore = !ignore; } if (text[i] != delimiter) { if (counter == part) { back[j++] = text[i]; } } else { if (ignore && counter == part) { back[j++] = text[i]; } } if (text[i] == delimiter && !ignore) { counter++; } } back[j] = '\0'; return 0; } int rest(char *text, uint8_t pos, char *back) { if (pos >= strlen(text)) { return 0; } uint8_t j = 0; for (uint8_t i = pos; i < strlen(text); i++) { back[j++] = text[i]; } back[j] = '\0'; return j; } void SRam::open(const char *filename) { if (SD.exists(filename)) { bool d = SD.remove(filename); if (!d) { Serial.println("Failed to delete"); } } // FILE_WRITE != O_RDWR this->ram = SD.open(filename, FILE_WRITE); this->ram.close(); this->ram = SD.open(filename, O_RDWR); this->filename = (char *)malloc(strlen(filename) + 1); memcpy(this->filename, filename, strlen(filename)); this->filename[strlen(filename)] = '\0'; if (!this->ram) { return; } this->isOpen = true; } void SRam::close() { if (this->isOpen) { free(this->filename); this->ram.flush(); this->ram.close(); } } int SRam::ensureOpen() { if (this->filename == NULL || strlen(this->filename) == 0) { return -1; } if (!this->ram) { this->ram = SD.open(this->filename, O_RDWR); if (!this->ram) { return -1; } } return 0; } File SRam::get_file(memoryBlockHeader *m) { File r; if (!m || m->type != TYPE_FILE) { return r; } char *fname = (char *)malloc(MAX_FILE_PATH); memset(fname, '\0', MAX_FILE_PATH); this->read_all(m->varname, m->pid, fname, true); if (!SD.exists(fname)) { r = SD.open(fname, FILE_WRITE); r.close(); } r = SD.open(fname, O_RDWR); r.seek(0); free(fname); return r; } memoryBlockHeader *SRam::find_variable(char *name, uint16_t pid) { // Idea! // PID | VARNAME | USED | POSITION | SIZE | VARIABLE-DATA | PID | VARNAME | // USED... Header followed by the value. then the next variable header. memoryBlockHeader *variable = (memoryBlockHeader *)malloc(HeaderSize); if (name[0] == '$') { variable->exists = true; variable->pid = pid; variable->position = 0; variable->size = sizeof(double); variable->type = TYPE_DOUBLE; return variable; } uint32_t pos = 0; variable->exists = 0; this->ensureOpen(); this->ram.seek(0); while (this->ram.available()) { this->ram.readBytes((char *)(variable), HeaderSize); if (!variable->exists || variable->pid != pid || strcmp(variable->varname, name) != 0) { pos += HeaderSize + variable->size; // fast forward to the next variable position bool seek = this->ram.seek(pos); if (!seek) { break; } continue; } variable->position = pos + HeaderSize; return variable; } free(variable); return NULL; } void SRam::allocate_variable(char *name, uint16_t pid, uint16_t variableSize, uint8_t variable_type) { memoryBlockHeader variable; if (this->ensureOpen() == -1) { Serial.println("File not open"); return; } this->ram.seek(this->ram.size()); strcpy(variable.varname, name); variable.exists = 1; if (variable_type == TYPE_FILE) { variable.size = MAX_FILE_PATH; } else { variable.size = variableSize; } variable.pid = pid; variable.type = variable_type; this->ram.write((char *)(&variable), HeaderSize); this->ram.flush(); // allocate extra space for the variable for (uint16_t i = 0; i < variable.size; i++) { this->ram.write("\0", 1); if (i % 128 == 0) { this->ram.flush(); } } this->ram.flush(); } void SRam::delete_variable(char *name, uint16_t pid) { memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return; } uint32_t location = variable->position - HeaderSize + 1; variable->exists = 0; this->ram.seek(location); this->ram.write((char *)(variable), HeaderSize); this->ram.flush(); free(variable); } uint16_t SRam::read(char *name, uint16_t pid, uint32_t pos, char *buffer, uint16_t size, bool raw) { memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return 0; } if (variable->type == TYPE_FILE && !raw) { File f = this->get_file(variable); if (!f) { free(variable); return 0; } if (pos > f.size()) { free(variable); return 0; } f.seek(pos); if (f.available() == 0) { free(variable); return 0; } uint16_t size_read = f.readBytes(buffer, size); f.close(); free(variable); return size_read; } if (pos > variable->size) { free(variable); return 0; } if (pos + size > variable->size) { size = variable->size - pos; } bool seek_check = this->ram.seek(variable->position + pos); if (!seek_check) { free(variable); return 0; } free(variable); return this->ram.readBytes(buffer, size); } uint16_t SRam::read_all(char *name, uint16_t pid, char *buffer, bool raw) { memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return 0; } uint16_t r = this->read(name, pid, 0, buffer, variable->size, raw); free(variable); return r; } uint16_t SRam::write(char *name, uint16_t pid, uint32_t pos, char *data, uint16_t size, bool raw) { if (name[0] == '$') { char rest[2] = "\0"; strcpy(rest, name + 1); int index = atoi(rest); this->registers[index] = ctod(data); return sizeof(double); } memoryBlockHeader *variable = this->find_variable(name, pid); if (variable == NULL) { return -1; } if (variable->type == TYPE_FILE && !raw) { File f = this->get_file(variable); if (!f) { free(variable); return 0; } if (pos > f.size()) { pos = f.size(); } f.seek(pos); uint16_t size_write = f.write(data); f.close(); free(variable); return size_write; } if (size + pos > variable->size) { free(variable); return -2; } bool seek_check = this->ram.seek(variable->position + pos); if (!seek_check) { free(variable); return -3; } free(variable); uint16_t size_w = this->ram.write(data, size); this->ram.flush(); return size_w; } // sinan int SRam::get_var_size(char *text, uint16_t pid) { if (text[0] == '"' && text[strlen(text) - 1] == '"') { return strlen(text); } if (strlen(text) > 0 && isdigit(text[0])) { return sizeof(double); } if (text[0] == '$') { return sizeof(double); } memoryBlockHeader *m; char *shortened = (char *)malloc(strlen(text)); if (strstr(text, "[") != NULL && strstr(text, "]") != NULL) { memset(shortened, '\0', strlen(text)); extract(text, '[', 0, shortened); m = this->find_variable(shortened, pid); } else { m = this->find_variable(text, pid); } if (m == NULL) { free(shortened); return -1; } if (m->type == TYPE_NUM) { free(m); free(shortened); return sizeof(double); } uint16_t read_size = m->size; if (strstr(text, "[") != NULL && strstr(text, "]") != NULL) { uint32_t end = this->get_end(text, pid); free(shortened); free(m); return end; } if (m->type == TYPE_FILE) { File f = this->get_file(m); if (!f) { return -1; } uint32_t s = f.size(); f.close(); free(shortened); free(m); return s; } free(shortened); free(m); return read_size; } uint32_t SRam::get_start(char *text, uint16_t pid) { char temp[16]; char back[4]; int state = 0; int p = 0; for (uint8_t i = 0; i < strlen(text); i++) { if (text[i] == ':' || text[i] == ']') { break; } if (state == 1) { temp[p++] = text[i]; temp[p] = '\0'; } if (text[i] == '[') { state = 1; } } memset(back, 0, 4); this->get_var(temp, pid, back); return ctod(back); } uint32_t SRam::get_end(char *text, uint16_t pid) { char temp[16]; char back[4]; int state = 0; int p = 0; for (uint8_t i = 0; i < strlen(text); i++) { if (text[i] == ']') { break; } if (state == 1) { temp[p++] = text[i]; temp[p] = '\0'; } if (text[i] == ':') { state = 1; } } memset(back, 0, 4); this->get_var(temp, pid, back); return ctod(back); } /** * @brief Get variable from memory file * * @param text - variable name * @param pid - process id * @param back - back buffer * @return int - return 0 for text, 1 for number, -1 for no match */ int SRam::get_var(char *text, uint16_t pid, char *back) { if (back == NULL) { return 0; } if (text[0] == '$') { char rest[2] = "\0"; strcpy(rest, text + 1); int index = atoi(rest); memcpy(back, dtoc(this->registers[index]), sizeof(double)); return TYPE_NUM; } if (text[0] == '"' && text[strlen(text) - 1] == '"') { uint8_t p = 0; for (unsigned int i = 1; i < strlen(text) - 1; i++) { back[p++] = text[i]; } return TYPE_BYTE; } if (strlen(text) > 0 && isdigit(text[0])) { double x = atof(text); memcpy(back, dtoc(x), sizeof(double)); return TYPE_NUM; } if (strcmp(text, "millis") == 0) { double x = millis(); memset(back, 0, 4); memcpy(back, dtoc(x), sizeof(double)); return TYPE_NUM; } char *shortened = (char *)malloc(strlen(text)); bool partial = false; memset(shortened, 0, strlen(text)); memoryBlockHeader *m; if (strstr(text, "[") != NULL && strstr(text, "]") != NULL) { extract(text, '[', 0, shortened); partial = true; m = this->find_variable(shortened, pid); } else { m = this->find_variable(text, pid); } if (m == NULL) { free(shortened); return -1; } uint16_t from = 0; uint16_t read_size = m->size; if (partial) { from = uint16_t(this->get_start(text, pid)); read_size = uint16_t(this->get_end(text, pid)); this->read(shortened, pid, from, back, read_size, false); } else { this->read(text, pid, from, back, read_size, false); } free(shortened); int ret = m->type; free(m); return ret; } void SRam::dump() { // Idea! // PID | VARNAME | USED | POSITION | SIZE | VARIABLE-DATA | PID | VARNAME | // USED... Header followed by the value. then the next variable header. memoryBlockHeader variable; this->ram.seek(0); if (this->ensureOpen() == -1) { Serial.println("Memory is not accessable"); } Serial.print("Filename: "); Serial.println(this->filename); Serial.print("Memory size:"); Serial.print(this->ram.size()); Serial.println(" bytes"); while (this->ram.readBytes((char *)(&variable), HeaderSize) > 0) { Serial.print("Variable name: "); Serial.println(variable.varname); Serial.print("Variable exists: "); Serial.println(variable.exists); Serial.print("Variable size: "); Serial.println(variable.size); Serial.print("Variable type: "); Serial.println(variable.type); this->ram.seek(this->ram.position() + variable.size); } }
21.747761
100
0.49372
sinanislekdemir
2b3437df2442f79b844247273b091143e02b3108
3,341
cpp
C++
Game.cpp
JankoDedic/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
1
2018-02-28T14:21:14.000Z
2018-02-28T14:21:14.000Z
Game.cpp
djanko1337/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
null
null
null
Game.cpp
djanko1337/TappyPlane
79b047e6343aaaa41fdf1281e4db9dfbb95bb0d2
[ "MIT" ]
1
2020-07-13T08:56:55.000Z
2020-07-13T08:56:55.000Z
#include "Game.hpp" #include "RectangleFunctions.hpp" #include "Renderer.hpp" namespace TappyPlane { using namespace SDLW::Video; using namespace SDLW::Events; constexpr auto backgroundSpritesheetHandle = "background"; constexpr auto backgroundBounds = canvasBounds; constexpr auto backgroundScrollSpeed = 0.5f; constexpr auto groundSpritesheetHandle = "ground"; constexpr Rectangle groundBounds{0, canvasBounds.height() - 270, canvasBounds.width(), 270}; constexpr auto groundScrollSpeed = 2.0f; constexpr int spikePairDistance{420}; constexpr int spikesScrollSpeed{5}; constexpr auto getReadySpritesheetHandle = "getReady"; constexpr Rectangle getReadyBounds{canvasBounds.width() / 2 - 907 / 2, canvasBounds.height() / 2 - 163 / 2, 907, 163}; constexpr auto gameOverSpritesheetHandle = "gameOver"; constexpr Rectangle gameOverBounds{canvasBounds.width() / 2 - 934 / 2, canvasBounds.height() / 2 - 176 / 2, 934, 176}; Game::Game() : mGameState(State::GetReady) , mBackground(backgroundSpritesheetHandle, backgroundBounds, backgroundScrollSpeed) , mGround(groundSpritesheetHandle, groundBounds, groundScrollSpeed) , mSpikes(spikePairDistance, spikesScrollSpeed) , mGetReadySprite(getReadySpritesheetHandle, getReadyBounds) , mGameOverSprite(gameOverSpritesheetHandle, gameOverBounds) { } void Game::handleEvent(const Event& event) noexcept { if (event.type() == Event::Type::MouseButtonDown) { switch (mGameState) { case State::GetReady: start(); break; case State::InProgress: mPlane.jump(); break; case State::GameOver: reset(); break; default: break; } } } void Game::update() noexcept { if (mGameState != State::InProgress) { return; } mBackground.update(); mGround.update(); mSpikes.update(); mPlane.update(); if (hasPlaneCrashed()) { mBackground.pause(); mGround.pause(); mSpikes.pause(); mPlane.pause(); mGameState = State::GameOver; } } void Game::draw() const { mBackground.draw(); mPlane.draw(); mSpikes.draw(); mGround.draw(); if (mGameState == State::GetReady) { mGetReadySprite.draw(); } else if (mGameState == State::GameOver) { mGameOverSprite.draw(); } } void Game::start() { mBackground.play(); mSpikes.play(); mGround.play(); mPlane.play(); mGameState = State::InProgress; } void Game::reset() { mPlane.reset(); mSpikes.reset(); mGameState = State::GetReady; } static bool areColliding(const Plane& plane, const Spikes& spikes) { for (auto[first, last] = spikes.bounds(); first < last; ++first) { if (areIntersecting(plane.bounds(), first->topSpikeBounds) || areIntersecting(plane.bounds(), first->bottomSpikeBounds)) { return true; } } return false; } bool Game::hasPlaneCrashed() { return areColliding(mPlane, mSpikes) || didPlaneHitTheGround() || didPlaneHitTheCeiling(); } bool Game::didPlaneHitTheGround() { return areIntersecting(mPlane.bounds(), mGround.bounds()); } bool Game::didPlaneHitTheCeiling() { return topOf(mPlane.bounds()) < topOf(canvasBounds); } } // namespace TappyPlane
24.566176
75
0.657887
JankoDedic
2b3c6494fcf05fd98c75d47ed901c2fa1affe08f
24,449
cpp
C++
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
9
2020-04-01T04:15:22.000Z
2021-09-26T21:03:47.000Z
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
17
2020-04-02T19:38:40.000Z
2020-04-12T05:47:08.000Z
src/article.cpp
taviso/mpgravity
f6a2a7a02014b19047e44db76ae551bd689c16ac
[ "BSD-3-Clause" ]
null
null
null
/*****************************************************************************/ /* SOURCE CONTROL VERSIONS */ /*---------------------------------------------------------------------------*/ /* */ /* Version Date Time Author / Comment (optional) */ /* */ /* $Log: article.cpp,v $ /* Revision 1.1 2010/07/21 17:14:56 richard_wood /* Initial checkin of V3.0.0 source code and other resources. /* Initial code builds V3.0.0 RC1 /* /* Revision 1.3 2009/08/25 20:04:25 richard_wood /* Updates for 2.9.9 /* /* Revision 1.2 2009/08/16 21:05:38 richard_wood /* Changes for V2.9.7 /* /* Revision 1.1 2009/06/09 13:21:28 richard_wood /* *** empty log message *** /* /* Revision 1.7 2008/09/19 14:51:10 richard_wood /* Updated for VS 2005 /* /* */ /*****************************************************************************/ /********************************************************************************** Copyright (c) 2003, Albert M. Choy 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 Microplanet, 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 OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. **********************************************************************************/ /////////////////////////////////////////////////////////////////////////// // article.cpp - The outer object relays requests to the // inner object. This module is mostly fluff. // #include "stdafx.h" #include "afxmt.h" #include "article.h" #include "utilstr.h" #include "codepg.h" #include "tglobopt.h" #include "rgcomp.h" #include "8859x.h" #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char BASED_CODE THIS_FILE[] = __FILE__; #endif // live and die at global scope TMemShack TArticleHeader::m_gsMemShack(sizeof(TArticleHeader), "Hdr"); static CCriticalSection sArtCritical; extern ULONG String_base64_decode (LPTSTR pInBuf, int nInSz, LPTSTR pOutBuf, int nOutSz); extern ULONG String_QP_decode (LPCTSTR pInBuf, int nInSz, LPTSTR pOutBuf, int nOutSz); int magic_isohdr_translate (LPCTSTR text, CString & strOut); // Used for RFC 2047 decoding in headers class TAnsiCodePage { public: TAnsiCodePage() { // Old Wisdom // ISO-8859-1 == LATIN 1 == CP 1252 // ISO-8859-2 == LATIN 2 == CP 1250 } // this is used strictly for SUBJECT and FROM lines BOOL CanTranslate(LPCTSTR pszText, int & iType, GravCharset * & rpCharset) { int unusedLen = 0; int ret = this->FindISOString ( pszText, unusedLen, rpCharset ); if (0==ret) return FALSE; else { iType = ret; return TRUE; } } // =========================================================== // return 1 for QP, 2 for B64, 0 for 'can not handle it' // // update ln - offset to start of good data (after 8859-15?Q?) // // example: // =?iso-8859-1?q?this=20is=20some=20text?= BOOL FindISOString (LPCTSTR cpIn, int & ln, GravCharset * & rpCharset) { CString strcp = cpIn; strcp.MakeLower(); LPCTSTR cp = strcp; LPTSTR pRes = 0; pRes = (LPSTR)strstr (cp, "=?"); if (NULL == pRes) return FALSE; if (NULL == *(pRes+2)) return FALSE; else { CString charsetName; LPTSTR pTravel = pRes + 2; int n=0; LPTSTR pTxt = charsetName.GetBuffer(strcp.GetLength()); while (*pTravel && ('?' != *pTravel)) { *pTxt++ = *pTravel++; n++; } charsetName.ReleaseBuffer(n); // use the map for a fast lookup rpCharset = gsCharMaster.findByName( charsetName ); if (NULL == rpCharset) return FALSE; if (NULL == *pTravel) // pTravel should point to the ?q? or ?b? return FALSE; ASSERT('?' == *pTravel); ++pTravel; TCHAR cEncoding = *pTravel; int ret = 0; if (NULL == cEncoding) return 0; if ('q' == cEncoding) ret = 1; else if ('b' == cEncoding) ret = 2; else return ret; ++pTravel; // point to 2nd ? if ((NULL == *pTravel) || ('?' != *pTravel)) return 0; ++pTravel; // point to start of data ln = pTravel - cp; return ret; } } }; static TAnsiCodePage gsCodePage; /////////////////////////////////////////////////////////////////////////// // TPersist822Header // #if defined(_DEBUG) void TPersist822Header::Dump(CDumpContext& dc) const { TBase822Header::Dump( dc ); m_pRep->Dump (dc); dc << "TPersist822Hdr\n" ; } #endif /////////////////////////////////////////////////////////////////////////// // Destructor TPersist822Header::TPersist822Header() { m_pRep = 0; // the derived classes must instantiate the Inner representation } /////////////////////////////////////////////////////////////////////////// // copy-constructor TPersist822Header::TPersist822Header(const TPersist822Header& src) { m_pRep = src.m_pRep; m_pRep->AddRef (); } /////////////////////////////////////////////////////////////////////////// // Destructor TPersist822Header::~TPersist822Header() { try { ASSERT(m_pRep); m_pRep->DeleteRef (); } catch(...) { // catch everything - no exceptions can leave a destructor } } void TPersist822Header::copy_on_write() { if (m_pRep->iGetRefCount() == 1) return; // call virt function to make the right kind of object TPersist822HeaderInner * pCpyInner = m_pRep->duplicate(); TPersist822HeaderInner * pOriginal = m_pRep; m_pRep = pCpyInner; // I now have a fresh copy all to myself pOriginal->DeleteRef(); // you have 1 less client } /////////////////////////////////////////////////////////////////////////// // NOTE: ask Al before using this function // // 5-01-96 amc Created void TPersist822Header::PrestoChangeo_AddReferenceCount() { ASSERT(m_pRep); m_pRep->AddRef (); // you have 1 more client } void TPersist822Header::PrestoChangeo_DelReferenceCount() { ASSERT(m_pRep); m_pRep->DeleteRef (); // you have 1 less client } void TPersist822Header::SetNumber(LONG n) { copy_on_write(); m_pRep->SetNumber(n); } void TPersist822Header::SetLines (int lines) { copy_on_write(); m_pRep->SetLines ( lines ); } void TPersist822Header::SetLines (const CString& body) { copy_on_write(); m_pRep->SetLines ( body ); } void TPersist822Header::StampCurrentTime() { copy_on_write(); m_pRep->StampCurrentTime(); } void TPersist822Header::SetMimeLines(LPCTSTR ver, LPCTSTR type, LPCTSTR encode, LPCTSTR desc) { copy_on_write(); // the inner function is virtual m_pRep->SetMimeLines (ver, type, encode, desc); } void TPersist822Header::GetMimeLines(CString* pVer, CString* pType, CString* pCode, CString* pDesc) { // the inner function is virtual m_pRep->GetMimeLines (pVer, pType, pCode, pDesc); } void TPersist822Header::Serialize(CArchive & archive) { // the inner function is virtual m_pRep->Serialize ( archive ); } TPersist822Header & TPersist822Header::operator=(const TPersist822Header &rhs) { if (&rhs == this) return *this; m_pRep->DeleteRef(); // he has one less client m_pRep = rhs.m_pRep; // copy ptr m_pRep->AddRef (); // you have 1 more client return *this; } ///// end TPersist822Header /////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // TArticleHeader // TArticleHeader::TArticleHeader() { // set object version m_pRep = new TArticleHeaderInner(TArticleHeaderInner::kVersion); } // Destructor TArticleHeader::~TArticleHeader() { /* empty */ } TArticleHeader& TArticleHeader::operator=(const TArticleHeader &rhs) { if (&rhs == this) return *this; TPersist822Header::operator=(rhs); return *this; } /////////////////////////////////////////////////////////////////////////// ULONG TArticleHeader::ShrinkMemPool() { if (true) { CSingleLock sLock(&sArtCritical, TRUE); ULONG u1 = TArticleHeader::m_gsMemShack.Shrink (); } ULONG u2 = TArticleHeaderInner::ShrinkMemPool(); return u2; } #if defined(_DEBUG) void TArticleHeader::Dump(CDumpContext& dc) const { // base class version TPersist822Header::Dump(dc); dc << "ArtHdr\n" ; } #endif ///// member functions void TArticleHeader::FormatExt(const CString& control, CString& strLine) { GetPA()->FormatExt (control, strLine); } void TArticleHeader::SetArticleNumber (LONG artInt) { copy_on_write(); m_pRep->SetNumber(artInt); } void TArticleHeader::SetDate(LPCTSTR date_line) { copy_on_write(); GetPA()->SetDate ( date_line ); } LPCTSTR TArticleHeader::GetDate(void) { return GetPA()->GetDate (); } void TArticleHeader::AddNewsGroup (LPCTSTR ngroup) { copy_on_write(); GetPA()->AddNewsGroup ( ngroup ); } void TArticleHeader::GetNewsGroups (CStringList* pList) const { GetPA()->GetNewsGroups ( pList ); } int TArticleHeader::GetNumOfNewsGroups () const { return GetPA()->GetNumOfNewsGroups (); } void TArticleHeader::ClearNewsGroups () { copy_on_write(); GetPA()->ClearNewsGroups (); } BOOL TArticleHeader::operator<= (const TArticleHeader & rhs) { return (*GetPA()) <= ( *(rhs.GetPA()) ); } void TArticleHeader::SetControl (LPCTSTR control) { copy_on_write(); GetPA()->SetControl ( control ); } LPCTSTR TArticleHeader::GetControl () { return GetPA()->GetControl (); } void TArticleHeader::SetDistribution(LPCTSTR dist) { copy_on_write(); GetPA()->SetDistribution (dist); } LPCTSTR TArticleHeader::GetDistribution() { return GetPA()->GetDistribution(); } void TArticleHeader::SetExpires(LPCTSTR dist) { copy_on_write(); GetPA()->SetExpires (dist); } LPCTSTR TArticleHeader::GetExpires() { return GetPA()->GetExpires(); } // user sets what groups to Followup-To void TArticleHeader::SetFollowup(LPCTSTR follow) { copy_on_write(); GetPA()->SetFollowup(follow); } LPCTSTR TArticleHeader::GetFollowup(void) const { return GetPA()->GetFollowup(); } void TArticleHeader::SetOrganization(LPCTSTR org) { copy_on_write(); GetPA()->SetOrganization(org); } LPCTSTR TArticleHeader::GetOrganization() { return GetPA()->GetOrganization(); } void TArticleHeader::SetKeywords(LPCTSTR keywords) { copy_on_write(); GetPA()->SetKeywords(keywords); } LPCTSTR TArticleHeader::GetKeywords(void) { return GetPA()->GetKeywords(); } void TArticleHeader::SetSender(LPCTSTR sndr) { copy_on_write(); GetPA()->SetSender(sndr); } LPCTSTR TArticleHeader::GetSender(void) { return GetPA()->GetSender(); } void TArticleHeader::SetReplyTo(LPCTSTR replyto) { copy_on_write(); GetPA()->SetReplyTo(replyto); } LPCTSTR TArticleHeader::GetReplyTo() { return GetPA()->GetReplyTo(); } void TArticleHeader::SetSummary(LPCTSTR sum) { copy_on_write(); GetPA()->SetSummary (sum); } LPCTSTR TArticleHeader::GetSummary(void) { return GetPA()->GetSummary(); } void TArticleHeader::SetXRef(LPCTSTR xref) { copy_on_write(); GetPA()->SetXRef(xref); } LPCTSTR TArticleHeader::GetXRef(void) { return GetPA()->GetXRef(); } // ------------------------------------------------------------------ // // void TArticleHeader::SetQPFrom (const CString & from) { copy_on_write(); // put it in GetPA()->SetFrom (from); } void TArticleHeader::SetFrom (const CString & from) { GetPA()->SetFrom (from); } CString TArticleHeader::GetFrom () { return GetPA()->GetFrom (); } const CString & TArticleHeader::GetOrigFrom(void) { return GetPA()->GetOrigFrom (); } void TArticleHeader::SetOrigFrom(const CString & f) { GetPA()->SetOrigFrom(f); } const CString & TArticleHeader::GetPhrase(void) { return GetPA()->GetPhrase(); } void TArticleHeader::SetMessageID (LPCTSTR msgid) { copy_on_write(); GetPA()->SetMessageID(msgid); } LPCTSTR TArticleHeader::GetMessageID(void) { return GetPA()->GetMessageID(); } int handle_2hex_digits (LPCTSTR cp, TCHAR & cOut) { BYTE e; TCHAR c, c2; if ((NULL == (c = cp[1])) || (NULL == (c2 = cp[2]))) return 1; if (!isxdigit (c)) /* must be hex! */ return 1; if (isdigit (c)) e = c - '0'; else e = c - (isupper (c) ? 'A' - 10 : 'a' - 10); c = c2; /* snarf next character */ if (!isxdigit (c)) /* must be hex! */ return 1; if (isdigit (c)) c -= '0'; else c -= (isupper (c) ? 'A' - 10 : 'a' - 10); cOut = TCHAR( BYTE( (e << 4) + c) ); /* merge the two hex digits */ return 0; } // ---------------------------------------------------------- // handle 2047 translation // struct T2047Segment { T2047Segment(LPCTSTR txt, bool fWS0) : fWS(fWS0), text(txt) { iEncodingType = 0; len = 0; } bool fWS; CString text; int iEncodingType; int len; }; typedef T2047Segment* P2047Segment; inline bool is_lwsp(TCHAR c) { if (' ' == c || '\t' == c) return true; else return false; } LPCTSTR read_ws_token (LPCTSTR pTrav, LPTSTR pToken) { while (*pTrav && is_lwsp(*pTrav)) *pToken++ = *pTrav++; *pToken = 0; return pTrav; } LPCTSTR read_black_token (LPCTSTR pTrav, LPTSTR pToken) { while (*pTrav && !is_lwsp(*pTrav)) *pToken++ = *pTrav++; *pToken = 0; return pTrav; } // ---------------------------------------------------------- int magic_hdr2047_segmentize ( LPCSTR subject, CTypedPtrArray<CPtrArray, P2047Segment> & listSegments, LPTSTR rcToken) { LPCTSTR pTrav = subject; while (*pTrav) { if (is_lwsp(*pTrav)) { pTrav = read_ws_token (pTrav, rcToken); listSegments.Add ( new T2047Segment(rcToken, true) ); } else { pTrav = read_black_token (pTrav, rcToken); listSegments.Add ( new T2047Segment(rcToken, false) ); } } return 0; } // ---------------------------------------------------------- // Example 1: // Subject: Hobbits v Sm=?ISO-8859-1?B?6Q==?=agol // This is incorrectly encoded // // Subject: =?Windows-1252?Q?Re:_Hobbits_v_Sm=E9agol?= // // this is better, since the encoded word is 1 ATOM (see rfc2047 section 5) // // HOWEVER, to be generous, I handle the top case now // int segment_2047_translate (T2047Segment * pS1, LPTSTR rcToken) { LPCTSTR cp = pS1->text; TCHAR c; int ret = 0; std::istrstream in_stream(const_cast<LPTSTR>(cp)); std::ostrstream out_stream(rcToken, 4096 * 4); std::vector<BYTE> vEncodedBytes; bool insideEncodedWord = false; int questionCount; while (in_stream.get(c)) { if (!insideEncodedWord) { if ('=' == c && '?' == TCHAR(in_stream.peek())) { insideEncodedWord = true; questionCount = 0; ret = 1; // set return to error } else { out_stream.put( c ); } } else { if (questionCount < 3) { if (c == '?') { questionCount++; } } else { if (c == '?' && TCHAR(in_stream.peek()) == '=') { in_stream.get(c); //eat = TCHAR rcDecoded[4024]; ULONG uLen; vEncodedBytes.push_back(0); LPTSTR psz=reinterpret_cast<LPTSTR>(&vEncodedBytes[0]); if (2 == pS1->iEncodingType) uLen = String_base64_decode (psz, vEncodedBytes.size()-1, rcDecoded, sizeof(rcDecoded)); else uLen = String_QP_decode (psz, vEncodedBytes.size()-1, rcDecoded, sizeof(rcDecoded)); for (int n = 0; n < uLen; ++n) out_stream.put (rcDecoded[n]); insideEncodedWord = false; vEncodedBytes.clear(); ret = 0; } else { vEncodedBytes.push_back((1 == pS1->iEncodingType && '_' == c) ? ' ' : c); } } } // end insideEW } // while // final cleanup if (0 == ret) { out_stream.put(0); pS1->text = rcToken; } return ret; } // ---------------------------------------------------------- int magic_hdr2047_translate (LPCSTR subject, CString & strOut) { TCHAR rcToken[4096 * 4]; CTypedPtrArray<CPtrArray, P2047Segment> listSegments; int iStat=0; magic_hdr2047_segmentize (subject, listSegments, rcToken); int sz = listSegments.GetSize(); int i; for (i = 0; i < sz; i++) { T2047Segment * pSeg = listSegments[i]; GravCharset * pCharsetDummy = 0; int encType = gsCodePage.FindISOString (pSeg->text, pSeg->len, pCharsetDummy); pSeg->iEncodingType = encType; } // drop LWSP segments in between encoded words for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if ((i+2) < listSegments.GetSize()) { T2047Segment* pS2 = listSegments[i+1]; T2047Segment* pS3 = listSegments[i+2]; if (pS1->iEncodingType && !pS1->text.IsEmpty() && pS2->fWS && pS3->iEncodingType && !pS3->text.IsEmpty()) { delete pS2; listSegments.RemoveAt (i+1); } } } // per segment translate for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if (pS1->iEncodingType) { iStat = segment_2047_translate (pS1, rcToken); if (iStat) break; } } // cleanup and build final string for (i = 0; i < listSegments.GetSize(); i++) { T2047Segment* pS1 = listSegments[i]; if (0 == iStat) strOut += pS1->text; delete pS1; } return iStat; } // ---------------------------------------------------------- int magic_isohdr_translate (LPCSTR subject, CString & strOut) { // do QP translation here // ex: // =?iso-8859-1?q?this=20is=20some=20text?= int iType = 0; GravCharset * pCharset = 0; if (FALSE == gsCodePage.CanTranslate(subject, iType, pCharset)) { // this may be untagged eight bit if ( using_hibit(subject) ) { int iSendCharset = gpGlobalOptions->GetRegCompose()->GetSendCharset(); GravCharset* pCharsetUser = gsCharMaster.findById( iSendCharset ); return CP_Util_Inbound (pCharsetUser, subject, lstrlen(subject), strOut); } else return 1; } CString strBytes; int stat = magic_hdr2047_translate (subject, strBytes); if (stat) return stat; // go from bytes to chars return CP_Util_Inbound ( pCharset, strBytes, strBytes.GetLength(), strOut); } // ---------------------------------------------------------- void TArticleHeader::SetQPSubject(LPCTSTR subject, LPCTSTR pszFrom) { copy_on_write(); CString strOut; // do QP translation here if (0 == magic_isohdr_translate (subject, strOut)) GetPA()->SetSubject(strOut); else GetPA()->SetSubject(subject); } void TArticleHeader::SetSubject(LPCTSTR subject) { copy_on_write(); GetPA()->SetSubject(subject); } LPCTSTR TArticleHeader::GetSubject (void) { return GetPA()->GetSubject(); } void TArticleHeader::GetDestList(TStringList* pList) const { GetPA()->GetDestList (pList); } void TArticleHeader::Format (CString& strLine) { GetPA()->Format(strLine); } int TArticleHeader::ParseFrom (CString& phrase, CString& address) { return GetPA()->ParseFrom(phrase, address); } void TArticleHeader::SetReferences (const CString& refs) { copy_on_write(); GetPA()->SetReferences (refs); } void TArticleHeader::SetCustomHeaders (const CStringList &sCustomHeaders) { copy_on_write(); GetPA()->SetCustomHeaders (sCustomHeaders); } const CStringList &TArticleHeader::GetCustomHeaders () const { return GetPA()->GetCustomHeaders(); } BOOL TArticleHeader::AtRoot(void) { return GetPA()->AtRoot(); } BOOL TArticleHeader::FindInReferences(const CString& msgID) { return GetPA()->FindInReferences(msgID); } int TArticleHeader::GetReferencesCount() { return GetPA()->GetReferencesCount(); } void TArticleHeader::CopyReferences(const TArticleHeader & src) { copy_on_write(); GetPA()->CopyReferences( *(src.GetPA()) ); } void TArticleHeader::ConstructReferences(const TArticleHeader & src, const CString& msgid) { GetPA()->ConstructReferences(*(src.GetPA()), msgid); } void TArticleHeader::GetDadRef(CString& str) { GetPA()->GetDadRef (str); } void TArticleHeader::GetFirstRef(CString& str) { GetPA()->GetFirstRef(str); } void TArticleHeader::GetReferencesWSList(CString& line) { GetPA()->GetReferencesWSList(line); } void TArticleHeader::GetReferencesStringList(CStringList* pList) { GetPA()->GetReferencesStringList(pList); } const TFlatStringArray &TArticleHeader::GetReferences () { return GetPA()->GetReferences(); } // end of TArticle Implementation /////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////// // TEmailHeader // TEmailHeader::TEmailHeader() { m_pRep = new TEmailHeaderInner(TEmailHeaderInner::kVersion); // object version is 1 } // Empty destructor TEmailHeader::~TEmailHeader() { /* empty */ } TEmailHeader& TEmailHeader::operator=(const TEmailHeader &rhs) { if (&rhs == this) return *this; TPersist822Header::operator=(rhs); // do normal stuff return *this; } void TEmailHeader::Set_InReplyTo (LPCTSTR irt) { copy_on_write(); GetPE()->Set_InReplyTo(irt); } LPCTSTR TEmailHeader::Get_InReplyTo () { return GetPE()->Get_InReplyTo(); } int TEmailHeader::GetDestinationCount(TBase822Header::EAddrType eAddr) { return GetPE()->GetDestinationCount(eAddr); } void TEmailHeader::ParseTo(const CString & to, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseTo (to, pOutList, pErrList); } void TEmailHeader::GetToText(CString& txt) { GetPE()->GetToText (txt); } // CC - store the comma separated list of addresses void TEmailHeader::ParseCC(const CString& comma_sep_CC_list, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseCC (comma_sep_CC_list, pOutList, pErrList); } // CC - get the displayable text, separated by commas void TEmailHeader::GetCCText(CString& txt) { GetPE()->GetCCText ( txt ); } // BCC - store the comma separated list of addresses void TEmailHeader::ParseBCC(const CString& comma_sep_BCC_list, TStringList * pOutList /* = 0 */, CStringList * pErrList /* = 0 */) { if (0 == pOutList) copy_on_write(); GetPE()->ParseBCC ( comma_sep_BCC_list, pOutList, pErrList ); } // BCC - get the displayable text, separated by commas void TEmailHeader::GetBCCText(CString& txt) { GetPE()->GetBCCText ( txt ); } void TEmailHeader::GetDestinationList (TBase822Header::EAddrType eAddr, TStringList * pstrList) const { GetPE()->GetDestinationList(eAddr, pstrList); } // end of file
24.4002
95
0.598961
taviso
2b3f56c43262005553a7666cdfa8b342238ac1bd
3,199
hpp
C++
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
attributes/attribute.hpp
5cript/electronpp
03e257d62f2b939544c5d1c2d8718e58f2d71e34
[ "MIT" ]
null
null
null
#pragma once #include "generic_attribute.hpp" #include "../util/observer.hpp" #include <emscripten/val.h> #include <functional> #include <iostream> namespace CppDom::Attributes { template <typename ValueT> class Attribute : public GenericAttribute { public: Attribute(std::string name, ValueT value) : name_{std::move(name)} , value_{std::move(value)} { } void setOn(emscripten::val& node) override { using emscripten::val; node.call<val>("setAttribute", val(name_), val(value_)); } Attribute* clone() const override { return new Attribute(name_, value_); } Attribute(Attribute const&) = default; Attribute(Attribute&&) = default; private: std::string name_; ValueT value_; }; class ComplexAttribute : public GenericAttribute { public: ComplexAttribute(std::function <void(emscripten::val&)> setOn) : GenericAttribute{} , setOn_{setOn} { } void setOn(emscripten::val& node) override { setOn_(node); } ComplexAttribute* clone() const override { return new ComplexAttribute(setOn_); } private: std::function <void(emscripten::val&)> setOn_; }; template <typename ValueT> class ReactiveAttribute : public GenericAttribute { public: ReactiveAttribute(std::string name, SharedObserver<ValueT> value) : name_{std::move(name)} , value_{std::move(value)} { value_.subscribe(this); } ~ReactiveAttribute() { value_.unsubscribe(this); } operator=(ReactiveAttribute const&) = delete; ReactiveAttribute(ReactiveAttribute const&) = delete; void setOn(emscripten::val& node) override { using emscripten::val; node.call<val>("setAttribute", val(name_), val(static_cast <ValueT&>(value_))); parent_ = &node; } void update() override { std::cout << "update reactive\n"; using emscripten::val; if (parent_ != nullptr) parent_->call<val>("setAttribute", val(name_), val(static_cast <ValueT&>(value_))); } ReactiveAttribute* clone() const override { return new ReactiveAttribute(name_, value_); } private: emscripten::val* parent_; std::string name_; SharedObserver<ValueT> value_; }; } #define MAKE_HTML_STRING_ATTRIBUTE(NAME) \ namespace CppDom::Attributes \ { \ struct NAME ## _ { \ Attribute <char const*> operator=(char const* val) \ { \ return {#NAME, std::move(val)}; \ } \ template <typename T> \ ReactiveAttribute <T> operator=(SharedObserver<T> observed) \ { \ return {#NAME, std::move(observed)}; \ } \ } NAME; \ }
26.438017
100
0.530166
5cript
2b422105b1d620f109831fd004da587a0acba6f1
3,431
cpp
C++
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
5
2019-12-20T05:48:26.000Z
2021-10-13T12:32:50.000Z
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
null
null
null
goldfilter/win32/msgpack_server.cpp
orinocoz/dripcap
096f464e8855da9882fbf0ec3294ff6d7e329dc9
[ "MIT" ]
2
2020-03-07T11:40:38.000Z
2022-01-24T22:37:40.000Z
#include "msgpack_server.hpp" #include <msgpack.hpp> typedef long ssize_t; typedef std::basic_string<TCHAR> tstring; inline void operator<<(tstring &t, const std::string &s) { #ifdef _UNICODE if (s.size() > 0) { t.resize(s.size() + 1); size_t length = 0; mbstowcs_s(&length, &t[0], t.size(), s.c_str(), _TRUNCATE); t.resize(length); } else { t.clear(); } #else t = s; #endif } class Reply : public ReplyInterface { public: Reply(HANDLE pipe, uint32_t id); bool write(const char *data, std::size_t length); uint32_t id() const; private: HANDLE hPipe; uint32_t callid; }; Reply::Reply(HANDLE pipe, uint32_t id) : hPipe(pipe), callid(id) { } bool Reply::write(const char *data, std::size_t len) { DWORD length = 0; WriteFile(hPipe, data, len, &length, NULL); return length > 0; } uint32_t Reply::id() const { return callid; } class MsgpackServer::Private { public: Private(); ~Private(); public: tstring path; std::unordered_map<std::string, MsgpackCallback> handlers; HANDLE hPipe; bool active; }; MsgpackServer::Private::Private() : active(false) { } MsgpackServer::Private::~Private() { } MsgpackServer::MsgpackServer(const std::string &path) : d(new Private()) { d->path << path; } MsgpackServer::~MsgpackServer() { delete d; } void MsgpackServer::handle(const std::string &command, const MsgpackCallback &func) { if (func) { d->handlers[command] = func; } else { d->handlers.erase(command); } } bool MsgpackServer::start() { auto spd = spdlog::get("console"); size_t const try_read_size = 256; d->hPipe = CreateNamedPipe(d->path.c_str(), PIPE_ACCESS_DUPLEX, PIPE_TYPE_BYTE, 1, try_read_size, try_read_size, 1000, NULL); if (d->hPipe == INVALID_HANDLE_VALUE) { spd->error("CreateNamedPipe() failed"); return false; } if (!ConnectNamedPipe(d->hPipe, NULL)) { spd->error("ConnectNamedPipe() failed"); return false; } msgpack::unpacker unp; d->active = true; while (d->active) { unp.reserve_buffer(try_read_size); DWORD actual_read_size = 0; if (!ReadFile(d->hPipe, unp.buffer(), try_read_size, &actual_read_size, NULL)) { spd->error("ReadFile() failed"); break; } unp.buffer_consumed(actual_read_size); msgpack::object_handle result; while (unp.next(result)) { msgpack::object obj(result.get()); spd->debug("recv: {}", obj); try { const auto &tuple = obj.as<std::tuple<std::string, uint32_t, msgpack::object>>(); const auto &it = d->handlers.find(std::get<0>(tuple)); if (it != d->handlers.end()) { Reply reply(d->hPipe, std::get<1>(tuple)); (it->second)(std::get<2>(tuple), reply); } } catch (const std::bad_cast &err) { spd->error("msgpack decoding error: {}", err.what()); } if (!d->active) break; } } CloseHandle(d->hPipe); return true; } bool MsgpackServer::stop() { if (d->active) { d->active = false; return true; } return false; }
21.179012
97
0.558146
orinocoz
2b423a2bbdd5dc4457462f2f23e00bd3dc3cf5b4
190
cpp
C++
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
14
2019-04-29T15:17:24.000Z
2020-12-30T12:51:05.000Z
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
null
null
null
flare_skia/src/skr_actor_star.cpp
taehyub/flare_cpp
7731bc0bcf2ce721f103586a48f74aa5c12504e8
[ "MIT" ]
6
2019-04-29T15:17:25.000Z
2021-11-16T03:20:59.000Z
#include "flare_skia/skr_actor_star.hpp" using namespace flare; SkrActorStar::SkrActorStar() : SkrActorBasePath(this) {} void SkrActorStar::invalidateDrawable() { m_IsPathValid = false; }
27.142857
66
0.784211
taehyub
2b47e6487736be4f7af55e23d51fc838ea6e9d7f
4,965
cc
C++
content/renderer/pepper/ppb_tcp_socket_private_impl.cc
MIPS/external-chromium_org
e31b3128a419654fd14003d6117caa8da32697e7
[ "BSD-3-Clause" ]
2
2017-03-21T23:19:25.000Z
2019-02-03T05:32:47.000Z
content/renderer/pepper/ppb_tcp_socket_private_impl.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
null
null
null
content/renderer/pepper/ppb_tcp_socket_private_impl.cc
carlosavignano/android_external_chromium_org
2b5652f7889ccad0fbdb1d52b04bad4c23769547
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
3
2017-07-31T19:09:52.000Z
2019-01-04T18:48:50.000Z
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/renderer/pepper/ppb_tcp_socket_private_impl.h" #include "content/common/pepper_messages.h" #include "content/renderer/pepper/host_globals.h" #include "content/renderer/pepper/pepper_plugin_instance_impl.h" #include "content/renderer/render_thread_impl.h" #include "ppapi/proxy/ppapi_messages.h" #include "ppapi/shared_impl/socket_option_data.h" namespace content { PPB_TCPSocket_Private_Impl::PPB_TCPSocket_Private_Impl( PP_Instance instance, uint32 socket_id, int routing_id) : ppapi::TCPSocketPrivateImpl(instance, socket_id), routing_id_(routing_id) { ChildThread::current()->AddRoute(routing_id, this); } PPB_TCPSocket_Private_Impl::~PPB_TCPSocket_Private_Impl() { ChildThread::current()->RemoveRoute(routing_id_); Disconnect(); } PP_Resource PPB_TCPSocket_Private_Impl::CreateResource(PP_Instance instance) { int routing_id = RenderThreadImpl::current()->GenerateRoutingID(); uint32 socket_id = 0; RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_CreatePrivate( routing_id, 0, &socket_id)); if (!socket_id) return 0; return (new PPB_TCPSocket_Private_Impl( instance, socket_id, routing_id))->GetReference(); } void PPB_TCPSocket_Private_Impl::SendConnect(const std::string& host, uint16_t port) { RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_Connect( routing_id_, socket_id_, host, port)); } void PPB_TCPSocket_Private_Impl::SendConnectWithNetAddress( const PP_NetAddress_Private& addr) { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_ConnectWithNetAddress( routing_id_, socket_id_, addr)); } void PPB_TCPSocket_Private_Impl::SendSSLHandshake( const std::string& server_name, uint16_t server_port, const std::vector<std::vector<char> >& trusted_certs, const std::vector<std::vector<char> >& untrusted_certs) { RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_SSLHandshake( socket_id_, server_name, server_port, trusted_certs, untrusted_certs)); } void PPB_TCPSocket_Private_Impl::SendRead(int32_t bytes_to_read) { RenderThreadImpl::current()->Send(new PpapiHostMsg_PPBTCPSocket_Read( socket_id_, bytes_to_read)); } void PPB_TCPSocket_Private_Impl::SendWrite(const std::string& buffer) { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_Write(socket_id_, buffer)); } void PPB_TCPSocket_Private_Impl::SendDisconnect() { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_Disconnect(socket_id_)); } void PPB_TCPSocket_Private_Impl::SendSetOption( PP_TCPSocket_Option name, const ppapi::SocketOptionData& value) { RenderThreadImpl::current()->Send( new PpapiHostMsg_PPBTCPSocket_SetOption(socket_id_, name, value)); } bool PPB_TCPSocket_Private_Impl::OnMessageReceived( const IPC::Message& message) { bool handled = true; IPC_BEGIN_MESSAGE_MAP(PPB_TCPSocket_Private_Impl, message) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_ConnectACK, OnTCPSocketConnectACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_SSLHandshakeACK, OnTCPSocketSSLHandshakeACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_ReadACK, OnTCPSocketReadACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_WriteACK, OnTCPSocketWriteACK) IPC_MESSAGE_HANDLER(PpapiMsg_PPBTCPSocket_SetOptionACK, OnTCPSocketSetOptionACK) IPC_MESSAGE_UNHANDLED(handled = false) IPC_END_MESSAGE_MAP() return handled; } void PPB_TCPSocket_Private_Impl::OnTCPSocketConnectACK( uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result, const PP_NetAddress_Private& local_addr, const PP_NetAddress_Private& remote_addr) { OnConnectCompleted(result, local_addr, remote_addr); } void PPB_TCPSocket_Private_Impl::OnTCPSocketSSLHandshakeACK( uint32 plugin_dispatcher_id, uint32 socket_id, bool succeeded, const ppapi::PPB_X509Certificate_Fields& certificate_fields) { OnSSLHandshakeCompleted(succeeded, certificate_fields); } void PPB_TCPSocket_Private_Impl::OnTCPSocketReadACK(uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result, const std::string& data) { OnReadCompleted(result, data); } void PPB_TCPSocket_Private_Impl::OnTCPSocketWriteACK( uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result) { OnWriteCompleted(result); } void PPB_TCPSocket_Private_Impl::OnTCPSocketSetOptionACK( uint32 plugin_dispatcher_id, uint32 socket_id, int32_t result) { OnSetOptionCompleted(result); } } // namespace content
34.964789
80
0.749446
MIPS
2b4859e0cf3cce1bcdb6792c1ddba2420c735dfa
11,602
cpp
C++
hi_modules/nodes/FXNodes.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_modules/nodes/FXNodes.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
hi_modules/nodes/FXNodes.cpp
romsom/HISE
73e0e299493ce9236e6fafa7938d3477fcc36a4a
[ "Intel" ]
null
null
null
/* =========================================================================== * * This file is part of HISE. * Copyright 2016 Christoph Hart * * HISE is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HISE is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HISE. If not, see <http://www.gnu.org/licenses/>. * * Commercial licenses for using HISE in an closed source project are * available on request. Please visit the project's website to get more * information about commercial licensing: * * http://www.hise.audio/ * * HISE is based on the JUCE library, * which must be separately licensed for closed source applications: * * http://www.juce.com * * =========================================================================== */ namespace scriptnode { using namespace juce; using namespace hise; namespace fx { template <int V> sampleandhold_impl<V>::sampleandhold_impl() { } template <int V> void sampleandhold_impl<V>::setFactor(double value) { auto factor = jlimit(1, 44100, roundToInt(value)); if (data.isMonophonicOrInsideVoiceRendering()) data.get().factor = factor; else data.forEachVoice([factor](Data& d_) {d_.factor = factor; }); } template <int V> void sampleandhold_impl<V>::createParameters(Array<ParameterData>& d) { { ParameterData p("Counter"); p.range = { 1, 64, 1.0 }; p.db = BIND_MEMBER_FUNCTION_1(sampleandhold_impl::setFactor); d.add(std::move(p)); } } template <int V> void sampleandhold_impl<V>::processSingle(float* numFrames, int numChannels) { auto& v = data.get(); if (v.counter == 0) { FloatVectorOperations::copy(v.currentValues, numFrames, numChannels); v.counter = v.factor; } else { FloatVectorOperations::copy(numFrames, v.currentValues, numChannels); v.counter--; } } template <int V> void sampleandhold_impl<V>::reset() noexcept { if (data.isMonophonicOrInsideVoiceRendering()) data.get().clear(lastChannelAmount); else data.forEachVoice([this](Data& d_) {d_.clear(lastChannelAmount); }); } template <int V> void sampleandhold_impl<V>::process(ProcessData& d) { Data& v = data.get(); if (v.counter > d.size) { for (int i = 0; i < d.numChannels; i++) FloatVectorOperations::fill(d.data[i], v.currentValues[i], d.size); v.counter -= d.size; } else { for (int i = 0; i < d.size; i++) { if (v.counter == 0) { for (int c = 0; c < d.numChannels; c++) { v.currentValues[c] = d.data[c][i]; v.counter = v.factor + 1; } } for (int c = 0; c < d.numChannels; c++) d.data[c][i] = v.currentValues[c]; v.counter--; } } } template <int V> void sampleandhold_impl<V>::prepare(PrepareSpecs ps) { data.prepare(ps); lastChannelAmount = ps.numChannels; } template <int V> void sampleandhold_impl<V>::initialise(NodeBase* ) { } DEFINE_EXTERN_NODE_TEMPIMPL(sampleandhold_impl); template <int V> bitcrush_impl<V>::bitcrush_impl() { bitDepth.setAll(16.0f); } template <int V> void bitcrush_impl<V>::setBitDepth(double newBitDepth) { auto v = jlimit(1.0f, 16.0f, (float)newBitDepth); if (bitDepth.isMonophonicOrInsideVoiceRendering()) bitDepth.get() = v; else bitDepth.setAll(v); } template <int V> void bitcrush_impl<V>::createParameters(Array<ParameterData>& data) { { ParameterData p("Bit Depth"); p.range = { 4.0, 16.0, 0.1 }; p.defaultValue = 16.0; p.db = BIND_MEMBER_FUNCTION_1(bitcrush_impl::setBitDepth); data.add(std::move(p)); } } template <int V> bool bitcrush_impl<V>::handleModulation(double&) noexcept { return false; } template <int V> void bitcrush_impl<V>::reset() noexcept { } // ====================================================================================================== void getBitcrushedValue(float* data, int numSamples, float bitDepth) { const float invStepSize = pow(2.0f, bitDepth); const float stepSize = 1.0f / invStepSize; for (int i = 0; i < numSamples; i++) data[i] = (stepSize * ceil(data[i] * invStepSize) - 0.5f * stepSize); } // ====================================================================================================== template <int V> void bitcrush_impl<V>::process(ProcessData& d) { for (auto ch : d) getBitcrushedValue(ch, d.size, bitDepth.get()); } template <int V> void bitcrush_impl<V>::processSingle(float* numFrames, int numChannels) { getBitcrushedValue(numFrames, numChannels, bitDepth.get()); } template <int V> void bitcrush_impl<V>::prepare(PrepareSpecs ps) { bitDepth.prepare(ps); } template <int V> void bitcrush_impl<V>::initialise(NodeBase* ) { } DEFINE_EXTERN_NODE_TEMPIMPL(bitcrush_impl) template <int V> phase_delay_impl<V>::phase_delay_impl() { } template <int V> void phase_delay_impl<V>::initialise(NodeBase* ) { } template <int V> void phase_delay_impl<V>::prepare(PrepareSpecs ps) { sr = ps.sampleRate * 0.5; delays[0].prepare(ps); delays[1].prepare(ps); } template <int V> void phase_delay_impl<V>::process(ProcessData& d) { int numChannels = jmin(2, d.numChannels); for (int c = 0; c < numChannels; c++) { auto ptr = d.data[c]; auto& dl = delays[c].get(); for (int i = 0; i < d.size; i++) { auto v = *ptr; *ptr++ = dl.getNextSample(v); } } } template <int V> void scriptnode::fx::phase_delay_impl<V>::reset() noexcept { if (delays[0].isMonophonicOrInsideVoiceRendering()) { delays[0].get().reset(); delays[1].get().reset(); } else { auto f = [](AllpassDelay& d) { d.reset(); }; delays[0].forEachVoice(f); delays[1].forEachVoice(f); } } template <int V> void phase_delay_impl<V>::processSingle(float* numFrames, int numChannels) { numChannels = jmin(2, numChannels); for (int i = 0; i < numChannels; i++) numFrames[i] = delays[i].get().getNextSample(numFrames[i]); } template <int V> bool phase_delay_impl<V>::handleModulation(double&) noexcept { return false; } template <int V> void phase_delay_impl<V>::createParameters(Array<ParameterData>& data) { { ParameterData p("Frequency"); p.range = { 20.0, 20000.0, 0.1 }; p.range.setSkewForCentre(1000.0); p.defaultValue = 400.0; p.db = BIND_MEMBER_FUNCTION_1(phase_delay_impl::setFrequency); data.add(std::move(p)); } } template <int V> void phase_delay_impl<V>::setFrequency(double newFrequency) { newFrequency /= sr; auto coefficient = AllpassDelay::getDelayCoefficient((float)newFrequency); if (delays[0].isMonophonicOrInsideVoiceRendering()) { delays[0].get().setDelay(coefficient); delays[1].get().setDelay(coefficient); } else { auto f = [coefficient](AllpassDelay& d) {d.setDelay(coefficient); }; delays[0].forEachVoice(f); delays[1].forEachVoice(f); } } DEFINE_EXTERN_NODE_TEMPIMPL(phase_delay_impl); template <int V> void haas_impl<V>::setPosition(double newValue) { position = newValue; auto d = std::abs(position) * 0.02; if (delayL.isMonophonicOrInsideVoiceRendering()) { if (position == 0.0) { delayL.get().setDelayTimeSamples(0); delayR.get().setDelayTimeSamples(0); } else if (position > 0.0) { delayL.get().setDelayTimeSeconds(d); delayR.get().setDelayTimeSamples(0); } else if (position < 0.0) { delayL.get().setDelayTimeSamples(0); delayR.get().setDelayTimeSeconds(d); } } else { // We don't allow fade times in polyphonic effects because there is no constant flow of signal that // causes issues with the fade time logic... int fadeTime = NumVoices == 1 ? 2048 : 0; auto setZero = [fadeTime](DelayType& t) { t.setFadeTimeSamples(fadeTime); t.setDelayTimeSamples(0); }; auto setSeconds = [fadeTime, d](DelayType& t) { t.setFadeTimeSamples(fadeTime); t.setDelayTimeSeconds(d); }; if (position == 0.0) { delayL.forEachVoice(setZero); delayR.forEachVoice(setZero); } else if (position > 0.0) { delayL.forEachVoice(setSeconds); delayR.forEachVoice(setZero); } else if (position < 0.0) { delayL.forEachVoice(setZero); delayR.forEachVoice(setSeconds); } } } template <int V> bool haas_impl<V>::handleModulation(double&) { return false; } template <int V> void haas_impl<V>::process(ProcessData& d) { if (d.numChannels == 2) { delayL.get().processBlock(d.data[0], d.size); delayR.get().processBlock(d.data[1], d.size); } } template <int V> void haas_impl<V>::processSingle(float* data, int numChannels) { if (numChannels == 2) { data[0] = delayL.get().getDelayedValue(data[0]); data[1] = delayR.get().getDelayedValue(data[1]); } } template <int V> void haas_impl<V>::reset() { if (delayL.isMonophonicOrInsideVoiceRendering()) { jassert(delayR.isMonophonicOrInsideVoiceRendering()); delayL.get().setFadeTimeSamples(0); delayR.get().setFadeTimeSamples(0); delayL.get().clear(); delayR.get().clear(); } else { auto f = [](DelayType& d) {d.clear(); }; delayL.forEachVoice(f); delayR.forEachVoice(f); } } template <int V> void haas_impl<V>::prepare(PrepareSpecs ps) { delayL.prepare(ps); delayR.prepare(ps); auto sr = ps.sampleRate; auto f = [sr](DelayType& d) { d.prepareToPlay(sr); d.setFadeTimeSamples(0); }; delayL.forEachVoice(f); delayR.forEachVoice(f); setPosition(position); } template <int V> void haas_impl<V>::createParameters(Array<ParameterData>& data) { { ParameterData p("Position"); p.range = { -1.0, 1.0, 0.1 }; p.defaultValue = 0.0; p.db = BIND_MEMBER_FUNCTION_1(haas_impl::setPosition); data.add(std::move(p)); } } DEFINE_EXTERN_NODE_TEMPIMPL(haas_impl); reverb::reverb() { auto p = r.getParameters(); p.dryLevel = 0.0f; r.setParameters(p); } void reverb::initialise(NodeBase* ) { } void reverb::prepare(PrepareSpecs ps) { r.setSampleRate(ps.sampleRate); } void reverb::process(ProcessData& d) { if (d.numChannels == 2) r.processStereo(d.data[0], d.data[1], d.size); else if (d.numChannels == 1) r.processMono(d.data[0], d.size); } void reverb::reset() noexcept { r.reset(); } void reverb::processSingle(float* numFrames, int numChannels) { if (numChannels == 2) r.processStereo(numFrames, numFrames + 1, 1); else if (numChannels == 1) r.processMono(numFrames, 1); } bool reverb::handleModulation(double&) noexcept { return false; } void reverb::createParameters(Array<ParameterData>& data) { { ParameterData p("Size"); p.range = { 0.0, 1.0, 0.01 }; p.defaultValue = 0.5f; p.db = BIND_MEMBER_FUNCTION_1(reverb::setSize); data.add(std::move(p)); } { ParameterData p("Damping"); p.range = { 0.0, 1.0, 0.01 }; p.defaultValue = 0.5f; p.db = BIND_MEMBER_FUNCTION_1(reverb::setDamping); data.add(std::move(p)); } { ParameterData p("Width"); p.range = { 0.0, 1.0, 0.01 }; p.defaultValue = 0.5f; p.db = BIND_MEMBER_FUNCTION_1(reverb::setWidth); data.add(std::move(p)); } } void reverb::setDamping(double newDamping) { auto p = r.getParameters(); p.damping = jlimit(0.0f, 1.0f, (float)newDamping); r.setParameters(p); } void reverb::setWidth(double width) { auto p = r.getParameters(); p.damping = jlimit(0.0f, 1.0f, (float)width); r.setParameters(p); } void reverb::setSize(double size) { auto p = r.getParameters(); p.roomSize = jlimit(0.0f, 1.0f, (float)size); r.setParameters(p); } } }
20.390158
110
0.658593
romsom
2b4df60058134010d44cb4d759db34fe24b65a3b
7,330
cpp
C++
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
3
2021-12-16T13:57:28.000Z
2022-03-26T07:50:08.000Z
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
null
null
null
src/gameworld/gameworld/other/fb/rolestoryfb.cpp
mage-game/metagame-xm-server
193b67389262803fe0eae742800b1e878b5b3087
[ "MIT" ]
1
2022-03-26T07:50:11.000Z
2022-03-26T07:50:11.000Z
#include "rolestoryfb.hpp" #include "obj/character/role.h" #include "config/logicconfigmanager.hpp" #include "other/vip/vipconfig.hpp" #include "other/fb/storyfbconfig.hpp" #include "servercommon/errornum.h" #include "protocal/msgfb.h" #include "other/event/eventhandler.hpp" #include "monster/monsterpool.h" #include "gameworld/world.h" #include "servercommon/string/gameworldstr.h" #include "scene/scene.h" #include "item/itempool.h" #include "item/knapsack.h" #include "other/route/mailroute.hpp" #include "global/worldstatus/worldstatus.hpp" #include "global/usercache/usercache.hpp" #include "other/vip/vip.hpp" #include "other/daycounter/daycounter.hpp" RoleStoryFB::RoleStoryFB() : m_role(NULL) { } RoleStoryFB::~RoleStoryFB() { } void RoleStoryFB::Init(Role *role, const StoryFBParam &param) { m_role = role; m_param = param; } void RoleStoryFB::GetInitParam(StoryFBParam *param) { *param = m_param; } void RoleStoryFB::OnDayChange(unsigned int old_dayid, unsigned int now_dayid) { for (int i = 0; i < FB_STORY_MAX_COUNT; i++) { m_param.fb_list[i].today_times = 0; } this->SendInfo(); } bool RoleStoryFB::CanEnter(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return false; } if (fb_index > 0 && !this->IsPassLevel(fb_index - 1) && 0 == m_param.fb_list[fb_index - 1].today_times) { m_role->NoticeNum(errornum::EN_PRVE_FB_NOT_COMPLETED); return false; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return false; } if (m_role->GetLevel() < level_cfg->role_level) { m_role->NoticeNum(errornum::EN_STORY_FB_FUN_OPEN_LEVEL_LIMIT); return false; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times) { m_role->NoticeNum(errornum::EN_STORY_FB_TIMES_LIMIT); return false; } return true; } void RoleStoryFB::OnEnterFB(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } m_param.curr_fb_index = fb_index; m_param.fb_list[fb_index].today_times++; m_role->GetDayCounter()->DayCountSet(DayCounter::DAYCOUNT_ID_FB_STORY, 1); this->SendInfo(); } void RoleStoryFB::AutoFBReqOne(int fb_index) { Scene *scene = m_role->GetScene(); if (NULL == scene) { return; } if (Scene::SCENE_TYPE_STORY_FB == scene->GetSceneType()) { m_role->NoticeNum(errornum::EN_FB_OPERATE_LIMIT); return; } if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return; } if (0 == m_param.fb_list[fb_index].is_pass) { m_role->NoticeNum(errornum::EN_STORY_FB_NO_PASS); return; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times) { const int vip_buy_times = LOGIC_CONFIG->GetVipConfig().GetAuthParam(m_role->GetVip()->GetVipLevel(), VAT_FB_STROY_COUNT); if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times + vip_buy_times) { m_role->NoticeNum(errornum::EN_BUY_STROY_FB_TIME_LIMIT); return; } if (level_cfg->reset_gold > 0 && !m_role->GetKnapsack()->GetMoney()->AllGoldMoreThan(level_cfg->reset_gold)) { m_role->NoticeNum(errornum::EN_GOLD_NOT_ENOUGH); return; } } ItemConfigData reward_item_list[MonsterInitParam::MAX_DROP_ITEM_COUNT]; int index_count = MonsterInitParam::MAX_DROP_ITEM_COUNT; long long reward_exp = 0; for(int i = 0; i < level_cfg->monster_count && i < StoryFBLevelCfg::MONSTER_COUNT_MAX; i++) { if (0 != level_cfg->monster_id_list[i]) { MONSTERPOOL->GetMonsterDrop(level_cfg->monster_id_list[i], reward_item_list, &index_count, &reward_exp, NULL, NULL); } } short item_count = 0; for (int j = 0; j < index_count && j < MonsterInitParam::MAX_DROP_ITEM_COUNT; j++) { if (0 == reward_item_list[j].item_id) { break; } item_count++; } if (m_param.fb_list[fb_index].today_times >= level_cfg->free_times && !m_role->GetKnapsack()->GetMoney()->UseAllGold(level_cfg->reset_gold, "StoryFBAuto")) { m_role->NoticeNum(errornum::EN_GOLD_NOT_ENOUGH); return; } m_param.fb_list[fb_index].today_times++; EventHandler::Instance().OnAutoFbStory(m_role); m_role->AddExp(reward_exp, "StoryFBAuto", Role::EXP_ADD_REASON_DEFAULT); if (item_count > 0) { m_role->GetKnapsack()->PutList(item_count, reward_item_list, PUT_REASON_STORY_FB); } this->SendInfo(); } void RoleStoryFB::AutoFBReqAll() { Scene *scene = m_role->GetScene(); if (NULL == scene) { return; } if (Scene::SCENE_TYPE_STORY_FB == scene->GetSceneType()) { m_role->NoticeNum(errornum::EN_FB_OPERATE_LIMIT); return; } bool is_auto_succ = false; for(int i = 0; i < FB_STORY_MAX_COUNT; i ++) { const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(i); if (NULL == level_cfg) { break; } if (0 == m_param.fb_list[i].is_pass) { continue; } if (m_param.fb_list[i].today_times >= level_cfg->free_times) { continue; } ItemConfigData reward_item_list[MonsterInitParam::MAX_DROP_ITEM_COUNT]; int index_count = MonsterInitParam::MAX_DROP_ITEM_COUNT; long long reward_exp = 0; for(int j = 0; j < level_cfg->monster_count && j < StoryFBLevelCfg::MONSTER_COUNT_MAX; j++) { if (0 != level_cfg->monster_id_list[j]) { MONSTERPOOL->GetMonsterDrop(level_cfg->monster_id_list[j], reward_item_list, &index_count, &reward_exp, NULL, NULL); } } short item_count = 0; for(int k = 0; k < index_count && k < MonsterInitParam::MAX_DROP_ITEM_COUNT; k++) { if (0 == reward_item_list[i].item_id) { break; } item_count++; } is_auto_succ = true; m_param.fb_list[i].today_times++; m_role->AddExp(reward_exp, "StoryFBAuto", Role::EXP_ADD_REASON_DEFAULT); if (index_count > 0) { m_role->GetKnapsack()->PutList(item_count, reward_item_list , PUT_REASON_STORY_FB); } EventHandler::Instance().OnAutoFbStory(m_role); } if (is_auto_succ) { m_role->GetDayCounter()->DayCountSet(DayCounter::DAYCOUNT_ID_FB_STORY, 1); this->SendInfo(); } else { m_role->NoticeNum(errornum::EN_STORY_FB_NOT_LEVEL); } } void RoleStoryFB::SendInfo() { static Protocol::SCStoryFBInfo cmd; for (int i = 0; i < FB_STORY_MAX_COUNT; i++) { cmd.info_list[i].is_pass = m_param.fb_list[i].is_pass; cmd.info_list[i].today_times = m_param.fb_list[i].today_times; } EngineAdapter::Instance().NetSend(m_role->GetNetId(), (const char*)&cmd, sizeof(cmd)); } void RoleStoryFB::OnPassLevel(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return; } const StoryFBLevelCfg::ConfigItem *level_cfg = LOGIC_CONFIG->GetStoryFBConfig().GetLevelCfg(fb_index); if (NULL == level_cfg) { return; } if (0 == m_param.fb_list[fb_index].is_pass) { m_param.fb_list[fb_index].is_pass = 1; m_role->GetKnapsack()->PutListOrMail(level_cfg->first_reward_list, PUT_REASON_STORY_FB); } else { m_role->GetKnapsack()->PutListOrMail(level_cfg->normal_reward_list, PUT_REASON_STORY_FB); } m_role->AddExp(level_cfg->reward_exp, "StoryFBPass", Role::EXP_ADD_REASON_DEFAULT); this->SendInfo(); } bool RoleStoryFB::IsPassLevel(int fb_index) { if (fb_index < 0 || fb_index >= FB_STORY_MAX_COUNT) { return false; } return 0 != m_param.fb_list[fb_index].is_pass; }
22.978056
156
0.715825
mage-game
2b4e6076e6ed4c30ab1de9d92ebdfbe43d6fc701
4,120
cpp
C++
src/parsing.cpp
MicroTransactionsMatterToo/midiparser-cpp
1e95cc445dc4a0411c2ba0bbfd1814dffa368c47
[ "MIT" ]
null
null
null
src/parsing.cpp
MicroTransactionsMatterToo/midiparser-cpp
1e95cc445dc4a0411c2ba0bbfd1814dffa368c47
[ "MIT" ]
null
null
null
src/parsing.cpp
MicroTransactionsMatterToo/midiparser-cpp
1e95cc445dc4a0411c2ba0bbfd1814dffa368c47
[ "MIT" ]
null
null
null
// Copyright Ennis Massey 18/12/16 // // Created by Ennis Massey on 18/12/16. // #include "parsing.h" uint32_t midiparser::ParseUint32(std::ifstream &input_file) { // If the file isn't open, return 0 if (!input_file.is_open()) { return (uint32_t) 0; } // Create buffer char buffer[4]; // Read from stream input_file.read(buffer, 4); // If we couldn't read 4 bytes, we just return 0 if (input_file.eof()) { return (uint32_t) 0; } uint32_t value = (uint32_t) 0x00; value |= (uint32_t) buffer[3] << 0; value |= (uint32_t) buffer[2] << 8; value |= (uint32_t) buffer[1] << 16; value |= (uint32_t) buffer[0] << 24; return value; } uint32_t midiparser::ParseUint24(std::ifstream &input_file) { // If the file isn't open, return 0 if (!input_file.is_open()) { return (uint32_t) 0; } // Create buffer char buffer[3]; // Read from stream input_file.read(buffer, 3); // If we couldn't read 3 bytes, return 0 if (input_file.eof()) { return (uint32_t) 0; } uint32_t value = 0x00; value |= (uint32_t) buffer[2] << 0; value |= (uint32_t) buffer[1] << 8; value |= (uint32_t) buffer[0] << 16; return value; } uint16_t midiparser::ParseUint16(std::ifstream &input_file) { // If the file isn't open, return 0 if (!input_file.is_open()) { return (uint16_t) 0; } // Create buffer char buffer[2]; // Read from stream input_file.read(buffer, 2); if (input_file.eof()) { return (uint16_t) 0; } uint16_t value = 0x00; value |= (uint16_t) buffer[1] << 0; value |= (uint16_t) buffer[0] << 8; return value; } uint8_t midiparser::ParseUint7(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint8_t) 0; } char buffer[1]; input_file.read(buffer, 1); if (input_file.eof()) { return (uint8_t) 0; } uint8_t value = 0x00; value = (uint8_t) (buffer[0] & 0x7F); return value; } std::tuple<uint8_t, uint8_t> midiparser::ParseTwoUint7(std::ifstream &input_file) { if (!input_file.is_open()) { return std::make_tuple((uint8_t) 0, (uint8_t) 0); } char buffer[2]; input_file.read(buffer, 2); if (input_file.eof()) { return std::make_tuple((uint8_t) 0, (uint8_t) 0); } uint8_t value_one = (uint8_t) (buffer[0] & 0x7F); uint8_t value_two = (uint8_t) (buffer[1] & 0x7F); std::tuple<uint8_t, uint8_t> value = std::make_tuple(value_one, value_two); return value; } uint8_t midiparser::ParseUint8(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint8_t) 0; } char buffer[1]; input_file.read(buffer, 1); if (input_file.eof()) { return (uint8_t) 0; } return (uint8_t) buffer[0]; } int8_t midiparser::ParseInt8(std::ifstream &input_file) { if (!input_file.is_open()) { return (int8_t) 0; } char buffer[1]; input_file.read(buffer, 1); if (input_file.eof()) { return (int8_t) 0; } return (int8_t) buffer[0]; } uint16_t midiparser::ParsePitchWheelValue(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint16_t) 0; } char buffer[2]; input_file.read(buffer, 2); if (input_file.eof()) { return (uint16_t) 0; } uint16_t value = 0x00; value = (uint16_t) (buffer[1] & 0x7F); value <<= 7; value |= (uint16_t) (buffer[0] & 0x7F); return value; } uint32_t midiparser::ParseVariableLengthValue(std::ifstream &input_file) { if (!input_file.is_open()) { return (uint32_t) 0; } char buffer[1]; bool did_return = false; uint32_t value = 0x00; bool first = true; while (first || (((buffer[0] & 0x80) == 0x80) && (did_return))) { value <<= 7; input_file.read(buffer, 1); if (input_file.eof()) { did_return = false; break; } did_return = true; value |= (uint32_t) buffer[0] & 0x7F; first = false; } return value; }
24.819277
83
0.583252
MicroTransactionsMatterToo
2b531c733edd0986429110aec5a426add9e73335
354
hpp
C++
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
292
2020-03-19T22:38:52.000Z
2022-03-05T22:49:34.000Z
ntd/vector.hpp
aconstlink/natus
d2123c6e1798bd0771b8a1a05721c68392afc92f
[ "MIT" ]
null
null
null
#pragma once #include <natus/memory/allocator.hpp> #include <vector> namespace natus { namespace ntd { //template< typename T > //using vector = ::std::vector< T, natus::memory::allocator<T> > ; // for now, we use the default allocator template< typename T > using vector = ::std::vector< T > ; } }
19.666667
74
0.581921
aconstlink
2b5441573aab4a4ad911786a7ae38e80d31a1a94
2,276
cpp
C++
src/camera.cpp
LesleyLai/GLGrassRenderer
34c9a4822f1908e35620f10298839c96ab830958
[ "Apache-2.0" ]
57
2019-02-24T00:54:07.000Z
2022-03-09T22:08:59.000Z
src/camera.cpp
LesleyLai/GLGrassRenderer
34c9a4822f1908e35620f10298839c96ab830958
[ "Apache-2.0" ]
null
null
null
src/camera.cpp
LesleyLai/GLGrassRenderer
34c9a4822f1908e35620f10298839c96ab830958
[ "Apache-2.0" ]
11
2019-08-30T13:04:10.000Z
2021-12-25T04:03:49.000Z
#include "camera.hpp" Camera::Camera(glm::vec3 position, glm::vec3 up, float yaw, float pitch) : front_(glm::vec3(0.0f, 0.0f, -1.0f)), speed_(initial_speed), mouse_sensitivity_(init_sensitivity), zoom_(init_zoom) { position_ = position; world_up_ = up; yam_ = yaw; pitch_ = pitch; update_camera_vectors(); } void Camera::move(Camera::Movement direction, std::chrono::duration<float, std::milli> delta_time) { float dx = speed_ * delta_time.count() / 1000; switch (direction) { case Camera::Movement::forward: position_ += front_ * dx; break; case Camera::Movement::backward: position_ -= front_ * dx; break; case Camera::Movement::left: position_ -= right_ * dx; break; case Camera::Movement::right: position_ += right_ * dx; break; } } void Camera::mouse_movement(float xoffset, float yoffset, GLboolean constrainPitch) { xoffset *= mouse_sensitivity_; yoffset *= mouse_sensitivity_; yam_ += xoffset; pitch_ += yoffset; // Make sure that when pitch is out of bounds, screen doesn't get flipped if (constrainPitch) { if (pitch_ > 89.0f) { pitch_ = 89.0f; } if (pitch_ < -89.0f) { pitch_ = -89.0f; } } // Update Front, Right and Up Vectors using the updated Euler angles update_camera_vectors(); } void Camera::mouse_scroll(float yoffset) { if (zoom_ >= 1.0f && zoom_ <= 45.0f) { zoom_ -= yoffset; } if (zoom_ <= 1.0f) { zoom_ = 1.0f; } if (zoom_ >= 45.0f) { zoom_ = 45.0f; } } void Camera::update_camera_vectors() { // Calculate the new Front vector glm::vec3 front; front.x = std::cos(glm::radians(yam_)) * std::cos(glm::radians(pitch_)); front.y = std::sin(glm::radians(pitch_)); front.z = std::sin(glm::radians(yam_)) * std::cos(glm::radians(pitch_)); front_ = glm::normalize(front); // Also re-calculate the Right and Up vector right_ = glm::normalize(glm::cross( front_, world_up_)); // Normalize the vectors, because their length gets // closer to 0 the more you look up or down which // results in slower movement. up_ = glm::normalize(glm::cross(right_, front_)); }
26.776471
79
0.614675
LesleyLai
2b5c0973d77dc6cbcd0829a6c30084dc53a6eb39
112
cc
C++
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
17
2016-11-27T13:13:40.000Z
2021-09-07T06:42:25.000Z
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
22
2017-01-18T06:10:18.000Z
2019-05-15T03:49:19.000Z
src/messages/reply.cc
zzunny97/Graduate-Velox
d820e7c8cee52f22d7cd9027623bd82ca59733ca
[ "Apache-2.0" ]
5
2017-07-24T15:19:32.000Z
2022-02-19T09:11:01.000Z
#include "reply.hh" using namespace eclipse::messages; std::string Reply::get_type() const { return "Reply"; }
22.4
55
0.723214
zzunny97
2b605c0a5c1cfdd09444dd5187f3d3a7193f9301
1,994
hpp
C++
include/Zelta/Core/RenderLayer.hpp
RafaelGC/ese
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
1
2018-01-28T21:35:14.000Z
2018-01-28T21:35:14.000Z
include/Zelta/Core/RenderLayer.hpp
RafaelGC/ese
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
1
2018-01-23T02:03:45.000Z
2018-01-23T02:03:45.000Z
include/Zelta/Core/RenderLayer.hpp
rafaelgc/ESE
95868d2f7221334271d4a74ef38b2ed3478a8b91
[ "MIT" ]
null
null
null
#ifndef ZELTALIB_LAYER_HPP #define ZELTALIB_LAYER_HPP #include <vector> #include <SFML/Graphics/Drawable.hpp> // Base class: sf::Drawable #include <SFML/Graphics/RenderTarget.hpp> namespace zt { /** * @brief Container for drawable objects. * This class allows you to group sf::Drawable elements such as sf::Sprite. * The container keeps pointers to the objects, so your drawable objects * should be kept alive while using the render layer. * */ class RenderLayer : public sf::Drawable { protected: /** * @brief If it's false the contained objects won't be drawn. * */ bool visible; /** * @brief Vector que contiene un puntero a los dibujables de esta capa. * */ std::vector<sf::Drawable*>drawableItems; public: /** * @brief Constructs an empty layer. * */ RenderLayer(bool visible = true); virtual ~RenderLayer(); /** * @brief Draws all contained objects if the layer is visible. * */ virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const; /** * @brief Adds a drawable. * */ void addDrawable(sf::Drawable &item); /** * @brief Removes a drawable if it exists. * @param item Drawable you cant to remove. * @return True if it was removed. */ bool removeDrawable(sf::Drawable & item); /** * @brief Sets the visibility. * */ void setVisible(bool visible); bool isVisible() const; int getZ() const; void setZ(int z); unsigned int count() const; bool isEmpty() const; /** * Compares the depth of the layer. * @param other * @return */ bool operator<(zt::RenderLayer & other) const; }; } #endif // LAYER_HPP
26.236842
83
0.549147
RafaelGC
2b6481839159df93be542ffbc8d7757e642639bd
1,127
cpp
C++
src/gpu_monitor_hip.cpp
enp1s0/gpu_monitor
3d1ebb39803861e57670d08ead883d1208d6e35b
[ "MIT" ]
null
null
null
src/gpu_monitor_hip.cpp
enp1s0/gpu_monitor
3d1ebb39803861e57670d08ead883d1208d6e35b
[ "MIT" ]
null
null
null
src/gpu_monitor_hip.cpp
enp1s0/gpu_monitor
3d1ebb39803861e57670d08ead883d1208d6e35b
[ "MIT" ]
null
null
null
#include <hiptf/device.hpp> #include <hiptf/rsmi.hpp> #include "gpu_monitor_hip.hpp" void mtk::gpu_monitor::gpu_monitor_hip::init() { HIPTF_CHECK_ERROR(rsmi_init(0)); } void mtk::gpu_monitor::gpu_monitor_hip::shutdown() { } std::size_t mtk::gpu_monitor::gpu_monitor_hip::get_num_devices() const { return hiptf::device::get_num_devices(); } std::size_t mtk::gpu_monitor::gpu_monitor_hip::get_current_device() const { return hiptf::device::get_device_id(); } double mtk::gpu_monitor::gpu_monitor_hip::get_current_temperature(const unsigned gpu_id) const { int64_t temperature; HIPTF_CHECK_ERROR(rsmi_dev_temp_metric_get(gpu_id, 0, RSMI_TEMP_CURRENT, &temperature)); return temperature / 1000.0; } double mtk::gpu_monitor::gpu_monitor_hip::get_current_power(const unsigned gpu_id) const { uint64_t power; HIPTF_CHECK_ERROR(rsmi_dev_power_cap_get(gpu_id, 0, &power)); return power / 1000000.0; } std::size_t mtk::gpu_monitor::gpu_monitor_hip::get_current_used_memory(const unsigned gpu_id) const { uint64_t used; HIPTF_CHECK_ERROR(rsmi_dev_memory_usage_get(gpu_id, RSMI_MEM_TYPE_VRAM, &used)); return used; }
28.175
101
0.785271
enp1s0
2b6a60525f50008936b2c335749c76337bbd685d
935
cpp
C++
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
106
2021-07-04T01:10:18.000Z
2022-03-21T00:58:27.000Z
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
119
2021-07-10T14:26:24.000Z
2022-03-22T22:48:18.000Z
test/example/executor/strand.cpp
YACLib/YACLib
fa5e13cdcc1f719e6b6363ba25a4791315e66916
[ "MIT" ]
7
2021-07-23T11:23:04.000Z
2021-11-13T20:22:56.000Z
/** * \example strand.cpp * Simple \ref Strand examples */ #include <yaclib/executor/strand.hpp> #include <yaclib/executor/thread_pool.hpp> #include <iostream> #include <gtest/gtest.h> using namespace yaclib; TEST(Example, Strand) { std::cout << "Strand" << std::endl; auto tp = MakeThreadPool(4); auto strand = MakeStrand(tp); size_t counter = 0; static constexpr size_t kThreads = 5; static constexpr size_t kIncrementsPerThread = 12345; std::vector<std::thread> threads; for (size_t i = 0; i < kThreads; ++i) { threads.emplace_back([&]() { for (size_t j = 0; j < kIncrementsPerThread; ++j) { strand->Execute([&] { ++counter; }); } }); } for (auto& t : threads) { t.join(); } tp->Stop(); tp->Wait(); std::cout << "Counter value = " << counter << ", expected " << kThreads * kIncrementsPerThread << std::endl; std::cout << std::endl; }
18.7
110
0.59893
YACLib
2b6d76ef984531a8a4aa2be05d6e7ede8a9f96a9
12,142
cpp
C++
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
28
2015-05-22T16:03:29.000Z
2022-01-15T12:12:46.000Z
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
15
2015-10-21T11:19:09.000Z
2020-07-15T05:01:12.000Z
src/c++/lib/model/IntervalGenerator.cpp
sequencing/EAGLE
6da0438c1f7620ea74dec1f34baf20bb0b14b110
[ "BSD-3-Clause" ]
8
2017-01-21T00:31:17.000Z
2018-08-12T13:28:57.000Z
/** ** Copyright (c) 2014 Illumina, Inc. ** ** This file is part of Illumina's Enhanced Artificial Genome Engine (EAGLE), ** covered by the "BSD 2-Clause License" (see accompanying LICENSE file) ** ** \description Generation of random/uniform intervals with precise boundaries ** Based on: ** [1] Jon Louis Bentley and James B. Saxe. 1980. Generating Sorted Lists of Random Numbers. ** ACM Trans. Math. Softw. 6, 3 (September 1980), 359-364. ** DOI=10.1145/355900.355907 http://doi.acm.org/10.1145/355900.355907 ** ** \author Lilian Janin **/ #include <numeric> #include <boost/foreach.hpp> #include <boost/format.hpp> #include "common/Exceptions.hh" #include "model/IntervalGenerator.hh" using namespace std; namespace eagle { namespace model { // Class RandomSequenceGenerator unsigned long RandomSequenceGenerator::getNext() { return static_cast<unsigned long>( floor(getNextAsDouble()) ); } bool RandomSequenceGenerator::hasFinished() { return (remainingSampleCount_ <= 0); } double RandomSequenceGenerator::getNextAsDouble() { if (remainingSampleCount_ <= 0) { BOOST_THROW_EXCEPTION( eagle::common::EagleException( 0, "RandomSequenceGenerator: all samples have already been generated") ); } double rand0to1 = (1.0+rand())/(1.0+RAND_MAX); curMax_ *= exp(log(rand0to1)/remainingSampleCount_); remainingSampleCount_--; return (1-curMax_)*intervalSize_; } // Class RandomIntervalGenerator pair< unsigned long, unsigned int > RandomIntervalGenerator::getNext( const signed long testValue ) { unsigned long intervalNum = (testValue<0)?randomSeq_.getNext():testValue; // Convert intervalNum to interval while ( intervalNum > currentContigIntervalInfo_->lastInterval || currentContigIntervalInfo_->lastInterval == 0xFFFFFFFFFFFFFFFF ) { ++currentContigIntervalInfo_; if (verbose_) { clog << "Generating fragments for chromosome starting at global pos " << currentContigIntervalInfo_->firstIntervalGlobalPos << endl; } } assert( intervalNum >= currentContigIntervalInfo_->firstInterval ); pair< unsigned long, unsigned int > p; if ( intervalNum < currentContigIntervalInfo_->firstSmallerInterval ) { unsigned long localIntervalNum = intervalNum - currentContigIntervalInfo_->firstInterval; p.first = currentContigIntervalInfo_->firstIntervalGlobalPos + localIntervalNum / intervalsPerNormalPosition_; p.second = minFragmentLength_ + localIntervalNum % intervalsPerNormalPosition_; } else { // static unsigned long lastSmallerIntervalNum = -1; // if ( currentContigIntervalInfo_->firstSmallerInterval != lastSmallerIntervalNum ) { unsigned long localIntervalNum = intervalNum - currentContigIntervalInfo_->firstSmallerInterval; unsigned int intervalCountForThisPos = maxFragmentLength_ - minFragmentLength_; unsigned long currentPos = currentContigIntervalInfo_->firstSmallerIntervalGlobalPos; while (intervalCountForThisPos > 0) { if ( localIntervalNum < intervalCountForThisPos ) { p.first = currentPos; p.second = localIntervalNum + minFragmentLength_; break; } localIntervalNum -= intervalCountForThisPos; --intervalCountForThisPos; ++currentPos; } assert( intervalCountForThisPos>0 && "should never happen" ); } } return p; } unsigned long RandomIntervalGenerator::getIntervalCount() { unsigned long intervalCount = 0; unsigned long globalPos = 0; BOOST_FOREACH( const unsigned long l, contigLengths_ ) { struct ContigIntervalInfo intervalInfo; intervalInfo.firstInterval = intervalCount; intervalInfo.firstIntervalGlobalPos = globalPos; if ( l+1 >= maxFragmentLength_ ) { unsigned long normalPositionCount = l - maxFragmentLength_ + 1; intervalCount += intervalsPerNormalPosition_ * normalPositionCount; intervalInfo.firstSmallerInterval = intervalCount; intervalCount += intervalsPerNormalPosition_ * (intervalsPerNormalPosition_-1) / 2; intervalInfo.firstSmallerIntervalGlobalPos = globalPos + normalPositionCount; } else { intervalInfo.firstSmallerIntervalGlobalPos = 0; EAGLE_WARNING( "Chromosome shorter than insert length" ); } intervalInfo.lastInterval = intervalCount - 1; if (verbose_) { clog << "Chromosome at global pos " << globalPos << " has " << (intervalInfo.lastInterval-intervalInfo.firstInterval+1) << " intervals" << endl; } globalPos += l; contigIntervalInfo_.push_back( intervalInfo ); } return intervalCount; } // Class RandomIntervalGeneratorUsingIntervalLengthDistribution pair< unsigned long, unsigned int > RandomIntervalGeneratorUsingIntervalLengthDistribution::getNext( const signed long testValue ) { assert( testValue < 0 ); // positive test case not implemented if (randomSeq_.hasFinished()) { return make_pair(0,0); } double randomPos = randomSeq_.getNextAsDouble(); // randomPos => currentPos double probaOfCurrentPos = getIntervalsProbaAtPos( currentPos_ ); while (randomPos >= accumulatedProbasUntilCurrentPos_ + probaOfCurrentPos) { accumulatedProbasUntilCurrentPos_ += probaOfCurrentPos; ++currentPos_; probaOfCurrentPos = getIntervalsProbaAtPos( currentPos_ ); } // randomPos(-currentPos) => fragmentLength unsigned int fragmentLength = fragmentLengthDist_.min(); double probaDiff = randomPos - accumulatedProbasUntilCurrentPos_; while (probaDiff > fragmentLengthDist_[fragmentLength]) { probaDiff -= fragmentLengthDist_[fragmentLength++]; } return make_pair( currentPos_, fragmentLength ); } double RandomIntervalGeneratorUsingIntervalLengthDistribution::getIntervalsProbaAtPos( unsigned long globalPos ) { assert( contigLengths_.size() == 1 ); // We restrict the current implementation to one contig at a time const unsigned long contigLength = contigLengths_[0]; if (globalPos + fragmentLengthDist_.max() < contigLength) { return 1.0; } else { unsigned int distanceToContigEnd = contigLength - globalPos; unsigned int index = fragmentLengthDist_.max() - distanceToContigEnd; if (index >= probas_.size()) { // We expect to build the index 1 entry at a time( index == probas_.size() most of the time), but we need to skip some initial entries for chromosomes smaller than the max template length if (index > probas_.size()) { probas_.resize( index, 0 ); } double p = 0; for (unsigned int i=fragmentLengthDist_.min(); i<=distanceToContigEnd; ++i) { p += fragmentLengthDist_[i]; } probas_.push_back( p ); // clog << (boost::format("Adding proba %f at index %d (for globalPos %d)") % p % index % globalPos).str() << endl; } return probas_[index]; } } double RandomIntervalGeneratorUsingIntervalLengthDistribution::getTotalIntervalsProba() { assert( contigLengths_.size() == 1 ); // We restrict the current implementation to one contig at a time const unsigned long contigLength = contigLengths_[0]; double intervalCount = 0; for (unsigned long globalPos=0; globalPos<contigLength; ++globalPos) { intervalCount += getIntervalsProbaAtPos( globalPos ); } if (verbose_) { EAGLE_DEBUG( 0, "Contig's total intervals probability: " << intervalCount ); } return intervalCount; } // Class UniformIntervalGenerator UniformIntervalGenerator::UniformIntervalGenerator( const vector<unsigned long>& contigLengths, const unsigned int medianFragmentLength, const double step, unsigned long& readCount, bool verbose) : IntervalGenerator( contigLengths, readCount, medianFragmentLength, medianFragmentLength, medianFragmentLength, verbose) , step_( step ) { unsigned long intervalCount = 0; unsigned long globalPos = 0; BOOST_FOREACH( const unsigned long l, contigLengths_ ) { struct ContigIntervalInfo intervalInfo; intervalInfo.firstGlobalPos = globalPos; unsigned long contigValidPosCount = l - medianFragmentLength + 1; intervalCount += contigValidPosCount; intervalInfo.lastGlobalPos = globalPos + contigValidPosCount - 1; globalPos += l; contigIntervalInfo_.push_back( intervalInfo ); } currentContigIntervalInfo_ = contigIntervalInfo_.begin(); currentGlobalPos_ = 0 - step_; unsigned long newReadCount = static_cast<unsigned long>( (double)intervalCount / step_ ); if (verbose_) { clog << (boost::format("Uniform coverage attempts to achieve the specified coverage depth for all the chromosome positions, which is impossible to achieve at the chromosome extremities => the average coverage depth will be lower than specified. Changing read count from %d to %d, for a step of %d") % readCount % newReadCount % step_).str() << endl; } readCount = newReadCount; } pair< unsigned long, unsigned int > UniformIntervalGenerator::getNext( const signed long testValue ) { currentGlobalPos_ += step_; // Convert intervalNum to interval while ( floor(currentGlobalPos_) > currentContigIntervalInfo_->lastGlobalPos ) { if ( currentContigIntervalInfo_+1 != contigIntervalInfo_.end() ) { ++currentContigIntervalInfo_; currentGlobalPos_ = currentContigIntervalInfo_->firstGlobalPos; if (verbose_) { clog << "Generating fragments for chromosome starting at global pos " << currentContigIntervalInfo_->firstGlobalPos << endl; } } else { return make_pair( 0, 0 ); //EAGLE_WARNING( "Too many reads generated at the end!" ); } } assert( floor(currentGlobalPos_) >= currentContigIntervalInfo_->firstGlobalPos ); return std::make_pair( (unsigned long)floor(currentGlobalPos_), medianFragmentLength_ ); } pair< unsigned long, unsigned int > RandomIntervalGeneratorFromProbabilityMatrix::getNext( const signed long testValue ) { if (remainingSampleCount_ > 0) { double rand0to1 = (1.0+rand())/(1.0+RAND_MAX); curMax_ *= exp(log(rand0to1)/remainingSampleCount_); remainingSampleCount_--; double choice = (1-curMax_) * intervalSize_; lastChoiceRemainder += choice - lastChoice; while (lastChoiceRemainder >= fragmentLengthProbabilityMatrix_.getProbabilities()[ lastChoiceIndex ]) { lastChoiceRemainder -= fragmentLengthProbabilityMatrix_.getProbabilities()[ lastChoiceIndex ]; if (lastChoiceIndex < fragmentLengthProbabilityMatrix_.getProbabilities().size()) { ++lastChoiceIndex; } else { // Avoid going past the end of the array because of rounding errors break; } } lastChoice = choice; unsigned long pickedGlobalPos = lastChoiceIndex / fragmentLengthDist_size; unsigned long pickedFragmentLength = lastChoiceIndex % fragmentLengthDist_size + fragmentLengthDist_min; cout << (boost::format("remainingSampleCount_=%d, choice=%f, choiceIndex=%d, pickedGlobalPos=%d, pickedFragmentLength=%d") % remainingSampleCount_ % choice % lastChoiceIndex % pickedGlobalPos % pickedFragmentLength).str() << endl; return make_pair( pickedGlobalPos, pickedFragmentLength ); } else { EAGLE_WARNING( "Too many reads generated at the end!" ); return make_pair( 0, 0 ); } } } // namespace model } // namespace eagle
37.36
357
0.674848
sequencing
2b6edefa630bd18dcd564cccb200219b6dcbb4d4
4,791
cpp
C++
src/web/downloadthread.cpp
quizzmaster/chemkit
803e4688b514008c605cb5c7790f7b36e67b68fc
[ "BSD-3-Clause" ]
34
2015-01-24T23:59:41.000Z
2020-11-12T13:48:01.000Z
src/web/downloadthread.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
4
2015-12-28T20:29:16.000Z
2016-01-26T06:48:19.000Z
src/web/downloadthread.cpp
soplwang/chemkit
d62b7912f2d724a05fa8be757f383776fdd5bbcb
[ "BSD-3-Clause" ]
17
2015-01-23T14:50:24.000Z
2021-06-10T15:43:50.000Z
/****************************************************************************** ** ** Copyright (C) 2009-2011 Kyle Lutz <kyle.r.lutz@gmail.com> ** All rights reserved. ** ** This file is a part of the chemkit project. For more information ** see <http://www.chemkit.org>. ** ** 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 chemkit project nor the names of its ** contributors may be used to endorse or promote products derived ** from this software without specific prior written permission. ** ** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT ** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR ** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT ** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, ** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT ** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, ** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY ** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT ** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE ** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ** ******************************************************************************/ #include "downloadthread.h" namespace chemkit { // === DownloadThread ====================================================== // /// \class DownloadThread downloadthread.h /// \ingroup chemkit-web /// \internal /// \brief The DownloadThread class provides an interface for /// downloading data from the web. // --- Construction and Destruction ---------------------------------------- // /// Creates a new download thread object. DownloadThread::DownloadThread(const QUrl &url) : QThread(), m_url(url) { m_manager = 0; m_ftp = 0; m_reply = 0; } /// Destroys the download thread object. DownloadThread::~DownloadThread() { delete m_ftp; delete m_manager; } // --- Properties ---------------------------------------------------------- // /// Returns the downloaded data. QByteArray DownloadThread::data() const { return m_data; } // --- Thread -------------------------------------------------------------- // /// Starts the download. /// /// This method should not be called directly. Use QThread::start(). void DownloadThread::run() { if(m_url.scheme() == "ftp"){ m_dataBuffer.open(QBuffer::ReadWrite); m_ftp = new QFtp; connect(m_ftp, SIGNAL(done(bool)), SLOT(ftpDone(bool)), Qt::DirectConnection); m_ftp->connectToHost(m_url.host()); m_ftp->login("anonymous", "chemkit"); QFileInfo fileInfo(m_url.path()); m_ftp->cd(fileInfo.path() + "/"); m_ftp->get(fileInfo.fileName(), &m_dataBuffer); m_ftp->close(); } else{ m_manager = new QNetworkAccessManager; connect(m_manager, SIGNAL(finished(QNetworkReply*)), SLOT(replyFinished(QNetworkReply*)), Qt::DirectConnection); m_reply = m_manager->get(QNetworkRequest(m_url)); connect(m_reply, SIGNAL(error(QNetworkReply::NetworkError)), SLOT(replyError(QNetworkReply::NetworkError)), Qt::DirectConnection); } exec(); } // --- Static Methods ------------------------------------------------------ // /// Downloads and returns the data from \p url. QByteArray DownloadThread::download(const QUrl &url) { DownloadThread thread(url); thread.start(); thread.wait(); return thread.data(); } // --- Slots --------------------------------------------------------------- // void DownloadThread::replyFinished(QNetworkReply *reply) { m_data = reply->readAll(); reply->deleteLater(); m_manager->deleteLater(); exit(0); } void DownloadThread::replyError(QNetworkReply::NetworkError error) { Q_UNUSED(error); qDebug() << "chemkit-web: DownloadThread Error: " << m_reply->errorString(); } void DownloadThread::ftpDone(bool error) { if(error){ qDebug() << "chemkit-web: DownloadThread Ftp Error:" << m_ftp->errorString(); exit(-1); } m_data = m_dataBuffer.data(); exit(0); } } // end chemkit namespace
33.041379
86
0.615947
quizzmaster
2b6feb5740721ab22d1b8a61391e5f5f9cb7af52
60
cpp
C++
common/UIOverlay.cpp
daozhangXDZ/OpenGLES_Examples
9266842fbd0ae899446b6ccda9cd63eeeaf1451f
[ "MIT" ]
248
2019-06-04T16:46:24.000Z
2022-02-13T11:21:14.000Z
common/UIOverlay.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
null
null
null
common/UIOverlay.cpp
YKHahahaha/OpenGLES_Examples
b3451184bb5fffd2d6e8390ece93ca6cfcf80bfc
[ "MIT" ]
40
2019-07-18T09:59:22.000Z
2021-09-17T13:00:05.000Z
// Implementation of Common library #include "UIOverlay.h"
20
36
0.766667
daozhangXDZ
2b763a401e508f70e6f79004fda13fa62b744358
10,614
cpp
C++
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
1
2020-06-16T11:45:26.000Z
2020-06-16T11:45:26.000Z
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
null
null
null
mpegts/mpegts/mpegts_muxer.cpp
Unit-X/srt_tango_2
9443457f807ad151c9b543f892c969404e74e3a7
[ "MIT" ]
null
null
null
#include "mpegts_muxer.h" #include "simple_buffer.h" #include "ts_packet.h" #include "crc.h" #include <string.h> #include "common.h" static const uint16_t MPEGTS_NULL_PACKET_PID = 0x1FFF; static const uint16_t MPEGTS_PAT_PID = 0x00; static const uint16_t MPEGTS_PMT_PID = 0x100; static const uint16_t MPEGTS_PCR_PID = 0x110; class MpegTsAdaptationFieldType { public: // Reserved for future use by ISO/IEC static const uint8_t mReserved = 0x00; // No adaptation_field, payload only static const uint8_t mPayloadOnly = 0x01; // Adaptation_field only, no payload static const uint8_t mAdaptionOnly = 0x02; // Adaptation_field followed by payload static const uint8_t mPayloadAdaptionBoth = 0x03; }; MpegTsMuxer::MpegTsMuxer() { } MpegTsMuxer::~MpegTsMuxer() { } void MpegTsMuxer::createPat(SimpleBuffer *pSb, uint16_t lPmtPid, uint8_t lCc) { int lPos = pSb->pos(); TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 1; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_PAT_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = lCc; AdaptationFieldHeader lAdaptField; PATHeader lPatHeader; lPatHeader.mTableId = 0x00; lPatHeader.mSectionSyntaxIndicator = 1; lPatHeader.mB0 = 0; lPatHeader.mReserved0 = 0x3; lPatHeader.mTransportStreamId = 0; lPatHeader.mReserved1 = 0x3; lPatHeader.mVersionNumber = 0; lPatHeader.mCurrentNextIndicator = 1; lPatHeader.mSectionNumber = 0x0; lPatHeader.mLastSectionNumber = 0x0; //program_number uint16_t lProgramNumber = 0x0001; //program_map_PID uint16_t lProgramMapPid = 0xe000 | (lPmtPid & 0x1fff); unsigned int lSectionLength = 4 + 4 + 5; lPatHeader.mSectionLength = lSectionLength & 0x3ff; lTsHeader.encode(pSb); lAdaptField.encode(pSb); lPatHeader.encode(pSb); pSb->write_2bytes(lProgramNumber); pSb->write_2bytes(lProgramMapPid); // crc32 uint32_t lCrc32 = crc32((uint8_t *) pSb->data() + 5, pSb->pos() - 5); pSb->write_4bytes(lCrc32); std::string lStuff(188 - (pSb->pos() - lPos), 0xff); pSb->write_string(lStuff); } void MpegTsMuxer::createPmt(SimpleBuffer *pSb, std::map<uint8_t, int> lStreamPidMap, uint16_t lPmtPid, uint8_t lCc) { int lPos = pSb->pos(); TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 1; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = lPmtPid; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = lCc; AdaptationFieldHeader lAdaptField; PMTHeader lPmtHeader; lPmtHeader.mTableId = 0x02; lPmtHeader.mSectionSyntaxIndicator = 1; lPmtHeader.mB0 = 0; lPmtHeader.mReserved0 = 0x3; lPmtHeader.mSectionLength = 0; lPmtHeader.mProgramNumber = 0x0001; lPmtHeader.mReserved1 = 0x3; lPmtHeader.mVersionNumber = 0; lPmtHeader.mCurrentNextIndicator = 1; lPmtHeader.mSectionNumber = 0x00; lPmtHeader.mLastSectionNumber = 0x00; lPmtHeader.mReserved2 = 0x7; lPmtHeader.mReserved3 = 0xf; lPmtHeader.mProgramInfoLength = 0; for (auto lIt = lStreamPidMap.begin(); lIt != lStreamPidMap.end(); lIt++) { lPmtHeader.mInfos.push_back(std::shared_ptr<PMTElementInfo>(new PMTElementInfo(lIt->first, lIt->second))); if (lIt->first == MpegTsStream::AVC) { lPmtHeader.mPcrPid = lIt->second; } } uint16_t lSectionLength = lPmtHeader.size() - 3 + 4; lPmtHeader.mSectionLength = lSectionLength & 0x3ff; lTsHeader.encode(pSb); lAdaptField.encode(pSb); lPmtHeader.encode(pSb); // crc32 uint32_t lCrc32 = crc32((uint8_t *) pSb->data() + lPos + 5, pSb->pos() - lPos - 5); pSb->write_4bytes(lCrc32); std::string lStuff(188 - (pSb->pos() - lPos), 0xff); pSb->write_string(lStuff); } void MpegTsMuxer::createPes(TsFrame *pFrame, SimpleBuffer *pSb) { bool lFirst = true; while (!pFrame->mData->empty()) { SimpleBuffer lPacket(188); TsHeader lTsHeader; lTsHeader.mPid = pFrame->mPid; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = getCc(pFrame->mStreamType); if (lFirst) { lTsHeader.mPayloadUnitStartIndicator = 0x01; if (pFrame->mStreamType == MpegTsStream::AVC) { lTsHeader.mAdaptationFieldControl |= 0x02; AdaptationFieldHeader adapt_field_header; adapt_field_header.mAdaptationFieldLength = 0x07; adapt_field_header.mRandomAccessIndicator = 0x01; adapt_field_header.mPcrFlag = 0x01; lTsHeader.encode(&lPacket); adapt_field_header.encode(&lPacket); writePcr(&lPacket, pFrame->mDts); } else { lTsHeader.encode(&lPacket); } PESHeader lPesHeader; lPesHeader.mPacketStartCode = 0x000001; lPesHeader.mStreamId = pFrame->mStreamId; lPesHeader.mMarkerBits = 0x02; lPesHeader.mOriginalOrCopy = 0x01; if (pFrame->mPts != pFrame->mDts) { lPesHeader.mPtsDtsFlags = 0x03; lPesHeader.mHeaderDataLength = 0x0A; } else { lPesHeader.mPtsDtsFlags = 0x2; lPesHeader.mHeaderDataLength = 0x05; } uint32_t lPesSize = (lPesHeader.mHeaderDataLength + pFrame->mData->size() + 3); lPesHeader.mPesPacketLength = lPesSize > 0xffff ? 0 : lPesSize; lPesHeader.encode(&lPacket); if (lPesHeader.mPtsDtsFlags == 0x03) { writePts(&lPacket, 3, pFrame->mPts); writePts(&lPacket, 1, pFrame->mDts); } else { writePts(&lPacket, 2, pFrame->mPts); } lFirst = false; } else { lTsHeader.encode(&lPacket); } uint32_t lBodySize = lPacket.size() - lPacket.pos(); uint32_t lInSize = pFrame->mData->size() - pFrame->mData->pos(); if (lBodySize <= lInSize) { // MpegTsAdaptationFieldType::payload_only or MpegTsAdaptationFieldType::payload_adaption_both for AVC lPacket.write_string(pFrame->mData->read_string(lBodySize)); } else { uint16_t lStuffSize = lBodySize - lInSize; if (lTsHeader.mAdaptationFieldControl == MpegTsAdaptationFieldType::mAdaptionOnly || lTsHeader.mAdaptationFieldControl == MpegTsAdaptationFieldType::mPayloadAdaptionBoth) { char *lpBase = lPacket.data() + 5 + lPacket.data()[4]; lPacket.setData(lpBase - lPacket.data() + lStuffSize, lpBase, lPacket.data() + lPacket.pos() - lpBase); memset(lpBase, 0xff, lStuffSize); lPacket.skip(lStuffSize); lPacket.data()[4] += lStuffSize; } else { // adaptationFieldControl |= 0x20 == MpegTsAdaptationFieldType::payload_adaption_both lPacket.data()[3] |= 0x20; lPacket.setData(188 - 4 - lStuffSize, lPacket.data() + 4, lPacket.pos() - 4); lPacket.skip(lStuffSize); lPacket.data()[4] = lStuffSize - 1; if (lStuffSize >= 2) { lPacket.data()[5] = 0; memset(&(lPacket.data()[6]), 0xff, lStuffSize - 2); } } lPacket.write_string(pFrame->mData->read_string(lInSize)); } pSb->append(lPacket.data(), lPacket.size()); } } void MpegTsMuxer::createPcr(SimpleBuffer *pSb) { uint64_t lPcr = 0; TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 0; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_PCR_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mAdaptionOnly; lTsHeader.mContinuityCounter = 0; AdaptationFieldHeader lAdaptField; lAdaptField.mAdaptationFieldLength = 188 - 4 - 1; lAdaptField.mSiscontinuityIndicator = 0; lAdaptField.mRandomAccessIndicator = 0; lAdaptField.mElementaryStreamPriorityIndicator = 0; lAdaptField.mPcrFlag = 1; lAdaptField.mOpcrFlag = 0; lAdaptField.mSplicingPointFlag = 0; lAdaptField.mTransportPrivateDataFlag = 0; lAdaptField.mAdaptationFieldExtensionFlag = 0; char *p = pSb->data(); lTsHeader.encode(pSb); lAdaptField.encode(pSb); writePcr(pSb, lPcr); } void MpegTsMuxer::createNull(SimpleBuffer *pSb) { TsHeader lTsHeader; lTsHeader.mSyncByte = 0x47; lTsHeader.mTransportErrorIndicator = 0; lTsHeader.mPayloadUnitStartIndicator = 0; lTsHeader.mTransportPriority = 0; lTsHeader.mPid = MPEGTS_NULL_PACKET_PID; lTsHeader.mTransportScramblingControl = 0; lTsHeader.mAdaptationFieldControl = MpegTsAdaptationFieldType::mPayloadOnly; lTsHeader.mContinuityCounter = 0; lTsHeader.encode(pSb); } void MpegTsMuxer::encode(TsFrame *pFrame, std::map<uint8_t, int> lStreamPidMap, uint16_t lPmtPid, SimpleBuffer *pSb) { if (shouldCreatePat()) { uint8_t lPatPmtCc = getCc(0); createPat(pSb, lPmtPid, lPatPmtCc); createPmt(pSb, lStreamPidMap, lPmtPid, lPatPmtCc); } createPes(pFrame, pSb); } uint8_t MpegTsMuxer::getCc(uint32_t lWithPid) { if (mPidCcMap.find(lWithPid) != mPidCcMap.end()) { mPidCcMap[lWithPid] = (mPidCcMap[lWithPid] + 1) & 0x0F; return mPidCcMap[lWithPid]; } mPidCcMap[lWithPid] = 0; return 0; } bool MpegTsMuxer::shouldCreatePat() { bool lRet = false; static const int lPatInterval = 20; static int lCurrentIndex = 0; if (lCurrentIndex % lPatInterval == 0) { if (lCurrentIndex > 0) { lCurrentIndex = 0; } lRet = true; } lCurrentIndex++; return lRet; }
36.102041
129
0.63746
Unit-X
2b7686c4291f08c186373e586ed0a4847757da18
632
hpp
C++
include/DynamicBitset.hpp
GiugnoLab/GRASS
2b65b37b03988a842318256e9b364d91221adabd
[ "Intel", "MIT" ]
1
2022-03-03T03:32:45.000Z
2022-03-03T03:32:45.000Z
include/DynamicBitset.hpp
GiugnoLab/GRASS
2b65b37b03988a842318256e9b364d91221adabd
[ "Intel", "MIT" ]
null
null
null
include/DynamicBitset.hpp
GiugnoLab/GRASS
2b65b37b03988a842318256e9b364d91221adabd
[ "Intel", "MIT" ]
null
null
null
/* * Dynamic Bitset Class powered by Mingz & Frank * Version 1.0 */ #ifndef DYNAMICBITSET_H #define DYNAMICBITSET_H #include <iostream> #include <cstring> #include <cstdlib> #include <cmath> using namespace std; #define BIT_PER_DATASET_TYPE 8 typedef unsigned char dataset_t; class DynamicBitset { public: DynamicBitset(unsigned int size); ~DynamicBitset(); void reset(); void allset(); void set(unsigned int pos, bool value); bool get(unsigned int pos); unsigned int onset(unsigned int length); //debug print void print(); //private: unsigned int size; unsigned int words; dataset_t *dataset; }; #endif
15.414634
48
0.72943
GiugnoLab
2b795362dfcbc6fe454f61ae890685908c7f1d6f
694
cpp
C++
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
flex-engine/src/flex-engine/Log.cpp
flexed-team/flex-engine
481f40a431a33a9f1a4cc0de95edb7dc81aba34e
[ "Apache-2.0" ]
null
null
null
#include "log.hpp" namespace FE { std::shared_ptr<spdlog::logger> Log::s_core_logger; std::shared_ptr<spdlog::logger> Log::s_client_logger; void Log::init() { // See spdlog [wiki](https://github.com/gabime/spdlog/wiki) for more pattern settings // ^ - start color range // T - ISO 8601 time format // n - logger's name // v - actual text to log // $ - end color range spdlog::set_pattern("%^[%T] %n: %v%$"); // Create color multi threaded logger s_core_logger = spdlog::stdout_color_mt("FE"); s_core_logger->set_level(spdlog::level::trace); s_client_logger = spdlog::stdout_color_mt("APP"); s_client_logger->set_level(spdlog::level::trace); } } // namespace FE
26.692308
87
0.680115
flexed-team
2b7dfcb07b052af8e1404f5f78aab97ae12524d8
1,842
cc
C++
src/attributes/Akima474MethodWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
41
2018-12-07T23:10:50.000Z
2022-02-19T03:01:49.000Z
src/attributes/Akima474MethodWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
59
2019-01-04T15:43:30.000Z
2022-03-31T09:48:15.000Z
src/attributes/Akima474MethodWrapper.cc
b8raoult/magics
eb2c86ec6e392e89c90044128dc671f22283d6ad
[ "ECL-2.0", "Apache-2.0" ]
13
2019-01-07T14:36:33.000Z
2021-09-06T14:48:36.000Z
/****************************** LICENSE ******************************* * (C) Copyright 1996-2017 ECMWF. * * This software is licensed under the terms of the Apache Licence Version 2.0 * which can be obtained at http://www.apache.org/licenses/LICENSE-2.0. * In applying this licence, ECMWF does not waive the privileges and immunities * granted to it by virtue of its status as an intergovernmental organisation nor * does it submit to any jurisdiction. ******************************* LICENSE *******************************/ /*! \\file Akima474MethodAttributes.h \\brief Definition of Akima474Method Attributes class. This file is automatically generated. Do Not Edit! */ #include "MagRequest.h" #include "Akima474MethodWrapper.h" #include "MagicsParameter.h" #include "Factory.h" #include "MagTranslator.h" #include "MagicsGlobal.h" using namespace magics; Akima474MethodWrapper::Akima474MethodWrapper(): akima474method_(new Akima474Method()) { ContourMethodWrapper::object(akima474method_); } Akima474MethodWrapper::Akima474MethodWrapper(Akima474Method* akima474method): akima474method_(akima474method) { ContourMethodWrapper::object(akima474method_); } Akima474MethodWrapper::~Akima474MethodWrapper() { } void Akima474MethodWrapper::set(const MagRequest& request) { ContourMethodWrapper::set(request); if (request.countValues("CONTOUR_AKIMA_X_RESOLUTION") ) { double resolutionX_value = request("CONTOUR_AKIMA_X_RESOLUTION"); akima474method_->resolutionX_ = resolutionX_value; } if (request.countValues("CONTOUR_AKIMA_Y_RESOLUTION") ) { double resolutionY_value = request("CONTOUR_AKIMA_Y_RESOLUTION"); akima474method_->resolutionY_ = resolutionY_value; } } void Akima474MethodWrapper::print(ostream& out) const { out << "Akima474MethodWrapper[]"; }
22.192771
109
0.711726
b8raoult
2b88daacbff2a89f428e813af6cdbe47db5703b9
8,677
hxx
C++
com/ole32/olethunk/h/interop.hxx
npocmaka/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
17
2020-11-13T13:42:52.000Z
2021-09-16T09:13:13.000Z
com/ole32/olethunk/h/interop.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
2
2020-10-19T08:02:06.000Z
2020-10-19T08:23:18.000Z
com/ole32/olethunk/h/interop.hxx
sancho1952007/Windows-Server-2003
5c6fe3db626b63a384230a1aa6b92ac416b0765f
[ "Unlicense" ]
14
2020-11-14T09:43:20.000Z
2021-08-28T08:59:57.000Z
//+------------------------------------------------------------------------- // // Microsoft Windows // Copyright (C) Microsoft Corporation, 1992 - 1994. // // File: interop.hxx // // Contents: Common definitions for the interop project // // History: 18-Feb-94 DrewB Created // //-------------------------------------------------------------------------- #ifndef __INTEROP_HXX__ #define __INTEROP_HXX__ //+--------------------------------------------------------------------------- // // Purpose: Standard debugging support // // History: 18-Feb-94 DrewB Created // //---------------------------------------------------------------------------- #include <debnot.h> // // The rest of the OACF flags are defined in thunkapi.hxx. This one is here // because it is shared between ole2.dll and olethk32.dll. The 16-bit binaries // do not include thunkapi.hxx at the moment. KevinRo promises to fix this someday // Feel free to fix this if you wish. // #define OACF_CORELTRASHMEM 0x10000000 // CorelDraw relies on the fact that // OLE16 trashed memory during paste- // link. Therefore, we'll go ahead // and trash it for them if this // flag is on. #define OACF_CRLPNTPERSIST 0x01000000 // CorelPaint IPersistStg used in their // OleSave screws up in QI #define OACF_WORKSCLIPOBJ 0x00100000 // Works 3.0b creates a clipboard // data object with a zero ref count // Word 6 does this too. Same flag used. // Also Paradox5, Novel/Corel WrdPft. // They all call OleIsCurrentClipboard // with a 0-refcount 16-bit IDataObject ptr. #define OACF_TEXTARTDOBJ 0x00010000 // TextArt IDataAdvHolder::DAdvise has // data object with a zero ref count #if DBG == 1 #ifdef WIN32 DECLARE_DEBUG(thk); #else DECLARE_DEBUG(thk1); #endif #define DEB_DLL 0x0008 #define DEB_THOPS DEB_USER1 #define DEB_INVOKES DEB_USER2 #define DEB_ARGS DEB_USER3 #define DEB_NESTING DEB_USER4 #define DEB_CALLTRACE DEB_USER5 #define DEB_THUNKMGR DEB_USER6 #define DEB_MEMORY DEB_USER7 #define DEB_TLSTHK DEB_USER8 #define DEB_UNKNOWN DEB_USER9 #define DEB_FAILURES DEB_USER10 #define DEB_DLLS16 DEB_USER11 #define DEB_APIS16 DEB_USER12 // api calls to 16 bit entry point #define DEB_DBGFAIL DEB_USER13 // Pop up dialog to allow debugging #endif #if DBG == 1 #ifdef WIN32 #define thkDebugOut(x) thkInlineDebugOut x #else #define thkDebugOut(x) thk1InlineDebugOut x #endif #define thkAssert(e) Win4Assert(e) #define thkVerify(e) Win4Assert(e) #else #define thkDebugOut(x) #define thkAssert(e) #define thkVerify(e) (e) #endif #define OLETHUNK_DLL16NOTFOUND 0x88880002 //+--------------------------------------------------------------------------- // // Purpose: Declarations and definitions shared across everything // // History: 18-Feb-94 DrewB Created // //---------------------------------------------------------------------------- // An IID pointer or an index into the list of known interfaces // If the high word is zero, it's an index, otherwise it's a pointer typedef DWORD IIDIDX; #define IIDIDX_IS_INDEX(ii) (HIWORD(ii) == 0) #define IIDIDX_IS_IID(ii) (!IIDIDX_IS_INDEX(ii)) #define IIDIDX_INVALID ((IIDIDX)0xffff) #define INDEX_IIDIDX(idx) ((IIDIDX)(idx)) #define IID_IIDIDX(piid) ((IIDIDX)(piid)) #define IIDIDX_INDEX(ii) ((int)(ii)) #define IIDIDX_IID(ii) ((IID const *)(ii)) // Methods are treated as if they all existed on a single interface // Their method numbers are biased to distinguish them from real methods #define THK_API_BASE 0xf0000000 #define THK_API_METHOD(method) (THK_API_BASE+(method)) // Standard method indices in the vtable #define SMI_QUERYINTERFACE 0 #define SMI_ADDREF 1 #define SMI_RELEASE 2 #define SMI_COUNT 3 #ifndef WIN32 #define UNALIGNED #endif //+--------------------------------------------------------------------------- // // Struct: CALLDATA // // Purpose: Data describing a 16-bit call to be made on behalf of // the 32-bit code, used since Callback16 can only pass // one parameter // // History: 18-Feb-94 JohannP Created // //---------------------------------------------------------------------------- typedef struct tagCallData { DWORD vpfn; DWORD vpvStack16; DWORD cbStack; } CALLDATA; typedef CALLDATA UNALIGNED FAR *LPCALLDATA; //+--------------------------------------------------------------------------- // // Struct: DATA16 // // Purpose: Data describing things in the 16-bit world that need to be // known to the 32-bit world. // // History: 3-Mar-94 BobDay Created // //---------------------------------------------------------------------------- typedef struct tagDATA16 { DWORD atfnProxy1632Vtbl; DWORD fnCallbackHandler; DWORD fnTaskAlloc; DWORD fnTaskFree; DWORD fnLoadProcDll; DWORD fnUnloadProcDll; DWORD fnCallGetClassObject; DWORD fnCallCanUnloadNow; DWORD fnQueryInterface16; DWORD fnAddRef16; DWORD fnRelease16; DWORD fnReleaseStgMedium16; DWORD avpfnSm16ReleaseHandlerVtbl; DWORD fnTouchPointer16; DWORD fnStgMediumStreamHandler16; DWORD fnCallStub16; DWORD fnSetOwnerPublic16; DWORD fnWinExec16; } DATA16; typedef DATA16 UNALIGNED FAR * LPDATA16; //+--------------------------------------------------------------------------- // // Struct: LOADPROCDLLSTRUCT // // Purpose: Data passed to the LoadProcDll function that is called from // the 32-bit function of similar name. // // History: 11-Mar-94 BobDay Created // //---------------------------------------------------------------------------- typedef struct tagLOADPROCDLLSTRUCT { DWORD vpDllName; DWORD vpfnGetClassObject; DWORD vpfnCanUnloadNow; DWORD vhmodule; } LOADPROCDLLSTRUCT; typedef LOADPROCDLLSTRUCT UNALIGNED FAR * LPLOADPROCDLLSTRUCT; //+--------------------------------------------------------------------------- // // Struct: CALLGETCLASSOBJECTSTRUCT // // Purpose: Data passed to the CallGetClassObject function that is called // from the 32-bit function of similar name. // // History: 11-Mar-94 BobDay Created // //---------------------------------------------------------------------------- typedef struct tagCALLGETCLASSOBJECTSTRUCT { DWORD vpfnGetClassObject; CLSID clsid; IID iid; DWORD iface; } CALLGETCLASSOBJECTSTRUCT; typedef CALLGETCLASSOBJECTSTRUCT UNALIGNED FAR * LPCALLGETCLASSOBJECTSTRUCT; //+--------------------------------------------------------------------------- // // Struct: WINEXEC16STRUCT // // Purpose: Data passed to the WinExec16 function that is called from // the 32-bit function of similar name. // // History: 27-Jul-94 AlexT Created // //---------------------------------------------------------------------------- typedef struct tagWINEXEC16STRUCT { DWORD vpCommandLine; unsigned short vusShow; } WINEXEC16STRUCT; typedef WINEXEC16STRUCT UNALIGNED FAR * LPWINEXEC16STRUCT; //+--------------------------------------------------------------------------- // // Class: CSm16ReleaseHandler (srh) // // Purpose: Provides punkForRelease for 32->16 STGMEDIUM conversion // // Interface: IUnknown // // History: 24-Apr-94 DrewB Created // //---------------------------------------------------------------------------- #ifdef __cplusplus class CSm16ReleaseHandler { public: void Init(IUnknown *pUnk, STGMEDIUM *psm32, STGMEDIUM UNALIGNED *psm16, IUnknown *punkForRelease, CLIPFORMAT cfFormat); void CallFailed() { _punkForRelease = NULL; } DWORD _avpfnVtbl; STGMEDIUM _sm32; STGMEDIUM _sm16; IUnknown *_punkForRelease; LONG _cReferences; CLIPFORMAT _cfFormat; IUnknown *_pUnkThkMgr; }; #endif #endif // __INTEROP_HXX__
30.660777
85
0.530483
npocmaka
2b8b20fd3f2f2b67388e511070ed3135875ff451
1,362
cpp
C++
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.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-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2021-10-14T16:57:00.000Z
2021-10-18T10:47:24.000Z
aws-cpp-sdk-cloudtrail/source/model/ListEventDataStoresResult.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "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/cloudtrail/model/ListEventDataStoresResult.h> #include <aws/core/utils/json/JsonSerializer.h> #include <aws/core/AmazonWebServiceResult.h> #include <aws/core/utils/StringUtils.h> #include <aws/core/utils/UnreferencedParam.h> #include <utility> using namespace Aws::CloudTrail::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; using namespace Aws; ListEventDataStoresResult::ListEventDataStoresResult() { } ListEventDataStoresResult::ListEventDataStoresResult(const Aws::AmazonWebServiceResult<JsonValue>& result) { *this = result; } ListEventDataStoresResult& ListEventDataStoresResult::operator =(const Aws::AmazonWebServiceResult<JsonValue>& result) { JsonView jsonValue = result.GetPayload().View(); if(jsonValue.ValueExists("EventDataStores")) { Array<JsonView> eventDataStoresJsonList = jsonValue.GetArray("EventDataStores"); for(unsigned eventDataStoresIndex = 0; eventDataStoresIndex < eventDataStoresJsonList.GetLength(); ++eventDataStoresIndex) { m_eventDataStores.push_back(eventDataStoresJsonList[eventDataStoresIndex].AsObject()); } } if(jsonValue.ValueExists("NextToken")) { m_nextToken = jsonValue.GetString("NextToken"); } return *this; }
27.24
126
0.768722
perfectrecall
2b957045c492074cd0090fa7e5a5a8b75985c999
2,954
cpp
C++
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
source/RegistCallback.cpp
xzrunner/nserializer
44c252703a53c5970b8d9f2b608d56830601055e
[ "MIT" ]
null
null
null
#include "ns/RegistCallback.h" #include "ns/CompSerializer.h" #include "ns/CompNoSerialize.h" #include "ns/N0CompComplex.h" #include <node0/CompComplex.h> #include "ns/N2CompAnim.h" #include <node2/CompAnim.h> #include "ns/N2CompColorCommon.h" #include <node2/CompColorCommon.h> #include "ns/N2CompColorMap.h" #include <node2/CompColorMap.h> #include "ns/N2CompTransform.h" #include <node2/CompTransform.h> #include <node2/CompBoundingBox.h> #include "ns/N2CompUniquePatch.h" #include <node2/CompUniquePatch.h> #include "ns/N2CompSharedPatch.h" #include <node2/CompSharedPatch.h> #include "ns/N2CompScissor.h" #include <node2/CompScissor.h> #include "ns/N2CompScript.h" #include <node2/CompScript.h> #include "ns/N2CompScript.h" // todo #include <node2/EditOp.h> #include "ns/N0CompIdentity.h" #include <node0/CompIdentity.h> #include "ns/N0CompComplex.h" #include <node0/CompComplex.h> #include "ns/N2CompImage.h" #include <node2/CompImage.h> #include "ns/N2CompMask.h" #include <node2/CompMask.h> #include "ns/N2CompText.h" #include <node2/CompText.h> #include "ns/N2CompScale9.h" #include <node2/CompScale9.h> #include "ns/N2CompShape.h" #include <node2/CompShape.h> #include "ns/N3CompAABB.h" #include <node3/CompAABB.h> #include "ns/N3CompTransform.h" #include <node3/CompTransform.h> #include "ns/N3CompModel.h" #include <node3/CompModel.h> #include "ns/N3CompModelInst.h" #include <node3/CompModelInst.h> #include "ns/N3CompShape.h" #include <node3/CompShape.h> #include "ns/N0CompFlags.h" #include <node0/CompFlags.h> #include <node0/SceneNode.h> #include <memmgr/LinearAllocator.h> #include <anim/Layer.h> #include <anim/KeyFrame.h> namespace ns { void RegistCallback::Init() { AddUniqueCB<n0::CompIdentity, N0CompIdentity>(); AddUniqueCB<n2::CompColorCommon, N2CompColorCommon>(); AddUniqueCB<n2::CompColorMap, N2CompColorMap>(); AddUniqueCB<n2::CompTransform, N2CompTransform>(); AddUniqueNullCB<n2::CompBoundingBox, CompNoSerialize>(); AddUniqueCB<n2::CompUniquePatch, N2CompUniquePatch>(); AddUniqueCB<n2::CompSharedPatch, N2CompSharedPatch>(); AddUniqueCB<n2::CompScissor, N2CompScissor>(); AddUniqueCB<n2::CompScript, N2CompScript>(); AddSharedCB<n0::CompComplex, N0CompComplex>(); AddSharedCB<n2::CompAnim, N2CompAnim>(); AddSharedCB<n2::CompImage, N2CompImage>(); AddSharedCB<n2::CompMask, N2CompMask>(); AddSharedCB<n2::CompText, N2CompText>(); AddSharedCB<n2::CompScale9, N2CompScale9>(); //AddSharedCB<n2::CompShape, N2CompShape>(); AddUniqueCB<n3::CompAABB, N3CompAABB>(); AddUniqueCB<n3::CompTransform, N3CompTransform>(); AddSharedCB<n3::CompModel, N3CompModel>(); AddUniqueCB<n3::CompModelInst, N3CompModelInst>(); AddUniqueCB<n3::CompShape, N3CompShape>(); AddUniqueCB<n0::CompFlags, N0CompFlags>(); AddAssetCB<n0::CompComplex>(); AddAssetCB<n2::CompAnim>(); AddAssetCB<n2::CompImage>(); AddAssetCB<n2::CompMask>(); AddAssetCB<n2::CompText>(); AddAssetCB<n2::CompScale9>(); } }
27.607477
57
0.756601
xzrunner
2b9629798298c6704a0c43083e35af2d7e4529af
145
inl
C++
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2019-04-23T05:24:16.000Z
2019-04-23T05:24:16.000Z
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2016-08-16T13:05:39.000Z
2016-08-16T13:05:39.000Z
Projects/CygnusAuxBoardMonitor/Resources/ConfigurationXML_info.inl
hightower70/CygnusGroundStationDev
9fd709f28a67adb293a99c5c251b4ed89e755db3
[ "BSD-2-Clause" ]
1
2018-06-24T14:51:20.000Z
2018-06-24T14:51:20.000Z
0x00, 0x00, 0x01, 0x01, 0x01, 0x00, 0x02, 0x0A, 0x03, 0x00, 0x02, 0x0A, 0x05, 0x00, 0x02, 0x03, 0x07, 0x00, 0x02, 0x0A, 0x09, 0x00, 0x02, 0x03
48.333333
96
0.662069
hightower70
2b9cbd43fc10d98d1346ed20f4b7af95539df4fb
12,800
cpp
C++
src/providers/postgres/qgspostgresprojectstorage.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/providers/postgres/qgspostgresprojectstorage.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
null
null
null
src/providers/postgres/qgspostgresprojectstorage.cpp
dyna-mis/Hilabeling
cb7d5d4be29624a20c8a367162dbc6fd779b2b52
[ "MIT" ]
1
2021-12-25T08:40:30.000Z
2021-12-25T08:40:30.000Z
/*************************************************************************** qgspostgresprojectstorage.cpp --------------------- begin : April 2018 copyright : (C) 2018 by Martin Dobias email : wonder dot sk at gmail dot com *************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include "qgspostgresprojectstorage.h" #include "qgspostgresconn.h" #include "qgspostgresconnpool.h" #include "qgsreadwritecontext.h" #include <QIODevice> #include <QJsonDocument> #include <QJsonObject> #include <QUrl> static bool _parseMetadataDocument( const QJsonDocument &doc, QgsProjectStorage::Metadata &metadata ) { if ( !doc.isObject() ) return false; QJsonObject docObj = doc.object(); metadata.lastModified = QDateTime(); if ( docObj.contains( "last_modified_time" ) ) { QString lastModifiedTimeStr = docObj["last_modified_time"].toString(); if ( !lastModifiedTimeStr.isEmpty() ) { QDateTime lastModifiedUtc = QDateTime::fromString( lastModifiedTimeStr, Qt::ISODate ); lastModifiedUtc.setTimeSpec( Qt::UTC ); metadata.lastModified = lastModifiedUtc.toLocalTime(); } } return true; } static bool _projectsTableExists( QgsPostgresConn &conn, const QString &schemaName ) { QString tableName( "qgis_projects" ); QString sql( QStringLiteral( "SELECT COUNT(*) FROM information_schema.tables WHERE table_name=%1 and table_schema=%2" ) .arg( QgsPostgresConn::quotedValue( tableName ), QgsPostgresConn::quotedValue( schemaName ) ) ); QgsPostgresResult res( conn.PQexec( sql ) ); return res.PQgetvalue( 0, 0 ).toInt() > 0; } QStringList QgsPostgresProjectStorage::listProjects( const QString &uri ) { QStringList lst; QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) return lst; QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) return lst; if ( _projectsTableExists( *conn, projectUri.schemaName ) ) { QString sql( QStringLiteral( "SELECT name FROM %1.qgis_projects" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ) ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { int count = result.PQntuples(); for ( int i = 0; i < count; ++i ) { QString name = result.PQgetvalue( i, 0 ); lst << name; } } } QgsPostgresConnPool::instance()->releaseConnection( conn ); return lst; } bool QgsPostgresProjectStorage::readProject( const QString &uri, QIODevice *device, QgsReadWriteContext &context ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) { context.pushMessage( QObject::tr( "Invalid URI for PostgreSQL provider: " ) + uri, Qgis::Critical ); return false; } QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) { context.pushMessage( QObject::tr( "Could not connect to the database: " ) + projectUri.connInfo.connectionInfo( false ), Qgis::Critical ); return false; } if ( !_projectsTableExists( *conn, projectUri.schemaName ) ) { context.pushMessage( QObject::tr( "Table qgis_projects does not exist or it is not accessible." ), Qgis::Critical ); QgsPostgresConnPool::instance()->releaseConnection( conn ); return false; } bool ok = false; QString sql( QStringLiteral( "SELECT content FROM %1.qgis_projects WHERE name = %2" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ) ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { if ( result.PQntuples() == 1 ) { // TODO: would be useful to have QByteArray version of PQgetvalue to avoid bytearray -> string -> bytearray conversion QString hexEncodedContent( result.PQgetvalue( 0, 0 ) ); QByteArray binaryContent( QByteArray::fromHex( hexEncodedContent.toUtf8() ) ); device->write( binaryContent ); device->seek( 0 ); ok = true; } else { context.pushMessage( QObject::tr( "The project '%1' does not exist in schema '%2'." ).arg( projectUri.projectName, projectUri.schemaName ), Qgis::Critical ); } } QgsPostgresConnPool::instance()->releaseConnection( conn ); return ok; } bool QgsPostgresProjectStorage::writeProject( const QString &uri, QIODevice *device, QgsReadWriteContext &context ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) { context.pushMessage( QObject::tr( "Invalid URI for PostgreSQL provider: " ) + uri, Qgis::Critical ); return false; } QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) { context.pushMessage( QObject::tr( "Could not connect to the database: " ) + projectUri.connInfo.connectionInfo( false ), Qgis::Critical ); return false; } if ( !_projectsTableExists( *conn, projectUri.schemaName ) ) { // try to create projects table QString sql = QStringLiteral( "CREATE TABLE %1.qgis_projects(name TEXT PRIMARY KEY, metadata JSONB, content BYTEA)" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ) ); QgsPostgresResult res( conn->PQexec( sql ) ); if ( res.PQresultStatus() != PGRES_COMMAND_OK ) { QString errCause = QObject::tr( "Unable to save project. It's not possible to create the destination table on the database. Maybe this is due to database permissions (user=%1). Please contact your database admin." ).arg( projectUri.connInfo.username() ); context.pushMessage( errCause, Qgis::Critical ); QgsPostgresConnPool::instance()->releaseConnection( conn ); return false; } } // read from device and write to the table QByteArray content = device->readAll(); QString metadataExpr = QStringLiteral( "(%1 || (now() at time zone 'utc')::text || %2 || current_user || %3)::jsonb" ).arg( QgsPostgresConn::quotedValue( "{ \"last_modified_time\": \"" ), QgsPostgresConn::quotedValue( "\", \"last_modified_user\": \"" ), QgsPostgresConn::quotedValue( "\" }" ) ); // TODO: would be useful to have QByteArray version of PQexec() to avoid bytearray -> string -> bytearray conversion QString sql( "INSERT INTO %1.qgis_projects VALUES (%2, %3, E'\\\\x" ); sql = sql.arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ), metadataExpr // no need to quote: already quoted ); sql += QString::fromAscii( content.toHex() ); sql += "') ON CONFLICT (name) DO UPDATE SET content = EXCLUDED.content, metadata = EXCLUDED.metadata;"; QgsPostgresResult res( conn->PQexec( sql ) ); if ( res.PQresultStatus() != PGRES_COMMAND_OK ) { QString errCause = QObject::tr( "Unable to insert or update project (project=%1) in the destination table on the database. Maybe this is due to table permissions (user=%2). Please contact your database admin." ).arg( projectUri.projectName, projectUri.connInfo.username() ); context.pushMessage( errCause, Qgis::Critical ); QgsPostgresConnPool::instance()->releaseConnection( conn ); return false; } QgsPostgresConnPool::instance()->releaseConnection( conn ); return true; } bool QgsPostgresProjectStorage::removeProject( const QString &uri ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) return false; QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) return false; bool removed = false; if ( _projectsTableExists( *conn, projectUri.schemaName ) ) { QString sql( QStringLiteral( "DELETE FROM %1.qgis_projects WHERE name = %2" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ) ) ); QgsPostgresResult res( conn->PQexec( sql ) ); removed = res.PQresultStatus() == PGRES_COMMAND_OK; } QgsPostgresConnPool::instance()->releaseConnection( conn ); return removed; } bool QgsPostgresProjectStorage::readProjectStorageMetadata( const QString &uri, QgsProjectStorage::Metadata &metadata ) { QgsPostgresProjectUri projectUri = decodeUri( uri ); if ( !projectUri.valid ) return false; QgsPostgresConn *conn = QgsPostgresConnPool::instance()->acquireConnection( projectUri.connInfo.connectionInfo( false ) ); if ( !conn ) return false; bool ok = false; QString sql( QStringLiteral( "SELECT metadata FROM %1.qgis_projects WHERE name = %2" ).arg( QgsPostgresConn::quotedIdentifier( projectUri.schemaName ), QgsPostgresConn::quotedValue( projectUri.projectName ) ) ); QgsPostgresResult result( conn->PQexec( sql ) ); if ( result.PQresultStatus() == PGRES_TUPLES_OK ) { if ( result.PQntuples() == 1 ) { metadata.name = projectUri.projectName; QString metadataStr = result.PQgetvalue( 0, 0 ); QJsonDocument doc( QJsonDocument::fromJson( metadataStr.toUtf8() ) ); ok = _parseMetadataDocument( doc, metadata ); } } QgsPostgresConnPool::instance()->releaseConnection( conn ); return ok; } #ifdef HAVE_GUI #include "qgspostgresprojectstoragedialog.h" QString QgsPostgresProjectStorage::visibleName() { return QObject::tr( "PostgreSQL" ); } QString QgsPostgresProjectStorage::showLoadGui() { QgsPostgresProjectStorageDialog dlg( false ); if ( !dlg.exec() ) return QString(); return dlg.currentProjectUri(); } QString QgsPostgresProjectStorage::showSaveGui() { QgsPostgresProjectStorageDialog dlg( true ); if ( !dlg.exec() ) return QString(); return dlg.currentProjectUri(); } #endif QString QgsPostgresProjectStorage::encodeUri( const QgsPostgresProjectUri &postUri ) { QUrl u; QUrlQuery urlQuery; u.setScheme( "postgresql" ); u.setHost( postUri.connInfo.host() ); if ( !postUri.connInfo.port().isEmpty() ) u.setPort( postUri.connInfo.port().toInt() ); u.setUserName( postUri.connInfo.username() ); u.setPassword( postUri.connInfo.password() ); if ( !postUri.connInfo.service().isEmpty() ) urlQuery.addQueryItem( "service", postUri.connInfo.service() ); if ( !postUri.connInfo.authConfigId().isEmpty() ) urlQuery.addQueryItem( "authcfg", postUri.connInfo.authConfigId() ); if ( postUri.connInfo.sslMode() != QgsDataSourceUri::SslPrefer ) urlQuery.addQueryItem( "sslmode", QgsDataSourceUri::encodeSslMode( postUri.connInfo.sslMode() ) ); urlQuery.addQueryItem( "dbname", postUri.connInfo.database() ); urlQuery.addQueryItem( "schema", postUri.schemaName ); if ( !postUri.projectName.isEmpty() ) urlQuery.addQueryItem( "project", postUri.projectName ); u.setQuery( urlQuery ); return QString::fromUtf8( u.toEncoded() ); } QgsPostgresProjectUri QgsPostgresProjectStorage::decodeUri( const QString &uri ) { QUrl u = QUrl::fromEncoded( uri.toUtf8() ); QUrlQuery urlQuery( u.query() ); QgsPostgresProjectUri postUri; postUri.valid = u.isValid(); QString host = u.host(); QString port = u.port() != -1 ? QString::number( u.port() ) : QString(); QString username = u.userName(); QString password = u.password(); QgsDataSourceUri::SslMode sslMode = QgsDataSourceUri::decodeSslMode( urlQuery.queryItemValue( "sslmode" ) ); QString authConfigId = urlQuery.queryItemValue( "authcfg" ); QString dbName = urlQuery.queryItemValue( "dbname" ); QString service = urlQuery.queryItemValue( "service" ); if ( !service.isEmpty() ) postUri.connInfo.setConnection( service, dbName, username, password, sslMode, authConfigId ); else postUri.connInfo.setConnection( host, port, dbName, username, password, sslMode, authConfigId ); postUri.schemaName = urlQuery.queryItemValue( "schema" ); postUri.projectName = urlQuery.queryItemValue( "project" ); return postUri; }
37.317784
278
0.672969
dyna-mis
2b9d7e925eb9565282276d2ef7e186d71bfa2bba
16,851
cc
C++
tests/ut/cpp/dataset/c_api_audio_a_to_q_test.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
null
null
null
tests/ut/cpp/dataset/c_api_audio_a_to_q_test.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
null
null
null
tests/ut/cpp/dataset/c_api_audio_a_to_q_test.cc
LottieWang/mindspore
1331c7e432fb691d1cfa625ab7cc7451dcfc7ce0
[ "Apache-2.0" ]
null
null
null
/** * Copyright 2021 Huawei Technologies Co., Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "common/common.h" #include "include/api/types.h" #include "utils/log_adapter.h" #include "minddata/dataset/include/dataset/audio.h" #include "minddata/dataset/include/dataset/datasets.h" #include "minddata/dataset/include/dataset/execute.h" #include "minddata/dataset/include/dataset/transforms.h" using namespace mindspore::dataset; using mindspore::LogStream; using mindspore::ExceptionType::NoExceptionType; using mindspore::MsLogLevel::INFO; using namespace std; class MindDataTestPipeline : public UT::DatasetOpTesting { protected: }; TEST_F(MindDataTestPipeline, TestAmplitudeToDBPipeline) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto amplitude_to_db_op = audio::AmplitudeToDB(); ds = ds->Map({amplitude_to_db_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, TestAmplitudeToDBWrongArgs) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto amplitude_to_db_op = audio::AmplitudeToDB(ScaleType::kPower, 1.0, -1e-10, 80.0); ds = ds->Map({amplitude_to_db_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); // Expect failure EXPECT_EQ(iter, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBandBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BandBiquadOp = audio::BandBiquad(44100, 200.0); ds = ds->Map({BandBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBandBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto band_biquad_op_01 = audio::BandBiquad(0, 200); ds01 = ds->Map({band_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto band_biquad_op_02 = audio::BandBiquad(44100, 200, 0); ds02 = ds->Map({band_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestAllpassBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto AllpassBiquadOp = audio::AllpassBiquad(44100, 200.0); ds = ds->Map({AllpassBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by allpassbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestAllpassBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "Sample_rate_ is zero."; auto allpass_biquad_op_01 = audio::AllpassBiquad(0, 200.0, 0.707); ds01 = ds->Map({allpass_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto allpass_biquad_op_02 = audio::AllpassBiquad(44100, 200, 0); ds02 = ds->Map({allpass_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBandpassBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BandpassBiquadOp = audio::BandpassBiquad(44100, 200.0); ds = ds->Map({BandpassBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandpassbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBandpassBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto bandpass_biquad_op_01 = audio::BandpassBiquad(0, 200); ds01 = ds->Map({bandpass_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto bandpass_biquad_op_02 = audio::BandpassBiquad(44100, 200, 0); ds02 = ds->Map({bandpass_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBandrejectBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BandrejectBiquadOp = audio::BandrejectBiquad(44100, 200.0); ds = ds->Map({BandrejectBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandrejectbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBandrejectBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto bandreject_biquad_op_01 = audio::BandrejectBiquad(0, 200); ds01 = ds->Map({bandreject_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto bandreject_biquad_op_02 = audio::BandrejectBiquad(44100, 200, 0); ds02 = ds->Map({bandreject_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, Level0_TestBassBiquad001) { MS_LOG(INFO) << "Basic Function Test"; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto BassBiquadOp = audio::BassBiquad(44100, 50, 200.0); ds = ds->Map({BassBiquadOp}); EXPECT_NE(ds, nullptr); // Filtered waveform by bassbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, Level0_TestBassBiquad002) { MS_LOG(INFO) << "Wrong Arg."; std::shared_ptr<SchemaObj> schema = Schema(); // Original waveform ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); std::shared_ptr<Dataset> ds01; std::shared_ptr<Dataset> ds02; EXPECT_NE(ds, nullptr); // Check sample_rate MS_LOG(INFO) << "sample_rate is zero."; auto bass_biquad_op_01 = audio::BassBiquad(0, 50, 200.0); ds01 = ds->Map({bass_biquad_op_01}); EXPECT_NE(ds01, nullptr); std::shared_ptr<Iterator> iter01 = ds01->CreateIterator(); EXPECT_EQ(iter01, nullptr); // Check Q_ MS_LOG(INFO) << "Q_ is zero."; auto bass_biquad_op_02 = audio::BassBiquad(44100, 50, 200.0, 0); ds02 = ds->Map({bass_biquad_op_02}); EXPECT_NE(ds02, nullptr); std::shared_ptr<Iterator> iter02 = ds02->CreateIterator(); EXPECT_EQ(iter02, nullptr); } TEST_F(MindDataTestPipeline, TestAnglePipeline) { MS_LOG(INFO) << "Doing MindDataTestPipeline-TestAnglePipeline"; std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("complex", mindspore::DataType::kNumberTypeFloat32, {2, 2})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto angle_op = audio::Angle(); ds = ds->Map({angle_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {2}; int i = 0; while (row.size() != 0) { auto col = row["complex"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 1); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, TestAnglePipelineError) { MS_LOG(INFO) << "Doing MindDataTestPipeline-TestAnglePipelineError"; std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("complex", mindspore::DataType::kNumberTypeFloat32, {3, 2, 1})); std::shared_ptr<Dataset> ds = RandomData(4, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto angle_op = audio::Angle(); ds = ds->Map({angle_op}); EXPECT_NE(ds, nullptr); std::shared_ptr<Iterator> iter = ds->CreateIterator(); std::unordered_map<std::string, mindspore::MSTensor> row; EXPECT_ERROR(iter->GetNextRow(&row)); } TEST_F(MindDataTestPipeline, TestFrequencyMaskingPipeline) { MS_LOG(INFO) << "Doing TestFrequencyMasking Pipeline."; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {200, 200})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto frequencymasking = audio::FrequencyMasking(true, 6); ds = ds->Map({frequencymasking}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); EXPECT_NE(ds, nullptr); std::unordered_map<std::string, mindspore::MSTensor> row; ASSERT_OK(iter->GetNextRow(&row)); std::vector<int64_t> expected = {200, 200}; int i = 0; while (row.size() != 0) { auto col = row["inputData"]; ASSERT_EQ(col.Shape(), expected); ASSERT_EQ(col.Shape().size(), 2); ASSERT_EQ(col.DataType(), mindspore::DataType::kNumberTypeFloat32); ASSERT_OK(iter->GetNextRow(&row)); i++; } EXPECT_EQ(i, 50); iter->Stop(); } TEST_F(MindDataTestPipeline, TestFrequencyMaskingWrongArgs) { MS_LOG(INFO) << "Doing TestFrequencyMasking with wrong args."; // Original waveform std::shared_ptr<SchemaObj> schema = Schema(); ASSERT_OK(schema->add_column("inputData", mindspore::DataType::kNumberTypeFloat32, {20, 20})); std::shared_ptr<Dataset> ds = RandomData(50, schema); EXPECT_NE(ds, nullptr); ds = ds->SetNumWorkers(4); EXPECT_NE(ds, nullptr); auto frequencymasking = audio::FrequencyMasking(true, -100); ds = ds->Map({frequencymasking}); EXPECT_NE(ds, nullptr); // Filtered waveform by bandbiquad std::shared_ptr<Iterator> iter = ds->CreateIterator(); // Expect failure EXPECT_EQ(iter, nullptr); }
30.471971
98
0.699958
LottieWang
2b9e3b7072aa6eac36c65a288f0b47b2c92fdab0
2,406
cpp
C++
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
2
2018-01-02T14:07:54.000Z
2021-07-05T08:05:21.000Z
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
null
null
null
Examples/Chess/src/chess-application.cpp
JoachimHerber/Bembel-Game-Engine
5c4e46c5a15356af6e997038a8d76065b0691b50
[ "MIT" ]
null
null
null
#include "chess-application.h" #include <GLFW/glfw3.h> #include <chrono> #include <iostream> #include <random> #include "selection-rendering-stage.h" using namespace bembel; ChessApplication::ChessApplication() : kernel::Application() { this->graphic_system = this->kernel->addSystem<graphics::GraphicSystem>(); this->graphic_system->getRendertingStageFactory() .registerDefaultObjectGenerator<SelectionRenderingStage>("SelectionRenderingStage"); auto& event_mgr = this->kernel->getEventManager(); event_mgr.addHandler<kernel::WindowShouldCloseEvent>(this); event_mgr.addHandler<kernel::FrameBufferResizeEvent>(this); } ChessApplication::~ChessApplication() { } bool ChessApplication::init() { BEMBEL_LOG_INFO() << "Loading Application Settings"; if(!this->kernel->loadSetting("chess/config.xml")) return false; auto pipline = this->graphic_system->getRenderingPipelines()[0].get(); this->camera = std::make_shared<CameraControle>(this->kernel->getEventManager(), pipline->getCamera()); BEMBEL_LOG_INFO() << "Initalizing Game"; this->chess_game = std::make_unique<ChessGame>( this->kernel->getAssetManager(), this->kernel->getEventManager(), *(this->graphic_system)); this->chess_game->resetChessBoard(); this->chess_game->resetChessBoard(); BEMBEL_LOG_INFO() << "Initalizing Camera"; pipline->setScene(this->chess_game->getScene()); this->camera->setCameraOffset(glm::vec3(8, 0.5f, 8)); this->camera->enableManualControle(true); BEMBEL_LOG_INFO() << "Initalizing Systems"; this->kernel->initSystems(); return true; } void ChessApplication::cleanup() { this->chess_game.reset(); this->kernel->shutdownSystems(); this->kernel->getAssetManager().deleteUnusedAssets(); this->kernel->getDisplayManager().closeOpenWindows(); } void ChessApplication::update(double time) { this->camera->update(time); this->chess_game->update(time); } void ChessApplication::handleEvent(const kernel::WindowShouldCloseEvent& event) { this->quit(); } void ChessApplication::handleEvent(const kernel::FrameBufferResizeEvent& event) { auto pipline = this->graphic_system->getRenderingPipelines()[0].get(); pipline->setResulution(event.size); pipline->getCamera()->setUpProjection( 60.0f * 3.14159265359f / 180.0f, event.size.x / event.size.y, 0.1f, 1000.0f); }
32.08
99
0.715711
JoachimHerber
2ba7bcde3e5dfc15bf94af1a4d55546f3cfbba51
14,693
cpp
C++
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
macros/phi_correlation_he6_carbon_compare.cpp
serjinio/thesis_ana
633a61dee56cf2cf4dcb67997ac87338537fb578
[ "MIT" ]
null
null
null
#include <iostream> #include "init_6he_ds.hpp" #include "TChain.h" void hdraw(TTree& tree, TString name, TString draw_cmd, TString binning, TCut cuts = "", TString title = "", TString xaxis_title = "", TString yaxis_title = "", TString draw_opts = "colz") { TString hstr = TString::Format("%s >>%s%s", draw_cmd.Data(), name.Data(), binning.Data()); tree.Draw(hstr, cuts, draw_opts); TH1 *hist = static_cast<TH1*>(gPad->GetPrimitive(name)); if (yaxis_title != "") { hist->GetYaxis()->SetTitle(yaxis_title); } if (xaxis_title != "") { hist->GetXaxis()->SetTitle(xaxis_title); } if (title != "") { hist->SetTitle(title); } } void phi_correlation_he6_carbon_compare() { init_dataset(); init_carbon_dataset(); std::cout << "Total number of events for he6: " << g_chain_total.GetEntries() << std::endl; std::cout << "Total number of events for carbon: " << g_c_chain.GetEntries() << std::endl; TCut p_angle_sn_cut = "p_theta*57.3>65 && p_theta*57.3<68"; TCut p_angle_acceptance_cut = "p_theta*57.3>55 && p_theta*57.3<70"; TCut phi_corr_cut_1d = "abs(abs(p_phi*57.3-s1dc_phi*57.3) - 180) < 8"; TCut target_cut{"tgt_up_xpos*tgt_up_xpos + tgt_up_ypos*tgt_up_ypos < 81"}; TCut vertex_zpos_cut{"es_vertex_zpos > -30 && es_vertex_zpos < 30"}; // distribution on HODF plastics // pla IDs [7,9]: beam / beam stopper // pla ID [0,4]: left scattering 6He // pla ID [11,14]: right scattering 6He // pla ID [17,23]: 4He (from inelastic shannel) std::string hodf_cut_str = ""; for (int i = 0; i < 5; i++) { hodf_cut_str += TString::Format("(hodf_q[%i]>14 && hodf_q[%i]<17) ", i, i); if (i != 4) hodf_cut_str += "|| "; } hodf_cut_str += "|| "; for (int i = 11; i < 15; i++) { hodf_cut_str += TString::Format("(hodf_q[%i]>14 && hodf_q[%i]<17) ", i, i); if (i != 14) hodf_cut_str += "|| "; } cout << "HODF cut:\n" << hodf_cut_str << std::endl; TCut hodf_cut{hodf_cut_str.c_str()}; TFile hist_out("out/phi_correlation_he6_carbon_compare.root", "RECREATE"); TCanvas c1("c1"); gStyle->SetOptStat(1111111); // // proton phi // c1.Clear(); // c1.Divide(2); // c1.cd(1); // hdraw(g_chain_total, "esl_p_phi", "esl_p_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left, proton phi angle", // "Proton #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "esr_p_phi", "esr_p_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right, proton phi angle", // "Proton #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // He phi // c1.Clear(); // c1.Divide(1); // c1.cd(1); // hdraw(g_chain_total, "fragment_phi_s1dc", "s1dc_phi*57.3", "(360,-180,180)", // "triggers[5]==1" && target_cut && hodf_cut, // "Fragment azimuthal angle", // "Fragment #phi angle [lab. deg.]", "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // phi 2d corr ESPRI L&R // c1.Clear(); // c1.Divide(2); // c1.cd(1); // hdraw(g_chain_total, "esl_phi_corr", "esl_p_phi*57.3:s1dc_phi*57.3", // "(100,60,120,100,-120,-60)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left, phi correlation", // "Fragment #phi angle [lab. deg.]", // "Proton #phi angle [lab. deg.]"); // c1.cd(2); // hdraw(g_chain_total, "esr_phi_corr", "esr_p_phi*57.3:s1dc_phi*57.3", // "(100,-120,-60,100,60,120)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right, phi correlation", // "Fragment #phi angle [lab. deg.]", // "Proton #phi angle [lab. deg.]"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // ESPRI L&R phi corr 1d // c1.Clear(); // c1.Divide(1,2); // c1.cd(1); // hdraw(g_chain_total, "esl_phi_corr_1d", "esl_p_phi*57.3-s1dc_phi*57.3", // "(300,-350,-10)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left: P_{#phi} - He_{#phi}", // "P_{#phi} - He_{#phi} [deg]", // "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "esr_phi_corr_1d", "esr_p_phi*57.3-s1dc_phi*57.3", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI right: P_{#phi} - He_{#phi}", // "P_{#phi} - He_{#phi} [deg]", // "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // ESPRI total - phi, hodf cuts // c1.Clear(); // c1.Divide(1,2); // c1.cd(1); // hdraw(g_chain_total, "tot_phi_corr_1d", "abs(p_phi*57.3-s1dc_phi*57.3)", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut, // "ESPRI left & right: P_{#phi} - He_{#phi} (no #phi cut)", // "P_{#phi} - He_{#phi} [deg.]", // "Counts"); // //gPad->SetLogy(); // c1.cd(2); // hdraw(g_chain_total, "tot_phi_corr_1d_cut", "abs(p_phi*57.3-s1dc_phi*57.3)", // "(300,10,350)", // "triggers[5]==1" && target_cut && hodf_cut && // phi_corr_cut_1d, // "ESPRI left & right: P_{#phi} - He_{#phi} (#phi cut)", // "P_{#phi} - He_{#phi} [deg.]", // "Counts"); // //gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // polar corr with diff. cuts // // HODF cut - He6 vs. carbon // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_phi_hodf", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && hodf_cut, // "#theta angle correlation for 6he-p (tgt, hodf cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_phi_hodf2", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && hodf_cut, // "#theta angle correlation for 6he-C (tgt, hodf cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // tgt,phi,hodf cut - He6 vs. carbon // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_tgt_phi1d_hodf", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && // phi_corr_cut_1d && hodf_cut, // "#theta angle corr.: 6he-p (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_tgt_phi1d_hodf2", "p_theta*57.3:s1dc_theta*57.3", // "(200,0.1,10,200,50,75)", // "triggers[5]==1" && target_cut && // phi_corr_cut_1d && hodf_cut, // "#theta angle corr.: 6he-C (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Proton #theta angle [lab. deg.]", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // 1d hist theta corr S/N // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_tgt_phi1d_hodf_1d", "s1dc_theta*57.3", // "(200,0,10)", // "triggers[5]==1" && target_cut && // hodf_cut && phi_corr_cut_1d && p_angle_sn_cut, // "#theta angle corr.: 6he-p (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Counts", "colz"); // c1.cd(2); // hdraw(g_c_chain, "polar_tgt_phi1d_hodf_1d2", "s1dc_theta*57.3", // "(200,0,10)", // "triggers[5]==1" && target_cut && // hodf_cut && phi_corr_cut_1d && p_angle_sn_cut, // "#theta angle corr.: 6he-C (tgt, hodf, phi cuts)", // "Fragment #theta angle [lab. deg.]", // "Counts", "colz"); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // theta exp - theta_theor 2d corr c1.Clear(); c1.Divide(2,1); c1.cd(1); hdraw(g_chain_total, "polar_t_tgt_hodf_phi", "p_theta*57.3:s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8,200,50,75)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Proton #theta angle [lab. deg.]", "colz"); c1.cd(2); hdraw(g_c_chain, "polar_t_tgt_hodf_phi2", "p_theta*57.3:s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8,200,50,75)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Proton #theta angle [lab. deg.]", "colz"); c1.Print("out/phi_correlation_he6_carbon_compare.pdf(", "pdf"); // // theta exp - theta_theor 1d corr // c1.Clear(); // c1.Divide(2,1); // c1.cd(1); // hdraw(g_chain_total, "polar_t_1d", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "colz"); // gPad->SetLogy(); // c1.cd(2); // hdraw(g_c_chain, "polar_t_1d2", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "colz"); // gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // // theta exp - theta_theor 1d corr + carbon BG // c1.Clear(); // c1.Divide(1); // c1.cd(1); // g_chain_total.SetLineColor(kBlue); // hdraw(g_chain_total, "polar_t_1d_hc1", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts"); // g_c_chain.SetLineColor(kRed); // hdraw(g_c_chain, "polar_t_1d_hc2", // "s1dc_theta*57.3 - he_theta_theor*57.3", // "(200,-8,8)", // "triggers[5]==1" && target_cut && // hodf_cut && p_angle_acceptance_cut, // "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf cuts)", // "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", // "Counts", "SAME"); // gPad->SetLogy(); // c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr + phi cut c1.Clear(); c1.Divide(2,1); c1.cd(1); hdraw(g_chain_total, "polar_t_1d_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "colz"); gPad->SetLogy(); c1.cd(2); g_c_chain.SetLineColor(kBlue); hdraw(g_c_chain, "polar_t_1d2_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "colz"); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr + phi cut + carbon BG c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); hdraw(g_chain_total, "polar_t_1d_hc1_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts"); g_c_chain.SetLineColor(kRed); hdraw(g_c_chain, "polar_t_1d_hc2_phi", "s1dc_theta*57.3 - he_theta_theor*57.3", "(200,-8,8)", "triggers[5]==1" && target_cut && hodf_cut && phi_corr_cut_1d && p_angle_acceptance_cut, "#theta angle corr.: #theta_{exp}-#theta_{theor} for 6he-p and 6he-C (tgt, hodf, phi cuts)", "Fragment: #theta_{exp} - #theta_{theor} [lab. deg.]", "Counts", "SAME"); TH1* he6_polar = static_cast<TH1*>(gPad->GetPrimitive("polar_t_1d_hc1_phi")); TH1* carbon_polar = static_cast<TH1*>(gPad->GetPrimitive("polar_t_1d_hc2_phi")); carbon_polar->Scale(3); he6_polar->Draw(); carbon_polar->SetLineColor(kRed); carbon_polar->Draw("SAME"); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); // theta exp - theta_theor 1d corr - carbon BG c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); g_c_chain.SetLineColor(kBlue); TH1* he6_polar_min_bg = (TH1*)he6_polar->Clone(); he6_polar_min_bg->Add(carbon_polar, -1); he6_polar_min_bg->SetTitle("#theta angle corr.: #theta_{exp}-#theta_{theor} for " "6he-p - 6he-C (tgt, hodf, phi cuts)"); he6_polar_min_bg->Draw(); gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); c1.Clear(); c1.Divide(1); c1.cd(1); he6_polar->Draw(); carbon_polar->SetLineColor(kRed); carbon_polar->Draw("SAME"); //gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf", "pdf"); c1.Clear(); c1.Divide(1); c1.cd(1); g_chain_total.SetLineColor(kBlue); g_c_chain.SetLineColor(kBlue); he6_polar_min_bg->Draw(); //gPad->SetLogy(); c1.Print("out/phi_correlation_he6_carbon_compare.pdf)", "pdf"); hist_out.Write(); hist_out.Close(); }
38.064767
100
0.574355
serjinio
2ba8b7704ef008a72827b0bfff98fe3808468963
10,557
cpp
C++
src/drivers/milliped.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-01-25T20:16:33.000Z
2021-01-25T20:16:33.000Z
src/drivers/milliped.cpp
pierrelouys/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
1
2021-05-24T20:28:35.000Z
2021-05-25T14:44:54.000Z
src/drivers/milliped.cpp
PSP-Archive/PSP-MAME4ALL
54374b0579b7e2377f015ac155d8f519addfaa1a
[ "Unlicense" ]
null
null
null
/*************************************************************************** Millipede memory map (preliminary) 0400-040F POKEY 1 0800-080F POKEY 2 1000-13BF SCREEN RAM (8x8 TILES, 32x30 SCREEN) 13C0-13CF SPRITE IMAGE OFFSETS 13D0-13DF SPRITE HORIZONTAL OFFSETS 13E0-13EF SPRITE VERTICAL OFFSETS 13F0-13FF SPRITE COLOR OFFSETS 2000 BIT 1-4 trackball BIT 5 IS P1 FIRE BIT 6 IS P1 START BIT 7 IS VBLANK 2001 BIT 1-4 trackball BIT 5 IS P2 FIRE BIT 6 IS P2 START BIT 7,8 (?) 2010 BIT 1 IS P1 RIGHT BIT 2 IS P1 LEFT BIT 3 IS P1 DOWN BIT 4 IS P1 UP BIT 5 IS SLAM, LEFT COIN, AND UTIL COIN BIT 6,7 (?) BIT 8 IS RIGHT COIN 2030 earom read 2480-249F COLOR RAM 2500-2502 Coin counters 2503-2504 LEDs 2505-2507 Coin door lights ?? 2600 INTERRUPT ACKNOWLEDGE 2680 CLEAR WATCHDOG 2700 earom control 2780 earom write 4000-7FFF GAME CODE Known issues: * The dipswitches under $2000 aren't fully emulated. There must be some sort of trick to reading them properly. *************************************************************************/ #include "driver.h" #include "vidhrdw/generic.h" #include "machine/atari_vg.h" void milliped_paletteram_w(int offset,int data); void milliped_vh_screenrefresh(struct osd_bitmap *bitmap,int full_refresh); int milliped_IN0_r(int offset); /* JB 971220 */ int milliped_IN1_r(int offset); /* JB 971220 */ void milliped_input_select_w(int offset, int data); void milliped_led_w (int offset, int data) { osd_led_w (offset, ~(data >> 7)); } static struct MemoryReadAddress readmem[] = { { 0x0000, 0x03ff, MRA_RAM }, { 0x0400, 0x040f, pokey1_r }, { 0x0800, 0x080f, pokey2_r }, { 0x1000, 0x13ff, MRA_RAM }, { 0x2000, 0x2000, milliped_IN0_r }, /* JB 971220 */ { 0x2001, 0x2001, milliped_IN1_r }, /* JB 971220 */ { 0x2010, 0x2010, input_port_2_r }, { 0x2011, 0x2011, input_port_3_r }, { 0x2030, 0x2030, atari_vg_earom_r }, { 0x4000, 0x7fff, MRA_ROM }, { 0xf000, 0xffff, MRA_ROM }, /* for the reset / interrupt vectors */ { -1 } /* end of table */ }; static struct MemoryWriteAddress writemem[] = { { 0x0000, 0x03ff, MWA_RAM }, { 0x0400, 0x040f, pokey1_w }, { 0x0800, 0x080f, pokey2_w }, { 0x1000, 0x13ff, videoram_w, &videoram, &videoram_size }, { 0x13c0, 0x13ff, MWA_RAM, &spriteram }, { 0x2480, 0x249f, milliped_paletteram_w, &paletteram }, { 0x2680, 0x2680, watchdog_reset_w }, { 0x2600, 0x2600, MWA_NOP }, /* IRQ ack */ { 0x2500, 0x2502, coin_counter_w }, { 0x2503, 0x2504, milliped_led_w }, { 0x2505, 0x2505, milliped_input_select_w }, { 0x2780, 0x27bf, atari_vg_earom_w }, { 0x2700, 0x2700, atari_vg_earom_ctrl }, { 0x2505, 0x2507, MWA_NOP }, /* coin door lights? */ { 0x4000, 0x73ff, MWA_ROM }, { -1 } /* end of table */ }; INPUT_PORTS_START( input_ports ) PORT_START /* IN0 $2000 */ /* see port 6 for x trackball */ PORT_DIPNAME (0x03, 0x00, "Language", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "English" ) PORT_DIPSETTING ( 0x01, "German" ) PORT_DIPSETTING ( 0x02, "French" ) PORT_DIPSETTING ( 0x03, "Spanish" ) PORT_DIPNAME (0x0c, 0x04, "Bonus", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "0" ) PORT_DIPSETTING ( 0x04, "0 1x" ) PORT_DIPSETTING ( 0x08, "0 1x 2x" ) PORT_DIPSETTING ( 0x0c, "0 1x 2x 3x" ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_START1 ) PORT_BIT ( 0x40, IP_ACTIVE_HIGH, IPT_VBLANK ) PORT_BIT ( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START /* IN1 $2001 */ /* see port 7 for y trackball */ PORT_BIT ( 0x03, IP_ACTIVE_HIGH, IPT_UNKNOWN ) /* JB 971220 */ PORT_DIPNAME (0x04, 0x00, "Credit Minimum", IP_KEY_NONE ) /* JB 971220 */ PORT_DIPSETTING ( 0x00, "1" ) PORT_DIPSETTING ( 0x04, "2" ) PORT_DIPNAME (0x08, 0x00, "Coin Counters", IP_KEY_NONE ) /* JB 971220 */ PORT_DIPSETTING ( 0x00, "1" ) PORT_DIPSETTING ( 0x08, "2" ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_BUTTON1 | IPF_COCKTAIL ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_START2 ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x80, IP_ACTIVE_HIGH, IPT_UNKNOWN ) PORT_START /* IN2 $2010 */ PORT_BIT ( 0x01, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_TILT ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_COIN1 ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_COIN2 ) PORT_BIT ( 0x80, IP_ACTIVE_LOW, IPT_COIN3 ) PORT_START /* IN3 $2011 */ PORT_BIT ( 0x01, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x02, IP_ACTIVE_LOW, IP_KEY_NONE ) PORT_BIT ( 0x04, IP_ACTIVE_LOW, IPT_JOYSTICK_DOWN | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT ( 0x08, IP_ACTIVE_LOW, IPT_JOYSTICK_UP | IPF_8WAY | IPF_COCKTAIL ) PORT_BIT ( 0x10, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x20, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BIT ( 0x40, IP_ACTIVE_LOW, IPT_UNKNOWN ) PORT_BITX( 0x80, 0x80, IPT_DIPSWITCH_NAME | IPF_TOGGLE, "Service Mode", OSD_KEY_F2, IP_JOY_NONE, 0 ) PORT_DIPSETTING( 0x80, "Off" ) PORT_DIPSETTING( 0x00, "On" ) PORT_START /* 4 */ /* DSW1 $0408 */ PORT_DIPNAME (0x01, 0x00, "Millipede Head", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x01, "Hard" ) PORT_DIPNAME (0x02, 0x00, "Beetle", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x02, "Hard" ) PORT_DIPNAME (0x0c, 0x04, "Lives", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "2" ) PORT_DIPSETTING ( 0x04, "3" ) PORT_DIPSETTING ( 0x08, "4" ) PORT_DIPSETTING ( 0x0c, "5" ) PORT_DIPNAME (0x30, 0x10, "Bonus Life", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "12000" ) PORT_DIPSETTING ( 0x10, "15000" ) PORT_DIPSETTING ( 0x20, "20000" ) PORT_DIPSETTING ( 0x30, "None" ) PORT_DIPNAME (0x40, 0x00, "Spider", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Easy" ) PORT_DIPSETTING ( 0x40, "Hard" ) PORT_DIPNAME (0x80, 0x00, "Starting Score Select", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "On" ) PORT_DIPSETTING ( 0x80, "Off" ) PORT_START /* 5 */ /* DSW2 $0808 */ PORT_DIPNAME (0x03, 0x02, "Coinage", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "Free Play" ) PORT_DIPSETTING ( 0x01, "1 Coin/2 Credits" ) PORT_DIPSETTING ( 0x02, "1 Coin/1 Credit" ) PORT_DIPSETTING ( 0x03, "2 Coins/1 Credit" ) PORT_DIPNAME (0x0c, 0x00, "Right Coin", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "*1" ) PORT_DIPSETTING ( 0x04, "*4" ) PORT_DIPSETTING ( 0x08, "*5" ) PORT_DIPSETTING ( 0x0c, "*6" ) PORT_DIPNAME (0x10, 0x00, "Left Coin", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "*1" ) PORT_DIPSETTING ( 0x10, "*2" ) PORT_DIPNAME (0xe0, 0x00, "Bonus Coins", IP_KEY_NONE ) PORT_DIPSETTING ( 0x00, "None" ) PORT_DIPSETTING ( 0x20, "3 credits/2 coins" ) PORT_DIPSETTING ( 0x40, "5 credits/4 coins" ) PORT_DIPSETTING ( 0x60, "6 credits/4 coins" ) PORT_DIPSETTING ( 0x80, "6 credits/5 coins" ) PORT_DIPSETTING ( 0xa0, "4 credits/3 coins" ) PORT_DIPSETTING ( 0xc0, "Demo mode" ) PORT_START /* IN6: FAKE - used for trackball-x at $2000 */ PORT_ANALOGX( 0xff, 0x00, IPT_TRACKBALL_X | IPF_REVERSE, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE, 4 ) PORT_START /* IN7: FAKE - used for trackball-y at $2001 */ PORT_ANALOGX( 0xff, 0x00, IPT_TRACKBALL_Y | IPF_REVERSE, 50, 10, 0, 0, IP_KEY_NONE, IP_KEY_NONE, IP_JOY_NONE, IP_JOY_NONE, 4 ) INPUT_PORTS_END static struct GfxLayout charlayout = { 8,8, /* 8*8 characters */ 256, /* 256 characters */ 2, /* 2 bits per pixel */ { 0, 256*8*8 }, /* the two bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8 }, 8*8 /* every char takes 8 consecutive bytes */ }; static struct GfxLayout spritelayout = { 8,16, /* 16*8 sprites */ 128, /* 64 sprites */ 2, /* 2 bits per pixel */ { 0, 128*16*8 }, /* the two bitplanes are separated */ { 0, 1, 2, 3, 4, 5, 6, 7 }, { 0*8, 1*8, 2*8, 3*8, 4*8, 5*8, 6*8, 7*8, 8*8, 9*8, 10*8, 11*8, 12*8, 13*8, 14*8, 15*8 }, 16*8 /* every sprite takes 16 consecutive bytes */ }; static struct GfxDecodeInfo gfxdecodeinfo[] = { { 1, 0x0000, &charlayout, 0, 4 }, /* use colors 0-15 */ { 1, 0x0000, &spritelayout, 16, 1 }, /* use colors 16-19 */ { -1 } /* end of array */ }; static struct POKEYinterface pokey_interface = { 2, /* 2 chips */ 1500000, /* 1.5 MHz??? */ 50, POKEY_DEFAULT_GAIN, NO_CLIP, /* The 8 pot handlers */ { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, { 0, 0 }, /* The allpot handler */ { input_port_4_r, input_port_5_r }, }; static struct MachineDriver machine_driver = { /* basic machine hardware */ { { CPU_M6502, 1500000, /* 1.5 Mhz ???? */ 0, readmem,writemem,0,0, interrupt,4 } }, 60, DEFAULT_REAL_60HZ_VBLANK_DURATION, /* frames per second, vblank duration */ 10, 0, /* video hardware */ 32*8, 32*8, { 0*8, 32*8-1, 0*8, 30*8-1 }, gfxdecodeinfo, 32, 32, 0, VIDEO_TYPE_RASTER|VIDEO_SUPPORTS_DIRTY|VIDEO_MODIFIES_PALETTE, 0, generic_vh_start, generic_vh_stop, milliped_vh_screenrefresh, /* sound hardware */ 0,0,0,0, { { SOUND_POKEY, &pokey_interface } } }; /*************************************************************************** Game driver(s) ***************************************************************************/ ROM_START( milliped_rom ) ROM_REGION(0x10000) /* 64k for code */ ROM_LOAD( "milliped.104", 0x4000, 0x1000, 0x40711675 ) ROM_LOAD( "milliped.103", 0x5000, 0x1000, 0xfb01baf2 ) ROM_LOAD( "milliped.102", 0x6000, 0x1000, 0x62e137e0 ) ROM_LOAD( "milliped.101", 0x7000, 0x1000, 0x46752c7d ) ROM_RELOAD( 0xf000, 0x1000 ) /* for the reset and interrupt vectors */ ROM_REGION_DISPOSE(0x1000) /* temporary space for graphics (disposed after conversion) */ ROM_LOAD( "milliped.106", 0x0000, 0x0800, 0xf4468045 ) ROM_LOAD( "milliped.107", 0x0800, 0x0800, 0x68c3437a ) ROM_END struct GameDriver milliped_driver = { __FILE__, 0, "milliped", "Millipede", "1982", "Atari", "Ivan Mackintosh\nNicola Salmoria\nJohn Butler\nAaron Giles\nBernd Wiebelt\nBrad Oliver", 0, &machine_driver, 0, milliped_rom, 0, 0, 0, 0, /* sound_prom */ input_ports, 0, 0, 0, ORIENTATION_ROTATE_270, atari_vg_earom_load, atari_vg_earom_save };
29.822034
134
0.637586
pierrelouys
ad9601f7ae49dc17671c16c6096ce479c6bbd639
9,600
cpp
C++
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
4
2018-07-03T14:21:39.000Z
2021-06-01T06:12:14.000Z
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
quake_framebuffer/quake_framebuffer/sv_move.cpp
WarlockD/quake-stm32
8414f407f6fc529bf9d5a371ed91c1ee1194679b
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 1996-1997 Id Software, Inc. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. */ // sv_move.c -- monster movement #include "icommon.h" #define STEPSIZE 18 /* ============= SV_CheckBottom Returns false if any part of the bottom of the entity is off an edge that is not a staircase. ============= */ int c_yes, c_no; qboolean SV_CheckBottom (edict_t *ent) { vec3_t mins, maxs, start, stop; trace_t trace; int x, y; float mid, bottom; VectorAdd (ent->v.origin, ent->v.mins, mins); VectorAdd (ent->v.origin, ent->v.maxs, maxs); // if all of the points under the corners are solid world, don't bother // with the tougher checks // the corners must be within 16 of the midpoint start[2] = mins[2] - 1; for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { start[0] = x ? maxs[0] : mins[0]; start[1] = y ? maxs[1] : mins[1]; if (SV_PointContents (start) != CONTENTS_SOLID) goto realcheck; } c_yes++; return true; // we got out easy realcheck: c_no++; // // check it for real... // start[2] = mins[2]; // the midpoint must be within 16 of the bottom start[0] = stop[0] = (mins[0] + maxs[0])*0.5f; start[1] = stop[1] = (mins[1] + maxs[1])*0.5f; stop[2] = start[2] - 2*STEPSIZE; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction == 1.0) return false; mid = bottom = trace.endpos[2]; // the corners must be within 16 of the midpoint for (x=0 ; x<=1 ; x++) for (y=0 ; y<=1 ; y++) { start[0] = stop[0] = x ? maxs[0] : mins[0]; start[1] = stop[1] = y ? maxs[1] : mins[1]; trace = SV_Move (start, vec3_origin, vec3_origin, stop, true, ent); if (trace.fraction != 1.0 && trace.endpos[2] > bottom) bottom = trace.endpos[2]; if (trace.fraction == 1.0 || mid - trace.endpos[2] > STEPSIZE) return false; } c_yes++; return true; } /* ============= SV_movestep Called by monster program code. The move will be adjusted for slopes and stairs, but if the move isn't possible, no move is done, false is returned, and vm.pr_global_struct->trace_normal is set to the normal of the blocking wall ============= */ qboolean SV_movestep (edict_t *ent, vec3_t move, qboolean relink) { float dz; vec3_t oldorg, neworg, end; trace_t trace; int i; edict_t *enemy; // try the move VectorCopy (ent->v.origin, oldorg); VectorAdd (ent->v.origin, move, neworg); // flying monsters don't step up if ( (int)ent->v.flags & (FL_SWIM | FL_FLY) ) { // try one move with vertical motion, then one without for (i=0 ; i<2 ; i++) { VectorAdd (ent->v.origin, move, neworg); enemy = ent->v.enemy; if (i == 0 && enemy != sv.worldedict) { dz = ent->v.origin[2] - ent->v.enemy->v.origin[2]; if (dz > 40) neworg[2] -= 8; if (dz < 30) neworg[2] += 8; } trace = SV_Move (ent->v.origin, ent->v.mins, ent->v.maxs, neworg, false, ent); if (trace.fraction == 1) { if ( ((int)ent->v.flags & FL_SWIM) && SV_PointContents(trace.endpos) == CONTENTS_EMPTY ) return false; // swim monster left water VectorCopy (trace.endpos, ent->v.origin); if (relink) SV_LinkEdict (ent, true); return true; } if (enemy == nullptr) break; } return false; } // push down from a step height above the wished position neworg[2] += STEPSIZE; VectorCopy (neworg, end); end[2] -= STEPSIZE*2; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid) return false; if (trace.startsolid) { neworg[2] -= STEPSIZE; trace = SV_Move (neworg, ent->v.mins, ent->v.maxs, end, false, ent); if (trace.allsolid || trace.startsolid) return false; } if (trace.fraction == 1) { // if monster had the ground pulled out, go ahead and fall if ( (int)ent->v.flags & FL_PARTIALGROUND ) { VectorAdd (ent->v.origin, move, ent->v.origin); if (relink) SV_LinkEdict (ent, true); ent->v.flags = static_cast<float>((int)ent->v.flags & ~FL_ONGROUND); // Con_Printf ("fall down\n"); return true; } return false; // walked off an edge } // check point traces down for dangling corners VectorCopy (trace.endpos, ent->v.origin); if (!SV_CheckBottom (ent)) { if ( (int)ent->v.flags & FL_PARTIALGROUND ) { // entity had floor mostly pulled out from underneath it // and is trying to correct if (relink) SV_LinkEdict (ent, true); return true; } VectorCopy (oldorg, ent->v.origin); return false; } if ( (int)ent->v.flags & FL_PARTIALGROUND ) { // Con_Printf ("back on ground\n"); ent->v.flags = static_cast<float>(static_cast<int>(ent->v.flags) & ~FL_PARTIALGROUND); } ent->v.groundentity = vm.EDICT_TO_PROG(trace.ent); // the move is ok if (relink) SV_LinkEdict (ent, true); return true; } //============================================================================ /* ====================== SV_StepDirection Turns to the movement direction, and walks the current distance if facing it. ====================== */ void PF_changeyaw (void); qboolean SV_StepDirection (edict_t *ent, float yaw, float dist) { vec3_t move, oldorigin; float delta; ent->v.ideal_yaw = yaw; PF_changeyaw(); static constexpr float yaw_constant= static_cast<float>(M_PI*2.0 / 360.0); yaw = yaw* yaw_constant; move[0] = cos(yaw)*dist; move[1] = sin(yaw)*dist; move[2] = 0; VectorCopy (ent->v.origin, oldorigin); if (SV_movestep (ent, move, false)) { delta = ent->v.angles[YAW] - ent->v.ideal_yaw; if (delta > 45.0f && delta < 315.0f) { // not turned far enough, so don't take the step VectorCopy (oldorigin, ent->v.origin); } SV_LinkEdict (ent, true); return true; } SV_LinkEdict (ent, true); return false; } /* ====================== SV_FixCheckBottom ====================== */ void SV_FixCheckBottom (edict_t *ent) { // Con_Printf ("SV_FixCheckBottom\n"); ent->v.flags = static_cast<float>(static_cast<int>(ent->v.flags) | FL_PARTIALGROUND); } /* ================ SV_NewChaseDir ================ */ #define DI_NODIR -1 void SV_NewChaseDir (edict_t *actor, edict_t *enemy, float dist) { float deltax,deltay; float d[3]; float tdir, olddir, turnaround; olddir = anglemod( (int)(actor->v.ideal_yaw/45.0f)*45.0f ); turnaround = anglemod(olddir - 180); deltax = enemy->v.origin[0] - actor->v.origin[0]; deltay = enemy->v.origin[1] - actor->v.origin[1]; if (deltax>10) d[1]= 0; else if (deltax<-10) d[1]= 180; else d[1]= DI_NODIR; if (deltay<-10) d[2]= 270; else if (deltay>10) d[2]= 90; else d[2]= DI_NODIR; // try direct route if (d[1] != DI_NODIR && d[2] != DI_NODIR) { if (d[1] == 0) tdir = d[2] == 90.0f ? 45.0f : 315.0f; else tdir = d[2] == 90.0f ? 135.0f : 215.0f; if (tdir != turnaround && SV_StepDirection(actor, tdir, dist)) return; } // try other directions if ( ((rand()&3) & 1) || std::abs(deltay)>abs(deltax)) { tdir=d[1]; d[1]=d[2]; d[2]=tdir; } if (d[1]!=DI_NODIR && d[1]!=turnaround && SV_StepDirection(actor, d[1], dist)) return; if (d[2]!=DI_NODIR && d[2]!=turnaround && SV_StepDirection(actor, d[2], dist)) return; /* there is no direct path to the player, so pick another direction */ if (olddir!=DI_NODIR && SV_StepDirection(actor, olddir, dist)) return; if (rand()&1) /*randomly determine direction of search*/ { for (tdir=0 ; tdir<=315 ; tdir += 45) if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) return; } else { for (tdir=315 ; tdir >=0 ; tdir -= 45) if (tdir!=turnaround && SV_StepDirection(actor, tdir, dist) ) return; } if (turnaround != DI_NODIR && SV_StepDirection(actor, turnaround, dist) ) return; actor->v.ideal_yaw = olddir; // can't move // if a bridge was pulled out from underneath a monster, it may not have // a valid standing position at all if (!SV_CheckBottom (actor)) SV_FixCheckBottom (actor); } /* ====================== SV_CloseEnough ====================== */ qboolean SV_CloseEnough (edict_t *ent, edict_t *goal, float dist) { int i; for (i=0 ; i<3 ; i++) { if (goal->v.absmin[i] > ent->v.absmax[i] + dist) return false; if (goal->v.absmax[i] < ent->v.absmin[i] - dist) return false; } return true; } /* ====================== SV_MoveToGoal ====================== */ void SV_MoveToGoal (void) { #ifdef QUAKE2 edict_t *enemy; #endif auto ent = vm.pr_global_struct->self; auto goal = ent->v.goalentity; float dist = vm.G_FLOAT(OFS_PARM0); if ( !( (int)ent->v.flags & (FL_ONGROUND|FL_FLY|FL_SWIM) ) ) { vm.G_FLOAT(OFS_RETURN) = 0; return; } // if the next step hits the enemy, return immediately #ifdef QUAKE2 enemy = vm.PROG_TO_EDICT(ent->v.enemy); if (enemy != sv.edicts && SV_CloseEnough (ent, enemy, dist) ) #else if (ent->v.enemy != nullptr && SV_CloseEnough (ent, goal, dist) ) #endif return; // bump around... if ( (rand()&3)==1 || !SV_StepDirection (ent, ent->v.ideal_yaw, dist)) { SV_NewChaseDir (ent, goal, dist); } }
22.535211
92
0.621354
WarlockD