text
string
size
int64
token_count
int64
#include <bits/stdc++.h> using namespace std; void APUtil(vector<int> adj[], int u, bool visited[], int disc[], int low[], int& time, int parent, bool isAP[]) { int children = 0; visited[u] = true; disc[u] = low[u] = ++time; for (auto v : adj[u]) { if (!visited[v]) { children++; APUtil(adj, v, visited, disc, low, time, u, isAP); low[u] = min(low[u], low[v]); if (parent != -1 && low[v] >= disc[u]) isAP[u] = true; } else if (v != parent) low[u] = min(low[u], disc[v]); } if (parent == -1 && children > 1) isAP[u] = true; } void AP(vector<int> adj[], int V) { int disc[V] = { 0 }; int low[V]; bool visited[V] = { false }; bool isAP[V] = { false }; int time = 0, par = -1; for (int u = 0; u < V; u++) if (!visited[u]) APUtil(adj, u, visited, disc, low, time, par, isAP); for (int u = 0; u < V; u++) if (isAP[u] == true) cout << u << " "; } void addEdge(vector<int> adj[], int u, int v) { adj[u].push_back(v); adj[v].push_back(u); } int main() { cout << "Articulation points in first graph \n"; int V = 5; vector<int> adj1[V]; addEdge(adj1, 1, 0); addEdge(adj1, 0, 2); addEdge(adj1, 2, 1); addEdge(adj1, 0, 3); addEdge(adj1, 3, 4); AP(adj1, V); cout << "\nArticulation points in second graph \n"; V = 4; vector<int> adj2[V]; addEdge(adj2, 0, 1); addEdge(adj2, 1, 2); addEdge(adj2, 2, 3); AP(adj2, V); cout << "\nArticulation points in third graph \n"; V = 7; vector<int> adj3[V]; addEdge(adj3, 0, 1); addEdge(adj3, 1, 2); addEdge(adj3, 2, 0); addEdge(adj3, 1, 3); addEdge(adj3, 1, 4); addEdge(adj3, 1, 6); addEdge(adj3, 3, 5); addEdge(adj3, 4, 5); AP(adj3, V); return 0; }
1,969
850
#include "memory.hpp" #include <vulkan/vulkan_core.h> #include "utils.hpp" #include "config.hpp" #include <cstring> #include <iostream> using namespace std; namespace bps3D { namespace vk { namespace BufferFlags { static constexpr VkBufferUsageFlags commonUsage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; static constexpr VkBufferUsageFlags stageUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT; static constexpr VkBufferUsageFlags geometryUsage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT; static constexpr VkBufferUsageFlags shaderUsage = VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; static constexpr VkBufferUsageFlags paramUsage = VK_BUFFER_USAGE_VERTEX_BUFFER_BIT; static constexpr VkBufferUsageFlags hostRTUsage = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; static constexpr VkBufferUsageFlags hostUsage = stageUsage | shaderUsage | paramUsage; static constexpr VkBufferUsageFlags indirectUsage = VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; static constexpr VkBufferUsageFlags localUsage = commonUsage | geometryUsage | shaderUsage | indirectUsage; static constexpr VkBufferUsageFlags dedicatedUsage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT; static constexpr VkBufferUsageFlags rtGeometryUsage = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_BUILD_INPUT_READ_ONLY_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT; static constexpr VkBufferUsageFlags rtAccelScratchUsage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; static constexpr VkBufferUsageFlags rtAccelUsage = VK_BUFFER_USAGE_ACCELERATION_STRUCTURE_STORAGE_BIT_KHR | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; static constexpr VkBufferUsageFlags localRTUsage = rtGeometryUsage | rtAccelScratchUsage | rtAccelUsage; }; namespace ImageFlags { static constexpr VkFormatFeatureFlags textureReqs = VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT; static constexpr VkImageUsageFlags textureUsage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; static constexpr VkImageUsageFlags colorAttachmentUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; static constexpr VkFormatFeatureFlags colorAttachmentReqs = VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; static constexpr VkImageUsageFlags depthAttachmentUsage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; static constexpr VkFormatFeatureFlags depthAttachmentReqs = VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT | VK_FORMAT_FEATURE_TRANSFER_SRC_BIT; static constexpr VkImageUsageFlags rtStorageUsage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; static constexpr VkFormatFeatureFlags rtStorageReqs = VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT | VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT; }; template <bool host_mapped> void AllocDeleter<host_mapped>::operator()(VkBuffer buffer) const { if (mem_ == VK_NULL_HANDLE) return; const DeviceState &dev = alloc_.dev; if constexpr (host_mapped) { dev.dt.unmapMemory(dev.hdl, mem_); } dev.dt.freeMemory(dev.hdl, mem_, nullptr); dev.dt.destroyBuffer(dev.hdl, buffer, nullptr); } template <> void AllocDeleter<false>::operator()(VkImage image) const { if (mem_ == VK_NULL_HANDLE) return; const DeviceState &dev = alloc_.dev; dev.dt.freeMemory(dev.hdl, mem_, nullptr); dev.dt.destroyImage(dev.hdl, image, nullptr); } template <bool host_mapped> void AllocDeleter<host_mapped>::clear() { mem_ = VK_NULL_HANDLE; } HostBuffer::HostBuffer(VkBuffer buf, void *p, VkMappedMemoryRange mem_range, AllocDeleter<true> deleter) : buffer(buf), ptr(p), mem_range_(mem_range), deleter_(deleter) {} HostBuffer::HostBuffer(HostBuffer &&o) : buffer(o.buffer), ptr(o.ptr), mem_range_(o.mem_range_), deleter_(o.deleter_) { o.deleter_.clear(); } HostBuffer::~HostBuffer() { deleter_(buffer); } void HostBuffer::flush(const DeviceState &dev) { dev.dt.flushMappedMemoryRanges(dev.hdl, 1, &mem_range_); } void HostBuffer::flush(const DeviceState &dev, VkDeviceSize offset, VkDeviceSize num_bytes) { VkMappedMemoryRange sub_range = mem_range_; sub_range.offset = offset; sub_range.size = num_bytes; dev.dt.flushMappedMemoryRanges(dev.hdl, 1, &sub_range); } LocalBuffer::LocalBuffer(VkBuffer buf, AllocDeleter<false> deleter) : buffer(buf), deleter_(deleter) {} LocalBuffer::LocalBuffer(LocalBuffer &&o) : buffer(o.buffer), deleter_(o.deleter_) { o.deleter_.clear(); } LocalBuffer::~LocalBuffer() { deleter_(buffer); } LocalImage::LocalImage(uint32_t w, uint32_t h, uint32_t mip_levels, VkImage img, AllocDeleter<false> deleter) : width(w), height(h), mipLevels(mip_levels), image(img), deleter_(deleter) {} LocalImage::LocalImage(LocalImage &&o) : width(o.width), height(o.height), mipLevels(o.mipLevels), image(o.image), deleter_(o.deleter_) { o.deleter_.clear(); } LocalImage::~LocalImage() { deleter_(image); } static VkFormatProperties2 getFormatProperties(const InstanceState &inst, VkPhysicalDevice phy, VkFormat fmt) { VkFormatProperties2 props; props.sType = VK_STRUCTURE_TYPE_FORMAT_PROPERTIES_2; props.pNext = nullptr; inst.dt.getPhysicalDeviceFormatProperties2(phy, fmt, &props); return props; } template <size_t N> static VkFormat chooseFormat(VkPhysicalDevice phy, const InstanceState &inst, VkFormatFeatureFlags required_features, const array<VkFormat, N> &desired_formats) { for (auto fmt : desired_formats) { VkFormatProperties2 props = getFormatProperties(inst, phy, fmt); if ((props.formatProperties.optimalTilingFeatures & required_features) == required_features) { return fmt; } } cerr << "Unable to find required features in given formats" << endl; fatalExit(); } static pair<VkBuffer, VkMemoryRequirements> makeUnboundBuffer( const DeviceState &dev, VkDeviceSize num_bytes, VkBufferUsageFlags usage) { VkBufferCreateInfo buffer_info; buffer_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_info.pNext = nullptr; buffer_info.flags = 0; buffer_info.size = num_bytes; buffer_info.usage = usage; buffer_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; VkBuffer buffer; REQ_VK(dev.dt.createBuffer(dev.hdl, &buffer_info, nullptr, &buffer)); VkMemoryRequirements reqs; dev.dt.getBufferMemoryRequirements(dev.hdl, buffer, &reqs); return pair(buffer, reqs); } static VkImage makeImage(const DeviceState &dev, uint32_t width, uint32_t height, uint32_t mip_levels, VkFormat format, VkImageUsageFlags usage, VkImageCreateFlags img_flags = 0) { VkImageCreateInfo img_info; img_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; img_info.pNext = nullptr; img_info.flags = img_flags; img_info.imageType = VK_IMAGE_TYPE_2D; img_info.format = format; img_info.extent = {width, height, 1}; img_info.mipLevels = mip_levels; img_info.arrayLayers = 1; img_info.samples = VK_SAMPLE_COUNT_1_BIT; img_info.tiling = VK_IMAGE_TILING_OPTIMAL; img_info.usage = usage; img_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; img_info.queueFamilyIndexCount = 0; img_info.pQueueFamilyIndices = nullptr; img_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VkImage img; REQ_VK(dev.dt.createImage(dev.hdl, &img_info, nullptr, &img)); return img; } uint32_t findMemoryTypeIndex(uint32_t allowed_type_bits, VkMemoryPropertyFlags required_props, VkPhysicalDeviceMemoryProperties2 &mem_props) { uint32_t num_mems = mem_props.memoryProperties.memoryTypeCount; for (uint32_t idx = 0; idx < num_mems; idx++) { uint32_t mem_type_bits = (1 << idx); if (!(allowed_type_bits & mem_type_bits)) continue; VkMemoryPropertyFlags supported_props = mem_props.memoryProperties.memoryTypes[idx].propertyFlags; if ((required_props & supported_props) == required_props) { return idx; } } cerr << "Failed to find desired memory type" << endl; fatalExit(); } static VkMemoryRequirements getImageMemReqs(const DeviceState &dev, VkImage img) { VkMemoryRequirements reqs; dev.dt.getImageMemoryRequirements(dev.hdl, img, &reqs); return reqs; } static MemoryTypeIndices findTypeIndices(const DeviceState &dev, const InstanceState &inst, const ResourceFormats &formats) { auto get_generic_buffer_reqs = [&](VkBufferUsageFlags usage_flags) { auto [test_buffer, reqs] = makeUnboundBuffer(dev, 1, usage_flags); dev.dt.destroyBuffer(dev.hdl, test_buffer, nullptr); return reqs; }; auto get_generic_image_reqs = [&](VkFormat format, VkImageUsageFlags usage_flags, VkImageCreateFlags img_flags = 0) { VkImage test_image = makeImage(dev, 1, 1, 1, format, usage_flags, img_flags); VkMemoryRequirements reqs = getImageMemReqs(dev, test_image); dev.dt.destroyImage(dev.hdl, test_image, nullptr); return reqs; }; VkPhysicalDeviceMemoryProperties2 dev_mem_props; dev_mem_props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MEMORY_PROPERTIES_2; dev_mem_props.pNext = nullptr; inst.dt.getPhysicalDeviceMemoryProperties2(dev.phy, &dev_mem_props); VkMemoryRequirements host_generic_reqs = get_generic_buffer_reqs(BufferFlags::hostUsage); uint32_t host_type_idx = findMemoryTypeIndex(host_generic_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_CACHED_BIT, dev_mem_props); VkMemoryRequirements buffer_local_reqs = get_generic_buffer_reqs(BufferFlags::localUsage); VkMemoryRequirements tex_local_reqs = get_generic_image_reqs(formats.texture, ImageFlags::textureUsage); uint32_t local_type_idx = findMemoryTypeIndex( buffer_local_reqs.memoryTypeBits & tex_local_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); VkMemoryRequirements dedicated_reqs = get_generic_buffer_reqs(BufferFlags::dedicatedUsage); uint32_t dedicated_type_idx = findMemoryTypeIndex( dedicated_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); VkMemoryRequirements color_attachment_reqs = get_generic_image_reqs( formats.colorAttachment, ImageFlags::colorAttachmentUsage); uint32_t color_attachment_idx = findMemoryTypeIndex( color_attachment_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); VkMemoryRequirements depth_attachment_reqs = get_generic_image_reqs( formats.depthAttachment, ImageFlags::depthAttachmentUsage); uint32_t depth_attachment_idx = findMemoryTypeIndex( depth_attachment_reqs.memoryTypeBits, VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT, dev_mem_props); return MemoryTypeIndices { host_type_idx, local_type_idx, dedicated_type_idx, color_attachment_idx, depth_attachment_idx, }; } static Alignments getMemoryAlignments(const InstanceState &inst, VkPhysicalDevice phy) { VkPhysicalDeviceProperties2 props {}; props.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2; inst.dt.getPhysicalDeviceProperties2(phy, &props); return Alignments { props.properties.limits.minUniformBufferOffsetAlignment, props.properties.limits.minStorageBufferOffsetAlignment}; } MemoryAllocator::MemoryAllocator(const DeviceState &d, const InstanceState &inst) : dev(d), formats_ { chooseFormat(dev.phy, inst, ImageFlags::textureReqs, array {VK_FORMAT_BC7_UNORM_BLOCK}), chooseFormat(dev.phy, inst, ImageFlags::colorAttachmentReqs, array {VK_FORMAT_R8G8B8A8_UNORM}), chooseFormat( dev.phy, inst, ImageFlags::depthAttachmentReqs, array {VK_FORMAT_D32_SFLOAT, VK_FORMAT_D32_SFLOAT_S8_UINT}), chooseFormat(dev.phy, inst, ImageFlags::colorAttachmentReqs, array {VK_FORMAT_R32_SFLOAT}), }, type_indices_(findTypeIndices(dev, inst, formats_)), alignments_(getMemoryAlignments(inst, dev.phy)), local_buffer_usage_flags_(BufferFlags::localUsage) {} HostBuffer MemoryAllocator::makeHostBuffer(VkDeviceSize num_bytes, VkBufferUsageFlags usage) { auto [buffer, reqs] = makeUnboundBuffer(dev, num_bytes, usage); VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_indices_.host; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindBufferMemory(dev.hdl, buffer, memory, 0)); void *mapped_ptr; REQ_VK(dev.dt.mapMemory(dev.hdl, memory, 0, reqs.size, 0, &mapped_ptr)); VkMappedMemoryRange range; range.sType = VK_STRUCTURE_TYPE_MAPPED_MEMORY_RANGE; range.pNext = nullptr; range.memory = memory, range.offset = 0; range.size = VK_WHOLE_SIZE; return HostBuffer(buffer, mapped_ptr, range, AllocDeleter<true>(memory, *this)); } HostBuffer MemoryAllocator::makeStagingBuffer(VkDeviceSize num_bytes) { return makeHostBuffer(num_bytes, BufferFlags::stageUsage); } HostBuffer MemoryAllocator::makeParamBuffer(VkDeviceSize num_bytes) { return makeHostBuffer(num_bytes, BufferFlags::commonUsage | BufferFlags::shaderUsage | BufferFlags::paramUsage); } optional<LocalBuffer> MemoryAllocator::makeLocalBuffer( VkDeviceSize num_bytes, VkBufferUsageFlags usage) { auto [buffer, reqs] = makeUnboundBuffer(dev, num_bytes, usage); VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_indices_.local; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindBufferMemory(dev.hdl, buffer, memory, 0)); return LocalBuffer(buffer, AllocDeleter<false>(memory, *this)); } optional<LocalBuffer> MemoryAllocator::makeLocalBuffer(VkDeviceSize num_bytes) { return makeLocalBuffer(num_bytes, local_buffer_usage_flags_); } optional<LocalBuffer> MemoryAllocator::makeIndirectBuffer( VkDeviceSize num_bytes) { return makeLocalBuffer(num_bytes, BufferFlags::commonUsage | BufferFlags::shaderUsage | BufferFlags::indirectUsage); } pair<LocalBuffer, VkDeviceMemory> MemoryAllocator::makeDedicatedBuffer( VkDeviceSize num_bytes) { auto [buffer, reqs] = makeUnboundBuffer(dev, num_bytes, BufferFlags::dedicatedUsage); VkMemoryDedicatedAllocateInfo dedicated; dedicated.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; dedicated.pNext = nullptr; dedicated.image = VK_NULL_HANDLE; dedicated.buffer = buffer; VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = &dedicated; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_indices_.dedicatedBuffer; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindBufferMemory(dev.hdl, buffer, memory, 0)); return pair(LocalBuffer(buffer, AllocDeleter<false>(memory, *this)), memory); } pair<LocalTexture, TextureRequirements> MemoryAllocator::makeTexture( uint32_t width, uint32_t height, uint32_t mip_levels) { VkImage texture_img = makeImage(dev, width, height, mip_levels, formats_.texture, ImageFlags::textureUsage); auto reqs = getImageMemReqs(dev, texture_img); return { LocalTexture { width, height, mip_levels, texture_img, }, TextureRequirements { reqs.alignment, reqs.size, }, }; } void MemoryAllocator::destroyTexture(LocalTexture &&texture) { dev.dt.destroyImage(dev.hdl, texture.image, nullptr); } optional<VkDeviceMemory> MemoryAllocator::alloc(VkDeviceSize num_bytes) { VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = nullptr; alloc.allocationSize = num_bytes; alloc.memoryTypeIndex = type_indices_.local; VkDeviceMemory mem; VkResult res = dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &mem); if (res == VK_ERROR_OUT_OF_DEVICE_MEMORY) { return optional<VkDeviceMemory>(); } return mem; } LocalImage MemoryAllocator::makeDedicatedImage(uint32_t width, uint32_t height, uint32_t mip_levels, VkFormat format, VkImageUsageFlags usage, uint32_t type_idx) { auto img = makeImage(dev, width, height, mip_levels, format, usage); auto reqs = getImageMemReqs(dev, img); VkMemoryDedicatedAllocateInfo dedicated; dedicated.sType = VK_STRUCTURE_TYPE_MEMORY_DEDICATED_ALLOCATE_INFO; dedicated.pNext = nullptr; dedicated.image = img; dedicated.buffer = VK_NULL_HANDLE; VkMemoryAllocateInfo alloc; alloc.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO; alloc.pNext = &dedicated; alloc.allocationSize = reqs.size; alloc.memoryTypeIndex = type_idx; VkDeviceMemory memory; REQ_VK(dev.dt.allocateMemory(dev.hdl, &alloc, nullptr, &memory)); REQ_VK(dev.dt.bindImageMemory(dev.hdl, img, memory, 0)); return LocalImage(width, height, mip_levels, img, AllocDeleter<false>(memory, *this)); } LocalImage MemoryAllocator::makeColorAttachment(uint32_t width, uint32_t height) { return makeDedicatedImage(width, height, 1, formats_.colorAttachment, ImageFlags::colorAttachmentUsage, type_indices_.colorAttachment); } LocalImage MemoryAllocator::makeDepthAttachment(uint32_t width, uint32_t height) { return makeDedicatedImage(width, height, 1, formats_.depthAttachment, ImageFlags::depthAttachmentUsage, type_indices_.depthAttachment); } LocalImage MemoryAllocator::makeLinearDepthAttachment(uint32_t width, uint32_t height) { return makeDedicatedImage(width, height, 1, formats_.linearDepthAttachment, ImageFlags::colorAttachmentUsage, type_indices_.colorAttachment); } VkDeviceSize MemoryAllocator::alignUniformBufferOffset( VkDeviceSize offset) const { return alignOffset(offset, alignments_.uniformBuffer); } VkDeviceSize MemoryAllocator::alignStorageBufferOffset( VkDeviceSize offset) const { return alignOffset(offset, alignments_.storageBuffer); } } }
20,831
7,028
// graph-tool -- a general graph modification and manipulation thingy // // Copyright (C) 2006-2018 Tiago de Paula Peixoto <tiago@skewed.de> // // 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/>. #ifndef GRAPH_BLOCKMODEL_PARTITION_HH #define GRAPH_BLOCKMODEL_PARTITION_HH #include "../support/util.hh" #include "../support/int_part.hh" namespace graph_tool { // =============== // Partition stats // =============== constexpr size_t null_group = std::numeric_limits<size_t>::max(); typedef vprop_map_t<std::vector<std::tuple<size_t, size_t, size_t>>>::type degs_map_t; struct simple_degs_t {}; template <class Graph, class Vprop, class Eprop, class F> __attribute__((always_inline)) __attribute__((flatten)) inline void degs_op(size_t v, Vprop& vweight, Eprop& eweight, const simple_degs_t&, Graph& g, F&& f) { f(in_degreeS()(v, g, eweight), out_degreeS()(v, g, eweight), vweight[v]); } template <class Graph, class Vprop, class Eprop, class F> __attribute__((always_inline)) __attribute__((flatten)) inline void degs_op(size_t v, Vprop& vweight, Eprop& eweight, const typename degs_map_t::unchecked_t& degs, Graph& g, F&& f) { auto& ks = degs[v]; if (ks.empty()) { degs_op(v, vweight, eweight, simple_degs_t(), g, std::forward<F>(f)); } else { for (auto& k : ks) f(get<0>(k), get<1>(k), get<2>(k)); } } template <bool use_rmap> class partition_stats { public: typedef gt_hash_map<pair<size_t,size_t>, int> map_t; template <class Graph, class Vprop, class VWprop, class Eprop, class Degs, class Mprop, class Vlist> partition_stats(Graph& g, Vprop& b, Vlist& vlist, size_t E, size_t B, VWprop& vweight, Eprop& eweight, Degs& degs, const Mprop& ignore_degree, std::vector<size_t>& bmap, bool allow_empty) : _bmap(bmap), _N(0), _E(E), _total_B(B), _allow_empty(allow_empty) { if (!use_rmap) { _hist.resize(num_vertices(g)); _total.resize(num_vertices(g)); _ep.resize(num_vertices(g)); _em.resize(num_vertices(g)); } for (auto v : vlist) { if (vweight[v] == 0) continue; auto r = get_r(b[v]); if (v >= _ignore_degree.size()) _ignore_degree.resize(v + 1, 0); _ignore_degree[v] = ignore_degree[v]; degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto kout, auto n) { if (_ignore_degree[v] == 2) kout = 0; if (_ignore_degree[v] != 1) { _hist[r][make_pair(kin, kout)] += n; _em[r] += kin * n; _ep[r] += kout * n; } _total[r] += n; _N += n; }); } _actual_B = 0; for (auto n : _total) { if (n > 0) _actual_B++; } } size_t get_r(size_t r) { if (use_rmap) { constexpr size_t null = std::numeric_limits<size_t>::max(); if (r >= _bmap.size()) _bmap.resize(r + 1, null); size_t nr = _bmap[r]; if (nr == null) nr = _bmap[r] = _hist.size(); r = nr; } if (r >= _hist.size()) { _hist.resize(r + 1); _total.resize(r + 1); _ep.resize(r + 1); _em.resize(r + 1); } return r; } double get_partition_dl() { double S = 0; if (_allow_empty) S += lbinom(_total_B + _N - 1, _N); else S += lbinom(_N - 1, _actual_B - 1); S += lgamma_fast(_N + 1); for (auto nr : _total) S -= lgamma_fast(nr + 1); S += safelog_fast(_N); return S; } template <class Rs, class Ks> double get_deg_dl_ent(Rs&& rs, Ks&& ks) { double S = 0; for (auto r : rs) { r = get_r(r); size_t total = 0; if (ks.empty()) { for (auto& k_c : _hist[r]) { S -= xlogx_fast(k_c.second); total += k_c.second; } } else { auto& h = _hist[r]; for (auto& k : ks) { auto iter = h.find(k); auto k_c = (iter != h.end()) ? iter->second : 0; S -= xlogx(k_c); } total = _total[r]; } S += xlogx_fast(total); } return S; } template <class Rs, class Ks> double get_deg_dl_uniform(Rs&& rs, Ks&&) { double S = 0; for (auto r : rs) { r = get_r(r); S += lbinom(_total[r] + _ep[r] - 1, _ep[r]); S += lbinom(_total[r] + _em[r] - 1, _em[r]); } return S; } template <class Rs, class Ks> double get_deg_dl_dist(Rs&& rs, Ks&& ks) { double S = 0; for (auto r : rs) { r = get_r(r); S += log_q(_ep[r], _total[r]); S += log_q(_em[r], _total[r]); size_t total = 0; if (ks.empty()) { for (auto& k_c : _hist[r]) { S -= lgamma_fast(k_c.second + 1); total += k_c.second; } } else { auto& h = _hist[r]; for (auto& k : ks) { auto iter = h.find(k); auto k_c = (iter != h.end()) ? iter->second : 0; S -= lgamma_fast(k_c + 1); } total = _total[r]; } S += lgamma_fast(total + 1); } return S; } template <class Rs, class Ks> double get_deg_dl(int kind, Rs&& rs, Ks&& ks) { switch (kind) { case deg_dl_kind::ENT: return get_deg_dl_ent(rs, ks); case deg_dl_kind::UNIFORM: return get_deg_dl_uniform(rs, ks); case deg_dl_kind::DIST: return get_deg_dl_dist(rs, ks); default: return numeric_limits<double>::quiet_NaN(); } } double get_deg_dl(int kind) { return get_deg_dl(kind, boost::counting_range(size_t(0), _total_B), std::array<std::pair<size_t,size_t>,0>()); } template <class Graph> double get_edges_dl(size_t B, Graph& g) { size_t BB = (graph_tool::is_directed(g)) ? B * B : (B * (B + 1)) / 2; return lbinom(BB + _E - 1, _E); } template <class VProp> double get_delta_partition_dl(size_t v, size_t r, size_t nr, VProp& vweight) { if (r == nr) return 0; if (r != null_group) r = get_r(r); if (nr != null_group) nr = get_r(nr); int n = vweight[v]; if (n == 0) { if (r == null_group) n = 1; else return 0; } double S_b = 0, S_a = 0; if (r != null_group) { S_b += -lgamma_fast(_total[r] + 1); S_a += -lgamma_fast(_total[r] - n + 1); } if (nr != null_group) { S_b += -lgamma_fast(_total[nr] + 1); S_a += -lgamma_fast(_total[nr] + n + 1); } int dN = 0; if (r == null_group) dN += n; if (nr == null_group) dN -= n; S_b += lgamma_fast(_N + 1); S_a += lgamma_fast(_N + dN + 1); int dB = 0; if (r != null_group && _total[r] == n) dB--; if (nr != null_group && _total[nr] == 0) dB++; if ((dN != 0 || dB != 0) && !_allow_empty) { S_b += lbinom_fast(_N - 1, _actual_B - 1); S_a += lbinom_fast(_N - 1 + dN, _actual_B + dB - 1); } if (dN != 0) { S_b += safelog_fast(_N); S_a += safelog_fast(_N + dN); } return S_a - S_b; } template <class VProp, class Graph> double get_delta_edges_dl(size_t v, size_t r, size_t nr, VProp& vweight, size_t actual_B, Graph& g) { if (r == nr || _allow_empty) return 0; if (r != null_group) r = get_r(r); if (nr != null_group) nr = get_r(nr); double S_b = 0, S_a = 0; int n = vweight[v]; if (n == 0) { if (r == null_group) n = 1; else return 0; } int dB = 0; if (r != null_group && _total[r] == n) dB--; if (nr != null_group && _total[nr] == 0) dB++; if (dB != 0) { S_b += get_edges_dl(actual_B, g); S_a += get_edges_dl(actual_B + dB, g); } return S_a - S_b; } template <class Graph, class VProp, class EProp, class Degs> double get_delta_deg_dl(size_t v, size_t r, size_t nr, VProp& vweight, EProp& eweight, Degs& degs, Graph& g, int kind) { if (r == nr || _ignore_degree[v] == 1 || vweight[v] == 0) return 0; if (r != null_group) r = get_r(r); if (nr != null_group) nr = get_r(nr); auto dop = [&](auto&& f) { if (_ignore_degree[v] == 2) { degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto, auto n) { f(kin, 0, n); }); } else { degs_op(v, vweight, eweight, degs, g, [&](auto... k) { f(k...); }); } }; double dS = 0; switch (kind) { case deg_dl_kind::ENT: if (r != null_group) dS += get_delta_deg_dl_ent_change(r, dop, -1); if (nr != null_group) dS += get_delta_deg_dl_ent_change(nr, dop, +1); break; case deg_dl_kind::UNIFORM: if (r != null_group) dS += get_delta_deg_dl_uniform_change(v, r, dop, -1); if (nr != null_group) dS += get_delta_deg_dl_uniform_change(v, nr, dop, +1); break; case deg_dl_kind::DIST: if (r != null_group) dS += get_delta_deg_dl_dist_change(v, r, dop, -1); if (nr != null_group) dS += get_delta_deg_dl_dist_change(v, nr, dop, +1); break; default: dS = numeric_limits<double>::quiet_NaN(); } return dS; } template <class DegOP> double get_delta_deg_dl_ent_change(size_t r, DegOP&& dop, int diff) { int nr = _total[r]; auto get_Sk = [&](size_t s, pair<size_t, size_t>& deg, int delta) { int nd = 0; auto iter = _hist[s].find(deg); if (iter != _hist[s].end()) nd = iter->second; assert(nd + delta >= 0); return -xlogx_fast(nd + delta); }; double S_b = 0, S_a = 0; int dn = 0; dop([&](size_t kin, size_t kout, int nk) { dn += diff * nk; auto deg = make_pair(kin, kout); S_b += get_Sk(r, deg, 0); S_a += get_Sk(r, deg, diff * nk); }); S_b += xlogx_fast(nr); S_a += xlogx_fast(nr + dn); return S_a - S_b; } template <class DegOP> double get_delta_deg_dl_uniform_change(size_t v, size_t r, DegOP&& dop, int diff) { auto get_Se = [&](int dn, int dkin, int dkout) { double S = 0; S += lbinom_fast(_total[r] + dn + _ep[r] - 1 + dkout, _ep[r] + dkout); S += lbinom_fast(_total[r] + dn + _em[r] - 1 + dkin, _em[r] + dkin); return S; }; double S_b = 0, S_a = 0; int tkin = 0, tkout = 0, n = 0; dop([&](auto kin, auto kout, int nk) { tkin += kin * nk; if (_ignore_degree[v] != 2) tkout += kout * nk; n += nk; }); S_b += get_Se( 0, 0, 0); S_a += get_Se(diff * n, diff * tkin, diff * tkout); return S_a - S_b; } template <class DegOP> double get_delta_deg_dl_dist_change(size_t v, size_t r, DegOP&& dop, int diff) { auto get_Se = [&](int delta, int kin, int kout) { double S = 0; assert(_total[r] + delta >= 0); assert(_em[r] + kin >= 0); assert(_ep[r] + kout >= 0); S += log_q(_em[r] + kin, _total[r] + delta); S += log_q(_ep[r] + kout, _total[r] + delta); return S; }; auto get_Sr = [&](int delta) { assert(_total[r] + delta + 1 >= 0); return lgamma_fast(_total[r] + delta + 1); }; auto get_Sk = [&](pair<size_t, size_t>& deg, int delta) { int nd = 0; auto iter = _hist[r].find(deg); if (iter != _hist[r].end()) nd = iter->second; assert(nd + delta >= 0); return -lgamma_fast(nd + delta + 1); }; double S_b = 0, S_a = 0; int tkin = 0, tkout = 0, n = 0; dop([&](size_t kin, size_t kout, int nk) { tkin += kin * nk; if (_ignore_degree[v] != 2) tkout += kout * nk; n += nk; auto deg = make_pair(kin, kout); S_b += get_Sk(deg, 0); S_a += get_Sk(deg, diff * nk); }); S_b += get_Se( 0, 0, 0); S_a += get_Se(diff * n, diff * tkin, diff * tkout); S_b += get_Sr( 0); S_a += get_Sr(diff * n); return S_a - S_b; } template <class Graph, class VWeight, class EWeight, class Degs> void change_vertex(size_t v, size_t r, bool deg_corr, Graph& g, VWeight& vweight, EWeight& eweight, Degs& degs, int diff) { int vw = vweight[v]; int dv = vw * diff; if (_total[r] == 0 && dv > 0) _actual_B++; if (_total[r] == vw && dv < 0) _actual_B--; _total[r] += dv; _N += dv; assert(_total[r] >= 0); if (deg_corr && _ignore_degree[v] != 1) { degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto kout, auto n) { int dk = diff * n; if (_ignore_degree[v] == 2) kout = 0; auto& h = _hist[r]; auto deg = make_pair(kin, kout); auto iter = h.insert({deg, 0}).first; iter->second += dk; if (iter->second == 0) h.erase(iter); _em[r] += dk * deg.first; _ep[r] += dk * deg.second; }); } } template <class Graph, class VWeight, class EWeight, class Degs> void remove_vertex(size_t v, size_t r, bool deg_corr, Graph& g, VWeight& vweight, EWeight& eweight, Degs& degs) { if (r == null_group || vweight[v] == 0) return; r = get_r(r); change_vertex(v, r, deg_corr, g, vweight, eweight, degs, -1); } template <class Graph, class VWeight, class EWeight, class Degs> void add_vertex(size_t v, size_t nr, bool deg_corr, Graph& g, VWeight& vweight, EWeight& eweight, Degs& degs) { if (nr == null_group || vweight[v] == 0) return; nr = get_r(nr); change_vertex(v, nr, deg_corr, g, vweight, eweight, degs, 1); } void change_k(size_t v, size_t r, bool deg_corr, int vweight, int kin, int kout, int diff) { if (_total[r] == 0 && diff * vweight > 0) _actual_B++; if (_total[r] == vweight && diff * vweight < 0) _actual_B--; _total[r] += diff * vweight; _N += diff * vweight; assert(_total[r] >= 0); if (deg_corr && _ignore_degree[v] != 1) { if (_ignore_degree[v] == 2) kout = 0; auto deg = make_pair(kin, kout); auto iter = _hist[r].insert({deg, 0}).first; iter->second += diff * vweight; if (iter->second == 0) _hist[r].erase(iter); _em[r] += diff * deg.first * vweight; _ep[r] += diff * deg.second * vweight; } } void change_E(int dE) { _E += dE; } size_t get_N() { return _N; } size_t get_E() { return _E; } size_t get_actual_B() { return _actual_B; } void add_block() { _total_B++; } template <class Graph, class VProp, class VWeight, class EWeight, class Degs> bool check_degs(Graph& g, VProp& b, VWeight& vweight, EWeight& eweight, Degs& degs) { vector<map_t> dhist; for (auto v : vertices_range(g)) { degs_op(v, vweight, eweight, degs, g, [&](auto kin, auto kout, auto n) { auto r = get_r(b[v]); if (r >= dhist.size()) dhist.resize(r + 1); dhist[r][{kin, kout}] += n; }); } for (size_t r = 0; r < dhist.size(); ++r) { for (auto& kn : dhist[r]) { auto count = (r >= _hist.size()) ? 0 : _hist[r][kn.first]; if (kn.second != count) { assert(false); return false; } } } for (size_t r = 0; r < _hist.size(); ++r) { for (auto& kn : _hist[r]) { auto count = (r >= dhist.size()) ? 0 : dhist[r][kn.first]; if (kn.second != count) { assert(false); return false; } } } return true; } private: vector<size_t>& _bmap; size_t _N; size_t _E; size_t _actual_B; size_t _total_B; bool _allow_empty; vector<map_t> _hist; vector<int> _total; vector<int> _ep; vector<int> _em; vector<uint8_t> _ignore_degree; }; } //namespace graph_tool #endif // GRAPH_BLOCKMODEL_PARTITION_HH
20,268
7,028
//------------------------------------------------------------------------------ // Copyright (c) 2016 by contributors. 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. //------------------------------------------------------------------------------ /* Author: Chao Ma (mctt90@gmail.com) This file is the implementation of the base Score class. */ #include "src/score/score_function.h" #include "src/score/linear_score.h" #include "src/score/fm_score.h" #include "src/score/ffm_score.h" namespace xLearn { //------------------------------------------------------------------------------ // Class register //------------------------------------------------------------------------------ CLASS_REGISTER_IMPLEMENT_REGISTRY(xLearn_score_registry, Score); REGISTER_SCORE("linear", LinearScore); REGISTER_SCORE("fm", FMScore); REGISTER_SCORE("ffm", FFMScore); } // namespace xLearn
1,412
400
#include "testUtils.h" namespace CLI { std::ostream & operator<<( std::ostream & os, border::Element::Type type ) { switch(type) { case border::Element::NONE: return os << "NONE"; case border::Element::UNUSED_1: return os << "UNUSED_1"; case border::Element::UNUSED_2: return os << "UNUSED_2"; case border::Element::TOP_RIGHT: return os << "TOP_RIGHT"; case border::Element::UNUSED_4: return os << "UNUSED_4"; case border::Element::VERTICAL: return os << "VERTICAL"; case border::Element::BOTTOM_RIGHT: return os << "BOTTOM_RIGHT"; case border::Element::TEE_RIGHT: return os << "TEE_RIGHT"; case border::Element::UNUSED_8: return os << "UNUSED_8"; case border::Element::TOP_LEFT: return os << "TOP_LEFT"; case border::Element::HORIZONTAL: return os << "HORIZONTAL"; case border::Element::TEE_TOP: return os << "TEE_TOP"; case border::Element::BOTTOM_LEFT: return os << "BOTTOM_LEFT"; case border::Element::TEE_LEFT: return os << "TEE_LEFT"; case border::Element::TEE_BOTTOM: return os << "TEE_BOTTOM"; case border::Element::CROSS: return os << "CROSS"; case border::Element::INVERT: return os << "INVERT"; default: return os; } } std::ostream & operator<<( std::ostream & os, util::Color color ) { switch(color) { case util::BLACK: return os << "BLACK"; case util::WHITE: return os << "WHITE"; case util::RED: return os << "RED"; case util::GREEN: return os << "GREEN"; case util::BLUE: return os << "BLUE"; case util::YELLOW: return os << "YELLOW"; case util::CYAN: return os << "CYAN"; case util::MAGENTA: return os << "MAGENTA"; default: return os; } } std::ostream & operator<<( std::ostream & os, util::Attribute attr ) { switch(attr) { case util::NONE: return os << "NONE"; case util::BOLD: return os << "BOLD"; case util::DIM: return os << "DIM"; case util::UNDERSCORE: return os << "UNDERSCORE"; case util::BLINK: return os << "BLINK"; case util::INVERSE: return os << "INVERSE"; case util::HIDDEN: return os << "HIDDEN"; default: return os; } } std::string to_string( util::Point const& point ) { std::stringstream result; result << "P(x: " << point.x() << ", y: " << point.y() << ")"; return result.str(); } std::string to_string( util::Size const& size ) { std::stringstream result; result << "S(w: " << size.width() << ", h: " << size.height() << ")"; return result.str(); } std::string to_string( util::Properties const& prop ) { std::stringstream result; result << "Prop(fg: " << prop.foreground << ", bg: " << prop.background << ", attr: " << prop.attribute << ")"; return result.str(); } std::string to_string( util::SizeConstraint const& constraint ) { std::stringstream result; result << "C(min: " << constraint.min_val() << ", max: " << constraint.max_val() << ", f: " << constraint.factor() << ")"; return result.str(); } std::string to_string( util::SizeHint const& size_hint ) { std::stringstream result; result << "Hwidth: " << to_string(size_hint.width()) << ", Hheight:" << to_string(size_hint.height()); return result.str(); } std::string to_string( border::Buffer & buffer ) { char char_map[16] = { ' ',//NONE = 0b00000, '0',//UNUSED_1 = 0b00001, '0',//UNUSED_2 = 0b00010, '7',//BOTTOM_LEFT = 0b00011, '0',//UNUSED_4 = 0b00100, '|',//VERTICAL = 0b00101, '1',//TOP_LEFT = 0b00110, '8',//TEE_RIGHT = 0b00111, '0',//UNUSED_8 = 0b01000, '5',//BOTTOM_RIGHT = 0b01001, '-',//HORIZONTAL = 0b01010, '6',//TEE_TOP = 0b01011, '3',//TOP_RIGHT = 0b01100, '4',//TEE_LEFT = 0b01101, '2',//TEE_BOTTOM = 0b01110, '+' //CROSS = 0b01111, }; char inv_map[16] = { ' ',//NONE = 0b00000, '0',//UNUSED_1 = 0b00001, '0',//UNUSED_2 = 0b00010, 'G',//BOTTOM_LEFT = 0b00011, '0',//UNUSED_4 = 0b00100, '#',//VERTICAL = 0b00101, 'A',//TOP_LEFT = 0b00110, 'H',//TEE_RIGHT = 0b00111, '0',//UNUSED_8 = 0b01000, 'E',//BOTTOM_RIGHT = 0b01001, '=',//HORIZONTAL = 0b01010, 'F',//TEE_TOP = 0b01011, 'C',//TOP_RIGHT = 0b01100, 'D',//TEE_LEFT = 0b01101, 'B',//TEE_BOTTOM = 0b01110, '%' //CROSS = 0b01111, }; std::stringstream borders; util::Point pos; border::Element *element; while( element = buffer.get( pos ) ) { while( element = buffer.get( pos ) ) { //borders << element->to_char(char_map); if(element->is_inverted()) { borders << element->to_char(inv_map); } else { borders << element->to_char(char_map); } pos.right(); } borders << "\n"; pos.break_line(); } return borders.str(); } }
5,437
2,150
// // Created by root on 17-5-3. // #include "decode_ts.h"
60
31
// RUN: %clangxx_hwasan -DSIZE=16 -O0 %s -o %t && %run %t 2>&1 | FileCheck %s // REQUIRES: stable-runtime #include <assert.h> #include <stdlib.h> #include <sys/mman.h> #include <sanitizer/hwasan_interface.h> int main() { char *alloc = (char *)malloc(4096); // Simulate short granule tags. alloc[15] = 0x00; alloc[31] = 0xbb; alloc[47] = 0xcc; alloc[63] = 0xdd; alloc[79] = 0xee; alloc[95] = 0xff; // __hwasan_tag_memory expects untagged pointers. char *p = (char *)__hwasan_tag_pointer(alloc, 0); assert(p); // Write tags to shadow. __hwasan_tag_memory(p, 1, 32); __hwasan_tag_memory(p + 32, 16, 16); __hwasan_tag_memory(p + 48, 0, 32); __hwasan_tag_memory(p + 80, 4, 16); char *q = (char *)__hwasan_tag_pointer(p, 7); __hwasan_print_shadow(q + 5, 89 - 5); // CHECK: HWASan shadow map for {{.*}}5 .. {{.*}}9 (pointer tag 7) // CHECK-NEXT: {{.*}}0: 01(00) // CHECK-NEXT: {{.*}}0: 01(bb) // CHECK-NEXT: {{.*}}0: 10 // CHECK-NEXT: {{.*}}0: 00 // CHECK-NEXT: {{.*}}0: 00 // CHECK-NEXT: {{.*}}0: 04(ff) free(alloc); }
1,090
555
#include <bits/stdc++.h> #define ll long long using namespace std; int main() { ios_base::sync_with_stdio(0); cin.tie(0); char s[] = "nilesh"; int n = sizeof(s) / sizeof(s[0]); // n i l e s h \0 // | | // p q char *p = s; char *q = s+n-2; for(int i=0; i<n/2; i++) { char tmp = *p; *p = *q; *q = tmp; p++, q--; } cout << s << '\n'; return 0; }
414
201
#include "SD.h" #include <cstdio> // set up variables using the SD utility library functions: Sd2Card card; SdVolume volume; SdFile root; extern "C" { void sd_demo(void); } void sd_demo() { printf("Initializing SD card...\r\n"); // see if the card is present and can be initialized: if (!SD.begin(0)) { printf("Card failed, or not present\r\n"); // don't do anything more: while (1); } printf("card initialized.\r\n"); // open the file. note that only one file can be open at a time, // so you have to close this one before opening another. File dataFile = SD.open("busybox.txt"); // if the file is available, write to it: if (dataFile) { uint8_t cnt = 0; while (dataFile.available()) { if (cnt == 0) { printf("\r\n"); } cnt++; printf("%c",dataFile.read()); } printf("\r\nClosing file\r\n"); dataFile.close(); } // if the file isn't open, pop up an error: else { printf("error opening file"); } printf("Done!\r\n"); }
1,028
364
#include <iostream> #include <string> #include <vector> using namespace std; double celcius_a_fahrenheit (double celcius) { double fahrenheit = ((celcius * 9.0)/5.0) + 32.0; return fahrenheit; } //función principal int main () { double grados_celcius; cout << "Ingrese los grados celcius para pasarlos a Fahrenheit" << endl; cin >> grados_celcius; cout << "La conversión es: " << grados_celcius << "ºC" << " = " << celcius_a_fahrenheit (grados_celcius) << "ºF." << endl; }
487
190
/* ## @file # # Copyright (c) 2018 Loongson Technology Corporation Limited (www.loongson.cn). # All intellectual property rights(Copyright, Patent and Trademark) reserved. # # Any violations of copyright or other intellectual property rights of the Loongson Technology # Corporation Limited will be held accountable in accordance with the law, # if you (or any of your subsidiaries, corporate affiliates or agents) initiate # directly or indirectly any Intellectual Property Assertion or Intellectual Property Litigation: # (i) against Loongson Technology Corporation Limited or any of its subsidiaries or corporate affiliates, # (ii) against any party if such Intellectual Property Assertion or Intellectual Property Litigation arises # in whole or in part from any software, technology, product or service of Loongson Technology Corporation # Limited or any of its subsidiaries or corporate affiliates, or (iii) against any party relating to the Software. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, # THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR # BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, # PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION). # # ## */ extern"C" { #include <Uefi.h> #include <Library/UefiBootServicesTableLib.h> } #undef NULL #define NULL 0 VOID *operator new(UINTN Size) throw() { VOID *RetVal; EFI_STATUS Status; if (Size == 0) { return NULL; } Status = gBS->AllocatePool(EfiLoaderData, (UINTN)Size, &RetVal); if (Status != EFI_SUCCESS) { RetVal = NULL; } return RetVal; } VOID *operator new[](UINTN cb) { VOID *res = operator new(cb); return res; } VOID operator delete(VOID *p) { if (p != NULL) { (VOID)gBS->FreePool(p); } } VOID operator delete[](VOID *p) { operator delete(p); } extern "C" VOID _Unwind_Resume(struct _Unwind_Exception *object) { } #include "CppCrt.cpp"
2,164
780
#include "DataFormats/EgammaCandidates/interface/ElectronFwd.h" #include "DataFormats/METReco/interface/CaloMET.h" #include "DataFormats/METReco/interface/CaloMETCollection.h" #include "CommonTools/CandAlgos/interface/ShallowCloneProducer.h" typedef ShallowCloneProducer<reco::CaloMETCollection> CaloMETShallowCloneProducer; #include "FWCore/Framework/interface/MakerMacros.h" DEFINE_FWK_MODULE(CaloMETShallowCloneProducer);
428
169
/*========================================================================= * * Copyright NumFOCUS * * 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 * * https://www.apache.org/licenses/LICENSE-2.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *=========================================================================*/ #ifndef itkVector_hxx #define itkVector_hxx #include "itkMath.h" #include "vnl/vnl_vector.h" #include "itkObject.h" #include "itkNumericTraitsVectorPixel.h" namespace itk { template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension>::Vector(const ValueType & r) : Superclass{ r } {} template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> & Vector<T, TVectorDimension>::operator=(const ValueType r[TVectorDimension]) { BaseArray::operator=(r); return *this; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::operator+=(const Self & vec) -> const Self & { for (unsigned int i = 0; i < TVectorDimension; ++i) { (*this)[i] += vec[i]; } return *this; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::operator-=(const Self & vec) -> const Self & { for (unsigned int i = 0; i < TVectorDimension; ++i) { (*this)[i] -= vec[i]; } return *this; } template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> Vector<T, TVectorDimension>::operator-() const { Self result; for (unsigned int i = 0; i < TVectorDimension; ++i) { result[i] = -(*this)[i]; } return result; } template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> Vector<T, TVectorDimension>::operator+(const Self & vec) const { Self result; for (unsigned int i = 0; i < TVectorDimension; ++i) { result[i] = (*this)[i] + vec[i]; } return result; } template <typename T, unsigned int TVectorDimension> Vector<T, TVectorDimension> Vector<T, TVectorDimension>::operator-(const Self & vec) const { Self result; for (unsigned int i = 0; i < TVectorDimension; ++i) { result[i] = (*this)[i] - vec[i]; } return result; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::GetSquaredNorm() const -> RealValueType { typename NumericTraits<RealValueType>::AccumulateType sum = NumericTraits<T>::ZeroValue(); for (unsigned int i = 0; i < TVectorDimension; ++i) { const RealValueType value = (*this)[i]; sum += value * value; } return sum; } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::GetNorm() const -> RealValueType { return RealValueType(std::sqrt(static_cast<double>(this->GetSquaredNorm()))); } template <typename T, unsigned int TVectorDimension> auto Vector<T, TVectorDimension>::Normalize() -> RealValueType { const RealValueType norm = this->GetNorm(); if (norm < NumericTraits<RealValueType>::epsilon()) { return norm; // Prevent division by 0 } const RealValueType inversedNorm = 1.0 / norm; for (unsigned int i = 0; i < TVectorDimension; ++i) { (*this)[i] = static_cast<T>(static_cast<RealValueType>((*this)[i] * inversedNorm)); } return norm; } template <typename T, unsigned int TVectorDimension> vnl_vector_ref<T> Vector<T, TVectorDimension>::GetVnlVector() { return vnl_vector_ref<T>(TVectorDimension, this->GetDataPointer()); } template <typename T, unsigned int TVectorDimension> vnl_vector<T> Vector<T, TVectorDimension>::GetVnlVector() const { // Return a vector_ref<>. This will be automatically converted to a // vnl_vector<>. We have to use a const_cast<> which would normally // be prohibited in a const method, but it is safe to do here // because the cast to vnl_vector<> will ultimately copy the data. return vnl_vector_ref<T>(TVectorDimension, const_cast<T *>(this->GetDataPointer())); } template <typename T, unsigned int TVectorDimension> void Vector<T, TVectorDimension>::SetVnlVector(const vnl_vector<T> & v) { for (unsigned int i = 0; i < v.size(); ++i) { (*this)[i] = v(i); } } template <typename T, unsigned int TVectorDimension> std::ostream & operator<<(std::ostream & os, const Vector<T, TVectorDimension> & vct) { os << "["; if (TVectorDimension == 1) { os << vct[0]; } else { for (unsigned int i = 0; i + 1 < TVectorDimension; ++i) { os << vct[i] << ", "; } os << vct[TVectorDimension - 1]; } os << "]"; return os; } template <typename T, unsigned int TVectorDimension> std::istream & operator>>(std::istream & is, Vector<T, TVectorDimension> & vct) { for (unsigned int i = 0; i < TVectorDimension; ++i) { is >> vct[i]; } return is; } template <typename T, unsigned int TVectorDimension> typename Vector<T, TVectorDimension>::ValueType Vector<T, TVectorDimension>::operator*(const Self & other) const { typename NumericTraits<T>::AccumulateType value = NumericTraits<T>::ZeroValue(); for (unsigned int i = 0; i < TVectorDimension; ++i) { value += (*this)[i] * other[i]; } return value; } } // end namespace itk #endif
5,537
1,889
#include "Geometry.hpp" /** \brief Initializes a Geometry node visible with a mesh. The node will take the name of the mesh * \param M Mesh to use in this geometry node. It takes ownership of the mesh and takes care of deleting it at the end */ Geometry::Geometry(Mesh* M) : CompositeNode(M->GetName()), Visible(true), _state(0) { SetMesh(M); }; /** \brief Initializes a Geometry node visible with a mesh and a name. * \param M Mesh to use in this geometry node. It takes ownership of the mesh and takes care of deleting it at the end * \param Name of the GeometryNode */ Geometry::Geometry(Mesh* M, const string& Name) : CompositeNode(Name), Visible(true), _state(0) { SetMesh(M); }; /** \brief Destructor deletes mesh */ Geometry::~Geometry() { delete _mesh; delete _state; }; /** \brief Accept method just calls VisitGeometry from Visitor * \param Visitor of the Node */ void Geometry::Accept( NodeVisitor* Visitor ) { Visitor->VisitGeometry( this ); } /** \brief Set a new mesh for this Geometry object * \param M to set */ void Geometry::SetMesh( Mesh* M ) { if (M == 0) LOG(WARNING) << "Try to initialize Geometry with null pointer!" << endl; _mesh = M; } const Mesh* Geometry::GetMesh() const { return _mesh; } /** \brief Set a State for this Geometry. If there was an old state it will be removed. We take control over the state and free it at the end * \param s to use */ void Geometry::SetState(State* s) { delete _state; _state = s; } /** \brief Get the State for this Geometry. Can be zero! */ const State* Geometry::GetState() const { return _state; } /** \brief Decides if the object is visible or not * \param NewStatus is true -> is visible, otherwise not */ void Geometry::SetVisibility(bool NewStatus) { this->Visible = NewStatus; } /** \brief Check if the object is visible * \return true if visible, false otherwise */ bool Geometry::GetVisibility() const { return this->Visible; }
1,948
632
//! \file translator_exceptions.hpp //! \brief Exception classes that may be thrown by the translator. #ifndef AUTONOMY_COMPILER_TRANSLATOR_EXCEPTIONS_HPP #define AUTONOMY_COMPILER_TRANSLATOR_EXCEPTIONS_HPP #include <string> #include <exception> #include <autonomy/compiler/parser_ids.hpp> namespace autonomy { namespace compiler { //! \class translator_exception //! \brief Generic translator exception. class translator_exception : public std::exception { public: translator_exception(std::string const& msg); ~translator_exception() throw () {} virtual const char* what() const throw (); private: std::string _msg; }; //! \class corrupted_parse_tree //! \brief Exception for parse trees recognized as malformed. class corrupted_parse_tree : public translator_exception { public: corrupted_parse_tree(parser_id_t at_node, parser_id_t prev_node); ~corrupted_parse_tree() throw () {} }; //! \class undeclared_variable //! \brief Thrown when attempting to reference an undeclared variable. class undeclared_variable : public translator_exception { public: undeclared_variable(std::string const& symbol); ~undeclared_variable() throw () {} }; //! \class undefined_command //! \brief Thrown when attempting to access an unavailable command. class undefined_command : public translator_exception { public: undefined_command(std::string const& symbol); ~undefined_command() throw () {} }; } } #endif
1,911
503
// Made by RequestFX#1541 #pragma once namespace vals { namespace signatures { static long anim_overlays, clientstate_choked_commands, clientstate_delta_ticks, clientstate_last_outgoing_command, clientstate_net_channel, convar_name_hash_table, dwClientState, dwClientState_GetLocalPlayer, dwClientState_IsHLTV, dwClientState_Map, dwClientState_MapDirectory, dwClientState_MaxPlayer, dwClientState_PlayerInfo, dwClientState_State, dwClientState_ViewAngles, dwEntityList, dwForceAttack, dwForceAttack2, dwForceBackward, dwForceForward, dwForceJump, dwForceLeft, dwForceRight, dwGameDir, dwGameRulesProxy, dwGetAllClasses, dwGlobalVars, dwGlowObjectManager, dwInput, dwInterfaceLinkList, dwLocalPlayer, dwMouseEnable, dwMouseEnablePtr, dwPlayerResource, dwRadarBase, dwSensitivity, dwSensitivityPtr, dwSetClanTag, dwViewMatrix, dwWeaponTable, dwWeaponTableIndex, dwYawPtr, dwZoomSensitivityRatioPtr, dwbSendPackets, dwppDirect3DDevice9, find_hud_element, force_update_spectator_glow, interface_engine_cvar, is_c4_owner, m_bDormant, m_flSpawnTime, m_pStudioHdr, m_pitchClassPtr, m_yawClassPtr, model_ambient_min, set_abs_angles, set_abs_origin; } namespace netvars { static long cs_gamerules_data, m_ArmorValue, m_Collision, m_CollisionGroup, m_Local, m_MoveType, m_OriginalOwnerXuidHigh, m_OriginalOwnerXuidLow, m_SurvivalGameRuleDecisionTypes, m_SurvivalRules, m_aimPunchAngle, m_aimPunchAngleVel, m_angEyeAnglesX, m_angEyeAnglesY, m_bBombPlanted, m_bFreezePeriod, m_bGunGameImmunity, m_bHasDefuser, m_bHasHelmet, m_bInReload, m_bIsDefusing, m_bIsQueuedMatchmaking, m_bIsScoped, m_bIsValveDS, m_bSpotted, m_bSpottedByMask, m_bStartedArming, m_bUseCustomAutoExposureMax, m_bUseCustomAutoExposureMin, m_bUseCustomBloomScale, m_clrRender, m_dwBoneMatrix, m_fAccuracyPenalty, m_fFlags, m_flC4Blow, m_flCustomAutoExposureMax, m_flCustomAutoExposureMin, m_flCustomBloomScale, m_flDefuseCountDown, m_flDefuseLength, m_flFallbackWear, m_flFlashDuration, m_flFlashMaxAlpha, m_flLastBoneSetupTime, m_flLowerBodyYawTarget, m_flNextAttack, m_flNextPrimaryAttack, m_flSimulationTime, m_flTimerLength, m_hActiveWeapon, m_hMyWeapons, m_hObserverTarget, m_hOwner, m_hOwnerEntity, m_hViewModel, m_iAccountID, m_iClip1, m_iCompetitiveRanking, m_iCompetitiveWins, m_iCrosshairId, m_iEntityQuality, m_iFOV, m_iFOVStart, m_iGlowIndex, m_iHealth, m_iItemDefinitionIndex, m_iItemIDHigh, m_iMostRecentModelBoneCounter, m_iObserverMode, m_iShotsFired, m_iState, m_iTeamNum, m_iViewModelIndex, m_lifeState, m_nFallbackPaintKit, m_nFallbackSeed, m_nFallbackStatTrak, m_nForceBone, m_nModelIndex, m_nTickBase, m_rgflCoordinateFrame, m_szCustomName, m_szLastPlaceName, m_thirdPersonViewAngles, m_vecOrigin, m_vecVelocity, m_vecViewOffset, m_viewPunchAngle; } }
3,332
1,665
/// @copyright (c) 2007 CSIRO /// Australia Telescope National Facility (ATNF) /// Commonwealth Scientific and Industrial Research Organisation (CSIRO) /// PO Box 76, Epping NSW 1710, Australia /// atnf-enquiries@csiro.au /// /// This file is part of the ASKAP software distribution. /// /// The ASKAP software distribution 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 <askap_synthesis.h> #include <askap/AskapLogging.h> ASKAP_LOGGER(logger, ".measurementequation.imagedftequation"); #include <askap/AskapError.h> #include <dataaccess/SharedIter.h> #include <fitting/Params.h> #include <measurementequation/ImageDFTEquation.h> #include <fitting/GenericNormalEquations.h> #include <fitting/DesignMatrix.h> #include <fitting/Axes.h> #include <casacore/scimath/Mathematics/RigidVector.h> #include <casacore/casa/BasicSL/Constants.h> #include <casacore/casa/BasicSL/Complex.h> #include <casacore/casa/Arrays/Vector.h> #include <casacore/casa/Arrays/Matrix.h> #include <casacore/casa/Arrays/ArrayMath.h> #include <stdexcept> using askap::scimath::Params; using askap::scimath::Axes; using askap::scimath::DesignMatrix; namespace askap { namespace synthesis { ImageDFTEquation::ImageDFTEquation(const askap::scimath::Params& ip, accessors::IDataSharedIter& idi) : scimath::Equation(ip), askap::scimath::GenericEquation(ip), itsIdi(idi) { init(); }; ImageDFTEquation::ImageDFTEquation(accessors::IDataSharedIter& idi) : itsIdi(idi) { reference(defaultParameters().clone()); init(); } ImageDFTEquation::~ImageDFTEquation() { } ImageDFTEquation::ImageDFTEquation(const ImageDFTEquation& other) : Equation(other), GenericEquation(other) { operator=(other); } ImageDFTEquation& ImageDFTEquation::operator=(const ImageDFTEquation& other) { if(this!=&other) { static_cast<askap::scimath::GenericEquation*>(this)->operator=(other); itsIdi=other.itsIdi; } return *this; } void ImageDFTEquation::init() { } askap::scimath::Params ImageDFTEquation::defaultParameters() { Params ip; ip.add("image"); return ip; } /// Clone this into a shared pointer /// @return shared pointer to a copy ImageDFTEquation::ShPtr ImageDFTEquation::clone() const { return ImageDFTEquation::ShPtr(new ImageDFTEquation(*this)); } void ImageDFTEquation::predict() const { vector<string> completions(parameters().completions("image.i")); vector<string>::const_iterator it; if(completions.size()==0) { ASKAPLOG_WARN_STR(logger, "No parameters appropriate for ImageFFTEquation"); return; } // itsIdi.chooseBuffer("model"); for (itsIdi.init();itsIdi.hasMore();itsIdi.next()) { const casa::Vector<double>& freq=itsIdi->frequency(); //const double time=itsIdi->time(); const uint nChan=freq.nelements(); const uint nRow=itsIdi->nRow(); casa::Matrix<double> vis(nRow,2*nChan); vis.set(0.0); for (it=completions.begin();it!=completions.end();it++) { string imageName("image.i"+(*it)); const casa::Array<double> imagePixels(parameters().value(imageName)); const casa::IPosition imageShape(imagePixels.shape()); Axes axes(parameters().axes(imageName)); if(!axes.has("RA")||!axes.has("DEC")) { throw(std::invalid_argument("RA and DEC specification not present for "+imageName)); } double raStart=axes.start("RA"); double raEnd=axes.end("RA"); int raCells=imageShape(axes.order("RA")); double decStart=axes.start("DEC"); double decEnd=axes.end("DEC"); int decCells=imageShape(axes.order("DEC")); casa::Matrix<double> noDeriv(0,0); this->calcVisDFT(imagePixels, raStart, raEnd, raCells, decStart, decEnd, decCells, freq, itsIdi->uvw(), vis, false, noDeriv); for (uint row=0;row<nRow;row++) { for (uint i=0;i<nChan;i++) { itsIdi->rwVisibility()(row,i,0) += casa::Complex(vis(row,2*i), vis(row,2*i+1)); } } } } }; void ImageDFTEquation::calcGenericEquations(askap::scimath::GenericNormalEquations& ne) const { // Loop over all completions i.e. all sources vector<string> completions(parameters().completions("image.i")); vector<string>::iterator it; if(completions.size()==0) { ASKAPLOG_WARN_STR(logger, "No parameters appropriate for ImageFFTEquation"); return; } // itsIdi.chooseOriginal(); for (itsIdi.init();itsIdi.hasMore();itsIdi.next()) { const casa::Vector<double>& freq=itsIdi->frequency(); const uint nChan=freq.nelements(); const uint nRow=itsIdi->nRow(); //const double time=itsIdi->time(); // Set up arrays to hold the output values // Row, Two values (complex) per channel, single pol casa::Vector<double> residual(2*nRow*nChan); casa::Vector<double> weights(2*nRow*nChan); weights.set(1.0); casa::Matrix<double> vis(nRow,2*nChan); vis.set(0.0); for (it=completions.begin();it!=completions.end();it++) { string imageName("image.i"+(*it)); if(parameters().isFree(imageName)) { const casa::Array<double> imagePixels(parameters().value(imageName)); const casa::IPosition imageShape(imagePixels.shape()); Axes axes(parameters().axes(imageName)); if(!axes.has("RA")||!axes.has("DEC")) { throw(std::invalid_argument("RA and DEC specification not present for "+imageName)); } double raStart=axes.start("RA"); double raEnd=axes.end("RA"); int raCells=imageShape(axes.order("RA")); double decStart=axes.start("DEC"); double decEnd=axes.end("DEC"); int decCells=imageShape(axes.order("DEC")); const uint nPixels=imagePixels.nelements(); DesignMatrix designmatrix; //old parameters: parameters(); casa::Matrix<double> imageDeriv(2*nRow*nChan,nPixels); this->calcVisDFT(imagePixels, raStart, raEnd, raCells, decStart, decEnd, decCells, freq, itsIdi->uvw(), vis, true, imageDeriv); for (uint row=0;row<itsIdi->nRow();row++) { for (uint i=0;i<freq.nelements();i++) { residual(nChan*row+2*i)=real(itsIdi->visibility()(row,i,0))-vis(row,2*i); residual(nChan*row+2*i+1)=imag(itsIdi->visibility()(row,i,0))-vis(row,2*i+1); } } // Now we can add the design matrix, residual, and weights designmatrix.addDerivative(imageName, imageDeriv); designmatrix.addResidual(residual, weights); ne.add(designmatrix); } } } }; void ImageDFTEquation::calcVisDFT(const casa::Array<double>& imagePixels, const double raStart, const double raEnd, const int raCells, const double decStart, const double decEnd, const int decCells, const casa::Vector<double>& freq, const casa::Vector<casa::RigidVector<double, 3> >& uvw, casa::Matrix<double>& vis, bool doDeriv, casa::Matrix<double>& imageDeriv) { double raInc=(raStart-raEnd)/double(raCells); double decInc=(decStart-decEnd)/double(decCells); const uint nRow=uvw.nelements(); const uint nChan=freq.nelements(); vis.set(0.0); for (uint row=0;row<nRow;row++) { uint pixel=0; double u=uvw(row)(0); double v=uvw(row)(1); double w=uvw(row)(2); ASKAPDEBUGASSERT(decCells>=0); ASKAPDEBUGASSERT(raCells>=0); for (uint m=0;m<uint(decCells);++m) { double dec = decStart + m * decInc; for (uint l=0;l<uint(raCells);l++) { double ra = raStart + l * raInc; double delay = casa::C::_2pi * (ra * u + dec * v + sqrt(1 - ra * ra - dec * dec) * w)/casa::C::c; double flux = imagePixels(casa::IPosition(2, l, m)); if(doDeriv) { for (uint i=0;i<nChan;i++) { double phase = delay * freq(i); vis(row,2*i) += flux * cos(phase); vis(row,2*i+1) += flux * sin(phase); imageDeriv(nChan*row+2*i,pixel) = cos(phase); imageDeriv(nChan*row+2*i+1,pixel) = sin(phase); } } else { for (uint i=0;i<nChan;i++) { double phase = delay * freq(i); vis(row,2*i) += flux * cos(phase); vis(row,2*i+1) += flux * sin(phase); } } pixel++; } } } } } }
9,807
3,247
/* * Author: Jon Trulson <jtrulson@ics.com> * Copyright (c) 2015 Intel Corporation. * * This code is heavily based on the Adafruit-PN532 library at * https://github.com/adafruit/Adafruit-PN532, which is licensed under * the BSD license. See upm/src/pn532/license.txt * * 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 <unistd.h> #include <math.h> #include <iostream> #include <string> #include <stdexcept> #include "pn532.hpp" using namespace upm; using namespace std; #define PN532_PACKBUFFSIZ 64 static uint8_t pn532_packetbuffer[PN532_PACKBUFFSIZ]; static uint8_t pn532ack[] = {0x00, 0x00, 0xFF, 0x00, 0xFF, 0x00}; static uint32_t pn532_firmwarerev = 0x00320106; PN532::PN532(int irq, int reset, int bus, uint8_t address): m_gpioIRQ(irq), m_gpioReset(reset), m_i2c(bus) { m_addr = address; m_uidLen = 0; m_inListedTag = 0; m_SAK = 0; m_ATQA = 0; m_isrInstalled = false; m_irqRcvd = false; memset(m_uid, 0, 7); memset(m_key, 0, 6); // turn off debugging by default pn532Debug(false); mifareDebug(false); mraa::Result rv; if ( (rv = m_i2c.address(m_addr)) != mraa::SUCCESS) { throw std::runtime_error(std::string(__FUNCTION__) + ": I2c.address() failed"); return; } m_gpioIRQ.dir(mraa::DIR_IN); m_gpioReset.dir(mraa::DIR_OUT); } PN532::~PN532() { if (m_isrInstalled) m_gpioIRQ.isrExit(); } bool PN532::init() { m_gpioReset.write(1); m_gpioReset.write(0); usleep(400000); // install an interrupt handler m_gpioIRQ.isr(mraa::EDGE_FALLING, dataReadyISR, this); m_isrInstalled = true; m_gpioReset.write(1); return true; } /**************************************************************************/ /*! @brief Prints a hexadecimal value in plain characters @param data Pointer to the byte data @param numBytes Data length in bytes */ /**************************************************************************/ static void PrintHex(const uint8_t * data, const uint32_t numBytes) { uint32_t szPos; for (szPos=0; szPos < numBytes; szPos++) { fprintf(stderr, "0x%02x ", data[szPos] & 0xff); } fprintf(stderr, "\n"); } /**************************************************************************/ /*! @brief Prints a hexadecimal value in plain characters, along with the char equivalents in the following format 00 00 00 00 00 00 ...... @param data Pointer to the byte data @param numBytes Data length in bytes */ /**************************************************************************/ static void PrintHexChar(const uint8_t * data, const uint32_t numBytes) { uint32_t szPos; for (szPos=0; szPos < numBytes; szPos++) { fprintf(stderr, "0x%02x ", data[szPos] & 0xff); } fprintf(stderr, " "); for (szPos=0; szPos < numBytes; szPos++) { if (data[szPos] <= 0x1F) fprintf(stderr, "."); else fprintf(stderr, "%c ", (char)data[szPos]); } fprintf(stderr, "\n"); } /**************************************************************************/ /*! @brief Checks the firmware version of the PN5xx chip @returns The chip's firmware version and ID */ /**************************************************************************/ uint32_t PN532::getFirmwareVersion() { uint32_t response = 0; pn532_packetbuffer[0] = CMD_GETFIRMWAREVERSION; if (! sendCommandCheckAck(pn532_packetbuffer, 1)) return 0; // read data packet readData(pn532_packetbuffer, 12); int offset = 7; // Skip the ready byte when using I2C response <<= 8; response |= pn532_packetbuffer[offset++]; response <<= 8; response |= pn532_packetbuffer[offset++]; response <<= 8; response |= pn532_packetbuffer[offset++]; if (response != pn532_firmwarerev) fprintf(stderr, "Warning: firmware revision 0x%08x does not match expected rev 0x%08x\n", response, pn532_firmwarerev); return response; } /**************************************************************************/ /*! @brief Sends a command and waits a specified period for the ACK @param cmd Pointer to the command buffer @param cmdlen The size of the command in bytes @param timeout timeout before giving up @returns 1 if everything is OK, 0 if timeout occurred before an ACK was received */ /**************************************************************************/ // default timeout of one second bool PN532::sendCommandCheckAck(uint8_t *cmd, uint8_t cmdlen, uint16_t timeout) { // clear any outstanding irq's isReady(); // write the command writeCommand(cmd, cmdlen); // Wait for chip to say its ready! if (!waitForReady(timeout)) { cerr << __FUNCTION__ << ": Not ready, timeout" << endl; return false; } if (m_pn532Debug) cerr << __FUNCTION__ << ": IRQ received" << endl; // read acknowledgement if (!readAck()) { if (m_pn532Debug) cerr << __FUNCTION__ << ": No ACK frame received!" << endl; return false; } return true; // ack'd command } /**************************************************************************/ /*! @brief Configures the SAM (Secure Access Module) */ /**************************************************************************/ bool PN532::SAMConfig(void) { pn532_packetbuffer[0] = CMD_SAMCONFIGURATION; pn532_packetbuffer[1] = 0x01; // normal mode; pn532_packetbuffer[2] = 0x14; // timeout 50ms * 20 = 1 second pn532_packetbuffer[3] = 0x01; // use IRQ pin! if (! sendCommandCheckAck(pn532_packetbuffer, 4)) return false; // read data packet readData(pn532_packetbuffer, 8); int offset = 6; return (pn532_packetbuffer[offset] == 0x15); } /**************************************************************************/ /*! Sets the MxRtyPassiveActivation byte of the RFConfiguration register @param maxRetries 0xFF to wait forever, 0x00..0xFE to timeout after mxRetries @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::setPassiveActivationRetries(uint8_t maxRetries) { pn532_packetbuffer[0] = CMD_RFCONFIGURATION; pn532_packetbuffer[1] = 5; // Config item 5 (MaxRetries) pn532_packetbuffer[2] = 0xFF; // MxRtyATR (default = 0xFF) pn532_packetbuffer[3] = 0x01; // MxRtyPSL (default = 0x01) pn532_packetbuffer[4] = maxRetries; if (m_mifareDebug) cerr << __FUNCTION__ << ": Setting MxRtyPassiveActivation to " << (int)maxRetries << endl; if (! sendCommandCheckAck(pn532_packetbuffer, 5)) return false; // no ACK return true; } /***** ISO14443A Commands ******/ /**************************************************************************/ /*! Waits for an ISO14443A target to enter the field @param cardBaudRate Baud rate of the card @param uid Pointer to the array that will be populated with the card's UID (up to 7 bytes) @param uidLength Pointer to the variable that will hold the length of the card's UID. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::readPassiveTargetID(BAUD_T cardbaudrate, uint8_t * uid, uint8_t * uidLength, uint16_t timeout) { pn532_packetbuffer[0] = CMD_INLISTPASSIVETARGET; pn532_packetbuffer[1] = 1; // max 1 cards at once (we can set this // to 2 later) pn532_packetbuffer[2] = cardbaudrate; if (!sendCommandCheckAck(pn532_packetbuffer, 3, timeout)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": No card(s) read" << endl; return false; // no cards read } // wait for a card to enter the field (only possible with I2C) if (m_pn532Debug) cerr << __FUNCTION__ << ": Waiting for IRQ (indicates card presence)" << endl; if (!waitForReady(timeout)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": IRQ Timeout" << endl; return false; } // read data packet readData(pn532_packetbuffer, 20); // check some basic stuff /* ISO14443A card response should be in the following format: byte Description ------------- ------------------------------------------ b0..6 Frame header and preamble b7 Tags Found b8 Tag Number (only one used in this example) b9..10 SENS_RES b11 SEL_RES b12 NFCID Length b13..NFCIDLen NFCID */ // SENS_RES SEL_RES Manufacturer/Card Type NFCID Len // -------- ------- ----------------------- --------- // 00 04 08 NXP Mifare Classic 1K 4 bytes // 00 02 18 NXP Mifare Classic 4K 4 bytes if (m_mifareDebug) cerr << __FUNCTION__ << ": Found " << (int)pn532_packetbuffer[7] << " tags" << endl; // only one card can be handled currently if (pn532_packetbuffer[7] != 1) return false; uint16_t sens_res = pn532_packetbuffer[9]; sens_res <<= 8; sens_res |= pn532_packetbuffer[10]; // store these for later retrieval, they can be used to more accurately // ID the type of card. m_ATQA = sens_res; m_SAK = pn532_packetbuffer[11]; // SEL_RES if (m_mifareDebug) { fprintf(stderr, "ATQA: 0x%04x\n", m_ATQA); fprintf(stderr, "SAK: 0x%02x\n", m_SAK); } /* Card appears to be Mifare Classic */ // JET: How so? *uidLength = pn532_packetbuffer[12]; if (m_mifareDebug) fprintf(stderr, "UID: "); for (uint8_t i=0; i < pn532_packetbuffer[12]; i++) { uid[i] = pn532_packetbuffer[13+i]; if (m_mifareDebug) fprintf(stderr, "0x%02x ", uid[i]); } if (m_mifareDebug) fprintf(stderr, "\n"); return true; } /**************************************************************************/ /*! @brief Exchanges an APDU with the currently inlisted peer @param send Pointer to data to send @param sendLength Length of the data to send @param response Pointer to response data @param responseLength Pointer to the response data length */ /**************************************************************************/ bool PN532::inDataExchange(uint8_t * send, uint8_t sendLength, uint8_t * response, uint8_t * responseLength) { if (sendLength > PN532_PACKBUFFSIZ-2) { if (m_pn532Debug) cerr << __FUNCTION__ << ": APDU length too long for packet buffer" << endl; return false; } uint8_t i; pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; // 0x40 pn532_packetbuffer[1] = m_inListedTag; for (i=0; i<sendLength; ++i) { pn532_packetbuffer[i+2] = send[i]; } if (!sendCommandCheckAck(pn532_packetbuffer,sendLength+2,1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Could not send ADPU" << endl; return false; } if (!waitForReady(1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Response never received for ADPU..." << endl; return false; } readData(pn532_packetbuffer, sizeof(pn532_packetbuffer)); if (pn532_packetbuffer[0] == 0 && pn532_packetbuffer[1] == 0 && pn532_packetbuffer[2] == 0xff) { uint8_t length = pn532_packetbuffer[3]; if (pn532_packetbuffer[4]!=(uint8_t)(~length+1)) { if (m_pn532Debug) fprintf(stderr, "Length check invalid: 0x%02x != 0x%02x\n", length, (~length)+1); return false; } if (pn532_packetbuffer[5]==PN532_PN532TOHOST && pn532_packetbuffer[6]==RSP_INDATAEXCHANGE) { if ((pn532_packetbuffer[7] & 0x3f)!=0) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Status code indicates an error" << endl; return false; } length -= 3; if (length > *responseLength) { length = *responseLength; // silent truncation... } for (i=0; i<length; ++i) { response[i] = pn532_packetbuffer[8+i]; } *responseLength = length; return true; } else { fprintf(stderr, "Don't know how to handle this command: 0x%02x\n", pn532_packetbuffer[6]); return false; } } else { cerr << __FUNCTION__ << ": Preamble missing" << endl; return false; } } /**************************************************************************/ /*! @brief 'InLists' a passive target. PN532 acting as reader/initiator, peer acting as card/responder. */ /**************************************************************************/ bool PN532::inListPassiveTarget() { m_inListedTag = 0; pn532_packetbuffer[0] = CMD_INLISTPASSIVETARGET; pn532_packetbuffer[1] = 1; pn532_packetbuffer[2] = 0; if (m_pn532Debug) cerr << __FUNCTION__ << ": About to inList passive target" << endl; if (!sendCommandCheckAck(pn532_packetbuffer,3,1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": Could not send inlist message" << endl; return false; } if (!waitForReady(30000)) { return false; } readData(pn532_packetbuffer, sizeof(pn532_packetbuffer)); if (pn532_packetbuffer[0] == 0 && pn532_packetbuffer[1] == 0 && pn532_packetbuffer[2] == 0xff) { uint8_t length = pn532_packetbuffer[3]; if (pn532_packetbuffer[4]!=(uint8_t)(~length+1)) { if (m_pn532Debug) fprintf(stderr, "Length check invalid: 0x%02x != 0x%02x\n", length, (~length)+1); return false; } if (pn532_packetbuffer[5]==PN532_PN532TOHOST && pn532_packetbuffer[6]==RSP_INLISTPASSIVETARGET) { if (pn532_packetbuffer[7] != 1) { cerr << __FUNCTION__ << ": Unhandled number of tags inlisted: " << (int)pn532_packetbuffer[7] << endl; return false; } m_inListedTag = pn532_packetbuffer[8]; if (m_pn532Debug) cerr << __FUNCTION__ << ": Tag number: " << (int)m_inListedTag << endl; return true; } else { if (m_pn532Debug) cerr << __FUNCTION__ << ": Unexpected response to inlist passive host" << endl; return false; } } else { if (m_pn532Debug) cerr << __FUNCTION__ << ": Preamble missing" << endl; return false; } return true; } /***** Mifare Classic Functions ******/ /* MIFARE CLASSIC DESCRIPTION ========================== Taken from: https://www.kismetwireless.net/code-old/svn/hardware/kisbee-02/firmware/drivers/rf/pn532/helpers/pn532_mifare_classic.c MIFARE Classic cards come in 1K and 4K varieties. While several varieties of chips exist, the two main chipsets used are described in the following publicly accessible documents: MF1S503x Mifare Classic 1K data sheet: http://www.nxp.com/documents/data_sheet/MF1S503x.pdf MF1S70yyX MIFARE Classic 4K data sheet: http://www.nxp.com/documents/data_sheet/MF1S70YYX.pdf Mifare Classic cards typically have a a 4-byte NUID, though you may find cards with 7 byte IDs as well EEPROM MEMORY ============= Mifare Classic cards have either 1K or 4K of EEPROM memory. Each memory block can be configured with different access conditions, with two seperate authentication keys present in each block. The two main Mifare Classic card types are organised as follows: 1K Cards: 16 sectors of 4 blocks (0..15) 4K Cards: 32 sectors of 4 blocks (0..31) and 8 sectors of 16 blocks (32..39) 4 block sectors =============== Sector Block Bytes Description ------ ----- ----- ----------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 1 3 [-------KEY A-------] [Access Bits] [-------KEY A-------] Sector Trailer 1 2 [ Data ] Data 1 [ Data ] Data 0 [ Data ] Data 0 3 [-------KEY A-------] [Access Bits] [-------KEY A-------] Sector Trailer 1 2 [ Data ] Data 1 [ Data ] Data 0 [ Manufacturer Data ] Manufacturer Block Sector Trailer (Block 3) ------------------------ The sector trailer block contains the two secret keys (Key A and Key B), as well as the access conditions for the four blocks. It has the following structure: Sector Trailer Bytes -------------------------------------------------------------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [ Key A ] [Access Bits] [ Key B ] For more information in using Keys to access the clock contents, see Accessing Data Blocks further below. Data Blocks (Blocks 0..2) ------------------------- Data blocks are 16 bytes wide and, depending on the permissions set in the access bits, can be read from and written to. You are free to use the 16 data bytes in any way you wish. You can easily store text input, store four 32-bit integer values, a 16 character uri, etc. Data Blocks as "Value Blocks" ----------------------------- An alternative to storing random data in the 16 byte-wide blocks is to configure them as "Value Blocks". Value blocks allow performing electronic purse functions (valid commands are: read, write, increment, decrement, restore, transfer). Each Value block contains a single signed 32-bit value, and this value is stored 3 times for data integrity and security reasons. It is stored twice non-inverted, and once inverted. The last 4 bytes are used for a 1-byte address, which is stored 4 times (twice non-inverted, and twice inverted). Data blocks configured as "Value Blocks" have the following structure: Value Block Bytes -------------------------------------------------------------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 [ Value ] [ ~Value ] [ Value ] [A ~A A ~A] Manufacturer Block (Sector 0, Block 0) -------------------------------------- Sector 0 is special since it contains the Manufacturer Block. This block contains the manufacturer data, and is read-only. It should be avoided unless you know what you are doing. 16 block sectors ================ 16 block sectors are identical to 4 block sectors, but with more data blocks. The same structure described in the 4 block sectors above applies. Sector Block Bytes Description ------ ----- ----- ---------- 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 32 15 [-------KEY A-------] [Access Bits] [-------KEY B-------] Sector Trailer 32 14 [ Data ] Data 13 [ Data ] Data ... 2 [ Data ] Data 1 [ Data ] Data 0 [ Data ] Data ACCESSING DATA BLOCKS ===================== Before you can access the cards, you must following two steps: 1.) You must retrieve the 7 byte UID or the 4-byte NUID of the card. This can be done using pn532_mifareclassic_WaitForPassiveTarget() below, which will return the appropriate ID. 2.) You must authenticate the sector you wish to access according to the access rules defined in the Sector Trailer block for that sector. This can be done using pn532_mifareclassic_AuthenticateBlock(), passing in the appropriate key value. Most new cards have a default Key A of 0xFF 0xFF 0xFF 0xFF 0xFF 0xFF, but some common values worth trying are: 0XFF 0XFF 0XFF 0XFF 0XFF 0XFF 0XD3 0XF7 0XD3 0XF7 0XD3 0XF7 0XA0 0XA1 0XA2 0XA3 0XA4 0XA5 0XB0 0XB1 0XB2 0XB3 0XB4 0XB5 0X4D 0X3A 0X99 0XC3 0X51 0XDD 0X1A 0X98 0X2C 0X7E 0X45 0X9A 0XAA 0XBB 0XCC 0XDD 0XEE 0XFF 0X00 0X00 0X00 0X00 0X00 0X00 0XAB 0XCD 0XEF 0X12 0X34 0X56 3.) Once authenication has succeeded, and depending on the sector permissions, you can then read/write/increment/decrement the contents of the specific block, using one of the helper functions included in this module. */ /**************************************************************************/ /*! Indicates whether the specified block number is the first block in the sector (block 0 relative to the current sector) */ /**************************************************************************/ bool PN532::mifareclassic_IsFirstBlock (uint32_t uiBlock) { // Test if we are in the small or big sectors if (uiBlock < 128) return ((uiBlock) % 4 == 0); else return ((uiBlock) % 16 == 0); } /**************************************************************************/ /*! Indicates whether the specified block number is the sector trailer */ /**************************************************************************/ bool PN532::mifareclassic_IsTrailerBlock (uint32_t uiBlock) { // Test if we are in the small or big sectors if (uiBlock < 128) return ((uiBlock + 1) % 4 == 0); else return ((uiBlock + 1) % 16 == 0); } /**************************************************************************/ /*! Tries to authenticate a block of memory on a MIFARE card using the INDATAEXCHANGE command. See section 7.3.8 of the PN532 User Manual for more information on sending MIFARE and other commands. @param uid Pointer to a byte array containing the card UID @param uidLen The length (in bytes) of the card's UID (Should be 4 for MIFARE Classic) @param blockNumber The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). @param keyNumber Which key type to use during authentication (0 = MIFARE_CMD_AUTH_A, 1 = MIFARE_CMD_AUTH_B) @param keyData Pointer to a byte array containing the 6 byte key value @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_AuthenticateBlock (uint8_t * uid, uint8_t uidLen, uint32_t blockNumber, uint8_t keyNumber, uint8_t * keyData) { uint8_t i; // Hang on to the key and uid data memcpy (m_key, keyData, 6); memcpy (m_uid, uid, uidLen); m_uidLen = uidLen; if (m_mifareDebug) { fprintf(stderr, "Trying to authenticate card "); PrintHex(m_uid, m_uidLen); fprintf(stderr, "Using authentication KEY %c: ", keyNumber ? 'B' : 'A'); PrintHex(m_key, 6); } // Prepare the authentication command // pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; /* Data Exchange Header */ pn532_packetbuffer[1] = 1; /* Max card numbers */ pn532_packetbuffer[2] = (keyNumber) ? MIFARE_CMD_AUTH_B : MIFARE_CMD_AUTH_A; pn532_packetbuffer[3] = blockNumber; /* Block Number (1K = 0..63, 4K = 0..255 */ memcpy (pn532_packetbuffer+4, m_key, 6); for (i = 0; i < m_uidLen; i++) { pn532_packetbuffer[10+i] = m_uid[i]; /* 4 byte card ID */ } if (! sendCommandCheckAck(pn532_packetbuffer, 10+m_uidLen)) return false; if (!waitForReady(1000)) { if (m_pn532Debug) cerr << __FUNCTION__ << ": timeout waiting auth..." << endl; return false; } // Read the response packet readData(pn532_packetbuffer, 12); // check if the response is valid and we are authenticated??? // for an auth success it should be bytes 5-7: 0xD5 0x41 0x00 // Mifare auth error is technically byte 7: 0x14 but anything other // and 0x00 is not good if (pn532_packetbuffer[7] != 0x00) { if (m_pn532Debug) { fprintf(stderr, "Authentication failed: "); PrintHexChar(pn532_packetbuffer, 12); } return false; } return true; } /**************************************************************************/ /*! Tries to read an entire 16-byte data block at the specified block address. @param blockNumber The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). @param data Pointer to the byte array that will hold the retrieved data (if any) @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_ReadDataBlock (uint8_t blockNumber, uint8_t * data) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Trying to read 16 bytes from block " << (int)blockNumber << endl; /* Prepare the command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_CMD_READ; /* Mifare Read command = 0x30 */ pn532_packetbuffer[3] = blockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 4)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for read command" << endl; return false; } /* Read the response packet */ readData(pn532_packetbuffer, 26); /* If byte 8 isn't 0x00 we probably have an error */ if (pn532_packetbuffer[7] != 0x00) { if (m_mifareDebug) { fprintf(stderr, "Unexpected response: "); PrintHexChar(pn532_packetbuffer, 26); } return false; } /* Copy the 16 data bytes to the output buffer */ /* Block content starts at byte 9 of a valid response */ memcpy (data, pn532_packetbuffer+8, 16); /* Display data for debug if requested */ if (m_mifareDebug) { fprintf(stderr, "Block %d: ", blockNumber); PrintHexChar(data, 16); } return true; } /**************************************************************************/ /*! Tries to write an entire 16-byte data block at the specified block address. @param blockNumber The block number to authenticate. (0..63 for 1KB cards, and 0..255 for 4KB cards). @param data The byte array that contains the data to write. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_WriteDataBlock (uint8_t blockNumber, uint8_t * data) { if (m_mifareDebug) fprintf(stderr, "Trying to write 16 bytes to block %d\n", blockNumber); /* Prepare the first command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_CMD_WRITE; /* Mifare Write command = 0xA0 */ pn532_packetbuffer[3] = blockNumber; /* Block Number (0..63 for 1K, 0..255 for 4K) */ memcpy (pn532_packetbuffer+4, data, 16); /* Data Payload */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 20)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for write command" << endl; return false; } usleep(10000); /* Read the response packet */ readData(pn532_packetbuffer, 26); return true; } /**************************************************************************/ /*! Formats a Mifare Classic card to store NDEF Records @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_FormatNDEF (void) { uint8_t sectorbuffer1[16] = {0x14, 0x01, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}; uint8_t sectorbuffer2[16] = {0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1, 0x03, 0xE1}; uint8_t sectorbuffer3[16] = {0xA0, 0xA1, 0xA2, 0xA3, 0xA4, 0xA5, 0x78, 0x77, 0x88, 0xC1, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; // Note 0xA0 0xA1 0xA2 0xA3 0xA4 0xA5 must be used for key A // for the MAD sector in NDEF records (sector 0) // Write block 1 and 2 to the card if (!(mifareclassic_WriteDataBlock (1, sectorbuffer1))) return false; if (!(mifareclassic_WriteDataBlock (2, sectorbuffer2))) return false; // Write key A and access rights card if (!(mifareclassic_WriteDataBlock (3, sectorbuffer3))) return false; // Seems that everything was OK (?!) return true; } /**************************************************************************/ /*! Writes an NDEF URI Record to the specified sector (1..15) Note that this function assumes that the Mifare Classic card is already formatted to work as an "NFC Forum Tag" and uses a MAD1 file system. You can use the NXP TagWriter app on Android to properly format cards for this. @param sectorNumber The sector that the URI record should be written to (can be 1..15 for a 1K card) @param uriIdentifier The uri identifier code (0 = none, 0x01 = "http://www.", etc.) @param url The uri text to write (max 38 characters). @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::mifareclassic_WriteNDEFURI (uint8_t sectorNumber, NDEF_URI_T uriIdentifier, const char * url) { if (!url) return false; // Figure out how long the string is uint8_t len = strlen(url); // Make sure we're within a 1K limit for the sector number if ((sectorNumber < 1) || (sectorNumber > 15)) return false; // Make sure the URI payload is between 1 and 38 chars if ((len < 1) || (len > 38)) return false; // Note 0xD3 0xF7 0xD3 0xF7 0xD3 0xF7 must be used for key A // in NDEF records // Setup the sector buffer (w/pre-formatted TLV wrapper and NDEF message) uint8_t sectorbuffer1[16] = {0x00, 0x00, 0x03, static_cast<uint8_t>(len+5), 0xD1, 0x01, static_cast<uint8_t>(len+1), 0x55, static_cast<uint8_t>(uriIdentifier), 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t sectorbuffer2[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t sectorbuffer3[16] = {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}; uint8_t sectorbuffer4[16] = {0xD3, 0xF7, 0xD3, 0xF7, 0xD3, 0xF7, 0x7F, 0x07, 0x88, 0x40, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF}; if (len <= 6) { // Unlikely we'll get a url this short, but why not ... memcpy (sectorbuffer1+9, url, len); sectorbuffer1[len+9] = 0xFE; } else if (len == 7) { // 0xFE needs to be wrapped around to next block memcpy (sectorbuffer1+9, url, len); sectorbuffer2[0] = 0xFE; } else if ((len > 7) && (len <= 22)) { // Url fits in two blocks memcpy (sectorbuffer1+9, url, 7); memcpy (sectorbuffer2, url+7, len-7); sectorbuffer2[len-7] = 0xFE; } else if (len == 23) { // 0xFE needs to be wrapped around to final block memcpy (sectorbuffer1+9, url, 7); memcpy (sectorbuffer2, url+7, len-7); sectorbuffer3[0] = 0xFE; } else { // Url fits in three blocks memcpy (sectorbuffer1+9, url, 7); memcpy (sectorbuffer2, url+7, 16); memcpy (sectorbuffer3, url+23, len-24); sectorbuffer3[len-23] = 0xFE; } // Now write all three blocks back to the card if (!(mifareclassic_WriteDataBlock (sectorNumber*4, sectorbuffer1))) return false; if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+1, sectorbuffer2))) return false; if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+2, sectorbuffer3))) return false; if (!(mifareclassic_WriteDataBlock ((sectorNumber*4)+3, sectorbuffer4))) return false; // Seems that everything was OK (?!) return true; } /***** NTAG2xx/ultralight Functions ******/ // Ultralight tags are limited to 64 pages max, with ntag2XX tags can // have up to 231 pages. /* MIFARE ULTRALIGHT DESCRIPTION ============================= Taken from: https://www.kismetwireless.net/code-old/svn/hardware/kisbee-02/firmware/drivers/rf/pn532/helpers/pn532_mifare_ultralight.c MIFARE Ultralight cards typically contain 512 bits (64 bytes) of memory, including 4 bytes (32-bits) of OTP (One Time Programmable) memory where the individual bits can be written but not erased. MF0ICU1 Mifare Ultralight Functional Specification: http://www.nxp.com/documents/data_sheet/MF0ICU1.pdf Mifare Ultralight cards have a 7-byte UID EEPROM MEMORY ============= Mifare Ultralight cards have 512 bits (64 bytes) of EEPROM memory, including 4 byte (32 bits) of OTP memory. Unlike Mifare Classic cards, there is no authentication on a per block level, although the blocks can be set to "read-only" mode using Lock Bytes (described below). EEPROM memory is organised into 16 pages of four bytes eachs, in the following order Page Description ---- ------------ 0 Serial Number (4 bytes) 1 Serial Number (4 bytes) 2 Byte 0: Serial Number Byte 1: Internal Memory Byte 2..3: lock bytes 3 One-time programmable memory (4 bytes) 4..15 User memory (4 bytes) Lock Bytes (Page 2) ------------------- Bytes 2 and 3 of page 2 are referred to as "Lock Bytes". Each page from 0x03 and higher can individually locked by setting the corresponding locking bit to "1" to prevent further write access, effectively making the memory read only. For information on the lock byte mechanism, refer to section 8.5.2 of the datasheet (referenced above). OTP Bytes (Page 3) ------------------ Page 3 is the OTP memory, and by default all bits on this page are set to 0. These bits can be bitwise modified using the Mifare WRITE command, and individual bits can be set to 1, but can not be changed back to 0. Data Pages (Pages 4..15) ------------------------ Pages 4 to 15 are can be freely read from and written to, provided there is no conflict with the Lock Bytes described above. After production, the bytes have the following default values: Page Byte Values ---- ---------------------- 0 1 2 3 4 0xFF 0xFF 0xFF 0xFF 5..15 0x00 0x00 0x00 0x00 ACCESSING DATA BLOCKS ===================== Before you can access the cards, you must following two steps: 1.) 'Connect' to a Mifare Ultralight card and retrieve the 7 byte UID of the card. 2.) Memory can be read and written directly once a passive mode connection has been made. No authentication is required for Mifare Ultralight cards. */ /**************************************************************************/ /*! Tries to read an entire 4-byte page at the specified address. @param page The page number (0..63 in most cases) @param buffer Pointer to the byte array that will hold the retrieved data (if any) */ /**************************************************************************/ bool PN532::ntag2xx_ReadPage (uint8_t page, uint8_t * buffer) { // TAG Type PAGES USER START USER STOP // -------- ----- ---------- --------- // NTAG 203 42 4 39 // NTAG 213 45 4 39 // NTAG 215 135 4 129 // NTAG 216 231 4 225 if (page >= 231) { cerr << __FUNCTION__ << ": Page value out of range" << endl; return false; } if (m_mifareDebug) fprintf(stderr, "Reading page %d\n", page); /* Prepare the command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_CMD_READ; /* Mifare Read command = 0x30 */ pn532_packetbuffer[3] = page; /* Page Number (0..63 in most cases) */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 4)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for write command" << endl; return false; } /* Read the response packet */ readData(pn532_packetbuffer, 26); if (m_mifareDebug) { fprintf(stderr, "Received: \n"); PrintHexChar(pn532_packetbuffer, 26); } /* If byte 8 isn't 0x00 we probably have an error */ if (pn532_packetbuffer[7] == 0x00) { /* Copy the 4 data bytes to the output buffer */ /* Block content starts at byte 9 of a valid response */ /* Note that the command actually reads 16 byte or 4 */ /* pages at a time ... we simply discard the last 12 */ /* bytes */ memcpy (buffer, pn532_packetbuffer+8, 4); } else { if (m_mifareDebug) { fprintf(stderr, "Unexpected response reading block: \n"); PrintHexChar(pn532_packetbuffer, 26); } return false; } /* Display data for debug if requested */ if (m_mifareDebug) { fprintf(stderr, "Page %d:\n", page); PrintHexChar(buffer, 4); } // Return OK signal return true; } /**************************************************************************/ /*! Tries to write an entire 4-byte page at the specified block address. @param page The page number to write. (0..63 for most cases) @param data The byte array that contains the data to write. Should be exactly 4 bytes long. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::ntag2xx_WritePage (uint8_t page, uint8_t * data) { // TAG Type PAGES USER START USER STOP // -------- ----- ---------- --------- // NTAG 203 42 4 39 // NTAG 213 45 4 39 // NTAG 215 135 4 129 // NTAG 216 231 4 225 if ((page < 4) || (page > 225)) { cerr << __FUNCTION__ << ": Page value out of range" << endl; return false; } if (m_mifareDebug) fprintf(stderr, "Trying to write 4 byte page %d\n", page); /* Prepare the first command */ pn532_packetbuffer[0] = CMD_INDATAEXCHANGE; pn532_packetbuffer[1] = 1; /* Card number */ pn532_packetbuffer[2] = MIFARE_ULTRALIGHT_CMD_WRITE; /* Mifare Ultralight Write command = 0xA2 */ pn532_packetbuffer[3] = page; /* Page Number (0..63 for most cases) */ memcpy (pn532_packetbuffer+4, data, 4); /* Data Payload */ /* Send the command */ if (! sendCommandCheckAck(pn532_packetbuffer, 8)) { if (m_mifareDebug) cerr << __FUNCTION__ << ": Failed to receive ACK for write command" << endl; // Return Failed Signal return false; } usleep(10000); /* Read the response packet */ readData(pn532_packetbuffer, 26); // Return OK Signal return true; } /**************************************************************************/ /*! Writes an NDEF URI Record starting at the specified page (4..nn) Note that this function assumes that the NTAG2xx card is already formatted to work as an "NFC Forum Tag". @param uriIdentifier The uri identifier code (0 = none, 0x01 = "http://www.", etc.) @param url The uri text to write (null-terminated string). @param dataLen The size of the data area for overflow checks. @returns 1 if everything executed properly, 0 for an error */ /**************************************************************************/ bool PN532::ntag2xx_WriteNDEFURI (NDEF_URI_T uriIdentifier, char * url, uint8_t dataLen) { uint8_t pageBuffer[4] = { 0, 0, 0, 0 }; // Remove NDEF record overhead from the URI data (pageHeader below) uint8_t wrapperSize = 12; // Figure out how long the string is uint8_t len = strlen(url); // Make sure the URI payload will fit in dataLen (include 0xFE trailer) if ((len < 1) || (len+1 > (dataLen-wrapperSize))) return false; // Setup the record header // See NFCForum-TS-Type-2-Tag_1.1.pdf for details uint8_t pageHeader[12] = { /* NDEF Lock Control TLV (must be first and always present) */ 0x01, /* Tag Field (0x01 = Lock Control TLV) */ 0x03, /* Payload Length (always 3) */ 0xA0, /* The position inside the tag of the lock bytes (upper 4 = page address, lower 4 = byte offset) */ 0x10, /* Size in bits of the lock area */ 0x44, /* Size in bytes of a page and the number of bytes each lock bit can lock (4 bit + 4 bits) */ /* NDEF Message TLV - URI Record */ 0x03, /* Tag Field (0x03 = NDEF Message) */ static_cast<uint8_t>(len+5), /* Payload Length (not including 0xFE trailer) */ 0xD1, /* NDEF Record Header (TNF=0x1:Well known record + SR + ME + MB) */ 0x01, /* Type Length for the record type indicator */ static_cast<uint8_t>(len+1), /* Payload len */ 0x55, /* Record Type Indicator (0x55 or 'U' = URI Record) */ static_cast<uint8_t>(uriIdentifier) /* URI Prefix (ex. 0x01 = "http://www.") */ }; // Write 12 byte header (three pages of data starting at page 4) memcpy (pageBuffer, pageHeader, 4); if (!(ntag2xx_WritePage (4, pageBuffer))) return false; memcpy (pageBuffer, pageHeader+4, 4); if (!(ntag2xx_WritePage (5, pageBuffer))) return false; memcpy (pageBuffer, pageHeader+8, 4); if (!(ntag2xx_WritePage (6, pageBuffer))) return false; // Write URI (starting at page 7) uint8_t currentPage = 7; char * urlcopy = url; while (len) { if (len < 4) { memset(pageBuffer, 0, 4); memcpy(pageBuffer, urlcopy, len); pageBuffer[len] = 0xFE; // NDEF record footer if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; // DONE! return true; } else if (len == 4) { memcpy(pageBuffer, urlcopy, len); if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; memset(pageBuffer, 0, 4); pageBuffer[0] = 0xFE; // NDEF record footer currentPage++; if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; // DONE! return true; } else { // More than one page of data left memcpy(pageBuffer, urlcopy, 4); if (!(ntag2xx_WritePage (currentPage, pageBuffer))) return false; currentPage++; urlcopy+=4; len-=4; } } // Seems that everything was OK (?!) return true; } /**************************************************************************/ /*! @brief Tries to read/verify the ACK packet */ /**************************************************************************/ bool PN532::readAck() { uint8_t ackbuff[6]; readData(ackbuff, 6); return (0 == memcmp((char *)ackbuff, (char *)pn532ack, 6)); } /**************************************************************************/ /*! @brief Return true if the PN532 is ready with a response. */ /**************************************************************************/ bool PN532::isReady() { // ALWAYS clear the m_irqRcvd flag if set. if (m_irqRcvd) { m_irqRcvd = false; return true; } return false; } /**************************************************************************/ /*! @brief Waits until the PN532 is ready. @param timeout Timeout before giving up */ /**************************************************************************/ bool PN532::waitForReady(uint16_t timeout) { uint16_t timer = 0; while(!isReady()) { if (timeout != 0) { timer += 10; if (timer > timeout) { return false; } } usleep(10000); } return true; } /**************************************************************************/ /*! @brief Reads n bytes of data from the PN532 via SPI or I2C. @param buff Pointer to the buffer where data will be written @param n Number of bytes to be read */ /**************************************************************************/ void PN532::readData(uint8_t* buff, uint8_t n) { uint8_t buf[n + 2]; int rv; memset(buf, 0, n+2); usleep(2000); rv = m_i2c.read(buf, n + 2); if (m_pn532Debug) { cerr << __FUNCTION__ << ": read returned " << rv << "bytes" << endl; fprintf(stderr, "(raw) buf (%d) = ", rv); PrintHex(buf, rv); fprintf(stderr, "\n"); } for (int i=0; i<n; i++) buff[i] = buf[i+1]; if (m_pn532Debug) { fprintf(stderr, "(returned) buf (%d) = \n", n); PrintHex(buff, n); fprintf(stderr, "\n"); } } /**************************************************************************/ /*! @brief Writes a command to the PN532, automatically inserting the preamble and required frame details (checksum, len, etc.) @param cmd Pointer to the command buffer @param cmdlen Command length in bytes */ /**************************************************************************/ void PN532::writeCommand(uint8_t* cmd, uint8_t cmdlen) { // I2C command write. cmdlen++; usleep(2000); // 2ms max in case board needs to wake up // command + packet wrapper uint8_t buf[cmdlen + 8]; memset(buf, 0, cmdlen + 8); int offset = 0; if (m_pn532Debug) cerr << __FUNCTION__ << ": Sending: " << endl; uint8_t checksum = PN532_PREAMBLE + PN532_PREAMBLE + PN532_STARTCODE2; buf[offset++] = PN532_PREAMBLE; buf[offset++] = PN532_PREAMBLE; buf[offset++] = PN532_STARTCODE2; buf[offset++] = cmdlen; buf[offset++] = ~cmdlen + 1; buf[offset++] = PN532_HOSTTOPN532; checksum += PN532_HOSTTOPN532; for (uint8_t i=0; i<cmdlen - 1; i++) { buf[offset++] = cmd[i]; checksum += cmd[i]; } buf[offset++] = ~checksum; buf[offset] = PN532_POSTAMBLE; if (m_i2c.write(buf, cmdlen + 8 - 1) != mraa::SUCCESS) { throw std::runtime_error(std::string(__FUNCTION__) + ": mraa_i2c_write() failed"); return; } if (m_pn532Debug) { cerr << __FUNCTION__ << ": cmdlen + 8 = " << cmdlen + 8 <<", offset = " << offset << endl; PrintHex(buf, cmdlen + 8); } } void PN532::dataReadyISR(void *ctx) { upm::PN532 *This = (upm::PN532 *)ctx; // if debugging is enabled, indicate when an interrupt occurred, and // a previously triggered interrupt was still set. if (This->m_pn532Debug) if (This->m_irqRcvd) cerr << __FUNCTION__ << ": INFO: Unhandled IRQ detected." << endl; This->m_irqRcvd = true; } PN532::TAG_TYPE_T PN532::tagType() { // This is really just a guess, ATQA and SAK could in theory be used // to refine the detection. if (m_uidLen == 4) return TAG_TYPE_MIFARE_CLASSIC; else if (m_uidLen == 7) return TAG_TYPE_NFC2; else return TAG_TYPE_UNKNOWN; }
51,507
17,892
#include <iostream> #include <cstdio> #include <cstring> #include <cassert> #include <cctype> #include <algorithm> using namespace std; typedef long long lint; #define ni (next_num<int>()) #define nl (next_num<lint>()) template<class T>inline T next_num(){ T i=0;char c; while(!isdigit(c=getchar())&&c!='-'); bool flag=c=='-'; flag?(c=getchar()):0; while(i=i*10-'0'+c,isdigit(c=getchar())); return flag?-i:i; } inline void apmin(int &a,const int &b){ if(a>b){ a=b; } } const int N=250010,logN=20,INF=0x7f7f7f7f; struct Tree{ static const int E=N*2; int to[E],bro[E],val[E],head[N],etop; }; struct Virtual:Tree{ Virtual(){ memset(tag,0,sizeof(tag)); memset(vis,0,sizeof(vis)); tim=0; } int tag[N],tim; inline void add_edge(int,int); int vis[N]; lint f[N]; void dfs(int x){ f[x]=0; for(int i=head[x],v;~i;i=bro[i]){ if(vis[v=to[i]]==tim){ f[x]+=val[i]; }else{ dfs(v); f[x]+=min(f[v],(lint)val[i]); } } } }V; int dfn[N]; inline bool dfncmp(const int &a,const int &b){ return dfn[a]<dfn[b]; } struct Actual:Tree{ int fa[N][logN],len[N][logN],dep[N],ldep[N]; inline void reset(){ memset(head,-1,sizeof(head)); memset(len,127,sizeof(len)); memset(fa,0,sizeof(fa)); etop=tim=dep[1]=ldep[1]=0; dep[0]=-1; } inline void add_edge(int u,int v,int w){ to[etop]=v; bro[etop]=head[u]; val[etop]=w; head[u]=etop++; } int tim; void dfs(int x,int f){ dfn[x]=++tim; fa[x][0]=f; for(int &j=ldep[x];fa[x][j+1]=fa[fa[x][j]][j];j++){ len[x][j+1]=min(len[x][j],len[fa[x][j]][j]); } for(int i=head[x],v;~i;i=bro[i]){ v=to[i]; if(v!=f){ dep[v]=dep[x]+1; len[v][0]=val[i]; dfs(v,x); } } } inline int lca(int u,int v){ if(dep[u]<dep[v]){ swap(u,v); } for(int j=ldep[u];j>=0;j--){ if(dep[fa[u][j]]>=dep[v]){ u=fa[u][j]; } } if(u==v){ return u; } for(int j=min(ldep[u],ldep[v]);j>=0;j--){ if(fa[u][j]!=fa[v][j]){ u=fa[u][j],v=fa[v][j]; } } assert(fa[u][0]==fa[v][0]); return fa[u][0]; } inline int dist(int u,int v){ int ans=INF; if(dep[u]<dep[v]){ swap(u,v); } for(int j=ldep[u];j>=0;j--){ if(dep[fa[u][j]]>=dep[v]){ apmin(ans,len[u][j]); u=fa[u][j]; } } if(u==v){ return ans; } for(int j=min(ldep[u],ldep[v]);j>=0;j--){ if(fa[u][j]!=fa[v][j]){ apmin(ans,min(len[u][j],len[v][j])); u=fa[u][j],v=fa[v][j]; } } assert(fa[u][0]==fa[v][0]); return ans; } int seq[N],stk[N]; inline lint work(int n){ V.tim++; V.etop=0; for(int i=0;i<n;i++){ V.vis[seq[i]=ni]=V.tim; } sort(seq,seq+n,dfncmp); int stop=0; stk[++stop]=1; for(int i=0;i<n;i++){ int x=seq[i],f=x; for(int v=stk[stop];v!=f&&dep[f=lca(x,v)]<dep[v];v=stk[stop]){ if(dep[f]>dep[stk[--stop]]){ stk[++stop]=f; } V.add_edge(stk[stop],v); } assert(stk[stop]==f); assert(stk[stop]!=x); stk[++stop]=x; } for(;stop>1;stop--){ V.add_edge(stk[stop-1],stk[stop]); } V.dfs(1); return V.f[1]; } }T; inline void Virtual::add_edge(int u,int v){ if(tag[u]<tim){ tag[u]=tim; head[u]=-1; } to[etop]=v; bro[etop]=head[u]; val[etop]=T.dist(u,v); head[u]=etop++; } int main(){ T.reset(); int n=ni; for(int i=1;i<n;i++){ int u=ni,v=ni,w=ni; T.add_edge(u,v,w); T.add_edge(v,u,w); } T.dfs(1,0); for(int tot=ni;tot--;){ printf("%lld\n",T.work(ni)); } }
3,370
2,001
/// /// \class l1t::Stage1Layer2FlowAlgorithm /// /// \authors: Maxime Guilbaud /// R. Alex Barbieri /// /// Description: Flow Algorithm HI #include "FWCore/MessageLogger/interface/MessageLogger.h" #include "L1Trigger/L1TCalorimeter/interface/Stage1Layer2HFRingSumAlgorithmImp.h" #include "L1Trigger/L1TCalorimeter/interface/PUSubtractionMethods.h" #include "L1Trigger/L1TCalorimeter/interface/legacyGtHelper.h" l1t::Stage1Layer2FlowAlgorithm::Stage1Layer2FlowAlgorithm(CaloParamsHelper const* params){ //now do what ever initialization is needed //Converting phi to be as it is define at GCT (-pi to pi instead of 0 to 2*pi) for(unsigned int i = 0; i < L1CaloRegionDetId::N_PHI; i++) { if(i < 10){ sinPhi.push_back(sin(2. * 3.1415927 * i * 1.0 / L1CaloRegionDetId::N_PHI)); cosPhi.push_back(cos(2. * 3.1415927 * i * 1.0 / L1CaloRegionDetId::N_PHI)); } else { sinPhi.push_back(sin(-3.1415927 + 2. * 3.1415927 * (i-9) * 1.0 / L1CaloRegionDetId::N_PHI)); cosPhi.push_back(cos(-3.1415927 + 2. * 3.1415927 * (i-9) * 1.0 / L1CaloRegionDetId::N_PHI)); } } } void l1t::Stage1Layer2FlowAlgorithm::processEvent(const std::vector<l1t::CaloRegion> & regions, const std::vector<l1t::CaloEmCand> & EMCands, const std::vector<l1t::Tau> * taus, l1t::CaloSpare * spare) { double q2x = 0; double q2y = 0; double regionET=0.; for(std::vector<CaloRegion>::const_iterator region = regions.begin(); region != regions.end(); region++) { int ieta=region->hwEta(); if (ieta > 3 && ieta < 18) { continue; } int iphi=region->hwPhi(); regionET=region->hwPt(); q2x+= regionET * cosPhi[iphi]; q2y+= regionET * sinPhi[iphi]; } int HFq2 = q2x*q2x+q2y*q2y; //double psi2 = 0.5 * atan(q2y/q2x); // ROOT::Math::LorentzVector<ROOT::Math::PxPyPzE4D<double> > dummy(0,0,0,0); // l1t::CaloSpare V2 (*&dummy,CaloSpare::CaloSpareType::V2,(int)HFq2,0,0,0); // spares->push_back(V2); spare->SetRing(1, HFq2&0x7); }
2,018
913
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License (MIT). See License.txt in the repo root for license information. // ------------------------------------------------------------ #include "stdafx.h" namespace Common { ExtendedEventMetadata::ExtendedEventMetadata(std::string const& publicEventName, std::string const& category) : publicEventName_(publicEventName) , category_(category) { } std::unique_ptr<ExtendedEventMetadata> ExtendedEventMetadata::Create(std::string const& publicEventName, std::string const& category) { return std::make_unique<ExtendedEventMetadata>(publicEventName, category); } std::string ExtendedEventMetadata::AddMetadataFields(TraceEvent & traceEvent, size_t & fieldsCount) { size_t index = 0; traceEvent.AddEventField<std::string>("eventName", index); traceEvent.AddEventField<std::string>("category", index); // Number of appended fields. fieldsCount = index; return std::string(GetMetadataFieldsFormat().begin()); } void ExtendedEventMetadata::AppendFields(TraceEventContext & context) const { context.Write(GetPublicEventNameField()); context.Write(GetCategoryField()); } void ExtendedEventMetadata::AppendFields(StringWriter & writer) const { writer.Write(GetMetadataFieldsFormat(), GetPublicEventNameField(), GetCategoryField()); } StringLiteral const& ExtendedEventMetadata::GetMetadataFieldsFormat() { static StringLiteral const format("EventName: {0} Category: {1} "); return format; } }
1,727
443
/* * Copyright (C) 2010 Google, Inc. All Rights Reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "third_party/blink/renderer/core/script/script_runner.h" #include <algorithm> #include "base/feature_list.h" #include "third_party/blink/public/common/features.h" #include "third_party/blink/public/platform/platform.h" #include "third_party/blink/public/platform/task_type.h" #include "third_party/blink/renderer/core/dom/document.h" #include "third_party/blink/renderer/core/frame/local_dom_window.h" #include "third_party/blink/renderer/core/script/script_loader.h" #include "third_party/blink/renderer/platform/heap/handle.h" #include "third_party/blink/renderer/platform/runtime_enabled_features.h" #include "third_party/blink/renderer/platform/scheduler/public/cooperative_scheduling_manager.h" #include "third_party/blink/renderer/platform/scheduler/public/thread.h" #include "third_party/blink/renderer/platform/scheduler/public/thread_scheduler.h" #include "third_party/blink/renderer/platform/wtf/casting.h" namespace blink { ScriptRunner::ScriptRunner(Document* document) : ExecutionContextLifecycleStateObserver(document->GetExecutionContext()), document_(document), task_runner_(document->GetTaskRunner(TaskType::kNetworking)) { DCHECK(document); UpdateStateIfNeeded(); } void ScriptRunner::QueueScriptForExecution(PendingScript* pending_script) { DCHECK(pending_script); document_->IncrementLoadEventDelayCount(); switch (pending_script->GetSchedulingType()) { case ScriptSchedulingType::kAsync: pending_async_scripts_.insert(pending_script); break; case ScriptSchedulingType::kInOrder: pending_in_order_scripts_.push_back(pending_script); number_of_in_order_scripts_with_pending_notification_++; break; default: NOTREACHED(); break; } } void ScriptRunner::PostTask(const base::Location& web_trace_location) { task_runner_->PostTask( web_trace_location, WTF::Bind(&ScriptRunner::ExecuteTask, WrapWeakPersistent(this))); } void ScriptRunner::ContextLifecycleStateChanged( mojom::FrameLifecycleState state) { if (!IsExecutionSuspended()) PostTasksForReadyScripts(FROM_HERE); } bool ScriptRunner::IsExecutionSuspended() { return !GetExecutionContext() || GetExecutionContext()->IsContextPaused() || is_force_deferred_; } void ScriptRunner::SetForceDeferredExecution(bool force_deferred) { DCHECK(force_deferred != is_force_deferred_); is_force_deferred_ = force_deferred; if (!IsExecutionSuspended()) PostTasksForReadyScripts(FROM_HERE); } void ScriptRunner::PostTasksForReadyScripts( const base::Location& web_trace_location) { DCHECK(!IsExecutionSuspended()); for (size_t i = 0; i < async_scripts_to_execute_soon_.size(); ++i) { PostTask(web_trace_location); } for (size_t i = 0; i < in_order_scripts_to_execute_soon_.size(); ++i) { PostTask(web_trace_location); } } void ScriptRunner::ScheduleReadyInOrderScripts() { while (!pending_in_order_scripts_.IsEmpty() && pending_in_order_scripts_.front() ->IsReady()) { in_order_scripts_to_execute_soon_.push_back( pending_in_order_scripts_.TakeFirst()); PostTask(FROM_HERE); } } void ScriptRunner::DelayAsyncScriptUntilMilestoneReached( PendingScript* pending_script) { DCHECK(!delay_async_script_milestone_reached_); SECURITY_CHECK(pending_async_scripts_.Contains(pending_script)); pending_async_scripts_.erase(pending_script); // When the ScriptRunner is notified via // |NotifyDelayedAsyncScriptsMilestoneReached()|, the scripts in // |pending_delayed_async_scripts_| will be scheduled for execution. pending_delayed_async_scripts_.push_back(pending_script); } void ScriptRunner::NotifyDelayedAsyncScriptsMilestoneReached() { delay_async_script_milestone_reached_ = true; while (!pending_delayed_async_scripts_.IsEmpty()) { PendingScript* pending_script = pending_delayed_async_scripts_.TakeFirst(); DCHECK_EQ(pending_script->GetSchedulingType(), ScriptSchedulingType::kAsync); async_scripts_to_execute_soon_.push_back(pending_script); PostTask(FROM_HERE); } } bool ScriptRunner::CanDelayAsyncScripts() { static bool flags_enabled = base::FeatureList::IsEnabled(features::kDelayAsyncScriptExecution) || RuntimeEnabledFeatures:: DelayAsyncScriptExecutionUntilFinishedParsingEnabled() || RuntimeEnabledFeatures:: DelayAsyncScriptExecutionUntilFirstPaintOrFinishedParsingEnabled(); return !delay_async_script_milestone_reached_ && flags_enabled; } void ScriptRunner::NotifyScriptReady(PendingScript* pending_script) { SECURITY_CHECK(pending_script); switch (pending_script->GetSchedulingType()) { case ScriptSchedulingType::kAsync: // SECURITY_CHECK() makes us crash in a controlled way in error cases // where the PendingScript is associated with the wrong ScriptRunner // (otherwise we'd cause a use-after-free in ~ScriptRunner when it tries // to detach). SECURITY_CHECK(pending_async_scripts_.Contains(pending_script)); if (pending_script->IsEligibleForDelay() && CanDelayAsyncScripts()) { DelayAsyncScriptUntilMilestoneReached(pending_script); return; } pending_async_scripts_.erase(pending_script); async_scripts_to_execute_soon_.push_back(pending_script); PostTask(FROM_HERE); break; case ScriptSchedulingType::kInOrder: SECURITY_CHECK(number_of_in_order_scripts_with_pending_notification_ > 0); number_of_in_order_scripts_with_pending_notification_--; ScheduleReadyInOrderScripts(); break; default: NOTREACHED(); break; } } bool ScriptRunner::RemovePendingInOrderScript(PendingScript* pending_script) { auto it = std::find(pending_in_order_scripts_.begin(), pending_in_order_scripts_.end(), pending_script); if (it == pending_in_order_scripts_.end()) return false; pending_in_order_scripts_.erase(it); SECURITY_CHECK(number_of_in_order_scripts_with_pending_notification_ > 0); number_of_in_order_scripts_with_pending_notification_--; return true; } void ScriptRunner::MovePendingScript(Document& old_document, Document& new_document, ScriptLoader* script_loader) { Document* new_context_document = new_document.GetExecutionContext() ? To<LocalDOMWindow>(new_document.GetExecutionContext())->document() : &new_document; Document* old_context_document = old_document.GetExecutionContext() ? To<LocalDOMWindow>(old_document.GetExecutionContext())->document() : &old_document; if (old_context_document == new_context_document) return; PendingScript* pending_script = script_loader ->GetPendingScriptIfControlledByScriptRunnerForCrossDocMove(); if (!pending_script) { // The ScriptLoader is not controlled by ScriptRunner. This can happen // because MovePendingScript() is called for all <script> elements // moved between Documents, not only for those controlled by ScriptRunner. return; } old_context_document->GetScriptRunner()->MovePendingScript( new_context_document->GetScriptRunner(), pending_script); } void ScriptRunner::MovePendingScript(ScriptRunner* new_runner, PendingScript* pending_script) { auto it = pending_async_scripts_.find(pending_script); if (it != pending_async_scripts_.end()) { new_runner->QueueScriptForExecution(pending_script); pending_async_scripts_.erase(it); document_->DecrementLoadEventDelayCount(); return; } if (RemovePendingInOrderScript(pending_script)) { new_runner->QueueScriptForExecution(pending_script); document_->DecrementLoadEventDelayCount(); } } bool ScriptRunner::ExecuteInOrderTask() { TRACE_EVENT0("blink", "ScriptRunner::ExecuteInOrderTask"); if (in_order_scripts_to_execute_soon_.IsEmpty()) return false; PendingScript* pending_script = in_order_scripts_to_execute_soon_.TakeFirst(); DCHECK(pending_script); DCHECK_EQ(pending_script->GetSchedulingType(), ScriptSchedulingType::kInOrder) << "In-order scripts queue should not contain any async script."; pending_script->ExecuteScriptBlock(NullURL()); document_->DecrementLoadEventDelayCount(); return true; } bool ScriptRunner::ExecuteAsyncTask() { TRACE_EVENT0("blink", "ScriptRunner::ExecuteAsyncTask"); if (async_scripts_to_execute_soon_.IsEmpty()) return false; // Remove the async script loader from the ready-to-exec set and execute. PendingScript* pending_script = async_scripts_to_execute_soon_.TakeFirst(); DCHECK_EQ(pending_script->GetSchedulingType(), ScriptSchedulingType::kAsync) << "Async scripts queue should not contain any in-order script."; pending_script->ExecuteScriptBlock(NullURL()); document_->DecrementLoadEventDelayCount(); return true; } void ScriptRunner::ExecuteTask() { // This method is triggered by ScriptRunner::PostTask, and runs directly from // the scheduler. So, the call stack is safe to reenter. scheduler::CooperativeSchedulingManager::AllowedStackScope allowed_stack_scope(scheduler::CooperativeSchedulingManager::Instance()); if (IsExecutionSuspended()) return; if (ExecuteAsyncTask()) return; if (ExecuteInOrderTask()) return; } void ScriptRunner::Trace(Visitor* visitor) const { ExecutionContextLifecycleStateObserver::Trace(visitor); visitor->Trace(document_); visitor->Trace(pending_in_order_scripts_); visitor->Trace(pending_async_scripts_); visitor->Trace(pending_delayed_async_scripts_); visitor->Trace(async_scripts_to_execute_soon_); visitor->Trace(in_order_scripts_to_execute_soon_); } } // namespace blink
11,122
3,530
#include "Core.h" namespace AsquiEngine { template <> String GetString<float2>(const float2& vec) { return fmt::format("{{x = {}, y = {}}}", vec.x, vec.y); } template <> String GetString<float3>(const float3& vec) { return fmt::format("{{x = {}, y = {}, z = {}}}", vec.x, vec.y, vec.z); } template <> String GetString<float4>(const float4& vec) { return fmt::format("{{x = {}, y = {}, z = {}, w = {}}}", vec.x, vec.y, vec.z, vec.w); } template <> String GetString<Quaternion>(const Quaternion& quat) { return fmt::format("{{x = {}, y = {}, z = {}, w = {}}}", quat.x, quat.y, quat.z, quat.w); } }
617
245
namespace Logic { bool init_entity() { // This limits the memory to one arena, just to keep // tabs on the memory, if you trust this code switch it // to true to have UNLIMITED entities. _fog_es.memory = Util::request_arena(false); _fog_es.next_free = 0; _fog_es.entities = Util::create_list<Entity *>(100), _fog_es.max_entity = -1; _fog_es.num_entities = 0; _fog_es.num_removed = 0; _fog_es.defrag_limit = 100; _fog_global_type_table.arena = Util::request_arena(); return true; } const char *Entity::show() { char *buffer = Util::request_temporary_memory<char>(512); char *ptr = buffer; EMeta meta_info = _fog_global_entity_list[(u32) type()]; auto write = [&ptr](const char *c) { while (*c) *(ptr++) = *(c++); }; auto seek = [&ptr]() { // Seeks until a nullterminated character. while (*ptr) ptr++; }; write(type_name()); write("\n"); u8 *raw_address = (u8 *) this; for (u32 i = 0; i < meta_info.num_fields; i++) { write(" "); // Indentation, might remove later. const ETypeInfo *info = fetch_type(meta_info.fields[i].hash); if (info) write(info->name); else write("????"); write(" "); write(meta_info.fields[i].name); if (info && info->show) { write(" = "); info->show(ptr, raw_address + meta_info.fields[i].offset); seek(); } write("\n"); } *ptr = '\0'; return buffer; } EMeta meta_data_for(EntityType type) { ASSERT((u32) type < (u32) EntityType::NUM_ENTITY_TYPES, "Invalid type"); EMeta meta = _fog_global_entity_list[(u32) type]; ASSERT(meta.registered, "Entity is not registerd."); return _fog_global_entity_list[(u32) type]; } void *_entity_vtable(EntityType type) { meta_data_for(type); return _fog_global_entity_vtable[(u32) type](); } template <typename T> bool contains_type() { return fetch_type(typeid(T).hash_code()); } bool contains_type(u64 hash) { return fetch_type(hash); } void register_type(ETypeInfo info) { ETypeInfo **current = _fog_global_type_table.data + (info.hash % TypeTable::NUM_SLOTS); while (*current) { if ((*current)->hash == info.hash) ERR("Type hash collision (last added ->) '%s' '%s', " "adding the same type twice?", info.name, (*current)->name); current = &(*current)->next; } info.next = nullptr; *current = _fog_global_type_table.arena->push(info); } template <typename T> const ETypeInfo *fetch_type() { return fetch_type(typeid(T).hash_code()); } const ETypeInfo *fetch_entity_type(EntityType type) { return fetch_type(meta_data_for(type).hash); } const ETypeInfo *fetch_type(u64 hash) { ETypeInfo *current = _fog_global_type_table.data[hash % TypeTable::NUM_SLOTS]; while (current) { if (current->hash == hash) return current; current = current->next; } ERR("Invalid entity query %llu", hash); return current; } // ES EntityID generate_entity_id() { EntityID id; _fog_es.num_entities++; if (_fog_es.next_free < 0) { // Reusing id.slot = -_fog_es.next_free - 1; _fog_es.next_free = _fog_es.entities[id.slot]->id.slot; } else { id.slot = _fog_es.next_free++; id.gen = 0; } if ((s32) _fog_es.entities.capacity <= id.slot) { _fog_es.entities.resize(id.slot * 2); } id.gen++; _fog_es.max_entity = MAX(id.slot, _fog_es.max_entity); return id; } template<typename T> EntityID add_entity(T entity) { static_assert(std::is_base_of<Entity, T>(), "You supplied a class that isn't based on Logic::Entity"); EntityID id = generate_entity_id(); entity.id = id; Util::allow_allocation(); _fog_es.entities[id.slot] = _fog_es.memory->push(entity); ASSERT((u64) _fog_es.entities[id.slot] > 1000, "Invalid pointer in entity system."); Util::strict_allocation_check(); return id; } EntityID add_entity_ptr(Entity *entity) { EntityID id = generate_entity_id(); entity->id = id; u32 size = Logic::fetch_entity_type(entity->type())->size; Util::allow_allocation(); Entity *copy = (Entity *) _fog_es.memory->push<u8>(size); Util::strict_allocation_check(); Util::copy_bytes(entity, copy, size); _fog_es.entities[id.slot] = entity; ASSERT((u64) _fog_es.entities[id.slot] > 1000, "Invalid pointer in entity system."); return id; } void clear_entitysystem() { _fog_es.memory->clear(); _fog_es.next_free = 0; _fog_es.entities.clear(); _fog_es.max_entity = 0; _fog_es.num_entities = 0; _fog_es.num_removed = 0; } Entity *fetch_entity(EntityID id) { if (id.slot >= 0) { Entity *entity = _fog_es.entities[id.slot]; if (entity && id == entity->id) return entity; } return nullptr; } template <typename T> T *fetch_entity(EntityID id) { Entity *entity = fetch_entity(id); ASSERT(entity, "Cannot find entity"); //ASSERT(entity->type() == T::st_type(), "Types don't match!"); return (T *) entity; } bool valid_entity(EntityID id) { return fetch_entity(id) != nullptr; } bool remove_entity(EntityID id) { Entity *entity = fetch_entity(id); if (!entity) return false; _fog_es.num_entities--; _fog_es.num_removed++; s32 slot = entity->id.slot; entity->id.slot = _fog_es.next_free; _fog_es.next_free = -slot - 1; if (slot == _fog_es.max_entity) { while (_fog_es.entities[_fog_es.max_entity]->id.slot < 0 && 0 <= _fog_es.max_entity) _fog_es.max_entity--; } return true; } void for_entity_of_type(EntityType type, MapFunc f) { for (s32 i = _fog_es.max_entity; 0 <= i; i--) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (e->type() != type) continue; if (f(e)) break; } } void for_entity(MapFunc f) { for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (f(e)) break; } } EntityID fetch_first_of_type(EntityType type) { for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; if (e->type() == type) return e->id; } return {-1, 0}; } void update_es() { START_PERF(ENTITY_UPDATE); const f32 delta = Logic::delta(); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; e->update(delta); } STOP_PERF(ENTITY_UPDATE); } void draw_es() { START_PERF(ENTITY_DRAW); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; if (!e) continue; if (e->id.slot != i) continue; e->draw(); } STOP_PERF(ENTITY_DRAW); } // TODO(ed): Make this doable across multiple frames, so we // can spend 1ms on it everyframe or something like that... void defragment_entity_memory() { START_PERF(ENTITY_DEFRAG); if (_fog_es.num_removed < _fog_es.defrag_limit) { STOP_PERF(ENTITY_DEFRAG); return; } // This is kinda hacky... Util::allow_allocation(); Util::MemoryArena *target_arena = Util::request_arena(false); u64 memory = 0; ASSERT(offsetof(Entity, id) < 16, "Empty entity is quite large"); for (s32 i = 0; i <= _fog_es.max_entity; i++) { Entity *e = _fog_es.entities[i]; u32 size; if (e->id.slot != i) { size = offsetof(Entity, id) + sizeof(EntityID); } else { size = fetch_type(meta_data_for(e->type()).hash)->size; } memory += size; Util::allow_allocation(); u8 *target = target_arena->push<u8>(size); Util::copy_bytes(e, target, size); _fog_es.entities[i] = (Entity *) target; ASSERT((u64) _fog_es.entities[i] > 1000, "Invalid pointer in entity system."); } ASSERT(memory < Util::ARENA_SIZE_IN_BYTES, "Too large allocations"); _fog_es.memory->pop(); _fog_es.memory = target_arena; _fog_es.num_removed = 0; // We've not removed any now STOP_PERF(ENTITY_DEFRAG); } };
9,483
3,216
/**************************************************************************** ** ** Copyright (C) 2006-2009 fullmetalcoder <fullmetalcoder@hotmail.fr> ** ** This file is part of the Edyuk project <http://edyuk.org> ** ** This file may be used under the terms of the GNU General Public License ** version 3 as published by the Free Software Foundation and appearing in the ** file GPL.txt included in the packaging of this file. ** ** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE ** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. ** ****************************************************************************/ #include "qlinechangepanel.h" /*! \file qlinechangepanel.cpp \brief Implementation of the QLineChangePanel class. */ #include "qeditor.h" #include "qdocument.h" #include "qdocumentline.h" #include <QIcon> #include <QMenu> #include <QPainter> #include <QScrollBar> #include <QContextMenuEvent> /*! \ingroup widgets @{ */ /*! \class QLineMarkPanel \brief A specific panel in charge of drawing line numbers of an editor \see QEditorInterface */ QCE_AUTO_REGISTER(QLineChangePanel) /*! \brief Constructor */ QLineChangePanel::QLineChangePanel(QWidget *p) : QPanel(p) { setFixedWidth(4); } /*! \brief Empty destructor */ QLineChangePanel::~QLineChangePanel() { } /*! */ QString QLineChangePanel::type() const { return "Line changes"; } /*! \internal */ void QLineChangePanel::paint(QPainter *p, QEditor *e) { if ( !e || !e->document() ) return; const QFontMetrics fm( e->document()->font() ); int n, posY, maxCount = 0, as = fm.ascent(), ls = fm.lineSpacing(), pageBottom = e->viewport()->height(), contentsY = e->verticalOffset(); QString txt; QDocument *d = e->document(); n = d->lineNumber(contentsY); posY = 2 + d->y(n) - contentsY; for ( ; ; ++n ) { //qDebug("n = %i; pos = %i", n, posY); QDocumentLine line = d->line(n); if ( line.isNull() || ((posY - as) > pageBottom) ) break; if ( line.isHidden() ) continue; int span = line.lineSpan(); if ( d->isLineModified(line) ) { p->fillRect(1, posY, 2, ls * span, Qt::red); } else if ( d->hasLineEverBeenModified(line) ) { p->fillRect(1, posY, 2, ls * span, Qt::green); } posY += ls * span; } } /*! @} */
2,906
891
//Lab 1 //modified from http://learnopengl.com/ #include "common/stdafx.h" using namespace std; GLFWwindow* window; glm::vec3 c_pos = glm::vec3(0, 0, 2); glm::vec3 c_dir = glm::normalize(glm::vec3(0, 0, -2)); glm::vec3 c_up = glm::vec3(0, 1, 0); glm::mat4 vm; int initWindow(); void update_view(); void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods); int main() { if (initWindow() != 0) { return -1; } glClearColor(.7, .7, .7, 0); GLuint shdr = loadShaders("vertex.shader", "fragment.shader"); glUseProgram(shdr); std::vector<glm::vec3> v = { glm::vec3(0, 0, 0), glm::vec3(0, 1, 0), glm::vec3(1, 0, 0) }; GLuint VAO; glGenVertexArrays(1, &VAO); glBindVertexArray(VAO); GLuint VBO; glGenBuffers(1, &VBO); glBindBuffer(GL_ARRAY_BUFFER, VBO); glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3)*v.size(), &v[0], GL_STATIC_DRAW); glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0); glEnableVertexAttribArray(0); //------ MODEL MATRIX --------- glm::mat4 mm; glm::mat4 scale; glm::mat4 translate; glm::mat4 rotate; //------ VIEW MATRIX --------- vm = glm::lookAt(c_pos, c_pos + c_dir, c_up); //------ PROJECTION MATRIX ------- glm::mat4 pm = glm::perspective(45.f, 800.f / 600.f, 0.1f, 100.f); GLuint mm_addr = glGetUniformLocation(shdr, "m_m"); GLuint pm_addr = glGetUniformLocation(shdr, "p_m"); GLuint vm_addr = glGetUniformLocation(shdr, "v_m"); glUniformMatrix4fv(mm_addr, 1, false, glm::value_ptr(mm)); glUniformMatrix4fv(pm_addr, 1, false, glm::value_ptr(pm)); while (!glfwWindowShouldClose(window)) { glClear(GL_COLOR_BUFFER_BIT); glUniformMatrix4fv(vm_addr, 1, false, glm::value_ptr(vm)); glm::mat4 anchor = glm::translate(glm::mat4(1.0f), -glm::vec3(0, 0.5, 0)); glm::mat4 _anchor = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0.5, 0)); scale = glm::scale(glm::mat4(1.0f), glm::vec3(.5, .5, .5)); translate = glm::translate(glm::mat4(1.0f), glm::vec3(0, 0, 0)); rotate = glm::rotate(glm::mat4(1.0f), glm::radians(0.f), glm::vec3(0, 0, 1)); glm::mat4 mem = translate * _anchor * rotate * anchor; mm = mem * scale; glUniformMatrix4fv(mm_addr, 1, false, glm::value_ptr(mm)); glDrawArrays(GL_TRIANGLES, 0, v.size()); translate = glm::translate(glm::mat4(1.0f), glm::vec3(0.5, -0.5, 0)); rotate = glm::rotate(glm::mat4(1.0f), glm::radians(45.f), glm::vec3(0, 0, 1)); mm = mem * translate * _anchor * rotate * anchor * scale; glUniformMatrix4fv(mm_addr, 1, false, glm::value_ptr(mm)); glDrawArrays(GL_TRIANGLES, 0, v.size()); glfwPollEvents(); glfwSwapBuffers(window); } return 0; } void update_view() { vm = glm::lookAt(c_pos, c_pos + c_dir, c_up); } void keyCallback(GLFWwindow* window, int key, int scancode, int action, int mods) { if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS) { glfwSetWindowShouldClose(window, true); } if (key == GLFW_KEY_DOWN) { c_pos.z += 1; update_view(); } if (key == GLFW_KEY_UP) { c_pos.z -= 1; update_view(); } } int initWindow() { glfwInit(); window = glfwCreateWindow(800, 600, "First windwo", nullptr, nullptr); glfwSetKeyCallback(window, keyCallback); if (window == nullptr) { glfwTerminate(); return -1; } glfwMakeContextCurrent(window); if (glewInit() != 0) { return -1; } return 0; }
3,311
1,609
#include <uv.h> #include <algorithm> #include <cstring> #include <iostream> #include <queue> #include <string> #include <string_view> #include <vector> // https://developer.chrome.com/docs/apps/nativeMessaging/#native-messaging-host-protocol // https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Native_messaging#app_side struct State { std::string origin; uv_stream_t *tty_in = nullptr; uv_stream_t *tty_out = nullptr; uv_stream_t *keeweb_pipe = nullptr; std::queue<uv_buf_t> pending_to_keeweb{}; std::queue<uv_buf_t> pending_to_stdout{}; bool write_to_keeweb_in_progress = false; bool write_to_stdout_in_progress = false; bool keeweb_launched = false; uint32_t keeweb_connect_attempts = 0; }; State state{}; void process_keeweb_queue(); void process_stdout_queue(); void close_keeweb_pipe(); void connect_keeweb_pipe(); void alloc_buf(uv_handle_t *, size_t size, uv_buf_t *buf) { buf->base = new char[size]; buf->len = static_cast<decltype(uv_buf_t::len)>(size); } void quit_on_error() { if (state.keeweb_pipe) { close_keeweb_pipe(); } else { uv_read_stop(state.tty_in); uv_loop_close(uv_default_loop()); } } void stdin_read_cb(uv_stream_t *, ssize_t nread, const uv_buf_t *buf) { if (nread > 0) { state.pending_to_keeweb.emplace( uv_buf_init(buf->base, static_cast<decltype(uv_buf_t::len)>(nread))); process_keeweb_queue(); } else if (nread == UV_EOF) { quit_on_error(); } else if (nread < 0) { std::cerr << "STDIN read error: " << uv_err_name(static_cast<int>(nread)) << std::endl; quit_on_error(); } } void stdout_write_cb(uv_write_t *req, int status) { delete req; auto buf = state.pending_to_stdout.front(); state.pending_to_stdout.pop(); delete[] buf.base; state.write_to_stdout_in_progress = false; auto success = status >= 0; if (success) { process_stdout_queue(); } else { std::cerr << "STDOUT write error: " << uv_err_name(status) << std::endl; quit_on_error(); } } void process_stdout_queue() { if (state.write_to_stdout_in_progress || state.pending_to_stdout.empty()) { return; } auto buf = state.pending_to_stdout.front(); auto write_req = new uv_write_t{}; uv_write(write_req, state.tty_out, &buf, 1, stdout_write_cb); state.write_to_stdout_in_progress = true; } void keeweb_pipe_close_cb(uv_handle_t *pipe) { delete pipe; uv_read_stop(state.tty_in); uv_loop_close(uv_default_loop()); } void close_keeweb_pipe() { if (!state.keeweb_pipe) { return; } auto pipe = state.keeweb_pipe; state.keeweb_pipe = nullptr; uv_read_stop(pipe); uv_close(reinterpret_cast<uv_handle_t *>(pipe), keeweb_pipe_close_cb); } void keeweb_write_cb(uv_write_t *req, int status) { delete req; auto buf = state.pending_to_keeweb.front(); state.pending_to_keeweb.pop(); delete[] buf.base; state.write_to_keeweb_in_progress = false; auto success = status >= 0; if (success) { process_keeweb_queue(); } else { std::cerr << "Error writing to KeeWeb: " << uv_err_name(status) << std::endl; close_keeweb_pipe(); } } void process_keeweb_queue() { if (!state.keeweb_pipe || state.write_to_keeweb_in_progress || state.pending_to_keeweb.empty()) { return; } auto buf = state.pending_to_keeweb.front(); auto write_req = new uv_write_t{}; uv_write(write_req, state.keeweb_pipe, &buf, 1, keeweb_write_cb); state.write_to_keeweb_in_progress = true; } void keeweb_pipe_read_cb(uv_stream_t *, ssize_t nread, const uv_buf_t *buf) { if (nread > 0) { state.pending_to_stdout.emplace( uv_buf_init(buf->base, static_cast<decltype(uv_buf_t::len)>(nread))); process_stdout_queue(); } else if (nread == UV_EOF) { close_keeweb_pipe(); } else if (nread < 0) { std::cerr << "KeeWeb read error: " << uv_err_name(static_cast<int>(nread)) << std::endl; close_keeweb_pipe(); } } void keeweb_pipe_connect_cb(uv_connect_t *req, int status) { auto pipe = req->handle; delete req; auto connected = status >= 0; if (connected) { state.keeweb_pipe = pipe; uv_read_start(pipe, alloc_buf, keeweb_pipe_read_cb); process_keeweb_queue(); } else { std::cerr << "Cannot connect to KeeWeb: " << uv_err_name(status) << std::endl; quit_on_error(); } } std::string keeweb_pipe_name() { std::string pipe_name; uv_passwd_t user_info; auto err = uv_os_get_passwd(&user_info); if (err) { std::cerr << "Error getting user info: " << uv_err_name(err) << std::endl; } else { #if defined(WIN32) || defined(_WIN32) || defined(__WIN32) pipe_name = "\\\\.\\pipe\\keeweb-connect-" + std::string{user_info.username}; #elif __APPLE__ pipe_name = "/Users/" + std::string{user_info.username} + "/Library/Group Containers/3LE7JZ657W.keeweb/conn.sock"; #else size_t buf_size = MAXPATHLEN + 1; char tmpdir[MAXPATHLEN + 1]; err = uv_os_tmpdir(tmpdir, &buf_size); if (err < 0) { std::cerr << "Cannot get tmp dir" << uv_err_name(err) << std::endl; } else { pipe_name = tmpdir + ("/keeweb-connect-" + std::to_string(user_info.uid) + ".sock"); } #endif uv_os_free_passwd(&user_info); } return pipe_name; } void connect_keeweb_pipe() { state.keeweb_connect_attempts++; auto pipe_name = keeweb_pipe_name(); if (pipe_name.empty()) { quit_on_error(); return; } auto keeweb_pipe = new uv_pipe_t{}; uv_pipe_init(uv_default_loop(), keeweb_pipe, false); auto connect_req = new uv_connect_t(); uv_pipe_connect(connect_req, keeweb_pipe, pipe_name.c_str(), keeweb_pipe_connect_cb); } void start_reading_stdin() { uv_read_start(state.tty_in, alloc_buf, stdin_read_cb); } void push_first_message_to_keeweb() { auto origin = state.origin; std::replace(origin.begin(), origin.end(), '"', '\''); auto message = "{\"pid\":" + std::to_string(uv_os_getpid()) + ",\"ppid\":" + std::to_string(uv_os_getppid()) + ",\"origin\":\"" + origin + "\"}"; auto message_length = message.length() + sizeof(uint32_t); auto data = new char[message_length]; auto size_ptr = reinterpret_cast<uint32_t *>(data); *size_ptr = static_cast<uint32_t>(message.length()); memcpy(data + sizeof(uint32_t), message.c_str(), message.length()); state.pending_to_keeweb.emplace( uv_buf_init(data, static_cast<decltype(uv_buf_t::len)>(message_length))); } uv_stream_t *open_tty_or_pipe(uv_file fd) { if (uv_guess_handle(fd) == UV_NAMED_PIPE) { auto pipe = new uv_pipe_t{}; uv_pipe_init(uv_default_loop(), pipe, 0); uv_pipe_open(pipe, fd); return reinterpret_cast<uv_stream_t *>(pipe); } else { auto tty = new uv_tty_t{}; uv_tty_init(uv_default_loop(), tty, fd, 0); return reinterpret_cast<uv_stream_t *>(tty); } } void init_tty() { state.tty_in = open_tty_or_pipe(0); state.tty_out = open_tty_or_pipe(1); } std::string get_origin_by_args(int argc, char *argv[]) { for (int i = 1; i < argc; i++) { std::string arg{argv[i]}; if (arg.rfind("chrome-extension://", 0) == 0) { return arg; } if (arg.find("@kee") != arg.npos && arg.find(".json") == arg.npos) { return arg; } } return {}; } int main(int argc, char *argv[]) { state.origin = get_origin_by_args(argc, argv); if (state.origin.empty()) { std::cerr << "Expected origin" << std::endl; return 1; } push_first_message_to_keeweb(); init_tty(); start_reading_stdin(); connect_keeweb_pipe(); uv_run(uv_default_loop(), UV_RUN_DEFAULT); }
8,020
3,061
#include "NUIE_NodeEditor.hpp" #include "NUIE_NodeTree.hpp" #include "WAS_GdiOffscreenContext.hpp" #include "WAS_WindowsAppUtils.hpp" #include "WAS_HwndEventHandler.hpp" #include "WAS_ParameterDialog.hpp" #include "WAS_NodeTree.hpp" #include "BI_BuiltInNodes.hpp" #include <windows.h> #include <windowsx.h> static void InitNodeTree (NUIE::NodeTree& nodeTree) { size_t inputNodes = nodeTree.AddGroup (L"Input Nodes"); nodeTree.AddItem (inputNodes, L"Boolean", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::BooleanNode (NE::LocString (L"Boolean"), position, true)); }); nodeTree.AddItem (inputNodes, L"Integer", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::IntegerUpDownNode (NE::LocString (L"Integer"), position, 0, 1)); }); nodeTree.AddItem (inputNodes, L"Number", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DoubleUpDownNode (NE::LocString (L"Number"), position, 0.0, 1.0)); }); nodeTree.AddItem (inputNodes, L"Integer Increment", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::IntegerIncrementedNode (NE::LocString (L"Integer Increment"), position)); }); nodeTree.AddItem (inputNodes, L"Number Increment", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DoubleIncrementedNode (NE::LocString (L"Number Increment"), position)); }); nodeTree.AddItem (inputNodes, L"Number Distribution", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DoubleDistributedNode (NE::LocString (L"Number Distribution"), position)); }); nodeTree.AddItem (inputNodes, L"List Builder", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::ListBuilderNode (NE::LocString (L"List Builder"), position)); }); size_t arithmeticNodes = nodeTree.AddGroup (L"Arithmetic Nodes"); nodeTree.AddItem (arithmeticNodes, L"Addition", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::AdditionNode (NE::LocString (L"Addition"), position)); }); nodeTree.AddItem (arithmeticNodes, L"Subtraction", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::SubtractionNode (NE::LocString (L"Subtraction"), position)); }); nodeTree.AddItem (arithmeticNodes, L"Multiplication", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::MultiplicationNode (NE::LocString (L"Multiplication"), position)); }); nodeTree.AddItem (arithmeticNodes, L"Division", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::DivisionNode (NE::LocString (L"Division"), position)); }); size_t otherNodes = nodeTree.AddGroup (L"Other Nodes"); nodeTree.AddItem (otherNodes, L"Viewer", [&] (const NUIE::Point& position) { return NUIE::UINodePtr (new BI::MultiLineViewerNode (NE::LocString (L"Viewer"), position, 5)); }); } class MyEventHandler : public WAS::HwndEventHandler { public: MyEventHandler () : WAS::HwndEventHandler (), nodeEditor (nullptr), nodeTree () { InitNodeTree (nodeTree); } void SetNodeEditor (NUIE::NodeEditor* nodeEditorPtr) { nodeEditor = nodeEditorPtr; } virtual NUIE::MenuCommandPtr OnContextMenu (NUIE::EventHandler::ContextMenuType type, const NUIE::Point& position, const NUIE::MenuCommandStructure& commands) override { if (type == NUIE::EventHandler::ContextMenuType::EmptyArea) { NUIE::MenuCommandStructure finalCommands = commands; NUIE::AddNodeTreeToMenuStructure (nodeTree, position, nodeEditor, finalCommands); return WAS::SelectCommandFromContextMenu (hwnd, position, finalCommands); } else { return WAS::SelectCommandFromContextMenu (hwnd, position, commands); } } private: NUIE::NodeEditor* nodeEditor; NUIE::NodeTree nodeTree; }; class MyNodeUIEnvironment : public NUIE::NodeUIEnvironment { public: MyNodeUIEnvironment () : NUIE::NodeUIEnvironment (), stringConverter (NE::BasicStringConverter (WAS::GetStringSettingsFromSystem ())), skinParams (NUIE::GetDefaultSkinParams ()), eventHandler (), clipboardHandler (), evaluationEnv (nullptr), drawingContext (new WAS::GdiOffscreenContext ()), nodeEditor (nullptr), editorHandle (nullptr) { } void Init (NUIE::NodeEditor* nodeEditorPtr, HWND editorWindowHandle) { nodeEditor = nodeEditorPtr; editorHandle = editorWindowHandle; drawingContext->Init (editorHandle); eventHandler.Init (editorHandle); eventHandler.SetNodeEditor (nodeEditor); } void OnResize (int width, int height) { drawingContext->Resize (width, height); } void OnPaint () { nodeEditor->Draw (); drawingContext->BlitToWindow (editorHandle); } virtual const NE::StringConverter& GetStringConverter () override { return stringConverter; } virtual const NUIE::SkinParams& GetSkinParams () override { return skinParams; } virtual NUIE::DrawingContext& GetDrawingContext () override { return *drawingContext; } virtual double GetWindowScale () override { return 1.0; } virtual NE::EvaluationEnv& GetEvaluationEnv () override { return evaluationEnv; } virtual void OnEvaluationBegin () override { } virtual void OnEvaluationEnd () override { } virtual void OnValuesRecalculated () override { } virtual void OnRedrawRequested () override { InvalidateRect (editorHandle, NULL, FALSE); } virtual NUIE::EventHandler& GetEventHandler () override { return eventHandler; } virtual NUIE::ClipboardHandler& GetClipboardHandler () override { return clipboardHandler; } virtual void OnSelectionChanged (const NUIE::Selection&) override { } virtual void OnUndoStateChanged (const NUIE::UndoState&) override { } virtual void OnClipboardStateChanged (const NUIE::ClipboardState&) override { } virtual void OnIncompatibleVersionPasted (const NUIE::Version&) override { } private: NE::BasicStringConverter stringConverter; NUIE::BasicSkinParams skinParams; MyEventHandler eventHandler; NUIE::MemoryClipboardHandler clipboardHandler; NE::EvaluationEnv evaluationEnv; NUIE::NativeDrawingContextPtr drawingContext; NUIE::NodeEditor* nodeEditor; HWND editorHandle; }; static MyNodeUIEnvironment uiEnvironment; static NUIE::NodeEditor nodeEditor (uiEnvironment); static LRESULT CALLBACK ApplicationWindowProc (HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { switch (msg) { case WM_CREATE: { uiEnvironment.Init (&nodeEditor, hwnd); } break; case WM_SIZE: { int newWidth = LOWORD (lParam); int newHeight = HIWORD (lParam); uiEnvironment.OnResize (newWidth, newHeight); } break; case WM_PAINT: uiEnvironment.OnPaint (); break; case WM_CLOSE: DestroyWindow (hwnd); break; case WM_DESTROY: PostQuitMessage (0); break; case WM_ERASEBKGND: return 0; case WM_LBUTTONDOWN: { WAS::SetWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDown (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Left, x, y); } break; case WM_MBUTTONDOWN: { WAS::SetWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDown (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Middle, x, y); } break; case WM_RBUTTONDOWN: { WAS::SetWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDown (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Right, x, y); } break; case WM_LBUTTONUP: { WAS::ReleaseWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseUp (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Left, x, y); } break; case WM_MBUTTONUP: { WAS::ReleaseWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseUp (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Middle, x, y); } break; case WM_RBUTTONUP: { WAS::ReleaseWindowCapture (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseUp (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Right, x, y); } break; case WM_MOUSEMOVE: { SetFocus (hwnd); int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseMove (WAS::GetModiferKeysFromEvent (wParam), x, y); } break; case WM_MOUSEWHEEL: { POINT mousePos; mousePos.x = GET_X_LPARAM (lParam); mousePos.y = GET_Y_LPARAM (lParam); ScreenToClient (hwnd, &mousePos); int delta = GET_WHEEL_DELTA_WPARAM (wParam); NUIE::MouseWheelRotation rotation = delta > 0 ? NUIE::MouseWheelRotation::Forward : NUIE::MouseWheelRotation::Backward; nodeEditor.OnMouseWheel (WAS::GetModiferKeysFromEvent (wParam), rotation, mousePos.x, mousePos.y); } break; case WM_LBUTTONDBLCLK: { int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDoubleClick (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Left, x, y); } break; case WM_MBUTTONDBLCLK: { int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDoubleClick (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Middle, x, y); } break; case WM_RBUTTONDBLCLK: { int x = GET_X_LPARAM (lParam); int y = GET_Y_LPARAM (lParam); nodeEditor.OnMouseDoubleClick (WAS::GetModiferKeysFromEvent (wParam), NUIE::MouseButton::Right, x, y); } break; case WM_KEYDOWN: { NUIE::CommandCode commandCode = NUIE::CommandCode::Undefined; bool isControlPressed = (GetKeyState (VK_CONTROL) < 0); bool isShiftPressed = (GetKeyState (VK_SHIFT) < 0); if (isControlPressed) { switch (wParam) { case 'A': commandCode = NUIE::CommandCode::SelectAll; break; case 'C': commandCode = NUIE::CommandCode::Copy; break; case 'V': commandCode = NUIE::CommandCode::Paste; break; case 'G': if (isShiftPressed) { commandCode = NUIE::CommandCode::Ungroup; } else { commandCode = NUIE::CommandCode::Group; } break; case 'Z': if (isShiftPressed) { commandCode = NUIE::CommandCode::Redo; } else { commandCode = NUIE::CommandCode::Undo; } break; } } else { switch (wParam) { case VK_ESCAPE: commandCode = NUIE::CommandCode::Escape; break; case VK_DELETE: case VK_BACK: commandCode = NUIE::CommandCode::Delete; break; } } if (commandCode != NUIE::CommandCode::Undefined) { nodeEditor.ExecuteCommand (commandCode); } } break; case WM_CANCELMODE: WAS::ReleaseWindowCapture (hwnd); break; } return DefWindowProc (hwnd, msg, wParam, lParam); } #if defined(BUILD_MONOLITHIC) #define wWinMain WED_WinMain #endif int wWinMain (HINSTANCE hInstance, HINSTANCE /*hPrevInstance*/, LPWSTR /*lpCmdLine*/, int /*nCmdShow*/) { WNDCLASSEX windowClass; ZeroMemory (&windowClass, sizeof (WNDCLASSEX)); windowClass.cbSize = sizeof (WNDCLASSEX); windowClass.style = CS_DBLCLKS; windowClass.lpfnWndProc = ApplicationWindowProc; windowClass.cbClsExtra = 0; windowClass.cbWndExtra = 0; windowClass.hInstance = hInstance; windowClass.hIcon = LoadIcon (NULL, IDI_APPLICATION); windowClass.hIconSm = LoadIcon (NULL, IDI_APPLICATION); windowClass.hCursor = LoadCursor (NULL, IDC_ARROW); windowClass.hbrBackground = (HBRUSH) COLOR_WINDOW; windowClass.lpszMenuName = NULL; windowClass.lpszClassName = L"VisualScriptEngineDemo"; if (!RegisterClassEx (&windowClass)) { return 1; } RECT requiredRect = { 0, 0, 900, 500 }; AdjustWindowRect (&requiredRect, WS_OVERLAPPEDWINDOW, false); HWND windowHandle = CreateWindowEx ( WS_EX_WINDOWEDGE | WS_CLIPCHILDREN, windowClass.lpszClassName, L"Visual Script Engine Demo", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, requiredRect.right - requiredRect.left, requiredRect.bottom - requiredRect.top, NULL, NULL, NULL, nullptr ); if (windowHandle == NULL) { return 1; } ShowWindow (windowHandle, SW_SHOW); UpdateWindow (windowHandle); MSG msg; while (GetMessage (&msg, NULL, 0, 0)) { TranslateMessage (&msg); DispatchMessage (&msg); } return 0; }
12,366
5,132
/* * Copyright (c) 2016 MariaDB Corporation Ab * * Use of this software is governed by the Business Source License included * in the LICENSE.TXT file and at www.mariadb.com/bsl11. * * Change Date: 2024-11-26 * * On the date above, in accordance with the Business Source License, use * of this software will be governed by version 2 or later of the General * Public License. */ #include <iostream> #include <string> #include <vector> #include <maxbase/string.hh> #include <maxtest/testconnections.hh> // This test checks // - that a failure to connect to redis/memcached does not stall the client and // - that when redis/memcached become available, they are transparently taken into use. using namespace std; namespace { const int PORT_RWS = 4006; const int PORT_RWS_REDIS = 4007; const int PORT_RWS_MEMCACHED = 4008; const int TIMEOUT = 10; // This should be bigger that the cache timeout in the config. bool restart_service(TestConnections& test, const char* zService) { bool rv = test.maxscales->ssh_node_f(0, true, "service %s restart", zService) == 0; sleep(1); // A short sleep to ensure connecting is possible. return rv; } bool start_service(TestConnections& test, const char* zService) { bool rv = test.maxscales->ssh_node_f(0, true, "service %s start", zService) == 0; sleep(1); // A short sleep to ensure connecting is possible. return rv; } bool stop_service(TestConnections& test, const char* zService) { return test.maxscales->ssh_node_f(0, true, "service %s stop", zService) == 0; } bool start_redis(TestConnections& test) { return start_service(test, "redis"); } bool stop_redis(TestConnections& test) { return stop_service(test, "redis"); } bool start_memcached(TestConnections& test) { return start_service(test, "memcached"); } bool stop_memcached(TestConnections& test) { return stop_service(test, "memcached"); } void drop(TestConnections& test) { MYSQL* pMysql = test.maxscales->conn_rwsplit[0]; test.try_query(pMysql, "DROP TABLE IF EXISTS cache_distributed"); test.maxscales->ssh_node_f(0, true, "redis-cli flushall"); restart_service(test, "memcached"); } void create(TestConnections& test) { drop(test); MYSQL* pMysql = test.maxscales->conn_rwsplit[0]; test.try_query(pMysql, "CREATE TABLE cache_distributed (f INT)"); } Connection connect(TestConnections& test, int port) { Connection c = test.maxscales->get_connection(port); bool connected = c.connect(); test.expect(connected, "Could not connect to %d.", port); return c; } void insert(TestConnections& test, Connection& c) { bool inserted = c.query("INSERT INTO cache_distributed values (1)"); test.expect(inserted, "Could not insert value."); } void select(TestConnections& test, const char* zName, Connection& c, size_t n) { Result rows = c.rows("SELECT * FROM cache_distributed"); test.expect(rows.size() == n, "%s: Expected %lu rows, but got %lu.", zName, n, rows.size()); } void install_and_start_redis_and_memcached(Maxscales& maxscales) { setenv("maxscale_000_keyfile", maxscales.sshkey(0), 0); setenv("maxscale_000_whoami", maxscales.user_name.c_str(), 0); setenv("maxscale_000_network", maxscales.ip4(0), 0); string path(test_dir); path += "/cache_install_and_start_storages.sh"; system(path.c_str()); } } int main(int argc, char* argv[]) { TestConnections::skip_maxscale_start(true); TestConnections test(argc, argv); auto maxscales = test.maxscales; install_and_start_redis_and_memcached(*maxscales); maxscales->start(); if (maxscales->connect_rwsplit() == 0) { create(test); sleep(1); Connection none = connect(test, PORT_RWS); insert(test, none); test.tprintf("Connecting with running redis/memcached."); test.set_timeout(TIMEOUT); Connection redis = connect(test, PORT_RWS_REDIS); Connection memcached = connect(test, PORT_RWS_MEMCACHED); // There has been 1 insert so we should get 1 in all cases. As redis and memcached // are running, the caches will be populated as well. test.set_timeout(TIMEOUT); select(test, "none", none, 1); select(test, "redis", redis, 1); select(test, "memcached", memcached, 1); test.stop_timeout(); test.tprintf("Stopping redis/memcached."); stop_redis(test); stop_memcached(test); test.tprintf("Connecting with stopped redis/memcached."); // Using a short timeout at connect-time ensure that if the async connecting // does not work, we'll get a quick failure. test.set_timeout(TIMEOUT); redis = connect(test, PORT_RWS_REDIS); memcached = connect(test, PORT_RWS_MEMCACHED); // There has still been only one insert, so in all cases we should get just one row. // As redis and memcached are not running, the result comes from the backend. test.set_timeout(TIMEOUT); select(test, "none", none, 1); select(test, "redis", redis, 1); select(test, "memcached", memcached, 1); test.stop_timeout(); // Lets add another row. insert(test, none); // There has been two inserts, and as redis/memcached are stopped, we should // get two in all cases. test.set_timeout(TIMEOUT); select(test, "none", none, 2); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); test.stop_timeout(); test.tprintf("Starting redis/memcached."); start_redis(test); start_memcached(test); sleep(1); // To allow things to stabalize. // As the caches are now running, they will now be taken into use. However, that // will be triggered by the fetching and hence the first result will be fetched from // the backend and possibly cached as well, if the connection to the cache is established // faster that what getting the result from the backend is. test.set_timeout(TIMEOUT); select(test, "none", none, 2); select(test, "redis", redis, 2); select(test, "memcache", memcached, 2); test.stop_timeout(); // To make sure the result ends up in the cache, we select again after having slept // for a short while. sleep(2); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); // Add another row, should not be visible from cached alternatives. insert(test, none); select(test, "none", none, 3); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); // Add yet another row, should not be visible from cached alternatives. insert(test, none); select(test, "none", none, 4); select(test, "redis", redis, 2); select(test, "memcached", memcached, 2); } else { ++test.global_result; } return test.global_result; }
7,058
2,314
#include "game.hpp" #include "board.hpp" #include "game_options.hpp" #include "game_solver.hpp" #include "input.hpp" #include "main_menu.hpp" #include <bulls_and_cows_lib\game_options.cpp> #include <chrono> #include <fstream> #include <iostream> #include <thread> namespace bulls_and_cows { void user_plays_against_computer(const GameOptions& game_options) { Board board = create_board(game_options); AttemptAndFeedback newAttemptAndFeedback; do { display_board(std::cout, game_options, board); newAttemptAndFeedback.attempt = ask_attempt(std::cout, std::cin, game_options, board); while (!validate_attempt(game_options, newAttemptAndFeedback.attempt)) { std::cout << "Your attempt is not valid, try again\n"; newAttemptAndFeedback.attempt = ask_attempt(std::cout, std::cin, game_options, board); } newAttemptAndFeedback.feedback = compare_attempt_with_secret_code(newAttemptAndFeedback.attempt, board.secret_code); board.attempts_and_feedbacks.push_back(newAttemptAndFeedback); } while (!(is_end_of_game(game_options, board)) && !(is_win(game_options, board))); std::cout << "\n\n"; display_board(std::cout, game_options, board); if (is_win(game_options, board)) { std::cout << "Wow you just won !! The secret code was : " << board.secret_code.value << std::endl; } else { std::cout << "Sorry but you lost. The secret combinaison was : " << board.secret_code.value << std::endl; } } void computer_plays_against_computer(const GameOptions& game_options) { std::cout << "TODO:\n" " Create a board with a randomly generated secret code\n" " Generate the list of all the possible codes\n" " DO\n" " Display the board and the list of attempts so far\n" " Display the number of remaining possible codes so far\n" " Wait for 2 seconds\n" " Pick a random attempt among in the list of remaining possible codes\n" " Compare the computer's attempt with the secret code and deduce the number of bulls and cows\n" " Add the computer's attempt to the list of attempts of the board\n" " Remove all the codes that are incompatible with the attempt's feedback from the list of " "possible codes\n" " WHILE not end of game\n" " Display the board and the list of attempts so far\n" " Display a message telling if the computer won or lost\n"; } void configure_game_options(GameOptions& game_options) { bool exit = false; std::string path = "./save.txt"; std::ofstream save; std::ifstream load(path); while (!exit) { std::cout << "\n"; std::cout << "#################################" << "\n"; std::cout << "#################################" << "\n"; std::cout << "#################################" << "\n"; std::cout << "\n"; display_game_options(std::cout, game_options); display_game_options_menu(std::cout); const auto choice = ask_game_options_menu_choice(std::cin); switch (choice) { case GameOptionsMenuChoice::BackToMain: return; case GameOptionsMenuChoice::ModifyMaximumNumberOfAttempts: { option_ModifyMaximumNumberOfAttempts(game_options); break; } case GameOptionsMenuChoice::ModifyNumberOfCharactersPerCode: { option_ModifyNumberOfCharactersPerCode(game_options); break; } case GameOptionsMenuChoice::ModifyMinimumAllowedCharacter: { option_ModifyMinimumAllowedCharacter(game_options); break; } case GameOptionsMenuChoice::ModifyMaximumAllowedCharacter: { option_ModifyMaximumAllowedCharacter(game_options); break; } case GameOptionsMenuChoice::SaveOptions: { std::ofstream game_options_file{"game_options.txt", std::ios::app}; save_game_options(game_options_file, game_options); game_options_file.close(); break; } case GameOptionsMenuChoice::LoadOptions: { std::ifstream file("game_options.txt"); load_game_options(file, game_options); break; } case GameOptionsMenuChoice::Error: std::cout << "\nYou did not enter a valid choice, please try again\n"; break; } } } void play_game() { GameOptions game_options{}; while (true) { std::cout << "\n#################################\n"; std::cout << "\n#################################\n"; display_main_menu(std::cout); const auto choice = ask_main_menu_choice(std::cin); switch (choice) { case MainMenuChoice::Quit: std::cout << "\nGood bye!\n"; return; case MainMenuChoice::UserPlaysAgainstComputer: user_plays_against_computer(game_options); break; case MainMenuChoice::ComputerPlaysAgainstComputer: computer_plays_against_computer(game_options); break; case MainMenuChoice::ConfigureOptions: configure_game_options(game_options); break; case MainMenuChoice::Error: std::cout << "\nYou did not enter a valid choice, please try again\n"; break; } } } } // namespace bulls_and_cows
6,180
1,632
#pragma once #include "zlib.h" namespace xul { int gzip_uncompress( Bytef *dest, uLongf *destLen, const Bytef *source, uLong sourceLen) { z_stream stream; int err; int gzip = 1; stream.next_in = (Bytef*)source; stream.avail_in = (uInt)sourceLen; /* Check for source > 64K on 16-bit machine: */ if ((uLong)stream.avail_in != sourceLen) return Z_BUF_ERROR; stream.next_out = dest; stream.avail_out = (uInt)*destLen; if ((uLong)stream.avail_out != *destLen) return Z_BUF_ERROR; stream.zalloc = (alloc_func)0; stream.zfree = (free_func)0; if (gzip == 1) { err = inflateInit2(&stream, 47); } else { err = inflateInit(&stream); } if (err != Z_OK) return err; err = inflate(&stream, Z_FINISH); if (err != Z_STREAM_END) { inflateEnd(&stream); if (err == Z_NEED_DICT || (err == Z_BUF_ERROR && stream.avail_in == 0)) return Z_DATA_ERROR; return err; } *destLen = stream.total_out; err = inflateEnd(&stream); return err; } }
1,087
429
#include "Macierz.hh" Macierz::Macierz(Wektor a1, Wektor a2, Wektor a3) { Wektor a1,a2,a3; } double & Wektor::operator[](int index) { if(index > ROZMIAR || index < 0) { exit(1); } return tab[index]; } const double & Wektor::operator[](int index) const { if(index > ROZMIAR || index < 0) { exit(1); } return tab[index]; } void Macierz::transpozycja() { Macierz pomoc; for (int i=0; i<ROZMIAR; i++) { for(int j=0; j<ROZMIAR; j++) { pomoc[i][j]=tab[i][j]; } } for (int i=0; i<ROZMIAR; i++) { for(int j=0; j<ROZMIAR; j++) { tab[i][j]=pomoc[j][i]; } } } Wektor Macierz::operator *(Wektor W) { Wektor Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i]=Wynik[i] + (tab[i][j]*W[j]); } } return Wynik; } Macierz Macierz::operator *(Macierz W) { Macierz Wynik; W.transpozycja(); for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=Wynik[i][j] + (tab[i][j] * W[i][j]); } } return Wynik; } Macierz Macierz::operator +(Macierz W) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]+W[i][j]; } } return Wynik; } Macierz Macierz::operator -(Macierz W) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]-W[i][j]; } } return Wynik; } Macierz Macierz::operator * (double l) { Macierz Wynik; for(int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Wynik[i][j]=tab[i][j]*l; } } return Wynik; } double Macierz::wyznacznikSarus () { double Wynik; Wynik = tab[0][0]*tab[1][1]*tab[2][2]+tab[1][0]*tab[2][1]*tab[0][2]+ tab[2][0]*tab[0][1]*tab[0][2]-tab[0][2]*tab[1][1]*tab[2][0]- tab[1][2]*tab[2][1]*tab[0][0]-tab[2][2]*tab[0][1]*tab[1][0]; return Wynik; } void Macierz::odwrotnosc() { int s; Macierz wyzn, pomoc; double mac2x2[4]; double wyznacznik; for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { wyzn[i][j]=tab[i][j]; pomoc[i][j]=tab[i][j]; } } wyznacznik = wyzn.wyznacznikSarus; for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { s=0; for (int k=0; k<ROZMIAR; k++) { for (int l=0; l<ROZMIAR; l++) { if (k != i && l != j) { mac2x2[s]=pomoc[k][l]; s++; } } } if ((i+j)%2 != 0) { wyzn[i][j]=-(Wyznacznik2x2(mac2x2)); } else { wyzn[i][j]=Wyznacznik2x2(mac2x2); } } } wyzn.transpozycja(); for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { tab[i][j]=(1/wyznacznik)*wyzn[i][j]; } } } double Macierz::Wyznacznik2x2 (double mac2x2[4]) { double Wynik; Wynik=mac2x2[0]*mac2x2[2]-mac2x2[1]*mac2x2[3]; return Wynik; } bool Macierz::operator == (const Macierz & W2)const { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { if (abs(tab[i][j]-W2[i][j]) >= 0.000001) { return false; } } } return true; } bool Macierz::operator != (const Macierz & W2)const { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { if (abs(tab[i][j]-W2[i][j]) >= 0.000001) { return true; } } } return false; } const Wektor & Macierz::zwroc_kolumne (int ind) { Wektor Wynik; for (int i=0; i<ROZMIAR; i++) { Wynik[i] = tab[ind][i]; } return Wynik; } void Macierz::zmien_kolumne(int ind, Wektor nowy) { for (int i=0; i<ROZMIAR; i++) { tab[ind][i] = nowy[i]; } } std::istream& operator >> (std::istream &Strm, Macierz &Mac) { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Strm>>Mac[i][j]; return Strm; } } Mac.transpozycja(); } std::ostream& operator << (std::ostream &Strm, Macierz &Mac) { for (int i=0; i<ROZMIAR; i++) { for (int j=0; j<ROZMIAR; j++) { Strm<<Mac[i][j]; return Strm; } } }
4,849
2,135
/*********************************************************************************** * Copyright (c) 2012, Sepehr Taghdisian * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * ***********************************************************************************/ #include <stdio.h> #include "luacore.i" #include "script.h" #include "dhcore/util.h" /************************************************************************************************* * global funcs */ void printcon(const char* text) { if (text == NULL) { log_printf(LOG_WARNING, "incoming [null] text for 'printcon'"); return; } log_printf(LOG_INFO, "lua: %s", text); } float randFloat(float min, float max) { return rand_getf(min, max); } int randInt(int min, int max) { return rand_geti(min, max); } /************************************************************************************************* * vector funcs */ Vector::Vector() { vec3_setzero(&v_); } Vector::Vector(float x, float y, float z) { vec3_setf(&v_, x, y, z); } Vector::Vector(const Vector& v) { vec3_setv(&this->v_, &v.v_); } const char* Vector::__str__() { static char text[64]; sprintf(text, "Vector: %.3f %.3f %.3f", v_.x, v_.y, v_.z); return text; } Vector& Vector::__eq__(const Vector& v) { vec3_setv(&this->v_, &v.v_); return *this; } Vector Vector::__add__(const Vector& v1) { Vector r; vec3_add(&r.v_, &this->v_, &v1.v_); return r; } Vector Vector::__sub__(const Vector& v1) { Vector r; vec3_sub(&r.v_, &this->v_, &v1.v_); return r; } float Vector::__mul__(const Vector& v1) { return vec3_dot(&this->v_, &v1.v_); } Vector Vector::__mul__(float k) { Vector r; vec3_muls(&r.v_, &this->v_, k); return r; } Vector Vector::__div__(float k) { Vector r; vec3_muls(&r.v_, &this->v_, 1.0f/k); return r; } Vector Vector::cross(const Vector& v) { Vector r; vec3_cross(&r.v_, &this->v_, &v.v_); return r; } float Vector::x() const { return v_.x; } float Vector::y() const { return v_.y; } float Vector::z() const { return v_.z; } void Vector::set(float x, float y, float z) { v_.x = x; v_.y = y; v_.z = z; } void Vector::lerp(const Vector& v1, const Vector& v2, float t) { vec3_lerp(&this->v_, &v1.v_, &v2.v_, t); } void Vector::cubic(const Vector& v0, const Vector& v1, const Vector& v2, const Vector& v3, float t) { vec3_cubic(&this->v_, &v0.v_, &v1.v_, &v2.v_, &v3.v_, t); } void Vector::normalize() { vec3_norm(&v_, &v_); } void Vector::__setitem__(int x, float value) { if (x < 0 || x > 2) { sct_throwerror("Index out of bounds"); return; } v_.f[x] = value; } float Vector::__getitem__(int x) { if (x < 0 || x > 2) { sct_throwerror("Index out of bounds"); return 0.0f; } return v_.f[x]; } /************************************************************************************************* * Quat */ Quat::Quat() { quat_setidentity(&this->q_); } Quat::Quat(float x, float y, float z, float w) { quat_setf(&this->q_, x, y, z, w); } Quat::Quat(const Quat& q) { quat_setq(&this->q_, &q.q_); } const char* Quat::__str__() { static char text[64]; sprintf(text, "Quat: %.3f %.3f %.3f %.3f", q_.x, q_.y, q_.z, q_.w); return text; } Quat& Quat::__eq__(const Quat& q) { quat_setq(&this->q_, &q.q_); return *this; } void Quat::setEuler(float rx, float ry, float rz) { quat_fromeuler(&this->q_, rx, ry, rz); } Vector Quat::getEuler() { float rx; float ry; float rz; quat_geteuler(&rx, &ry, &rz, &this->q_); Vector r; vec3_setf(&r.v_, rx, ry, rz); return r; } Quat& Quat::inverse() { quat_inv(&this->q_, &this->q_); return *this; } void Quat::slerp(const Quat& q1, const Quat& q2, float t) { quat_slerp(&this->q_, &q1.q_, &q2.q_, t); } float Quat::__getitem__(int x) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return 0.0f; } return q_.f[x]; } void Quat::__setitem__(int x, float value) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return; } q_.f[x] = value; } /************************************************************************************************* * Color */ Color::Color() { color_setc(&c_, &g_color_black); } Color::Color(float r, float g, float b, float a) { color_setf(&c_, r, g, b, a); } Color::Color(const Color& c) { color_setc(&c_, &c.c_); } void Color::set(float r, float g, float b, float a) { color_setf(&c_, r, g, b, a); } void Color::setInt(uint r, uint g, uint b, uint a) { color_seti(&c_, (uint8)r, (uint8)g, (uint8)b, (uint8)a); } const char* Color::__str__() { static char text[64]; sprintf(text, "Color: %.3f %.3f %.3f %.3f", c_.r, c_.r, c_.b, c_.a); return text; } Color& Color::__eq__(const Color& c) { color_setc(&c_, &c.c_); return *this; } Color Color::__add__(const Color& c1) { Color r; color_add(&r.c_, &c_, &c1.c_); return r; } Color Color::__mul__(const Color& c1) { Color r; color_mul(&r.c_, &c_, &c1.c_); return r; } Color Color::__mul__(float k) { Color r; color_muls(&r.c_, &c_, k); return r; } float Color::r() const { return c_.r; } float Color::g() const { return c_.g; } float Color::b() const { return c_.b; } float Color::a() const { return c_.a; } void Color::lerp(const Color& c1, const Color& c2, float t) { color_lerp(&c_, &c1.c_, &c2.c_, t); } Color Color::toGamma() { Color r; color_togamma(&r.c_, &c_); return r; } Color Color::toLinear() { Color r; color_tolinear(&r.c_, &c_); return r; } uint Color::toUint() { return color_rgba_uint(&c_); } float Color::__getitem__(int x) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return 0.0f; } return c_.f[x]; } void Color::__setitem__(int x, float value) { if (x < 0 || x > 3) { sct_throwerror("Index out of bounds"); return; } c_.f[x] = value; } /************************************************************************************************* * Vector2D */ Vector2D::Vector2D() { vec2i_setzero(&v_); } Vector2D::Vector2D(int x, int y) { vec2i_seti(&v_, x, y); } Vector2D::Vector2D(const Vector2D& v) { vec2i_setv(&v_, &v.v_); } void Vector2D::set(int x, int y) { vec2i_seti(&v_, x, y); } const char* Vector2D::__str() { static char text[64]; sprintf(text, "Vector2D: %d, %d", v_.x, v_.y); return text; } Vector2D& Vector2D::__eq__(const Vector2D& v) { vec2i_setv(&v_, &v.v_); return *this; } Vector2D Vector2D::__add__(const Vector2D& v1) { Vector2D r; vec2i_add(&r.v_, &v_, &v1.v_); return r; } Vector2D Vector2D::__sub__(const Vector2D& v1) { Vector2D r; vec2i_sub(&r.v_, &v_, &v1.v_); return r; } Vector2D Vector2D::__mul__(int k) { Vector2D r; vec2i_muls(&r.v_, &v_, k); return r; } void Vector2D::__setitem__(int x, int value) { if (x < 0 || x > 1) { sct_throwerror("Index out of bounds"); return; } v_.n[x] = value; } int Vector2D::__getitem__(int x) { if (x < 0 || x > 1) { sct_throwerror("Index out of bounds"); return 0; } return v_.n[x]; }
7,859
3,188
/* * Interfaces for SDC/MLSDC/PFASST algorithms. */ #ifndef _PFASST_INTERFACES_HPP_ #define _PFASST_INTERFACES_HPP_ #include <cassert> #include <deque> #include <exception> #include <iterator> #include <memory> #include <string> #include "globals.hpp" using namespace std; namespace pfasst { using time_precision = double; // forward declare for ISweeper template<typename time> class Controller; /** * not implemented yet exception. * * Used by PFASST to mark methods that are required for a particular algorithm (SDC/MLSDC/PFASST) * that may not be necessary for all others. */ class NotImplementedYet : public exception { string msg; public: NotImplementedYet(string msg) : msg(msg) {} const char* what() const throw() { return (string("Not implemented/supported yet, required for: ") + this->msg).c_str(); } }; /** * value exception. * * Thrown when a PFASST routine is passed an invalid value. */ class ValueError : public exception { string msg; public: ValueError(string msg) : msg(msg) {} const char* what() const throw() { return (string("ValueError: ") + this->msg).c_str(); } }; class ICommunicator { public: virtual ~ICommunicator() { } virtual int size() = 0; virtual int rank() = 0; }; /** * abstract SDC sweeper. * @tparam time time precision * defaults to pfasst::time_precision */ template<typename time = time_precision> class ISweeper { protected: Controller<time>* controller; public: //! @{ virtual ~ISweeper() {} //! @} //! @{ /** * set the sweepers controller. */ void set_controller(Controller<time>* ctrl) { this->controller = ctrl; } Controller<time>* get_controller() { assert(this->controller); return this->controller; } //! @} //! @{ /** * setup (allocate etc) the sweeper. * @param[in] coarse * `true` if this sweeper exists on a coarsened MLSDC or PFASST level. * This implies that space for an FAS correction and "saved" solutions are necessary. */ virtual void setup(bool coarse = false) { UNUSED(coarse); } /** * perform a predictor sweep. * * Compute a provisional solution from the initial condition. * This is typically very similar to a regular SDC sweep, except that integral terms based on * previous iterations don't exist yet. * @param[in] initial * `true` if function values at the first node need to be computed. * `false` if functions values at the first node already exist (usually this is the case * when advancing from one time step to the next). */ virtual void predict(bool initial) = 0; /** * Perform one SDC sweep/iteration. * * Compute a correction and update solution values. Note that this function can assume that * valid function values exist from a previous pfasst::ISweeper::sweep() or * pfasst::ISweeper::predict(). */ virtual void sweep() = 0; /** * Advance from one time step to the next. * * Essentially this means copying the solution and function values from the last node to the * first node. */ virtual void advance() = 0; /** * Save states (and/or function values) at all nodes. * * This is typically done in MLSDC/PFASST immediately after a call to restrict. * The saved states are used to compute deltas during interpolation. * * @note This method must be implemented in derived sweepers. */ virtual void save(bool initial_only=false) { UNUSED(initial_only); throw NotImplementedYet("mlsdc/pfasst"); } virtual void spread() { throw NotImplementedYet("pfasst"); } //! @} //! @{ virtual void post(ICommunicator* comm, int tag) { UNUSED(comm); UNUSED(tag); }; virtual void send(ICommunicator* comm, int tag, bool blocking) { UNUSED(comm); UNUSED(tag); UNUSED(blocking); throw NotImplementedYet("pfasst"); } virtual void recv(ICommunicator* comm, int tag, bool blocking) { UNUSED(comm); UNUSED(tag); UNUSED(blocking); throw NotImplementedYet("pfasst"); } virtual void broadcast(ICommunicator* comm) { UNUSED(comm); throw NotImplementedYet("pfasst"); } //! @} }; /** * abstract time/space transfer (restrict/interpolate) class. * @tparam time time precision * defaults to pfasst::time_precision */ template<typename time = time_precision> class ITransfer { public: //! @{ virtual ~ITransfer() {} //! @} //! @{ /** * Interpolate initial condition from the coarse sweeper to the fine sweeper. */ virtual void interpolate_initial(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) { UNUSED(dst); UNUSED(src); throw NotImplementedYet("pfasst"); } /** * Interpolate, in time and space, from the coarse sweeper to the fine sweeper. * @param[in] interp_initial * `true` if a delta for the initial condtion should also be computed (PFASST). */ virtual void interpolate(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src, bool interp_initial = false) = 0; /** * Restrict initial condition from the fine sweeper to the coarse sweeper. * @param[in] restrict_initial * `true` if the initial condition should also be restricted. */ virtual void restrict_initial(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) { UNUSED(dst); UNUSED(src); throw NotImplementedYet("pfasst"); } /** * Restrict, in time and space, from the fine sweeper to the coarse sweeper. * @param[in] restrict_initial * `true` if the initial condition should also be restricted. */ virtual void restrict(shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src, bool restrict_initial = false) = 0; /** * Compute FAS correction between the coarse and fine sweepers. */ virtual void fas(time dt, shared_ptr<ISweeper<time>> dst, shared_ptr<const ISweeper<time>> src) = 0; //! @} }; } // ::pfasst #endif
6,947
2,084
//----------------------------------------------------------------------- // Copyright 2011 Ciaran McHale. // // 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's //-------- #include "SchemaLex.h" namespace CONFIG4CPP_NAMESPACE { //-------- // This array must be kept sorted becaue we do a binary search on it. //-------- static LexBase::KeywordInfo keywordInfoArray[] = { //---------------------------------------------------------------------- // spelling symbol //---------------------------------------------------------------------- {"@ignoreEverythingIn", SchemaLex::LEX_IGNORE_EVERYTHING_IN_SYM}, {"@ignoreScopesIn", SchemaLex::LEX_IGNORE_SCOPES_IN_SYM}, {"@ignoreVariablesIn", SchemaLex::LEX_IGNORE_VARIABLES_IN_SYM}, {"@optional", SchemaLex::LEX_OPTIONAL_SYM}, {"@required", SchemaLex::LEX_REQUIRED_SYM}, {"@typedef", SchemaLex::LEX_TYPEDEF_SYM}, }; const static int keywordInfoArraySize = sizeof(keywordInfoArray) / sizeof(keywordInfoArray[0]); SchemaLex::SchemaLex(const char * str) : LexBase(str) { m_keywordInfoArray = keywordInfoArray; m_keywordInfoArraySize = keywordInfoArraySize; } SchemaLex::~SchemaLex() { } }; // namespace CONFIG4CPP_NAMESPACE
2,375
759
/* Time Complexity : 1. Shortest path by Dijkstra, using a Binary Min-heap as priority queue O(|V| + |E|)*log|V| = O(|E|log|V|) 2. Shortest path by Dijkstra, using a Fibonacci Min-heap as priority queue O(|E| + |V|log|V|) 3. Shortest path by Dijkstra, using an unsorted array as priority queue O(|V|^2) */ #include<cstdio> #include<vector> #include<queue> using namespace std; enum{NIL = -1, MAX = 50, INF = 9999}; typedef pair<int,int> ii; typedef vector<int> vi; typedef vector<vi> vvi; typedef vector<ii> vii; typedef vector<vii> vvii; vvii G(MAX); vi dist(MAX); vi parent(MAX); int n; void dijkstra(int s) { for(int u = 0; u < n; u++) { dist[u] = INF; parent[u] = NIL; } dist[s] = 0; priority_queue<ii, vector<ii>, greater<ii> > Q; Q.push(ii(dist[s],s)); while(!Q.empty()) { ii top = Q.top(); Q.pop(); int u = top.second; int d = top.first; if(d <= dist[u]) { for(vii::iterator it = G[u].begin(); it != G[u].end(); ++it) { int v = it->first; int w = it->second; if(dist[v] > dist[u] + w) { dist[v] = dist[u] + w; parent[v] = u; Q.push(ii(dist[v],v)); } } } } } void printPath(int s, int t) { if(t == s) printf("%d ",s); else { printPath(s, parent[t]); printf("%d ",t); } } int main() { int m; scanf("%d %d",&n,&m); int u,v,w; for(int i = 0; i < m; i++) { scanf("%d %d %d",&u,&v,&w); G[u].push_back(ii(v,w)); G[v].push_back(ii(u,w)); } int s, t; scanf("%d %d",&s,&t); dijkstra(s); printPath(s,t); printf("\n"); return 0; }
1,582
828
// // EEDataUtils.hpp // ee-library // // Created by Zinge on 7/20/17. // // #ifndef EE_LIBRARY_DATA_UTILS_HPP #define EE_LIBRARY_DATA_UTILS_HPP #ifdef __cplusplus #include <cstddef> #include <string> #include "ee/cocos/EEDataMeta.hpp" namespace ee { namespace detail { /// Globally sets a data value. /// @param[in] dataId The data unique ID. /// @param[in] key The data key. /// @param[in] value The data value. void set0(std::size_t dataId, const std::string& key, const std::string& value); /// Globally gets a data value. /// @param[in] dataId The data unique ID. /// @param]in] key The data key. /// @param[out] result The data value. /// @return True if result is assigned, false otherwise. bool get0(std::size_t dataId, const std::string& key, std::string& result); /// Globally removes a data value. /// @param[in] dataId The data unique ID. /// @param[in] key The data key. void remove0(std::size_t dataId, const std::string& key); } // namespace detail template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Value, class... Keys, EE_REQUIRES(detail::is_data_info_v<DataType>), EE_REQUIRES(detail::can_store_v<Traits, Value>), EE_REQUIRES(detail::is_formattable_v<Formatter, Keys...>)> void set(Value&& value, Keys&&... keys) { detail::set0(DataType::Id, Formatter::createKey(std::forward<Keys>(keys)...), Traits::store(std::forward<Value>(value))); } template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Value = typename DataType::ValueType, class... Keys, EE_REQUIRES(detail::is_data_info_v<DataType>), EE_REQUIRES(detail::can_load_v<Traits, Value>), EE_REQUIRES(detail::is_formattable_v<Formatter, Keys...>)> Value get(Keys&&... keys) { // Return type must not be decltype(auto) because // DataTraits<std::string>::load returns const std::string& would result a // segment fault. std::string result; detail::get0(DataType::Id, Formatter::createKey(std::forward<Keys>(keys)...), result); return Traits::load(result); } template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Value = typename DataType::ValueType, class... Keys, EE_REQUIRES(detail::is_data_info_v<DataType>), EE_REQUIRES(detail::is_formattable_v<Formatter, Keys...>), EE_REQUIRES(detail::is_traits_v<Traits, Value>)> void getAndSet(const typename DataType::SetterType& setter, Keys&&... keys) { auto current = get<DataType, Traits, Formatter>(keys...); setter(current); set<DataType, Traits, Formatter>(current, std::forward<Keys>(keys)...); } template <class DataType, class Traits = typename DataType::TraitsType, class Formatter = typename DataType::FormatType, class Function, class... Keys, class = std::enable_if_t< std::is_same<bool, typename DataType::ValueType>::value>> void getAndSetIf(bool conditionalValue, Function&& setter, Keys&&... keys) { auto current = get<DataType, Traits>(keys...); if (current == conditionalValue) { current = not conditionalValue; setter(); set<DataType, Traits>(current, std::forward<Keys>(keys)...); } } template <class DataType, class... Keys> void remove(Keys&&... keys) { detail::remove0(DataType::Id, DataType::createKey(std::forward<Keys>(keys)...)); } class Increment final { public: explicit Increment(std::size_t times = 1) : times_(times) {} template <class T> void operator()(T& value) const { for (std::size_t i = 0; i < times_; ++i) { ++value; } } private: std::size_t times_; }; class Decrement final { public: explicit Decrement(std::size_t times = 1) : times_(times) {} template <class T> void operator()(T& value) const { for (std::size_t i = 0; i < times_; ++i) { --value; } } private: std::size_t times_; }; } // namespace ee #endif // __cplusplus #endif /* EE_LIBRARY_DATA_UTILS_HPP */
4,312
1,439
/* * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include "ui_test_chart_polyline.h" #include "common/screen.h" namespace OHOS { namespace { static int16_t g_blank = 20; static int g_curSerialCount = 0; static int g_curArrayCount = 0; static bool g_secondScreenFlag = false; static bool g_addPointsFlag = false; static bool g_hidePointsFlag = false; } // namespace void UITestChartPolyline::SetUp() { if (container_ == nullptr) { container_ = new UIScrollView(); container_->Resize(Screen::GetInstance().GetWidth(), Screen::GetInstance().GetHeight() - BACK_BUTTON_HEIGHT); container_->SetHorizontalScrollState(false); container_->SetThrowDrag(true); } dataSerial_[0] = new UIChartDataSerial(); dataSerial_[0]->SetMaxDataCount(5); // 5: number of data points Point pointArray[5] = {{0, 2478}, {1, 2600}, {2, 3000}, {3, 3200}, {4, 3500}}; dataSerial_[0]->AddPoints(pointArray, 5); // 5: number of data points dataSerial_[0]->SetLineColor(Color::Red()); dataSerial_[0]->SetFillColor(Color::Red()); dataSerial_[0]->EnableGradient(true); dataSerial_[1] = new UIChartDataSerial(); dataSerial_[1]->SetMaxDataCount(5); // 5: number of data points Point pointArray1[5] = {{0, 2000}, {1, 0}, {2, 800}, {3, 700}, {4, 433}}; dataSerial_[1]->AddPoints(pointArray1, 5); // 5: number of data points dataSerial_[1]->SetLineColor(Color::Green()); dataSerial_[1]->SetFillColor(Color::Green()); dataSerial_[1]->EnableGradient(true); dataSerial_[2] = new UIChartDataSerial(); // 2: array index dataSerial_[2]->SetMaxDataCount(5); // 2: array index, 5: number of data points Point pointArray2[5] = {{0, 100}, {1, 200}, {2, 300}, {3, 400}, {4, 500}}; dataSerial_[2]->AddPoints(pointArray2, 5); // 2: array index, 5: number of data points dataSerial_[2]->SetLineColor(Color::Blue()); // 2: array index curDataIndex_ = 0; } void UITestChartPolyline::InnerDeleteChildren(UIView* view) const { if (view == nullptr) { return; } while (view != nullptr) { UIView* tempView = view; view = view->GetNextSibling(); if (tempView->IsViewGroup()) { InnerDeleteChildren(static_cast<UIViewGroup*>(tempView)->GetChildrenHead()); } if (tempView->GetViewType() == UI_AXIS) { return; } if (tempView->GetParent()) { static_cast<UIViewGroup*>(tempView->GetParent())->Remove(tempView); } delete tempView; } } void UITestChartPolyline::TearDown() { ECGAnimator_->Stop(); delete ECGAnimator_; ECGAnimator_ = nullptr; chart_->ClearDataSerial(); for (uint8_t i = 0; i < DATA_NUM; i++) { delete dataSerial_[i]; dataSerial_[i] = nullptr; } InnerDeleteChildren(container_); container_ = nullptr; lastX_ = 0; lastY_ = 0; positionX_ = 0; positionY_ = 0; g_curSerialCount = 0; g_curArrayCount = 0; g_secondScreenFlag = false; g_addPointsFlag = false; g_hidePointsFlag = false; } const UIView* UITestChartPolyline::GetTestView() { UIKit_ChartPolyline_Test_AddDataSerial_001(); UIKit_ChartPolyline_Test_EnableReverse_002(); UIKit_ChartPolyline_Test_SetGradientBottom_003(); UIKit_ChartPolyline_Test_AddPoints_004(); return container_; } void UITestChartPolyline::UIKit_ChartPolyline_Test_AddDataSerial_001() { UILabel* label = new UILabel(); container_->Add(label); lastY_ = TEXT_DISTANCE_TO_TOP_SIDE; // 29: label height label->SetPosition(TEXT_DISTANCE_TO_LEFT_SIDE, lastY_, Screen::GetInstance().GetWidth(), 29); label->SetText("chart添加、删除数据串 "); label->SetFont(DEFAULT_VECTOR_FONT_FILENAME, FONT_DEFAULT_SIZE); chart_ = new UIChartPolyline(); chart_->SetPosition(VIEW_DISTANCE_TO_LEFT_SIDE, VIEW_DISTANCE_TO_TOP_SIDE); chart_->SetWidth(454); // 454: width chart_->SetHeight(250); // 250: height UIXAxis& xAxis = chart_->GetXAxis(); UIYAxis& yAxis = chart_->GetYAxis(); xAxis.SetMarkNum(5); // 5: number of scales xAxis.SetDataRange(0, 5); // 0: minimum value, 5: maximum value yAxis.SetDataRange(0, 5000); // 0: minimum value, 5000: maximum value chart_->SetGradientOpacity(25, 127); // 25: min opacity, 127: max opacity chart_->AddDataSerial(dataSerial_[0]); curDataIndex_++; container_->Add(chart_); SetLastPos(chart_); addDataSerialBtn_ = new UILabelButton(); deleteDataSerialBtn_ = new UILabelButton(); clearDataSerialBtn_ = new UILabelButton(); topPointBtn_ = new UILabelButton(); bottomPointBtn_ = new UILabelButton(); headPointBtn_ = new UILabelButton(); positionX_ = VIEW_DISTANCE_TO_LEFT_SIDE; positionY_ = lastY_ + 10; // 10: increase y-coordinate SetUpButton(addDataSerialBtn_, "添加数据 "); positionX_ = addDataSerialBtn_->GetX() + addDataSerialBtn_->GetWidth() + g_blank; positionY_ = addDataSerialBtn_->GetY(); SetUpButton(deleteDataSerialBtn_, "删除数据 "); positionX_ = deleteDataSerialBtn_->GetX() + deleteDataSerialBtn_->GetWidth() + g_blank; positionY_ = deleteDataSerialBtn_->GetY(); SetUpButton(clearDataSerialBtn_, "清空数据 "); positionX_ = VIEW_DISTANCE_TO_LEFT_SIDE; SetUpButton(topPointBtn_, "最高点 "); positionX_ = topPointBtn_->GetX() + topPointBtn_->GetWidth() + g_blank; positionY_ = topPointBtn_->GetY(); SetUpButton(bottomPointBtn_, "最低点 "); positionX_ = bottomPointBtn_->GetX() + bottomPointBtn_->GetWidth() + g_blank; positionY_ = bottomPointBtn_->GetY(); SetUpButton(headPointBtn_, "最新点 "); } void UITestChartPolyline::UIKit_ChartPolyline_Test_EnableReverse_002() { reverseBtn_ = new UILabelButton(); positionX_ = VIEW_DISTANCE_TO_LEFT_SIDE; SetUpButton(reverseBtn_, "翻转 "); SetLastPos(reverseBtn_); } void UITestChartPolyline::UIKit_ChartPolyline_Test_SetGradientBottom_003() { gradientBottomBtn_ = new UILabelButton(); positionX_ = reverseBtn_->GetX() + reverseBtn_->GetWidth() + g_blank; positionY_ = reverseBtn_->GetY(); SetUpButton(gradientBottomBtn_, "填充底部位置 "); SetLastPos(gradientBottomBtn_); } namespace { const int16_t DATA_COUNT = 480; } /* ECG test data */ static int16_t g_ECGData[DATA_COUNT] = { 68, 70, 73, 83, 95, 107, 118, 127, 118, 103, 90, 77, 66, 61, 57, 58, 60, 61, 62, 62, 63, 64, 64, 65, 67, 69, 70, 71, 73, 75, 76, 78, 78, 79, 80, 80, 80, 80, 80, 80, 79, 78, 77, 76, 75, 73, 72, 71, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 71, 71, 71, 70, 70, 70, 70, 71, 73, 75, 78, 80, 81, 82, 82, 82, 80, 78, 76, 73, 71, 69, 69, 68, 68, 68, 68, 68, 70, 76, 88, 100, 111, 122, 126, 112, 98, 85, 73, 61, 58, 57, 59, 60, 61, 62, 62, 63, 64, 65, 66, 68, 69, 70, 72, 74, 76, 77, 78, 79, 79, 80, 80, 80, 80, 79, 79, 79, 78, 77, 76, 74, 73, 72, 71, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 72, 71, 71, 70, 70, 69, 70, 70, 72, 74, 76, 78, 80, 82, 82, 82, 81, 79, 77, 75, 72, 70, 69, 68, 68, 68, 68, 68, 69, 72, 80, 93, 104, 115, 126, 121, 106, 93, 80, 68, 59, 57, 58, 60, 61, 62, 62, 63, 63, 64, 65, 67, 68, 70, 71, 73, 75, 76, 77, 78, 79, 80, 80, 80, 80, 80, 79, 79, 78, 78, 76, 75, 74, 72, 71, 70, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 73, 73, 73, 73, 74, 74, 74, 74, 74, 75, 75, 75, 75, 75, 75, 75, 75, 75, 74, 74, 74, 74, 74, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 73, 72, 72, 71, 71, 70, 70, 69, 70, 71, 72, 75, 77, 79, 81, 82, 82, 82, 80, 79, 76, 74, 71, 70, 69, 68, 68, 68, 68, 69, 70, 75, 85, 97, 109, 120, 127, 115, 101, 88, 75, 64, 57, 56, 58, 60, 61, 62, 62, 63, 64, 65, 66, 67, 69, 71, 72, 74, 75, 77, 78, 79, 79, 80, 80, 80, 80, 80, 79, 79, 78, 77, 76, 74, 73, 72, 71, 70, 70, 70, 70, 70, 70, 70, 71, 71, 71, 71, 71, 71, 72, 72, 72, 72, 80, 93, 104, 115, 126, 121, 106, 93, 80, 68, 59, 57, 58, 60, 61, 62, 62, 63, 63, 64, 65, 67, 68, 70, 71, 73}; class ImageAnimatorCallbackDemo : public OHOS::AnimatorCallback { public: explicit ImageAnimatorCallbackDemo(UIChartDataSerial* serial) : times_(0), serial_(serial) {} ~ImageAnimatorCallbackDemo() {} virtual void Callback(UIView* view) { if (view == nullptr) { return; } if (!g_addPointsFlag) { return; /* Control the addition of points by button, and automate if commented out */ } if (times_++ != 6) { /* Add 10 points for every 6 ticks */ return; } times_ = 0; if (g_curSerialCount == 0) { view->Invalidate(); } Point pointArray1[10]; for (uint16_t i = 0; i < 10; i++) { // 10: array max index pointArray1[i].x = g_curSerialCount; pointArray1[i].y = g_ECGData[g_curArrayCount]; g_curSerialCount++; g_curArrayCount++; if (g_curArrayCount == DATA_COUNT) { g_curArrayCount = 0; } if (!g_secondScreenFlag) { serial_->AddPoints(&pointArray1[i], 1); } else { serial_->ModifyPoint(g_curSerialCount, pointArray1[i]); if (g_hidePointsFlag) { serial_->HidePoint(g_curSerialCount, 30); // 30: the number of points } } } if (g_curSerialCount > 454) { // 454: max serial count g_curSerialCount = 0; g_secondScreenFlag = true; } UIChart* chart = static_cast<UIChart*>(view); chart->RefreshChart(); g_addPointsFlag = false; } protected: int16_t times_; UIChartDataSerial* serial_; }; void UITestChartPolyline::UIKit_ChartPolyline_Test_AddPoints_004() { UIViewGroup* uiViewGroup = new UIViewGroup(); // 2: x-coordinate, half of screen width; 2: half of screen width; 470: screen height uiViewGroup->SetPosition(Screen::GetInstance().GetWidth() / 2, 0, Screen::GetInstance().GetWidth() / 2, 470); container_->Add(uiViewGroup); UILabel* label = new UILabel(); uiViewGroup->Add(label); label->SetPosition(TEXT_DISTANCE_TO_LEFT_SIDE, TEXT_DISTANCE_TO_TOP_SIDE, Screen::GetInstance().GetWidth() / 2 - TEXT_DISTANCE_TO_LEFT_SIDE, // 2: half of screen width; TITLE_LABEL_DEFAULT_HEIGHT); label->SetText("chart追加点、修改点、平滑化"); label->SetFont(DEFAULT_VECTOR_FONT_FILENAME, FONT_DEFAULT_SIZE); ECGChart_ = new UIChartPolyline(); // 454: new width, 250: new height ECGChart_->SetPosition(VIEW_DISTANCE_TO_LEFT_SIDE, VIEW_DISTANCE_TO_TOP_SIDE, 454, 250); uiViewGroup->Add(ECGChart_); SetLastPos(ECGChart_); ECGChart_->SetStyle(STYLE_LINE_WIDTH, 5); // 5: line width UIXAxis& xAxis = ECGChart_->GetXAxis(); UIYAxis& yAxis = ECGChart_->GetYAxis(); xAxis.SetDataRange(0, 454); // 454: maximum value xAxis.SetMarkNum(10); // 10: number of scales yAxis.SetDataRange(0, 200); // 200: maximum value ECGDataSerial_ = new UIChartDataSerial(); ECGDataSerial_->SetMaxDataCount(454); // 454: number of data points ECGDataSerial_->SetLineColor(Color::Red()); ECGDataSerial_->EnableHeadPoint(true); ECGChart_->AddDataSerial(ECGDataSerial_); ImageAnimatorCallbackDemo* imageAnimCallback = new ImageAnimatorCallbackDemo(ECGDataSerial_); ECGAnimator_ = new OHOS::Animator(imageAnimCallback, ECGChart_, 0, true); ECGAnimator_->Start(); addPointsBtn_ = new UILabelButton(); smoothBtn_ = new UILabelButton(); hidePointsBtn_ = new UILabelButton(); // 2: half of screen width positionX_ = Screen::GetInstance().GetWidth() / 2 + VIEW_DISTANCE_TO_LEFT_SIDE; positionY_ = lastY_ + 10; // 10: increase y-coordinate SetUpButton(addPointsBtn_, "添加点 "); positionX_ = addPointsBtn_->GetX() + addPointsBtn_->GetWidth() + g_blank; positionY_ = addPointsBtn_->GetY(); SetUpButton(smoothBtn_, "平滑化 "); positionX_ = smoothBtn_->GetX() + smoothBtn_->GetWidth() + g_blank; positionY_ = smoothBtn_->GetY(); SetUpButton(hidePointsBtn_, "隐藏点 "); } bool UITestChartPolyline::OnClick(UIView& view, const ClickEvent& event) { UIChartDataSerial::PointStyle pointStyle; pointStyle.fillColor = Color::White(); pointStyle.radius = 5; // 5: Inner radius pointStyle.strokeColor = Color::Red(); pointStyle.strokeWidth = 2; // 2: border width if (&view == addDataSerialBtn_) { if (curDataIndex_ >= DATA_NUM) { return true; } chart_->AddDataSerial(dataSerial_[curDataIndex_]); curDataIndex_++; chart_->Invalidate(); } else if (&view == deleteDataSerialBtn_) { if (curDataIndex_ <= 0) { return true; } chart_->DeleteDataSerial(dataSerial_[curDataIndex_ - 1]); curDataIndex_--; chart_->Invalidate(); } else if (&view == clearDataSerialBtn_) { chart_->ClearDataSerial(); curDataIndex_ = 0; chart_->Invalidate(); } else if (&view == topPointBtn_) { dataSerial_[0]->EnableTopPoint(true); pointStyle.strokeColor = Color::Red(); dataSerial_[0]->SetTopPointStyle(pointStyle); chart_->Invalidate(); } else if (&view == bottomPointBtn_) { dataSerial_[0]->EnableBottomPoint(true); pointStyle.strokeColor = Color::Blue(); dataSerial_[0]->SetBottomPointStyle(pointStyle); chart_->Invalidate(); } else if (&view == headPointBtn_) { dataSerial_[0]->EnableHeadPoint(true); pointStyle.strokeColor = Color::Yellow(); dataSerial_[0]->SetHeadPointStyle(pointStyle); chart_->Invalidate(); } else if (&view == reverseBtn_) { chart_->EnableReverse(true); chart_->Invalidate(); } else { ClickExpand(view, pointStyle); } return true; } bool UITestChartPolyline::ClickExpand(UIView& view, UIChartDataSerial::PointStyle pointStyle) { if (&view == gradientBottomBtn_) { chart_->SetGradientBottom(50); // 50: bottom of the filling range chart_->Invalidate(); } else if (&view == addPointsBtn_) { g_addPointsFlag = true; } else if (&view == smoothBtn_) { ECGDataSerial_->EnableSmooth(true); ECGChart_->Invalidate(); } else if (&view == hidePointsBtn_) { g_hidePointsFlag = true; } return true; } void UITestChartPolyline::SetUpButton(UILabelButton* btn, const char* title) { if (btn == nullptr) { return; } container_->Add(btn); btn->SetPosition(positionX_, positionY_, BUTTON_WIDHT2, BUTTON_HEIGHT2); positionY_ += btn->GetHeight() + 10; // 10: increase height btn->SetText(title); btn->SetFont(DEFAULT_VECTOR_FONT_FILENAME, BUTTON_LABEL_SIZE); btn->SetOnClickListener(this); btn->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_STYLE_BORDER_RADIUS_VALUE, UIButton::RELEASED); btn->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_STYLE_BORDER_RADIUS_VALUE, UIButton::PRESSED); btn->SetStyleForState(STYLE_BORDER_RADIUS, BUTTON_STYLE_BORDER_RADIUS_VALUE, UIButton::INACTIVE); btn->SetStyleForState(STYLE_BACKGROUND_COLOR, BUTTON_STYLE_BACKGROUND_COLOR_VALUE, UIButton::RELEASED); btn->SetStyleForState(STYLE_BACKGROUND_COLOR, BUTTON_STYLE_BACKGROUND_COLOR_VALUE, UIButton::PRESSED); btn->SetStyleForState(STYLE_BACKGROUND_COLOR, BUTTON_STYLE_BACKGROUND_COLOR_VALUE, UIButton::INACTIVE); container_->Invalidate(); } void UITestChartPolyline::SetLastPos(UIView* view) { if (view == nullptr) { return; } lastX_ = view->GetX(); lastY_ = view->GetY() + view->GetHeight(); } } // namespace OHOS
16,776
7,137
/* * Copyright (c) CERN 2013 * * Copyright (c) Members of the EMI Collaboration. 2011-2013 * See http://www.eu-emi.eu/partners for details on the copyright * holders. * * Licensed under the Apache License, Version 2.0 * See the LICENSE file for further information * */ /** @file PluginLoader.hh * @brief A helper class that loads a plugin * @author Fabrizio Furano * @date Oct 2010 */ #include "PluginLoader.hh" #include "SimpleDebug.hh" #include <dlfcn.h> #include <stdlib.h> PluginLoader::~PluginLoader() { if (libHandle) dlclose(libHandle); if (libPath) free((char *)libPath); } // Gets a pointer to the function that instantiates the // main class defined in the plugin. void *PluginLoader::getPlugin(const char *pname, int errok) { void *ep; // Open the plugin library if not already opened // if (!libHandle && !(libHandle = dlopen(libPath, RTLD_NOW | RTLD_GLOBAL))) { Error("PluginLoader::getPlugin", "Unable to open" << libPath << " - dlerror: " << dlerror()); return 0; } // Get the plugin object creator // if (!(ep = dlsym(libHandle, pname)) && !errok) { Error("PluginLoader::getPlugin", "Unable to find " << pname << " in " << pname << " - dlerror: " << dlerror()); return 0; } // All done // return ep; }
1,365
483
class Solution { public: int hist(vector<int> &h){ int ans=0; stack<int> s; int i=0; for(i=0;i<h.size();i++){ if(s.empty() || h[i]>=h[s.top()]){ s.push(i); } else{ while(!s.empty() && h[i]<h[s.top()]){ int top=s.top(); s.pop(); if(s.empty()){ ans = max(ans, h[top]*i); } else{ ans = max(ans, h[top]*(i-1-s.top())); } } s.push(i); } } while(!s.empty()){ int top=s.top(); s.pop(); if(s.empty()){ ans = max(ans, h[top]*i); } else{ ans = max(ans, h[top]*(i-1-s.top())); } } return ans; } int maximalRectangle(vector<vector<char>>& m) { if(m.size()==0 || m[0].size()==0) return 0; vector<vector<int>> v(m.size(), vector<int> (m[0].size())); for(int i=0;i<m.size();i++){ for(int j=0;j<m[0].size();j++){ v[i][j] = m[i][j]-'0'; } } for(int j=0;j<m[0].size();j++){ for(int i=1;i<m.size();i++){ if(v[i][j]!=0){ v[i][j]+=v[i-1][j]; } } } int ans=0; for(int i=0;i<m.size();i++){ ans = max(ans, hist(v[i])); } return ans; } };
1,651
564
#ifndef RED4EXT_STATIC_LIB #error Please define 'RED4EXT_STATIC_LIB' to compile this file. #endif #include <RED4ext/Scripting/Natives/ScriptGameInstance-inl.hpp>
163
64
// // editssn.cpp // // CEditSession2 // #include "private.h" #include "korimx.h" #include "editssn.h" #include "helpers.h" #define SafeAddRef(x) { if ((x)) { (x)->AddRef(); } } /* C E D I T S E S S I O N 2 */ /*------------------------------------------------------------------------------ Constructor ------------------------------------------------------------------------------*/ CEditSession2::CEditSession2(ITfContext *pic, CKorIMX *ptip, ESSTRUCT *pess, PFNESCALLBACK pfnCallback) { Assert(pic != NULL); Assert(ptip != NULL); Assert(pess != NULL); m_cRef = 1; m_pic = pic; m_ptip = ptip; m_ess = *pess; m_pfnCallback = pfnCallback; // add reference count in the struct SafeAddRef(m_pic); SafeAddRef(m_ptip); SafeAddRef(m_ess.ptim); SafeAddRef(m_ess.pRange); SafeAddRef(m_ess.pEnumRange); SafeAddRef(m_ess.pCandList); SafeAddRef(m_ess.pCandStr); } /* ~ C E D I T S E S S I O N 2 */ /*------------------------------------------------------------------------------ Destructor ------------------------------------------------------------------------------*/ CEditSession2::~CEditSession2( void ) { SafeRelease(m_pic); SafeRelease(m_ptip); SafeRelease(m_ess.ptim); SafeRelease(m_ess.pRange); SafeRelease(m_ess.pEnumRange); SafeRelease(m_ess.pCandList); SafeRelease(m_ess.pCandStr); } /* Q U E R Y I N T E R F A C E */ /*------------------------------------------------------------------------------ Query interface of object (IUnknown method) ------------------------------------------------------------------------------*/ STDAPI CEditSession2::QueryInterface(REFIID riid, void **ppvObj) { *ppvObj = NULL; if (IsEqualIID( riid, IID_IUnknown ) || IsEqualIID(riid, IID_ITfEditSession)) *ppvObj = SAFECAST(this, ITfEditSession*); if (*ppvObj) { AddRef(); return S_OK; } return E_NOINTERFACE; } /* A D D R E F */ /*------------------------------------------------------------------------------ Add reference count (IUnknown method) ------------------------------------------------------------------------------*/ STDAPI_(ULONG) CEditSession2::AddRef() { return ++m_cRef; } /* R E L E A S E */ /*------------------------------------------------------------------------------ Release object (IUnknown method) ------------------------------------------------------------------------------*/ STDAPI_(ULONG) CEditSession2::Release() { long cr; cr = --m_cRef; Assert(cr >= 0); if (cr == 0) delete this; return cr; } /* E D I T S E S S I O N */ /*------------------------------------------------------------------------------ Callback function of edit session (ITfEditSession method) ------------------------------------------------------------------------------*/ STDAPI CEditSession2::DoEditSession(TfEditCookie ec) { return m_pfnCallback(ec, this); } /* I N V O K E */ /*------------------------------------------------------------------------------ ------------------------------------------------------------------------------*/ HRESULT CEditSession2::Invoke(DWORD dwFlag, HRESULT *phrSession) { HRESULT hr; DWORD dwFlagES = 0; if ((m_pic == NULL) || (m_ptip == NULL)) return E_FAIL; // read/readwrite flag switch (dwFlag & ES2_READWRITEMASK) { default: case ES2_READONLY: dwFlagES |= TF_ES_READ; break; case ES2_READWRITE: dwFlagES |= TF_ES_READWRITE; break; } // sync/async flag switch (dwFlag & ES2_SYNCMASK) { default: Assert(fFalse); // fall through case ES2_ASYNC: dwFlagES |= TF_ES_ASYNC; break; case ES2_SYNC: dwFlagES |= TF_ES_SYNC; break; case ES2_SYNCASYNC: dwFlagES |= TF_ES_ASYNCDONTCARE; break; } // invoke m_fProcessed = FALSE; hr = m_pic->RequestEditSession(m_ptip->GetTID(), this, dwFlagES, phrSession); // try ASYNC session when SYNC session failed // NOTE: KOJIW: // How can we know if the edit session has been processed synchronously? // Satori#2409 - do not invoke callback twice // if (!m_fProcessed && ((dwFlag & ES2_SYNCMASK) == ES2_SYNCASYNC)) { // hr = m_pic->EditSession( m_ptip->GetTID(), this, (dwFlagES & ~TF_ES_SYNC), phrSession ); // } return hr; }
4,773
1,615
#include <iostream> class Foo { public: int foo; }; class Bar { public: char bar; }; std::pair<Foo, Bar> f() { std::pair<Foo, Bar> result; auto& foo = result.first; auto& bar = result.second; // fill foo and bar... foo.foo = 0xFF; bar.bar = 'x'; return result; } int main(int argc, char** argv) { /* Structured bindings * A proposal for de-structuring initialization, that would allow writing auto [ x, y, z ] = expr; * where the type of expr was a tuple-like object, whose elements * would be bound to the variables x, y, and z (which this construct declares). * Tuple-like objects include std::tuple, std::pair, std::array, and aggregate structures. */ auto [foo, bar] = f(); std::cout << foo.foo << std::endl; std::cout << bar.bar << std::endl; return 0; }
861
291
//+------------------------------------------------------------------------- // // Microsoft Windows // // Copyright (C) Microsoft Corporation, 1999 - 1999 // // File: DsplComp.cpp // //-------------------------------------------------------------------------- #include "stdafx.h" #include "displ2.h" #include "DsplMgr2.h" // local proto HRESULT ApplyOption (int nCommandID); extern HINSTANCE g_hinst; // in displ2.cpp HSCOPEITEM g_root_scope_item = 0; CComponent::CComponent() { m_pResultData = NULL; m_pHeaderCtrl = NULL; m_pComponentData = NULL; // the guy who created me m_IsTaskPad = 0; // TODO: should get this from the persisted data m_pConsole = NULL; m_TaskPadCount = 0; m_toggle = FALSE; m_toggleEntry = FALSE; } CComponent::~CComponent() { _ASSERT (m_pResultData == NULL); _ASSERT (m_pHeaderCtrl == NULL); } HRESULT CComponent::Initialize (LPCONSOLE lpConsole) { _ASSERT(lpConsole != NULL); _ASSERT (m_pResultData == NULL); // should be called only once... _ASSERT (m_pHeaderCtrl == NULL); // should be called only once... m_pConsole = lpConsole; // hang onto this HRESULT hresult = lpConsole->QueryInterface(IID_IResultData, (VOID**)&m_pResultData); _ASSERT (m_pResultData != NULL); hresult = lpConsole->QueryInterface(IID_IHeaderCtrl, (VOID**)&m_pHeaderCtrl); _ASSERT (m_pHeaderCtrl != NULL); if (m_pHeaderCtrl) // Give the console the header control interface pointer lpConsole->SetHeader(m_pHeaderCtrl); #ifdef TODO_ADD_THIS_LATER hr = lpConsole->QueryResultImageList(&m_pImageResult); _ASSERT(hr == S_OK); hr = lpConsole->QueryConsoleVerb(&m_pConsoleVerb); _ASSERT(hr == S_OK); // Load the bitmaps from the dll for the results pane m_hbmp16x16 = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_RESULT_16x16)); _ASSERT(m_hbmp16x16); m_hbmp32x32 = LoadBitmap(g_hinst, MAKEINTRESOURCE(IDB_RESULT_32x32)); _ASSERT(m_hbmp32x32); #endif return hresult; } HRESULT CComponent::Destroy (long cookie) { if (m_pResultData) { m_pResultData->Release (); m_pResultData = NULL; } if (m_pHeaderCtrl) { m_pHeaderCtrl->Release (); m_pHeaderCtrl = NULL; } // hmmm... I wonder if I have to release my IConsole pointer? it doesn't look like it.... return S_OK; } HRESULT CComponent::Notify (LPDATAOBJECT lpDataObject, MMC_NOTIFY_TYPE event, long arg, long param) { switch (event) { case MMCN_SHOW: return OnShow (lpDataObject, arg, param); case MMCN_ADD_IMAGES: return OnAddImages (lpDataObject, arg, param); case MMCN_DBLCLICK: return OnDblClick (lpDataObject, arg, param); case MMCN_SELECT: // return OnSelect (lpDataObject, arg, param); break; case MMCN_REFRESH: // return OnRefresh (lpDataObject, arg, param); case MMCN_VIEW_CHANGE: case MMCN_CLICK: case MMCN_BTN_CLICK: case MMCN_ACTIVATE: case MMCN_MINIMIZED: break; case MMCN_LISTPAD: return OnListPad (lpDataObject, arg, param); case MMCN_RESTORE_VIEW: return OnRestoreView (lpDataObject, arg, param); default: return E_UNEXPECTED; } return S_OK; } HRESULT CComponent::GetResultViewType (long cookie, LPOLESTR* ppViewType, long* pViewOptions) { *ppViewType = NULL; *pViewOptions = MMC_VIEW_OPTIONS_NONE; // only allow taskpad when root is selected if (cookie != 0) m_IsTaskPad = 0; // special case for taskpads only if (m_IsTaskPad != 0) { USES_CONVERSION; TCHAR szBuffer[MAX_PATH*2]; // a little extra lstrcpy (szBuffer, _T("res://")); TCHAR * temp = szBuffer + lstrlen(szBuffer); switch (m_IsTaskPad) { case IDM_CUSTOMPAD: // get "res://"-type string for custom taskpad ::GetModuleFileName (g_hinst, temp, MAX_PATH); lstrcat (szBuffer, _T("/default.htm")); break; case IDM_TASKPAD: // get "res://"-type string for custom taskpad ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/default.htm")); break; case IDM_TASKPAD_WALLPAPER_OPTIONS: // get "res://"-type string for custom taskpad ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/default.htm#wallpaper_options")); break; case IDM_TASKPAD_LISTVIEW: // get "res://"-type string for custom taskpad // ::GetModuleFileName (g_hinst, temp, MAX_PATH); // lstrcat (szBuffer, _T("/listview.htm")); ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/horizontal.htm")); break; case IDM_DEFAULT_LISTVIEW: // get "res://"-type string for custom taskpad ::GetModuleFileName (NULL, temp, MAX_PATH); lstrcat (szBuffer, _T("/listpad.htm")); break; default: _ASSERT (0); return S_FALSE; } // return URL *ppViewType = CoTaskDupString (T2OLE(szBuffer)); if (!*ppViewType) return E_OUTOFMEMORY; // or S_FALSE ??? return S_OK; } return S_FALSE; // false for default } HRESULT CComponent::QueryDataObject (long cookie, DATA_OBJECT_TYPES type, LPDATAOBJECT* ppDataObject) { _ASSERT (ppDataObject != NULL); CDataObject *pdo = new CDataObject (cookie, type); *ppDataObject = pdo; if (!pdo) return E_OUTOFMEMORY; return S_OK; } HRESULT CComponent::GetDisplayInfo (RESULTDATAITEM* prdi) { _ASSERT(prdi != NULL); if (prdi) { // Provide strings for scope tree items if (prdi->bScopeItem == TRUE) { if (prdi->mask & RDI_STR) { if (prdi->nCol == 0) { switch (prdi->lParam) { case DISPLAY_MANAGER_WALLPAPER: if (m_toggle == FALSE) prdi->str = (LPOLESTR)L"Wallpaper"; else prdi->str = (LPOLESTR)L"RenamedWallpaper"; break; case DISPLAY_MANAGER_PATTERN: prdi->str = (LPOLESTR)L"Pattern"; break; case DISPLAY_MANAGER_PATTERN_CHILD: prdi->str = (LPOLESTR)L"Pattern child"; break; default: prdi->str = (LPOLESTR)L"Hey! You shouldn't see this!"; break; } } else if (prdi->nCol == 1) prdi->str = (LPOLESTR)L"Display Option"; else prdi->str = (LPOLESTR)L"Error:Should not see this!"; } if (prdi->mask & RDI_IMAGE) prdi->nImage = 0; } else { // listpad uses lparam on -1, anything else is wallpaper if (prdi->lParam == -1) { if (prdi->mask & RDI_STR) if (m_toggleEntry == FALSE) prdi->str = (LPOLESTR)L"here's a listpad entry"; else prdi->str = (LPOLESTR)L"Changed listpad entry"; if (prdi->mask & RDI_IMAGE) prdi->nImage = 0; } else { lParamWallpaper * lpwp = NULL; if (prdi->lParam) lpwp = (lParamWallpaper *)prdi->lParam; if (prdi->mask & RDI_STR) { if (prdi->nCol == 0) { if (lpwp && (!IsBadReadPtr (lpwp, sizeof (lParamWallpaper)))) prdi->str = lpwp->filename; else prdi->str = (LPOLESTR)L"hmm.... error"; } else if (prdi->nCol == 1) prdi->str = (LPOLESTR)L"result pane display name col 1"; else prdi->str = (LPOLESTR)L"Error:Should not see this!"; } if (prdi->mask & RDI_IMAGE) { switch (prdi->lParam) { case DISPLAY_MANAGER_WALLPAPER: case DISPLAY_MANAGER_PATTERN: case DISPLAY_MANAGER_PATTERN_CHILD: prdi->nImage = 0; break; default: prdi->nImage = 3; break; } } } } } return S_OK; } HRESULT CComponent::CompareObjects (LPDATAOBJECT lpDataObjectA, LPDATAOBJECT lpDataObjectB) { return E_NOTIMPL;} // private functions HRESULT CComponent::OnShow(LPDATAOBJECT pDataObject, long arg, long param) { USES_CONVERSION; CDataObject * pcdo = (CDataObject *)pDataObject; if (arg == 0) { // de-selecting: free up resources, if any if (pcdo->GetCookie() == DISPLAY_MANAGER_WALLPAPER) { // enumerate result data items RESULTDATAITEM rdi; ZeroMemory(&rdi, sizeof(rdi)); rdi.mask = RDI_PARAM | RDI_STATE; rdi.nIndex = -1; while (1) { if (m_pResultData->GetNextItem (&rdi) != S_OK) break; if (rdi.lParam) { lParamWallpaper * lpwp = (lParamWallpaper *)rdi.lParam; delete lpwp; } } m_pResultData->DeleteAllRsltItems (); } return S_OK; } // init column headers _ASSERT (m_pHeaderCtrl != NULL); m_pHeaderCtrl->InsertColumn (0, L"Name", 0, 120); if (m_pComponentData) { if (m_pResultData) // use large icons by default m_pResultData->SetViewMode (m_pComponentData->GetViewMode ()); } // add our stuff RESULTDATAITEM rdi; ZeroMemory(&rdi, sizeof(rdi)); rdi.mask = RDI_PARAM | RDI_STR | RDI_IMAGE; rdi.nImage = (int)MMC_CALLBACK; rdi.str = MMC_CALLBACK; if (pcdo->GetCookie () == DISPLAY_MANAGER_WALLPAPER) { // enumerate all .bmp files in "c:\winnt.40\" (windows directory) TCHAR path[MAX_PATH]; GetWindowsDirectory (path, MAX_PATH); lstrcat (path, _T("\\*.bmp")); int i = 0; // first do "(none)" lParamWallpaper * lpwp = new lParamWallpaper; wcscpy (lpwp->filename, L"(none)"); rdi.lParam = reinterpret_cast<LONG>(lpwp); rdi.nImage = i++; m_pResultData->InsertItem (&rdi); WIN32_FIND_DATA fd; ZeroMemory(&fd, sizeof(fd)); HANDLE hFind = FindFirstFile (path, &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) || (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ) continue; // files only // new a struct to hold info, and cast to lParam. lParamWallpaper * lpwp = new lParamWallpaper; wcscpy (lpwp->filename, T2OLE(fd.cFileName)); // rdi.str = lpwp->filename; rdi.lParam = reinterpret_cast<LONG>(lpwp); rdi.nImage = i++; m_pResultData->InsertItem (&rdi); } while (FindNextFile (hFind, &fd) == TRUE); FindClose(hFind); } } else { // DISPLAY_MANAGER_PATTERN ; // hard code a few things. } return S_OK; } #include <windowsx.h> inline long LongScanBytes (long bits) { bits += 31; bits /= 8; bits &= ~3; return bits; } void GetBitmaps (TCHAR * fn, HBITMAP * smallbm, HBITMAP * largebm) { *smallbm = *largebm = (HBITMAP)NULL; // in case of error // read bmp file into DIB DWORD dwRead; HANDLE hf = CreateFile (fn, GENERIC_READ, FILE_SHARE_READ, (LPSECURITY_ATTRIBUTES) NULL, OPEN_EXISTING, FILE_ATTRIBUTE_READONLY, (HANDLE) NULL); if (hf != (HANDLE)HFILE_ERROR) { BITMAPFILEHEADER bmfh; ReadFile(hf, &bmfh, sizeof(BITMAPFILEHEADER), &dwRead, (LPOVERLAPPED)NULL); BITMAPINFOHEADER bmih; ReadFile(hf, &bmih, sizeof(BITMAPINFOHEADER), &dwRead, (LPOVERLAPPED)NULL); // Allocate memory for the DIB DWORD dwSize = sizeof(BITMAPINFOHEADER); if (bmih.biBitCount*bmih.biPlanes <= 8) dwSize += (sizeof(RGBQUAD))*(1<<(bmih.biBitCount*bmih.biPlanes)); dwSize += bmih.biHeight*LongScanBytes (bmih.biWidth*(bmih.biBitCount*bmih.biPlanes)); BITMAPINFOHEADER * lpbmih = (BITMAPINFOHEADER *)GlobalAllocPtr(GHND, dwSize); if (lpbmih) { *lpbmih = bmih; RGBQUAD * rgbq = (RGBQUAD *)&lpbmih[1]; char * bits = (char *)rgbq; if (bmih.biBitCount*bmih.biPlanes <= 8) { ReadFile (hf, rgbq, ((1<<(bmih.biBitCount*bmih.biPlanes))*sizeof(RGBQUAD)), &dwRead, (LPOVERLAPPED) NULL); bits += dwRead; } SetFilePointer (hf, bmfh.bfOffBits, NULL, FILE_BEGIN); ReadFile (hf, bits, dwSize - (bits - (char *)lpbmih), &dwRead, (LPOVERLAPPED) NULL); // we should now have a decent DIB HWND hwnd = GetDesktopWindow (); HDC hdc = GetDC (hwnd); HDC hcompdc = CreateCompatibleDC (hdc); // SetStretchBltMode (hcompdc, COLORONCOLOR); // SetStretchBltMode (hcompdc, WHITEONBLACK); SetStretchBltMode (hcompdc, HALFTONE); HGDIOBJ hold; // *smallbm = CreateCompatibleBitmap (hcompdc, 16, 16); *smallbm = CreateCompatibleBitmap (hdc, 16, 16); if (*smallbm) { hold = SelectObject (hcompdc, (HGDIOBJ)(*smallbm)); StretchDIBits (hcompdc, // handle of device context 0, 0, 16, 16, 0, 0, lpbmih->biWidth, lpbmih->biHeight, (CONST VOID *)bits, (CONST BITMAPINFO *)lpbmih, DIB_RGB_COLORS, // usage SRCCOPY // raster operation code ); SelectObject (hcompdc, hold); } // *largebm = CreateCompatibleBitmap (hcompdc, 32, 32); *largebm = CreateCompatibleBitmap (hdc, 32, 32); if (*largebm) { // testing /* HDC nullDC = GetDC (NULL); hold = SelectObject (nullDC, (HGDIOBJ)*largebm); StretchDIBits (nullDC, // handle of device context 0, 0, lpbmih->biWidth, lpbmih->biHeight, 0, 0, lpbmih->biWidth, lpbmih->biHeight, (CONST VOID *)bits, (CONST BITMAPINFO *)lpbmih, DIB_RGB_COLORS, // usage SRCCOPY // raster operation code ); SelectObject (hdc, hold); ReleaseDC (NULL, nullDC); */ // testing hold = SelectObject (hcompdc, (HGDIOBJ)*largebm); StretchDIBits (hcompdc, // handle of device context 0, 0, 32, 32, 0, 0, lpbmih->biWidth, lpbmih->biHeight, (CONST VOID *)bits, (CONST BITMAPINFO *)lpbmih, DIB_RGB_COLORS, // usage SRCCOPY // raster operation code ); SelectObject (hcompdc, hold); } DeleteDC (hcompdc); ReleaseDC (hwnd, hdc); GlobalFreePtr (lpbmih); } CloseHandle(hf); } } HRESULT CComponent::OnAddImages (LPDATAOBJECT pDataObject, long arg, long param) { IImageList * pImageList = (IImageList *)arg; HSCOPEITEM hsi = (HSCOPEITEM)param; _ASSERT (pImageList != NULL); CDataObject * cdo = (CDataObject *)pDataObject; if (cdo->GetCookie () != DISPLAY_MANAGER_WALLPAPER) { if (cdo->GetCookie () == 0) { g_root_scope_item = hsi; if (cdo->GetType () == CCT_RESULT) { // add a custom image HBITMAP hbmSmall, hbmLarge; GetBitmaps (_T("c:\\winnt\\dax.bmp"), &hbmSmall, &hbmLarge); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, 3, RGB(1, 0, 254)); DeleteObject (hbmSmall); DeleteObject (hbmLarge); } } return S_OK; // TODO: for now } // create HBITMAPs from bmp files int i = 0; // create some invisible bitmaps { BYTE bits[] = { 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255}; HBITMAP hbmSmall = CreateBitmap (16, 16, 1, 1, (CONST VOID *)bits); HBITMAP hbmLarge = CreateBitmap (32, 32, 1, 1, (CONST VOID *)bits); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, i++, RGB(1, 0, 254)); DeleteObject (hbmSmall); DeleteObject (hbmLarge); } TCHAR path[MAX_PATH]; GetWindowsDirectory (path, MAX_PATH); TCHAR * pfqfn = path + lstrlen(path) + 1; lstrcat (path, _T("\\*.bmp")); WIN32_FIND_DATA fd; ZeroMemory(&fd, sizeof(fd)); HANDLE hFind = FindFirstFile (path, &fd); if (hFind != INVALID_HANDLE_VALUE) { do { if ((fd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) || (fd.dwFileAttributes & FILE_ATTRIBUTE_SYSTEM) || (fd.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) ) continue; // files only lstrcpy (pfqfn, fd.cFileName); HBITMAP hbmSmall, hbmLarge; GetBitmaps (path, &hbmSmall, &hbmLarge); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, i++, RGB(1, 0, 254)); DeleteObject (hbmSmall); DeleteObject (hbmLarge); } while (FindNextFile (hFind, &fd) == TRUE); FindClose(hFind); } return S_OK; } #ifdef TODO_FIGURE_THIS_OUT HRESULT CComponent::OnSelect(LPDATAOBJECT pDataObject, long arg, long param) { if (!HIWORD(arg)) // being de-selected return S_OK; // don't care about this if (LOWORD(arg)) // in scope pane return S_OK; // don't care about this, either CDataObject *cdo = (CDataObject *)pDataObject; if (cdo->GetCookie() != DISPLAY_MANAGER_WALLPAPER) return S_OK; // TODO: do patterns later // // Bail if we couldn't get the console verb interface, or if the // selected item is the root; // if (!m_pConsoleVerb || pdo->GetCookieType() == COOKIE_IS_ROOT) { return S_OK; } // // Use selections and set which verbs are allowed // if (bScope) { if (pdo->GetCookieType() == COOKIE_IS_STATUS) { hr = m_pConsoleVerb->SetVerbState(MMC_VERB_REFRESH, ENABLED, TRUE); _ASSERT(hr == S_OK); } } else { // // Selection is in the result pane // } return S_OK; } #endif HRESULT CComponent::OnDblClick(LPDATAOBJECT pDataObject, long arg, long param) {//see note in CComponent::Command, below !!! _ASSERT (pDataObject); _ASSERT (m_pResultData); // hmmm: no documentation on arg or param.... CDataObject *cdo = (CDataObject *)pDataObject; lParamWallpaper * lpwp = (lParamWallpaper *)cdo->GetCookie(); if (lpwp) if (!IsBadReadPtr (lpwp, sizeof (lParamWallpaper))) { USES_CONVERSION; SystemParametersInfo (SPI_SETDESKWALLPAPER, 0, (void *)OLE2T(lpwp->filename), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); } return S_OK; } HRESULT CComponent::OnListPad (LPDATAOBJECT pDataObject, long arg, long param) { if (arg == TRUE) { // attaching IImageList* pImageList = NULL; m_pConsole->QueryResultImageList (&pImageList); if (pImageList) { HBITMAP hbmSmall, hbmLarge; GetBitmaps (_T("c:\\winnt\\dax.bmp"), &hbmSmall, &hbmLarge); pImageList->ImageListSetStrip ((long *)hbmSmall, (long *)hbmLarge, 0, RGB(1, 0, 254)); pImageList->Release(); } // m_pResultData->SetViewMode (LVS_ICON); m_pResultData->SetViewMode (LVS_REPORT); m_pHeaderCtrl->InsertColumn (0, L"Name", 0, 170); // populate listview control via IResultData RESULTDATAITEM rdi; ZeroMemory(&rdi, sizeof(rdi)); rdi.mask = RDI_PARAM | RDI_STR | RDI_IMAGE; rdi.nImage = (int)MMC_CALLBACK; rdi.str = MMC_CALLBACK; rdi.lParam = -1; for (int i=0; i<11; i++) m_pResultData->InsertItem (&rdi); } return S_OK; } HRESULT CComponent::OnRestoreView (LPDATAOBJECT pDataObject, long arg, long param) { MMC_RESTORE_VIEW* pmrv = (MMC_RESTORE_VIEW*)arg; BOOL * pb = (BOOL *)param; _ASSERT (pmrv); _ASSERT (pb); // some versioning (not really necessary since this is the new rev.) if (pmrv->dwSize < sizeof(MMC_RESTORE_VIEW)) return E_FAIL; // version too old // maintain my internal state if (pmrv->pViewType) { USES_CONVERSION; // there are going to be two cases: // 1. custom html pages (res in my .dll) // 2. default html pages (res in mmc.exe) // get path to my .dll and compare to pViewType TCHAR szPath[MAX_PATH]; ::GetModuleFileName (g_hinst, szPath, MAX_PATH); if (wcsstr (pmrv->pViewType, T2OLE(szPath))) { // custom html if (wcsstr (pmrv->pViewType, L"/default.htm")) m_IsTaskPad = IDM_CUSTOMPAD; else if (wcsstr (pmrv->pViewType, L"/listview.htm")) m_IsTaskPad = IDM_TASKPAD_LISTVIEW; else { // this will happen when you can get to a taskpad by clicking // on a task, but there is no corresponding view menu option // to select. Therefore do something reasonable. // In my case, I can get to "wallpapr.htm" by either custom // or default routes (which is probably rather unusual). So, // I think I'll just leave the m_IsTaskPad value alone if // it's non-NULL, else pick one. if (m_IsTaskPad == 0) m_IsTaskPad = IDM_TASKPAD; } } else { // default html if (wcsstr (pmrv->pViewType, L"/default.htm#wallpaper_options")) m_IsTaskPad = IDM_TASKPAD_WALLPAPER_OPTIONS; else if (wcsstr (pmrv->pViewType, L"/default.htm")) m_IsTaskPad = IDM_TASKPAD; else if (wcsstr (pmrv->pViewType, L"/listpad.htm")) m_IsTaskPad = IDM_DEFAULT_LISTVIEW; else if (wcsstr (pmrv->pViewType, L"/horizontal.htm")) m_IsTaskPad = IDM_TASKPAD_LISTVIEW; else { _ASSERT (0 && "can't find MMC's resources"); return E_FAIL; } } } else m_IsTaskPad = 0; *pb = TRUE; // I'm handling the new history notify return S_OK; } // IExtendContextMenu HRESULT CComponent::AddMenuItems (LPDATAOBJECT pDataObject, LPCONTEXTMENUCALLBACK pContextMenuCallback, long *pInsertionAllowed) { CDataObject * cdo = (CDataObject *)pDataObject; switch (cdo->GetCookie ()) { case DISPLAY_MANAGER_WALLPAPER: case DISPLAY_MANAGER_PATTERN: return S_OK; case 0: // root // this is when they pull down the view menu if (*pInsertionAllowed & CCM_INSERTIONALLOWED_VIEW) { // add my taskpads and delete thingy CONTEXTMENUITEM m[] = { {L"Custom TaskPad", L"Custom TaskPad", IDM_CUSTOMPAD, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Default TaskPad", L"Default TaskPad", IDM_TASKPAD, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Wallpaper Options TaskPad", L"Wallpaper Options TaskPad", IDM_TASKPAD_WALLPAPER_OPTIONS, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Horizontal ListView", L"ListView TaskPad", IDM_TASKPAD_LISTVIEW, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Default ListPad", L"Default ListPad", IDM_DEFAULT_LISTVIEW, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"DeleteRootChildren", L"just testing", IDM_DELETECHILDREN, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"RenameRoot", L"just testing", IDM_RENAMEROOT, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"RenameWallPaperNode",L"just testing", IDM_RENAMEWALL, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"ChangeIcon", L"just testing", IDM_CHANGEICON, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Pre-Load", L"just testing", IDM_PRELOAD, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0}, {L"Test IConsoleVerb", L"just testing", IDM_CONSOLEVERB, CCM_INSERTIONPOINTID_PRIMARY_VIEW, 0, 0} }; if (m_IsTaskPad == IDM_CUSTOMPAD) m[0].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_TASKPAD) m[1].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_TASKPAD_WALLPAPER_OPTIONS) m[2].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_TASKPAD_LISTVIEW) m[3].fFlags = MF_CHECKED; if (m_IsTaskPad == IDM_DEFAULT_LISTVIEW) m[4].fFlags = MF_CHECKED; if (m_pComponentData->GetPreload() == TRUE) m[9].fFlags = MF_CHECKED; pContextMenuCallback->AddItem (&m[0]); pContextMenuCallback->AddItem (&m[1]); pContextMenuCallback->AddItem (&m[2]); pContextMenuCallback->AddItem (&m[3]); pContextMenuCallback->AddItem (&m[4]); pContextMenuCallback->AddItem (&m[5]); pContextMenuCallback->AddItem (&m[6]); pContextMenuCallback->AddItem (&m[7]); pContextMenuCallback->AddItem (&m[8]); pContextMenuCallback->AddItem (&m[9]); return pContextMenuCallback->AddItem (&m[10]); } return S_OK; default: break; } // add to context menu, only if in result pane: // this is when they right-click on the result pane. if (cdo->GetType() == CCT_RESULT) { CONTEXTMENUITEM cmi; cmi.strName = L"Center"; cmi.strStatusBarText = L"Center Desktop Wallpaper"; cmi.lCommandID = IDM_CENTER; cmi.lInsertionPointID = CCM_INSERTIONPOINTID_PRIMARY_TOP; cmi.fFlags = 0; cmi.fSpecialFlags = CCM_SPECIAL_DEFAULT_ITEM; pContextMenuCallback->AddItem (&cmi); cmi.strName = L"Tile"; cmi.strStatusBarText = L"Tile Desktop Wallpaper"; cmi.lCommandID = IDM_TILE; cmi.lInsertionPointID = CCM_INSERTIONPOINTID_PRIMARY_TOP; cmi.fFlags = 0; cmi.fSpecialFlags = 0; // CCM_SPECIAL_DEFAULT_ITEM; pContextMenuCallback->AddItem (&cmi); cmi.strName = L"Stretch"; cmi.strStatusBarText = L"Stretch Desktop Wallpaper"; cmi.lCommandID = IDM_STRETCH; cmi.lInsertionPointID = CCM_INSERTIONPOINTID_PRIMARY_TOP; cmi.fFlags = 0; cmi.fSpecialFlags = 0; // CCM_SPECIAL_DEFAULT_ITEM; pContextMenuCallback->AddItem (&cmi); } return S_OK; } HRESULT CComponent::Command (long nCommandID, LPDATAOBJECT pDataObject) { m_IsTaskPad = 0; CDataObject * cdo = reinterpret_cast<CDataObject *>(pDataObject); switch (nCommandID) { case IDM_TILE: case IDM_CENTER: case IDM_STRETCH: // write registry key: { HKEY hkey; HRESULT r = RegOpenKeyEx (HKEY_CURRENT_USER, _T("Control Panel\\Desktop"), 0, KEY_ALL_ACCESS, &hkey); if (r == ERROR_SUCCESS) { // write new value(s) DWORD dwType = REG_SZ; TCHAR szBuffer[2]; // first do "TileWallpaper" if (nCommandID == IDM_TILE) lstrcpy (szBuffer, _T("1")); else lstrcpy (szBuffer, _T("0")); DWORD dwCount = sizeof(TCHAR)*(1+lstrlen (szBuffer)); r = RegSetValueEx (hkey, (LPCTSTR)_T("TileWallpaper"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // then do "WallpaperStyle" if (nCommandID == IDM_STRETCH) lstrcpy (szBuffer, _T("2")); else lstrcpy (szBuffer, _T("0")); r = RegSetValueEx (hkey, (LPCTSTR)_T("WallpaperStyle"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // close up shop RegCloseKey(hkey); _ASSERT(r == ERROR_SUCCESS); /* [HKEY_CURRENT_USER\Control Panel\Desktop] "CoolSwitch"="1" "CoolSwitchRows"="3" "CoolSwitchColumns"="7" "CursorBlinkRate"="530" "ScreenSaveTimeOut"="900" "ScreenSaveActive"="0" "ScreenSaverIsSecure"="0" "Pattern"="(None)" "Wallpaper"="C:\\WINNT\\dax.bmp" "TileWallpaper"="0" "GridGranularity"="0" "IconSpacing"="75" "IconTitleWrap"="1" "IconTitleFaceName"="MS Sans Serif" "IconTitleSize"="9" "IconTitleStyle"="0" "DragFullWindows"="1" "HungAppTimeout"="5000" "WaitToKillAppTimeout"="20000" "AutoEndTasks"="0" "FontSmoothing"="0" "MenuShowDelay"="400" "DragHeight"="2" "DragWidth"="2" "WheelScrollLines"="3" "WallpaperStyle"="0" */ } } break; case IDM_TASKPAD: case IDM_CUSTOMPAD: case IDM_TASKPAD_LISTVIEW: case IDM_DEFAULT_LISTVIEW: case IDM_TASKPAD_WALLPAPER_OPTIONS: if (cdo->GetCookie() == 0) { HSCOPEITEM root = m_pComponentData->GetRoot(); if (root) { // we should now be ready for taskpad "view" m_IsTaskPad = nCommandID; // set before selecting node // cause new view to be "created" m_pConsole->SelectScopeItem (root); } } return S_OK; case IDM_DELETECHILDREN: if (g_root_scope_item != 0) m_pComponentData->myDeleteItem (g_root_scope_item, TRUE); return S_OK; case IDM_RENAMEROOT: if (g_root_scope_item != 0) m_pComponentData->myRenameItem (g_root_scope_item, L"Yippee!"); return S_OK; case IDM_RENAMEWALL: if (m_toggle) m_toggle = FALSE; else m_toggle = TRUE; m_pComponentData->myRenameItem (m_pComponentData->GetWallPaperNode(), NULL); return S_OK; case IDM_CHANGEICON: m_pComponentData->myChangeIcon (); return S_OK; case IDM_PRELOAD: m_pComponentData->myPreLoad(); return S_OK; case IDM_CONSOLEVERB: TestConsoleVerb(); return S_OK; default: return E_UNEXPECTED; } return OnDblClick (pDataObject, NULL, NULL); // note what I'm passing! } long CComponent::GetViewMode () { long vm = LVS_ICON; if (m_pResultData) m_pResultData->GetViewMode (&vm); return vm; } /////////////////////////////////////////////////////////////////////////////// // IExtendTaskPad interface members HRESULT CComponent::TaskNotify (IDataObject * pdo, VARIANT * pvarg, VARIANT * pvparam) { if (pvarg->vt == VT_BSTR) { USES_CONVERSION; OLECHAR * path = pvarg->bstrVal; // replace any '*' with ' ': see enumtask.cpp // hash mechanism can't handle spaces, and // filenames can't have '*'s, so this works out ok. OLECHAR * temp; while (temp = wcschr (path, '*')) *temp = ' '; // now go do it! SystemParametersInfo (SPI_SETDESKWALLPAPER, 0, (void *)OLE2T(path), SPIF_UPDATEINIFILE | SPIF_SENDWININICHANGE); return S_OK; } if (pvarg->vt == VT_I4) { switch (pvarg->lVal) { case 1: if (m_pComponentData->GetWallPaperNode () != (HSCOPEITEM)0) { _ASSERT (m_pConsole != NULL); m_pConsole->SelectScopeItem (m_pComponentData->GetWallPaperNode()); return S_OK; } break; case 2: // Center return ApplyOption (IDM_CENTER); case 3: // Tile return ApplyOption (IDM_TILE); case 4: // Stretch return ApplyOption (IDM_STRETCH); case -1: if (m_toggleEntry == FALSE) m_toggleEntry = TRUE; else m_toggleEntry = FALSE; // empty and repopulate listpad m_pResultData->DeleteAllRsltItems(); m_pHeaderCtrl->DeleteColumn (0); OnListPad (NULL, TRUE, 0); return S_OK; } } ::MessageBox (NULL, _T("unrecognized task notification"), _T("Display Manager"), MB_OK); return S_OK; } HRESULT CComponent::GetTitle (LPOLESTR szGroup, LPOLESTR * pszTitle) { *pszTitle = CoTaskDupString (L"Display Manager TaskPad"); if (!pszTitle) return E_OUTOFMEMORY; return S_OK; } HRESULT CComponent::GetDescriptiveText (LPOLESTR szGroup, LPOLESTR * pszTitle) { *pszTitle = CoTaskDupString (L"Bill's Handy-Dandy Display Manager TaskPad Sample"); if (!pszTitle) return E_OUTOFMEMORY; return S_OK; } HRESULT CComponent::GetBackground (LPOLESTR szGroup, MMC_TASK_DISPLAY_OBJECT * pdo) { USES_CONVERSION; if(NULL==szGroup) return E_FAIL; if (szGroup[0] == 0) { // bitmap case pdo->eDisplayType = MMC_TASK_DISPLAY_TYPE_BITMAP; MMC_TASK_DISPLAY_BITMAP *pdb = &pdo->uBitmap; // fill out bitmap URL TCHAR szBuffer[MAX_PATH*2]; // that should be enough _tcscpy (szBuffer, _T("res://")); ::GetModuleFileName (g_hinst, szBuffer + _tcslen(szBuffer), MAX_PATH); _tcscat (szBuffer, _T("/img\\ntbanner.gif")); pdb->szMouseOverBitmap = CoTaskDupString (T2OLE(szBuffer)); if (pdb->szMouseOverBitmap) return S_OK; return E_OUTOFMEMORY; } else { // symbol case pdo->eDisplayType = MMC_TASK_DISPLAY_TYPE_SYMBOL; MMC_TASK_DISPLAY_SYMBOL *pds = &pdo->uSymbol; // fill out symbol stuff pds->szFontFamilyName = CoTaskDupString (L"Kingston"); // name of font family if (pds->szFontFamilyName) { TCHAR szBuffer[MAX_PATH*2]; // that should be enough _tcscpy (szBuffer, _T("res://")); ::GetModuleFileName (g_hinst, szBuffer + _tcslen(szBuffer), MAX_PATH); _tcscat (szBuffer, _T("/KINGSTON.eot")); pds->szURLtoEOT = CoTaskDupString (T2OLE(szBuffer)); // "res://"-type URL to EOT file if (pds->szURLtoEOT) { pds->szSymbolString = CoTaskDupString (T2OLE(_T("A<BR>BCDEFGHIJKLMNOPQRSTUVWXYZ"))); // 1 or more symbol characters if (pds->szSymbolString) return S_OK; CoTaskFreeString (pds->szURLtoEOT); } CoTaskFreeString (pds->szFontFamilyName); } return E_OUTOFMEMORY; } } HRESULT CComponent::EnumTasks (IDataObject * pdo, LPOLESTR szTaskGroup, IEnumTASK** ppEnumTASK) { HRESULT hresult = S_OK; CEnumTasks * pet = new CEnumTasks; if (!pet) hresult = E_OUTOFMEMORY; else { pet->AddRef (); // make sure release works properly on failure hresult = pet->Init (pdo, szTaskGroup); if (hresult == S_OK) hresult = pet->QueryInterface (IID_IEnumTASK, (void **)ppEnumTASK); pet->Release (); } return hresult; } HRESULT CComponent::GetListPadInfo (LPOLESTR szGroup, MMC_LISTPAD_INFO * pListPadInfo) { pListPadInfo->szTitle = CoTaskDupString (L"Display Manager ListPad Title"); pListPadInfo->szButtonText = CoTaskDupString (L"Change..."); pListPadInfo->nCommandID = -1; return S_OK; } HRESULT ApplyOption (int nCommandID) { switch (nCommandID) { case IDM_TILE: case IDM_CENTER: case IDM_STRETCH: // write registry key: { HKEY hkey; HRESULT r = RegOpenKeyEx (HKEY_CURRENT_USER, _T("Control Panel\\Desktop"), 0, KEY_ALL_ACCESS, &hkey); if (r == ERROR_SUCCESS) { // write new value(s) DWORD dwType = REG_SZ; TCHAR szBuffer[2]; // first do "TileWallpaper" if (nCommandID == IDM_TILE) lstrcpy (szBuffer, _T("1")); else lstrcpy (szBuffer, _T("0")); DWORD dwCount = sizeof(TCHAR)*(1+lstrlen (szBuffer)); r = RegSetValueEx (hkey, (LPCTSTR)_T("TileWallpaper"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // then do "WallpaperStyle" if (nCommandID == IDM_STRETCH) lstrcpy (szBuffer, _T("2")); else lstrcpy (szBuffer, _T("0")); r = RegSetValueEx (hkey, (LPCTSTR)_T("WallpaperStyle"), NULL, dwType, (CONST BYTE *)&szBuffer, dwCount); // close up shop RegCloseKey(hkey); _ASSERT(r == ERROR_SUCCESS); /* [HKEY_CURRENT_USER\Control Panel\Desktop] "CoolSwitch"="1" "CoolSwitchRows"="3" "CoolSwitchColumns"="7" "CursorBlinkRate"="530" "ScreenSaveTimeOut"="900" "ScreenSaveActive"="0" "ScreenSaverIsSecure"="0" "Pattern"="(None)" "Wallpaper"="C:\\WINNT\\dax.bmp" "TileWallpaper"="0" "GridGranularity"="0" "IconSpacing"="75" "IconTitleWrap"="1" "IconTitleFaceName"="MS Sans Serif" "IconTitleSize"="9" "IconTitleStyle"="0" "DragFullWindows"="1" "HungAppTimeout"="5000" "WaitToKillAppTimeout"="20000" "AutoEndTasks"="0" "FontSmoothing"="0" "MenuShowDelay"="400" "DragHeight"="2" "DragWidth"="2" "WheelScrollLines"="3" "WallpaperStyle"="0" */ } if (r == ERROR_SUCCESS) ::MessageBox (NULL, _T("Option set Successfully!"), _T("Display Manager"), MB_OK); return r; } default: break; } return S_FALSE; } void CComponent::TestConsoleVerb(void) { IConsoleVerb* pConsoleVerb = NULL; m_pConsole->QueryConsoleVerb (&pConsoleVerb); _ASSERT (pConsoleVerb != NULL); if (pConsoleVerb) { pConsoleVerb->SetVerbState (MMC_VERB_PASTE, ENABLED, TRUE); pConsoleVerb->Release(); } }
44,199
15,017
#include<bits/stdc++.h> using namespace std; // COPY LIST WITH RANDOM POINTER: class solution{ public: Node* copyRandomList(Node* head){ // CREATING NORMAL LINKED LIST THAT HAS A DATA FIELD AND ADDRESS FIELD: Node* curr=head; while(curr!=NULL){ Node* next=curr->next; curr->next=new Node(curr->val); curr->next->next=next; curr=next; } // CREATING LINKED LIST THAT HAS A RANDOM ADDRESS FIELD: curr=head; while(curr!=NULL){ if(curr->random!=NULL){ curr->next->random=curr->random->next; }else{ curr->next->random=NULL; } curr=curr->next->next; } // CREATING ANOTHER LINKED LIST: Node* newhead=new Node(0); Node* copycurr=newhead; curr=head; while(curr!=NULL){ copycurr->next=curr->next; curr->next=copycurr->next->next; curr=curr->next; copycurr=copycurr->next; } return newnode->next; } };
1,135
360
#include "n_class.h" bool Comp(const int &a,const int &b) { return a>b; } bool Branch::get_r_points_of_branch(vector<NeuronSWC> &r_points, NeuronTree &nt) { NeuronSWC tmp=end_point; r_points.push_back(end_point); while(tmp.n!=head_point.n) { tmp=nt.listNeuron[nt.hashNeuron.value(tmp.parent)]; r_points.push_back(tmp); } return true; } bool Branch::get_points_of_branch(vector<NeuronSWC> &points, NeuronTree &nt) { vector<NeuronSWC> r_points; this->get_r_points_of_branch(r_points,nt); while(!r_points.empty()) { NeuronSWC tmp=r_points.back(); r_points.pop_back(); points.push_back(tmp); } return true; } bool SwcTree::initialize(NeuronTree t) { nt.deepCopy(t); NeuronSWC ori; V3DLONG num_p=nt.listNeuron.size(); vector<vector<V3DLONG> > children=vector<vector<V3DLONG> >(num_p,vector<V3DLONG>()); for(V3DLONG i=0;i<num_p;++i) { V3DLONG par=nt.listNeuron[i].parent; if(par<0) { ori=nt.listNeuron[i]; continue; } children[nt.hashNeuron.value(par)].push_back(i); } vector<NeuronSWC> queue; queue.push_back(ori); //initial head_point,end_point,distance,length cout<<"initial head_point,end_point,distance,length"<<endl; while(!queue.empty()) { NeuronSWC tmp=queue.front(); queue.erase(queue.begin()); for(int i=0;i<children[nt.hashNeuron.value(tmp.n)].size();++i) { Branch branch; branch.head_point=tmp; NeuronSWC child=nt.listNeuron[children[nt.hashNeuron.value(branch.head_point.n)][i]]; branch.length+=distance_two_point(tmp,child); Angle near_point_angle = Angle(child.x-tmp.x,child.y-tmp.y,child.z-tmp.z); near_point_angle.norm_angle(); double sum_angle = 0; while(children[nt.hashNeuron.value(child.n)].size()==1) { NeuronSWC par=child; child=nt.listNeuron[children[nt.hashNeuron.value(par.n)][0]]; branch.length+=distance_two_point(par,child); Angle next_point_angle = Angle(child.x-par.x,child.y-par.y,child.z-par.z); next_point_angle.norm_angle(); sum_angle += acos(near_point_angle*next_point_angle); } if(children[nt.hashNeuron.value(child.n)].size()>=1) { queue.push_back(child); } branch.end_point=child; branch.distance=branch.get_distance(); branch.sum_angle = sum_angle; branchs.push_back(branch); } } //initial head_angle,end_angle cout<<"initial head_angle,end_angle"<<endl; for(int i=0;i<branchs.size();++i) { vector<NeuronSWC> points; branchs[i].get_points_of_branch(points,nt); double length=0; NeuronSWC par0=points[0]; for(int j=1;j<points.size();++j) { NeuronSWC child0=points[j]; length+=distance_two_point(par0,child0); if(length>5) { branchs[i].head_angle.x=child0.x-points[0].x; branchs[i].head_angle.y=child0.y-points[0].y; branchs[i].head_angle.z=child0.z-points[0].z; double d=norm_v(branchs[i].head_angle); branchs[i].head_angle.x/=d; branchs[i].head_angle.y/=d; branchs[i].head_angle.z/=d; break; } par0=child0; } if(length<=5) { branchs[i].head_angle.x=par0.x-points[0].x; branchs[i].head_angle.y=par0.y-points[0].y; branchs[i].head_angle.z=par0.z-points[0].z; double d=norm_v(branchs[i].head_angle); branchs[i].head_angle.x/=d; branchs[i].head_angle.y/=d; branchs[i].head_angle.z/=d; } length=0; points.clear(); branchs[i].get_r_points_of_branch(points,nt); NeuronSWC child1=points[0]; for(int j=1;j<points.size();++j) { NeuronSWC par1=points[j]; length+=distance_two_point(par1,child1); if(length>5) { branchs[i].end_angle.x=par1.x-points[0].x; branchs[i].end_angle.y=par1.y-points[0].y; branchs[i].end_angle.z=par1.z-points[0].z; double d=norm_v(branchs[i].end_angle); branchs[i].end_angle.x/=d; branchs[i].end_angle.y/=d; branchs[i].end_angle.z/=d; break; } child1=par1; } if(length<=5) { branchs[i].end_angle.x=child1.x-points[0].x; branchs[i].end_angle.y=child1.y-points[0].y; branchs[i].end_angle.z=child1.z-points[0].z; double d=norm_v(branchs[i].end_angle); branchs[i].end_angle.x/=d; branchs[i].end_angle.y/=d; branchs[i].end_angle.z/=d; } } //initial parent cout<<"initial parent"<<endl; for(int i=0;i<branchs.size();++i) { if(branchs[i].head_point.parent<0) { branchs[i].parent=0; } else { for(int j=0;j<branchs.size();++j) { if(branchs[i].head_point==branchs[j].end_point) { branchs[i].parent=&branchs[j]; } } } } //initial level for(int i=0;i<branchs.size();++i) { Branch* tmp; tmp=&branchs[i]; int level=0; while(tmp->parent!=0) { level++; tmp=tmp->parent; } branchs[i].level=level; } return true; } bool SwcTree::get_level_index(vector<int> &level_index,int level) { for(int i=0;i<branchs.size();++i) { if(branchs[i].level==level) { level_index.push_back(i); } } return true; } bool SwcTree::get_points_of_branchs(vector<Branch> &b,vector<NeuronSWC> &points,NeuronTree &ntb) { for(int i=0;i<(b.size()-1);++i) { b[i].get_points_of_branch(points,ntb); points.pop_back(); } b[(b.size()-1)].get_points_of_branch(points,ntb); return true; } int SwcTree::get_max_level() { int max_level; for(int i=0;i<branchs.size();++i) { max_level=(max_level>branchs[i].level)?max_level:branchs[i].level; } return max_level; } bool SwcTree::get_bifurcation_image(QString dir, int resolutionX, int resolutionY, int resolutionZ, bool all, QString braindir, V3DPluginCallback2 &callback) { int num_b = branchs.size(); map<Branch,int> mapbranch; for(int i=0; i<num_b ;++i) { mapbranch[branchs[i]] = i; } vector<vector<int> > branch_children=vector<vector<int> >(num_b,vector<int>()); for(int i=0; i<num_b; ++i) { if(branchs[i].parent==0) continue; branch_children[mapbranch[*(branchs[i].parent)]].push_back(i); } vector<int> queue; get_level_index(queue,0); int num = 0; while(!queue.empty()){ int bi = queue.front();//branch_index queue.erase(queue.begin()); if(branch_children[bi].size()>0){ int level = branchs[bi].level; num++; if(all || branchs[bi].level>2){ QString filename = dir+"/b_level"+QString::number(level) +"_x"+QString::number(branchs[bi].end_point.x) +"_y"+QString::number(branchs[bi].end_point.y) +"_z"+QString::number(branchs[bi].end_point.z)+QString::number(num)+".tif"; get3DImageBasedPoint(filename.toStdString().c_str(),branchs[bi].end_point,resolutionX,resolutionY,resolutionZ,braindir,callback); } for(int i=0; i<branch_children[bi].size(); ++i){ queue.push_back(branch_children[bi][i]); } } } return true; } bool SwcTree::get_un_bifurcation_image(QString dir, int resolutionX, int resolutionY, int resolutionZ, bool all, QString braindir, V3DPluginCallback2 &callback) { const int distance_to_bifurcation = 20; int num_b = branchs.size(); int num = 0; for(int i=0; i<num_b; ++i){ if(all||branchs[i].length<200){ if(branchs[i].length>2*distance_to_bifurcation){ vector<NeuronSWC> points; branchs[i].get_points_of_branch(points,nt); int level = branchs[i].level; int num_p = points.size(); if(num_p>10){ int k; if(all) k = 1; else k = 3; for(int j=5; j<num_p-5; j+=k){ if(distance_two_point(points[j],points[0])>distance_to_bifurcation && distance_two_point(points[j],points[num_p-1])>distance_to_bifurcation) { num++; QString filename = dir+"/level"+QString::number(level)+"_j"+QString::number(j)+"_" +QString::number(num)+"_x"+QString::number(points[j].x) +"_y"+QString::number(points[j].y)+"_z"+QString::number(points[j].z)+".tif"; get3DImageBasedPoint(filename.toStdString().c_str(),points[j],resolutionX,resolutionY,resolutionZ,braindir,callback); } } } } } } return true; }
9,760
3,494
// Copyright (c) 2014-2016 Barobo, Inc. // // 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 UTIL_ANY_HPP #define UTIL_ANY_HPP #include <utility> namespace util { template <class T> constexpr bool any (T&& x) { return std::forward<T>(x); } template <class T, class... Ts> constexpr bool any (T&& x, Ts&&... xs) { return std::forward<T>(x) || any(std::forward<Ts>(xs)...); } } // namespace util #endif
527
217
// jsbind // Copyright (c) 2019 Chobolabs Inc. // http://www.chobolabs.com/ // // Distributed under the MIT Software License // See accompanying file LICENSE.txt or copy at // http://opensource.org/licenses/MIT // #pragma once #include "global.hpp" #include "jsbind/common/wrapped_class.hpp" #include <string> #include <type_traits> #include <climits> namespace jsbind { class local; namespace internal { template <typename T, typename Enable = void> // enable used by enable_if specializations struct convert; template <> struct convert<std::string> { using from_type = std::string; using to_type = v8::Local<v8::String>; static from_type from_v8(v8::Local<v8::Value> val) { const v8::String::Utf8Value str(isolate, val); return from_type(*str, str.length()); } static to_type to_v8(const from_type& val) { return v8::String::NewFromUtf8(isolate, val.c_str(), v8::String::kNormalString, int(val.length())); } }; template <> struct convert<const char*> { using from_type = const char*; using to_type = v8::Local<v8::String>; // raw pointer converion not supported // it could be supported but emscripten doesn't do it, so we'll follow static from_type from_v8(v8::Local<v8::Value> val) = delete; static to_type to_v8(const char* val) { return v8::String::NewFromUtf8(isolate, val); } }; template<> struct convert<bool> { using from_type = bool; using to_type = v8::Local<v8::Boolean>; static from_type from_v8(v8::Local<v8::Value> value) { return value->ToBoolean(isolate)->Value(); } static to_type to_v8(bool value) { return v8::Boolean::New(isolate, value); } }; template<typename T> struct convert<T, typename std::enable_if<std::is_integral<T>::value>::type> { using from_type = T; using to_type = v8::Local<v8::Number>; enum { bits = sizeof(T) * CHAR_BIT, is_signed = std::is_signed<T>::value }; static from_type from_v8(v8::Local<v8::Value> value) { auto& v8ctx = *reinterpret_cast<v8::Local<v8::Context>*>(&internal::ctx.v8ctx); if (bits <= 32) { if (is_signed) { return static_cast<T>(value->Int32Value(v8ctx).FromMaybe(0)); } else { return static_cast<T>(value->Uint32Value(v8ctx).FromMaybe(0)); } } else { return static_cast<T>(value->IntegerValue(v8ctx).FromMaybe(0)); } } static to_type to_v8(from_type value) { if (bits <= 32) { if (is_signed) { return v8::Integer::New(isolate, static_cast<int32_t>(value)); } else { return v8::Integer::NewFromUnsigned(isolate, static_cast<uint32_t>(value)); } } else { // check value < (1<<57) to fit in double? return v8::Number::New(isolate, static_cast<double>(value)); } } }; template<typename T> struct convert<T, typename std::enable_if<std::is_floating_point<T>::value>::type> { using from_type = T; using to_type = v8::Local<v8::Number>; static from_type from_v8(v8::Local<v8::Value> value) { auto& v8ctx = *reinterpret_cast<v8::Local<v8::Context>*>(&internal::ctx.v8ctx); return static_cast<T>(value->NumberValue(v8ctx).FromMaybe(0)); } static to_type to_v8(T value) { return v8::Number::New(isolate, value); } }; template <> struct convert<void> { using from_type = void; using to_type = v8::Local<v8::Primitive>; static from_type from_v8(v8::Local<v8::Value>) {} static to_type to_v8() { return v8::Undefined(isolate); } }; template <> struct convert<local> { using from_type = local; using to_type = v8::Local<v8::Value>; static from_type from_v8(v8::Local<v8::Value>); static to_type to_v8(const from_type&); }; template<typename T> struct convert<T&> : convert<T>{}; template<typename T> struct convert<const T&> : convert<T>{}; /////////////////////////////////////////////////////////////////////////// template <typename T> T convert_wrapped_class_from_v8(v8::Local<v8::Value> value); template <typename T> v8::Local<v8::Object> convert_wrapped_class_to_v8(const T& t); template <typename T> struct convert<T, typename std::enable_if<is_wrapped_class<T>::value>::type> { using from_type = T; using to_type = v8::Local<v8::Object>; static from_type from_v8(v8::Local<v8::Value> value) { return convert_wrapped_class_from_v8<from_type>(value); } static to_type to_v8(const from_type& value) { return convert_wrapped_class_to_v8(value); } }; /////////////////////////////////////////////////////////////////////////// template<typename T> typename convert<T>::from_type from_v8(v8::Local<v8::Value> value) { return convert<T>::from_v8(value); } template<size_t N> v8::Local<v8::String> to_v8(const char (&str)[N]) { return convert<const char*>::to_v8(str); } template<typename T> typename convert<T>::to_type to_v8(const T& value) { return convert<T>::to_v8(value); } } }
5,904
1,920
// MIT License // Copyright (C) August 2016 Hotride CGUIHTMLButton::CGUIHTMLButton( CGUIHTMLGump *htmlGump, int serial, uint16_t graphic, uint16_t graphicSelected, uint16_t graphicPressed, int x, int y) : CGUIButton(serial, graphic, graphicSelected, graphicPressed, x, y) , m_HTMLGump(htmlGump) { } CGUIHTMLButton::~CGUIHTMLButton() { } void CGUIHTMLButton::SetShaderMode() { DEBUG_TRACE_FUNCTION; glUniform1iARB(g_ShaderDrawMode, SDM_NO_COLOR); } void CGUIHTMLButton::Scroll(bool up, int delay) { DEBUG_TRACE_FUNCTION; if (m_HTMLGump != nullptr) { m_HTMLGump->Scroll(up, delay); } }
657
267
/* State Pattern Code Example - This example descirbes the time for someone to wake up depending if it is a weekday or weekend Matt Frankmore */ #include <iostream> #include <typeinfo> using namespace std; class Context; //All methods that all concrete states should implement class State { protected: Context *_context; public: virtual ~State() { } void setContext(Context *context) { this->_context = context; } virtual void handle1() = 0; virtual void handle2() = 0; }; class Context { private: State *_state; public: //Context allows switching state at runtime Context(State *state) : _state(nullptr) { this->transitionTo(state); } ~Context() { delete _state; } //Outputs the transition to console and switches states void transitionTo(State *state) { cout << "Context: Transition to " << typeid(*state).name() << ".\n"; if (this->_state != nullptr) delete this->_state; this->_state = state; this->_state->setContext(this); } void request1() { this->_state->handle1(); } void request2() { this->_state->handle2(); } }; /* * Concrete State implementations */ class Weekday : public State { public: //Switch states after run void handle1() override; //Keep Current State after run void handle2() override { cout << "Weekday handles request2.\n"; //Here to illustrate the changes in state cout << " Today is a Weekday, you need to wake up at 7:00am and go to sleep by 11:00pm.\n"; } }; class Weekend : public State { public: void handle1() override { cout << "Weekend handles request1.\n"; //Here to illustrate the changes in state cout << " Today is a Weekend, wake up and go to sleep when you want.\n"; } void handle2() override { cout << "Weekend handles request2.\n"; //Here to illustrate the changes in state cout << " Today is a weekend, wake up when you want but you need to go to sleep by 11:00pm. Tomorrow is a Weekday.\n"; cout << "Weekend wants to change the state of the context.\n"; //Here to illustrate the changes in state this->_context->transitionTo(new Weekday); } }; void Weekday::handle1() { cout << "Weekday handles request1.\n"; //Here to illustrate the changes in state cout << " Today is a weekday, you need to wake up at 7:00am and go to sleep whenever. Tomorrow is the weekend.\n"; cout << "Weekday wants to change the state of the context.\n"; //Here to illustrate the changes in state this->_context->transitionTo(new Weekend); } //Function that starts everything and would process the state requests void clientCode() { Context *context = new Context(new Weekend); //Events that would change the object's internal state (Hard coded to start on a Sunday and goes until the next Sunday) context->request2(); //Sunday - Switches to Weekday context->request2(); //Monday context->request2(); //Tuesday context->request2(); //Wednesday context->request2(); //Thursday context->request1(); //Friday - Switches to Weekend context->request1(); //Saturday context->request2(); //Sunday - Switches to Weekday delete context; } int main() { clientCode(); return 0; }
3,416
990
#pragma once #include <string_view> #include "Runtime/Weapon/CBeamInfo.hpp" #include "Runtime/World/CActor.hpp" #include "Runtime/World/CDamageInfo.hpp" namespace metaforce { class CWeaponDescription; class CScriptBeam : public CActor { TCachedToken<CWeaponDescription> xe8_weaponDescription; CBeamInfo xf4_beamInfo; CDamageInfo x138_damageInfo; TUniqueId x154_projectileId; public: CScriptBeam(TUniqueId, std::string_view, const CEntityInfo&, const zeus::CTransform&, bool, const TToken<CWeaponDescription>&, const CBeamInfo&, const CDamageInfo&); void Accept(IVisitor& visitor) override; void Think(float, CStateManager&) override; void AcceptScriptMsg(EScriptObjectMessage, TUniqueId, CStateManager&) override; }; } // namespace metaforce
777
278
#include <iostream> #include <string> #include "expression.hpp" #include "kineticrewriter.hpp" #include "parser.hpp" #include "alg_collect.hpp" #include "common.hpp" #include "expr_expand.hpp" expr_list_type& statements(Expression *e) { if (e) { if (auto block = e->is_block()) { return block->statements(); } if (auto sym = e->is_symbol()) { if (auto proc = sym->is_procedure()) { return proc->body()->statements(); } if (auto proc = sym->is_procedure()) { return proc->body()->statements(); } } } throw std::runtime_error("not a block, function or procedure"); } inline symbol_ptr state_var(const char* name) { auto v = make_symbol<VariableExpression>(Location(), name); v->is_variable()->state(true); return v; } inline symbol_ptr assigned_var(const char* name) { return make_symbol<VariableExpression>(Location(), name); } static const char* kinetic_abc = "KINETIC kin { \n" " u = 3 \n" " ~ a <-> b (u, v) \n" " u = 4 \n" " v = sin(u) \n" " ~ b <-> 3b + c (u, v) \n" "} \n"; static const char* derivative_abc = "DERIVATIVE deriv { \n" " a' = -3*a + b*v \n" " LOCAL rev2 \n" " rev2 = c*b^3*sin(4) \n" " b' = 3*a - v*b + 8*b - 2*rev2\n" " c' = 4*b - rev2 \n" "} \n"; TEST(KineticRewriter, equiv) { auto kin = Parser(kinetic_abc).parse_procedure(); auto deriv = Parser(derivative_abc).parse_procedure(); auto kin_ptr = kin.get(); auto deriv_ptr = deriv.get(); ASSERT_NE(nullptr, kin); ASSERT_NE(nullptr, deriv); ASSERT_TRUE(kin->is_symbol() && kin->is_symbol()->is_procedure()); ASSERT_TRUE(deriv->is_symbol() && deriv->is_symbol()->is_procedure()); scope_type::symbol_map globals; globals["kin"] = std::move(kin); globals["deriv"] = std::move(deriv); globals["a"] = state_var("a"); globals["b"] = state_var("b"); globals["c"] = state_var("c"); globals["u"] = assigned_var("u"); globals["v"] = assigned_var("v"); deriv_ptr->semantic(globals); auto kin_body = kin_ptr->is_procedure()->body(); scope_ptr scope = std::make_shared<scope_type>(globals); kin_body->semantic(scope); auto kin_deriv = kinetic_rewrite(kin_body); verbose_print("derivative procedure:\n", deriv_ptr); verbose_print("kin procedure:\n", kin_ptr); verbose_print("rewritten kin body:\n", kin_deriv); auto deriv_map = expand_assignments(statements(deriv_ptr)); auto kin_map = expand_assignments(statements(kin_deriv.get())); if (g_verbose_flag) { std::cout << "derivative assignments (canonical):\n"; for (const auto&p: deriv_map) { std::cout << p.first << ": " << p.second << "\n"; } std::cout << "rewritten kin assignments (canonical):\n"; for (const auto&p: kin_map) { std::cout << p.first << ": " << p.second << "\n"; } } EXPECT_EQ(deriv_map["a'"], kin_map["a'"]); EXPECT_EQ(deriv_map["b'"], kin_map["b'"]); EXPECT_EQ(deriv_map["c'"], kin_map["c'"]); }
3,321
1,189
#include "../../strange__core.h" namespace strange { template <typename element_d> var<symbol_a> queue_a<element_d>::cat(con<> const& me) { static auto r = sym("<strange::queue>"); //TODO cat return r; } template <typename element_d> typename queue_a<element_d>::creator_fp queue_a<element_d>::creator(con<symbol_a> const& scope, con<symbol_a> const& thing, con<symbol_a> const& function) { if (scope == "strange") { if (thing == "queue") { if (function == "create_from_range") { // return thing_t::create_from_range; } } } return nullptr; } // instantiation template struct queue_a<>; template struct queue_a<int64_t>; template struct queue_a<uint8_t>; }
713
298
#include "CppML/CppML.hpp" namespace NoneOfTest { template <typename T> using Predicate = std::is_class<T>; template <typename T> struct R {}; struct Type0 {}; struct Type1 {}; void run() { { using T = ml::f<ml::NoneOf<ml::F<Predicate>, ml::F<R>>, int, char, Type0>; static_assert(std::is_same<T, R<ml::Bool<false>>>::value, "NoneOf with a non-empty pack 1"); } { using T = ml::f<ml::NoneOf<ml::F<Predicate>, ml::F<R>>>; static_assert(std::is_same<T, R<ml::Bool<true>>>::value, "NoneOf with empty pack"); } } } // namespace NoneOfTest
596
227
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "content/browser/attribution_reporting/storable_source.h" #include "base/check_op.h" #include "net/base/schemeful_site.h" namespace content { StorableSource::StorableSource(uint64_t impression_data, url::Origin impression_origin, url::Origin conversion_origin, url::Origin reporting_origin, base::Time impression_time, base::Time expiry_time, SourceType source_type, int64_t priority, AttributionLogic attribution_logic, absl::optional<Id> impression_id) : impression_data_(impression_data), impression_origin_(std::move(impression_origin)), conversion_origin_(std::move(conversion_origin)), reporting_origin_(std::move(reporting_origin)), impression_time_(impression_time), expiry_time_(expiry_time), source_type_(source_type), priority_(priority), attribution_logic_(attribution_logic), impression_id_(impression_id) { // 30 days is the max allowed expiry for an impression. DCHECK_GE(base::Days(30), expiry_time - impression_time); // The impression must expire strictly after it occurred. DCHECK_GT(expiry_time, impression_time); DCHECK(!impression_origin.opaque()); DCHECK(!reporting_origin.opaque()); DCHECK(!conversion_origin.opaque()); } StorableSource::StorableSource(const StorableSource& other) = default; StorableSource& StorableSource::operator=(const StorableSource& other) = default; StorableSource::StorableSource(StorableSource&& other) = default; StorableSource& StorableSource::operator=(StorableSource&& other) = default; StorableSource::~StorableSource() = default; net::SchemefulSite StorableSource::ConversionDestination() const { return net::SchemefulSite(conversion_origin_); } net::SchemefulSite StorableSource::ImpressionSite() const { return net::SchemefulSite(impression_origin_); } } // namespace content
2,281
655
#include <bits/stdc++.h> #define int long long using namespace std; signed main() { // Turn off synchronization between cin/cout and scanf/printf ios_base::sync_with_stdio(false); // Disable automatic flush of cout when reading from cin cin.tie(0); cin.tie(0); int n, groups; cin >> n >> groups; vector<vector<bool>>con(n, vector<bool>(n)); vector<vector<int>>E(n); for (int i = 0; i < n; ++i) { int k; cin >> k; for (int j = 0; j < k; ++j) { int x; cin >> x; con[i][x]=true; con[x][i]=true; E[x].push_back(i); } } vector<int>first, second; vector<int>cols(n,-1); vector<vector<int>>g(groups); for (int i = 0; i < n; ++i) { vector<bool>used(groups); for (int w : E[i]) { if(cols[w]==-1){ continue;} used[cols[w]]=true; } for (int j = 0; j < groups; ++j) { if(used[j]){ continue;} cols[i]=j; g[j].push_back(i); break; } } for (int i = 0; i < groups; ++i) { cout << g[i].size() << " "; for (int j = 0; j < g[i].size(); ++j) { cout << g[i][j] << " "; } cout << "\n"; } }
1,287
474
//===-- RegisterContextPOSIX_arm.cpp --------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include <cerrno> #include <cstdint> #include <cstring> #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Target/Thread.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/RegisterValue.h" #include "lldb/Utility/Scalar.h" #include "llvm/Support/Compiler.h" #include "RegisterContextPOSIX_arm.h" using namespace lldb; using namespace lldb_private; bool RegisterContextPOSIX_arm::IsGPR(unsigned reg) { if (m_register_info_up->GetRegisterSetFromRegisterIndex(reg) == RegisterInfoPOSIX_arm::GPRegSet) return true; return false; } bool RegisterContextPOSIX_arm::IsFPR(unsigned reg) { if (m_register_info_up->GetRegisterSetFromRegisterIndex(reg) == RegisterInfoPOSIX_arm::FPRegSet) return true; return false; } RegisterContextPOSIX_arm::RegisterContextPOSIX_arm( lldb_private::Thread &thread, std::unique_ptr<RegisterInfoPOSIX_arm> register_info) : lldb_private::RegisterContext(thread, 0), m_register_info_up(std::move(register_info)) {} RegisterContextPOSIX_arm::~RegisterContextPOSIX_arm() {} void RegisterContextPOSIX_arm::Invalidate() {} void RegisterContextPOSIX_arm::InvalidateAllRegisters() {} unsigned RegisterContextPOSIX_arm::GetRegisterOffset(unsigned reg) { return m_register_info_up->GetRegisterInfo()[reg].byte_offset; } unsigned RegisterContextPOSIX_arm::GetRegisterSize(unsigned reg) { return m_register_info_up->GetRegisterInfo()[reg].byte_size; } size_t RegisterContextPOSIX_arm::GetRegisterCount() { return m_register_info_up->GetRegisterCount(); } size_t RegisterContextPOSIX_arm::GetGPRSize() { return m_register_info_up->GetGPRSize(); } const lldb_private::RegisterInfo *RegisterContextPOSIX_arm::GetRegisterInfo() { // Commonly, this method is overridden and g_register_infos is copied and // specialized. So, use GetRegisterInfo() rather than g_register_infos in // this scope. return m_register_info_up->GetRegisterInfo(); } const lldb_private::RegisterInfo * RegisterContextPOSIX_arm::GetRegisterInfoAtIndex(size_t reg) { if (reg < GetRegisterCount()) return &GetRegisterInfo()[reg]; return nullptr; } size_t RegisterContextPOSIX_arm::GetRegisterSetCount() { return m_register_info_up->GetRegisterSetCount(); } const lldb_private::RegisterSet * RegisterContextPOSIX_arm::GetRegisterSet(size_t set) { return m_register_info_up->GetRegisterSet(set); } const char *RegisterContextPOSIX_arm::GetRegisterName(unsigned reg) { if (reg < GetRegisterCount()) return GetRegisterInfo()[reg].name; return nullptr; }
3,014
993
#pragma once /** * \file z/util/regex/rgx.hpp * \namespace z::util::rgx * \brief Namespace containing all regex rules for the sake of organization. **/ #include "rules/alpha.hpp" #include "rules/alnum.hpp" #include "rules/andlist.hpp" #include "rules/anything.hpp" #include "rules/begin.hpp" #include "rules/boundary.hpp" #include "rules/character.hpp" #include "rules/compound.hpp" #include "rules/digit.hpp" #include "rules/end.hpp" #include "rules/lookahead.hpp" #include "rules/lookbehind.hpp" #include "rules/newline.hpp" #include "rules/orlist.hpp" #include "rules/punct.hpp" #include "rules/range.hpp" #include "rules/space.hpp" #include "rules/word.hpp"
666
244
/* File: remoteExec.cpp Author: Julian Bauer (julian.bauer@cationstudio.com) Description: Remote exec config file for management system. */ class cat_perm_fnc_getInfos { allowedTargets=2; }; class cat_perm_fnc_updateRank { allowedTargets=2; }; class cat_perm_fnc_getInfosHC { allowedTargets=HC_Life; }; class cat_perm_fnc_updateRankHC { allowedTargets=HC_Life; }; class cat_perm_fnc_updatePlayer { allowedTargets=1; } class cat_perm_fnc_updatePermDialog { allowedTargets=1; }
517
192
// Part of the LSFML library -- Copyright (c) Christian Neumüller 2015 // This file is subject to the terms of the BSD 2-Clause License. // See LICENSE.txt or http://opensource.org/licenses/BSD-2-Clause #ifndef LSFML_RESOURCE_TEXT_HPP_INCLUDED #define LSFML_RESOURCE_TEXT_HPP_INCLUDED #include <lsfml/resource_media.hpp> #include <SFML/Graphics/Text.hpp> namespace lsfml { using resource_text = resource_media<sf::Text, sf::Font>; inline void update_resource_media( sf::Text& s, resource_text::res_ptr const& fnt) { s.setFont(*fnt); } } // namespace lsfml #endif // LSFML_RESOURCE_TEXT_HPP_INCLUDED
614
246
#include <math.h> #include "TMP006.h" #include "../../register/ByteInvert.h" using namespace wlp; TMP006::TMP006(uint8_t address, uint16_t sample_rate) : m_sample_rate(sample_rate), m_register(address) {} bool TMP006::begin() { m_register.write16(TMP006::CONFIG, TMP006::CFG_MODEON | TMP006::CFG_DRDYEN | m_sample_rate); auto man_id = byte_invert<uint16_t>(m_register.read16(TMP006::MAN_ID)); auto dev_id = byte_invert<uint16_t>(m_register.read16(TMP006::DEV_ID)); return man_id == TMP006_MAN_ID && dev_id == TMP006_DEV_ID; } void TMP006::sleep() { uint16_t config = m_register.read16(TMP006::CONFIG); config &= ~TMP006::CFG_MODEON; m_register.write16(TMP006::CONFIG, config); } void TMP006::wake() { uint16_t config = m_register.read16(TMP006::CONFIG); config |= TMP006::CFG_MODEON; m_register.write16(TMP006::CONFIG, config); } int16_t TMP006::read_raw_die_temperature() { auto raw_value = static_cast<int16_t>(byte_invert<uint16_t>(m_register.read16(TMP006::TAMB))); raw_value >>= 2; return raw_value; } int16_t TMP006::read_raw_voltage() { return static_cast<int16_t>(byte_invert<uint16_t>(m_register.read16(TMP006::VOBJ))); } double TMP006::read_die_temperature() { return read_raw_die_temperature() * 0.03125; } double TMP006::read_obj_temperature() { double die_temp = read_die_temperature() + 273.15; double vobj = read_raw_voltage() * 1.5625e-7; double die_ref_temp = die_temp - TMP006_TREF; double die_ref_temp_sq = die_ref_temp * die_ref_temp; double S = 1 + TMP006_A1 * die_ref_temp + TMP006_A2 * die_ref_temp_sq; S *= TMP006_S0 * 1e-14; double vos = TMP006_B0 + TMP006_B1 * die_ref_temp + TMP006_B2 * die_ref_temp_sq; double vdiff = vobj - vos; double f_vobj = vdiff + TMP006_C2 * vdiff * vdiff; double die_temp_sq = die_temp * die_temp; double temperature = sqrt(sqrt(die_temp_sq * die_temp_sq + f_vobj / S)); return temperature - 273.15; }
2,031
939
/** \copyright * Copyright (c) 2016, Balazs Racz * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * \file CC32xxEEPROMFlushFlow.hxx * Helper state flow for flushing the CC32xx EEPROM emulation automatically. * * @author Balazs Racz * @date 24 June 2017 */ #ifndef FREERTOS_DRIVERS_TI_CC32XXEEPROMFLUSHFLOW_HXX_ #define FREERTOS_DRIVERS_TI_CC32XXEEPROMFLUSHFLOW_HXX_ #include "executor/StateFlow.hxx" extern "C" { void eeprom_flush(); } class EepromTimerFlow : public StateFlowBase, protected Atomic { public: EepromTimerFlow(Service* s) : StateFlowBase(s) , isWaiting_(0) , isDirty_(0) { start_flow(STATE(test_and_sleep)); } void wakeup() { AtomicHolder h(this); isDirty_ = 1; if (isWaiting_) { isWaiting_ = 0; notify(); } } private: Action test_and_sleep() { bool need_sleep = false; { AtomicHolder h(this); if (isDirty_) { isDirty_ = 0; need_sleep = true; } else { isWaiting_ = 1; } } if (need_sleep) { return sleep_and_call( &timer_, MSEC_TO_NSEC(1000), STATE(test_and_flush)); } else { return wait(); } } Action test_and_flush() { bool need_sleep = false; { AtomicHolder h(this); if (isDirty_) { // we received another write during the sleep. Go back to sleep. isDirty_ = 0; need_sleep = true; } } if (need_sleep) { return sleep_and_call( &timer_, MSEC_TO_NSEC(1000), STATE(test_and_flush)); } eeprom_flush(); return call_immediately(STATE(test_and_sleep)); } StateFlowTimer timer_{this}; // 1 if the flow is sleeping and needs to be notified to wake up. unsigned isWaiting_ : 1; // 1 if we received a notification from the eeprom handler. unsigned isDirty_ : 1; }; extern EepromTimerFlow eepromTimerFlow_; #ifndef SKIP_UPDATED_CALLBACK extern "C" { void eeprom_updated_notification() { eepromTimerFlow_.wakeup(); } } #endif #endif // FREERTOS_DRIVERS_TI_CC32XXEEPROMFLUSHFLOW_HXX_
3,679
1,294
#include<fstream> using namespace std; int a[101][101],v[1001]; int main() { ifstream f("seif1.in"); ofstream g("seif1.out"); int n,k,i,j,x=0,p=0,l=1; f>>n>>k; k=k%(n*2); for(i=1;i<=n;i++) for(j=1;j<=n;j++) f>>a[i][j]; for(i=1;i<=n/2;i++) x++,v[x]=a[i][n/2-i+1]; for(i=1;i<=n/2;i++) x++,v[x]=a[n/2+i][i]; for(i=1;i<=n/2;i++) x++,v[x]=a[n-i+1][n/2+i]; for(i=1;i<=n/2;i++) x++,v[x]=a[n/2-i+1][n-i+1]; for(i=k+1;i<=x;i++) g<<v[i]<<' '; for(i=1;i<=k;i++) g<<v[i]<<' '; return 0; }
538
338
// // RoutesMap.hpp // transportnyi-spravochnik // // Created by Mykyta Cheshulko on 02.07.2020. // Copyright © 2020 Mykyta Cheshulko. All rights reserved. // #ifndef RoutesMap_hpp #define RoutesMap_hpp #include "Route.hpp" #include "Stop.hpp" #include "DirectedWeightedGraph.hpp" #include "Router.hpp" #include <optional> #include <set> #include <unordered_map> #include <map> #include <tuple> namespace guide::route { class RoutesMap { public: class Settings final { public: Settings(size_t busWaitTime, size_t busVelocity); size_t GetBusWaitTime() const; size_t GetBusVelocity() const; private: size_t busWaitTime_; size_t busVelocity_; }; public: RoutesMap(); RoutesMap(std::vector<std::shared_ptr<Route>> routes, std::vector<std::shared_ptr<Stop>> stops); bool AddStop(std::shared_ptr<Stop> stop); bool AddRoute(std::shared_ptr<Route> route); std::optional<std::weak_ptr<Stop>> FindStop(const std::string& name) const; std::optional<std::weak_ptr<Stop>> FindStop(std::shared_ptr<Stop> stop) const; std::optional<std::weak_ptr<Route>> FindRoute(const std::string& name) const; void SetSettings(std::shared_ptr<Settings> settings_); size_t GetStopsCount() const; const Settings& GetSettings() const; std::optional<size_t> GetStopId(std::shared_ptr<Stop> stop) const; std::optional<std::weak_ptr<Stop>> GetStop(size_t stopId) const; std::optional<std::weak_ptr<Route>> GetRoute(size_t routeId) const; std::optional< std::vector<std::tuple< std::weak_ptr<Stop>, /* From stop */ std::weak_ptr<Stop>, /* To stop */ double, /* Time, minutes */ std::weak_ptr<Route>, /* Using route */ size_t /* Stops count */ >>> GetOptimalRoute(std::shared_ptr<Stop> fromStop, std::shared_ptr<Stop> toStop); void BuildGraph(); private: std::shared_ptr<Settings> settings_; private: std::set<std::shared_ptr<Route>, Route::SharedComparator> routes_; std::set<std::shared_ptr<Stop>, Stop::SharedComparator> stops_; private: /* These for graph */ std::map< std::weak_ptr<Stop>, size_t, Stop::WeakComparator > stopsId_; std::vector<std::weak_ptr<Stop>> idStops_; std::vector<std::weak_ptr<Route>> idRoutes_; private: std::unique_ptr<structure::graph::Router<double>> router_; std::unique_ptr<structure::graph::DirectedWeightedGraph<double>> graph_; }; } #endif /* RoutesMap_hpp */
2,634
885
////////////////////////////////////////////////////////////////////////// // // Copyright (c) 2016, Image Engine Design Inc. All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above // copyright notice, this list of conditions and the following // disclaimer. // // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided with // the distribution. // // * Neither the name of Image Engine Design nor the names of // any other contributors to this software may be used to endorse or // promote products derived from this software without specific prior // written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS // IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, // THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR // PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR // CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, // EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, // PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR // PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF // LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING // NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. // ////////////////////////////////////////////////////////////////////////// #include "GafferImage/VectorWarp.h" #include "GafferImage/FilterAlgo.h" #include "GafferImage/ImageAlgo.h" #include "Gaffer/Context.h" #include "OpenEXR/ImathFun.h" #include <cmath> using namespace Imath; using namespace IECore; using namespace Gaffer; using namespace GafferImage; ////////////////////////////////////////////////////////////////////////// // Engine implementation ////////////////////////////////////////////////////////////////////////// struct VectorWarp::Engine : public Warp::Engine { Engine( const Box2i &displayWindow, const Box2i &tileBound, const Box2i &validTileBound, ConstFloatVectorDataPtr xData, ConstFloatVectorDataPtr yData, ConstFloatVectorDataPtr aData, VectorMode vectorMode, VectorUnits vectorUnits ) : m_displayWindow( displayWindow ), m_tileBound( tileBound ), m_xData( xData ), m_yData( yData ), m_aData( aData ), m_x( xData->readable() ), m_y( yData->readable() ), m_a( aData->readable() ), m_vectorMode( vectorMode ), m_vectorUnits( vectorUnits ) { } Imath::V2f inputPixel( const Imath::V2f &outputPixel ) const override { const V2i outputPixelI( (int)floorf( outputPixel.x ), (int)floorf( outputPixel.y ) ); const size_t i = BufferAlgo::index( outputPixelI, m_tileBound ); if( m_a[i] == 0.0f ) { return black; } else { V2f result = m_vectorMode == Relative ? outputPixel : V2f( 0.0f ); result += m_vectorUnits == Screen ? screenToPixel( V2f( m_x[i], m_y[i] ) ) : V2f( m_x[i], m_y[i] ); if( !std::isfinite( result[0] ) || !std::isfinite( result[1] ) ) { return black; } return result; } } private : inline V2f screenToPixel( const V2f &vector ) const { return V2f( lerp<float>( m_displayWindow.min.x, m_displayWindow.max.x, vector.x ), lerp<float>( m_displayWindow.min.y, m_displayWindow.max.y, vector.y ) ); } const Box2i m_displayWindow; const Box2i m_tileBound; ConstFloatVectorDataPtr m_xData; ConstFloatVectorDataPtr m_yData; ConstFloatVectorDataPtr m_aData; const std::vector<float> &m_x; const std::vector<float> &m_y; const std::vector<float> &m_a; const VectorMode m_vectorMode; const VectorUnits m_vectorUnits; }; ////////////////////////////////////////////////////////////////////////// // VectorWarp implementation ////////////////////////////////////////////////////////////////////////// GAFFER_GRAPHCOMPONENT_DEFINE_TYPE( VectorWarp ); size_t VectorWarp::g_firstPlugIndex = 0; VectorWarp::VectorWarp( const std::string &name ) : Warp( name ) { storeIndexOfNextChild( g_firstPlugIndex ); addChild( new ImagePlug( "vector" ) ); addChild( new IntPlug( "vectorMode", Gaffer::Plug::In, (int)Absolute, (int)Relative, (int)Absolute ) ); addChild( new IntPlug( "vectorUnits", Gaffer::Plug::In, (int)Screen, (int)Pixels, (int)Screen ) ); outPlug()->formatPlug()->setInput( vectorPlug()->formatPlug() ); outPlug()->dataWindowPlug()->setInput( vectorPlug()->dataWindowPlug() ); } VectorWarp::~VectorWarp() { } ImagePlug *VectorWarp::vectorPlug() { return getChild<ImagePlug>( g_firstPlugIndex ); } const ImagePlug *VectorWarp::vectorPlug() const { return getChild<ImagePlug>( g_firstPlugIndex ); } IntPlug *VectorWarp::vectorModePlug() { return getChild<IntPlug>( g_firstPlugIndex + 1 ); } const IntPlug *VectorWarp::vectorModePlug() const { return getChild<IntPlug>( g_firstPlugIndex + 1 ); } IntPlug *VectorWarp::vectorUnitsPlug() { return getChild<IntPlug>( g_firstPlugIndex + 2 ); } const IntPlug *VectorWarp::vectorUnitsPlug() const { return getChild<IntPlug>( g_firstPlugIndex + 2 ); } void VectorWarp::affects( const Gaffer::Plug *input, AffectedPlugsContainer &outputs ) const { Warp::affects( input, outputs ); if( input == vectorPlug()->deepPlug() ) { outputs.push_back( outPlug()->deepPlug() ); } } bool VectorWarp::affectsEngine( const Gaffer::Plug *input ) const { return Warp::affectsEngine( input ) || input == inPlug()->formatPlug() || input == vectorPlug()->channelNamesPlug() || input == vectorPlug()->channelDataPlug() || input == vectorModePlug() || input == vectorUnitsPlug(); } void VectorWarp::hashEngine( const Imath::V2i &tileOrigin, const Gaffer::Context *context, IECore::MurmurHash &h ) const { Warp::hashEngine( tileOrigin, context, h ); h.append( tileOrigin ); ConstStringVectorDataPtr channelNames; { ImagePlug::GlobalScope c( context ); channelNames = vectorPlug()->channelNamesPlug()->getValue(); vectorPlug()->dataWindowPlug()->hash( h ); inPlug()->formatPlug()->hash( h ); } ImagePlug::ChannelDataScope channelDataScope( context ); if( ImageAlgo::channelExists( channelNames->readable(), "R" ) ) { channelDataScope.setChannelName( "R" ); vectorPlug()->channelDataPlug()->hash( h ); } if( ImageAlgo::channelExists( channelNames->readable(), "G" ) ) { channelDataScope.setChannelName( "G" ); vectorPlug()->channelDataPlug()->hash( h ); } if( ImageAlgo::channelExists( channelNames->readable(), "A" ) ) { channelDataScope.setChannelName( "A" ); vectorPlug()->channelDataPlug()->hash( h ); } vectorModePlug()->hash( h ); vectorUnitsPlug()->hash( h ); } const Warp::Engine *VectorWarp::computeEngine( const Imath::V2i &tileOrigin, const Gaffer::Context *context ) const { const Box2i tileBound( tileOrigin, tileOrigin + V2i( ImagePlug::tileSize() ) ); Box2i validTileBound; ConstStringVectorDataPtr channelNames; Box2i displayWindow; { ImagePlug::GlobalScope c( context ); validTileBound = BufferAlgo::intersection( tileBound, vectorPlug()->dataWindowPlug()->getValue() ); channelNames = vectorPlug()->channelNamesPlug()->getValue(); displayWindow = inPlug()->formatPlug()->getValue().getDisplayWindow(); } ImagePlug::ChannelDataScope channelDataScope( context ); ConstFloatVectorDataPtr xData = ImagePlug::blackTile(); if( ImageAlgo::channelExists( channelNames->readable(), "R" ) ) { channelDataScope.setChannelName( "R" ); xData = vectorPlug()->channelDataPlug()->getValue(); } ConstFloatVectorDataPtr yData = ImagePlug::blackTile(); if( ImageAlgo::channelExists( channelNames->readable(), "G" ) ) { channelDataScope.setChannelName( "G" ); yData = vectorPlug()->channelDataPlug()->getValue(); } ConstFloatVectorDataPtr aData = ImagePlug::whiteTile(); if( ImageAlgo::channelExists( channelNames->readable(), "A" ) ) { channelDataScope.setChannelName( "A" ); aData = vectorPlug()->channelDataPlug()->getValue(); } if( xData->readable().size() != (unsigned int)ImagePlug::tilePixels() || yData->readable().size() != (unsigned int)ImagePlug::tilePixels() || aData->readable().size() != (unsigned int)ImagePlug::tilePixels() ) { throw IECore::Exception( "VectorWarp::computeEngine : Bad channel data size on vector plug. Maybe it's deep?" ); } return new Engine( displayWindow, tileBound, validTileBound, xData, yData, aData, (VectorMode)vectorModePlug()->getValue(), (VectorUnits)vectorUnitsPlug()->getValue() ); } void VectorWarp::hashDeep( const GafferImage::ImagePlug *parent, const Gaffer::Context *context, IECore::MurmurHash &h ) const { FlatImageProcessor::hashDeep( parent, context, h ); h.append( vectorPlug()->deepPlug()->hash() ); } bool VectorWarp::computeDeep( const Gaffer::Context *context, const ImagePlug *parent ) const { if( vectorPlug()->deepPlug()->getValue() ) { throw IECore::Exception( "Deep data not supported in input \"vector\"" ); } return false; }
9,323
3,350
#include "dumps.h" #include "solver.h" dump_manager_class :: dump_manager_class() { } dump_manager_class :: ~dump_manager_class() { for (int i=0; i<dumpN; i++) delete (dump_slaves[i]); free(dump_slaves); } dump_manager_class :: dump_manager_class(FILE* optfid) { dumpN = load_namedint(optfid, "DUMPS_N", true, 0); dump_slaves = (dump_type_empty_class**)malloc_ch(sizeof(dump_type_empty_class*)*dumpN); for (int i=0; i<dumpN; i++) { char cbuf[100]; load_namednumstringn(optfid, "DUMPTYPE", cbuf, i, 100, false); if (strcmp(cbuf, "full")==0) dump_slaves[i] = new dump_type_full_class (optfid,i); else if (strcmp(cbuf, "maxI")==0) dump_slaves[i] = new dump_type_maxI_class (optfid,i); else if (strcmp(cbuf, "flux")==0) dump_slaves[i] = new dump_type_flux_class (optfid,i); else if (strcmp(cbuf, "ysection")==0) dump_slaves[i] = new dump_type_ysection_class (optfid,i); else if (strcmp(cbuf, "ysection_maxI")==0) dump_slaves[i] = new dump_type_ysection_maxI_class (optfid,i); else if (strcmp(cbuf, "ysection_flux")==0) dump_slaves[i] = new dump_type_ysection_flux_class (optfid,i); else if (strcmp(cbuf, "plasma_full")==0) dump_slaves[i] = new dump_type_full_plasma_class (optfid,i); else if (strcmp(cbuf, "plasma_max")==0) dump_slaves[i] = new dump_type_plasma_max_class (optfid,i); else if (strcmp(cbuf, "plasma_ysection")==0) dump_slaves[i] = new dump_type_ysection_plasma_class (optfid,i); else if (strcmp(cbuf, "plasma_ysection_max")==0) dump_slaves[i] = new dump_type_ysection_plasma_max_class (optfid,i); else if (strcmp(cbuf, "youngy")==0) dump_slaves[i] = new dump_type_youngy_class(optfid, i); else if (strcmp(cbuf, "fluxk") ==0) dump_slaves[i] = new dump_type_fluxk_class(optfid, i); else if (strcmp(cbuf, "ysectionk")==0) dump_slaves[i] = new dump_type_ysectionk_class(optfid,i); else if (strcmp(cbuf, "field_axis") ==0) dump_slaves[i] = new dump_type_field_axis_class(optfid,i); else if (strcmp(cbuf, "plasma_axis")==0) dump_slaves[i] = new dump_type_plasma_axis_class(optfid,i); else if (strcmp(cbuf, "Z_axis")==0) dump_slaves[i] = new dump_type_Z_axis_class(optfid,i); else if (strcmp(cbuf, "average_spectrum")==0) dump_slaves[i] = new dump_type_average_spectrum_class(optfid,i); else if (strcmp(cbuf, "duration")==0) dump_slaves[i] = new dump_type_duration_class(optfid, i); else throw "dump_manager_class :: dump_manager_class(FILE* fid) >>> Error! Unknown dump type specified! Revise DUMPTYPE values"; } } void dump_manager_class :: dump() { if (ISMASTER) printf("\nDumping (n_Z=%d, Z=%f)...", n_Z, CURRENT_Z); for (int i=0; i<dumpN; i++) dump_slaves[i]->dump_noflush(); if (ISMASTER) printf("Done."); } void create_wfilter(f_complex* wfilter, const char* name) { //TODO: Other filters if (strncmp(name, "longpass",8)==0) {float_type lambda=(float_type)atof(name+8); create_longpass_filter(wfilter,lambda);} else if (strncmp(name, "lp",2)==0) {float_type lambda=(float_type)atof(name+2); create_longpass_filter(wfilter,lambda);} else if (strncmp(name, "shortpass",9)==0) {float_type lambda=(float_type)atof(name+9); create_shortpass_filter(wfilter,lambda);} else if (strncmp(name, "sp",2)==0) {float_type lambda=(float_type)atof(name+2); create_shortpass_filter(wfilter,lambda);} else if (strncmp(name, "NO",2)==0) {for (int nw=0; nw<N_T; nw++) wfilter[nw]=1.0; } else if (strncmp(name, "file_",5)==0) {load_spectrum_fromfile(wfilter, OMEGA, N_T, name+5, "text_lambdanm");} else throw "create_wfilter: Unknown filter shape!"; } void create_longpass_filter(f_complex* wfilter, float_type lambda) { float_type omega = 2*M_PI*LIGHT_VELOCITY/lambda; for (int nw=0; nw<N_T; nw++) if (OMEGA[nw]<omega) wfilter[nw]=1.0; else wfilter[nw]=0.0; } void create_shortpass_filter(f_complex* wfilter, float_type lambda) { float_type omega = 2*M_PI*LIGHT_VELOCITY/lambda; for (int nw=0; nw<N_T; nw++) if (OMEGA[nw]>omega) wfilter[nw]=1.0; else wfilter[nw]=0.0; } void create_filter_fromfile(f_complex* wfilter, char* filename) { FILE* fid = fopen(filename, "rt"); }
4,329
1,866
/************************************************************************** * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. * * * * Author: The ALICE Off-line Project. * * Contributors are mentioned in the code where appropriate. * * * * Permission to use, copy, modify and distribute this software and its * * documentation strictly for non-commercial purposes is hereby granted * * without fee, provided that the above copyright notice appears in all * * copies and that both the copyright notice and this permission notice * * appear in the supporting documentation. The authors make no claims * * about the suitability of this software for any purpose. It is * * provided "as is" without express or implied warranty. * **************************************************************************/ /////////////////////////////////////////////////////////////////////////// // ---- CORRECTION FRAMEWORK ---- // AliCFAcceptanceCuts implementation // Class to cut on the number of AliTrackReference's // for each detector /////////////////////////////////////////////////////////////////////////// // author : R. Vernet (renaud.vernet@cern.ch) /////////////////////////////////////////////////////////////////////////// #include "AliLog.h" #include "AliMCParticle.h" #include "AliCFAcceptanceCuts.h" #include "TH1F.h" #include "TH2F.h" #include "TList.h" #include "TBits.h" ClassImp(AliCFAcceptanceCuts) //______________________________ AliCFAcceptanceCuts::AliCFAcceptanceCuts() : AliCFCutBase(), fMCInfo(0x0), fMinNHitITS(0), fMinNHitTPC(0), fMinNHitTRD(0), fMinNHitTOF(0), fMinNHitMUON(0), fhCutStatistics(0x0), fhCutCorrelation(0x0), fBitmap(new TBits(0)) { // //ctor // for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=0x0; } //______________________________ AliCFAcceptanceCuts::AliCFAcceptanceCuts(const Char_t* name, const Char_t* title) : AliCFCutBase(name,title), fMCInfo(0x0), fMinNHitITS(0), fMinNHitTPC(0), fMinNHitTRD(0), fMinNHitTOF(0), fMinNHitMUON(0), fhCutStatistics(0x0), fhCutCorrelation(0x0), fBitmap(new TBits(0)) { // //ctor // for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=0x0; } //______________________________ AliCFAcceptanceCuts::AliCFAcceptanceCuts(const AliCFAcceptanceCuts& c) : AliCFCutBase(c), fMCInfo(c.fMCInfo), fMinNHitITS(c.fMinNHitITS), fMinNHitTPC(c.fMinNHitTPC), fMinNHitTRD(c.fMinNHitTRD), fMinNHitTOF(c.fMinNHitTOF), fMinNHitMUON(c.fMinNHitMUON), fhCutStatistics(c.fhCutStatistics), fhCutCorrelation(c.fhCutCorrelation), fBitmap(c.fBitmap) { // //copy ctor // for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=c.fhQA[i][j]; } //______________________________ AliCFAcceptanceCuts& AliCFAcceptanceCuts::operator=(const AliCFAcceptanceCuts& c) { // // Assignment operator // if (this != &c) { AliCFCutBase::operator=(c) ; fMCInfo=c.fMCInfo; fMinNHitITS=c.fMinNHitITS; fMinNHitTPC=c.fMinNHitTPC; fMinNHitTRD=c.fMinNHitTRD; fMinNHitTOF=c.fMinNHitTOF; fMinNHitMUON=c.fMinNHitMUON; fhCutStatistics = c.fhCutStatistics ; fhCutCorrelation = c.fhCutCorrelation ; fBitmap = c.fBitmap ; for (int i=0; i<kNCuts; i++) for (int j=0; j<kNStepQA; j++) fhQA[i][j]=c.fhQA[i][j]; } return *this ; } //______________________________________________________________ Bool_t AliCFAcceptanceCuts::IsSelected(TObject *obj) { // // check if selections on 'obj' are passed // 'obj' must be an AliMCParticle // SelectionBitMap(obj); if (fIsQAOn) FillHistograms(obj,kFALSE); for (UInt_t icut=0; icut<fBitmap->GetNbits(); icut++) if (!fBitmap->TestBitNumber(icut)) return kFALSE ; if (fIsQAOn) FillHistograms(obj,kTRUE); return kTRUE; } //______________________________ void AliCFAcceptanceCuts::SelectionBitMap(TObject* obj) { // // checks the number of track references associated to 'obj' // 'obj' must be an AliMCParticle // for (UInt_t i=0; i<kNCuts; i++) fBitmap->SetBitNumber(i,kFALSE); if (!obj) return; TString className(obj->ClassName()); if (className.CompareTo("AliMCParticle") != 0) { AliError("obj must point to an AliMCParticle !"); return ; } AliMCParticle * part = dynamic_cast<AliMCParticle*>(obj); if(!part) return ; Int_t nHitsITS=0, nHitsTPC=0, nHitsTRD=0, nHitsTOF=0, nHitsMUON=0 ; for (Int_t iTrackRef=0; iTrackRef<part->GetNumberOfTrackReferences(); iTrackRef++) { AliTrackReference * trackRef = part->GetTrackReference(iTrackRef); if(trackRef){ Int_t detectorId = trackRef->DetectorId(); switch(detectorId) { case AliTrackReference::kITS : nHitsITS++ ; break ; case AliTrackReference::kTPC : nHitsTPC++ ; break ; case AliTrackReference::kTRD : nHitsTRD++ ; break ; case AliTrackReference::kTOF : nHitsTOF++ ; break ; case AliTrackReference::kMUON : nHitsMUON++ ; break ; default : break ; } } } Int_t iCutBit = 0; if (nHitsITS >= fMinNHitITS ) fBitmap->SetBitNumber(iCutBit,kTRUE); iCutBit++; if (nHitsTPC >= fMinNHitTPC ) fBitmap->SetBitNumber(iCutBit,kTRUE); iCutBit++; if (nHitsTRD >= fMinNHitTRD ) fBitmap->SetBitNumber(iCutBit,kTRUE); iCutBit++; if (nHitsTOF >= fMinNHitTOF ) fBitmap->SetBitNumber(iCutBit,kTRUE); iCutBit++; if (nHitsMUON >= fMinNHitMUON) fBitmap->SetBitNumber(iCutBit,kTRUE); } void AliCFAcceptanceCuts::SetMCEventInfo(const TObject* mcInfo) { // // Sets pointer to MC event information (AliMCEvent) // if (!mcInfo) { AliError("Pointer to AliMCEvent !"); return; } TString className(mcInfo->ClassName()); if (className.CompareTo("AliMCEvent") != 0) { AliError("argument must point to an AliMCEvent !"); return ; } fMCInfo = (AliMCEvent*) mcInfo ; } //__________________________________________________________________________________ void AliCFAcceptanceCuts::AddQAHistograms(TList *qaList) { // // saves the histograms in a TList // DefineHistograms(); qaList->Add(fhCutStatistics); qaList->Add(fhCutCorrelation); for (Int_t j=0; j<kNStepQA; j++) { for(Int_t i=0; i<kNCuts; i++) qaList->Add(fhQA[i][j]); } } //__________________________________________________________________________________ void AliCFAcceptanceCuts::DefineHistograms() { // // histograms for cut variables, cut statistics and cut correlations // Int_t color = 2; // book cut statistics and cut correlation histograms fhCutStatistics = new TH1F(Form("%s_cut_statistics",GetName()),"",kNCuts,0.5,kNCuts+0.5); fhCutStatistics->SetLineWidth(2); int k = 1; fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits ITS") ; k++; fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits TPC") ; k++; fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits TRD") ; k++; fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits TOF") ; k++; fhCutStatistics->GetXaxis()->SetBinLabel(k,"hits MUON"); k++; fhCutCorrelation = new TH2F(Form("%s_cut_correlation",GetName()),"",kNCuts,0.5,kNCuts+0.5,kNCuts,0.5,kNCuts+0.5); fhCutCorrelation->SetLineWidth(2); for (k=1; k<=kNCuts; k++) { fhCutCorrelation->GetXaxis()->SetBinLabel(k,fhCutStatistics->GetXaxis()->GetBinLabel(k)); fhCutCorrelation->GetYaxis()->SetBinLabel(k,fhCutStatistics->GetXaxis()->GetBinLabel(k)); } Char_t str[5]; for (int i=0; i<kNStepQA; i++) { if (i==0) snprintf(str,5," "); else snprintf(str,5,"_cut"); fhQA[kCutHitsITS] [i] = new TH1F(Form("%s_HitsITS%s" ,GetName(),str),"",10,0,10); fhQA[kCutHitsTPC] [i] = new TH1F(Form("%s_HitsTPC%s" ,GetName(),str),"",5,0,5); fhQA[kCutHitsTRD] [i] = new TH1F(Form("%s_HitsTRD%s" ,GetName(),str),"",20,0,20); fhQA[kCutHitsTOF] [i] = new TH1F(Form("%s_HitsTOF%s" ,GetName(),str),"",5,0,5); fhQA[kCutHitsMUON][i] = new TH1F(Form("%s_HitsMUON%s" ,GetName(),str),"",5,0,5); } for(Int_t i=0; i<kNCuts; i++) fhQA[i][1]->SetLineColor(color); } //__________________________________________________________________________________ void AliCFAcceptanceCuts::FillHistograms(TObject* obj, Bool_t afterCuts) { // // fill the QA histograms // AliMCParticle* part = dynamic_cast<AliMCParticle *>(obj); if (!part) { AliError("casting failed"); return; } Int_t nHitsITS=0, nHitsTPC=0, nHitsTRD=0, nHitsTOF=0, nHitsMUON=0 ; for (Int_t iTrackRef=0; iTrackRef<part->GetNumberOfTrackReferences(); iTrackRef++) { AliTrackReference * trackRef = part->GetTrackReference(iTrackRef); if(trackRef){ Int_t detectorId = trackRef->DetectorId(); switch(detectorId) { case AliTrackReference::kITS : nHitsITS++ ; break ; case AliTrackReference::kTPC : nHitsTPC++ ; break ; case AliTrackReference::kTRD : nHitsTRD++ ; break ; case AliTrackReference::kTOF : nHitsTOF++ ; break ; case AliTrackReference::kMUON : nHitsMUON++ ; break ; default : break ; } } } fhQA[kCutHitsITS ][afterCuts]->Fill(nHitsITS ); fhQA[kCutHitsTPC ][afterCuts]->Fill(nHitsTPC ); fhQA[kCutHitsTRD ][afterCuts]->Fill(nHitsTRD ); fhQA[kCutHitsTOF ][afterCuts]->Fill(nHitsTOF ); fhQA[kCutHitsMUON][afterCuts]->Fill(nHitsMUON); // fill cut statistics and cut correlation histograms with information from the bitmap if (afterCuts) return; // Number of single cuts in this class UInt_t ncuts = fBitmap->GetNbits(); for(UInt_t bit=0; bit<ncuts;bit++) { if (!fBitmap->TestBitNumber(bit)) { fhCutStatistics->Fill(bit+1); for (UInt_t bit2=bit; bit2<ncuts;bit2++) { if (!fBitmap->TestBitNumber(bit2)) fhCutCorrelation->Fill(bit+1,bit2+1); } } } }
9,988
4,051
// -*- mode:C++; tab-width:8; c-basic-offset:2; indent-tabs-mode:t -*- // vim: ts=8 sw=2 smarttab /* * Ceph - scalable distributed file system * * Copyright (C) 2011 New Dream Network * * This is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software * Foundation. See file COPYING. * */ #include "gtest/gtest.h" #include "include/cephfs/libcephfs.h" #include <errno.h> #include <fcntl.h> #include <unistd.h> #include <sys/types.h> #include <sys/stat.h> #include <dirent.h> #include <sys/xattr.h> TEST(LibCephFS, MulticlientSimple) { struct ceph_mount_info *ca, *cb; ASSERT_EQ(ceph_create(&ca, NULL), 0); ASSERT_EQ(ceph_conf_read_file(ca, NULL), 0); ASSERT_EQ(0, ceph_conf_parse_env(ca, NULL)); ASSERT_EQ(ceph_mount(ca, NULL), 0); ASSERT_EQ(ceph_create(&cb, NULL), 0); ASSERT_EQ(ceph_conf_read_file(cb, NULL), 0); ASSERT_EQ(0, ceph_conf_parse_env(cb, NULL)); ASSERT_EQ(ceph_mount(cb, NULL), 0); char name[20]; snprintf(name, sizeof(name), "foo.%d", getpid()); int fda = ceph_open(ca, name, O_CREAT|O_RDWR, 0644); ASSERT_LE(0, fda); int fdb = ceph_open(cb, name, O_CREAT|O_RDWR, 0644); ASSERT_LE(0, fdb); char bufa[4] = "foo"; char bufb[4]; for (int i=0; i<10; i++) { strcpy(bufa, "foo"); ASSERT_EQ((int)sizeof(bufa), ceph_write(ca, fda, bufa, sizeof(bufa), i*6)); ASSERT_EQ((int)sizeof(bufa), ceph_read(cb, fdb, bufb, sizeof(bufa), i*6)); ASSERT_EQ(0, memcmp(bufa, bufb, sizeof(bufa))); strcpy(bufb, "bar"); ASSERT_EQ((int)sizeof(bufb), ceph_write(cb, fdb, bufb, sizeof(bufb), i*6+3)); ASSERT_EQ((int)sizeof(bufb), ceph_read(ca, fda, bufa, sizeof(bufb), i*6+3)); ASSERT_EQ(0, memcmp(bufa, bufb, sizeof(bufa))); } ceph_close(ca, fda); ceph_close(cb, fdb); ceph_shutdown(ca); ceph_shutdown(cb); } TEST(LibCephFS, MulticlientHoleEOF) { struct ceph_mount_info *ca, *cb; ASSERT_EQ(ceph_create(&ca, NULL), 0); ASSERT_EQ(ceph_conf_read_file(ca, NULL), 0); ASSERT_EQ(0, ceph_conf_parse_env(ca, NULL)); ASSERT_EQ(ceph_mount(ca, NULL), 0); ASSERT_EQ(ceph_create(&cb, NULL), 0); ASSERT_EQ(ceph_conf_read_file(cb, NULL), 0); ASSERT_EQ(0, ceph_conf_parse_env(cb, NULL)); ASSERT_EQ(ceph_mount(cb, NULL), 0); char name[20]; snprintf(name, sizeof(name), "foo.%d", getpid()); int fda = ceph_open(ca, name, O_CREAT|O_RDWR, 0644); ASSERT_LE(0, fda); int fdb = ceph_open(cb, name, O_CREAT|O_RDWR, 0644); ASSERT_LE(0, fdb); ASSERT_EQ(3, ceph_write(ca, fda, "foo", 3, 0)); ASSERT_EQ(0, ceph_ftruncate(ca, fda, 1000000)); char buf[4]; ASSERT_EQ(2, ceph_read(cb, fdb, buf, sizeof(buf), 1000000-2)); ASSERT_EQ(0, buf[0]); ASSERT_EQ(0, buf[1]); ceph_close(ca, fda); ceph_close(cb, fdb); ceph_shutdown(ca); ceph_shutdown(cb); }
2,864
1,390
/* 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, write to the Free Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA. */ namespace jlv2 { static uint32 portBufferPadSize (uint32 size) { return (size + 7) & (~7); } PortBuffer::PortBuffer (bool inputPort, uint32 portType, uint32 dataType, uint32 bufferSize) : type (portType), capacity (std::max (sizeof (float), (size_t) bufferSize)), bufferType (dataType), input (inputPort) { data.reset (new uint8 [capacity]); if (type == PortType::Atom) { buffer.atom = (LV2_Atom*) data.get(); } else if (type == PortType::Event) { buffer.event = (LV2_Event_Buffer*) data.get(); } else if (type == PortType::Audio) { buffer.audio = (float*) data.get(); } else if (type == PortType::Control) { buffer.control = (float*) data.get(); } else { // trying to use an unsupported buffer type jassertfalse; } reset(); } PortBuffer::~PortBuffer() { buffer.atom = nullptr; data.reset(); } float PortBuffer::getValue() const { jassert (type == PortType::Control); jassert (buffer.control != nullptr); return *buffer.control; } void PortBuffer::setValue (float newValue) { jassert (type == PortType::Control); jassert (buffer.control != nullptr); *buffer.control = newValue; } bool PortBuffer::addEvent (int64 frames, uint32 size, uint32 bodyType, const uint8* data) { if (isSequence()) { if (sizeof(LV2_Atom) + buffer.atom->size + lv2_atom_pad_size(size) > capacity) return false; LV2_Atom_Sequence* seq = (LV2_Atom_Sequence*) buffer.atom; LV2_Atom_Event* ev = (LV2_Atom_Event*) ((uint8*)seq + lv2_atom_total_size (&seq->atom)); ev->time.frames = frames; ev->body.size = size; ev->body.type = bodyType; memcpy (ev + 1, data, size); buffer.atom->size += sizeof (LV2_Atom_Event) + lv2_atom_pad_size (size); return true; } else if (isEvent()) { if (buffer.event->capacity - buffer.event->size < sizeof(LV2_Event) + size) return false; LV2_Event* ev = (LV2_Event*)(buffer.event->data + buffer.event->size); ev->frames = static_cast<uint32> (frames); ev->subframes = 0; ev->type = type; ev->size = size; memcpy ((uint8*)ev + sizeof(LV2_Event), data, size); buffer.event->size += portBufferPadSize (sizeof (LV2_Event) + size); buffer.event->event_count += 1; return true; } return false; } void PortBuffer::clear() { if (isAudio() || isControl()) { } else if (isSequence()) { buffer.atom->size = sizeof (LV2_Atom_Sequence_Body); } else if (isEvent()) { buffer.event->event_count = 0; buffer.event->size = 0; } } void PortBuffer::reset() { if (isAudio()) { buffer.atom->size = capacity - sizeof (LV2_Atom); } else if (isControl()) { buffer.atom->size = sizeof (float); buffer.atom->type = bufferType; } else if (isSequence()) { buffer.atom->size = input ? sizeof (LV2_Atom_Sequence_Body) : capacity - sizeof (LV2_Atom_Sequence_Body); buffer.atom->type = bufferType; LV2_Atom_Sequence* seq = (LV2_Atom_Sequence*) buffer.atom; seq->body.unit = 0; seq->body.pad = 0; } else if (isEvent()) { buffer.event->capacity = capacity - sizeof (LV2_Event_Buffer); buffer.event->header_size = sizeof (LV2_Event_Buffer); buffer.event->stamp_type = LV2_EVENT_AUDIO_STAMP; buffer.event->event_count = 0; buffer.event->size = 0; buffer.event->data = data.get() + sizeof (LV2_Event_Buffer); } } void* PortBuffer::getPortData() const { return referenced ? buffer.referred : data.get(); } }
4,557
1,540
/* Cafu Engine, http://www.cafu.de/ Copyright (c) Carsten Fuchs and other contributors. This project is licensed under the terms of the MIT license. */ #ifndef CAFU_OBSERVER_PATTERN_HPP_INCLUDED #define CAFU_OBSERVER_PATTERN_HPP_INCLUDED /// \file /// This file provides the classes for the Observer pattern as described in the book by the GoF. /// Note that implementations of ObserverT normally maintain a pointer to the subject(s) that they observe, /// e.g. in order to be able to redraw themselves also outside of and independent from the NotifySubjectChanged() method. /// This however in turn creates problems when the life of the observer begins before or ends after the life of the observed subject(s). /// In fact, it seems that the observers have to maintain lists of valid, observed subjects as the subjects maintain lists of observers. /// Fortunately, these possibly tough problems can (and apparently must) be addressed by the concrete implementation classes of /// observers and subjects, not by the base classes that the Observer pattern describes and provided herein. #include "Math3D/BoundingBox.hpp" #include "Templates/Array.hpp" #include "Templates/Pointer.hpp" #include "wx/string.h" namespace cf { namespace GameSys { class EntityT; } } namespace cf { namespace TypeSys { class VarBaseT; } } namespace MapEditor { class CompMapEntityT; } class SubjectT; class MapElementT; class MapPrimitiveT; //##################################### //# New observer notifications hints. # //##################################### enum MapElemModDetailE { MEMD_GENERIC, ///< Generic change of map elements (useful if the subject doesn't know what exactly has been changed). MEMD_TRANSFORM, ///< A map element has been transformed. MEMD_PRIMITIVE_PROPS_CHANGED, ///< The properties of a map primitive have been modified. MEMD_SURFACE_INFO_CHANGED, ///< The surface info of a map element has changed. Note that surface info changes also include the selection of faces. MEMD_ASSIGN_PRIM_TO_ENTITY, ///< A map primitive has been assigned to another entity (the world or any custom entity). MEMD_VISIBILITY ///< The visibility of a map element has changed. }; enum EntityModDetailE { EMD_COMPONENTS, ///< The set of components has changed (e.g. added, deleted, order changed). EMD_HIERARCHY ///< The position of an entity in the entity hierarchy has changed. }; enum MapDocOtherDetailT { UPDATE_GRID, UPDATE_POINTFILE, UPDATE_GLOBALOPTIONS }; //############################################ //# End of new observer notifications hints. # //############################################ class ObserverT { public: //################################################################################################################################### //# New observer notifications methods. These methods differ from the basic observer pattern from the GoF and are CaWE specific! # //# Note that the new methods are NOT pure virtual since a concrete observer might not be interested in some of these notifications # //################################################################################################################################### /// Notifies the observer that some other detail than those specifically addressed below has changed. virtual void NotifySubjectChanged(SubjectT* Subject, MapDocOtherDetailT OtherDetail) { } /// Notifies the observer that the selection in the current subject has been changed. /// @param Subject The map document in which the selection has been changed. /// @param OldSelection Array of the previously selected objects. /// @param NewSelection Array of the new selected objects. virtual void NotifySubjectChanged_Selection(SubjectT* Subject, const ArrayT<MapElementT*>& OldSelection, const ArrayT<MapElementT*>& NewSelection) { } /// Notifies the observer that the groups in the current subject have been changed (new group added, group deleted, visibility changed, anything). /// @param Subject The map document in which the group inventory has been changed. virtual void NotifySubjectChanged_Groups(SubjectT* Subject) { } /// Notifies the observer that one or more entities have been created. /// @param Subject The map document in which the entities have been created. /// @param Entities List of created entities. virtual void NotifySubjectChanged_Created(SubjectT* Subject, const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities) { } /// Notifies the observer that one or more map primitives have been created. /// @param Subject The map document in which the primitives have been created. /// @param Primitives List of created map primitives. virtual void NotifySubjectChanged_Created(SubjectT* Subject, const ArrayT<MapPrimitiveT*>& Primitives) { } /// Notifies the observer that one or more entities have been deleted. /// @param Subject The map document in which the entities have been deleted. /// @param Entities List of deleted entities. virtual void NotifySubjectChanged_Deleted(SubjectT* Subject, const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities) { } /// Notifies the observer that one or more map primitives have been deleted. /// @param Subject The map document in which the primitives have been deleted. /// @param Primitives List of deleted map primitives. virtual void NotifySubjectChanged_Deleted(SubjectT* Subject, const ArrayT<MapPrimitiveT*>& Primitives) { } /// @name Modification notification method and overloads. /// These methods notify the observer that one or more map elements have been modified. /// The first 3 parameters are common to all of these methods since they are the basic information needed to communicate /// an object modification. //@{ /// @param Subject The map document in which the elements have been modified. /// @param MapElements List of modified map elements. /// @param Detail Information about what has been modified: /// Can be one of MEMD_PRIMITIVE_PROPS_CHANGED, MEMD_GENERIC, MEMD_ASSIGN_PRIM_TO_ENTITY and MEMD_MATERIAL_CHANGED. virtual void NotifySubjectChanged_Modified(SubjectT* Subject, const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail) { } /// @param Subject The map document in which the elements have been modified. /// @param MapElements List of modified map elements. /// @param Detail Information about what has been modified: /// Can be MEMD_TRANSFORM or MEMD_PRIMITIVE_PROPS_CHANGED. /// In the case of MEMD_PRIMITIVE_PROPS_CHANGED one can assume that /// only map primitives (no entities) are in the MapElements array. /// @param OldBounds Holds the bounds of each objects BEFORE the modification (has the same size as MapElements). virtual void NotifySubjectChanged_Modified(SubjectT* Subject, const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail, const ArrayT<BoundingBox3fT>& OldBounds) { } /// @param Subject The map document in which the entities have been modified. /// @param Entities List of modified map entities. /// @param Detail Information about what has been modified. virtual void Notify_EntChanged(SubjectT* Subject, const ArrayT< IntrusivePtrT<MapEditor::CompMapEntityT> >& Entities, EntityModDetailE Detail) { } /// Notifies the observer that a variable has changed. /// @param Subject The map document in which a variable has changed. /// @param Var The variable whose value has changed. virtual void Notify_VarChanged(SubjectT* Subject, const cf::TypeSys::VarBaseT& Var) { } //@} //############################################ //# End of new observer notification methods # //############################################ /// This method is called whenever a subject is about the be destroyed (and become unavailable). /// \param dyingSubject The subject that is being destroyed. virtual void NotifySubjectDies(SubjectT* dyingSubject)=0; /// The virtual destructor. virtual ~ObserverT(); protected: /// The constructor. It is protected so that only derived classes can create instances of this class. ObserverT(); }; class SubjectT { public: /// Registers the observer Obs for notification on updates of this class. /// \param Obs The observer that is to be registered. void RegisterObserver(ObserverT* Obs); /// Unregisters the observer Obs from further notification on updates of this class. /// \param Obs The observer that is to be unregistered. void UnregisterObserver(ObserverT* Obs); //################################################################################################################################### //# New observer notifications methods. These methods differ from the basic observer pattern from the GoF and are CaWE specific! # //# For detailed comments on the parameters, see the equivalent methods in ObserverT # //################################################################################################################################### void UpdateAllObservers(MapDocOtherDetailT OtherDetail); void UpdateAllObservers_SelectionChanged(const ArrayT<MapElementT*>& OldSelection, const ArrayT<MapElementT*>& NewSelection); void UpdateAllObservers_GroupsChanged(); void UpdateAllObservers_Created(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities); void UpdateAllObservers_Created(const ArrayT<MapPrimitiveT*>& Primitives); void UpdateAllObservers_Deleted(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entites); void UpdateAllObservers_Deleted(const ArrayT<MapPrimitiveT*>& Primitives); void UpdateAllObservers_Modified(const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail); void UpdateAllObservers_Modified(const ArrayT<MapElementT*>& MapElements, MapElemModDetailE Detail, const ArrayT<BoundingBox3fT>& OldBounds); void UpdateAllObservers_EntChanged(const ArrayT< IntrusivePtrT<MapEditor::CompMapEntityT> >& Entities, EntityModDetailE Detail); void UpdateAllObservers_EntChanged(const ArrayT< IntrusivePtrT<cf::GameSys::EntityT> >& Entities, EntityModDetailE Detail); void UpdateAllObservers_EntChanged(IntrusivePtrT<cf::GameSys::EntityT> Entity, EntityModDetailE Detail); void UpdateAllObservers_VarChanged(const cf::TypeSys::VarBaseT& Var); void UpdateAllObservers_SubjectDies(); /// The virtual destructor. virtual ~SubjectT(); protected: /// The constructor. It is protected so that only derived classes can create instances of this class. SubjectT(); private: /// The list of the observers that have registered for notification on updates of this class. ArrayT<ObserverT*> m_Observers; }; #endif
11,146
2,878
#include "rfx/pch.h" #include "rfx/application/Window.h" #include <rfx/common/Algorithm.h> #ifdef _WINDOWS #define GLFW_EXPOSE_NATIVE_WIN32 #include <GLFW/glfw3native.h> #endif // _WINDOWS using namespace rfx; using namespace std; // --------------------------------------------------------------------------------------------------------------------- void Window::create(const string& title, int width, int height) { glfwWindowHint(GLFW_VISIBLE, GLFW_FALSE); window = glfwCreateWindow(width, height, title.c_str(), nullptr, nullptr); if (!window) { RFX_THROW("Failed to create window"); } glfwGetFramebufferSize(window, &width_, &height_); glfwSetWindowUserPointer(window, this); glfwSetKeyCallback(window, onKeyEvent); glfwSetFramebufferSizeCallback(window, onResize); glfwSetCursorEnterCallback(window, onCursorEntered); glfwSetCursorPosCallback(window, onCursorPos); } // --------------------------------------------------------------------------------------------------------------------- void Window::show() { glfwShowWindow(window); } // --------------------------------------------------------------------------------------------------------------------- void Window::onResize(GLFWwindow* window, int width, int height) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onResize(width, height); } // --------------------------------------------------------------------------------------------------------------------- void Window::onResize(int width, int height) { width_ = width; height_ = height; ranges::for_each(listeners, [this, width, height](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onResized(*this, width, height); } }); } // --------------------------------------------------------------------------------------------------------------------- GLFWwindow* Window::getGlfwWindow() const { return window; } // --------------------------------------------------------------------------------------------------------------------- void* Window::getHandle() const { return glfwGetWin32Window(window); } // --------------------------------------------------------------------------------------------------------------------- uint32_t Window::getClientWidth() const { return width_; } // --------------------------------------------------------------------------------------------------------------------- uint32_t Window::getClientHeight() const { return height_; } // --------------------------------------------------------------------------------------------------------------------- void Window::addListener(const shared_ptr<WindowListener>& listener) { if (!contains(listeners, listener)) { listeners.push_back(listener); } } // --------------------------------------------------------------------------------------------------------------------- void Window::onKeyEvent(GLFWwindow* window, int key, int scancode, int action, int mods) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onKeyEvent(key, scancode, action, mods); } // --------------------------------------------------------------------------------------------------------------------- void Window::onKeyEvent(int key, int scancode, int action, int mods) { ranges::for_each(listeners, [this, key, scancode, action, mods](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onKeyEvent(*this, key, scancode, action, mods); } }); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorPos(GLFWwindow* window, double x, double y) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onCursorPos(static_cast<float>(x), static_cast<float>(y)); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorPos(float x, float y) { ranges::for_each(listeners, [this, x, y](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onCursorPos(*this, x, y); } }); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorEntered(GLFWwindow* window, int entered) { auto rfxWindow = reinterpret_cast<Window*>(glfwGetWindowUserPointer(window)); rfxWindow->onCursorEntered(entered); } // --------------------------------------------------------------------------------------------------------------------- void Window::onCursorEntered(bool entered) { ranges::for_each(listeners, [this, entered](const weak_ptr<WindowListener>& weakListener) { if (auto listener = weakListener.lock()) { listener->onCursorEntered(*this, entered); } }); } // ---------------------------------------------------------------------------------------------------------------------
5,354
1,296
//===-- FindAllSymbolsTests.cpp - find all symbols unit tests ---*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "FindAllSymbolsAction.h" #include "HeaderMapCollector.h" #include "SymbolInfo.h" #include "SymbolReporter.h" #include "clang/ASTMatchers/ASTMatchFinder.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Frontend/CompilerInstance.h" #include "clang/Frontend/PCHContainerOperations.h" #include "clang/Tooling/Tooling.h" #include "llvm/ADT/IntrusiveRefCntPtr.h" #include "llvm/ADT/STLExtras.h" #include "llvm/ADT/StringRef.h" #include "llvm/Support/MemoryBuffer.h" #include "llvm/Support/VirtualFileSystem.h" #include "gtest/gtest.h" #include <memory> #include <string> #include <vector> namespace clang { namespace find_all_symbols { static const char HeaderName[] = "symbols.h"; class TestSymbolReporter : public SymbolReporter { public: ~TestSymbolReporter() override {} void reportSymbols(llvm::StringRef FileName, const SymbolInfo::SignalMap &NewSymbols) override { for (const auto &Entry : NewSymbols) Symbols[Entry.first] += Entry.second; } int seen(const SymbolInfo &Symbol) const { auto it = Symbols.find(Symbol); return it == Symbols.end() ? 0 : it->second.Seen; } int used(const SymbolInfo &Symbol) const { auto it = Symbols.find(Symbol); return it == Symbols.end() ? 0 : it->second.Used; } private: SymbolInfo::SignalMap Symbols; }; class FindAllSymbolsTest : public ::testing::Test { public: int seen(const SymbolInfo &Symbol) { return Reporter.seen(Symbol); } int used(const SymbolInfo &Symbol) { return Reporter.used(Symbol); } bool runFindAllSymbols(StringRef HeaderCode, StringRef MainCode) { llvm::IntrusiveRefCntPtr<llvm::vfs::InMemoryFileSystem> InMemoryFileSystem( new llvm::vfs::InMemoryFileSystem); llvm::IntrusiveRefCntPtr<FileManager> Files( new FileManager(FileSystemOptions(), InMemoryFileSystem)); std::string FileName = "symbol.cc"; const std::string InternalHeader = "internal/internal_header.h"; const std::string TopHeader = "<top>"; // Test .inc header path. The header for `IncHeaderClass` should be // internal.h, which will eventually be mapped to <top>. std::string IncHeader = "internal/private.inc"; std::string IncHeaderCode = "class IncHeaderClass {};"; HeaderMapCollector::RegexHeaderMap RegexMap = { {R"(internal_.*\.h$)", TopHeader.c_str()}, }; std::string InternalCode = "#include \"private.inc\"\nclass Internal {};"; SymbolInfo InternalSymbol("Internal", SymbolInfo::SymbolKind::Class, TopHeader, {}); SymbolInfo IncSymbol("IncHeaderClass", SymbolInfo::SymbolKind::Class, TopHeader, {}); InMemoryFileSystem->addFile( IncHeader, 0, llvm::MemoryBuffer::getMemBuffer(IncHeaderCode)); InMemoryFileSystem->addFile(InternalHeader, 0, llvm::MemoryBuffer::getMemBuffer(InternalCode)); std::unique_ptr<tooling::FrontendActionFactory> Factory( new FindAllSymbolsActionFactory(&Reporter, &RegexMap)); tooling::ToolInvocation Invocation( {std::string("find_all_symbols"), std::string("-fsyntax-only"), std::string("-std=c++11"), FileName}, Factory->create(), Files.get(), std::make_shared<PCHContainerOperations>()); InMemoryFileSystem->addFile(HeaderName, 0, llvm::MemoryBuffer::getMemBuffer(HeaderCode)); std::string Content = "#include\"" + std::string(HeaderName) + "\"\n" "#include \"" + InternalHeader + "\""; #if !defined(_MSC_VER) && !defined(__MINGW32__) // Test path cleaning for both decls and macros. const std::string DirtyHeader = "./internal/./a/b.h"; Content += "\n#include \"" + DirtyHeader + "\""; const std::string CleanHeader = "internal/a/b.h"; const std::string DirtyHeaderContent = "#define INTERNAL 1\nclass ExtraInternal {};"; InMemoryFileSystem->addFile( DirtyHeader, 0, llvm::MemoryBuffer::getMemBuffer(DirtyHeaderContent)); SymbolInfo DirtyMacro("INTERNAL", SymbolInfo::SymbolKind::Macro, CleanHeader, {}); SymbolInfo DirtySymbol("ExtraInternal", SymbolInfo::SymbolKind::Class, CleanHeader, {}); #endif // _MSC_VER && __MINGW32__ Content += "\n" + MainCode.str(); InMemoryFileSystem->addFile(FileName, 0, llvm::MemoryBuffer::getMemBuffer(Content)); Invocation.run(); EXPECT_EQ(1, seen(InternalSymbol)); EXPECT_EQ(1, seen(IncSymbol)); #if !defined(_MSC_VER) && !defined(__MINGW32__) EXPECT_EQ(1, seen(DirtySymbol)); EXPECT_EQ(1, seen(DirtyMacro)); #endif // _MSC_VER && __MINGW32__ return true; } protected: TestSymbolReporter Reporter; }; TEST_F(FindAllSymbolsTest, VariableSymbols) { static const char Header[] = R"( extern int xargc; namespace na { static bool SSSS = false; namespace nb { const long long *XXXX; } })"; static const char Main[] = R"( auto y = &na::nb::XXXX; int main() { if (na::SSSS) return xargc; } )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("xargc", SymbolInfo::SymbolKind::Variable, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("SSSS", SymbolInfo::SymbolKind::Variable, HeaderName, {{SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("XXXX", SymbolInfo::SymbolKind::Variable, HeaderName, {{SymbolInfo::ContextType::Namespace, "nb"}, {SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, ExternCSymbols) { static const char Header[] = R"( extern "C" { int C_Func() { return 0; } struct C_struct { int Member; }; })"; static const char Main[] = R"( C_struct q() { int(*ptr)() = C_Func; return {0}; } )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("C_Func", SymbolInfo::SymbolKind::Function, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("C_struct", SymbolInfo::SymbolKind::Class, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, CXXRecordSymbols) { static const char Header[] = R"( struct Glob {}; struct A; // Not a defintion, ignored. class NOP; // Not a defintion, ignored namespace na { struct A { struct AAAA {}; int x; int y; void f() {} }; }; // )"; static const char Main[] = R"( static Glob glob; static na::A::AAAA* a; )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("Glob", SymbolInfo::SymbolKind::Class, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("A", SymbolInfo::SymbolKind::Class, HeaderName, {{SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("AAA", SymbolInfo::SymbolKind::Class, HeaderName, {{SymbolInfo::ContextType::Record, "A"}, {SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(0, seen(Symbol)); EXPECT_EQ(0, used(Symbol)); } TEST_F(FindAllSymbolsTest, CXXRecordSymbolsTemplate) { static const char Header[] = R"( template <typename T> struct T_TEMP { template <typename _Tp1> struct rebind { typedef T_TEMP<_Tp1> other; }; }; // Ignore specialization. template class T_TEMP<char>; template <typename T> class Observer { }; // Ignore specialization. template <> class Observer<int> {}; )"; static const char Main[] = R"( extern T_TEMP<int>::rebind<char> weirdo; )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("T_TEMP", SymbolInfo::SymbolKind::Class, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, DontIgnoreTemplatePartialSpecialization) { static const char Code[] = R"( template<class> class Class; // undefined template<class R, class... ArgTypes> class Class<R(ArgTypes...)> { }; template<class T> void f() {}; template<> void f<int>() {}; )"; runFindAllSymbols(Code, ""); SymbolInfo Symbol = SymbolInfo("Class", SymbolInfo::SymbolKind::Class, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); Symbol = SymbolInfo("f", SymbolInfo::SymbolKind::Function, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); } TEST_F(FindAllSymbolsTest, FunctionSymbols) { static const char Header[] = R"( namespace na { int gg(int); int f(const int &a) { int Local; static int StaticLocal; return 0; } static void SSSFFF() {} } // namespace na namespace na { namespace nb { template<typename T> void fun(T t) {}; } // namespace nb } // namespace na"; )"; static const char Main[] = R"( int(*gg)(int) = &na::gg; int main() { (void)na::SSSFFF; na::nb::fun(0); return na::f(gg(0)); } )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("gg", SymbolInfo::SymbolKind::Function, HeaderName, {{SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("f", SymbolInfo::SymbolKind::Function, HeaderName, {{SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("SSSFFF", SymbolInfo::SymbolKind::Function, HeaderName, {{SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("fun", SymbolInfo::SymbolKind::Function, HeaderName, {{SymbolInfo::ContextType::Namespace, "nb"}, {SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, NamespaceTest) { static const char Header[] = R"( int X1; namespace { int X2; } namespace { namespace { int X3; } } namespace { namespace nb { int X4; } } namespace na { inline namespace __1 { int X5; } } )"; static const char Main[] = R"( using namespace nb; int main() { X1 = X2; X3 = X4; (void)na::X5; } )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("X1", SymbolInfo::SymbolKind::Variable, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("X2", SymbolInfo::SymbolKind::Variable, HeaderName, {{SymbolInfo::ContextType::Namespace, ""}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("X3", SymbolInfo::SymbolKind::Variable, HeaderName, {{SymbolInfo::ContextType::Namespace, ""}, {SymbolInfo::ContextType::Namespace, ""}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("X4", SymbolInfo::SymbolKind::Variable, HeaderName, {{SymbolInfo::ContextType::Namespace, "nb"}, {SymbolInfo::ContextType::Namespace, ""}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("X5", SymbolInfo::SymbolKind::Variable, HeaderName, {{SymbolInfo::ContextType::Namespace, "na"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, DecayedTypeTest) { static const char Header[] = "void DecayedFunc(int x[], int y[10]) {}"; static const char Main[] = R"(int main() { DecayedFunc(nullptr, nullptr); })"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo( "DecayedFunc", SymbolInfo::SymbolKind::Function, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, CTypedefTest) { static const char Header[] = R"( typedef unsigned size_t_; typedef struct { int x; } X; using XX = X; )"; static const char Main[] = R"( size_t_ f; template<typename T> struct vector{}; vector<X> list; void foo(const XX&){} )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("size_t_", SymbolInfo::SymbolKind::TypedefName, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("X", SymbolInfo::SymbolKind::TypedefName, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("XX", SymbolInfo::SymbolKind::TypedefName, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, EnumTest) { static const char Header[] = R"( enum Glob_E { G1, G2 }; enum class Altitude { high='h', low='l'}; enum { A1, A2 }; class A { public: enum A_ENUM { X1, X2 }; }; enum DECL : int; )"; static const char Main[] = R"( static auto flags = G1 | G2; static auto alt = Altitude::high; static auto nested = A::X1; extern DECL whatever; static auto flags2 = A1 | A2; )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("Glob_E", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(0, used(Symbol)); Symbol = SymbolInfo("G1", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, {{SymbolInfo::ContextType::EnumDecl, "Glob_E"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("G2", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, {{SymbolInfo::ContextType::EnumDecl, "Glob_E"}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("Altitude", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("high", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, {{SymbolInfo::ContextType::EnumDecl, "Altitude"}}); EXPECT_EQ(0, seen(Symbol)); EXPECT_EQ(0, used(Symbol)); Symbol = SymbolInfo("A1", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, {{SymbolInfo::ContextType::EnumDecl, ""}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("A2", SymbolInfo::SymbolKind::EnumConstantDecl, HeaderName, {{SymbolInfo::ContextType::EnumDecl, ""}}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {}); EXPECT_EQ(0, seen(Symbol)); EXPECT_EQ(0, used(Symbol)); Symbol = SymbolInfo("A_ENUM", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {{SymbolInfo::ContextType::Record, "A"}}); EXPECT_EQ(0, seen(Symbol)); EXPECT_EQ(0, used(Symbol)); Symbol = SymbolInfo("X1", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {{SymbolInfo::ContextType::EnumDecl, "A_ENUM"}, {SymbolInfo::ContextType::Record, "A"}}); EXPECT_EQ(0, seen(Symbol)); Symbol = SymbolInfo("DECL", SymbolInfo::SymbolKind::EnumDecl, HeaderName, {}); EXPECT_EQ(0, seen(Symbol)); } TEST_F(FindAllSymbolsTest, IWYUPrivatePragmaTest) { static const char Header[] = R"( // IWYU pragma: private, include "bar.h" struct Bar { }; )"; static const char Main[] = R"( Bar bar; )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("Bar", SymbolInfo::SymbolKind::Class, "bar.h", {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, MacroTest) { static const char Header[] = R"( #define X #define Y 1 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) )"; static const char Main[] = R"( #ifdef X int main() { return MAX(0,Y); } #endif )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("X", SymbolInfo::SymbolKind::Macro, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, MacroTestWithIWYU) { static const char Header[] = R"( // IWYU pragma: private, include "bar.h" #define X 1 #define Y 1 #define MAX(X, Y) ((X) > (Y) ? (X) : (Y)) )"; static const char Main[] = R"( #ifdef X int main() { return MAX(0,Y); } #endif )"; runFindAllSymbols(Header, Main); SymbolInfo Symbol = SymbolInfo("X", SymbolInfo::SymbolKind::Macro, "bar.h", {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("Y", SymbolInfo::SymbolKind::Macro, "bar.h", {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); Symbol = SymbolInfo("MAX", SymbolInfo::SymbolKind::Macro, "bar.h", {}); EXPECT_EQ(1, seen(Symbol)); EXPECT_EQ(1, used(Symbol)); } TEST_F(FindAllSymbolsTest, NoFriendTest) { static const char Header[] = R"( class WorstFriend { friend void Friend(); friend class BestFriend; }; )"; runFindAllSymbols(Header, ""); SymbolInfo Symbol = SymbolInfo("WorstFriend", SymbolInfo::SymbolKind::Class, HeaderName, {}); EXPECT_EQ(1, seen(Symbol)); Symbol = SymbolInfo("Friend", SymbolInfo::SymbolKind::Function, HeaderName, {}); EXPECT_EQ(0, seen(Symbol)); Symbol = SymbolInfo("BestFriend", SymbolInfo::SymbolKind::Class, HeaderName, {}); EXPECT_EQ(0, seen(Symbol)); } } // namespace find_all_symbols } // namespace clang
18,781
6,335
//******************************************************************* // Copyright (C) 2000 ImageLinks Inc. // // License: LGPL // // See LICENSE.txt file in the top level directory for more details. // // Author: Garrett Potts // //************************************************************************* // $Id: ossimImageChain.cpp 21850 2012-10-21 20:09:55Z dburken $ #include <ossim/imaging/ossimImageChain.h> #include <ossim/base/ossimCommon.h> #include <ossim/base/ossimConnectableContainer.h> #include <ossim/base/ossimDrect.h> #include <ossim/base/ossimNotifyContext.h> #include <ossim/base/ossimObjectFactoryRegistry.h> #include <ossim/base/ossimKeywordlist.h> #include <ossim/base/ossimTrace.h> #include <ossim/base/ossimEventIds.h> #include <ossim/base/ossimObjectEvents.h> #include <ossim/base/ossimIdManager.h> #include <ossim/base/ossimVisitor.h> #include <ossim/imaging/ossimImageData.h> #include <ossim/imaging/ossimImageGeometry.h> #include <algorithm> #include <iostream> #include <iterator> using namespace std; static ossimTrace traceDebug("ossimImageChain"); RTTI_DEF3(ossimImageChain, "ossimImageChain", ossimImageSource, ossimConnectableObjectListener, ossimConnectableContainerInterface); void ossimImageChain::processEvent(ossimEvent& event) { ossimConnectableObjectListener::processEvent(event); ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, event.getCurrentObject()); if((ossimConnectableObject*)getFirstSource() == obj) { if(event.isPropagatingToOutputs()) { ossimConnectableObject::ConnectableObjectList& outputList = getOutputList(); ossim_uint32 idx = 0; for(idx = 0; idx < outputList.size();++idx) { if(outputList[idx].valid()) { outputList[idx]->fireEvent(event); outputList[idx]->propagateEventToOutputs(event); } } } } } ossimImageChain::ossimImageChain() :ossimImageSource(0, 0, // number of inputs 0, // number of outputs false, // input's fixed false), // outputs are not fixed ossimConnectableContainerInterface((ossimObject*)NULL), theBlankTile(NULL), theLoadStateFlag(false) { ossimConnectableContainerInterface::theBaseObject = this; //thePropagateEventFlag = false; addListener((ossimConnectableObjectListener*)this); } ossimImageChain::~ossimImageChain() { removeListener((ossimConnectableObjectListener*)this); deleteList(); } bool ossimImageChain::addFirst(ossimConnectableObject* obj) { ossimConnectableObject* rightOfThisObj = (ossimConnectableObject*)getFirstObject(); return insertRight(obj, rightOfThisObj); } bool ossimImageChain::addLast(ossimConnectableObject* obj) { if(imageChainList().size() > 0) { ossimConnectableObject* lastSource = imageChainList()[ imageChainList().size() -1].get(); // if(dynamic_cast<ossimImageSource*>(obj)&&lastSource) if(lastSource) { // obj->disconnect(); ossimConnectableObject::ConnectableObjectList tempIn = getInputList(); lastSource->disconnectAllInputs(); lastSource->connectMyInputTo(obj); obj->changeOwner(this); obj->connectInputList(tempIn); tempIn = obj->getInputList(); theInputListIsFixedFlag = obj->getInputListIsFixedFlag(); setNumberOfInputs(obj->getNumberOfInputs()); imageChainList().push_back(obj); obj->addListener((ossimConnectableObjectListener*)this); // Send an event to any listeners. ossimContainerEvent event((ossimObject*)this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(obj); fireEvent(event); return true; } } else { return add(obj); } return false;; } ossimImageSource* ossimImageChain::getFirstSource() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>(imageChainList()[0].get()); } return 0; } const ossimImageSource* ossimImageChain::getFirstSource() const { if(imageChainList().size()>0) return dynamic_cast<const ossimImageSource*>(imageChainList()[0].get()); return 0; } ossimObject* ossimImageChain::getFirstObject() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>(imageChainList()[0].get()); } return 0; } ossimImageSource* ossimImageChain::getLastSource() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>((*(imageChainList().end()-1)).get()); } return NULL; } const ossimImageSource* ossimImageChain::getLastSource() const { if(imageChainList().size()>0) return dynamic_cast<const ossimImageSource*>((*(imageChainList().end()-1)).get()); return NULL; } ossimObject* ossimImageChain::getLastObject() { if(imageChainList().size()>0) { return dynamic_cast<ossimImageSource*>((*(imageChainList().end()-1)).get()); } return 0; } ossimConnectableObject* ossimImageChain::findObject(const ossimId& id, bool /* recurse */) { std::vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).get()) { if(id == (*current)->getId()) { return (*current).get(); } } ++current; } current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* object = child->findObject(id, true); if(object) return object; } ++current; } return NULL; } ossimConnectableObject* ossimImageChain::findObject(const ossimConnectableObject* obj, bool /* recurse */) { std::vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()) { if(obj == (*current).get()) { return (*current).get(); } } ++current; } current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* object = child->findObject(obj, true); if(object) return object; } ++current; } return 0; } ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const RTTItypeid& typeInfo, bool recurse) { vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(typeInfo)) { return (*current).get(); } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* temp = child->findFirstObjectOfType(typeInfo, recurse); if(temp) { return temp; } } ++current; } } return (ossimConnectableObject*)NULL; } ossimConnectableObject* ossimImageChain::findFirstObjectOfType(const ossimString& className, bool recurse) { vector<ossimRefPtr<ossimConnectableObject> >::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(className) ) { return (*current).get(); } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject* temp = child->findFirstObjectOfType(className, recurse); if(temp) { return temp; } } ++current; } } return (ossimConnectableObject*)0; } ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const RTTItypeid& typeInfo, bool recurse) { ossimConnectableObject::ConnectableObjectList result; ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(typeInfo)) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), (*current).get()); if(iter == result.end()) { result.push_back((*current).get()); } } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject::ConnectableObjectList temp; temp = child->findAllObjectsOfType(typeInfo, recurse); for(long index=0; index < (long)temp.size();++index) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]); if(iter == result.end()) { result.push_back(temp[index]); } } } ++current; } } return result; } ossimConnectableObject::ConnectableObjectList ossimImageChain::findAllObjectsOfType(const ossimString& className, bool recurse) { ossimConnectableObject::ConnectableObjectList result; ossimConnectableObject::ConnectableObjectList::iterator current = imageChainList().begin(); while(current != imageChainList().end()) { if((*current).valid()&& (*current)->canCastTo(className)) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), (*current).get()); if(iter == result.end()) { result.push_back((*current).get()); } } ++current; } if(recurse) { current = imageChainList().begin(); while(current != imageChainList().end()) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, (*current).get()); if(child) { ossimConnectableObject::ConnectableObjectList temp; temp = child->findAllObjectsOfType(className, recurse); for(long index=0; index < (long)temp.size();++index) { ossimConnectableObject::ConnectableObjectList::iterator iter = std::find(result.begin(), result.end(), temp[index]); if(iter == result.end()) { result.push_back(temp[index]); } } } ++current; } } return result; } void ossimImageChain::makeUniqueIds() { setId(ossimIdManager::instance()->generateId()); for(long index = 0; index < (long)imageChainList().size(); ++index) { ossimConnectableContainerInterface* container = PTR_CAST(ossimConnectableContainerInterface, imageChainList()[index].get()); if(container) { container->makeUniqueIds(); } else { if(imageChainList()[index].valid()) { imageChainList()[index]->setId(ossimIdManager::instance()->generateId()); } } } } ossim_uint32 ossimImageChain::getNumberOfObjects(bool recurse)const { ossim_uint32 result = (ossim_uint32)imageChainList().size(); if(recurse) { for(ossim_uint32 i = 0; i < imageChainList().size(); ++i) { ossimConnectableContainerInterface* child=PTR_CAST(ossimConnectableContainerInterface, imageChainList()[i].get()); if(child) { result += child->getNumberOfObjects(true); } } } return result; } ossim_uint32 ossimImageChain::getNumberOfSources() const { ossimNotify(ossimNotifyLevel_NOTICE) << "ossimImageChain::getNumberOfSources is deprecated!" << "\nUse: ossimImageChain::getNumberOfObjects(false)" << std::endl; return getNumberOfObjects(false); } bool ossimImageChain::addChild(ossimConnectableObject* object) { return add(object); } bool ossimImageChain::removeChild(ossimConnectableObject* object) { bool result = false; vector<ossimRefPtr<ossimConnectableObject> >::iterator current = std::find(imageChainList().begin(), imageChainList().end(), object); if(current!=imageChainList().end()) { result = true; object->removeListener((ossimConnectableObjectListener*)this); if(current == imageChainList().begin()) { object->removeListener((ossimConnectableObjectListener*)this); } if(imageChainList().size() == 1) { object->changeOwner(0); current = imageChainList().erase(current); } else { ossimConnectableObject::ConnectableObjectList input = object->getInputList(); ossimConnectableObject::ConnectableObjectList output = object->getOutputList(); object->changeOwner(0);// set the owner to 0 bool erasingBeginning = (current == imageChainList().begin()); // bool erasingEnd = (current+1) == imageChainList().end(); current = imageChainList().erase(current); object->disconnect(); if(!imageChainList().empty()) { if(erasingBeginning) // the one that receives the first getTile { (*imageChainList().begin())->addListener(this); } else if(current==imageChainList().end()) // one that receives the last getTIle { current = imageChainList().begin()+(imageChainList().size()-1); (*current)->connectInputList(input); theInputObjectList = (*current)->getInputList(); theInputListIsFixedFlag = (*current)->getInputListIsFixedFlag(); } else { // prepare interior setup and removal and connect surrounding nodes // take the outputs of the node we are removing and connect them to the old inputs ossim_uint32 outIndex = 0; for(outIndex = 0; outIndex < output.size();++outIndex) { output[outIndex]->connectInputList(input); } } } } // Send an event to any listeners. ossimContainerEvent event((ossimObject*)this, OSSIM_EVENT_REMOVE_OBJECT_ID); event.setObjectList(object); fireEvent(event); } return result; } ossimConnectableObject* ossimImageChain::removeChild(const ossimId& id) { ossimIdVisitor visitor( id, (ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS ) ); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { removeChild(obj); } return obj; } void ossimImageChain::getChildren(vector<ossimConnectableObject*>& children, bool immediateChildrenOnlyFlag) { ossim_uint32 i = 0; vector<ossimConnectableObject*> temp; for(i = 0; i < imageChainList().size();++i) { temp.push_back(imageChainList()[i].get()); } for(i = 0; i < temp.size();++i) { ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface, temp[i]); if(immediateChildrenOnlyFlag) { children.push_back(temp[i]); } else if(!interface) { children.push_back(temp[i]); } } if(!immediateChildrenOnlyFlag) { for(i = 0; i < temp.size();++i) { ossimConnectableContainerInterface* interface = PTR_CAST(ossimConnectableContainerInterface, temp[i]); if(interface) { interface->getChildren(children, false); } } } } bool ossimImageChain::add(ossimConnectableObject* source) { bool result = false; // if(PTR_CAST(ossimImageSource, source)) { source->changeOwner(this); if(imageChainList().size() > 0) { source->disconnectAllOutputs(); theOutputListIsFixedFlag = source->getOutputListIsFixedFlag(); imageChainList()[0]->removeListener(this); imageChainList().insert(imageChainList().begin(), source); imageChainList()[0]->addListener(this); source->addListener((ossimConnectableObjectListener*)this); imageChainList()[0]->connectMyInputTo(imageChainList()[1].get()); result = true; } else { theInputListIsFixedFlag = false; theOutputListIsFixedFlag = false; if(!theInputObjectList.empty()) { source->connectInputList(getInputList()); } theInputObjectList = source->getInputList(); theInputListIsFixedFlag = source->getInputListIsFixedFlag(); // theOutputObjectList = source->getOutputList(); // theOutputListIsFixedFlag= source->getOutputListIsFixedFlag(); imageChainList().push_back(source); source->addListener((ossimConnectableObjectListener*)this); source->addListener(this); result = true; } } if (result && source) { ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(source); fireEvent(event); } return result; } bool ossimImageChain::insertRight(ossimConnectableObject* newObj, ossimConnectableObject* rightOfThisObj) { if(!newObj&&!rightOfThisObj) return false; if(!imageChainList().size()) { return add(newObj); } std::vector<ossimRefPtr<ossimConnectableObject> >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), rightOfThisObj); if(iter!=imageChainList().end()) { if(iter == imageChainList().begin()) { return add(newObj); } else //if(PTR_CAST(ossimImageSource, newObj)) { ossimConnectableObject::ConnectableObjectList outputList = rightOfThisObj->getOutputList(); rightOfThisObj->disconnectAllOutputs(); // Core dump fix. Connect input prior to outputs. (drb) newObj->connectMyInputTo(rightOfThisObj); newObj->connectOutputList(outputList); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); imageChainList().insert(iter, newObj); // Send event to any listeners. ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(newObj); fireEvent(event); return true; } } return false; } bool ossimImageChain::insertRight(ossimConnectableObject* newObj, const ossimId& id) { #if 1 ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN ); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { return insertRight(newObj, obj); } return false; #else ossimConnectableObject* obj = findObject(id, false); if(obj) { return insertRight(newObj, obj); } return false; #endif } bool ossimImageChain::insertLeft(ossimConnectableObject* newObj, ossimConnectableObject* leftOfThisObj) { if(!newObj&&!leftOfThisObj) return false; if(!imageChainList().size()) { return add(newObj); } std::vector<ossimRefPtr<ossimConnectableObject> >::iterator iter = std::find(imageChainList().begin(), imageChainList().end(), leftOfThisObj); if(iter!=imageChainList().end()) { if((iter+1)==imageChainList().end()) { return addLast(newObj); } else { ossimConnectableObject::ConnectableObjectList inputList = leftOfThisObj->getInputList(); newObj->connectInputList(inputList); leftOfThisObj->disconnectAllInputs(); leftOfThisObj->connectMyInputTo(newObj); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); imageChainList().insert(iter+1, newObj); // Send an event to any listeners. ossimContainerEvent event(this, OSSIM_EVENT_ADD_OBJECT_ID); event.setObjectList(newObj); fireEvent(event); return true; } } return false; } bool ossimImageChain::insertLeft(ossimConnectableObject* newObj, const ossimId& id) { #if 1 ossimIdVisitor visitor( id, ossimVisitor::VISIT_CHILDREN|ossimVisitor::VISIT_INPUTS); accept( visitor ); ossimConnectableObject* obj = visitor.getObject(); if ( obj ) { return insertLeft(newObj, obj); } return false; #else ossimConnectableObject* obj = findObject(id, false); if(obj) { return insertLeft(newObj, obj); } return false; #endif } bool ossimImageChain::replace(ossimConnectableObject* newObj, ossimConnectableObject* oldObj) { ossim_int32 idx = indexOf(oldObj); if(idx >= 0) { ossimConnectableObject::ConnectableObjectList& inputList = oldObj->getInputList(); ossimConnectableObject::ConnectableObjectList& outputList = oldObj->getOutputList(); oldObj->removeListener((ossimConnectableObjectListener*)this); oldObj->removeListener(this); oldObj->changeOwner(0); imageChainList()[idx] = newObj; newObj->connectInputList(inputList); newObj->connectOutputList(outputList); newObj->changeOwner(this); newObj->addListener((ossimConnectableObjectListener*)this); if(idx == 0) { newObj->addListener(this); } } return (idx >= 0); } ossimRefPtr<ossimImageData> ossimImageChain::getTile( const ossimIrect& tileRect, ossim_uint32 resLevel) { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* inputSource = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(inputSource) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs return inputSource->getTile(tileRect, resLevel); } } else { if(getInput(0)) { ossimImageSource* inputSource = PTR_CAST(ossimImageSource, getInput(0)); if(inputSource) { ossimRefPtr<ossimImageData> inputTile = inputSource->getTile(tileRect, resLevel); // if(inputTile.valid()) // { // std::cout << *(inputTile.get()) << std::endl; // } return inputTile.get(); } } } // std::cout << "RETURNING A BLANK TILE!!!!" << std::endl; /* if(theBlankTile.get()) { theBlankTile->setImageRectangle(tileRect); } return theBlankTile; */ return 0; } ossim_uint32 ossimImageChain::getNumberOfInputBands() const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNumberOfOutputBands(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNumberOfOutputBands(); } } } return 0; } double ossimImageChain::getNullPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNullPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNullPixelValue(band); } } } return ossim::defaultNull(getOutputScalarType()); } double ossimImageChain::getMinPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getMinPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getMinPixelValue(band); } } } return ossim::defaultMin(getOutputScalarType()); } double ossimImageChain::getMaxPixelValue(ossim_uint32 band)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* inter = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(inter) { return inter->getMaxPixelValue(band); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getMaxPixelValue(band); } } } return ossim::defaultMax(getOutputScalarType()); } void ossimImageChain::getOutputBandList(std::vector<ossim_uint32>& bandList) const { if( (imageChainList().size() > 0) && isSourceEnabled() ) { ossimRefPtr<const ossimImageSource> inter = dynamic_cast<const ossimImageSource*>( imageChainList()[0].get() ); if( inter.valid() ) { // cout << "cn: " << inter->getClassName() << endl; inter->getOutputBandList(bandList); } } } ossimScalarType ossimImageChain::getOutputScalarType() const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getOutputScalarType(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getOutputScalarType(); } } } return OSSIM_SCALAR_UNKNOWN; } ossim_uint32 ossimImageChain::getTileWidth()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getTileWidth();; } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getTileWidth(); } } } return 0; } ossim_uint32 ossimImageChain::getTileHeight()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getTileHeight(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getTileHeight(); } } } return 0; } ossimIrect ossimImageChain::getBoundingRect(ossim_uint32 resLevel)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getBoundingRect(resLevel); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getBoundingRect(); } } } ossimDrect rect; rect.makeNan(); return rect; } void ossimImageChain::getValidImageVertices(vector<ossimIpt>& validVertices, ossimVertexOrdering ordering, ossim_uint32 resLevel)const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface =PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getValidImageVertices(validVertices, ordering, resLevel); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getValidImageVertices(validVertices, ordering, resLevel); } } } } ossimRefPtr<ossimImageGeometry> ossimImageChain::getImageGeometry() { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if( interface ) { return interface->getImageGeometry(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getImageGeometry(); } } } return ossimRefPtr<ossimImageGeometry>(); } void ossimImageChain::getDecimationFactor(ossim_uint32 resLevel, ossimDpt& result) const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getDecimationFactor(resLevel, result); return; } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactor(resLevel, result); return; } } } result.makeNan(); } void ossimImageChain::getDecimationFactors(vector<ossimDpt>& decimations) const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { interface->getDecimationFactors(decimations); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { interface->getDecimationFactors(decimations); return; } } } } ossim_uint32 ossimImageChain::getNumberOfDecimationLevels()const { if((imageChainList().size() > 0)&&(isSourceEnabled())) { ossimImageSource* interface = PTR_CAST(ossimImageSource, imageChainList()[0].get()); if(interface) { return interface->getNumberOfDecimationLevels(); } } else { if(getInput(0)) { ossimImageSource* interface = PTR_CAST(ossimImageSource, getInput(0)); if(interface) { return interface->getNumberOfDecimationLevels(); } } } return 1; } bool ossimImageChain::addAllSources(map<ossimId, vector<ossimId> >& idMapping, const ossimKeywordlist& kwl, const char* prefix) { static const char* MODULE = "ossimImageChain::addAllSources"; ossimString copyPrefix = prefix; bool result = ossimImageSource::loadState(kwl, copyPrefix.c_str()); if(!result) { return result; } long index = 0; // ossimSource* source = NULL; vector<ossimId> inputConnectionIds; ossimString regExpression = ossimString("^(") + copyPrefix + "object[0-9]+.)"; vector<ossimString> keys = kwl.getSubstringKeyList( regExpression ); long numberOfSources = (long)keys.size();//kwl.getNumberOfSubstringKeys(regExpression); int offset = (int)(copyPrefix+"object").size(); int idx = 0; std::vector<int> theNumberList(numberOfSources); for(idx = 0; idx < (int)theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); for(idx=0;idx < (int)theNumberList.size();++idx) { ossimString newPrefix = copyPrefix; newPrefix += ossimString("object"); newPrefix += ossimString::toString(theNumberList[idx]); newPrefix += ossimString("."); if(traceDebug()) { CLOG << "trying to create source with prefix: " << newPrefix << std::endl; } ossimRefPtr<ossimObject> object = ossimObjectFactoryRegistry::instance()->createObject(kwl, newPrefix.c_str()); ossimConnectableObject* source = PTR_CAST(ossimConnectableObject, object.get()); if(source) { // we did find a source so include it in the count if(traceDebug()) { CLOG << "Created source with prefix: " << newPrefix << std::endl; } //if(PTR_CAST(ossimImageSource, source)) { ossimId id = source->getId(); inputConnectionIds.clear(); findInputConnectionIds(inputConnectionIds, kwl, newPrefix); if(inputConnectionIds.size() == 0) { // we will try to do a default connection // if(imageChainList().size()) { if(traceDebug()) { CLOG << "connecting " << source->getClassName() << " to " << imageChainList()[0]->getClassName() << std::endl; } source->connectMyInputTo(0, imageChainList()[0].get()); } } else { // we remember the connection id's so we can connect this later. // this way we make sure all sources were actually // allocated. // idMapping.insert(std::make_pair(id, inputConnectionIds)); } add(source); } // else // { source = 0; // } } else { object = 0; source = 0; } ++index; } if(imageChainList().size()) { ossimConnectableObject* obj = imageChainList()[(ossim_int32)imageChainList().size()-1].get(); if(obj) { setNumberOfInputs(obj->getNumberOfInputs()); } } return result; } void ossimImageChain::findInputConnectionIds(vector<ossimId>& result, const ossimKeywordlist& kwl, const char* prefix) { ossimString copyPrefix = prefix; ossim_uint32 idx = 0; ossimString regExpression = ossimString("^") + ossimString(prefix) + "input_connection[0-9]+"; vector<ossimString> keys = kwl.getSubstringKeyList( regExpression ); ossim_int32 offset = (ossim_int32)(copyPrefix+"input_connection").size(); ossim_uint32 numberOfKeys = (ossim_uint32)keys.size(); std::vector<int> theNumberList(numberOfKeys); for(idx = 0; idx < theNumberList.size();++idx) { ossimString numberStr(keys[idx].begin() + offset, keys[idx].end()); theNumberList[idx] = numberStr.toInt(); } std::sort(theNumberList.begin(), theNumberList.end()); copyPrefix += ossimString("input_connection"); for(idx=0;idx < theNumberList.size();++idx) { const char* lookup = kwl.find(copyPrefix,ossimString::toString(theNumberList[idx])); if(lookup) { long id = ossimString(lookup).toLong(); result.push_back(ossimId(id)); } } } bool ossimImageChain::connectAllSources(const map<ossimId, vector<ossimId> >& idMapping) { // cout << "this->getId(): " << this->getId() << endl; if(idMapping.size()) { map<ossimId, vector<ossimId> >::const_iterator iter = idMapping.begin(); while(iter != idMapping.end()) { // cout << "(*iter).first): " << (*iter).first << endl; #if 0 ossimConnectableObject* currentSource = findObject((*iter).first); #else ossimIdVisitor visitor( (*iter).first, (ossimVisitor::VISIT_CHILDREN ) ); // ossimVisitor::VISIT_INPUTS ) ); accept( visitor ); ossimConnectableObject* currentSource = visitor.getObject(); #endif if(currentSource) { // cout << "currentSource->getClassName: " << currentSource->getClassName() << endl; long upperBound = (long)(*iter).second.size(); for(long index = 0; index < upperBound; ++index) { //cout << "(*iter).second[index]: " << (*iter).second[index] << endl; if((*iter).second[index].getId() > -1) { #if 0 ossimConnectableObject* inputSource = PTR_CAST(ossimConnectableObject, findObject((*iter).second[index])); #else visitor.reset(); visitor.setId( (*iter).second[index] ); accept( visitor ); ossimConnectableObject* inputSource = visitor.getObject(); #endif // cout << "inputSource is " << (inputSource?"good...":"null...") << endl; if ( inputSource ) { // cout << "inputSource->getClassName(): " << inputSource->getClassName() << endl; // Check for connection to self. if ( this != inputSource ) { currentSource->connectMyInputTo(index, inputSource); } // else warning??? } } else // -1 id { currentSource->disconnectMyInput((ossim_int32)index); } } } else { cerr << "Could not find " << (*iter).first << " for source: "; return false; } ++iter; } } // abort(); return true; } bool ossimImageChain::saveState(ossimKeywordlist& kwl, const char* prefix)const { bool result = true; result = ossimImageSource::saveState(kwl, prefix); if(!result) { return result; } ossim_uint32 upper = (ossim_uint32)imageChainList().size(); ossim_uint32 counter = 1; if (upper) { ossim_int32 idx = upper-1; // start with the tail and go to the head fo the list. for(;((idx >= 0)&&result);--idx, ++counter) { ossimString newPrefix = prefix; newPrefix += (ossimString("object") + ossimString::toString(counter) + ossimString(".")); result = imageChainList()[idx]->saveState(kwl, newPrefix.c_str()); } } return result; } bool ossimImageChain::loadState(const ossimKeywordlist& kwl, const char* prefix) { static const char* MODULE = "ossimImageChain::loadState(kwl, prefix)"; deleteList(); ossimImageSource::loadState(kwl, prefix); theLoadStateFlag = true; bool result = true; map<ossimId, vector<ossimId> > idMapping; result = addAllSources(idMapping, kwl, prefix); if(!result) { CLOG << "problems adding sources" << std::endl; } result = connectAllSources(idMapping); if(!result) { CLOG << "problems connecting sources" << std::endl; } theLoadStateFlag = false; return result; } void ossimImageChain::initialize() { static const char* MODULE = "ossimImageChain::initialize()"; if (traceDebug()) CLOG << " Entered..." << std::endl; long upper = (ossim_uint32)imageChainList().size(); for(long index = upper - 1; index >= 0; --index) { if(traceDebug()) { CLOG << "initializing source: " << imageChainList()[index]->getClassName() << std::endl; } if(imageChainList()[index].valid()) { ossimSource* interface = PTR_CAST(ossimSource, imageChainList()[index].get()); if(interface) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs interface->initialize(); } } } if (traceDebug()) CLOG << " Exited..." << std::endl; } void ossimImageChain::enableSource() { ossim_int32 upper = static_cast<ossim_int32>(imageChainList().size()); ossim_int32 index = 0; for(index = upper - 1; index >= 0; --index) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get()); if(source) { source->enableSource(); } } theEnableFlag = true; } void ossimImageChain::disableSource() { long upper = (ossim_uint32)imageChainList().size(); for(long index = upper - 1; index >= 0; --index) { // make sure we initialize in reverse order. // some source may depend on the initialization of // its inputs ossimSource* source = PTR_CAST(ossimSource, imageChainList()[index].get()); if(source) { source->disableSource(); } } theEnableFlag = false; } void ossimImageChain::prepareForRemoval(ossimConnectableObject* connectableObject) { if(connectableObject) { connectableObject->removeListener((ossimConnectableObjectListener*)this); connectableObject->changeOwner(0); connectableObject->disconnect(); } } bool ossimImageChain::deleteFirst() { if (imageChainList().size() == 0) return false; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); prepareForRemoval(imageChainList()[0].get()); // Clear any listeners, memory. event.setObjectList(imageChainList()[0].get()); imageChainList()[0] = 0; // Remove from the vector. std::vector<ossimRefPtr<ossimConnectableObject> >::iterator i = imageChainList().begin(); imageChainList().erase(i); fireEvent(event); return true; } bool ossimImageChain::deleteLast() { if (imageChainList().size() == 0) return false; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); // Clear any listeners, memory. ossim_uint32 idx = (ossim_uint32)imageChainList().size() - 1; prepareForRemoval(imageChainList()[idx].get()); event.setObjectList(imageChainList()[idx].get()); imageChainList()[idx] = 0; // Remove from the vector. imageChainList().pop_back(); fireEvent(event); return true; } void ossimImageChain::deleteList() { ossim_uint32 upper = (ossim_uint32) imageChainList().size(); ossim_uint32 idx = 0; ossimContainerEvent event(this, OSSIM_EVENT_REMOVE_OBJECT_ID); for(; idx < upper; ++idx) { if(imageChainList()[idx].valid()) { event.getObjectList().push_back(imageChainList()[idx].get()); prepareForRemoval(imageChainList()[idx].get()); imageChainList()[idx] = 0; } } imageChainList().clear(); fireEvent(event); } void ossimImageChain::disconnectInputEvent(ossimConnectionEvent& event) { if(imageChainList().size()) { if(event.getObject()==this) { if(imageChainList()[imageChainList().size()-1].valid()) { for(ossim_uint32 i = 0; i < event.getNumberOfOldObjects(); ++i) { imageChainList()[imageChainList().size()-1]->disconnectMyInput(event.getOldObject(i)); } } } } } void ossimImageChain::disconnectOutputEvent(ossimConnectionEvent& /* event */) { } void ossimImageChain::connectInputEvent(ossimConnectionEvent& event) { if(imageChainList().size()) { if(event.getObject()==this) { if(imageChainList()[imageChainList().size()-1].valid()) { for(ossim_uint32 i = 0; i < event.getNumberOfNewObjects(); ++i) { ossimConnectableObject* obj = event.getNewObject(i); imageChainList()[imageChainList().size()-1]->connectMyInputTo(findInputIndex(obj), obj, false); } } } else if(event.getObject() == imageChainList()[0].get()) { if(!theLoadStateFlag) { // theInputObjectList = imageChainList()[0]->getInputList(); } } initialize(); } } void ossimImageChain::connectOutputEvent(ossimConnectionEvent& /* event */) { } // void ossimImageChain::propertyEvent(ossimPropertyEvent& event) // { // if(imageChainList().size()) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, // event.getObject()); // if(obj) // { // ossimImageSource* interface = findSource(obj->getId()); // if(interface) // { // ossimConnectableObject* obj = PTR_CAST(ossimConnectableObject, // interface.getObject()); // if(obj) // { // } // } // } // } // } void ossimImageChain::objectDestructingEvent(ossimObjectDestructingEvent& event) { if(!event.getObject()) return; if(imageChainList().size()&&(event.getObject()!=this)) { removeChild(PTR_CAST(ossimConnectableObject, event.getObject())); } } void ossimImageChain::propagateEventToOutputs(ossimEvent& event) { //if(thePropagateEventFlag) return; //thePropagateEventFlag = true; if(imageChainList().size()) { if(imageChainList()[imageChainList().size()-1].valid()) { imageChainList()[imageChainList().size()-1]->fireEvent(event); imageChainList()[imageChainList().size()-1]->propagateEventToOutputs(event); } } //ossimConnectableObject::propagateEventToOutputs(event); // thePropagateEventFlag = false; } void ossimImageChain::propagateEventToInputs(ossimEvent& event) { // if(thePropagateEventFlag) return; // thePropagateEventFlag = true; if(imageChainList().size()) { if(imageChainList()[0].valid()) { imageChainList()[0]->fireEvent(event); imageChainList()[0]->propagateEventToInputs(event); } } // thePropagateEventFlag = false; } ossimConnectableObject* ossimImageChain::operator[](ossim_uint32 index) { return getConnectableObject(index); } ossimConnectableObject* ossimImageChain::getConnectableObject( ossim_uint32 index) { if(imageChainList().size() && (index < imageChainList().size())) { return imageChainList()[index].get(); } return 0; } ossim_int32 ossimImageChain::indexOf(ossimConnectableObject* obj)const { ossim_uint32 idx = 0; for(idx = 0; idx < imageChainList().size();++idx) { if(imageChainList()[idx] == obj) { return (ossim_int32)idx; } } return -1; } void ossimImageChain::accept(ossimVisitor& visitor) { if(!visitor.hasVisited(this)) { visitor.visit(this); ossimVisitor::VisitorType currentType = visitor.getVisitorType(); //--- // Lets make sure inputs and outputs are turned off for we are traversing all children // and we should not have to have that enabled. //--- visitor.turnOffVisitorType(ossimVisitor::VISIT_INPUTS|ossimVisitor::VISIT_OUTPUTS); if(visitor.getVisitorType() & ossimVisitor::VISIT_CHILDREN) { ConnectableObjectList::reverse_iterator current = imageChainList().rbegin(); while((current != imageChainList().rend())&&!visitor.stopTraversal()) { ossimRefPtr<ossimConnectableObject> currentObject = (*current); if(currentObject.get() && !visitor.hasVisited(currentObject.get())) currentObject->accept(visitor); ++current; } } visitor.setVisitorType(currentType); ossimConnectableObject::accept(visitor); } } //************************************************************************************************** // Inserts all of its children and inputs into the container provided. Since ossimImageChain is // itself a form of container, this method will consolidate this chain with the argument // container. Therefore this chain object will not be represented in the container (but its // children will be, with correct input and output connections to external objects). // Returns TRUE if successful. //************************************************************************************************** #if 0 bool ossimImageChain::fillContainer(ossimConnectableContainer& container) { // Grab the first source in the chain and let it fill the container with itself and inputs. This // will traverse down the chain and will even pick up external sources that feed this chain: ossimRefPtr<ossimConnectableObject> first_source = getFirstSource(); if (!first_source.valid()) return false; first_source->fillContainer(container); // Instead of adding ourselves, make sure my first source is properly connected to my output, // thus obviating the need for this image chain (my chain items become part of 'container': ConnectableObjectList& obj_list = getOutputList(); ossimRefPtr<ossimConnectableObject> output_connection = 0; while (!obj_list.empty()) { // Always pick off the beginning of the list since it is shrinking with each disconnect: output_connection = obj_list[0]; disconnectMyOutput(output_connection.get(), true, false); first_source->connectMyOutputTo(output_connection.get()); } return true; } #endif
54,032
15,990
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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 <boost/test/unit_test.hpp> #include "ignite/ignition.h" #include "ignite/test_utils.h" using namespace ignite; using namespace cache; using namespace boost::unit_test; namespace { /** Test put affinity key Java task. */ const std::string TEST_PUT_AFFINITY_KEY_TASK("org.apache.ignite.platform.PlatformComputePutAffinityKeyTask"); } class InteropTestSuiteFixture { public: InteropTestSuiteFixture() { // No-op. } ~InteropTestSuiteFixture() { ignite::Ignition::StopAll(false); } }; /** * Affinity key class. */ struct AffinityKey { /** Key */ int32_t key; /** Affinity key */ int32_t aff; /** * Default constructor. */ AffinityKey() : key(0), aff(0) { // No-op. } /** * Constructor. * @param key Key. * @param aff Affinity key. */ AffinityKey(int32_t key, int32_t aff) : key(key), aff(aff) { // No-op. } }; namespace ignite { namespace binary { template<> struct BinaryType<AffinityKey> : BinaryTypeDefaultAll<AffinityKey> { static void GetTypeName(std::string& dst) { dst = "AffinityKey"; } static void Write(BinaryWriter& writer, const AffinityKey& obj) { writer.WriteInt32("key", obj.key); writer.WriteInt32("aff", obj.aff); } static void Read(BinaryReader& reader, AffinityKey& dst) { dst.key = reader.ReadInt32("key"); dst.aff = reader.ReadInt32("aff"); } static void GetAffinityFieldName(std::string& dst) { dst = "aff"; } }; } } BOOST_FIXTURE_TEST_SUITE(InteropTestSuite, InteropTestSuiteFixture) #ifdef ENABLE_STRING_SERIALIZATION_VER_2_TESTS BOOST_AUTO_TEST_CASE(StringUtfInvalidSequence) { Ignite ignite = ignite_test::StartNode("cache-test.xml"); Cache<std::string, std::string> cache = ignite.CreateCache<std::string, std::string>("Test"); std::string initialValue; initialValue.push_back(static_cast<unsigned char>(0xD8)); initialValue.push_back(static_cast<unsigned char>(0x00)); try { cache.Put("key", initialValue); std::string cachedValue = cache.Get("key"); BOOST_ERROR("Exception is expected due to invalid format."); } catch (const IgniteError&) { // Expected in this mode. } Ignition::StopAll(false); } BOOST_AUTO_TEST_CASE(StringUtfInvalidCodePoint) { putenv("IGNITE_BINARY_MARSHALLER_USE_STRING_SERIALIZATION_VER_2=true"); Ignite ignite = ignite_test::StartNode("cache-test.xml"); Cache<std::string, std::string> cache = ignite.CreateCache<std::string, std::string>("Test"); std::string initialValue; // 1110xxxx 10xxxxxx 10xxxxxx | // <= 11011000 00000000 | U+D8 // = 11101101 10100000 10000000 | ED A0 80 initialValue.push_back(static_cast<unsigned char>(0xED)); initialValue.push_back(static_cast<unsigned char>(0xA0)); initialValue.push_back(static_cast<unsigned char>(0x80)); cache.Put("key", initialValue); std::string cachedValue = cache.Get("key"); // This is a valid case. Invalid code points are supported in this mode. BOOST_CHECK_EQUAL(initialValue, cachedValue); Ignition::StopAll(false); } #endif BOOST_AUTO_TEST_CASE(StringUtfValid4ByteCodePoint) { Ignite ignite = ignite_test::StartPlatformNode("cache-test.xml", "ServerNode"); Cache<std::string, std::string> cache = ignite.CreateCache<std::string, std::string>("Test"); std::string initialValue; // 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx | // <= 00001 00000001 01001011 | U+1014B // <= 000 010000 000101 001011 | U+1014B // = 11110000 10010000 10000101 10001011 | F0 90 85 8B initialValue.push_back(static_cast<unsigned char>(0xF0)); initialValue.push_back(static_cast<unsigned char>(0x90)); initialValue.push_back(static_cast<unsigned char>(0x85)); initialValue.push_back(static_cast<unsigned char>(0x8B)); cache.Put("key", initialValue); std::string cachedValue = cache.Get("key"); // This is a valid UTF-8 code point. Should be supported in default mode. BOOST_CHECK_EQUAL(initialValue, cachedValue); Ignition::StopAll(false); } BOOST_AUTO_TEST_CASE(PutObjectByCppThenByJava) { Ignite ignite = ignite_test::StartPlatformNode("interop.xml", "ServerNode"); cache::Cache<AffinityKey, AffinityKey> cache = ignite.GetOrCreateCache<AffinityKey, AffinityKey>("default"); AffinityKey key1(2, 3); cache.Put(key1, key1); compute::Compute compute = ignite.GetCompute(); compute.ExecuteJavaTask<int*>(TEST_PUT_AFFINITY_KEY_TASK); AffinityKey key2(1, 2); AffinityKey val = cache.Get(key2); BOOST_CHECK_EQUAL(val.key, 1); BOOST_CHECK_EQUAL(val.aff, 2); } BOOST_AUTO_TEST_CASE(PutObjectPointerByCppThenByJava) { Ignite ignite = ignite_test::StartPlatformNode("interop.xml", "ServerNode"); cache::Cache<AffinityKey*, AffinityKey*> cache = ignite.GetOrCreateCache<AffinityKey*, AffinityKey*>("default"); AffinityKey* key1 = new AffinityKey(2, 3); cache.Put(key1, key1); delete key1; compute::Compute compute = ignite.GetCompute(); compute.ExecuteJavaTask<int*>(TEST_PUT_AFFINITY_KEY_TASK); AffinityKey* key2 = new AffinityKey(1, 2); AffinityKey* val = cache.Get(key2); BOOST_CHECK_EQUAL(val->key, 1); BOOST_CHECK_EQUAL(val->aff, 2); delete key2; delete val; } BOOST_AUTO_TEST_SUITE_END()
6,554
2,306
// // This file is part of the "vps" project // See "LICENSE" for license information. // #include <doctest.h> #include <vps.h> #define VMA_IMPLEMENTATION #include <vk_mem_alloc.h> #define STB_IMAGE_IMPLEMENTATION #include <stb_image.h> #define STB_IMAGE_WRITE_IMPLEMENTATION #include <stb_image_write.h> #include <iostream> using namespace std; using namespace doctest; TEST_SUITE_BEGIN("image threshold to zero test suite"); //---------------------------------------------------------------------------------------------------------------------- TEST_CASE("test image threshold to zero") { /*Window_desc desc; desc.title = default_title; desc.extent = default_extent; auto window = make_unique<Window>(desc); CHECK(window); REQUIRE(window->title() == default_title); REQUIRE(window->extent() == default_extent);*/ VkResult result; VkInstance instance; { const char* layerNames = "VK_LAYER_KHRONOS_validation"; VkInstanceCreateInfo create_info {}; create_info.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO; create_info.enabledLayerCount = 1; create_info.ppEnabledLayerNames = &layerNames; result = vkCreateInstance(&create_info, nullptr, &instance); } VkPhysicalDevice physical_device; { uint32_t cnt = 1; result = vkEnumeratePhysicalDevices(instance, &cnt, &physical_device); } VkDevice device; { float priority = 1.0f; VkDeviceQueueCreateInfo queue_info {}; queue_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO; queue_info.queueFamilyIndex = 0; queue_info.queueCount = 1; queue_info.pQueuePriorities = &priority; VkDeviceCreateInfo info {}; info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO; info.queueCreateInfoCount = 1; info.pQueueCreateInfos = &queue_info; result = vkCreateDevice(physical_device, &info, nullptr, &device); } VmaAllocator allocator; { VmaAllocatorCreateInfo create_info {}; create_info.physicalDevice = physical_device; create_info.device = device; create_info.instance = instance; vmaCreateAllocator(&create_info, &allocator); } int x, y, n; unsigned char* contents; { contents = stbi_load(VPS_ASSET_PATH"/image/lena.bmp", &x, &y, &n, STBI_rgb_alpha); // contents = stbi_load("C:/Users/djang/repos/vps/build/vps/src.png", &x, &y, &n, STBI_rgb_alpha); } VkImage src_image; VmaAllocation src_allocation; VkImageView src_image_view; { VkImageCreateInfo image_info {}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = VK_FORMAT_R8G8B8A8_UNORM; image_info.extent.width = x; image_info.extent.height = y; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.tiling = VK_IMAGE_TILING_LINEAR; // image_info.tiling = VK_IMAGE_TILING_OPTIMAL; image_info.usage = VK_IMAGE_USAGE_STORAGE_BIT; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VmaAllocationCreateInfo allocation_info {}; allocation_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; vmaCreateImage(allocator, &image_info, &allocation_info, &src_image, &src_allocation, nullptr); VkImageViewCreateInfo view_info {}; view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_info.image = src_image; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.format = VK_FORMAT_R8G8B8A8_UNORM; view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.layerCount = 1; view_info.subresourceRange.levelCount = 1; vkCreateImageView(device, &view_info, nullptr, &src_image_view); } { void* ptr; vmaMapMemory(allocator, src_allocation, &ptr); memcpy(ptr, contents, x * y * 4); stbi_image_free(contents); } VkImage dst_image; VmaAllocation dst_allocation; VkImageView dst_image_view; VmaAllocationInfo i {}; { VkImageCreateInfo image_info {}; image_info.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; image_info.imageType = VK_IMAGE_TYPE_2D; image_info.format = VK_FORMAT_R8G8B8A8_UNORM; image_info.extent.width = x; image_info.extent.height = y; image_info.extent.depth = 1; image_info.mipLevels = 1; image_info.arrayLayers = 1; image_info.samples = VK_SAMPLE_COUNT_1_BIT; image_info.tiling = VK_IMAGE_TILING_LINEAR; image_info.usage = VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT; image_info.sharingMode = VK_SHARING_MODE_EXCLUSIVE; image_info.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED; VmaAllocationCreateInfo allocation_info {}; allocation_info.usage = VMA_MEMORY_USAGE_CPU_TO_GPU; vmaCreateImage(allocator, &image_info, &allocation_info, &dst_image, &dst_allocation, &i); VkImageViewCreateInfo view_info {}; view_info.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO; view_info.image = dst_image; view_info.viewType = VK_IMAGE_VIEW_TYPE_2D; view_info.format = VK_FORMAT_R8G8B8A8_UNORM; view_info.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; view_info.subresourceRange.baseArrayLayer = 0; view_info.subresourceRange.baseMipLevel = 0; view_info.subresourceRange.layerCount = 1; view_info.subresourceRange.levelCount = 1; vkCreateImageView(device, &view_info, nullptr, &dst_image_view); } VkBuffer dump; VmaAllocation dump_alloc; { VkBufferCreateInfo buffer_create_info {}; buffer_create_info.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO; buffer_create_info.size = x * y * 4; buffer_create_info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; VmaAllocationCreateInfo allocation_create_info {}; allocation_create_info.usage = VMA_MEMORY_USAGE_CPU_COPY; result = vmaCreateBuffer(allocator, &buffer_create_info, &allocation_create_info, &dump, &dump_alloc, nullptr); } VkCommandPool command_pool; { VkCommandPoolCreateInfo create_info {}; create_info.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; create_info.queueFamilyIndex = 0; vkCreateCommandPool(device, &create_info, nullptr, &command_pool); } VkCommandBuffer cmd_buf; { VkCommandBufferAllocateInfo allocate_info {}; allocate_info.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO; allocate_info.commandPool = command_pool; allocate_info.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; allocate_info.commandBufferCount = 1; vkAllocateCommandBuffers(device, &allocate_info, &cmd_buf); } VkQueue queue; vkGetDeviceQueue(device, 0, 0, &queue); VpsContextCreateInfo createInfo {}; createInfo.instance = instance; createInfo.physicalDevice = physical_device; createInfo.device = device; VpsContext context = VK_NULL_HANDLE; vpsCreateContext(&createInfo, &context); VkCommandBufferBeginInfo bi {}; bi.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO; vkBeginCommandBuffer(cmd_buf, &bi); { VkImageMemoryBarrier barriers[2]; barriers[0] = {}; barriers[0].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barriers[0].srcAccessMask = 0; barriers[0].dstAccessMask = VK_ACCESS_SHADER_READ_BIT; barriers[0].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barriers[0].newLayout = VK_IMAGE_LAYOUT_GENERAL; barriers[0].image = src_image; barriers[0].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barriers[0].subresourceRange.baseArrayLayer = 0; barriers[0].subresourceRange.baseMipLevel = 0; barriers[0].subresourceRange.layerCount = 1; barriers[0].subresourceRange.levelCount = 1; barriers[1] = {}; barriers[1].sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barriers[1].srcAccessMask = 0; barriers[1].dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; barriers[1].oldLayout = VK_IMAGE_LAYOUT_UNDEFINED; barriers[1].newLayout = VK_IMAGE_LAYOUT_GENERAL; barriers[1].image = dst_image; barriers[1].subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barriers[1].subresourceRange.baseArrayLayer = 0; barriers[1].subresourceRange.baseMipLevel = 0; barriers[1].subresourceRange.layerCount = 1; barriers[1].subresourceRange.levelCount = 1; vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 2, barriers); } vpsCmdImageThresholdToZero(context, cmd_buf, src_image_view, dst_image_view, 0.2, nullptr); { VkImageMemoryBarrier barrier; barrier = {}; barrier.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER; barrier.srcAccessMask = 0; barrier.dstAccessMask = VK_ACCESS_SHADER_WRITE_BIT; barrier.oldLayout = VK_IMAGE_LAYOUT_GENERAL; barrier.newLayout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; barrier.image = dst_image; barrier.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; barrier.subresourceRange.baseArrayLayer = 0; barrier.subresourceRange.baseMipLevel = 0; barrier.subresourceRange.layerCount = 1; barrier.subresourceRange.levelCount = 1; vkCmdPipelineBarrier(cmd_buf, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT, 0, 0, nullptr, 0, nullptr, 1, &barrier); } { VkBufferImageCopy region {}; region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT; region.imageSubresource.baseArrayLayer = 0; region.imageSubresource.layerCount = 1; region.imageSubresource.mipLevel = 0; region.imageExtent.width = x; region.imageExtent.height = y; region.imageExtent.depth = 1; vkCmdCopyImageToBuffer(cmd_buf, dst_image, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, dump, 1, &region); } vkEndCommandBuffer(cmd_buf); VkSubmitInfo si {}; si.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO; si.commandBufferCount = 1; si.pCommandBuffers = &cmd_buf; vkQueueSubmit(queue, 1, &si, VK_NULL_HANDLE); vkDeviceWaitIdle(device); void* p; vmaMapMemory(allocator, dump_alloc, &p); stbi_write_png("result.png", x, y, STBI_rgb_alpha, p, 0); // vpsDestoryContext(context); } //---------------------------------------------------------------------------------------------------------------------- TEST_SUITE_END();
10,281
4,435
#include "threadfilereaders.h" ThreadImageRotator::ThreadImageRotator(const QString *pathToSourceSvg,const QString *pathToRendedImage,const QString *fileType, const QString *slash, QObject *parent) : QObject(parent) , m_timer(new QTimer(this)) , m_imageRotatorHash(new QHash<QThread*, ImageRotator*>()) , m_freeThreadsQueue(new std::queue<QThread*>()) , m_tilesQueue(new std::queue<TileData>()) , m_svgType(new QString(QStringLiteral(".svg"))) { qInfo()<<"ThreadFileReader constructor"; initTimer(); createDataStructs(pathToSourceSvg, pathToRendedImage, fileType, slash); createConnections(); } ThreadImageRotator::~ThreadImageRotator() { QHashIterator<QThread*, ImageRotator*> iterator(*m_imageRotatorHash); while (iterator.hasNext()) { iterator.next(); delete iterator.value(); delete iterator.key(); } delete m_tilesQueue; delete m_imageRotatorHash; delete m_freeThreadsQueue; delete m_timer; } void ThreadImageRotator::gettingTilesToConvert(QStringList &tiles, int &numOfImages, QString &azm, QString &layer) { char firstParam=azm.at(0).toLatin1(); char secondParam=azm.at(1).toLatin1(); char thirdParam=azm.at(2).toLatin1(); QStringList::iterator it=tiles.begin(); if(m_freeThreadsQueue->size()>=numOfImages) { for (; it!=tiles.end(); ++it) { QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->value(thread)->setParams(*it, azm, layer, firstParam, secondParam, thirdParam); thread->start(); } } else { int numImagesToQueue=numOfImages; for (int i=0; i<m_freeThreadsQueue->size(); i++, ++it) { QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->value(thread)->setParams(*it, azm, layer, firstParam, secondParam, thirdParam); thread->start(); numImagesToQueue--; } for (int i=numOfImages-1; i>numOfImages-numImagesToQueue; i--) { m_tilesQueue->push(TileData(tiles[i], azm , layer)); } m_timer->start(m_timerInterval); } } void ThreadImageRotator::seekAvailableThreads() { if (!m_tilesQueue->empty()) { readFilesFromQueue(); } } void ThreadImageRotator::addThreadToQueue() { m_freeThreadsQueue->push(qobject_cast<QThread *>(sender())); } void ThreadImageRotator::readFilesFromQueue() { if (!m_tilesQueue->empty()&&!m_freeThreadsQueue->empty()) { if(m_tilesQueue->size()<=m_freeThreadsQueue->size()) { for (int i=0; i<m_tilesQueue->size(); i++) { TileData tile= m_tilesQueue->front(); m_tilesQueue->pop(); char firstParam=tile.azm.at(0).toLatin1(); char secondParam=tile.azm.at(1).toLatin1(); char thirdParam=tile.azm.at(2).toLatin1(); QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->operator [](thread)->setParams(tile.tile, tile.azm, tile.layer, firstParam, secondParam, thirdParam); thread->start(QThread::TimeCriticalPriority); } } else { for (int i=0; i<m_freeThreadsQueue->size(); i++) { TileData tile= m_tilesQueue->front(); m_tilesQueue->pop(); char firstParam=tile.azm.at(0).toLatin1(); char secondParam=tile.azm.at(1).toLatin1(); char thirdParam=tile.azm.at(2).toLatin1(); QThread *thread=m_freeThreadsQueue->front(); m_freeThreadsQueue->pop(); m_imageRotatorHash->operator [](thread)->setParams(tile.tile, tile.azm, tile.layer, firstParam, secondParam, thirdParam); thread->start(QThread::TimeCriticalPriority); } m_timer->start(m_timerInterval); } } } void ThreadImageRotator::initTimer() { m_timer->setInterval(m_timerInterval); m_timer->setTimerType(Qt::CoarseTimer); m_timer->setSingleShot(true); } void ThreadImageRotator::createDataStructs(const QString *pathToSourceSvg,const QString *pathToRendedImage,const QString *fileType, const QString *slash) { for (int i=0; i<m_numOfThreads; i++) { m_imageRotatorHash->insert(new QThread(), new ImageRotator(pathToSourceSvg, pathToRendedImage, fileType, slash, m_svgType, nullptr)); } QList<QThread*>keys=m_imageRotatorHash->keys(); for (QList<QThread*>::const_iterator it=keys.cbegin(), total = keys.cend(); it!=total; ++it) { m_freeThreadsQueue->push(*it); } } void ThreadImageRotator::createConnections() { QHashIterator<QThread*, ImageRotator*> iterator(*m_imageRotatorHash); while (iterator.hasNext()) { iterator.next(); connect(iterator.key(), &QThread::started, iterator.value(), &ImageRotator::doing); connect(iterator.value(), &ImageRotator::finished, iterator.key(), &QThread::quit); connect(iterator.key(), &QThread::finished, this, &ThreadImageRotator::addThreadToQueue); iterator.value()->moveToThread(iterator.key()); } connect(m_timer, &QTimer::timeout, this, &ThreadImageRotator::seekAvailableThreads); }
5,425
1,755
#ifndef MAPNODE_HPP #define MAPNODE_HPP struct Estremi{ int minX, minY, maxX, maxY; }; class MapNode { protected: int X, Y; int building; MapNode *N, *S, *E, *W; MapNode *next; MapNode *LineRight; MapNode* FindNode(int x, int y); Estremi EstremiMappa(); void LinkLine(MapNode* pos); MapNode* mostLeftLine(int y); public: MapNode(); MapNode* GateNord(MapNode* pos); MapNode* GateSud(MapNode* pos); MapNode* GateEast(MapNode* pos); MapNode* GateWest(MapNode* pos); MapNode* CreateNord(MapNode* pos); MapNode* CreateSud(MapNode* pos); MapNode* CreateEast(MapNode* pos); MapNode* CreateWest(MapNode* pos); void Stampa(); }; #endif // MAPNODE_HPP
838
298
#include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/Voxelizer.hpp" #include "Castor3D/DebugDefines.hpp" #include "Castor3D/Engine.hpp" #include "Castor3D/Buffer/GpuBuffer.hpp" #include "Castor3D/Buffer/UniformBufferPools.hpp" #include "Castor3D/Event/Frame/GpuFunctorEvent.hpp" #include "Castor3D/Material/Texture/Sampler.hpp" #include "Castor3D/Material/Texture/TextureLayout.hpp" #include "Castor3D/Miscellaneous/ProgressBar.hpp" #include "Castor3D/Render/RenderDevice.hpp" #include "Castor3D/Render/Technique/RenderTechniqueVisitor.hpp" #include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelBufferToTexture.hpp" #include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelizePass.hpp" #include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSceneData.hpp" #include "Castor3D/Render/GlobalIllumination/VoxelConeTracing/VoxelSecondaryBounce.hpp" #include "Castor3D/Scene/Camera.hpp" #include "Castor3D/Scene/Scene.hpp" #include "Castor3D/Scene/SceneNode.hpp" #include "Castor3D/Shader/ShaderBuffer.hpp" #include "Castor3D/Shader/Shaders/GlslVoxel.hpp" #include "Castor3D/Shader/Ubos/VoxelizerUbo.hpp" #include <CastorUtils/Design/ResourceCache.hpp> #include <CastorUtils/Miscellaneous/BitSize.hpp> #include <ashespp/RenderPass/FrameBuffer.hpp> #include <RenderGraph/FrameGraph.hpp> #include <RenderGraph/GraphContext.hpp> #include <RenderGraph/RunnablePasses/GenerateMipmaps.hpp> CU_ImplementCUSmartPtr( castor3d, Voxelizer ) using namespace castor; namespace castor3d { //********************************************************************************************* namespace { Texture createTexture( RenderDevice const & device , crg::ResourceHandler & handler , String const & name , VkExtent3D const & size ) { return Texture{ device , handler , name , VK_IMAGE_CREATE_2D_ARRAY_COMPATIBLE_BIT , size , 1u , getMipLevels( size, VK_FORMAT_R16G16B16A16_SFLOAT ) , VK_FORMAT_R16G16B16A16_SFLOAT , ( VK_IMAGE_USAGE_STORAGE_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT ) , VK_BORDER_COLOR_FLOAT_OPAQUE_BLACK , false }; } ashes::BufferPtr< Voxel > createSsbo( Engine & engine , RenderDevice const & device , String const & name , uint32_t voxelGridSize ) { return castor3d::makeBuffer< Voxel >( device , voxelGridSize * voxelGridSize * voxelGridSize , VK_BUFFER_USAGE_STORAGE_BUFFER_BIT , VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT , name ); } } //********************************************************************************************* Voxelizer::Voxelizer( crg::ResourceHandler & handler , RenderDevice const & device , ProgressBar * progress , Scene & scene , Camera & camera , MatrixUbo & matrixUbo , VoxelizerUbo & voxelizerUbo , VoxelSceneData const & voxelConfig ) : m_engine{ *device.renderSystem.getEngine() } , m_device{ device } , m_voxelConfig{ voxelConfig } , m_graph{ handler, "Voxelizer" } , m_culler{ scene, &camera } , m_matrixUbo{ device } , m_firstBounce{ createTexture( device, handler, "VoxelizedSceneFirstBounce", { m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value() } ) } , m_secondaryBounce{ createTexture( device, handler, "VoxelizedSceneSecondaryBounce", { m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value(), m_voxelConfig.gridSize.value() } ) } , m_voxels{ createSsbo( m_engine, device, "VoxelizedSceneBuffer", m_voxelConfig.gridSize.value() ) } , m_voxelizerUbo{ voxelizerUbo } , m_voxelizePassDesc{ doCreateVoxelizePass( progress ) } , m_voxelToTextureDesc{ doCreateVoxelToTexture( m_voxelizePassDesc, progress ) } , m_voxelMipGen{ doCreateVoxelMipGen( m_voxelToTextureDesc, "FirstBounceMip", m_firstBounce.wholeViewId, progress ) } , m_voxelSecondaryBounceDesc{ doCreateVoxelSecondaryBounce( m_voxelMipGen, progress ) } , m_voxelSecondaryMipGen{ doCreateVoxelMipGen( m_voxelSecondaryBounceDesc, "SecondaryBounceMip", m_secondaryBounce.wholeViewId, progress ) } , m_runnable{ m_graph.compile( m_device.makeContext() ) } { m_firstBounce.create(); m_secondaryBounce.create(); auto runnable = m_runnable.get(); m_device.renderSystem.getEngine()->postEvent( makeGpuFunctorEvent( EventType::ePreRender , [runnable]( RenderDevice const & , QueueData const & ) { runnable->record(); } ) ); } Voxelizer::~Voxelizer() { m_runnable.reset(); m_voxels.reset(); m_engine.getSamplerCache().remove( "VoxelizedSceneSecondaryBounce" ); m_engine.getSamplerCache().remove( "VoxelizedSceneFirstBounce" ); } void Voxelizer::update( CpuUpdater & updater ) { if ( m_voxelizePass ) { auto & camera = *updater.camera; auto & aabb = camera.getScene()->getBoundingBox(); auto max = std::max( aabb.getDimensions()->x, std::max( aabb.getDimensions()->y, aabb.getDimensions()->z ) ); auto cellSize = float( m_voxelConfig.gridSize.value() ) / max; auto voxelSize = ( cellSize * m_voxelConfig.voxelSizeFactor ); m_grid = castor::Point4f{ 0.0f , 0.0f , 0.0f , voxelSize }; m_voxelizePass->update( updater ); m_voxelizerUbo.cpuUpdate( m_voxelConfig , voxelSize , m_voxelConfig.gridSize.value() ); } } void Voxelizer::update( GpuUpdater & updater ) { if ( m_voxelizePass ) { m_voxelizePass->update( updater ); } } void Voxelizer::accept( RenderTechniqueVisitor & visitor ) { visitor.visit( "Voxelisation First Bounce" , m_firstBounce , m_graph.getFinalLayout( m_firstBounce.wholeViewId ).layout , TextureFactors::tex3D( &m_grid ) ); visitor.visit( "Voxelisation Secondary Bounce" , m_secondaryBounce , m_graph.getFinalLayout( m_secondaryBounce.wholeViewId ).layout , TextureFactors::tex3D( &m_grid ) ); m_voxelizePass->accept( visitor ); m_voxelToTexture->accept( visitor ); m_voxelSecondaryBounce->accept( visitor ); } crg::SemaphoreWait Voxelizer::render( crg::SemaphoreWait const & semaphore , ashes::Queue const & queue ) { return m_runnable->run( semaphore, queue ); } crg::FramePass & Voxelizer::doCreateVoxelizePass( ProgressBar * progress ) { stepProgressBar( progress, "Creating voxelize pass" ); auto & result = m_graph.createPass( "VoxelizePass" , [this, progress]( crg::FramePass const & framePass , crg::GraphContext & context , crg::RunnableGraph & runnableGraph ) { stepProgressBar( progress, "Initialising voxelize pass" ); auto res = std::make_unique< VoxelizePass >( framePass , context , runnableGraph , m_device , m_matrixUbo , m_culler , m_voxelizerUbo , *m_voxels , m_voxelConfig ); m_voxelizePass = res.get(); m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer" , res->getTimer() ); return res; } ); result.addOutputStorageBuffer( { m_voxels->getBuffer(), "Voxels" } , 0u , 0u , m_voxels->getBuffer().getSize() ); return result; } crg::FramePass & Voxelizer::doCreateVoxelToTexture( crg::FramePass const & previousPass , ProgressBar * progress ) { stepProgressBar( progress, "Creating voxel buffer to texture pass" ); auto & result = m_graph.createPass( "VoxelBufferToTexture" , [this, progress]( crg::FramePass const & framePass , crg::GraphContext & context , crg::RunnableGraph & runnableGraph ) { stepProgressBar( progress, "Initialising voxel buffer to texture pass" ); auto res = std::make_unique< VoxelBufferToTexture >( framePass , context , runnableGraph , m_device , m_voxelConfig ); m_voxelToTexture = res.get(); m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer" , res->getTimer() ); return res; } ); result.addDependency( previousPass ); result.addInputStorageBuffer( { m_voxels->getBuffer(), "Voxels" } , 0u , 0u , m_voxels->getBuffer().getSize() ); result.addOutputStorageView( m_firstBounce.wholeViewId , 1u , VK_IMAGE_LAYOUT_UNDEFINED ); return result; } crg::FramePass & Voxelizer::doCreateVoxelMipGen( crg::FramePass const & previousPass , std::string const & name , crg::ImageViewId const & view , ProgressBar * progress ) { stepProgressBar( progress, "Creating voxel mipmap generation pass" ); auto & result = m_graph.createPass( name , [this, progress]( crg::FramePass const & framePass , crg::GraphContext & context , crg::RunnableGraph & runnableGraph ) { stepProgressBar( progress, "Initialising voxel mipmap generation pass" ); auto res = std::make_unique< crg::GenerateMipmaps >( framePass , context , runnableGraph , VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL ); m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer" , res->getTimer() ); return res; } ); result.addDependency( previousPass ); result.addTransferInOutView( view ); return result; } crg::FramePass & Voxelizer::doCreateVoxelSecondaryBounce( crg::FramePass const & previousPass , ProgressBar * progress ) { stepProgressBar( progress, "Creating voxel secondary bounce pass" ); auto & result = m_graph.createPass( "VoxelSecondaryBounce" , [this, progress]( crg::FramePass const & framePass , crg::GraphContext & context , crg::RunnableGraph & runnableGraph ) { stepProgressBar( progress, "Initialising voxel secondary bounce pass" ); auto res = std::make_unique< VoxelSecondaryBounce >( framePass , context , runnableGraph , m_device , m_voxelConfig ); m_voxelSecondaryBounce = res.get(); m_device.renderSystem.getEngine()->registerTimer( runnableGraph.getName() + "/Voxelizer" , res->getTimer() ); return res; } ); result.addDependency( previousPass ); result.addInOutStorageBuffer( { m_voxels->getBuffer(), "Voxels" } , 0u , 0u , m_voxels->getBuffer().getSize() ); m_voxelizerUbo.createPassBinding( result , 1u ); result.addSampledView( m_firstBounce.wholeViewId , 2u , VK_IMAGE_LAYOUT_UNDEFINED ); result.addOutputStorageView( m_secondaryBounce.wholeViewId , 3u , VK_IMAGE_LAYOUT_UNDEFINED ); return result; } }
10,273
4,285
/* * GblPoint.cpp * * Created on: Aug 18, 2011 * Author: kleinwrt */ #include "GblPoint.h" //! Namespace for the general broken lines package namespace gbl { /// Create a point. /** * Create point on (initial) trajectory. Needs transformation jacobian from previous point. * \param [in] aJacobian Transformation jacobian from previous point */ GblPoint::GblPoint(const TMatrixD &aJacobian) : theLabel(0), theOffset(0), measDim(0), transFlag(false), measTransformation(), scatFlag( false), localDerivatives(), globalLabels(), globalDerivatives() { for (unsigned int i = 0; i < 5; ++i) { for (unsigned int j = 0; j < 5; ++j) { p2pJacobian(i, j) = aJacobian(i, j); } } } GblPoint::GblPoint(const SMatrix55 &aJacobian) : theLabel(0), theOffset(0), p2pJacobian(aJacobian), measDim(0), transFlag( false), measTransformation(), scatFlag(false), localDerivatives(), globalLabels(), globalDerivatives() { } GblPoint::~GblPoint() { } /// Add a measurement to a point. /** * Add measurement (in meas. system) with diagonal precision (inverse covariance) matrix. * ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position) * \param [in] aProjection Projection from local to measurement system * \param [in] aResiduals Measurement residuals * \param [in] aPrecision Measurement precision (diagonal) * \param [in] minPrecision Minimal precision to accept measurement */ void GblPoint::addMeasurement(const TMatrixD &aProjection, const TVectorD &aResiduals, const TVectorD &aPrecision, double minPrecision) { measDim = aResiduals.GetNrows(); unsigned int iOff = 5 - measDim; for (unsigned int i = 0; i < measDim; ++i) { measResiduals(iOff + i) = aResiduals[i]; measPrecision(iOff + i) = ( aPrecision[i] >= minPrecision ? aPrecision[i] : 0.); for (unsigned int j = 0; j < measDim; ++j) { measProjection(iOff + i, iOff + j) = aProjection(i, j); } } } /// Add a measurement to a point. /** * Add measurement (in meas. system) with arbitrary precision (inverse covariance) matrix. * Will be diagonalized. * ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position) * \param [in] aProjection Projection from local to measurement system * \param [in] aResiduals Measurement residuals * \param [in] aPrecision Measurement precision (matrix) * \param [in] minPrecision Minimal precision to accept measurement */ void GblPoint::addMeasurement(const TMatrixD &aProjection, const TVectorD &aResiduals, const TMatrixDSym &aPrecision, double minPrecision) { measDim = aResiduals.GetNrows(); TMatrixDSymEigen measEigen(aPrecision); measTransformation.ResizeTo(measDim, measDim); measTransformation = measEigen.GetEigenVectors(); measTransformation.T(); transFlag = true; TVectorD transResiduals = measTransformation * aResiduals; TVectorD transPrecision = measEigen.GetEigenValues(); TMatrixD transProjection = measTransformation * aProjection; unsigned int iOff = 5 - measDim; for (unsigned int i = 0; i < measDim; ++i) { measResiduals(iOff + i) = transResiduals[i]; measPrecision(iOff + i) = ( transPrecision[i] >= minPrecision ? transPrecision[i] : 0.); for (unsigned int j = 0; j < measDim; ++j) { measProjection(iOff + i, iOff + j) = transProjection(i, j); } } } /// Add a measurement to a point. /** * Add measurement in local system with diagonal precision (inverse covariance) matrix. * ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position) * \param [in] aResiduals Measurement residuals * \param [in] aPrecision Measurement precision (diagonal) * \param [in] minPrecision Minimal precision to accept measurement */ void GblPoint::addMeasurement(const TVectorD &aResiduals, const TVectorD &aPrecision, double minPrecision) { measDim = aResiduals.GetNrows(); unsigned int iOff = 5 - measDim; for (unsigned int i = 0; i < measDim; ++i) { measResiduals(iOff + i) = aResiduals[i]; measPrecision(iOff + i) = ( aPrecision[i] >= minPrecision ? aPrecision[i] : 0.); } measProjection = ROOT::Math::SMatrixIdentity(); } /// Add a measurement to a point. /** * Add measurement in local system with arbitrary precision (inverse covariance) matrix. * Will be diagonalized. * ((up to) 2D: position, 4D: slope+position, 5D: curvature+slope+position) * \param [in] aResiduals Measurement residuals * \param [in] aPrecision Measurement precision (matrix) * \param [in] minPrecision Minimal precision to accept measurement */ void GblPoint::addMeasurement(const TVectorD &aResiduals, const TMatrixDSym &aPrecision, double minPrecision) { measDim = aResiduals.GetNrows(); TMatrixDSymEigen measEigen(aPrecision); measTransformation.ResizeTo(measDim, measDim); measTransformation = measEigen.GetEigenVectors(); measTransformation.T(); transFlag = true; TVectorD transResiduals = measTransformation * aResiduals; TVectorD transPrecision = measEigen.GetEigenValues(); unsigned int iOff = 5 - measDim; for (unsigned int i = 0; i < measDim; ++i) { measResiduals(iOff + i) = transResiduals[i]; measPrecision(iOff + i) = ( transPrecision[i] >= minPrecision ? transPrecision[i] : 0.); for (unsigned int j = 0; j < measDim; ++j) { measProjection(iOff + i, iOff + j) = measTransformation(i, j); } } } /// Check for measurement at a point. /** * Get dimension of measurement (0 = none). * \return measurement dimension */ unsigned int GblPoint::hasMeasurement() const { return measDim; } /// Retrieve measurement of a point. /** * \param [out] aProjection Projection from (diagonalized) measurement to local system * \param [out] aResiduals Measurement residuals * \param [out] aPrecision Measurement precision (diagonal) */ void GblPoint::getMeasurement(SMatrix55 &aProjection, SVector5 &aResiduals, SVector5 &aPrecision) const { aProjection = measProjection; aResiduals = measResiduals; aPrecision = measPrecision; } /// Get measurement transformation (from diagonalization). /** * \param [out] aTransformation Transformation matrix */ void GblPoint::getMeasTransformation(TMatrixD &aTransformation) const { aTransformation.ResizeTo(measDim, measDim); if (transFlag) { aTransformation = measTransformation; } else { aTransformation.UnitMatrix(); } } /// Add a (thin) scatterer to a point. /** * Add scatterer with diagonal precision (inverse covariance) matrix. * Changes local track direction. * * \param [in] aResiduals Scatterer residuals * \param [in] aPrecision Scatterer precision (diagonal of inverse covariance matrix) */ void GblPoint::addScatterer(const TVectorD &aResiduals, const TVectorD &aPrecision) { scatFlag = true; scatResiduals(0) = aResiduals[0]; scatResiduals(1) = aResiduals[1]; scatPrecision(0) = aPrecision[0]; scatPrecision(1) = aPrecision[1]; scatTransformation = ROOT::Math::SMatrixIdentity(); } /// Add a (thin) scatterer to a point. /** * Add scatterer with arbitrary precision (inverse covariance) matrix. * Will be diagonalized. Changes local track direction. * * The precision matrix for the local slopes is defined by the * angular scattering error theta_0 and the scalar products c_1, c_2 of the * offset directions in the local frame with the track direction: * * (1 - c_1*c_1 - c_2*c_2) | 1 - c_1*c_1 - c_1*c_2 | * P = ~~~~~~~~~~~~~~~~~~~~~~~ * | | * theta_0*theta_0 | - c_1*c_2 1 - c_2*c_2 | * * \param [in] aResiduals Scatterer residuals * \param [in] aPrecision Scatterer precision (matrix) */ void GblPoint::addScatterer(const TVectorD &aResiduals, const TMatrixDSym &aPrecision) { scatFlag = true; TMatrixDSymEigen scatEigen(aPrecision); TMatrixD aTransformation = scatEigen.GetEigenVectors(); aTransformation.T(); TVectorD transResiduals = aTransformation * aResiduals; TVectorD transPrecision = scatEigen.GetEigenValues(); for (unsigned int i = 0; i < 2; ++i) { scatResiduals(i) = transResiduals[i]; scatPrecision(i) = transPrecision[i]; for (unsigned int j = 0; j < 2; ++j) { scatTransformation(i, j) = aTransformation(i, j); } } } /// Check for scatterer at a point. bool GblPoint::hasScatterer() const { return scatFlag; } /// Retrieve scatterer of a point. /** * \param [out] aTransformation Scatterer transformation from diagonalization * \param [out] aResiduals Scatterer residuals * \param [out] aPrecision Scatterer precision (diagonal) */ void GblPoint::getScatterer(SMatrix22 &aTransformation, SVector2 &aResiduals, SVector2 &aPrecision) const { aTransformation = scatTransformation; aResiduals = scatResiduals; aPrecision = scatPrecision; } /// Get scatterer transformation (from diagonalization). /** * \param [out] aTransformation Transformation matrix */ void GblPoint::getScatTransformation(TMatrixD &aTransformation) const { aTransformation.ResizeTo(2, 2); if (scatFlag) { for (unsigned int i = 0; i < 2; ++i) { for (unsigned int j = 0; j < 2; ++j) { aTransformation(i, j) = scatTransformation(i, j); } } } else { aTransformation.UnitMatrix(); } } /// Add local derivatives to a point. /** * Point needs to have a measurement. * \param [in] aDerivatives Local derivatives (matrix) */ void GblPoint::addLocals(const TMatrixD &aDerivatives) { if (measDim) { localDerivatives.ResizeTo(aDerivatives); if (transFlag) { localDerivatives = measTransformation * aDerivatives; } else { localDerivatives = aDerivatives; } } } /// Retrieve number of local derivatives from a point. unsigned int GblPoint::getNumLocals() const { return localDerivatives.GetNcols(); } /// Retrieve local derivatives from a point. const TMatrixD& GblPoint::getLocalDerivatives() const { return localDerivatives; } /// Add global derivatives to a point. /** * Point needs to have a measurement. * \param [in] aLabels Global derivatives labels * \param [in] aDerivatives Global derivatives (matrix) */ void GblPoint::addGlobals(const std::vector<int> &aLabels, const TMatrixD &aDerivatives) { if (measDim) { globalLabels = aLabels; globalDerivatives.ResizeTo(aDerivatives); if (transFlag) { globalDerivatives = measTransformation * aDerivatives; } else { globalDerivatives = aDerivatives; } } } /// Retrieve number of global derivatives from a point. unsigned int GblPoint::getNumGlobals() const { return globalDerivatives.GetNcols(); } /// Retrieve global derivatives labels from a point. std::vector<int> GblPoint::getGlobalLabels() const { return globalLabels; } /// Retrieve global derivatives from a point. const TMatrixD& GblPoint::getGlobalDerivatives() const { return globalDerivatives; } /// Define label of point (by GBLTrajectory constructor) /** * \param [in] aLabel Label identifying point */ void GblPoint::setLabel(unsigned int aLabel) { theLabel = aLabel; } /// Retrieve label of point unsigned int GblPoint::getLabel() const { return theLabel; } /// Define offset for point (by GBLTrajectory constructor) /** * \param [in] anOffset Offset number */ void GblPoint::setOffset(int anOffset) { theOffset = anOffset; } /// Retrieve offset for point int GblPoint::getOffset() const { return theOffset; } /// Retrieve point-to-(previous)point jacobian const SMatrix55& GblPoint::getP2pJacobian() const { return p2pJacobian; } /// Define jacobian to previous scatterer (by GBLTrajectory constructor) /** * \param [in] aJac Jacobian */ void GblPoint::addPrevJacobian(const SMatrix55 &aJac) { int ifail = 0; // to optimize: need only two last rows of inverse // prevJacobian = aJac.InverseFast(ifail); // block matrix algebra SMatrix23 CA = aJac.Sub<SMatrix23>(3, 0) * aJac.Sub<SMatrix33>(0, 0).InverseFast(ifail); // C*A^-1 SMatrix22 DCAB = aJac.Sub<SMatrix22>(3, 3) - CA * aJac.Sub<SMatrix32>(0, 3); // D - C*A^-1 *B DCAB.InvertFast(); prevJacobian.Place_at(DCAB, 3, 3); prevJacobian.Place_at(-DCAB * CA, 3, 0); } /// Define jacobian to next scatterer (by GBLTrajectory constructor) /** * \param [in] aJac Jacobian */ void GblPoint::addNextJacobian(const SMatrix55 &aJac) { nextJacobian = aJac; } /// Retrieve derivatives of local track model /** * Linearized track model: F_u(q/p,u',u) = J*u + S*u' + d*q/p, * W is inverse of S, negated for backward propagation. * \param [in] aDirection Propagation direction (>0 forward, else backward) * \param [out] matW W * \param [out] matWJ W*J * \param [out] vecWd W*d * \exception std::overflow_error : matrix S is singular. */ void GblPoint::getDerivatives(int aDirection, SMatrix22 &matW, SMatrix22 &matWJ, SVector2 &vecWd) const { SMatrix22 matJ; SVector2 vecd; if (aDirection < 1) { matJ = prevJacobian.Sub<SMatrix22>(3, 3); matW = -prevJacobian.Sub<SMatrix22>(3, 1); vecd = prevJacobian.SubCol<SVector2>(0, 3); } else { matJ = nextJacobian.Sub<SMatrix22>(3, 3); matW = nextJacobian.Sub<SMatrix22>(3, 1); vecd = nextJacobian.SubCol<SVector2>(0, 3); } if (!matW.InvertFast()) { std::cout << " GblPoint::getDerivatives failed to invert matrix: " << matW << std::endl; std::cout << " Possible reason for singular matrix: multiple GblPoints at same arc-length" << std::endl; throw std::overflow_error("Singular matrix inversion exception"); } matWJ = matW * matJ; vecWd = matW * vecd; } /// Print GblPoint /** * \param [in] level print level (0: minimum, >0: more) */ void GblPoint::printPoint(unsigned int level) const { std::cout << " GblPoint"; if (theLabel) { std::cout << ", label " << theLabel; if (theOffset >= 0) { std::cout << ", offset " << theOffset; } } if (measDim) { std::cout << ", " << measDim << " measurements"; } if (scatFlag) { std::cout << ", scatterer"; } if (transFlag) { std::cout << ", diagonalized"; } if (localDerivatives.GetNcols()) { std::cout << ", " << localDerivatives.GetNcols() << " local derivatives"; } if (globalDerivatives.GetNcols()) { std::cout << ", " << globalDerivatives.GetNcols() << " global derivatives"; } std::cout << std::endl; if (level > 0) { if (measDim) { std::cout << " Measurement" << std::endl; std::cout << " Projection: " << std::endl << measProjection << std::endl; std::cout << " Residuals: " << measResiduals << std::endl; std::cout << " Precision: " << measPrecision << std::endl; } if (scatFlag) { std::cout << " Scatterer" << std::endl; std::cout << " Residuals: " << scatResiduals << std::endl; std::cout << " Precision: " << scatPrecision << std::endl; } if (localDerivatives.GetNcols()) { std::cout << " Local Derivatives:" << std::endl; localDerivatives.Print(); } if (globalDerivatives.GetNcols()) { std::cout << " Global Labels:"; for (unsigned int i = 0; i < globalLabels.size(); ++i) { std::cout << " " << globalLabels[i]; } std::cout << std::endl; std::cout << " Global Derivatives:" << std::endl; globalDerivatives.Print(); } std::cout << " Jacobian " << std::endl; std::cout << " Point-to-point " << std::endl << p2pJacobian << std::endl; if (theLabel) { std::cout << " To previous offset " << std::endl << prevJacobian << std::endl; std::cout << " To next offset " << std::endl << nextJacobian << std::endl; } } } }
15,240
5,738
#include "opengl.h" #include "logger.h" #define CHECK_GL(...) check_gl_error(__FILE__, __LINE__); int check_gl_error(char * file, int line) { GLuint err = glGetError(); if (err > 0) { log_warning("GL Error - file:%s line: %d error: %d", file, line, err); switch(err) { case GL_INVALID_ENUM: log_warning("GL_INVALID_ENUM: Given when an enumeration parameter is not a legal enumeration for that function. This is given only for local problems; if the spec allows the enumeration in certain circumstances, where other parameters or state dictate those circumstances, then GL_INVALID_OPERATION is the result instead."); break; case GL_INVALID_VALUE: log_warning("GL_INVALID_VALUE: Given when a value parameter is not a legal value for that function. This is only given for local problems; if the spec allows the value in certain circumstances, where other parameters or state dictate those circumstances, then GL_INVALID_OPERATION is the result instead."); break; case GL_INVALID_OPERATION: log_warning("GL_INVALID_OPERATION: Given when the set of state for a command is not legal for the parameters given to that command. It is also given for commands where combinations of parameters define what the legal parameters are."); break; case GL_STACK_OVERFLOW: log_warning("GL_STACK_OVERFLOW: Given when a stack pushing operation cannot be done because it would overflow the limit of that stack's size."); break; case GL_STACK_UNDERFLOW: log_warning("GL_STACK_UNDERFLOW: Given when a stack popping operation cannot be done because the stack is already at its lowest point."); break; case GL_OUT_OF_MEMORY: log_warning("GL_OUT_OF_MEMORY: Given when performing an operation that can allocate memory, and the memory cannot be allocated. The results of OpenGL functions that return this error are undefined; it is allowable for partial operations to happen."); break; case GL_INVALID_FRAMEBUFFER_OPERATION: log_warning("GL_INVALID_FRAMEBUFFER_OPERATION: Given when doing anything that would attempt to read from or write/render to a framebuffer that is not complete."); break; case GL_CONTEXT_LOST: log_warning("GL_CONTEXT_LOST: Given if the OpenGL context has been lost, due to a graphics card reset."); break; } } return err; } void init_renderer(void* data) { if (!gladLoadGLLoader((GLADloadproc)data)) { printf("Failed to init GLAD. \n"); Assert(false); } // TODO : Print those char* opengl_vendor = (char*)glGetString(GL_VENDOR); char* opengl_renderer = (char*)glGetString(GL_RENDERER); char* opengl_version = (char*)glGetString(GL_VERSION); char* shading_language_version = (char*)glGetString(GL_SHADING_LANGUAGE_VERSION); log_info("GL Vendor %s", opengl_vendor); log_info("GL Renderer %s", opengl_renderer); log_info("GL Version %s", opengl_version); log_info("GL Shading Language Version %s", shading_language_version); // GLint n, i; // glGetIntegerv(GL_NUM_EXTENSIONS, &n); // for (i = 0; i < n; i++) // { // char* extension = (char*)glGetStringi(GL_EXTENSIONS, i); // } }
3,055
970
// Copyright (C) 2018 ETH Zurich // Copyright (C) 2018 UT-Battelle, LLC // All rights reserved. // // See LICENSE for terms of usage. // See CITATION.md for citation guidelines, if DCA++ is used for scientific publications. // // Author: Peter Staar (taa@zurich.ibm.com) // // This class computes the nonlocal \f$\chi(k_1,k_2,q)\f$. /* * Definition of two-particle functions: * * \section ph particle-hole channel: * * The magnetic channel, * * \f{eqnarray*}{ * G^{II}_{ph} &=& \frac{1}{4} \sum_{\sigma_1,\sigma_2 = \pm1} (\sigma_1 \: \sigma_2) \langle * T_\tau\{c^\dagger_{k_1+q,\sigma_1} c_{k_1,\sigma_1} c^\dagger_{k_2,\sigma_2} * c_{k_2+q,\sigma_2} \}\rangle * \f} * * The charge channel, * * \f{eqnarray*}{ * G^{II}_{ph} &=& \frac{1}{4} \sum_{\sigma_1,\sigma_2 = \pm1} \langle * T_\tau\{c^\dagger_{k_1+q,\sigma_1} c_{k_1,\sigma_1} c^\dagger_{k_2,\sigma_2} * c_{k_2+q,\sigma_2} \}\rangle * \f} * * The transverse channel, * * \f{eqnarray*}{ * G^{II}_{ph} &=& \frac{1}{2} \sum_{\sigma = \pm1} \langle T_\tau\{c^\dagger_{k_1+q,\sigma} * c_{k_1,-\sigma} c^\dagger_{k_2,-\sigma} c_{k_2+q,\sigma} \}\rangle * \f} * * \section pp particle-hole channel: * * The transverse (or superconducting) channel, * * \f{eqnarray*}{ * G^{II}_{pp} &=& \frac{1}{2} \sum_{\sigma= \pm1} \langle T_\tau\{ c^\dagger_{q-k_1,\sigma} * c^\dagger_{k_1,-\sigma} c_{k_2,-\sigma} c_{q-k_2,\sigma} \} * \f} */ #ifndef DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP #define DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP #include <cassert> #include <cmath> #include <complex> #include "dca/function/domains.hpp" #include "dca/function/function.hpp" #include "dca/phys/domains/cluster/cluster_domain.hpp" #include "dca/phys/domains/quantum/electron_band_domain.hpp" #include "dca/phys/domains/time_and_frequency/vertex_frequency_domain.hpp" #include "dca/phys/four_point_type.hpp" #include "dca/phys/domains/cluster/cluster_domain_aliases.hpp" namespace dca { namespace phys { namespace solver { namespace ctaux { // dca::phys::solver::ctaux:: template <class parameters_type, class MOMS_type> class accumulator_nonlocal_chi { public: using w_VERTEX = func::dmn_0<domains::vertex_frequency_domain<domains::COMPACT>>; using w_VERTEX_EXTENDED = func::dmn_0<domains::vertex_frequency_domain<domains::EXTENDED>>; using w_VERTEX_EXTENDED_POS = func::dmn_0<domains::vertex_frequency_domain<domains::EXTENDED_POSITIVE>>; using b = func::dmn_0<domains::electron_band_domain>; using CDA = ClusterDomainAliases<parameters_type::lattice_type::DIMENSION>; using RClusterDmn = typename CDA::RClusterDmn; using KClusterDmn = typename CDA::KClusterDmn; // This needs shifted to new aliases typedef RClusterDmn r_dmn_t; typedef KClusterDmn k_dmn_t; typedef typename r_dmn_t::parameter_type r_cluster_type; typedef typename k_dmn_t::parameter_type k_cluster_type; typedef typename parameters_type::profiler_type profiler_t; typedef typename parameters_type::concurrency_type concurrency_type; typedef typename parameters_type::MC_measurement_scalar_type scalar_type; typedef typename parameters_type::G4_w1_dmn_t w1_dmn_t; typedef typename parameters_type::G4_w2_dmn_t w2_dmn_t; typedef func::dmn_variadic<b, b, r_dmn_t, r_dmn_t, w1_dmn_t, w2_dmn_t> b_b_r_r_w_w_dmn_t; typedef func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w1_dmn_t, w2_dmn_t> b_b_k_k_w_w_dmn_t; public: accumulator_nonlocal_chi( parameters_type& parameters_ref, MOMS_type& MOMS_ref, int id, func::function<std::complex<double>, func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4_ref); void initialize(); void finalize(); template <class nonlocal_G_t> void execute(scalar_type current_sign, nonlocal_G_t& nonlocal_G_obj); private: void F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result); void F(int n1, int m1, int k1, int k2, int w1, int w2, func::function< std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result); void F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result); void F(int n1, int m1, int k1, int k2, int w1, int w2, func::function< std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function< std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result); void accumulate_particle_hole_transverse( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); void accumulate_particle_hole_magnetic( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); void accumulate_particle_hole_charge( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); void accumulate_particle_particle_superconducting( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign); private: parameters_type& parameters; MOMS_type& MOMS; concurrency_type& concurrency; int thread_id; func::function<std::complex<double>, func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4; int w_VERTEX_EXTENDED_POS_dmn_size; func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED> b_b_k_k_w_full_w_full_dmn; func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED> b_b_k_k_w_pos_w_full_dmn; func::function<int, k_dmn_t> min_k_dmn_t; func::function<int, k_dmn_t> q_plus_; func::function<int, k_dmn_t> q_min_; func::function<int, w_VERTEX> min_w_vertex; func::function<int, w_VERTEX_EXTENDED> min_w_vertex_ext; func::function<int, w_VERTEX> w_vertex_2_w_vertex_ext; func::function<int, w_VERTEX_EXTENDED> w_vertex_ext_2_w_vertex_ext_pos; }; template <class parameters_type, class MOMS_type> accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulator_nonlocal_chi( parameters_type& parameters_ref, MOMS_type& MOMS_ref, int id, func::function<std::complex<double>, func::dmn_variadic<b, b, b, b, k_dmn_t, k_dmn_t, w_VERTEX, w_VERTEX>>& G4_ref) : parameters(parameters_ref), MOMS(MOMS_ref), concurrency(parameters.get_concurrency()), thread_id(id), G4(G4_ref), w_VERTEX_EXTENDED_POS_dmn_size(w_VERTEX_EXTENDED_POS::dmn_size()), b_b_k_k_w_full_w_full_dmn(), b_b_k_k_w_pos_w_full_dmn(), min_k_dmn_t("min_k_dmn_t"), q_plus_("q_plus_"), q_min_("q_min_"), min_w_vertex(" min_w_vertex"), min_w_vertex_ext("min_w_vertex_ext"), w_vertex_2_w_vertex_ext("w_vertex_2_w_vertex_ext"), w_vertex_ext_2_w_vertex_ext_pos("w_vertex_ext_2_w_vertex_ext_pos") { int q_channel = parameters.get_four_point_momentum_transfer_index(); // int k0_index = k_cluster_type::get_k_0_index(); int k0_index = k_cluster_type::origin_index(); for (int l = 0; l < k_cluster_type::get_size(); l++) { min_k_dmn_t(l) = k_cluster_type::subtract(l, k0_index); q_plus_(l) = k_cluster_type::add(l, q_channel); q_min_(l) = k_cluster_type::subtract(l, q_channel); } { for (int l = 0; l < w_VERTEX::dmn_size(); l++) min_w_vertex(l) = w_VERTEX::dmn_size() - 1 - l; for (int l = 0; l < w_VERTEX_EXTENDED::dmn_size(); l++) min_w_vertex_ext(l) = w_VERTEX_EXTENDED::dmn_size() - 1 - l; } { for (int i = 0; i < w_VERTEX::dmn_size(); i++) for (int j = 0; j < w_VERTEX_EXTENDED::dmn_size(); j++) if (std::fabs(w_VERTEX::get_elements()[i] - w_VERTEX_EXTENDED::get_elements()[j]) < 1.e-6) w_vertex_2_w_vertex_ext(i) = j; } { for (int l = 0; l < w_VERTEX_EXTENDED::dmn_size(); l++) { if (l < w_VERTEX_EXTENDED_POS::dmn_size()) w_vertex_ext_2_w_vertex_ext_pos(l) = w_VERTEX_EXTENDED_POS::dmn_size() - 1 - l; else w_vertex_ext_2_w_vertex_ext_pos(l) = l - w_VERTEX_EXTENDED_POS::dmn_size(); // cout << l << "\t" << w_vertex_ext_2_w_vertex_ext_pos(l) << "\n"; } } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::initialize() { MOMS.get_G4_k_k_w_w() = 0.; } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::finalize() { // for(int i=0; i<G4.size(); i++) // MOMS.G4_k_k_w_w(i) = G4(i); } template <class parameters_type, class MOMS_type> template <class nonlocal_G_t> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::execute(scalar_type current_sign, nonlocal_G_t& nonlocal_G_obj) { profiler_t profiler("compute nonlocal-chi", "CT-AUX accumulator", __LINE__, thread_id); switch (parameters.get_four_point_type()) { case PARTICLE_HOLE_TRANSVERSE: accumulate_particle_hole_transverse(nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; case PARTICLE_HOLE_MAGNETIC: accumulate_particle_hole_magnetic(nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; case PARTICLE_HOLE_CHARGE: accumulate_particle_hole_charge(nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; case PARTICLE_PARTICLE_UP_DOWN: accumulate_particle_particle_superconducting( nonlocal_G_obj.get_G_k_k_w_w_e_DN(), nonlocal_G_obj.get_G_k_k_w_w_e_UP(), current_sign); break; default: throw std::logic_error(__FUNCTION__); } } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result) { G2_result = G2(n1, m1, k1, k2, w1, w2); } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2, std::complex<scalar_type>& G2_result) { if (w1 < w_VERTEX_EXTENDED_POS_dmn_size) { G2_result = conj(G2(n1, m1, min_k_dmn_t(k1), min_k_dmn_t(k2), w_vertex_ext_2_w_vertex_ext_pos(w1), min_w_vertex_ext(w2))); } else { G2_result = G2(n1, m1, k1, k2, w_vertex_ext_2_w_vertex_ext_pos(w1), w2); } } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result) { int lin_ind = b_b_k_k_w_full_w_full_dmn(n1, m1, k1, k2, w1, w2); G2_dn_result = G2_dn(lin_ind); G2_up_result = G2_up(lin_ind); } template <class parameters_type, class MOMS_type> inline void accumulator_nonlocal_chi<parameters_type, MOMS_type>::F( int n1, int m1, int k1, int k2, int w1, int w2, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_dn, std::complex<scalar_type>& G2_dn_result, func::function<std::complex<scalar_type>, func::dmn_variadic<b, b, k_dmn_t, k_dmn_t, w_VERTEX_EXTENDED_POS, w_VERTEX_EXTENDED>>& G2_up, std::complex<scalar_type>& G2_up_result) { if (w1 < w_VERTEX_EXTENDED_POS_dmn_size) { int lin_ind = b_b_k_k_w_pos_w_full_dmn(n1, m1, min_k_dmn_t(k1), min_k_dmn_t(k2), w_vertex_ext_2_w_vertex_ext_pos(w1), min_w_vertex_ext(w2)); G2_dn_result = conj(G2_dn(lin_ind)); G2_up_result = conj(G2_up(lin_ind)); } else { int lin_ind = b_b_k_k_w_pos_w_full_dmn(n1, m1, k1, k2, w_vertex_ext_2_w_vertex_ext_pos(w1), w2); G2_dn_result = G2_dn(lin_ind); G2_up_result = G2_up(lin_ind); } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_magnetic( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { // n1 ------------------------ m1 // | | // | | // | | // n2 ------------------------ m2 std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_UP_n1_m1_k1_k1_plus_q_w1_w1, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4_val; int k2_plus_q, k1_plus_q; scalar_type sign_div_2 = scalar_type(sign) / 2.; int w_nu = parameters.get_four_point_frequency_transfer(); for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w2_ext_plus_w_nu = w2_ext + w_nu; assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) < 1.e-6); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w1_ext_plus_w_nu = w1_ext + w_nu; for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { // int k2_plus_q = k_cluster_type::add(k2,q_channel); k2_plus_q = q_plus_(k2); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { // int k1_plus_q = k_cluster_type::add(k1,q_channel); k1_plus_q = q_plus_(k1); for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); F(n1, m1, k1, k1_plus_q, w1_ext, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k1_plus_q_w1_w1); F(n2, m2, k2_plus_q, k2, w2_ext_plus_w_nu, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_k2_plus_q_k2_w2_w2); G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 + G2_UP_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1) + (G2_UP_n1_m1_k1_k1_plus_q_w1_w1 - G2_DN_n1_m1_k1_k1_plus_q_w1_w1) * (G2_UP_n2_m2_k2_plus_q_k2_w2_w2 - G2_DN_n2_m2_k2_plus_q_k2_w2_w2); /* G4 = - (G2_k_k_w_w_e_DN(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_DN(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel) + G2_k_k_w_w_e_UP(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_UP(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel)) + (G2_k_k_w_w_e_UP(n1, m1, k1, k1_plus_q, w1, w1+w_channel) - G2_k_k_w_w_e_DN(n1, m1, k1, k1_plus_q, w1, w1+w_channel)) * (G2_k_k_w_w_e_UP(n2, m2, k2_plus_q, k2, w2+w_channel, w2) - G2_k_k_w_w_e_DN(n2, m2, k2_plus_q, k2, w2+w_channel, w2)); */ G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); // MOMS.G4_k_k_w_w(n1, n2, m1, m2, k1, k2, w1, w2) += // std::complex<double>(sign_div_2 * G4); } } } } } } } } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_transverse( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { // n1 ------------------------ m1 // | | // | | // | | // n2 ------------------------ m2 std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G4_val; int k2_plus_q, k1_plus_q; scalar_type sign_div_2 = scalar_type(sign) / 2.; int w_nu = parameters.get_four_point_frequency_transfer(); for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w2_ext_plus_w_nu = w2_ext + w_nu; assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) < 1.e-6); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w1_ext_plus_w_nu = w1_ext + w_nu; for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { k2_plus_q = q_plus_(k2); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { k1_plus_q = q_plus_(k1); for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { // F(n1, m2, k1, k2, w1, w2, // G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, // G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); // F(n2, m1, k2_plus_q, k1_plus_q, w2+w_nu, w1+w_nu, // G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, // G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1 + G2_UP_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1); G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); } } } } } } } } } /* template<class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_magnetic_fast(func::function<std::complex<scalar_type>, func::dmn_variadic<b,b,k_dmn_t,k_dmn_t,w_VERTEX,w_VERTEX> >& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, func::dmn_variadic<b,b,k_dmn_t,k_dmn_t,w_VERTEX,w_VERTEX> >& G2_k_k_w_w_e_UP, scalar_type sign) { std::complex<scalar_type> *G2_DN_n1_m2_k1_k2_w1_w2, *G2_UP_n1_m2_k1_k2_w1_w2, *G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, *G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, *G2_DN_n1_m1_k1_k1_plus_q_w1_w1, *G2_UP_n1_m1_k1_k1_plus_q_w1_w1, *G2_DN_n2_m2_k2_plus_q_k2_w2_w2, *G2_UP_n2_m2_k2_plus_q_k2_w2_w2; std::complex<double>* G4; int k2_plus_q, k1_plus_q; scalar_type sign_div_2 =scalar_type(sign)/2.; for(int w2=0; w2<w_VERTEX::dmn_size(); w2++){ for(int w1=0; w1<w_VERTEX::dmn_size(); w1++){ for(int k2=0; k2<k_dmn_t::dmn_size(); k2++){ // int k2_plus_q = k_cluster_type::add(k2,q_channel); k2_plus_q = q_plus_(k2); for(int k1=0; k1<k_dmn_t::dmn_size(); k1++){ // int k1_plus_q = k_cluster_type::add(k1,q_channel); k1_plus_q = q_plus_(k1); G2_DN_n1_m2_k1_k2_w1_w2 = &G2_k_k_w_w_e_DN(0, 0, k1, k2, w1, w2); G2_UP_n1_m2_k1_k2_w1_w2 = &G2_k_k_w_w_e_UP(0, 0, k1, k2, w1, w2); G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 = &G2_k_k_w_w_e_DN(0, 0, k2_plus_q, k1_plus_q, w2, w1); G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1 = &G2_k_k_w_w_e_UP(0, 0, k2_plus_q, k1_plus_q, w2, w1); G2_DN_n1_m1_k1_k1_plus_q_w1_w1 = &G2_k_k_w_w_e_DN(0, 0, k1, k1_plus_q, w1, w1); G2_UP_n1_m1_k1_k1_plus_q_w1_w1 = &G2_k_k_w_w_e_UP(0, 0, k1, k1_plus_q, w1, w1); G2_DN_n2_m2_k2_plus_q_k2_w2_w2 = &G2_k_k_w_w_e_DN(0, 0, k2_plus_q, k2, w2, w2); G2_UP_n2_m2_k2_plus_q_k2_w2_w2 = &G2_k_k_w_w_e_UP(0, 0, k2_plus_q, k2, w2, w2); G4 = &MOMS.G4_k_k_w_w(0,0,0,0, k1, k2, w1, w2); accumulator_nonlocal_chi_atomic<model, PARTICLE_HOLE_MAGNETIC>::execute(G2_DN_n1_m2_k1_k2_w1_w2 , G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n1_m1_k1_k1_plus_q_w1_w1 , G2_UP_n1_m1_k1_k1_plus_q_w1_w1, G2_DN_n2_m2_k2_plus_q_k2_w2_w2 , G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4, sign_div_2); } } } } } */ template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_hole_charge( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { // n1 ------------------------ m1 // | | // | | // | | // n2 ------------------------ m2 // int q_channel = parameters.get_q_channel(); std::complex<scalar_type> G2_DN_n1_m2_k1_k2_w1_w2, G2_UP_n1_m2_k1_k2_w1_w2, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_UP_n1_m1_k1_k1_plus_q_w1_w1, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_UP_n2_m2_k2_plus_q_k2_w2_w2, G4_val; int w_nu = parameters.get_four_point_frequency_transfer(); scalar_type sign_div_2 = scalar_type(sign) / 2.; for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w2_ext_plus_w_nu = w2_ext + w_nu; assert(std::fabs(w_VERTEX::get_elements()[w2] - w_VERTEX_EXTENDED::get_elements()[w2_ext]) < 1.e-6); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w1_ext_plus_w_nu = w1_ext + w_nu; for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { // int k2_plus_q = k_cluster_type::add(k2,q_channel); int k2_plus_q = q_plus_(k2); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { // int k1_plus_q = k_cluster_type::add(k1,q_channel); int k1_plus_q = q_plus_(k1); for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { F(n1, m2, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m2_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m2_k1_k2_w1_w2); F(n2, m1, k2_plus_q, k1_plus_q, w2_ext_plus_w_nu, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1, G2_k_k_w_w_e_UP, G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1); F(n1, m1, k1, k1_plus_q, w1_ext, w1_ext_plus_w_nu, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k1_plus_q_w1_w1, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k1_plus_q_w1_w1); F(n2, m2, k2_plus_q, k2, w2_ext_plus_w_nu, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n2_m2_k2_plus_q_k2_w2_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_k2_plus_q_k2_w2_w2); G4_val = -(G2_DN_n1_m2_k1_k2_w1_w2 * G2_DN_n2_m1_k2_plus_q_k1_plus_q_w2_w1 + G2_UP_n1_m2_k1_k2_w1_w2 * G2_UP_n2_m1_k2_plus_q_k1_plus_q_w2_w1) + (G2_UP_n1_m1_k1_k1_plus_q_w1_w1 + G2_DN_n1_m1_k1_k1_plus_q_w1_w1) * (G2_UP_n2_m2_k2_plus_q_k2_w2_w2 + G2_DN_n2_m2_k2_plus_q_k2_w2_w2); /* G4 = - (G2_k_k_w_w_e_DN(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_DN(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel) + G2_k_k_w_w_e_UP(n1, m2, k1, k2, w1, w2) * G2_k_k_w_w_e_UP(n2, m1, k2_plus_q, k1_plus_q, w2+w_channel, w1+w_channel)) + (G2_k_k_w_w_e_UP(n1, m1, k1, k1_plus_q, w1, w1+w_channel) + G2_k_k_w_w_e_DN(n1, m1, k1, k1_plus_q, w1, w1+w_channel)) * (G2_k_k_w_w_e_UP(n2, m2, k2_plus_q, k2, w2+w_channel, w2) + G2_k_k_w_w_e_DN(n2, m2, k2_plus_q, k2, w2+w_channel, w2)); */ G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); // MOMS.G4_k_k_w_w(n1, n2, m1, m2, k1, k2, w1, w2) += // std::complex<double>(sign_div_2 * G4); } } } } } } } } } template <class parameters_type, class MOMS_type> void accumulator_nonlocal_chi<parameters_type, MOMS_type>::accumulate_particle_particle_superconducting( func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_DN, func::function<std::complex<scalar_type>, b_b_k_k_w_w_dmn_t>& G2_k_k_w_w_e_UP, scalar_type sign) { std::complex<scalar_type> G2_UP_n1_m1_k1_k2_w1_w2, G2_DN_n1_m1_k1_k2_w1_w2, G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G4_val; int w_nu = parameters.get_four_point_frequency_transfer(); scalar_type sign_div_2 = sign / 2.; for (int w2 = 0; w2 < w_VERTEX::dmn_size(); w2++) { int w2_ext = w_vertex_2_w_vertex_ext(w2); int w_nu_min_w2 = w_nu + w_vertex_2_w_vertex_ext(min_w_vertex(w2)); for (int w1 = 0; w1 < w_VERTEX::dmn_size(); w1++) { int w1_ext = w_vertex_2_w_vertex_ext(w1); int w_nu_min_w1 = w_nu + w_vertex_2_w_vertex_ext(min_w_vertex(w1)); for (int k1 = 0; k1 < k_dmn_t::dmn_size(); k1++) { int q_minus_k1 = q_min_(k1); for (int k2 = 0; k2 < k_dmn_t::dmn_size(); k2++) { int q_minus_k2 = q_min_(k2); for (int n1 = 0; n1 < b::dmn_size(); n1++) { for (int n2 = 0; n2 < b::dmn_size(); n2++) { for (int m1 = 0; m1 < b::dmn_size(); m1++) { for (int m2 = 0; m2 < b::dmn_size(); m2++) { F(n1, m1, k1, k2, w1_ext, w2_ext, G2_k_k_w_w_e_DN, G2_DN_n1_m1_k1_k2_w1_w2, G2_k_k_w_w_e_UP, G2_UP_n1_m1_k1_k2_w1_w2); F(n2, m2, q_minus_k1, q_minus_k2, w_nu_min_w1, w_nu_min_w2, G2_k_k_w_w_e_UP, G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2, G2_k_k_w_w_e_DN, G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2); G4_val = (G2_UP_n1_m1_k1_k2_w1_w2 * G2_DN_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2 + G2_DN_n1_m1_k1_k2_w1_w2 * G2_UP_n2_m2_q_min_k1_q_min_k2_min_w1_min_w2); G4(n1, n2, m1, m2, k1, k2, w1, w2) += std::complex<double>(sign_div_2 * G4_val); } } } } } } } } } } // ctaux } // solver } // phys } // dca #endif // DCA_PHYS_DCA_STEP_CLUSTER_SOLVER_CTAUX_ACCUMULATOR_TP_ACCUMULATOR_NONLOCAL_CHI_HPP
29,878
15,002
/* * MarkerFilter.hpp * * Created on: Mar 4, 2014 * Author: dacocp */ #ifndef MARKERFILTER_HPP_ #define MARKERFILTER_HPP_ #include "common/FTag2.hpp" #include "tracker/PayloadFilter.hpp" #include "detector/FTag2Detector.hpp" #include "tracker/Kalman.hpp" using namespace std; class MarkerFilter { private: FTag2Marker detectedTag; int frames_without_detection; PayloadFilter IF; Kalman KF; static int num_Markers; int marker_id; public: bool active; bool got_detection_in_current_frame; FTag2Marker hypothesis; MarkerFilter(int tagType) : detectedTag(tagType), IF(tagType), hypothesis(tagType) { frames_without_detection = 0; active = false; got_detection_in_current_frame = false; }; MarkerFilter(FTag2Marker detection, double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion ); virtual ~MarkerFilter() {}; FTag2Marker getHypothesis() { return hypothesis; } int get_frames_without_detection() { return frames_without_detection; } void step( FTag2Marker detection, double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion ); void step( double quadSizeM, cv::Mat cameraIntrinsic, cv::Mat cameraDistortion ); void updateParameters(); }; #endif /* MARKERFILTER_HPP_ */
1,240
452
#include "Scene/INativeScript.h" using namespace gear; using namespace scene; class TestScript : public INativeScript { public: TestScript() = default; ~TestScript() = default; bool first = true; mars::float3 initPos; void OnCreate() { } void OnDestroy() { objects::Transform& transform = GetEntity().GetComponent<TransformComponent>().transform; transform.translation = initPos; } void OnUpdate(float deltaTime) { objects::Transform& transform = GetEntity().GetComponent<TransformComponent>().transform; mars::float3& pos = transform.translation; if (first) { initPos = pos; first = false; } pos.z += 0.5f * deltaTime; } }; GEAR_LOAD_SCRIPT(TestScript); GEAR_UNLOAD_SCRIPT(TestScript);
728
263
#define CATCH_CONFIG_MAIN // This tells Catch to provide a main() - only do this in on #define CATCH_CONFIG_FAST_COMPILE // Sacrifices some (rather minor) features for compilation speed #define CATCH_CONFIG_DISABLE_MATCHERS // Do not compile Matchers in this compilation unit #include "catch.hpp"
320
91
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // // $NoKeywords: $ //=============================================================================// #include "IMessageListener.h" #include "VPanel.h" #include "vgui_internal.h" #include <KeyValues.h> #include "vgui/IClientPanel.h" #include "vgui/IVGui.h" // memdbgon must be the last include file in a .cpp file!!! #include "tier0/memdbgon.h" namespace vgui { //----------------------------------------------------------------------------- // Implementation of the message listener //----------------------------------------------------------------------------- class CMessageListener : public IMessageListener { public: virtual void Message( VPanel* pSender, VPanel* pReceiver, KeyValues* pKeyValues, MessageSendType_t type ); }; void CMessageListener::Message( VPanel* pSender, VPanel* pReceiver, KeyValues* pKeyValues, MessageSendType_t type ) { char const *pSenderName = "NULL"; if (pSender) pSenderName = pSender->Client()->GetName(); char const *pSenderClass = "NULL"; if (pSender) pSenderClass = pSender->Client()->GetClassName(); char const *pReceiverName = "unknown name"; if (pReceiver) pReceiverName = pReceiver->Client()->GetName(); char const *pReceiverClass = "unknown class"; if (pReceiver) pReceiverClass = pReceiver->Client()->GetClassName(); // FIXME: Make a bunch of filters here // filter out key focus messages if (!strcmp (pKeyValues->GetName(), "KeyFocusTicked")) { return; } // filter out mousefocus messages else if (!strcmp (pKeyValues->GetName(), "MouseFocusTicked")) { return; } // filter out cursor movement messages else if (!strcmp (pKeyValues->GetName(), "CursorMoved")) { return; } // filter out cursor entered messages else if (!strcmp (pKeyValues->GetName(), "CursorEntered")) { return; } // filter out cursor exited messages else if (!strcmp (pKeyValues->GetName(), "CursorExited")) { return; } // filter out MouseCaptureLost messages else if (!strcmp (pKeyValues->GetName(), "MouseCaptureLost")) { return; } // filter out MousePressed messages else if (!strcmp (pKeyValues->GetName(), "MousePressed")) { return; } // filter out MouseReleased messages else if (!strcmp (pKeyValues->GetName(), "MouseReleased")) { return; } // filter out Tick messages else if (!strcmp (pKeyValues->GetName(), "Tick")) { return; } Msg( "%s : (%s (%s) - > %s (%s)) )\n", pKeyValues->GetName(), pSenderClass, pSenderName, pReceiverClass, pReceiverName ); } //----------------------------------------------------------------------------- // Singleton instance //----------------------------------------------------------------------------- static CMessageListener s_MessageListener; IMessageListener *MessageListener() { return &s_MessageListener; } }
2,860
894
/** * @file * @author Mamadou Babaei <info@babaei.net> * @version 0.1.0 * * @section LICENSE * * (The MIT License) * * Copyright (c) 2016 - 2021 Mamadou Babaei * * 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. * * @section DESCRIPTION * * A tiny utility program to spawn a collection of wthttpd applications if they * won't exists in memory already. In addition to that, it monitors the * application and does re-spawn it in case of a crash. * You might want to run this as a cron job. */ #include <fstream> #include <iostream> #include <map> #include <stdexcept> #include <streambuf> #include <string> #include <vector> #include <csignal> #include <cstdlib> #include <boost/algorithm/string.hpp> #include <boost/exception/diagnostic_information.hpp> #include <boost/filesystem.hpp> #include <boost/foreach.hpp> #include <boost/format.hpp> #include <boost/lexical_cast.hpp> #include <boost/property_tree/json_parser.hpp> #include <boost/property_tree/ptree.hpp> #include <CoreLib/CoreLib.hpp> #include <CoreLib/Exception.hpp> #include <CoreLib/FileSystem.hpp> #include <CoreLib/Log.hpp> #include <CoreLib/System.hpp> #define UNKNOWN_ERROR "Unknown error!" const std::string DATABASE_FILE_NAME = "spawn-wthttpd.db"; static boost::property_tree::ptree appsTree; [[ noreturn ]] void Terminate(int signo); bool ReadApps(); void ReSpawn(); int main(int argc, char **argv) { try { /// Gracefully handling SIGTERM void (*prev_fn)(int); prev_fn = signal(SIGTERM, Terminate); if (prev_fn == SIG_IGN) signal(SIGTERM, SIG_IGN); /// Extract the executable path and name boost::filesystem::path path(boost::filesystem::initial_path<boost::filesystem::path>()); if (argc > 0 && argv[0] != NULL) path = boost::filesystem::system_complete(boost::filesystem::path(argv[0])); std::string appId(path.filename().string()); std::string appPath(boost::algorithm::replace_last_copy(path.string(), appId, "")); /// Force changing the current path to executable path boost::filesystem::current_path(appPath); /// Initializing CoreLib CoreLib::CoreLibInitialize(argc, argv); #if GDPR_COMPLIANCE CoreLib::Log::Initialize(std::cout); #else // GDPR_COMPLIANCE CoreLib::Log::Initialize(std::cout, (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("log")).string(), "SpawnWtHttpd"); #endif // GDPR_COMPLIANCE /// Acquiring process lock std::string lockId; #if defined ( __unix__ ) int lock; lockId = (boost::filesystem::path(appPath) / boost::filesystem::path("..") / boost::filesystem::path("tmp") / (appId + ".lock")).string(); #elif defined ( _WIN32 ) HANDLE lock; lockId = appId; #endif // defined ( __unix__ ) if(!CoreLib::System::GetLock(lockId, lock)) { std::cerr << "Could not get lock!" << std::endl; std::cerr << "Probably process is already running!" << std::endl; return EXIT_FAILURE; } else { LOG_INFO("Got the process lock!"); } if(!ReadApps()) { return EXIT_FAILURE; } if (appsTree.empty() || appsTree.count("apps") == 0 || appsTree.get_child("apps").count("") == 0) { std::cerr << "There is no WtHttpd app to spawn!" << std::endl; return EXIT_FAILURE; } while (true) { ReSpawn(); sleep(1); } } catch (CoreLib::Exception<std::string> &ex) { LOG_ERROR(ex.What()); } catch (boost::exception &ex) { LOG_ERROR(boost::diagnostic_information(ex)); } catch (std::exception &ex) { LOG_ERROR(ex.what()); } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } return EXIT_SUCCESS; } void Terminate(int signo) { std::clog << "Terminating...." << std::endl; exit(signo); } bool ReadApps() { std::ifstream dbFile( (boost::filesystem::path("..") / boost::filesystem::path("db") / DATABASE_FILE_NAME).string() ); if (!dbFile.is_open()) { std::cerr << "Unable to open the database file!" << std::endl; return false; } try { boost::property_tree::read_json(dbFile, appsTree); } catch (std::exception const &ex) { LOG_ERROR(ex.what()); return false; } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } return true; } void ReSpawn() { try { BOOST_FOREACH(boost::property_tree::ptree::value_type &appNode, appsTree.get_child("apps")) { if (appNode.first.empty()) { bool running = false; std::vector<int> pids; if (appNode.second.get_child_optional("pid-file")) { if (CoreLib::FileSystem::FileExists(appNode.second.get<std::string>("pid-file"))) { std::ifstream pidFile(appNode.second.get<std::string>("pid-file")); if (pidFile.is_open()) { std::string firstLine; getline(pidFile, firstLine); pidFile.close(); boost::algorithm::trim(firstLine); try { int pid = boost::lexical_cast<int>(firstLine); // The shell way: // To check if ${PID} exists // kill -0 ${PID} // Other possible ways to get process name or full-path // ps -p ${PID} -o comm= // or // FreeBSD // ps axwww -o pid,command | grep ${PID} // GNU/Linux // ps ax -o pid,cmd | grep ${PID} if (CoreLib::System::GetPidsOfProcess( CoreLib::System::GetProcessNameFromPath(appNode.second.get<std::string>("app")), pids)) { if (pids.size() > 0 && std::find(pids.begin(), pids.end(), pid) != pids.end()) { running = true; } } } catch (...) { } } else { } } else { } } else { throw "No socket or port specified!"; } if (!running) { for (std::vector<int>::const_iterator it = pids.begin(); it != pids.end(); ++it) { std::string output; std::string cmd = (boost::format("/bin/ps -p %1% | grep '%2%'") % *it % appNode.second.get<std::string>("app")).str(); CoreLib::System::Exec(cmd, output); if (output.find(appNode.second.get<std::string>("app")) != std::string::npos) { std::clog << std::endl << (boost::format(" * KILLING ==> %1%" "\n\t%2%") % *it % appNode.second.get<std::string>("app")).str() << std::endl; cmd = (boost::format("/bin/kill -SIGKILL %1%") % *it).str(); CoreLib::System::Exec(cmd); } } std::clog << std::endl << (boost::format(" * RESPAWNING WTHTTPD APP ==> %1%" "\n\tWorking Directory : %2%" "\n\tThreads : %3%" "\n\tServer Name : %4%" "\n\tDocument Root : %5%" "\n\tApplication Root : %6%" "\n\tError Root : %7%" "\n\tAccess Log : %8%" "\n\tCompression : %9%" "\n\tDeploy Path : %10%" "\n\tSession ID Prefix : %11%" "\n\tPid File : %12%" "\n\tConfig File : %13%" "\n\tMax Memory Request Size : %14%" "\n\tGDB : %15%" "\n\tHttp Address : %16%" "\n\tHttp Port : %17%" "\n\tHttps Address : %18%" "\n\tHttps Port : %19%" "\n\tSSL Certificate : %20%" "\n\tSSL Private Key : %21%" "\n\tSSL Temp Diffie Hellman : %22%" "\n\tSSL Enable v3 : %23%" "\n\tSSL Client Verification : %24%" "\n\tSSL Verify Depth : %25%" "\n\tSSL CA Certificates : %26%" "\n\tSSL Cipherlist : %27%") % appNode.second.get<std::string>("app") % appNode.second.get<std::string>("workdir") % appNode.second.get<std::string>("threads") % appNode.second.get<std::string>("servername") % appNode.second.get<std::string>("docroot") % appNode.second.get<std::string>("approot") % appNode.second.get<std::string>("errroot") % appNode.second.get<std::string>("accesslog") % appNode.second.get<std::string>("compression") % appNode.second.get<std::string>("deploy-path") % appNode.second.get<std::string>("session-id-prefix") % appNode.second.get<std::string>("pid-file") % appNode.second.get<std::string>("config") % appNode.second.get<std::string>("max-memory-request-size") % appNode.second.get<std::string>("gdb") % appNode.second.get<std::string>("http-address") % appNode.second.get<std::string>("http-port") % appNode.second.get<std::string>("https-address") % appNode.second.get<std::string>("https-port") % appNode.second.get<std::string>("ssl-certificate") % appNode.second.get<std::string>("ssl-private-key") % appNode.second.get<std::string>("ssl-tmp-dh") % appNode.second.get<std::string>("ssl-enable-v3") % appNode.second.get<std::string>("ssl-client-verification") % appNode.second.get<std::string>("ssl-verify-depth") % appNode.second.get<std::string>("ssl-ca-certificates") % appNode.second.get<std::string>("ssl-cipherlist") ).str() << std::endl << std::endl; std::string cmd((boost::format("cd %2% && %1%") % appNode.second.get<std::string>("app") % appNode.second.get<std::string>("workdir") ).str()); if (!appNode.second.get<std::string>("threads").empty() && appNode.second.get<std::string>("threads") != "-1") { cmd += (boost::format(" --threads %1%") % appNode.second.get<std::string>("threads")).str(); } if (!appNode.second.get<std::string>("servername").empty()) { cmd += (boost::format(" --servername %1%") % appNode.second.get<std::string>("servername")).str(); } if (!appNode.second.get<std::string>("docroot").empty()) { cmd += (boost::format(" --docroot \"%1%\"") % appNode.second.get<std::string>("docroot")).str(); } if (!appNode.second.get<std::string>("approot").empty()) { cmd += (boost::format(" --approot \"%1%\"") % appNode.second.get<std::string>("approot")).str(); } if (!appNode.second.get<std::string>("errroot").empty()) { cmd += (boost::format(" --errroot \"%1%\"") % appNode.second.get<std::string>("errroot")).str(); } if (!appNode.second.get<std::string>("accesslog").empty()) { cmd += (boost::format(" --accesslog \"%1%\"") % appNode.second.get<std::string>("accesslog")).str(); } if (!appNode.second.get<std::string>("compression").empty() && appNode.second.get<std::string>("compression") != "yes") { cmd += " --no-compression"; } if (!appNode.second.get<std::string>("deploy-path").empty()) { cmd += (boost::format(" --deploy-path %1%") % appNode.second.get<std::string>("deploy-path")).str(); } if (!appNode.second.get<std::string>("session-id-prefix").empty()) { cmd += (boost::format(" --session-id-prefix %1%") % appNode.second.get<std::string>("session-id-prefix")).str(); } if (!appNode.second.get<std::string>("pid-file").empty()) { cmd += (boost::format(" --pid-file \"%1%\"") % appNode.second.get<std::string>("pid-file")).str(); } if (!appNode.second.get<std::string>("config").empty()) { cmd += (boost::format(" --config \"%1%\"") % appNode.second.get<std::string>("config")).str(); } if (!appNode.second.get<std::string>("max-memory-request-size").empty()) { cmd += (boost::format(" --max-memory-request-size %1%") % appNode.second.get<std::string>("max-memory-request-size")).str(); } if (!appNode.second.get<std::string>("gdb").empty() && appNode.second.get<std::string>("gdb") != "yes") { cmd += " --gdb"; } if (!appNode.second.get<std::string>("http-address").empty()) { cmd += (boost::format(" --http-address %1%") % appNode.second.get<std::string>("http-address")).str(); } if (!appNode.second.get<std::string>("http-port").empty()) { cmd += (boost::format(" --http-port %1%") % appNode.second.get<std::string>("http-port")).str(); } if (!appNode.second.get<std::string>("https-address").empty()) { cmd += (boost::format(" --https-address %1%") % appNode.second.get<std::string>("https-address")).str(); } if (!appNode.second.get<std::string>("https-port").empty()) { cmd += (boost::format(" --https-port %1%") % appNode.second.get<std::string>("https-port")).str(); } if (!appNode.second.get<std::string>("ssl-certificate").empty()) { cmd += (boost::format(" --ssl-certificate \"%1%\"") % appNode.second.get<std::string>("ssl-certificate")).str(); } if (!appNode.second.get<std::string>("ssl-private-key").empty()) { cmd += (boost::format(" --ssl-private-key \"%1%\"") % appNode.second.get<std::string>("ssl-private-key")).str(); } if (!appNode.second.get<std::string>("ssl-tmp-dh").empty()) { cmd += (boost::format(" --ssl-tmp-dh \"%1%\"") % appNode.second.get<std::string>("ssl-tmp-dh")).str(); } if (!appNode.second.get<std::string>("ssl-enable-v3").empty() && appNode.second.get<std::string>("ssl-enable-v3") != "yes") { cmd += " --ssl-enable-v3"; } if (!appNode.second.get<std::string>("ssl-client-verification").empty()) { cmd += (boost::format(" --ssl-client-verification %1%") % appNode.second.get<std::string>("ssl-client-verification")).str(); } if (!appNode.second.get<std::string>("ssl-verify-depth").empty()) { cmd += (boost::format(" --ssl-verify-depth %1%") % appNode.second.get<std::string>("ssl-verify-depth")).str(); } if (!appNode.second.get<std::string>("ssl-ca-certificates").empty()) { cmd += (boost::format(" --ssl-ca-certificates \"%1%\"") % appNode.second.get<std::string>("ssl-ca-certificates")).str(); } if (!appNode.second.get<std::string>("ssl-cipherlist").empty()) { cmd += (boost::format(" --ssl-cipherlist %1%") % appNode.second.get<std::string>("ssl-cipherlist")).str(); } cmd += " &"; CoreLib::System::Exec(cmd); } } } } catch (const char * const &ex) { LOG_ERROR(ex); } catch (std::exception const &ex) { LOG_ERROR(ex.what()); } catch (...) { LOG_ERROR(UNKNOWN_ERROR); } }
21,324
5,754
// 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 "components/password_manager/core/browser/password_manager_constants.h" namespace password_manager { const base::FilePath::CharType kAffiliationDatabaseFileName[] = FILE_PATH_LITERAL("Affiliation Database"); const base::FilePath::CharType kLoginDataForProfileFileName[] = FILE_PATH_LITERAL("Login Data"); const base::FilePath::CharType kLoginDataForAccountFileName[] = FILE_PATH_LITERAL("Login Data For Account"); const char kPasswordManagerAccountDashboardURL[] = "https://passwords.google.com"; const char kPasswordManagerHelpCenteriOSURL[] = "https://support.google.com/chrome/answer/95606?ios=1"; const char kPasswordManagerHelpCenterSmartLock[] = "https://support.google.com/accounts?p=smart_lock_chrome"; } // namespace password_manager
949
292
// fts_search.cpp /** * Copyright (C) 2012 10gen Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "mongo/pch.h" #include "mongo/db/btreecursor.h" #include "mongo/db/fts/fts_index_format.h" #include "mongo/db/fts/fts_search.h" #include "mongo/db/kill_current_op.h" #include "mongo/db/pdfile.h" namespace mongo { namespace fts { /* * Constructor generates query and term dictionaries * @param ns, namespace * @param idxNum, index number * @param search, query string * @param language, language of the query * @param filter, filter object */ FTSSearch::FTSSearch( IndexDescriptor* descriptor, const FTSSpec& ftsSpec, const BSONObj& indexPrefix, const FTSQuery& query, const BSONObj& filter ) : _descriptor(descriptor), _ftsSpec(ftsSpec), _indexPrefix( indexPrefix ), _query( query ), _ftsMatcher(query, ftsSpec) { if ( !filter.isEmpty() ) _matcher.reset( new CoveredIndexMatcher( filter, _descriptor->keyPattern() ) ); _keysLookedAt = 0; _objectsLookedAt = 0; } bool FTSSearch::_ok( Record* record ) const { if ( !_query.hasNonTermPieces() ) return true; return _ftsMatcher.matchesNonTerm( BSONObj::make( record ) ); } /* * GO: sets the tree cursors on each term in terms, processes the terms by advancing * the terms cursors and storing the partial * results and lastly calculates the top results * @param results, the priority queue containing the top results * @param limit, number of results in the priority queue */ void FTSSearch::go(Results* results, unsigned limit ) { vector< shared_ptr<BtreeCursor> > cursors; for ( unsigned i = 0; i < _query.getTerms().size(); i++ ) { const string& term = _query.getTerms()[i]; BSONObj min = FTSIndexFormat::getIndexKey( MAX_WEIGHT, term, _indexPrefix ); BSONObj max = FTSIndexFormat::getIndexKey( 0, term, _indexPrefix ); shared_ptr<BtreeCursor> c( BtreeCursor::make( nsdetails(_descriptor->parentNS().c_str()), _descriptor->getOnDisk(), min, max, true, -1 ) ); cursors.push_back( c ); } while ( !inShutdown() ) { bool gotAny = false; for ( unsigned i = 0; i < cursors.size(); i++ ) { if ( cursors[i]->eof() ) continue; gotAny = true; _process( cursors[i].get() ); cursors[i]->advance(); } if ( !gotAny ) break; RARELY killCurrentOp.checkForInterrupt(); } // priority queue using a compare that grabs the lowest of two ScoredLocations by score. for ( Scores::iterator i = _scores.begin(); i != _scores.end(); ++i ) { if ( i->second < 0 ) continue; // priority queue if ( results->size() < limit ) { // case a: queue unfilled if ( !_ok( i->first ) ) continue; results->push( ScoredLocation( i->first, i->second ) ); } else if ( i->second > results->top().score ) { // case b: queue filled if ( !_ok( i->first ) ) continue; results->pop(); results->push( ScoredLocation( i->first, i->second ) ); } else { // else do nothing (case c) } } } /* * Takes a cursor and updates the partial score for said cursor in _scores map * @param cursor, btree cursor pointing to the current document to be scored */ void FTSSearch::_process( BtreeCursor* cursor ) { _keysLookedAt++; BSONObj key = cursor->currKey(); BSONObjIterator i( key ); for ( unsigned j = 0; j < _ftsSpec.numExtraBefore(); j++) i.next(); i.next(); // move past indexToken BSONElement scoreElement = i.next(); double score = scoreElement.number(); double& cur = _scores[(cursor->currLoc()).rec()]; if ( cur < 0 ) { // already been rejected return; } if ( cur == 0 && _matcher.get() ) { // we haven't seen this before and we have a matcher MatchDetails d; if ( !_matcher->matchesCurrent( cursor, &d ) ) { cur = -1; } if ( d.hasLoadedRecord() ) _objectsLookedAt++; if ( cur == -1 ) return; } if ( cur ) cur += score * (1 + 1 / score); else cur += score; } } }
5,969
1,641
// Copyright 2020 The Fuchsia Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "blobfs/fsck.h" #include <blobfs/mkfs.h> #include <block-client/cpp/fake-device.h> #include <gtest/gtest.h> #include "blobfs.h" #include "utils.h" namespace blobfs { namespace { using block_client::FakeBlockDevice; constexpr uint32_t kBlockSize = 512; constexpr uint32_t kNumBlocks = 400 * kBlobfsBlockSize / kBlockSize; TEST(FsckTest, TestEmpty) { auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize); ASSERT_TRUE(device); ASSERT_EQ(FormatFilesystem(device.get()), ZX_OK); MountOptions options; ASSERT_EQ(Fsck(std::move(device), &options), ZX_OK); } TEST(FsckTest, TestUnmountable) { auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize); ASSERT_TRUE(device); MountOptions options; ASSERT_EQ(Fsck(std::move(device), &options), ZX_ERR_INVALID_ARGS); } TEST(FsckTest, TestCorrupted) { auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize); ASSERT_TRUE(device); ASSERT_EQ(FormatFilesystem(device.get()), ZX_OK); char block[kBlobfsBlockSize]; DeviceBlockRead(device.get(), block, sizeof(block), kSuperblockOffset); Superblock* info = reinterpret_cast<Superblock*>(block); info->alloc_inode_count++; DeviceBlockWrite(device.get(), block, sizeof(block), kSuperblockOffset); MountOptions options; ASSERT_EQ(Fsck(std::move(device), &options), ZX_ERR_IO_OVERRUN); } TEST(FsckTest, TestOverflow) { auto device = std::make_unique<FakeBlockDevice>(kNumBlocks, kBlockSize); ASSERT_TRUE(device); ASSERT_EQ(FormatFilesystem(device.get()), ZX_OK); char block[kBlobfsBlockSize]; DeviceBlockRead(device.get(), block, sizeof(block), kSuperblockOffset); Superblock* info = reinterpret_cast<Superblock*>(block); info->inode_count = std::numeric_limits<uint64_t>::max(); DeviceBlockWrite(device.get(), block, sizeof(block), kSuperblockOffset); MountOptions options; ASSERT_EQ(Fsck(std::move(device), &options), ZX_ERR_OUT_OF_RANGE); } } // namespace } // namespace blobfs
2,156
813
#include "util/util.h" #include <ctime> #include <fstream> #include <iostream> #include <mutex> namespace pd2hook { namespace Logging { namespace { std::string GetDateString() { std::time_t currentTime = time(0); std::tm now; localtime_s(&now, &currentTime); char datestring[100]; std::strftime(datestring, sizeof(datestring), "%Y_%m_%d", &now); return datestring; } std::ostream& LogTime(std::ostream& os) { std::time_t currentTime = time(0); std::tm now; localtime_s(&now, &currentTime); char datestring[100]; std::strftime(datestring, sizeof(datestring), "%I:%M:%S %p", &now); os << datestring << ' '; return os; } std::ostream& operator<<(std::ostream& os, LogType msgType) { switch (msgType){ case LogType::LOGGING_FUNC: break; case LogType::LOGGING_LOG: os << "Log: "; break; case LogType::LOGGING_LUA: os << "Lua: "; break; case LogType::LOGGING_WARN: os << "WARNING: "; break; case LogType::LOGGING_ERROR: os << "FATAL ERROR: "; break; default: os << "Message: "; break; } return os; } std::ostream& quick_endl(std::ostream& os) { os << '\n'; return os; } typedef decltype(&quick_endl) LineTerminator_t; std::mutex& GetLoggerMutex() { static std::mutex loggerMutex; return loggerMutex; } class LoggerImpl : public Logger { public: LoggerImpl(std::string&& file); void setForceFlush(bool forceFlush); bool isOpen() const { return mIsOpen; } void openFile(std::string&& file); void close(); void log(const Message_t& msg); private: bool mIsOpen = false; LineTerminator_t mEndl = quick_endl; std::string mFilename; std::ofstream mOut; }; void LoggerImpl::setForceFlush(bool forceFlush) { std::ostream& (*forceFlusher)(std::ostream&) = &std::endl; mEndl = forceFlush ? forceFlusher : quick_endl; } LoggerImpl::LoggerImpl(std::string&& file) { openFile(std::forward<std::string>(file)); } void LoggerImpl::openFile(std::string&& file) { if (mFilename == file) { return; } std::lock_guard<std::mutex> lock(GetLoggerMutex()); mOut.close(); mOut = std::ofstream(file.c_str(), std::ios::app); mFilename = std::move(file); mIsOpen = !!mOut; } void LoggerImpl::close() { std::lock_guard<std::mutex> lock(GetLoggerMutex()); if (!mIsOpen) { return; } mOut.close(); mFilename.clear(); mIsOpen = false; } void LoggerImpl::log(const Message_t& msg) { std::lock_guard<std::mutex> lock(GetLoggerMutex()); if (!mIsOpen) { return; } mOut << msg << mEndl; std::cout << msg << mEndl; } } Logger& Logger::Instance() { static LoggerImpl logger("mods/logs/" + GetDateString() + "_log.txt"); return logger; } void Logger::Close() { static_cast<LoggerImpl&>(Instance()).close(); } void Logger::setForceFlush(bool forceFlush) { static_cast<LoggerImpl *>(this)->setForceFlush(forceFlush); } void Logger::log(const Message_t& msg) { static_cast<LoggerImpl *>(this)->log(msg); } LogWriter::LogWriter(LogType msgType) { *this << LogTime << msgType << ' '; } LogWriter::LogWriter(const char *file, int line, LogType msgType) { if (line && line > 0) { *this << LogTime << msgType << " (" << file << ':' << line << ") "; } else if (file) { *this << LogTime << msgType << " (" << file << ") "; } else { *this << LogTime << msgType; } } } }
3,252
1,338
/* * Sudoku.cpp * */ #include "Sudoku.h" #include <vector> #include <string.h> #include <climits> /** Inicia um Sudoku vazio. */ Sudoku::Sudoku() { this->initialize(); this->n_solucoes = 0; this->countFilled = 0; } /** * Inicia um Sudoku com um conte�do inicial. * Lan�a excep��o IllegalArgumentException se os valores * estiverem fora da gama de 1 a 9 ou se existirem n�meros repetidos * por linha, coluna ou bloc 3x3. * * @param nums matriz com os valores iniciais (0 significa por preencher) */ Sudoku::Sudoku(int nums[9][9]) { this->initialize(); for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { if (nums[i][j] != 0) { int n = nums[i][j]; numbers[i][j] = n; lineHasNumber[i][n] = true; columnHasNumber[j][n] = true; block3x3HasNumber[i / 3][j / 3][n] = true; countFilled++; } } } this->n_solucoes = 0; } void Sudoku::initialize() { for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { for (int n = 0; n < 10; n++) { numbers[i][j] = 0; lineHasNumber[i][n] = false; columnHasNumber[j][n] = false; block3x3HasNumber[i / 3][j / 3][n] = false; } } } this->countFilled = 0; } /** * Obtem o conte�do actual (s� para leitura!). */ int** Sudoku::getNumbers() { int** ret = new int*[9]; for (int i = 0; i < 9; i++) { ret[i] = new int[9]; for (int a = 0; a < 9; a++) ret[i][a] = numbers[i][a]; } return ret; } /** * Verifica se o Sudoku j� est� completamente resolvido */ bool Sudoku::isComplete() { return countFilled == 9 * 9; } /** * Resolve o Sudoku. * Retorna indica��o de sucesso ou insucesso (sudoku imposs�vel). */ bool Sudoku::solve() { //this->print(); //cout << endl; if(countFilled == 81) { this->print(); cout << endl; n_solucoes++; return true; } int x ,y; int n_accepted = INT_MAX; vector<bool> num_accepted; for (int i = 0; i < 9; i++) { for (int j = 0; j < 9; j++) { int tmp_n_accepted = 9; vector<bool> acceptable_num(10,true); if(this->numbers[i][j] != 0) continue; for(int k = 0; k < 10; k++) { acceptable_num[k] = acceptable_num[k] & !this->columnHasNumber[j][k]; acceptable_num[k] = acceptable_num[k] & !this->lineHasNumber[i][k]; acceptable_num[k] = acceptable_num[k] & !this->block3x3HasNumber[i/3][j/3][k]; if(!acceptable_num[k]) tmp_n_accepted--; } //cout << "x: " << i << " y: " << j << endl; //cout << tmp_n_accepted << ' ' << n_accepted << endl; if(tmp_n_accepted == 0) return false; if(tmp_n_accepted <= n_accepted) { n_accepted = tmp_n_accepted; num_accepted.clear(); num_accepted.insert(num_accepted.begin(),acceptable_num.begin(), acceptable_num.end()); x = i; y = j; } } } if(n_accepted == 1) { int a = 1; while(!num_accepted[a]) a++; //cout << "Added: " << a << " in x: " << x << " y: " << y << endl << endl; this->numbers[x][y] = a; this->countFilled++; lineHasNumber[x][a] = true; columnHasNumber[y][a] = true; block3x3HasNumber[x / 3][y / 3][a] = true; if(this->solve()) { return true; } else { this->numbers[x][y] = 0; this->countFilled--; lineHasNumber[x][a] = false; columnHasNumber[y][a] = false; block3x3HasNumber[x / 3][y / 3][a] = false; return false; } } else { //cout << x << "\t" << y << "\n"; std::vector<int> possible_sol; for(int i = 1; i < 10; i++) if(num_accepted[i]) { //cout << i << " acceptated\n"; possible_sol.push_back(i); } for(size_t j = 0; j < possible_sol.size(); j++) { //cout << "Added: " << possible_sol[j] << " in x: " << x << " y: " << y << endl << endl; this->numbers[x][y] = possible_sol[j]; this->countFilled++; lineHasNumber[x][possible_sol[j]] = true; columnHasNumber[y][possible_sol[j]] = true; block3x3HasNumber[x / 3][y / 3][possible_sol[j]] = true; if(this->solve()) { return true; } else { this->numbers[x][y] = 0; this->countFilled--; lineHasNumber[x][possible_sol[j]] = false; columnHasNumber[y][possible_sol[j]] = false; block3x3HasNumber[x / 3][y / 3][possible_sol[j]] = false; } } } return false; } /** * Imprime o Sudoku. */ void Sudoku::print() { for (int i = 0; i < 9; i++) { for (int a = 0; a < 9; a++) cout << this->numbers[i][a] << " "; cout << endl; } }
4,364
2,171
#include <assert.h> #include "stubs.h" /******************************************************************************* * Names for some of our resources. */ // Names for clist slots static constexpr uintptr_t // Where reply keys arrive. k0 = 0, // We move reply keys here immediately so they don't get stomped // by subsequent operations. k_saved_reply = 4, // We accept one flush request and keep its reply key pending // here across concurrent operations on other ports. k_flush_reply = 5, // Register access grant. k_reg = 14, // System access. k_sys = 15; // Names for our ports. static constexpr uintptr_t p_mon = 0, p_tx = 1, p_irq = 2, p_rx = 3; /******************************************************************************* * Constants describing our protocols and others'. Some of this ought to move * into header files. */ static constexpr uintptr_t // mon protocol t_mon_heartbeat = 0, // mem protocol t_mem_write32 = 0, t_mem_read32 = 1, // uart.tx protocol t_tx_send1 = 0, t_tx_flush = 1, // uart.rx protocol t_rx_recv1 = 0; /******************************************************************************* * Declarations of implementation factors. */ // Functions used in received-message port dispatching. static void handle_mon(Message const &); static void handle_tx(Message const &); static void handle_irq(Message const &); static void handle_rx(Message const &); // Utility function for using k_saved_reply with no keys. static void reply(uintptr_t md0 = 0, uintptr_t md1 = 0, uintptr_t md2 = 0, uintptr_t md3 = 0) { send(false, k_saved_reply, Message{{md0, md1, md2, md3}}); } /******************************************************************************* * Main loop */ int main() { // We mask the receive port until we get evidence from the // hardware that data is available. // TODO: if we're restarted, the hardware may already hold // data -- we should check. mask(p_rx); while (true) { ReceivedMessage rm; auto r = open_receive(true, &rm); if (r != SysResult::success) continue; move_cap(k0, k_saved_reply); // TODO: clear transients switch (rm.port) { case p_mon: handle_mon(rm.m); break; case p_tx: handle_tx(rm.m); break; case p_irq: handle_irq(rm.m); break; case p_rx: handle_rx(rm.m); break; default: // This would indicate that the kernel has handed us // a message from a port we don't know about. This // is either a bug in the kernel or in this dispatch // code. assert(false); } } } /******************************************************************************* * Mem protocol wrappers for UART register access. * * These all use the register access grant kept in k_reg. Because we assume * a simple memory grant, or something compatible with one, we handle error * returns in a heavy-handed manner. */ static void write_cr1(uint32_t value) { auto r = send(true, k_reg, Message{t_mem_write32, 0xC, value}); assert(r == SysResult::success); } static void write_dr(uint8_t value) { auto r = send(true, k_reg, Message{t_mem_write32, 4, value}); assert(r == SysResult::success); } static uint32_t read_dr() { ReceivedMessage response; auto r = call(true, k_reg, Message{t_mem_read32, 4}, &response); assert(r == SysResult::success); return uint32_t(response.m.data[0]); } static uint32_t read_cr1() { ReceivedMessage response; auto r = call(true, k_reg, Message{t_mem_read32, 0xC}, &response); assert(r == SysResult::success); return uint32_t(response.m.data[0]); } static uint32_t read_sr() { ReceivedMessage response; auto r = call(true, k_reg, Message{t_mem_read32, 0}, &response); assert(r == SysResult::success); return uint32_t(response.m.data[0]); } static void enable_irq_on_txe() { write_cr1(read_cr1() | (1 << 7)); } static void enable_irq_on_rxne() { write_cr1(read_cr1() | (1 << 5)); } static void enable_irq_on_tc() { write_cr1(read_cr1() | (1 << 6)); } /******************************************************************************* * Mon server implementation */ static void handle_mon(Message const & req) { switch (req.data[0]) { case t_mon_heartbeat: reply(req.data[1], req.data[2], req.data[3]); break; } } /******************************************************************************* * UART.TX server implementation */ static bool flushing; static void do_send1(Message const & req) { write_dr(uint8_t(req.data[1])); mask(p_tx); enable_irq_on_txe(); reply(); } static void do_flush(Message const &) { enable_irq_on_tc(); mask(p_tx); move_cap(k_saved_reply, k_flush_reply); flushing = true; // Do not reply yet. } static void handle_tx(Message const & req) { switch (req.data[0]) { case t_tx_send1: do_send1(req); break; case t_tx_flush: do_flush(req); break; } } /******************************************************************************* * IRQ server implementation */ static void handle_irq(Message const &) { auto sr = read_sr(); auto cr1 = read_cr1(); if ((sr & (1 << 7)) && (cr1 & (1 << 7))) { // TXE set and interrupt enabled. // Disable interrupt in preparation for allowing another send. cr1 &= ~(1 << 7); write_cr1(cr1); if (!flushing) unmask(p_tx); } if ((sr & (1 << 5)) && (cr1 & (1 << 5))) { // RxNE set and interrupt enabled. cr1 &= ~(1 << 5); write_cr1(cr1); unmask(p_rx); } if ((sr & (1 << 6)) && (cr1 & (1 << 6))) { // TC set and interrupt enabled -- a flush has completed. cr1 &= ~(1 << 6); write_cr1(cr1); assert(flushing); send(false, k_flush_reply, Message{{0, 0, 0, 0}}); flushing = false; unmask(p_tx); } reply(1); } /******************************************************************************* * UART.RX server implementation */ static void do_recv1(Message const & req) { auto b = read_dr(); mask(p_rx); enable_irq_on_rxne(); reply(b); } static void handle_rx(Message const & req) { switch (req.data[0]) { case t_rx_recv1: do_recv1(req); break; } }
6,224
2,167
#ifndef _TYPE_HPP_ #define _TYPE_HPP_ #include "ICompilerEngine.hpp" class Type { std::string name; llvm::Type* type; public: const std::string& Name() { return name; } const llvm::Type* Type() { return type; } std::size_t SizeBytes() const { // figure out the type of type of type. if its primitive just return the size, if its a struct type // then it will have to be interated over unsigned std::size_t sizeof_type = 0; if(type->isFloatTy()) sizeof_type = 4; // 32 bits else if(type->isDoubleTy()) // 64 bits sizeof_type = 8; else if(type->isIntegerTy()) { // variable width that type can report sizeof_type = dynamic_cast<llvm::IntegerType>(type)->getBitWidth(); } else if(type->isStructTy()) { // iterate over all elements and sum them } } }; #endif // _TYPE_HPP_
1,001
305
# Makefile to build booz using Turbo C++ 1.0 and NDMAKE 4.31 OOZOBJS = booz.obj addbfcrc.obj lzd.obj oozext.obj portable.obj \ io.obj huf.obj decode.obj maketbl.obj CC = tcc CFLAGS = -c -O # CFLAGS = -c -g .SUFFIXES : .exe .obj .c .c.obj : $(CC) $(CFLAGS) $*.c booz : booz.exe booz.exe : $(OOZOBJS) $(CC) -ebooz $(OOZOBJS) install : booz.exe copy booz.exe \bin\booz.exe clean : -del *.obj # DEPENDENCIES follow booz.obj: booz.h zoo.h decode.obj: ar.h booz.h lzh.h zoo.h huf.obj: ar.h booz.h lzh.h zoo.h io.obj: ar.h booz.h lzh.h zoo.h lzd.obj: booz.h maketbl.obj: ar.h booz.h lzh.h zoo.h oozext.obj: booz.h zoo.h portable.obj: booz.h zoo.h
690
382
//have to include calculus.hpp #pragma once #include"difference_equation.hpp" #ifndef NAGA_LIBRARIES_PID_HPP__ #define NAGA_LIBRARIES_PID_HPP__ class I_PID{ public: I_PID() {} virtual ~I_PID() = 0; }; class PosType_PID : private I_PID{ difference_equation difference; const float kp, ki, kd; public: PosType_PID(float _period = 1.0f, float _kp = 0, float _ki = 0, float _kd = 0):kp(_kp), ki(_ki), kd(_kd){} float operator()(); }; #endif //NAGA_LIBRARIES_PID_HPP__
493
218
#include <iostream> #include <string> #include <vector> using std::cout; using std::cin; using std::endl; using std::string; using std::vector; int main() { vector<int> v1; // size:0, no values. vector<int> v2(10); // size:10, value:0 vector<int> v3(10, 42); // size:10, value:42 vector<int> v4{ 10 }; // size:1, value:10 vector<int> v5{ 10, 42 }; // size:2, value:10, 42 vector<string> v6{ 10 }; // size:10, value:"" vector<string> v7{ 10, "hi" }; // size:10, value:"hi" cout << "v1 has " << v1.size() << " elements: " << endl; if (v1.size() > 0) { for (auto a : v1) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v2 has " << v2.size() << " elements: " << endl; if (v2.size() > 0) { for (auto a : v2) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v3 has " << v3.size() << " elements: " << endl; if (v3.size() > 0) { for (auto a : v3) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v4 has " << v4.size() << " elements: " << endl; if (v4.size() > 0) { for (auto a : v4) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v5 has " << v5.size() << " elements: " << endl; if (v5.size() > 0) { for (auto a : v5) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v6 has " << v6.size() << " elements: " << endl; if (v6.size() > 0) { for (auto a : v6) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } cout << "v7 has " << v7.size() << " elements: " << endl; if (v7.size() > 0) { for (auto a : v7) cout << a << " "; cout << endl; } else { cout << "N/A" << endl; } return 0; }
1,996
799
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "elastos/droid/bluetooth/BluetoothGattServer.h" #include "elastos/droid/bluetooth/CBluetoothAdapter.h" #include "elastos/droid/os/CParcelUuid.h" #include "elastos/core/AutoLock.h" #include <elastos/utility/logging/Logger.h> using Elastos::Droid::Os::CParcelUuid; using Elastos::Droid::Os::EIID_IBinder; using Elastos::Core::AutoLock; using Elastos::Utility::CArrayList; using Elastos::Utility::IUUIDHelper; using Elastos::Utility::CUUIDHelper; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Bluetooth { //===================================================================== // BluetoothGattServer::BluetoothGattServerCallbackStub //===================================================================== CAR_INTERFACE_IMPL_2(BluetoothGattServer::BluetoothGattServerCallbackStub, Object, IIBluetoothGattServerCallback, IBinder); BluetoothGattServer::BluetoothGattServerCallbackStub::BluetoothGattServerCallbackStub() { } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::constructor( /* [in] */ IBluetoothGattServer* owner) { mOwner = (BluetoothGattServer*)owner; return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnServerRegistered( /* [in] */ Int32 status, /* [in] */ Int32 serverIf) { if (DBG) Logger::D(TAG, "onServerRegistered() - status=%d, serverIf=%d", status, serverIf); { AutoLock lock(mOwner->mServerIfLock); if (mOwner->mCallback != NULL) { mOwner->mServerIf = serverIf; mOwner->mServerIfLock->Notify(); } else { // registration timeout Logger::E(TAG, "onServerRegistered: mCallback is NULL"); } } return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnScanResult( /* [in] */ const String& address, /* [in] */ Int32 rssi, /* [in] */ ArrayOf<Byte>* advData) { VALIDATE_NOT_NULL(advData); if (VDBG) Logger::D(TAG, "onScanResult() - Device=%s, RSSI=%d", address.string(), rssi); // // no op return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnServerConnectionState( /* [in] */ Int32 status, /* [in] */ Int32 serverIf, /* [in] */ Boolean connected, /* [in] */ const String& address) { if (DBG) Logger::D(TAG, "onServerConnectionState() - status=%d, serverIf=%d, device=%s", status, serverIf, address.string()); //try { AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); mOwner->mCallback->OnConnectionStateChange(device, status, connected ? IBluetoothProfile::STATE_CONNECTED : IBluetoothProfile::STATE_DISCONNECTED); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnServiceAdded( /* [in] */ Int32 status, /* [in] */ Int32 srvcType, /* [in] */ Int32 srvcInstId, /* [in] */ IParcelUuid* srvcId) { VALIDATE_NOT_NULL(srvcId); AutoPtr<IUUID> srvcUuid; srvcId->GetUuid((IUUID**)&srvcUuid); if (DBG) Logger::D(TAG, "onServiceAdded() - service=");// + srvcUuid + "status=" + status); AutoPtr<IBluetoothGattService> service; mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service); if (service == NULL) return NOERROR; //try { mOwner->mCallback->OnServiceAdded(status, service); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnCharacteristicReadRequest( /* [in] */ const String& address, /* [in] */ Int32 transId, /* [in] */ Int32 offset, /* [in] */ Boolean isLong, /* [in] */ Int32 srvcType, /* [in] */ Int32 srvcInstId, /* [in] */ IParcelUuid* srvcId, /* [in] */ Int32 charInstId, /* [in] */ IParcelUuid* charId) { AutoPtr<IUUID> srvcUuid; srvcId->GetUuid((IUUID**)&srvcUuid); AutoPtr<IUUID> charUuid; charId->GetUuid((IUUID**)&charUuid); if (VDBG) Logger::D(TAG, "onCharacteristicReadRequest() - "); //+ "service=" + srvcUuid + ", characteristic=" + charUuid); AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); AutoPtr<IBluetoothGattService> service; mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service); if (service == NULL) return NOERROR; AutoPtr<IBluetoothGattCharacteristic> characteristic; service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic); if (characteristic == NULL) return NOERROR; //try { mOwner->mCallback->OnCharacteristicReadRequest(device, transId, offset, characteristic); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnDescriptorReadRequest( /* [in] */ const String& address, /* [in] */ Int32 transId, /* [in] */ Int32 offset, /* [in] */ Boolean isLong, /* [in] */ Int32 srvcType, /* [in] */ Int32 srvcInstId, /* [in] */ IParcelUuid* srvcId, /* [in] */ Int32 charInstId, /* [in] */ IParcelUuid* charId, /* [in] */ IParcelUuid* descrId) { AutoPtr<IUUID> srvcUuid; srvcId->GetUuid((IUUID**)&srvcUuid); AutoPtr<IUUID> charUuid; charId->GetUuid((IUUID**)&charUuid); AutoPtr<IUUID> descrUuid; descrId->GetUuid((IUUID**)&descrUuid); if (VDBG) Logger::D(TAG, "onCharacteristicReadRequest() - "); //+ "service=" + srvcUuid + ", characteristic=" + charUuid //+ "descriptor=" + descrUuid); AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); AutoPtr<IBluetoothGattService> service; mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service); if (service == NULL) return NOERROR; AutoPtr<IBluetoothGattCharacteristic> characteristic; service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic); if (characteristic == NULL) return NOERROR; AutoPtr<IBluetoothGattDescriptor> descriptor; characteristic->GetDescriptor(descrUuid, (IBluetoothGattDescriptor**)&descriptor); if (descriptor == NULL) return NOERROR; //try { mOwner->mCallback->OnDescriptorReadRequest(device, transId, offset, descriptor); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnCharacteristicWriteRequest( /* [in] */ const String& address, /* [in] */ Int32 transId, /* [in] */ Int32 offset, /* [in] */ Int32 length, /* [in] */ Boolean isPrep, /* [in] */ Boolean needRsp, /* [in] */ Int32 srvcType, /* [in] */ Int32 srvcInstId, /* [in] */ IParcelUuid* srvcId, /* [in] */ Int32 charInstId, /* [in] */ IParcelUuid* charId, /* [in] */ ArrayOf<Byte>* value) { AutoPtr<IUUID> srvcUuid; srvcId->GetUuid((IUUID**)&srvcUuid); AutoPtr<IUUID> charUuid; charId->GetUuid((IUUID**)&charUuid); if (VDBG) Logger::D(TAG, "onCharacteristicWriteRequest() - "); //+ "service=" + srvcUuid + ", characteristic=" + charUuid); AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); AutoPtr<IBluetoothGattService> service; mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service); if (service == NULL) return NOERROR; AutoPtr<IBluetoothGattCharacteristic> characteristic; service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic); if (characteristic == NULL) return NOERROR; //try { mOwner->mCallback->OnCharacteristicWriteRequest(device, transId, characteristic, isPrep, needRsp, offset, value); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnDescriptorWriteRequest( /* [in] */ const String& address, /* [in] */ Int32 transId, /* [in] */ Int32 offset, /* [in] */ Int32 length, /* [in] */ Boolean isPrep, /* [in] */ Boolean needRsp, /* [in] */ Int32 srvcType, /* [in] */ Int32 srvcInstId, /* [in] */ IParcelUuid* srvcId, /* [in] */ Int32 charInstId, /* [in] */ IParcelUuid* charId, /* [in] */ IParcelUuid* descrId, /* [in] */ ArrayOf<Byte>* value) { AutoPtr<IUUID> srvcUuid; srvcId->GetUuid((IUUID**)&srvcUuid); AutoPtr<IUUID> charUuid; charId->GetUuid((IUUID**)&charUuid); AutoPtr<IUUID> descrUuid; descrId->GetUuid((IUUID**)&descrUuid); if (VDBG) Logger::D(TAG, "onDescriptorWriteRequest() - "); //+ "service=" + srvcUuid + ", characteristic=" + charUuid //+ "descriptor=" + descrUuid); AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); AutoPtr<IBluetoothGattService> service; mOwner->GetService(srvcUuid, srvcInstId, srvcType, (IBluetoothGattService**)&service); if (service == NULL) return NOERROR; AutoPtr<IBluetoothGattCharacteristic> characteristic; service->GetCharacteristic(charUuid, (IBluetoothGattCharacteristic**)&characteristic); if (characteristic == NULL) return NOERROR; AutoPtr<IBluetoothGattDescriptor> descriptor; characteristic->GetDescriptor(descrUuid, (IBluetoothGattDescriptor**)&descriptor); if (descriptor == NULL) return NOERROR; //try { mOwner->mCallback->OnDescriptorWriteRequest(device, transId, descriptor, isPrep, needRsp, offset, value); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnExecuteWrite( /* [in] */ const String& address, /* [in] */ Int32 transId, /* [in] */ Boolean execWrite) { if (DBG) Logger::D(TAG, "onExecuteWrite() - "); //+ "device=" + address + ", transId=" + transId //+ "execWrite=" + execWrite); AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); if (device == NULL) return NOERROR; //try { mOwner->mCallback->OnExecuteWrite(device, transId, execWrite); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception in callback", ex); //} return NOERROR; } ECode BluetoothGattServer::BluetoothGattServerCallbackStub::OnNotificationSent( /* [in] */ const String& address, /* [in] */ Int32 status) { if (VDBG) Logger::D(TAG, "onNotificationSent() - "); //+ "device=" + address + ", status=" + status); AutoPtr<IBluetoothDevice> device; mOwner->mAdapter->GetRemoteDevice(address, (IBluetoothDevice**)&device); if (device == NULL) return NOERROR; //try { mOwner->mCallback->OnNotificationSent(device, status); //} catch (Exception ex) { // Log.w(TAG, "Unhandled exception: " + ex); //} return NOERROR; } //===================================================================== // BluetoothGattServer //===================================================================== const String BluetoothGattServer::TAG("BluetoothGattServer"); const Boolean BluetoothGattServer::DBG = TRUE; const Boolean BluetoothGattServer::VDBG = FALSE; const Int32 BluetoothGattServer::CALLBACK_REG_TIMEOUT; CAR_INTERFACE_IMPL_2(BluetoothGattServer, Object, IBluetoothGattServer, IBluetoothProfile); BluetoothGattServer::BluetoothGattServer() { } BluetoothGattServer::BluetoothGattServer( /* [in] */ IContext* context, /* [in] */ IIBluetoothGatt* iGatt, /* [in] */ Int32 transport) { mContext = context; mService = iGatt; //mAdapter = BluetoothAdapter.getDefaultAdapter(); mAdapter = CBluetoothAdapter::GetDefaultAdapter(); mCallback = NULL; mServerIf = 0; mTransport = transport; //mServices = new ArrayList<BluetoothGattService>(); CArrayList::New((IList**)&mServices); } ECode BluetoothGattServer::Close() { if (DBG) Logger::D(TAG, "close()"); UnregisterCallback(); return NOERROR; } ECode BluetoothGattServer::RegisterCallback( /* [in] */ IBluetoothGattServerCallback* callback, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); if (DBG) Logger::D(TAG, "registerCallback()"); if (mService == NULL) { Logger::E(TAG, "GATT service not available"); *result = FALSE; return NOERROR; } AutoPtr<IUUIDHelper> uuidHelper; CUUIDHelper::AcquireSingleton((IUUIDHelper**)&uuidHelper); AutoPtr<IUUID> uuid; uuidHelper->RandomUUID((IUUID**)&uuid); if (DBG) Logger::D(TAG, "registerCallback() - UUID=");// + uuid); { AutoLock lock(mServerIfLock); if (mCallback != NULL) { Logger::E(TAG, "App can register callback only once"); *result = FALSE; return NOERROR; } mCallback = callback; //try { AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); ECode ec = mService->RegisterServer(parcelUuid, mBluetoothGattServerCallback); //} catch (RemoteException e) { if (FAILED(ec)) { //Logger::E(TAG,"",e); mCallback = NULL; *result = FALSE; return NOERROR; } //} //try { ec = mServerIfLock->Wait(CALLBACK_REG_TIMEOUT); //} catch (InterruptedException e) { // Logger::E(TAG, "" + e); if (FAILED(ec)) { mCallback = NULL; } //} if (mServerIf == 0) { mCallback = NULL; *result = FALSE; return NOERROR; } else { *result = TRUE; return NOERROR; } } return NOERROR; } ECode BluetoothGattServer::GetService( /* [in] */ IUUID* uuid, /* [in] */ Int32 instanceId, /* [in] */ Int32 type, /* [out] */ IBluetoothGattService** result) { VALIDATE_NOT_NULL(result); Int32 size; mServices->GetSize(&size); for(Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> obj; mServices->Get(i, (IInterface**)&obj); IBluetoothGattService* svc = IBluetoothGattService::Probe(obj); Int32 sType; Int32 sInstanceId; AutoPtr<IUUID> sUuid; svc->GetType(&sType); svc->GetInstanceId(&sInstanceId); svc->GetUuid((IUUID**)&sUuid); Boolean eq = FALSE; if (sType == type && sInstanceId == instanceId && (sUuid->Equals(uuid, &eq), eq)) { *result = svc; REFCOUNT_ADD(*result); return NOERROR; } } *result = NULL; return NOERROR; } ECode BluetoothGattServer::Connect( /* [in] */ IBluetoothDevice* device, /* [in] */ Boolean autoConnect, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; if (DBG) Logger::D(TAG, "connect() - device: ");// + device.getAddress() + ", auto: " + autoConnect); if (mService == NULL || mServerIf == 0) return NOERROR; String address; device->GetAddress(&address); //try { ECode ec = mService->ServerConnect(mServerIf, address, autoConnect ? FALSE : TRUE, mTransport); // autoConnect is inverse of "isDirect" //} catch (RemoteException e) { // Logger::E(TAG,"",e); if (FAILED(ec)) { return NOERROR; } //} *result = TRUE; return NOERROR; } ECode BluetoothGattServer::CancelConnection( /* [in] */ IBluetoothDevice* device) { if (DBG) Logger::D(TAG, "cancelConnection() - device: ");// + device.getAddress()); if (mService == NULL || mServerIf == 0) return NOERROR; String address; device->GetAddress(&address); //try { mService->ServerDisconnect(mServerIf, address); //} catch (RemoteException e) { // Logger::E(TAG,"",e); //} return NOERROR; } ECode BluetoothGattServer::SendResponse( /* [in] */ IBluetoothDevice* device, /* [in] */ Int32 requestId, /* [in] */ Int32 status, /* [in] */ Int32 offset, /* [in] */ ArrayOf<Byte>* value, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; if (VDBG) Logger::D(TAG, "sendResponse() - device: ");// + device.getAddress()); if (mService == NULL || mServerIf == 0) return NOERROR; String address; device->GetAddress(&address); //try { ECode ec = mService->SendResponse(mServerIf, address, requestId, status, offset, value); //} catch (RemoteException e) { // Logger::E(TAG,"",e); if (FAILED(ec)) { return FALSE; } //} *result = TRUE; return NOERROR; } ECode BluetoothGattServer::NotifyCharacteristicChanged( /* [in] */ IBluetoothDevice* device, /* [in] */ IBluetoothGattCharacteristic* characteristic, /* [in] */ Boolean confirm, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; if (VDBG) Logger::D(TAG, "notifyCharacteristicChanged() - device: ");// + device.getAddress()); if (mService == NULL || mServerIf == 0) return NOERROR; AutoPtr<IBluetoothGattService> service; characteristic->GetService((IBluetoothGattService**)&service); if (service == NULL) return NOERROR; AutoPtr<ArrayOf<Byte> > value; characteristic->GetValue((ArrayOf<Byte>**)&value); if (value == NULL) { //throw new IllegalArgumentException("Chracteristic value is empty. Use " // + "BluetoothGattCharacteristic#setvalue to update"); Logger::E(TAG, "Chracteristic value is empty. Use BluetoothGattCharacteristic#setvalue to update"); return E_ILLEGAL_ARGUMENT_EXCEPTION; } //try { String address; device->GetAddress(&address); Int32 type; service->GetType(&type); Int32 instanceId; service->GetInstanceId(&instanceId); AutoPtr<IUUID> uuid; service->GetUuid((IUUID**)&uuid); AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); Int32 cInstanceId; characteristic->GetInstanceId(&cInstanceId); AutoPtr<IUUID> cuuid; characteristic->GetUuid((IUUID**)&cuuid); AutoPtr<IParcelUuid> pcUuid; CParcelUuid::New(cuuid, (IParcelUuid**)&pcUuid); ECode ec = mService->SendNotification(mServerIf, address, type, instanceId, parcelUuid, cInstanceId, pcUuid, confirm, value); //} catch (RemoteException e) { // Logger::E(TAG,"",e); if (FAILED(ec)) { return FALSE; } //} *result = TRUE; return NOERROR; } ECode BluetoothGattServer::AddService( /* [in] */ IBluetoothGattService* service, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; if (DBG) Logger::D(TAG, "addService() - service: ");// + service.getUuid()); if (mService == NULL || mServerIf == 0) return NOERROR; mServices->Add(TO_IINTERFACE(service)); Int32 type; service->GetType(&type); Int32 instanceId; service->GetInstanceId(&instanceId); AutoPtr<IUUID> uuid; service->GetUuid((IUUID**)&uuid); AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); Boolean preferred; service->IsAdvertisePreferred(&preferred); Int32 handles = 0; service->GetHandles(&handles); //try { mService->BeginServiceDeclaration(mServerIf, type, instanceId, handles, parcelUuid, preferred); //List<BluetoothGattService> includedServices = service.getIncludedServices(); AutoPtr<IList> includedServices; service->GetIncludedServices((IList**)&includedServices); Int32 size; includedServices->GetSize(&size); for(Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> obj; includedServices->Get(i, (IInterface**)&obj); IBluetoothGattService* includedService = IBluetoothGattService::Probe(obj); Int32 iType, iInstanceId; includedService->GetType(&iType); includedService->GetInstanceId(&iInstanceId); AutoPtr<IUUID> uuid; includedService->GetUuid((IUUID**)&uuid); AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); mService->AddIncludedService(mServerIf, iType, iInstanceId, parcelUuid); } //List<BluetoothGattCharacteristic> characteristics = service.getCharacteristics(); AutoPtr<IList> characteristics; service->GetCharacteristics((IList**)&characteristics); Int32 csize; characteristics->GetSize(&csize); for(Int32 i = 0; i < csize; ++i) { AutoPtr<IInterface> obj; characteristics->Get(i, (IInterface**)&obj); IBluetoothGattCharacteristic* characteristic = IBluetoothGattCharacteristic::Probe(obj); Int32 keySize = 0, permissions = 0; characteristic->GetKeySize(&keySize); characteristic->GetPermissions(&permissions); Int32 permission = ((keySize - 7) << 12) + permissions; AutoPtr<IUUID> uuid; characteristic->GetUuid((IUUID**)&uuid); AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); Int32 properties; characteristic->GetProperties(&properties); mService->AddCharacteristic(mServerIf, parcelUuid, properties, permission); //List<BluetoothGattDescriptor> descriptors = characteristic.getDescriptors(); AutoPtr<IList> descriptors; characteristic->GetDescriptors((IList**)&descriptors); Int32 size; descriptors->GetSize(&size); for(Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> obj; IBluetoothGattDescriptor* descriptor = IBluetoothGattDescriptor::Probe(obj); Int32 dPermissions; descriptor->GetPermissions(&dPermissions); permission = ((keySize - 7) << 12) + dPermissions; AutoPtr<IUUID> uuid; descriptor->GetUuid((IUUID**)&uuid); AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); mService->AddDescriptor(mServerIf, parcelUuid, permission); } } mService->EndServiceDeclaration(mServerIf); //} catch (RemoteException e) { // Logger::E(TAG,"",e); // return FALSE; //} *result = TRUE; return NOERROR; } ECode BluetoothGattServer::RemoveService( /* [in] */ IBluetoothGattService* service, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = FALSE; if (DBG) Logger::D(TAG, "removeService() - service: ");// + service.getUuid()); if (mService == NULL || mServerIf == 0) return NOERROR; AutoPtr<IBluetoothGattService> intService; AutoPtr<IUUID> uuid; service->GetUuid((IUUID**)&uuid); Int32 instanceId, type; service->GetInstanceId(&instanceId); service->GetType(&type); GetService(uuid, instanceId, type, (IBluetoothGattService**)&intService); if (intService == NULL) return NOERROR; AutoPtr<IParcelUuid> parcelUuid; CParcelUuid::New(uuid, (IParcelUuid**)&parcelUuid); //try { ECode ec = mService->RemoveService(mServerIf, type, instanceId, parcelUuid); mServices->Remove(intService); //} catch (RemoteException e) { // Logger::E(TAG,"",e); if (FAILED(ec)) { return FALSE; } //} *result = TRUE; return NOERROR; } ECode BluetoothGattServer::ClearServices() { if (DBG) Logger::D(TAG, "clearServices()"); if (mService == NULL || mServerIf == 0) return NOERROR; //try { mService->ClearServices(mServerIf); mServices->Clear(); //} catch (RemoteException e) { // Logger::E(TAG,"",e); //} return NOERROR; } ECode BluetoothGattServer::GetServices( /* [out] */ IList** result) { VALIDATE_NOT_NULL(result); *result = mServices; REFCOUNT_ADD(*result); return NOERROR; } ECode BluetoothGattServer::GetService( /* [in] */ IUUID* uuid, /* [out] */ IBluetoothGattService** result) { VALIDATE_NOT_NULL(result); Int32 size; mServices->GetSize(&size); for(Int32 i = 0; i < size; ++i) { AutoPtr<IInterface> obj; mServices->Get(i, (IInterface**)&obj); IBluetoothGattService* service = IBluetoothGattService::Probe(obj); AutoPtr<IUUID> sUuid; service->GetUuid((IUUID**)&sUuid); Boolean eq = FALSE; if (sUuid->Equals(uuid, &eq), eq) { *result = service; REFCOUNT_ADD(*result); return NOERROR; } } *result = NULL; return NOERROR; } ECode BluetoothGattServer::GetConnectionState( /* [in] */ IBluetoothDevice* device, /* [out] */ Int32* state) { // throw new UnsupportedOperationException("Use BluetoothManager#getConnectionState instead."); return E_UNSUPPORTED_OPERATION_EXCEPTION; } ECode BluetoothGattServer::GetConnectedDevices( /* [out] */ IList** devices) { // throw new UnsupportedOperationException // ("Use BluetoothManager#getConnectedDevices instead."); return E_UNSUPPORTED_OPERATION_EXCEPTION; } ECode BluetoothGattServer::GetDevicesMatchingConnectionStates( /* [in] */ ArrayOf<Int32>* states, /* [out] */ IList** devices) { // throw new UnsupportedOperationException // ("Use BluetoothManager#getDevicesMatchingConnectionStates instead."); return E_UNSUPPORTED_OPERATION_EXCEPTION; } void BluetoothGattServer::UnregisterCallback() { if (DBG) Logger::D(TAG, "unregisterCallback() - mServerIf=");// + mServerIf); if (mService == NULL || mServerIf == 0) return; //try { mCallback = NULL; mService->UnregisterServer(mServerIf); mServerIf = 0; //} catch (RemoteException e) { // Logger::E(TAG,"",e); //} } } // namespace Bluetooth } // namespace Droid } // namespace Elastos
27,692
9,203
/** * BCL to FASTQ file converter * Copyright (c) 2007-2017 Illumina, Inc. * * This software is covered by the accompanying EULA * and certain third party copyright/licenses, and any user of this * source file is bound by the terms therein. * * \file barcodeCollisionDetector.hh * * \brief BarcodeCollisionDetector cppunit test declarations. * * \author Aaron Day */ #ifndef BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH #define BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH #include <cppunit/extensions/HelperMacros.h> #include <vector> /// \brief Test suite for BarcodeCollisionDetector. class TestBarcodeCollisionDetector : public CppUnit::TestFixture { CPPUNIT_TEST_SUITE(TestBarcodeCollisionDetector); CPPUNIT_TEST(testSuccess); CPPUNIT_TEST(testMismatchLength); CPPUNIT_TEST(testNumComponents); CPPUNIT_TEST(testCollisionSameSample); CPPUNIT_TEST(testCollision); CPPUNIT_TEST_SUITE_END(); private: std::vector<std::size_t> componentMaxMismatches_; public: TestBarcodeCollisionDetector() : componentMaxMismatches_() {} void setUp(); void tearDown(); void testSuccess(); void testMismatchLength(); void testNumComponents(); void testCollisionSameSample(); void testCollision(); }; #endif // BCL2FASTQ_LAYOUT_TEST_BARCODE_COLLISION_DETECTOR_HH
1,346
485
#include "deskmate/arduino/input/crank.h" #include <Arduino.h> #include "deskmate/input/input.h" namespace deskmate { namespace arduino { namespace input { namespace { using deskmate::input::InputEvent; using deskmate::input::InputEventHandler; deskmate::input::InputEventHandler *input_handler = nullptr; struct CrankPin { int pin_n; volatile int pin_value; }; CrankPin crank_a{-1, HIGH}; CrankPin crank_b{-1, HIGH}; class State { public: enum States { kInitial = 0, k1CW, k2CW, k3CW, k1CCW, k2CCW, k3CCW, }; }; State::States state = State::kInitial; State::States transition_table[][4] = { // 00 01 10 11 {State::kInitial, State::k1CCW, State::k1CW, State::kInitial}, // State::kInitial // Clockwise transitions. {State::kInitial, State::kInitial, State::k1CW, State::k2CW}, // State::k1CW {State::kInitial, State::k3CW, State::kInitial, State::k2CW}, // State::k2CW {State::kInitial, State::k3CW, State::kInitial, State::kInitial}, // State::k3CW // Counter-clockwise transitions. {State::kInitial, State::k1CCW, State::kInitial, State::k2CCW}, // State::k1CCW {State::kInitial, State::kInitial, State::k3CCW, State::k2CCW}, // State::k2CCW {State::kInitial, State::kInitial, State::k3CCW, State::kInitial}, // State::k3CCW }; void HandleStateTransition() { int transition = ((crank_a.pin_value == LOW) << 1 | crank_b.pin_value == LOW) & 0x3; State::States next = transition_table[state][transition]; if (state == State::k3CW && next == State::kInitial) { input_handler->HandleInputEvent(InputEvent::kCrankCW); } else if (state == State::k3CCW && next == State::kInitial) { input_handler->HandleInputEvent(InputEvent::kCrankCCW); } state = next; } void ISRCrankA() { crank_a.pin_value = digitalRead(crank_a.pin_n); HandleStateTransition(); } void ISRCrankB() { crank_b.pin_value = digitalRead(crank_b.pin_n); HandleStateTransition(); } } // namespace void SetupCrankInterruptHandler(uint8_t crank_a_pin, uint8_t crank_b_pin, InputEventHandler *handler) { input_handler = handler; crank_a.pin_n = crank_a_pin; crank_b.pin_n = crank_b_pin; pinMode(crank_a.pin_n, INPUT); pinMode(crank_b.pin_n, INPUT); attachInterrupt(crank_a.pin_n, ISRCrankA, CHANGE); attachInterrupt(crank_b.pin_n, ISRCrankB, CHANGE); } } // namespace input } // namespace arduino } // namespace deskmate
2,536
991
/************************************************************** * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you 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. * *************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_scfilt.hxx" // INCLUDE --------------------------------------------------------------- #include "scitems.hxx" #include <editeng/eeitem.hxx> #include <svx/algitem.hxx> #include <editeng/boxitem.hxx> #include <editeng/brshitem.hxx> #include <editeng/colritem.hxx> #include <editeng/crsditem.hxx> #include <editeng/editdata.hxx> #include <editeng/editeng.hxx> #include <editeng/editobj.hxx> #include <editeng/fhgtitem.hxx> #include <editeng/fontitem.hxx> #include <editeng/lrspitem.hxx> #include <svx/pageitem.hxx> #include <editeng/postitem.hxx> #include <editeng/sizeitem.hxx> #include <editeng/udlnitem.hxx> #include <editeng/ulspitem.hxx> #include <editeng/wghtitem.hxx> #include <svl/zforlist.hxx> #include <svl/PasswordHelper.hxx> #include <stdio.h> #include <math.h> #include <string.h> #include "global.hxx" #include "sc.hrc" #include "attrib.hxx" #include "patattr.hxx" #include "docpool.hxx" #include "document.hxx" #include "collect.hxx" #include "rangenam.hxx" #include "dbcolect.hxx" #include "stlsheet.hxx" #include "stlpool.hxx" #include "filter.hxx" #include "scflt.hxx" #include "cell.hxx" #include "scfobj.hxx" #include "docoptio.hxx" #include "viewopti.hxx" #include "postit.hxx" #include "globstr.hrc" #include "ftools.hxx" #include "tabprotection.hxx" #include "fprogressbar.hxx" using namespace com::sun::star; #define DEFCHARSET RTL_TEXTENCODING_MS_1252 #define SC10TOSTRING(p) String((p),DEFCHARSET) const SCCOL SC10MAXCOL = 255; // #i85906# don't try to load more columns than there are in the file /** Those strings are used with SC10TOSTRING() and strcmp() and such, hence need to be 0-terminated. */ static void lcl_ReadFixedString( SvStream& rStream, void* pData, size_t nLen ) { sal_Char* pBuf = static_cast<sal_Char*>(pData); if (!nLen) pBuf[0] = 0; else { rStream.Read( pBuf, nLen); pBuf[nLen-1] = 0; } } static void lcl_ReadFileHeader(SvStream& rStream, Sc10FileHeader& rFileHeader) { lcl_ReadFixedString( rStream, &rFileHeader.CopyRight, sizeof(rFileHeader.CopyRight)); rStream >> rFileHeader.Version; rStream.Read(&rFileHeader.Reserved, sizeof(rFileHeader.Reserved)); } static void lcl_ReadTabProtect(SvStream& rStream, Sc10TableProtect& rProtect) { lcl_ReadFixedString( rStream, &rProtect.PassWord, sizeof(rProtect.PassWord)); rStream >> rProtect.Flags; rStream >> rProtect.Protect; } static void lcl_ReadSheetProtect(SvStream& rStream, Sc10SheetProtect& rProtect) { lcl_ReadFixedString( rStream, &rProtect.PassWord, sizeof(rProtect.PassWord)); rStream >> rProtect.Flags; rStream >> rProtect.Protect; } static void lcl_ReadRGB(SvStream& rStream, Sc10Color& rColor) { rStream >> rColor.Dummy; rStream >> rColor.Blue; rStream >> rColor.Green; rStream >> rColor.Red; } static void lcl_ReadPalette(SvStream& rStream, Sc10Color* pPalette) { for (sal_uInt16 i = 0; i < 16; i++) lcl_ReadRGB(rStream, pPalette[i]); } static void lcl_ReadValueFormat(SvStream& rStream, Sc10ValueFormat& rFormat) { rStream >> rFormat.Format; rStream >> rFormat.Info; } static void lcl_ReadLogFont(SvStream& rStream, Sc10LogFont& rFont) { rStream >> rFont.lfHeight; rStream >> rFont.lfWidth; rStream >> rFont.lfEscapement; rStream >> rFont.lfOrientation; rStream >> rFont.lfWeight; rStream >> rFont.lfItalic; rStream >> rFont.lfUnderline; rStream >> rFont.lfStrikeOut; rStream >> rFont.lfCharSet; rStream >> rFont.lfOutPrecision; rStream >> rFont.lfClipPrecision; rStream >> rFont.lfQuality; rStream >> rFont.lfPitchAndFamily; lcl_ReadFixedString( rStream, &rFont.lfFaceName, sizeof(rFont.lfFaceName)); } static void lcl_ReadBlockRect(SvStream& rStream, Sc10BlockRect& rBlock) { rStream >> rBlock.x1; rStream >> rBlock.y1; rStream >> rBlock.x2; rStream >> rBlock.y2; } static void lcl_ReadHeadFootLine(SvStream& rStream, Sc10HeadFootLine& rLine) { lcl_ReadFixedString( rStream, &rLine.Title, sizeof(rLine.Title)); lcl_ReadLogFont(rStream, rLine.LogFont); rStream >> rLine.HorJustify; rStream >> rLine.VerJustify; rStream >> rLine.Raster; rStream >> rLine.Frame; lcl_ReadRGB(rStream, rLine.TextColor); lcl_ReadRGB(rStream, rLine.BackColor); lcl_ReadRGB(rStream, rLine.RasterColor); rStream >> rLine.FrameColor; rStream >> rLine.Reserved; } static void lcl_ReadPageFormat(SvStream& rStream, Sc10PageFormat& rFormat) { lcl_ReadHeadFootLine(rStream, rFormat.HeadLine); lcl_ReadHeadFootLine(rStream, rFormat.FootLine); rStream >> rFormat.Orientation; rStream >> rFormat.Width; rStream >> rFormat.Height; rStream >> rFormat.NonPrintableX; rStream >> rFormat.NonPrintableY; rStream >> rFormat.Left; rStream >> rFormat.Top; rStream >> rFormat.Right; rStream >> rFormat.Bottom; rStream >> rFormat.Head; rStream >> rFormat.Foot; rStream >> rFormat.HorCenter; rStream >> rFormat.VerCenter; rStream >> rFormat.PrintGrid; rStream >> rFormat.PrintColRow; rStream >> rFormat.PrintNote; rStream >> rFormat.TopBottomDir; lcl_ReadFixedString( rStream, &rFormat.PrintAreaName, sizeof(rFormat.PrintAreaName)); lcl_ReadBlockRect(rStream, rFormat.PrintArea); rStream.Read(&rFormat.PrnZoom, sizeof(rFormat.PrnZoom)); rStream >> rFormat.FirstPageNo; rStream >> rFormat.RowRepeatStart; rStream >> rFormat.RowRepeatEnd; rStream >> rFormat.ColRepeatStart; rStream >> rFormat.ColRepeatEnd; rStream.Read(&rFormat.Reserved, sizeof(rFormat.Reserved)); } static void lcl_ReadGraphHeader(SvStream& rStream, Sc10GraphHeader& rHeader) { rStream >> rHeader.Typ; rStream >> rHeader.CarretX; rStream >> rHeader.CarretY; rStream >> rHeader.CarretZ; rStream >> rHeader.x; rStream >> rHeader.y; rStream >> rHeader.w; rStream >> rHeader.h; rStream >> rHeader.IsRelPos; rStream >> rHeader.DoPrint; rStream >> rHeader.FrameType; rStream >> rHeader.IsTransparent; lcl_ReadRGB(rStream, rHeader.FrameColor); lcl_ReadRGB(rStream, rHeader.BackColor); rStream.Read(&rHeader.Reserved, sizeof(rHeader.Reserved)); } static void lcl_ReadImageHeaer(SvStream& rStream, Sc10ImageHeader& rHeader) { lcl_ReadFixedString( rStream, &rHeader.FileName, sizeof(rHeader.FileName)); rStream >> rHeader.Typ; rStream >> rHeader.Linked; rStream >> rHeader.x1; rStream >> rHeader.y1; rStream >> rHeader.x2; rStream >> rHeader.y2; rStream >> rHeader.Size; } static void lcl_ReadChartHeader(SvStream& rStream, Sc10ChartHeader& rHeader) { rStream >> rHeader.MM; rStream >> rHeader.xExt; rStream >> rHeader.yExt; rStream >> rHeader.Size; } static void lcl_ReadChartSheetData(SvStream& rStream, Sc10ChartSheetData& rSheetData) { rStream >> rSheetData.HasTitle; rStream >> rSheetData.TitleX; rStream >> rSheetData.TitleY; rStream >> rSheetData.HasSubTitle; rStream >> rSheetData.SubTitleX; rStream >> rSheetData.SubTitleY; rStream >> rSheetData.HasLeftTitle; rStream >> rSheetData.LeftTitleX; rStream >> rSheetData.LeftTitleY; rStream >> rSheetData.HasLegend; rStream >> rSheetData.LegendX1; rStream >> rSheetData.LegendY1; rStream >> rSheetData.LegendX2; rStream >> rSheetData.LegendY2; rStream >> rSheetData.HasLabel; rStream >> rSheetData.LabelX1; rStream >> rSheetData.LabelY1; rStream >> rSheetData.LabelX2; rStream >> rSheetData.LabelY2; rStream >> rSheetData.DataX1; rStream >> rSheetData.DataY1; rStream >> rSheetData.DataX2; rStream >> rSheetData.DataY2; rStream.Read(&rSheetData.Reserved, sizeof(rSheetData.Reserved)); } static void lcl_ReadChartTypeData(SvStream& rStream, Sc10ChartTypeData& rTypeData) { rStream >> rTypeData.NumSets; rStream >> rTypeData.NumPoints; rStream >> rTypeData.DrawMode; rStream >> rTypeData.GraphType; rStream >> rTypeData.GraphStyle; lcl_ReadFixedString( rStream, &rTypeData.GraphTitle, sizeof(rTypeData.GraphTitle)); lcl_ReadFixedString( rStream, &rTypeData.BottomTitle, sizeof(rTypeData.BottomTitle)); sal_uInt16 i; for (i = 0; i < 256; i++) rStream >> rTypeData.SymbolData[i]; for (i = 0; i < 256; i++) rStream >> rTypeData.ColorData[i]; for (i = 0; i < 256; i++) rStream >> rTypeData.ThickLines[i]; for (i = 0; i < 256; i++) rStream >> rTypeData.PatternData[i]; for (i = 0; i < 256; i++) rStream >> rTypeData.LinePatternData[i]; for (i = 0; i < 11; i++) rStream >> rTypeData.NumGraphStyles[i]; rStream >> rTypeData.ShowLegend; for (i = 0; i < 256; i++) lcl_ReadFixedString( rStream, &rTypeData.LegendText[i], sizeof(Sc10ChartText)); rStream >> rTypeData.ExplodePie; rStream >> rTypeData.FontUse; for (i = 0; i < 5; i++) rStream >> rTypeData.FontFamily[i]; for (i = 0; i < 5; i++) rStream >> rTypeData.FontStyle[i]; for (i = 0; i < 5; i++) rStream >> rTypeData.FontSize[i]; rStream >> rTypeData.GridStyle; rStream >> rTypeData.Labels; rStream >> rTypeData.LabelEvery; for (i = 0; i < 50; i++) lcl_ReadFixedString( rStream, &rTypeData.LabelText[i], sizeof(Sc10ChartText)); lcl_ReadFixedString( rStream, &rTypeData.LeftTitle, sizeof(rTypeData.LeftTitle)); rStream.Read(&rTypeData.Reserved, sizeof(rTypeData.Reserved)); } double lcl_PascalToDouble(sal_Char* tp6) { sal_uInt8* pnUnsigned = reinterpret_cast< sal_uInt8* >( tp6 ); // biased exponent sal_uInt8 be = pnUnsigned[ 0 ]; // lower 16 bits of mantissa sal_uInt16 v1 = static_cast< sal_uInt16 >( pnUnsigned[ 2 ] * 256 + pnUnsigned[ 1 ] ); // next 16 bits of mantissa sal_uInt16 v2 = static_cast< sal_uInt16 >( pnUnsigned[ 4 ] * 256 + pnUnsigned[ 3 ] ); // upper 7 bits of mantissa sal_uInt8 v3 = static_cast< sal_uInt8 >( pnUnsigned[ 5 ] & 0x7F ); // sign bit bool s = (pnUnsigned[ 5 ] & 0x80) != 0; if (be == 0) return 0.0; return (((((128 + v3) * 65536.0) + v2) * 65536.0 + v1) * ldexp ((s ? -1.0 : 1.0), be - (129+39))); } static void lcl_ChangeColor( sal_uInt16 nIndex, Color& rColor ) { ColorData aCol; switch( nIndex ) { case 1: aCol = COL_RED; break; case 2: aCol = COL_GREEN; break; case 3: aCol = COL_BROWN; break; case 4: aCol = COL_BLUE; break; case 5: aCol = COL_MAGENTA; break; case 6: aCol = COL_CYAN; break; case 7: aCol = COL_GRAY; break; case 8: aCol = COL_LIGHTGRAY; break; case 9: aCol = COL_LIGHTRED; break; case 10: aCol = COL_LIGHTGREEN; break; case 11: aCol = COL_YELLOW; break; case 12: aCol = COL_LIGHTBLUE; break; case 13: aCol = COL_LIGHTMAGENTA; break; case 14: aCol = COL_LIGHTCYAN; break; case 15: aCol = COL_WHITE; break; default: aCol = COL_BLACK; } rColor.SetColor( aCol ); } String lcl_MakeOldPageStyleFormatName( sal_uInt16 i ) { String aName = ScGlobal::GetRscString( STR_PAGESTYLE ); aName.AppendAscii( " " ); aName += String::CreateFromInt32( i + 1 ); return aName; } template < typename T > sal_uLong insert_new( ScCollection* pCollection, SvStream& rStream ) { T* pData = new (::std::nothrow) T( rStream); sal_uLong nError = rStream.GetError(); if (pData) { if (nError) delete pData; else pCollection->Insert( pData); } else nError = errOutOfMemory; return nError; } //-------------------------------------------- // Font //-------------------------------------------- Sc10FontData::Sc10FontData(SvStream& rStream) { rStream >> Height; rStream >> CharSet; rStream >> PitchAndFamily; sal_uInt16 nLen; rStream >> nLen; if (nLen < sizeof(FaceName)) rStream.Read(FaceName, nLen); else rStream.SetError(ERRCODE_IO_WRONGFORMAT); } Sc10FontCollection::Sc10FontCollection(SvStream& rStream) : ScCollection (4, 4), nError (0) { sal_uInt16 ID; rStream >> ID; if (ID == FontID) { sal_uInt16 nAnz; rStream >> nAnz; for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++) { nError = insert_new<Sc10FontData>( this, rStream); } } else { DBG_ERROR( "FontID" ); nError = errUnknownID; } } //-------------------------------------------- // Benannte-Bereiche //-------------------------------------------- Sc10NameData::Sc10NameData(SvStream& rStream) { sal_uInt8 nLen; rStream >> nLen; rStream.Read(Name, sizeof(Name) - 1); if (nLen >= sizeof(Name)) nLen = sizeof(Name) - 1; Name[nLen] = 0; rStream >> nLen; rStream.Read(Reference, sizeof(Reference) - 1); if (nLen >= sizeof(Reference)) nLen = sizeof(Reference) - 1; Reference[nLen] = 0; rStream.Read(Reserved, sizeof(Reserved)); } Sc10NameCollection::Sc10NameCollection(SvStream& rStream) : ScCollection (4, 4), nError (0) { sal_uInt16 ID; rStream >> ID; if (ID == NameID) { sal_uInt16 nAnz; rStream >> nAnz; for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++) { nError = insert_new<Sc10NameData>( this, rStream); } } else { DBG_ERROR( "NameID" ); nError = errUnknownID; } } //-------------------------------------------- // Vorlagen //-------------------------------------------- Sc10PatternData::Sc10PatternData(SvStream& rStream) { lcl_ReadFixedString( rStream, Name, sizeof(Name)); lcl_ReadValueFormat(rStream, ValueFormat); lcl_ReadLogFont(rStream, LogFont); rStream >> Attr; rStream >> Justify; rStream >> Frame; rStream >> Raster; rStream >> nColor; rStream >> FrameColor; rStream >> Flags; rStream >> FormatFlags; rStream.Read(Reserved, sizeof(Reserved)); } Sc10PatternCollection::Sc10PatternCollection(SvStream& rStream) : ScCollection (4, 4), nError (0) { sal_uInt16 ID; rStream >> ID; if (ID == PatternID) { sal_uInt16 nAnz; rStream >> nAnz; for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++) { nError = insert_new<Sc10PatternData>( this, rStream); } } else { DBG_ERROR( "PatternID" ); nError = errUnknownID; } } //-------------------------------------------- // Datenbank //-------------------------------------------- Sc10DataBaseData::Sc10DataBaseData(SvStream& rStream) { lcl_ReadFixedString( rStream, &DataBaseRec.Name, sizeof(DataBaseRec.Name)); rStream >> DataBaseRec.Tab; lcl_ReadBlockRect(rStream, DataBaseRec.Block); rStream >> DataBaseRec.RowHeader; rStream >> DataBaseRec.SortField0; rStream >> DataBaseRec.SortUpOrder0; rStream >> DataBaseRec.SortField1; rStream >> DataBaseRec.SortUpOrder1; rStream >> DataBaseRec.SortField2; rStream >> DataBaseRec.SortUpOrder2; rStream >> DataBaseRec.IncludeFormat; rStream >> DataBaseRec.QueryField0; rStream >> DataBaseRec.QueryOp0; rStream >> DataBaseRec.QueryByString0; lcl_ReadFixedString( rStream, &DataBaseRec.QueryString0, sizeof(DataBaseRec.QueryString0)); DataBaseRec.QueryValue0 = ScfTools::ReadLongDouble(rStream); rStream >> DataBaseRec.QueryConnect1; rStream >> DataBaseRec.QueryField1; rStream >> DataBaseRec.QueryOp1; rStream >> DataBaseRec.QueryByString1; lcl_ReadFixedString( rStream, &DataBaseRec.QueryString1, sizeof(DataBaseRec.QueryString1)); DataBaseRec.QueryValue1 = ScfTools::ReadLongDouble(rStream); rStream >> DataBaseRec.QueryConnect2; rStream >> DataBaseRec.QueryField2; rStream >> DataBaseRec.QueryOp2; rStream >> DataBaseRec.QueryByString2; lcl_ReadFixedString( rStream, &DataBaseRec.QueryString2, sizeof(DataBaseRec.QueryString2)); DataBaseRec.QueryValue2 = ScfTools::ReadLongDouble(rStream); } Sc10DataBaseCollection::Sc10DataBaseCollection(SvStream& rStream) : ScCollection (4, 4), nError (0) { sal_uInt16 ID; rStream >> ID; if (ID == DataBaseID) { lcl_ReadFixedString( rStream, ActName, sizeof(ActName)); sal_uInt16 nAnz; rStream >> nAnz; for (sal_uInt16 i=0; (i < nAnz) && (nError == 0); i++) { nError = insert_new<Sc10DataBaseData>( this, rStream); } } else { DBG_ERROR( "DataBaseID" ); nError = errUnknownID; } } int Sc10LogFont::operator==( const Sc10LogFont& rData ) const { return !strcmp( lfFaceName, rData.lfFaceName ) && lfHeight == rData.lfHeight && lfWidth == rData.lfWidth && lfEscapement == rData.lfEscapement && lfOrientation == rData.lfOrientation && lfWeight == rData.lfWeight && lfItalic == rData.lfItalic && lfUnderline == rData.lfUnderline && lfStrikeOut == rData.lfStrikeOut && lfCharSet == rData.lfCharSet && lfOutPrecision == rData.lfOutPrecision && lfClipPrecision == rData.lfClipPrecision && lfQuality == rData.lfQuality && lfPitchAndFamily == rData.lfPitchAndFamily; } int Sc10Color::operator==( const Sc10Color& rColor ) const { return ((Red == rColor.Red) && (Green == rColor.Green) && (Blue == rColor.Blue)); } int Sc10HeadFootLine::operator==( const Sc10HeadFootLine& rData ) const { return !strcmp(Title, rData.Title) && LogFont == rData.LogFont && HorJustify == rData.HorJustify && VerJustify == rData.VerJustify && Raster == rData.Raster && Frame == rData.Frame && TextColor == rData.TextColor && BackColor == rData.BackColor && RasterColor == rData.RasterColor && FrameColor == rData.FrameColor && Reserved == rData.Reserved; } int Sc10PageFormat::operator==( const Sc10PageFormat& rData ) const { return !strcmp(PrintAreaName, rData.PrintAreaName) && HeadLine == rData.HeadLine && FootLine == rData.FootLine && Orientation == rData.Orientation && Width == rData.Width && Height == rData.Height && NonPrintableX == rData.NonPrintableX && NonPrintableY == rData.NonPrintableY && Left == rData.Left && Top == rData.Top && Right == rData.Right && Bottom == rData.Bottom && Head == rData.Head && Foot == rData.Foot && HorCenter == rData.HorCenter && VerCenter == rData.VerCenter && PrintGrid == rData.PrintGrid && PrintColRow == rData.PrintColRow && PrintNote == rData.PrintNote && TopBottomDir == rData.TopBottomDir && FirstPageNo == rData.FirstPageNo && RowRepeatStart == rData.RowRepeatStart && RowRepeatEnd == rData.RowRepeatEnd && ColRepeatStart == rData.ColRepeatStart && ColRepeatEnd == rData.ColRepeatEnd && !memcmp( PrnZoom, rData.PrnZoom, sizeof(PrnZoom) ) && !memcmp( &PrintArea, &rData.PrintArea, sizeof(PrintArea) ); } sal_uInt16 Sc10PageCollection::InsertFormat( const Sc10PageFormat& rData ) { for (sal_uInt16 i=0; i<nCount; i++) if (At(i)->aPageFormat == rData) return i; Insert( new Sc10PageData(rData) ); return nCount-1; } static inline sal_uInt8 GetMixedCol( const sal_uInt8 nB, const sal_uInt8 nF, const sal_uInt16 nFak ) { sal_Int32 nT = nB - nF; nT *= ( sal_Int32 ) nFak; nT /= 0xFFFF; nT += nF; return ( sal_uInt8 ) nT; } static inline Color GetMixedColor( const Color& rFore, const Color& rBack, sal_uInt16 nFact ) { return Color( GetMixedCol( rBack.GetRed(), rFore.GetRed(), nFact ), GetMixedCol( rBack.GetGreen(), rFore.GetGreen(), nFact ), GetMixedCol( rBack.GetBlue(), rFore.GetBlue(), nFact ) ); } void Sc10PageCollection::PutToDoc( ScDocument* pDoc ) { ScStyleSheetPool* pStylePool = pDoc->GetStyleSheetPool(); EditEngine aEditEngine( pDoc->GetEnginePool() ); EditTextObject* pEmptyObject = aEditEngine.CreateTextObject(); for (sal_uInt16 i=0; i<nCount; i++) { Sc10PageFormat* pPage = &At(i)->aPageFormat; pPage->Width = (short) ( pPage->Width * ( 72.0 / 72.27 ) + 0.5 ); pPage->Height = (short) ( pPage->Height * ( 72.0 / 72.27 ) + 0.5 ); pPage->Top = (short) ( pPage->Top * ( 72.0 / 72.27 ) + 0.5 ); pPage->Bottom = (short) ( pPage->Bottom * ( 72.0 / 72.27 ) + 0.5 ); pPage->Left = (short) ( pPage->Left * ( 72.0 / 72.27 ) + 0.5 ); pPage->Right = (short) ( pPage->Right * ( 72.0 / 72.27 ) + 0.5 ); pPage->Head = (short) ( pPage->Head * ( 72.0 / 72.27 ) + 0.5 ); pPage->Foot = (short) ( pPage->Foot * ( 72.0 / 72.27 ) + 0.5 ); String aName = lcl_MakeOldPageStyleFormatName( i ); ScStyleSheet* pSheet = (ScStyleSheet*) &pStylePool->Make( aName, SFX_STYLE_FAMILY_PAGE, SFXSTYLEBIT_USERDEF | SCSTYLEBIT_STANDARD ); // #i68483# set page style name at sheet... pDoc->SetPageStyle( static_cast< SCTAB >( i ), aName ); SfxItemSet* pSet = &pSheet->GetItemSet(); for (sal_uInt16 nHeadFoot=0; nHeadFoot<2; nHeadFoot++) { Sc10HeadFootLine* pHeadFootLine = nHeadFoot ? &pPage->FootLine : &pPage->HeadLine; SfxItemSet aEditAttribs(aEditEngine.GetEmptyItemSet()); FontFamily eFam = FAMILY_DONTKNOW; switch (pPage->HeadLine.LogFont.lfPitchAndFamily & 0xF0) { case ffDontCare: eFam = FAMILY_DONTKNOW; break; case ffRoman: eFam = FAMILY_ROMAN; break; case ffSwiss: eFam = FAMILY_SWISS; break; case ffModern: eFam = FAMILY_MODERN; break; case ffScript: eFam = FAMILY_SCRIPT; break; case ffDecorative: eFam = FAMILY_DECORATIVE; break; default: eFam = FAMILY_DONTKNOW; break; } aEditAttribs.Put( SvxFontItem( eFam, SC10TOSTRING( pHeadFootLine->LogFont.lfFaceName ), EMPTY_STRING, PITCH_DONTKNOW, RTL_TEXTENCODING_DONTKNOW, EE_CHAR_FONTINFO ), EE_CHAR_FONTINFO ); aEditAttribs.Put( SvxFontHeightItem( Abs( pHeadFootLine->LogFont.lfHeight ), 100, EE_CHAR_FONTHEIGHT ), EE_CHAR_FONTHEIGHT); Sc10Color nColor = pHeadFootLine->TextColor; Color TextColor( nColor.Red, nColor.Green, nColor.Blue ); aEditAttribs.Put(SvxColorItem(TextColor, EE_CHAR_COLOR), EE_CHAR_COLOR); // FontAttr if (pHeadFootLine->LogFont.lfWeight != fwNormal) aEditAttribs.Put(SvxWeightItem(WEIGHT_BOLD, EE_CHAR_WEIGHT), EE_CHAR_WEIGHT); if (pHeadFootLine->LogFont.lfItalic != 0) aEditAttribs.Put(SvxPostureItem(ITALIC_NORMAL, EE_CHAR_ITALIC), EE_CHAR_ITALIC); if (pHeadFootLine->LogFont.lfUnderline != 0) aEditAttribs.Put(SvxUnderlineItem(UNDERLINE_SINGLE, EE_CHAR_UNDERLINE), EE_CHAR_UNDERLINE); if (pHeadFootLine->LogFont.lfStrikeOut != 0) aEditAttribs.Put(SvxCrossedOutItem(STRIKEOUT_SINGLE, EE_CHAR_STRIKEOUT), EE_CHAR_STRIKEOUT); String aText( pHeadFootLine->Title, DEFCHARSET ); aEditEngine.SetText( aText ); aEditEngine.QuickSetAttribs( aEditAttribs, ESelection( 0, 0, 0, aText.Len() ) ); EditTextObject* pObject = aEditEngine.CreateTextObject(); ScPageHFItem aHeaderItem(nHeadFoot ? ATTR_PAGE_FOOTERRIGHT : ATTR_PAGE_HEADERRIGHT); switch (pHeadFootLine->HorJustify) { case hjCenter: aHeaderItem.SetLeftArea(*pEmptyObject); aHeaderItem.SetCenterArea(*pObject); aHeaderItem.SetRightArea(*pEmptyObject); break; case hjRight: aHeaderItem.SetLeftArea(*pEmptyObject); aHeaderItem.SetCenterArea(*pEmptyObject); aHeaderItem.SetRightArea(*pObject); break; default: aHeaderItem.SetLeftArea(*pObject); aHeaderItem.SetCenterArea(*pEmptyObject); aHeaderItem.SetRightArea(*pEmptyObject); break; } delete pObject; pSet->Put( aHeaderItem ); SfxItemSet aSetItemItemSet( *pDoc->GetPool(), ATTR_BACKGROUND, ATTR_BACKGROUND, ATTR_BORDER, ATTR_SHADOW, ATTR_PAGE_SIZE, ATTR_PAGE_SIZE, ATTR_LRSPACE, ATTR_ULSPACE, ATTR_PAGE_ON, ATTR_PAGE_SHARED, 0 ); nColor = pHeadFootLine->BackColor; Color aBColor( nColor.Red, nColor.Green, nColor.Blue ); nColor = pHeadFootLine->RasterColor; Color aRColor( nColor.Red, nColor.Green, nColor.Blue ); sal_uInt16 nFact; sal_Bool bSwapCol = sal_False; switch (pHeadFootLine->Raster) { case raNone: nFact = 0xffff; bSwapCol = sal_True; break; case raGray12: nFact = (0xffff / 100) * 12; break; case raGray25: nFact = (0xffff / 100) * 25; break; case raGray50: nFact = (0xffff / 100) * 50; break; case raGray75: nFact = (0xffff / 100) * 75; break; default: nFact = 0xffff; } if( bSwapCol ) aSetItemItemSet.Put( SvxBrushItem( GetMixedColor( aBColor, aRColor, nFact ), ATTR_BACKGROUND ) ); else aSetItemItemSet.Put( SvxBrushItem( GetMixedColor( aRColor, aBColor, nFact ), ATTR_BACKGROUND ) ); if (pHeadFootLine->Frame != 0) { sal_uInt16 nLeft = 0; sal_uInt16 nTop = 0; sal_uInt16 nRight = 0; sal_uInt16 nBottom = 0; sal_uInt16 fLeft = (pHeadFootLine->Frame & 0x000F); sal_uInt16 fTop = (pHeadFootLine->Frame & 0x00F0) / 0x0010; sal_uInt16 fRight = (pHeadFootLine->Frame & 0x0F00) / 0x0100; sal_uInt16 fBottom = (pHeadFootLine->Frame & 0xF000) / 0x1000; if (fLeft > 1) nLeft = 50; else if (fLeft > 0) nLeft = 20; if (fTop > 1) nTop = 50; else if (fTop > 0) nTop = 20; if (fRight > 1) nRight = 50; else if (fRight > 0) nRight = 20; if (fBottom > 1) nBottom = 50; else if (fBottom > 0) nBottom = 20; Color ColorLeft(COL_BLACK); Color ColorTop(COL_BLACK); Color ColorRight(COL_BLACK); Color ColorBottom(COL_BLACK); sal_uInt16 cLeft = (pHeadFootLine->FrameColor & 0x000F); sal_uInt16 cTop = (pHeadFootLine->FrameColor & 0x00F0) >> 4; sal_uInt16 cRight = (pHeadFootLine->FrameColor & 0x0F00) >> 8; sal_uInt16 cBottom = (pHeadFootLine->FrameColor & 0xF000) >> 12; lcl_ChangeColor(cLeft, ColorLeft); lcl_ChangeColor(cTop, ColorTop); lcl_ChangeColor(cRight, ColorRight); lcl_ChangeColor(cBottom, ColorBottom); SvxBorderLine aLine; SvxBoxItem aBox( ATTR_BORDER ); aLine.SetOutWidth(nLeft); aLine.SetColor(ColorLeft); aBox.SetLine(&aLine, BOX_LINE_LEFT); aLine.SetOutWidth(nTop); aLine.SetColor(ColorTop); aBox.SetLine(&aLine, BOX_LINE_TOP); aLine.SetOutWidth(nRight); aLine.SetColor(ColorRight); aBox.SetLine(&aLine, BOX_LINE_RIGHT); aLine.SetOutWidth(nBottom); aLine.SetColor(ColorBottom); aBox.SetLine(&aLine, BOX_LINE_BOTTOM); aSetItemItemSet.Put(aBox); } pSet->Put( SvxULSpaceItem( 0, 0, ATTR_ULSPACE ) ); if (nHeadFoot==0) aSetItemItemSet.Put( SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, pPage->Top - pPage->Head ) ) ); else aSetItemItemSet.Put( SvxSizeItem( ATTR_PAGE_SIZE, Size( 0, pPage->Bottom - pPage->Foot ) ) ); aSetItemItemSet.Put(SfxBoolItem( ATTR_PAGE_ON, sal_True )); aSetItemItemSet.Put(SfxBoolItem( ATTR_PAGE_DYNAMIC, sal_False )); aSetItemItemSet.Put(SfxBoolItem( ATTR_PAGE_SHARED, sal_True )); pSet->Put( SvxSetItem( nHeadFoot ? ATTR_PAGE_FOOTERSET : ATTR_PAGE_HEADERSET, aSetItemItemSet ) ); } SvxPageItem aPageItem(ATTR_PAGE); aPageItem.SetPageUsage( SVX_PAGE_ALL ); aPageItem.SetLandscape( pPage->Orientation != 1 ); aPageItem.SetNumType( SVX_ARABIC ); pSet->Put(aPageItem); pSet->Put(SvxLRSpaceItem( pPage->Left, pPage->Right, 0,0, ATTR_LRSPACE )); pSet->Put(SvxULSpaceItem( pPage->Top, pPage->Bottom, ATTR_ULSPACE )); pSet->Put(SfxBoolItem( ATTR_PAGE_HORCENTER, pPage->HorCenter )); pSet->Put(SfxBoolItem( ATTR_PAGE_VERCENTER, pPage->VerCenter )); //---------------- // Area-Parameter: //---------------- { ScRange* pRepeatRow = NULL; ScRange* pRepeatCol = NULL; if ( pPage->ColRepeatStart >= 0 ) pRepeatCol = new ScRange( static_cast<SCCOL> (pPage->ColRepeatStart), 0, 0 ); if ( pPage->RowRepeatStart >= 0 ) pRepeatRow = new ScRange( 0, static_cast<SCROW> (pPage->RowRepeatStart), 0 ); if ( pRepeatRow || pRepeatCol ) { // // an allen Tabellen setzen // for ( SCTAB nTab = 0, nTabCount = pDoc->GetTableCount(); nTab < nTabCount; ++nTab ) { pDoc->SetRepeatColRange( nTab, pRepeatCol ); pDoc->SetRepeatRowRange( nTab, pRepeatRow ); } } delete pRepeatRow; delete pRepeatCol; } //----------------- // Table-Parameter: //----------------- pSet->Put( SfxBoolItem( ATTR_PAGE_NOTES, pPage->PrintNote ) ); pSet->Put( SfxBoolItem( ATTR_PAGE_GRID, pPage->PrintGrid ) ); pSet->Put( SfxBoolItem( ATTR_PAGE_HEADERS, pPage->PrintColRow ) ); pSet->Put( SfxBoolItem( ATTR_PAGE_TOPDOWN, pPage->TopBottomDir ) ); pSet->Put( ScViewObjectModeItem( ATTR_PAGE_CHARTS, VOBJ_MODE_SHOW ) ); pSet->Put( ScViewObjectModeItem( ATTR_PAGE_OBJECTS, VOBJ_MODE_SHOW ) ); pSet->Put( ScViewObjectModeItem( ATTR_PAGE_DRAWINGS, VOBJ_MODE_SHOW ) ); pSet->Put( SfxUInt16Item( ATTR_PAGE_SCALE, (sal_uInt16)( lcl_PascalToDouble( pPage->PrnZoom ) * 100 ) ) ); pSet->Put( SfxUInt16Item( ATTR_PAGE_FIRSTPAGENO, 1 ) ); pSet->Put( SvxSizeItem( ATTR_PAGE_SIZE, Size( pPage->Width, pPage->Height ) ) ); } delete pEmptyObject; } ScDataObject* Sc10PageData::Clone() const { return new Sc10PageData(aPageFormat); } //-------------------------------------------- // Import //-------------------------------------------- Sc10Import::Sc10Import(SvStream& rStr, ScDocument* pDocument ) : rStream (rStr), pDoc (pDocument), pFontCollection (NULL), pNameCollection (NULL), pPatternCollection (NULL), pDataBaseCollection (NULL), nError (0), nShowTab (0) { pPrgrsBar = NULL; } Sc10Import::~Sc10Import() { pDoc->CalcAfterLoad(); pDoc->UpdateAllCharts(); delete pFontCollection; delete pNameCollection; delete pPatternCollection; delete pDataBaseCollection; DBG_ASSERT( pPrgrsBar == NULL, "*Sc10Import::Sc10Import(): Progressbar lebt noch!?" ); } sal_uLong Sc10Import::Import() { pPrgrsBar = new ScfStreamProgressBar( rStream, pDoc->GetDocumentShell() ); ScDocOptions aOpt = pDoc->GetDocOptions(); aOpt.SetDate( 1, 1, 1900 ); aOpt.SetYear2000( 18 + 1901 ); // ab SO51 src513e vierstellig pDoc->SetDocOptions( aOpt ); pDoc->GetFormatTable()->ChangeNullDate( 1, 1, 1900 ); LoadFileHeader(); pPrgrsBar->Progress(); if (!nError) { LoadFileInfo(); pPrgrsBar->Progress(); } if (!nError) { LoadEditStateInfo(); pPrgrsBar->Progress(); } if (!nError) { LoadProtect(); pPrgrsBar->Progress(); } if (!nError) { LoadViewColRowBar(); pPrgrsBar->Progress(); } if (!nError) { LoadScrZoom(); pPrgrsBar->Progress(); } if (!nError) { LoadPalette(); pPrgrsBar->Progress(); } if (!nError) { LoadFontCollection(); pPrgrsBar->Progress(); } if (!nError) { LoadNameCollection(); pPrgrsBar->Progress(); } if (!nError) { LoadPatternCollection(); pPrgrsBar->Progress(); } if (!nError) { LoadDataBaseCollection(); pPrgrsBar->Progress(); } if (!nError) { LoadTables(); pPrgrsBar->Progress(); } if (!nError) { LoadObjects(); pPrgrsBar->Progress(); } if (!nError) { ImportNameCollection(); pPrgrsBar->Progress(); } pDoc->SetViewOptions( aSc30ViewOpt ); #ifdef DBG_UTIL if (nError) { DBG_ERROR( ByteString::CreateFromInt32( nError ).GetBuffer() ); } #endif delete pPrgrsBar; #ifdef DBG_UTIL pPrgrsBar = NULL; #endif return nError; } void Sc10Import::LoadFileHeader() { Sc10FileHeader FileHeader; lcl_ReadFileHeader(rStream, FileHeader); nError = rStream.GetError(); if ( nError == 0 ) { sal_Char Sc10CopyRight[32]; strcpy(Sc10CopyRight, "Blaise-Tabelle"); // #100211# - checked Sc10CopyRight[14] = 10; Sc10CopyRight[15] = 13; Sc10CopyRight[16] = 0; if ((strcmp(FileHeader.CopyRight, Sc10CopyRight) != 0) || (FileHeader.Version < 101) || (FileHeader.Version > 102)) nError = errUnknownFormat; } } void Sc10Import::LoadFileInfo() { Sc10FileInfo FileInfo; rStream.Read(&FileInfo, sizeof(FileInfo)); nError = rStream.GetError(); // Achtung Info Uebertragen } void Sc10Import::LoadEditStateInfo() { Sc10EditStateInfo EditStateInfo; rStream.Read(&EditStateInfo, sizeof(EditStateInfo)); nError = rStream.GetError(); nShowTab = static_cast<SCTAB>(EditStateInfo.DeltaZ); // Achtung Cursorposition und Offset der Tabelle Uebertragen (soll man das machen??) } void Sc10Import::LoadProtect() { lcl_ReadSheetProtect(rStream, SheetProtect); nError = rStream.GetError(); ScDocProtection aProtection; aProtection.setProtected(static_cast<bool>(SheetProtect.Protect)); aProtection.setPassword(SC10TOSTRING(SheetProtect.PassWord)); pDoc->SetDocProtection(&aProtection); } void Sc10Import::LoadViewColRowBar() { sal_uInt8 ViewColRowBar; rStream >> ViewColRowBar; nError = rStream.GetError(); aSc30ViewOpt.SetOption( VOPT_HEADER, (sal_Bool)ViewColRowBar ); } void Sc10Import::LoadScrZoom() { // Achtung Zoom ist leider eine 6Byte TP real Zahl (keine Ahnung wie die Umzusetzen ist) sal_Char cZoom[6]; rStream.Read(cZoom, sizeof(cZoom)); nError = rStream.GetError(); } void Sc10Import::LoadPalette() { lcl_ReadPalette(rStream, TextPalette); lcl_ReadPalette(rStream, BackPalette); lcl_ReadPalette(rStream, RasterPalette); lcl_ReadPalette(rStream, FramePalette); nError = rStream.GetError(); } void Sc10Import::LoadFontCollection() { pFontCollection = new Sc10FontCollection(rStream); if (!nError) nError = pFontCollection->GetError(); } void Sc10Import::LoadNameCollection() { pNameCollection = new Sc10NameCollection(rStream); if (!nError) nError = pNameCollection->GetError(); } void Sc10Import::ImportNameCollection() { ScRangeName* pRN = pDoc->GetRangeName(); for (sal_uInt16 i = 0; i < pNameCollection->GetCount(); i++) { Sc10NameData* pName = pNameCollection->At( i ); pRN->Insert( new ScRangeData( pDoc, SC10TOSTRING( pName->Name ), SC10TOSTRING( pName->Reference ) ) ); } } void Sc10Import::LoadPatternCollection() { pPatternCollection = new Sc10PatternCollection( rStream ); if (!nError) nError = pPatternCollection->GetError(); if (nError == errOutOfMemory) return; // hopeless ScStyleSheetPool* pStylePool = pDoc->GetStyleSheetPool(); for( sal_uInt16 i = 0 ; i < pPatternCollection->GetCount() ; i++ ) { Sc10PatternData* pPattern = pPatternCollection->At( i ); String aName( pPattern->Name, DEFCHARSET ); SfxStyleSheetBase* pStyle = pStylePool->Find( aName, SFX_STYLE_FAMILY_PARA ); if( pStyle == NULL ) pStylePool->Make( aName, SFX_STYLE_FAMILY_PARA ); else { pPattern->Name[ 27 ] = 0; strcat( pPattern->Name, "_Old" ); // #100211# - checked aName = SC10TOSTRING( pPattern->Name ); pStylePool->Make( aName, SFX_STYLE_FAMILY_PARA ); } pStyle = pStylePool->Find( aName, SFX_STYLE_FAMILY_PARA ); if( pStyle != NULL ) { SfxItemSet &rItemSet = pStyle->GetItemSet(); // Font if( ( pPattern->FormatFlags & pfFont ) == pfFont ) { FontFamily eFam = FAMILY_DONTKNOW; switch( pPattern->LogFont.lfPitchAndFamily & 0xF0 ) { case ffDontCare : eFam = FAMILY_DONTKNOW; break; case ffRoman : eFam = FAMILY_ROMAN; break; case ffSwiss : eFam = FAMILY_SWISS; break; case ffModern : eFam = FAMILY_MODERN; break; case ffScript : eFam = FAMILY_SCRIPT; break; case ffDecorative : eFam = FAMILY_DECORATIVE; break; default: eFam = FAMILY_DONTKNOW; break; } rItemSet.Put( SvxFontItem( eFam, SC10TOSTRING( pPattern->LogFont.lfFaceName ), EMPTY_STRING, PITCH_DONTKNOW, RTL_TEXTENCODING_DONTKNOW, ATTR_FONT ) ); rItemSet.Put( SvxFontHeightItem( Abs( pPattern->LogFont.lfHeight ), 100, ATTR_FONT_HEIGHT ) ); Color TextColor( COL_BLACK ); lcl_ChangeColor( ( pPattern->nColor & 0x000F ), TextColor ); rItemSet.Put( SvxColorItem( TextColor, ATTR_FONT_COLOR ) ); // FontAttr if( pPattern->LogFont.lfWeight != fwNormal ) rItemSet.Put( SvxWeightItem( WEIGHT_BOLD, ATTR_FONT_WEIGHT ) ); if( pPattern->LogFont.lfItalic != 0 ) rItemSet.Put( SvxPostureItem( ITALIC_NORMAL, ATTR_FONT_POSTURE ) ); if( pPattern->LogFont.lfUnderline != 0 ) rItemSet.Put( SvxUnderlineItem( UNDERLINE_SINGLE, ATTR_FONT_UNDERLINE ) ); if( pPattern->LogFont.lfStrikeOut != 0 ) rItemSet.Put( SvxCrossedOutItem( STRIKEOUT_SINGLE, ATTR_FONT_CROSSEDOUT ) ); } // Ausrichtung if( ( pPattern->FormatFlags & pfJustify ) == pfJustify ) { sal_uInt16 HorJustify = ( pPattern->Justify & 0x000F ); sal_uInt16 VerJustify = ( pPattern->Justify & 0x00F0 ) >> 4; sal_uInt16 OJustify = ( pPattern->Justify & 0x0F00 ) >> 8; sal_uInt16 EJustify = ( pPattern->Justify & 0xF000 ) >> 12; if( HorJustify != 0 ) switch( HorJustify ) { case hjLeft: rItemSet.Put( SvxHorJustifyItem( SVX_HOR_JUSTIFY_LEFT, ATTR_HOR_JUSTIFY ) ); break; case hjCenter: rItemSet.Put( SvxHorJustifyItem( SVX_HOR_JUSTIFY_CENTER, ATTR_HOR_JUSTIFY ) ); break; case hjRight: rItemSet.Put( SvxHorJustifyItem( SVX_HOR_JUSTIFY_RIGHT, ATTR_HOR_JUSTIFY ) ); break; } if( VerJustify != 0 ) switch( VerJustify ) { case vjTop: rItemSet.Put( SvxVerJustifyItem( SVX_VER_JUSTIFY_TOP, ATTR_VER_JUSTIFY ) ); break; case vjCenter: rItemSet.Put( SvxVerJustifyItem( SVX_VER_JUSTIFY_CENTER, ATTR_VER_JUSTIFY ) ); break; case vjBottom: rItemSet.Put( SvxVerJustifyItem( SVX_VER_JUSTIFY_BOTTOM, ATTR_VER_JUSTIFY ) ); break; } if( ( OJustify & ojWordBreak ) == ojWordBreak ) rItemSet.Put( SfxBoolItem( sal_True ) ); if( ( OJustify & ojBottomTop ) == ojBottomTop ) rItemSet.Put( SfxInt32Item( ATTR_ROTATE_VALUE, 9000 ) ); else if( ( OJustify & ojTopBottom ) == ojTopBottom ) rItemSet.Put( SfxInt32Item( ATTR_ROTATE_VALUE, 27000 ) ); sal_Int16 Margin = Max( ( sal_uInt16 ) 20, ( sal_uInt16 ) ( EJustify * 20 ) ); if( ( ( OJustify & ojBottomTop ) == ojBottomTop ) ) rItemSet.Put( SvxMarginItem( 20, Margin, 20, Margin, ATTR_MARGIN ) ); else rItemSet.Put( SvxMarginItem( Margin, 20, Margin, 20, ATTR_MARGIN ) ); } // Frame if( ( pPattern->FormatFlags & pfFrame ) == pfFrame ) { if( pPattern->Frame != 0 ) { sal_uInt16 nLeft = 0; sal_uInt16 nTop = 0; sal_uInt16 nRight = 0; sal_uInt16 nBottom = 0; sal_uInt16 fLeft = ( pPattern->Frame & 0x000F ); sal_uInt16 fTop = ( pPattern->Frame & 0x00F0 ) / 0x0010; sal_uInt16 fRight = ( pPattern->Frame & 0x0F00 ) / 0x0100; sal_uInt16 fBottom = ( pPattern->Frame & 0xF000 ) / 0x1000; if( fLeft > 1 ) nLeft = 50; else if( fLeft > 0 ) nLeft = 20; if( fTop > 1 ) nTop = 50; else if( fTop > 0 ) nTop = 20; if( fRight > 1 ) nRight = 50; else if( fRight > 0 ) nRight = 20; if( fBottom > 1 ) nBottom = 50; else if( fBottom > 0 ) nBottom = 20; Color ColorLeft( COL_BLACK ); Color ColorTop( COL_BLACK ); Color ColorRight( COL_BLACK ); Color ColorBottom( COL_BLACK ); sal_uInt16 cLeft = ( pPattern->FrameColor & 0x000F ); sal_uInt16 cTop = ( pPattern->FrameColor & 0x00F0 ) >> 4; sal_uInt16 cRight = ( pPattern->FrameColor & 0x0F00 ) >> 8; sal_uInt16 cBottom = ( pPattern->FrameColor & 0xF000 ) >> 12; lcl_ChangeColor( cLeft, ColorLeft ); lcl_ChangeColor( cTop, ColorTop ); lcl_ChangeColor( cRight, ColorRight ); lcl_ChangeColor( cBottom, ColorBottom ); SvxBorderLine aLine; SvxBoxItem aBox( ATTR_BORDER ); aLine.SetOutWidth( nLeft ); aLine.SetColor( ColorLeft ); aBox.SetLine( &aLine, BOX_LINE_LEFT ); aLine.SetOutWidth( nTop ); aLine.SetColor( ColorTop ); aBox.SetLine( &aLine, BOX_LINE_TOP ); aLine.SetOutWidth( nRight ); aLine.SetColor( ColorRight ); aBox.SetLine( &aLine, BOX_LINE_RIGHT ); aLine.SetOutWidth( nBottom ); aLine.SetColor( ColorBottom ); aBox.SetLine( &aLine, BOX_LINE_BOTTOM ); rItemSet.Put( aBox ); } } // Raster if( ( pPattern->FormatFlags & pfRaster ) == pfRaster ) { if( pPattern->Raster != 0 ) { sal_uInt16 nBColor = ( pPattern->nColor & 0x00F0 ) >> 4; sal_uInt16 nRColor = ( pPattern->nColor & 0x0F00 ) >> 8; Color aBColor( COL_BLACK ); lcl_ChangeColor( nBColor, aBColor ); if( nBColor == 0 ) aBColor.SetColor( COL_WHITE ); else if( nBColor == 15 ) aBColor.SetColor( COL_BLACK ); Color aRColor( COL_BLACK ); lcl_ChangeColor( nRColor, aRColor ); sal_uInt16 nFact; sal_Bool bSwapCol = sal_False; sal_Bool bSetItem = sal_True; switch (pPattern->Raster) { case raNone: nFact = 0xffff; bSwapCol = sal_True; bSetItem = (nBColor > 0); break; case raGray12: nFact = (0xffff / 100) * 12; break; case raGray25: nFact = (0xffff / 100) * 25; break; case raGray50: nFact = (0xffff / 100) * 50; break; case raGray75: nFact = (0xffff / 100) * 75; break; default: nFact = 0xffff; bSetItem = (nRColor < 15); } if ( bSetItem ) { if( bSwapCol ) rItemSet.Put( SvxBrushItem( GetMixedColor( aBColor, aRColor, nFact ), ATTR_BACKGROUND ) ); else rItemSet.Put( SvxBrushItem( GetMixedColor( aRColor, aBColor, nFact ), ATTR_BACKGROUND ) ); } } } // ZahlenFormate if( ( pPattern->ValueFormat.Format != 0 ) && ( ( pPattern->FormatFlags & pfValue ) == pfValue ) ) { sal_uLong nKey = 0; ChangeFormat( pPattern->ValueFormat.Format, pPattern->ValueFormat.Info, nKey ); rItemSet.Put( SfxUInt32Item( ATTR_VALUE_FORMAT, ( sal_uInt32 ) nKey ) ); } // Zellattribute (Schutz, Versteckt...) if( ( pPattern->Flags != 0 ) && ( ( pPattern->FormatFlags & pfProtection ) == pfProtection ) ) { sal_Bool bProtect = ( ( pPattern->Flags & paProtect ) == paProtect ); sal_Bool bHFormula = ( ( pPattern->Flags & paHideFormula ) == paHideFormula ); sal_Bool bHCell = ( ( pPattern->Flags & paHideAll ) == paHideAll ); sal_Bool bHPrint = ( ( pPattern->Flags & paHidePrint ) == paHidePrint ); rItemSet.Put( ScProtectionAttr( bProtect, bHFormula, bHCell, bHPrint ) ); } } // if Style != 0 } // for (i = 0; i < GetCount() } void Sc10Import::LoadDataBaseCollection() { pDataBaseCollection = new Sc10DataBaseCollection(rStream); if (!nError) nError = pDataBaseCollection->GetError(); if (nError == errOutOfMemory) return; // hopeless for( sal_uInt16 i = 0 ; i < pDataBaseCollection->GetCount() ; i++ ) { Sc10DataBaseData* pOldData = pDataBaseCollection->At(i); ScDBData* pNewData = new ScDBData( SC10TOSTRING( pOldData->DataBaseRec.Name ), ( SCTAB ) pOldData->DataBaseRec.Tab, ( SCCOL ) pOldData->DataBaseRec.Block.x1, ( SCROW ) pOldData->DataBaseRec.Block.y1, ( SCCOL ) pOldData->DataBaseRec.Block.x2, ( SCROW ) pOldData->DataBaseRec.Block.y2, sal_True, ( sal_Bool) pOldData->DataBaseRec.RowHeader ); pDoc->GetDBCollection()->Insert( pNewData ); } } void Sc10Import::LoadTables() { Sc10PageCollection aPageCollection; sal_Int16 nTabCount; rStream >> nTabCount; for (sal_Int16 Tab = 0; (Tab < nTabCount) && (nError == 0); Tab++) { Sc10PageFormat PageFormat; sal_Int16 DataBaseIndex; Sc10TableProtect TabProtect; sal_Int16 TabNo; sal_Char TabName[128]; sal_uInt16 Display; sal_uInt8 Visible; sal_uInt16 ID; sal_uInt16 DataCount; sal_uInt16 DataStart; sal_uInt16 DataEnd; sal_uInt16 DataValue; sal_uInt16 Count; sal_uInt16 i; String aStr; // Universal-Konvertierungs-String lcl_ReadPageFormat(rStream, PageFormat); sal_uInt16 nAt = aPageCollection.InsertFormat(PageFormat); String aPageName = lcl_MakeOldPageStyleFormatName( nAt ); pPrgrsBar->Progress(); rStream >> DataBaseIndex; lcl_ReadTabProtect(rStream, TabProtect); ScTableProtection aProtection; aProtection.setProtected(static_cast<bool>(TabProtect.Protect)); aProtection.setPassword(SC10TOSTRING(TabProtect.PassWord)); pDoc->SetTabProtection(static_cast<SCTAB>(Tab), &aProtection); rStream >> TabNo; sal_uInt8 nLen; rStream >> nLen; rStream.Read(TabName, sizeof(TabName) - 1); if (nLen >= sizeof(TabName)) nLen = sizeof(TabName) - 1; TabName[nLen] = 0; //---------------------------------------------------------- rStream >> Display; if ( Tab == (sal_Int16)nShowTab ) { ScVObjMode eObjMode = VOBJ_MODE_SHOW; aSc30ViewOpt.SetOption( VOPT_FORMULAS, IS_SET(dfFormula,Display) ); aSc30ViewOpt.SetOption( VOPT_NULLVALS, IS_SET(dfZerro,Display) ); aSc30ViewOpt.SetOption( VOPT_SYNTAX, IS_SET(dfSyntax,Display) ); aSc30ViewOpt.SetOption( VOPT_NOTES, IS_SET(dfNoteMark,Display) ); aSc30ViewOpt.SetOption( VOPT_VSCROLL, sal_True ); aSc30ViewOpt.SetOption( VOPT_HSCROLL, sal_True ); aSc30ViewOpt.SetOption( VOPT_TABCONTROLS, sal_True ); aSc30ViewOpt.SetOption( VOPT_OUTLINER, sal_True ); aSc30ViewOpt.SetOption( VOPT_GRID, IS_SET(dfGrid,Display) ); // VOPT_HEADER wird in LoadViewColRowBar() gesetzt if ( IS_SET(dfObjectAll,Display) ) // Objekte anzeigen eObjMode = VOBJ_MODE_SHOW; else if ( IS_SET(dfObjectFrame,Display) ) // Objekte als Platzhalter eObjMode = VOBJ_MODE_SHOW; else if ( IS_SET(dfObjectNone,Display) ) // Objekte nicht anzeigen eObjMode = VOBJ_MODE_HIDE; aSc30ViewOpt.SetObjMode( VOBJ_TYPE_OLE, eObjMode ); aSc30ViewOpt.SetObjMode( VOBJ_TYPE_CHART, eObjMode ); aSc30ViewOpt.SetObjMode( VOBJ_TYPE_DRAW, eObjMode ); } /* wofuer wird das benoetigt? Da in SC 1.0 die Anzeigeflags pro Tabelle gelten und nicht pro View Dieses Flag in die ViewOptions eintragen bei Gelegenheit, Sollte der Stephan Olk machen sal_uInt16 nDisplayMask = 0xFFFF; sal_uInt16 nDisplayValue = 0; if (Tab == 0) nDisplayValue = Display; else { sal_uInt16 nDiff = Display ^ nDisplayValue; nDisplayMask &= ~nDiff; } */ //-------------------------------------------------------------------- rStream >> Visible; nError = rStream.GetError(); if (nError != 0) return; if (TabNo == 0) pDoc->RenameTab(static_cast<SCTAB> (TabNo), SC10TOSTRING( TabName ), sal_False); else pDoc->InsertTab(SC_TAB_APPEND, SC10TOSTRING( TabName ) ); pDoc->SetPageStyle( static_cast<SCTAB>(Tab), aPageName ); if (Visible == 0) pDoc->SetVisible(static_cast<SCTAB> (TabNo), sal_False); // ColWidth rStream >> ID; if (ID != ColWidthID) { DBG_ERROR( "ColWidthID" ); nError = errUnknownID; return; } rStream >> DataCount; DataStart = 0; for (i=0; i < DataCount; i++) { rStream >> DataEnd; rStream >> DataValue; for (SCCOL j = static_cast<SCCOL>(DataStart); j <= static_cast<SCCOL>(DataEnd); j++) pDoc->SetColWidth(j, static_cast<SCTAB> (TabNo), DataValue); DataStart = DataEnd + 1; } pPrgrsBar->Progress(); // ColAttr rStream >> ID; if (ID != ColAttrID) { DBG_ERROR( "ColAttrID" ); nError = errUnknownID; return; } rStream >> DataCount; DataStart = 0; for (i=0; i < DataCount; i++) { rStream >> DataEnd; rStream >> DataValue; if (DataValue != 0) { bool bPageBreak = ((DataValue & crfSoftBreak) == crfSoftBreak); bool bManualBreak = ((DataValue & crfHardBreak) == crfHardBreak); bool bHidden = ((DataValue & crfHidden) == crfHidden); for (SCCOL k = static_cast<SCCOL>(DataStart); k <= static_cast<SCCOL>(DataEnd); k++) { pDoc->SetColHidden(k, k, static_cast<SCTAB>(TabNo), bHidden); pDoc->SetColBreak(k, static_cast<SCTAB> (TabNo), bPageBreak, bManualBreak); } } DataStart = DataEnd + 1; } pPrgrsBar->Progress(); // RowHeight rStream >> ID; if (ID != RowHeightID) { DBG_ERROR( "RowHeightID" ); nError = errUnknownID; return; } rStream >> DataCount; DataStart = 0; for (i=0; i < DataCount; i++) { rStream >> DataEnd; rStream >> DataValue; pDoc->SetRowHeightRange(static_cast<SCROW> (DataStart), static_cast<SCROW> (DataEnd), static_cast<SCTAB> (TabNo), DataValue); DataStart = DataEnd + 1; } pPrgrsBar->Progress(); // RowAttr rStream >> ID; if (ID != RowAttrID) { DBG_ERROR( "RowAttrID" ); nError = errUnknownID; return; } rStream >> DataCount; DataStart = 0; for (i=0; i < DataCount; i++) { rStream >> DataEnd; rStream >> DataValue; if (DataValue != 0) { bool bPageBreak = ((DataValue & crfSoftBreak) == crfSoftBreak); bool bManualBreak = ((DataValue & crfHardBreak) == crfHardBreak); bool bHidden = ((DataValue & crfHidden) == crfHidden); for (SCROW l = static_cast<SCROW>(DataStart); l <= static_cast<SCROW>(DataEnd); l++) { pDoc->SetRowHidden(l, l, static_cast<SCTAB> (TabNo), bHidden); pDoc->SetRowBreak(l, static_cast<SCTAB> (TabNo), bPageBreak, bManualBreak); } } DataStart = DataEnd + 1; } pPrgrsBar->Progress(); // DataTable rStream >> ID; if (ID != TableID) { DBG_ERROR( "TableID" ); nError = errUnknownID; return; } for (SCCOL Col = 0; (Col <= SC10MAXCOL) && (nError == 0); Col++) { rStream >> Count; nError = rStream.GetError(); if ((Count != 0) && (nError == 0)) LoadCol(Col, static_cast<SCTAB> (TabNo)); } DBG_ASSERT( nError == 0, "Stream" ); } pPrgrsBar->Progress(); aPageCollection.PutToDoc( pDoc ); } void Sc10Import::LoadCol(SCCOL Col, SCTAB Tab) { LoadColAttr(Col, Tab); sal_uInt16 CellCount; sal_uInt8 CellType; sal_uInt16 Row; rStream >> CellCount; SCROW nScCount = static_cast< SCROW >( CellCount ); if (nScCount > MAXROW) nError = errUnknownFormat; for (sal_uInt16 i = 0; (i < CellCount) && (nError == 0); i++) { rStream >> CellType; rStream >> Row; nError = rStream.GetError(); if (nError == 0) { switch (CellType) { case ctValue : { const SfxPoolItem* pValueFormat = pDoc->GetAttr(Col, static_cast<SCROW> (Row), Tab, ATTR_VALUE_FORMAT); sal_uLong nFormat = ((SfxUInt32Item*)pValueFormat)->GetValue(); double Value = ScfTools::ReadLongDouble(rStream); // Achtung hier ist eine Anpassung Notwendig wenn Ihr das Basisdatum aendert // In StarCalc 1.0 entspricht 0 dem 01.01.1900 // if ((nFormat >= 30) && (nFormat <= 35)) // Value += 0; if ((nFormat >= 40) && (nFormat <= 45)) Value /= 86400.0; pDoc->SetValue(Col, static_cast<SCROW> (Row), Tab, Value); break; } case ctString : { sal_uInt8 Len; sal_Char s[256]; rStream >> Len; rStream.Read(s, Len); s[Len] = 0; pDoc->SetString( Col, static_cast<SCROW> (Row), Tab, SC10TOSTRING( s ) ); break; } case ctFormula : { /*double Value =*/ ScfTools::ReadLongDouble(rStream); sal_uInt8 Len; sal_Char s[256+1]; rStream >> Len; rStream.Read(&s[1], Len); s[0] = '='; s[Len + 1] = 0; ScFormulaCell* pCell = new ScFormulaCell( pDoc, ScAddress( Col, static_cast<SCROW> (Row), Tab ) ); pCell->SetHybridFormula( SC10TOSTRING( s ),formula::FormulaGrammar::GRAM_NATIVE ); pDoc->PutCell( Col, static_cast<SCROW> (Row), Tab, pCell, (sal_Bool)sal_True ); break; } case ctNote : break; default : nError = errUnknownFormat; break; } sal_uInt16 NoteLen; rStream >> NoteLen; if (NoteLen != 0) { sal_Char* pNote = new sal_Char[NoteLen+1]; rStream.Read(pNote, NoteLen); pNote[NoteLen] = 0; String aNoteText( SC10TOSTRING(pNote)); delete [] pNote; ScAddress aPos( Col, static_cast<SCROW>(Row), Tab ); ScNoteUtil::CreateNoteFromString( *pDoc, aPos, aNoteText, false, false ); } } pPrgrsBar->Progress(); } } void Sc10Import::LoadColAttr(SCCOL Col, SCTAB Tab) { Sc10ColAttr aFont; Sc10ColAttr aAttr; Sc10ColAttr aJustify; Sc10ColAttr aFrame; Sc10ColAttr aRaster; Sc10ColAttr aValue; Sc10ColAttr aColor; Sc10ColAttr aFrameColor; Sc10ColAttr aFlag; Sc10ColAttr aPattern; if (nError == 0) LoadAttr(aFont); if (nError == 0) LoadAttr(aAttr); if (nError == 0) LoadAttr(aJustify); if (nError == 0) LoadAttr(aFrame); if (nError == 0) LoadAttr(aRaster); if (nError == 0) LoadAttr(aValue); if (nError == 0) LoadAttr(aColor); if (nError == 0) LoadAttr(aFrameColor); if (nError == 0) LoadAttr(aFlag); if (nError == 0) LoadAttr(aPattern); if (nError == 0) { SCROW nStart; SCROW nEnd; sal_uInt16 i; sal_uInt16 nLimit; sal_uInt16 nValue1; Sc10ColData *pColData; // Font (Name, Groesse) nStart = 0; nEnd = 0; nLimit = aFont.Count; pColData = aFont.pData; for( i = 0 ; i < nLimit ; i++, pColData++ ) { nEnd = static_cast<SCROW>(pColData->Row); if ((nStart <= nEnd) && (pColData->Value)) { FontFamily eFam = FAMILY_DONTKNOW; Sc10FontData* pFont = pFontCollection->At(pColData->Value); if (pFont) { switch (pFont->PitchAndFamily & 0xF0) { case ffDontCare : eFam = FAMILY_DONTKNOW; break; case ffRoman : eFam = FAMILY_ROMAN; break; case ffSwiss : eFam = FAMILY_SWISS; break; case ffModern : eFam = FAMILY_MODERN; break; case ffScript : eFam = FAMILY_SCRIPT; break; case ffDecorative : eFam = FAMILY_DECORATIVE; break; default: eFam = FAMILY_DONTKNOW; break; } ScPatternAttr aScPattern(pDoc->GetPool()); aScPattern.GetItemSet().Put(SvxFontItem(eFam, SC10TOSTRING( pFont->FaceName ), EMPTY_STRING, PITCH_DONTKNOW, RTL_TEXTENCODING_DONTKNOW, ATTR_FONT )); aScPattern.GetItemSet().Put(SvxFontHeightItem(Abs(pFont->Height), 100, ATTR_FONT_HEIGHT )); pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern); } } nStart = nEnd + 1; } // Fontfarbe nStart = 0; nEnd = 0; nLimit = aColor.Count; pColData = aColor.pData; for( i = 0 ; i < nLimit ; i++, pColData++ ) { nEnd = static_cast<SCROW>(pColData->Row); if ((nStart <= nEnd) && (pColData->Value)) { Color TextColor(COL_BLACK); lcl_ChangeColor((pColData->Value & 0x000F), TextColor); ScPatternAttr aScPattern(pDoc->GetPool()); aScPattern.GetItemSet().Put(SvxColorItem(TextColor, ATTR_FONT_COLOR )); pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern); } nStart = nEnd + 1; } // Fontattribute (Fett, Kursiv...) nStart = 0; nEnd = 0; nLimit = aAttr.Count; pColData = aAttr.pData; for( i = 0 ; i < nLimit ; i++, pColData++ ) { nEnd = static_cast<SCROW>(pColData->Row); nValue1 = pColData->Value; if ((nStart <= nEnd) && (nValue1)) { ScPatternAttr aScPattern(pDoc->GetPool()); if ((nValue1 & atBold) == atBold) aScPattern.GetItemSet().Put(SvxWeightItem(WEIGHT_BOLD, ATTR_FONT_WEIGHT)); if ((nValue1 & atItalic) == atItalic) aScPattern.GetItemSet().Put(SvxPostureItem(ITALIC_NORMAL, ATTR_FONT_POSTURE)); if ((nValue1 & atUnderline) == atUnderline) aScPattern.GetItemSet().Put(SvxUnderlineItem(UNDERLINE_SINGLE, ATTR_FONT_UNDERLINE)); if ((nValue1 & atStrikeOut) == atStrikeOut) aScPattern.GetItemSet().Put(SvxCrossedOutItem(STRIKEOUT_SINGLE, ATTR_FONT_CROSSEDOUT)); pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern); } nStart = nEnd + 1; } // Zellausrichtung nStart = 0; nEnd = 0; nLimit = aJustify.Count; pColData = aJustify.pData; for( i = 0 ; i < nLimit ; i++, pColData++ ) { nEnd = static_cast<SCROW>(pColData->Row); nValue1 = pColData->Value; if ((nStart <= nEnd) && (nValue1)) { ScPatternAttr aScPattern(pDoc->GetPool()); sal_uInt16 HorJustify = (nValue1 & 0x000F); sal_uInt16 VerJustify = (nValue1 & 0x00F0) >> 4; sal_uInt16 OJustify = (nValue1 & 0x0F00) >> 8; sal_uInt16 EJustify = (nValue1 & 0xF000) >> 12; switch (HorJustify) { case hjLeft: aScPattern.GetItemSet().Put(SvxHorJustifyItem(SVX_HOR_JUSTIFY_LEFT, ATTR_HOR_JUSTIFY)); break; case hjCenter: aScPattern.GetItemSet().Put(SvxHorJustifyItem(SVX_HOR_JUSTIFY_CENTER, ATTR_HOR_JUSTIFY)); break; case hjRight: aScPattern.GetItemSet().Put(SvxHorJustifyItem(SVX_HOR_JUSTIFY_RIGHT, ATTR_HOR_JUSTIFY)); break; } switch (VerJustify) { case vjTop: aScPattern.GetItemSet().Put(SvxVerJustifyItem(SVX_VER_JUSTIFY_TOP, ATTR_VER_JUSTIFY)); break; case vjCenter: aScPattern.GetItemSet().Put(SvxVerJustifyItem(SVX_VER_JUSTIFY_CENTER, ATTR_VER_JUSTIFY)); break; case vjBottom: aScPattern.GetItemSet().Put(SvxVerJustifyItem(SVX_VER_JUSTIFY_BOTTOM, ATTR_VER_JUSTIFY)); break; } if (OJustify & ojWordBreak) aScPattern.GetItemSet().Put(SfxBoolItem(sal_True)); if (OJustify & ojBottomTop) aScPattern.GetItemSet().Put(SfxInt32Item(ATTR_ROTATE_VALUE,9000)); else if (OJustify & ojTopBottom) aScPattern.GetItemSet().Put(SfxInt32Item(ATTR_ROTATE_VALUE,27000)); sal_Int16 Margin = Max((sal_uInt16)20, (sal_uInt16)(EJustify * 20)); if (((OJustify & ojBottomTop) == ojBottomTop) || ((OJustify & ojBottomTop) == ojBottomTop)) aScPattern.GetItemSet().Put(SvxMarginItem(20, Margin, 20, Margin, ATTR_MARGIN)); else aScPattern.GetItemSet().Put(SvxMarginItem(Margin, 20, Margin, 20, ATTR_MARGIN)); pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern); } nStart = nEnd + 1; } // Umrandung sal_Bool bEnd = sal_False; sal_uInt16 nColorIndex = 0; sal_uInt16 nFrameIndex = 0; // Special Fix... const sal_uInt32 nHelpMeStart = 100; sal_uInt32 nHelpMe = nHelpMeStart; sal_uInt16 nColorIndexOld = nColorIndex; sal_uInt16 nFrameIndexOld = nColorIndex; nEnd = 0; nStart = 0; while( !bEnd && nHelpMe ) { pColData = &aFrame.pData[ nFrameIndex ]; sal_uInt16 nValue = pColData->Value; sal_uInt16 nLeft = 0; sal_uInt16 nTop = 0; sal_uInt16 nRight = 0; sal_uInt16 nBottom = 0; sal_uInt16 fLeft = ( nValue & 0x000F ); sal_uInt16 fTop = ( nValue & 0x00F0 ) >> 4; sal_uInt16 fRight = ( nValue & 0x0F00 ) >> 8; sal_uInt16 fBottom = ( nValue & 0xF000 ) >> 12; if( fLeft > 1 ) nLeft = 50; else if( fLeft > 0 ) nLeft = 20; if( fTop > 1 ) nTop = 50; else if( fTop > 0 ) nTop = 20; if( fRight > 1 ) nRight = 50; else if( fRight > 0 ) nRight = 20; if( fBottom > 1 ) nBottom = 50; else if( fBottom > 0 ) nBottom = 20; Color ColorLeft( COL_BLACK ); Color ColorTop( COL_BLACK ); Color ColorRight( COL_BLACK ); Color ColorBottom( COL_BLACK ); sal_uInt16 nFrmColVal = aFrameColor.pData[ nColorIndex ].Value; SCROW nFrmColRow = static_cast<SCROW>(aFrameColor.pData[ nColorIndex ].Row); sal_uInt16 cLeft = ( nFrmColVal & 0x000F ); sal_uInt16 cTop = ( nFrmColVal & 0x00F0 ) >> 4; sal_uInt16 cRight = ( nFrmColVal & 0x0F00 ) >> 8; sal_uInt16 cBottom = ( nFrmColVal & 0xF000 ) >> 12; lcl_ChangeColor( cLeft, ColorLeft ); lcl_ChangeColor( cTop, ColorTop ); lcl_ChangeColor( cRight, ColorRight ); lcl_ChangeColor( cBottom, ColorBottom ); if( static_cast<SCROW>(pColData->Row) < nFrmColRow ) { nEnd = static_cast<SCROW>(pColData->Row); if( nFrameIndex < ( aFrame.Count - 1 ) ) nFrameIndex++; } else if( static_cast<SCROW>(pColData->Row) > nFrmColRow ) { nEnd = static_cast<SCROW>(aFrameColor.pData[ nColorIndex ].Row); if( nColorIndex < ( aFrameColor.Count - 1 ) ) nColorIndex++; } else { nEnd = nFrmColRow; if( nFrameIndex < (aFrame.Count - 1 ) ) nFrameIndex++; if( nColorIndex < ( aFrameColor.Count - 1 ) ) nColorIndex++; } if( ( nStart <= nEnd ) && ( nValue != 0 ) ) { ScPatternAttr aScPattern(pDoc->GetPool()); SvxBorderLine aLine; SvxBoxItem aBox( ATTR_BORDER ); aLine.SetOutWidth( nLeft ); aLine.SetColor( ColorLeft ); aBox.SetLine( &aLine, BOX_LINE_LEFT ); aLine.SetOutWidth( nTop ); aLine.SetColor( ColorTop ); aBox.SetLine( &aLine, BOX_LINE_TOP ); aLine.SetOutWidth( nRight ); aLine.SetColor( ColorRight ); aBox.SetLine( &aLine, BOX_LINE_RIGHT ); aLine.SetOutWidth( nBottom ); aLine.SetColor( ColorBottom ); aBox.SetLine( &aLine, BOX_LINE_BOTTOM ); aScPattern.GetItemSet().Put( aBox ); pDoc->ApplyPatternAreaTab( Col, nStart, Col, nEnd, Tab, aScPattern ); } nStart = nEnd + 1; bEnd = ( nFrameIndex == ( aFrame.Count - 1 ) ) && ( nColorIndex == ( aFrameColor.Count - 1 ) ); if( nColorIndexOld != nColorIndex || nFrameIndexOld != nFrameIndex ) { nColorIndexOld = nColorIndex; nFrameIndexOld = nFrameIndex; nHelpMe = nHelpMeStart; } else nHelpMe--; pColData++; } // ACHTUNG: Code bis hier ueberarbeitet ... jetzt hab' ich keinen Bock mehr! (GT) // Hintergrund (Farbe, Raster) sal_uInt16 nRasterIndex = 0; bEnd = sal_False; nColorIndex = 0; nEnd = 0; nStart = 0; // Special Fix... nHelpMe = nHelpMeStart; sal_uInt16 nRasterIndexOld = nRasterIndex; while( !bEnd && nHelpMe ) { sal_uInt16 nBColor = ( aColor.pData[ nColorIndex ].Value & 0x00F0 ) >> 4; sal_uInt16 nRColor = ( aColor.pData[ nColorIndex ].Value & 0x0F00 ) >> 8; Color aBColor( COL_BLACK ); lcl_ChangeColor( nBColor, aBColor ); if( nBColor == 0 ) aBColor.SetColor( COL_WHITE ); else if( nBColor == 15 ) aBColor.SetColor( COL_BLACK ); Color aRColor( COL_BLACK ); lcl_ChangeColor( nRColor, aRColor ); ScPatternAttr aScPattern( pDoc->GetPool() ); sal_uInt16 nFact; sal_Bool bSwapCol = sal_False; sal_Bool bSetItem = sal_True; switch ( aRaster.pData[ nRasterIndex ].Value ) { case raNone: nFact = 0xffff; bSwapCol = sal_True; bSetItem = (nBColor > 0); break; case raGray12: nFact = (0xffff / 100) * 12; break; case raGray25: nFact = (0xffff / 100) * 25; break; case raGray50: nFact = (0xffff / 100) * 50; break; case raGray75: nFact = (0xffff / 100) * 75; break; default: nFact = 0xffff; bSetItem = (nRColor < 15); } if ( bSetItem ) { if( bSwapCol ) aScPattern.GetItemSet().Put( SvxBrushItem( GetMixedColor( aBColor, aRColor, nFact ), ATTR_BACKGROUND ) ); else aScPattern.GetItemSet().Put( SvxBrushItem( GetMixedColor( aRColor, aBColor, nFact ), ATTR_BACKGROUND ) ); } if( aRaster.pData[ nRasterIndex ].Row < aColor.pData[ nColorIndex ].Row ) { nEnd = static_cast<SCROW>(aRaster.pData[ nRasterIndex ].Row); if( nRasterIndex < ( aRaster.Count - 1 ) ) nRasterIndex++; } else if( aRaster.pData[ nRasterIndex ].Row > aColor.pData[ nColorIndex ].Row ) { nEnd = static_cast<SCROW>(aColor.pData[ nColorIndex ].Row); if( nColorIndex < ( aColor.Count - 1 ) ) nColorIndex++; } else { nEnd = static_cast<SCROW>(aColor.pData[ nColorIndex ].Row); if( nRasterIndex < ( aRaster.Count - 1 ) ) nRasterIndex++; if( nColorIndex < ( aColor.Count - 1 ) ) nColorIndex++; } if( nStart <= nEnd ) pDoc->ApplyPatternAreaTab( Col, nStart, Col, nEnd, Tab, aScPattern ); nStart = nEnd + 1; bEnd = ( nRasterIndex == ( aRaster.Count - 1 ) ) && ( nColorIndex == ( aColor.Count - 1 ) ); if( nColorIndexOld != nColorIndex || nRasterIndexOld != nRasterIndex ) { nColorIndexOld = nColorIndex; nRasterIndexOld = nRasterIndex; nHelpMe = nHelpMeStart; } else nHelpMe--; nHelpMe--; } // Zahlenformate nStart = 0; nEnd = 0; nLimit = aValue.Count; pColData = aValue.pData; for (i=0; i<nLimit; i++, pColData++) { nEnd = static_cast<SCROW>(pColData->Row); nValue1 = pColData->Value; if ((nStart <= nEnd) && (nValue1)) { sal_uLong nKey = 0; sal_uInt16 nFormat = (nValue1 & 0x00FF); sal_uInt16 nInfo = (nValue1 & 0xFF00) >> 8; ChangeFormat(nFormat, nInfo, nKey); ScPatternAttr aScPattern(pDoc->GetPool()); aScPattern.GetItemSet().Put(SfxUInt32Item(ATTR_VALUE_FORMAT, (sal_uInt32)nKey)); pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern); } nStart = nEnd + 1; } // Zellattribute (Schutz, Versteckt...) nStart = 0; nEnd = 0; for (i=0; i<aFlag.Count; i++) { nEnd = static_cast<SCROW>(aFlag.pData[i].Row); if ((nStart <= nEnd) && (aFlag.pData[i].Value != 0)) { sal_Bool bProtect = ((aFlag.pData[i].Value & paProtect) == paProtect); sal_Bool bHFormula = ((aFlag.pData[i].Value & paHideFormula) == paHideFormula); sal_Bool bHCell = ((aFlag.pData[i].Value & paHideAll) == paHideAll); sal_Bool bHPrint = ((aFlag.pData[i].Value & paHidePrint) == paHidePrint); ScPatternAttr aScPattern(pDoc->GetPool()); aScPattern.GetItemSet().Put(ScProtectionAttr(bProtect, bHFormula, bHCell, bHPrint)); pDoc->ApplyPatternAreaTab(Col, nStart, Col, nEnd, Tab, aScPattern); } nStart = nEnd + 1; } // ZellVorlagen nStart = 0; nEnd = 0; ScStyleSheetPool* pStylePool = pDoc->GetStyleSheetPool(); for (i=0; i<aPattern.Count; i++) { nEnd = static_cast<SCROW>(aPattern.pData[i].Row); if ((nStart <= nEnd) && (aPattern.pData[i].Value != 0)) { sal_uInt16 nPatternIndex = (aPattern.pData[i].Value & 0x00FF) - 1; Sc10PatternData* pPattern = pPatternCollection->At(nPatternIndex); if (pPattern != NULL) { ScStyleSheet* pStyle = (ScStyleSheet*) pStylePool->Find( SC10TOSTRING( pPattern->Name ), SFX_STYLE_FAMILY_PARA); if (pStyle != NULL) pDoc->ApplyStyleAreaTab(Col, nStart, Col, nEnd, Tab, *pStyle); } } nStart = nEnd + 1; } } } void Sc10Import::LoadAttr(Sc10ColAttr& rAttr) { // rAttr is not reused, otherwise we'd have to delete [] rAttr.pData; rStream >> rAttr.Count; if (rAttr.Count) { rAttr.pData = new (::std::nothrow) Sc10ColData[rAttr.Count]; if (rAttr.pData != NULL) { for (sal_uInt16 i = 0; i < rAttr.Count; i++) { rStream >> rAttr.pData[i].Row; rStream >> rAttr.pData[i].Value; } nError = rStream.GetError(); } else { nError = errOutOfMemory; rAttr.Count = 0; } } } void Sc10Import::ChangeFormat(sal_uInt16 nFormat, sal_uInt16 nInfo, sal_uLong& nKey) { // Achtung: Die Formate werden nur auf die StarCalc 3.0 internen Formate gemappt // Korrekterweise muessten zum Teil neue Formate erzeugt werden (sollte Stephan sich ansehen) nKey = 0; switch (nFormat) { case vfStandard : if (nInfo > 0) nKey = 2; break; case vfMoney : if (nInfo > 0) nKey = 21; else nKey = 20; break; case vfThousend : if (nInfo > 0) nKey = 4; else nKey = 5; break; case vfPercent : if (nInfo > 0) nKey = 11; else nKey = 10; break; case vfExponent : nKey = 60; break; case vfZerro : // Achtung kein Aequivalent break; case vfDate : switch (nInfo) { case df_NDMY_Long : nKey = 31; break; case df_DMY_Long : nKey = 30; break; case df_MY_Long : nKey = 32; break; case df_NDM_Long : nKey = 31; break; case df_DM_Long : nKey = 33; break; case df_M_Long : nKey = 34; break; case df_NDMY_Short : nKey = 31; break; case df_DMY_Short : nKey = 30; break; case df_MY_Short : nKey = 32; break; case df_NDM_Short : nKey = 31; break; case df_DM_Short : nKey = 33; break; case df_M_Short : nKey = 34; break; case df_Q_Long : nKey = 35; break; case df_Q_Short : nKey = 35; break; default : nKey = 30; break; } break; case vfTime : switch (nInfo) { case tf_HMS_Long : nKey = 41; break; case tf_HM_Long : nKey = 40; break; case tf_HMS_Short : nKey = 43; break; case tf_HM_Short : nKey = 42; break; default : nKey = 41; break; } break; case vfBoolean : nKey = 99; break; case vfStandardRed : if (nInfo > 0) nKey = 2; break; case vfMoneyRed : if (nInfo > 0) nKey = 23; else nKey = 22; break; case vfThousendRed : if (nInfo > 0) nKey = 4; else nKey = 5; break; case vfPercentRed : if (nInfo > 0) nKey = 11; else nKey = 10; break; case vfExponentRed : nKey = 60; break; case vfFormula : break; case vfString : break; default : break; } } void Sc10Import::LoadObjects() { sal_uInt16 ID; rStream >> ID; if (rStream.IsEof()) return; if (ID == ObjectID) { #ifdef SC10_SHOW_OBJECTS // Achtung nur zu Debugzwecken //----------------------------------- pDoc->InsertTab(SC_TAB_APPEND, "GraphObjects"); SCCOL nCol = 0; SCROW nRow = 0; SCTAB nTab = 0; pDoc->GetTable("GraphObjects", nTab); pDoc->SetString(nCol++, nRow, nTab, "ObjectTyp"); pDoc->SetString(nCol++, nRow, nTab, "Col"); pDoc->SetString(nCol++, nRow, nTab, "Row"); pDoc->SetString(nCol++, nRow, nTab, "Tab"); pDoc->SetString(nCol++, nRow, nTab, "X"); pDoc->SetString(nCol++, nRow, nTab, "Y"); pDoc->SetString(nCol++, nRow, nTab, "W"); pDoc->SetString(nCol++, nRow, nTab, "H"); //----------------------------------- #endif sal_uInt16 nAnz; rStream >> nAnz; sal_Char Reserved[32]; rStream.Read(Reserved, sizeof(Reserved)); nError = rStream.GetError(); if ((nAnz > 0) && (nError == 0)) { sal_uInt8 ObjectType; Sc10GraphHeader GraphHeader; sal_Bool IsOleObject = sal_False; // Achtung dies ist nur ein Notnagel for (sal_uInt16 i = 0; (i < nAnz) && (nError == 0) && !rStream.IsEof() && !IsOleObject; i++) { rStream >> ObjectType; lcl_ReadGraphHeader(rStream, GraphHeader); double nPPTX = ScGlobal::nScreenPPTX; double nPPTY = ScGlobal::nScreenPPTY; long nStartX = 0; for (SCsCOL nX=0; nX<GraphHeader.CarretX; nX++) nStartX += pDoc->GetColWidth(nX, static_cast<SCTAB>(GraphHeader.CarretZ)); nStartX = (long) ( nStartX * HMM_PER_TWIPS ); nStartX += (long) ( GraphHeader.x / nPPTX * HMM_PER_TWIPS ); long nSizeX = (long) ( GraphHeader.w / nPPTX * HMM_PER_TWIPS ); long nStartY = pDoc->GetRowHeight( 0, static_cast<SCsROW>(GraphHeader.CarretY) - 1, static_cast<SCTAB>(GraphHeader.CarretZ)); nStartY = (long) ( nStartY * HMM_PER_TWIPS ); nStartY += (long) ( GraphHeader.y / nPPTY * HMM_PER_TWIPS ); long nSizeY = (long) ( GraphHeader.h / nPPTY * HMM_PER_TWIPS ); #ifdef SC10_SHOW_OBJECTS // Achtung nur zu Debugzwecken //----------------------------------- nCol = 0; nRow++; switch (ObjectType) { case otOle : pDoc->SetString(nCol++, nRow, nTab, "Ole-Object"); break; case otImage : pDoc->SetString(nCol++, nRow, nTab, "Image-Object"); break; case otChart : pDoc->SetString(nCol++, nRow, nTab, "Chart-Object"); break; default : pDoc->SetString(nCol++, nRow, nTab, "ERROR"); break; } pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.CarretX); pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.CarretY); pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.CarretZ); pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.x); pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.y); pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.w); pDoc->SetValue(nCol++, nRow, nTab, GraphHeader.h); //----------------------------------- #endif switch (ObjectType) { case otOle : // Achtung hier muss sowas wie OleLoadFromStream passieren IsOleObject = sal_True; break; case otImage : { Sc10ImageHeader ImageHeader; lcl_ReadImageHeaer(rStream, ImageHeader); // Achtung nun kommen die Daten (Bitmap oder Metafile) // Typ = 1 Device Dependend Bitmap DIB // Typ = 2 MetaFile rStream.SeekRel(ImageHeader.Size); if( ImageHeader.Typ != 1 && ImageHeader.Typ != 2 ) nError = errUnknownFormat; break; } case otChart : { Sc10ChartHeader ChartHeader; Sc10ChartSheetData ChartSheetData; Sc10ChartTypeData* pTypeData = new (::std::nothrow) Sc10ChartTypeData; if (!pTypeData) nError = errOutOfMemory; else { lcl_ReadChartHeader(rStream, ChartHeader); //! altes Metafile verwenden ?? rStream.SeekRel(ChartHeader.Size); lcl_ReadChartSheetData(rStream, ChartSheetData); lcl_ReadChartTypeData(rStream, *pTypeData); Rectangle aRect( Point(nStartX,nStartY), Size(nSizeX,nSizeY) ); Sc10InsertObject::InsertChart( pDoc, static_cast<SCTAB>(GraphHeader.CarretZ), aRect, static_cast<SCTAB>(GraphHeader.CarretZ), ChartSheetData.DataX1, ChartSheetData.DataY1, ChartSheetData.DataX2, ChartSheetData.DataY2 ); delete pTypeData; } } break; default : nError = errUnknownFormat; break; } nError = rStream.GetError(); } } } else { DBG_ERROR( "ObjectID" ); nError = errUnknownID; } } //----------------------------------------------------------------------------------------------- FltError ScFormatFilterPluginImpl::ScImportStarCalc10( SvStream& rStream, ScDocument* pDocument ) { rStream.Seek( 0UL ); Sc10Import aImport( rStream, pDocument ); return ( FltError ) aImport.Import(); }
74,906
32,916