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
bce3ea10273c30077254035d26981fee66346d94
1,273
cpp
C++
Programs/21 Stack/linkedListImplementation.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
5
2021-04-04T18:39:14.000Z
2021-12-18T09:31:55.000Z
Programs/21 Stack/linkedListImplementation.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
null
null
null
Programs/21 Stack/linkedListImplementation.cpp
Lord-Lava/DSA-CPP-Apna-College
077350c2aa900bb0cdb137ece2b95be58ccd76a8
[ "MIT" ]
1
2021-09-26T11:01:26.000Z
2021-09-26T11:01:26.000Z
//implementation using single ll //top <-node4 <-node3 <-node2 <-node1 #include <iostream> using namespace std; class node{ public: int data; node* next; // node* prev; node(int val){ data = val; next = NULL; // prev = NULL; } }; class stack{ node* top; public: stack(){ top = NULL; }//constructor void push(int x){ node* n = new node(x); // top->next = n; n->next = top; //singly ll implementation top = n; // top->prev = top; } void pop(){ if(top==NULL){ cout<<"Stack Underflow"<<endl; return; } node* todelete = top; // top = top->next; delete todelete; } int Top(){ if(top == NULL){ cout<<"Empty Stack"<<endl; return -1; } return top->data; } bool empty(){ return top==NULL; } }; int main(){ stack st; st.push(1); st.push(2); st.push(3); st.push(4); cout<<st.Top()<<endl; st.pop(); cout<<st.Top()<<endl; st.pop(); cout<<st.Top()<<endl; st.pop(); cout<<st.Top()<<endl; st.pop(); st.pop(); cout<<st.empty()<<endl; return 0; }
15.337349
49
0.451689
Lord-Lava
bce4c58ee69b751be22d58a1a61db3dcde96d3c3
1,183
hpp
C++
libs/modelmd3/impl/include/sge/model/md3/impl/frame.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
libs/modelmd3/impl/include/sge/model/md3/impl/frame.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
libs/modelmd3/impl/include/sge/model/md3/impl/frame.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_MODEL_MD3_IMPL_FRAME_HPP_INCLUDED #define SGE_MODEL_MD3_IMPL_FRAME_HPP_INCLUDED #include <sge/model/md3/scalar.hpp> #include <sge/model/md3/string.hpp> #include <sge/model/md3/impl/vec3.hpp> #include <fcppt/config/external_begin.hpp> #include <iosfwd> #include <fcppt/config/external_end.hpp> namespace sge::model::md3::impl { class frame { public: explicit frame(std::istream &); [[nodiscard]] sge::model::md3::impl::vec3 const &min_bounds() const; [[nodiscard]] sge::model::md3::impl::vec3 const &max_bounds() const; [[nodiscard]] sge::model::md3::impl::vec3 const &local_origin() const; [[nodiscard]] sge::model::md3::scalar radius() const; [[nodiscard]] sge::model::md3::string const &name() const; private: sge::model::md3::impl::vec3 min_bounds_; sge::model::md3::impl::vec3 max_bounds_; sge::model::md3::impl::vec3 local_origin_; sge::model::md3::scalar radius_; sge::model::md3::string name_; }; } #endif
24.142857
72
0.705833
cpreh
bce648c2796de1a4becbd9949a9caeda3b8ee146
10,593
cpp
C++
VulkanFramework/Device.cpp
Snowapril/VFS
a366f519c1382cfa2669b56346b67737513d6099
[ "MIT" ]
2
2022-02-14T16:34:39.000Z
2022-02-25T06:11:42.000Z
VulkanFramework/Device.cpp
Snowapril/vk_voxel_cone_tracing
a366f519c1382cfa2669b56346b67737513d6099
[ "MIT" ]
null
null
null
VulkanFramework/Device.cpp
Snowapril/vk_voxel_cone_tracing
a366f519c1382cfa2669b56346b67737513d6099
[ "MIT" ]
null
null
null
// Author : Jihong Shin (snowapril) #include <VulkanFramework/pch.h> #include <VulkanFramework/DebugUtils.h> #include <VulkanFramework/Device.h> #include <VulkanFramework/VulkanExtensions.h> #include <VulkanFramework/Window.h> #include <GLFW/glfw3.h> #include <Common/Logger.h> #include <cassert> #include <set> constexpr const char* REQUIRED_EXTENSIONS[] = { VK_KHR_SWAPCHAIN_EXTENSION_NAME }; constexpr const char* REQUIRED_LAYERS[] = { "VK_LAYER_KHRONOS_validation" }; namespace vfs { Device::Device(const char* appTitle) { assert(initialize(appTitle)); } Device::~Device() { destroyDevice(); } void Device::destroyDevice() { if (_memoryAllocator != nullptr) { vmaDestroyAllocator(_memoryAllocator); _memoryAllocator = nullptr; } if (_device != VK_NULL_HANDLE) { vkDestroyDevice(_device, nullptr); _device = VK_NULL_HANDLE; } if (_enableValidationLayer && _debugMessenger != VK_NULL_HANDLE) { vkDestroyDebugUtilsMessengerEXT(_instance, _debugMessenger, nullptr); _debugMessenger = VK_NULL_HANDLE; } if (_instance != VK_NULL_HANDLE) { vkDestroyInstance(_instance, nullptr); _instance = VK_NULL_HANDLE; } } bool Device::initialize(const char* appTitle) { #ifdef NDEBUG _enableValidationLayer = false; #else _enableValidationLayer = true; #endif if (_enableValidationLayer) { uint32_t layerCount; vkEnumerateInstanceLayerProperties(&layerCount, nullptr); std::vector<VkLayerProperties> layerProperties(layerCount); vkEnumerateInstanceLayerProperties(&layerCount, layerProperties.data()); bool layerFound{ false }; for (const VkLayerProperties& property : layerProperties) { if (strcmp(property.layerName, "VK_LAYER_KHRONOS_validation") == 0) { layerFound = true; break; } } if (!layerFound) { VFS_ERROR << "Failed to find validation layer in this device"; _enableValidationLayer = false; } } if (!initializeInstance(appTitle)) { return false; } initializeVulkanExtensions(_instance); if (_enableValidationLayer) { VkDebugUtilsMessengerCreateInfoEXT debugInfo = {}; queryDebugUtilsCreateInfo(&debugInfo); if (vkCreateDebugUtilsMessengerEXT(_instance, &debugInfo, nullptr, &_debugMessenger) != VK_SUCCESS) { VFS_ERROR << "Failed to create debug messenger"; return false; } } if (!pickPhysicalDevice()) { return false; } return true; } bool Device::initializeInstance(const char* appTitle) { VkApplicationInfo appInfo = {}; appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO; appInfo.pNext = nullptr; appInfo.pApplicationName = appTitle; appInfo.applicationVersion = VK_MAKE_VERSION(0, 0, 0); appInfo.pEngineName = "PAEngine"; appInfo.apiVersion = VK_API_VERSION_1_2; VkInstanceCreateInfo instanceInfo = {}; instanceInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; instanceInfo.pNext = nullptr; instanceInfo.pApplicationInfo = &appInfo; std::vector<const char*> extensions = getRequiredExtensions(); instanceInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size()); instanceInfo.ppEnabledExtensionNames = extensions.data(); VkDebugUtilsMessengerCreateInfoEXT debugInfo = {}; if (_enableValidationLayer) { instanceInfo.enabledLayerCount = sizeof(REQUIRED_LAYERS) / sizeof(const char*); instanceInfo.ppEnabledLayerNames = REQUIRED_LAYERS; queryDebugUtilsCreateInfo(&debugInfo); instanceInfo.pNext = reinterpret_cast<VkDebugUtilsMessengerCreateInfoEXT*>(&debugInfo); } else { instanceInfo.enabledLayerCount = 0; instanceInfo.ppEnabledLayerNames = nullptr; } if (vkCreateInstance(&instanceInfo, nullptr, &_instance) != VK_SUCCESS) { return false; } if (!checkExtensionSupport()) { return false; } return true; } void Device::queryDebugUtilsCreateInfo(VkDebugUtilsMessengerCreateInfoEXT* desc) const { desc->sType = VK_STRUCTURE_TYPE_DEBUG_UTILS_MESSENGER_CREATE_INFO_EXT; desc->pNext = nullptr; desc->pUserData = nullptr; desc->messageSeverity = VK_DEBUG_UTILS_MESSAGE_SEVERITY_ERROR_BIT_EXT; // VK_DEBUG_UTILS_MESSAGE_SEVERITY_WARNING_BIT_EXT desc->messageType = VK_DEBUG_UTILS_MESSAGE_TYPE_GENERAL_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_VALIDATION_BIT_EXT | VK_DEBUG_UTILS_MESSAGE_TYPE_PERFORMANCE_BIT_EXT; desc->pfnUserCallback = DebugUtils::DebugCallback; } bool Device::pickPhysicalDevice() { uint32_t physicalDeviceCount{}; vkEnumeratePhysicalDevices(_instance, &physicalDeviceCount, nullptr); std::vector<VkPhysicalDevice> physicalDevices(physicalDeviceCount); vkEnumeratePhysicalDevices(_instance, &physicalDeviceCount, physicalDevices.data()); for (auto device : physicalDevices) { if (checkDeviceSuitable(device)) { _physicalDevice = device; break; } } if (_physicalDevice == VK_NULL_HANDLE) { VFS_ERROR << "No Available vulkan device"; return false; } vkGetPhysicalDeviceProperties(_physicalDevice, &_physicalDeviceProperties); vkGetPhysicalDeviceFeatures(_physicalDevice, &_physicalDeviceFeatures); VFS_INFO << "Selected Physical Device : " << _physicalDeviceProperties.deviceName; return true; } bool Device::initializeLogicalDevice(const std::vector<uint32_t>& queueFamilyIndices) { constexpr float QUEUE_PRIORITY = 1.0f; std::set<uint32_t> uniqueQueueFamilies(queueFamilyIndices.begin(), queueFamilyIndices.end()); std::vector<VkDeviceQueueCreateInfo> queueInfos; queueInfos.reserve(uniqueQueueFamilies.size()); for (const uint32_t queueFamily : uniqueQueueFamilies) { VkDeviceQueueCreateInfo queueInfo = {}; queueInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queueInfo.pNext = nullptr; queueInfo.queueCount = 1; queueInfo.queueFamilyIndex = queueFamily; queueInfo.pQueuePriorities = &QUEUE_PRIORITY; queueInfos.emplace_back(std::move(queueInfo)); } // TODO(snowapril) : support for device feature control VkPhysicalDeviceFeatures deviceFeatures = {}; deviceFeatures.samplerAnisotropy = VK_TRUE; deviceFeatures.fragmentStoresAndAtomics = VK_TRUE; deviceFeatures.geometryShader = VK_TRUE; deviceFeatures.multiDrawIndirect = VK_TRUE; deviceFeatures.fillModeNonSolid = VK_TRUE; deviceFeatures.sampleRateShading = VK_TRUE; deviceFeatures.multiViewport = VK_TRUE; deviceFeatures.vertexPipelineStoresAndAtomics = VK_TRUE; deviceFeatures.shaderTessellationAndGeometryPointSize = VK_TRUE; // TODO(snowapril) : support for device feature control VkPhysicalDeviceDescriptorIndexingFeatures descIndexingFeatures = {}; descIndexingFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DESCRIPTOR_INDEXING_FEATURES; descIndexingFeatures.descriptorBindingPartiallyBound = VK_TRUE; descIndexingFeatures.descriptorBindingUniformBufferUpdateAfterBind = VK_TRUE; descIndexingFeatures.descriptorBindingUpdateUnusedWhilePending = VK_TRUE; VkDeviceCreateInfo deviceCreateInfo = {}; deviceCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; deviceCreateInfo.pNext = &descIndexingFeatures; deviceCreateInfo.queueCreateInfoCount = static_cast<uint32_t>(queueInfos.size()); deviceCreateInfo.pQueueCreateInfos = queueInfos.data(); deviceCreateInfo.pEnabledFeatures = &deviceFeatures; // TODO(snowapril) : Add control over extension and validation layer deviceCreateInfo.enabledExtensionCount = sizeof(REQUIRED_EXTENSIONS) / sizeof(const char*); deviceCreateInfo.ppEnabledExtensionNames = REQUIRED_EXTENSIONS; if (_enableValidationLayer) { deviceCreateInfo.enabledLayerCount = sizeof(REQUIRED_LAYERS) / sizeof(const char*); deviceCreateInfo.ppEnabledLayerNames = REQUIRED_LAYERS; } else { deviceCreateInfo.enabledLayerCount = 0; deviceCreateInfo.ppEnabledLayerNames = nullptr; } if (vkCreateDevice(_physicalDevice, &deviceCreateInfo, nullptr, &_device) != VK_FALSE) { return false; } return true; } bool Device::initializeMemoryAllocator(void) { VmaAllocatorCreateInfo allocatorInfo = {}; allocatorInfo.physicalDevice = _physicalDevice; allocatorInfo.device = _device; allocatorInfo.instance = _instance; // TODO(snowapril) : may need to add more config for allocator if (vmaCreateAllocator(&allocatorInfo, &_memoryAllocator) != VK_SUCCESS) { return false; } return true; } void Device::getQueueFamilyProperties(std::vector<VkQueueFamilyProperties>* properties) { uint32_t queueFamilyCount{ 0 }; vkGetPhysicalDeviceQueueFamilyProperties(_physicalDevice, &queueFamilyCount, nullptr); properties->resize(queueFamilyCount); vkGetPhysicalDeviceQueueFamilyProperties(_physicalDevice, &queueFamilyCount, properties->data()); } bool Device::checkDeviceSuitable(VkPhysicalDevice device) const { // TODO(snowapril) : findQueueFamilyIndices(device) check completeness // TODO(snowapril) : checkDeviceExtensionSupport(device) check true // TODO(snowapril) : add check querySwapChainSupport formats, presentModes not empty return true; } bool Device::checkDeviceExtensionSupport(VkPhysicalDevice device) const { // TODO(snowapril) : Add device suitability check here uint32_t deviceExtensionPropertyCount{ 0 }; vkEnumerateDeviceExtensionProperties(device, nullptr, &deviceExtensionPropertyCount, nullptr); std::vector<VkExtensionProperties> deviceExtensions(deviceExtensionPropertyCount); vkEnumerateDeviceExtensionProperties(device, nullptr, &deviceExtensionPropertyCount, deviceExtensions.data()); // TODO(snowapril) : check REQUIRED_EXTENSIONS are all in the deviceExtensions return true; } bool Device::checkExtensionSupport() const { uint32_t extensionCount {}; vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, nullptr); std::vector<VkExtensionProperties> properties(extensionCount); vkEnumerateInstanceExtensionProperties(nullptr, &extensionCount, properties.data()); std::vector<const char*> requiredExtensions = getRequiredExtensions(); // TODO(snowapril) : compare properties and required extensions here. return true; } std::vector<const char*> Device::getRequiredExtensions() const { uint32_t glfwExtensionCount = 0; const char** glfwExtensions; glfwExtensions = glfwGetRequiredInstanceExtensions(&glfwExtensionCount); std::vector<const char*> extensions(glfwExtensions, glfwExtensions + glfwExtensionCount); if (_enableValidationLayer) { extensions.emplace_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME); } return extensions; } }
31.155882
123
0.765789
Snowapril
bcf0e815b7d797a4eb99a6de118174a97048d0f3
4,315
cpp
C++
source/rendering/pipes/MirrorPipe.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
2
2021-01-27T15:49:04.000Z
2021-01-28T07:40:30.000Z
source/rendering/pipes/MirrorPipe.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
null
null
null
source/rendering/pipes/MirrorPipe.cpp
RaygenEngine/Raygen
2e61afd35f594d06186c16397b536412ebf4298d
[ "MIT" ]
1
2021-03-07T23:17:31.000Z
2021-03-07T23:17:31.000Z
#include "MirrorPipe.h" #include "rendering/assets/GpuAssetManager.h" #include "rendering/assets/GpuShader.h" #include "rendering/assets/GpuShaderStage.h" #include "rendering/pipes/StaticPipes.h" #include "rendering/scene/Scene.h" #include "rendering/scene/SceneCamera.h" namespace { struct PushConstant { int32 depth; int32 pointlightCount; int32 spotlightCount; int32 dirlightCount; int32 irragridCount; int32 quadlightCount; int32 reflprobeCount; }; static_assert(sizeof(PushConstant) <= 128); } // namespace namespace vl { vk::UniquePipelineLayout MirrorPipe::MakePipelineLayout() { return rvk::makePipelineLayout<PushConstant>( { DescriptorLayouts->global.handle(), // gbuffer and stuff DescriptorLayouts->_1storageImage.handle(), // images DescriptorLayouts->accelerationStructure.handle(), // as DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // geometry and texture DescriptorLayouts->_1storageBuffer.handle(), // pointlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // spotlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // dirlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // irragrids DescriptorLayouts->_1storageBuffer.handle(), // quadlights DescriptorLayouts->_1storageBuffer_1024samplerImage.handle(), // reflprobes }, vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eClosestHitKHR); } vk::UniquePipeline MirrorPipe::MakePipeline() { auto getShader = [](const auto& path) -> auto& { GpuAsset<Shader>& gpuShader = GpuAssetManager->CompileShader(path); gpuShader.onCompile = [&]() { StaticPipes::Recompile<MirrorPipe>(); }; return gpuShader; }; // all rt shaders here auto& ptshader = getShader("engine-data/spv/raytrace/mirror/mirror.shader"); auto& ptQuadlightShader = getShader("engine-data/spv/raytrace/mirror/mirror-quadlight.shader"); auto get = [](auto shader) { return *shader.Lock().module; }; AddRaygenGroup(get(ptshader.rayGen)); AddMissGroup(get(ptshader.miss)); // miss general 0 AddHitGroup(get(ptshader.closestHit), get(ptshader.anyHit)); // gltf mat 0, ahit for mask AddHitGroup(get(ptQuadlightShader.closestHit)); // quad lights 1 vk::RayTracingPipelineCreateInfoKHR rayPipelineInfo{}; rayPipelineInfo .setLayout(layout()) // .setMaxPipelineRayRecursionDepth(1); // Assemble the shader stages and construct the SBT return MakeRaytracingPipeline(rayPipelineInfo); } void MirrorPipe::RecordCmd(vk::CommandBuffer cmdBuffer, const SceneRenderDesc& sceneDesc, const vk::Extent3D& extent, vk::DescriptorSet mirrorImageStorageDescSet, int32 bounces) const { COMMAND_SCOPE_AUTO(cmdBuffer); cmdBuffer.bindPipeline(vk::PipelineBindPoint::eRayTracingKHR, pipeline()); cmdBuffer.bindDescriptorSets(vk::PipelineBindPoint::eRayTracingKHR, layout(), 0u, { sceneDesc.globalDesc, mirrorImageStorageDescSet, sceneDesc.scene->sceneAsDescSet, sceneDesc.scene->tlas.sceneDesc.descSetGeometryAndTextures[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetPointlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetSpotlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetDirlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetIrragrids[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetQuadlights[sceneDesc.frameIndex], sceneDesc.scene->tlas.sceneDesc.descSetReflprobes[sceneDesc.frameIndex], }, nullptr); PushConstant pc{ .depth = bounces, .pointlightCount = sceneDesc.scene->tlas.sceneDesc.pointlightCount, .spotlightCount = sceneDesc.scene->tlas.sceneDesc.spotlightCount, .dirlightCount = sceneDesc.scene->tlas.sceneDesc.dirlightCount, .irragridCount = sceneDesc.scene->tlas.sceneDesc.irragridCount, .quadlightCount = sceneDesc.scene->tlas.sceneDesc.quadlightCount, .reflprobeCount = sceneDesc.scene->tlas.sceneDesc.reflprobeCount, }; cmdBuffer.pushConstants(layout(), vk::ShaderStageFlagBits::eRaygenKHR | vk::ShaderStageFlagBits::eClosestHitKHR, 0u, sizeof(PushConstant), &pc); TraceRays(cmdBuffer, extent.width, extent.height, 1u); } } // namespace vl
37.198276
117
0.756431
RaygenEngine
bcf8c8fec0ebf865e37923634ced910583cb65e8
3,082
hpp
C++
inc/streamDumper.hpp
WMFO/Silence-Detector
af932c13e6e121b094038ad08e7d2e667c67351c
[ "MIT" ]
18
2015-07-18T11:44:41.000Z
2021-03-27T17:23:48.000Z
inc/streamDumper.hpp
WMFO/Silence-Detector
af932c13e6e121b094038ad08e7d2e667c67351c
[ "MIT" ]
null
null
null
inc/streamDumper.hpp
WMFO/Silence-Detector
af932c13e6e121b094038ad08e7d2e667c67351c
[ "MIT" ]
6
2017-05-26T08:55:05.000Z
2021-10-08T01:56:41.000Z
#ifndef STREAMDUMPER_H #define STREAMDUMPER_H #include <exception> #include <string> #include <iostream> #include <list> class streamDumper { public: streamDumper(); streamDumper(const std::string &bindAddr, const std::string &ipaddr, int portNumber); void openMulticastStream(const std::string &bindAddr, const std::string &ipaddr, int portNumber); ~streamDumper(); void getSocketData(unsigned char* buf, unsigned long bufLen); private: std::string multicastAddr; int port; bool socketActive; bool subscriptionActive; int socketDescriptor; unsigned char *remainderData; unsigned long remainderDataLength; void openSocket(); void closeSocket(); void readSocket(); class RTPHeader { public: RTPHeader(); RTPHeader(unsigned char*); ~RTPHeader(); void readData(unsigned char*); int getVersion() const; bool hasPadding() const; bool hasExtension() const; unsigned int getCSRCCount() const; unsigned int getPayloadType() const; unsigned long getSequenceNumber() const; unsigned long getTimestamp() const; unsigned long getSSRCIdentifier() const; unsigned long getHeaderLength() const; private: int version; bool padding; bool extensions; unsigned int CSRCCount; unsigned int payloadType; unsigned long sequenceNumber; unsigned long timeStamp; unsigned long SSRCIdentifier; unsigned long extensionLength; }; class RTPPacket { public: RTPHeader header; RTPPacket(); RTPPacket(unsigned char*, unsigned long); ~RTPPacket(); void readData(unsigned char*, unsigned long); unsigned long getContentLength() const; unsigned char *getContent() const; bool operator<(const RTPPacket &b) const; RTPPacket(const RTPPacket &b); RTPPacket &operator=(const RTPPacket &b); private: unsigned char *content; unsigned long contentLength; }; void setRemainderData(const unsigned char *, unsigned long, const std::list<RTPPacket>&); }; //Exceptions class streamDumperException : public std::exception { public: streamDumperException(const std::string &reason) throw() { exceptionWhat = reason; } virtual const char *what() const throw() { return exceptionWhat.c_str(); } virtual ~streamDumperException() throw() {}; private: std::string exceptionWhat; }; #endif
28.803738
105
0.544452
WMFO
bcf9360d4a9bee78e6fe23da18d9aceae454edbf
527
cpp
C++
test/tools/llvm-pdbdump/Inputs/FilterTest.cpp
kpdev/llvm-tnt
d81ccf6fad01597f0143a1598d94d7d29002cf41
[ "MIT" ]
1,073
2017-06-28T05:11:54.000Z
2022-03-31T12:52:07.000Z
test/tools/llvm-pdbdump/Inputs/FilterTest.cpp
rjordans/avr-llvm
1802f85a455fbbe5fd1b55183bf588e2e4731dc5
[ "FSFAP" ]
25
2018-07-23T08:34:15.000Z
2021-11-05T07:13:36.000Z
test/tools/llvm-pdbdump/Inputs/FilterTest.cpp
rjordans/avr-llvm
1802f85a455fbbe5fd1b55183bf588e2e4731dc5
[ "FSFAP" ]
244
2017-06-28T05:08:57.000Z
2022-03-13T05:03:12.000Z
// Compile with "cl /c /Zi /GR- FilterTest.cpp" // Link with "link FilterTest.obj /debug /nodefaultlib /entry:main" class FilterTestClass { public: typedef int NestedTypedef; enum NestedEnum { NestedEnumValue1 }; void MemberFunc() {} private: int IntMemberVar; double DoubleMemberVar; }; int IntGlobalVar; double DoubleGlobalVar; typedef int GlobalTypedef; enum GlobalEnum { GlobalEnumVal1 } GlobalEnumVar; int main(int argc, char **argv) { FilterTestClass TestClass; GlobalTypedef v1; return 0; }
17.566667
67
0.732448
kpdev
bcfbc46ae8d61352d53dac09f9d91c2d8c3b3f7d
9,319
cpp
C++
src/theory/sets/theory_sets_rewriter.cpp
HasibShakur/CVC4
7a303390a65fd395a53085833d504acc312dc6a6
[ "BSL-1.0" ]
null
null
null
src/theory/sets/theory_sets_rewriter.cpp
HasibShakur/CVC4
7a303390a65fd395a53085833d504acc312dc6a6
[ "BSL-1.0" ]
null
null
null
src/theory/sets/theory_sets_rewriter.cpp
HasibShakur/CVC4
7a303390a65fd395a53085833d504acc312dc6a6
[ "BSL-1.0" ]
null
null
null
/********************* */ /*! \file theory_sets_rewriter.cpp ** \verbatim ** Original author: Kshitij Bansal ** Major contributors: none ** Minor contributors (to current version): none ** This file is part of the CVC4 project. ** Copyright (c) 2013-2014 New York University and The University of Iowa ** See the file COPYING in the top-level source directory for licensing ** information.\endverbatim ** ** \brief Sets theory rewriter. ** ** Sets theory rewriter. **/ #include "theory/sets/theory_sets_rewriter.h" namespace CVC4 { namespace theory { namespace sets { typedef std::set<TNode> Elements; typedef std::hash_map<TNode, Elements, TNodeHashFunction> SettermElementsMap; bool checkConstantMembership(TNode elementTerm, TNode setTerm) { // Assume from pre-rewrite constant sets look like the following: // (union (setenum bla) (union (setenum bla) ... (union (setenum bla) (setenum bla) ) ... )) if(setTerm.getKind() == kind::EMPTYSET) { return false; } if(setTerm.getKind() == kind::SET_SINGLETON) { return elementTerm == setTerm[0]; } Assert(setTerm.getKind() == kind::UNION && setTerm[1].getKind() == kind::SET_SINGLETON, "kind was %d, term: %s", setTerm.getKind(), setTerm.toString().c_str()); return elementTerm == setTerm[1][0] || checkConstantMembership(elementTerm, setTerm[0]); // switch(setTerm.getKind()) { // case kind::EMPTYSET: // return false; // case kind::SET_SINGLETON: // return elementTerm == setTerm[0]; // case kind::UNION: // return checkConstantMembership(elementTerm, setTerm[0]) || // checkConstantMembership(elementTerm, setTerm[1]); // case kind::INTERSECTION: // return checkConstantMembership(elementTerm, setTerm[0]) && // checkConstantMembership(elementTerm, setTerm[1]); // case kind::SETMINUS: // return checkConstantMembership(elementTerm, setTerm[0]) && // !checkConstantMembership(elementTerm, setTerm[1]); // default: // Unhandled(); // } } // static RewriteResponse TheorySetsRewriter::postRewrite(TNode node) { NodeManager* nm = NodeManager::currentNM(); Kind kind = node.getKind(); switch(kind) { case kind::MEMBER: { if(node[0].isConst() && node[1].isConst()) { // both are constants TNode S = preRewrite(node[1]).node; bool isMember = checkConstantMembership(node[0], S); return RewriteResponse(REWRITE_DONE, nm->mkConst(isMember)); } break; }//kind::MEMBER case kind::SUBSET: { // rewrite (A subset-or-equal B) as (A union B = B) TNode A = node[0]; TNode B = node[1]; return RewriteResponse(REWRITE_AGAIN_FULL, nm->mkNode(kind::EQUAL, nm->mkNode(kind::UNION, A, B), B) ); }//kind::SUBSET case kind::EQUAL: case kind::IFF: { //rewrite: t = t with true (t term) //rewrite: c = c' with c different from c' false (c, c' constants) //otherwise: sort them if(node[0] == node[1]) { Trace("sets-postrewrite") << "Sets::postRewrite returning true" << std::endl; return RewriteResponse(REWRITE_DONE, nm->mkConst(true)); } else if (node[0].isConst() && node[1].isConst()) { Trace("sets-postrewrite") << "Sets::postRewrite returning false" << std::endl; return RewriteResponse(REWRITE_DONE, nm->mkConst(false)); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::IFF case kind::SETMINUS: { if(node[0] == node[1]) { Node newNode = nm->mkConst(EmptySet(nm->toType(node[0].getType()))); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } else if(node[0].getKind() == kind::EMPTYSET || node[1].getKind() == kind::EMPTYSET) { Trace("sets-postrewrite") << "Sets::postRewrite returning " << node[0] << std::endl; return RewriteResponse(REWRITE_DONE, node[0]); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::INTERSECION case kind::INTERSECTION: { if(node[0] == node[1]) { Trace("sets-postrewrite") << "Sets::postRewrite returning " << node[0] << std::endl; return RewriteResponse(REWRITE_DONE, node[0]); } else if(node[0].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[0]); } else if(node[1].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[1]); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::INTERSECION case kind::UNION: { if(node[0] == node[1]) { Trace("sets-postrewrite") << "Sets::postRewrite returning " << node[0] << std::endl; return RewriteResponse(REWRITE_DONE, node[0]); } else if(node[0].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[1]); } else if(node[1].getKind() == kind::EMPTYSET) { return RewriteResponse(REWRITE_DONE, node[0]); } else if (node[0] > node[1]) { Node newNode = nm->mkNode(node.getKind(), node[1], node[0]); Trace("sets-postrewrite") << "Sets::postRewrite returning " << newNode << std::endl; return RewriteResponse(REWRITE_DONE, newNode); } break; }//kind::UNION default: break; }//switch(node.getKind()) // This default implementation return RewriteResponse(REWRITE_DONE, node); } const Elements& collectConstantElements(TNode setterm, SettermElementsMap& settermElementsMap) { SettermElementsMap::const_iterator it = settermElementsMap.find(setterm); if(it == settermElementsMap.end() ) { Kind k = setterm.getKind(); unsigned numChildren = setterm.getNumChildren(); Elements cur; if(numChildren == 2) { const Elements& left = collectConstantElements(setterm[0], settermElementsMap); const Elements& right = collectConstantElements(setterm[1], settermElementsMap); switch(k) { case kind::UNION: if(left.size() >= right.size()) { cur = left; cur.insert(right.begin(), right.end()); } else { cur = right; cur.insert(left.begin(), left.end()); } break; case kind::INTERSECTION: std::set_intersection(left.begin(), left.end(), right.begin(), right.end(), std::inserter(cur, cur.begin()) ); break; case kind::SETMINUS: std::set_difference(left.begin(), left.end(), right.begin(), right.end(), std::inserter(cur, cur.begin()) ); break; default: Unhandled(); } } else { switch(k) { case kind::EMPTYSET: /* assign emptyset, which is default */ break; case kind::SET_SINGLETON: Assert(setterm[0].isConst()); cur.insert(TheorySetsRewriter::preRewrite(setterm[0]).node); break; default: Unhandled(); } } Debug("sets-rewrite-constant") << "[sets-rewrite-constant] "<< setterm << " " << setterm.getId() << std::endl; it = settermElementsMap.insert(SettermElementsMap::value_type(setterm, cur)).first; } return it->second; } Node elementsToNormalConstant(Elements elements, TypeNode setType) { NodeManager* nm = NodeManager::currentNM(); if(elements.size() == 0) { return nm->mkConst(EmptySet(nm->toType(setType))); } else { Elements::iterator it = elements.begin(); Node cur = nm->mkNode(kind::SET_SINGLETON, *it); while( ++it != elements.end() ) { cur = nm->mkNode(kind::UNION, cur, nm->mkNode(kind::SET_SINGLETON, *it)); } return cur; } } // static RewriteResponse TheorySetsRewriter::preRewrite(TNode node) { NodeManager* nm = NodeManager::currentNM(); // do nothing if(node.getKind() == kind::EQUAL && node[0] == node[1]) return RewriteResponse(REWRITE_DONE, nm->mkConst(true)); // Further optimization, if constants but differing ones if(node.getType().isSet() && node.isConst()) { //rewrite set to normal form SettermElementsMap setTermElementsMap; // cache const Elements& elements = collectConstantElements(node, setTermElementsMap); RewriteResponse response(REWRITE_DONE, elementsToNormalConstant(elements, node.getType())); Debug("sets-rewrite-constant") << "[sets-rewrite-constant] Rewriting " << node << std::endl << "[sets-rewrite-constant] to " << response.node << std::endl; return response; } return RewriteResponse(REWRITE_DONE, node); } }/* CVC4::theory::sets namespace */ }/* CVC4::theory namespace */ }/* CVC4 namespace */
35.568702
114
0.620882
HasibShakur
bcfce3b0d01b36731990972df7194dd9411ed08f
497
cc
C++
zeo/r_table.cc
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
43
2019-09-29T01:14:25.000Z
2022-03-02T23:48:25.000Z
zeo/r_table.cc
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
15
2019-10-19T23:39:39.000Z
2021-12-30T22:03:51.000Z
zeo/r_table.cc
softwarecapital/chr1shr.voro
122531fbe162ea9a94b7e96ee9d57d3957c337ca
[ "BSD-3-Clause-LBNL" ]
23
2019-10-19T23:40:57.000Z
2022-03-29T16:53:17.000Z
// Voro++, a 3D cell-based Voronoi library // // Author : Chris H. Rycroft (LBL / UC Berkeley) // Email : chr@alum.mit.edu // Date : July 1st 2008 #include <cstdlib> const int n_table=2; const char rad_ctable[][4]={ "O", "Si" }; const double rad_table[]={ 0.8, 0.5 }; double radial_lookup(char *buffer) { for(int i=0;i<n_table;i++) if(strcmp(rad_ctable[i],buffer)==0) return rad_table[i]; fprintf(stderr,"Entry \"%s\" not found in table\n",buffer); exit(VOROPP_FILE_ERROR); }
19.115385
84
0.647887
softwarecapital
bcfdc549ffe55591888e2088498b9f43fa364212
37,103
cpp
C++
RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
RenderSystems/Vulkan/src/OgreVulkanTextureGpu.cpp
dawlane/ogre
7bae21738c99b117ef2eab3fcb1412891b8c2025
[ "MIT" ]
null
null
null
/* ----------------------------------------------------------------------------- This source file is part of OGRE (Object-oriented Graphics Rendering Engine) For the latest info, see http://www.ogre3d.org/ Copyright (c) 2000-2017 Torus Knot Software Ltd Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ----------------------------------------------------------------------------- */ #include "OgreVulkanTextureGpu.h" #include "OgreException.h" #include "OgreVector.h" #include "OgreVulkanMappings.h" #include "OgreVulkanTextureGpuManager.h" #include "OgreVulkanUtils.h" #include "OgreVulkanHardwareBuffer.h" #include "OgreBitwise.h" #include "OgreRoot.h" #include "OgreVulkanTextureGpuWindow.h" #define TODO_add_resource_transitions namespace Ogre { VulkanHardwarePixelBuffer::VulkanHardwarePixelBuffer(VulkanTextureGpu* tex, uint32 width, uint32 height, uint32 depth, uint8 face, uint32 mip) : HardwarePixelBuffer(width, height, depth, tex->getFormat(), tex->getUsage(), false, false), mParent(tex), mFace(face), mLevel(mip) { if(mParent->getUsage() & TU_RENDERTARGET) { // Create render target for each slice mSliceTRT.reserve(mDepth); for(size_t zoffset=0; zoffset<mDepth; ++zoffset) { String name; name = "rtt/"+StringConverter::toString((size_t)this) + "/" + mParent->getName(); RenderTexture *trt = new VulkanRenderTexture(name, this, zoffset, mParent, mFace); mSliceTRT.push_back(trt); Root::getSingleton().getRenderSystem()->attachRenderTarget(*trt); } } } PixelBox VulkanHardwarePixelBuffer::lockImpl(const Box &lockBox, LockOptions options) { PixelBox ret(lockBox, mParent->getFormat()); auto textureManager = static_cast<VulkanTextureGpuManager*>(mParent->getCreator()); VulkanDevice* device = textureManager->getDevice(); mStagingBuffer.reset(new VulkanHardwareBuffer(VK_BUFFER_USAGE_TRANSFER_SRC_BIT, ret.getConsecutiveSize(), HBU_CPU_ONLY, false, device)); return PixelBox(lockBox, mParent->getFormat(), mStagingBuffer->lock(options)); } void VulkanHardwarePixelBuffer::unlockImpl() { mStagingBuffer->unlock(); auto textureManager = static_cast<VulkanTextureGpuManager*>(mParent->getCreator()); VulkanDevice* device = textureManager->getDevice(); device->mGraphicsQueue.getCopyEncoder( 0, mParent, false ); VkBuffer srcBuffer = mStagingBuffer->getVkBuffer(); VkBufferImageCopy region; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = mLevel; region.imageSubresource.baseArrayLayer = mFace; region.imageSubresource.layerCount = 1; region.imageOffset.x = mCurrentLock.left; region.imageOffset.y = mCurrentLock.top; region.imageOffset.z = mCurrentLock.front; region.imageExtent.width = mCurrentLock.getWidth(); region.imageExtent.height = mCurrentLock.getHeight(); region.imageExtent.depth = mCurrentLock.getDepth(); if(mParent->getTextureType() == TEX_TYPE_2D_ARRAY) { region.imageSubresource.baseArrayLayer = mCurrentLock.front; region.imageOffset.z = 0; } vkCmdCopyBufferToImage(device->mGraphicsQueue.mCurrentCmdBuffer, srcBuffer, mParent->getFinalTextureName(), VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &region); bool finalSlice = region.imageSubresource.baseArrayLayer == mParent->getNumLayers() - 1; if((mParent->getUsage() & TU_AUTOMIPMAP) && finalSlice) mParent->_autogenerateMipmaps(); mStagingBuffer.reset(); } void VulkanHardwarePixelBuffer::blitFromMemory(const PixelBox& src, const Box& dstBox) { OgreAssert(src.getSize() == dstBox.getSize(), "scaling currently not supported"); // convert to image native format if necessary if(src.format != mFormat) { std::vector<uint8> buffer; buffer.resize(PixelUtil::getMemorySize(src.getWidth(), src.getHeight(), src.getDepth(), mFormat)); PixelBox converted = PixelBox(src.getWidth(), src.getHeight(), src.getDepth(), mFormat, buffer.data()); PixelUtil::bulkPixelConversion(src, converted); blitFromMemory(converted, dstBox); // recursive call return; } auto ptr = lock(dstBox, HBL_WRITE_ONLY).data; memcpy(ptr, src.data, src.getConsecutiveSize()); unlock(); } void VulkanHardwarePixelBuffer::blitToMemory(const Box& srcBox, const PixelBox& dst) { OgreAssert(srcBox.getSize() == dst.getSize(), "scaling currently not supported"); auto textureManager = static_cast<VulkanTextureGpuManager*>(mParent->getCreator()); VulkanDevice* device = textureManager->getDevice(); auto stagingBuffer = std::make_shared<VulkanHardwareBuffer>( VK_BUFFER_USAGE_TRANSFER_DST_BIT, dst.getConsecutiveSize(), HBU_CPU_ONLY, false, device); device->mGraphicsQueue.getCopyEncoder(0, mParent, true); VkBuffer dstBuffer = stagingBuffer->getVkBuffer(); VkBufferImageCopy region; region.bufferOffset = 0; region.bufferRowLength = 0; region.bufferImageHeight = 0; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.mipLevel = 0; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageOffset.x = 0; region.imageOffset.y = 0; region.imageOffset.z = 0; region.imageExtent.width = srcBox.getWidth(); region.imageExtent.height = srcBox.getHeight(); region.imageExtent.depth = srcBox.getDepth(); vkCmdCopyImageToBuffer(device->mGraphicsQueue.mCurrentCmdBuffer, mParent->getFinalTextureName(), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstBuffer, 1u, &region); device->mGraphicsQueue.commitAndNextCommandBuffer(); stagingBuffer->readData(0, dst.getConsecutiveSize(), dst.data); } VulkanTextureGpu::VulkanTextureGpu(TextureManager* textureManager, const String& name, ResourceHandle handle, const String& group, bool isManual, ManualResourceLoader* loader) : Texture(textureManager, name, handle, group, isManual, loader ), mDefaultDisplaySrv( 0 ), mDisplayTextureName( 0 ), mFinalTextureName( 0 ), mMemory(VK_NULL_HANDLE), mMsaaTextureName( 0 ), mMsaaMemory(VK_NULL_HANDLE), mCurrLayout( VK_IMAGE_LAYOUT_UNDEFINED ), mNextLayout( VK_IMAGE_LAYOUT_UNDEFINED ) { } //----------------------------------------------------------------------------------- VulkanTextureGpu::~VulkanTextureGpu() { unload(); } //----------------------------------------------------------------------------------- void VulkanTextureGpu::createInternalResourcesImpl( void ) { if( mFormat == PF_UNKNOWN ) return; // Nothing to do // Adjust format if required. mFormat = TextureManager::getSingleton().getNativeFormat(mTextureType, mFormat, mUsage); mNumMipmaps = std::min(mNumMipmaps, Bitwise::mostSignificantBitSet(std::max(mWidth, std::max(mHeight, mDepth)))); VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; imageInfo.imageType = getVulkanTextureType(); imageInfo.extent.width = getWidth(); imageInfo.extent.height = getHeight(); imageInfo.extent.depth = getDepth(); imageInfo.mipLevels = mNumMipmaps + 1; imageInfo.arrayLayers = getNumFaces(); imageInfo.flags = 0; imageInfo.format = VulkanMappings::get( mFormat ); imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; if(mTextureType == TEX_TYPE_2D_ARRAY) std::swap(imageInfo.extent.depth, imageInfo.arrayLayers); if( hasMsaaExplicitResolves() ) { imageInfo.samples = VkSampleCountFlagBits(std::max(mFSAA, 1u)); } else imageInfo.samples = VK_SAMPLE_COUNT_1_BIT; if( mTextureType == TEX_TYPE_CUBE_MAP /*|| mTextureType == TextureTypes::TypeCubeArray*/ ) imageInfo.flags |= VK_IMAGE_CREATE_CUBE_COMPATIBLE_BIT; imageInfo.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if (PixelUtil::isDepth(mFormat)) imageInfo.usage |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT; else if(mUsage & TU_RENDERTARGET) imageInfo.usage |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; if( isUav() ) imageInfo.usage |= VK_IMAGE_USAGE_STORAGE_BIT; String textureName = getName(); auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice* device = textureManager->getDevice(); OGRE_VK_CHECK(vkCreateImage(device->mDevice, &imageInfo, 0, &mFinalTextureName)); setObjectName( device->mDevice, (uint64_t)mFinalTextureName, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, textureName.c_str() ); VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements( device->mDevice, mFinalTextureName, &memRequirements ); VkMemoryAllocateInfo memAllocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; memAllocInfo.allocationSize = memRequirements.size; memAllocInfo.memoryTypeIndex = 0; const auto& memProperties = device->mDeviceMemoryProperties; for(; memAllocInfo.memoryTypeIndex < memProperties.memoryTypeCount; memAllocInfo.memoryTypeIndex++) { if ((memProperties.memoryTypes[memAllocInfo.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { break; } } OGRE_VK_CHECK(vkAllocateMemory(device->mDevice, &memAllocInfo, NULL, &mMemory)); OGRE_VK_CHECK(vkBindImageMemory(device->mDevice, mFinalTextureName, mMemory, 0)); OgreAssert(device->mGraphicsQueue.getEncoderState() != VulkanQueue::EncoderGraphicsOpen, "interrupting RenderPass not supported"); device->mGraphicsQueue.endAllEncoders(); // Pool owners transition all its slices to read_only_optimal to avoid the validation layers // from complaining the unused (and untouched) slices are in the wrong layout. // We wait for no stage, and no stage waits for us. No caches are flushed. // // Later our TextureGpus using individual slices will perform an // undefined -> read_only_optimal transition on the individual slices & mips // to fill the data; and those transitions will be the ones who take care of blocking // previous/later stages in their respective barriers VkImageMemoryBarrier imageBarrier = this->getImageMemoryBarrier(); imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageBarrier.newLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; if( PixelUtil::isDepth( mFormat ) ) imageBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); mCurrLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; mNextLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL; // create uint32 depth = mDepth; for (uint8 face = 0; face < getNumFaces(); face++) { uint32 width = mWidth; uint32 height = mHeight; for (uint32 mip = 0; mip <= getNumMipmaps(); mip++) { auto buf = std::make_shared<VulkanHardwarePixelBuffer>(this, width, height, depth, face, mip); mSurfaceList.push_back(buf); if (width > 1) width = width / 2; if (height > 1) height = height / 2; if (depth > 1 && mTextureType != TEX_TYPE_2D_ARRAY) depth = depth / 2; } } mDefaultDisplaySrv = _createView(0, 0, 0, getNumLayers()); if( mFSAA > 1 && !hasMsaaExplicitResolves() ) createMsaaSurface(); } //----------------------------------------------------------------------------------- void VulkanTextureGpu::freeInternalResourcesImpl( void ) { // If 'this' is being destroyed: We must call notifyTextureDestroyed // // If 'this' is only being transitioned to OnStorage: // Our VkImage is being destroyed; and there may be pending image operations on it. // This wouldn't be a problem because the vkDestroyImage call is delayed. // However if the texture is later transitioned again to Resident, mCurrLayout & mNextLayout // will get out of sync when endCopyEncoder gets called. // // e.g. if a texture performs: // OnStorage -> Resident -> <upload operation> -> OnStorage -> Resident -> // endCopyEncoder -> <upload operation> -> endCopyEncoder // // then the 1st endCopyEncoder will set mCurrLayout to SHADER_READ_ONLY_OPTIMAL because // it thinks it changed the layout of the current mFinalTextureName, but it actually // changed the layout of the previous mFinalTextureName which is scheduled to be destroyed auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice *device = textureManager->getDevice(); device->mGraphicsQueue.notifyTextureDestroyed( this ); vkDestroyImageView(device->mDevice, mDefaultDisplaySrv, 0); mDefaultDisplaySrv = 0; vkDestroyImage(device->mDevice, mFinalTextureName, 0); vkFreeMemory(device->mDevice, mMemory, 0); destroyMsaaSurface(); mCurrLayout = VK_IMAGE_LAYOUT_UNDEFINED; mNextLayout = VK_IMAGE_LAYOUT_UNDEFINED; } //----------------------------------------------------------------------------------- void VulkanTextureGpu::copyTo( TextureGpu *dst, const PixelBox &dstBox, uint8 dstMipLevel, const PixelBox &srcBox, uint8 srcMipLevel, bool keepResolvedTexSynced, ResourceAccess::ResourceAccess issueBarriers ) { //TextureGpu::copyTo( dst, dstBox, dstMipLevel, srcBox, srcMipLevel, issueBarriers ); OGRE_ASSERT_HIGH( dynamic_cast<VulkanTextureGpu *>( dst ) ); VulkanTextureGpu *dstTexture = static_cast<VulkanTextureGpu *>( dst ); VulkanTextureGpuManager *textureManager = static_cast<VulkanTextureGpuManager *>( mCreator ); VulkanDevice *device = textureManager->getDevice(); if( issueBarriers & ResourceAccess::Read ) device->mGraphicsQueue.getCopyEncoder( 0, this, true ); else { // This won't generate barriers, but it will close all other encoders // and open the copy one device->mGraphicsQueue.getCopyEncoder( 0, 0, true ); } if( issueBarriers & ResourceAccess::Write ) device->mGraphicsQueue.getCopyEncoder( 0, dstTexture, false ); VkImageCopy region; const uint32 sourceSlice = srcBox.front;// + getInternalSliceStart(); const uint32 destinationSlice = dstBox.front;// + dstTexture->getInternalSliceStart(); const uint32 numSlices = dstBox.getDepth() != 0 ? dstBox.getDepth() : dstTexture->getDepth(); region.srcSubresource.aspectMask = VulkanMappings::getImageAspect( this->getFormat() ); region.srcSubresource.mipLevel = srcMipLevel; region.srcSubresource.baseArrayLayer = sourceSlice; region.srcSubresource.layerCount = numSlices; region.srcOffset.x = static_cast<int32_t>( srcBox.left ); region.srcOffset.y = static_cast<int32_t>( srcBox.top ); region.srcOffset.z = static_cast<int32_t>( srcBox.front ); region.dstSubresource.aspectMask = VulkanMappings::getImageAspect( dst->getFormat() ); region.dstSubresource.mipLevel = dstMipLevel; region.dstSubresource.baseArrayLayer = destinationSlice; region.dstSubresource.layerCount = numSlices; region.dstOffset.x = dstBox.left; region.dstOffset.y = dstBox.top; region.dstOffset.z = dstBox.front; region.extent.width = srcBox.getWidth(); region.extent.height = srcBox.getHeight(); region.extent.depth = srcBox.getDepth(); VkImage srcTextureName = this->mFinalTextureName; VkImage dstTextureName = dstTexture->mFinalTextureName; if( this->isMultisample() && !this->hasMsaaExplicitResolves() ) srcTextureName = this->mMsaaTextureName; if( dstTexture->isMultisample() && !dstTexture->hasMsaaExplicitResolves() ) dstTextureName = dstTexture->mMsaaTextureName; vkCmdCopyImage( device->mGraphicsQueue.mCurrentCmdBuffer, srcTextureName, mCurrLayout, dstTextureName, dstTexture->mCurrLayout, 1u, &region ); if( dstTexture->isMultisample() && !dstTexture->hasMsaaExplicitResolves() && keepResolvedTexSynced ) { TODO_add_resource_transitions; // We must add res. transitions and then restore them // Must keep the resolved texture up to date. VkImageResolve resolve = {}; resolve.srcSubresource = region.dstSubresource; resolve.dstSubresource = region.dstSubresource; resolve.extent.width = getWidth(); resolve.extent.height = getHeight(); resolve.extent.depth = getDepth(); vkCmdResolveImage( device->mGraphicsQueue.mCurrentCmdBuffer, dstTexture->mMsaaTextureName, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dstTexture->mFinalTextureName, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &resolve ); } // Do not perform the sync if notifyDataIsReady hasn't been called yet (i.e. we're // still building the HW mipmaps, and the texture will never be ready) /*if( dst->_isDataReadyImpl() && dst->getGpuPageOutStrategy() == GpuPageOutStrategy::AlwaysKeepSystemRamCopy ) { dst->_syncGpuResidentToSystemRam(); }*/ } //----------------------------------------------------------------------------------- void VulkanTextureGpu::_autogenerateMipmaps( bool bUseBarrierSolver ) { // TODO: Integrate FidelityFX Single Pass Downsampler - SPD // // https://gpuopen.com/fidelityfx-spd/ // https://github.com/GPUOpen-Effects/FidelityFX-SPD VulkanTextureGpuManager *textureManager = static_cast<VulkanTextureGpuManager *>( mCreator ); VulkanDevice *device = textureManager->getDevice(); const bool callerIsCompositor = mCurrLayout == VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; if( callerIsCompositor ) device->mGraphicsQueue.getCopyEncoder( 0, 0, true ); else { // We must transition to VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL // By the time we exit _autogenerateMipmaps, the texture will // still be in VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, thus // endCopyEncoder will perform as expected device->mGraphicsQueue.getCopyEncoder( 0, this, true ); } const uint32 numSlices = getNumLayers(); VkImageMemoryBarrier imageBarrier = getImageMemoryBarrier(); imageBarrier.subresourceRange.levelCount = 1u; const uint32 internalWidth = getWidth(); const uint32 internalHeight = getHeight(); for( size_t i = 1u; i <= mNumMipmaps; ++i ) { // Convert the dst mipmap 'i' to TRANSFER_DST_OPTIMAL. Does not have to wait // on anything because previous barriers (compositor or getCopyEncoder) // have already waited imageBarrier.subresourceRange.baseMipLevel = static_cast<uint32_t>( i ); imageBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; imageBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; imageBarrier.srcAccessMask = 0; imageBarrier.dstAccessMask = 0; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); VkImageBlit region; region.srcSubresource.aspectMask = VulkanMappings::getImageAspect( this->getFormat() ); region.srcSubresource.mipLevel = static_cast<uint32_t>( i - 1u ); region.srcSubresource.baseArrayLayer = 0u; region.srcSubresource.layerCount = numSlices; region.srcOffsets[0].x = 0; region.srcOffsets[0].y = 0; region.srcOffsets[0].z = 0; region.srcOffsets[1].x = static_cast<int32_t>( std::max( internalWidth >> ( i - 1u ), 1u ) ); region.srcOffsets[1].y = static_cast<int32_t>( std::max( internalHeight >> ( i - 1u ), 1u ) ); region.srcOffsets[1].z = static_cast<int32_t>( std::max( getDepth() >> ( i - 1u ), 1u ) ); region.dstSubresource.aspectMask = region.srcSubresource.aspectMask; region.dstSubresource.mipLevel = static_cast<uint32_t>( i ); region.dstSubresource.baseArrayLayer = 0u; region.dstSubresource.layerCount = numSlices; region.dstOffsets[0].x = 0; region.dstOffsets[0].y = 0; region.dstOffsets[0].z = 0; region.dstOffsets[1].x = static_cast<int32_t>( std::max( internalWidth >> i, 1u ) ); region.dstOffsets[1].y = static_cast<int32_t>( std::max( internalHeight >> i, 1u ) ); region.dstOffsets[1].z = static_cast<int32_t>( std::max( getDepth() >> i, 1u ) ); if(mTextureType == TEX_TYPE_2D_ARRAY) { region.srcOffsets[1].z = 1; region.dstOffsets[1].z = 1; } vkCmdBlitImage( device->mGraphicsQueue.mCurrentCmdBuffer, mFinalTextureName, mCurrLayout, mFinalTextureName, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1u, &region, VK_FILTER_LINEAR ); // Wait for vkCmdBlitImage on mip i to finish before advancing to mip i+1 // Also transition src mip 'i' to TRANSFER_SRC_OPTIMAL imageBarrier.oldLayout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; imageBarrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; imageBarrier.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT; imageBarrier.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); } } //----------------------------------------------------------------------------------- VkImageType VulkanTextureGpu::getVulkanTextureType( void ) const { // clang-format off switch( mTextureType ) { case TEX_TYPE_1D: return VK_IMAGE_TYPE_1D; case TEX_TYPE_2D: return VK_IMAGE_TYPE_2D; case TEX_TYPE_2D_ARRAY: return VK_IMAGE_TYPE_2D; case TEX_TYPE_CUBE_MAP: return VK_IMAGE_TYPE_2D; case TEX_TYPE_3D: return VK_IMAGE_TYPE_3D; case TEX_TYPE_EXTERNAL_OES: break; } // clang-format on return VK_IMAGE_TYPE_2D; } //----------------------------------------------------------------------------------- VkImageViewType VulkanTextureGpu::getInternalVulkanTextureViewType( void ) const { // clang-format off switch( getTextureType() ) { case TEX_TYPE_1D: return VK_IMAGE_VIEW_TYPE_1D; case TEX_TYPE_2D: return VK_IMAGE_VIEW_TYPE_2D; case TEX_TYPE_2D_ARRAY: return VK_IMAGE_VIEW_TYPE_2D_ARRAY; case TEX_TYPE_CUBE_MAP: return VK_IMAGE_VIEW_TYPE_CUBE; case TEX_TYPE_3D: return VK_IMAGE_VIEW_TYPE_3D; case TEX_TYPE_EXTERNAL_OES: break; } // clang-format on return VK_IMAGE_VIEW_TYPE_2D; } //----------------------------------------------------------------------------------- VkImageView VulkanTextureGpu::_createView( uint8 mipLevel, uint8 numMipmaps, uint16 arraySlice, uint32 numSlices, VkImage imageOverride ) const { VkImageViewType texType = this->getInternalVulkanTextureViewType(); if (numSlices == 1u && mTextureType == TEX_TYPE_CUBE_MAP) { texType = VK_IMAGE_VIEW_TYPE_2D_ARRAY; } if( !numMipmaps ) numMipmaps = mNumMipmaps - mipLevel + 1; OGRE_ASSERT_LOW( numMipmaps <= (mNumMipmaps - mipLevel + 1) && "Asking for more mipmaps than the texture has!" ); auto textureManager = static_cast<VulkanTextureGpuManager*>(TextureManager::getSingletonPtr()); VulkanDevice *device = textureManager->getDevice(); VkImageViewCreateInfo imageViewCi = {VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO}; imageViewCi.image = imageOverride ? imageOverride : mFinalTextureName; imageViewCi.viewType = texType; imageViewCi.format = VulkanMappings::get( mFormat ); if (PixelUtil::isLuminance(mFormat) && !PixelUtil::isDepth(mFormat)) { if (PixelUtil::getComponentCount(mFormat) == 2) { imageViewCi.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_G}; } else { imageViewCi.components = {VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_R, VK_COMPONENT_SWIZZLE_ONE}; } } else if (mFormat == PF_A8) { imageViewCi.components = {VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_ONE, VK_COMPONENT_SWIZZLE_R}; } // Using both depth & stencil aspects in an image view for texture sampling is illegal // Thus prefer depth over stencil. We only use both flags for FBOs imageViewCi.subresourceRange.aspectMask = VulkanMappings::getImageAspect(mFormat, imageOverride == 0); imageViewCi.subresourceRange.baseMipLevel = mipLevel; imageViewCi.subresourceRange.levelCount = numMipmaps; imageViewCi.subresourceRange.baseArrayLayer = arraySlice; if( numSlices == 0u ) imageViewCi.subresourceRange.layerCount = VK_REMAINING_ARRAY_LAYERS; else imageViewCi.subresourceRange.layerCount = numSlices; VkImageViewUsageCreateInfo flagRestriction = {VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO}; if( textureManager->canRestrictImageViewUsage() && isUav() ) { // Some formats (e.g. *_SRGB formats) do not support USAGE_STORAGE_BIT at all // Thus we need to mark when this view won't be using that bit. // // If VK_KHR_maintenance2 is not available then we cross our fingers // and hope the driver doesn't stop us from doing it (it should work) // // The validation layers will complain though. This was a major Vulkan oversight. imageViewCi.pNext = &flagRestriction; flagRestriction.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; flagRestriction.usage |= VK_IMAGE_USAGE_SAMPLED_BIT; if (mUsage & TU_RENDERTARGET) { flagRestriction.usage |= PixelUtil::isDepth(mFormat) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; } } VkImageView imageView; OGRE_VK_CHECK(vkCreateImageView( device->mDevice, &imageViewCi, 0, &imageView )); return imageView; } //----------------------------------------------------------------------------------- void VulkanTextureGpu::destroyView( VkImageView imageView ) { //VulkanTextureGpuManager *textureManager = // static_cast<VulkanTextureGpuManager *>( mCreator ); //VulkanDevice *device = textureManager->getDevice(); //delayed_vkDestroyImageView( textureManager->getVaoManager(), device->mDevice, imageView, 0 ); } //----------------------------------------------------------------------------------- VkImageView VulkanTextureGpu::createView( void ) const { OGRE_ASSERT_MEDIUM( mDefaultDisplaySrv && "Either the texture wasn't properly loaded or _setToDisplayDummyTexture " "wasn't called when it should have been" ); return mDefaultDisplaySrv; } //----------------------------------------------------------------------------------- VkImageMemoryBarrier VulkanTextureGpu::getImageMemoryBarrier( void ) const { VkImageMemoryBarrier imageMemBarrier = {VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER}; imageMemBarrier.image = mFinalTextureName; imageMemBarrier.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemBarrier.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED; imageMemBarrier.subresourceRange.aspectMask = VulkanMappings::getImageAspect(mFormat); imageMemBarrier.subresourceRange.baseMipLevel = 0u; imageMemBarrier.subresourceRange.levelCount = mNumMipmaps + 1; imageMemBarrier.subresourceRange.baseArrayLayer = 0; imageMemBarrier.subresourceRange.layerCount = getNumLayers(); return imageMemBarrier; } //----------------------------------------------------------------------------------- void VulkanTextureGpu::createMsaaSurface( void ) { VkImageCreateInfo imageInfo = {VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO}; imageInfo.imageType = getVulkanTextureType(); imageInfo.extent.width = getWidth(); imageInfo.extent.height = getHeight(); imageInfo.extent.depth = getDepth(); imageInfo.mipLevels = 1u; imageInfo.arrayLayers = 1u; imageInfo.format = VulkanMappings::get( mFormat ); imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL; imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT; imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE; imageInfo.samples = VkSampleCountFlagBits( mFSAA ); imageInfo.flags = 0; imageInfo.usage |= PixelUtil::isDepth( mFormat ) ? VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT : VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT; String textureName = getName() + "/MsaaImplicit"; auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice* device = textureManager->getDevice(); OGRE_VK_CHECK(vkCreateImage( device->mDevice, &imageInfo, 0, &mMsaaTextureName )); setObjectName(device->mDevice, (uint64_t)mMsaaTextureName, VK_DEBUG_REPORT_OBJECT_TYPE_IMAGE_EXT, textureName.c_str()); VkMemoryRequirements memRequirements; vkGetImageMemoryRequirements( device->mDevice, mMsaaTextureName, &memRequirements ); VkMemoryAllocateInfo memAllocInfo = {VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO}; memAllocInfo.allocationSize = memRequirements.size; memAllocInfo.memoryTypeIndex = 0; const auto& memProperties = device->mDeviceMemoryProperties; for(; memAllocInfo.memoryTypeIndex < memProperties.memoryTypeCount; memAllocInfo.memoryTypeIndex++) { if ((memProperties.memoryTypes[memAllocInfo.memoryTypeIndex].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT)) { break; } } OGRE_VK_CHECK(vkAllocateMemory(device->mDevice, &memAllocInfo, NULL, &mMsaaMemory)); OGRE_VK_CHECK(vkBindImageMemory(device->mDevice, mMsaaTextureName, mMsaaMemory, 0)); // Immediately transition to its only state VkImageMemoryBarrier imageBarrier = this->getImageMemoryBarrier(); imageBarrier.oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; imageBarrier.newLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL; if( PixelUtil::isDepth( mFormat ) ) imageBarrier.newLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL; imageBarrier.image = mMsaaTextureName; vkCmdPipelineBarrier( device->mGraphicsQueue.mCurrentCmdBuffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0u, 0, 0u, 0, 1u, &imageBarrier ); } //----------------------------------------------------------------------------------- void VulkanTextureGpu::destroyMsaaSurface( void ) { if(!mMsaaTextureName) return; auto textureManager = static_cast<VulkanTextureGpuManager*>(mCreator); VulkanDevice *device = textureManager->getDevice(); vkDestroyImage(device->mDevice, mMsaaTextureName, 0); vkFreeMemory(device->mDevice, mMsaaMemory, 0); } VulkanRenderTexture::VulkanRenderTexture(const String& name, HardwarePixelBuffer* buffer, uint32 zoffset, VulkanTextureGpu* target, uint32 face) : RenderTexture(buffer, zoffset) { mName = name; auto texMgr = TextureManager::getSingletonPtr(); VulkanDevice* device = static_cast<VulkanTextureGpuManager*>(texMgr)->getDevice(); target->setFSAA(1, ""); bool depthTarget = PixelUtil::isDepth(target->getFormat()); if(!depthTarget) { mDepthTexture.reset(new VulkanTextureGpu(texMgr, mName+"/Depth", 0, "", true, 0)); mDepthTexture->setWidth(target->getWidth()); mDepthTexture->setHeight(target->getHeight()); mDepthTexture->setFormat(PF_DEPTH32F); mDepthTexture->createInternalResources(); mDepthTexture->setFSAA(1, ""); } mRenderPassDescriptor.reset(new VulkanRenderPassDescriptor(&device->mGraphicsQueue, device->mRenderSystem)); mRenderPassDescriptor->mColour[0] = depthTarget ? 0 : target; mRenderPassDescriptor->mSlice = face; mRenderPassDescriptor->mDepth = depthTarget ? target : mDepthTexture.get(); mRenderPassDescriptor->mNumColourEntries = int(depthTarget == 0); mRenderPassDescriptor->entriesModified(true); } } // namespace Ogre
46.436796
122
0.630488
dawlane
4c010613929393f758a5955fe16d392919f02e27
4,419
hpp
C++
include/codegen/include/UnityEngine/UI/Mask.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
1
2021-11-12T09:29:31.000Z
2021-11-12T09:29:31.000Z
include/codegen/include/UnityEngine/UI/Mask.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
null
null
null
include/codegen/include/UnityEngine/UI/Mask.hpp
Futuremappermydud/Naluluna-Modifier-Quest
bfda34370764b275d90324b3879f1a429a10a873
[ "MIT" ]
2
2021-10-03T02:14:20.000Z
2021-11-12T09:29:36.000Z
// Autogenerated from CppHeaderCreator on 7/27/2020 3:10:38 PM // Created by Sc2ad // ========================================================================= #pragma once #pragma pack(push, 8) // Begin includes // Including type: UnityEngine.EventSystems.UIBehaviour #include "UnityEngine/EventSystems/UIBehaviour.hpp" // Including type: UnityEngine.ICanvasRaycastFilter #include "UnityEngine/ICanvasRaycastFilter.hpp" // Including type: UnityEngine.UI.IMaterialModifier #include "UnityEngine/UI/IMaterialModifier.hpp" #include "utils/il2cpp-utils.hpp" // Completed includes // Begin forward declares // Forward declaring namespace: UnityEngine namespace UnityEngine { // Forward declaring type: RectTransform class RectTransform; // Forward declaring type: Material class Material; // Forward declaring type: Vector2 struct Vector2; // Forward declaring type: Camera class Camera; } // Forward declaring namespace: UnityEngine::UI namespace UnityEngine::UI { // Forward declaring type: Graphic class Graphic; } // Completed forward declares // Type namespace: UnityEngine.UI namespace UnityEngine::UI { // Autogenerated type: UnityEngine.UI.Mask class Mask : public UnityEngine::EventSystems::UIBehaviour, public UnityEngine::ICanvasRaycastFilter, public UnityEngine::UI::IMaterialModifier { public: // private UnityEngine.RectTransform m_RectTransform // Offset: 0x18 UnityEngine::RectTransform* m_RectTransform; // private System.Boolean m_ShowMaskGraphic // Offset: 0x20 bool m_ShowMaskGraphic; // private UnityEngine.UI.Graphic m_Graphic // Offset: 0x28 UnityEngine::UI::Graphic* m_Graphic; // private UnityEngine.Material m_MaskMaterial // Offset: 0x30 UnityEngine::Material* m_MaskMaterial; // private UnityEngine.Material m_UnmaskMaterial // Offset: 0x38 UnityEngine::Material* m_UnmaskMaterial; // public UnityEngine.RectTransform get_rectTransform() // Offset: 0x11EBDC0 UnityEngine::RectTransform* get_rectTransform(); // public System.Boolean get_showMaskGraphic() // Offset: 0x11EBE40 bool get_showMaskGraphic(); // public System.Void set_showMaskGraphic(System.Boolean value) // Offset: 0x11EBE48 void set_showMaskGraphic(bool value); // public UnityEngine.UI.Graphic get_graphic() // Offset: 0x11EBF20 UnityEngine::UI::Graphic* get_graphic(); // public System.Boolean MaskEnabled() // Offset: 0x11EBFB0 bool MaskEnabled(); // public System.Void OnSiblingGraphicEnabledDisabled() // Offset: 0x11EC050 void OnSiblingGraphicEnabledDisabled(); // protected System.Void .ctor() // Offset: 0x11EBFA0 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::.ctor() // Base method: System.Void MonoBehaviour::.ctor() // Base method: System.Void Behaviour::.ctor() // Base method: System.Void Component::.ctor() // Base method: System.Void Object::.ctor() // Base method: System.Void Object::.ctor() static Mask* New_ctor(); // protected override System.Void OnEnable() // Offset: 0x11EC054 // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnEnable() void OnEnable(); // protected override System.Void OnDisable() // Offset: 0x11EC37C // Implemented from: UnityEngine.EventSystems.UIBehaviour // Base method: System.Void UIBehaviour::OnDisable() void OnDisable(); // public System.Boolean IsRaycastLocationValid(UnityEngine.Vector2 sp, UnityEngine.Camera eventCamera) // Offset: 0x11EC4E4 // Implemented from: UnityEngine.ICanvasRaycastFilter // Base method: System.Boolean ICanvasRaycastFilter::IsRaycastLocationValid(UnityEngine.Vector2 sp, UnityEngine.Camera eventCamera) bool IsRaycastLocationValid(UnityEngine::Vector2 sp, UnityEngine::Camera* eventCamera); // public UnityEngine.Material GetModifiedMaterial(UnityEngine.Material baseMaterial) // Offset: 0x11EC5AC // Implemented from: UnityEngine.UI.IMaterialModifier // Base method: UnityEngine.Material IMaterialModifier::GetModifiedMaterial(UnityEngine.Material baseMaterial) UnityEngine::Material* GetModifiedMaterial(UnityEngine::Material* baseMaterial); }; // UnityEngine.UI.Mask } DEFINE_IL2CPP_ARG_TYPE(UnityEngine::UI::Mask*, "UnityEngine.UI", "Mask"); #pragma pack(pop)
42.085714
147
0.732519
Futuremappermydud
4c03ecd5ab9d1dbdbefc12556bca25d2d7107df8
26,916
cpp
C++
Source/Gadgets/Mining/1_FastFrequentSubgraphMining/pattern.cpp
spxuw/RFIM
32b78fbb90c7008b1106b0cff4f8023ae83c9b6d
[ "MIT" ]
null
null
null
Source/Gadgets/Mining/1_FastFrequentSubgraphMining/pattern.cpp
spxuw/RFIM
32b78fbb90c7008b1106b0cff4f8023ae83c9b6d
[ "MIT" ]
null
null
null
Source/Gadgets/Mining/1_FastFrequentSubgraphMining/pattern.cpp
spxuw/RFIM
32b78fbb90c7008b1106b0cff4f8023ae83c9b6d
[ "MIT" ]
null
null
null
#pragma warning (disable:4786 4018 4267) #include <vector> #include <fstream> #include <algorithm> #include <set> using namespace std; #include "pattChild.h" gBase * pattern ::gb = NULL; MyTimer * pattern ::Timers = NULL; Register * pattern ::Registers = NULL; DLONG pattern ::totalPatterns = 0; bool pattern :: denseEnough(int d, int sizeup, bool final){ int s = M->size(); if( s == 1 || s== 2) return true; return M->size() <= sizeup && M->denseEnough(d, final); } void pattern :: initPattern(gBase *gb1, MyTimer & t, Register & mr){ gb = gb1; Timers = &t; Registers = &mr; } int pattern:: isCarnonicalForm(void) { stage = 1; #ifdef TIMERFLAG Timers->start_timer(TIMER4); #endif fixM(); #ifdef TIMERFLAG Timers->stop_timer(TIMER4); #endif #ifdef TIMERFLAG Timers->start_timer(TIMER2); #endif int flag = M->isCanonicalForm(); #ifdef TIMERFLAG Timers->stop_timer(TIMER2); #endif return flag; } void pattern:: sprint(int level) { cout << "the adj matrix is" << endl; if( M ) M->print(); else cout <<"matrix is not initialized" <<endl; cout << "pattern optimal " << optimal << " cost " << hex << mycost.intValue() << dec << endl; if( level & 2 ){ cout << "the coccs structures are: size: " << coccs->size() << endl; COCCS :: iterator ip1; for(ip1 = coccs->begin(); ip1 != coccs->end(); ip1++){ DLONG key = *ip1; cout << "index is " << (FIRSTKEY(key) ) << " node is " << (THIRDKEY(key)) << " graph " << (SECONDKEY(key)) << endl; } } if( level & 4 ){ cout << "there are total: " << child.size() << " children in this pattern " << endl; vector<pattern *> :: iterator ip1 ; for(ip1 = child.begin(); ip1 != child.end(); ip1++){ (*ip1)->sprint(5); } } } void pattern:: print() { cout << "the adj matrix is" << endl; if( M ) M->print(); else cout <<"matrix is not initialized" <<endl; //int i; cout << "the index structure are" << endl; COCCS :: iterator ip1; for(ip1 = coccs->begin(); ip1 != coccs->end(); ip1++){ DLONG key = *ip1; cout << "index is " << (int)(FIRSTKEY(key) ) << " node is " << (int) (THIRDKEY(key)) << endl; } cout << "cost is " << hex << mycost.intValue() << endl; } void pattern:: fsm1( vector<AdjMatrix * > & result, int freq, int level, int density, string nodef, string edgef, string header, int sizelimit, int sizeup, map<int, int> & gIndex) { CHLTYPE :: iterator ip; //cout << "start search total frequent node :" << child.size() << endl; vector<pattern*> wlist; int totalnum = 0; for( ip = child.begin(); ip!=child.end(); ip++){ //cout << "search with support: " << (*ip)->sup() << endl; #ifdef DEBUG3 cout << "start search" << endl; (*ip)->sprint(3); #endif //(*ip)->print(); (*ip)->fsm2(result, freq, level+1, totalnum, density, nodef, edgef, header, sizelimit, sizeup, gIndex); //delete the edge; delete (*ip); } //cout << "=====FFSM Results Are =====" << endl; cout << "Total frequent patterns: " << dec << totalnum << "\t"; #ifdef DEBUG8 edbLocal->print(); #endif } void pattern:: fsm2( vector<AdjMatrix * > & result, int freq, int level, int& totalnum, int density, string nodef, string edgef, string header, int sizelimit, int sizeup, map<int, int> & gIndex){ #ifdef DEBUG2 cout << "search at level " << level << endl; sprint(3); #endif stage = 4; if( level >= 2){ totalnum++; if( totalnum % 1000 == 0 ) cout <<"."; if( totalnum % 10000 == 0 ) cout << totalnum << "\n"; #ifdef REGISTERFLAG if( M->isPath() ) Registers->peg(REGISTER1); #endif M->setTotalSup(sup()); #ifdef SAVERESULTS /* #if (SAVERESULTS == 3) //vector<occur*> loccs; //recordOccs(loccs); //M->setGraphs(loccs); */ #if (SAVERESULTS == 2) M->setTIDs(gids); #endif result.push_back(M); #endif } //should output the results if( result.size() >= BUFFERSIZE){ cout << "output results " << totalnum << endl; for(int ri=0; ri< result.size(); ri++){ bool dflag = true; #ifdef DENSITY if(!result[ri]->denseEnough(density, true) && M->size() <= sizeup) dflag = false; #endif #ifdef SAVERESULTS if( dflag && result[ri]->size()>= sizelimit) result[ri]->print(totalPatterns++, nodef, edgef, header, gIndex); delete result[ri]; #endif } result.clear(); } pattern * pi, *pj; bool maximal; for( int i = 0; i< child.size(); i++){ pi = child[i]; vector<pattern*> outChild; #ifdef DEBUG3 for( int lii = 0; lii< level; lii++) cout << " "; cout << "cost and child size " << hex << pi->mycost.intValue() << dec << " " << pi->child.size() << endl; #endif if( (pi->optimal & 1) && pi->denseEnough(density, sizeup, false) ){ //the pattern must be in carnonical form for subsequent search maximal = true; if( size != pi->size ) { //only one edge in the last row #ifdef TIMERFLAG Timers->start_timer(TIMER3); #endif #ifdef TIMERFLAG Timers->start_timer(TIMER6); #endif maximal = pi->proposeOuterChild(freq, outChild); #ifdef TIMERFLAG Timers->stop_timer(TIMER6); #endif #ifdef TIMERFLAG Timers->stop_timer(TIMER3); #endif } #if (defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) if( maximal ){ #endif #ifdef DEBUG2 cout << "children are (proposed by outer): " << endl; int k = 0; for( ; k< pi->outChild.size(); k++) (pi->child[k])->sprint(); #endif for(int j = i; j< child.size(); j++){ pj = child[j]; pi->join(pj, freq); } #ifdef DEBUG2 cout << "completed child proposing" << endl; cout << "children are: " << endl; for( k=0; k< pi->child.size(); k++) (pi->child[k])->sprint(); #endif //post processing (pi->child).insert((pi->child).end(), (pi->newchild).begin(), (pi->newchild).end()); (pi->child).insert((pi->child).end(), outChild.begin(), outChild.end()); pi->fsm2( result,freq, level+1 , totalnum, density, nodef, edgef, header, sizelimit, sizeup, gIndex); #if (defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) } #endif //if( pi->size == 2) gb->removeEdge(pi->mycost.intValue()); } delete pi; /*definitely need to be taken care of*/ } } void pattern:: constructM (void){ char node1 = (char) mycost.index(); char node2 = mycost.nlabel(); char edge = mycost.elabel(); M = new AdjMatrix(); M->addNode(node1); M->addNode(node2); M->addEdge(0, 1, edge); M->buildAdjList(); } void pattern:: fixM(void){ int index = mycost.index(); GLTYPE nlabel; int s1 = par->getSize(); if( s1 == size){ index -= s1; nlabel = EMPTY_EDGE; } else nlabel = mycost.nlabel(); index = size-2-index; //M = new AdjMatrix(M, index, mycost.elabel(), nlabel ); M = new AdjMatrix(M, size-1, index, mycost.elabel(), nlabel ); stage &= 1; } void pattern::setChild(EDGES & cm, EDGES & nm) { EDGES::iterator ip; vector<int> u; ip = cm.begin(); int v = COSTINDEX(ip->first), v1, k; u.push_back(ip->first); ip++; //search for those edges sharing the start node for( ; ip!= cm.end() ; ip++){ k = ip->first; v1 = COSTINDEX(k); if( v1 == v) u.push_back(k); else{ child.push_back(setUpChild(u, cm, nm, v)); u.clear(); u.push_back(k); v = v1; } } child.push_back(setUpChild(u, cm, nm, v)); } pattern * pattern :: setUpChild(vector<int> u, EDGES & edges, EDGES & gnodes, int nlabel) { pattern * p1 = new pattern(this, 0, 1), * p2; CHLTYPE & c1 = p1->child; TRA lmapper; //populate the lmapper OCCS * es = gnodes[nlabel]; OCCS::iterator oip = es->begin(); int index =0; for(; oip != es->end(); oip++){ occur * oc = *oip; DLONG key = MAKEKEY(INULLINDEX, oc->getGraph(), oc->getNodes(0)); if( lmapper.count(key) ) error("duplicated key"); lmapper[key] = index++; p1->coccs->push_back(key); } int i; for(i=0; i< u.size(); i++){ es = edges[u[i]]; p2 = new pattern(p1, u[i], 2); p2->constructM(); setUpEdges(p2, es, lmapper); #ifdef DEBUG5 cout << "p2 " << endl; p2->print(); #endif c1.push_back(p2); } #ifdef DEBUG5 cout << "p1 " << endl; p1->print(); #endif return p1; } void pattern :: setUpEdges(pattern * p2, OCCS * es, TRA & tra1) { //set up for the p2(edge) COCCS * cos2 = p2->coccs; GRAPHS1 & gid2 = p2->gids; int gi, d1, d2, t1, j; DLONG key; //every edge is frequent and in carnonical form p2->optimal = 1; for(j=0; j< es->size(); j++){ occur * noc = (*es)[j]; gi = noc->getGraph(); d1 = noc->getNodes(0), d2 = noc->getNodes(1); key = MAKEKEY(INULLINDEX, gi, d1); if( !tra1.count(key) ) error("the hash at p1 is not setting up"); t1 = tra1[key]; cos2->push_back(MAKEKEY(t1, gi, d2)); //for(int m=0; m< gid2.size(); m++){ // if( gid2[m] > gi) error("why redundant graphs"); if( !gid2.size() || gi != gid2[gid2.size()-1] ) gid2.push_back(gi); //} //if( !gid2.size() ) gid2.push_back(gi); } } void pattern :: join(pattern * p2, int freq){ cost1 c2 = p2->mycost; int index1 = mycost.index(),node1 = mycost.nlabel(); int index2 = c2.index(), node2 = c2.nlabel(); //check the intersection int sum=0; GRAPHS1 ::iterator iip1 = gids.begin(), iip2 = p2->gids.begin(); while( iip1 != gids.end() && iip2 != p2->gids.end() ){ if( *iip1 == * iip2){ iip1++; iip2++; sum++;} else if( * iip1 > *iip2) *iip2++; else iip1++; } //no way to be frequent if( sum < freq ) return; //test carnonical form first or occurrence first bool mf = true; if( size > 5) mf = false; //get the type of the join pattern * p3 = NULL;; int t = par->getSize(), type; //special treatment only for the first edge if( size == 2) index1 = index2 = 0; if( index2 >= t) { //inner + inner //notice it is okay for look back if( index1 != index2 && node1 == node2 ){ p3 = new pattern(this, c2.intValue(), size); type = 1; } } else if( index1 >= t){ //inner + outer p3 = new pattern(this, c2.intValue(), size+1); type = 2; } else{ if( index1 != index2 ){ #ifndef TREEBASEDSCAN if( node1 == node2 ){ int c = ((size+index2) << 16 ) | (c2.elabel() << 8 ) | node2; p3 = new pattern(this, c, size); type = 3; if ( join1(p2, p3, type, freq, mf) ) child.push_back(p3); else { delete p3 ; /*definitely need to be taken care of*/ } } #endif } else{ if( mycost.intValue()> c2.intValue() && p2->optimal){ //the only case we might switch the order p2->join(this, freq); } } int c = ((1+index2) << 16 ) | (c2.elabel() << 8 ) | node2; p3 = new pattern(this, c, size+1); type = 4; } //test for inner join of occurrences if ( p3 ) if(join1(p2, p3, type, freq, mf) ){ if( type == 4) newchild.push_back(p3); else child.push_back(p3); } else{ delete p3; /*definitely need to be taken care of*/ } } bool pattern :: join1(pattern * p2, pattern * p3, int type, int freq, bool mf) { //test carnonical form is mf is marked int t; bool carno = false; bool support = false; #ifdef REGISTERFLAG if( !support){ Registers->peg(REGISTER1); } #endif if( mf) { t = p3->isCarnonicalForm(); if( t< 0) { carno = false; } else{ if( t> 0 ) p3->optimal = 1; carno = true; //for optimal and suboptimal } } //get the inner join of occurrences #ifdef TIMERFLAG Timers->start_timer(TIMER3); #endif if( !mf || carno ){ if( (type & 1) ){ support = propose_inner(p2, p3, freq); } else if( type == 2){ support = propose_inner_outer(p2, p3, freq); } else{ support = propose_outer2(p2, p3, freq); } } #ifdef REGISTERFLAG if( !support){ Registers->peg(REGISTER2); } #endif #ifdef TIMERFLAG Timers->stop_timer(TIMER3); #endif //if frequent, to see whether in carnonical form or not if( !mf && support) { t = p3->isCarnonicalForm(); if( t< 0){ carno = false; optimal |= 2; } //added by Luke for Maximal else{ if( t> 0 ) p3->optimal = 1; carno = true; } } #ifdef DEBUG2 cout << "type : carnonical form and support test: " << type << " " << t << " " << support << endl; #endif //passed everything if( !carno || !support ) return false; else{ return true; } } //for inner + inner or outer + outer `case 1 bool pattern :: propose_inner(pattern * p2, pattern * p3, int freq) { //set up COCCS :: iterator ip1, ip2; COCCS * cos2 = p2->coccs; ip1 = coccs->begin(); ip2 = cos2->begin(); COCCS * cos3 = p3->coccs; GRAPHS1 & gid3 = p3->gids; int index =0; bool flag = true; while( ip1 != coccs->end() && ip2 != cos2->end() ){ if( *ip1 == *ip2 ){ int gi = SECONDKEY(*ip1); cos3->push_back(MAKEKEY(index, gi, GNULLINDEX)); //graph3->insert(gi); //update if( !gid3.size() || gi != gid3[gid3.size()-1]) gid3.push_back(gi); //end ip1++; index++; ip2++; } else if( *ip1 > *ip2 ){ ip2++; flag = false; } else{ ip1++; index++; } } #if (defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) if( flag ){ p2->optimal=0; //added by Luke for Maximal #ifdef DEBUG11 cout << "this is one absorbing "<< endl; #endif } #endif if( p3->sup() >= freq) { p3->stage = p3->stage | 2; return true; } else return false; } //for inner + outer bool pattern :: propose_inner_outer(pattern * p2, pattern * p3, int freq) { //set up COCCS :: iterator ip1, ip2, ips, ipe; COCCS * cos2 = p2->coccs; ip1 = coccs->begin(); ip2 = cos2->begin(); COCCS * cos3 = p3->coccs; GRAPHS1 & gid3 = p3->gids; int index = 0, t, k; bool flag = true; while( ip1 != coccs->end() && ip2 != cos2->end() ){ t = FIRSTKEY(*ip1); k = FIRSTKEY(*ip2); if( t == k ){ //find the ipe ips = ipe = ip2; while( ipe != cos2->end() && ( FIRSTKEY(*ipe) == t ) ) ipe++; int gi = SECONDKEY(*ip1); //graph3->insert(gi); //update if( !gid3.size() || gi != gid3[gid3.size()-1]) gid3.push_back(gi); //end for( ; ip2 != ipe; ip2++){ cos3->push_back(MAKEKEY(index, gi, THIRDKEY(*ip2))); } ip1++; index++; } else if( t > k ){ ip2++; flag = false; } else{ ip1++; index++; } } #if ( defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) if( flag ){ p2->optimal=0; //added by Luke for Maximal #ifdef DEBUG11 cout << "this is one absorbing in inner_outer "<< endl; #endif } #endif if( p3->sup() >= freq) { p3->stage = p3->stage | 2; return true; } else return false; } //for outer + outer case 2 bool pattern :: propose_outer2(pattern * p2, pattern * p3, int freq) { COCCS :: iterator ip1, ip2, ips, ipe; COCCS * cos2 = p2->coccs; ip1 = coccs->begin(); ip2 = cos2->begin(); COCCS * cos3 = p3->coccs; GRAPHS1 & gid3 = p3->gids; int index = 0, t, k; while( ip1 != coccs->end() && ip2 != cos2->end() ){ t = FIRSTKEY(*ip1); k = FIRSTKEY(*ip2); if( t == k ){ //find the ipe ips = ipe = ip2; while( ipe != cos2->end() && ( FIRSTKEY(*ipe) == t ) ) ipe++; int gi = SECONDKEY(*ip1); bool flag = false; for( ; ip2 != ipe; ip2++){ if( *ip1 != *ip2){ cos3->push_back(MAKEKEY(index, gi, THIRDKEY(*ip2))); flag = true; } } //if( flag ) graph3->insert(gi); if( flag ) //update if( !gid3.size() || gi != gid3[gid3.size()-1]) gid3.push_back(gi); //end ip1++; index++; ip2 = ips; } else if( t > k ){ ip2++; } else{ ip1++; index++; } } if( p3->sup() >= freq) { p3->stage = p3->stage | 2; return true; } else return false; } bool pattern:: proposeOuterChild(int freq, vector<pattern*> & outChild){ COCCS :: iterator ip = coccs->begin(); int i, u, gi, x, key, level; map<int, pattern * , greater<int> > children; int elabel, nlabel; AdjMatrix * gbi; pattern * p3; //for update int edgeSize = M->esize(), j; pattern * currp = this; vector<COCCS*> coccslist; vector<int> gindices(edgeSize, INULLINDEX); vector<short> checkpoint(edgeSize+1, 0); // DLONG mykey; int fkey, skey, fkey1; //cout << "start search" << endl; #if (defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) initialEdgeCan(); #endif for( i=0; i<= edgeSize; i++){ //update if( THIRDKEY((*(currp->coccs))[0]) != GNULLINDEX ) checkpoint[i] = 1; //end coccslist.push_back(currp->coccs); currp = currp->par; } vector<GNSIZE> filter(size, 0); for( i=0; ip != coccs->end(); i++ , ip++){ fkey = FIRSTKEY((*coccs)[i]), skey = THIRDKEY((*coccs)[i]); gi = SECONDKEY((*coccs)[i]); u = skey; level = 1; filter[0]= skey; for( j=0; j< edgeSize && fkey != gindices[j]; j++){ gindices[j] = fkey; fkey1 = FIRSTKEY((*(coccslist[j+1]))[fkey]); if( checkpoint[j+1]) filter[level++]= THIRDKEY((*(coccslist[j+1]))[fkey]); fkey = fkey1; } #ifdef DEBUG10 vector<GNSIZE> :: iterator fip = filter.begin(); cout << "the nodes in the filter " << i << endl; for( fip = filter.begin(); fip != filter.end(); fip++){ cout << (int) *fip << "\t" ; } cout << endl; #endif //get the neighbors gbi = gb->graph(gi); #if (defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) fillMoreEdge(filter, gbi); #endif //for debugging only vector<GNSIZE> * nei = gbi->getNeighbors(u); //propose child for( j=0; j< nei->size(); j++){ x = (*nei)[j]; if( (find(filter.begin(), filter.end(), x) == filter.end() ) && gbi->getLabel(u, x) != EMPTY_EDGE){ elabel = gbi->getLabel(u, x); nlabel = gbi->getLabel(x, x); key = elabel << 8 | nlabel; #ifdef REGISTERFLAG //cout << "* " << endl; Registers->peg(REGISTER3); #endif if( children.count(key) ){ p3 = children[key]; } else{ p3 = new pattern(this, key, size+1); children[key] = p3; } if( !p3->gids.size() || gi != p3->gids[p3->gids.size()-1]) p3->gids.push_back(gi); p3->coccs->push_back(MAKEKEY(i, gi, x)); } } } #if (defined MAXIMALPATTERN && (MAXIMALPATTERN & 1) ) if( !isInnerMaximal() ){ map<int, pattern * , greater<int> > ::iterator cit = children.begin(); for( ; cit != children.end(); cit++) delete cit->second; //#ifdef DEBUG12 //cout << "remove one "<< endl; //#endif return false; } #endif //scan children to see whether it is frequent and optimal scan(children,freq, outChild); return true; } void pattern:: scan(map<int, pattern*, greater<int> > & cand, int f, vector<pattern*> & result) { map<int, pattern*, greater<int> > :: iterator ip; for(ip = cand.begin(); ip!= cand.end(); ip++){ pattern * p = ip->second; #ifdef REGISTERFLAG Registers->peg(REGISTER8); #endif if( p->sup() < f ) { #ifdef REGISTERFLAG Registers->peg(REGISTER7); #endif #ifdef DEBUG2 cout << "failed support test " << endl; #endif delete p; /*definitely need to be taken care of*/ } else { int t = p->isCarnonicalForm(); #ifdef DEBUG2 cout << "the scan test and t value: " << t << endl; #endif if( t < 0 ) { #ifdef REGISTERFLAG Registers->peg(REGISTER6); #endif delete p; /*definitely need to be taken care of*/ optimal |= 2; /*added by Luke for maixmal*/ } else { p->optimal = t; //if( t == 1) p->fixOccs(); result.push_back(p); #ifdef REGISTERFLAG if( !t ) Registers->peg(REGISTER5); else Registers->peg(REGISTER4); #endif } } } } //save results #ifdef SAVERESULTS void pattern:: recordOccs(vector<occur*> & loccs) { //for update //M->print(); int edgeSize = M->esize(), j; pattern * currp = this; vector<int> gindices(edgeSize, INULLINDEX); vector<short> checkpoint(edgeSize+1, 0); vector<COCCS*> coccslist; // DLONG mykey; int fkey, skey, fkey1, gi, u, level, i; //cout <<"edge size " << edgeSize << endl; for( i=0; i<= edgeSize; i++){ if( THIRDKEY((*(currp->coccs))[0]) != GNULLINDEX ) checkpoint[i] = 1; coccslist.push_back(currp->coccs); currp = currp->par; } /* cout << "check points" << endl; for(i=0; i< checkpoint.size(); i++) cout << checkpoint[i] << " "; cout << endl; */ vector<GNSIZE> filter(size, 0); COCCS :: iterator ip = coccs->begin(); for( i=0; ip != coccs->end(); i++ , ip++){ fkey = FIRSTKEY((*coccs)[i]), skey = THIRDKEY((*coccs)[i]); gi = SECONDKEY((*coccs)[i]); u = skey; level = 0; if( checkpoint[0] ){ filter[0]= skey; level++; } for( j=0; j< edgeSize && fkey != gindices[j]; j++){ gindices[j] = fkey; fkey1 = FIRSTKEY((*(coccslist[j+1]))[fkey]); if( checkpoint[j+1]) filter[level++]= THIRDKEY((*(coccslist[j+1]))[fkey]); fkey = fkey1; } loccs.push_back(new occur(filter, gi)); } } #endif #ifdef GSPANFLAG void pattern :: findAllIsomorphisms(){ GRAPHS ::iterator ip = graphs->begin(); int sum=0; for(; ip!= graphs->end(); ip++){ //cout << *ip << endl; AdjMatrix * tg = gb->graph(*ip); sum += tg->findAllIsomophisms(M); } if( sum != occs->size()){ cout << "sum:" << sum << "\t" << occs->size(); M->print(); error("couting error"); } } #endif #ifdef MAXIMALPATTERN void pattern :: fillMoreEdge(vector<GNSIZE> & nodes, AdjMatrix * gbi ) { int key; short n1, n2; GLTYPE c; list<int>::iterator sit = edgeCan.begin(), sit1; list<GLTYPE> ::iterator lit = edgeLabels.begin(), lit1; bool flag; int n = nodes.size(); //cout << "new round of updating" << endl; for( sit; sit != edgeCan.end(); ){ key = *sit; n1 = key >> 16; n2 = (short) (key & 0x0000ffff); c = gbi->getLabel(nodes[n-n1-1], nodes[n-n2-1]); //cout << "n1 n2 c " << n1 << " " << n2 << " " << c << " " << (*lit) << endl; flag = false; if( c != EMPTY_EDGE ){ if( (*lit) == EMPTY_EDGE ) (*lit) = c; //initialization else if( c != (*lit)) flag = true; } else flag = true; sit1 = sit++; lit1 = lit++; if( flag ){ edgeCan.erase(sit1); edgeLabels.erase(lit1); } } } bool pattern :: isInnerMaximal(){ return ( !edgeLabels.size() ); } void pattern :: initialEdgeCan(){ int key; int index = mycost.index(); int s1 = par->getSize(); if( s1 == size) index -= s1; index = size-2-index; //M->print(); //cout <<"initialization" << endl; for(short i=1; i< (short) size; i++){ for( short j=0; j< i; j++){ if( M->getLabel(i, j) == EMPTY_EDGE && ( i != (size-1) || j< index) ){ key = (((int) i) << 16 ) | ((int) j); edgeCan.push_back(key); edgeLabels.push_back(EMPTY_EDGE); } } } } bool pattern :: isMaximal(int threshold){ CGOCC localCounter; /* //obtain each occurrence int edgeSize = M->esize(), j; pattern * currp = this; vector<int> gindices(edgeSize, INULLINDEX); vector<short> checkpoint(edgeSize+1, 0); vector<COCCS*> coccslist; int fkey, skey, fkey1, gi, level, i; for( i=0; i<= edgeSize; i++){ if( THIRDKEY((*(currp->coccs))[0]) != GNULLINDEX ) checkpoint[i] = 1; coccslist.push_back(currp->coccs); currp = currp->par; } vector<GNSIZE> filter(size, 0); COCCS :: iterator ip = coccs->begin(); for( i=0; ip != coccs->end(); i++ , ip++){ fkey = FIRSTKEY((*coccs)[i]), skey = THIRDKEY((*coccs)[i]); gi = SECONDKEY((*coccs)[i]); //u = skey; level = size-1; if( checkpoint[0] ) filter[level--]= skey; for( j=0; j< edgeSize && fkey != gindices[j]; j++){ gindices[j] = fkey; fkey1 = FIRSTKEY((*(coccslist[j+1]))[fkey]); if( checkpoint[j+1]) filter[level--]= THIRDKEY((*(coccslist[j+1]))[fkey]); fkey = fkey1; } */ SCANOCCURRENCES //update the counting procedure if( countSuperGraph(filter, gi, localCounter, threshold) ) return false; //loccs.push_back(new occur(filter, gi)); } //is maximal return true; } bool pattern :: countSuperGraph(vector<GNSIZE> & nodes, int gi, CGOCC & counter, int threshold){ AdjMatrix * gbi = gb->graph(gi); //inner checking GLTYPE c; int n = nodes.size()-1; #ifdef SAFEMODE if( n >= 127 ) error("pattern size is too large (> byte)"); #endif int key, value, i, j, k; vector<GNSIZE> * nei; vector<GNSIZE> :: iterator nip; for( i=1; i<= n; i++){ nei = gbi->getNeighbors(nodes[i]); for( k=0; k< nei->size(); k++){ if( (j = (int) (find(nodes.begin(), nodes.end(), (*nei)[k]) - nodes.begin() ) ) < i && M->getLabel(i,j) == EMPTY_EDGE){ c = gbi->getLabel(nodes[i], nodes[j]); key = (i << 24) | (j << 16) | 0 | c; if( !counter.count(key) ){ counter[key] = ( (gi<<16) | 1); //if( 1 >= threshold) return true; } value = counter[key]; if( (value >> 16) != gi) { counter[key] = (gi<<16) | ( (++value) & 0x0000ffff ); if( (value & 0x0000ffff) >= threshold ) return true; } } } } //outer checking int x; for( i=0; i<= n; i++){ nei = gbi->getNeighbors(nodes[i]); //propose child for( j=0; j< nei->size(); j++){ x = (*nei)[j]; if( (find(nodes.begin(), nodes.end(), x) == nodes.end() ) && (c=gbi->getLabel(nodes[i], x)) != EMPTY_EDGE ){ key = ((n+1) << 24) | (i<<16) | (gbi->getLabel(x,x) << 8 ) | c; if( !counter.count(key) ){ counter[key] = ( (gi<<16) | 1); //if( 1 >= threshold) return true; } value = counter[key]; if( value >> 16 != gi){ counter[key] = (gi<<16) | (( ++value ) & 0x0000ffff ); if( (value & 0x0000ffff) >= threshold ) return true; } } } } return false; } #endif void pattern:: frequentElement(vector<pattern*> & results, int freq){ //getElements FREELE candidates; scanElements(candidates, freq); //add to true patterns enuFreqEle(candidates, results, freq); } void pattern:: enuFreqEle(FREELE & candidates, vector<pattern*> & results , int freq) { } void pattern:: scanElements(FREELE & candidates , int freq) { ELEFRENQC counter; SCANOCCURRENCES addInstances(counter, filter, gi, i); } //post processing ELEFRENQC ::iterator eip = counter.begin(); IIDTYPE * tids; int sup; for( ; eip != counter.end(); eip++){ tids = eip->second; tids->push_back(eip->first); if( (sup = getSupport(tids) ) > freq ) { tids->push_back(sup); candidates.push_back(tids); } else delete tids; } //potentially sorting } void pattern :: addInstances(ELEFRENQC & counter, vector<GNSIZE> & nodes, int gi, int instanceID) { AdjMatrix * gbi = gb->graph(gi); int i, k,j, key; GLTYPE c; vector<GNSIZE> * nei; int n = nodes.size()-1; IIDTYPE * value; for( i=1; i<= n; i++){ nei = gbi->getNeighbors(nodes[i]); for( k=0; k< nei->size(); k++){ if( (j = (int) (find(nodes.begin(), nodes.end(), (*nei)[k]) - nodes.begin() ) ) < i && M->getLabel(i,j) == EMPTY_EDGE){ c = gbi->getLabel(nodes[i], nodes[j]); key = (i << 24) | (j << 16) | 0 | c; if( !counter.count(key) ) //initialization counter[key] = new IIDTYPE( (coccs->size()+31)/32 ); //initialize with zero value = counter[key]; TURNON(*value, instanceID); } } } } /* bool pattern :: intersectInstances(FREELE & ele1, FREELE & ele2){ return true //is closed } */ int pattern:: getSupport( IIDTYPE * iid) { int sup = 0; int gi=-1; for(int i=0; i< coccs->size(); i++){ if( GETTID(*iid, i) ){ if( gi != SECONDKEY((*coccs)[i]) ){ gi = SECONDKEY((*coccs)[i]); sup++; } } } return sup; }
21.688961
133
0.578875
spxuw
4c04c6967e347f91d24db94f0fe214a600cf3d56
9,354
cpp
C++
al_ui/src/scenerenderer.cpp
xorsnn/altexo
2587ecd66a970d6805cc40635a9ec19786b05dce
[ "MIT" ]
1
2018-09-06T15:37:19.000Z
2018-09-06T15:37:19.000Z
al_ui/src/scenerenderer.cpp
xorsnn/altexo
2587ecd66a970d6805cc40635a9ec19786b05dce
[ "MIT" ]
null
null
null
al_ui/src/scenerenderer.cpp
xorsnn/altexo
2587ecd66a970d6805cc40635a9ec19786b05dce
[ "MIT" ]
null
null
null
#include "scenerenderer.hpp" SceneRenderer::SceneRenderer(int winWidth, int winHeight) : WIDTH(0), HEIGHT(0), pendingRenderTexResize(false), m_debug(true), m_remoteFrameRenderer(-0.5, -0.5, -0.5, -0.5), m_localFrameRenderer(-0.5, -0.5, -0.5, -0.5), m_winWidth(winWidth), m_winHeight(winHeight), m_remoteStreamMode(al::MODE_2D), m_localStreamMode(al::MODE_2D) { _updateRenderersPos(); } void SceneRenderer::setRemoteStreamMode(al::VideoMode mode) { m_remoteStreamMode = mode; } void SceneRenderer::setLocalStreamModeCb(al::VideoMode mode) { m_localStreamMode = mode; } void SceneRenderer::updateResolutionCb(int width, int height) { WIDTH = width; HEIGHT = height; m_sensorDataFboRenderer.onUpdateResolution(width, height); pendingRenderTexResize = true; } int SceneRenderer::init() { m_newFrame = false; // GL_CHECK_ERRORS m_bottomPlane.init(); m_hologram.init(); initFBO(); m_sensorDataFboRenderer.init(); // TODO: doesn't make sense sitce it's default if (m_remoteStreamMode == al::MODE_2D) { m_remoteFrameRenderer.init(); } m_localFrameRenderer.init(); m_worldCoordinate.init(); // setup the camera position and target // cam.SetPosition(glm::vec3(1, 1, 1)); cam.SetPosition(glm::vec3(1000, 1000, 1000)); cam.SetTarget(glm::vec3(0, 0, 0)); // also rotate the camera for proper orientation glm::vec3 look = glm::normalize(cam.GetTarget() - cam.GetPosition()); float yaw = glm::degrees(float(atan2(look.z, look.x) + M_PI)); float pitch = glm::degrees(asin(look.y)); rX = yaw; rY = pitch; cam.Rotate(rX, rY, 0); cout << "Initialization successfull" << endl; return 1; } void SceneRenderer::render() { // TODO: move to 'onResize' event cam.SetupProjection(45, (GLfloat)m_winWidth / m_winHeight, 0.1f, 10000.0f); // set the camera transformation glm::mat4 MV = cam.GetViewMatrix(); glm::mat4 P = cam.GetProjectionMatrix(); glm::mat4 MVP = P * MV; if (pendingRenderTexResize) { pendingRenderTexResize = false; _resizeRenderTex(); } // ============ FBO ============== // enable FBO glBindFramebuffer(GL_FRAMEBUFFER, fboID); // render to colour attachment 0 glDrawBuffer(GL_COLOR_ATTACHMENT0); // clear the colour and depth buffers glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); // clear the colour and depth buffer // ============ ~FBO ============== m_sensorDataFboRenderer.render(WIDTH * 2, HEIGHT); // alLogger() << "preSendingFrames"; if (sendingFrames) { // alLogger() << "sendingFrames"; m_sensorDataFboRenderer.readGlFrame(); // TODO: NOT SURE IF IT IS OK TO MULTIPLY BY 2 newFrameSignal(m_sensorDataFboRenderer.m_outPixel, WIDTH * 2, HEIGHT); // NOTE: TESTING // TODO: remove // updateRemoteFrame(&(m_sensorDataFboRenderer.m_outPixel)[0], WIDTH * 2, // HEIGHT); } // ============ FBO ============== // unbind the FBO glBindFramebuffer(GL_FRAMEBUFFER, 0); // restore the default back buffer glDrawBuffer(GL_BACK_LEFT); // bind the FBO output at the current texture glActiveTexture(GL_TEXTURE3); glBindTexture(GL_TEXTURE_2D, renderTextureID); // ============ ~FBO ============== glViewport(0, 0, m_winWidth, m_winHeight); // Elements rendering m_bottomPlane.render(&MVP); // TODO: case when both sides has sensors is not handled if (m_remoteStreamMode == al::MODE_2D) { m_remoteFrameRenderer.render(); } else if (m_remoteStreamMode == al::MODE_3D) { m_remoteFrameRenderer.bindToTex(); m_hologram.render(&MVP); } if (m_localStreamMode == al::MODE_3D) { m_hologram.render(&MVP); } else if (m_localStreamMode == al::MODE_2D) { m_localFrameRenderer.render(); } m_worldCoordinate.render(&MVP); glBindVertexArray(0); glBindBuffer(GL_ARRAY_BUFFER, 0); glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0); // seems to be needed by something, otherwise some artifacts appears glActiveTexture(GL_TEXTURE0); } // initialize FBO void SceneRenderer::initFBO() { // generate and bind fbo ID glGenFramebuffers(1, &fboID); glBindFramebuffer(GL_FRAMEBUFFER, fboID); // generate and bind render buffer ID glGenRenderbuffers(1, &rbID); glBindRenderbuffer(GL_RENDERBUFFER, rbID); // set the render buffer storage glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, WIDTH * 2, HEIGHT); // generate the offscreen texture glGenTextures(1, &renderTextureID); glBindTexture(GL_TEXTURE_2D, renderTextureID); // set texture parameters glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, WIDTH * 2, HEIGHT, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); // bind the renderTextureID as colour attachment of FBO glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, renderTextureID, 0); // set the render buffer as the depth attachment of FBO glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, rbID); // check for frame buffer completeness status GLuint status = glCheckFramebufferStatus(GL_FRAMEBUFFER); if (status == GL_FRAMEBUFFER_COMPLETE) { printf("FBO setup succeededa.\n"); } else { printf("Error in FBO setup.\n"); } // unbind the texture and FBO glBindTexture(GL_TEXTURE_2D, 0); glBindFramebuffer(GL_FRAMEBUFFER, 0); } void SceneRenderer::_resizeRenderTex() { glBindRenderbuffer(GL_RENDERBUFFER, rbID); // set the render buffer storage glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT32, WIDTH * 2, HEIGHT); glBindTexture(GL_TEXTURE_2D, renderTextureID); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, WIDTH * 2, HEIGHT, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); } void SceneRenderer::initFrameSending(AlSdkAPI *alSdkApi) { if (m_debug) { std::cout << "SceneRenderer::initFrameSending" << std::endl; } if (!sendingFrames) { newFrameSignal.connect( boost::bind(&AlSdkAPI::setImageData, alSdkApi, _1, _2, _3)); } sendingFrames = true; } void SceneRenderer::OnStartMouseMove(int initX, int initY) { oldRotateX = initX; oldRotateY = initY; oldPanX = initX; oldPanY = initY; } void SceneRenderer::onZoom(int deltaZoom) { cam.Zoom(deltaZoom * 100.0f); } void SceneRenderer::onPan(int x, int y) { float dy = float(y - oldPanY) / 5.0f; float dx = float(oldPanX - x) / 5.0f; if (useFiltering) { filterMouseMoves(dx, dy); } else { mouseX = dx; mouseY = dy; } cam.Pan(mouseX, mouseY); oldPanX = x; oldPanY = y; } void SceneRenderer::onRotate(int x, int y) { // seems like when state == 1 it means left button rY += (y - oldRotateY) / 5.0f; rX += (oldRotateX - x) / 5.0f; if (useFiltering) { filterMouseMoves(rX, rY); } else { mouseX = rX; mouseY = rY; } cam.Rotate(mouseX, mouseY, 0); oldRotateX = x; oldRotateY = y; } void SceneRenderer::filterMouseMoves(float dx, float dy) { for (int i = MOUSE_HISTORY_BUFFER_SIZE - 1; i > 0; --i) { mouseHistory[i] = mouseHistory[i - 1]; } // Store current mouse entry at front of array. mouseHistory[0] = glm::vec2(dx, dy); float averageX = 0.0f; float averageY = 0.0f; float averageTotal = 0.0f; float currentWeight = 1.0f; // Filter the mouse. for (int i = 0; i < MOUSE_HISTORY_BUFFER_SIZE; ++i) { glm::vec2 tmp = mouseHistory[i]; averageX += tmp.x * currentWeight; averageY += tmp.y * currentWeight; averageTotal += 1.0f * currentWeight; currentWeight *= MOUSE_FILTER_WEIGHT; } mouseX = averageX / averageTotal; mouseY = averageY / averageTotal; } void SceneRenderer::updateRemoteFrameCb(const uint8_t *image, int width, int height) { m_remoteFrameRenderer.updateFrame(image, width, height); } void SceneRenderer::updateLocalFrameCb(const uint8_t *image, int width, int height) { m_localFrameRenderer.updateFrame(image, width, height); } void SceneRenderer::onWinResize(int winWidth, int winHeight) { m_winWidth = winWidth; m_winHeight = winHeight; _updateRenderersPos(); } void SceneRenderer::_updateRenderersPos() { m_remoteFrameRenderer.setPosition(-0.8, -0.8, 0.8, 0.8, m_winWidth, m_winHeight); // 50px from left and 50px from bottom // 200 px for reqtangle int size = 200; VideoStreamRenderer::Borders absoluteBorders; absoluteBorders.x2 = float(m_winWidth - 50); absoluteBorders.x1 = float(m_winWidth - 50 - size); absoluteBorders.y1 = m_winHeight - float(m_winHeight - 50); absoluteBorders.y2 = m_winHeight - float(m_winHeight - 50 - size); VideoStreamRenderer::Borders relativeBorders = VideoStreamRenderer::absoluteToRelative(absoluteBorders, m_winWidth, m_winHeight); m_localFrameRenderer.setPosition(relativeBorders.x1, relativeBorders.y1, relativeBorders.x2, relativeBorders.y2, m_winWidth, m_winHeight); }
30.469055
77
0.677037
xorsnn
4c08f1f1a28af24ed904991632ed5e0570289d4a
9,988
cpp
C++
IdClient/Platform/Windows/PWindows.cpp
skrishnasantosh/id-desktop-lite
1bc9c056ec7fa50e02cf360552e794e22f74e501
[ "MIT" ]
null
null
null
IdClient/Platform/Windows/PWindows.cpp
skrishnasantosh/id-desktop-lite
1bc9c056ec7fa50e02cf360552e794e22f74e501
[ "MIT" ]
null
null
null
IdClient/Platform/Windows/PWindows.cpp
skrishnasantosh/id-desktop-lite
1bc9c056ec7fa50e02cf360552e794e22f74e501
[ "MIT" ]
null
null
null
#ifdef _WIN32 #define _CRT_SECURE_NO_WARNINGS #define WIN32_LEAN_AND_MEAN #define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING #include <Windows.h> #include <Shlwapi.h> #include <wincrypt.h> #include <WinInet.h> #include <codecvt> #include <string> #include <vector> #pragma comment(lib, "Shlwapi.lib") #pragma comment(lib, "Crypt32.lib") #pragma comment(lib, "Wininet.lib") #include "../../Platform.h" using namespace Autodesk::Identity::Client::Internal; struct BLOB_DMY { BLOBHEADER header; DWORD len; BYTE key[0]; }; thread_local uint64_t m_platformErrorCode = 0; pstring Platform::UrlEncode(const pstring& url) { HRESULT apiResult = E_FAIL; wchar_t sizeTest[1] = { 0 }; DWORD destSize = 1; size_t urlLen = url.length(); m_platformErrorCode = 0; if (urlLen == 0 || urlLen > INTERNET_MAX_URL_LENGTH) return pstring(); wstring urlW = Strings.ToDefaultString<wstring>(url); apiResult = UrlEscape(urlW.c_str(), sizeTest, &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult) && apiResult != E_POINTER) //E_POINTER expected { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } if (destSize <= 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } wstring destW; destW.resize(destSize); apiResult = UrlEscape(urlW.c_str(), &(destW.data())[0], &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult)) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } destW.resize(destSize); pstring dest = Strings.FromDefaultString<wstring>(destW); return dest; } pstring Platform::UrlDecode(const pstring& url) { HRESULT apiResult = E_FAIL; wchar_t sizeTest[1] = { 0 }; DWORD destSize = 1; size_t urlLen = url.length(); m_platformErrorCode = 0; if (urlLen == 0 || urlLen > INTERNET_MAX_URL_LENGTH) return pstring(); wstring urlW = Strings.ToDefaultString<wstring>(url); apiResult = UrlUnescape(&(urlW.data())[0], sizeTest, &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult) && apiResult != E_POINTER) //E_POINTER expected { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } if (destSize <= 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } wstring destW; destW.resize(destSize); apiResult = UrlUnescape(&(urlW.data())[0], &(destW.data())[0], &destSize, URL_ESCAPE_PERCENT | URL_ESCAPE_SEGMENT_ONLY | URL_ESCAPE_ASCII_URI_COMPONENT); if (!SUCCEEDED(apiResult)) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } destW.resize(destSize); pstring dest = Strings.FromDefaultString<wstring>(destW); return dest; } pstring Platform::Base64Encode(const vector<uint8_t>& data) { DWORD destSizeRecv = 0; BOOL result = FALSE; size_t dataLength = data.size(); if (dataLength > MAXDWORD || dataLength == 0) return pstring(); result = CryptBinaryToStringW((const BYTE*)&data[0], (DWORD)dataLength, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, NULL, &destSizeRecv); if (!result || destSizeRecv == 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } wstring destW; destW.resize(destSizeRecv - 1); result = CryptBinaryToStringW((const BYTE*)&data[0], (DWORD)dataLength, CRYPT_STRING_BASE64 | CRYPT_STRING_NOCRLF, &(destW.data())[0], &destSizeRecv); if (!result || destSizeRecv == 0) { m_platformErrorCode = (uint64_t)::GetLastError(); return pstring(); } pstring dest = Strings.FromDefaultString<wstring>(destW); return dest; } vector<uint8_t> Platform::HmacSha1(const vector<uint8_t>& data, const vector<uint8_t>& key) { HCRYPTPROV hProv = NULL; HCRYPTHASH hHash = NULL; HCRYPTKEY hKey = NULL; HCRYPTHASH hHmacHash = NULL; DWORD dwDataLen = 0; HMAC_INFO hMacInfo = { 0 }; BOOL result = FALSE; vector<uint8_t> hashValue; const int hashSize = 20; m_platformErrorCode = 0; hMacInfo.HashAlgid = CALG_SHA1; result = CryptAcquireContext(&hProv, NULL, MS_ENHANCED_PROV, PROV_RSA_FULL, CRYPT_VERIFYCONTEXT | CRYPT_NEWKEYSET); if (!result) m_platformErrorCode = GetLastError(); struct BLOB_DMY* blob = NULL; size_t keyLen = key.size(); size_t dataLen = data.size(); if (keyLen > MAXDWORD || dataLen > MAXDWORD) return vector<uint8_t>(); DWORD blobSize = sizeof(struct BLOB_DMY) + key.size() + 1; blob = (struct BLOB_DMY*)malloc(blobSize); if (blob == NULL) return vector<uint8_t>(); memset(blob, 0, blobSize); blob->header.bType = PLAINTEXTKEYBLOB; blob->header.aiKeyAlg = CALG_RC2; blob->header.reserved = 0; blob->header.bVersion = CUR_BLOB_VERSION; blob->len = (DWORD)keyLen; memcpy(&(blob->key), &(key[0]), keyLen + 1); //Copy zero at end result = CryptImportKey(hProv, (BYTE*)blob, blobSize, 0, CRYPT_IPSEC_HMAC_KEY, &hKey); if (!result) m_platformErrorCode = GetLastError(); else result = CryptCreateHash(hProv, CALG_HMAC, hKey, 0, &hHmacHash); if (!result) m_platformErrorCode = GetLastError(); else result = CryptSetHashParam(hHmacHash, HP_HMAC_INFO, (BYTE*)&hMacInfo, 0); if (!result) m_platformErrorCode = GetLastError(); else result = CryptHashData(hHmacHash, (BYTE*)&data[0], dataLen, 0); if (!result) m_platformErrorCode = GetLastError(); else { hashValue.resize(hashSize, 0); dwDataLen = hashSize; result = CryptGetHashParam(hHmacHash, HP_HASHVAL, (BYTE*) & (hashValue[0]), &dwDataLen, 0); if (!result) m_platformErrorCode = GetLastError(); } if (hHmacHash) CryptDestroyHash(hHmacHash); if (hKey) CryptDestroyKey(hKey); if (hHash) CryptDestroyHash(hHash); if (hProv) CryptReleaseContext(hProv, 0); return hashValue; //PlatformErrorCode set to 0 and return NULL if out of memory } HttpResponse Platform::HttpGet(const pstring& url, const map<pstring, pstring>& queries, const map<pstring, pstring>& headers) { pstring content = u""; HttpResponse response; HINTERNET hSession, hConnection, hRequest; response.m_httpStatusCode = 0; wstring agentName = GetHttpAgentName<wstring>(); Internal::Url urlParts; if (!TryParseUrl(url, urlParts)) return response; hSession = ::InternetOpen(agentName.c_str(), INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); if (hSession == NULL) { m_platformErrorCode = ::GetLastError(); return response; } wstring wideUrl = Strings.ToDefaultString<wstring>(urlParts.m_host); wstring widePath = Strings.ToDefaultString<wstring>(urlParts.m_path); INTERNET_PORT port = INTERNET_INVALID_PORT_NUMBER; DWORD flags = 0; if (urlParts.m_protocol.back() == u'S' || urlParts.m_protocol.back() == u's') { port = INTERNET_DEFAULT_HTTPS_PORT; flags = INTERNET_FLAG_SECURE | INTERNET_FLAG_NO_UI; } else { port = INTERNET_DEFAULT_HTTP_PORT; flags = INTERNET_FLAG_NO_UI; } hConnection = ::InternetConnect(hSession, wideUrl.c_str(), port, NULL, NULL, INTERNET_SERVICE_HTTP, 0, NULL); if (hConnection) { const wchar_t* acceptTypes[] = { L"*/*", NULL }; hRequest = ::HttpOpenRequest(hConnection, L"GET", widePath.c_str(), L"HTTP/1.1", NULL, acceptTypes, flags, 0); if (hRequest) { /*if (::HttpSendRequest(hRequest, ) { canContinue = HttpEndRequest(hRequest, NULL, 0, 0); }*/ } else m_platformErrorCode = ::GetLastError(); ::InternetCloseHandle(hConnection); } else m_platformErrorCode = ::GetLastError(); ::InternetCloseHandle(hSession); return response; } HttpResponse Platform::HttpPost(const pstring& url, const map<pstring, pstring>& queries, const map<pstring, pstring>& headers) { pstring content = u""; return { 0, content }; } bool Platform::TryParseUrl(const pstring& fullUrl, Url& url) { bool ret = false; URL_COMPONENTS urlComponents = { 0 }; wstring wstr = Strings.ToDefaultString<wstring>(fullUrl); urlComponents.dwStructSize = sizeof(URL_COMPONENTS); urlComponents.dwSchemeLength = DWORD(-1); urlComponents.dwHostNameLength = DWORD(-1); urlComponents.dwUserNameLength = DWORD(-1); urlComponents.dwPasswordLength = DWORD(-1); urlComponents.dwUrlPathLength = DWORD(-1); urlComponents.dwExtraInfoLength = DWORD(-1); urlComponents.nPort = 0; ret = ::InternetCrackUrl(wstr.c_str(), wstr.length(), 0, &urlComponents); if (ret) { if (urlComponents.dwSchemeLength > 0 && urlComponents.lpszScheme != NULL) { wstring wstr(urlComponents.lpszScheme, urlComponents.dwSchemeLength); url.m_protocol = Strings.FromDefaultString(wstr); } if (urlComponents.dwHostNameLength > 0 && urlComponents.lpszHostName != NULL) { wstring wstr(urlComponents.lpszHostName, urlComponents.dwHostNameLength); url.m_host = Strings.FromDefaultString(wstr); } if (urlComponents.dwUrlPathLength > 1 && urlComponents.lpszUrlPath != NULL) { wstring wstr(urlComponents.lpszUrlPath, 1, urlComponents.dwUrlPathLength - 1); url.m_path = Strings.FromDefaultString(wstr); } if (urlComponents.dwExtraInfoLength > 0 && urlComponents.lpszExtraInfo != NULL) { wstring query(urlComponents.lpszExtraInfo, urlComponents.dwExtraInfoLength + 1); //Skip the '?' unsigned int port = urlComponents.nPort; size_t fragmentPos = query.find_last_of(L'#'); if (fragmentPos != wstring::npos) { url.m_queryString = Strings.FromDefaultString(query.substr(1, fragmentPos - 1)); if (fragmentPos + 1 < query.length()) url.m_fragment = Strings.FromDefaultString(query.substr(fragmentPos + 1, query.length() - 1 - (fragmentPos + 1))); } else url.m_queryString = Strings.FromDefaultString(query); } url.m_port = urlComponents.nPort; } return ret; } #define AGENT_FORMAT_STRING L"AdDesktopClient[version(1.0),platform(win64),os(#),defaultCharSize(2)]"; template<class TString> TString Platform::GetHttpAgentName() { wstring agentName = AGENT_FORMAT_STRING; //TODO: Fill the OS Version before sending this return agentName; } #endif //_WIN32
25.414758
154
0.721165
skrishnasantosh
4c098427f2899cb8e91f687a7475d165dbc55687
152
cpp
C++
service/src/exo/hexcode.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
4
2021-01-23T14:36:34.000Z
2021-06-07T10:02:28.000Z
service/src/exo/hexcode.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2019-08-04T19:15:56.000Z
2019-08-04T19:15:56.000Z
service/src/exo/hexcode.cpp
BOBBYWY/exodusdb
cfe8a3452480af90071dd10cefeed58299eed4e7
[ "MIT" ]
1
2022-01-29T22:41:01.000Z
2022-01-29T22:41:01.000Z
#include <exodus/library.h> libraryinit() function main(in /*mode*/, io /*text*/) { //called from listen but only in DOS return 0; } libraryexit()
13.818182
41
0.671053
BOBBYWY
4c0b053537224646e959af3f4ecdfa7e3b2208ab
2,648
cpp
C++
Chapter8/main.cpp
PacktPublishing/Mastering-Real-time-Ray-Tracing
c0b2e95f6182d4fbe52ea9261a500890fb11dc64
[ "MIT" ]
3
2019-10-10T21:01:45.000Z
2021-11-14T14:45:17.000Z
Chapter8/main.cpp
PacktPublishing/Mastering-Real-time-Ray-Tracing
c0b2e95f6182d4fbe52ea9261a500890fb11dc64
[ "MIT" ]
null
null
null
Chapter8/main.cpp
PacktPublishing/Mastering-Real-time-Ray-Tracing
c0b2e95f6182d4fbe52ea9261a500890fb11dc64
[ "MIT" ]
2
2019-06-09T11:22:39.000Z
2019-12-24T19:38:14.000Z
#include <iostream> #include <random> // This is the real value for PI static const double kREAL_PI = 3.1415927; // N is the number of samples we've chosen to throw // Here we consider a quarter of unit circle to compute the area // We use the hit or miss approach double HitOrMissMonteCarlo_EstimatePI(int N) { // Prepare random gens std::random_device device; std::mt19937 generator(device()); std::uniform_real_distribution<> distribution; // Total number of hits int hits = 0; // Start throwing samplesd for (int i = 0; i < N; ++i) { double x = distribution(generator); double y = distribution(generator); if (sqrt(x * x + y * y) <= 1.0) { ++hits; } } // Now we just average the total number of hits by the total number of thrown samples return (static_cast<double>(hits) / static_cast<double>(N)) * 4.0; } // Here we consider a quarter of unit circle to compute the area // Use the sample mean approach // Equation of a unit circle double f(double x) { return sqrt(1.0 - x*x); } // Here the integration interval [a,b] is [0,1], therefore we evaluate the sample mean considering that (b-a) = (1-0) = 1 // In fact we use the basic Monte Carlo estimator (i.e. the one that uses a uniform probability density function pdf=1/(b-a)) double SampleMeanMonteCarlo_EstimatePI(int N) { // Prepare random gens std::random_device device; std::mt19937 generator(device()); std::uniform_real_distribution<> distribution; // Integration interval double a = 0.0; double b = 1.0; // Prepare to sum uniform randomly generated samples for f(x) double sum = 0.0; for (int i = 0; i < N; ++i) { // Generate a uniformly distributed samples in [0,1) double x = distribution(generator); // Sum the x sample sum += f(x); } // Estimate after N samples // Finally average them and multiply by 4 (remember we are considering the integration interval [0,1] for our circle) double En = (sum * (b - a) / static_cast<double>(N)) * 4.0; return En; } int main() { // Enter the number of samples std::cout << "Enter the number of samples to estimate PI: "; // Enter the number of samples int NumberOfSamples; std::cin >> NumberOfSamples; std::cout << std::endl; // Estimate PI with hit or miss Monte Carlo double PI = HitOrMissMonteCarlo_EstimatePI(NumberOfSamples); // Estimate PI with the sample mean Monte Carlo estimator //double PI = SampleMeanMonteCarlo_EstimatePI(NumberOfSamples); // Print the result on console std::cout << "Estimate of PI for " << NumberOfSamples << " samples: " << PI << '\n'; std::cout << "Estimate error " << std::abs(PI-kREAL_PI) << "\n"; return 0; }
25.461538
125
0.689199
PacktPublishing
4c0d770609dfe91d96ff21ce4991fa78831cad15
4,455
cpp
C++
src/game/client/tf/c_entity_bird.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
6
2022-01-23T09:40:33.000Z
2022-03-20T20:53:25.000Z
src/game/client/tf/c_entity_bird.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
null
null
null
src/game/client/tf/c_entity_bird.cpp
cstom4994/SourceEngineRebuild
edfd7f8ce8af13e9d23586318350319a2e193c08
[ "MIT" ]
1
2022-02-06T21:05:23.000Z
2022-02-06T21:05:23.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: Dove entity for the Meet the Medic tease. // //=============================================================================// #include "cbase.h" #include "tf_gamerules.h" #include "c_baseanimating.h" #define ENTITY_FLYING_BIRD_MODEL "models/props_forest/dove.mdl" //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- class C_EntityFlyingBird : public CBaseAnimating { DECLARE_CLASS( C_EntityFlyingBird, CBaseAnimating ); public: void InitFromServerData( float flyAngle, float flyAngleRate, float flAccelZ, float flSpeed, float flGlideTime ); virtual void Touch( CBaseEntity *pOther ); private: virtual void ClientThink( void ); void UpdateFlyDirection( void ); private: Vector m_flyForward; float m_flyAngle; float m_flyAngleRate; float m_flyZ; float m_accelZ; float m_speed; float m_timestamp; CountdownTimer m_lifetimeTimer; CountdownTimer m_glideTimer; }; //----------------------------------------------------------------------------- // Purpose: Server message that tells us to create a dove //----------------------------------------------------------------------------- void __MsgFunc_SpawnFlyingBird( bf_read &msg ) { Vector vecPos; msg.ReadBitVec3Coord( vecPos ); float flyAngle = msg.ReadFloat(); float flyAngleRate = msg.ReadFloat(); float flAccelZ = msg.ReadFloat(); float flSpeed = msg.ReadFloat(); float flGlideTime = msg.ReadFloat(); C_EntityFlyingBird *pBird = new C_EntityFlyingBird(); if ( !pBird ) return; pBird->SetAbsOrigin( vecPos ); pBird->InitFromServerData( flyAngle, flyAngleRate, flAccelZ, flSpeed, flGlideTime ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_EntityFlyingBird::UpdateFlyDirection( void ) { Vector forward; forward.x = cos( m_flyAngle ); forward.y = sin( m_flyAngle ); forward.z = m_flyZ; forward.NormalizeInPlace(); SetAbsVelocity( forward * m_speed ); QAngle angles; VectorAngles( forward, angles ); SetAbsAngles( angles ); } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_EntityFlyingBird::InitFromServerData( float flyAngle, float flyAngleRate, float flAccelZ, float flSpeed, float flGlideTime ) { if ( InitializeAsClientEntity( ENTITY_FLYING_BIRD_MODEL, RENDER_GROUP_OPAQUE_ENTITY ) == false ) { Release(); return; } SetMoveType( MOVETYPE_FLY ); SetSolid( SOLID_BBOX ); SetCollisionGroup( COLLISION_GROUP_DEBRIS ); SetSize( -Vector(8,8,0), Vector(8,8,16) ); m_flyAngle = flyAngle; m_flyAngleRate = flyAngleRate; m_accelZ = flAccelZ; m_flyZ = 0.0; m_speed = flSpeed; UpdateFlyDirection(); SetSequence( 0 ); SetPlaybackRate( 1.0f ); SetCycle( 0 ); ResetSequenceInfo(); // make sure the bird is removed m_lifetimeTimer.Start( 10.0f ); m_glideTimer.Start( flGlideTime ); SetNextClientThink( CLIENT_THINK_ALWAYS ); m_timestamp = gpGlobals->curtime; SetModelScale( 0.1f ); SetModelScale( 1.0f, 0.5f ); } //----------------------------------------------------------------------------- // Purpose: Fly away! //----------------------------------------------------------------------------- void C_EntityFlyingBird::ClientThink( void ) { if ( m_lifetimeTimer.IsElapsed() ) { Release(); return; } if ( m_glideTimer.HasStarted() && m_glideTimer.IsElapsed() ) { SetSequence( 1 ); SetPlaybackRate( 1.0f ); SetCycle( 0 ); ResetSequenceInfo(); m_glideTimer.Invalidate(); } StudioFrameAdvance(); PhysicsSimulate(); const float deltaT = gpGlobals->curtime - m_timestamp; m_flyAngle += m_flyAngleRate * deltaT; m_flyZ += m_accelZ * deltaT; UpdateFlyDirection(); m_timestamp = gpGlobals->curtime; } //----------------------------------------------------------------------------- // Purpose: //----------------------------------------------------------------------------- void C_EntityFlyingBird::Touch( CBaseEntity *pOther ) { if ( !pOther || !pOther->IsWorld() ) return; BaseClass::Touch( pOther ); // Die at next think. Not safe to remove ourselves during physics touch. m_lifetimeTimer.Invalidate(); }
26.052632
131
0.557351
cstom4994
4c110491426056fb34ad624b6aeb08532da44def
2,239
cpp
C++
src/Entry.cpp
teaglu/timeoutd
855d93cc291c1744abcb1fd901beb639b1ed51ce
[ "Apache-2.0" ]
null
null
null
src/Entry.cpp
teaglu/timeoutd
855d93cc291c1744abcb1fd901beb639b1ed51ce
[ "Apache-2.0" ]
null
null
null
src/Entry.cpp
teaglu/timeoutd
855d93cc291c1744abcb1fd901beb639b1ed51ce
[ "Apache-2.0" ]
null
null
null
#include "system.h" #include "Entry.h" #include "Log.h" std::string Entry::notifyScript= SCRIPTDIR "/timeoutd-notify"; Entry::Entry(char const *key, struct timeval & expires, char const *address) { this->key= key; this->expires= expires; this->lastAddress= address; } Entry::~Entry() { } void Entry::notify() { Log::log(LOG_INFO, "Timeout for %s (%s)", key.c_str(), lastAddress.c_str()); char const *childArgv[4]; childArgv[0]= notifyScript.c_str(); childArgv[1]= key.c_str(); childArgv[2]= lastAddress.c_str(); childArgv[3]= NULL; pid_t childPid= fork(); if (childPid == -1) { Log::log(LOG_ERROR, "Failed to fork for notification: %s", strerror(errno)); } else if (childPid == 0) { // This is the child execv(childArgv[0], (char **)childArgv); Log::log(LOG_ERROR, "Failed to launch notify script %s: %s", childArgv[0], strerror(errno)); _exit(99); } else { for (bool wait= true; wait; ) { wait=false; int status; pid_t waitRval= waitpid(childPid, &status, 0); if (waitRval == -1) { if (errno == EINTR) { wait= true; } else { Log::log(LOG_ERROR, "Error waiting for notification script: %s", strerror(errno)); } } else if (WIFEXITED(status)) { if (WEXITSTATUS(status) != 0) { Log::log(LOG_WARNING, "Notification script exited with status %d", WEXITSTATUS(status)); } } else if (WIFSIGNALED(status)) { Log::log(LOG_WARNING, "Notification script exited on signal %d", WTERMSIG(status)); } } } } bool Entry::CompareTimeout( const std::shared_ptr<Entry> a, const std::shared_ptr<Entry> b) { struct timeval *aExpires= a->getExpires(); struct timeval *bExpires= b->getExpires(); if (aExpires->tv_sec < bExpires->tv_sec) { return true; } else if (aExpires->tv_sec > bExpires->tv_sec) { return false; } else { if (aExpires->tv_usec < bExpires->tv_usec) { return true; } else if (aExpires->tv_usec > bExpires->tv_usec) { return false; } else { // Because we're using a multiset instead of a // priority queue, we have to make sure that // our key is absolutely unique or we could // remove the wrong item. return (strcmp(a->getKey(), b->getKey()) < 0); } } }
22.39
76
0.634658
teaglu
4c16165059184f7eb584fa5775deed9b746cd94e
900
hpp
C++
Solution/Crosshair/Source/Crosshair.hpp
c-m-w/Crosshair-Overlay
8fbefbbf9fed35a08b2a0a6a65fd816c97e05355
[ "MIT" ]
6
2019-01-27T20:42:43.000Z
2021-06-09T07:36:15.000Z
Solution/Crosshair/Source/Crosshair.hpp
c-m-w/Crosshair-Overlay
8fbefbbf9fed35a08b2a0a6a65fd816c97e05355
[ "MIT" ]
null
null
null
Solution/Crosshair/Source/Crosshair.hpp
c-m-w/Crosshair-Overlay
8fbefbbf9fed35a08b2a0a6a65fd816c97e05355
[ "MIT" ]
1
2020-01-14T08:25:35.000Z
2020-01-14T08:25:35.000Z
/// Crosshair.hpp #pragma once #if not defined UNICODE or defined _MBCS #error Unicode must be used for this project. #endif #if not defined WIN32 #error This project must be built in 32 bit mode. #endif #define _CRT_SECURE_NO_WARNINGS #include <Windows.h> #include <cstdio> #include <cassert> #include <string> #include <fstream> #include <sstream> #include <ctime> #include <chrono> #include <iostream> #include <thread> #include <filesystem> #include <d3d9.h> #include <d3dx9core.h> #pragma comment( lib, "d3d9.lib" ) #pragma comment( lib, "d3dx9.lib" ) #undef DeleteFile // theres a winapi function to delete files but filesystem has a function called deletefile inline BOOL bShutdown = FALSE; inline HINSTANCE hCurrentInstance = nullptr; #include "Utilities.hpp" #include "FileSystem.hpp" #include "Configuration.hpp" #include "Window.hpp" #include "Logging.hpp" #include "Drawing.hpp"
20.930233
109
0.753333
c-m-w
4c181970cf31ac9cec66047839ffc5dba714debc
171
cpp
C++
test/unit-tests/telemetry/telemetry_client/i_global_publisher_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
38
2021-04-06T03:20:55.000Z
2022-03-02T09:33:28.000Z
test/unit-tests/telemetry/telemetry_client/i_global_publisher_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
19
2021-04-08T02:27:44.000Z
2022-03-23T00:59:04.000Z
test/unit-tests/telemetry/telemetry_client/i_global_publisher_test.cpp
so931/poseidonos
2aa82f26bfbd0d0aee21cd0574779a655634f08c
[ "BSD-3-Clause" ]
28
2021-04-08T04:39:18.000Z
2022-03-24T05:56:00.000Z
#include "src/telemetry/telemetry_client/i_global_publisher.h" #include <gtest/gtest.h> namespace pos { TEST(IGlobalPublisher, PublishToServer_) { } } // namespace pos
14.25
62
0.77193
so931
4c1b3ec1782a85f5a76811c000e4bcc0992dc1c9
2,225
cpp
C++
D2hackIt/toolhelp.cpp
inrg/D2HackIt-backup
2f1e81f5ea29168ef780c8a957b02611954db3af
[ "Unlicense" ]
24
2016-10-09T08:53:35.000Z
2022-02-07T11:34:37.000Z
D2hackIt/toolhelp.cpp
bethington/D2HackIt
2f1e81f5ea29168ef780c8a957b02611954db3af
[ "Unlicense" ]
null
null
null
D2hackIt/toolhelp.cpp
bethington/D2HackIt
2f1e81f5ea29168ef780c8a957b02611954db3af
[ "Unlicense" ]
33
2016-08-30T08:35:22.000Z
2022-02-07T11:34:40.000Z
////////////////////////////////////////////////////////////////////// // toolhelp.cpp // ------------------------------------------------------------------- // // <thohell@home.se> ////////////////////////////////////////////////////////////////////// #define THIS_IS_SERVER #include "..\D2HackIt.h" ////////////////////////////////////////////////////////////////////// // GetImageSize_toolhelp // ------------------------------------------------------------------- // Used to get the image size of a dll/exe. ////////////////////////////////////////////////////////////////////// DWORD PRIVATE GetImageSize_toolhelp(LPSTR ModuleName) { MODULEENTRY32 lpme; if (FindImage_toolhelp(ModuleName, &lpme)) return lpme.modBaseSize; else return 0; } ////////////////////////////////////////////////////////////////////// // GetBaseAddress_toolhelp // ------------------------------------------------------------------- // Used to get the base address of a dll/exe. ////////////////////////////////////////////////////////////////////// DWORD PRIVATE GetBaseAddress_toolhelp(LPSTR ModuleName) { MODULEENTRY32 lpme; if (FindImage_toolhelp(ModuleName, &lpme)) return (DWORD)lpme.modBaseAddr; else return 0; } ////////////////////////////////////////////////////////////////////// // FindImage_toolhelp // ------------------------------------------------------------------- // Loop through loaded images to get the MODULEINFO32 you need. ////////////////////////////////////////////////////////////////////// BOOL PRIVATE FindImage_toolhelp(LPSTR ModuleName, MODULEENTRY32* lpme) { // Get a snapshot HANDLE hSnapshot = pfep->toolhelp.CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, psi->pid); if ((int)hSnapshot == -1) return FALSE; lpme->dwSize=sizeof(MODULEENTRY32); // Get first module, this is needed for win9x/ME if (!pfep->toolhelp.Module32First(hSnapshot, lpme)) { CloseHandle(hSnapshot); return FALSE; }; // Loop through all other modules while (TRUE) { if (!strcmpi(lpme->szModule, ModuleName)) { CloseHandle(hSnapshot); return TRUE; } if (!pfep->toolhelp.Module32Next(hSnapshot, lpme)) { CloseHandle(hSnapshot); return FALSE; }; } }
35.887097
96
0.439551
inrg
4c1fc073a965e88346a3f3f17d6326318d51cc3d
1,056
cpp
C++
set_power_series/test/subset_log.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
20
2021-06-21T00:18:54.000Z
2022-03-17T17:45:44.000Z
set_power_series/test/subset_log.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
56
2021-06-03T14:42:13.000Z
2022-03-26T14:15:30.000Z
set_power_series/test/subset_log.test.cpp
ankit6776/cplib-cpp
b9f8927a6c7301374c470856828aa1f5667d967b
[ "MIT" ]
3
2019-12-11T06:45:45.000Z
2020-09-07T13:45:32.000Z
#define PROBLEM "https://atcoder.jp/contests/arc105/tasks/arc105_f" #include "../../modint.hpp" #include "../subset_convolution.hpp" #include <iostream> using namespace std; using mint = ModInt<998244353>; // https://codeforces.com/blog/entry/83535?#comment-709269 int main() { int N, M; cin >> N >> M; vector<int> to(N); while (M--) { int a, b; cin >> a >> b; a--, b--; to[a] += 1 << b, to[b] += 1 << a; } const mint inv2 = mint(2).inv(); vector<mint> pow2(N * N + 1, 1), pow2inv(N * N + 1, 1); for (int i = 1; i <= N * N; i++) pow2[i] = pow2[i - 1] * 2, pow2inv[i] = pow2inv[i - 1] * inv2; vector<int> nbe(1 << N); vector<mint> f(1 << N); for (int s = 0; s < 1 << N; s++) { for (int i = 0; i < N; i++) nbe[s] += __builtin_popcount(to[i] & s) * ((s >> i) & 1); nbe[s] /= 2; f[s] = pow2inv[nbe[s]]; } f = subset_convolution(f, f); for (int s = 0; s < 1 << N; s++) f[s] *= pow2[nbe[s]]; subset_log(f); cout << f.back() / 2 << '\n'; }
29.333333
99
0.485795
ankit6776
4c220997bc1e1284fabf6b2232df796f81e904cb
2,880
cpp
C++
test/parsed.cpp
olanmatt/orq
0e85e547cdc78cfd37681b8addfa0f4507e9516a
[ "MIT" ]
35
2015-01-07T05:06:50.000Z
2022-01-15T13:59:35.000Z
test/parsed.cpp
olanmatt/orq
0e85e547cdc78cfd37681b8addfa0f4507e9516a
[ "MIT" ]
null
null
null
test/parsed.cpp
olanmatt/orq
0e85e547cdc78cfd37681b8addfa0f4507e9516a
[ "MIT" ]
11
2015-01-27T09:29:22.000Z
2021-10-21T10:47:11.000Z
/* * The MIT License (MIT) * * Copyright (c) 2014 Matt Olan, Prajjwal Bhandari * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ #include <parsed.h> #include <catch.h> #include <vector> #include <string> TEST_CASE("Parsed::of returns a 'valid' Parsed Object", "[Parsed]") { std::vector<int> test {1, 2, 3}; Parsed< std::vector<int> > &p = Parsed< std::vector<int> >::of(test); SECTION("It should be valid,") { REQUIRE(p.is_valid()); } SECTION("value() should return a copy of the object passed in.") { REQUIRE(p.value() == test); SECTION("The object that was passed in should be deep copied.") { std::vector<int> backup = test; test.push_back(4); REQUIRE(p.value() == backup); } } SECTION("failure_reason() should be empty.") { REQUIRE(p.failure_reason() == ""); } } TEST_CASE("Parsed::invalid returns an 'invalid' Parsed Object", "[Parsed]") { std::string reason = "reasons"; Parsed<int> &p = Parsed<int>::invalid(reason); SECTION("It should not be valid,") { REQUIRE_FALSE(p.is_valid()); } SECTION("value() should throw an exception") { REQUIRE_THROWS_AS(p.value(), std::string); SECTION("exception message should be the same as it's failure reason") { try { p.value(); } catch (std::string exception) { REQUIRE(p.failure_reason() == exception); } } } SECTION("failure_reason() returns a copy of the string passed in.") { REQUIRE(p.failure_reason() == reason); SECTION("The object that was passed in should be deep copied.") { std::string backup_reason = reason; reason += "foo"; REQUIRE(p.failure_reason() == backup_reason); } } }
33.103448
81
0.642014
olanmatt
4c23c7b66ceeab2064567b67db73e5d102c2bea4
812
cpp
C++
third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp
Wzzzx/chromium-crosswalk
768dde8efa71169f1c1113ca6ef322f1e8c9e7de
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
2
2019-01-28T08:09:58.000Z
2021-11-15T15:32:10.000Z
third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
null
null
null
third_party/WebKit/Source/platform/fonts/FontCacheMemoryDumpProvider.cpp
maidiHaitai/haitaibrowser
a232a56bcfb177913a14210e7733e0ea83a6b18d
[ "BSD-3-Clause" ]
6
2020-09-23T08:56:12.000Z
2021-11-18T03:40:49.000Z
// Copyright 2015 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 "platform/fonts/FontCacheMemoryDumpProvider.h" #include "platform/fonts/FontCache.h" #include "wtf/Assertions.h" namespace blink { FontCacheMemoryDumpProvider* FontCacheMemoryDumpProvider::instance() { DEFINE_STATIC_LOCAL(FontCacheMemoryDumpProvider, instance, ()); return &instance; } bool FontCacheMemoryDumpProvider::OnMemoryDump(const base::trace_event::MemoryDumpArgs&, base::trace_event::ProcessMemoryDump* memoryDump) { ASSERT(isMainThread()); FontCache::fontCache()->dumpFontPlatformDataCache(memoryDump); FontCache::fontCache()->dumpShapeResultCache(memoryDump); return true; } } // namespace blink
30.074074
138
0.775862
Wzzzx
4c2480210f32bcee789f9dda078a231f55f09495
1,016
cpp
C++
AS/AS02/AS02.cpp
RafaelAmauri/Laborat-rio-de-Projetos-de-Algoritmos
d4ea60aba70d007bc23da5961f7c27d9756d0d74
[ "MIT" ]
1
2021-11-12T21:03:05.000Z
2021-11-12T21:03:05.000Z
AS/AS02/AS02.cpp
RafaelAmauri/Laborat-rio-de-Projetos-de-Algoritmos
d4ea60aba70d007bc23da5961f7c27d9756d0d74
[ "MIT" ]
null
null
null
AS/AS02/AS02.cpp
RafaelAmauri/Laborat-rio-de-Projetos-de-Algoritmos
d4ea60aba70d007bc23da5961f7c27d9756d0d74
[ "MIT" ]
null
null
null
// Autor: Rafael Amauri // Tarefa: LED // ID da Tarefa: 1168 // URL: https://www.beecrowd.com.br/judge/pt/problems/view/1168 // Complexidade: O(N), onde N é o número de dígitos totais #include <iostream> #include <string> // Returns the number of LEDs required for a given num short leds_required(short num) { // 0 1 2 3 4 5 6 7 8 9 short num_leds[] = {6, 2, 5, 5, 4, 5, 6, 3, 7, 6}; return num_leds[num]; } int main() { short N, number_of_leds; std::string num; // reading the number of numbers that are going to be read from stdin std::cin >> N; for(short i = 0; i < N; i++) { std::cin >> num; number_of_leds = 0; // Para cada char na string, somar o numero de LEDs que o dígito precisa na // variavel <number_of_leds> for(char j: num) number_of_leds += leds_required(j-'0'); std::cout << number_of_leds << " leds\n"; } return 0; }
24.190476
83
0.555118
RafaelAmauri
4c24d15d97e70ebf71d7ae7fa2c94192251dcc5d
1,925
hh
C++
src/Utilities/nodeBoundingBoxes.hh
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Utilities/nodeBoundingBoxes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Utilities/nodeBoundingBoxes.hh
markguozhiming/spheral
bbb982102e61edb8a1d00cf780bfa571835e1b61
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//---------------------------------Spheral++----------------------------------// // nodeBoundingBoxes // // Compute minimum volume bounding boxes for nodes and their extent. // // Created by JMO, Sun Jan 24 16:13:16 PST 2010 //----------------------------------------------------------------------------// #ifndef __Spheral_nodeBoundingBox__ #define __Spheral_nodeBoundingBox__ #include <utility> namespace Spheral { // Forward declarations. template<typename Dimension> class NodeList; template<typename Dimension, typename Value> class Field; template<typename Dimension, typename Value> class FieldList; template<typename Dimension> class DataBase; //------------------------------------------------------------------------------ // The bounding box for a position and H. //------------------------------------------------------------------------------ template<typename Dimension> std::pair<typename Dimension::Vector, typename Dimension::Vector> boundingBox(const typename Dimension::Vector& xi, const typename Dimension::SymTensor& Hi, const typename Dimension::Scalar& kernelExtent); //------------------------------------------------------------------------------ // The bounding boxes for a NodeList. //------------------------------------------------------------------------------ template<typename Dimension> Field<Dimension, std::pair<typename Dimension::Vector, typename Dimension::Vector> > nodeBoundingBoxes(const NodeList<Dimension>& nodes); //------------------------------------------------------------------------------ // The bounding boxes for all nodes in a DataBase. //------------------------------------------------------------------------------ template<typename Dimension> FieldList<Dimension, std::pair<typename Dimension::Vector, typename Dimension::Vector> > nodeBoundingBoxes(const DataBase<Dimension>& dataBase); } #include "nodeBoundingBoxesInline.hh" #endif
39.285714
88
0.523117
jmikeowen
4c26baebdd604bd8c38f67b8a8b4b64f87674728
177
cc
C++
builtin.cc
jplevyak/ifa
4bcb162182f4f7b5f5730dca09f8e37094cae53a
[ "MIT" ]
11
2015-06-10T07:34:10.000Z
2021-11-13T00:39:46.000Z
builtin.cc
jplevyak/ifa
4bcb162182f4f7b5f5730dca09f8e37094cae53a
[ "MIT" ]
null
null
null
builtin.cc
jplevyak/ifa
4bcb162182f4f7b5f5730dca09f8e37094cae53a
[ "MIT" ]
1
2022-01-11T09:16:53.000Z
2022-01-11T09:16:53.000Z
/* -*-Mode: c++;-*- Copyright (c) 2004-2008 John Plevyak, All Rights Reserved */ #include "builtin.h" #define S(_n) Sym *sym_##_n = 0; #include "builtin_symbols.h" #undef S
19.666667
60
0.644068
jplevyak
4c2bc806ac09ad7825ab0d94b335e4437584cf16
330
hpp
C++
Delauney/Sorting.hpp
tod91/Delauney
946419312e3e2d789c2203a40de4084c4d1bbe5f
[ "MIT" ]
2
2020-03-03T17:05:54.000Z
2020-05-11T14:15:55.000Z
Delauney/Sorting.hpp
tod91/Delauney
946419312e3e2d789c2203a40de4084c4d1bbe5f
[ "MIT" ]
null
null
null
Delauney/Sorting.hpp
tod91/Delauney
946419312e3e2d789c2203a40de4084c4d1bbe5f
[ "MIT" ]
null
null
null
// // Sorting.hpp // PojectDelone // // Created by Todor Ivanov on 5/25/17. // Copyright © 2017 Todor Ivanov. All rights reserved. // #ifndef Sorting_hpp #define Sorting_hpp struct Vertex3D; // sorts points by their x coord bool BottomUpMergeSort(Vertex3D* points, const unsigned numOfPoints); #endif /* Sorting_hpp */
16.5
70
0.718182
tod91
4c2dd10d2ae44f17a8936f38a9fb369724167240
2,402
cc
C++
ash/projector/ui/projector_button.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
575
2015-06-18T23:58:20.000Z
2022-03-23T09:32:39.000Z
ash/projector/ui/projector_button.cc
Ron423c/chromium
2edf7b980065b648f8b2a6e52193d83832fe36b7
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
113
2015-05-04T09:58:14.000Z
2022-01-31T19:35:03.000Z
ash/projector/ui/projector_button.cc
iridium-browser/iridium-browser
907e31cf5ce5ad14d832796e3a7c11e496828959
[ "BSD-3-Clause-No-Nuclear-License-2014", "BSD-3-Clause" ]
52
2015-07-14T10:40:50.000Z
2022-03-15T01:11:49.000Z
// Copyright 2021 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 "ash/projector/ui/projector_button.h" #include "ash/public/cpp/style/color_provider.h" #include "ash/resources/vector_icons/vector_icons.h" #include "ash/style/ash_color_provider.h" #include "ui/gfx/canvas.h" #include "ui/gfx/paint_vector_icon.h" #include "ui/views/accessibility/view_accessibility.h" #include "ui/views/animation/ink_drop.h" #include "ui/views/background.h" #include "ui/views/controls/highlight_path_generator.h" namespace ash { namespace { constexpr gfx::Insets kButtonPadding{0}; } // namespace ProjectorButton::ProjectorButton(views::Button::PressedCallback callback) : ToggleImageButton(callback) { SetPreferredSize({kProjectorButtonSize, kProjectorButtonSize}); SetBorder(views::CreateEmptyBorder(kButtonPadding)); // Rounded background. views::InstallRoundRectHighlightPathGenerator(this, gfx::Insets(), kProjectorButtonSize / 2.f); } std::unique_ptr<views::InkDrop> ProjectorButton::CreateInkDrop() { std::unique_ptr<views::InkDrop> ink_drop = views::Button::CreateInkDrop(); ink_drop->SetShowHighlightOnHover(true); ink_drop->SetShowHighlightOnFocus(true); return ink_drop; } void ProjectorButton::OnPaintBackground(gfx::Canvas* canvas) { auto* color_provider = AshColorProvider::Get(); cc::PaintFlags flags; flags.setAntiAlias(true); flags.setStyle(cc::PaintFlags::kFill_Style); flags.setColor(color_provider->GetControlsLayerColor( GetToggled() ? AshColorProvider::ControlsLayerType::kControlBackgroundColorActive : AshColorProvider::ControlsLayerType:: kControlBackgroundColorInactive)); const gfx::RectF bounds(GetContentsBounds()); canvas->DrawCircle(bounds.CenterPoint(), bounds.width() / 2, flags); } void ProjectorButton::OnThemeChanged() { views::ToggleImageButton::OnThemeChanged(); // Ink Drop. const AshColorProvider::RippleAttributes ripple_attributes = AshColorProvider::Get()->GetRippleAttributes(); SetInkDropMode(views::InkDropHostView::InkDropMode::ON); SetHasInkDropActionOnClick(true); SetInkDropBaseColor(ripple_attributes.base_color); SetInkDropHighlightOpacity(ripple_attributes.highlight_opacity); } } // namespace ash
35.323529
78
0.756037
Ron423c
4c2ec4e004efcb973644ef859f80a39e89310592
4,261
ipp
C++
xs/src/boost/test/utils/runtime/cla/named_parameter.ipp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
460
2016-01-13T12:49:34.000Z
2022-02-20T04:10:40.000Z
xs/src/boost/test/utils/runtime/cla/named_parameter.ipp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
197
2017-07-06T16:53:59.000Z
2019-05-31T17:57:51.000Z
xs/src/boost/test/utils/runtime/cla/named_parameter.ipp
born2b/Slic3r
589a0b3ac1a50f84de694b89cc10abcac45c0ae6
[ "CC-BY-3.0" ]
148
2016-01-17T03:16:43.000Z
2022-03-17T12:20:36.000Z
// (C) Copyright Gennadiy Rozental 2005-2008. // Use, modification, and distribution are subject to the // Boost Software License, Version 1.0. (See accompanying file // LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) // See http://www.boost.org/libs/test for the library home page. // // File : $RCSfile$ // // Version : $Revision: 54633 $ // // Description : implements model of named parameter // *************************************************************************** #ifndef BOOST_RT_CLA_NAMED_PARAMETER_IPP_062904GER #define BOOST_RT_CLA_NAMED_PARAMETER_IPP_062904GER // Boost.Runtime.Parameter #include <boost/test/utils/runtime/config.hpp> #include <boost/test/utils/runtime/cla/named_parameter.hpp> #include <boost/test/utils/runtime/cla/char_parameter.hpp> // Boost.Test #include <boost/test/utils/algorithm.hpp> namespace boost { namespace BOOST_RT_PARAM_NAMESPACE { namespace cla { // ************************************************************************** // // ************** string_name_policy ************** // // ************************************************************************** // BOOST_RT_PARAM_INLINE string_name_policy::string_name_policy() : basic_naming_policy( rtti::type_id<string_name_policy>() ) , m_guess_name( false ) { assign_op( p_prefix.value, BOOST_RT_PARAM_CSTRING_LITERAL( "-" ), 0 ); } //____________________________________________________________________________// BOOST_RT_PARAM_INLINE bool string_name_policy::responds_to( cstring name ) const { std::pair<cstring::iterator,dstring::const_iterator> mm_pos; mm_pos = unit_test::mismatch( name.begin(), name.end(), p_name->begin(), p_name->end() ); return mm_pos.first == name.end() && (m_guess_name || (mm_pos.second == p_name->end()) ); } //____________________________________________________________________________// #ifdef BOOST_MSVC # pragma warning(push) # pragma warning(disable:4244) #endif BOOST_RT_PARAM_INLINE bool string_name_policy::conflict_with( identification_policy const& id ) const { if( id.p_type_id == p_type_id ) { string_name_policy const& snp = static_cast<string_name_policy const&>( id ); if( p_name->empty() || snp.p_name->empty() ) return false; if( p_prefix != snp.p_prefix ) return false; std::pair<dstring::const_iterator,dstring::const_iterator> mm_pos = unit_test::mismatch( p_name->begin(), p_name->end(), snp.p_name->begin(), snp.p_name->end() ); return mm_pos.first != p_name->begin() && // there is common substring ((m_guess_name && (mm_pos.second == snp.p_name->end()) ) || // that match other guy and I am guessing (snp.m_guess_name && (mm_pos.first == p_name->end()) )); // or me and the other guy is } if( id.p_type_id == rtti::type_id<char_name_policy>() ) { char_name_policy const& cnp = static_cast<char_name_policy const&>( id ); return m_guess_name && (p_prefix == cnp.p_prefix) && unit_test::first_char( cstring( p_name ) ) == unit_test::first_char( cstring( cnp.p_name ) ); } return false; } #ifdef BOOST_MSVC # pragma warning(pop) #endif //____________________________________________________________________________// BOOST_RT_PARAM_INLINE bool string_name_policy::match_name( argv_traverser& tr ) const { if( !m_guess_name ) return basic_naming_policy::match_name( tr ); cstring in = tr.input(); std::pair<cstring::iterator,dstring::const_iterator> mm_pos; mm_pos = unit_test::mismatch( in.begin(), in.end(), p_name->begin(), p_name->end() ); if( mm_pos.first == in.begin() ) return false; tr.trim( mm_pos.first - in.begin() ); return true; } //____________________________________________________________________________// } // namespace cla } // namespace BOOST_RT_PARAM_NAMESPACE } // namespace boost #endif // BOOST_RT_CLA_NAMED_PARAMETER_IPP_062904GER
32.776923
122
0.619808
born2b
4c31861b8a9df357e0c27e9d46d10647ea13a2d4
1,367
hpp
C++
search/stats_cache.hpp
kudlav/organicmaps
390236365749e0525b9229684132c2888d11369d
[ "Apache-2.0" ]
4,879
2015-09-30T10:56:36.000Z
2022-03-31T18:43:03.000Z
search/stats_cache.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
7,549
2015-09-30T10:52:53.000Z
2022-03-31T22:04:22.000Z
search/stats_cache.hpp
mbrukman/omim
d22fe2b6e0beee697f096e931df97a64f9db9dc1
[ "Apache-2.0" ]
1,493
2015-09-30T10:43:06.000Z
2022-03-21T09:16:49.000Z
#pragma once #include "base/logging.hpp" #include <cstddef> #include <string> #include <unordered_map> #include <utility> namespace search { template <class Key, class Value> class Cache { std::unordered_map<Key, Value> m_map; /// query statistics size_t m_accesses; size_t m_misses; size_t m_emptyQueriesCount; /// empty queries count at a row std::string m_name; /// cache name for print functions public: explicit Cache(std::string const & name) : m_accesses(0), m_misses(0), m_emptyQueriesCount(0), m_name(name) { } std::pair<Value &, bool> Get(Key const & key) { auto r = m_map.insert(std::make_pair(key, Value())); ++m_accesses; if (r.second) ++m_misses; return std::pair<Value &, bool>(r.first->second, r.second); } void Clear() { m_map.clear(); m_accesses = m_misses = 0; m_emptyQueriesCount = 0; } /// Called at the end of every search query. void ClearIfNeeded() { if (m_accesses != 0) { LOG(LDEBUG, ("Cache", m_name, "Queries =", m_accesses, "From cache =", m_accesses - m_misses, "Added =", m_misses)); m_accesses = m_misses = 0; m_emptyQueriesCount = 0; } else if (++m_emptyQueriesCount > 5) { LOG(LDEBUG, ("Clearing cache", m_name)); Clear(); } } }; } // namespace search
20.712121
99
0.61229
kudlav
4c33abdbf9b3217e0cec1aa5d43de2bec595a6a8
2,010
cpp
C++
src/plugins/anim/nodes/frame/edit.cpp
martin-pr/possumwood
0ee3e0fe13ef27cf14795a79fb497e4d700bef63
[ "MIT" ]
232
2017-10-09T11:45:28.000Z
2022-03-28T11:14:46.000Z
src/plugins/anim/nodes/frame/edit.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
26
2019-01-20T21:38:25.000Z
2021-10-16T03:57:17.000Z
src/plugins/anim/nodes/frame/edit.cpp
LIUJUN-liujun/possumwood
745e48eb44450b0b7f078ece81548812ab1ccc63
[ "MIT" ]
33
2017-10-26T19:20:38.000Z
2022-03-16T11:21:43.000Z
#include <OpenEXR/ImathEuler.h> #include <OpenEXR/ImathMatrix.h> #include <OpenEXR/ImathVec.h> #include <possumwood_sdk/node_implementation.h> #include "datatypes/animation.h" #include "datatypes/frame_editor_data.h" #include "maths/io/vec3.h" namespace { dependency_graph::InAttr<anim::Skeleton> a_inFrame; dependency_graph::InAttr<Imath::Vec3<float>> a_translate; dependency_graph::InAttr<float> a_scale; dependency_graph::InAttr<anim::FrameEditorData> a_editorData; dependency_graph::OutAttr<anim::Skeleton> a_outFrame; dependency_graph::State compute(dependency_graph::Values& data) { // update a_editorData, if needed if(data.get(a_editorData).skeleton() != data.get(a_inFrame)) { anim::FrameEditorData editorData = data.get(a_editorData); editorData.setSkeleton(data.get(a_inFrame)); data.set(a_editorData, editorData); } // do the computation itself anim::Skeleton frame = data.get(a_inFrame); const Imath::Vec3<float>& tr = data.get(a_translate); const float sc = data.get(a_scale); if(frame.size() > 0) { for(auto& b : frame) b.tr().translation *= sc; frame[0].tr().translation += tr; for(auto& i : data.get(a_editorData)) if(i.first < frame.size()) frame[i.first].tr() = frame[i.first].tr() * i.second; } data.set(a_outFrame, frame); return dependency_graph::State(); } void init(possumwood::Metadata& meta) { meta.addAttribute(a_inFrame, "in_frame", anim::Skeleton(), possumwood::AttrFlags::kVertical); meta.addAttribute(a_translate, "translate", Imath::Vec3<float>(0, 0, 0)); meta.addAttribute(a_scale, "scale", 1.0f); meta.addAttribute(a_editorData, "rotations"); meta.addAttribute(a_outFrame, "out_frame", anim::Skeleton(), possumwood::AttrFlags::kVertical); meta.addInfluence(a_inFrame, a_outFrame); meta.addInfluence(a_editorData, a_outFrame); meta.addInfluence(a_translate, a_outFrame); meta.addInfluence(a_scale, a_outFrame); meta.setCompute(compute); } possumwood::NodeImplementation s_impl("anim/frame/edit", init); } // namespace
30.923077
96
0.743781
martin-pr
4c353b39db60349f67cc8f036962b5dda0d59d63
296
hpp
C++
UnitTests/GXLayerUnitTest.hpp
manu88/GX
1eaeb0361db4edfb9c0764b4c47817ed77d4159c
[ "Apache-2.0" ]
2
2017-07-12T02:25:23.000Z
2017-08-30T23:46:32.000Z
UnitTests/GXLayerUnitTest.hpp
manu88/GX
1eaeb0361db4edfb9c0764b4c47817ed77d4159c
[ "Apache-2.0" ]
null
null
null
UnitTests/GXLayerUnitTest.hpp
manu88/GX
1eaeb0361db4edfb9c0764b4c47817ed77d4159c
[ "Apache-2.0" ]
null
null
null
// // GXLayerUnitTest.hpp // GX // // Created by Manuel Deneu on 22/06/2017. // Copyright © 2017 Unlimited Development. All rights reserved. // #ifndef GXLayerUnitTest_hpp #define GXLayerUnitTest_hpp class GXLayerUnitTest { public: bool run(); }; #endif /* GXLayerUnitTest_hpp */
14.8
64
0.699324
manu88
4c36b0fc84fa3d97c04c8876df4c6efeeca7d707
778
hpp
C++
src/include/test.hpp
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
1
2021-03-15T11:38:20.000Z
2021-03-15T11:38:20.000Z
src/include/test.hpp
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
src/include/test.hpp
jmorken/loda
99c09d2641e858b074f6344a352d13bc55601571
[ "Apache-2.0" ]
null
null
null
#pragma once #include "matcher.hpp" #include "number.hpp" #include "util.hpp" class Test { public: Test() { } void all(); void semantics(); void memory(); void knownPrograms(); void ackermann(); void collatz(); void optimizer(); void minimizer( size_t tests ); void linearMatcher(); void deltaMatcher(); void polynomialMatcher( size_t tests, size_t degree ); void stats(); void config(); private: void testSeq( size_t id, const Sequence &values ); void testBinary( const std::string &func, const std::string &file, const std::vector<std::vector<number_t> > &values ); void testMatcherSet( Matcher &matcher, const std::vector<size_t> &ids ); void testMatcherPair( Matcher &matcher, size_t id1, size_t id2 ); };
14.679245
74
0.66581
jmorken
4c37668fa6285fc04d5579aefcf602994cb4bd4a
436
hh
C++
RAVL2/Image/VideoIO/ImgIOSeq.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Image/VideoIO/ImgIOSeq.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
RAVL2/Image/VideoIO/ImgIOSeq.hh
isuhao/ravl2
317e0ae1cb51e320b877c3bad6a362447b5e52ec
[ "BSD-Source-Code" ]
null
null
null
#ifndef IMGIOSEQ_HEADER #define IMGIOSEQ_HEADER 1 //////////////////////////////////////////////////// //! rcsid="$Id: ImgIOSeq.hh 40 2001-04-23 16:17:51Z craftit $" #include "amma/DP/SPort.hh" #include "amma/DP/FileSeq.hh" template<class DataT> class DPImageSeqBodyC : public DPFileSequenceBodyC { public: DPImageSeqBaseBodyC(); //: Default constructor. protected: FileFormatBaseC format; // Format of stream. }; #endif
19.818182
62
0.644495
isuhao
4c392489a357dfbf7e556482c2d7587cff3b2500
1,234
cpp
C++
LeetCode/Two Sum.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
LeetCode/Two Sum.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
LeetCode/Two Sum.cpp
zombiecry/AlgorithmPractice
f42933883bd62a86aeef9740356f5010c6c9bebf
[ "MIT" ]
null
null
null
#include <vector> #include <list> #include <map> #include <set> #include <deque> #include<queue> #include <stack> #include <bitset> #include <algorithm> #include <functional> #include <numeric> #include <utility> #include <sstream> #include <iostream> #include <iomanip> #include <cstdio> #include <cmath> #include <cstdlib> #include <ctime> #include <cstring> #include <fstream> using namespace std; typedef pair<int,int> scpair; class Solution { public: int n; vector <scpair> a; vector<int> twoSum(vector<int> &numbers, int target) { n=numbers.size(); a.resize(n); for (int i=0;i<n;i++){ a[i]=scpair(numbers[i],i+1); } sort(a.begin(),a.end()); vector <int> res; for (int i=0;i<n-1;i++){ int left=target-a[i].first; int p=lower_bound(a.begin()+i+1,a.end(),scpair(left,0))-a.begin(); if (p<n){ if (a[p].first!=left){continue;} res.push_back(a[i].second); res.push_back(a[p].second); sort(res.begin(),res.end()); return res; } } return res; } }; int main (){ Solution *sol=new Solution; int a[]={150,24,79,50,88,345,3}; int t=200; vector<int> ret=sol->twoSum(vector<int>(a,a+sizeof(a)/sizeof(a[0])),t); for (int i=0;i<ret.size();i++){ cout<<ret[i]<<" "; } return 0; }
20.566667
72
0.63128
zombiecry
4c3b61e71a416bfee0e5928fc07a0ba75743b085
1,069
cc
C++
python/jittor/src/mem/allocator/cuda_dual_allocator.cc
Jittor/Jittor
bc945bae94bded917214b0afe12be6bf5b919dbe
[ "Apache-2.0" ]
4
2020-01-12T13:16:16.000Z
2020-01-12T15:43:54.000Z
python/jittor/src/mem/allocator/cuda_dual_allocator.cc
Jittor/Jittor
bc945bae94bded917214b0afe12be6bf5b919dbe
[ "Apache-2.0" ]
null
null
null
python/jittor/src/mem/allocator/cuda_dual_allocator.cc
Jittor/Jittor
bc945bae94bded917214b0afe12be6bf5b919dbe
[ "Apache-2.0" ]
1
2020-01-12T13:17:17.000Z
2020-01-12T13:17:17.000Z
// *************************************************************** // Copyright (c) 2022 Jittor. All Rights Reserved. // Maintainers: Dun Liang <randonlang@gmail.com>. // This file is subject to the terms and conditions defined in // file 'LICENSE.txt', which is part of this source code package. // *************************************************************** #ifdef HAS_CUDA #include "misc/cuda_flags.h" #include "mem/allocator/cuda_dual_allocator.h" #include "mem/allocator/cuda_host_allocator.h" #include "mem/allocator/cuda_device_allocator.h" #include "event_queue.h" namespace jittor { SFRLAllocator cuda_dual_host_allocator(&cuda_host_allocator, 0.3, 1<<28); SFRLAllocator cuda_dual_device_allocator(&cuda_device_allocator, 0.3, 1<<28); CudaDualAllocator cuda_dual_allocator; DelayFree delay_free; namespace cuda_dual_local { list<Allocation> allocations; static void free_caller() { allocations.pop_front(); } } void to_free_allocation(CUDA_HOST_FUNC_ARGS) { using namespace cuda_dual_local; event_queue.push(free_caller); } } #endif
27.410256
77
0.683817
Jittor
4c3bbd86701e97d67153d36ab7eecd7d3aa5868a
1,264
hpp
C++
gamess/libqc/src/iterator/range.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/src/iterator/range.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/src/iterator/range.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
#ifndef _ITERATOR_RANGE_HPP_ #define _ITERATOR_RANGE_HPP_ #include <boost/range/iterator_range.hpp> #include <boost/iterator/counting_iterator.hpp> #include <cassert> #include "iterator/increment.hpp" namespace iterator { template <typename T> boost::iterator_range<increment_iterator<T> > range(T from, T to, T increment = 1) { assert((increment >= T() && from <= to) || (increment < T() && from >= to)); typedef increment_iterator<T> iterator; return boost::make_iterator_range(iterator(from, increment), iterator(to)); } template <typename T> boost::iterator_range<increment_iterator<T> > range(T to) { typedef increment_iterator<T> iterator; return boost::make_iterator_range(iterator(T(0)), iterator(to)); } template<typename T = int> struct Range { typedef increment_iterator<T> iterator; typedef const increment_iterator<T> const_iterator; int first_, last_, increment_; Range(int last) : first_(0), last_(last), increment_(1) {} Range(int first, int last, int increment = 1) : first_(first), last_(last), increment_(increment) {} iterator begin() const { return iterator(first_, increment_); } iterator end() const { return iterator(last_, increment_); } }; } #endif /* _ITERATOR_RANGE_HPP_ */
30.829268
88
0.716772
andremirt
4c3d92eacb1af94282bc230c93323753495e4673
671
cpp
C++
LeetCode/198_house_robber/rob.cpp
harveyc95/ProgrammingProblems
d81dc58de0347fa155f5e25f27d3d426ce13cdc6
[ "MIT" ]
null
null
null
LeetCode/198_house_robber/rob.cpp
harveyc95/ProgrammingProblems
d81dc58de0347fa155f5e25f27d3d426ce13cdc6
[ "MIT" ]
null
null
null
LeetCode/198_house_robber/rob.cpp
harveyc95/ProgrammingProblems
d81dc58de0347fa155f5e25f27d3d426ce13cdc6
[ "MIT" ]
null
null
null
class Solution { public: int rob(vector<int>& nums) { if (nums.size() == 0) return 0; if (nums.size() == 1) return nums[0]; std::vector<int> dp (nums.size(), 0); dp[0] = nums[0]; dp[1] = nums[1]; if (nums.size() == 2) return max(dp[0], dp[1]); int maxMoney = max(dp[0], dp[1]); int maxBeforeNeighbour = 0; for (int i = 2; i < nums.size(); i++) { int neighbour = dp[i-1]; maxBeforeNeighbour = max(maxBeforeNeighbour, dp[i-2]); maxMoney = max(nums[i]+maxBeforeNeighbour,neighbour); dp[i] = maxMoney; } return maxMoney; } };
33.55
66
0.491803
harveyc95
4c4399c800b06c07a1546a72d4b36295a8f78ac9
2,895
cc
C++
components/service/ucloud/imm/src/model/ListImageJobsResult.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
1
2021-04-09T03:18:41.000Z
2021-04-09T03:18:41.000Z
components/service/ucloud/imm/src/model/ListImageJobsResult.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
null
null
null
components/service/ucloud/imm/src/model/ListImageJobsResult.cc
wanguojian/AliOS-Things
47fce29d4dd39d124f0bfead27998ad7beea8441
[ "Apache-2.0" ]
1
2021-06-20T06:43:12.000Z
2021-06-20T06:43:12.000Z
/* * Copyright 2009-2017 Alibaba Cloud All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <alibabacloud/imm/model/ListImageJobsResult.h> #include <json/json.h> using namespace AlibabaCloud::Imm; using namespace AlibabaCloud::Imm::Model; ListImageJobsResult::ListImageJobsResult() : ServiceResult() {} ListImageJobsResult::ListImageJobsResult(const std::string &payload) : ServiceResult() { parse(payload); } ListImageJobsResult::~ListImageJobsResult() {} void ListImageJobsResult::parse(const std::string &payload) { Json::Reader reader; Json::Value value; reader.parse(payload, value); setRequestId(value["RequestId"].asString()); auto allJobsNode = value["Jobs"]["JobsItem"]; for (auto valueJobsJobsItem : allJobsNode) { JobsItem jobsObject; if(!valueJobsJobsItem["Status"].isNull()) jobsObject.status = valueJobsJobsItem["Status"].asString(); if(!valueJobsJobsItem["JobId"].isNull()) jobsObject.jobId = valueJobsJobsItem["JobId"].asString(); if(!valueJobsJobsItem["JobType"].isNull()) jobsObject.jobType = valueJobsJobsItem["JobType"].asString(); if(!valueJobsJobsItem["Parameters"].isNull()) jobsObject.parameters = valueJobsJobsItem["Parameters"].asString(); if(!valueJobsJobsItem["Result"].isNull()) jobsObject.result = valueJobsJobsItem["Result"].asString(); if(!valueJobsJobsItem["StartTime"].isNull()) jobsObject.startTime = valueJobsJobsItem["StartTime"].asString(); if(!valueJobsJobsItem["EndTime"].isNull()) jobsObject.endTime = valueJobsJobsItem["EndTime"].asString(); if(!valueJobsJobsItem["ErrorMessage"].isNull()) jobsObject.errorMessage = valueJobsJobsItem["ErrorMessage"].asString(); if(!valueJobsJobsItem["NotifyEndpoint"].isNull()) jobsObject.notifyEndpoint = valueJobsJobsItem["NotifyEndpoint"].asString(); if(!valueJobsJobsItem["NotifyTopicName"].isNull()) jobsObject.notifyTopicName = valueJobsJobsItem["NotifyTopicName"].asString(); if(!valueJobsJobsItem["Progress"].isNull()) jobsObject.progress = std::stoi(valueJobsJobsItem["Progress"].asString()); jobs_.push_back(jobsObject); } if(!value["NextMarker"].isNull()) nextMarker_ = value["NextMarker"].asString(); } std::vector<ListImageJobsResult::JobsItem> ListImageJobsResult::getJobs()const { return jobs_; } std::string ListImageJobsResult::getNextMarker()const { return nextMarker_; }
34.058824
80
0.748877
wanguojian
4c48ce428d67d135060b987cb097f2a7e4f0bf96
3,786
cpp
C++
tests/sort_strings_example.cpp
kurpicz/tlx
a9a8a76c40a734b1f771d6eba482ba7166f1f6b4
[ "BSL-1.0" ]
284
2017-02-26T08:49:15.000Z
2022-03-30T21:55:37.000Z
tests/sort_strings_example.cpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
24
2017-09-05T21:02:41.000Z
2022-03-07T10:09:59.000Z
tests/sort_strings_example.cpp
xiao2mo/tlx
b311126e670753897c1defceeaa75c83d2d9531a
[ "BSL-1.0" ]
62
2017-02-23T12:29:27.000Z
2022-03-31T07:45:59.000Z
/******************************************************************************* * tests/sort_strings_example.cpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2020 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #include <tlx/cmdline_parser.hpp> #include <tlx/simple_vector.hpp> #include <tlx/string/format_iec_units.hpp> #include <tlx/timestamp.hpp> #include <tlx/sort/strings.hpp> #include <tlx/sort/strings_parallel.hpp> #include <cstring> #include <fstream> #include <iostream> int main(int argc, char* argv[]) { tlx::CmdlineParser cp; // add description cp.set_description("Example program to read a file and sort its lines."); bool parallel = false; cp.add_flag('p', "parallel", parallel, "sort with parallel algorithm"); // add a required parameter std::string file; cp.add_param_string("file", file, "A file to process"); // process command line if (!cp.process(argc, argv)) return -1; std::cerr << "Opening " << file << std::endl; std::ifstream in(file.c_str()); if (!in.good()) { std::cerr << "Error opening file: " << strerror(errno) << std::endl; return -1; } if (!in.seekg(0, std::ios::end).good()) { std::cerr << "Error seeking to end of file: " << strerror(errno) << std::endl; return -1; } size_t size = in.tellg(); // allocate uninitialized memory area and string pointer array tlx::simple_vector<uint8_t> data(size + 8); std::vector<uint8_t*> strings; // read file and make string pointer array double ts1_read = tlx::timestamp(); std::cerr << "Reading " << size << " bytes" << std::endl; in.seekg(0, std::ios::beg); // first string pointer strings.push_back(data.data() + 0); size_t pos = 0; while (pos < size) { size_t rem = std::min<size_t>(2 * 1024 * 1024u, size - pos); in.read(reinterpret_cast<char*>(data.data() + pos), rem); uint8_t* chunk = data.data() + pos; for (size_t i = 0; i < rem; ++i) { if (chunk[i] == '\n') { chunk[i] = 0; if (pos + i + 1 < size) { strings.push_back(chunk + i + 1); } } else if (chunk[i] == '\0') { if (pos + i + 1 < size) { strings.push_back(chunk + i + 1); } } } pos += rem; } // final zero termination data[size] = 0; double ts2_read = tlx::timestamp(); std::cerr << "Reading took " << ts2_read - ts1_read << " seconds at " << tlx::format_iec_units(size / (ts2_read - ts1_read)) << "B/s" << std::endl; std::cerr << "Found " << strings.size() << " strings to sort." << std::endl; // sort double ts1_sort = tlx::timestamp(); { if (parallel) tlx::sort_strings_parallel(strings); else tlx::sort_strings(strings); } double ts2_sort = tlx::timestamp(); std::cerr << "Sorting took " << ts2_sort - ts1_sort << " seconds." << std::endl; // output sorted strings double ts1_write = tlx::timestamp(); for (size_t i = 0; i < strings.size(); ++i) { std::cout << strings[i] << '\n'; } double ts2_write = tlx::timestamp(); std::cerr << "Writing took " << ts2_write - ts1_write << " seconds at " << tlx::format_iec_units(size / (ts2_write - ts1_write)) << "/s" << std::endl; return 0; } /******************************************************************************/
28.900763
80
0.51215
kurpicz
4c48f3a0894321dcd250130dd421e2c59419090d
128
hpp
C++
Vendor/GLM/glm/ext/vector_uint4.hpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
2
2022-01-11T21:15:31.000Z
2022-02-22T21:14:33.000Z
Vendor/GLM/glm/ext/vector_uint4.hpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
Vendor/GLM/glm/ext/vector_uint4.hpp
wdrDarx/DEngine3
27e2de3b56b6d4c8705e8a0e36f5911d8651caa2
[ "MIT" ]
null
null
null
version https://git-lfs.github.com/spec/v1 oid sha256:1afbf32485cf310fb8abd8f9610be2c7fef1fd71a5c4495cad4b942c74832b16 size 417
32
75
0.882813
wdrDarx
4c4be30e3878443d9effb9a9e22ae0838d6e87d2
2,439
hpp
C++
src/mfx/dsp/shape/DistBounce.hpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/shape/DistBounce.hpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
src/mfx/dsp/shape/DistBounce.hpp
mikelange49/pedalevite
a81bd8a6119c5920995ec91b9f70e11e9379580e
[ "WTFPL" ]
null
null
null
/***************************************************************************** DistBounce.hpp Author: Laurent de Soras, 2018 --- 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 (mfx_dsp_shape_DistBounce_CODEHEADER_INCLUDED) #define mfx_dsp_shape_DistBounce_CODEHEADER_INCLUDED /*\\\ INCLUDE FILES \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ #include <algorithm> namespace mfx { namespace dsp { namespace shape { /*\\\ PUBLIC \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ float DistBounce::process_sample (float x) { // Updates the current ball position according ot its speed _pos += _speed; float speed_max_loc = _speed_max; // If the ball falls under the floor, makes it bounce if (_pos < x) { _pos = x; speed_max_loc = bounce (x); } // Also makes it bounce if it goes over the ceiling else { const float tunnel_top = x + _tunnel_height; if (_pos > tunnel_top) { _pos = tunnel_top; speed_max_loc = bounce (x); } } // Speed is updated one sample too late with regard to the gravity. _speed -= _grav; // Updates the ball speed according to the gravity _speed = std::min (_speed, speed_max_loc); _prev_val = x; return _pos; } /*\\\ PROTECTED \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ /*\\\ PRIVATE \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/ float DistBounce::bounce (float val) { // Computes the ball speed according to the bounce angle on the curve and // bounce rate. const float slope = val - _prev_val; _speed = slope + (slope - _speed) * _bounce_rate; // Prevents ball to elevate with an exagerated velocity, which would get // it down very slowly (and would cut audio by saturation) const float speed_max_loc = std::max (slope, _speed_max); return speed_max_loc; } } // namespace shape } // namespace dsp } // namespace mfx #endif // mfx_dsp_shape_DistBounce_CODEHEADER_INCLUDED /*\\\ EOF \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\*/
21.584071
78
0.563346
mikelange49
4c4dd326cea35f8946374b9ff8fe82f898b94b49
306
cpp
C++
Online Judges/A2OJ/1500-1599 Ladder/478CTableDecorations.cpp
NelsonGomesNeto/ProgramC
e743b1b869f58f7f3022d18bac00c5e0b078562e
[ "MIT" ]
3
2018-12-18T13:39:42.000Z
2021-06-23T18:05:18.000Z
Online Judges/A2OJ/1500-1599 Ladder/478CTableDecorations.cpp
NelsonGomesNeto/ProgramC
e743b1b869f58f7f3022d18bac00c5e0b078562e
[ "MIT" ]
1
2018-11-02T21:32:40.000Z
2018-11-02T22:47:12.000Z
Online Judges/A2OJ/1500-1599 Ladder/478CTableDecorations.cpp
NelsonGomesNeto/ProgramC
e743b1b869f58f7f3022d18bac00c5e0b078562e
[ "MIT" ]
6
2018-10-27T14:07:52.000Z
2019-11-14T13:49:29.000Z
#include <bits/stdc++.h> #define lli long long int using namespace std; lli ballons[3]; int main() { scanf("%lld %lld %lld", &ballons[0], &ballons[1], &ballons[2]); sort(ballons, ballons+3); printf("%lld\n", min((ballons[0] + ballons[1] + ballons[2]) / 3, ballons[0] + ballons[1])); return(0); }
21.857143
93
0.617647
NelsonGomesNeto
4c4e40ce08975637d53728fd46ea9109fa9fd8b6
481
hpp
C++
src/autaxx/search/mcts/mcts.hpp
kz04px/autaxx
40393053ab1e6d96ba2d5825219ee139a962b48d
[ "MIT" ]
3
2020-05-06T02:03:35.000Z
2021-11-23T00:08:51.000Z
src/autaxx/search/mcts/mcts.hpp
kz04px/autaxx
40393053ab1e6d96ba2d5825219ee139a962b48d
[ "MIT" ]
1
2021-01-09T10:41:53.000Z
2021-01-10T20:43:51.000Z
src/autaxx/search/mcts/mcts.hpp
kz04px/autaxx
40393053ab1e6d96ba2d5825219ee139a962b48d
[ "MIT" ]
null
null
null
#ifndef SEARCH_MCTS_HPP #define SEARCH_MCTS_HPP #include <libataxx/position.hpp> #include "../search.hpp" namespace search::mcts { class MCTS : public Search { public: void go(const libataxx::Position pos, const Settings &settings) override { stop(); search_thread_ = std::thread(&MCTS::root, this, pos, settings); } private: void root(const libataxx::Position pos, const Settings &settings) noexcept; }; } // namespace search::mcts #endif
20.913043
79
0.68815
kz04px
4c53e89752572fe348dd8a7fdc646518d5d98b48
12,660
cc
C++
src/Utilities/iterateIdealH.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
22
2018-07-31T21:38:22.000Z
2020-06-29T08:58:33.000Z
src/Utilities/iterateIdealH.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
41
2020-09-28T23:14:27.000Z
2022-03-28T17:01:33.000Z
src/Utilities/iterateIdealH.cc
jmikeowen/Spheral
3e1082a7aefd6b328bd3ae24ca1a477108cfc3c4
[ "BSD-Source-Code", "BSD-3-Clause-LBNL", "FSFAP" ]
7
2019-12-01T07:00:06.000Z
2020-09-15T21:12:39.000Z
//------------------------------------------------------------------------------ // Iterate the ideal H algorithm to converge on a new H field. // This routine replaces the H field in place. //------------------------------------------------------------------------------ #include "iterateIdealH.hh" #include "Field/FieldList.hh" #include "NodeList/SmoothingScaleBase.hh" #include "Utilities/allReduce.hh" #include "Distributed/Communicator.hh" #include "Geometry/GeometryRegistrar.hh" #include <ctime> using std::vector; using std::string; using std::pair; using std::make_pair; using std::cout; using std::cerr; using std::endl; using std::min; using std::max; using std::abs; namespace Spheral { template<typename Dimension> void iterateIdealH(DataBase<Dimension>& dataBase, const vector<Boundary<Dimension>*>& boundaries, const TableKernel<Dimension>& W, const SmoothingScaleBase<Dimension>& smoothingScaleMethod, const int maxIterations, const double tolerance, const double nPerhForIteration, const bool sphericalStart, const bool fixDeterminant) { typedef typename Dimension::Scalar Scalar; typedef typename Dimension::Vector Vector; typedef typename Dimension::SymTensor SymTensor; // Start the timing. const auto t0 = clock(); // Extract the state we care about. const auto pos = dataBase.fluidPosition(); auto m = dataBase.fluidMass(); auto rho = dataBase.fluidMassDensity(); auto H = dataBase.fluidHfield(); // If we're using the fixDeterminant, take a snapshot of the input H determinants. auto Hdet0 = dataBase.newFluidFieldList(double()); if (fixDeterminant) { for (auto itr = dataBase.internalNodeBegin(); itr != dataBase.internalNodeEnd(); ++itr) Hdet0(itr) = H(itr).Determinant(); } // Store the input nperh for each NodeList. // If we're rescaling the nodes per h for our work, make a cut at it. vector<double> nperh0; for (auto nodeListItr = dataBase.fluidNodeListBegin(); nodeListItr != dataBase.fluidNodeListEnd(); ++nodeListItr) { const auto nperh = (*nodeListItr)->nodesPerSmoothingScale(); nperh0.push_back(nperh); if (distinctlyGreaterThan(nPerhForIteration, 0.0)) { auto& Hfield = **(H.fieldForNodeList(**nodeListItr)); Hfield *= Dimension::rootnu(nperh/nPerhForIteration); (*nodeListItr)->nodesPerSmoothingScale(nPerhForIteration); } } CHECK(nperh0.size() == dataBase.numFluidNodeLists()); // If we are both fixing the H determinant and rescaling the nodes per h, // we need a snapshot of the rescaled H determinant as well. auto Hdet1 = dataBase.newFluidFieldList(double()); if (fixDeterminant) { for (auto itr = dataBase.internalNodeBegin(); itr != dataBase.internalNodeEnd(); ++itr) Hdet1(itr) = H(itr).Determinant(); } // If requested, start by making all the H's round (volume preserving). if (sphericalStart) { for (auto itr = dataBase.internalNodeBegin(); itr != dataBase.internalNodeEnd(); ++itr) { const auto Hdeti = H(itr).Determinant(); const auto Hi = Dimension::rootnu(Hdeti) * SymTensor::one; H(itr) = Hi; } } // Build a list of flags to indicate which nodes have been completed. auto flagNodeDone = dataBase.newFluidFieldList(0, "node completed"); // Iterate until we either hit the max iterations or the H's achieve convergence. const auto numNodeLists = dataBase.numFluidNodeLists(); auto maxDeltaH = 2.0*tolerance; auto itr = 0; while (itr < maxIterations and maxDeltaH > tolerance) { ++itr; maxDeltaH = 0.0; // flagNodeDone = 0; // Remove any old ghost node information from the NodeLists. for (auto k = 0u; k < numNodeLists; ++k) { auto nodeListPtr = *(dataBase.fluidNodeListBegin() + k); nodeListPtr->numGhostNodes(0); nodeListPtr->neighbor().updateNodes(); } // Enforce boundary conditions. for (auto k = 0u; k < boundaries.size(); ++k) { auto boundaryPtr = *(boundaries.begin() + k); boundaryPtr->setAllGhostNodes(dataBase); boundaryPtr->applyFieldListGhostBoundary(m); boundaryPtr->applyFieldListGhostBoundary(rho); boundaryPtr->finalizeGhostBoundary(); for (auto nodeListItr = dataBase.fluidNodeListBegin(); nodeListItr != dataBase.fluidNodeListEnd(); ++nodeListItr) { (*nodeListItr)->neighbor().updateNodes(); } } // Prepare a FieldList to hold the new H. FieldList<Dimension, SymTensor> H1(H); H1.copyFields(); auto zerothMoment = dataBase.newFluidFieldList(0.0, "zerothMoment"); auto secondMoment = dataBase.newFluidFieldList(SymTensor::zero, "secondMoment"); // Get the new connectivity. dataBase.updateConnectivityMap(false, false, false); const auto& connectivityMap = dataBase.connectivityMap(); const auto& pairs = connectivityMap.nodePairList(); const auto npairs = pairs.size(); // Walk the pairs. #pragma omp parallel { typename SpheralThreads<Dimension>::FieldListStack threadStack; auto zerothMoment_thread = zerothMoment.threadCopy(threadStack); auto secondMoment_thread = secondMoment.threadCopy(threadStack); int i, j, nodeListi, nodeListj; Scalar ri, rj, mRZi, mRZj, Wi, gWi, Wj, gWj; Vector xij, etai, etaj, gradWi, gradWj; SymTensor thpt; #pragma omp for for (auto k = 0u; k < npairs; ++k) { i = pairs[k].i_node; j = pairs[k].j_node; nodeListi = pairs[k].i_list; nodeListj = pairs[k].j_list; // Anything to do? if (flagNodeDone(nodeListi, i) == 0 or flagNodeDone(nodeListj, j) == 0) { const auto& posi = pos(nodeListi, i); const auto& Hi = H(nodeListi, i); const auto mi = m(nodeListi, i); const auto rhoi = rho(nodeListi, i); const auto& posj = pos(nodeListj, j); const auto& Hj = H(nodeListj, j); const auto mj = m(nodeListj, j); const auto rhoj = rho(nodeListj, j); // Compute the node-node weighting auto fweightij = 1.0; if (nodeListi != nodeListj) { if (GeometryRegistrar::coords() == CoordinateType::RZ){ ri = abs(posi.y()); rj = abs(posj.y()); mRZi = mi/(2.0*M_PI*ri); mRZj = mj/(2.0*M_PI*rj); fweightij = mRZj*rhoi/(mRZi*rhoj); } else { fweightij = mj*rhoi/(mi*rhoj); } } xij = posi - posj; etai = Hi*xij; etaj = Hj*xij; thpt = xij.selfdyad()/(xij.magnitude2() + 1.0e-10); std::tie(Wi, gWi) = W.kernelAndGradValue(etai.magnitude(), 1.0); gradWi = gWi*Hi*etai.unitVector(); std::tie(Wj, gWj) = W.kernelAndGradValue(etaj.magnitude(), 1.0); gradWj = gWj*Hj*etaj.unitVector(); // Increment the moments zerothMoment_thread(nodeListi, i) += fweightij* std::abs(gWi); zerothMoment_thread(nodeListj, j) += 1.0/fweightij*std::abs(gWj); secondMoment_thread(nodeListi, i) += fweightij* gradWi.magnitude2()*thpt; secondMoment_thread(nodeListj, j) += 1.0/fweightij*gradWj.magnitude2()*thpt; } } // Do the thread reduction for zeroth and second moments. threadReduceFieldLists<Dimension>(threadStack); } // OMP parallel // Finish the moments and measure the new H. for (auto nodeListi = 0u; nodeListi < numNodeLists; ++nodeListi) { const auto nodeListPtr = *(dataBase.fluidNodeListBegin() + nodeListi); const auto ni = nodeListPtr->numInternalNodes(); const auto hmin = nodeListPtr->hmin(); const auto hmax = nodeListPtr->hmax(); const auto hminratio = nodeListPtr->hminratio(); const auto nPerh = nodeListPtr->nodesPerSmoothingScale(); #pragma omp parallel for for (auto i = 0u; i < ni; ++i) { if (flagNodeDone(nodeListi, i) == 0) { zerothMoment(nodeListi, i) = Dimension::rootnu(zerothMoment(nodeListi, i)); H1(nodeListi, i) = smoothingScaleMethod.newSmoothingScale(H(nodeListi, i), pos(nodeListi, i), zerothMoment(nodeListi, i), secondMoment(nodeListi, i), W, hmin, hmax, hminratio, nPerh, connectivityMap, nodeListi, i); // If we are preserving the determinant, do it. if (fixDeterminant) { H1(nodeListi, i) *= Dimension::rootnu(Hdet1(nodeListi, i)/H1(nodeListi, i).Determinant()); CHECK(fuzzyEqual(H1(nodeListi, i).Determinant(), Hdet1(nodeListi, i))); } // Check how much this H has changed. const auto H1sqrt = H1(nodeListi, i).sqrt(); const auto phi = (H1sqrt*H(nodeListi, i).Inverse()*H1sqrt).Symmetric().eigenValues(); const auto phimin = phi.minElement(); const auto phimax = phi.maxElement(); const auto deltaHi = max(abs(phimin - 1.0), abs(phimax - 1.0)); if (deltaHi <= tolerance) flagNodeDone(nodeListi, i) = 1; maxDeltaH = max(maxDeltaH, deltaHi); } } } // Assign the new H's. H.assignFields(H1); // Globally reduce the max H change. maxDeltaH = allReduce(maxDeltaH, MPI_MAX, Communicator::communicator()); // Output the statitics. if (Process::getRank() == 0) cerr << "iterateIdealH: (iteration, deltaH) = (" << itr << ", " << maxDeltaH << ")" << endl; } // If we have rescaled the nodes per h, now we have to iterate the H determinant // to convergence with the proper nperh. if (distinctlyGreaterThan(nPerhForIteration, 0.0)) { // Reset the nperh. size_t k = 0; for (auto nodeListItr = dataBase.fluidNodeListBegin(); nodeListItr != dataBase.fluidNodeListEnd(); ++nodeListItr, ++k) { CHECK(k < nperh0.size()); //const double nperh = nperh0[k]; // Field<Dimension, SymTensor>& Hfield = **(H.fieldForNodeList(**nodeListItr)); // Hfield *= Dimension::rootnu(nPerhForIteration/nperh); (*nodeListItr)->nodesPerSmoothingScale(nperh0[k]); } CHECK(k == nperh0.size()); } // If we're fixing the determinant, restore them. if (fixDeterminant) { for (auto itr = dataBase.internalNodeBegin(); itr != dataBase.internalNodeEnd(); ++itr) { H(itr) *= Dimension::rootnu(Hdet0(itr)/H(itr).Determinant()); ENSURE(fuzzyEqual(H(itr).Determinant(), Hdet0(itr), 1.0e-10)); } } // Leave the boundary conditions properly enforced. for (auto nodeListItr = dataBase.fluidNodeListBegin(); nodeListItr != dataBase.fluidNodeListEnd(); ++nodeListItr) { (*nodeListItr)->numGhostNodes(0); (*nodeListItr)->neighbor().updateNodes(); } for (auto boundaryItr = boundaries.begin(); boundaryItr != boundaries.end(); ++boundaryItr) { (*boundaryItr)->setAllGhostNodes(dataBase); (*boundaryItr)->finalizeGhostBoundary(); for (typename DataBase<Dimension>::FluidNodeListIterator nodeListItr = dataBase.fluidNodeListBegin(); nodeListItr != dataBase.fluidNodeListEnd(); ++nodeListItr) { (*nodeListItr)->neighbor().updateNodes(); } } for (auto boundaryItr = boundaries.begin(); boundaryItr != boundaries.end(); ++boundaryItr) { (*boundaryItr)->applyFieldListGhostBoundary(m); } for (auto boundaryItr = boundaries.begin(); boundaryItr != boundaries.end(); ++boundaryItr) { (*boundaryItr)->finalizeGhostBoundary(); } // Report the final timing. const auto t1 = clock(); if (Process::getRank() == 0) cerr << "iterateIdealH: required a total of " << (t1 - t0)/CLOCKS_PER_SEC << " seconds." << endl; } }
37.455621
105
0.584834
jmikeowen
4c5707c14fa320d7b997f11c6df0b19a42788ebe
3,696
cpp
C++
src/nbl/video/IPhysicalDevice.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
src/nbl/video/IPhysicalDevice.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
src/nbl/video/IPhysicalDevice.cpp
deprilula28/Nabla
6b5de216221718191713dcf6de8ed6407182ddf0
[ "Apache-2.0" ]
null
null
null
#include "nbl/video/IPhysicalDevice.h" namespace nbl::video { IPhysicalDevice::IPhysicalDevice(core::smart_refctd_ptr<system::ISystem>&& s, core::smart_refctd_ptr<asset::IGLSLCompiler>&& glslc) : m_system(std::move(s)), m_GLSLCompiler(std::move(glslc)) { } void IPhysicalDevice::addCommonGLSLDefines(std::ostringstream& pool, const bool runningInRenderdoc) { addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_UBO_SIZE",m_limits.maxUBOSize); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_SSBO_SIZE",m_limits.maxSSBOSize); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_BUFFER_VIEW_TEXELS",m_limits.maxBufferViewSizeTexels); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_BUFFER_SIZE",m_limits.maxBufferSize); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_IMAGE_ARRAY_LAYERS",m_limits.maxImageArrayLayers); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_PER_STAGE_SSBO_COUNT",m_limits.maxPerStageSSBOs); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_SSBO_COUNT",m_limits.maxSSBOs); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_UBO_COUNT",m_limits.maxUBOs); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_TEXTURE_COUNT",m_limits.maxTextures); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_STORAGE_IMAGE_COUNT",m_limits.maxStorageImages); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_DRAW_INDIRECT_COUNT",m_limits.maxDrawIndirectCount); addGLSLDefineToPool(pool,"NBL_LIMIT_MIN_POINT_SIZE",m_limits.pointSizeRange[0]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_POINT_SIZE",m_limits.pointSizeRange[1]); addGLSLDefineToPool(pool,"NBL_LIMIT_MIN_LINE_WIDTH",m_limits.lineWidthRange[0]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_LINE_WIDTH",m_limits.lineWidthRange[1]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_VIEWPORTS",m_limits.maxViewports); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_VIEWPORT_WIDTH",m_limits.maxViewportDims[0]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_VIEWPORT_HEIGHT",m_limits.maxViewportDims[1]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_WORKGROUP_SIZE_X",m_limits.maxWorkgroupSize[0]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_WORKGROUP_SIZE_Y",m_limits.maxWorkgroupSize[1]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_WORKGROUP_SIZE_Z",m_limits.maxWorkgroupSize[2]); addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_OPTIMALLY_RESIDENT_WORKGROUP_INVOCATIONS",m_limits.maxOptimallyResidentWorkgroupInvocations); // TODO: Need upper and lower bounds on workgroup sizes! // TODO: Need to know if subgroup size is constant/known addGLSLDefineToPool(pool,"NBL_LIMIT_SUBGROUP_SIZE",m_limits.subgroupSize); // TODO: @achal test examples 14 and 48 on all APIs and GPUs addGLSLDefineToPool(pool,"NBL_LIMIT_MAX_RESIDENT_INVOCATIONS",m_limits.maxResidentInvocations); // TODO: Add feature defines if (runningInRenderdoc) addGLSLDefineToPool(pool,"NBL_RUNNING_IN_RENDERDOC"); } bool IPhysicalDevice::validateLogicalDeviceCreation(const ILogicalDevice::SCreationParams& params) const { using range_t = core::SRange<const ILogicalDevice::SQueueCreationParams>; range_t qcis(params.queueParams, params.queueParams+params.queueParamsCount); for (const auto& qci : qcis) { if (qci.familyIndex >= m_qfamProperties->size()) return false; const auto& qfam = (*m_qfamProperties)[qci.familyIndex]; if (qci.count == 0u) return false; if (qci.count > qfam.queueCount) return false; for (uint32_t i = 0u; i < qci.count; ++i) { const float priority = qci.priorities[i]; if (priority < 0.f) return false; if (priority > 1.f) return false; } } return true; } }
42.976744
137
0.761093
deprilula28
4c586bbb63dbe59906ec2df3117c23c85a6c9fc1
6,077
hpp
C++
src/core/pin_mesh_base.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
11
2016-03-31T17:46:15.000Z
2022-02-14T01:07:56.000Z
src/core/pin_mesh_base.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2016-04-04T16:40:47.000Z
2019-10-16T22:22:54.000Z
src/core/pin_mesh_base.hpp
tp-ntouran/mocc
77d386cdf341b1a860599ff7c6e4017d46e0b102
[ "Apache-2.0" ]
3
2019-10-16T22:20:15.000Z
2019-11-28T11:59:03.000Z
/* Copyright 2016 Mitchell Young Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ #pragma once #include <string> #include "util/global_config.hpp" #include "util/pugifwd.hpp" #include "geometry/geom.hpp" #include "position.hpp" namespace mocc { /** * \ref PinMesh is a virtual class, which provides methods for performing * ray tracing and accessing data in common between all types of pin mesh, * such as region volumes, x and y pitch, etc. */ class PinMesh { public: PinMesh(const pugi::xml_node &input); virtual ~PinMesh() { } int id() const { return id_; } int n_reg() const { return n_reg_; } int n_xsreg() const { return n_xsreg_; } real_t pitch_x() const { return pitch_x_; } real_t pitch_y() const { return pitch_y_; } real_t area() const { return pitch_x_ * pitch_y_; } const VecF &areas() const { return areas_; } /** * \param[in] p1 the entry point of the ray. * \param[in] p2 the exit point of the ray. * \param[in] first_reg the index of the first FSR in the pin mesh. * \param[in,out] s the vector of ray segment lengths to be modified. * \param[in,out] reg the vector of ray segment FSR indices to be * modified. * * \returns The number of segments that pass through pin geometry * (useful for CMFD data). * * Given an entry and exit point, which should be on the boundary of the * pin (in pin-local coordinates), and the index of the first FSR in the * pin, append values to the vectors of segment length and corresponding * region index. * * * The segment lengths are uncorrected, which is to say that they are * the true lengths of the rays as they pass through the mesh. * Therefore, summing the volume of the segments in each FSR is not * guaranteed to return the correct FSR volume. Make sure to correct for * this after tracing all of the rays in a given angle. */ virtual int trace(Point2 p1, Point2 p2, int first_reg, VecF &s, VecI &reg) const = 0; /** * Find the pin-local region index corresponding to the point provided. * * \param[in] p the \ref Point2 for which to find the FSR index * * Given a point in pin-local coordinates, return the mesh region index * in which the point resides */ virtual int find_reg(Point2 p) const = 0; /** * \brief Find a pin-local region index corresponding to the \ref Point2 * and \ref Direction provided * * \param p a \ref Point2 containing the pin-local coordinates to look * up a region for. * \param dir a \ref Direction of travel, used to establish sense w.r.t. * internal surfaces. * * This is similar to PinMeshBase::find_reg(Point2), except that it * handles the case where the point \p p lies directly on one of the * surfaces in a well-defined manner. In such cases, the returned region * index should refer to the region on the side of the surface pointed * to by \p dir. */ virtual int find_reg(Point2 p, Direction dir) const = 0; /** * Return the number of flat source regions corresponding to an XS * region (indexed pin-locally). */ virtual size_t n_fsrs(unsigned int xsreg) const = 0; /** * \brief Insert hte \ref PinMesh into the passed ostream. * * This is useful to be able to use \c operator<< on a polymorphic \ref * PinMesh and have it work as expected. */ virtual void print(std::ostream &os) const; /** * \brief Return the distance to the nearest surface in the pin mesh, * and the boundary of the pin if that surface is at the edge of the * pin. * * \param p a Point2 containing the location from which to measure * \param dir a Direction containing the direction in which to measure * \param coincident whether the passed point is to be considered coincident * with the surface. This is useful for preventing repeated, logically * identical intersections */ virtual std::pair<real_t, bool> distance_to_surface(Point2 p, Direction dir, int &coincident) const = 0; /** * This essentially wraps the \ref Point2 version */ std::pair<real_t, bool> distance_to_surface(Point3 p, Direction dir, int &coincident) const { return this->distance_to_surface(p.to_2d(), dir, coincident); } /** * \brief Return a string containing PyCairo commands to draw the \ref * PinMesh. */ virtual std::string draw() const = 0; /** * \brief Provide stream insertion support. * * Calls the \ref PinMesh::print() routine, which is virtual, allowing * for polymorphism. */ friend std::ostream &operator<<(std::ostream &os, const PinMesh &pm); protected: int id_; int n_reg_; int n_xsreg_; real_t pitch_x_; real_t pitch_y_; VecF areas_; }; /** * This is a simple struct that contains a const pointer to a \ref PinMesh, * along with a Position describing its location. This is essentially a * useful tuple for returning both values from a lookup function (see * \ref CoreMesh::get_pinmesh() and \ref Plane::get_pinmesh()). */ struct PinMeshTuple { PinMeshTuple(Position pos, const PinMesh *pm) : position(pos), pm(pm) { } Position position; const PinMesh *pm; }; }
30.084158
80
0.648017
tp-ntouran
4c59823db506f58dc5c26ae1e30735dfe84a6096
3,975
cpp
C++
package/src/memmon.cpp
chrisburr/prmon
27dac8e979571811fc875edc8dd6072ab4e00880
[ "Apache-2.0" ]
null
null
null
package/src/memmon.cpp
chrisburr/prmon
27dac8e979571811fc875edc8dd6072ab4e00880
[ "Apache-2.0" ]
null
null
null
package/src/memmon.cpp
chrisburr/prmon
27dac8e979571811fc875edc8dd6072ab4e00880
[ "Apache-2.0" ]
null
null
null
// Copyright (C) 2018-2020 CERN // License Apache2 - see LICENCE file #include "memmon.h" #include <string.h> #include <unistd.h> #include <fstream> #include <iostream> #include <limits> #include <regex> #include <sstream> #include "utils.h" // Constructor; uses RAII pattern to be valid // after construction memmon::memmon() : mem_params{}, mem_stats{}, mem_peak_stats{}, mem_average_stats{}, mem_total_stats{}, iterations{0} { mem_params.reserve(params.size()); for (const auto& param : params) { mem_params.push_back(param.get_name()); mem_stats[param.get_name()] = 0; mem_peak_stats[param.get_name()] = 0; mem_average_stats[param.get_name()] = 0; mem_total_stats[param.get_name()] = 0; } } void memmon::update_stats(const std::vector<pid_t>& pids) { for (auto& stat : mem_stats) stat.second = 0; std::string key_str{}, value_str{}; for (const auto pid : pids) { std::stringstream smaps_fname{}; smaps_fname << "/proc/" << pid << "/smaps" << std::ends; std::ifstream smap_stat{smaps_fname.str()}; while (smap_stat) { // Read off the potentially interesting "key: value", then discard // the rest of the line smap_stat >> key_str >> value_str; smap_stat.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); if (smap_stat) { if (key_str == "Size:") { mem_stats["vmem"] += std::stol(value_str); } else if (key_str == "Pss:") { mem_stats["pss"] += std::stol(value_str); } else if (key_str == "Rss:") { mem_stats["rss"] += std::stol(value_str); } else if (key_str == "Swap:") { mem_stats["swap"] += std::stol(value_str); } } } } // Update the statistics with the new snapshot values ++iterations; for (const auto& mem_param : mem_params) { if (mem_stats[mem_param] > mem_peak_stats[mem_param]) mem_peak_stats[mem_param] = mem_stats[mem_param]; mem_total_stats[mem_param] += mem_stats[mem_param]; mem_average_stats[mem_param] = double(mem_total_stats[mem_param]) / iterations; } } // Return the summed counters std::map<std::string, unsigned long long> const memmon::get_text_stats() { return mem_stats; } // For JSON totals return peaks std::map<std::string, unsigned long long> const memmon::get_json_total_stats() { return mem_peak_stats; } // Average values are calculated already for us based on the iteration // count std::map<std::string, double> const memmon::get_json_average_stats( unsigned long long elapsed_clock_ticks) { return mem_average_stats; } // Collect related hardware information void const memmon::get_hardware_info(nlohmann::json& hw_json) { // Read some information from /proc/meminfo std::ifstream memInfoFile{"/proc/meminfo"}; if (!memInfoFile.is_open()) { std::cerr << "Failed to open /proc/meminfo" << std::endl; return; } // Metrics to read from the input std::vector<std::string> metrics{"MemTotal"}; // Loop over the file std::string line; while (std::getline(memInfoFile, line)) { if (line.empty()) continue; size_t splitIdx = line.find(":"); std::string val; if (splitIdx != std::string::npos) { val = line.substr(splitIdx + 1); if (val.empty()) continue; for (const auto& metric : metrics) { if (line.size() >= metric.size() && line.compare(0, metric.size(), metric) == 0) { val = val.substr(0, val.size() - 3); // strip the trailing kB hw_json["HW"]["mem"][metric] = std::stol(std::regex_replace(val, std::regex("^\\s+|\\s+$"), "")); } // end of metric check } // end of populating metrics } // end of seperator check } // end of reading memInfoFile // Close the file memInfoFile.close(); return; } void const memmon::get_unit_info(nlohmann::json& unit_json) { prmon::fill_units(unit_json, params); return; }
29.887218
80
0.633962
chrisburr
4c61eb3fc7ad06b5159b7ffb6a1d040791b07154
604
cpp
C++
HDU/5443.cpp
Superdanby/YEE
49a6349dc5644579246623b480777afbf8031fcd
[ "MIT" ]
1
2019-09-07T15:56:05.000Z
2019-09-07T15:56:05.000Z
HDU/5443.cpp
Superdanby/YEE
49a6349dc5644579246623b480777afbf8031fcd
[ "MIT" ]
null
null
null
HDU/5443.cpp
Superdanby/YEE
49a6349dc5644579246623b480777afbf8031fcd
[ "MIT" ]
null
null
null
//httpacm.hdu.edu.cnshowproblem.phppid=5443 #include <iostream> using namespace std; int cases, water, query; int main() { scanf("%d", &cases); while(cases--) { scanf("%d", &water); int W[water]; for(int x=0; x<water; x++) scanf("%d", &W[x]); scanf("%d", &query); int Max, front, back; for(int x=0; x<query; x++) { Max=0; scanf("%d %d", &front, &back); for(int x=front-1; x<back; x++) Max=max(Max, W[x]); printf("%d\n", Max); } } return 0; }
20.827586
43
0.440397
Superdanby
4c6412b497606b2ef8f4b66092e7ae1d9fb47cca
2,339
cc
C++
src/arch/beos/cbm5x0ui.cc
swingflip/C64_mini_VICE
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
[ "Apache-2.0" ]
2
2018-11-15T19:52:34.000Z
2022-01-17T19:45:01.000Z
src/arch/beos/cbm5x0ui.cc
Classicmods/C64_mini_VICE
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
[ "Apache-2.0" ]
null
null
null
src/arch/beos/cbm5x0ui.cc
Classicmods/C64_mini_VICE
7a6d9d41ae60409a2bb985bb8d6324a7269a0daa
[ "Apache-2.0" ]
3
2019-06-30T05:37:04.000Z
2021-12-04T17:12:35.000Z
/* * cbm5x0ui.cc - CBM5x0-specific user interface. * * Written by * Marcus Sutton <loggedoubt@gmail.com> * * This file is part of VICE, the Versatile Commodore Emulator. * See README for copyright notice. * * 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. * */ #include "vice.h" #include <Message.h> #include <stdio.h> extern "C" { #include "cbm2ui.h" #include "constants.h" #include "ui.h" #include "ui_cbm2.h" #include "ui_sid.h" #include "ui_vicii.h" #include "video.h" } ui_menu_toggle cbm5x0_ui_menu_toggles[] = { { "VICIIDoubleSize", MENU_TOGGLE_DOUBLESIZE }, { "VICIIDoubleScan", MENU_TOGGLE_DOUBLESCAN }, { "VICIIVideoCache", MENU_TOGGLE_VIDEOCACHE }, { NULL, 0 } }; ui_res_possible_values cbm5x0RenderFilters[] = { { VIDEO_FILTER_NONE, MENU_RENDER_FILTER_NONE }, { VIDEO_FILTER_CRT, MENU_RENDER_FILTER_CRT_EMULATION }, { VIDEO_FILTER_SCALE2X, MENU_RENDER_FILTER_SCALE2X }, { -1, 0 } }; ui_res_value_list cbm5x0_ui_res_values[] = { { "VICIIFilter", cbm5x0RenderFilters }, { NULL, NULL } }; void cbm5x0_ui_specific(void *msg, void *window) { switch (((BMessage*)msg)->what) { case MENU_CBM2_SETTINGS: ui_cbm2(); break; case MENU_VICII_SETTINGS: ui_vicii(); break; case MENU_SID_SETTINGS: ui_sid(NULL); break; default: ; } } int cbm5x0ui_init(void) { ui_register_machine_specific(cbm5x0_ui_specific); ui_register_menu_toggles(cbm5x0_ui_menu_toggles); ui_register_res_values(cbm5x0_ui_res_values); ui_update_menus(); return 0; } void cbm5x0ui_shutdown(void) { }
26.280899
72
0.690038
swingflip
4c67f34c3e043166b5e24fdf32c7d6cdd3292220
978
cpp
C++
ZF/ZFCore/zfsrc/ZFCore/ZFObjectDef/ZFTypeId_CoreType_float.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
57
2016-06-12T11:05:55.000Z
2021-05-22T13:12:17.000Z
ZF/ZFCore/zfsrc/ZFCore/ZFObjectDef/ZFTypeId_CoreType_float.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
null
null
null
ZF/ZFCore/zfsrc/ZFCore/ZFObjectDef/ZFTypeId_CoreType_float.cpp
ZFFrameworkDist/ZFFramework
6b498e7b95ee6d6aaa28d8369eef8c2ff94daaf7
[ "MIT" ]
20
2016-05-26T04:47:37.000Z
2020-12-13T01:39:39.000Z
#include "ZFTypeId_CoreType.h" #include "ZFObjectImpl.h" #include "ZFSerializableDataSerializableConverter.h" ZF_NAMESPACE_GLOBAL_BEGIN // ============================================================ // utils #define _ZFP_ZFTYPEID_DEFINE_float(TypeName, Type) \ ZFTYPEID_DEFINE_BY_STRING_CONVERTER(TypeName, Type, { \ return zfsToFloatT(v, src, srcLen); \ }, { \ return zfsFromFloatT(s, v); \ }) // ============================================================ _ZFP_ZFTYPEID_DEFINE_float(zffloat, zffloat) ZFTYPEID_PROGRESS_DEFINE_BY_VALUE(zffloat, zffloat) // ============================================================ _ZFP_ZFTYPEID_DEFINE_float(zfdouble, zfdouble) ZFTYPEID_PROGRESS_DEFINE_BY_VALUE(zfdouble, zfdouble) // ============================================================ _ZFP_ZFTYPEID_DEFINE_float(zflongdouble, zflongdouble) ZFTYPEID_PROGRESS_DEFINE_BY_VALUE(zflongdouble, zflongdouble) ZF_NAMESPACE_GLOBAL_END
32.6
63
0.5818
ZFFrameworkDist
4c6bea12759255848c3d87615522d087bb847ad7
11,251
hpp
C++
contrib/TAMM/src/tamm/eigen_utils.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
4
2020-10-14T17:43:00.000Z
2021-06-21T08:23:01.000Z
contrib/TAMM/src/tamm/eigen_utils.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
3
2020-06-03T19:54:30.000Z
2022-03-10T22:59:30.000Z
contrib/TAMM/src/tamm/eigen_utils.hpp
smferdous1/gfcc
e7112c0dd60566266728e4d51ea8d30aea4b775d
[ "MIT" ]
6
2020-06-08T03:54:16.000Z
2022-03-02T17:47:51.000Z
#ifndef TAMM_EIGEN_UTILS_HPP_ #define TAMM_EIGEN_UTILS_HPP_ // Eigen matrix algebra library #include "tamm/tamm.hpp" #include <Eigen/Dense> #include <unsupported/Eigen/CXX11/Tensor> #undef I using EigenTensorType=double; using Matrix = Eigen::Matrix<EigenTensorType, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; using Tensor1D = Eigen::Tensor<EigenTensorType, 1, Eigen::RowMajor>; using Tensor2D = Eigen::Tensor<EigenTensorType, 2, Eigen::RowMajor>; using Tensor3D = Eigen::Tensor<EigenTensorType, 3, Eigen::RowMajor>; using Tensor4D = Eigen::Tensor<EigenTensorType, 4, Eigen::RowMajor>; namespace tamm { template<typename T, int ndim> void patch_copy(std::vector<T>& sbuf, Eigen::Tensor<T, ndim, Eigen::RowMajor>& etensor, const std::array<int, ndim>& block_dims, const std::array<int, ndim>& block_offset, bool t2e = true) { assert(0); } template<typename T> void patch_copy(std::vector<T>& sbuf, Eigen::Tensor<T, 1, Eigen::RowMajor>& etensor, const std::vector<size_t>& block_dims, const std::vector<size_t>& block_offset, bool t2e = true) { size_t c = 0; for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++, c++) { if(t2e) etensor(i) = sbuf[c]; else sbuf[c] = etensor(i); } } template<typename T> void patch_copy(std::vector<T>& sbuf, Eigen::Tensor<T, 2, Eigen::RowMajor>& etensor, const std::vector<size_t>& block_dims, const std::vector<size_t>& block_offset, bool t2e = true) { size_t c = 0; for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++, c++) { if(t2e) etensor(i, j) = sbuf[c]; else sbuf[c] = etensor(i, j); } } } template<typename T> void patch_copy(std::vector<T>& sbuf, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor, const std::vector<size_t>& block_dims, const std::vector<size_t>& block_offset, bool t2e = true) { size_t c = 0; for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++, c++) { if(t2e) etensor(i, j) = sbuf[c]; else sbuf[c] = etensor(i, j); } } } template<typename T> void patch_copy(std::vector<T>& sbuf, Eigen::Tensor<T, 3, Eigen::RowMajor>& etensor, const std::vector<size_t>& block_dims, const std::vector<size_t>& block_offset, bool t2e = true) { size_t c = 0; for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++, c++) { if(t2e) etensor(i, j, k) = sbuf[c]; else sbuf[c] = etensor(i, j, k); } } } } template<typename T> void patch_copy(std::vector<T>& sbuf, Eigen::Tensor<T, 4, Eigen::RowMajor>& etensor, const std::vector<size_t>& block_dims, const std::vector<size_t>& block_offset, bool t2e = true) { size_t c = 0; for(size_t i = block_offset[0]; i < block_offset[0] + block_dims[0]; i++) { for(size_t j = block_offset[1]; j < block_offset[1] + block_dims[1]; j++) { for(size_t k = block_offset[2]; k < block_offset[2] + block_dims[2]; k++) { for(size_t l = block_offset[3]; l < block_offset[3] + block_dims[3]; l++, c++) { if(t2e) etensor(i, j, k, l) = sbuf[c]; else sbuf[c] = etensor(i, j, k, l); } } } } } template<typename T, int ndim> Eigen::Tensor<T, ndim, Eigen::RowMajor> tamm_to_eigen_tensor( const tamm::Tensor<T>& tensor) { std::array<long, ndim> dims; const auto& tindices = tensor.tiled_index_spaces(); for(int i = 0; i < ndim; i++) { dims[i] = tindices[i].index_space().num_indices(); } Eigen::Tensor<T, ndim, Eigen::RowMajor> etensor(dims); etensor.setZero(); for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, true); } return etensor; } template<typename T> void tamm_to_eigen_tensor( const tamm::Tensor<T>& tensor, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, true); } } template<typename T, int ndim> void tamm_to_eigen_tensor(const tamm::Tensor<T>& tensor, Eigen::Tensor<T, ndim, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, true); } } template<typename T, int ndim> void eigen_to_tamm_tensor(tamm::Tensor<T>& tensor, Eigen::Tensor<T, ndim, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); // tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, false); tensor.put(blockid, buf); } } template<typename T> void eigen_to_tamm_tensor( tamm::Tensor<T>& tensor, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); // tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, false); tensor.put(blockid, buf); } } template<typename T> void eigen_to_tamm_tensor_acc( tamm::Tensor<T>& tensor, Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); // tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, false); tensor.add(blockid, buf); } } template<typename T> void eigen_to_tamm_tensor_acc( tamm::Tensor<T>& tensor, Eigen::Tensor<T, 2, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); // tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, false); tensor.add(blockid, buf); } } template<typename T> void eigen_to_tamm_tensor_acc( tamm::Tensor<T>& tensor, Eigen::Tensor<T, 3, Eigen::RowMajor>& etensor) { for(const auto& blockid : tensor.loop_nest()) { const tamm::TAMM_SIZE size = tensor.block_size(blockid); std::vector<T> buf(size); // tensor.get(blockid, buf); auto block_dims = tensor.block_dims(blockid); auto block_offset = tensor.block_offsets(blockid); patch_copy<T>(buf, etensor, block_dims, block_offset, false); tensor.add(blockid, buf); } } template<typename T, typename fxn_t> void call_eigen_matrix_fxn(const tamm::Tensor<T>& tensor, fxn_t fxn) { tamm::Tensor<T> copy_t(tensor); auto eigen_t = tamm_to_eigen_tensor<T, 2>(copy_t); using eigen_matrix = Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor>; using eigen_map = Eigen::Map<eigen_matrix>; const auto nrow = eigen_t.dimensions()[0]; const auto ncol = eigen_t.dimensions()[1]; eigen_map mapped_t(eigen_t.data(), nrow, ncol); fxn(mapped_t); } template<int nmodes, typename T, typename matrix_type> void eigen_matrix_to_tamm(matrix_type&& mat, tamm::Tensor<T>& t){ using tensor1_type = Eigen::Tensor<T, 1, Eigen::RowMajor>; using tensor2_type = Eigen::Tensor<T, 2, Eigen::RowMajor>; const auto nrows = mat.rows(); if constexpr(nmodes == 1){ //Actually a vector tensor1_type t1(std::array<long int, 1>{nrows}); for(long int i = 0; i < nrows; ++i) t1(i) = mat(i); eigen_to_tamm_tensor(t, t1); } else if constexpr(nmodes == 2){ const auto ncols = mat.cols(); tensor2_type t1(std::array<long int, 2>{nrows, ncols}) ; for(long int i=0; i < nrows; ++i) for(long int j =0; j< ncols; ++j) t1(i, j) = mat(i, j); eigen_to_tamm_tensor(t, t1); } } template<typename T> tamm::Tensor<T> retile_rank2_tensor(tamm::Tensor<T>& tensor, const tamm::TiledIndexSpace &t1, const tamm::TiledIndexSpace &t2) { EXPECTS(tensor.num_modes() == 2); //auto* ec_tmp = tensor.execution_context(); //TODO: figure out why this seg faults tamm::ProcGroup pg = ProcGroup::create_coll(GA_MPI_Comm()); auto mgr = tamm::MemoryManagerGA::create_coll(pg); tamm::Distribution_NW distribution; tamm::ExecutionContext ec{pg,&distribution,mgr}; auto is1 = tensor.tiled_index_spaces()[0].index_space(); auto is2 = tensor.tiled_index_spaces()[1].index_space(); auto dim1 = is1.num_indices(); auto dim2 = is2.num_indices(); Eigen::Matrix<T, Eigen::Dynamic, Eigen::Dynamic, Eigen::RowMajor> eigent(dim1,dim2); tamm::Tensor<T> result{t1,t2}; tamm::Tensor<T>::allocate(&ec, result); tamm_to_eigen_tensor(tensor,eigent); eigen_to_tamm_tensor(result,eigent); ec.pg().barrier(); return result; } } #endif // TAMM_EIGEN_UTILS_HPP_
35.71746
128
0.607413
smferdous1
4c705d4909c13e6b1fad2a89085c029747a42d7c
11,419
cc
C++
quadris/grid.cc
kevinli9094/my_projects
fe38528e0cf3cebf1aba73fb69bca66a9c4d4ed7
[ "MIT" ]
null
null
null
quadris/grid.cc
kevinli9094/my_projects
fe38528e0cf3cebf1aba73fb69bca66a9c4d4ed7
[ "MIT" ]
null
null
null
quadris/grid.cc
kevinli9094/my_projects
fe38528e0cf3cebf1aba73fb69bca66a9c4d4ed7
[ "MIT" ]
null
null
null
#include "grid.h" #include "cell.h" #include "textdisplay.h" #include "block.h" #include <iostream> #include <string> #include <sstream> #include "window.h" using namespace std; Grid::Grid() : score(0), highscore(0), currentLevel(0){ W.fillRectangle(452, 0, 2, 814, Xwindow::Black); W.drawString(470, 10, "Next:", Xwindow::Black); W.drawString(470, 140, "Level:", Xwindow::Black); W.drawString(470, 160, "Score:", Xwindow::Black); W.drawString(470, 180, "Hi Score:", Xwindow::Black); theGrid = new Cell*[179]; next = new Cell*[7]; for (int i = 0; i <= 179; i++){ theGrid[i] = new Cell; theGrid[i]->setCoords(i / 10, i % 10, ((i % 10) * 45 + 2), ((i/ 10) * 45 + 2), 45, 45, &W); } for (int i = 0; i <= 7; i++){ next[i] = new Cell; next[i]->setCoords(i / 4, i % 4, ((i % 4) * 45 + 472), ((i / 4) * 45 + 22), 45, 45, &W); } td = new TextDisplay(); } Grid::~Grid() { delete[] theGrid; delete[] next; delete td; } void Grid::settextonly(bool b){ this->textonly = b; } void Grid::setlevel(int i){ currentLevel = i; } int Grid::getcurrentLevel() { return currentLevel; } int Grid::getscore() { return score; } int Grid::gethighscore(){ return highscore; } void Grid::insertnext(Blocks *b){ for (int i = 0; i <= 7; i++) { next[i]->blocktype = ' '; } next[(b->block1r - 2) * 4 + b->block1c]->blocktype = b->type; next[(b->block2r - 2) * 4 + b->block2c]->blocktype = b->type; next[(b->block3r - 2) * 4 + b->block3c]->blocktype = b->type; next[(b->block4r - 2) * 4 + b->block4c]->blocktype = b->type; } void Grid::removeBlocks(Blocks *b){ theGrid[b->block1r * 10 + b->block1c]->blocktype = ' '; theGrid[b->block2r * 10 + b->block2c]->blocktype = ' '; theGrid[b->block3r * 10 + b->block3c]->blocktype = ' '; theGrid[b->block4r * 10 + b->block4c]->blocktype = ' '; theGrid[b->block1r * 10 + b->block1c]->notifyDisplay(*td); theGrid[b->block2r * 10 + b->block2c]->notifyDisplay(*td); theGrid[b->block3r * 10 + b->block3c]->notifyDisplay(*td); theGrid[b->block4r * 10 + b->block4c]->notifyDisplay(*td); theGrid[b->block1r * 10 + b->block1c]->lv = 0; theGrid[b->block2r * 10 + b->block2c]->lv = 0; theGrid[b->block3r * 10 + b->block3c]->lv = 0; theGrid[b->block4r * 10 + b->block4c]->lv = 0; } void Grid::insertBlocks(Blocks *b){ theGrid[b->block1r * 10 + b->block1c]->blocktype = b->type; theGrid[b->block2r * 10 + b->block2c]->blocktype = b->type; theGrid[b->block3r * 10 + b->block3c]->blocktype = b->type; theGrid[b->block4r * 10 + b->block4c]->blocktype = b->type; theGrid[b->block1r * 10 + b->block1c]->notifyDisplay(*td); theGrid[b->block2r * 10 + b->block2c]->notifyDisplay(*td); theGrid[b->block3r * 10 + b->block3c]->notifyDisplay(*td); theGrid[b->block4r * 10 + b->block4c]->notifyDisplay(*td); theGrid[b->block1r * 10 + b->block1c]->lv = b->level; theGrid[b->block2r * 10 + b->block2c]->lv = b->level; theGrid[b->block3r * 10 + b->block3c]->lv = b->level; theGrid[b->block4r * 10 + b->block4c]->lv = b->level; } bool Grid::isLose(Blocks *b) { if ((theGrid[b->block1r * 10 + b->block1c]->getblocktype() == ' ') & (theGrid[b->block2r * 10 + b->block2c]->getblocktype() == ' ') & (theGrid[b->block3r * 10 + b->block3c]->getblocktype() == ' ') & (theGrid[b->block4r * 10 + b->block4c]->getblocktype() == ' ')) { return false; } return true; } void Grid::drop(Blocks *b){ this->removeBlocks(b); int stopAt; int i = 1; bool done = false; while (!done) { if ((((b->block1r + i) == 17) | ((b->block2r + i) == 17) | ((b->block3r + i) == 17) | ((b->block4r + i) == 17)) & ((theGrid[(b->block1r + i) * 10 + b->block1c]->getblocktype() == ' ') & (theGrid[(b->block2r + i) * 10 + b->block2c]->getblocktype() == ' ') & (theGrid[(b->block3r + i) * 10 + b->block3c]->getblocktype() == ' ') & (theGrid[(b->block4r + i) * 10 + b->block4c]->getblocktype() == ' '))){ i += 1; done = true; } else if ((((b->block1r + i) == 17) | ((b->block2r + i) == 17) | ((b->block3r + i) == 17) | ((b->block4r + i) == 17))){ done = true; } else if ((theGrid[(b->block1r + i) * 10 + b->block1c]->getblocktype() != ' ') | (theGrid[(b->block2r + i) * 10 + b->block2c]->getblocktype() != ' ') | (theGrid[(b->block3r + i) * 10 + b->block3c]->getblocktype() != ' ') | (theGrid[(b->block4r + i) * 10 + b->block4c]->getblocktype() != ' ')){ done = true; } else { i += 1; } } stopAt = i-1; b->drop(stopAt); this->insertBlocks(b); theGrid[b->block1r * 10 + b->block1c]->addCell(theGrid[b->block2r * 10 + b->block2c]); theGrid[b->block1r * 10 + b->block1c]->addCell(theGrid[b->block3r * 10 + b->block3c]); theGrid[b->block1r * 10 + b->block1c]->addCell(theGrid[b->block4r * 10 + b->block4c]); theGrid[b->block2r * 10 + b->block2c]->addCell(theGrid[b->block1r * 10 + b->block1c]); theGrid[b->block2r * 10 + b->block2c]->addCell(theGrid[b->block3r * 10 + b->block3c]); theGrid[b->block2r * 10 + b->block2c]->addCell(theGrid[b->block4r * 10 + b->block4c]); theGrid[b->block3r * 10 + b->block3c]->addCell(theGrid[b->block1r * 10 + b->block1c]); theGrid[b->block3r * 10 + b->block3c]->addCell(theGrid[b->block2r * 10 + b->block2c]); theGrid[b->block3r * 10 + b->block3c]->addCell(theGrid[b->block4r * 10 + b->block4c]); theGrid[b->block4r * 10 + b->block4c]->addCell(theGrid[b->block1r * 10 + b->block1c]); theGrid[b->block4r * 10 + b->block4c]->addCell(theGrid[b->block2r * 10 + b->block2c]); theGrid[b->block4r * 10 + b->block4c]->addCell(theGrid[b->block3r * 10 + b->block3c]); int numOfLine = 0; int lv0 = 0; int lv1 = 0; int lv2 = 0; int lv3 = 0; for (int k = 0; k <= 17; k++){ bool clear = true; for (int i = 0; i <= 9; i++){ if (theGrid[k * 10 + i]->getblocktype() == ' ') { clear = false; } } if (clear) { int num; int level = 0; for (int i = 0; i <= 9; i++){ num = theGrid[k * 10 + i]->getnum(); if (num == 0){ level = theGrid[k * 10 + i]->getlv(); if (level == 0) { lv0 += 1; } if (level == 1) { lv1 += 1; } if (level == 2) { lv2 += 1; } if (level == 3) { lv3 += 1; } } else { theGrid[k * 10 + i]->notifyOtherCells(); for (int j = 0; j < num; j++) { theGrid[k * 10 + i]->restOfTheBlocks[j] = 0; } theGrid[k * 10 + i]->num = 0; } theGrid[k * 10 + i]->blocktype = ' '; theGrid[k * 10 + i]->lv = 0; } numOfLine += 1; Cell **tmp; tmp = new Cell*[9]; for (int i = 0; i <= 9; i++) { tmp[i] = theGrid[k * 10 + i]; } for (int i = k; i > 0; i--) { for (int j = 0; j <= 9; j++) { theGrid[i * 10 + j] = theGrid[(i - 1) * 10 + j]; theGrid[i * 10 + j]->setCoords(i, j, (j * 45 + 2), (i * 45 + 2), 45, 45, &W); } } for (int i = 0; i <= 9; i++) { theGrid[i] = tmp[i]; tmp[i] = 0; theGrid[i]->setCoords(0, i, (i * 45 + 2), (0 * 45 + 2), 45, 45, &W); } delete[] *tmp; } } for (int k = 0; k <= 17; k++){ for (int i = 0; i <= 9; i++) { theGrid[k * 10 + i]->notifyDisplay(*td); } } score = score + ((currentLevel + numOfLine) * (currentLevel + numOfLine)) + lv0 + (lv1 * 4) + (lv2 * 9) + (lv3 * 16); if (score > highscore){ highscore = score; } } void Grid::move(Blocks *b, string s) { this->removeBlocks(b); if (s == "left") { if ((b->block1c <= 0) | (b->block2c <= 0) | (b->block3c <= 0) | (b->block4c <= 0)) { } else if ((theGrid[b->block1r * 10 + b->block1c - 1]->blocktype == ' ') & (theGrid[b->block2r * 10 + b->block2c - 1]->blocktype == ' ') & (theGrid[b->block3r * 10 + b->block3c - 1]->blocktype == ' ') & (theGrid[b->block4r * 10 + b->block4c - 1]->blocktype == ' ')) { b->move("left"); } } else if (s == "right") { if ((b->block1c >= 9) | (b->block2c >= 9) | (b->block3c >= 9) | (b->block4c >= 9)) { } else if ((theGrid[b->block1r * 10 + b->block1c + 1]->blocktype == ' ') & (theGrid[b->block2r * 10 + b->block2c + 1]->blocktype == ' ') & (theGrid[b->block3r * 10 + b->block3c + 1]->blocktype == ' ') & (theGrid[b->block4r * 10 + b->block4c + 1]->blocktype == ' ')) { b->move("right"); } } else if (s == "down") { if ((b->block1r >= 17) | (b->block2r >= 17) | (b->block3r >= 17) | (b->block4r >= 17)) { } else if ((theGrid[(b->block1r + 1) * 10 + b->block1c]->blocktype == ' ') & (theGrid[(b->block2r + 1) * 10 + b->block2c]->blocktype == ' ') & (theGrid[(b->block3r + 1) * 10 + b->block3c]->blocktype == ' ') & (theGrid[(b->block4r + 1) * 10 + b->block4c]->blocktype == ' ')) { b->move("down"); } } this->insertBlocks(b); } void Grid::rotate(Blocks *b, std::string s){ this->removeBlocks(b); if (s == "clockwise") { b->clockwise(); if ((b->block1r <= 17) & (b->block2r <= 17) & (b->block3r <= 17) & (b->block4r <= 17) & (b->block1c <= 9) & (b->block2c <= 9) & (b->block3c <= 9) & (b->block4c <= 9) & (theGrid[(b->block1r) * 10 + b->block1c]->blocktype == ' ') & (theGrid[(b->block2r) * 10 + b->block2c]->blocktype == ' ') & (theGrid[(b->block3r) * 10 + b->block3c]->blocktype == ' ') & (theGrid[(b->block4r) * 10 + b->block4c]->blocktype == ' ') ) { } else { b->counterclockwise(); } } else { b->counterclockwise(); if ((b->block1r <= 17) & (b->block2r <= 17) & (b->block3r <= 17) & (b->block4r <= 17) & (b->block1c <= 9) & (b->block2c <= 9) & (b->block3c <= 9) & (b->block4c <= 9) & (theGrid[(b->block1r) * 10 + b->block1c]->blocktype == ' ') & (theGrid[(b->block2r) * 10 + b->block2c]->blocktype == ' ') & (theGrid[(b->block3r) * 10 + b->block3c]->blocktype == ' ') & (theGrid[(b->block4r) * 10 + b->block4c]->blocktype == ' ') ) { } else { b->clockwise(); } } this->insertBlocks(b); } void Grid::restart() { score = 0; currentLevel = 0; td->restart(); for (int k = 0; k <= 17; k++){ for (int i = 0; i <= 9; i++){ theGrid[k * 10 + i]->reset(); theGrid[k * 10 + i]->setCoords(k, i, (i * 45 + 2), (k * 45 + 2), 45, 45, &W); } } for (int k = 0; k <= 1; k++){ for (int i = 0; i <= 3; i++){ theGrid[k * 10 + i]->reset(); theGrid[k * 10 + i]->setCoords(k, i, (i * 45 + 472), (k * 45 + 22), 45, 45, &W); } } } ostream &operator<< (ostream &out, Grid &g) { if (!(g.textonly)) { for (int k = 0; k <= 17; k++){ for (int i = 0; i <= 9; i++) { g.theGrid[k * 10 + i]->draw(); } } for (int k = 0; k <= 1; k++){ for (int i = 0; i <= 3; i++) { g.next[k * 4 + i]->draw(); } } string l, s, hs; stringstream lss; stringstream sss; stringstream hsss; lss << g.currentLevel; l = lss.str(); sss << g.score; s = sss.str(); hsss << g.highscore; hs = hsss.str(); g.W.fillRectangle(560, 140, 100, 100, Xwindow::White); g.W.drawString(560, 140, l, Xwindow::Black); g.W.drawString(560, 160, s, Xwindow::Black); g.W.drawString(560, 180, hs, Xwindow::Black); } out << "Level: " << g.currentLevel << endl; out << "Score: " << g.score << endl; out << "Hi Score: " << g.highscore << endl; out << "----------" << endl; out << *(g.td) << endl; out << "----------" << endl; out << "Next:" << endl; char display[7]; for (int i = 0; i < 2; i++){ for (int k = 0; k < 4; k++){ display[i * 4 + k] = (g.next[i * 4 + k])->getblocktype(); } } for (int i = 0; i < 2; i++){ for (int k = 0; k < 4; k++){ out << display[i * 4 + k]; } out << endl; } return out; }
28.334988
118
0.523163
kevinli9094
4c71d8f6475c29e56ba7811deaad7ae3556f5256
5,562
cpp
C++
main/solver/Solver.cpp
JLUCPGROUP/csptest
0475c631a48511dd35e63397a74cbdf1388cf495
[ "MIT" ]
null
null
null
main/solver/Solver.cpp
JLUCPGROUP/csptest
0475c631a48511dd35e63397a74cbdf1388cf495
[ "MIT" ]
null
null
null
main/solver/Solver.cpp
JLUCPGROUP/csptest
0475c631a48511dd35e63397a74cbdf1388cf495
[ "MIT" ]
null
null
null
#include "Solver.h" namespace cudacp { VarEvt::VarEvt(Network* m) : size_(m->vars.size()), cur_size_(0) { vars = m->vars; } IntVar* VarEvt::operator[](const int i) const { return vars[i]; } int VarEvt::size() const { return cur_size_; } IntVar* VarEvt::at(const int i) const { return vars[i]; } void VarEvt::push_back(IntVar* v) { vars[cur_size_] = v; ++cur_size_; } void VarEvt::clear() { cur_size_ = 0; } AssignedStack::AssignedStack(Network* m) :gm_(m) { max_size_ = m->vars.size(); //vals_.resize(m->vars.size()); vals_.reserve(m->vars.size()); asnd_.resize(m->vars.size(), false); } void AssignedStack::initial(Network* m) { gm_ = m; max_size_ = m->vars.size(); //vals_.resize(m->vars.size()); vals_.reserve(m->vars.size()); asnd_.resize(m->vars.size(), false); }; void AssignedStack::push(IntVal& v_a) { //vals_[top_] = v_a; //asnd_[v_a.vid()] = v_a.op(); //v_a.v()->assign(v_a.op()); //++top_; vals_.push_back(v_a); asnd_[v_a.vid()] = v_a.op(); v_a.v()->assign(v_a.op()); }; IntVal AssignedStack::pop() { //--top_; //asnd_[vals_[top_].vid()] = false; //vals_[top_].v()->assign(false); //return vals_[top_]; auto val = vals_.back(); vals_.pop_back(); asnd_[val.vid()] = false; val.v()->assign(false); return val; } //IntVal AssignedStack::top() const { return vals_[top_]; }; //int AssignedStack::size() const { return top_; } //int AssignedStack::capacity() const { return max_size_; } //bool AssignedStack::full() const { return top_ == max_size_; } //bool AssignedStack::empty() const { return top_ == 0; } //IntVal AssignedStack::operator[](const int i) const { return vals_[i]; }; //IntVal AssignedStack::at(const int i) const { return vals_[i]; }; //void AssignedStack::clear() { top_ = 0; }; //bool AssignedStack::assiged(const int v) const { return asnd_[v]; } //bool AssignedStack::assiged(const IntVar* v) const { return assiged(v->id()); }; IntVal AssignedStack::top() const { return vals_.back(); } int AssignedStack::size() const { return vals_.size(); } int AssignedStack::capacity() const { return vals_.capacity(); } bool AssignedStack::full() const { return size() == max_size_; } bool AssignedStack::empty() const { return vals_.empty(); } IntVal AssignedStack::operator[](const int i) const { return vals_[i]; } IntVal AssignedStack::at(const int i) const { return vals_[i]; } void AssignedStack::clear() { vals_.clear(); } void AssignedStack::del(const IntVal val) { remove(vals_.begin(), vals_.end(), val); asnd_[val.vid()] = false; } bool AssignedStack::assiged(const int v) const { return asnd_[v]; } bool AssignedStack::assiged(const IntVar* v) const { return assiged(v->id()); } vector<IntVal> AssignedStack::vals() const { return vals_; } ostream & operator<<(ostream & os, AssignedStack & I) { for (int i = 0; i < I.size(); ++i) os << I[i] << " "; return os; } ostream & operator<<(ostream & os, AssignedStack * I) { for (int i = 0; i < I->size(); ++i) os << I->at(i) << " "; return os; } void AssignedStack::update_model_assigned() { for (auto val : vals_) val.v()->assign(true); } /////////////////////////////////////////////////////////////////////// DeleteExplanation::DeleteExplanation(Network* m) : m_(m) { val_array_.resize(m_->vars.size(), vector<vector<IntVal>>(m_->max_domain_size())); } void DeleteExplanation::initial(Network* m) { m_ = m; val_array_.resize(m_->vars.size(), vector<vector<IntVal>>(m_->max_domain_size())); } vector<IntVal>& DeleteExplanation::operator[](const IntVal val) { return val_array_[val.vid()][val.a()]; } /////////////////////////////////////////////////////////////////////// arc_que::arc_que(const int cons_size, const int max_arity) : arity_(max_arity), m_size_(max_arity*cons_size + 1), m_front_(0), m_rear_(0) { m_data_.resize(m_size_); vid_set_.resize(m_size_); } void arc_que::MakeQue(const size_t cons_size, const size_t max_arity) { arity_ = max_arity; m_size_ = max_arity*cons_size + 1; m_front_ = 0; m_rear_ = 0; m_data_.resize(m_size_); vid_set_.resize(m_size_); } bool arc_que::empty() const { return m_front_ == m_rear_; } bool arc_que::full() const { return m_front_ == (m_rear_ + 1) % m_size_; } bool arc_que::push(arc& ele) throw(std::bad_exception) { if (full()) throw std::bad_exception(); if (have(ele)) return false; m_data_[m_rear_] = ele; m_rear_ = (m_rear_ + 1) % m_size_; have(ele) = 1; return true; } arc arc_que::pop() throw(std::bad_exception) { if (empty()) throw std::bad_exception(); arc tmp = m_data_[m_front_]; m_front_ = (m_front_ + 1) % m_size_; have(tmp) = 0; return tmp; } ///////////////////////////////////////////////////////////////////////// bool var_que::have(IntVar* v) { return vid_set_[v->id()]; } bool var_que::empty() const { return m_front_ == m_rear_; } void var_que::initial(const int size) { max_size_ = size + 1; m_data_.resize(max_size_, nullptr); vid_set_.resize(max_size_, 0); m_front_ = 0; m_rear_ = 0; size_ = 0; } bool var_que::full() const { return m_front_ == (m_rear_ + 1) % max_size_; } void var_que::push(IntVar* v) { if (have(v)) return; m_data_[m_rear_] = v; m_rear_ = (m_rear_ + 1) % max_size_; vid_set_[v->id()] = 1; ++size_; } IntVar* var_que::pop() { IntVar* tmp = m_data_[m_front_]; m_front_ = (m_front_ + 1) % max_size_; vid_set_[tmp->id()] = 0; --size_; return tmp; } void var_que::clear() { m_front_ = 0; m_rear_ = 0; size_ = 0; vid_set_.assign(vid_set_.size(), 0); } int var_que::max_size() const { return max_size_; } int var_que::size() const { return size_; } }
23.871245
83
0.634304
JLUCPGROUP
4c72a3bc63829c57f6812d99dc1fd8563948190e
485
hpp
C++
plugins/opengl/include/sge/opengl/vf/color_formats.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
2
2016-01-27T13:18:14.000Z
2018-05-11T01:11:32.000Z
plugins/opengl/include/sge/opengl/vf/color_formats.hpp
cpreh/spacegameengine
313a1c34160b42a5135f8223ffaa3a31bc075a01
[ "BSL-1.0" ]
null
null
null
plugins/opengl/include/sge/opengl/vf/color_formats.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_OPENGL_VF_COLOR_FORMATS_HPP_INCLUDED #define SGE_OPENGL_VF_COLOR_FORMATS_HPP_INCLUDED #include <sge/renderer/vf/dynamic/color_format_vector.hpp> namespace sge::opengl::vf { sge::renderer::vf::dynamic::color_format_vector color_formats(); } #endif
25.526316
64
0.756701
cpreh
dbc76dbf57ea7b32e76bafbe2abf52a298a70c8c
49,013
cpp
C++
src/DakotaInterface.cpp
jnnccc/Dakota-orb
96488e723be9c67f0f85be8162b7af52c312b770
[ "MIT" ]
null
null
null
src/DakotaInterface.cpp
jnnccc/Dakota-orb
96488e723be9c67f0f85be8162b7af52c312b770
[ "MIT" ]
null
null
null
src/DakotaInterface.cpp
jnnccc/Dakota-orb
96488e723be9c67f0f85be8162b7af52c312b770
[ "MIT" ]
null
null
null
/* _______________________________________________________________________ DAKOTA: Design Analysis Kit for Optimization and Terascale Applications Copyright 2014 Sandia Corporation. This software is distributed under the GNU Lesser General Public License. For more information, see the README file in the top Dakota directory. _______________________________________________________________________ */ //- Class: Interface //- Description: Class implementation for abstract interface base class //- Owner: Michael Eldred #include "DakotaInterface.hpp" #include "ProblemDescDB.hpp" #include "DakotaVariables.hpp" #include "SysCallApplicInterface.hpp" #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_UNISTD_H) #include "ForkApplicInterface.hpp" #elif defined(_WIN32) // or _MSC_VER (native MSVS compilers) #include "SpawnApplicInterface.hpp" #endif // HAVE_SYS_WAIT_H, HAVE_UNISTD_H // Direct interfaces #ifdef DAKOTA_GRID #include "GridApplicInterface.hpp" #endif // DAKOTA_GRID #ifdef DAKOTA_MATLAB #include "MatlabInterface.hpp" #endif // DAKOTA_MATLAB #ifdef DAKOTA_PYTHON #include "PythonInterface.hpp" #endif // DAKOTA_PYTHON #ifdef DAKOTA_SCILAB #include "ScilabInterface.hpp" #endif // DAKOTA_SCILAB #include "TestDriverInterface.hpp" #include "ApproximationInterface.hpp" #ifdef HAVE_AMPL #undef NO // avoid name collision from UTILIB #include "external/ampl/asl.h" #endif // HAVE_AMPL //#define DEBUG //#define REFCOUNT_DEBUG namespace Dakota { /** This constructor is the one which must build the base class data for all inherited interfaces. get_interface() instantiates a derived class letter and the derived constructor selects this base class constructor in its initialization list (to avoid the recursion of the base class constructor calling get_interface() again). Since this is the letter and the letter IS the representation, interfaceRep is set to NULL (an uninitialized pointer causes problems in ~Interface). */ Interface::Interface(BaseConstructor, const ProblemDescDB& problem_db): interfaceType(problem_db.get_ushort("interface.type")), interfaceId(problem_db.get_string("interface.id")), algebraicMappings(false), coreMappings(true), outputLevel(problem_db.get_short("method.output")), currEvalId(0), fineGrainEvalCounters(outputLevel > NORMAL_OUTPUT), evalIdCntr(0), newEvalIdCntr(0), evalIdRefPt(0), newEvalIdRefPt(0), multiProcEvalFlag(false), ieDedMasterFlag(false), // See base constructor in DakotaIterator.cpp for full discussion of output // verbosity. Interfaces support the full granularity in verbosity. appendIfaceId(true), interfaceRep(NULL), referenceCount(1), asl(NULL) { #ifdef DEBUG outputLevel = DEBUG_OUTPUT; #endif // DEBUG // Process the algebraic_mappings file (an AMPL .nl file) to get the number // of variables/responses (currently, the tags are converted to index arrays // at evaluation time, using the passed vars and response). // TO DO: parallel bcast of data or very proc reads file? const String& ampl_file_name = problem_db.get_string("interface.algebraic_mappings"); if (!ampl_file_name.empty()) { #ifdef HAVE_AMPL algebraicMappings = true; bool hess_flag = (problem_db.get_string("responses.hessian_type") == "analytic"); asl = (hess_flag) ? ASL_alloc(ASL_read_pfgh) : ASL_alloc(ASL_read_fg); // allow user input of either stub or stub.nl String stub = (strends(ampl_file_name, ".nl")) ? String(ampl_file_name, 0, ampl_file_name.size() - 3) : ampl_file_name; //std::ifstream ampl_nl(ampl_file_name); fint stub_str_len = stub.size(); // BMA NOTE: casting away the constness as done historically in DakotaString char* nonconst_stub = (char*) stub.c_str(); FILE* ampl_nl = jac0dim(nonconst_stub, stub_str_len); if (!ampl_nl) { Cerr << "\nError: failure opening " << ampl_file_name << std::endl; abort_handler(IO_ERROR); } int rtn = (hess_flag) ? pfgh_read(ampl_nl, ASL_return_read_err) : fg_read(ampl_nl, ASL_return_read_err); if (rtn) { Cerr << "\nError: AMPL processing problem with " << ampl_file_name << std::endl; abort_handler(IO_ERROR); } // extract input/output tag lists String row = stub + ".row", col = stub + ".col", ampl_tag; std::ifstream ampl_col(col.c_str()); if (!ampl_col) { Cerr << "\nError: failure opening " << col << std::endl; abort_handler(IO_ERROR); } algebraicVarTags.resize(n_var); for (size_t i=0; i<n_var; i++) { std::getline(ampl_col, ampl_tag); if (ampl_col.good()) algebraicVarTags[i] = ampl_tag; else { Cerr << "\nError: failure reading AMPL col file " << col << std::endl; abort_handler(IO_ERROR); } } std::ifstream ampl_row(row.c_str()); if (!ampl_row) { Cerr << "\nError: failure opening " << row << std::endl; abort_handler(IO_ERROR); } algebraicFnTags.resize(n_obj+n_con); algebraicFnTypes.resize(n_obj+n_con); algebraicConstraintWeights.resize(n_con); for (size_t i=0; i<n_obj+n_con; i++) { getline(ampl_row, ampl_tag); if (ampl_row.good()) { algebraicFnTags[i] = ampl_tag; algebraicFnTypes[i] = algebraic_function_type(ampl_tag); } else { Cerr << "\nError: failure reading AMPL row file " << row << std::endl; abort_handler(IO_ERROR); } } #ifdef DEBUG Cout << ">>>>> algebraicVarTags =\n" << algebraicVarTags << "\n>>>>> algebraicFnTags =\n" << algebraicFnTags << "\n>>>>> algebraicFnTypes =\n" << algebraicFnTypes << std::endl; #endif #else Cerr << "\nError: algebraic_mappings not supported without the AMPL solver " << "library provided with the Acro package." << std::endl; abort_handler(-1); #endif // HAVE_AMPL } #ifdef REFCOUNT_DEBUG Cout << "Interface::Interface(BaseConstructor, ProblemDescDB&) called to " << "build base class data for letter object." << std::endl; #endif } Interface::Interface(NoDBBaseConstructor, size_t num_fns, short output_level): interfaceId("NO_SPECIFICATION"), algebraicMappings(false), coreMappings(true), outputLevel(output_level), currEvalId(0), fineGrainEvalCounters(outputLevel > NORMAL_OUTPUT), evalIdCntr(0), newEvalIdCntr(0), evalIdRefPt(0), newEvalIdRefPt(0), multiProcEvalFlag(false), ieDedMasterFlag(false), appendIfaceId(true), interfaceRep(NULL), referenceCount(1) { #ifdef DEBUG outputLevel = DEBUG_OUTPUT; #endif // DEBUG #ifdef REFCOUNT_DEBUG Cout << "Interface::Interface(NoDBBaseConstructor) called to build base " << "class data for letter object." << std::endl; #endif } /** used in Model envelope class instantiations */ Interface::Interface(): interfaceRep(NULL), referenceCount(1) { } /** Used in Model instantiation to build the envelope. This constructor only needs to extract enough data to properly execute get_interface, since Interface::Interface(BaseConstructor, problem_db) builds the actual base class data inherited by the derived interfaces. */ Interface::Interface(ProblemDescDB& problem_db): referenceCount(1) { #ifdef REFCOUNT_DEBUG Cout << "Interface::Interface(ProblemDescDB&) called to instantiate envelope." << std::endl; #endif // Set the rep pointer to the appropriate interface type interfaceRep = get_interface(problem_db); if (!interfaceRep) // bad type or insufficient memory abort_handler(-1); } /** used only by the envelope constructor to initialize interfaceRep to the appropriate derived type. */ Interface* Interface::get_interface(ProblemDescDB& problem_db) { const unsigned short interface_type = problem_db.get_ushort("interface.type"); #ifdef REFCOUNT_DEBUG Cout << "Envelope instantiating letter: Getting interface " << interface_enum_to_string(interface_type) << std::endl; #endif // In the case where a derived interface type has been selected for managing // analysis_drivers, then this determines the letter instantiation and any // algebraic mappings are overlayed by ApplicationInterface. const String& algebraic_map_file = problem_db.get_string("interface.algebraic_mappings"); if (interface_type == SYSTEM_INTERFACE) return new SysCallApplicInterface(problem_db); else if (interface_type == FORK_INTERFACE) { #if defined(HAVE_SYS_WAIT_H) && defined(HAVE_UNISTD_H) // includes CYGWIN/MINGW return new ForkApplicInterface(problem_db); #elif defined(_WIN32) // or _MSC_VER (native MSVS compilers) return new SpawnApplicInterface(problem_db); #else Cerr << "Fork interface requested, but not enabled in this DAKOTA " << "executable." << std::endl; return NULL; #endif } else if (interface_type == TEST_INTERFACE) return new TestDriverInterface(problem_db); // Note: in the case of a plug-in direct interface, this object gets replaced // using Interface::assign_rep(). Error checking in DirectApplicInterface:: // derived_map_ac() should catch if this replacement fails to occur properly. #ifdef DAKOTA_GRID else if (interface_type == GRID_INTERFACE) return new GridApplicInterface(problem_db); #endif else if (interface_type == MATLAB_INTERFACE) { #ifdef DAKOTA_MATLAB return new MatlabInterface(problem_db); #else Cerr << "Direct Matlab interface requested, but not enabled in this " << "DAKOTA executable." << std::endl; return NULL; #endif } else if (interface_type == PYTHON_INTERFACE) { #ifdef DAKOTA_PYTHON return new PythonInterface(problem_db); #else Cerr << "Direct Python interface requested, but not enabled in this " << "DAKOTA executable." << std::endl; return NULL; #endif } else if (interface_type == SCILAB_INTERFACE) { #ifdef DAKOTA_SCILAB return new ScilabInterface(problem_db); #else Cerr << "Direct Scilab interface requested, but not enabled in this " << "DAKOTA executable." << std::endl; return NULL; #endif } // Should not be needed since ApproximationInterface is plugged-in from // DataFitSurrModel using Interface::assign_rep(). //else if (interface_type == APPROX_INTERFACE) // return new ApproximationInterface(problem_db, num_acv, num_fns); // In the case where only algebraic mappings are used, then no derived map // functionality is needed and ApplicationInterface is used for the letter. else if (!algebraic_map_file.empty()) { #ifdef DEBUG Cout << ">>>>> new ApplicationInterface: " << algebraic_map_file << std::endl; #endif // DEBUG return new ApplicationInterface(problem_db); } // If the interface type is empty (e.g., from default DataInterface creation // in ProblemDescDB::check_input()), then ApplicationInterface is the letter. else if (interface_type == DEFAULT_INTERFACE) { Cerr << "Warning: empty interface type in Interface::get_interface()." << std::endl; return new ApplicationInterface(problem_db); } else { Cerr << "Invalid interface: " << interface_enum_to_string(interface_type) << std::endl; return NULL; } } /** Copy constructor manages sharing of interfaceRep and incrementing of referenceCount. */ Interface::Interface(const Interface& interface_in) { // Increment new (no old to decrement) interfaceRep = interface_in.interfaceRep; if (interfaceRep) // Check for an assignment of NULL ++interfaceRep->referenceCount; #ifdef REFCOUNT_DEBUG Cout << "Interface::Interface(Interface&)" << std::endl; if (interfaceRep) Cout << "interfaceRep referenceCount = " << interfaceRep->referenceCount << std::endl; #endif } /** Assignment operator decrements referenceCount for old interfaceRep, assigns new interfaceRep, and increments referenceCount for new interfaceRep. */ Interface Interface::operator=(const Interface& interface_in) { if (interfaceRep != interface_in.interfaceRep) { // normal case: old != new // Decrement old if (interfaceRep) // Check for NULL if ( --interfaceRep->referenceCount == 0 ) delete interfaceRep; // Assign and increment new interfaceRep = interface_in.interfaceRep; if (interfaceRep) // Check for NULL ++interfaceRep->referenceCount; } // else if assigning same rep, then do nothing since referenceCount // should already be correct #ifdef REFCOUNT_DEBUG Cout << "Interface::operator=(Interface&)" << std::endl; if (interfaceRep) Cout << "interfaceRep referenceCount = " << interfaceRep->referenceCount << std::endl; #endif return *this; // calls copy constructor since returned by value } /** Destructor decrements referenceCount and only deletes interfaceRep if referenceCount is zero. */ Interface::~Interface() { // Check for NULL pointer if (interfaceRep) { --interfaceRep->referenceCount; #ifdef REFCOUNT_DEBUG Cout << "interfaceRep referenceCount decremented to " << interfaceRep->referenceCount << std::endl; #endif if (interfaceRep->referenceCount == 0) { #ifdef REFCOUNT_DEBUG Cout << "deleting interfaceRep" << std::endl; #endif delete interfaceRep; } } } /** Similar to the assignment operator, the assign_rep() function decrements referenceCount for the old interfaceRep and assigns the new interfaceRep. It is different in that it is used for publishing derived class letters to existing envelopes, as opposed to sharing representations among multiple envelopes (in particular, assign_rep is passed a letter object and operator= is passed an envelope object). Letter assignment supports two models as governed by ref_count_incr: \li ref_count_incr = true (default): the incoming letter belongs to another envelope. In this case, increment the reference count in the normal manner so that deallocation of the letter is handled properly. \li ref_count_incr = false: the incoming letter is instantiated on the fly and has no envelope. This case is modeled after get_interface(): a letter is dynamically allocated using new and passed into assign_rep, the letter's reference count is not incremented, and the letter is not remotely deleted (its memory management is passed over to the envelope). */ void Interface::assign_rep(Interface* interface_rep, bool ref_count_incr) { if (interfaceRep == interface_rep) { // if ref_count_incr = true (rep from another envelope), do nothing as // referenceCount should already be correct (see also operator= logic). // if ref_count_incr = false (rep from on the fly), then this is an error. if (!ref_count_incr) { Cerr << "Error: duplicated interface_rep pointer assignment without " << "reference count increment in Interface::assign_rep()." << std::endl; abort_handler(-1); } } else { // normal case: old != new // Decrement old if (interfaceRep) // Check for NULL if ( --interfaceRep->referenceCount == 0 ) delete interfaceRep; // Assign new interfaceRep = interface_rep; // Increment new if (interfaceRep && ref_count_incr) // Check for NULL & honor ref_count_incr interfaceRep->referenceCount++; } #ifdef REFCOUNT_DEBUG Cout << "Interface::assign_rep(Interface*)" << std::endl; if (interfaceRep) Cout << "interfaceRep referenceCount = " << interfaceRep->referenceCount << std::endl; #endif } void Interface::fine_grained_evaluation_counters(size_t num_fns) { if (interfaceRep) // envelope fwd to letter interfaceRep->fine_grained_evaluation_counters(num_fns); else if (!fineGrainEvalCounters) { // letter (not virtual) init_evaluation_counters(num_fns); fineGrainEvalCounters = true; } } void Interface::init_evaluation_counters(size_t num_fns) { if (interfaceRep) // envelope fwd to letter interfaceRep->init_evaluation_counters(num_fns); else { // letter (not virtual) //if (fnLabels.empty()) { // fnLabels.resize(num_fns); // build_labels(fnLabels, "response_fn_"); // generic resp fn labels //} if (fnValCounter.size() != num_fns) { fnValCounter.assign(num_fns, 0); fnGradCounter.assign(num_fns, 0); fnHessCounter.assign(num_fns, 0); newFnValCounter.assign(num_fns, 0); newFnGradCounter.assign(num_fns, 0); newFnHessCounter.assign(num_fns, 0); fnValRefPt.assign(num_fns, 0); fnGradRefPt.assign(num_fns, 0); fnHessRefPt.assign(num_fns, 0); newFnValRefPt.assign(num_fns, 0); newFnGradRefPt.assign(num_fns, 0); newFnHessRefPt.assign(num_fns, 0); } } } void Interface::set_evaluation_reference() { if (interfaceRep) // envelope fwd to letter interfaceRep->set_evaluation_reference(); else { // letter (not virtual) evalIdRefPt = evalIdCntr; newEvalIdRefPt = newEvalIdCntr; if (fineGrainEvalCounters) { size_t i, num_fns = fnValCounter.size(); for (i=0; i<num_fns; i++) { fnValRefPt[i] = fnValCounter[i]; newFnValRefPt[i] = newFnValCounter[i]; fnGradRefPt[i] = fnGradCounter[i]; newFnGradRefPt[i] = newFnGradCounter[i]; fnHessRefPt[i] = fnHessCounter[i]; newFnHessRefPt[i] = newFnHessCounter[i]; } } } } void Interface:: print_evaluation_summary(std::ostream& s, bool minimal_header, bool relative_count) const { if (interfaceRep) // envelope fwd to letter interfaceRep->print_evaluation_summary(s, minimal_header, relative_count); else { // letter (not virtual) // standard evaluation summary if (minimal_header) { if (interfaceId.empty()) s << " Interface evaluations"; else s << " " << interfaceId << " evaluations"; } else { s << "<<<<< Function evaluation summary"; if (!interfaceId.empty()) s << " (" << interfaceId << ')'; } int fn_evals = (relative_count) ? evalIdCntr - evalIdRefPt : evalIdCntr; int new_fn_evals = (relative_count) ? newEvalIdCntr - newEvalIdRefPt : newEvalIdCntr; s << ": " << fn_evals << " total (" << new_fn_evals << " new, " << fn_evals - new_fn_evals << " duplicate)\n"; // detailed evaluation summary if (fineGrainEvalCounters) { size_t i, num_fns = std::min(fnValCounter.size(), fnLabels.size()); for (i=0; i<num_fns; i++) { int t_v = (relative_count) ? fnValCounter[i] - fnValRefPt[i] : fnValCounter[i]; int n_v = (relative_count) ? newFnValCounter[i] - newFnValRefPt[i] : newFnValCounter[i]; int t_g = (relative_count) ? fnGradCounter[i] - fnGradRefPt[i] : fnGradCounter[i]; int n_g = (relative_count) ? newFnGradCounter[i] - newFnGradRefPt[i] : newFnGradCounter[i]; int t_h = (relative_count) ? fnHessCounter[i] - fnHessRefPt[i] : fnHessCounter[i]; int n_h = (relative_count) ? newFnHessCounter[i] - newFnHessRefPt[i] : newFnHessCounter[i]; s << std::setw(15) << fnLabels[i] << ": " << t_v << " val (" << n_v << " n, " << t_v - n_v << " d), " << t_g << " grad (" << n_g << " n, " << t_g - n_g << " d), " << t_h << " Hess (" << n_h << " n, " << t_h - n_h << " d)\n"; } } } } /// default implementation just sets the list of eval ID tags; /// derived classes containing additional models or interfaces should /// override (currently no use cases) void Interface:: eval_tag_prefix(const String& eval_id_str, bool append_iface_id) { if (interfaceRep) interfaceRep->eval_tag_prefix(eval_id_str, append_iface_id); else { evalTagPrefix = eval_id_str; appendIfaceId = append_iface_id; } } void Interface::map(const Variables& vars, const ActiveSet& set, Response& response, bool asynch_flag) { if (interfaceRep) // envelope fwd to letter interfaceRep->map(vars, set, response, asynch_flag); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual map function.\n" << "No default map defined at Interface base class." << std::endl; abort_handler(-1); } } void Interface:: init_algebraic_mappings(const Variables& vars, const Response& response) { size_t i, num_alg_vars = algebraicVarTags.size(), num_alg_fns = algebraicFnTags.size(); algebraicACVIndices.resize(num_alg_vars); algebraicACVIds.resize(num_alg_vars); StringMultiArrayConstView acv_labels = vars.all_continuous_variable_labels(); SizetMultiArrayConstView acv_ids = vars.all_continuous_variable_ids(); for (i=0; i<num_alg_vars; ++i) { // Note: variable mappings only support continuous variables. // discrete variables are not directly supported by ASL interface. size_t acv_index = find_index(acv_labels, algebraicVarTags[i]); //size_t adv_index = find_index(adv_labels, algebraicVarTags[i]); if (acv_index == _NPOS) { // && adv_index == _NPOS) { Cerr << "\nError: AMPL column label " << algebraicVarTags[i] << " does " <<"not exist in DAKOTA continuous variable descriptors.\n" << std::endl; abort_handler(INTERFACE_ERROR); } else { algebraicACVIndices[i] = acv_index; //algebraicADVIndices[i] = adv_index; algebraicACVIds[i] = acv_ids[acv_index]; } } algebraicFnIndices.resize(num_alg_fns); const StringArray& fn_labels = response.function_labels(); for (size_t i=0; i<num_alg_fns; ++i) { size_t fn_index = Pecos::find_index(fn_labels, algebraicFnTags[i]); if (fn_index == _NPOS) { Cerr << "\nError: AMPL row label " << algebraicFnTags[i] << " does not " <<"exist in DAKOTA response descriptors.\n" << std::endl; abort_handler(INTERFACE_ERROR); } else algebraicFnIndices[i] = fn_index; } } void Interface:: asv_mapping(const ActiveSet& total_set, ActiveSet& algebraic_set, ActiveSet& core_set) { const ShortArray& total_asv = total_set.request_vector(); const SizetArray& total_dvv = total_set.derivative_vector(); // algebraic_asv/dvv: // the algebraic active set is defined over reduced algebraic function // and variable spaces, rather than the original spaces. This simplifies // algebraic_mappings() and allows direct copies of data from AMPL. size_t i, num_alg_fns = algebraicFnTags.size(), num_alg_vars = algebraicVarTags.size(); ShortArray algebraic_asv(num_alg_fns); SizetArray algebraic_dvv(num_alg_vars); for (i=0; i<num_alg_fns; i++) // map total_asv to algebraic_asv algebraic_asv[i] = total_asv[algebraicFnIndices[i]]; algebraic_set.request_vector(algebraic_asv); algebraic_set.derivative_vector(algebraic_dvv); algebraic_set.derivative_start_value(1); // core_asv/dvv: // for now, core_asv is the same as total_asv, since there is no mechanism // yet to determine if the algebraic_mapping portion is the complete // definition (for which core_asv requests could be turned off). core_set.request_vector(total_asv); core_set.derivative_vector(total_dvv); } void Interface:: asv_mapping(const ActiveSet& algebraic_set, ActiveSet& total_set) { const ShortArray& algebraic_asv = algebraic_set.request_vector(); size_t i, num_alg_fns = algebraicFnTags.size(); for (i=0; i<num_alg_fns; i++) // map algebraic_asv to total_asv total_set.request_value(algebraic_asv[i], algebraicFnIndices[i]); } void Interface:: algebraic_mappings(const Variables& vars, const ActiveSet& algebraic_set, Response& algebraic_response) { #ifdef HAVE_AMPL // make sure cur_ASL is pointing to the ASL of this interface // this is important for problems with multiple interfaces set_cur_ASL(asl); const ShortArray& algebraic_asv = algebraic_set.request_vector(); const SizetArray& algebraic_dvv = algebraic_set.derivative_vector(); size_t i, num_alg_fns = algebraic_asv.size(), num_alg_vars = algebraic_dvv.size(); bool grad_flag = false, hess_flag = false; for (i=0; i<num_alg_fns; ++i) { if (algebraic_asv[i] & 2) grad_flag = true; if (algebraic_asv[i] & 4) hess_flag = true; } // dak_a_c_vars (DAKOTA space) -> nl_vars (reduced AMPL space) const RealVector& dak_a_c_vars = vars.all_continuous_variables(); //IntVector dak_a_d_vars = vars.all_discrete_variables(); Real* nl_vars = new Real [num_alg_vars]; for (i=0; i<num_alg_vars; i++) nl_vars[i] = dak_a_c_vars[algebraicACVIndices[i]]; // nl_vars -> algebraic_response algebraic_response.reset_inactive(); // zero inactive data Real fn_val; RealVector fn_grad; RealSymMatrix fn_hess; fint err = 0; for (i=0; i<num_alg_fns; i++) { // nl_vars -> response fns via AMPL if (algebraic_asv[i] & 1) { if (algebraicFnTypes[i] > 0) fn_val = objval(algebraicFnTypes[i]-1, nl_vars, &err); else fn_val = conival(-1-algebraicFnTypes[i], nl_vars, &err); if (err) { Cerr << "\nError: AMPL processing failure in objval().\n" << std::endl; abort_handler(INTERFACE_ERROR); } algebraic_response.function_value(fn_val, i); } // nl_vars -> response grads via AMPL if (algebraic_asv[i] & 6) { // need grad for Hessian fn_grad = algebraic_response.function_gradient_view(i); if (algebraicFnTypes[i] > 0) objgrd(algebraicFnTypes[i]-1, nl_vars, fn_grad.values(), &err); else congrd(-1-algebraicFnTypes[i], nl_vars, fn_grad.values(), &err); if (err) { Cerr << "\nError: AMPL processing failure in objgrad().\n" << std::endl; abort_handler(INTERFACE_ERROR); } } // nl_vars -> response Hessians via AMPL if (algebraic_asv[i] & 4) { fn_hess = algebraic_response.function_hessian_view(i); // the fullhess calls must follow corresp call to objgrad/congrad if (algebraicFnTypes[i] > 0) fullhes(fn_hess.values(), num_alg_vars, algebraicFnTypes[i]-1, NULL, NULL); else { algebraicConstraintWeights.assign(algebraicConstraintWeights.size(), 0); algebraicConstraintWeights[-1-algebraicFnTypes[i]] = 1; fullhes(fn_hess.values(), num_alg_vars, num_alg_vars, NULL, &algebraicConstraintWeights[0]); } } } delete [] nl_vars; algebraic_response.function_labels(algebraicFnTags); #ifdef DEBUG Cout << ">>>>> algebraic_response.fn_labels\n" << algebraic_response.function_labels() << std::endl; #endif // DEBUG if (outputLevel > NORMAL_OUTPUT) Cout << "Algebraic mapping applied.\n"; #endif // HAVE_AMPL } /** This function will get invoked even when only algebraic mappings are active (no core mappings from derived_map), since the AMPL algebraic_response may be ordered differently from the total_response. In this case, the core_response object is unused. */ void Interface:: response_mapping(const Response& algebraic_response, const Response& core_response, Response& total_response) { const ShortArray& total_asv = total_response.active_set_request_vector(); const SizetArray& total_dvv = total_response.active_set_derivative_vector(); size_t i, j, k, num_total_fns = total_asv.size(), num_total_vars = total_dvv.size(); bool grad_flag = false, hess_flag = false; for (i=0; i<num_total_fns; ++i) { if (total_asv[i] & 2) grad_flag = true; if (total_asv[i] & 4) hess_flag = true; } // core_response contributions to total_response: if (coreMappings) { total_response.reset_inactive(); const ShortArray& core_asv = core_response.active_set_request_vector(); size_t num_core_fns = core_asv.size(); for (i=0; i<num_core_fns; ++i) { if (core_asv[i] & 1) total_response.function_value(core_response.function_value(i), i); if (core_asv[i] & 2) total_response.function_gradient( core_response.function_gradient_view(i), i); if (core_asv[i] & 4) total_response.function_hessian(core_response.function_hessian(i), i); } } else { // zero all response data before adding algebraic data to it total_response.reset(); } // algebraic_response contributions to total_response: const ShortArray& algebraic_asv = algebraic_response.active_set_request_vector(); size_t num_alg_fns = algebraic_asv.size(), num_alg_vars = algebraic_response.active_set_derivative_vector().size(); if (num_alg_fns > num_total_fns) { Cerr << "Error: response size mismatch in Interface::response_mapping()." << std::endl; abort_handler(-1); } if ( (grad_flag || hess_flag) && num_alg_vars > num_total_vars) { Cerr << "Error: derivative variables size mismatch in Interface::" << "response_mapping()." << std::endl; abort_handler(-1); } SizetArray algebraic_dvv_indices; if (grad_flag || hess_flag) { algebraic_dvv_indices.resize(num_alg_vars); using Pecos::find_index; for (i=0; i<num_alg_vars; ++i) algebraic_dvv_indices[i] = find_index(total_dvv, algebraicACVIds[i]); // Note: _NPOS return is handled below } // augment total_response const RealVector& algebraic_fn_vals = algebraic_response.function_values(); const RealMatrix& algebraic_fn_grads = algebraic_response.function_gradients(); const RealSymMatrixArray& algebraic_fn_hessians = algebraic_response.function_hessians(); RealVector total_fn_vals = total_response.function_values_view(); for (i=0; i<num_alg_fns; ++i) { size_t fn_index = algebraicFnIndices[i]; if (algebraic_asv[i] & 1) total_fn_vals[fn_index] += algebraic_fn_vals[i]; if (algebraic_asv[i] & 2) { const Real* algebraic_fn_grad = algebraic_fn_grads[i]; RealVector total_fn_grad = total_response.function_gradient_view(fn_index); for (j=0; j<num_alg_vars; j++) { size_t dvv_index = algebraic_dvv_indices[j]; if (dvv_index != _NPOS) total_fn_grad[dvv_index] += algebraic_fn_grad[j]; } } if (algebraic_asv[i] & 4) { const RealSymMatrix& algebraic_fn_hess = algebraic_fn_hessians[i]; RealSymMatrix total_fn_hess = total_response.function_hessian_view(fn_index); for (j=0; j<num_alg_vars; ++j) { size_t dvv_index_j = algebraic_dvv_indices[j]; if (dvv_index_j != _NPOS) { for (k=0; k<=j; ++k) { size_t dvv_index_k = algebraic_dvv_indices[k]; if (dvv_index_k != _NPOS) total_fn_hess(dvv_index_j,dvv_index_k) += algebraic_fn_hess(j,k); } } } } } // output response sets: if (outputLevel == DEBUG_OUTPUT) { if (coreMappings) Cout << "core_response:\n" << core_response; Cout << "algebraic_response:\n" << algebraic_response << "total_response:\n" << total_response << '\n'; } } String Interface::final_eval_id_tag(int iface_eval_id) { if (interfaceRep) return interfaceRep->final_eval_id_tag(iface_eval_id); if (appendIfaceId) return evalTagPrefix + "." + boost::lexical_cast<std::string>(iface_eval_id); return evalTagPrefix; } int Interface::algebraic_function_type(String functionTag) { #ifdef HAVE_AMPL int i; for (i=0; i<n_obj; i++) if (strcontains(functionTag, obj_name(i))) return i+1; for (i=0; i<n_con; i++) if (strcontains(functionTag, con_name(i))) return -(i+1); Cerr << "Error: No function type available for \'" << functionTag << "\' " << "via algebraic_mappings interface." << std::endl; abort_handler(INTERFACE_ERROR); #else return 0; #endif // HAVE_AMPL } const IntResponseMap& Interface::synchronize() { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual synchronize() " << "function.\nNo default defined at Interface base class." << std::endl; abort_handler(-1); } return interfaceRep->synchronize(); } const IntResponseMap& Interface::synchronize_nowait() { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual synchronize_nowait" << "() function.\nNo default defined at Interface base class." << std::endl; abort_handler(-1); } return interfaceRep->synchronize_nowait(); } void Interface::cache_unmatched_response(int raw_id) { if (interfaceRep) // envelope fwd to letter interfaceRep->cache_unmatched_response(raw_id); else { // base definition; not virtual IntRespMIter rr_it = rawResponseMap.find(raw_id); if (rr_it != rawResponseMap.end()) { cachedResponseMap.insert(*rr_it); rawResponseMap.erase(rr_it); } } } void Interface::serve_evaluations() { if (interfaceRep) // envelope fwd to letter interfaceRep->serve_evaluations(); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual serve_evaluations " << "function.\nNo default serve_evaluations defined at Interface" << " base class." << std::endl; abort_handler(-1); } } void Interface::stop_evaluation_servers() { if (interfaceRep) // envelope fwd to letter interfaceRep->stop_evaluation_servers(); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual stop_evaluation_" << "servers fn.\nNo default stop_evaluation_servers defined at " << "Interface base class." << std::endl; abort_handler(-1); } } void Interface::init_communicators(const IntArray& message_lengths, int max_eval_concurrency) { if (interfaceRep) // envelope fwd to letter interfaceRep->init_communicators(message_lengths, max_eval_concurrency); else { // letter lacking redefinition of virtual fn. // ApproximationInterfaces: do nothing } } void Interface::set_communicators(const IntArray& message_lengths, int max_eval_concurrency) { if (interfaceRep) // envelope fwd to letter interfaceRep->set_communicators(message_lengths, max_eval_concurrency); else { // letter lacking redefinition of virtual fn. // ApproximationInterfaces: do nothing } } /* void Interface::free_communicators() { if (interfaceRep) // envelope fwd to letter interfaceRep->free_communicators(); else { // letter lacking redefinition of virtual fn. // default is no-op } } */ void Interface::init_serial() { if (interfaceRep) // envelope fwd to letter interfaceRep->init_serial(); else { // letter lacking redefinition of virtual fn. // ApproximationInterfaces: do nothing } } int Interface::asynch_local_evaluation_concurrency() const { if (interfaceRep) // envelope fwd to letter return interfaceRep->asynch_local_evaluation_concurrency(); else // letter lacking redefinition of virtual fn. return 0; // default (redefined only for ApplicationInterfaces) } short Interface::interface_synchronization() const { if (interfaceRep) // envelope fwd to letter return interfaceRep->interface_synchronization(); // ApplicationInterfaces else // letter lacking redefinition of virtual fn. return SYNCHRONOUS_INTERFACE; // default (ApproximationInterfaces) } int Interface::minimum_points(bool constraint_flag) const { if (interfaceRep) // envelope fwd to letter return interfaceRep->minimum_points(constraint_flag); else // letter lacking redefinition of virtual fn. return 0; // default (currently redefined only for ApproximationInterfaces) } int Interface::recommended_points(bool constraint_flag) const { if (interfaceRep) // envelope fwd to letter return interfaceRep->recommended_points(constraint_flag); else // letter lacking redefinition of virtual fn. return 0; // default (currently redefined only for ApproximationInterfaces) } void Interface::approximation_function_indices(const IntSet& approx_fn_indices) { if (interfaceRep) // envelope fwd to letter interfaceRep->approximation_function_indices(approx_fn_indices); // else: default implementation is no-op } void Interface:: update_approximation(const Variables& vars, const IntResponsePair& response_pr) { if (interfaceRep) // envelope fwd to letter interfaceRep->update_approximation(vars, response_pr); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual update_approximation" << "(Variables, IntResponsePair) function.\n This interface " << "does not support approximation updating." << std::endl; abort_handler(-1); } } void Interface:: update_approximation(const RealMatrix& samples, const IntResponseMap& resp_map) { if (interfaceRep) // envelope fwd to letter interfaceRep->update_approximation(samples, resp_map); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual update_approximation" << "(RealMatrix, IntResponseMap) function.\n This interface " << "does not support approximation updating." << std::endl; abort_handler(-1); } } void Interface:: update_approximation(const VariablesArray& vars_array, const IntResponseMap& resp_map) { if (interfaceRep) // envelope fwd to letter interfaceRep->update_approximation(vars_array, resp_map); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual update_approximation" << "(VariablesArray, IntResponseMap) function.\n This interface " << "does not support approximation updating." << std::endl; abort_handler(-1); } } void Interface:: append_approximation(const Variables& vars, const IntResponsePair& response_pr) { if (interfaceRep) // envelope fwd to letter interfaceRep->append_approximation(vars, response_pr); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual append_approximation" << "(Variables, IntResponsePair) function.\n This interface " << "does not support approximation appending." << std::endl; abort_handler(-1); } } void Interface:: append_approximation(const RealMatrix& samples, const IntResponseMap& resp_map) { if (interfaceRep) // envelope fwd to letter interfaceRep->append_approximation(samples, resp_map); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual append_approximation" << "(RealMatrix, IntResponseMap) function.\n This interface " << "does not support approximation appending." << std::endl; abort_handler(-1); } } void Interface:: append_approximation(const VariablesArray& vars_array, const IntResponseMap& resp_map) { if (interfaceRep) // envelope fwd to letter interfaceRep->append_approximation(vars_array, resp_map); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual append_approximation" << "(VariablesArray, IntResponseMap) function.\n This interface " << "does not support approximation appending." << std::endl; abort_handler(-1); } } void Interface:: build_approximation(const RealVector& c_l_bnds, const RealVector& c_u_bnds, const IntVector& di_l_bnds, const IntVector& di_u_bnds, const RealVector& dr_l_bnds, const RealVector& dr_u_bnds, size_t index) { if (interfaceRep) // envelope fwd to letter interfaceRep->build_approximation(c_l_bnds, c_u_bnds, di_l_bnds, di_u_bnds, dr_l_bnds, dr_u_bnds, index); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual build_approximation" << "() function.\n This interface does not support " << "approximations." << std::endl; abort_handler(-1); } } void Interface:: export_approximation() { if (interfaceRep) // envelope fwd to letter interfaceRep->export_approximation(); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual export_approximation" << "() function.\n This interface does not support exporting " << "approximations." << std::endl; abort_handler(-1); } } void Interface:: rebuild_approximation(const BoolDeque& rebuild_deque, size_t index) { if (interfaceRep) // envelope fwd to letter interfaceRep->rebuild_approximation(rebuild_deque, index); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual rebuild_" << "approximation() function.\n This interface does not " << "support approximations." << std::endl; abort_handler(-1); } } void Interface::pop_approximation(bool save_surr_data) { if (interfaceRep) // envelope fwd to letter interfaceRep->pop_approximation(save_surr_data); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual pop_approximation" << "(bool)\n function. This interface does not support " << "approximation\n data removal." << std::endl; abort_handler(-1); } } void Interface::push_approximation() { if (interfaceRep) // envelope fwd to letter interfaceRep->push_approximation(); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual push_" << "approximation() function.\n This interface does not " << "support approximation data retrieval." << std::endl; abort_handler(-1); } } bool Interface::push_available() { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual push_" << "available() function.\n This interface does not " << "support approximation data retrieval." << std::endl; abort_handler(-1); } return interfaceRep->push_available(); } void Interface::finalize_approximation() { if (interfaceRep) // envelope fwd to letter interfaceRep->finalize_approximation(); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual finalize_" << "approximation() function.\n This interface does not " << "support approximation finalization." << std::endl; abort_handler(-1); } } void Interface::store_approximation(size_t index) { if (interfaceRep) // envelope fwd to letter interfaceRep->store_approximation(index); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual store_approximation" << "() function.\n This interface does not support approximation" << " storage." << std::endl; abort_handler(-1); } } void Interface::restore_approximation(size_t index) { if (interfaceRep) // envelope fwd to letter interfaceRep->restore_approximation(index); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual restore_" << "approximation() function.\n This interface does not " << "support approximation storage." << std::endl; abort_handler(-1); } } void Interface::remove_stored_approximation(size_t index) { if (interfaceRep) // envelope fwd to letter interfaceRep->remove_stored_approximation(index); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual remove_stored_" << "approximation() function.\n This interface does not " << "support approximation storage." << std::endl; abort_handler(-1); } } void Interface::combine_approximation() { if (interfaceRep) // envelope fwd to letter interfaceRep->combine_approximation(); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual combine_" << "approximation() function.\n This interface does not " << "support approximation combination." << std::endl; abort_handler(-1); } } void Interface::clear_stored() { if (interfaceRep) // envelope fwd to letter interfaceRep->clear_stored(); //else // letter lacking redefinition of virtual fn. // default: no stored data to clear } Real2DArray Interface:: cv_diagnostics(const StringArray& metric_types, unsigned num_folds) { if (interfaceRep) // envelope fwd to letter return interfaceRep->cv_diagnostics(metric_types, num_folds); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual cv_diagnostics()" << "function.\n This interface does not " << "support cross-validation diagnostics." << std::endl; abort_handler(-1); } } RealArray Interface::challenge_diagnostics(const String& metric_type, const RealMatrix& challenge_pts) { if (interfaceRep) // envelope fwd to letter return interfaceRep->challenge_diagnostics(metric_type, challenge_pts); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual challenge_" << "diagnostics() function.\n This interface does not " << "support challenge data diagnostics." << std::endl; abort_handler(-1); } } void Interface::clear_current() { if (interfaceRep) // envelope fwd to letter interfaceRep->clear_current(); else { // letter lacking redefinition of virtual fn. // ApplicationInterfaces: do nothing } } void Interface::clear_all() { if (interfaceRep) // envelope fwd to letter interfaceRep->clear_all(); else { // letter lacking redefinition of virtual fn. // ApplicationInterfaces: do nothing } } void Interface::clear_popped() { if (interfaceRep) // envelope fwd to letter interfaceRep->clear_popped(); else { // letter lacking redefinition of virtual fn. // ApplicationInterfaces: do nothing } } SharedApproxData& Interface::shared_approximation() { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual shared_approximation" << "() function.\nThis interface does not support approximations." << std::endl; abort_handler(-1); } // envelope fwd to letter return interfaceRep->shared_approximation(); } std::vector<Approximation>& Interface::approximations() { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual approximations() " << "function.\n This interface does not support approximations." << std::endl; abort_handler(-1); } // envelope fwd to letter return interfaceRep->approximations(); } const Pecos::SurrogateData& Interface::approximation_data(size_t index) { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual approximation_data " << "function.\n This interface does not support approximations." << std::endl; abort_handler(-1); } // envelope fwd to letter return interfaceRep->approximation_data(index); } const RealVectorArray& Interface::approximation_coefficients(bool normalized) { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual approximation_" << "coefficients function.\n This interface does not support " << "approximations." << std::endl; abort_handler(-1); } // envelope fwd to letter return interfaceRep->approximation_coefficients(normalized); } void Interface:: approximation_coefficients(const RealVectorArray& approx_coeffs, bool normalized) { if (interfaceRep) // envelope fwd to letter interfaceRep->approximation_coefficients(approx_coeffs, normalized); else { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual approximation_" << "coefficients function.\n This interface does not support " << "approximations." << std::endl; abort_handler(-1); } } const RealVector& Interface::approximation_variances(const Variables& vars) { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual approximation_" << "variances function.\n This interface does not support " << "approximations." << std::endl; abort_handler(-1); } // envelope fwd to letter return interfaceRep->approximation_variances(vars); } const StringArray& Interface::analysis_drivers() const { if (!interfaceRep) { // letter lacking redefinition of virtual fn. Cerr << "Error: Letter lacking redefinition of virtual analysis_drivers " << "function." << std::endl; abort_handler(-1); } // envelope fwd to letter return interfaceRep->analysis_drivers(); } bool Interface::evaluation_cache() const { if (interfaceRep) return interfaceRep->evaluation_cache(); else // letter lacking redefinition of virtual fn. return false; // default } bool Interface::restart_file() const { if (interfaceRep) return interfaceRep->restart_file(); else // letter lacking redefinition of virtual fn. return false; // default } void Interface::file_cleanup() const { if (interfaceRep) interfaceRep->file_cleanup(); // else no-op } } // namespace Dakota
33.593557
81
0.706139
jnnccc
dbc96ef5cb52031d3609435909e9480440bb0cd3
4,465
cc
C++
src/PhysicsListMessenger.cc
phirippu/instrument-simulation
0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8
[ "CC-BY-4.0" ]
null
null
null
src/PhysicsListMessenger.cc
phirippu/instrument-simulation
0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8
[ "CC-BY-4.0" ]
null
null
null
src/PhysicsListMessenger.cc
phirippu/instrument-simulation
0a7cec84d8945a6f11e0ddca00f1e8fc0d32d7f8
[ "CC-BY-4.0" ]
1
2021-03-08T16:01:14.000Z
2021-03-08T16:01:14.000Z
// // ******************************************************************** // * License and Disclaimer * // * * // * The Geant4 software is copyright of the Copyright Holders of * // * the Geant4 Collaboration. It is provided under the terms and * // * conditions of the Geant4 Software License, included in the file * // * LICENSE and available at http://cern.ch/geant4/license . These * // * include a list of copyright holders. * // * * // * Neither the authors of this software system, nor their employing * // * institutes,nor the agencies providing financial support for this * // * work make any representation or warranty, express or implied, * // * regarding this software system or assume any liability for its * // * use. Please see the license in the file LICENSE and URL above * // * for the full disclaimer and the limitation of liability. * // * * // * This code implementation is the result of the scientific and * // * technical work of the GEANT4 collaboration. * // * By using, copying, modifying or distributing the software (or * // * any work based on the software) you agree to acknowledge its * // * use in resulting scientific publications, and indicate your * // * acceptance of all terms of the Geant4 Software license. * // ******************************************************************** // /// \file hadronic/Hadr01/src/PhysicsListMessenger.cc /// \brief Implementation of the PhysicsListMessenger class // // // // ///////////////////////////////////////////////////////////////////////// // // PhysicsListMessenger // // Created: 31.01.2006 V.Ivanchenko // // Modified: // 04.06.2006 Adoptation of Hadr01 (V.Ivanchenko) // //////////////////////////////////////////////////////////////////////// // // #include "PhysicsListMessenger.hh" #include "PhysicsList.hh" #include "G4UIcmdWithAString.hh" #include "G4UIcmdWithoutParameter.hh" //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysicsListMessenger::PhysicsListMessenger(PhysicsList* pPhys) :G4UImessenger(), fPhysicsList(pPhys) { fPListCmd = new G4UIcmdWithAString("/physics/add",this); fPListCmd->SetGuidance("Add modular physics list."); fPListCmd->SetParameterName("PList",false); fPListCmd->AvailableForStates(G4State_PreInit); fListCmd = new G4UIcmdWithoutParameter("/physics/list",this); fListCmd->SetGuidance("Available Physics Lists"); fListCmd->AvailableForStates(G4State_PreInit,G4State_Idle); } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... PhysicsListMessenger::~PhysicsListMessenger() { delete fPListCmd; delete fListCmd; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo...... void PhysicsListMessenger::SetNewValue(G4UIcommand* command, G4String newValue) { if( command == fPListCmd ) { if(fPhysicsList) { G4String name = newValue; if(name == "PHYSLIST") { char* path = std::getenv(name); if (path) name = G4String(path); else { G4cout << "### PhysicsListMessenger WARNING: " << " environment variable PHYSLIST is not defined" << G4endl; return; } } fPhysicsList->AddPhysicsList(name); } else { G4cout << "### PhysicsListMessenger WARNING: " << " /physics/add UI command is not available " << "for reference Physics List" << G4endl; } } else if( command == fListCmd ) { if(fPhysicsList) { fPhysicsList->List(); } else { G4cout << "### PhysicsListMessenger WARNING: " << " /physics/list UI command is not available " << "for reference Physics List" << G4endl; } } } void PhysicsListMessenger::SayHello() { G4cout << "[INFO] Hello from PhysicsListMessenger. Use /physics/add to add new physics." << G4endl; } //....oooOO0OOooo........oooOO0OOooo........oooOO0OOooo........oooOO0OOooo......
39.166667
103
0.542889
phirippu
dbcf9fe3ceb5d9de21cb26fedab6a6036cac3475
4,247
cpp
C++
mytunesmodel.cpp
Liz-Davies/2404
a0d9e9c27286eccc9a086290ea223b41edabe248
[ "FSFAP" ]
null
null
null
mytunesmodel.cpp
Liz-Davies/2404
a0d9e9c27286eccc9a086290ea223b41edabe248
[ "FSFAP" ]
null
null
null
mytunesmodel.cpp
Liz-Davies/2404
a0d9e9c27286eccc9a086290ea223b41edabe248
[ "FSFAP" ]
null
null
null
/* * * * * * * * * * * * * * * * * * * * * * * * * * */ /* */ /* Program: MyTunes Music Player */ /* Author: Louis Nel */ /* Sarah Davies - 100828244 */ /* Mike Sayegh - 101029473 */ /* Date: 21-SEP-2017 */ /* */ /* (c) 2017 Louis Nel */ /* All rights reserved. Distribution and */ /* reposting, in part or in whole, requires */ /* written consent of the author. */ /* */ /* COMP 2404 students may reuse this content for */ /* their course assignments without seeking consent */ /* * * * * * * * * * * * * * * * * * * * * * * * * * */ #include "mytunesmodel.h" using namespace std; MyTunesModel::MyTunesModel(){} // void Myrun(); MyTunesModel::~MyTunesModel(void){} void MyTunesModel::addRecording(Recording * x){ recordings.add(*x); } void MyTunesModel::addUser(User * x){ users.add(*x); } void MyTunesModel::addSong(Song * x){ songs.add(*x); } void MyTunesModel::addTrack(Track * x){ tracks.add(*x); } Recording * MyTunesModel::getRecordingByID(int ID){ return recordings.findByID(ID); } User * MyTunesModel::getUserByID(string aUserName){ return users.findUserByID(aUserName); } Song * MyTunesModel::getSongByID(int ID){ return songs.findByID(ID); } Track * MyTunesModel::getTrackByID(int ID){ return tracks.findByID(ID); } void MyTunesModel::removeRecording(Recording * x){ recordings.remove(*x); } void MyTunesModel::removeUser(User * x){ users.remove(*x); } void MyTunesModel::removeSong(Song * x){ songs.remove(*x); } void MyTunesModel::removeTrack(Track * x){ tracks.remove(*x); } void MyTunesModel::globalTrackDelete(Track * track){ vector<User*> theUsers = users.getCollection(); for(vector<User*>::iterator itr = theUsers.begin(); itr != theUsers.end(); itr++){ User* user = *itr; user->removeTrack(*track); } vector<Recording*> theRecordings = recordings.getCollection(); for(vector<Recording*>::iterator itr = theRecordings.begin(); itr != theRecordings.end(); itr++){ Recording* recording = *itr; recording->removeTrack(*track); } tracks.remove(*track); } void MyTunesModel::deleteSong(Song * song){ //Perform Cascaded Delete vector<Track*> theTracks = tracks.getCollection(); for(vector<Track*>::iterator itr = theTracks.begin(); itr != theTracks.end(); itr++){ Track* track = *itr; Song* trackSong = track->getSong(); if(song == trackSong){ //Cascaded GLOBAL Delete globalTrackDelete(track); } } songs.remove(*song); } void MyTunesModel::executeCMDSHOW(Command cmd,UI & view){ //show recordings //show recordings -r recording_id //show songs //show songs -s song_id //show tracks //show tracks -t track_id //show users //show users -u user_id enum arguments {SHOW, COLLECTION, FLAG, MEMBER_ID}; if(cmd.isTokenAt(COLLECTION, "songs") && cmd.hasToken("-s")) songs.showOn(view, stoi(cmd.getToken("-s"))); else if(cmd.isTokenAt(COLLECTION, "songs") && cmd.hasToken("-u")){ User * user = getUserByID(cmd.getToken("-u")); if(user == NULL)view.printOutput("Error: User not found"); else user->showOn(view,cmd.getToken("-p")); } else if(cmd.isTokenAt(COLLECTION, "songs")) songs.showOn(view); else if(cmd.isTokenAt(COLLECTION, "recordings") && !cmd.hasToken("-r")) recordings.showOn(view); else if(cmd.isTokenAt(COLLECTION, "recordings") && cmd.hasToken("-r")) recordings.showOn(view, stoi(cmd.getToken("-r"))); else if(cmd.isTokenAt(COLLECTION, "tracks") && !cmd.hasToken("-t")) tracks.showOn(view); else if(cmd.isTokenAt(COLLECTION, "tracks") && cmd.hasToken("-t")) tracks.showOn(view, stoi(cmd.getToken("-t"))); else if(cmd.isTokenAt(COLLECTION, "users") && !cmd.hasToken("-u")) users.showOn(view); else if(cmd.isTokenAt(COLLECTION, "users") && cmd.hasToken("-u")) users.showOn(view, cmd.getToken("-u")); else view.printOutput("EXECUTING: " + cmd.getCommandString()); }
33.179688
99
0.597598
Liz-Davies
dbd396b0cf7ed94ed6ebcd2d8bff470bfb0937cf
35,218
cpp
C++
test/blocks/electron/testcases_electron.cpp
awietek/hydra
724a101500e308e91186a5cd6c5c520d8b343a6c
[ "Apache-2.0" ]
null
null
null
test/blocks/electron/testcases_electron.cpp
awietek/hydra
724a101500e308e91186a5cd6c5c520d8b343a6c
[ "Apache-2.0" ]
null
null
null
test/blocks/electron/testcases_electron.cpp
awietek/hydra
724a101500e308e91186a5cd6c5c520d8b343a6c
[ "Apache-2.0" ]
null
null
null
#include "testcases_electron.h" namespace hydra::testcases::electron { std::tuple<BondList, Couplings> get_linear_chain(int n_sites, double t, double U) { // Create model BondList bondlist; for (int s = 0; s < n_sites; ++s) bondlist << Bond("HOP", "T", {s, (s + 1) % n_sites}); Couplings couplings; couplings["T"] = t; couplings["U"] = U; return {bondlist, couplings}; } std::tuple<BondList, Couplings> get_linear_chain_hb(int n_sites, double t, double U, double J) { // Create model BondList bondlist; // for (int s = 0; s < n_sites; ++s) // bondlist << Bond("HOP", "T", {s, (s + 1) % n_sites}); for (int s = 0; s < n_sites; ++s) bondlist << Bond("EXCHANGE", "J", {s, (s + 1) % n_sites}); Couplings couplings; // couplings["T"] = t; // couplings["U"] = U; couplings["J"] = J; return {bondlist, couplings}; } std::tuple<PermutationGroup, std::vector<Representation>> get_cyclic_group_irreps(int n_sites) { // Create cyclic group as space group std::vector<std::vector<int>> permutations; for (int sym = 0; sym < n_sites; ++sym) { std::vector<int> permutation; for (int site = 0; site < n_sites; ++site) { int newsite = (site + sym) % n_sites; permutation.push_back(newsite); } permutations.push_back(permutation); } auto space_group = PermutationGroup(permutations); // Create irreducible representations std::vector<Representation> irreps; for (int k = 0; k < n_sites; ++k) { std::vector<complex> chis; for (int l = 0; l < n_sites; ++l) chis.push_back({std::cos(2 * M_PI * l * k / n_sites), std::sin(2 * M_PI * l * k / n_sites)}); auto irrep = Representation(chis); irreps.push_back(irrep); } return {space_group, irreps}; } std::tuple<PermutationGroup, std::vector<Representation>, std::vector<int>> get_cyclic_group_irreps_mult(int n_sites) { // Create cyclic group as space group std::vector<std::vector<int>> permutations; for (int sym = 0; sym < n_sites; ++sym) { std::vector<int> permutation; for (int site = 0; site < n_sites; ++site) { int newsite = (site + sym) % n_sites; permutation.push_back(newsite); } permutations.push_back(permutation); } auto space_group = PermutationGroup(permutations); // Create irreducible representations std::vector<Representation> irreps; std::vector<int> multiplicities; for (int k = 0; k < n_sites; ++k) { std::vector<complex> chis; for (int l = 0; l < n_sites; ++l) chis.push_back({std::cos(2 * M_PI * l * k / n_sites), std::sin(2 * M_PI * l * k / n_sites)}); auto irrep = Representation(chis); irreps.push_back(irrep); multiplicities.push_back(1); } return {space_group, irreps, multiplicities}; } std::tuple<BondList, Couplings> heisenberg_triangle() { BondList bondlist; bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {2, 0}); Couplings couplings; couplings["J"] = 1.0; return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> heisenberg_alltoall(int n_sites) { std::default_random_engine generator; std::normal_distribution<double> distribution(0., 1.); BondList bondlist; Couplings couplings; for (int s1 = 0; s1 < n_sites; ++s1) for (int s2 = s1 + 1; s2 < n_sites; ++s2) { std::stringstream ss; ss << "J" << s1 << "_" << s2; std::string name = ss.str(); double value = distribution(generator); bondlist << Bond("HEISENBERG", name, {s1, s2}); couplings[name] = value; } return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> heisenberg_kagome15() { BondList bondlist; bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {0, 5}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {1, 6}); bondlist << Bond("HEISENBERG", "J", {2, 3}); bondlist << Bond("HEISENBERG", "J", {2, 6}); bondlist << Bond("HEISENBERG", "J", {2, 10}); bondlist << Bond("HEISENBERG", "J", {3, 4}); bondlist << Bond("HEISENBERG", "J", {3, 10}); bondlist << Bond("HEISENBERG", "J", {3, 14}); bondlist << Bond("HEISENBERG", "J", {4, 5}); bondlist << Bond("HEISENBERG", "J", {4, 14}); bondlist << Bond("HEISENBERG", "J", {6, 7}); bondlist << Bond("HEISENBERG", "J", {7, 8}); bondlist << Bond("HEISENBERG", "J", {8, 9}); bondlist << Bond("HEISENBERG", "J", {9, 10}); bondlist << Bond("HEISENBERG", "J", {9, 11}); bondlist << Bond("HEISENBERG", "J", {10, 11}); bondlist << Bond("HEISENBERG", "J", {11, 12}); bondlist << Bond("HEISENBERG", "J", {12, 13}); bondlist << Bond("HEISENBERG", "J", {13, 14}); Couplings couplings; couplings["J"] = 1.0; return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> heisenberg_kagome39() { BondList bondlist; bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {0, 5}); bondlist << Bond("HEISENBERG", "J", {0, 27}); bondlist << Bond("HEISENBERG", "J", {0, 28}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {1, 6}); bondlist << Bond("HEISENBERG", "J", {1, 28}); bondlist << Bond("HEISENBERG", "J", {2, 3}); bondlist << Bond("HEISENBERG", "J", {2, 6}); bondlist << Bond("HEISENBERG", "J", {2, 10}); bondlist << Bond("HEISENBERG", "J", {3, 4}); bondlist << Bond("HEISENBERG", "J", {3, 10}); bondlist << Bond("HEISENBERG", "J", {3, 14}); bondlist << Bond("HEISENBERG", "J", {4, 5}); bondlist << Bond("HEISENBERG", "J", {4, 14}); bondlist << Bond("HEISENBERG", "J", {4, 38}); bondlist << Bond("HEISENBERG", "J", {5, 27}); bondlist << Bond("HEISENBERG", "J", {5, 38}); bondlist << Bond("HEISENBERG", "J", {6, 7}); bondlist << Bond("HEISENBERG", "J", {6, 29}); bondlist << Bond("HEISENBERG", "J", {7, 8}); bondlist << Bond("HEISENBERG", "J", {7, 19}); bondlist << Bond("HEISENBERG", "J", {7, 29}); bondlist << Bond("HEISENBERG", "J", {8, 9}); bondlist << Bond("HEISENBERG", "J", {8, 15}); bondlist << Bond("HEISENBERG", "J", {8, 19}); bondlist << Bond("HEISENBERG", "J", {9, 10}); bondlist << Bond("HEISENBERG", "J", {9, 11}); bondlist << Bond("HEISENBERG", "J", {9, 15}); bondlist << Bond("HEISENBERG", "J", {10, 11}); bondlist << Bond("HEISENBERG", "J", {11, 12}); bondlist << Bond("HEISENBERG", "J", {11, 18}); bondlist << Bond("HEISENBERG", "J", {12, 13}); bondlist << Bond("HEISENBERG", "J", {12, 18}); bondlist << Bond("HEISENBERG", "J", {12, 26}); bondlist << Bond("HEISENBERG", "J", {13, 14}); bondlist << Bond("HEISENBERG", "J", {13, 26}); bondlist << Bond("HEISENBERG", "J", {13, 37}); bondlist << Bond("HEISENBERG", "J", {14, 37}); bondlist << Bond("HEISENBERG", "J", {15, 16}); bondlist << Bond("HEISENBERG", "J", {15, 22}); bondlist << Bond("HEISENBERG", "J", {16, 17}); bondlist << Bond("HEISENBERG", "J", {16, 22}); bondlist << Bond("HEISENBERG", "J", {16, 33}); bondlist << Bond("HEISENBERG", "J", {17, 18}); bondlist << Bond("HEISENBERG", "J", {17, 23}); bondlist << Bond("HEISENBERG", "J", {17, 33}); bondlist << Bond("HEISENBERG", "J", {18, 23}); bondlist << Bond("HEISENBERG", "J", {19, 20}); bondlist << Bond("HEISENBERG", "J", {19, 30}); bondlist << Bond("HEISENBERG", "J", {20, 21}); bondlist << Bond("HEISENBERG", "J", {20, 30}); bondlist << Bond("HEISENBERG", "J", {20, 31}); bondlist << Bond("HEISENBERG", "J", {21, 22}); bondlist << Bond("HEISENBERG", "J", {21, 31}); bondlist << Bond("HEISENBERG", "J", {21, 32}); bondlist << Bond("HEISENBERG", "J", {22, 32}); bondlist << Bond("HEISENBERG", "J", {23, 24}); bondlist << Bond("HEISENBERG", "J", {23, 34}); bondlist << Bond("HEISENBERG", "J", {24, 25}); bondlist << Bond("HEISENBERG", "J", {24, 34}); bondlist << Bond("HEISENBERG", "J", {24, 35}); bondlist << Bond("HEISENBERG", "J", {25, 26}); bondlist << Bond("HEISENBERG", "J", {25, 35}); bondlist << Bond("HEISENBERG", "J", {25, 36}); bondlist << Bond("HEISENBERG", "J", {26, 36}); Couplings couplings; couplings["J"] = 1.0; return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> freefermion_alltoall(int n_sites) { std::default_random_engine generator; std::normal_distribution<double> distribution(0., 1.); BondList bondlist; Couplings couplings; for (int s1 = 0; s1 < n_sites; ++s1) for (int s2 = s1 + 1; s2 < n_sites; ++s2) { std::stringstream ss; ss << "T" << s1 << "_" << s2; std::string name = ss.str(); double value = distribution(generator); bondlist << Bond("HOP", name, {s1, s2}); couplings[name] = value; } return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> freefermion_alltoall_complex_updn(int n_sites) { std::default_random_engine generator; std::normal_distribution<double> distribution(0., 1.); BondList bondlist; Couplings couplings; for (int s1 = 0; s1 < n_sites; ++s1) for (int s2 = s1 + 1; s2 < n_sites; ++s2) { // Hopping on upspins std::stringstream ss_up; ss_up << "TUP" << s1 << "_" << s2; std::string name_up = ss_up.str(); complex value_up = complex(distribution(generator), distribution(generator)); bondlist << Bond("HOPUP", name_up, {s1, s2}); couplings[name_up] = value_up; // Hopping on dnspins std::stringstream ss_dn; ss_dn << "TDN" << s1 << "_" << s2; std::string name_dn = ss_dn.str(); complex value_dn = complex(distribution(generator), distribution(generator)); bondlist << Bond("HOPDN", name_dn, {s1, s2}); couplings[name_dn] = value_dn; } return std::make_tuple(bondlist, couplings); } // std::tuple<BondList, Couplings> tJchain(int n_sites, double t, // double J) { // BondList bondlist; // Couplings couplings; // couplings["T"] = t; // couplings["J"] = J; // for (int s = 0; s < n_sites; ++s) { // bondlist << Bond("HUBBARDHOP", "T", {s, (s + 1) % n_sites}); // bondlist << Bond("HEISENBERG", "J", {s, (s + 1) % n_sites}); // } // return std::make_tuple(bondlist, couplings); // } std::tuple<BondList, Couplings, lila::Vector<double>> randomAlltoAll4NoU() { BondList bondlist; Couplings couplings; // couplings["T01"] = 3; // couplings["J01"] = 1; // couplings["T02"] = 3; // couplings["J02"] = -3; // couplings["T03"] = 3; // couplings["J03"] = 5; // couplings["T12"] = 4; // couplings["J12"] = -5; // couplings["T13"] = -1; // couplings["J13"] = -1; // couplings["T23"] = 2; // couplings["J23"] = 1; couplings["T01"] = -3; couplings["J01"] = 1; couplings["T02"] = -3; couplings["J02"] = -3; couplings["T03"] = -3; couplings["J03"] = 5; couplings["T12"] = -4; couplings["J12"] = -5; couplings["T13"] = 1; couplings["J13"] = -1; couplings["T23"] = -2; couplings["J23"] = 1; bondlist << Bond("HOP", "T01", {0, 1}); bondlist << Bond("HOP", "T02", {0, 2}); bondlist << Bond("HOP", "T03", {0, 3}); bondlist << Bond("HOP", "T12", {1, 2}); bondlist << Bond("HOP", "T13", {1, 3}); bondlist << Bond("HOP", "T23", {2, 3}); bondlist << Bond("HEISENBERG", "J01", {0, 1}); bondlist << Bond("HEISENBERG", "J02", {0, 2}); bondlist << Bond("HEISENBERG", "J03", {0, 3}); bondlist << Bond("HEISENBERG", "J12", {1, 2}); bondlist << Bond("HEISENBERG", "J13", {1, 3}); bondlist << Bond("HEISENBERG", "J23", {2, 3}); lila::Vector<double> eigs = {-17.035603173216636, -16.054529653295518, -16.054529653295504, -14.839136196281768, -14.839136196281759, -14.479223672075845, -13.947060439818175, -13.681140962579473, -13.681140962579473, -13.681140962579470, -12.146019505147946, -12.146019505147938, -11.123249987689370, -11.083677166546861, -11.083677166546861, -10.361590604796385, -10.141075725997615, -10.141075725997606, -9.879061771701892, -9.879061771701885, -9.879061771701874, -9.720915055042584, -9.720915055042580, -9.300171000114572, -8.898903149068287, -8.898903149068287, -8.898903149068287, -8.587797030969547, -8.574093646826530, -8.574093646826528, -8.574093646826526, -8.567342877760581, -8.556463239828611, -8.556463239828611, -8.156431544113079, -8.156431544113071, -7.595003505113175, -7.595003505113174, -7.595003505113174, -7.595003505113171, -7.428914803058910, -7.428914803058910, -7.406132446925684, -7.406132446925682, -7.298052445959064, -7.298052445959062, -7.298052445959062, -6.776050147544091, -6.776050147544089, -6.597100597834562, -6.382421301285782, -6.382421301285780, -6.382421301285776, -5.914206919262412, -5.914206919262412, -5.914206919262412, -5.914206919262406, -5.898063094032344, -5.697730676986595, -5.652742708313134, -5.652742708313128, -5.382395669397896, -5.382395669397890, -4.827554533410211, -4.827554533410209, -4.827554533410208, -4.565866945456345, -4.392721098506336, -4.392721098506335, -4.392721098506333, -4.386896721326241, -4.386896721326240, -4.386896721326238, -4.287074157175168, -4.269109370889475, -4.269109370889474, -4.083758285516160, -3.784107949888678, -3.784107949888678, -3.230851175883084, -3.230851175883084, -3.166425888361765, -3.166425888361761, -3.060272421221770, -3.060272421221768, -3.060272421221768, -3.060272421221767, -2.846017856191310, -2.846017856191308, -2.826551366644327, -2.822163676323597, -2.822163676323595, -2.373593337341226, -2.304206358771344, -2.291423386597424, -2.291423386597422, -2.291423386597419, -2.258325746389715, -2.100087802223023, -2.100087802223022, -2.100087802223021, -2.002616246412348, -2.002616246412347, -2.002616246412346, -2.002616246412346, -1.653289828765464, -1.653289828765462, -1.653289828765460, -1.537108454167115, -1.537108454167113, -1.468496478890581, -1.184332042222068, -1.184332042222067, -1.183220245290653, -1.183220245290652, -1.183220245290647, -1.158824284368453, -1.158824284368453, -0.797210829513575, -0.797210829513574, -0.753299251580644, -0.500000000000001, -0.500000000000000, -0.500000000000000, -0.500000000000000, -0.499999999999998, -0.370985460263250, -0.370985460263249, -0.281075696274453, -0.230909105391692, -0.230909105391692, -0.230909105391689, 0, 0, 0.226914386262986, 0.226914386262986, 0.226914386262988, 0.339587764690138, 0.339587764690138, 0.339587764690140, 0.339587764690141, 0.864151894040242, 0.864151894040242, 0.977357729518521, 0.977357729518522, 0.982508508938287, 0.982508508938294, 1.184332042222068, 1.184332042222068, 1.286333102260671, 1.360519899915624, 1.360519899915626, 1.831699701973819, 1.831699701973819, 1.831699701973821, 2.168605503366585, 2.304759071083118, 2.305593972115476, 2.305593972115481, 2.305593972115481, 2.565136835120275, 2.565136835120277, 2.680716385503151, 2.680716385503155, 2.680716385503157, 2.859450072401542, 2.867740829382918, 2.867740829382918, 2.867740829382920, 2.867740829382922, 2.919012177817019, 2.919012177817021, 3.230851175883083, 3.230851175883084, 3.586647790757984, 3.586647790757985, 3.866685809727107, 3.866685809727108, 3.866685809727108, 3.962683310049183, 3.962683310049187, 3.983903797596342, 3.983903797596345, 3.983903797596353, 4.106914761573067, 4.258514587211152, 4.258514587211155, 4.258514587211158, 4.279939892091212, 4.647129236685327, 4.647129236685331, 4.730285398111332, 5.382395669397893, 5.382395669397895, 5.557913081969264, 5.729878922142601, 5.729878922142602, 5.729878922142604, 5.729878922142607, 5.854994021510809, 5.854994021510811, 6.026195725670756, 6.026195725670764, 6.112978522336865, 6.112978522336867, 6.112978522336871, 6.298578032819039, 6.627388000300686, 6.627388000300687, 6.638917394627725, 6.638917394627728, 6.638917394627730, 7.106988282706432, 7.261271812957728, 7.428914803058909, 7.428914803058913, 7.634891575794040, 7.634891575794041, 7.634891575794042, 7.634891575794042, 8.034109956056216, 8.034109956056225, 8.433501672445885, 8.437627423133117, 8.437627423133124, 8.437627423133126, 8.487415286599031, 8.740704187459059, 8.740704187459061, 8.740704187459061, 8.758701982332155, 9.740946203547077, 9.740946203547077, 10.075541640416940, 10.075541640416946, 10.365553083134904, 10.365553083134905, 10.898695460947337, 10.898695460947337, 10.898695460947343, 11.368060459508595, 11.880069395522252, 12.081391252276028, 12.081391252276036, 12.355338794669144, 12.355338794669148, 12.833107262067776, 14.296824370037875, 14.296824370037879, 14.296824370037887, 15.091839736118505, 15.091839736118507, 15.880746138642490, 17.166681362460483, 17.166681362460491, 18.194539570876405}; return std::make_tuple(bondlist, couplings, eigs); } std::tuple<BondList, Couplings, lila::Vector<double>> randomAlltoAll4() { BondList bondlist; Couplings couplings; // couplings["U"] = 5; // couplings["T01"] = 3; // couplings["J01"] = -1; // couplings["T02"] = -3; // couplings["J02"] = -5; // couplings["T03"] = 3; // couplings["J03"] = -3; // couplings["T12"] = -1; // couplings["J12"] = 1; // couplings["T13"] = -3; // couplings["J13"] = 2; // couplings["T23"] = 0; // couplings["J23"] = -4; couplings["U"] = 5; couplings["T01"] = -3; couplings["J01"] = -1; couplings["T02"] = 3; couplings["J02"] = -5; couplings["T03"] = -3; couplings["J03"] = -3; couplings["T12"] = 1; couplings["J12"] = 1; couplings["T13"] = 3; couplings["J13"] = 2; couplings["T23"] = 0; couplings["J23"] = -4; bondlist << Bond("HOP", "T01", {0, 1}); bondlist << Bond("HOP", "T02", {0, 2}); bondlist << Bond("HOP", "T03", {0, 3}); bondlist << Bond("HOP", "T12", {1, 2}); bondlist << Bond("HOP", "T13", {1, 3}); bondlist << Bond("HOP", "T23", {2, 3}); bondlist << Bond("HEISENBERG", "J01", {0, 1}); bondlist << Bond("HEISENBERG", "J02", {0, 2}); bondlist << Bond("HEISENBERG", "J03", {0, 3}); bondlist << Bond("HEISENBERG", "J12", {1, 2}); bondlist << Bond("HEISENBERG", "J13", {1, 3}); bondlist << Bond("HEISENBERG", "J23", {2, 3}); lila::Vector<double> eigs = { -12.270231830055396, -12.270231830055389, -10.733666336755952, -10.069390063366962, -9.060858377591751, -9.060858377591751, -9.060858377591751, -8.419560252873284, -8.419560252873282, -8.419560252873278, -6.383158148575644, -6.383158148575637, -6.383158148575632, -6.352277902330186, -6.352277902330185, -6.273324224596429, -6.273324224596422, -6.250906641891413, -6.250906641891411, -6.164309032262214, -6.164309032262212, -6.164309032262212, -6.164309032262211, -5.730618769293929, -5.448935789669534, -5.448935789669532, -5.038951239070341, -4.949876862328434, -4.949876862328423, -4.532986251596143, -4.532986251596141, -4.532986251596141, -4.532986251596141, -3.353197524407229, -3.353197524407228, -3.353197524407226, -3.273406176414287, -3.002245918852136, -3.002245918852133, -2.753141709527037, -2.753141709527034, -2.753141709527034, -2.753141709527031, -2.646622091502864, -2.646622091502863, -2.646622091502862, -2.500000000000006, -2.500000000000000, -2.500000000000000, -2.500000000000000, -2.499999999999995, -2.002043720414641, -2.002043720414640, -2.002043720414639, -1.825844696317418, -1.825844696317417, -1.587175599207617, -1.587175599207614, -1.332228906443854, -1.332228906443853, -0.953827936085984, -0.635382900549627, -0.635382900549625, -0.635382900549624, -0.397581339114120, -0.397581339114115, -0.302660107585638, -0.302660107585633, -0.302660107585631, -0.080803683543577, -0.080803683543570, 0, 0.216457675593863, 0.256166291525251, 0.601566977837033, 0.601566977837038, 0.601566977837038, 0.601566977837040, 0.975606313924293, 0.975606313924297, 1.014605271271656, 1.014605271271658, 1.015859809070357, 1.015859809070358, 1.015859809070360, 1.020308313587130, 1.114881844698814, 1.791357286454801, 1.791357286454802, 1.791357286454810, 1.812876191672553, 2.051032557261542, 2.051032557261543, 2.054529439890590, 2.054529439890591, 2.054529439890594, 2.464728271742040, 2.464728271742042, 2.464728271742044, 2.464728271742044, 2.561461716067067, 2.599451504679192, 2.710382274715613, 2.710382274715615, 2.710382274715616, 2.999999999999997, 3.000000000000001, 3.165957899766594, 3.165957899766600, 3.217491411604103, 3.217491411604104, 3.217491411604105, 3.264426167093818, 3.264426167093818, 3.275854965551124, 3.873065426792698, 3.930285431436003, 3.930285431436005, 4.357654287008264, 4.373227423701834, 4.373227423701834, 4.373227423701836, 4.744551703509988, 4.744551703509988, 4.764857447396031, 4.764857447396040, 4.764857447396043, 4.838082241099029, 4.838082241099031, 5.078388983561651, 5.078388983561652, 5.095728306021306, 5.095728306021313, 5.095728306021315, 5.095728306021317, 5.270280349321774, 5.629364135391933, 5.629364135391936, 5.732050357363664, 5.732050357363669, 5.732050357363673, 5.902527336054253, 5.997898395939853, 5.997898395939854, 5.997898395939856, 6.168989353312808, 6.168989353312815, 6.168989353312816, 6.168989353312816, 6.251638235870590, 6.251638235870590, 6.639239164264768, 6.871779959503020, 6.871779959503024, 6.913606012729136, 7.197663951269839, 7.197663951269844, 7.241663577600812, 7.241663577600815, 7.548559413909176, 7.548559413909178, 7.548559413909183, 7.889853801872584, 8.012439704238972, 8.012439704238977, 8.048368645785640, 8.048368645785644, 8.195982486905091, 8.195982486905091, 8.195982486905095, 8.291793376177347, 8.291793376177351, 8.291793376177356, 8.468003039901994, 8.884687492644268, 8.929394188779456, 8.929394188779456, 9.084392860883399, 9.084392860883403, 9.084392860883410, 9.119424084472175, 9.119424084472177, 9.119424084472177, 9.119424084472181, 9.374280903298303, 9.374280903298303, 9.470513926885971, 9.470513926885971, 9.807459688038790, 9.894356293199492, 10.161917758900962, 10.161917758900971, 10.343135676951986, 10.647301560880138, 10.647301560880139, 10.781521078539114, 10.816967757221121, 10.816967757221125, 10.816967757221128, 10.989949094629180, 10.989949094629189, 10.989949094629189, 11.783921524648289, 11.862403712063079, 11.862403712063086, 11.999999999999995, 11.999999999999995, 12.122579175754746, 12.122579175754746, 12.422108994367830, 12.422108994367832, 12.660280744665648, 12.660280744665650, 12.660280744665654, 12.782275159258591, 13.142554967689829, 13.262004386769918, 13.262004386769929, 13.262004386769933, 13.345289206597041, 13.345289206597041, 13.920776472179945, 14.125358959870058, 14.125358959870061, 14.245875071040452, 14.245875071040452, 14.710043063865781, 14.821095142124749, 15.455920358765942, 15.455920358765947, 15.455920358765953, 15.977688392619838, 15.977688392619839, 16.548872176333433, 16.587175599207608, 16.587175599207615, 16.668859213157941, 16.668859213157944, 16.859992272946350, 17.289815197741845, 17.339978797436935, 17.339978797436938, 17.339978797436956, 18.075989445512761, 18.075989445512761, 18.524216278708529, 18.776715574088868, 18.776715574088868, 20.000000000000000, 20.972807969213903, 21.250906641891415, 21.250906641891415, 22.411220290848199, 22.411220290848210, 22.508215798228996, 25.052426347353144}; return std::make_tuple(bondlist, couplings, eigs); } std::tuple<BondList, Couplings> randomAlltoAll3() { BondList bondlist; Couplings couplings; couplings["T01"] = 1; couplings["J01"] = -2; couplings["T02"] = 0; couplings["J02"] = -1; couplings["T12"] = -5; couplings["J12"] = -3; bondlist << Bond("HUBBARDHOP", "T01", {0, 1}); bondlist << Bond("HUBBARDHOP", "T02", {0, 2}); bondlist << Bond("HUBBARDHOP", "T12", {1, 2}); bondlist << Bond("HEISENBERG", "J01", {0, 1}); bondlist << Bond("HEISENBERG", "J02", {0, 2}); bondlist << Bond("HEISENBERG", "J12", {1, 2}); return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> square2x2(double t, double J) { BondList bondlist; Couplings couplings; couplings["T"] = t; couplings["J"] = J; bondlist << Bond("HUBBARDHOP", "T", {0, 1}); bondlist << Bond("HUBBARDHOP", "T", {1, 0}); bondlist << Bond("HUBBARDHOP", "T", {2, 3}); bondlist << Bond("HUBBARDHOP", "T", {3, 2}); bondlist << Bond("HUBBARDHOP", "T", {0, 2}); bondlist << Bond("HUBBARDHOP", "T", {2, 0}); bondlist << Bond("HUBBARDHOP", "T", {1, 3}); bondlist << Bond("HUBBARDHOP", "T", {3, 1}); bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {1, 0}); bondlist << Bond("HEISENBERG", "J", {2, 3}); bondlist << Bond("HEISENBERG", "J", {3, 2}); bondlist << Bond("HEISENBERG", "J", {0, 2}); bondlist << Bond("HEISENBERG", "J", {2, 0}); bondlist << Bond("HEISENBERG", "J", {1, 3}); bondlist << Bond("HEISENBERG", "J", {3, 1}); return std::make_tuple(bondlist, couplings); } std::tuple<BondList, Couplings> square3x3(double t, double J) { BondList bondlist; Couplings couplings; couplings["T"] = t; couplings["J"] = J; bondlist << Bond("HOP", "T", {0, 1}); bondlist << Bond("HOP", "T", {1, 2}); bondlist << Bond("HOP", "T", {2, 0}); bondlist << Bond("HOP", "T", {3, 4}); bondlist << Bond("HOP", "T", {4, 5}); bondlist << Bond("HOP", "T", {5, 3}); bondlist << Bond("HOP", "T", {6, 7}); bondlist << Bond("HOP", "T", {7, 8}); bondlist << Bond("HOP", "T", {8, 6}); bondlist << Bond("HOP", "T", {0, 3}); bondlist << Bond("HOP", "T", {3, 6}); bondlist << Bond("HOP", "T", {6, 0}); bondlist << Bond("HOP", "T", {1, 4}); bondlist << Bond("HOP", "T", {4, 7}); bondlist << Bond("HOP", "T", {7, 1}); bondlist << Bond("HOP", "T", {2, 5}); bondlist << Bond("HOP", "T", {5, 8}); bondlist << Bond("HOP", "T", {8, 2}); bondlist << Bond("HEISENBERG", "J", {0, 1}); bondlist << Bond("HEISENBERG", "J", {1, 2}); bondlist << Bond("HEISENBERG", "J", {2, 0}); bondlist << Bond("HEISENBERG", "J", {3, 4}); bondlist << Bond("HEISENBERG", "J", {4, 5}); bondlist << Bond("HEISENBERG", "J", {5, 3}); bondlist << Bond("HEISENBERG", "J", {6, 7}); bondlist << Bond("HEISENBERG", "J", {7, 8}); bondlist << Bond("HEISENBERG", "J", {8, 6}); bondlist << Bond("HEISENBERG", "J", {0, 3}); bondlist << Bond("HEISENBERG", "J", {3, 6}); bondlist << Bond("HEISENBERG", "J", {6, 0}); bondlist << Bond("HEISENBERG", "J", {1, 4}); bondlist << Bond("HEISENBERG", "J", {4, 7}); bondlist << Bond("HEISENBERG", "J", {7, 1}); bondlist << Bond("HEISENBERG", "J", {2, 5}); bondlist << Bond("HEISENBERG", "J", {5, 8}); bondlist << Bond("HEISENBERG", "J", {8, 2}); return std::make_tuple(bondlist, couplings); } } // namespace hydra::testcases::electron
43.586634
80
0.502158
awietek
dbd84cee98d96317013f0b48af09dc5f80eebf15
2,745
hpp
C++
RobWorkStudio/src/rwslibs/planning/Planning.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWorkStudio/src/rwslibs/planning/Planning.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWorkStudio/src/rwslibs/planning/Planning.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * 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. ********************************************************************************/ #ifndef PLANNING_HPP #define PLANNING_HPP #define QT_NO_EMIT #include <rw/core/Ptr.hpp> #include <rw/trajectory/Path.hpp> #include <rws/RobWorkStudioPlugin.hpp> #include <QObject> namespace rw { namespace models { class Device; }} // namespace rw::models namespace rw { namespace models { class WorkCell; }} // namespace rw::models class QComboBox; class QCheckBox; namespace rws { //! @brief Planning plugin for basic pathplanning. class Planning : public RobWorkStudioPlugin { Q_OBJECT #ifndef RWS_USE_STATIC_LINK_PLUGINS Q_INTERFACES (rws::RobWorkStudioPlugin) Q_PLUGIN_METADATA (IID "dk.sdu.mip.Robwork.RobWorkStudioPlugin/0.1" FILE "plugin.json") #endif public: //! @brief Constructor. Planning (); //! @brief Destructor. virtual ~Planning (); //! @copydoc RobWorkStudioPlugin::open virtual void open (rw::models::WorkCell* workcell); //! @copydoc RobWorkStudioPlugin::close virtual void close (); private Q_SLOTS: void setStart (); void gotoStart (); void setGoal (); void gotoGoal (); void setPlanAll (int state); void deviceChanged (int index); void plan (); void optimize (); void savePath (); void loadPath (); void performStatistics (); private: rw::models::WorkCell* _workcell; rw::core::Ptr< rw::models::Device > _device; rw::core::Ptr< rw::models::Device > _compositeDevice; QComboBox* _cmbDevices; QCheckBox* _planAllDev; std::vector< rw::math::Q > _starts; std::vector< rw::math::Q > _goals; QComboBox* _cmbPlanners; QComboBox* _cmbCollisionDetectors; QComboBox* _cmbOptimization; rw::trajectory::QPath _path; rw::core::Ptr< rw::models::Device > getDevice (); void setAsTimedStatePath (); std::string _previousOpenSaveDirectory; }; } // namespace rws #endif //#ifndef PLANNING_HPP
27.45
91
0.657195
ZLW07
dbdb9256aa2526eec206e98330cdfafd568fbafd
32,093
cpp
C++
src/Person.cpp
MasterMenOfficial/CSPSP-Client
d8ab8cc52543ca4cb136aab98c10d3efb61f8ebe
[ "BSD-3-Clause" ]
3
2021-01-20T08:57:23.000Z
2021-11-21T02:10:13.000Z
src/Person.cpp
MasterMenSilver/PSP-CSPSP-Client
d8ab8cc52543ca4cb136aab98c10d3efb61f8ebe
[ "BSD-3-Clause" ]
1
2018-06-26T00:02:20.000Z
2020-10-20T21:07:54.000Z
src/Person.cpp
MasterMenOfficial/CSPSP-1.92-rev9.0-Source-Code
d8ab8cc52543ca4cb136aab98c10d3efb61f8ebe
[ "BSD-3-Clause" ]
null
null
null
#include "Person.h" #include "Globals.h" JRenderer* Person::mRenderer = NULL; JSoundSystem* Person::mSoundSystem = NULL; //------------------------------------------------------------------------------------------------ Person::Person(JQuad* quads[], JQuad* deadquad, std::vector<Bullet*>* bullets, std::vector<GunObject*>* guns, int team, char* name, int movementstyle) { mRenderer = JRenderer::GetInstance(); SetQuads(quads,deadquad); mX = 0.0f; mY = 0.0f; mOldX = 0.0f; mOldY = 0.0f; mWalkX = 0.0f; mWalkY = 0.0f; mSpeed = 0.0f; mAngle = 0.0f; mMaxSpeed = 0.0f; mMoveState = NOTMOVING; mState = DEAD; //mState = 0; mStateTime = 0.0f; mHealth = 100; mRegen = 0.0f; mRegenlol = 0.0f; mRegenTimer = 2.0f; //default 1 sec mRegenPoints = 5; //default 1 HP mRegenSfxType = 0; mGunMode = 0; mSilencedUSP = false; mSilencedM4A1 = false; mLRTimer = 0.0f; mComboType = 0; mComboTimer = 0; mMoney = 800; mRecoilAngle = 0.0f; SetTotalRotation(M_PI_2); //mRotation = 0.0f; //mFacingAngle = M_PI_2; //mLastFireAngle = 0.0f; mTeam = team; strncpy(mName,name,25); mName[25] = '\0'; mMovementStyle = movementstyle; mNumKills = 0; mNumDeaths = 0; mSoundId = -1; mNumDryFire = 0; /*mGuns[PRIMARY] = NULL; mGuns[SECONDARY] = NULL; mGuns[KNIFE] = NULL; mGuns[mGunIndex] = NULL;*/ for (int i=0; i<5; i++) { mGuns[i] = NULL; } mGunIndex = KNIFE; mFadeTime = 0.0f; mStepTime = 0.0f; mIsActive = true; mBullets = bullets; mGunObjects = guns; mPing = 0.0f; mIsPlayerOnline = false; mIsFiring = false; mHasFired = false; mHasLR = false; mIsFlashed = false; mFlashTime = 0.0f; mFlashIntensity = 0.0f; mIsInBuyZone = false; mIsInBombZone = false; mNode = NULL; mTargetNode = NULL; for (int i=0; i<10; i++) { mAnimations[i] = NULL; } for (int i=ANIM_PRIMARY; i<=ANIM_SECONDARY_RELOAD; i++) { mAnimations[i] = new Animation(gKeyFrameAnims[i],true,false); } mCurrentAnimation = mAnimations[1]; mKeyFrame = KeyFrame(); mKeyFrame.angles[BODY] = 0.4f; mKeyFrame.angles[RIGHTARM] = 0.0f; mKeyFrame.angles[RIGHTHAND] = 0.0f; mKeyFrame.angles[LEFTARM] = 0.0f; mKeyFrame.angles[LEFTHAND] = 0.0f; mKeyFrame.angles[GUN] = 0.0f; mKeyFrame.duration = 10; mWalkState = WALK1; mWalkTime = 0.0f; mWalkAngle = 0.0f; mMuzzleFlashIndex = 0; mMuzzleFlashAngle = 0.0f; mMuzzleFlashTime = 0.0f; mRadarTime = 0.0f; mRadarX = 0.0f; mRadarY = 0.0f; mHasFlag = false; mInvincibleTime = 0.0f; /*JTexture* texture = mRenderer->LoadTexture("gfx/playerparts.png"); mPartQuads[BODY] = new JQuad(texture,0,0,32,16); mPartQuads[BODY]->SetHotSpot(16,8); mPartQuads[5] = new JQuad(texture,16,16,16,16); mPartQuads[5]->SetHotSpot(8,8); mPartQuads[RIGHTARM] = new JQuad(texture,0,16,16,8); mPartQuads[RIGHTARM]->SetHotSpot(4.5f,3.5f); mPartQuads[RIGHTHAND] = new JQuad(texture,0,24,16,8); mPartQuads[RIGHTHAND]->SetHotSpot(3.5f,3.5f); mPartQuads[LEFTARM] = new JQuad(texture,0,16,16,8); mPartQuads[LEFTARM]->SetHotSpot(4.5f,3.5f); mPartQuads[LEFTARM]->SetVFlip(true); mPartQuads[LEFTHAND] = new JQuad(texture,0,24,16,8); mPartQuads[LEFTHAND]->SetHotSpot(3.5f,3.5f); mPartQuads[LEFTHAND]->SetVFlip(true);*/ mAllowRegeneration = true; char* AR = GetConfig("data/MatchSettings.txt","AllowRegeneration"); if (AR != NULL) { if (strcmp(AR,"true") == 0) { mAllowRegeneration = true; } else if (strcmp(AR,"false") == 0) { mAllowRegeneration = false; } delete AR; } } //------------------------------------------------------------------------------------------------ Person::~Person() { //mPeople.clear(); /*if (mGuns[PRIMARY]) delete mGuns[PRIMARY]; if (mGuns[SECONDARY]) delete mGuns[SECONDARY]; if (mGuns[KNIFE]) delete mGuns[KNIFE];*/ for (int i=0; i<5; i++) { if (mGuns[i]) { delete mGuns[i]; } } for (int i=0; i<10; i++) { if (mAnimations[i] != NULL) { delete mAnimations[i]; } } //delete mKeyFrame; mNodes.clear(); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } //JGERelease(); } //------------------------------------------------------------------------------------------------ void Person::PreUpdate(float dt) { if (mState == DEAD) { return; } float dx = mOldX-mX; float dy = mOldY-mY; //UpdateAngle(mWalkAngle,mAngle, 0.01*dt); float speed = sqrtf(dx*dx+dy*dy)/dt; if (speed > 0.15f) speed = 0.15f; if (mMoveState == NOTMOVING || speed < 0.03f) { if (mWalkTime > 0.0f) { mWalkTime -= dt; if (mWalkTime < 0.0f) { mWalkTime = 0.0f; mWalkState = (mWalkState+2)%4; } } } else {//if (mMoveState == MOVING) { //float speed = sqrtf(dx*dx+dy*dy)/dt; if (mWalkState == WALK1 || mWalkState == WALK3) { mWalkTime += dt*speed/0.1f; if (mWalkTime >= WALKTIME) { mWalkTime = WALKTIME-(mWalkTime-WALKTIME); mWalkState = (mWalkState+1)%4; } } else { mWalkTime -= dt*speed/0.1f; if (mWalkTime <= 0) { mWalkTime = -mWalkTime; mWalkState = (mWalkState+1)%4; } } } dx = mX-mWalkX; dy = mY-mWalkY; float d = sqrtf(dx*dx+dy*dy)/dt; if (d > 2+rand()%2) { mWalkX = mX; mWalkY = mY; //gSfxManager->PlaySample(gWalkSounds[rand()%2],mX,mY); } else if (speed > 0.06f) { mStepTime += dt; if (mStepTime > 480.0f + rand()%50 - 25.0f) { gSfxManager->PlaySample(gWalkSounds[rand()%2],mX,mY); mStepTime = 0.0f; } } //if (fabs(dx) >= EPSILON || fabs(dy) >= EPSILON) { /*if (speed > 0.06f) { mStepTime += dt; if (mStepTime > 480.0f + rand()%50 - 25.0f) { gSfxManager->PlaySample(gWalkSounds[rand()%2],mX,mY); mStepTime = 0.0f; } }*/ //} } //------------------------------------------------------------------------------------------------ void Person::Update(float dt) { if (mGuns[mGunIndex] == NULL) { printf("isPlayerOnline: %i\n",mIsPlayerOnline); printf("invalid gunindex: %i\n",mGunIndex); return; } mStateTime += dt; if (mState == DEAD) { if (mStateTime >= 15000.0f) { //P: time for deadbody = 15 secs //orig : 2 sec mFadeTime -= dt; if (mFadeTime < 0.0f) { mFadeTime = 0.0f; } } return; } //P: HEALTH REGEN (adds as HP the mRegenPoints per desired mRegenTimer) if (mAllowRegeneration == true) { if (mMoveState == NOTMOVING && mHealth != 100) { mRegen += dt/1000.0f; if (mRegen >= mRegenTimer) { // + mRegenPoints HP per mRegenTimer second(s) if (mHealth != 0) { mRegenlol += dt/25.0f; if (mRegenlol >= mRegenTimer){ mHealth += 1; mRegenPoints -= 1; mRegenlol = 0.0f; if (mRegenPoints == 4) { mRegenSfxType = 1; } } if (mRegenPoints <= 0){ mRegen = 0.0f; mRegenPoints = 5; } } } if (mHealth > 100) { //for safety and bug avoidance reasons, cause it could be done otherwise, but this is optimum. mHealth = 100; } if (mHealth == 100) { mRegen = 0.0f; } } if (mMoveState != NOTMOVING) { mRegen = 0.0f; mRegenPoints = 5; } } // Regen End mWalkAngle = mAngle; if (mIsActive) { if (mMoveState == NOTMOVING) { if (!mIsPlayerOnline) { mSpeed -= .0005f*dt; if (mSpeed < 0) { mSpeed = 0; } } mStepTime = 240.0f; } else if (mMoveState == MOVING) { if (!mIsPlayerOnline) { mSpeed += .0005f*dt; if (mSpeed > mMaxSpeed) { mSpeed = mMaxSpeed; } } if (mRecoilAngle < mGuns[mGunIndex]->mGun->mSpread*0.5f) { //HERE mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/50.0f*dt; if (mRecoilAngle > mGuns[mGunIndex]->mGun->mSpread*0.5f) { mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread*0.5f; } } } } if (!mIsPlayerOnline) { mOldX = mX; mOldY = mY; mX += mSpeed * cosf(mAngle) * dt; mY += mSpeed * sinf(mAngle) * dt; } //JSprite::Update(dt); if (mGuns[mGunIndex]->mGun->mId == 7 || mGuns[mGunIndex]->mGun->mId == 8) { //HERE mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread; } mLastFireAngle = mRotation; if (mState == NORMAL) { if (mGuns[mGunIndex]->mGun->mId != 7 && mGuns[mGunIndex]->mGun->mId != 8) { mRecoilAngle -= mGuns[mGunIndex]->mGun->mSpread/100.0f*dt; if (mRecoilAngle < 0) { mRecoilAngle = 0.0f; } } } else if (mState == ATTACKING) { if (mMoveState == NOTMOVING) { mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/500.0f*dt; } else if (mMoveState == MOVING) { mRecoilAngle += mGuns[mGunIndex]->mGun->mSpread/50.0f*dt; } if (mGuns[mGunIndex]->mGun->mId == 16 || mGuns[mGunIndex]->mGun->mId == 21 || mGuns[mGunIndex]->mGun->mId == 22 || mGuns[mGunIndex]->mGun->mId == 23) { mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread; } if (mRecoilAngle > mGuns[mGunIndex]->mGun->mSpread) { mRecoilAngle = mGuns[mGunIndex]->mGun->mSpread; } if (mRecoilAngle*500.0f >= 0.1f && mStateTime < 100.0f) { mLastFireAngle += (rand()%(int)ceilf(mRecoilAngle*500.0f))/1000.0f-(mRecoilAngle/4.0f); } if (mStateTime >= mGuns[mGunIndex]->mGun->mDelay) { if (mGunIndex == GRENADE) { mStateTime = mGuns[mGunIndex]->mGun->mDelay; } else { SetState(NORMAL); } } } else if (mState == RELOADING) { if (mStateTime >= mGuns[mGunIndex]->mGun->mReloadDelay) { mGuns[mGunIndex]->mRemainingAmmo -= (mGuns[mGunIndex]->mGun->mClip-mGuns[mGunIndex]->mClipAmmo); mGuns[mGunIndex]->mClipAmmo = mGuns[mGunIndex]->mGun->mClip; if (mGuns[mGunIndex]->mRemainingAmmo < 0) { mGuns[mGunIndex]->mClipAmmo = mGuns[mGunIndex]->mGun->mClip + mGuns[mGunIndex]->mRemainingAmmo ; mGuns[mGunIndex]->mRemainingAmmo = 0; } SetState(NORMAL); } if (mGuns[mGunIndex]->mGun->mId != 7 && mGuns[mGunIndex]->mGun->mId != 8) { mRecoilAngle -= mGuns[mGunIndex]->mGun->mSpread/100.0f*dt; if (mRecoilAngle < 0.0f) { mRecoilAngle = 0.0f; } } } else if (mState == DRYFIRING) { if (mGunIndex == PRIMARY) { if (mStateTime >= 250.0f) { SetState(NORMAL); mNumDryFire++; } } else if (mGunIndex == SECONDARY) { SetState(NORMAL); mNumDryFire++; } else if (mGunIndex == KNIFE) { if (mStateTime >= mGuns[mGunIndex]->mGun->mDelay) { SetState(NORMAL); } } } else if (mState == SWITCHING) { if (mGunIndex == PRIMARY || mGunIndex == SECONDARY) { float delay = mGuns[mGunIndex]->mGun->mDelay*0.75f; if (delay < 150.0f) delay = 150.0f; if (mStateTime >= delay) { SetState(NORMAL); } } else { if (mStateTime >= 150.0f) { SetState(NORMAL); } } } if (!mIsPlayerOnline) { if (mNumDryFire > 3) { Reload(); } } if (mIsFlashed) { mFlashTime -= dt/mFlashIntensity; if (mFlashTime < 0.0f) { mFlashTime = 0.0f; mIsFlashed = false; } } //P: Same thing as regen just add a timer mMuzzleFlashTime -= dt; if (mMuzzleFlashTime < 0.0f) { mMuzzleFlashTime = 0.0f; } mRadarTime -= dt; if (mRadarTime < 0.0f) { mRadarTime = 0.0f; } mCurrentAnimation->Update(dt,mKeyFrame); mInvincibleTime -= dt; if (mInvincibleTime < 0.0f) { mInvincibleTime = 0.0f; } } //------------------------------------------------------------------------------------------------ void Person::Render(float x, float y) { float offsetX = (x-SCREEN_WIDTH_2); float offsetY = (y-SCREEN_HEIGHT_2); if (mState != DEAD) { float rotation = mRotation+M_PI_2; float centerx = mX-offsetX-4*cosf(rotation); float centery = mY-offsetY-4*sinf(rotation); float x = centerx; float y = centery; float offsetangle = mWalkTime/WALKTIME*(M_PI_2); float offset = 7*sinf(offsetangle); if (mWalkState == WALK3 || mWalkState == WALK4) { //offset = -offset; mQuads[LEGS]->SetHFlip(true); } else { mQuads[LEGS]->SetHFlip(false); } float dx = offset*cosf(mAngle); float dy = offset*sinf(mAngle); float x2 = x+dx; float y2 = y+dy; //mRenderer->FillCircle(x,y,12,ARGB(100,0,0,0)); /*rotation = mAngle; if (rotation < 2*M_PI) { rotation += 2*M_PI; }*/ mRenderer->RenderQuad(mQuads[LEGS],x,y,mWalkAngle-M_PI_2,1.0f,offset/7); //mQuads[RIGHTLEG]->SetVFlip(true); //mRenderer->RenderQuad(mQuads[LEFTLEG],x+4*cosf(mWalkAngle-M_PI_2),y+4*sinf(mWalkAngle-M_PI_2),mWalkAngle-M_PI_2,1.0f,-offset/7); //mRenderer->FillCircle(x+4*cosf(mWalkAngle-M_PI_2) - offset*cosf(mWalkAngle),y+4*sinf(mWalkAngle-M_PI_2) - offset*sinf(mWalkAngle),3.0f,ARGB(255,0,0,0)); //mRenderer->FillCircle(x+4*cosf(mWalkAngle+M_PI_2) + offset*cosf(mWalkAngle),y+4*sinf(mWalkAngle+M_PI_2) + offset*sinf(mWalkAngle),3.0f,ARGB(255,0,0,0)); if (mGuns[mGunIndex] != NULL) { //mRenderer->RenderQuad(mGuns[mGunIndex]->mGun->mHandQuad,mX-offsetX,mY-offsetY,mLastFireAngle); if (mGunIndex == KNIFE && (mState == ATTACKING || mState == DRYFIRING)) { float angle = 0; if (mStateTime < (mGuns[KNIFE]->mGun->mDelay*0.2f)) { angle = mStateTime/(mGuns[KNIFE]->mGun->mDelay*0.2f); } else if (mStateTime >= (mGuns[KNIFE]->mGun->mDelay*0.2f)) { angle = (mGuns[KNIFE]->mGun->mDelay-mStateTime)/(mGuns[KNIFE]->mGun->mDelay*0.8f); } //mGuns[mGunIndex]->mGun->mHandQuad->SetColor(ARGB(200,255,255,255)); //mRenderer->RenderQuad(mGuns[mGunIndex]->mGun->mHandQuad,mX-offsetX,mY-offsetY,mLastFireAngle+angle); //mGuns[mGunIndex]->mGun->mHandQuad->SetColor(ARGB(255,255,255,255)); } } //mRenderer->RenderQuad(mQuads[mGunIndex],mX-offsetX,mY-offsetY,mRotation); rotation = mRotation+M_PI_2; centerx = mX-offsetX-5*cosf(rotation); centery = mY-offsetY-5*sinf(rotation); x = centerx; y = centery; dx = 10*cosf(mRotation+mKeyFrame.angles[BODY]); dy = 10*sinf(mRotation+mKeyFrame.angles[BODY]); x2 = x+dx; y2 = y+dy; if (mHasFlag) { float tempx = x-10*cosf(rotation); float tempy = y-10*sinf(rotation); if (mTeam == T) { gFlagQuad->SetColor(ARGB(255,153,204,255)); } else { gFlagQuad->SetColor(ARGB(255,255,64,64)); } mRenderer->RenderQuad(gFlagQuad,tempx,tempy,mRotation+mKeyFrame.angles[BODY]-M_PI_4*0.6f); } mRenderer->RenderQuad(mQuads[BODY],x,y,mRotation+mKeyFrame.angles[BODY]); //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); x = x2; y = y2; x2 = x+8*cosf(rotation+mKeyFrame.angles[LEFTARM]); y2 = y+8*sinf(rotation+mKeyFrame.angles[LEFTARM]); mRenderer->RenderQuad(mQuads[LEFTARM],x,y,mRotation+mKeyFrame.angles[LEFTARM]); //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); x = x2; y = y2; //x2 = x+10*cosf(mRotation+mKeyFrame.angles[LEFTHAND]); //y2 = y+10*sinf(mRotation+mKeyFrame.angles[LEFTHAND]); mRenderer->RenderQuad(mQuads[LEFTHAND],x,y,mRotation+mKeyFrame.angles[LEFTHAND]); //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); x = centerx; y = centery; x2 = x-dx; y2 = y-dy; //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); x = x2; y = y2; x2 = x+8*cosf(rotation+mKeyFrame.angles[RIGHTARM]); y2 = y+8*sinf(rotation+mKeyFrame.angles[RIGHTARM]); mRenderer->RenderQuad(mQuads[RIGHTARM],x,y,mRotation+mKeyFrame.angles[RIGHTARM]); //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); x = x2; y = y2; x2 = x+10*cosf(rotation+mKeyFrame.angles[RIGHTHAND]); y2 = y+10*sinf(rotation+mKeyFrame.angles[RIGHTHAND]); mRenderer->RenderQuad(mQuads[RIGHTHAND],x,y,mRotation+mKeyFrame.angles[RIGHTHAND]); //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); x = x2; y = y2; //x2 = x+11*cosf(mRotation+mKeyFrame.angles[GUN]); //y2 = y+11*sinf(mRotation+mKeyFrame.angles[GUN]); mRenderer->RenderQuad(mGuns[mGunIndex]->mGun->mHandQuad,x,y,mLastFireAngle+mKeyFrame.angles[GUN]); if (mMuzzleFlashTime > 0.0f) { /*x2 = x+10*cosf(rotation+mKeyFrame.angles[GUN]); y2 = y+10*sinf(rotation+mKeyFrame.angles[GUN]); x = x2; y = y2;*/ //int alpha = mMuzzleFlashTime/100.0f*255; //gMuzzleFlashQuads[mMuzzleFlashIndex]->SetColor(ARGB(alpha,255,255,255)); float scale = 1.0f; if (mMuzzleFlashIndex >= 3) { scale = 0.5f; } mRenderer->RenderQuad(gMuzzleFlashQuads[mMuzzleFlashIndex%3],x,y,mMuzzleFlashAngle-M_PI_2,1.0f,scale); } mRenderer->RenderQuad(mQuads[5],centerx,centery,mRotation); //mRenderer->DrawLine(x,y,x2,y2,ARGB(255,255,255,255)); /*mAnimationAngles[BODY] = 0.0f; mAnimationAngles[RIGHTARM] = 0.0f; mAnimationAngles[RIGHTHAND] = 0.0f; mAnimationAngles[LEFTARM] = 0.0f; mAnimationAngles[LEFTHAND] = 0.0f; mAnimationAngles[GUN] = 0.0f;*/ //mRenderer->DrawCircle(mOldX-offsetX,mOldY-offsetY,16,ARGB(255,0,0,0)); //mRenderer->DrawCircle(mX-offsetX,mY-offsetY,16,ARGB(255,255,255,255)); if (mInvincibleTime > 0.0f) { mRenderer->DrawCircle(mX-offsetX,mY-offsetY,17,ARGB(200,0,0,0)); mRenderer->DrawCircle(mX-offsetX,mY-offsetY,16,ARGB(255,255,255,255)); } } else { if (mFadeTime > 0) { mDeadQuad->SetColor(ARGB((int)(mFadeTime*(255.0f/1000.0f)),255,255,255)); mRenderer->RenderQuad(mDeadQuad,mX-offsetX,mY-offsetY,mRotation); } } } //------------------------------------------------------------------------------------------------ void Person::Move(float speed, float angle) { if (!mIsActive) return; SetMoveState(MOVING); mMaxSpeed = speed*mGuns[mGunIndex]->mGun->mSpeed; if (mMovementStyle == RELATIVE1) { mAngle = mFacingAngle+angle; } else if (mMovementStyle == ABSOLUTE1) { mAngle = angle-M_PI_2; } if (mAngle > M_PI) { mAngle -= 2*M_PI; } if (mAngle < -M_PI) { mAngle += 2*M_PI; } } //------------------------------------------------------------------------------------------------ std::vector<Bullet*> Person::Fire() { std::vector<Bullet*> bullets; if (!mIsActive) return bullets; if (mState == NORMAL) { mIsFiring = true; mHasFired = true; if (mGunIndex == KNIFE) { SetState(ATTACKING); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY); //return true; } else if (mGunIndex == GRENADE) { if (mGuns[mGunIndex]->mClipAmmo != 0) { SetState(ATTACKING); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY); } } else { if (mGuns[mGunIndex]->mClipAmmo != 0) { Bullet* bullet; float h = 24*sinf(mFacingAngle); float w = 24*cosf(mFacingAngle); float theta = mFacingAngle; float speed = 0.3f*mGuns[mGunIndex]->mGun->mBulletSpeed; if (mGuns[mGunIndex]->mGun->mId == 7) { theta -= mGuns[mGunIndex]->mGun->mSpread/2;//m0.36f; float step = mGuns[mGunIndex]->mGun->mSpread/5; for (int i=0; i<6; i++) { theta += (rand()%11)/100.0f-0.05f; bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this); bullets.push_back(bullet); mBullets->push_back(bullet); theta += step;//0.144f; } } else if (mGuns[mGunIndex]->mGun->mId == 8) { theta -= mGuns[mGunIndex]->mGun->mSpread/2;//0.36f; float step = mGuns[mGunIndex]->mGun->mSpread/3; for (int i=0; i<4; i++) { theta += (rand()%10)/100.0f-0.05f; bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this); bullets.push_back(bullet); mBullets->push_back(bullet); theta += step; //0.24f; } } else { if (mRecoilAngle*1000.0f >= 0.1f) { theta += (rand()%(int)ceilf(mRecoilAngle*1000.0f))/1000.0f-(mRecoilAngle*0.5f); //theta = mFacingAngle + (rand()%100)/400.0f-0.125f; } bullet = new Bullet(mX+w,mY+h,mX,mY,theta,speed,abs(mGuns[mGunIndex]->mGun->mDamage+rand()%17-8),this); bullets.push_back(bullet); mBullets->push_back(bullet); } gParticleEngine->GenerateParticles(BULLETSHELL,mX+10*cosf(mFacingAngle),mY+10*sinf(mFacingAngle),1); SetState(ATTACKING); mGuns[mGunIndex]->mClipAmmo--; //JSample *test = mEngine->LoadSample("sfx/m249.wav"); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mFireSound,mX,mY); mMuzzleFlashTime = 50.0f; mMuzzleFlashAngle = mFacingAngle; mMuzzleFlashIndex = mGuns[mGunIndex]->mGun->mType*3 + rand()%3; mRadarTime = 2000.0f; mRadarX = mX; mRadarY = mY; //return true; } else { SetState(DRYFIRING); gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mDryFireSound,mX,mY); //return; } } } return bullets; //return false; } //------------------------------------------------------------------------------------------------ std::vector<Bullet*> Person::StopFire() { std::vector<Bullet*> bullets; if (!mIsActive) return bullets; mIsFiring = false; mHasFired = false; if (mState == ATTACKING) { if (mGunIndex == GRENADE) { if (mGuns[mGunIndex]->mClipAmmo != 0) { float h = 24*sinf(mFacingAngle); float w = 24*cosf(mFacingAngle); float theta = mFacingAngle; float speed = 0.2f * mStateTime/(float)mGuns[mGunIndex]->mGun->mDelay; int type = HE; if (mGuns[mGunIndex]->mGun->mId == 25) { //FLASH type = FLASH; } else if (mGuns[mGunIndex]->mGun->mId == 26) { //HE type = HE; } else if (mGuns[mGunIndex]->mGun->mId == 27) { //SMOKE type = SMOKE; } Grenade* grenade = new Grenade(mX+w,mY+h,mX,mY,theta,speed,this,type); bullets.push_back(grenade); mBullets->push_back(grenade); SetState(NORMAL); gSfxManager->PlaySample(gFireInTheHoleSound,mX,mY); mGuns[mGunIndex]->mClipAmmo--; delete mGuns[mGunIndex]; mGuns[mGunIndex] = NULL; SwitchNext(); } } } return bullets; } //------------------------------------------------------------------------------------------------ bool Person::Reload() { if (mGunIndex == KNIFE || mGunIndex == GRENADE) return false; if (mState != RELOADING && mGuns[mGunIndex]->mClipAmmo != mGuns[mGunIndex]->mGun->mClip && mGuns[mGunIndex]->mRemainingAmmo != 0) { SetState(RELOADING); mSoundId = gSfxManager->PlaySample(mGuns[mGunIndex]->mGun->mReloadSound,mX,mY); mNumDryFire = 0; return true; } return false; } //------------------------------------------------------------------------------------------------ void Person::Switch(int index) { if (mGuns[index] != NULL) { mGunIndex = index; if (mState == RELOADING) { //SetState(NORMAL); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } } else if (mState == ATTACKING) { //SetState(NORMAL); } mRecoilAngle = 0.0f; mNumDryFire = 0; SetState(SWITCHING); } } //------------------------------------------------------------------------------------------------ void Person::SwitchNext() { if (mState == RELOADING) { //SetState(NORMAL); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } } else if (mState == ATTACKING) { //SetState(NORMAL); } int gunindex = mGunIndex; for (int i=0; i<5; i++) { gunindex++; if (gunindex > 4) { gunindex = 0; } if (mGuns[gunindex] != NULL) break; } if (gunindex == mGunIndex) return; mGunIndex = gunindex; if (mGunIndex == PRIMARY) { gSfxManager->PlaySample(gDeploySound,mX,mY); } /*if (mGunIndex == PRIMARY) { if (mGuns[SECONDARY] != NULL) { mGunIndex = SECONDARY; } else { mGunIndex = KNIFE; } } else if (mGunIndex == SECONDARY) { if (mGuns[KNIFE] != NULL) { mGunIndex = KNIFE; } else { mGunIndex = PRIMARY; gSfxManager->PlaySample(gDeploySound,mX,mY); } } else if (mGunIndex == KNIFE) { if (mGuns[PRIMARY] != NULL) { mGunIndex = PRIMARY; gSfxManager->PlaySample(gDeploySound,mX,mY); } else if (mGuns[SECONDARY] != NULL) { mGunIndex = SECONDARY; } }*/ mRecoilAngle = 0.0f; mNumDryFire = 0; SetState(SWITCHING); } //------------------------------------------------------------------------------------------------ bool Person::PickUp(GunObject* gunobject) { if (gunobject->mGun->mType == PRIMARY) { if (mGuns[PRIMARY] == NULL) { mGuns[PRIMARY] = gunobject; gunobject->mOnGround = false; /*if (mState == RELOADING) { SetState(NORMAL); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } } mGunIndex = PRIMARY;*/ Switch(PRIMARY); gSfxManager->PlaySample(gPickUpSound, mX, mY); return true; } } else if (gunobject->mGun->mType == SECONDARY) { if (mGuns[SECONDARY] == NULL) { mGuns[SECONDARY] = gunobject; gunobject->mOnGround = false; if (mGuns[PRIMARY] == NULL) { //mGunIndex = SECONDARY; Switch(SECONDARY); } gSfxManager->PlaySample(gPickUpSound, mX, mY); return true; } } else if (gunobject->mGun->mType == KNIFE) { if (mGuns[KNIFE] == NULL) { mGuns[KNIFE] = gunobject; gunobject->mOnGround = false; return true; } } else if (gunobject->mGun->mType == GRENADE) { if (mGuns[GRENADE] == NULL) { mGuns[GRENADE] = gunobject; gunobject->mOnGround = false; if (mGuns[PRIMARY] == NULL && mGuns[SECONDARY] == NULL) { //mGunIndex = GRENADE; Switch(GRENADE); } gSfxManager->PlaySample(gPickUpSound, mX, mY); return true; } } return false; } //------------------------------------------------------------------------------------------------ bool Person::Drop(int index, float speed) { if (index >= 5) return false; if (index == KNIFE) return false; GunObject* gunobject = mGuns[index]; if (gunobject == NULL) return false; /*if (mState == RELOADING) { SetState(NORMAL); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } }*/ gunobject->mX = mX; gunobject->mY = mY; gunobject->mOldX = mX; gunobject->mOldY = mY; gunobject->mRotation = mRotation; gunobject->mAngle = mFacingAngle; gunobject->mSpeed = speed; gunobject->mOnGround = false; mGunObjects->push_back(gunobject); mGuns[index] = NULL; if (mGuns[PRIMARY] != NULL) { //mGunIndex = PRIMARY; Switch(PRIMARY); } else if (mGuns[SECONDARY] != NULL) { //mGunIndex = SECONDARY; Switch(SECONDARY); } else if (mGuns[GRENADE] != NULL) { //mGunIndex = GRENADE; Switch(GRENADE); } else if (mGuns[KNIFE] != NULL) { //mGunIndex = KNIFE; Switch(KNIFE); } //mRecoilAngle = 0.0f; //mNumDryFire = 0; return true; } //------------------------------------------------------------------------------------------------ void Person::RotateFacing(float theta) { float thetaTemp = mRotation + theta; if (thetaTemp > M_PI*2.0f) { // angles are in radian, so 2 PI is one full circle thetaTemp -= M_PI*2.0f; } else if (thetaTemp < 0) { thetaTemp += M_PI*2.0f; } mRotation = thetaTemp; thetaTemp = mFacingAngle + theta; if (thetaTemp > M_PI*2.0f) { // angles are in radian, so 2 PI is one full circle thetaTemp -= M_PI*2.0f; } else if (thetaTemp < 0) { thetaTemp += M_PI*2.0f; } mFacingAngle = thetaTemp; } //------------------------------------------------------------------------------------------------ void Person::SetMoveState(int state) { if (mMoveState != state) { mMoveState = state; } } //------------------------------------------------------------------------------------------------ void Person::SetState(int state) { if (mState != state) { mState = state; mStateTime = 0; if (mState == NORMAL || mState == SWITCHING) { if (mGunIndex == PRIMARY) { SetAnimation(ANIM_PRIMARY); } else if (mGunIndex == SECONDARY) { SetAnimation(ANIM_SECONDARY); } else if (mGunIndex == KNIFE) { SetAnimation(ANIM_KNIFE); } else if (mGunIndex == GRENADE) { SetAnimation(ANIM_GRENADE); } } else if (mState == ATTACKING) { if (mGunIndex == PRIMARY) { SetAnimation(ANIM_PRIMARY_FIRE); //mCurrentAnimation->Reset(); //mCurrentAnimation->Play(); mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mDelay); } else if (mGunIndex == SECONDARY) { SetAnimation(ANIM_SECONDARY_FIRE); //mCurrentAnimation->Reset(); //mCurrentAnimation->Play(); mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mDelay); } else if (mGunIndex == KNIFE) { SetAnimation(ANIM_KNIFE_SLASH); //mCurrentAnimation->Reset(); //mCurrentAnimation->Play(); mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mDelay); } else if (mGunIndex == GRENADE) { SetAnimation(ANIM_GRENADE_PULLBACK); } } else if (mState == RELOADING) { if (mGunIndex == PRIMARY) { SetAnimation(ANIM_PRIMARY_RELOAD); mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mReloadDelay); } else if (mGunIndex == SECONDARY) { SetAnimation(ANIM_SECONDARY_RELOAD); mCurrentAnimation->SetSpeed(1000.0f/mGuns[mGunIndex]->mGun->mReloadDelay); } } } if (mState == SWITCHING) { if (mGunIndex == PRIMARY) { SetAnimation(ANIM_PRIMARY); //mCurrentAnimation->SetSpeed(100.0f/(mGuns[mGunIndex]->mGun->mDelay*0.75f)); } else if (mGunIndex == SECONDARY) { SetAnimation(ANIM_SECONDARY); //mCurrentAnimation->SetSpeed(100.0f/(mGuns[mGunIndex]->mGun->mDelay*0.75f)); } else if (mGunIndex == KNIFE) { SetAnimation(ANIM_KNIFE); mCurrentAnimation->SetSpeed(1); } else if (mGunIndex == GRENADE) { SetAnimation(ANIM_GRENADE); mCurrentAnimation->SetSpeed(1); } mKeyFrame.angles[GUN] = mCurrentAnimation->GetKeyFrame(0)->angles[GUN]; } } //------------------------------------------------------------------------------------------------ void Person::SetAnimation(int animation) { if (mCurrentAnimation != mAnimations[animation]) { mCurrentAnimation->Reset(); mCurrentAnimation = mAnimations[animation]; mCurrentAnimation->Play(); } else { //mCurrentAnimation->Reset(); //mCurrentAnimation->Play(); } } //------------------------------------------------------------------------------------------------ void Person::SetTotalRotation(float theta) { mFacingAngle = theta; mLastFireAngle = theta-M_PI_2; mRotation = theta-M_PI_2; mAngle = theta; mWalkAngle = theta; } //------------------------------------------------------------------------------------------------ void Person::Die() { mStateTime = 0.0f; StopFire(); Drop(mGunIndex,0); Drop(GRENADE,0); if (mSoundId != -1) { mSoundSystem->StopSample(mSoundId); mSoundId = -1; } if (mGuns[PRIMARY] != NULL) { delete mGuns[PRIMARY]; mGuns[PRIMARY] = NULL; } if (mGuns[SECONDARY] != NULL) { delete mGuns[SECONDARY]; mGuns[SECONDARY] = NULL; } /*if (mGunIndex != KNIFE) { mGuns[mGunIndex] = NULL; }*/ if (mGuns[GRENADE] != NULL) { delete mGuns[GRENADE]; mGuns[GRENADE] = NULL; } mGunIndex = KNIFE; mNumDryFire = 0; gSfxManager->PlaySample(gDieSounds[rand()%3],mX,mY); SetState(DEAD); mFadeTime = 1000.0f; SetMoveState(NOTMOVING); mSpeed = 0.0f; } //------------------------------------------------------------------------------------------------ void Person::Reset() { //mX = mSpawn->x; //mY = mSpawn->y; //SetPosition(mSpawn->x,mSpawn->y); //mOldX = mSpawn->x; //mOldY = mSpawn->y; SetTotalRotation(M_PI_2); SetMoveState(NOTMOVING); mSpeed = 0.0f; mHealth = 100; if (mState == DEAD) { SetState(NORMAL); } if (mState == ATTACKING || mState == DRYFIRING) { SetState(NORMAL); } mIsActive = false; mIsFlashed = false; mIsFiring = false; mHasFired = false; mWalkState = WALK1; mWalkTime = 0.0f; mWalkAngle = 0.0f; mMuzzleFlashTime = 0.0f; mRadarTime = 0.0f; mHasFlag = false; mGunMode = 0; } void Person::TakeDamage(int damage) { if (mInvincibleTime > 0.0f) return; if (mState != DEAD) { SetMoveState(NOTMOVING); mSpeed *= 0.1f; mHealth -= damage; if (mHealth <= 0) { mHealth = 0; Die(); } } } void Person::ReceiveFlash(float intensity) { if (mInvincibleTime > 0.0f) return; mIsFlashed = true; mFlashTime = 15000.0f; if (intensity < 0.01f) { intensity = 0.01f; } mFlashIntensity = intensity; } void Person::SetQuads(JQuad* quads[], JQuad* deadquad) { for (int i=0; i<NUM_QUADS; i++) { mQuads[i] = quads[i]; } mDeadQuad = deadquad; } void Person::UpdateAngle(float &angle, float targetangle, float speed) { float diffangle = angle-targetangle; if (diffangle > M_PI) { diffangle -= 2*M_PI; } if (diffangle < -M_PI) { diffangle += 2*M_PI; } if (diffangle >= 0) { if (diffangle < speed) { angle = targetangle; } else { angle -= speed; } } else { if (diffangle > -speed) { angle = targetangle; } else { angle += speed; } } } void Person::Teleport(float x, float y) { mX = x; mY = y; mOldX = x; mOldY = y; mWalkX = x; mWalkY = y; }
25.756822
156
0.601034
MasterMenOfficial
dbdd4b085673934075be9f66452d9e3bcdda2ad9
1,514
cpp
C++
src/main/cpp/states/turret/ManualAim.cpp
Team302/2020InfiiniteRechargeImportedInto2021
cfdbcc78e3a83e57cb8a0acc894609a94ab57193
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/states/turret/ManualAim.cpp
Team302/2020InfiiniteRechargeImportedInto2021
cfdbcc78e3a83e57cb8a0acc894609a94ab57193
[ "BSD-3-Clause" ]
null
null
null
src/main/cpp/states/turret/ManualAim.cpp
Team302/2020InfiiniteRechargeImportedInto2021
cfdbcc78e3a83e57cb8a0acc894609a94ab57193
[ "BSD-3-Clause" ]
null
null
null
/*----------------------------------------------------------------------------*/ /* Copyright (c) 2018 FIRST. All Rights Reserved. */ /* Open Source Software - may be modified and shared by FRC teams. The code */ /* must be accompanied by the FIRST BSD license file in the root directory of */ /* the project. */ /*----------------------------------------------------------------------------*/ #include "states/turret/ManualAim.h" #include "subsys/MechanismFactory.h" #include "subsys/IMechanism.h" #include "subsys/Turret.h" #include "controllers/ControlData.h" #include "frc/smartdashboard/SmartDashboard.h" #include "gamepad/TeleopControl.h" ManualAim::ManualAim(ControlData* controlData) : m_controlData(controlData), m_atTarget(false) { auto factory = MechanismFactory::GetMechanismFactory(); m_turret = factory->GetIMechanism(MechanismTypes::TURRET); } void ManualAim::Init() { } void ManualAim::Run() { double val = TeleopControl::GetInstance()->GetAxisValue(TeleopControl::FUNCTION_IDENTIFIER::TURRET_MANUAL_AXIS); if (std::abs(val) < 0.04) { val = 0.0; } frc::SmartDashboard::PutNumber("Turret Joystick", val); m_turret->SetOutput(m_controlData->GetMode(), val * .75); //scaled to a percentage of a 45 degree turn //m_turret->SetOutput(ControlModes::POSITION_DEGREES, 0.0); m_atTarget = true; } bool ManualAim::AtTarget() const { return m_atTarget; }
34.409091
116
0.598415
Team302
dbdd6d99ee992b4585d632517f4f5fd627ded9f8
1,187
cpp
C++
oled/main.cpp
FaizalSupriadi/IPASS
a5543f5b6ddd5da799148f09d7e59ec14f2b14fa
[ "BSL-1.0" ]
null
null
null
oled/main.cpp
FaizalSupriadi/IPASS
a5543f5b6ddd5da799148f09d7e59ec14f2b14fa
[ "BSL-1.0" ]
null
null
null
oled/main.cpp
FaizalSupriadi/IPASS
a5543f5b6ddd5da799148f09d7e59ec14f2b14fa
[ "BSL-1.0" ]
null
null
null
#include "oled.hpp" #include "ball.hpp" #include <array> int main( void ){ namespace target = hwlib::target; auto scl = target::pin_oc( target::pins::scl ); auto sda = target::pin_oc( target::pins::sda ); auto i2c_bus = hwlib::i2c_bus_bit_banged_scl_sda( scl,sda ); auto display = oled( i2c_bus, 0x3c ); hwlib::xy location_ball( 0,32 ); hwlib::xy ball_speed( 5, 0 ); line top( display, hwlib::xy( 0, 0 ), hwlib::xy( 128, 0 ) ); line right( display, hwlib::xy( 127, 0 ), hwlib::xy( 127, 63 ) ); line bottom( display, hwlib::xy( 0, 63 ), hwlib::xy( 127, 63 ) ); line left( display, hwlib::xy( 0, 0 ), hwlib::xy( 0, 63 ) ); ball b( display, location_ball, 4, ball_speed ); std::array< drawable *, 5 > objects = { &b, &top,&right,&bottom,&left}; for(;;){ display.clear(); for( auto & p : objects ){ p->draw(); } display.flush(); hwlib::wait_ms( 100 ); for( auto & p : objects ){ p->update(); } for( auto & p : objects ){ for( auto & other : objects ){ p->interact( *other, location_ball ); } } } }
26.377778
74
0.528222
FaizalSupriadi
dbe03d19ea3fb4556459dcbde7ba94c8739445a5
1,895
cpp
C++
main.cpp
nks5117/MyCalc
f2fa2b344da94065239cbd09ca85b1c25f00290d
[ "MIT" ]
null
null
null
main.cpp
nks5117/MyCalc
f2fa2b344da94065239cbd09ca85b1c25f00290d
[ "MIT" ]
null
null
null
main.cpp
nks5117/MyCalc
f2fa2b344da94065239cbd09ca85b1c25f00290d
[ "MIT" ]
null
null
null
// main.cpp // Copyright (c) 2018 Ni Kesu. All rights reserved. #include <iostream> #include <string> #include <vector> #include <ctime> #include "bigint.h" #include "token.h" #include "expression.h" #include "variable.h" #ifdef TIME #include <ctime> #endif using std::cin; using std::cout; using std::endl; using std::cerr; using std::string; #define PROMPT '$' std::vector<Variable> variableList; void title() { cout << "MyCalc v1.5.0\n"; cout << "[Type \"exit\" to exit]\n"; } int main() { title(); variableList.push_back(Variable("ans", V_NA, ZERO, 0.0)); variableList.push_back(Variable("pi", V_DOUBLE, ZERO, 3.1415926535897)); variableList.push_back(Variable("e", V_DOUBLE, ZERO, 2.7182818284590)); variableList.push_back(Variable("c", V_BIGINT, BigInt(299792458), 0.0)); cout.precision(10); Value ans; while (1) { cout << PROMPT << ' '; string s; getline(cin, s); if (s == "exit") { break; } bool showAnswer = (s[s.size() - 1] != ';'); if (!showAnswer) { s.erase(s.end()-1); } #ifdef TIME auto startTime = clock(); #endif ans = Expression(s).evaluate(); if (showAnswer) { cout << "ans =\n\n "; } if (ans.type() == V_DOUBLE) { if (showAnswer) { cout << ans.doubleValue() << endl << endl; } *(variableList[0].doubleValue()) = ans.doubleValue(); } else if(ans.type() == V_BIGINT) { if (showAnswer) { cout << ans.intValue().toString() << endl << endl; #ifdef TIME auto endTime = clock(); cout << "total use " << (double)(endTime - startTime) / CLOCKS_PER_SEC << 's' << endl << endl; #endif } *(variableList[0].intValue()) = ans.intValue(); } variableList[0].setType(ans.type()); } return 0; }
21.055556
79
0.553562
nks5117
dbe457c9850da84925d57176ca89b390a9d32715
376
cpp
C++
dp/longest-increasing-subsequence.cpp
beet-aizu/library-2
51579421d2c695ae298eed3943ca90f5224f768a
[ "Unlicense" ]
null
null
null
dp/longest-increasing-subsequence.cpp
beet-aizu/library-2
51579421d2c695ae298eed3943ca90f5224f768a
[ "Unlicense" ]
null
null
null
dp/longest-increasing-subsequence.cpp
beet-aizu/library-2
51579421d2c695ae298eed3943ca90f5224f768a
[ "Unlicense" ]
1
2020-10-14T20:51:44.000Z
2020-10-14T20:51:44.000Z
template< typename T > size_t longest_increasing_subsequence(const vector< T > &a, bool strict) { vector< T > lis; for(auto &p : a) { typename vector< T >::iterator it; if(strict) it = lower_bound(begin(lis), end(lis), p); else it = upper_bound(begin(lis), end(lis), p); if(end(lis) == it) lis.emplace_back(p); else *it = p; } return lis.size(); }
28.923077
74
0.62234
beet-aizu
dbe77bfa29b3acaa6bab9cfc57dfee288b284139
6,127
cpp
C++
src/services/pcn-nat/src/RuleDnatEntry.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
1
2020-07-16T04:49:29.000Z
2020-07-16T04:49:29.000Z
src/services/pcn-nat/src/RuleDnatEntry.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
src/services/pcn-nat/src/RuleDnatEntry.cpp
mbertrone/polycube
b35a6aa13273c000237d53c5f1bf286f12e4b9bd
[ "ECL-2.0", "Apache-2.0" ]
null
null
null
/* * Copyright 2018 The Polycube Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Modify these methods with your own implementation #include "RuleDnatEntry.h" #include "Nat.h" using namespace polycube::service; RuleDnatEntry::RuleDnatEntry(RuleDnat &parent, const RuleDnatEntryJsonObject &conf) : parent_(parent) { logger()->info("Creating RuleDnatEntry instance: {0} -> {1}", conf.getExternalIp(), conf.getInternalIp()); update(conf); } RuleDnatEntry::~RuleDnatEntry() {} void RuleDnatEntry::update(const RuleDnatEntryJsonObject &conf) { // This method updates all the object/parameter in RuleDnatEntry object // specified in the conf JsonObject. // You can modify this implementation. if (conf.externalIpIsSet()) { setExternalIp(conf.getExternalIp()); } if (conf.internalIpIsSet()) { setInternalIp(conf.getInternalIp()); } } RuleDnatEntryJsonObject RuleDnatEntry::toJsonObject() { RuleDnatEntryJsonObject conf; conf.setId(getId()); conf.setExternalIp(getExternalIp()); conf.setInternalIp(getInternalIp()); return conf; } void RuleDnatEntry::create(RuleDnat &parent, const uint32_t &id, const RuleDnatEntryJsonObject &conf) { // This method creates the actual RuleDnatEntry object given thee key param. // Please remember to call here the create static method for all sub-objects // of RuleDnatEntry. auto newRule = new RuleDnatEntry(parent, conf); if (newRule == nullptr) { // Totally useless, but it is needed to avoid the compiler making wrong // assumptions and reordering throw std::runtime_error("I won't be thrown"); } // Check for duplicates for (int i = 0; i < parent.rules_.size(); i++) { auto rule = parent.rules_[i]; if (rule->getExternalIp() == newRule->getExternalIp()) { throw std::runtime_error("Cannot insert duplicate mapping"); } } parent.rules_.resize(parent.rules_.size() + 1); parent.rules_[parent.rules_.size() - 1].reset(newRule); parent.rules_[parent.rules_.size() - 1]->id = id; // Inject rule in the datapath table newRule->injectToDatapath(); } std::shared_ptr<RuleDnatEntry> RuleDnatEntry::getEntry(RuleDnat &parent, const uint32_t &id) { // This method retrieves the pointer to RuleDnatEntry object specified by its // keys. for (int i = 0; i < parent.rules_.size(); i++) { if (parent.rules_[i]->id == id) { return parent.rules_[i]; } } throw std::runtime_error("There is no rule " + id); } void RuleDnatEntry::removeEntry(RuleDnat &parent, const uint32_t &id) { // This method removes the single RuleDnatEntry object specified by its keys. // Remember to call here the remove static method for all-sub-objects of // RuleDnatEntry. if (parent.rules_.size() < id || !parent.rules_[id]) { throw std::runtime_error("There is no rule " + id); } for (int i = 0; i < parent.rules_.size(); i++) { if (parent.rules_[i]->id == id) { // Remove rule from data path parent.rules_[i]->removeFromDatapath(); break; } } for (uint32_t i = id; i < parent.rules_.size() - 1; ++i) { parent.rules_[i] = parent.rules_[i + 1]; parent.rules_[i]->id = i; } parent.rules_.resize(parent.rules_.size() - 1); parent.logger()->info("Removed DNAT entry {0}", id); } std::vector<std::shared_ptr<RuleDnatEntry>> RuleDnatEntry::get( RuleDnat &parent) { // This methods get the pointers to all the RuleDnatEntry objects in RuleDnat. std::vector<std::shared_ptr<RuleDnatEntry>> rules; for (auto it = parent.rules_.begin(); it != parent.rules_.end(); ++it) { if (*it) { rules.push_back(*it); } } return rules; } void RuleDnatEntry::remove(RuleDnat &parent) { // This method removes all RuleDnatEntry objects in RuleDnat. // Remember to call here the remove static method for all-sub-objects of // RuleDnatEntry. RuleDnat::removeEntry(parent.parent_); } uint32_t RuleDnatEntry::getId() { // This method retrieves the id value. return id; } std::string RuleDnatEntry::getExternalIp() { // This method retrieves the externalIp value. struct IpAddr addr = {externalIp, 32}; return addr.toString(); } void RuleDnatEntry::setExternalIp(const std::string &value) { // This method set the externalIp value. struct IpAddr addr; addr.fromString(value); this->externalIp = addr.ip; } std::string RuleDnatEntry::getInternalIp() { // This method retrieves the internalIp value. struct IpAddr addr = {internalIp, 32}; return addr.toString(); } void RuleDnatEntry::setInternalIp(const std::string &value) { // This method set the internalIp value. struct IpAddr addr; addr.fromString(value); this->internalIp = addr.ip; } std::shared_ptr<spdlog::logger> RuleDnatEntry::logger() { return parent_.logger(); } void RuleDnatEntry::injectToDatapath() { auto dp_rules = parent_.parent_.getParent().get_hash_table<dp_k, dp_v>( "dp_rules", 0, ProgramType::INGRESS); dp_k key{ .mask = 32, .external_ip = externalIp, .external_port = 0, .proto = 0, }; dp_v value{ .internal_ip = internalIp, .internal_port = 0, .entry_type = (uint8_t)NattingTableOriginatingRuleEnum::DNAT, }; dp_rules.set(key, value); } void RuleDnatEntry::removeFromDatapath() { auto dp_rules = parent_.parent_.getParent().get_hash_table<dp_k, dp_v>( "dp_rules", 0, ProgramType::INGRESS); dp_k key{ .mask = 32, .external_ip = externalIp, .external_port = 0, .proto = 0, }; dp_rules.remove(key); }
30.944444
80
0.681573
mbertrone
dbebb4e9cbedf7bafba78905508e2ea789ac01fb
1,418
cpp
C++
lib/colortwist_ipp.cpp
ptahmose/colortwist
6234d952d2550ad8d4f1fdd89f351d06fcdc78db
[ "BSD-2-Clause" ]
null
null
null
lib/colortwist_ipp.cpp
ptahmose/colortwist
6234d952d2550ad8d4f1fdd89f351d06fcdc78db
[ "BSD-2-Clause" ]
1
2020-10-25T19:53:38.000Z
2020-10-25T19:53:38.000Z
lib/colortwist_ipp.cpp
ptahmose/colortwist
6234d952d2550ad8d4f1fdd89f351d06fcdc78db
[ "BSD-2-Clause" ]
null
null
null
#include "colortwist.h" #include "colortwist_config.h" #if COLORTWISTLIB_HASIPP #include "utils.h" #include <ipp.h> using namespace colortwist; StatusCode colorTwistRGB48_IPP(const void* pSrc, std::uint32_t width, std::uint32_t height, int strideSrc, void* pDst, std::int32_t strideDst, const float* twistMatrix) { StatusCode rc = checkArgumentsRgb48(pSrc, width, strideSrc, pDst, strideDst, twistMatrix); if (rc != colortwist::StatusCode::OK) { return rc; } IppStatus status = ippiColorTwist32f_16u_C3R((const Ipp16u*)pSrc, strideSrc, (Ipp16u*)pDst, strideDst, IppiSize{ (int)width,(int)height }, (const Ipp32f(*)[4]) twistMatrix); return (status == ippStsNoErr || status == ippStsNoOperation) ? StatusCode::OK : StatusCode::UnspecifiedError; } colortwist::StatusCode colorTwistRGB24_IPP(const void* pSrc, uint32_t width, uint32_t height, int strideSrc, void* pDst, int strideDst, const float* twistMatrix) { StatusCode rc = checkArgumentsRgb24(pSrc, width, strideSrc, pDst, strideDst, twistMatrix); if (rc != colortwist::StatusCode::OK) { return rc; } IppStatus status = ippiColorTwist32f_8u_C3R((const Ipp8u*)pSrc, strideSrc, (Ipp8u*)pDst, strideDst, IppiSize{ (int)width,(int)height }, (const Ipp32f(*)[4]) twistMatrix); return (status == ippStsNoErr || status == ippStsNoOperation) ? StatusCode::OK : StatusCode::UnspecifiedError; } #endif
39.388889
177
0.723554
ptahmose
dbed25ed91935f7368b91c880e51a28ea3ba8fba
6,823
cpp
C++
modules/tracktion_engine/model/edit/tracktion_PitchSequence.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/model/edit/tracktion_PitchSequence.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
modules/tracktion_engine/model/edit/tracktion_PitchSequence.cpp
jbloit/tracktion_engine
b3fa7d6a3a404f64ae419abdf9c801d672cffb16
[ "MIT", "Unlicense" ]
null
null
null
/* ,--. ,--. ,--. ,--. ,-' '-.,--.--.,--,--.,---.| |,-.,-' '-.`--' ,---. ,--,--, Copyright 2018 '-. .-'| .--' ,-. | .--'| /'-. .-',--.| .-. || \ Tracktion Software | | | | \ '-' \ `--.| \ \ | | | |' '-' '| || | Corporation `---' `--' `--`--'`---'`--'`--' `---' `--' `---' `--''--' www.tracktion.com Tracktion Engine uses a GPL/commercial licence - see LICENCE.md for details. */ namespace tracktion_engine { struct PitchSequence::PitchList : public ValueTreeObjectList<PitchSetting>, private juce::AsyncUpdater { PitchList (PitchSequence& s, const juce::ValueTree& parentTree) : ValueTreeObjectList<PitchSetting> (parentTree), pitchSequence (s) { rebuildObjects(); } ~PitchList() override { freeObjects(); } bool isSuitableType (const juce::ValueTree& v) const override { return v.hasType (IDs::PITCH); } PitchSetting* createNewObject (const juce::ValueTree& v) override { auto t = new PitchSetting (pitchSequence.getEdit(), v); t->incReferenceCount(); return t; } void deleteObject (PitchSetting* t) override { jassert (t != nullptr); t->decReferenceCount(); } void newObjectAdded (PitchSetting*) override { sendChange(); } void objectRemoved (PitchSetting*) override { sendChange(); } void objectOrderChanged() override { sendChange(); } void valueTreePropertyChanged (juce::ValueTree&, const juce::Identifier&) override { sendChange(); } void sendChange() { if (! pitchSequence.getEdit().isLoading()) triggerAsyncUpdate(); } void handleAsyncUpdate() override { pitchSequence.getEdit().sendTempoOrPitchSequenceChangedUpdates(); } PitchSequence& pitchSequence; }; //============================================================================== PitchSequence::PitchSequence() {} PitchSequence::~PitchSequence() {} Edit& PitchSequence::getEdit() const { jassert (edit != nullptr); return *edit; } juce::UndoManager* PitchSequence::getUndoManager() const { return &getEdit().getUndoManager(); } void PitchSequence::clear() { if (auto first = getPitch (0)) { auto pitch = first->getPitch(); state.removeAllChildren (getUndoManager()); insertPitch (0, pitch); } else { jassertfalse; } } void PitchSequence::initialise (Edit& ed, const juce::ValueTree& v) { edit = &ed; state = v; list = std::make_unique<PitchList> (*this, state); if (getNumPitches() == 0) insertPitch (0, 60); sortEvents(); } void PitchSequence::freeResources() { list.reset(); } void PitchSequence::copyFrom (const PitchSequence& other) { copyValueTree (state, other.state, nullptr); } const juce::Array<PitchSetting*>& PitchSequence::getPitches() const { return list->objects; } int PitchSequence::getNumPitches() const { return list->objects.size(); } PitchSetting* PitchSequence::getPitch (int index) const { return list->objects[index]; } PitchSetting& PitchSequence::getPitchAt (double time) const { return *list->objects[indexOfPitchAt (time)]; } PitchSetting& PitchSequence::getPitchAtBeat (double beat) const { for (int i = list->objects.size(); --i > 0;) { auto p = list->objects.getUnchecked (i); if (p->getStartBeatNumber() <= beat) return *p; } jassert (list->size() > 0); return *list->objects.getFirst(); } int PitchSequence::indexOfPitchAt (double t) const { for (int i = list->objects.size(); --i > 0;) if (list->objects.getUnchecked (i)->getPosition().getStart() <= t) return i; jassert (list->size() > 0); return 0; } int PitchSequence::indexOfNextPitchAt (double t) const { for (int i = 0; i < list->objects.size(); ++i) if (list->objects.getUnchecked (i)->getPosition().getStart() >= t) return i; jassert (list->size() > 0); return list->objects.size(); } int PitchSequence::indexOfPitch (const PitchSetting* pitchSetting) const { return list->objects.indexOf ((PitchSetting*) pitchSetting); } PitchSetting::Ptr PitchSequence::insertPitch (double time) { return insertPitch (edit->tempoSequence.timeToBeats (time), -1); } PitchSetting::Ptr PitchSequence::insertPitch (double beatNum, int pitch) { int newIndex = -1; if (list->size() > 0) { auto& prev = getPitchAtBeat (beatNum); // don't add in the same place as another one if (prev.getStartBeatNumber() == beatNum) { if (pitch >= 0) prev.setPitch (pitch); return prev; } if (pitch < 0) pitch = prev.getPitch(); newIndex = indexOfPitch (&prev) + 1; } auto v = createValueTree (IDs::PITCH, IDs::startBeat, beatNum, IDs::pitch, pitch); if (newIndex < 0) newIndex = list->objects.size(); state.addChild (v, newIndex, getUndoManager()); jassert (list->objects[newIndex]->state == v); return list->objects[newIndex]; } void PitchSequence::movePitchStart (PitchSetting& p, double deltaBeats, bool snapToBeat) { auto index = indexOfPitch (&p); if (index > 0 && deltaBeats != 0) { if (auto t = getPitch (index)) { t->startBeat.forceUpdateOfCachedValue(); auto newBeat = t->getStartBeat() + deltaBeats; t->setStartBeat (juce::jlimit (0.0, 1e10, snapToBeat ? juce::roundToInt (newBeat) : newBeat)); } } } void PitchSequence::insertSpaceIntoSequence (double time, double amountOfSpaceInSeconds, bool snapToBeat) { // there may be a temp change at this time so we need to find the tempo to the left of it hence the nudge time = time - 0.00001; auto beatsToInsert = getEdit().tempoSequence.getBeatsPerSecondAt (time) * amountOfSpaceInSeconds; auto endIndex = indexOfNextPitchAt (time); for (int i = getNumPitches(); --i >= endIndex;) movePitchStart (*getPitch (i), beatsToInsert, snapToBeat); } void PitchSequence::sortEvents() { struct PitchSorter { static int compareElements (const juce::ValueTree& p1, const juce::ValueTree& p2) noexcept { const double beat1 = p1[IDs::startBeat]; const double beat2 = p2[IDs::startBeat]; return beat1 < beat2 ? -1 : (beat1 > beat2 ? 1 : 0); } }; PitchSorter sorter; state.sort (sorter, getUndoManager(), true); } }
27.623482
120
0.5757
jbloit
dbf0eced071dc9d3cb472b01f0c0649e75d58148
2,709
cpp
C++
Source/Ui/TreeItems/OnexTreeZlibItem.cpp
Pumbaa98/OnexExplorer
eaee2aa9f0e71b9960da586f425f79e628013021
[ "BSL-1.0" ]
14
2019-06-19T18:49:55.000Z
2020-05-30T12:09:12.000Z
Source/Ui/TreeItems/OnexTreeZlibItem.cpp
Pumbaa98/OnexExplorer
eaee2aa9f0e71b9960da586f425f79e628013021
[ "BSL-1.0" ]
34
2019-06-21T20:19:11.000Z
2019-12-10T22:16:54.000Z
Source/Ui/TreeItems/OnexTreeZlibItem.cpp
Pumba98/OnexExplorer
eaee2aa9f0e71b9960da586f425f79e628013021
[ "BSL-1.0" ]
3
2020-08-30T03:09:12.000Z
2021-12-26T18:01:20.000Z
#include "OnexTreeZlibItem.h" #include <QDate> OnexTreeZlibItem::OnexTreeZlibItem(const QString &name, NosZlibOpener *opener, QByteArray content, int id, int creationDate, bool compressed) : OnexTreeItem(name, opener, content), id(id), creationDate(creationDate), compressed(compressed) { if (creationDate == 0) setCreationDate(QDate::currentDate().toString("dd/MM/yyyy"), true); } OnexTreeZlibItem::~OnexTreeZlibItem() = default; int OnexTreeZlibItem::getId() { return id; } int OnexTreeZlibItem::getCreationDate() { return creationDate; } QString OnexTreeZlibItem::getDateAsString() { int year = (getCreationDate() & 0xFFFF0000) >> 0x10; int month = (getCreationDate() & 0xFF00) >> 0x08; int day = getCreationDate() & 0xFF; return QString("%1/%2/%3").arg(day, 2, 16, QChar('0')).arg(month, 2, 16, QChar('0')).arg(year, 4, 16, QChar('0')); } bool OnexTreeZlibItem::isCompressed() { return compressed; } void OnexTreeZlibItem::setName(QString name) { OnexTreeItem::setName(name); setId(name.toInt(), true); } void OnexTreeZlibItem::setId(int id, bool update) { this->id = id; OnexTreeItem::setName(QString::number(id)); if (update) emit changeSignal("ID", id); } void OnexTreeZlibItem::setCreationDate(const QString &date, bool update) { QStringList parts = date.split("/", QString::SplitBehavior::SkipEmptyParts); if (parts.size() != 3) this->creationDate = 0; else { int year = parts[2].toInt(nullptr, 16) << 0x10; int month = parts[1].toInt(nullptr, 16) << 0x08; int day = parts[0].toInt(nullptr, 16); this->creationDate = year + month + day; } if (update) emit changeSignal("Date", getDateAsString()); } void OnexTreeZlibItem::setCompressed(bool compressed, bool update) { this->compressed = compressed; if (update) emit changeSignal("isCompressed", compressed); } FileInfo *OnexTreeZlibItem::generateInfos() { auto *infos = OnexTreeItem::generateInfos(); if (getId() == -1) { infos->addStringLineEdit("Header", QString::fromUtf8(getContent(), getContent().size()))->setEnabled(false); } else { connect(infos->addIntLineEdit("ID", getId()), &QLineEdit::textChanged, [=](const QString &value) { setId(value.toInt()); }); connect(infos->addStringLineEdit("Date", getDateAsString()), &QLineEdit::textChanged, [=](const QString &value) { setCreationDate(value); }); connect(infos->addCheckBox("isCompressed", isCompressed()), &QCheckBox::clicked, [=](const bool value) { setCompressed(value); }); } return infos; }
34.291139
141
0.647471
Pumbaa98
dbf3ef314931c15334401a0c51b45759e4e63f13
458
hh
C++
include/Bina_RunAction.hh
fenu-exp/BINA.simulation
11c32e5abcd117a9d79d550d8d90028a0cc05835
[ "MIT" ]
null
null
null
include/Bina_RunAction.hh
fenu-exp/BINA.simulation
11c32e5abcd117a9d79d550d8d90028a0cc05835
[ "MIT" ]
null
null
null
include/Bina_RunAction.hh
fenu-exp/BINA.simulation
11c32e5abcd117a9d79d550d8d90028a0cc05835
[ "MIT" ]
null
null
null
#ifndef Bina_RunAction_h #define Bina_RunAction_h 1 #include "G4UserRunAction.hh" #include "globals.hh" #include "time.h" #include "g4root.hh" class G4Run; class Bina_RunAction : public G4UserRunAction { public: Bina_RunAction(bool); virtual ~Bina_RunAction(); virtual void BeginOfRunAction(const G4Run* ); virtual void EndOfRunAction(const G4Run* ); bool root=false; private: clock_t fbegin; clock_t fend; }; #endif
17.615385
49
0.716157
fenu-exp
dbf4b2944c3340d632004a6f1f5d4e84cfd5a1b5
2,659
cpp
C++
Quanta/Source/Graphics/Imaging/Image32.cpp
thedoctorquantum/Quanta
c952c8ca0832f978ea1fc1aa9e9a840c500977a3
[ "MIT" ]
null
null
null
Quanta/Source/Graphics/Imaging/Image32.cpp
thedoctorquantum/Quanta
c952c8ca0832f978ea1fc1aa9e9a840c500977a3
[ "MIT" ]
null
null
null
Quanta/Source/Graphics/Imaging/Image32.cpp
thedoctorquantum/Quanta
c952c8ca0832f978ea1fc1aa9e9a840c500977a3
[ "MIT" ]
null
null
null
#include <Quanta/Graphics/Imaging/Image32.h> #include <stb_image.h> #include "../../Debugging/Validation.h" namespace Quanta { Image32::Image32(const USize width, const USize height) { DEBUG_ASSERT(width != 0); DEBUG_ASSERT(height != 0); data = new Color32[width * height]; this->width = width; this->height = height; } Image32::Image32(Color32* const data, const USize width, const USize height) { DEBUG_ASSERT(data != nullptr); DEBUG_ASSERT(width != 0); DEBUG_ASSERT(height != 0); this->data = data; this->width = width; this->height = height; } Image32::~Image32() { delete[] data; } Image32::Image32(Image32&& other) noexcept { if (this == &other) return; data = other.data; width = other.width; height = other.height; other.data = nullptr; other.width = 0; other.height = 0; } std::shared_ptr<Image32> Image32::FromFile(const std::string& filepath) { int width = 0; int height = 0; int channels = 0; stbi_uc* const data = stbi_load(filepath.c_str(), &width, &height, &channels, STBI_rgb_alpha); DEBUG_ASSERT(data != nullptr); return std::make_shared<Image32>(reinterpret_cast<Color32*>(data), width, height); } Image32& Image32::operator=(Image32&& other) noexcept { if (this == &other) return *this; delete[] data; data = other.data; width = other.width; height = other.height; other.data = nullptr; other.width = 0; other.height = 0; return *this; } Color32& Image32::operator[](const USize index) { DEBUG_ASSERT(index < width * height); return data[index]; } const Color32& Image32::operator[](const USize index) const { DEBUG_ASSERT(index < width * height); return data[index]; } Color32& Image32::operator()(const USize x, const USize y) { DEBUG_ASSERT(x < width); DEBUG_ASSERT(y < height); return data[x + width * y]; } const Color32& Image32::operator()(const USize x, const USize y) const { return this->operator()(x, y); } const Color32* Image32::GetData() const { return data; } Color32* Image32::GetData() { return data; } USize Image32::GetWidth() const { return width; } USize Image32::GetHeight() const { return height; } }
21.443548
102
0.547574
thedoctorquantum
dbfa995e7c7b58d71b777f59ac46aafc816002a0
934
cpp
C++
cpp/abc182_c/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
cpp/abc182_c/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
cpp/abc182_c/main.cpp
kokosabu/atcoder
8d512587d234eb45941a2f6341c4dd003e6c9ad3
[ "Apache-2.0" ]
null
null
null
#include <iostream> #include <cmath> using namespace std; int main() { string N; cin >> N; int max = 0; for(int i = 0; i < N.size(); i++) { max += N[i] - '0'; } if(max%3 == 0) { cout << 0 << endl; return 0; } int min_count = 20; for(int i = 1; i < pow(2, N.size())-1; i++) { int count = 0; int sum = max; int digit = 1; int j = i; while(j) { if((j&1) == 1) { sum -= N[N.size()-digit] - '0'; count += 1; // if(count >= min_count) { // break; // } } j >>= 1; digit += 1; } if(count < min_count && sum%3 == 0) { min_count = count; } } if(min_count == 20) { cout << -1 << endl; } else { cout << min_count << endl; } return 0; }
18.68
49
0.347966
kokosabu
dbffda099bb561610ccce893764c56a956320804
23,298
hpp
C++
src/metadata.hpp
olivia76/cpp-sas7bdat
1cd22561a13ee3df6bcec0b057f928de2014b81f
[ "Apache-2.0" ]
4
2021-12-23T13:24:03.000Z
2022-02-24T10:20:12.000Z
src/metadata.hpp
olivia76/cpp-sas7bdat
1cd22561a13ee3df6bcec0b057f928de2014b81f
[ "Apache-2.0" ]
6
2022-02-23T14:05:53.000Z
2022-03-17T13:47:46.000Z
src/metadata.hpp
olivia76/cpp-sas7bdat
1cd22561a13ee3df6bcec0b057f928de2014b81f
[ "Apache-2.0" ]
null
null
null
/** * \file src/metadata.hpp * * \brief Metadata reading * * \author Olivia Quinet */ #ifndef _CPP_SAS7BDAT_SRC_METADATA_HPP_ #define _CPP_SAS7BDAT_SRC_METADATA_HPP_ #include "formatters.hpp" #include "page.hpp" namespace cppsas7bdat { namespace INTERNAL { constexpr const std::string_view COLUMN_DATETIME_FORMAT[] = { "DATETIME", "DTWKDATX", "B8601DN", "B8601DT", "B8601DX", "B8601DZ", "B8601LX", "E8601DN", "E8601DT", "E8601DX", "E8601DZ", "E8601LX", "DATEAMPM", "DTDATE", "DTMONYY", "DTMONYY", "DTWKDATX", "DTYEAR", "TOD", "MDYAMPM"}; constexpr const std::string_view COLUMN_DATE_FORMAT[] = { "DATE", "DAY", "DDMMYY", "DOWNAME", "JULDAY", "JULIAN", "MMDDYY", "MMYY", "MMYYC", "MMYYD", "MMYYP", "MMYYS", "MMYYN", "MONNAME", "MONTH", "MONYY", "QTR", "QTRR", "NENGO", "WEEKDATE", "WEEKDATX", "WEEKDAY", "WEEKV", "WORDDATE", "WORDDATX", "YEAR", "YYMM", "YYMMC", "YYMMD", "YYMMP", "YYMMS", "YYMMN", "YYMON", "YYMMDD", "YYQ", "YYQC", "YYQD", "YYQP", "YYQS", "YYQN", "YYQR", "YYQRC", "YYQRD", "YYQRP", "YYQRS", "YYQRN", "YYMMDDP", "YYMMDDC", "E8601DA", "YYMMDDN", "MMDDYYC", "MMDDYYS", "MMDDYYD", "YYMMDDS", "B8601DA", "DDMMYYN", "YYMMDDD", "DDMMYYB", "DDMMYYP", "MMDDYYP", "YYMMDDB", "MMDDYYN", "DDMMYYC", "DDMMYYD", "DDMMYYS", "MINGUO"}; constexpr const std::string_view COLUMN_TIME_FORMAT[] = {"TIME"}; template <Format _format> struct METADATA_CONSTANT; template <> struct METADATA_CONSTANT<Format::bit64> { static constexpr const size_t lcs_offset = 682; static constexpr const size_t lcp_offset = 706; static constexpr const size_t compression_offset = 20; static constexpr BYTE ROW_SIZE_SUBHEADER[][8] = { {0x00, 0x00, 0x00, 0x00, 0xF7, 0xF7, 0xF7, 0xF7}, {0xF7, 0xF7, 0xF7, 0xF7, 0x00, 0x00, 0x00, 0x00}}; static constexpr BYTE COLUMN_SIZE_SUBHEADER[][8] = { {0x00, 0x00, 0x00, 0x00, 0xF6, 0xF6, 0xF6, 0xF6}, {0xF6, 0xF6, 0xF6, 0xF6, 0x00, 0x00, 0x00, 0x00}}; static constexpr BYTE SUBHEADER_COUNTS_SUBHEADER[][8] = { {0x00, 0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC, 0x00}}; static constexpr BYTE COLUMN_TEXT_SUBHEADER[][8] = { {0xFD, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFD}}; static constexpr BYTE COLUMN_NAME_SUBHEADER[][8] = { {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}}; static constexpr BYTE COLUMN_ATTRIBUTES_SUBHEADER[][8] = { {0xFC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFC}}; static constexpr BYTE FORMAT_AND_LABEL_SUBHEADER[][8] = { {0xFE, 0xFB, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFB, 0xFE}}; static constexpr BYTE COLUMN_LIST_SUBHEADER[][8] = { {0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFE}}; }; template <> struct METADATA_CONSTANT<Format::bit32> { static constexpr const size_t lcs_offset = 354; static constexpr const size_t lcp_offset = 378; static constexpr const size_t compression_offset = 16; static constexpr BYTE ROW_SIZE_SUBHEADER[][4] = {{0xF7, 0xF7, 0xF7, 0xF7}}; static constexpr BYTE COLUMN_SIZE_SUBHEADER[][4] = {{0xF6, 0xF6, 0xF6, 0xF6}}; static constexpr BYTE SUBHEADER_COUNTS_SUBHEADER[][4] = { {0x00, 0xFC, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFC, 0x00}}; static constexpr BYTE COLUMN_TEXT_SUBHEADER[][4] = {{0xFD, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFD}}; static constexpr BYTE COLUMN_NAME_SUBHEADER[][4] = {{0xFF, 0xFF, 0xFF, 0xFF}}; static constexpr BYTE COLUMN_ATTRIBUTES_SUBHEADER[][4] = { {0xFC, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFC}}; static constexpr BYTE FORMAT_AND_LABEL_SUBHEADER[][4] = { {0xFE, 0xFB, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFB, 0xFE}}; static constexpr BYTE COLUMN_LIST_SUBHEADER[][4] = {{0xFE, 0xFF, 0xFF, 0xFF}, {0xFF, 0xFF, 0xFF, 0xFE}}; }; template <typename _DataSource, Endian _endian, Format _format> struct READ_METADATA : public READ_PAGE<_DataSource, _endian, _format>, public METADATA_CONSTANT<_format> { using DataSource = _DataSource; constexpr static auto endian = _endian; constexpr static auto format = _format; using CBUFFER = INTERNAL::BUFFER<_endian, _format>; constexpr static size_t integer_size = CBUFFER::integer_size; using METADATA_CONSTANT<_format>::lcs_offset; using METADATA_CONSTANT<_format>::lcp_offset; using METADATA_CONSTANT<_format>::compression_offset; using METADATA_CONSTANT<_format>::ROW_SIZE_SUBHEADER; using METADATA_CONSTANT<_format>::COLUMN_SIZE_SUBHEADER; using METADATA_CONSTANT<_format>::SUBHEADER_COUNTS_SUBHEADER; using METADATA_CONSTANT<_format>::COLUMN_TEXT_SUBHEADER; using METADATA_CONSTANT<_format>::COLUMN_NAME_SUBHEADER; using METADATA_CONSTANT<_format>::COLUMN_ATTRIBUTES_SUBHEADER; using METADATA_CONSTANT<_format>::FORMAT_AND_LABEL_SUBHEADER; using METADATA_CONSTANT<_format>::COLUMN_LIST_SUBHEADER; static constexpr const char RLE_COMPRESSION[] = "SASYZCRL"; static constexpr const char RDC_COMPRESSION[] = "SASYZCR2"; DATASUBHEADERS data_subheaders; std::vector<std::string> column_texts; std::vector<std::string> column_names; std::vector<std::string> column_formats; std::vector<std::string> column_labels; std::vector<size_t> column_data_offsets; std::vector<size_t> column_data_lengths; std::vector<Column::Type> column_data_types; using READ_PAGE<_DataSource, _endian, _format>::read_page; using READ_PAGE<_DataSource, _endian, _format>::process_page_subheaders; using READ_PAGE<_DataSource, _endian, _format>::current_page_header; using READ_PAGE<_DataSource, _endian, _format>::buf; READ_METADATA(READ_HEADER<_DataSource, _endian, _format> &&_rh, const Properties::Header *_header) : READ_PAGE<_DataSource, _endian, _format>(std::move(_rh.is), std::move(_rh.buf), _header) {} void set_metadata(Properties::Metadata *_metadata, const Reader::PFILTER &_filter) { while (read_page()) { if (process_page(_metadata)) break; } create_columns(_metadata, _filter); } bool process_page(Properties::Metadata *_metadata) { D(spdlog::info("process_page: type={}\n", current_page_header.type)); bool data_reached = false; if (is_page_meta_mix_amd(current_page_header.type)) data_reached = process_page_metadata(_metadata); return is_page_data_mix(current_page_header.type) || data_reached; } bool process_page_metadata(Properties::Metadata *_metadata) { bool data_reached = false; auto psh = [&](const PAGE_SUBHEADER &_psh) { if (process_subheader(_psh, _metadata)) data_reached = true; }; process_page_subheaders(psh); return data_reached; } bool process_subheader(const PAGE_SUBHEADER &_subheader, Properties::Metadata *_metadata) { // Match the subheader signature to the correct processing function const auto subheader_signature = buf.get_bytes(_subheader.offset, integer_size); if (match_signature(ROW_SIZE_SUBHEADER, subheader_signature)) { process_ROW_SIZE_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(COLUMN_SIZE_SUBHEADER, subheader_signature)) { process_COLUMN_SIZE_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(SUBHEADER_COUNTS_SUBHEADER, subheader_signature)) { process_SUBHEADER_COUNTS_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(COLUMN_TEXT_SUBHEADER, subheader_signature)) { process_COLUMN_TEXT_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(COLUMN_NAME_SUBHEADER, subheader_signature)) { process_COLUMN_NAME_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(COLUMN_ATTRIBUTES_SUBHEADER, subheader_signature)) { process_COLUMN_ATTRIBUTES_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(FORMAT_AND_LABEL_SUBHEADER, subheader_signature)) { process_FORMAT_AND_LABEL_SUBHEADER(_subheader, _metadata); return false; } if (match_signature(COLUMN_LIST_SUBHEADER, subheader_signature)) { process_COLUMN_LIST_SUBHEADER(_subheader, _metadata); return false; } if (DataSubHeader::check(_metadata, _subheader)) { process_DATA_SUBHEADER(_subheader); return true; } // Unknown subheader... spdlog::warn("Unknown subheader signature!"); return false; } template <size_t n, size_t m> static bool match_signature(const BYTE (&_s)[n][m], const BYTES _signature) noexcept { return std::any_of(std::begin(_s), std::end(_s), [sig = _signature.data()](auto s) { return std::memcmp(s, sig, m) == 0; }); } void process_ROW_SIZE_SUBHEADER([[maybe_unused]] const PAGE_SUBHEADER &_subheader, Properties::Metadata *_metadata) const noexcept { D(spdlog::info("READ_METADATA::process_ROW_SIZE_SUBHEADER: {}, {} : ", _subheader.offset, _subheader.length)); buf.assert_check(_subheader.offset + lcp_offset, 4); _metadata->lcs = buf.get_uint16(_subheader.offset + lcs_offset); _metadata->lcp = buf.get_uint16(_subheader.offset + lcp_offset); _metadata->row_length = buf.get_uinteger(_subheader.offset + 5 * integer_size); _metadata->row_count = buf.get_uinteger(_subheader.offset + 6 * integer_size); _metadata->col_count_p1 = buf.get_uinteger(_subheader.offset + 9 * integer_size); _metadata->col_count_p2 = buf.get_uinteger(_subheader.offset + 10 * integer_size); _metadata->mix_page_row_count = buf.get_uinteger(_subheader.offset + 15 * integer_size); D(spdlog::info("lcs={}, lcp={}, row_length={}, row_count={}, " "col_count_p1={}, col_count_p2={}, mix_page_row_count={}\n", _metadata->lcs, _metadata->lcp, _metadata->row_length, _metadata->row_count, _metadata->col_count_p1, _metadata->col_count_p2, _metadata->mix_page_row_count)); } void process_COLUMN_SIZE_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, Properties::Metadata *_metadata) const noexcept { D(spdlog::info("READ_METADATA::process_COLUMN_SIZE_SUBHEADER: {}, {} : ", _subheader.offset, _subheader.length)); _metadata->column_count = buf.template get_uinteger<ASSERT::YES>( _subheader.offset + integer_size); D(spdlog::info("column_count={}\n", _metadata->column_count)); if (_metadata->col_count_p1 + _metadata->col_count_p2 != _metadata->column_count) spdlog::warn("Column count mismatch\n"); } void process_SUBHEADER_COUNTS_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, [[maybe_unused]] Properties::Metadata *_metadata) const noexcept { D(spdlog::info( "READ_METADATA::process_SUBHEADER_COUNTS_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); // spdlog::info("READ_METADATA::process_SUBHEADER_COUNTS_SUBHEADER: {}\n", // buf.get_string_untrim(_subheader.offset, _subheader.length)); } void process_COLUMN_TEXT_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, Properties::Metadata *_metadata) noexcept { D(spdlog::info("READ_METADATA::process_COLUMN_TEXT_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); const size_t length = buf.template get_uint16<ASSERT::YES>(_subheader.offset + integer_size); const auto text = buf.template get_string_untrim<ASSERT::YES>( _subheader.offset + integer_size, length); D(spdlog::info("text: {}\n", text)); column_texts.emplace_back(text); if (column_texts.size() == 1) { if (text.find(RLE_COMPRESSION) != text.npos) _metadata->compression = Compression::RLE; else if (text.find(RDC_COMPRESSION) != text.npos) _metadata->compression = Compression::RDC; const auto compression = buf.template get_string<ASSERT::YES>( _subheader.offset + compression_offset, 8); if (compression == "") { _metadata->lcs = 0; _metadata->creator_proc = buf.template get_string<ASSERT::YES>( _subheader.offset + compression_offset + 16, _metadata->lcp); } else if (compression == RLE_COMPRESSION) { _metadata->creator_proc = buf.template get_string<ASSERT::YES>( _subheader.offset + compression_offset + 24, _metadata->lcp); } else if (_metadata->lcs > 0) { _metadata->lcp = 0; _metadata->creator = buf.template get_string<ASSERT::YES>( _subheader.offset + compression_offset, _metadata->lcs); } D(spdlog::info("compression: {}, creator: {}, creator_proc: {}\n", _metadata->compression, _metadata->creator, _metadata->creator_proc)); } } std::string get_column_text_substr(const size_t _idx, size_t _offset, size_t _length) const noexcept { if (_idx < column_texts.size()) { const auto ct = column_texts[std::min(_idx, column_texts.size() - 1)]; const auto n = ct.size(); _offset = std::min(_offset, n); _length = std::min(_length, n - _offset); if (_length && std::isprint(ct[_offset])) { while (_length && std::isspace(ct[_offset])) { ++_offset; --_length; } while (_length && (!std::isprint(ct[_offset + _length - 1]) || std::isspace(ct[_offset + _length - 1]))) { --_length; } return ct.substr(_offset, _length); } } return {}; } void process_COLUMN_NAME_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, [[maybe_unused]] Properties::Metadata *_metadata) noexcept { D(spdlog::info("READ_METADATA::process_COLUMN_NAME_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); const size_t offset_max = _subheader.offset + _subheader.length - 12 - integer_size; for (size_t offset = _subheader.offset + integer_size + 8; offset <= offset_max; offset += 8) { const size_t idx = buf.get_uint16(offset + 0); const size_t name_offset = buf.get_uint16(offset + 2); const size_t name_length = buf.get_uint16(offset + 4); const auto column_name = get_column_text_substr(idx, name_offset, name_length); column_names.emplace_back(column_name); D(spdlog::info("column name: {},{},{}: {}\n", idx, name_offset, name_length, column_name)); } } void process_COLUMN_ATTRIBUTES_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, [[maybe_unused]] Properties::Metadata *_metadata) noexcept { D(spdlog::info( "READ_METADATA::process_COLUMN_ATTRIBUTES_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); const size_t offset_max = _subheader.offset + _subheader.length - 12 - integer_size; for (size_t offset = _subheader.offset + integer_size + 8; offset <= offset_max; offset += integer_size + 8) { const size_t column_data_offset = buf.get_uinteger(offset + 0); const size_t column_data_length = buf.get_uint32(offset + integer_size); const uint8_t column_data_type = buf.get_byte(offset + integer_size + 6); column_data_offsets.emplace_back(column_data_offset); column_data_lengths.emplace_back(column_data_length); column_data_types.emplace_back( column_data_type == 1 ? Column::Type::number : Column::Type::string); D(spdlog::info("column attribute: {}, {}, {}\n", column_data_offset, column_data_length, column_data_type)); } } void process_FORMAT_AND_LABEL_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, [[maybe_unused]] Properties::Metadata *_metadata) noexcept { D(spdlog::info( "READ_METADATA::process_FORMAT_AND_LABEL_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); const size_t offset = _subheader.offset + 3 * integer_size; buf.assert_check(offset + 32, 2); const size_t format_idx = buf.get_uint16(offset + 22); const size_t format_offset = buf.get_uint16(offset + 24); const size_t format_length = buf.get_uint16(offset + 26); const size_t label_idx = buf.get_uint16(offset + 28); const size_t label_offset = buf.get_uint16(offset + 30); const size_t label_length = buf.get_uint16(offset + 32); D(spdlog::info("column format: {}, {}, {}: ", format_idx, format_offset, format_length)); const auto column_format = get_column_text_substr(format_idx, format_offset, format_length); D(spdlog::info("{}\n", column_format)); D(spdlog::info("column_label: {}, {}, {}: ", label_idx, label_offset, label_length)); const auto column_label = get_column_text_substr(label_idx, label_offset, label_length); D(spdlog::info("{}\n", column_label)); column_formats.emplace_back(column_format); column_labels.emplace_back(column_label); } void process_COLUMN_LIST_SUBHEADER( [[maybe_unused]] const PAGE_SUBHEADER &_subheader, [[maybe_unused]] Properties::Metadata *_metadata) const noexcept { D(spdlog::info("READ_METADATA::process_COLUMN_LIST_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); // spdlog::info("READ_METADATA::process_COLUMN_LIST_SUBHEADER: {}\n", // buf.get_string_untrim(_subheader.offset, _subheader.length)); } void process_DATA_SUBHEADER([ [maybe_unused]] const PAGE_SUBHEADER &_subheader) noexcept { D(spdlog::info("READ_METADATA::process_DATA_SUBHEADER: {}, {}\n", _subheader.offset, _subheader.length)); data_subheaders.emplace_back(_subheader); } void create_columns(Properties::Metadata *_metadata, const Reader::PFILTER &_filter) { const size_t ncols = _metadata->column_count; _metadata->columns.reserve(ncols); auto get_value = [&](auto arg, auto vals, const size_t icol) { const auto n = std::min(ncols, vals.size()); if (n != ncols) spdlog::info("Mismatch between the expected number of columns ({}) and " "the number ({}) of '{}' values!\n", ncols, vals.size(), arg); return vals.at(icol); }; using Type = Column::Type; for (size_t icol = 0; icol < ncols; ++icol) { D(spdlog::info("READ_METADATA::create_columns: {}/{}\n", icol, ncols)); const auto column_name = get_value("name", column_names, icol); const auto column_label = get_value("label", column_labels, icol); const auto column_format = get_value("format", column_formats, icol); const auto column_offset = get_value("data_offset", column_data_offsets, icol); const auto column_length = get_value("data_length", column_data_lengths, icol); const auto column_type = get_value("data_type", column_data_types, icol); bool column_type_not_supported = true; auto add_column = [&](auto &&formatter) { D(spdlog::info("add_column: {}, {}, {}, {}, {}, {}\n", column_name, column_label, column_format, column_offset, column_length, column_type)); column_type_not_supported = false; Column column(column_name, column_label, column_format, std::forward<decltype(formatter)>(formatter)); if (!_filter || _filter->accept(column)) _metadata->columns.emplace_back( std::move(column)); // column_name, column_label, column_format, // std::move(formatter)); }; if (column_type == Type::string) add_column(FORMATTER::StringFormatter(column_offset, column_length)); else if (column_type == Type::number) { if (column_length == 1) add_column( FORMATTER::SmallIntegerFormatter(column_offset, column_length)); else if (column_length == 2) add_column(FORMATTER::IntegerFormatter<_endian, int16_t>( column_offset, column_length)); else if (is_datetime_format(column_format)) add_column(FORMATTER::DateTimeFormatter<_endian>(column_offset, column_length)); else if (is_date_format(column_format)) add_column( FORMATTER::DateFormatter<_endian>(column_offset, column_length)); else if (is_time_format(column_format)) add_column( FORMATTER::TimeFormatter<_endian>(column_offset, column_length)); else { if (column_length == 8) add_column(FORMATTER::DoubleFormatter<_endian>(column_offset, column_length)); else if (column_length == 3) add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 3>( column_offset, column_length)); else if (column_length == 4) add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 4>( column_offset, column_length)); else if (column_length == 5) add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 5>( column_offset, column_length)); else if (column_length == 6) add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 6>( column_offset, column_length)); else if (column_length == 7) add_column(FORMATTER::IncompleteDoubleFormatter<_endian, 7>( column_offset, column_length)); } } if (column_type_not_supported) { D(spdlog::warn("NoFormatter: {}, {}: ", column_type, column_format)); add_column(FORMATTER::NoFormatter(column_offset, column_length)); } } } template <size_t n> static bool match_column_format(const std::string_view (&_list)[n], const std::string_view &_f) noexcept { return std::any_of(std::begin(_list), std::end(_list), [_f](auto _g) { return _f == _g; }); } static bool is_datetime_format(const std::string_view &_f) noexcept { return match_column_format(COLUMN_DATETIME_FORMAT, _f); } static bool is_date_format(const std::string_view &_f) noexcept { return match_column_format(COLUMN_DATE_FORMAT, _f); } static bool is_time_format(const std::string_view &_f) noexcept { return match_column_format(COLUMN_TIME_FORMAT, _f); } }; } // namespace INTERNAL } // namespace cppsas7bdat #endif
44.546845
80
0.651687
olivia76
e001a967cddba7e6a3bea2882b635095df873de8
1,846
hpp
C++
include/emr/detail/marked_ptr.hpp
mpoeter/emr
390ee0c3b92b8ad0adb897177202e1dd2c53a1b7
[ "MIT" ]
43
2017-12-07T13:28:02.000Z
2022-03-23T13:51:11.000Z
include/emr/detail/marked_ptr.hpp
mpoeter/emr
390ee0c3b92b8ad0adb897177202e1dd2c53a1b7
[ "MIT" ]
1
2019-07-22T17:08:17.000Z
2019-07-24T04:58:09.000Z
include/emr/detail/marked_ptr.hpp
mpoeter/emr
390ee0c3b92b8ad0adb897177202e1dd2c53a1b7
[ "MIT" ]
2
2019-02-26T08:26:53.000Z
2019-10-17T04:06:16.000Z
#pragma once #include <cassert> #include <cstdint> #include <cstddef> namespace emr { namespace detail { template <class T, std::size_t N> class marked_ptr { public: // Construct a marked ptr marked_ptr(T* p = nullptr, uintptr_t mark = 0) noexcept { assert(mark <= MarkMask && "mark exceeds the number of bits reserved"); assert((reinterpret_cast<uintptr_t>(p) & MarkMask) == 0 && "bits reserved for masking are occupied by the pointer"); ptr = reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(p) | mark); } // Set to nullptr void reset() noexcept { ptr = nullptr; } // Get mark bits uintptr_t mark() const noexcept { return reinterpret_cast<uintptr_t>(ptr) & MarkMask; } // Get underlying pointer (with mark bits stripped off). T* get() const noexcept { return reinterpret_cast<T*>(reinterpret_cast<uintptr_t>(ptr) & ~MarkMask); } // True if get() != nullptr || mark() != 0 explicit operator bool() const noexcept { return ptr != nullptr; } // Get pointer with mark bits stripped off. T* operator->() const noexcept { return get(); } // Get reference to target of pointer. T& operator*() const noexcept { return *get(); } inline friend bool operator==(const marked_ptr& l, const marked_ptr& r) { return l.ptr == r.ptr; } inline friend bool operator!=(const marked_ptr& l, const marked_ptr& r) { return l.ptr != r.ptr; } static constexpr std::size_t number_of_mark_bits = N; private: static constexpr uintptr_t MarkMask = (1 << N) - 1; T* ptr; #ifdef _MSC_VER // These members are only for the VS debugger visualizer (natvis). enum Masking { MarkMask_ = MarkMask }; using PtrType = T*; #endif }; }}
31.827586
103
0.619177
mpoeter
e003393d2a85960394ac9d840a4ba3eff65eaf70
10,320
cpp
C++
shore/shore-kits/debug-shore.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
4
2019-01-24T02:00:23.000Z
2021-03-17T11:56:59.000Z
shore/shore-kits/debug-shore.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
1
2021-11-25T18:08:22.000Z
2021-11-25T18:08:22.000Z
shore/shore-kits/debug-shore.cpp
anshsarkar/TailBench
25845756aee9a892229c25b681051591c94daafd
[ "MIT" ]
4
2019-01-22T10:35:55.000Z
2021-03-17T11:57:23.000Z
#define private public #define protected public #include "w_defines.h" #include "w_base.h" #include "w_rc.h" #include "sthread.h" #include "latch.h" #include "basics.h" #include "stid_t.h" #include "sm_base.h" #include "sm_int_0.h" #include "lid_t.h" #include "sm_s.h" #include "bf.h" #include "bf_s.h" #include "bf_core.h" #include "page_s.h" #include "page.h" #include "page_h.h" #include "sm_int_1.h" #include "lock.h" #include "lock_s.h" #include "pmap.h" #include "sm_io.h" #include "log.h" #include "logrec.h" #include "xct.h" #include "xct_impl.h" #include "xct_dependent.h" #include "lock_x.h" #include "lock_core.h" #include "kvl_t.h" #include <sstream> #include <map> #include <stdio.h> /* CC -DHAVE_CONFIG_H -I/raid/small/ryanjohn/projects/shore-elr-manos/config -g -DSOLARIS2 -DSTHREAD_CORE_PTHREAD -DARCH_LP64 -DNO_FASTNEW -D_REENTRANT -mt -xtarget=native64 -xdebugformat=stabs -features=extensions -DW_LARGEFILE -I/raid/small/ryanjohn/projects/shore-elr-manos/src/fc -I/raid/small/ryanjohn/projects/shore-elr-manos/src/sthread -I/raid/small/ryanjohn/projects/shore-elr-manos/src/common -I/raid/small/ryanjohn/projects/shore-elr-manos/src/sm -xcode=pic13 -G -o debug-shore.so debug-shore.cpp -I/raid/small/ryanjohn/projects/ppmcs -features=zla -library=stlport4 */ // stolen from lock_core.cpp... class bucket_t { public: #ifndef NOT_PREEMPTIVE #ifndef ONE_MUTEX DEF_LOCK_X; lock_x mutex; // serialize access to lock_info_t #endif #endif w_list_t<lock_head_t> chain; NORET bucket_t() : #ifndef NOT_PREEMPTIVE #ifndef ONE_MUTEX // mutex("lkbkt"), #endif #endif chain(W_LIST_ARG(lock_head_t, chain)) { } private: // disabled NORET bucket_t(const bucket_t&); bucket_t& operator=(const bucket_t&); }; class page_mark_t { public: int2_t idx; uint2_t len; }; char const* page_tag_to_str(int page_tag) { switch (page_tag) { case page_p::t_extlink_p: return "t_extlink_p"; case page_p::t_stnode_p: return "t_stnode_p"; case page_p::t_keyed_p: return "t_keyed_p"; case page_p::t_btree_p: return "t_btree_p"; case page_p::t_rtree_p: return "t_rtree_p"; case page_p::t_file_p: return "t_file_p"; default: return "<garbage>"; } } char const* pretty_print(logrec_t const* rec, int i=0, char const* s=0) { static char tmp_data[1024]; static char type_data[1024]; switch(rec->type()) { case logrec_t::t_page_mark: case logrec_t::t_page_reclaim: { page_mark_t* pm = (page_mark_t*) rec->_data; snprintf(type_data, sizeof(type_data), " idx = %d\n" " len = %d\n", pm->idx, pm->len); break; } default: snprintf(type_data, sizeof(type_data), ""); } // what categories? typedef char const* str; str undo=(rec->is_undo()? "undo " : ""), redo=(rec->is_redo()? "redo " : ""), cpsn=(rec->is_cpsn()? "cpsn " : ""), logical=(rec->is_logical()? "logical " : ""); snprintf(tmp_data, sizeof(tmp_data), "{\n" " _len = %d\n" " _type = %s\n" "%s" " _cat = %s%s%s%s\n" " _tid = %d.%d\n" " _pid = %d.%d.%d\n" " _page_tag = %s\n" " _prev = %d.%ld\n" " _ck_lsn = %d.%ld\n" "}", rec->length(), rec->type_str(), type_data, logical, undo, redo, cpsn, rec->tid().get_hi(), rec->tid().get_lo(), rec->construct_pid().vol().vol, rec->construct_pid().store(), rec->construct_pid().page, page_tag_to_str(rec->tag()), rec->prev().hi(), rec->prev().lo(), rec->get_lsn_ck().hi(), rec->get_lsn_ck().lo() ); return tmp_data; } void scan_lock_pool() { typedef std::map<int, int> lmap; lmap lengths; lock_core_m* core = smlevel_0::lm->_core; for(int i=0; i < core->_htabsz; i++) lengths[core->_htab[i].chain.num_members()]++; printf("Bucket density histogram:\n"); for(lmap::iterator it=lengths.begin(); it != lengths.end(); ++it) printf("\t%d: %d\n", it->first, it->second); printf("\n"); } #if 0 void debug_dump_waits_for(w_descend_list_t<xct_t, tid_t>* xlist=&xct_t::_xlist, bool acquire=false) { if(acquire) W_COERCE(xct_t::acquire_xlist_mutex()); std::map<lock_head_t*, int> lockmap; w_list_i<xct_t> i(*xlist); while ( xct_t* me = i.next() ) { if( lock_request_t* mine = me->lock_info()->wait ) { lock_head_t* lock = mine->get_lock_head(); ostringstream os; os << lock->name << ends << std::flush; std::string str = os.str(); char const* lname = str.c_str(); printf("\"0x%p\" -> \"%s\"\n", mine->thread, lname); if(++lockmap[lock] == 1) { // print out all current lock holders as dependencies. This // isn't perfect because other waiting requests ahead of me // are also a problem, but it should be enough to get the job // done. w_list_i<lock_request_t> i2(lock->queue); while(lock_request_t* theirs = i2.next()) { if(mine->status() == lock_m::t_converting && theirs->status() == lock_m::t_waiting) break; if(mine->status() == lock_m::t_waiting && theirs == mine) break; sthread_t* thread = theirs->thread; printf("\"%s\" -> \"0x%p\" [ color=%s style=%s]\n", lname, thread? thread : 0, theirs->mode == EX? "red" : "blue", theirs->status() == lock_m::t_waiting? "dotted" : "solid"); } } } } if(acquire) xct_t::release_xlist_mutex(); } #endif bfcb_t* verify_page_lsn() { for(int i=0; i < bf_m::_core->_num_bufs; i++) { bfcb_t &b = bf_m::_core->_buftab[i]; if(b.pid.page && b.dirty) { if(b.rec_lsn > b.frame->lsn1) return &b; } } return 0; } char const* db_pretty_print(logrec_t const* rec, int i=0, char const* s=0); int vnum_to_match = 1; int snum_to_match; int pnum_to_match; void match_page(logrec_t* rp) { lpid_t log_pid = rp->construct_pid(); lpid_t test_pid(vnum_to_match, snum_to_match, pnum_to_match); if(log_pid == test_pid) { fprintf(stderr, "%s\n", pretty_print(rp)); } } int tidhi_to_match = 0; int tidlo_to_match; void match_trx(logrec_t* rp) { tid_t log_tid = rp->tid(); tid_t test_tid(tidlo_to_match, tidhi_to_match); if(log_tid == test_tid) { fprintf(stderr, "%s\n", pretty_print(rp)); } } void match_all(logrec_t* rp) { fprintf(stderr, "%s\n", pretty_print(rp)); } void match_n(logrec_t* rp) { } std::map<lpid_t, lsn_t> page_deps; std::map<tid_t, lsn_t> tid_deps; bool lpid_t::operator<(lpid_t const &other) const { return page < other.page; } struct log_dump_file { FILE* _f; log_dump_file() : _f(fopen("logdump.dot", "w")) { fprintf(_f, "digraph logdeps {\n" " node [ width=0.1 height=0.1 fixedsize=true label=<> ]\n" " edge [ arrowhead=normal arrowtail=none ]\n" " node [ shape=oval ]\n" " node [ style=filled fillcolor=gray ]\n" ); } ~log_dump_file() { fclose(_f); } operator FILE*() { return _f; } } __log_dump_file; void match_all_and_dump(logrec_t* rp) { lsn_t lsn = rp->get_lsn_ck(); tid_t tid = rp->tid(); lpid_t pid = rp->construct_pid(); if(!pid.valid() || tid.invalid()) return; fprintf(__log_dump_file, " lr%lx [ tooltip=<LSN: %d.%09d TID: %d.%d PID: %d.%d.%d> ]\n", lsn._data, lsn.hi(), lsn.lo(), tid.get_hi(), tid.get_lo(), pid.vol().vol, pid.store(), pid.page, lsn._data, rp->prev()._data); lsn_t &tid_prev = tid_deps[tid]; if(tid_prev.valid()) { fprintf(__log_dump_file, " lr%lx -> lr%lx [ color=blue tooltip=<TID: %d.%d> weight=100 ]\n" , lsn._data, tid_prev._data, tid.get_hi(), tid.get_lo()); } lsn_t &page_prev = page_deps[pid]; if(page_prev.valid()) { fprintf(__log_dump_file, " lr%lx -> lr%lx [ color=darkgreen tooltip=<PID: %d.%d.%d> weight=0 ]\n", lsn._data, page_prev._data, pid.vol().vol, pid.store(), pid.page); } tid_prev = page_prev = lsn; } void match_non_transactional(logrec_t* rp) { switch(rp->_type) { case logrec_t::t_skip: case logrec_t::t_chkpt_begin: case logrec_t::t_chkpt_bf_tab: case logrec_t::t_chkpt_xct_tab: case logrec_t::t_chkpt_dev_tab: case logrec_t::t_chkpt_end: case logrec_t::t_mount_vol: case logrec_t::t_dismount_vol: fprintf(stderr, "%s\n", pretty_print(rp)); break; default: break; } } #include <map> struct page_history { lpid_t pid; bool found_format; int last_slot; page_history(lpid_t const &p=lpid_t(), bool f=false, int l=-1) : pid(p), found_format(f), last_slot(l) { } }; typedef std::map<long, page_history> phist_map; phist_map page_histories; typedef std::map<long, long> size_dist_map; size_dist_map size_dist; void print_size_dist() { // skip entry 0... size_dist_map::iterator it=size_dist.begin(); fprintf(stderr, "Log record size distribution (%ld total):\n", it->second); while(++it != size_dist.end()) fprintf(stderr, " %ld %ld\n", it->first, it->second); size_dist.clear(); } void match_all_measure_size_dist(logrec_t* rp) { size_dist[0]++; // total... size_dist[rp->length()]++; } void match_slotted_pages(logrec_t* rp, char const* name=0) { if(rp->tag() != page_p::t_file_p) return; if(!name) name = ""; lpid_t pid = rp->construct_pid(); phist_map::iterator it = page_histories.find(pid.page); switch(rp->type()) { case logrec_t::t_page_format: { if(it != page_histories.end()) { fprintf(stderr, "%s Reformatting an existing page: %d.%d.%d (was %d.%d.%d with %d slots)\n", name, pid.vol().vol, pid.store(), pid.page, it->second.pid.vol().vol, it->second.pid.store(), it->second.pid.page, it->second.last_slot); } page_histories[pid.page] = page_history(pid, true, 0); } break; case logrec_t::t_page_reclaim: { short idx = *(short*) rp->data(); if(it == page_histories.end()) { // page existed before start of log page_histories[pid.page] = page_history(pid, false, idx); } else { // we've seen this page before if(idx != it->second.last_slot + 1) { fprintf(stderr, "%s Missing log record(s) for page: %d.%d.%d (skips from %d to %d)\n", name, pid.vol().vol, pid.store(), pid.page, it->second.last_slot, idx); } it->second.last_slot = idx; } } break; default: break; } }
27.52
583
0.628391
anshsarkar
e003be90313c7870a28c28c1b5ce22ea1c04647c
1,730
cpp
C++
Module4/AYonaty_MergeSort/Source.cpp
ariyonaty/ECE3310
845d7204c16e84712fab2e25f79c0f16cb1e7c99
[ "MIT" ]
null
null
null
Module4/AYonaty_MergeSort/Source.cpp
ariyonaty/ECE3310
845d7204c16e84712fab2e25f79c0f16cb1e7c99
[ "MIT" ]
null
null
null
Module4/AYonaty_MergeSort/Source.cpp
ariyonaty/ECE3310
845d7204c16e84712fab2e25f79c0f16cb1e7c99
[ "MIT" ]
1
2021-09-22T04:01:52.000Z
2021-09-22T04:01:52.000Z
/* * Ari Yonaty * ECE3310 * MergeSort */ #include <iostream> #define N 10 void display(double*, int); void mergeSort(double*, double*, int); void bubbleSort(double*, int n); void swap(double* x, double* y); int main() { int x1[N], y1[N], x2[N], y2[N]; double a[N], b[N]; for (int i = 0; i < N; i++) { x1[i] = rand() % 301; y1[i] = -10 + rand() % 21; x2[i] = rand() % 301; y2[i] = -10 + rand() % 21; a[i] = 7.03 + 0.05 * x1[i] + y1[i]; b[i] = 7.03 + 0.05 * x2[i] + y2[i]; } std::cout << "Array A before sort: "; display(a, N); std::cout << "Array B before sort: "; display(b, N); bubbleSort(a, N); bubbleSort(b, N); std::cout << "Array A after sort: "; display(a, N); std::cout << "Array B after sort: "; display(b, N); mergeSort(a, b, N); return 0; } void swap(double* x, double* y) { double temp = *x; *x = *y; *y = temp; } void bubbleSort(double* arr, int n) { for (int i = 0; i < n - 1; i++) { for (int j = 0; j < n - i - 1; j++) { if (arr[j] > arr[j + 1]) swap(&arr[j], &arr[j + 1]); } } } void mergeSort(double* arr1, double* arr2, int size) { double x = arr1[0]; double y = arr2[0]; double result[2 * N]; int i = 0, j = 0, k = 0; while (i < size && j < size) { if (arr1[i] <= arr2[j]) { result[k] = arr1[i]; i++; } else { result[k] = arr2[j]; j++; } k++; } while (i < size) { result[k] = arr1[i]; i++; k++; } while (j < size) { result[k] = arr2[j]; j++; k++; } std::cout << "Array A+B after sorted merge: "; display(result, 2 * N); } void display(double* arr, int size) { std::cout << std::endl; for (int i = 0; i < size; i++) { std::cout << arr[i] << " "; } std::cout << std::endl << std::endl; }
15.043478
52
0.500578
ariyonaty
e00444a132d9267e92c2dcec29f71e6c7b7a02e3
1,401
cc
C++
src/cut_tree/greedy_treepacking.cc
math314/cut-tree
0332ba0907af9a900e8c0c29c51a66428d9bed4b
[ "MIT" ]
11
2016-09-27T06:49:44.000Z
2021-11-17T01:12:23.000Z
iwiwi/src/agl/cut_tree/greedy_treepacking.cc
imos/icfpc2017
d50c76b1f44e9289a92f564f319750049d952a5d
[ "MIT" ]
null
null
null
iwiwi/src/agl/cut_tree/greedy_treepacking.cc
imos/icfpc2017
d50c76b1f44e9289a92f564f319750049d952a5d
[ "MIT" ]
2
2016-10-01T16:32:44.000Z
2018-10-10T13:41:55.000Z
#include "greedy_treepacking.h" DEFINE_int32(cut_tree_gtp_dfs_edge_max, 1000000000, "greedy tree packing breadth limit"); using namespace std; namespace agl { void greedy_treepacking::dfs(int v) { used_revision_[v] = vertices_revision_; auto& to_edges = edges_[v]; const int rem_edges = min(to_edges.size(), FLAGS_cut_tree_gtp_dfs_edge_max); for (int i = 0; i < rem_edges; i++) { V to = to_edges.current(); // logging::gtp_edge_count++; if (used_revision_[to] == vertices_revision_) { to_edges.advance(); // logging::gtp_edge_miss++; } else { to_edges.remove_current(); inedge_count_[to]++; // in-edgeの本数が増える dfs(to); // logging::gtp_edge_use++; } } } greedy_treepacking::greedy_treepacking(const vector<pair<V, V>>& edges, int num_vs) : n_(num_vs), edges_(n_), inedge_count_(n_), used_revision_(n_), vertices_revision_(1) { for (auto& e : edges) { edges_[e.first].add(e.second); edges_[e.second].add(e.first); } for (auto& e : edges_) { auto& edges_ = this->edges_; sort(e.to_.begin(), e.to_.end(), [&edges_](const V l, const V r) { int a = edges_[l].size(); int b = edges_[r].size(); return a < b; }); } } void greedy_treepacking::arborescence_packing(int from) { for (int i = 0; i < edges_[from].size(); i++) { dfs(from); vertices_revision_++; } } } // namespace agl
28.02
89
0.638116
math314
e0074d5e13c7c6e6017b47a8ff8e2a7a4efd3403
1,756
cpp
C++
server/util/pending_buffer_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
7
2019-04-09T16:25:49.000Z
2021-12-07T10:29:52.000Z
server/util/pending_buffer_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
null
null
null
server/util/pending_buffer_test.cpp
RickAi/csci5570
2814c0a6bf608c73bf81d015d13e63443470e457
[ "Apache-2.0" ]
4
2019-08-07T07:43:27.000Z
2021-05-21T07:54:14.000Z
#include "glog/logging.h" #include "gtest/gtest.h" #include "server/util/pending_buffer.hpp" namespace minips { namespace { class TestPendingBuffer : public testing::Test { public: TestPendingBuffer() {} ~TestPendingBuffer() {} protected: void SetUp() {} void TearDown() {} }; TEST_F(TestPendingBuffer, Construct) { PendingBuffer pending_buffer; } TEST_F(TestPendingBuffer, PushAndPop) { PendingBuffer pending_buffer; // Message m1 Message m1; m1.meta.flag = Flag::kAdd; m1.meta.model_id = 0; m1.meta.sender = 2; m1.meta.recver = 0; third_party::SArray<int> m1_keys({0}); third_party::SArray<int> m1_vals({1}); m1.AddData(m1_keys); m1.AddData(m1_vals); // Message m2 Message m2; m2.meta.flag = Flag::kAdd; m2.meta.model_id = 0; m2.meta.sender = 2; m2.meta.recver = 0; third_party::SArray<int> m2_keys({0}); third_party::SArray<int> m2_vals({1}); m2.AddData(m1_keys); m2.AddData(m1_vals); pending_buffer.Push(0, m1); pending_buffer.Push(0, m1); pending_buffer.Push(1, m2); EXPECT_EQ(pending_buffer.Size(0), 2); EXPECT_EQ(pending_buffer.Size(1), 1); std::vector<Message> messages_0 = pending_buffer.Pop(0); std::vector<Message> messages_1 = pending_buffer.Pop(1); EXPECT_EQ(messages_0.size(), 2); EXPECT_EQ(messages_1.size(), 1); } } // namespace } // namespace minips
27.4375
78
0.531891
RickAi
e009a5ca0f1382ef10a4566cf375f4f5f9300220
970
cpp
C++
codeforces/354/B/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
2
2020-05-30T17:11:47.000Z
2021-09-25T08:16:48.000Z
codeforces/354/B/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
null
null
null
codeforces/354/B/test.cpp
rdragos/work
aed4c9ace3fad6b0c63caadee69de2abde108b40
[ "MIT" ]
1
2021-09-24T11:14:27.000Z
2021-09-24T11:14:27.000Z
#include <cstdio> #include <algorithm> #include <fstream> #include <iostream> #include <vector> #include <queue> #include <map> #include <cstring> #include <string> #include <set> #include <stack> #define pb push_back #define mp make_pair #define f first #define s second #define ll long long using namespace std; int main() { ifstream cin("test.in"); ofstream cout("test.out"); int N, T; cin >> N >> T; vector<vector<long double>> cant(N + 2,vector<long double>(N + 2, 0)); cant[1][1] = T; for (int i = 1; i <= N; ++i) { for (int j = 1; j <= i; ++j) { cant[i][j] -= 1.0; long double t = cant[i][j]; t = max(0.000L, t); cant[i + 1][j] += t / 2.0; cant[i + 1][j + 1] += t / 2.0; } } int answer = 0; for (int i = 1; i <= N; ++i) { for (int j = 1; j <= i; ++j) { answer += (cant[i][j] >= 0.000000); cout << cant[i][j] << " "; } cout << "\n"; } cout << answer << "\n"; return 0; }
19.019608
72
0.518557
rdragos
e00a4486dab6c5fca623b352aa77483c766abc0d
228
hpp
C++
pythran/pythonic/include/string/digits.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/string/digits.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
pythran/pythonic/include/string/digits.hpp
xmar/pythran
dbf2e8b70ed1e4d4ac6b5f26ead4add940a72592
[ "BSD-3-Clause" ]
null
null
null
#ifndef PYTHONIC_INCLUDE_STRING_DIGITS_HPP #define PYTHONIC_INCLUDE_STRING_DIGITS_HPP #include "pythonic/types/str.hpp" namespace pythonic { namespace string { types::str constexpr digits("0123456789"); } } #endif
14.25
46
0.77193
xmar
e00caeb79471fbd2811df2c101ec23e660c1ad7f
1,340
cpp
C++
LeetCode practice/Finite state machine/best-time-to-buy-and-sell-stock-iii.cpp
19hkm/algorithms
6b4494ca9165e77b9c2672d88e8a89838e8eef8f
[ "MIT" ]
null
null
null
LeetCode practice/Finite state machine/best-time-to-buy-and-sell-stock-iii.cpp
19hkm/algorithms
6b4494ca9165e77b9c2672d88e8a89838e8eef8f
[ "MIT" ]
null
null
null
LeetCode practice/Finite state machine/best-time-to-buy-and-sell-stock-iii.cpp
19hkm/algorithms
6b4494ca9165e77b9c2672d88e8a89838e8eef8f
[ "MIT" ]
null
null
null
class Solution { public: inline void prepLeftSell(vector<int> &prices, vector<vector<int>> &dp){ int n = prices.size(), mini =1e5+1, maxi =0, maxP=0; for(int i=0; i<n; i++){ if(prices[i]<mini){ mini = prices[i]; maxi = 0; } else if(prices[i]>maxi){ maxi = prices[i]; maxP = maxi - mini; } dp[0][i] = maxP; } return; } inline void prepRightSell(vector<int> &prices, vector<vector<int>> &dp) { int n = prices.size(), mini =1e5+1, maxi =0, maxP=0; for(int i=n-1; i>=0; i--){ if(prices[i]>maxi){ maxi = prices[i]; mini = 1e5+1; } else if(prices[i]<mini){ mini = prices[i]; maxP = maxi - mini; } dp[1][i] = maxP; } return; } int maxProfit(vector<int>& prices) { int n = prices.size(), mini =1e5+1, maxi =0, maxP=0; vector<vector<int>> dp(2, vector<int>(n,0)); prepLeftSell(prices, dp); prepRightSell(prices, dp); // printVec(dp); for(int i=0;i<n;i++) maxP = max(maxP, dp[0][i]+dp[1][i]); return maxP; } };
27.916667
77
0.420149
19hkm
e00e5e489184811fd9226712410bf485eca208fd
410
hpp
C++
libs/core/math/include/bksge/core/math/fwd/color_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
4
2018-06-10T13:35:32.000Z
2021-06-03T14:27:41.000Z
libs/core/math/include/bksge/core/math/fwd/color_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
566
2017-01-31T05:36:09.000Z
2022-02-09T05:04:37.000Z
libs/core/math/include/bksge/core/math/fwd/color_fwd.hpp
myoukaku/bksge
0f8b60e475a3f1709723906e4796b5e60decf06e
[ "MIT" ]
1
2018-07-05T04:40:53.000Z
2018-07-05T04:40:53.000Z
/** * @file color_fwd.hpp * * @brief Color の前方宣言 * * @author myoukaku */ #ifndef BKSGE_CORE_MATH_FWD_COLOR_FWD_HPP #define BKSGE_CORE_MATH_FWD_COLOR_FWD_HPP #include <cstddef> namespace bksge { namespace math { template <typename T, std::size_t N> class Color; } // namespace math using math::Color; } // namespace bksge #endif // BKSGE_CORE_MATH_FWD_COLOR_FWD_HPP
13.666667
44
0.682927
myoukaku
e01026b722c20138f6ce9f273ec4ed1d1362477e
277
hpp
C++
lib/state/parser.hpp
julienlopez/Aronda-RL
d93602d2ebab0a099f16d316b488f2d4a6713aaf
[ "MIT" ]
null
null
null
lib/state/parser.hpp
julienlopez/Aronda-RL
d93602d2ebab0a099f16d316b488f2d4a6713aaf
[ "MIT" ]
1
2018-04-04T08:45:24.000Z
2018-04-04T08:45:24.000Z
lib/state/parser.hpp
julienlopez/Aronda-RL
d93602d2ebab0a099f16d316b488f2d4a6713aaf
[ "MIT" ]
null
null
null
#pragma once #include "state.hpp" #include <nlohmann_json/json.hpp> namespace Aronda::State { class Parser { public: static GameState parse(const std::string& json_string); static Square parseSquare(const nlohmann::json& square, const Player current_player); }; }
15.388889
89
0.740072
julienlopez
e015742e016dd048e33cb43e397a4e076d9951ef
1,660
cpp
C++
src/netpayload/BinaryNetPayloadBase.cpp
andriyadi/PulseOximeterLib
f93ddea3fdc506a9937c410be147d658e5fed62d
[ "MIT" ]
null
null
null
src/netpayload/BinaryNetPayloadBase.cpp
andriyadi/PulseOximeterLib
f93ddea3fdc506a9937c410be147d658e5fed62d
[ "MIT" ]
null
null
null
src/netpayload/BinaryNetPayloadBase.cpp
andriyadi/PulseOximeterLib
f93ddea3fdc506a9937c410be147d658e5fed62d
[ "MIT" ]
null
null
null
// // Created by Andri Yadi on 1/25/17. // #include "BinaryNetPayloadBase.h" BinaryNetPayloadBase::~BinaryNetPayloadBase() { } void BinaryNetPayloadBase::copyTo(uint8_t* buffer, size_t size) const { if (size < getSize()) { // TODO failed sanity check! return; } memcpy(buffer, getBuffer(), size); } void BinaryNetPayloadBase::copyFrom(const uint8_t* buffer, size_t size) { //if (size != getSize()) { if (size > getSize()) { // TODO failed sanity check! return; } memcpy(getBuffer(), buffer, size); } uint16_t BinaryNetPayloadBase::getFieldStart(uint8_t fieldIndex) const { uint16_t result = 0; for (uint8_t i = 0; i < fieldIndex; i++) { result += getFieldSize(i); } return result; } uint8_t BinaryNetPayloadBase::getFieldValue(uint8_t fieldIndex, uint8_t* buffer, size_t size) const { uint8_t fieldSize = getFieldSize(fieldIndex); if (fieldIndex > getFieldCount() || fieldSize > size) { printf("getFieldValue(): sanity check failed!\r\n"); return 0; } uint16_t fieldStart = getFieldStart(fieldIndex); memcpy(buffer, getBuffer() + fieldStart, fieldSize); // already checked buffer size >= getFieldSize(fieldIndex) return fieldSize; } void BinaryNetPayloadBase::setFieldValue(uint8_t fieldIndex, const uint8_t* buffer, uint8_t size) const { if (fieldIndex > getFieldCount() || size > getFieldSize(fieldIndex)) { printf("setFieldValue(): sanity check failed!\r\n"); return; } uint16_t fieldStart = getFieldStart(fieldIndex); memcpy(getBuffer() + fieldStart, buffer, getFieldSize(fieldIndex)); }
24.776119
115
0.66988
andriyadi
e0173471a4e1ef325dd7c8aa5de0bf656ba88363
5,455
cpp
C++
Engine/Source/Editor/DetailCustomizations/Private/PrimitiveComponentDetails.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
1
2022-01-29T18:36:12.000Z
2022-01-29T18:36:12.000Z
Engine/Source/Editor/DetailCustomizations/Private/PrimitiveComponentDetails.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
Engine/Source/Editor/DetailCustomizations/Private/PrimitiveComponentDetails.cpp
windystrife/UnrealEngine_NVIDIAGameWork
b50e6338a7c5b26374d66306ebc7807541ff815e
[ "MIT" ]
null
null
null
// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved. #include "PrimitiveComponentDetails.h" #include "Components/SceneComponent.h" #include "Components/PrimitiveComponent.h" #include "DetailLayoutBuilder.h" #include "IDetailGroup.h" #include "DetailCategoryBuilder.h" #include "ObjectEditorUtils.h" #include "EditorCategoryUtils.h" #include "ComponentMaterialCategory.h" #define LOCTEXT_NAMESPACE "PrimitiveComponentDetails" ////////////////////////////////////////////////////////////// // This class customizes collision setting in primitive component ////////////////////////////////////////////////////////////// TSharedRef<IDetailCustomization> FPrimitiveComponentDetails::MakeInstance() { return MakeShareable( new FPrimitiveComponentDetails ); } void FPrimitiveComponentDetails::AddPhysicsCategory(IDetailLayoutBuilder& DetailBuilder) { BodyInstanceCustomizationHelper = MakeShareable(new FBodyInstanceCustomizationHelper(ObjectsCustomized)); BodyInstanceCustomizationHelper->CustomizeDetails(DetailBuilder, DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UPrimitiveComponent, BodyInstance))); } void FPrimitiveComponentDetails::AddCollisionCategory(IDetailLayoutBuilder& DetailBuilder) { if (DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UPrimitiveComponent, BodyInstance))->IsValidHandle()) { // Collision TSharedPtr<IPropertyHandle> BodyInstanceHandler = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UPrimitiveComponent, BodyInstance)); uint32 NumChildren = 0; BodyInstanceHandler->GetNumChildren(NumChildren); IDetailCategoryBuilder& CollisionCategory = DetailBuilder.EditCategory("Collision"); // add all collision properties for (uint32 ChildIndex = 0; ChildIndex < NumChildren; ++ChildIndex) { TSharedPtr<IPropertyHandle> ChildProperty = BodyInstanceHandler->GetChildHandle(ChildIndex); static const FName CollisionCategoryName(TEXT("Collision")); FName CategoryName = FObjectEditorUtils::GetCategoryFName(ChildProperty->GetProperty()); if (CategoryName == CollisionCategoryName) { CollisionCategory.AddProperty(ChildProperty); } } } } void FPrimitiveComponentDetails::CustomizeDetails( IDetailLayoutBuilder& DetailBuilder ) { // Get the objects being customized so we can enable/disable editing of 'Simulate Physics' DetailBuilder.GetObjectsBeingCustomized(ObjectsCustomized); // See if we are hiding Physics category TArray<FString> HideCategories; FEditorCategoryUtils::GetClassHideCategories(DetailBuilder.GetBaseClass(), HideCategories); if(!HideCategories.Contains("Materials")) { AddMaterialCategory(DetailBuilder); } TSharedRef<IPropertyHandle> MobilityHandle = DetailBuilder.GetProperty(GET_MEMBER_NAME_CHECKED(UPrimitiveComponent, Mobility), USceneComponent::StaticClass()); MobilityHandle->SetToolTipText(LOCTEXT("PrimitiveMobilityTooltip", "Mobility for primitive components controls how they can be modified in game and therefore how they interact with lighting and physics.\n* A movable primitive component can be changed in game, but requires dynamic lighting and shadowing from lights which have a large performance cost.\n* A static primitive component can't be changed in game, but can have its lighting baked, which allows rendering to be very efficient.")); if(!HideCategories.Contains("Physics")) { AddPhysicsCategory(DetailBuilder); } if (!HideCategories.Contains("Collision")) { AddCollisionCategory(DetailBuilder); } if(!HideCategories.Contains("Lighting")) { AddLightingCategory(DetailBuilder); } AddAdvancedSubCategory( DetailBuilder, "Rendering", "TextureStreaming" ); AddAdvancedSubCategory( DetailBuilder, "Rendering", "LOD"); } void FPrimitiveComponentDetails::AddMaterialCategory( IDetailLayoutBuilder& DetailBuilder ) { TArray<TWeakObjectPtr<USceneComponent> > Components; for( TWeakObjectPtr<UObject> Object : ObjectsCustomized ) { USceneComponent* Component = Cast<USceneComponent>(Object.Get()); if( Component ) { Components.Add( Component ); } } MaterialCategory = MakeShareable(new FComponentMaterialCategory(Components)); MaterialCategory->Create(DetailBuilder); } void FPrimitiveComponentDetails::AddLightingCategory(IDetailLayoutBuilder& DetailBuilder) { IDetailCategoryBuilder& LightingCategory = DetailBuilder.EditCategory("Lighting"); } void FPrimitiveComponentDetails::AddAdvancedSubCategory( IDetailLayoutBuilder& DetailBuilder, FName MainCategoryName, FName SubCategoryName) { TArray<TSharedRef<IPropertyHandle> > SubCategoryProperties; IDetailCategoryBuilder& SubCategory = DetailBuilder.EditCategory(SubCategoryName); const bool bSimpleProperties = false; const bool bAdvancedProperties = true; SubCategory.GetDefaultProperties( SubCategoryProperties, bSimpleProperties, bAdvancedProperties ); if( SubCategoryProperties.Num() > 0 ) { IDetailCategoryBuilder& MainCategory = DetailBuilder.EditCategory(MainCategoryName); const bool bForAdvanced = true; IDetailGroup& Group = MainCategory.AddGroup( SubCategoryName, FText::FromName(SubCategoryName), bForAdvanced ); for( int32 PropertyIndex = 0; PropertyIndex < SubCategoryProperties.Num(); ++PropertyIndex ) { TSharedRef<IPropertyHandle>& PropertyHandle = SubCategoryProperties[PropertyIndex]; // Ignore customized properties if( !PropertyHandle->IsCustomized() ) { Group.AddPropertyRow( SubCategoryProperties[PropertyIndex] ); } } } } #undef LOCTEXT_NAMESPACE
36.858108
493
0.788818
windystrife
e017d3db3377c8f32921357f19817e94a0bfda74
2,379
cxx
C++
HallA/THaVDCHit.cxx
chandabindu/analyzer
889be785858769446662ddf9ba250cc9d203bc47
[ "BSD-3-Clause" ]
null
null
null
HallA/THaVDCHit.cxx
chandabindu/analyzer
889be785858769446662ddf9ba250cc9d203bc47
[ "BSD-3-Clause" ]
null
null
null
HallA/THaVDCHit.cxx
chandabindu/analyzer
889be785858769446662ddf9ba250cc9d203bc47
[ "BSD-3-Clause" ]
null
null
null
/////////////////////////////////////////////////////////////////////////////// // // // THaVDCHit // // // // Class representing a single hit for the VDC // // // /////////////////////////////////////////////////////////////////////////////// #include "THaVDCHit.h" #include "THaVDCTimeToDistConv.h" #include "TError.h" const Double_t THaVDCHit::kBig = 1.e38; // Arbitrary large value using namespace VDC; //_____________________________________________________________________________ Double_t THaVDCHit::ConvertTimeToDist(Double_t slope) { // Converts TDC time to drift distance // Takes the (estimated) slope of the track as an argument VDC::TimeToDistConv* ttdConv = (fWire) ? fWire->GetTTDConv() : NULL; if (ttdConv) { // If a time to distance algorithm exists, use it to convert the TDC time // to the drift distance fDist = ttdConv->ConvertTimeToDist(fTime, slope, &fdDist); return fDist; } Error("ConvertTimeToDist()", "No Time to dist algorithm available"); return 0.0; } //_____________________________________________________________________________ Int_t THaVDCHit::Compare( const TObject* obj ) const { // Used to sort hits // A hit is "less than" another hit if it occurred on a lower wire number. // Also, for hits on the same wire, the first hit on the wire (the one with // the smallest time) is "less than" one with a higher time. If the hits // are sorted according to this scheme, they will be in order of increasing // wire number and, for each wire, will be in the order in which they hit // the wire assert( obj && IsA() == obj->IsA() ); if( obj == this ) return 0; #ifndef NDEBUG const THaVDCHit* other = dynamic_cast<const THaVDCHit*>( obj ); assert( other ); #else const THaVDCHit* other = static_cast<const THaVDCHit*>( obj ); #endif ByWireThenTime isless; if( isless( this, other ) ) return -1; if( isless( other, this ) ) return 1; return 0; } //_____________________________________________________________________________ ClassImp(THaVDCHit)
33.985714
79
0.570408
chandabindu
e018e31589187c6fc952e9abd3dfc6967b20aa87
25,774
cpp
C++
foedus_code/experiments-core/src/foedus/graphlda/lda.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/experiments-core/src/foedus/graphlda/lda.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
foedus_code/experiments-core/src/foedus/graphlda/lda.cpp
sam1016yu/cicada-exp-sigmod2017
64e582370076b2923d37b279d1c32730babc15f8
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2014-2015, Hewlett-Packard Development Company, LP. * 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 * * HP designates this particular file as subject to the "Classpath" exception * as provided by HP in the LICENSE.txt file that accompanied this code. */ /** * @file foedus/graphlda/lda.cpp * @brief Latent-Dirichlet Allocation experiment for Topic Modeling * @author kimurhid * @date 2014/11/22 * @details * This is a port of Fei Chen's LDA topic modeling program to FOEDUS. */ #include <stdint.h> #include <boost/math/special_functions/gamma.hpp> #include <gflags/gflags.h> #include <glog/logging.h> #include <algorithm> #include <fstream> #include <iostream> #include <string> #include <vector> #include "foedus/engine.hpp" #include "foedus/engine_options.hpp" #include "foedus/error_stack.hpp" #include "foedus/debugging/debugging_supports.hpp" #include "foedus/debugging/stop_watch.hpp" #include "foedus/fs/filesystem.hpp" #include "foedus/memory/engine_memory.hpp" #include "foedus/proc/proc_manager.hpp" #include "foedus/soc/shared_memory_repo.hpp" #include "foedus/soc/soc_manager.hpp" #include "foedus/storage/storage_id.hpp" #include "foedus/storage/storage_manager.hpp" #include "foedus/storage/array/array_storage.hpp" #include "foedus/thread/numa_thread_scope.hpp" #include "foedus/thread/thread.hpp" #include "foedus/thread/thread_pool.hpp" #include "foedus/thread/thread_pool_pimpl.hpp" #include "foedus/xct/xct_id.hpp" #include "foedus/xct/xct_manager.hpp" namespace foedus { namespace graphlda { DEFINE_string(dictionary_fname, "dictionary.txt", "Dictionary file"); DEFINE_string(counts_fname, "counts.tsv", "Counts file"); DEFINE_int32(ntopics, 50, "Number of topics"); DEFINE_int32(nburnin, 50, "Number of burnin iterations"); DEFINE_int32(nsamples, 10, "Number of sampling iterations"); DEFINE_int32(nthreads, 16, "Total number of threads"); DEFINE_double(alpha, 1.0, "Alpha prior"); DEFINE_double(beta, 0.1, "Beta prior"); DEFINE_bool(fork_workers, false, "Whether to fork(2) worker threads in child processes rather" " than threads in the same process. This is required to scale up to 100+ cores."); DEFINE_bool(profile, false, "Whether to profile the execution with gperftools."); typedef uint32_t WordId; typedef uint32_t DocId; typedef uint16_t TopicId; typedef uint32_t Count; const TopicId kNullTopicId = -1; /** Used for overflow check */ const Count kUnreasonablyLargeUint32 = (0xFFFF0000U); inline Count check_overflow(Count count) { if (count > kUnreasonablyLargeUint32) { return 0; } else { return count; } } // storage names /** * n_td(t,d) [1d: d * ntopics + t] Number of occurences of topic t in document d. * As an array storage, it's d records of ntopics Count. */ const char* kNtd = "n_td"; /** * n_tw(t,w) [1d: w * ntopics + t] Number of occurences of word w in topic t. * As an array storage, it's w records of ntopics Count. */ const char* kNtw = "n_tw"; /** * n_t(t) [1d: t] The total number of words assigned to topic t. * As an array storage, it's 1 record of ntopics Count. */ const char* kNt = "n_t"; struct Token { WordId word; DocId doc; Token(WordId word = 0, DocId doc = 0) : word(word), doc(doc) { } }; std::ostream& operator<<(std::ostream& out, const Token& tok) { return out << "(" << tok.word << ", " << tok.doc << ")"; } /** This object is held only by the driver thread. Individual worker uses SharedInputs. */ struct Corpus { size_t nwords, ndocs, ntokens; std::vector< Token > tokens; std::vector<std::string> dictionary; Corpus(const fs::Path& dictionary_fname, const fs::Path& counts_fname) : nwords(0), ndocs(0), ntokens(0) { dictionary.reserve(20000); tokens.reserve(100000); load_dictionary(dictionary_fname); load_counts(counts_fname); } void load_dictionary(const fs::Path& fname) { std::ifstream fin(fname.c_str()); std::string str; while (fin.good()) { std::getline(fin, str); if (fin.good()) { dictionary.push_back(str); nwords++; } } fin.close(); } void load_counts(const fs::Path& fname) { std::ifstream fin(fname.c_str()); while (fin.good()) { // Read a collection of tokens const size_t NULL_VALUE(-1); size_t word = NULL_VALUE, doc = NULL_VALUE, count = NULL_VALUE; fin >> doc >> word >> count; if (fin.good()) { ASSERT_ND(word != NULL_VALUE && doc != NULL_VALUE && count != NULL_VALUE); // update the doc counter ndocs = std::max(ndocs, doc + 1); // Assert valid word ASSERT_ND(word < nwords); // Update the words in document counter // Add all the tokens Token tok; tok.word = word; tok.doc = doc; for (size_t i = 0; i < count; ++i) { tokens.push_back(tok); } } } fin.close(); ntokens = tokens.size(); } }; /** A copy of essential parts of Corpus, which can be placed in shared memory. No vector/string */ struct SharedInputs { uint32_t nwords; uint32_t ndocs; uint32_t ntokens; uint32_t ntopics; uint32_t niterations; double alpha; double beta; /** * Actually "Token tokens[ntokens]" and then "TopicId topics[ntokens]". * Note that you can't do sizeof(SharedCorpus). */ char dynamic_data[8]; static uint64_t get_object_size(uint32_t ntokens) { return sizeof(SharedInputs) + (sizeof(Token) + sizeof(TopicId)) * ntokens; } void init(const Corpus& original) { nwords = original.nwords; ndocs = original.ndocs; ntokens = original.ntokens; ntopics = FLAGS_ntopics; niterations = 0; // set separately alpha = FLAGS_alpha; beta = FLAGS_beta; std::memcpy(get_tokens_data(), &(original.tokens[0]), sizeof(Token) * ntokens); std::memset(get_topics_data(), 0xFFU, sizeof(TopicId) * ntokens); // null topic ID } Token* get_tokens_data() { return reinterpret_cast<Token*>(dynamic_data); } TopicId* get_topics_data() { return reinterpret_cast<TopicId*>(dynamic_data + sizeof(Token) * ntokens); } }; /** Core implementation of LDA experiment. */ class LdaWorker { public: enum Constant { kIntNormalizer = 1 << 24, kNtApplyBatch = 1 << 8, }; explicit LdaWorker(const proc::ProcArguments& args) { engine = args.engine_; context = args.context_; shared_inputs = reinterpret_cast<SharedInputs*>( engine->get_soc_manager()->get_shared_memory_repo()->get_global_user_memory()); *args.output_used_ = 0; } ErrorStack on_lda_worker_task() { uint16_t thread_id = context->get_thread_global_ordinal(); LOG(INFO) << "Thread-" << thread_id << " started"; unirand.set_current_seed(thread_id); Token* shared_tokens = shared_inputs->get_tokens_data(); ntopics = shared_inputs->ntopics; ntopics_aligned = assorted::align8(ntopics); numwords = shared_inputs->nwords; TopicId* shared_topics = shared_inputs->get_topics_data(); const uint32_t numtokens = shared_inputs->ntokens; const uint32_t niterations = shared_inputs->niterations; const uint16_t all_threads = engine->get_options().thread_.get_total_thread_count(); tokens_per_core = numtokens / all_threads; int_a = static_cast<uint64_t>(shared_inputs->alpha * kIntNormalizer); int_b = static_cast<uint64_t>(shared_inputs->beta * kIntNormalizer); // allocate tmp memory on local NUMA node. // These are the only memory that need dynamic allocation in main_loop uint64_t tmp_memory_size = ntopics_aligned * sizeof(uint64_t) // conditional + tokens_per_core * sizeof(Token) // assigned_tokens + ntopics_aligned * sizeof(Count) // record_td + ntopics_aligned * sizeof(Count) // record_tw + ntopics_aligned * sizeof(Count) // record_t + ntopics_aligned * sizeof(Count) // record_t_diff + tokens_per_core * sizeof(TopicId); // topics_tmp tmp_memory.alloc( tmp_memory_size, 1 << 21, memory::AlignedMemory::kNumaAllocOnnode, context->get_numa_node()); char* tmp_block = reinterpret_cast<char*>(tmp_memory.get_block()); int_conditional = reinterpret_cast<uint64_t*>(tmp_block); tmp_block += ntopics_aligned * sizeof(uint64_t); assigned_tokens = reinterpret_cast<Token*>(tmp_block); tmp_block += tokens_per_core * sizeof(Token); record_td = reinterpret_cast<Count*>(tmp_block); tmp_block += ntopics_aligned * sizeof(Count); record_tw = reinterpret_cast<Count*>(tmp_block); tmp_block += ntopics_aligned * sizeof(Count); record_t = reinterpret_cast<Count*>(tmp_block); tmp_block += ntopics_aligned * sizeof(Count); record_t_diff = reinterpret_cast<Count*>(tmp_block); tmp_block += ntopics_aligned * sizeof(Count); topics_tmp = reinterpret_cast<TopicId*>(tmp_block); tmp_block += tokens_per_core * sizeof(TopicId); uint64_t size_check = tmp_block - reinterpret_cast<char*>(tmp_memory.get_block()); ASSERT_ND(size_check == tmp_memory_size); // initialize with previous result (if this is burnin, all null-topic) uint64_t assign_pos = tokens_per_core * thread_id; std::memcpy(topics_tmp, shared_topics + assign_pos, tokens_per_core * sizeof(TopicId)); std::memcpy(assigned_tokens, shared_tokens + assign_pos, tokens_per_core * sizeof(Token)); n_td = storage::array::ArrayStorage(engine, kNtd); n_tw = storage::array::ArrayStorage(engine, kNtw); n_t = storage::array::ArrayStorage(engine, kNt); ASSERT_ND(n_td.exists()); ASSERT_ND(n_tw.exists()); ASSERT_ND(n_t.exists()); nchanges = 0; std::memset(int_conditional, 0, sizeof(uint64_t) * ntopics_aligned); std::memset(record_td, 0, sizeof(Count) * ntopics_aligned); std::memset(record_tw, 0, sizeof(Count) * ntopics_aligned); std::memset(record_t, 0, sizeof(Count) * ntopics_aligned); std::memset(record_t_diff, 0, sizeof(Count) * ntopics_aligned); // Loop over all the tokens for (size_t gn = 0; gn < niterations; ++gn) { LOG(INFO) << "Thread-" << thread_id << " iteration " << gn << "/" << niterations; WRAP_ERROR_CODE(main_loop()); } // copy back the topics to shared. it's per-core, so this is the only thread that modifies it. std::memcpy(shared_topics + assign_pos, topics_tmp, tokens_per_core * sizeof(TopicId)); const uint64_t ntotal = niterations * tokens_per_core; LOG(INFO) << "Thread-" << thread_id << " done. nchanges/ntotal=" << nchanges << "/" << ntotal << "=" << (static_cast<double>(nchanges) / ntotal); return kRetOk; } private: Engine* engine; thread::Thread* context; SharedInputs* shared_inputs; uint16_t ntopics; uint16_t ntopics_aligned; uint32_t numwords; uint32_t tokens_per_core; uint64_t nchanges; uint64_t int_a; uint64_t int_b; storage::array::ArrayStorage n_td; // d records of ntopics Count storage::array::ArrayStorage n_tw; // w records of ntopics Count storage::array::ArrayStorage n_t; // 1 record of ntopics Count assorted::UniformRandom unirand; /** local memory to back the followings */ memory::AlignedMemory tmp_memory; uint64_t* int_conditional; // [ntopics] Token* assigned_tokens; // [tokens_per_core] Count* record_td; // [ntopics] Count* record_tw; // [ntopics] Count* record_t; // [ntopics] Count* record_t_diff; // [ntopics]. This batches changes to n_t, which is so contentious. TopicId* topics_tmp; // [tokens_per_core] ErrorCode main_loop() { xct::XctManager* xct_manager = engine->get_xct_manager(); uint16_t batched_t = 0; for (size_t i = 0; i < tokens_per_core; ++i) { // Get the word and document for the ith token const WordId w = assigned_tokens[i].word; const DocId d = assigned_tokens[i].doc; const TopicId old_topic = topics_tmp[i]; CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead)); // First, read from the global arrays CHECK_ERROR_CODE(n_td.get_record(context, d, record_td)); CHECK_ERROR_CODE(n_tw.get_record(context, w, record_tw)); // Construct the conditional uint64_t normalizer = 0; // We do the following calculation without double/float to speed up. // Notation: int_x := x * N (eg, int_ntd := ntd * N, int_alpha = alpha * N) // where N is some big number, such as 2^24 // conditional[t] = (a + ntd) * (b + ntw) / (b * nwords + nt) // <=> conditional[t] = (int_a + int_ntd) * (b + ntw) / (int_b * nwords + int_nt) // <=> int_conditional[t] = (int_a + int_ntd) * (int_b + int_ntw) / (int_b * nwords + int_nt) for (TopicId t = 0; t < ntopics; ++t) { uint64_t int_ntd = record_td[t], int_ntw = record_tw[t], int_nt = record_t[t]; if (t == old_topic) { // locally apply the decrements. we apply it to global array // when we are sure that new_topic != old_topic --int_ntd; --int_ntw; --int_nt; } int_ntd = check_overflow(int_ntd) * kIntNormalizer; int_ntw = check_overflow(int_ntw) * kIntNormalizer; int_nt = check_overflow(int_nt) * kIntNormalizer; int_conditional[t] = (int_a + int_ntd) * (int_b + int_ntw) / (int_b * numwords + int_nt); normalizer += int_conditional[t]; } // Draw a new valuez TopicId new_topic = topic_multinomial(normalizer); // Update the topic assignment and counters if (new_topic != old_topic) { nchanges++; topics_tmp[i] = new_topic; // We apply the inc/dec to global array only in this case. if (old_topic != kNullTopicId) { // Remove the word from the old counters uint16_t offset = old_topic * sizeof(Count); CHECK_ERROR_CODE(n_td.increment_record_oneshot<Count>(context, d, -1, offset)); CHECK_ERROR_CODE(n_tw.increment_record_oneshot<Count>(context, w, -1, offset)); // change to t are batched. will be applied later --record_t[old_topic]; --record_t_diff[old_topic]; } // Add the word to the new counters uint16_t offset = new_topic * sizeof(Count); CHECK_ERROR_CODE(n_td.increment_record_oneshot<Count>(context, d, 1, offset)); CHECK_ERROR_CODE(n_tw.increment_record_oneshot<Count>(context, w, 1, offset)); ++record_t[new_topic]; ++record_t_diff[new_topic]; Epoch ep; // because this is not serializable level and the only update is one-shot increment, // no race is possible. CHECK_ERROR_CODE(xct_manager->precommit_xct(context, &ep)); ++batched_t; if (batched_t >= kNtApplyBatch) { CHECK_ERROR_CODE(sync_record_t()); batched_t = 0; } } else { CHECK_ERROR_CODE(xct_manager->abort_xct(context)); } } CHECK_ERROR_CODE(sync_record_t()); return kErrorCodeOk; } TopicId topic_multinomial(uint64_t normalizer) { uint64_t sample = unirand.next_uint64() % normalizer; uint64_t cur_sum = 0; for (TopicId t = 0; t < ntopics; ++t) { cur_sum += int_conditional[t]; if (sample <= cur_sum) { return t; } } return ntopics - 1U; } ErrorCode sync_record_t() { xct::XctManager* xct_manager = engine->get_xct_manager(); Epoch ep; // first, "flush" batched increments/decrements to the global n_t // this transactionally applies all the inc/dec. CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead)); for (TopicId t = 0; t < ntopics_aligned; t += 4) { // for each uint64_t. we reserved additional size (align8) for simplifying this. uint64_t diff = *reinterpret_cast<uint64_t*>(&record_t_diff[t]); if (diff != 0) { uint16_t offset = t * sizeof(Count); CHECK_ERROR_CODE(n_t.increment_record_oneshot<uint64_t>(context, 0, diff, offset)); } } CHECK_ERROR_CODE(xct_manager->precommit_xct(context, &ep)); // then, retrive a fresh new copy of record_t, which contains updates from other threads. std::memset(record_t, 0, sizeof(Count) * ntopics_aligned); std::memset(record_t_diff, 0, sizeof(Count) * ntopics_aligned); CHECK_ERROR_CODE(xct_manager->begin_xct(context, xct::kDirtyRead)); CHECK_ERROR_CODE(n_t.get_record(context, 0, record_t)); CHECK_ERROR_CODE(xct_manager->abort_xct(context)); return kErrorCodeOk; } }; ErrorStack lda_worker_task(const proc::ProcArguments& args) { LdaWorker worker(args); return worker.on_lda_worker_task(); } void run_workers(Engine* engine, SharedInputs* shared_inputs, uint32_t niterations) { const EngineOptions& options = engine->get_options(); auto* thread_pool = engine->get_thread_pool(); std::vector< thread::ImpersonateSession > sessions; shared_inputs->niterations = niterations; for (uint16_t node = 0; node < options.thread_.group_count_; ++node) { for (uint16_t ordinal = 0; ordinal < options.thread_.thread_count_per_group_; ++ordinal) { thread::ImpersonateSession session; bool ret = thread_pool->impersonate_on_numa_node( node, "worker_task", nullptr, 0, &session); if (!ret) { LOG(FATAL) << "Couldn't impersonate"; } sessions.emplace_back(std::move(session)); } } LOG(INFO) << "Started running! #iter=" << niterations; for (uint32_t i = 0; i < sessions.size(); ++i) { LOG(INFO) << "result[" << i << "]=" << sessions[i].get_result(); COERCE_ERROR(sessions[i].get_result()); sessions[i].release(); } LOG(INFO) << "Completed"; } ErrorStack lda_populate_array_task(const proc::ProcArguments& args) { ASSERT_ND(args.input_len_ == sizeof(storage::StorageId)); storage::StorageId storage_id = *reinterpret_cast<const storage::StorageId*>(args.input_buffer_); storage::array::ArrayStorage array(args.engine_, storage_id); ASSERT_ND(array.exists()); thread::Thread* context = args.context_; uint16_t nodes = args.engine_->get_options().thread_.group_count_; uint16_t node = context->get_numa_node(); uint64_t records_per_node = array.get_array_size() / nodes; storage::array::ArrayOffset begin = records_per_node * node; storage::array::ArrayOffset end = records_per_node * (node + 1U); WRAP_ERROR_CODE(array.prefetch_pages(context, true, false, begin, end)); LOG(INFO) << "Population of " << array.get_name() << " done in node-" << node; return kRetOk; } void create_count_array( Engine* engine, const char* name, uint64_t records, uint64_t counts) { Epoch ep; uint64_t counts_aligned = assorted::align8(counts); storage::array::ArrayMetadata meta(name, counts_aligned * sizeof(Count), records); COERCE_ERROR(engine->get_storage_manager()->create_storage(&meta, &ep)); LOG(INFO) << "Populating empty " << name << "(id=" << meta.id_ << ")..."; // populate it with one thread per node. const EngineOptions& options = engine->get_options(); auto* thread_pool = engine->get_thread_pool(); std::vector< thread::ImpersonateSession > sessions; for (uint16_t node = 0; node < options.thread_.group_count_; ++node) { thread::ImpersonateSession session; bool ret = thread_pool->impersonate_on_numa_node( node, "populate_array_task", &meta.id_, sizeof(meta.id_), &session); if (!ret) { LOG(FATAL) << "Couldn't impersonate"; } sessions.emplace_back(std::move(session)); } for (uint32_t i = 0; i < sessions.size(); ++i) { LOG(INFO) << "populate result[" << i << "]=" << sessions[i].get_result(); COERCE_ERROR(sessions[i].get_result()); sessions[i].release(); } LOG(INFO) << "Populated empty " << name; } double run_experiment(Engine* engine, const Corpus &corpus) { const EngineOptions& options = engine->get_options(); // Input information placed in shared memory SharedInputs* shared_inputs = reinterpret_cast<SharedInputs*>( engine->get_soc_manager()->get_shared_memory_repo()->get_global_user_memory()); ASSERT_ND(options.soc_.shared_user_memory_size_kb_ * (1ULL << 10) >= SharedInputs::get_object_size(corpus.ntokens)); shared_inputs->init(corpus); // create empty tables. create_count_array(engine, kNtd, corpus.ndocs, FLAGS_ntopics); create_count_array(engine, kNtw, corpus.nwords, FLAGS_ntopics); create_count_array(engine, kNt, 1, FLAGS_ntopics); LOG(INFO) << "Created arrays"; if (FLAGS_profile) { COERCE_ERROR(engine->get_debug()->start_profile("lda.prof")); } debugging::StopWatch watch; run_workers(engine, shared_inputs, FLAGS_nburnin); LOG(INFO) << "Completed burnin!"; run_workers(engine, shared_inputs, FLAGS_nsamples); LOG(INFO) << "Completed final sampling!"; watch.stop(); LOG(INFO) << "Experiment ended. Elapsed time=" << watch.elapsed_sec() << "sec"; if (FLAGS_profile) { engine->get_debug()->stop_profile(); LOG(INFO) << "Check out the profile result: pprof --pdf lda lda.prof > lda.pdf; okular lda.pdf"; } LOG(INFO) << "Shutting down..."; LOG(INFO) << engine->get_memory_manager()->dump_free_memory_stat(); return watch.elapsed_sec(); } int driver_main(int argc, char** argv) { gflags::SetUsageMessage("LDA sampler code"); gflags::ParseCommandLineFlags(&argc, &argv, true); fs::Path dictionary_fname(FLAGS_dictionary_fname); fs::Path counts_fname(FLAGS_counts_fname); if (!fs::exists(dictionary_fname)) { std::cerr << "The dictionary file doesn't exist: " << dictionary_fname; return 1; } else if (!fs::exists(counts_fname)) { std::cerr << "The count file doesn't exist: " << counts_fname; return 1; } fs::Path folder("/dev/shm/foedus_lda"); if (fs::exists(folder)) { fs::remove_all(folder); } if (!fs::create_directories(folder)) { std::cerr << "Couldn't create " << folder << ". err=" << assorted::os_error(); return 1; } EngineOptions options; fs::Path savepoint_path(folder); savepoint_path /= "savepoint.xml"; options.savepoint_.savepoint_path_.assign(savepoint_path.string()); ASSERT_ND(!fs::exists(savepoint_path)); std::cout << "NUMA node count=" << static_cast<int>(options.thread_.group_count_) << std::endl; uint16_t thread_count = FLAGS_nthreads; if (thread_count < options.thread_.group_count_) { std::cout << "nthreads less than socket count. Using subset of sockets" << std::endl; options.thread_.group_count_ = thread_count; options.thread_.thread_count_per_group_ = 1; } else if (thread_count % options.thread_.group_count_ != 0) { std::cout << "nthreads not multiply of #sockets. adjusting" << std::endl; options.thread_.thread_count_per_group_ = thread_count / options.thread_.group_count_; } else { options.thread_.thread_count_per_group_ = thread_count / options.thread_.group_count_; } options.snapshot_.folder_path_pattern_ = "/dev/shm/foedus_lda/snapshot/node_$NODE$"; options.snapshot_.snapshot_interval_milliseconds_ = 100000000U; options.log_.folder_path_pattern_ = "/dev/shm/foedus_lda/log/node_$NODE$/logger_$LOGGER$"; options.log_.loggers_per_node_ = 1; options.log_.flush_at_shutdown_ = false; options.log_.log_file_size_mb_ = 1 << 16; options.log_.emulation_.null_device_ = true; options.memory_.page_pool_size_mb_per_node_ = 1 << 8; options.cache_.snapshot_cache_size_mb_per_node_ = 1 << 6; if (FLAGS_fork_workers) { std::cout << "Will fork workers in child processes" << std::endl; options.soc_.soc_type_ = kChildForked; } options.debugging_.debug_log_min_threshold_ = debugging::DebuggingOptions::kDebugLogInfo; // = debugging::DebuggingOptions::kDebugLogWarning; options.debugging_.verbose_modules_ = ""; options.debugging_.verbose_log_level_ = -1; std::cout << "Loading the corpus." << std::endl; Corpus corpus(dictionary_fname, counts_fname); std::cout << "Number of words: " << corpus.nwords << std::endl << "Number of docs: " << corpus.ndocs << std::endl << "Number of tokens: " << corpus.ntokens << std::endl << "Number of topics: " << FLAGS_ntopics << std::endl << "Number of threads: " << options.thread_.get_total_thread_count() << std::endl << "Alpha: " << FLAGS_alpha << std::endl << "Beta: " << FLAGS_beta << std::endl; options.soc_.shared_user_memory_size_kb_ = (SharedInputs::get_object_size(corpus.ntokens) >> 10) + 64; double elapsed; { Engine engine(options); engine.get_proc_manager()->pre_register("worker_task", lda_worker_task); engine.get_proc_manager()->pre_register("populate_array_task", lda_populate_array_task); COERCE_ERROR(engine.initialize()); { UninitializeGuard guard(&engine); elapsed = run_experiment(&engine, corpus); COERCE_ERROR(engine.uninitialize()); } } std::cout << "All done. elapsed time=" << elapsed << "sec" << std::endl; return 0; } } // namespace graphlda } // namespace foedus int main(int argc, char **argv) { return foedus::graphlda::driver_main(argc, argv); }
36.767475
100
0.680376
sam1016yu
e0208280f335a12f6264e041e2da3936af6a783e
371
cpp
C++
test/src/access.cpp
mathchq/rapidstring
b9cd820ebe3076797ff82c7a3ca741b4bef74961
[ "MIT" ]
1
2019-11-11T13:02:15.000Z
2019-11-11T13:02:15.000Z
test/src/access.cpp
mathchq/rapidstring
b9cd820ebe3076797ff82c7a3ca741b4bef74961
[ "MIT" ]
null
null
null
test/src/access.cpp
mathchq/rapidstring
b9cd820ebe3076797ff82c7a3ca741b4bef74961
[ "MIT" ]
null
null
null
#include "utility.hpp" #include <string> TEST_CASE("data") { const std::string first{ "Short!" }; const std::string second{ "A very long string to get around SSO!" }; rapidstring s1; rs_init_w(&s1, first.data()); REQUIRE(first == rs_data(&s1)); rapidstring s2; rs_init_w(&s2, second.data()); REQUIRE(second == rs_data(&s2)); rs_free(&s1); rs_free(&s2); }
17.666667
69
0.657682
mathchq
e02082c49cb7e4edd96cf299c82dc2db5227dc98
2,425
cpp
C++
detail/os/reactor/kqueue/events/kqueue_recv_from.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
null
null
null
detail/os/reactor/kqueue/events/kqueue_recv_from.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
1
2020-06-12T10:22:09.000Z
2020-06-12T10:22:09.000Z
detail/os/reactor/kqueue/events/kqueue_recv_from.cpp
wembikon/baba.io
87bec680c1febb64356af59e7e499c2b2b64d30c
[ "MIT" ]
null
null
null
/** * MIT License * Copyright (c) 2020 Adrian T. Visarra **/ #include "os/reactor/kqueue/events/kqueue_recv_from.h" #include "baba/semantics.h" #include "os/common/event_registrar.h" namespace baba::os { kqueue_recv_from::kqueue_recv_from(const lifetime &scope, const std::shared_ptr<reactor_io_descriptor> &io_desc, const enqueue_for_initiation_fn &enqueue_for_initiation, const register_to_reactor_fn &register_to_reactor, const enqueue_for_completion_fn &enqueue_for_completion, const recv_from_fn &do_recv_from) noexcept : _do_recv_from(do_recv_from), _evt(event_registrar::take()) { RUNTIME_ASSERT(scope); RUNTIME_ASSERT(io_desc); _evt->scope = scope; _evt->descriptor = io_desc; _evt->enqueue_for_initiation = enqueue_for_initiation; _evt->register_to_reactor = register_to_reactor; _evt->enqueue_for_completion = enqueue_for_completion; } kqueue_recv_from::~kqueue_recv_from() noexcept { auto final_evt = event_registrar::take(); final_evt->initiate = [final_evt, evt = _evt](io_handle) { final_evt->complete = [final_evt, evt]() { event_registrar::give(evt); event_registrar::give(final_evt); }; evt->enqueue_for_completion(final_evt); }; _evt->enqueue_for_initiation(final_evt); } void kqueue_recv_from::recv_from(const ip_endpoint &receiver_ep, uint8_t *buffer, int size, ip_endpoint &peer_ep, const receive_finish_fn &cb) noexcept { _evt->initiate = [evt = _evt, cb](io_handle kqueue_fd) { const auto ec = evt->register_to_reactor(kqueue_fd, evt, EVFILT_READ, 0, 0); if (ec != ec::OK) { evt->complete = [ec, cb]() { cb(ec, 0); }; evt->enqueue_for_completion(evt); } }; _evt->react = [evt = _evt, do_recv_from = _do_recv_from, &receiver_ep, buffer, size, &peer_ep, cb]() { int bytes = 0; const auto ec = do_recv_from(evt->descriptor->fd, receiver_ep, buffer, size, peer_ep, bytes); evt->complete = [ec, bytes, cb]() { cb(ec, bytes); }; evt->enqueue_for_completion(evt); }; _evt->enqueue_for_initiation(_evt); } void kqueue_recv_from::recv_from() noexcept { _evt->enqueue_for_initiation(_evt); } } // namespace baba::os
39.112903
98
0.641237
wembikon
e02341b4bc420c5d0558915521c41a8e64ee7706
2,264
cc
C++
ChiTech/ChiMesh/UnpartitionedMesh/lua/create.cc
Jrgriss2/chi-tech
db75df761d5f25ca4b79ee19d36f886ef240c2b5
[ "MIT" ]
null
null
null
ChiTech/ChiMesh/UnpartitionedMesh/lua/create.cc
Jrgriss2/chi-tech
db75df761d5f25ca4b79ee19d36f886ef240c2b5
[ "MIT" ]
null
null
null
ChiTech/ChiMesh/UnpartitionedMesh/lua/create.cc
Jrgriss2/chi-tech
db75df761d5f25ca4b79ee19d36f886ef240c2b5
[ "MIT" ]
null
null
null
#include "../../../ChiLua/chi_lua.h" #include "../chi_unpartitioned_mesh.h" #include "ChiMesh/MeshHandler/chi_meshhandler.h" /** \defgroup LuaUnpartitionedMesh Unpartitioned Mesh-Reader * \ingroup LuaMesh */ //################################################################### /**Creates an unpartitioned mesh from VTK Unstructured mesh files. * * \image html "InProgressImage.png" width=200px * * \param file_name char Filename of the .vtu file. * * \ingroup LuaUnpartitionedMesh * * \return A handle to the newly created UnpartitionedMesh*/ int chiUnpartitionedMeshFromVTU(lua_State* L) { const char func_name[] = "chiUnpartitionedMeshFromVTU"; int num_args = lua_gettop(L); if (num_args != 1) LuaPostArgAmountError(func_name,1,num_args); const char* temp = lua_tostring(L,1); auto new_object = new chi_mesh::UnpartitionedMesh; chi_mesh::UnpartitionedMesh::Options options; options.file_name = std::string(temp); new_object->ReadFromVTU(options); auto handler = chi_mesh::GetCurrentHandler(); handler->unpartitionedmesh_stack.push_back(new_object); lua_pushnumber(L,handler->unpartitionedmesh_stack.size()-1); return 1; } //################################################################### /**Creates an unpartitioned mesh from starccm+ exported * Ensight Gold mesh files. * * \param file_name char Filename of the .case file. * \param scale float Scale to apply to the mesh * * \ingroup LuaUnpartitionedMesh * * \return A handle to the newly created UnpartitionedMesh*/ int chiUnpartitionedMeshFromEnsightGold(lua_State* L) { const char func_name[] = "chiUnpartitionedMeshFromEnsightGold"; int num_args = lua_gettop(L); if (num_args <1) LuaPostArgAmountError(func_name,1,num_args); const char* temp = lua_tostring(L,1); double scale = 1.0; if (num_args >= 2) scale = lua_tonumber(L,2); auto new_object = new chi_mesh::UnpartitionedMesh; chi_mesh::UnpartitionedMesh::Options options; options.file_name = std::string(temp); options.scale = scale; new_object->ReadFromEnsightGold(options); auto handler = chi_mesh::GetCurrentHandler(); handler->unpartitionedmesh_stack.push_back(new_object); lua_pushnumber(L,handler->unpartitionedmesh_stack.size()-1); return 1; }
29.025641
69
0.70053
Jrgriss2
e025e5f805617de080c45ae6a3949e93a36d99f2
1,879
hpp
C++
inst/include/spress/hilbert.hpp
UFOKN/spress
8073fde53ced4f006634f761e6f90517ccf2f229
[ "MIT" ]
1
2021-12-09T22:16:27.000Z
2021-12-09T22:16:27.000Z
inst/include/spress/hilbert.hpp
UFOKN/spress
8073fde53ced4f006634f761e6f90517ccf2f229
[ "MIT" ]
null
null
null
inst/include/spress/hilbert.hpp
UFOKN/spress
8073fde53ced4f006634f761e6f90517ccf2f229
[ "MIT" ]
null
null
null
#pragma once #ifndef _SPRESS_HILBERT_H_ #define _SPRESS_HILBERT_H_ #include <numeric> using std::size_t; namespace spress { namespace hilbert { /** * Rotate X/Y coordinates based on Hilbert Curve. * @param n Dimensions of n x n grid. Must be a power of 2. * @param x [out] Pointer to the X coordinate variable * @param y [out] Pointer to the Y coordinate variable * @param rx Numeric bool for determining if rotation is needed * @param ry Numeric bool for determining if rotation is needed */ inline void rotate(size_t n, size_t *x, size_t *y, size_t rx, size_t ry) { if (ry == 0) { if (rx == 1) { *x = n - 1LL - *x; *y = n - 1LL - *y; } size_t t = *x; *x = *y; *y = t; } } /** * Convert a grid position to a Hilbert Curve index. * @param n Dimensions of n x n grid. Must be a power of 2. * @param x X coordinate in grid form * @param y Y coordinate in grid form */ inline size_t pos_index(size_t n, size_t x, size_t y) { size_t rx, ry; size_t d = 0LL; for (size_t s = n / 2LL; s > 0LL; s /= 2LL) { rx = (x & s) > 0LL; ry = (y & s) > 0LL; d += s * s * ((3LL * rx) ^ ry); rotate(n, &x, &y, rx, ry); } return d; } /** * Convert a Hilbert Curve index to a grid position. * @param n Dimensions of n x n grid. Must be a power of 2. * @param d Hilbert Curve index/distance. * @param x [out] Pointer to X coordinate variable * @param y [out] Pointer to Y coordinate variable */ inline void index_pos(size_t n, size_t d, size_t *x, size_t *y) { size_t rx, ry; size_t t = d; *x = 0LL; *y = 0LL; for (size_t s = 1LL; s < n; s *= 2LL) { rx = 1LL & (t / 2LL); ry = 1LL & (t ^ rx); rotate(s, x, y, rx, ry); *x += s * rx; *y += s * ry; t /= 4LL; } } } } #endif
22.638554
72
0.557743
UFOKN
e028ab7a30e55a3b90c8a5fab3112bfa01ca55f0
8,931
cpp
C++
src/utils/fns.cpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
13
2017-01-07T07:48:54.000Z
2021-09-29T05:33:38.000Z
src/utils/fns.cpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
27
2016-11-24T11:35:22.000Z
2022-02-14T14:38:09.000Z
src/utils/fns.cpp
melchor629/node-flac-bindings
584bd52ef12de4562dca0f198220f2c136666ce2
[ "0BSD" ]
3
2017-10-19T10:12:11.000Z
2019-10-11T16:21:09.000Z
#include "converters.hpp" #include "js_utils.hpp" #include "pointer.hpp" namespace flac_bindings { static int64_t readI32(const void* buff) { return *((const int32_t*) buff); } static void writeI32(void* buff, int64_t value) { *((int32_t*) buff) = value; } static int64_t readI24(const void* buff) { const auto tmp = (const uint8_t*) buff; const uint64_t val = tmp[0] | (tmp[1] << 8) | (tmp[2] << 16); return val | (val & 0x800000) * 0x1FE; } static void writeI24(void* buff, int64_t value) { auto tmp = (uint8_t*) buff; tmp[0] = value & 0xFF; tmp[1] = (value >> 8) & 0xFF; tmp[2] = (value >> 16) & 0xFF; } static int64_t readI16(const void* buff) { return *((const int16_t*) buff); } static void writeI16(void* buff, int64_t value) { *((int16_t*) buff) = value; } static int64_t readI8(const void* buff) { return *((const int8_t*) buff); } static void writeI8(void* buff, int64_t value) { *((int8_t*) buff) = value; } typedef int64_t (*BufferReader)(const void* buff); static inline BufferReader getReader(uint64_t inBps, Napi::Env env) { switch (inBps) { case 1: return readI8; case 2: return readI16; case 3: return readI24; case 4: return readI32; default: throw Napi::Error::New(env, "Unsupported "s + std::to_string(inBps) + " bits per sample"s); } } typedef void (*BufferWriter)(void* buff, int64_t); static inline BufferWriter getWriter(uint64_t outBps, Napi::Env env) { switch (outBps) { case 1: return writeI8; case 2: return writeI16; case 3: return writeI24; case 4: return writeI32; default: throw Napi::Error::New(env, "Unsupported "s + std::to_string(outBps) + " bits per sample"s); } } static Napi::Value zipAudio(const Napi::CallbackInfo& info) { using namespace Napi; EscapableHandleScope scope(info.Env()); if (!info[0].IsObject()) { throw TypeError::New(info.Env(), "Expected first argument to be object"); } auto obj = info[0].As<Object>(); auto samples = numberFromJs<uint64_t>(obj.Get("samples")); auto inBps = maybeNumberFromJs<uint64_t>(obj.Get("inBps")).value_or(4); auto outBps = maybeNumberFromJs<uint64_t>(obj.Get("outBps")).value_or(4); auto buffers = arrayFromJs<char*>(obj.Get("buffers"), [&samples, &inBps](auto val) { if (!val.IsBuffer()) { throw TypeError::New(val.Env(), "Expected value in buffers to be a Buffer"); } auto buffer = val.template As<Buffer<char>>(); if (buffer.ByteLength() < samples * inBps) { throw RangeError::New( val.Env(), "Buffer has size "s + std::to_string(buffer.ByteLength()) + " but expected to be at least "s + std::to_string(samples * inBps)); } return buffer.Data(); }); auto channels = buffers.size(); if (samples == 0 || inBps == 0 || outBps == 0 || channels == 0) { throw Error::New(info.Env(), "Invalid value for one of the given properties"); } // NOTE: if outBps > inBps means that after one sample copy, there is some bytes that need // to be cleared up. To be faster, all memory is cleared when allocated. // the reader and writer functions are here to properly read and write ints. auto reader = getReader(inBps, info.Env()); auto writer = getWriter(outBps, info.Env()); uint64_t outputBufferSize = samples * outBps * channels; char* outputBuffer = (char*) (outBps <= inBps ? malloc(outputBufferSize) : calloc(outputBufferSize, 1)); for (uint64_t sample = 0; sample < samples; sample++) { for (uint64_t channel = 0; channel < channels; channel++) { char* out = outputBuffer + (sample * channels + channel) * outBps; char* in = buffers[channel] + sample * inBps; auto value = reader(in); writer(out, value); } } return scope.Escape( Buffer<char>::New(info.Env(), outputBuffer, outputBufferSize, [](auto, auto data) { free(data); })); } static Napi::Value unzipAudio(const Napi::CallbackInfo& info) { using namespace Napi; EscapableHandleScope scope(info.Env()); if (!info[0].IsObject()) { throw TypeError::New(info.Env(), "Expected first argument to be object"); } auto obj = info[0].As<Object>(); auto inBps = maybeNumberFromJs<uint64_t>(obj.Get("inBps")).value_or(4); auto outBps = maybeNumberFromJs<uint64_t>(obj.Get("outBps")).value_or(4); auto channels = maybeNumberFromJs<uint64_t>(obj.Get("channels")).value_or(2); auto bufferPair = pointer::fromBuffer<char>(obj.Get("buffer")); auto buffer = std::get<0>(bufferPair); uint64_t samples = maybeNumberFromJs<uint64_t>(obj.Get("samples")) .value_or(std::get<1>(bufferPair) / inBps / channels); if (inBps == 0 || outBps == 0 || samples == 0 || channels == 0) { throw Error::New(info.Env(), "Invalid value for one of the given properties"); } if (std::get<1>(bufferPair) < samples * inBps * channels) { throw RangeError::New( info.Env(), "Buffer has size "s + std::to_string(std::get<1>(bufferPair)) + " but expected to be at least "s + std::to_string(samples * inBps * channels)); } // NOTE: see above function note about the outputBuffer auto reader = getReader(inBps, info.Env()); auto writer = getWriter(outBps, info.Env()); uint64_t outputBufferSize = samples * outBps; std::vector<char*> outputBuffers(channels); for (uint64_t channel = 0; channel < channels; channel += 1) { outputBuffers[channel] = (char*) (outBps <= inBps ? malloc(outputBufferSize) : calloc(outputBufferSize, 1)); } for (uint64_t sample = 0; sample < samples; sample++) { for (uint64_t channel = 0; channel < channels; channel += 1) { char* out = outputBuffers[channel] + sample * outBps; char* in = buffer + (sample * channels + channel) * inBps; auto value = reader(in); writer(out, value); } } auto array = Napi::Array::New(info.Env(), channels); for (uint64_t channel = 0; channel < channels; channel += 1) { array[channel] = Buffer<char>::New( info.Env(), outputBuffers[channel], outputBufferSize, [](auto, auto data) { free(data); }); } return scope.Escape(array); } static Napi::Value convertSampleFormat(const Napi::CallbackInfo& info) { using namespace Napi; EscapableHandleScope scope(info.Env()); if (!info[0].IsObject()) { throw TypeError::New(info.Env(), "Expected first argument to be object"); } auto obj = info[0].As<Object>(); auto inBps = maybeNumberFromJs<uint64_t>(obj.Get("inBps")).value_or(4); auto outBps = maybeNumberFromJs<uint64_t>(obj.Get("outBps")).value_or(4); if (inBps == outBps) { return scope.Escape(obj.Get("buffer")); } auto bufferPair = pointer::fromBuffer<char>(obj.Get("buffer")); auto buffer = std::get<0>(bufferPair); uint64_t samples = maybeNumberFromJs<uint64_t>(obj.Get("samples")).value_or(std::get<1>(bufferPair) / inBps); if (inBps == 0 || outBps == 0 || samples == 0) { throw Error::New(info.Env(), "Invalid value for one of the given properties"); } if (std::get<1>(bufferPair) < samples * inBps) { throw RangeError::New( info.Env(), "Buffer has size "s + std::to_string(std::get<1>(bufferPair)) + " but expected to be at least "s + std::to_string(samples * inBps)); } // NOTE: see above function note about the outputBuffer auto reader = getReader(inBps, info.Env()); auto writer = getWriter(outBps, info.Env()); uint64_t outputBufferSize = samples * outBps; char* outputBuffer = (char*) (outBps <= inBps ? malloc(outputBufferSize) : calloc(outputBufferSize, 1)); for (uint64_t sample = 0; sample < samples; sample++) { char* out = outputBuffer + sample * outBps; char* in = buffer + sample * inBps; auto value = reader(in); writer(out, value); } return scope.Escape( Buffer<char>::New(info.Env(), outputBuffer, outputBufferSize, [](auto, auto data) { free(data); })); } Napi::Object initFns(Napi::Env env) { using namespace Napi; EscapableHandleScope scope(env); auto obj = Object::New(env); obj.DefineProperties({ PropertyDescriptor::Function(env, obj, "zipAudio", zipAudio, napi_enumerable), PropertyDescriptor::Function(env, obj, "unzipAudio", unzipAudio, napi_enumerable), PropertyDescriptor::Function( env, obj, "convertSampleFormat", convertSampleFormat, napi_enumerable), }); return scope.Escape(objectFreeze(obj)).As<Object>(); } }
34.218391
100
0.616504
melchor629
e029d475bc384d9bcb173b09da13adbc7dacb371
298
cpp
C++
cpp/ql/test/library-tests/functions/getathrowntype/test.cpp
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
4,036
2020-04-29T00:09:57.000Z
2022-03-31T14:16:38.000Z
cpp/ql/test/library-tests/functions/getathrowntype/test.cpp
vadi2/codeql
a806a4f08696d241ab295a286999251b56a6860c
[ "MIT" ]
2,970
2020-04-28T17:24:18.000Z
2022-03-31T22:40:46.000Z
cpp/ql/test/library-tests/functions/getathrowntype/test.cpp
ScriptBox99/github-codeql
2ecf0d3264db8fb4904b2056964da469372a235c
[ "MIT" ]
794
2020-04-29T00:28:25.000Z
2022-03-30T08:21:46.000Z
void func1() noexcept; void func2() noexcept(true); void func3() noexcept(false); void func4() noexcept(func1); void func5(void param() noexcept); void func6() throw(); void func7() throw(int); void func8() throw(char, int); void func8() throw(char, int) { } class c { void func9() throw(); };
15.684211
34
0.674497
vadi2
e03130660378d31649865753bed09d77bdf8fa81
1,530
hh
C++
transformations/interpolation/SegmentWise.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
5
2019-10-14T01:06:57.000Z
2021-02-02T16:33:06.000Z
transformations/interpolation/SegmentWise.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
transformations/interpolation/SegmentWise.hh
gnafit/gna
c1a58dac11783342c97a2da1b19c97b85bce0394
[ "MIT" ]
null
null
null
#pragma once #include "GNAObject.hh" /** * @brief Determines the bins edges indices for a sorted array. * * For a given array of bin edges: * ```python * edges=(e1, e2, ..., eN) * ``` * * And for a given array of points: * ```python * points=(p1, p2, ..., pM) * ``` * * Determines the indices: * ```python * segments=(n1, n2, ..., nN) * ``` * * So that: * ```python * e1<=points[n1:n2]<e2 * e2<=points[n2:n3]<e3 * ... * eN-1<=points[nN-1:nN]<eN * ``` * * Segments with no points have coinciding indices nI=nJ. * * The transformation is needed in order to implement interpolation, * for example InterpExpoSorted. * * Inputs: * - segments.points - array (to interpolate on). * - segments.edges - edges. * * Outputs: * - segments.segment - segment indices. * - segments.widths - segment widths. * * @note If `edge-point<m_tolerance` is equivalent to `point==edge`. * * @author Maxim Gonchar * @date 02.2018 */ class SegmentWise: public GNAObject, public TransformationBind<SegmentWise> { public: SegmentWise(); ///< Constructor. void setTolerance(double value) { m_tolerance = value; } ///< Set tolerance. void determineSegments(FunctionArgs& fargs); ///< Function that determines segments. private: double m_tolerance{1.e-16}; ///< Tolerance. If point is below left edge on less than m_tolerance, it is considered to belong to the bin anyway. };
25.932203
176
0.598039
gnafit
e031d18b76d91a7c0efe44e0a2bff5e6bc987cf3
446
hpp
C++
lib/utils/BranchPrediction.hpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
[ "MIT" ]
19
2018-12-14T00:51:52.000Z
2022-02-20T02:43:50.000Z
lib/utils/BranchPrediction.hpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
[ "MIT" ]
487
2018-12-13T00:59:53.000Z
2022-02-07T16:12:56.000Z
lib/utils/BranchPrediction.hpp
james-s-willis/kotekan
155e874bb039702cec72c1785362a017548aa00a
[ "MIT" ]
5
2019-05-09T19:52:19.000Z
2021-03-27T20:13:21.000Z
/** * @file * @brief Explicitely instruct the compiler that a branch of execution is more or less likely than * any other. * * Only make use of this if you are certain that your code is actually a bottleneck and that using * this improves performance. */ #ifndef BRANCHPREDICTION_HPP #define BRANCHPREDICTION_HPP #define likely(x) __builtin_expect(!!(x), 1) #define unlikely(x) __builtin_expect(!!(x), 0) #endif // BRANCHPREDICTION_HPP
26.235294
98
0.744395
james-s-willis
e03a164c52cd7b4b6b1d88566f061dfc8a4c784b
793
hpp
C++
test/node-gdal-async/src/geometry/gdal_multilinestring.hpp
mmomtchev/yatag
37802e760a33939b65ceaa4379634529d0dc0092
[ "0BSD" ]
42
2021-03-26T17:34:52.000Z
2022-03-18T14:15:31.000Z
test/node-gdal-async/src/geometry/gdal_multilinestring.hpp
mmomtchev/yatag
37802e760a33939b65ceaa4379634529d0dc0092
[ "0BSD" ]
29
2021-06-03T14:24:01.000Z
2022-03-23T15:43:58.000Z
test/node-gdal-async/src/geometry/gdal_multilinestring.hpp
mmomtchev/yatag
37802e760a33939b65ceaa4379634529d0dc0092
[ "0BSD" ]
8
2021-05-14T19:26:37.000Z
2022-03-21T13:44:42.000Z
#ifndef __NODE_OGR_MULTILINESTRING_H__ #define __NODE_OGR_MULTILINESTRING_H__ // node #include <node.h> #include <node_object_wrap.h> // nan #include "../nan-wrapper.h" // ogr #include <ogrsf_frmts.h> #include "gdal_geometrycollectionbase.hpp" using namespace v8; using namespace node; namespace node_gdal { class MultiLineString : public GeometryCollectionBase<MultiLineString, OGRMultiLineString> { public: static Nan::Persistent<FunctionTemplate> constructor; using GeometryCollectionBase<MultiLineString, OGRMultiLineString>::GeometryCollectionBase; static void Initialize(Local<Object> target); using GeometryCollectionBase<MultiLineString, OGRMultiLineString>::New; static NAN_METHOD(toString); static NAN_METHOD(polygonize); }; } // namespace node_gdal #endif
22.657143
92
0.796974
mmomtchev
e03ca583974d7223395140a16f5b6579c8fe9d2f
12,762
cpp
C++
SVEngine/src/node/SVSpineNode.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
34
2018-09-28T08:28:27.000Z
2022-01-15T10:31:41.000Z
SVEngine/src/node/SVSpineNode.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
null
null
null
SVEngine/src/node/SVSpineNode.cpp
SVEChina/SVEngine
56174f479a3096e57165448142c1822e7db8c02f
[ "MIT" ]
8
2018-10-11T13:36:35.000Z
2021-04-01T09:29:34.000Z
// // SVSpineNode.cpp // SVEngine // Copyright 2017-2020 // yizhou Fu,long Yin,longfei Lin,ziyu Xu,xiaofan Li,daming Li // #include <spine/Slot.h> #include <spine/RegionAttachment.h> #include <spine/MeshAttachment.h> #include "SVSpineNode.h" #include "SVCameraNode.h" #include "SVScene.h" #include "../rendercore/SVRenderMgr.h" #include "../rendercore/SVRenderScene.h" #include "../rendercore/SVRenderMesh.h" #include "../rendercore/SVRenderObject.h" #include "../core/SVSpine.h" #include "../detect/SVDetectMgr.h" #include "../detect/SVDetectBase.h" #include "../event/SVEventMgr.h" #include "../event/SVEvent.h" #include "../event/SVOpEvent.h" #include "../mtl/SVMtlAni2D.h" #include "../mtl/SVTexMgr.h" #include "../mtl/SVTexture.h" #include "../basesys/SVConfig.h" #include "../rendercore/SVRenderer.h" // SVSpineNode::SVSpineNode(SVInst *_app) :SVNode(_app) { ntype = "SVSpineNode"; m_spine = nullptr; m_pRObj = nullptr; m_spine_callback = nullptr; m_p_cb_obj = nullptr; m_visible = false; m_loop = true; m_immediatelyPlay = true; m_state = tANI_STATE_WAIT; m_rsType = RST_SOLID_3D; m_cur_aniname = "animation"; m_canSelect = true; m_aabbBox_scale = 1.0f; } SVSpineNode::~SVSpineNode() { if(m_pRObj){ m_pRObj->clearMesh(); m_pRObj = nullptr; } clearSpine(); m_spine_callback = nullptr; m_p_cb_obj = nullptr; } void SVSpineNode::setSpine(SVSpinePtr _spine) { if (m_spine == _spine) { return; } if (m_spine) { clearSpine(); } m_spine = _spine; if(!m_pRObj){ m_pRObj = MakeSharedPtr<SVMultMeshMtlRenderObject>(); } m_pRObj->clearMesh(); //回调函数 m_spine->m_cb_startListener = [this](s32 itrackId) -> void { _spine_start(); }; // m_spine->m_cb_completeListener = [this](s32 itrackId, s32 iLoopCount) -> void { _spine_complete(); }; // m_spine->m_cb_endListener = [this](s32 itrackId) -> void { _spine_stop(); }; } SVSpinePtr SVSpineNode::getSpine() { return m_spine; } void SVSpineNode::clearSpine() { m_spine = nullptr; } void SVSpineNode::setstate(E_ANISTATE _state){ m_state = _state; } E_ANISTATE SVSpineNode::getstate(){ return m_state; } cptr8 SVSpineNode::getCurAniName(){ return m_cur_aniname.c_str(); } void SVSpineNode::setCurAniName(cptr8 _name){ m_cur_aniname = _name; } void SVSpineNode::setloop(bool _loop){ m_loop = _loop; } bool SVSpineNode::getloop(){ return m_loop; } bool SVSpineNode::isImmediatelyPlay(){ return m_immediatelyPlay; } void SVSpineNode::setSpineCallback(sv_spine_callback _cb,void* _obj) { m_spine_callback = _cb; m_p_cb_obj = _obj; } // void SVSpineNode::update(f32 dt) { if (!m_visible) return; if (m_state == E_ANISTATE::tANI_STATE_STOP) { return; } if( m_pRObj && m_spine) { //spine更新 m_spine->update(dt); _computeAABBBox(); SVNode::update(dt); //更新模型 m_pRObj->clearMesh(); for (s32 i = 0, n = m_spine->m_pSkeleton->slotsCount; i < n; i++) { spSlot *t_slot = m_spine->m_pSkeleton->drawOrder[i]; if (!t_slot->attachment) { continue; //没有挂在项目 } SpineMeshDataPtr pMeshData = m_spine->m_spineDataPool[i]; SVMtlAni2DPtr t_mtl = MakeSharedPtr<SVMtlAni2D>(mApp); t_mtl->setModelMatrix(m_absolutMat.get()); t_mtl->setTexture(0,pMeshData->m_pTex); t_mtl->setBlendEnable(true); t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA); t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_NORMAL); switch (pMeshData->m_blendMode) { case SP_BLEND_MODE_NORMAL:{ if(m_spine->m_preMultAlpha){ t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA); }else{ t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_ALPHA); } break; } case SP_BLEND_MODE_ADDITIVE:{ t_mtl->setBlendState(m_spine->m_preMultAlpha ? MTL_BLEND_ONE : MTL_BLEND_SRC_ALPHA, MTL_BLEND_ONE); t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_ADDITIVE); break; } case SP_BLEND_MODE_MULTIPLY:{ t_mtl->setBlendState(MTL_BLEND_DEST_COLOR, MTL_BLEND_ONE_MINUS_SRC_ALPHA); t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_MULTIPLY); break; } case SP_BLEND_MODE_SCREEN:{ t_mtl->setBlendState(MTL_BLEND_ONE, MTL_BLEND_ONE_MINUS_SRC_COLOR); t_mtl->setBlendMode(SVMtlAni2D::SV_MTL_BLENDMODE_SCREEN); break; } default:{ t_mtl->setBlendState(m_spine->m_preMultAlpha ? MTL_BLEND_ONE : MTL_BLEND_SRC_ALPHA, MTL_BLEND_ONE_MINUS_SRC_ALPHA); break; } } m_pRObj->addRenderObj(pMeshData->m_pRenderMesh,t_mtl); } } } void SVSpineNode::render() { if (!m_visible) return; if (m_state == E_ANISTATE::tANI_STATE_STOP) { return; } // if (!mApp->m_pGlobalParam->m_curScene) // return; SVRenderScenePtr t_rs = mApp->getRenderMgr()->getRenderScene(); if (m_pRObj) { m_pRObj->pushCmd(t_rs, m_rsType, "SVSpineNode"); } SVNode::render(); } void SVSpineNode::play(cptr8 _actname) { if( m_state != E_ANISTATE::tANI_STATE_PLAY ){ if (m_spine) { m_state = E_ANISTATE::tANI_STATE_PLAY; m_cur_aniname = _actname; m_spine->setToSetupPose(); m_spine->setAnimationForTrack(0, _actname, m_loop); m_visible = true; } } } void SVSpineNode::addAni(cptr8 _actname){ if (m_spine) { m_spine->addAnimationForTrack(0, _actname, m_loop,0); } m_visible = true; } void SVSpineNode::pause() { if( m_state != E_ANISTATE::tANI_STATE_PAUSE ){ m_state = E_ANISTATE::tANI_STATE_PAUSE; _sendAniEvent("ani_pause"); } } void SVSpineNode::stop() { if( m_state != E_ANISTATE::tANI_STATE_STOP ){ m_state = E_ANISTATE::tANI_STATE_STOP; m_visible = false; if (m_spine) { m_spine->clearTrack(0); } } } //开始回调 void SVSpineNode::_spine_start() { _sendAniEvent("ani_play"); //回调 if( m_spine_callback ){ (*m_spine_callback)(THIS_TO_SHAREPTR(SVSpineNode),m_p_cb_obj,1); } } //完成回调 void SVSpineNode::_spine_complete() { _sendAniEvent("ani_complete"); //回调 if( m_spine_callback ){ (*m_spine_callback)(THIS_TO_SHAREPTR(SVSpineNode),m_p_cb_obj,2); } } //停止回调 void SVSpineNode::_spine_stop() { if (m_state == E_ANISTATE::tANI_STATE_STOP) { return; } m_visible = false; m_state = E_ANISTATE::tANI_STATE_STOP; _sendAniEvent("ani_stop"); //回调 if( m_spine_callback ){ (*m_spine_callback)(THIS_TO_SHAREPTR(SVSpineNode),m_p_cb_obj,3); } } //发送事件 void SVSpineNode::_sendAniEvent(cptr8 _eventName) { SVString t_eventName = m_name + SVString("_") + SVString(_eventName); SVAnimateEventPtr t_event = MakeSharedPtr<SVAnimateEvent>(); t_event->personID = m_personID; t_event->m_AnimateName = m_spine->getSpineName(); t_event->eventName = t_eventName; mApp->getEventMgr()->pushEventToSecondPool(t_event); } void SVSpineNode::setAlpha(f32 _alpha){ if (_alpha < 0.0f || _alpha > 1.0f) { return; } if(m_spine){ m_spine->setAlpha(_alpha); } } bool SVSpineNode::getBonePosition(f32 &px, f32 &py, cptr8 bonename) { spBone *m_bone = m_spine->findBone(bonename); //绑定的骨头 if (m_bone) { px = m_bone->worldX*m_scale.x; py = m_bone->worldY*m_scale.y; //逐层找父节点,把本地坐标和世界坐标加上 SVNodePtr t_curNode = THIS_TO_SHAREPTR(SVSpineNode); while (t_curNode) { px = t_curNode->getPosition().x + px; py = t_curNode->getPosition().y + py; if (t_curNode->getParent()) { t_curNode = t_curNode->getParent(); } else { return true; } } } return false; } bool SVSpineNode::getBoneScale(f32 &sx, f32 &sy, cptr8 bonename){ spBone *m_bone = m_spine->findBone(bonename);//spSkeleton_findBone(,bonename); //绑定的骨头 if (m_bone) { sx = m_bone->scaleX; sy = m_bone->scaleY; SVNodePtr t_curNode = THIS_TO_SHAREPTR(SVSpineNode); while (t_curNode) { sx = sx * t_curNode->getScale().x; sy = sy * t_curNode->getScale().y; if (t_curNode->getParent()) { t_curNode = t_curNode->getParent(); } else { return true; } } } return false; } bool SVSpineNode::getBoneRotation(f32 &rotation, cptr8 bonename){ spBone *m_bone = m_spine->findBone(bonename);//spSkeleton_findBone(,bonename); //绑定的骨头 if (m_bone) { rotation = m_bone->rotation; SVNodePtr t_curNode = THIS_TO_SHAREPTR(SVSpineNode); while (t_curNode) { rotation = rotation * t_curNode->getRotation().z; if (t_curNode->getParent()) { t_curNode = t_curNode->getParent(); } else { return true; } } } return false; } f32 SVSpineNode::getSlotAlpha(cptr8 bonename) { spSlot *t_slot = m_spine->findSlot(bonename); f32 fAlpha = 1.0f; if (t_slot == NULL) { return fAlpha; } fAlpha = t_slot->color.a; return fAlpha; } void SVSpineNode::setAABBBoxScale(f32 _scale){ m_aabbBox_scale = _scale; } void SVSpineNode::_computeAABBBox(){ if (m_spine) { SVBoundBox t_boundingBox = m_spine->m_aabbBox; FVec3 t_min = t_boundingBox.getMin(); FVec3 t_max = t_boundingBox.getMax(); m_aabbBox = SVBoundBox(FVec3(t_min.x*m_aabbBox_scale, t_min.y*m_aabbBox_scale, 1.0), FVec3(t_max.x*m_aabbBox_scale, t_max.y*m_aabbBox_scale, 1.0)); } } //序列化 void SVSpineNode::toJSON(RAPIDJSON_NAMESPACE::Document::AllocatorType &_allocator, RAPIDJSON_NAMESPACE::Value &_objValue){ RAPIDJSON_NAMESPACE::Value locationObj(RAPIDJSON_NAMESPACE::kObjectType);//创建一个Object类型的元素 _toJsonData(_allocator, locationObj); // locationObj.AddMember("aniname", RAPIDJSON_NAMESPACE::StringRef(m_cur_aniname.c_str()), _allocator); bool m_hasSpine = false; if(m_spine){ //有spine m_hasSpine = true; locationObj.AddMember("ske_atlas", RAPIDJSON_NAMESPACE::StringRef(m_spine->m_spine_atlas.c_str()), _allocator); locationObj.AddMember("ske_json", RAPIDJSON_NAMESPACE::StringRef(m_spine->m_spine_json.c_str()), _allocator); } locationObj.AddMember("loop", m_loop, _allocator); locationObj.AddMember("play", m_immediatelyPlay, _allocator); locationObj.AddMember("spine", m_hasSpine, _allocator); _objValue.AddMember("SVSpineNode", locationObj, _allocator); } void SVSpineNode::fromJSON(RAPIDJSON_NAMESPACE::Value &item){ _fromJsonData(item); if (item.HasMember("aniname") && item["aniname"].IsString()) { m_cur_aniname = item["aniname"].GetString(); } if (item.HasMember("play") && item["play"].IsBool()) { m_immediatelyPlay = item["play"].GetBool(); } if (item.HasMember("loop") && item["loop"].IsBool()) { m_loop = item["loop"].GetBool(); } bool m_hasSpine = false; if (item.HasMember("spine") && item["spine"].IsBool()) { m_hasSpine = item["spine"].GetBool(); } if(m_hasSpine){ //有spine SVString t_atlas; SVString t_json; if (item.HasMember("ske_atlas") && item["ske_atlas"].IsString()) { t_atlas = item["ske_atlas"].GetString(); } if (item.HasMember("ske_json") && item["ske_json"].IsString()) { t_json = item["ske_json"].GetString(); } SVSpinePtr t_spine = SVSpine::createSpine(mApp, m_rootPath + t_json, m_rootPath + t_atlas, 1.0f, m_enableMipMap); if ( t_spine ) { s32 len = t_atlas.size(); s32 pos = t_atlas.rfind('.'); SVString t_spineName = SVString::substr(t_atlas.c_str(), 0, pos); t_spine->setSpineName(t_spineName.c_str()); setSpine(t_spine); } //从特效包里加载的spine动画,写死了走这个渲染流!! m_rsType = RST_SOLID_3D; } }
29.817757
155
0.609622
SVEChina
e03d76dc57e4aad695c5dd753863e741aefd8046
4,340
cpp
C++
src/lib/navigation/siteicon.cpp
pejakm/qupzilla
c1901cd81d9d3488a7dc1f25b777fb56f67cb39e
[ "BSD-3-Clause" ]
1
2019-05-07T15:00:56.000Z
2019-05-07T15:00:56.000Z
src/lib/navigation/siteicon.cpp
pejakm/qupzilla
c1901cd81d9d3488a7dc1f25b777fb56f67cb39e
[ "BSD-3-Clause" ]
null
null
null
src/lib/navigation/siteicon.cpp
pejakm/qupzilla
c1901cd81d9d3488a7dc1f25b777fb56f67cb39e
[ "BSD-3-Clause" ]
null
null
null
/* ============================================================ * QupZilla - WebKit based browser * Copyright (C) 2010-2014 David Rosca <nowrep@gmail.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 3 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, see <http://www.gnu.org/licenses/>. * ============================================================ */ #include "siteicon.h" #include "siteinfowidget.h" #include "locationbar.h" #include "tabbedwebview.h" #include "qztools.h" #include <QDrag> #include <QTimer> #include <QMimeData> #include <QApplication> #include <QContextMenuEvent> SiteIcon::SiteIcon(BrowserWindow* window, LocationBar* parent) : ToolButton(parent) , m_window(window) , m_locationBar(parent) , m_view(0) { setObjectName("locationbar-siteicon"); setToolButtonStyle(Qt::ToolButtonIconOnly); setCursor(Qt::ArrowCursor); setToolTip(LocationBar::tr("Show information about this page")); setFocusPolicy(Qt::ClickFocus); m_updateTimer = new QTimer(this); m_updateTimer->setInterval(100); m_updateTimer->setSingleShot(true); connect(m_updateTimer, SIGNAL(timeout()), this, SLOT(updateIcon())); } void SiteIcon::setWebView(WebView* view) { m_view = view; } void SiteIcon::setIcon(const QIcon &icon) { bool wasNull = m_icon.isNull(); m_icon = icon; if (wasNull) { updateIcon(); } else { m_updateTimer->start(); } } void SiteIcon::updateIcon() { ToolButton::setIcon(m_icon); } void SiteIcon::popupClosed() { setDown(false); } void SiteIcon::contextMenuEvent(QContextMenuEvent* e) { // Prevent propagating to LocationBar e->accept(); } void SiteIcon::mousePressEvent(QMouseEvent* e) { if (e->buttons() == Qt::LeftButton) { m_dragStartPosition = e->pos(); } // Prevent propagating to LocationBar e->accept(); ToolButton::mousePressEvent(e); } void SiteIcon::mouseReleaseEvent(QMouseEvent* e) { // Mouse release event is restoring Down state // So we pause updates to prevent flicker bool activated = false; if (e->button() == Qt::LeftButton && rect().contains(e->pos())) { // Popup may not be always shown, eg. on qupzilla: pages activated = showPopup(); } if (activated) { setUpdatesEnabled(false); } ToolButton::mouseReleaseEvent(e); if (activated) { setDown(true); setUpdatesEnabled(true); } } void SiteIcon::mouseMoveEvent(QMouseEvent* e) { if (!m_locationBar || e->buttons() != Qt::LeftButton) { ToolButton::mouseMoveEvent(e); return; } int manhattanLength = (e->pos() - m_dragStartPosition).manhattanLength(); if (manhattanLength <= QApplication::startDragDistance()) { ToolButton::mouseMoveEvent(e); return; } const QUrl url = m_locationBar->webView()->url(); const QString title = m_locationBar->webView()->title(); if (url.isEmpty() || title.isEmpty()) { ToolButton::mouseMoveEvent(e); return; } QDrag* drag = new QDrag(this); QMimeData* mime = new QMimeData; mime->setUrls(QList<QUrl>() << url); mime->setText(title); mime->setImageData(icon().pixmap(16, 16).toImage()); drag->setMimeData(mime); drag->setPixmap(QzTools::createPixmapForSite(icon(), title, url.toString())); drag->exec(); // Restore Down state setDown(false); } bool SiteIcon::showPopup() { if (!m_view || !m_window) { return false; } QUrl url = m_view->url(); if (url.isEmpty() || url.scheme() == QLatin1String("qupzilla")) { return false; } setDown(true); SiteInfoWidget* info = new SiteInfoWidget(m_window); info->showAt(parentWidget()); connect(info, SIGNAL(destroyed()), this, SLOT(popupClosed())); return true; }
24.8
81
0.641705
pejakm
e040071f6af73b3136a24b1d7340c97ae2d81c52
2,970
cpp
C++
Sources/Scenes/Entity.cpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Scenes/Entity.cpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
Sources/Scenes/Entity.cpp
liuping1997/Acid
0b28d63d03ead41047d5881f08e3b693a4e6e63f
[ "MIT" ]
null
null
null
#include "Entity.hpp" #include "Files/FileSystem.hpp" #include "Scenes.hpp" #include "EntityPrefab.hpp" namespace acid { Entity::Entity(const Transform &transform) : m_name(""), m_localTransform(transform), m_parent(nullptr), m_removed(false) { } Entity::Entity(const std::string &filename, const Transform &transform) : Entity(transform) { auto prefabObject = EntityPrefab::Create(filename); for (const auto &child : prefabObject->GetParent()->GetChildren()) { if (child->GetName().empty()) { continue; } auto component = Scenes::Get()->GetComponentRegister().Create(child->GetName()); if (component == nullptr) { continue; } Scenes::Get()->GetComponentRegister().Decode(child->GetName(), *child, component); AddComponent(component); } m_name = FileSystem::FileName(filename); } Entity::~Entity() { if (m_parent != nullptr) { m_parent->RemoveChild(this); } } void Entity::Update() { for (auto it = m_components.begin(); it != m_components.end();) { if ((*it)->IsRemoved()) { it = m_components.erase(it); continue; } if ((*it)->GetParent() != this) { (*it)->SetParent(this); } if ((*it)->IsEnabled()) { if (!(*it)->m_started) { (*it)->Start(); (*it)->m_started = true; } (*it)->Update(); } ++it; } } Component *Entity::AddComponent(Component *component) { if (component == nullptr) { return nullptr; } component->SetParent(this); m_components.emplace_back(component); return component; } void Entity::RemoveComponent(Component *component) { m_components.erase(std::remove_if(m_components.begin(), m_components.end(), [component](std::unique_ptr<Component> &c) { return c.get() == component; }), m_components.end()); } void Entity::RemoveComponent(const std::string &name) { m_components.erase(std::remove_if(m_components.begin(), m_components.end(), [&](std::unique_ptr<Component> &c) { auto componentName = Scenes::Get()->GetComponentRegister().FindName(c.get()); return componentName && name == *componentName; }), m_components.end()); } Transform Entity::GetWorldTransform() const { if (m_localTransform.IsDirty()) { if (m_parent != nullptr) { m_worldTransform = m_parent->GetWorldTransform() * m_localTransform; } else { m_worldTransform = m_localTransform; } for (const auto &child : m_children) { child->m_localTransform.SetDirty(true); } m_localTransform.SetDirty(false); } return m_worldTransform; } Matrix4 Entity::GetWorldMatrix() const { return GetWorldTransform().GetWorldMatrix(); } void Entity::SetParent(Entity *parent) { if (m_parent != nullptr) { m_parent->RemoveChild(this); } m_parent = parent; if (m_parent != nullptr) { m_parent->AddChild(this); } } void Entity::AddChild(Entity *child) { m_children.emplace_back(child); } void Entity::RemoveChild(Entity *child) { m_children.erase(std::remove(m_children.begin(), m_children.end(), child), m_children.end()); } }
18.109756
119
0.674747
liuping1997
e042481d0fb9269219e36d3db4b5c63f73c049d7
2,700
cpp
C++
src/AnimatedObject.cpp
ArionasMC/TicTacToe
998585ca415c7d263eeb73e43840fbf98d9a4c99
[ "Apache-2.0" ]
3
2019-02-23T18:20:24.000Z
2019-02-23T18:30:18.000Z
src/AnimatedObject.cpp
ArionasMC/TicTacToe
998585ca415c7d263eeb73e43840fbf98d9a4c99
[ "Apache-2.0" ]
null
null
null
src/AnimatedObject.cpp
ArionasMC/TicTacToe
998585ca415c7d263eeb73e43840fbf98d9a4c99
[ "Apache-2.0" ]
null
null
null
#include "AnimatedObject.h" using namespace std; AnimatedObject::AnimatedObject(const char* textureSheet, SDL_Renderer* ren, double x, double y, vector<SDL_Rect> frameRects, int endFrame, int secondsToNext) : GameObject(textureSheet, ren, x, y) { this->show = true; this->setSimpleTexture(true); this->frameRects = frameRects; this->endFrame = endFrame; this->secondsToNext = secondsToNext; this->maxFrames = frameRects.size(); this->playSoundEffect = false; /* this->destR.w = 75; this->destR.h = 75; this->srcR.x = this->frame * 50 ; this->srcR.y = 0; this->srcR.w = 49; this->srcR.h = 50; */ } void AnimatedObject::update() { GameObject::update(); if(this->show) { this->destR.x = this->x; this->destR.y = this->y; this->destR.w = this->width; this->destR.h = this->height; this->srcR.x = frameRects[frame].x; this->srcR.y = frameRects[frame].y; this->srcR.w = frameRects[frame].w; this->srcR.h = frameRects[frame].h; if(!animated) timer++; } } void AnimatedObject::render() { if(show) SDL_RenderCopyEx(renderer, texture, &srcR, &destR, degrees, NULL, SDL_FLIP_NONE); } void AnimatedObject::playAnimation() { if(!animated) { if(playSoundEffect) { Mix_PlayChannel(-1, soundEffect, 0); playSoundEffect = false; } if(frame < maxFrames) { if(timer >= secondsToNext) { timer = 0; frame++; //cout << "heyy"; //this->srcR.x = this->frame * 50; } if(frame == maxFrames) { animated = true; //cout << "hey!"; frame = endFrame; } } //cout << frame << '\n'; } } void AnimatedObject::restartAnimation() { this->frame = 0; animated = false; playAnimation(); } void AnimatedObject::generateFrameRects(int times, int deltaX, int deltaY, int conW, int conH) { for(int i = 0; i < times; i++) { frameRects.push_back({i*deltaX, i*deltaY, conW, conH}); //cout << i*deltaX <<", "<<i*deltaY<<", "<<conW<<", "<<conH<<'\n'; } this->maxFrames = frameRects.size(); } bool AnimatedObject::getAnimated() { return this->animated; } void AnimatedObject::setAnimated(bool a) { this->animated = a; } void AnimatedObject::setPlaySoundEffect(bool p) { this->playSoundEffect = p; } void AnimatedObject::setSoundEffectSource(string source) { this->soundEffect = Mix_LoadWAV(source.c_str()); }
28.421053
196
0.554444
ArionasMC